@promptctl/cc-candybar 1.46.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +31 -31
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as e}from"node:module";import t from"node:process";import{json as n}from"node:stream/consumers";import r,{createReadStream as i,existsSync as a,statSync as o,watch as s}from"node:fs";import c,{basename as l,dirname as u,join as d}from"node:path";import f,{homedir as p}from"node:os";import{spawn as m,spawnSync as h}from"node:child_process";import g from"node:net";import _ from"node:v8";import{URL as v,URLSearchParams as y,fileURLToPath as b,pathToFileURL as x}from"node:url";import{parseArgs as S}from"node:util";import{get as C}from"node:https";import{createHash as ee}from"node:crypto";import{setTimeout as w}from"node:timers/promises";import{open as T,readFile as te,readdir as ne,stat as re}from"node:fs/promises";import{createInterface as E}from"node:readline";import{clearInterval as D,setInterval as ie}from"node:timers";var ae=Object.create,oe=Object.defineProperty,se=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyNames,le=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty,de=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),fe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ce(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ue.call(e,s)&&s!==n&&oe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=se(t,s))||r.enumerable});return e},pe=(e,t,n)=>(n=e==null?{}:ae(le(e)),fe(t||!e||!e.__esModule?oe(n,`default`,{value:e,enumerable:!0}):n,e));function O(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const me={"click.pbcopy":1e3,"click.open":1e3},he=new Map;function ge(e){let t=me[e];if(t===void 0)return{allowed:!0};let n=he.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function k(e){he.set(e,Date.now())}function _e(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ve=null;function ye(e){ve=e}async function be(e){let t=ge(e.category);if(!t.allowed)return _e(e.category,t.minIntervalMs,t.sinceLastMs);k(e.category);let n=Date.now();return ve?.onStart(e.category),new Promise(t=>{let r;try{r=m(e.bin,e.args??[],{cwd:e.cwd,env:e.env,stdio:[`pipe`,`pipe`,`pipe`]})}catch(r){ve?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:r instanceof Error?r.message:String(r)});return}let i=``,a=``,o=!1,s=null,c=null,l=!1,u=r=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),ve?.onEnd(e.category,Date.now()-n),t(r))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,e=>{u({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:e.message})}),r.on(`close`,(e,t)=>{if(l){u({ok:!1,reason:`timeout`,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){u({ok:!0,stdout:i,stderr:a,exitCode:e});return}u({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>{l=!0,r.pid!==void 0&&(r.kill(`SIGTERM`),c=setTimeout(()=>{r.kill(`SIGKILL`)},250))},e.timeoutMs)),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function xe(e){let t=ge(e.category);if(!t.allowed)return _e(e.category,t.minIntervalMs,t.sinceLastMs);k(e.category);let n=Date.now();ve?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=h(e.bin,e.args??[],{cwd:e.cwd,env:e.env,input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ve?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:t.error.message};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ve?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:t instanceof Error?t.message:String(t)}}}function Se(e){let t=ge(e.category);if(!t.allowed)return _e(e.category,t.minIntervalMs,t.sinceLastMs);k(e.category);let n=Date.now();ve?.onStart(e.category);let r=Ce(e);return ve?.onEnd(e.category,Date.now()-n),r}function Ce(e){let t;try{t=m(e.bin,e.args??[],{cwd:e.cwd,env:e.env,detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function we(e){let t=process.env[e];return t&&t.length>0?t:void 0}function Te(){let e=we(`XDG_STATE_HOME`)??c.join(f.homedir(),`.local`,`state`);return c.join(e,`cc-candybar`)}function Ee(){let e=we(`XDG_CACHE_HOME`)??c.join(f.homedir(),`.cache`);return c.join(e,`cc-candybar`)}function De(){return Te()}function Oe(){let e=process.env.CC_CANDYBAR_SOCKET;if(e)return e;let t=f.userInfo().uid;return c.join(`/tmp`,`cc-candybar-${t}`,`socket`)}function ke(e){r.mkdirSync(e,{recursive:!0,mode:448});let t=r.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=f.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function A(e){ke(c.dirname(e));for(let t of[e,Ae(e)])try{if(r.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Ae(e){return`${e}.lease`}function je(){return Ae(Oe())}function Me(){return c.join(Te(),`session-state.json`)}function Ne(){return c.join(Te(),`config-edit-history.json`)}function Pe(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=f.userInfo().uid;return c.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Fe(){return c.join(Te(),`spawn.lock`)}function Ie(){return c.join(Te(),`spawn.cooldown`)}function Le(){return c.join(Te(),`spawn.backoff`)}function Re(){return c.join(Te(),`diagnostics`)}function ze(){return c.join(Te(),`daemon.log`)}function Be(e){let t=He(e.termCols),n=He(e.termRows),r=Ue(e.ssh);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r}}}const Ve=1e4;function He(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Ve?Ve:t}function Ue(e){return typeof e==`boolean`?e:void 0}var We=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Ge(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Ke(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 We(`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 We(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function qe(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=Ke(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(Ge(t))})}async function Je(e,t,n){let r=null;try{r=await $e(Oe(),t.connectMs);let i=await qe(r,{v:3,...e},t.budgetMs);return Ze(e.kind,i,n)}catch(e){return Qe(e)}finally{r&&r.destroy()}}function Ye(e,t){return typeof e==`string`?e:t}function Xe(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Ze(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=Ye(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Xe(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 Qe(e){if(e instanceof We||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 $e(e,t){return new Promise((n,r)=>{let i=g.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function et(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 tt={connectMs:50,budgetMs:150},nt={connectMs:50,budgetMs:200};function rt(e){let t=e.output;return typeof t==`string`?t:void 0}function it(e,t,n,r){return Je({kind:`render`,hookData:e,args:t,cwd:n,...r},tt,rt)}function at(e,t){return Je({kind:`click`,verb:e,value:t},nt,rt)}let ot=null;function st(e){if(ot!==null)return ot;r.mkdirSync(c.dirname(e),{recursive:!0});try{ot=r.statSync(e).size}catch{ot=0}return ot}function ct(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}ot=0}function j(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=ze(),t=st(e);r.appendFileSync(e,n),ot=t+Buffer.byteLength(n,`utf8`),ot>=5242880&&ct(e)}catch(e){ot=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const lt=`CC_CANDYBAR_RSS_LIMIT_MB`;function ut(e){let t=e[lt];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${lt} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function dt(e){return ut(e)*2}const ft=1024*1024;function pt(e){return ut(e)*ft}function mt(e){let t=e.rssLimitBytes??512*ft,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=c.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),ht(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function ht(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function gt(e,t,n={}){let i=De();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:j,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listSnapshots:()=>{try{return r.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function _t(e={}){if(Nt()!==null)return;let n=e.spawn??M,r=At();if(r.kind===`contended`){let e=yt();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),vt(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),vt(n);return}try{vt(n)}finally{Mt()}}function vt(e){Et()&&bt(e)}function yt(){try{let e=r.statSync(Fe());return Date.now()-e.mtimeMs}catch{return null}}function bt(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
3
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function xt(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function St(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ct(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 wt(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Tt(){try{r.unlinkSync(Le())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Et(){let e=Ie(),n=Le(),r=Ct(n),i=xt(Dt(e),St(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`),Ot(e),wt(n,Math.min(r+1,5)),!0)}function Dt(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ot(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let kt=null;function At(){let e=Fe();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 kt={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(!jt(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 jt(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Mt(){if(!kt)return;let{fd:e,path:t}=kt;kt=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function Nt(){try{return r.mkdirSync(De(),{recursive:!0}),null}catch(e){return`mkdir ${De()}: ${e.message}`}}function M(){let e=t.execPath,n=t.argv[1];return n?Se({bin:e,args:[`--max-old-space-size=${dt(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Pt=`cc-candybar`,N=`dispatch`,Ft=`set-state`,It=`step-state`,Lt=`copy`,Rt=`open-vscode`,zt=`show-config-error`,Bt=`show-config-warning`,Vt=`set-config`,Ht=`step-config`,Ut=`reset-config`,Wt=`apply-layout-op`,Gt=`undo`,Kt=`redo`;function qt(e){return e.map(encodeURIComponent).join(`/`)}function Jt(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Yt(e){return`${Pt}://${N}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${qt(e.args)}`)}`).join(`&`)}`}function Xt(e){return new y(e).getAll(`e`).map(Zt)}function Zt(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Qt=`closed`;function $t(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function en(e,t,n,r){let i=$t(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function tn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function P(e,...t){return`{{ and ${[e,...t].map(nn).join(` `)} }}`}function nn(e){return`(eq .${e.variable} "${tn(e.member)}")`}function rn(e,t,n){return`{{ action "${e}" "${tn(t)}" "${tn(n)}" }}`}function an(e,t){return{kind:`state`,key:e,default:t}}function on(e,t){return{set:e,cycle:[Qt,t]}}const sn=`1.46.0`;function F(e){return{kind:`ok`,value:e}}const I={kind:`absent`};function L(e){return{kind:`failed`,reason:e}}function cn(e,t){return e?.kind===`ok`?e.value:t}const ln=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function un(e){let t=ln.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 dn(e){return e.join(`.`)}function R([e,t,n],[r,i,a]){return e-r||t-i||n-a}async function fn(e,t){let n=`https://registry.npmjs.org/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(n,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return L(`registry responded ${e.status} for ${n}`);let r=await e.json();return typeof r.latest==`string`?un(r.latest):I}catch(e){return L(e instanceof Error?e.message:String(e))}}function pn(e,t){let n=un(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=R(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 mn(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${dn(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${dn(t.installed)} is newer than the registry's latest release (${dn(t.latest)}): an unpublished build.\n`};case`stale`:{let n=dn(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${dn(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 hn=`@promptctl/cc-candybar`,gn=`CCCandybarURLHandler`,_n=[],vn={"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 yn(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function z(e,t){return[e,...t].map(yn).join(` `)}function bn(){return c.join(f.homedir(),`Applications`,`${gn}.app`)}function xn(){return c.join(f.homedir(),`.claude`,`settings.json`)}function Sn(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Cn(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function wn(){return c.join(Cn(),`bin`,`cc-candybar`)}function Tn(){return c.join(Cn(),`dist`,`index.mjs`)}function En(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(`
3
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function xt(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function St(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ct(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 wt(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Tt(){try{r.unlinkSync(Le())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Et(){let e=Ie(),n=Le(),r=Ct(n),i=xt(Dt(e),St(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`),Ot(e),wt(n,Math.min(r+1,5)),!0)}function Dt(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ot(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let kt=null;function At(){let e=Fe();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 kt={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(!jt(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 jt(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Mt(){if(!kt)return;let{fd:e,path:t}=kt;kt=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function Nt(){try{return r.mkdirSync(De(),{recursive:!0}),null}catch(e){return`mkdir ${De()}: ${e.message}`}}function M(){let e=t.execPath,n=t.argv[1];return n?Se({bin:e,args:[`--max-old-space-size=${dt(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Pt=`cc-candybar`,N=`dispatch`,Ft=`set-state`,It=`step-state`,Lt=`copy`,Rt=`open-vscode`,zt=`show-config-error`,Bt=`show-config-warning`,Vt=`set-config`,Ht=`step-config`,Ut=`reset-config`,Wt=`apply-layout-op`,Gt=`undo`,Kt=`redo`;function qt(e){return e.map(encodeURIComponent).join(`/`)}function Jt(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Yt(e){return`${Pt}://${N}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${qt(e.args)}`)}`).join(`&`)}`}function Xt(e){return new y(e).getAll(`e`).map(Zt)}function Zt(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Qt=`closed`;function $t(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function en(e,t,n,r){let i=$t(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function tn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function P(e,...t){return`{{ and ${[e,...t].map(nn).join(` `)} }}`}function nn(e){return`(eq .${e.variable} "${tn(e.member)}")`}function rn(e,t,n){return`{{ action "${e}" "${tn(t)}" "${tn(n)}" }}`}function an(e,t){return{kind:`state`,key:e,default:t}}function on(e,t){return{set:e,cycle:[Qt,t]}}const sn=`1.48.0`;function F(e){return{kind:`ok`,value:e}}const I={kind:`absent`};function L(e){return{kind:`failed`,reason:e}}function cn(e,t){return e?.kind===`ok`?e.value:t}const ln=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function un(e){let t=ln.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 dn(e){return e.join(`.`)}function R([e,t,n],[r,i,a]){return e-r||t-i||n-a}async function fn(e,t){let n=`https://registry.npmjs.org/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(n,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return L(`registry responded ${e.status} for ${n}`);let r=await e.json();return typeof r.latest==`string`?un(r.latest):I}catch(e){return L(e instanceof Error?e.message:String(e))}}function pn(e,t){let n=un(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=R(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 mn(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${dn(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${dn(t.installed)} is newer than the registry's latest release (${dn(t.latest)}): an unpublished build.\n`};case`stale`:{let n=dn(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${dn(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 hn=`@promptctl/cc-candybar`,gn=`CCCandybarURLHandler`,_n=[],vn={"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 yn(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function z(e,t){return[e,...t].map(yn).join(` `)}function bn(){return c.join(f.homedir(),`Applications`,`${gn}.app`)}function xn(){return c.join(f.homedir(),`.claude`,`settings.json`)}function Sn(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Cn(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function wn(){return c.join(Cn(),`bin`,`cc-candybar`)}function Tn(){return c.join(Cn(),`dist`,`index.mjs`)}function En(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(`
4
4
  `)}function Dn(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function On(t){let n=vn[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function kn(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function An(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 ${hn}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function jn(){let e=Dn(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=On(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Tn()),{recursive:!0}),r.mkdirSync(c.dirname(wn()),{recursive:!0}),kn(e,Tn()),kn(t.sourcePath,wn()),r.chmodSync(wn(),493),r.rmSync(c.join(Cn(),`url-handler.mjs`),{force:!0});let n=An(wn());return process.stdout.write(`Staged cc-candybar v${sn} runtime at ${Cn()}\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:wn(),distPath:Tn(),entryKind:n}}function Mn(){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>${Pt}</string>`,` </array>`,` </dict>`,`</array>`].join(`
5
5
  `)}]}function Nn(e){let t=bn();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=xe({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,En(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of Mn())xe({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of Mn()){let n=xe({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 ${Pt}:// with Launch Services\n`);let a=xe({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(`✓ ${gn}.app installed and registered.\n`),process.stdout.write(` Test: open '${Pt}://hello-world' && pbpaste\n`)}function B(){Sn(),Nn(jn().distPath)}function Pn(e,t=Pt){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:Lt,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Fn(e){e||(process.stderr.write(`url-handle: missing URL argument.
6
6
  `),process.exit(1));let t;try{t=Pn(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await at(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(_t(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(In(n)+`
@@ -159,47 +159,47 @@ Config tooling:
159
159
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
160
160
  Single-row example: root: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`layout`])}),t.root!==void 0&&(n.root=l_(e,`root`,t.root)),t.actions!==void 0&&(n.actions=ty(e,t.actions)),t.looks!==void 0&&(n.looks=Uy(e,t.looks)),t.presets!==void 0&&(n.presets=Gy(e,t.presets)),t.editGlobals!==void 0&&(n.editGlobals=fg(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(n.helpers=Ky(e,t.helpers)),y_(e,n),I_(e,n),uh(e,n),th(e,n,$_,`the global settings menu`),n}const Fb=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]),Ib=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Lb(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 Rb(e){let t=await zb(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function zb(e){for(let t of[65536,1048576]){let n=await ri(e,t);if(n.kind!==`ok`)return n;let r=Bb(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function Bb(e,t){let n=e.toString(`utf8`).split(`
161
161
  `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Ib.test(t))continue;let r=Lb(t);if(r!=null)return r}return null}function Vb(e,t,n){let r=ol(t(`preset`),e.globals.preset,e.presets),i=ll(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:Rc(a.palette,t(`theme`),i.palette),look:Hc(a.look,t(`look`),i.look,e.looks),style:Kc(a.style,t(`style`),i.style),separator:a.default_separator??i.default_separator,autoWrap:tl(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:nl(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}const Hb=10*1e3;function Ub(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 Wb(e,t){if(!(t<60))return e*3600/t}function Gb(e,t,n,r){let i=r-t;if(i<50||i>Hb)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Kb(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Gb(t.input,t.atMs,n.input,n.atMs),i=Gb(t.output,t.atMs,n.output,n.atMs),a=Gb(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 qb(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>Hb)continue;let o=Gb(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Jb(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function Yb(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`,()=>Jb(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function Xb(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,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}`,i);let n=[],r=new Set;for(let t of _h(e.root)){if(t.when)for(let e of tb(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of tb(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Zb(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of tb(e.template))n.push(t)}}}return i}function Zb(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 Qb(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function $b(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 ex(e,t,n,r,i,a){let o=e=>Qb(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>L(`${e}: ${String(t)}`)):Promise.resolve(I),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,$b(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>Rb(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=rx(l);_.push(...y.failures);let b=Yb(a);_.push(...b.failures);let x=v(u),S=v(d),C=v(f),ee=v(p),w=v(m),T=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let te=e.rate_limits?.five_hour,ne=e.rate_limits?.seven_day,re=te?Ub(te.used_percentage,te.resets_at,18e6,s):void 0,E=ne?Ub(ne.used_percentage,ne.resets_at,6048e5,s):void 0,D=x?.session.cost,ie=ee?.sessionDuration,ae=o(`burn`)&&D!=null&&ie!=null?Wb(D,ie):void 0,oe=v(g),se=oe===void 0?void 0:Kb(oe),ce=oe===void 0?void 0:qb(oe),le=se!==void 0||ce!==void 0?{...se,...ce!==void 0&&{history:ce}}:void 0,ue=nx(process.env.HOME??process.env.USERPROFILE),de=e.workspace?{...e.workspace,current_dir:nx(e.workspace.current_dir)??``,project_dir:nx(e.workspace.project_dir)??``}:e.workspace,fe=x===void 0?void 0:tx({cost:x.session.cost,tokens:x.session.tokens}),pe=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},O=ee===void 0?void 0:tx({lastResponseTime:ee.lastResponseTime,responseTime:ee.responseTime,sessionDuration:ee.sessionDuration,messageCount:ee.messageCount,linesAdded:ee.linesAdded,linesRemoved:ee.linesRemoved});return{...e,...de!==void 0&&{workspace:de},...ue!==void 0&&{home:ue},...y.git!==void 0&&{git:y.git},...w!==void 0&&{tmux:{session:w}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...fe!==void 0&&{session:fe},...pe!==void 0&&{today:pe},...ae!==void 0&&{burn:{costPerHour:ae}},...le!==void 0&&{speed:le},...o(`block`)&&te!==void 0&&{block:{nativeUtilization:te.used_percentage,resetsAt:te.resets_at,...re!==void 0&&{etaMinutes:re}}},...ne!==void 0&&{weekly:{percentage:ne.used_percentage,resetsAt:ne.resets_at,...E!==void 0&&{etaMinutes:E}}},...T!==void 0&&{cache:{expiresAt:T}},...C!==void 0&&{context:{totalTokens:C.totalTokens,contextLeft:C.contextLeftPercentage}},...O!==void 0&&{metrics:O}}}function tx(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 nx(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function rx(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 ix=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,ax=`{{ \$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 (${ix}) (basename .project_dir) (ne (${ix}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,ox={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},sx=(e,t)=>`{{ fg (color "${ox[e]}") ${t} }}`,cx=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,lx=`{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} ({{ \$first := true }}{{ if gt .git.staged 0 }}${sx(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${sx(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${sx(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${sx(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,ux=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${sx(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${sx(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${sx(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+lx+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${sx(`stash`,`(printf "⧇ %v" .git.stash)`)}{{ end }} {{ if eq .git.status "conflicts" }}{{ fg (color "error") "⚠" }}{{ else }}{{ if eq .git.status "dirty" }}{{ fg (color "warning") "●" }}{{ else }}{{ fg (color "success") "✓" }}{{ end }}{{ end }}`;function dx(e,t){return`{{ if ge (round ${e}) ${t} }}error{{ else }}{{ if ge (round ${e}) 50 }}warning{{ else }}panel{{ end }}{{ end }}`}function fx(e){return`{{ if ge (round ${e}) 50 }}button-color-foreground{{ else }}foreground{{ end }}`}function px(e,t,n){return`{{ if lt ${e} 0 }}panel{{ else }}{{ if lt ${e} ${n} }}error{{ else }}{{ if lt ${e} ${t} }}warning{{ else }}panel{{ end }}{{ end }}{{ end }}`}function mx(e,t){return`{{ if lt ${e} 0 }}foreground{{ else }}{{ if lt ${e} ${t} }}button-color-foreground{{ else }}foreground{{ end }}{{ end }}`}const hx={globals:{palette:`tokyo-night`},variables:{current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},version:{kind:`input`,path:`version`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"style.effective":{kind:`input`,path:`style.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"hue.step":{kind:`literal`,value:14},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.repoUrl":{kind:`input`,path:`git.repoUrl`,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.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0}},segments:{directory:{template:ax,bg:`surface`,fg:`foreground`},model:{template:`✱ {{ formatModelName .model.display_name }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{template:`⌗{{ trunc 8 .session.id }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{template:`◈ v{{ .version }}`,bg:`surface`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{template:`tmux:{{ .tmux.session | default "none" }}`,bg:`surface-active`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{template:ux,bg:`surface-active`,fg:cx,when:`{{ ne .git.branch "" }}`},gitaculous:{template:`(git){{ if ne .git.repoName "" }} {{ .git.repoName }}{{ end }}{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} {{ if gt .git.staged 0 }}${sx(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${sx(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${sx(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${sx(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${sx(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${sx(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${sx(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${sx(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,bg:`surface-active`,fg:cx,when:`{{ ne .git.branch "" }}`},gitPr:{template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,bg:`surface-active`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,bg:`surface`,fg:`foreground`},session:{template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},today:{template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,bg:`surface`,fg:`foreground`},block:{template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .block.resetsAt) }})`,bg:dx(`.block.nativeUtilization`,`.block.budget.warningThreshold`),fg:fx(`.block.nativeUtilization`),when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .weekly.resetsAt) }})`,bg:dx(`.weekly.percentage`,`.weekly.budget.warningThreshold`),fg:fx(`.weekly.percentage`),when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:px(`.block.etaMinutes`,`.burn.eta.warnMinutes`,`.burn.eta.errorMinutes`),fg:mx(`.block.etaMinutes`,`.burn.eta.warnMinutes`),when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,bg:`panel`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{template:`⚡ {{ sparkline .speed.history 24 }}`,bg:`panel`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,bg:`surface`,fg:`{{ if le (minutesUntilReset .cache.expiresAt) 8 }}error{{ else }}{{ if le (minutesUntilReset .cache.expiresAt) 20 }}warning{{ else }}foreground{{ end }}{{ end }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ if le .context.contextLeft 20 }}error{{ else }}{{ if le .context.contextLeft 40 }}warning{{ else }}surface-active{{ end }}{{ end }}`,fg:`{{ if le .context.contextLeft 40 }}button-color-foreground{{ else }}foreground{{ end }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{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 }} `,bg:`panel`,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" "▸" "▾" }} {{ action "resetCharset" "↺" }}`,bg:`surface`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" "▸" "▾" }} {{ action "resetColorCompat" "↺" }}`,bg:`surface`,fg:`foreground`},directoryPaletteControl:{template:`🎨 directory {{ menu "applyDirectoryPaletteForever" "▸" "▾" }} {{ action "resetDirectoryPalette" "↺" }}`,bg:`surface`,fg:`foreground`}},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:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ terminal`,direction:`horizontal`,children:[`charsetControl`,`colorCompatControl`,`directoryPaletteControl`]}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}]},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{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:`segment`,name:`toolbar`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,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 }}`}},gx=new Set([hx.globals.palette,...Object.values(hx.segments).map(e=>e.palette)].filter(e=>e!==void 0)),_x=ng(Mb(`<default>`,JSON.stringify(hx),gx),hx);function vx(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function yx(e){return typeof e==`string`?e:String(e)}function bx(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function xx(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}const Sx=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,Cx=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function wx(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(Sx);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(Cx);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function Tx(e){let t=e.match(Cx);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function Ex(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function Dx(e){return e.toLocaleString()}const Ox=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],kx=Ox.length;function Ax(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(kx-1));o+=Ox[t]}return o}function jx(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}const Mx=Bc(),Nx=[...Wc];function Px(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>Ex(e),argTypes:[`string`]},int:{fn:e=>bx(e),argTypes:[`value`]},string:{fn:e=>yx(e),argTypes:[`value`]},bool:{fn:e=>xx(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>Mx,argTypes:[]},styles:{fn:()=>Nx,argTypes:[]},sparkline:{fn:(e,t)=>Ax(jx(e),t),argTypes:[`string`,`int`]}}}function Fx(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>Dx(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>wx(e),argTypes:[`string`]},shortenModelName:{fn:e=>Tx(e),argTypes:[`string`]}}}function Ix(e,t=()=>new Date){return Yu({fromString:e=>new os(e),toString:e=>e.plain,clock:t,missingKey:`error`,funcs:{...Bf(),...Xm(),...Ep(),...Jp(),...Mf(t),...xd(),...ep(),...Pc(),...Px(),...Fx(t),...e??{}}})}function Lx(e){return Rx(e,new Set(e.names()),``)}function Rx(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return Rx(e,t,a)}})}function zx(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Bx(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}async function Vx(e){let t=await be({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`});return t.ok?{stdout:t.stdout,exitCode:t.exitCode??0}:{stdout:t.stdout,exitCode:t.exitCode??1}}async function Hx(e,t,n){let r;try{r=await te(e,`utf8`)}catch{return{error:`file unreadable: ${e}`}}if(n!==void 0){let t=new RegExp(n).exec(r);return t?.[1]?{content:t[1].replace(/\n/g,` `)}:{error:`regex no-match in "${e}"`}}return t===`first-line`?{content:(r.split(`
162
- `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const Ux=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Wx=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Gx=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Kx=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function qx(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>Ux[e.getMonth()]],[`Monday`,e=>Gx[e.getDay()]],[`Jan`,e=>Wx[e.getMonth()]],[`Mon`,e=>Kx[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const Jx={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Yx(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=Jx[t];try{return $x(r,e)}catch{return eS(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return cn(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return cn(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return cn(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return cn(e.stashCount,0)}}var Xx=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},Zx=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ie(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(D(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())D(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Qx(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function $x(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?yx(e):t===`number`?bx(e):xx(e)}function eS(e){return e===`number`?0:e===`boolean`?!1:``}var tS=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new Xx;ttlMgr=new Zx;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=Ix();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new Kr({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,vx(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){let r=zx(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=Lx(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return qx(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,qx(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=Jx[t.field],r=t.varDefault===void 0?eS(n):$x(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe:this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,Yx(t,n,i,this.defaultEmptyValue))})})},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Qx(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,$x(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Y.reaction)(()=>{let t=Lx(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Y.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await Vx(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await Hx(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,$x(this.defaultEmptyValue,t))}catch{this.store.setBox(e,eS(t))}}defaultFor(e){try{return $x(this.defaultEmptyValue,e)}catch{return eS(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}};const nS=new Map,rS=new Map;function iS(e){let t=Ic(e),n=nS.get(t);if(n!==void 0)return n;let r=wo(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return nS.set(t,r),r}function aS(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=rS.get(n);if(r!==void 0)return r;let i=Io(e,t);return rS.set(n,i),i}function oS(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=sS(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=sS([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function sS(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>cS(e,t)):e,r=os.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function cS(e,t){let n=e.copy();return n.style=t.add(e.style),n}function lS(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function uS(e,t){let n=os.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function dS(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=uS(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var fS=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function pS(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=mS(r,a),c=s===void 0?void 0:hS(n,s,`bg`);o.bg=c;let l=mS(i,a),u=l===void 0?void 0:hS(n,l,`fg`);return new q({bgcolor:c===void 0?void 0:Oa.fromRgba(c),color:u===void 0?void 0:Oa.fromRgba(u)})}function mS(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function hS(e,t,n){try{return ro(e,t)}catch(e){throw e instanceof eo?new fS(t,n,e.message):e}}const gS=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function _S(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,vS(e,a,o,n,r));return i}function vS(e,t,n,r,i){if(Jv(n)){let[a,o]=Yv(n);return yS(r.get(n.persistWhen)??n.persistWhen,n.set,vS(e,t,a,r,i),vS(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...Zy(n.from,i)]}:`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=gS.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...Zy(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...Zy(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:xS(e,n.copy,t)}:`open`in n?{kind:`open`,target:xS(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function yS(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function bS(e,t){return e.kind===`dual`?$c(SS(t,e.selector))===!0?e.durable:e.session:e}function xS(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function SS(e,t){return e.has(t)?yx(e.read(t)):``}function CS(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function wS(e,t,n){let r=new os(e,{style:new q({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function TS(e,t){return Math.max(e.members.indexOf(SS(t,e.stateVar)),0)}function ES(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=SS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=SS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=SS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(TS(e,r)+1)%e.members.length];return{effects:[{verb:Ft,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:It,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Lt,args:[CS(e.text,Lx(r))]}],active:!1};case`open`:return{effects:[{verb:Rt,args:[CS(e.target,Lx(r))]}],active:!1};case`persist-literal`:{let t=SS(r,e.stateVar);return{effects:[{verb:Vt,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=SS(r,e.stateVar);return{effects:[{verb:Vt,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(TS(e,r)+1)%e.members.length];return{effects:[{verb:Vt,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Ht,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Ut,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Gt,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Kt,args:[i]}],active:!1};case`layout-op`:return{effects:[{verb:Wt,args:[i,e.key,L_(e.op)]}],active:!1};case`dual`:{let a=bS(e,r),{effects:o,active:s}=ES(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Wt,args:[i,e.key,L_(r)]}],active:!1}}}}function DS(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:en(`action "${e}"`,n,t.members.length,TS(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 OS(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}=DS(e,bS(r,i),t,i),{effects:s,active:c}=ES(r,a,o,i,SS(i,`session.id`));return wS(a,Yt(s),c)}function kS(e){return{action:{fn:(t,...n)=>OS(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function AS(e){return new os(e).cellLength}function jS(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 MS(e,t){let n=[];for(let t of e)n.length>0&&n.push(new os(` `)),n.push(t);let r=os.fromFragments(n);return r.noWrap=t,r.end=``,r}function NS(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 PS(e,t){let n=e.compiled.get(t),r=n&&bS(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker 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 ${r?`a ${r.kind} action`:`no such action`}`);return r}function FS(e,t,n,r,i,a){let o=PS(a,e),s=a.compiled.get(e),c=a.store,l=SS(c,`session.id`),u=`stateVar`in o?SS(c,o.stateVar):void 0,d=o.options.map(AS),f=i?Math.max(1,bx(c.read(`term.cols`))-mh(a.stripStyle)-2*a.padding):1/0,p=AS(`✕`)+1,m=AS(`←`)+1+AS(`→`)+1,h=jS(d,f,p),g=h.length>1?jS(d,f,p+m):h,_=parseInt(SS(c,t.stateVar),10),v=Number.isInteger(_)?Math.max(0,Math.min(_,g.length-1)):0,y=g[v]??[],b=e=>Yt([{verb:Ft,args:[l,t.key,String(e)]}]),x=n.flatMap(([e,t])=>[e,t]),S=Yt([{verb:Ft,args:[l,...x]}]),C=r?[{verb:Ft,args:[l,...x]}]:[],ee=e=>{let{effects:t}=ES(s,e,e,c,l),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?Yt([{verb:Ft,args:[...n.args,...r?x:[]]}]):Yt([...t,...C])},w=[wS(`✕`,S,!1)];v>0&&w.push(wS(`←`,b(v-1),!1));for(let e of y){let t=o.options[e];w.push(wS(t,ee(t),t===u))}return v<g.length-1&&w.push(wS(`→`,b(v+1),!1)),MS(w,i)}function IS(e){return{picker:{fn:(t,n,r,i)=>{let a=NS(e,n,`set-int`,`an int action ({ set, int: true })`);return FS(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const LS=Symbol(`cc-candybar.menuDrop`);function RS(e){return e.flatMap(e=>e[LS]??[])}function zS(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=C_(i.segName,e,n.key),s=T_(o),c=S_(e),l=SS(a.store,o)===c,u=SS(a.store,`session.id`),d=l?Qt:c,f=wS(en(`{{ menu "${e}" }}`,t,2,+!!l),Yt([{verb:Ft,args:[u,o,d,s,`0`]}]),!1);return f[LS]=l?[FS(e,{key:s,stateVar:s},[[o,Qt],[s,`0`]],n.closeOnPick,n.paged,a)]:[],f}const BS=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function VS(e,t){let n=t[t.length-1],r=BS(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:E_(r??{})}}function HS(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=VS(t,n);return zS(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function US(){return{current:null}}function WS(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 GS(e){let t={fn:(()=>{let t=WS(e,`bgOf`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`};return{...Nc(()=>WS(e,`color`).palette),bgOf:t}}function KS(e){let t=[],n=[];for(let r of e){if(!r.contains(`
162
+ `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const Ux=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Wx=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Gx=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Kx=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function qx(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>Ux[e.getMonth()]],[`Monday`,e=>Gx[e.getDay()]],[`Jan`,e=>Wx[e.getMonth()]],[`Mon`,e=>Kx[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const Jx={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Yx(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=Jx[t];try{return $x(r,e)}catch{return eS(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return cn(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return cn(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return cn(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return cn(e.stashCount,0)}}var Xx=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},Zx=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ie(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(D(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())D(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Qx(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function $x(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?yx(e):t===`number`?bx(e):xx(e)}function eS(e){return e===`number`?0:e===`boolean`?!1:``}var tS=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new Xx;ttlMgr=new Zx;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=Ix();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new Kr({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,vx(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){let r=zx(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=Lx(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return qx(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,qx(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=Jx[t.field],r=t.varDefault===void 0?eS(n):$x(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe:this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,Yx(t,n,i,this.defaultEmptyValue))})})},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Qx(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,$x(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Y.reaction)(()=>{let t=Lx(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Y.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await Vx(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await Hx(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,$x(this.defaultEmptyValue,t))}catch{this.store.setBox(e,eS(t))}}defaultFor(e){try{return $x(this.defaultEmptyValue,e)}catch{return eS(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}};const nS=new Map,rS=new Map;function iS(e){let t=Ic(e),n=nS.get(t);if(n!==void 0)return n;let r=wo(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return nS.set(t,r),r}function aS(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=rS.get(n);if(r!==void 0)return r;let i=Io(e,t);return rS.set(n,i),i}const oS=[`primary`,`secondary`,`accent`],sS=[`surface`,`panel`,`surface-lighten-1`],cS=[.16,.3];cS.reduce((e,t)=>t>e?t:e),cS.flatMap(e=>oS.flatMap(t=>sS.map(n=>({base:n,hue:t,amount:e}))));function lS(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=uS(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=uS([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function uS(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>dS(e,t)):e,r=os.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function dS(e,t){let n=e.copy();return n.style=t.add(e.style),n}function fS(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function pS(e,t){let n=os.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function mS(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=pS(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var hS=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function gS(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=_S(r,a),c=s===void 0?void 0:vS(n,s,`bg`);o.bg=c;let l=_S(i,a),u=l===void 0?void 0:vS(n,l,`fg`);return new q({bgcolor:c===void 0?void 0:Oa.fromRgba(c),color:u===void 0?void 0:Oa.fromRgba(u)})}function _S(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function vS(e,t,n){try{return ro(e,t)}catch(e){throw e instanceof eo?new hS(t,n,e.message):e}}const yS=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function bS(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,xS(e,a,o,n,r));return i}function xS(e,t,n,r,i){if(Jv(n)){let[a,o]=Yv(n);return SS(r.get(n.persistWhen)??n.persistWhen,n.set,xS(e,t,a,r,i),xS(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...Zy(n.from,i)]}:`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=yS.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...Zy(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...Zy(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:wS(e,n.copy,t)}:`open`in n?{kind:`open`,target:wS(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function SS(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function CS(e,t){return e.kind===`dual`?$c(TS(t,e.selector))===!0?e.durable:e.session:e}function wS(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function TS(e,t){return e.has(t)?yx(e.read(t)):``}function ES(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function DS(e,t,n){let r=new os(e,{style:new q({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function OS(e,t){return Math.max(e.members.indexOf(TS(t,e.stateVar)),0)}function kS(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=TS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=TS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=TS(r,e.stateVar);return{effects:[{verb:Ft,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(OS(e,r)+1)%e.members.length];return{effects:[{verb:Ft,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:It,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Lt,args:[ES(e.text,Lx(r))]}],active:!1};case`open`:return{effects:[{verb:Rt,args:[ES(e.target,Lx(r))]}],active:!1};case`persist-literal`:{let t=TS(r,e.stateVar);return{effects:[{verb:Vt,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=TS(r,e.stateVar);return{effects:[{verb:Vt,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(OS(e,r)+1)%e.members.length];return{effects:[{verb:Vt,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Ht,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Ut,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Gt,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Kt,args:[i]}],active:!1};case`layout-op`:return{effects:[{verb:Wt,args:[i,e.key,L_(e.op)]}],active:!1};case`dual`:{let a=CS(e,r),{effects:o,active:s}=kS(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Wt,args:[i,e.key,L_(r)]}],active:!1}}}}function AS(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:en(`action "${e}"`,n,t.members.length,OS(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 jS(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}=AS(e,CS(r,i),t,i),{effects:s,active:c}=kS(r,a,o,i,TS(i,`session.id`));return DS(a,Yt(s),c)}function MS(e){return{action:{fn:(t,...n)=>jS(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function NS(e){return new os(e).cellLength}function PS(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 FS(e,t){let n=[];for(let t of e)n.length>0&&n.push(new os(` `)),n.push(t);let r=os.fromFragments(n);return r.noWrap=t,r.end=``,r}function IS(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 LS(e,t){let n=e.compiled.get(t),r=n&&CS(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker 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 ${r?`a ${r.kind} action`:`no such action`}`);return r}function RS(e,t,n,r,i,a){let o=LS(a,e),s=a.compiled.get(e),c=a.store,l=TS(c,`session.id`),u=`stateVar`in o?TS(c,o.stateVar):void 0,d=o.options.map(NS),f=i?Math.max(1,bx(c.read(`term.cols`))-mh(a.stripStyle)-2*a.padding):1/0,p=NS(`✕`)+1,m=NS(`←`)+1+NS(`→`)+1,h=PS(d,f,p),g=h.length>1?PS(d,f,p+m):h,_=parseInt(TS(c,t.stateVar),10),v=Number.isInteger(_)?Math.max(0,Math.min(_,g.length-1)):0,y=g[v]??[],b=e=>Yt([{verb:Ft,args:[l,t.key,String(e)]}]),x=n.flatMap(([e,t])=>[e,t]),S=Yt([{verb:Ft,args:[l,...x]}]),C=r?[{verb:Ft,args:[l,...x]}]:[],ee=e=>{let{effects:t}=kS(s,e,e,c,l),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?Yt([{verb:Ft,args:[...n.args,...r?x:[]]}]):Yt([...t,...C])},w=[DS(`✕`,S,!1)];v>0&&w.push(DS(`←`,b(v-1),!1));for(let e of y){let t=o.options[e];w.push(DS(t,ee(t),t===u))}return v<g.length-1&&w.push(DS(`→`,b(v+1),!1)),FS(w,i)}function zS(e){return{picker:{fn:(t,n,r,i)=>{let a=IS(e,n,`set-int`,`an int action ({ set, int: true })`);return RS(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const BS=Symbol(`cc-candybar.menuDrop`);function VS(e){return e.flatMap(e=>e[BS]??[])}function HS(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=C_(i.segName,e,n.key),s=T_(o),c=S_(e),l=TS(a.store,o)===c,u=TS(a.store,`session.id`),d=l?Qt:c,f=DS(en(`{{ menu "${e}" }}`,t,2,+!!l),Yt([{verb:Ft,args:[u,o,d,s,`0`]}]),!1);return f[BS]=l?[RS(e,{key:s,stateVar:s},[[o,Qt],[s,`0`]],n.closeOnPick,n.paged,a)]:[],f}const US=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function WS(e,t){let n=t[t.length-1],r=US(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:E_(r??{})}}function GS(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=WS(t,n);return HS(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function KS(){return{current:null}}function qS(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 JS(e){let t={fn:(()=>{let t=qS(e,`bgOf`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`};return{...Nc(()=>qS(e,`color`).palette),bgOf:t}}function YS(e){let t=[],n=[];for(let r of e){if(!r.contains(`
163
163
  `)){n.push(r);continue}let e=r.split(`
164
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function qS(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const JS={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return qS(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name}},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,a=t.nextHueShift();if(!t.visible)return[];try{if(!lS(i.when,t.scope))return[];let n=i.palette===void 0?t.look:Ga,o=aS(i.palette??t.basePalette,{...n,hueShift:n.hueShift+a}),s=t.enterSegment(e.name,o,i.bg,i.fg),c=i.template.evaluate(t.scope),l=t.exitSegment(c),u=l.length>0?t.focusTint(s):s,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=KS(oS(c,u)).map(e=>dS(e,d)),p=l.map(e=>dS(oS([e],u),d)),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),m}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new os(`⚠ ${e.name}: ${r}`)]]}}}};function YS(e){return JS[e]}function XS(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Bx(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 ZS(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,regex:n.regex,cache:XS(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:XS(n.cache),varDefault: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?Bx(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 QS(e,t){let n=Il.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}function $S(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=US(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=al(e.presets),l=new Map([...Yy(e),...Rv(e)]),u=Ix({...kS(i),...IS(i),...HS(o),...GS(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=QS(u,e.helpers),f=e=>u.parse(e,d),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.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`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=_S(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{ZS(t,n,i,r)}catch(e){m.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{ZS(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[t]={when:n.when===void 0?void 0:e(n.when,`when`),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`),palette:n.palette===void 0?void 0:iS(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),compileChild:_};return YS(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=cl(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function eC(e){let t=e.bgcolor;return t===void 0?e:new q({bgcolor:Oa.fromRgba(uo(t.getTruecolor(),1)),color:e.color})}function tC(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=Ga,preset:f=rl}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=Lx(n),m=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,h=Number.isFinite(m)?m:0;l?.clear();let g={value:0},_=()=>{let e=g.value*h;return g.value+=1,e},v=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},y=(e,n,r,i)=>pS(t.activeSegment,e,n,r,i,p),b=e=>(t.activeSegment.current=null,RS(e)),x=(e,t)=>{let n={scope:p,basePalette:a,look:d,visible:t&&lS(e.when,p),padding:o.padding,nextHueShift:_,perSegmentSink:l,onSegmentError:u,enterSegment:y,exitSegment:b,focusTint:eC,lookupSegment:v,renderChild:x};return YS(e.kind).render(e,n)},S=t.roots.get(f);if(S===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${rl}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return x(S,!0).map(e=>hh(e,o)).join(`
165
- `)}const nC=/^-?\d+$/;function rC(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function iC(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 aC(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!nC.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 oC(e,t,n){return r=>r?nC.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 sC(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=>!nC.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:rC(r[0].seed,t,i)}}return{kind:`int`}}function cC(e){return e===`config`?`set-config`:`set-state`}function lC(e,t,n){return t.kind===`int`?aC(`menu page "${e}"`):t.kind===`range`?oC(t.min,t.max,`${n} stepper "${e}"`):iC(t.allowed,`${n} "${e}"`,cC(n))}function uC(e,t,n){return lC(e,sC(e,t,n),n)}function dC(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:sC(e,n,t)}))}function fC(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=uC(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:uC(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=uC(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=sC(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const pC=Bc(),mC=new Set(pC),hC=new Set(Wc),gC=e=>e?mC.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${pC.join(`, `)})`}:{ok:!1,reason:`theme name is required`},_C=e=>e?hC.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Wc.join(`, `)})`}:{ok:!1,reason:`style name is required`},vC=new Set([`1`,`true`]),yC=new Set([`0`,`false`]),bC=fC({style:_C,theme:gC,"toolbar-expanded":e=>vC.has(e)?{ok:!0,value:`1`}:yC.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function xC(){return bC.listKeys()}function SC(e,t){return bC.register(e,t)}function CC(e,t){return bC.validate(e,t)}function wC(e){return bC.rangeParamsFor(e)}function TC(e,t,n){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:Zy(e.from,n)}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:rC(t.get(e.set),e.min,e.max)}}]:[]}function EC(e){let t=new Set(bC.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function DC(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of _g(e.globals))t.set(n,r);return t}function OC(e){let t=DC(e),n=Yy(e);return EC(Object.values(e.actions).flatMap(Yv).flatMap(e=>TC(e,t,n)))}function kC(e){return dC(OC(e))}const AC=fC({},`config`);function jC(){return AC.listKeys()}function MC(e,t){return AC.validate(e,t)}function NC(e){return AC.rangeParamsFor(e)}function PC(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Zy(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[L_({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[L_({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Zy(e.insertSegmentFrom,n).map(t=>L_({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:rC(t.get(e.persist),e.min,e.max)}}]:[]}function FC(e){return _g(e.globals)}function IC(e){let t=new Set;for(let n of RC(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=U_(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:H_(e),spec:{kind:`allow-list`,allowed:[]}}))}function LC(e){let t=FC(e),n=new Map([...Yy(e),...Rv(e)]);return[...IC(e),...RC(e).flatMap(e=>PC(e,t,n))]}function RC(e){return Object.values(e.actions).flatMap(Yv)}function zC(e){return dC(LC(e),`config`)}function BC(e,t){return AC.register(e,t)}var VC=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,UC(e,t,n,`initial value`),this.cell=Y.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){UC(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},HC=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Y.computed)(()=>{let e=n();return UC(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function UC(e,t,n,r){let i=vx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var WC=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new VC(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new HC(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,Y.runInAction)(()=>n.set(t))}runInAction(e){(0,Y.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function GC(e,t,n){return e+`\0`+t+`\0`+(n??``)}function KC(e,t){return new Set(al(e.presets).filter(n=>cl(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function qC(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function JC(e,t){let n=new Map;for(let t of wb(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=qC(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}var YC=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=GC(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=Ob(e,t,n),i=kb(e,t),a;try{a=this.buildState(t,r)}catch(e){return{resolvedPath:r,warning:i,state:null,error:e instanceof Zm||e instanceof Error?e.message:String(e)}}return{resolvedPath:r,warning:[i,...a.compiled.loadWarnings].filter(Boolean).join(`
166
- `)||null,state:a,error:null}}buildState(e,t){let{config:n,raw:r,source:i}=Ab(t,_x),a=jb(n,t??`<default>`,i),o=new WC,s=new tS(o,a.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),c,l=[];try{c=$S(a,s,{cwd:e});for(let{key:e,spec:t}of kC(a))l.push(SC(e,t));for(let{key:e,spec:t}of zC(a))l.push(BC(e,t))}catch(e){for(let e of l)e();throw s.dispose(),e}return{config:a,store:o,registry:s,compiled:c,neededInputPaths:Xb(a),lastRenderCellsBySegment:new Map,validatorDisposers:l,authoredRoots:KC(n,r)}}refreshWatcher(e,t){e.configFilePath=t;let n=JC(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){j(`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 XC=16384;var ZC=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<XC){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%XC}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:sn,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const QC={load:()=>({}),save:()=>{},flush:()=>{}};function $C(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var ew=class{sessions;storage;atom=(0,Y.createAtom)(`SessionState`);constructor(e=QC,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=$C(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,Y.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,Y.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,Y.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const tw=(e,t)=>O(t);function nw(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 rw=class{timer=null;pending=null;constructor(e,t=500,n=tw){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 nw(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},$=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},iw=class extends Error{constructor(e,t){super(`${e} (at offset ${t})`),this.offset=t,this.name=`Json5EditError`}};const aw=/[A-Za-z_$\p{L}]/u,ow=/[A-Za-z0-9_$\u200C\u200D\p{L}\p{N}]/u,sw=/[A-Za-z0-9_$.+\-\p{L}\p{N}]/u,cw=/[\t\n\v\f\r \u00A0\uFEFF\u2028\u2029\p{Zs}]/u;var lw=class{pos=0;constructor(e){this.text=e}peek(){return this.text[this.pos]??``}fail(e){throw new iw(e,this.pos)}skipTrivia(){for(;;){let e=this.peek();if(e===``)return;if(cw.test(e))this.pos++;else if(e===`/`&&this.text[this.pos+1]===`/`){let e=this.text.indexOf(`
167
- `,this.pos);this.pos=e===-1?this.text.length:e}else if(e===`/`&&this.text[this.pos+1]===`*`){let e=this.text.indexOf(`*/`,this.pos+2);e===-1&&this.fail(`unterminated block comment`),this.pos=e+2}else return}}expect(e){this.peek()!==e&&this.fail(`expected "${e}"`),this.pos++}value(){this.skipTrivia();let e=this.peek();if(e===`{`)return this.object();if(e===`[`)return this.array();if(e===`"`||e===`'`){let e=this.stringSpan();return{kind:`string`,span:e,value:this.decode(e)}}e===``&&this.fail(`unexpected end of input`);let t=this.pos;for(;this.pos<this.text.length&&sw.test(this.peek());)this.pos++;this.pos===t&&this.fail(`unexpected character "${e}"`);let n={start:t,end:this.pos},r=this.decode(n);return r===null?{kind:`null`,span:n}:typeof r==`boolean`?{kind:`boolean`,span:n,value:r}:typeof r==`number`?{kind:`number`,span:n,value:r}:this.fail(`unexpected word "${this.text.slice(t,this.pos)}"`)}decode(e){try{return Oh.default.parse(this.text.slice(e.start,e.end))}catch(t){throw new iw(t.message,e.start)}}stringSpan(){let e=this.pos,t=this.peek();for(this.pos++;;){let n=this.peek();if(n===``&&this.fail(`unterminated string`),n===`\\`){let e=this.text.startsWith(`\r
164
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function XS(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const ZS={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return XS(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name}},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,a=t.nextHueShift();if(!t.visible)return[];try{if(!fS(i.when,t.scope))return[];let n=i.palette===void 0?t.look:Ga,o=aS(i.palette??t.basePalette,{...n,hueShift:n.hueShift+a}),s=t.enterSegment(e.name,o,i.bg,i.fg),c=i.template.evaluate(t.scope),l=t.exitSegment(c),u=l.length>0?t.focusTint(s):s,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=YS(lS(c,u)).map(e=>mS(e,d)),p=l.map(e=>mS(lS([e],u),d)),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),m}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new os(`⚠ ${e.name}: ${r}`)]]}}}};function QS(e){return ZS[e]}function $S(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Bx(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 eC(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,regex:n.regex,cache:$S(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:$S(n.cache),varDefault: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?Bx(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 tC(e,t){let n=Il.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}function nC(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=KS(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=al(e.presets),l=new Map([...Yy(e),...Rv(e)]),u=Ix({...MS(i),...zS(i),...GS(o),...JS(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=tC(u,e.helpers),f=e=>u.parse(e,d),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.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`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=bS(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{eC(t,n,i,r)}catch(e){m.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{eC(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[t]={when:n.when===void 0?void 0:e(n.when,`when`),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`),palette:n.palette===void 0?void 0:iS(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),compileChild:_};return QS(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=cl(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function rC(e){let t=e.bgcolor;return t===void 0?e:new q({bgcolor:Oa.fromRgba(uo(t.getTruecolor(),1)),color:e.color})}function iC(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=Ga,preset:f=rl}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=Lx(n),m=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,h=Number.isFinite(m)?m:0;l?.clear();let g={value:0},_=()=>{let e=g.value*h;return g.value+=1,e},v=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},y=(e,n,r,i)=>gS(t.activeSegment,e,n,r,i,p),b=e=>(t.activeSegment.current=null,VS(e)),x=(e,t)=>{let n={scope:p,basePalette:a,look:d,visible:t&&fS(e.when,p),padding:o.padding,nextHueShift:_,perSegmentSink:l,onSegmentError:u,enterSegment:y,exitSegment:b,focusTint:rC,lookupSegment:v,renderChild:x};return QS(e.kind).render(e,n)},S=t.roots.get(f);if(S===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${rl}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return x(S,!0).map(e=>hh(e,o)).join(`
165
+ `)}const aC=/^-?\d+$/;function oC(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function sC(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 cC(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!aC.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 lC(e,t,n){return r=>r?aC.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 uC(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=>!aC.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:oC(r[0].seed,t,i)}}return{kind:`int`}}function dC(e){return e===`config`?`set-config`:`set-state`}function fC(e,t,n){return t.kind===`int`?cC(`menu page "${e}"`):t.kind===`range`?lC(t.min,t.max,`${n} stepper "${e}"`):sC(t.allowed,`${n} "${e}"`,dC(n))}function pC(e,t,n){return fC(e,uC(e,t,n),n)}function mC(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:uC(e,n,t)}))}function hC(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=pC(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:pC(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=pC(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=uC(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const gC=Bc(),_C=new Set(gC),vC=new Set(Wc),yC=e=>e?_C.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${gC.join(`, `)})`}:{ok:!1,reason:`theme name is required`},bC=e=>e?vC.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Wc.join(`, `)})`}:{ok:!1,reason:`style name is required`},xC=new Set([`1`,`true`]),SC=new Set([`0`,`false`]),CC=hC({style:bC,theme:yC,"toolbar-expanded":e=>xC.has(e)?{ok:!0,value:`1`}:SC.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function wC(){return CC.listKeys()}function TC(e,t){return CC.register(e,t)}function EC(e,t){return CC.validate(e,t)}function DC(e){return CC.rangeParamsFor(e)}function OC(e,t,n){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:Zy(e.from,n)}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:oC(t.get(e.set),e.min,e.max)}}]:[]}function kC(e){let t=new Set(CC.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function AC(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of _g(e.globals))t.set(n,r);return t}function jC(e){let t=AC(e),n=Yy(e);return kC(Object.values(e.actions).flatMap(Yv).flatMap(e=>OC(e,t,n)))}function MC(e){return mC(jC(e))}const NC=hC({},`config`);function PC(){return NC.listKeys()}function FC(e,t){return NC.validate(e,t)}function IC(e){return NC.rangeParamsFor(e)}function LC(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Zy(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[L_({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[L_({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Zy(e.insertSegmentFrom,n).map(t=>L_({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:oC(t.get(e.persist),e.min,e.max)}}]:[]}function RC(e){return _g(e.globals)}function zC(e){let t=new Set;for(let n of VC(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=U_(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:H_(e),spec:{kind:`allow-list`,allowed:[]}}))}function BC(e){let t=RC(e),n=new Map([...Yy(e),...Rv(e)]);return[...zC(e),...VC(e).flatMap(e=>LC(e,t,n))]}function VC(e){return Object.values(e.actions).flatMap(Yv)}function HC(e){return mC(BC(e),`config`)}function UC(e,t){return NC.register(e,t)}var WC=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,KC(e,t,n,`initial value`),this.cell=Y.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){KC(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},GC=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Y.computed)(()=>{let e=n();return KC(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function KC(e,t,n,r){let i=vx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var qC=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new WC(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new GC(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,Y.runInAction)(()=>n.set(t))}runInAction(e){(0,Y.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function JC(e,t,n){return e+`\0`+t+`\0`+(n??``)}function YC(e,t){return new Set(al(e.presets).filter(n=>cl(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function XC(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function ZC(e,t){let n=new Map;for(let t of wb(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=XC(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}var QC=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=JC(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=Ob(e,t,n),i=kb(e,t),a;try{a=this.buildState(t,r)}catch(e){return{resolvedPath:r,warning:i,state:null,error:e instanceof Zm||e instanceof Error?e.message:String(e)}}return{resolvedPath:r,warning:[i,...a.compiled.loadWarnings].filter(Boolean).join(`
166
+ `)||null,state:a,error:null}}buildState(e,t){let{config:n,raw:r,source:i}=Ab(t,_x),a=jb(n,t??`<default>`,i),o=new qC,s=new tS(o,a.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),c,l=[];try{c=nC(a,s,{cwd:e});for(let{key:e,spec:t}of MC(a))l.push(TC(e,t));for(let{key:e,spec:t}of HC(a))l.push(UC(e,t))}catch(e){for(let e of l)e();throw s.dispose(),e}return{config:a,store:o,registry:s,compiled:c,neededInputPaths:Xb(a),lastRenderCellsBySegment:new Map,validatorDisposers:l,authoredRoots:YC(n,r)}}refreshWatcher(e,t){e.configFilePath=t;let n=ZC(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){j(`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 $C=16384;var ew=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<$C){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%$C}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:sn,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const tw={load:()=>({}),save:()=>{},flush:()=>{}};function nw(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var rw=class{sessions;storage;atom=(0,Y.createAtom)(`SessionState`);constructor(e=tw,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=nw(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,Y.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,Y.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,Y.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const iw=(e,t)=>O(t);function aw(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 ow=class{timer=null;pending=null;constructor(e,t=500,n=iw){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 aw(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},$=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},sw=class extends Error{constructor(e,t){super(`${e} (at offset ${t})`),this.offset=t,this.name=`Json5EditError`}};const cw=/[A-Za-z_$\p{L}]/u,lw=/[A-Za-z0-9_$\u200C\u200D\p{L}\p{N}]/u,uw=/[A-Za-z0-9_$.+\-\p{L}\p{N}]/u,dw=/[\t\n\v\f\r \u00A0\uFEFF\u2028\u2029\p{Zs}]/u;var fw=class{pos=0;constructor(e){this.text=e}peek(){return this.text[this.pos]??``}fail(e){throw new sw(e,this.pos)}skipTrivia(){for(;;){let e=this.peek();if(e===``)return;if(dw.test(e))this.pos++;else if(e===`/`&&this.text[this.pos+1]===`/`){let e=this.text.indexOf(`
167
+ `,this.pos);this.pos=e===-1?this.text.length:e}else if(e===`/`&&this.text[this.pos+1]===`*`){let e=this.text.indexOf(`*/`,this.pos+2);e===-1&&this.fail(`unterminated block comment`),this.pos=e+2}else return}}expect(e){this.peek()!==e&&this.fail(`expected "${e}"`),this.pos++}value(){this.skipTrivia();let e=this.peek();if(e===`{`)return this.object();if(e===`[`)return this.array();if(e===`"`||e===`'`){let e=this.stringSpan();return{kind:`string`,span:e,value:this.decode(e)}}e===``&&this.fail(`unexpected end of input`);let t=this.pos;for(;this.pos<this.text.length&&uw.test(this.peek());)this.pos++;this.pos===t&&this.fail(`unexpected character "${e}"`);let n={start:t,end:this.pos},r=this.decode(n);return r===null?{kind:`null`,span:n}:typeof r==`boolean`?{kind:`boolean`,span:n,value:r}:typeof r==`number`?{kind:`number`,span:n,value:r}:this.fail(`unexpected word "${this.text.slice(t,this.pos)}"`)}decode(e){try{return Oh.default.parse(this.text.slice(e.start,e.end))}catch(t){throw new sw(t.message,e.start)}}stringSpan(){let e=this.pos,t=this.peek();for(this.pos++;;){let n=this.peek();if(n===``&&this.fail(`unterminated string`),n===`\\`){let e=this.text.startsWith(`\r
168
168
  `,this.pos+1);this.pos+=e?3:2;continue}if(this.pos++,n===t)return{start:e,end:this.pos};n===`
169
- `&&this.fail(`unterminated string`)}}key(){let e=this.peek();if(e===`"`||e===`'`){let e=this.stringSpan();return{key:this.decode(e),span:e}}let t=this.pos;for(aw.test(e)||this.fail(`expected an object key`);this.pos<this.text.length&&ow.test(this.peek());)this.pos++;return{key:this.text.slice(t,this.pos),span:{start:t,end:this.pos}}}object(){let e=this.pos;this.expect(`{`);let t=[];for(;this.skipTrivia(),this.peek()!==`}`;){let{key:e,span:n}=this.key();if(t.some(t=>t.key===e))throw new iw(`duplicate key "${e}"`,n.start);this.skipTrivia(),this.expect(`:`);let r=this.value();if(t.push({key:e,keySpan:n,value:r,span:{start:n.start,end:r.span.end}}),this.skipTrivia(),this.peek()===`,`){this.pos++;continue}this.peek()!==`}`&&this.fail(`expected "," or "}"`)}return this.expect(`}`),{kind:`object`,span:{start:e,end:this.pos},entries:t}}array(){let e=this.pos;this.expect(`[`);let t=[];for(;this.skipTrivia(),this.peek()!==`]`;){if(t.push(this.value()),this.skipTrivia(),this.peek()===`,`){this.pos++;continue}this.peek()!==`]`&&this.fail(`expected "," or "]"`)}return this.expect(`]`),{kind:`array`,span:{start:e,end:this.pos},elements:t}}};function uw(e){let t=new lw(e),n=t.value();return t.skipTrivia(),t.pos!==e.length&&t.fail(`trailing content after the document`),n}function dw(e,t){return e.kind===`object`?e.entries.find(e=>e.key===t):void 0}function fw(e,t){let n=e;for(let e of t)n=n===void 0?void 0:dw(n,e)?.value;return n}function pw(e,t){return e.slice(t.span.start,t.span.end)}const mw=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function hw(e){return mw.test(e)?e:JSON.stringify(e)}function gw(e){if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>` ${vw(gw(e),` `,`
169
+ `&&this.fail(`unterminated string`)}}key(){let e=this.peek();if(e===`"`||e===`'`){let e=this.stringSpan();return{key:this.decode(e),span:e}}let t=this.pos;for(cw.test(e)||this.fail(`expected an object key`);this.pos<this.text.length&&lw.test(this.peek());)this.pos++;return{key:this.text.slice(t,this.pos),span:{start:t,end:this.pos}}}object(){let e=this.pos;this.expect(`{`);let t=[];for(;this.skipTrivia(),this.peek()!==`}`;){let{key:e,span:n}=this.key();if(t.some(t=>t.key===e))throw new sw(`duplicate key "${e}"`,n.start);this.skipTrivia(),this.expect(`:`);let r=this.value();if(t.push({key:e,keySpan:n,value:r,span:{start:n.start,end:r.span.end}}),this.skipTrivia(),this.peek()===`,`){this.pos++;continue}this.peek()!==`}`&&this.fail(`expected "," or "}"`)}return this.expect(`}`),{kind:`object`,span:{start:e,end:this.pos},entries:t}}array(){let e=this.pos;this.expect(`[`);let t=[];for(;this.skipTrivia(),this.peek()!==`]`;){if(t.push(this.value()),this.skipTrivia(),this.peek()===`,`){this.pos++;continue}this.peek()!==`]`&&this.fail(`expected "," or "]"`)}return this.expect(`]`),{kind:`array`,span:{start:e,end:this.pos},elements:t}}};function pw(e){let t=new fw(e),n=t.value();return t.skipTrivia(),t.pos!==e.length&&t.fail(`trailing content after the document`),n}function mw(e,t){return e.kind===`object`?e.entries.find(e=>e.key===t):void 0}function hw(e,t){let n=e;for(let e of t)n=n===void 0?void 0:mw(n,e)?.value;return n}function gw(e,t){return e.slice(t.span.start,t.span.end)}const _w=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function vw(e){return _w.test(e)?e:JSON.stringify(e)}function yw(e){if(Array.isArray(e))return e.length===0?`[]`:`[\n${e.map(e=>` ${xw(yw(e),` `,`
170
170
  `)},`).join(`
171
- `)}\n]`;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>e!==void 0);return t.length===0?`{}`:`{\n${t.map(([e,t])=>` ${hw(e)}: ${vw(gw(t),` `,`
171
+ `)}\n]`;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>e!==void 0);return t.length===0?`{}`:`{\n${t.map(([e,t])=>` ${vw(e)}: ${xw(yw(t),` `,`
172
172
  `)},`).join(`
173
- `)}\n}`}return JSON.stringify(e)}function _w(e){return e.includes(`\r
173
+ `)}\n}`}return JSON.stringify(e)}function bw(e){return e.includes(`\r
174
174
  `)?`\r
175
175
  `:`
176
- `}function vw(e,t,n){return e.split(`
177
- `).join(`${n}${t}`)}function yw(e,t){let[n,...r]=e,i=r.length===0?t:`{\n ${vw(yw(r,t),` `,`
178
- `)},\n}`;return`${hw(n)}: ${i}`}function bw(e,t,n,r){return e.slice(0,t)+r+e.slice(n)}function xw(e,t){return e.lastIndexOf(`
179
- `,t-1)+1}function Sw(e){return/^[ \t]*$/.test(e)}function Cw(e,t){let n=xw(e,t);return/^[ \t]*/.exec(e.slice(n))[0]}function ww(e,t){return Sw(e.slice(xw(e,t),t))}const Tw=/(?:\/\/[^\n]*?)?(\r\n|\n|$)/y;function Ew(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n++;let r=e[n]===`,`?n+1:-1;for(r!==-1&&(n=r);n<e.length&&(e[n]===` `||e[n]===` `);)n++;Tw.lastIndex=n;let i=Tw.exec(e);if(i===null)return{commaEnd:r,line:null};let a=n+i[0].length;return{commaEnd:r,line:{at:a-i[1].length,next:a}}}function Dw(e,t){let{commaEnd:n,line:r}=Ew(e,t.end);if(ww(e,t.start)&&r!==null)return bw(e,xw(e,t.start),r.next,``);if(n!==-1){let r=n;for(;r<e.length&&e[r]===` `;)r++;return bw(e,t.start,r,``)}let i=t.start;for(;i>0&&(e[i-1]===` `||e[i-1]===` `);)i--;return e[i-1]===`,`?bw(e,i-1,t.end,``):bw(e,t.start,t.end,``)}function Ow(e,t,n,r,i){let a=n.commaEnd!==-1,o=a?e:bw(e,t.end,t.end,`,`),s=n.line.at+ +!a,c=_w(e);return bw(o,s,s,`${c}${i}${vw(r,i,c)}${a?`,`:``}`)}function kw(e,t,n){let r=t.kind===`object`?t.entries:t.elements,i=r[r.length-1],a=Cw(e,t.span.start);if(i===void 0){let r=a+` `,i=_w(e);return bw(e,t.span.start+1,t.span.end-1,`${i}${r}${vw(n,r,i)},${i}${a}`)}let{commaEnd:o,line:s}=Ew(e,i.span.end);if(ww(e,i.span.start)&&s!==null){let t=e.slice(xw(e,i.span.start),i.span.start);return Ow(e,i.span,{commaEnd:o,line:s},n,t)}let c=o===-1?i.span.end:o;return bw(e,c,c,`${o===-1?`, `:` `}${n}${o===-1?``:`,`}`)}function Aw(e,t,n){if(t.length===0)throw new iw(`setValue needs a non-empty path`,0);if(/^\s*$/.test(e)){let r=_w(e);return`{${r} ${vw(yw(t,n),` `,r)},${r}}${r}`}let r=uw(e);for(let i=0;i<t.length;i++){if(r.kind!==`object`)throw new iw(`cannot set ${t.join(`.`)}: ${t.slice(0,i).join(`.`)||`the document`} is not an object`,r.span.start);let a=dw(r,t[i]);if(a===void 0)return kw(e,r,yw(t.slice(i),n));if(i===t.length-1){let t=Cw(e,a.keySpan.start);return bw(e,a.value.span.start,a.value.span.end,vw(n,t,_w(e)))}r=a.value}throw new iw(`unreachable: path exhausted`,0)}function jw(e,t){if(t.length===0)throw new iw(`deleteValue needs a non-empty path`,0);if(/^\s*$/.test(e))return e;let n=fw(uw(e),t.slice(0,-1)),r=n===void 0?void 0:dw(n,t[t.length-1]);return r===void 0?e:Dw(e,r.span)}const Mw=[`h`,`v`,`children`];function Nw(e){if(e.kind===`string`)return e.value;if(e.kind!==`object`)return;let t=dw(e,`seg`)?.value;if(t?.kind===`string`)return t.value;let n=dw(e,`kind`)?.value,r=dw(e,`name`)?.value;return n?.kind===`string`&&n.value===`segment`&&r?.kind===`string`?r.value:void 0}function Pw(e){return e.kind===`object`?Mw.map(t=>dw(e,t)?.value).filter(e=>e?.kind===`array`):[]}function Fw(e,t){let n=fw(uw(e),t);if(n===void 0)return null;if(Pw(n).length>0)return{text:e,root:n};let r=Aw(e,t,`{ h: [${pw(e,n)}] }`);return{text:r,root:fw(uw(r),t)}}function Iw(e,t){for(let n of Pw(e))for(let[e,r]of n.elements.entries()){if(Nw(r)===t)return{array:n,index:e};let i=Iw(r,t);if(i!==null)return i}return null}function Lw(e,t,n){let r=Fw(e,t);if(r===null)return null;let i=Iw(r.root,n);return i===null?null:Dw(r.text,i.array.elements[i.index].span)}function Rw(e,t,n,r,i){let a=Fw(e,t);if(a===null)return null;let o=Iw(a.root,r);if(o===null)return null;let s=a.text,c=o.array.elements[o.index],l=JSON.stringify(n),{commaEnd:u,line:d}=Ew(s,c.span.end);if(ww(s,c.span.start)&&d!==null){let e=s.slice(xw(s,c.span.start),c.span.start);return i===`after`?Ow(s,c.span,{commaEnd:u,line:d},l,e):bw(s,c.span.start,c.span.start,`${l},${_w(s)}${e}`)}let f=pw(s,c),p=i===`before`?`${l}, ${f}`:`${f}, ${l}`;return bw(s,c.span.start,c.span.end,p)}const zw={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,colorCompatibility:`string`},Bw=new Set([`1`,`true`]),Vw=new Set([`0`,`false`,``]);function Hw(e,t){let n=U_(e);if(n===null||n.scope===`preset-root`)throw Error(`persistValueText: "${e}" does not name a value`);let r=n.scope===`globals`?zw[n.field]:`string`;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(Bw.has(t))return`true`;if(Vw.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function Uw(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Ww(e,t,n){let i=`${e}.tmp`;try{r.writeFileSync(i,t,n===void 0?{}:{mode:n}),r.renameSync(i,e)}catch(e){throw r.rmSync(i,{force:!0}),e}}function Gw(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ww(e,t,r.statSync(e,{throwIfNoEntry:!1})?.mode)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Kw(e){return/^\s*$/.test(e)?null:uw(e)}function qw(e,t){return e!==null&&fw(e,t)!==void 0}function Jw(e){return e.kind===`segment`?e.when===void 0?e.name:{seg:e.name,when:e.when}:e.kind===`container`?{[e.direction===`horizontal`?`h`:`v`]:e.children.map(Jw),...e.when!==void 0&&{when:e.when}}:e}function Yw(e){return{...e.root!==void 0&&{root:Jw(e.root)},...e.globals!==void 0&&{globals:e.globals}}}const Xw=hx,Zw=Xw.segments,Qw=Xw.presets;function $w(e,t,n,r){if(qw(e,t))return{source:`file`};if(n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`);return{source:`bundled`,decl:n}}function eT(e,t,n){return e.source===`file`?null:{path:t,value:n(e.decl)}}function tT(e,t){if(t.scope===`globals`)return{path:G_(t),unit:null};if(t.scope===`segment-palette`){let n=G_(t),r=[`segments`,t.segment];return{path:n,unit:eT($w(e,r,Zw[t.segment],n.join(`.`)),r,e=>e)}}let n=[`presets`,t.preset],r=$w(e,n,Qw[t.preset],[...n,`root`].join(`.`));return(r.source===`file`?qw(e,[...n,`root`]):r.decl.root!==void 0)?{path:W_(t.preset,!0),unit:eT(r,n,Yw)}:{path:W_(t.preset,!1),unit:eT($w(e,[`root`],Xw.root,`root`),[`root`],Jw)}}function nT(e,{unit:t}){return t===null?e:Aw(e,t.path,gw(t.value))}function rT(e){let t=U_(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function iT(e,t){let n=rT(t);if(n.scope===`preset-root`)return;let r=Kw(Uw(e)??``),i=r===null?void 0:fw(r,G_(n));return i!==void 0&&`value`in i?i.value:void 0}function aT(e,t,n,r){let i=rT(n),a=Uw(t),o=tT(Kw(a??``),i);hT(e,t,{before:a,after:Aw(nT(a??``,o),o.path,Hw(n,r))})}function oT(e,t,n){let r=rT(n),i=Uw(t);if(i===null)return;let a=jw(i,tT(Kw(i),r).path);a!==i&&hT(e,t,{before:i,after:a})}function sT(e,t,n,r){let i=rT(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=Uw(t),o=tT(Kw(a??``),i),s=nT(a??``,o),c=r.op===`remove`?Lw(s,o.path,r.target):Rw(s,o.path,r.segment,r.anchor,r.relation);if(c===null){let e=r.op===`remove`?r.target:r.anchor;throw new $(`${o.path.join(`.`)} in ${t} has no segment "${e}" — the bar you clicked is stale; it reloads on the next render`)}hT(e,t,{before:a,after:c})}const cT={past:[],future:[]};function lT(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function uT(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(lT)&&Array.isArray(t.future)&&t.future.every(lT)}function dT(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(uT))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function fT(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ww(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function pT(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function mT(e,t,n,r,i){Gw(t,n,e.logger);try{fT(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function hT(e,t,n){let r=dT(e),{past:i}=r[t]??cT;mT(e,t,n.after,{...r,[t]:{past:pT(i,n),future:[]}},`edit`)}function gT(e,t){let n=dT(e),{past:r,future:i}=n[t]??cT,a=r[r.length-1];return a===void 0?null:(vT(t,a.after,`undo`),mT(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:pT(i,a)}},`undo`),a)}function _T(e,t){let n=dT(e),{past:r,future:i}=n[t]??cT,a=i[i.length-1];return a===void 0?null:(vT(t,a.before,`redo`),mT(e,t,a.after,{...n,[t]:{past:pT(r,a),future:i.slice(0,-1)}},`redo`),a)}function vT(e,t,n){if(Uw(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function yT(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function bT(e){return xT(()=>decodeURIComponent(e))}function xT(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function ST(e,t){let n=xe({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 CT=(e,t)=>ST(bT(e),t),wT=(e,t)=>{let n=xe({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,bT(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`})`)}},TT=(e,t)=>ST(bT(e),t),ET=(e,t)=>ST(bT(e),t),DT=(e,t)=>{let n=yT(bT(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},OT=(e,t)=>{let[n=``,...r]=xT(()=>Jt(e)),i=yT(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${xC().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: ${xC().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=CC(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},kT=/^-?\d+$/;function AT(e,t,n){return e>n?t:e<t?n:e}function jT(e,t){if(!e)return null;if(!xC().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${xC().join(`, `)})`);return e}function MT(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const NT=(e,t)=>{let[n=``,r=``,i=``]=xT(()=>Jt(e)),a=yT(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!kT.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=wC(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${xC().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&kT.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=AT(l+o,s.min,s.max),d=CC(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},PT=`render-origin`;function FT(e){return JSON.stringify(e)}function IT(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 LT(e,t){let n=e.sessionState.get(t,PT);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=IT(n);return Db(r.projectDir,r.cwd,r.configFile??void 0)}function RT(e){return{historyPath:Ne(),logger:e.dlog}}const zT=(e,t)=>{let[n=``,r=``,i=``,a=``]=xT(()=>Jt(e)),o=yT(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${jC().join(`, `)})`);let s=MC(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=jT(a,`set-config`),l=LT(t,o);aT(RT(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),MT(c,o,t,`set-config`)},BT=(e,t)=>{let[n=``,r=``,i=``,a=``]=xT(()=>Jt(e)),o=yT(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!kT.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=jT(a,`step-config`),l=NC(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${jC().join(`, `)})`);let u=LT(t,o),d=iT(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=AT(f+s,l.min,l.max),m=MC(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);aT(RT(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),MT(c,o,t,`step-config`)},VT=(e,t)=>{let[n=``,r=``]=xT(()=>Jt(e)),i=yT(n);if(!r||!jC().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${jC().join(`, `)})`);let a=LT(t,i);oT(RT(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},HT=(e,t)=>{let[n=``,r=``,i=``]=xT(()=>Jt(e)),a=yT(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${jC().join(`, `)})`);let o=MC(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=R_(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=LT(t,a);sT(RT(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},UT=(e,t)=>{let[n=``]=xT(()=>Jt(e)),r=yT(n),i=LT(t,r);if(gT(RT(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},WT=(e,t)=>{let[n=``]=xT(()=>Jt(e)),r=yT(n),i=LT(t,r);if(_T(RT(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},GT=`config-override`,KT=new Map([[Lt,CT],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=yT(xT(()=>decodeURIComponent(e.slice(0,n)))),i=xT(()=>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,GT),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,GT,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Rt,wT],[Ft,OT],[It,NT],[Vt,zT],[Ht,BT],[Ut,VT],[Wt,HT],[Gt,UT],[Kt,WT],[zt,TT],[Bt,ET],[`toolbar-toggle`,DT]]),qT=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Xt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`set-config`||a===`step-config`||a===`reset-config`||a===`apply-layout-op`||a===`undo`||a===`redo`||a===`toolbar-toggle`)){let e=Jt(o);e.length>0&&e[0]&&(i=e[0])}let e=KT.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(`
180
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},JT=new Map([...KT,[N,qT]]);Object.freeze([...JT.keys()]);const YT=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`]),XT=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]];function ZT(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of XT){let i=$T(n,e);if(i==null)t.missingRequired.push(e);else{let n=QT(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))YT.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function QT(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function $T(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 eE(e,t){switch(e){case`vars`:return{what:e,vars:tE(t)};case`segments`:return{what:e,segments:aE(t)};case`config`:return{what:e,config:cE(t)}}}function tE(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=rE(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,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:nE(r.lastUpdatedMs())})}return o}function nE(e){return e===null?null:Math.max(0,Date.now()-e)}function rE(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,iE(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}`,iE(i));return t}function iE(e){return e.kind}function aE(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=oE(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:sE(t.template,i),lastRender:r.get(e)??null})}return o}function oE(e){let t=[],n=new Set;for(let r of _h(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 sE(e,t){let n=new Set;for(let r of tb(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function cE(e){return e===null?null:e.config}const lE=[`vars`,`segments`,`config`];function uE(e){return typeof e==`string`&&lE.includes(e)}function dE(e){return Math.max(1,e-2)}var fE=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 ci(e);if(n.length===0)return O(`No entries in transcript`),I;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})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),I}catch(e){return L(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function pE(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var mE=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(pE(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}async foldMetrics(e,t){let n=this.state.get(e),r=Xr(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await fi(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(pE(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const hE=new Map;function gE(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var _E=class{async getSessionId(){if(!process.env.TMUX_PANE)return I;let e=gE(process.env.TMUX),t=hE.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await be({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?F(n.stdout.trim()):I:L(`tmux display-message: ${n.reason}`);return hE.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function vE(e){return e<32||e===127||e>=128&&e<=159}function yE(e){let t=``;for(let n of e)t+=vE(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function bE(e,t){let n=yE(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const xE=`\x1B[38;2;255;255;255m`,SE=`\x1B[48;2;200;40;40m`;function CE(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 wE={fg:CE(xE),bg:CE(SE)},TE={fg:CE(`\x1B[38;2;0;0;0m`),bg:CE(`\x1B[48;2;220;160;40m`)};function EE(e){return Math.min(20,e??20)}function DE(e,t){let[n,...r]=[OE(e,zt,wE),OE(t,Bt,TE)].flat();return n===void 0?null:{channels:[n,...r]}}function OE(e,t,n){let[r,...i]=e.split(/\r\n|\r|\n/).map(yE).filter(Boolean);return r===void 0?[]:[{verb:t,colors:n,message:e,lines:[r,...i]}]}function kE(e){return e.channels.map(e=>`${AE[e.verb]}\n${e.message}\n`).join(`
181
- `)}const AE={[zt]:`ERROR`,[Bt]:`WARNING`};function jE(e,t,n,r){if(t===null)return e;let i=ME(r),a=t.channels.flatMap(e=>NE(e,i)),o=a.slice(0,r.rowCap-1),s=[...o,PE(t,n,a.length-o.length,i)].join(`
182
- `);return e?`${s}\n${e}`:s}function ME(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function NE(e,t){let n=new q({bgcolor:e.colors.bg,color:e.colors.fg,link:Yt([{verb:e.verb,args:[e.message]}])}),r=W(Math.max(2,t.width-1));return e.lines.flatMap((e,i)=>hh([i===0?`⚠`:` `,...e.split(` `)].flatMap(e=>ma(e,r)).map(e=>new os(`${e} `,{style:n,end:``,noWrap:!0})),t).split(`
183
- `))}function PE(e,t,n,r){let{colors:i}=e.channels[0],{fullText:a,failedConfigFile:o}=t,s=new q({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new os(e,{style:t,end:``,noWrap:!0}),l=[c(`↳ ${n>0?`${n} more rows · `:``}`,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${yE(a.reason)}`,s)],u=o===null?[]:[c(` · open `,s),c(yE(o),s.withLink(x(o).href))],d=[...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=os.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,hh([m],r)}var FE=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const IE=new ZC;ye(IE.launchStats);const LE=new zr({counters:IE,logger:j}),RE=new Kr({watchers:LE,logger:j}),zE=new wi,BE=new ew,VE=new FE(Re()),HE=new fE,UE=new mE,WE=new _E,GE=new YC({gitService:RE,sessionState:BE,watchers:LE},{observers:{onReload:e=>j(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),KE=60*1e3,qE=hr({entryUrl:import.meta.url,intervalMs:KE,log:j});let JE=null,YE=null,XE=0;function ZE(){t.on(`uncaughtException`,e=>{j(`error`,`uncaughtException: ${e.stack||e.message}`),cD(1)}),t.on(`unhandledRejection`,e=>{j(`error`,`unhandledRejection: ${String(e)}`),cD(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{j(`info`,`received ${e}, shutting down`),cD(0)});try{XE=pt(t.env)}catch(e){j(`error`,`refusing to boot: ${e.message}`),cD(1);return}JE=Yn(t.pid);let e=ar(sr(JE));if(!e.decision.allow){j(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),cD(1);return}YE=e.registryPath,r.mkdirSync(De(),{recursive:!0}),A(Oe()),BE.useStorage(new rw(Me(),500,j)),Qn({anchor:Zn(t.env),isAlive:$n,onOrphaned:e=>{j(`info`,`parent watchdog: ${e}; shutting down`),cD(0)}}),QE(g.createServer({allowHalfOpen:!1},e=>{lD(e)}),Oe(),!1)}function QE(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){j(`error`,`server error: ${i.message}`),cD(1);return}if(r){j(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}$E(e,n)}),e.listen(n,()=>eD(n))}function $E(e,n){let i=Bn(V(Ae(n)),(e,t)=>Jn(e,t,{readStartTime:qn,pidAlive:$n}));if(i.kind===`attach-and-exit`){j(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}j(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){j(`error`,`cannot unlink stale socket ${n}: ${e.message}`),cD(1);return}}QE(e,n,!0)}function eD(e){let n=Un(e);if(n.kind!==`present`){j(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),cD(0);return}aD(e);try{r.chmodSync(e,384)}catch(e){j(`warn`,`chmod socket failed: ${e.message}`)}j(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(XE/1048576)}MB`),Tt();let i=VE.reset();i!==null&&j(`warn`,`diagnostic dump wipe failed: ${i}`),nD(),qE.arm(),iD(),tD(e,n.identity)}function tD(e,n){Kn({bound:n,myPid:t.pid,readIdentity:()=>Un(e),readLease:()=>V(Ae(e)),shutdown:e=>cD(e),log:j}).arm()}function nD(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(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{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){j(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),cD(0);return}}catch(e){j(`warn`,`bin stat failed: ${e.message}`)}},KE);a.unref()}let rD=null;function iD(){rD=mt(gt(IE.startedAt.getTime(),e=>cD(e),{rssLimitBytes:XE})),rD.arm()}function aD(e){let n=Vn(Ae(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:JE});n!==null&&j(`warn`,`lease write failed: ${n}`)}let oD=0,sD=!1;function cD(e){if(!sD){sD=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{RE.close()}catch(e){j(`warn`,`gitService close failed: ${e.message}`)}try{zE.close()}catch(e){j(`warn`,`usageStore close failed: ${e.message}`)}try{LE.closeAll()}catch(e){j(`warn`,`watcherRegistry close failed: ${e.message}`)}try{BE.flush()}catch(e){j(`warn`,`sessionState flush failed: ${e.message}`)}Hn(je(),t.pid),YE!==null&&or(YE,t.pid,rr,e=>r.unlinkSync(e)),t.exit(e)}}function lD(e){oD++,IE.inFlight=oD;let t=!1,n=(n,r)=>{if(t){r!==null&&j(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>cD(r);try{e.end(Ge(n),i)}catch(e){j(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{IE.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Ke(e=>{dD(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{j(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{j(`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=>{j(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),oD=Math.max(0,oD-1),IE.inFlight=oD})}const uD=e=>({resp:e,exitAfterFlush:null});async function dD(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return uD({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?j(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):j(`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 uD({ok:!0,stats:IE.snapshot({gitCache:RE.getStats(),usageCache:zE.getStats(),renderCacheSize:GE.size,watchersActive:LE.size(),nextRestartReason:rD?.describeNextRestart()??null})});if(e.kind===`render`){IE.requestsTotal++;let t=Date.now();try{let{report:n}=ZT(e.hookData);for(let e of n.unknownTopLevelFields)j(`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 IE.requestsErrored++,j(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),uD({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=fD(e.args),s=e.hookData.session_id,c=BE.get(s,`config-override`)??a,l=GE.getOrCreate(i,e.cwd,c),u=FT({projectDir:i,cwd:e.cwd,configFile:c??null});BE.get(s,`render-origin`)!==u&&BE.set(s,PT,u);let d=Be(e),f=d.termCols,p=dE(f??120),m=EE(d.termRows),h={...mD,width:p},{authoredRoots:g}=l.state,_=Vb(l.state.config,t=>BE.get(e.hookData.session_id,t),e=>g.has(e)),v=await ex(e.hookData,vD,e.cwd,l.state.neededInputPaths,_,d),y=iS(_.theme);h.style=_.style,h.separator=_.separator,h.wrap=_.autoWrap,h.padding=_.padding,h.charset=_.charset,h.colorCompatibility=_.colorCompatibility;let b=tC(l.state.config,l.state.compiled,l.state.store,l.state.registry,v,y,h,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:Uc(l.state.config.looks,_.look),preset:_.preset}),x=BE.get(e.hookData.session_id,`click.error`);x&&BE.clear(e.hookData.session_id,`click.error`);let S=[o,l.lastError,x].filter(Boolean).join(`
184
- `),C=[qE.warning(),l.lastWarning].filter(Boolean).join(`
185
- `),ee=l.lastError===null?null:l.configFilePath,w=DE(S,C),T=VE.sync(s,w===null?null:kE(w));T!==null&&j(`warn`,`diagnostic dump failed: ${T}`);let te=jE(b,w,{fullText:T===null?{kind:`file`,path:VE.pathFor(s)}:{kind:`unavailable`,reason:T},failedConfigFile:ee},{width:p,rowCap:m,colorCompatibility:_.colorCompatibility}),ne=Date.now()-t,re=RE.getStats(),E=zE.getStats();return j(`info`,`render sid=${e.hookData.session_id??`?`} took=${ne}ms termCols=${f??`?`} termRows=${d.termRows??`?`} width=${p} git=${re.size}/${re.hits}h/${re.misses}m usage=${E.size}/${E.hits}h/${E.misses}m err=${S?`Y`:`N`} warn=${C?`Y`:`N`}`),uD({ok:!0,output:te+`
186
- `})}catch(e){throw IE.requestsErrored++,e}}if(e.kind===`click`)return uD(await yD(e.verb,e.value));if(e.kind===`debug`){if(!uE(e.what))return uD({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${lE.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=GE.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?_D(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):gD};return uD({ok:!0,debug:eE(e.what,n)})}return uD({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function fD(e){let{values:t,tokens:n}=S({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}`))],i=t.config;return{configFile:i===void 0?void 0:Cb(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const pD={sessionState:BE,dlog:j},mD={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},hD={...mD,width:1/0},gD=new Map;function _D(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,hh(a,{...hD,charset:t,colorCompatibility:n}));return r}const vD={gitProvider:RE,usageStore:zE,contextProvider:HE,metricsProvider:UE,tmuxService:WE,log:j,clock:()=>new Date};function yD(e,t){let n=JT.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,pD),{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 bD={connectMs:200,budgetMs:500};async function xD(e){let n=e.includes(`--json`),r=await SD();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${et(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
187
- `);return}t.stdout.write(ED(r.value))}function SD(){return Je({kind:`stats`},bD,e=>`stats`in e?e.stats:void 0)}function CD(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function wD(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function TD(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 ED(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 ${TD(e.uptimeSec)}`),t.push(` rss ${CD(e.rssBytes)}`),t.push(` heapUsed ${CD(e.heapUsedBytes)}`),t.push(` heapTotal ${CD(e.heapTotalBytes)}`),t.push(` external ${CD(e.externalBytes)}`),t.push(` arrayBuffers ${CD(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 ${wD(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 ${wD(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(`
176
+ `}function xw(e,t,n){return e.split(`
177
+ `).join(`${n}${t}`)}function Sw(e,t){let[n,...r]=e,i=r.length===0?t:`{\n ${xw(Sw(r,t),` `,`
178
+ `)},\n}`;return`${vw(n)}: ${i}`}function Cw(e,t,n,r){return e.slice(0,t)+r+e.slice(n)}function ww(e,t){return e.lastIndexOf(`
179
+ `,t-1)+1}function Tw(e){return/^[ \t]*$/.test(e)}function Ew(e,t){let n=ww(e,t);return/^[ \t]*/.exec(e.slice(n))[0]}function Dw(e,t){return Tw(e.slice(ww(e,t),t))}const Ow=/(?:\/\/[^\n]*?)?(\r\n|\n|$)/y;function kw(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n++;let r=e[n]===`,`?n+1:-1;for(r!==-1&&(n=r);n<e.length&&(e[n]===` `||e[n]===` `);)n++;Ow.lastIndex=n;let i=Ow.exec(e);if(i===null)return{commaEnd:r,line:null};let a=n+i[0].length;return{commaEnd:r,line:{at:a-i[1].length,next:a}}}function Aw(e,t){let{commaEnd:n,line:r}=kw(e,t.end);if(Dw(e,t.start)&&r!==null)return Cw(e,ww(e,t.start),r.next,``);if(n!==-1){let r=n;for(;r<e.length&&e[r]===` `;)r++;return Cw(e,t.start,r,``)}let i=t.start;for(;i>0&&(e[i-1]===` `||e[i-1]===` `);)i--;return e[i-1]===`,`?Cw(e,i-1,t.end,``):Cw(e,t.start,t.end,``)}function jw(e,t,n,r,i){let a=n.commaEnd!==-1,o=a?e:Cw(e,t.end,t.end,`,`),s=n.line.at+ +!a,c=bw(e);return Cw(o,s,s,`${c}${i}${xw(r,i,c)}${a?`,`:``}`)}function Mw(e,t,n){let r=t.kind===`object`?t.entries:t.elements,i=r[r.length-1],a=Ew(e,t.span.start);if(i===void 0){let r=a+` `,i=bw(e);return Cw(e,t.span.start+1,t.span.end-1,`${i}${r}${xw(n,r,i)},${i}${a}`)}let{commaEnd:o,line:s}=kw(e,i.span.end);if(Dw(e,i.span.start)&&s!==null){let t=e.slice(ww(e,i.span.start),i.span.start);return jw(e,i.span,{commaEnd:o,line:s},n,t)}let c=o===-1?i.span.end:o;return Cw(e,c,c,`${o===-1?`, `:` `}${n}${o===-1?``:`,`}`)}function Nw(e,t,n){if(t.length===0)throw new sw(`setValue needs a non-empty path`,0);if(/^\s*$/.test(e)){let r=bw(e);return`{${r} ${xw(Sw(t,n),` `,r)},${r}}${r}`}let r=pw(e);for(let i=0;i<t.length;i++){if(r.kind!==`object`)throw new sw(`cannot set ${t.join(`.`)}: ${t.slice(0,i).join(`.`)||`the document`} is not an object`,r.span.start);let a=mw(r,t[i]);if(a===void 0)return Mw(e,r,Sw(t.slice(i),n));if(i===t.length-1){let t=Ew(e,a.keySpan.start);return Cw(e,a.value.span.start,a.value.span.end,xw(n,t,bw(e)))}r=a.value}throw new sw(`unreachable: path exhausted`,0)}function Pw(e,t){if(t.length===0)throw new sw(`deleteValue needs a non-empty path`,0);if(/^\s*$/.test(e))return e;let n=hw(pw(e),t.slice(0,-1)),r=n===void 0?void 0:mw(n,t[t.length-1]);return r===void 0?e:Aw(e,r.span)}const Fw=[`h`,`v`,`children`];function Iw(e){if(e.kind===`string`)return e.value;if(e.kind!==`object`)return;let t=mw(e,`seg`)?.value;if(t?.kind===`string`)return t.value;let n=mw(e,`kind`)?.value,r=mw(e,`name`)?.value;return n?.kind===`string`&&n.value===`segment`&&r?.kind===`string`?r.value:void 0}function Lw(e){return e.kind===`object`?Fw.map(t=>mw(e,t)?.value).filter(e=>e?.kind===`array`):[]}function Rw(e,t){let n=hw(pw(e),t);if(n===void 0)return null;if(Lw(n).length>0)return{text:e,root:n};let r=Nw(e,t,`{ h: [${gw(e,n)}] }`);return{text:r,root:hw(pw(r),t)}}function zw(e,t){for(let n of Lw(e))for(let[e,r]of n.elements.entries()){if(Iw(r)===t)return{array:n,index:e};let i=zw(r,t);if(i!==null)return i}return null}function Bw(e,t,n){let r=Rw(e,t);if(r===null)return null;let i=zw(r.root,n);return i===null?null:Aw(r.text,i.array.elements[i.index].span)}function Vw(e,t,n,r,i){let a=Rw(e,t);if(a===null)return null;let o=zw(a.root,r);if(o===null)return null;let s=a.text,c=o.array.elements[o.index],l=JSON.stringify(n),{commaEnd:u,line:d}=kw(s,c.span.end);if(Dw(s,c.span.start)&&d!==null){let e=s.slice(ww(s,c.span.start),c.span.start);return i===`after`?jw(s,c.span,{commaEnd:u,line:d},l,e):Cw(s,c.span.start,c.span.start,`${l},${bw(s)}${e}`)}let f=gw(s,c),p=i===`before`?`${l}, ${f}`:`${f}, ${l}`;return Cw(s,c.span.start,c.span.end,p)}const Hw={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,colorCompatibility:`string`},Uw=new Set([`1`,`true`]),Ww=new Set([`0`,`false`,``]);function Gw(e,t){let n=U_(e);if(n===null||n.scope===`preset-root`)throw Error(`persistValueText: "${e}" does not name a value`);let r=n.scope===`globals`?Hw[n.field]:`string`;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(Uw.has(t))return`true`;if(Ww.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function Kw(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function qw(e,t,n){let i=`${e}.tmp`;try{r.writeFileSync(i,t,n===void 0?{}:{mode:n}),r.renameSync(i,e)}catch(e){throw r.rmSync(i,{force:!0}),e}}function Jw(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),qw(e,t,r.statSync(e,{throwIfNoEntry:!1})?.mode)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Yw(e){return/^\s*$/.test(e)?null:pw(e)}function Xw(e,t){return e!==null&&hw(e,t)!==void 0}function Zw(e){return e.kind===`segment`?e.when===void 0?e.name:{seg:e.name,when:e.when}:e.kind===`container`?{[e.direction===`horizontal`?`h`:`v`]:e.children.map(Zw),...e.when!==void 0&&{when:e.when}}:e}function Qw(e){return{...e.root!==void 0&&{root:Zw(e.root)},...e.globals!==void 0&&{globals:e.globals}}}const $w=hx,eT=$w.segments,tT=$w.presets;function nT(e,t,n,r){if(Xw(e,t))return{source:`file`};if(n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`);return{source:`bundled`,decl:n}}function rT(e,t,n){return e.source===`file`?null:{path:t,value:n(e.decl)}}function iT(e,t){if(t.scope===`globals`)return{path:G_(t),unit:null};if(t.scope===`segment-palette`){let n=G_(t),r=[`segments`,t.segment];return{path:n,unit:rT(nT(e,r,eT[t.segment],n.join(`.`)),r,e=>e)}}let n=[`presets`,t.preset],r=nT(e,n,tT[t.preset],[...n,`root`].join(`.`));return(r.source===`file`?Xw(e,[...n,`root`]):r.decl.root!==void 0)?{path:W_(t.preset,!0),unit:rT(r,n,Qw)}:{path:W_(t.preset,!1),unit:rT(nT(e,[`root`],$w.root,`root`),[`root`],Zw)}}function aT(e,{unit:t}){return t===null?e:Nw(e,t.path,yw(t.value))}function oT(e){let t=U_(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function sT(e,t){let n=oT(t);if(n.scope===`preset-root`)return;let r=Yw(Kw(e)??``),i=r===null?void 0:hw(r,G_(n));return i!==void 0&&`value`in i?i.value:void 0}function cT(e,t,n,r){let i=oT(n),a=Kw(t),o=iT(Yw(a??``),i);vT(e,t,{before:a,after:Nw(aT(a??``,o),o.path,Gw(n,r))})}function lT(e,t,n){let r=oT(n),i=Kw(t);if(i===null)return;let a=Pw(i,iT(Yw(i),r).path);a!==i&&vT(e,t,{before:i,after:a})}function uT(e,t,n,r){let i=oT(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=Kw(t),o=iT(Yw(a??``),i),s=aT(a??``,o),c=r.op===`remove`?Bw(s,o.path,r.target):Vw(s,o.path,r.segment,r.anchor,r.relation);if(c===null){let e=r.op===`remove`?r.target:r.anchor;throw new $(`${o.path.join(`.`)} in ${t} has no segment "${e}" — the bar you clicked is stale; it reloads on the next render`)}vT(e,t,{before:a,after:c})}const dT={past:[],future:[]};function fT(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function pT(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(fT)&&Array.isArray(t.future)&&t.future.every(fT)}function mT(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(pT))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function hT(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),qw(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function gT(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function _T(e,t,n,r,i){Jw(t,n,e.logger);try{hT(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function vT(e,t,n){let r=mT(e),{past:i}=r[t]??dT;_T(e,t,n.after,{...r,[t]:{past:gT(i,n),future:[]}},`edit`)}function yT(e,t){let n=mT(e),{past:r,future:i}=n[t]??dT,a=r[r.length-1];return a===void 0?null:(xT(t,a.after,`undo`),_T(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:gT(i,a)}},`undo`),a)}function bT(e,t){let n=mT(e),{past:r,future:i}=n[t]??dT,a=i[i.length-1];return a===void 0?null:(xT(t,a.before,`redo`),_T(e,t,a.after,{...n,[t]:{past:gT(r,a),future:i.slice(0,-1)}},`redo`),a)}function xT(e,t,n){if(Kw(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function ST(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function CT(e){return wT(()=>decodeURIComponent(e))}function wT(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function TT(e,t){let n=xe({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 ET=(e,t)=>TT(CT(e),t),DT=(e,t)=>{let n=xe({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,CT(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`})`)}},OT=(e,t)=>TT(CT(e),t),kT=(e,t)=>TT(CT(e),t),AT=(e,t)=>{let n=ST(CT(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},jT=(e,t)=>{let[n=``,...r]=wT(()=>Jt(e)),i=ST(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${wC().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: ${wC().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=EC(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},MT=/^-?\d+$/;function NT(e,t,n){return e>n?t:e<t?n:e}function PT(e,t){if(!e)return null;if(!wC().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${wC().join(`, `)})`);return e}function FT(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const IT=(e,t)=>{let[n=``,r=``,i=``]=wT(()=>Jt(e)),a=ST(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!MT.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=DC(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${wC().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&MT.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=NT(l+o,s.min,s.max),d=EC(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},LT=`render-origin`;function RT(e){return JSON.stringify(e)}function zT(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 BT(e,t){let n=e.sessionState.get(t,LT);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=zT(n);return Db(r.projectDir,r.cwd,r.configFile??void 0)}function VT(e){return{historyPath:Ne(),logger:e.dlog}}const HT=(e,t)=>{let[n=``,r=``,i=``,a=``]=wT(()=>Jt(e)),o=ST(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${PC().join(`, `)})`);let s=FC(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=PT(a,`set-config`),l=BT(t,o);cT(VT(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),FT(c,o,t,`set-config`)},UT=(e,t)=>{let[n=``,r=``,i=``,a=``]=wT(()=>Jt(e)),o=ST(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!MT.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=PT(a,`step-config`),l=IC(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${PC().join(`, `)})`);let u=BT(t,o),d=sT(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=NT(f+s,l.min,l.max),m=FC(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);cT(VT(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),FT(c,o,t,`step-config`)},WT=(e,t)=>{let[n=``,r=``]=wT(()=>Jt(e)),i=ST(n);if(!r||!PC().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${PC().join(`, `)})`);let a=BT(t,i);lT(VT(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},GT=(e,t)=>{let[n=``,r=``,i=``]=wT(()=>Jt(e)),a=ST(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${PC().join(`, `)})`);let o=FC(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=R_(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=BT(t,a);uT(VT(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},KT=(e,t)=>{let[n=``]=wT(()=>Jt(e)),r=ST(n),i=BT(t,r);if(yT(VT(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},qT=(e,t)=>{let[n=``]=wT(()=>Jt(e)),r=ST(n),i=BT(t,r);if(bT(VT(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},JT=`config-override`,YT=new Map([[Lt,ET],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=ST(wT(()=>decodeURIComponent(e.slice(0,n)))),i=wT(()=>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,JT),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,JT,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Rt,DT],[Ft,jT],[It,IT],[Vt,HT],[Ht,UT],[Ut,WT],[Wt,GT],[Gt,KT],[Kt,qT],[zt,OT],[Bt,kT],[`toolbar-toggle`,AT]]),XT=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Xt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`set-config`||a===`step-config`||a===`reset-config`||a===`apply-layout-op`||a===`undo`||a===`redo`||a===`toolbar-toggle`)){let e=Jt(o);e.length>0&&e[0]&&(i=e[0])}let e=YT.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(`
180
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},ZT=new Map([...YT,[N,XT]]);Object.freeze([...ZT.keys()]);const QT=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`]),$T=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]];function eE(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of $T){let i=nE(n,e);if(i==null)t.missingRequired.push(e);else{let n=tE(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))QT.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function tE(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function nE(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 rE(e,t){switch(e){case`vars`:return{what:e,vars:iE(t)};case`segments`:return{what:e,segments:cE(t)};case`config`:return{what:e,config:dE(t)}}}function iE(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=oE(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,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:aE(r.lastUpdatedMs())})}return o}function aE(e){return e===null?null:Math.max(0,Date.now()-e)}function oE(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,sE(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}`,sE(i));return t}function sE(e){return e.kind}function cE(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=lE(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:uE(t.template,i),lastRender:r.get(e)??null})}return o}function lE(e){let t=[],n=new Set;for(let r of _h(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 uE(e,t){let n=new Set;for(let r of tb(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function dE(e){return e===null?null:e.config}const fE=[`vars`,`segments`,`config`];function pE(e){return typeof e==`string`&&fE.includes(e)}function mE(e){return Math.max(1,e-2)}var hE=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 ci(e);if(n.length===0)return O(`No entries in transcript`),I;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})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),I}catch(e){return L(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function gE(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var _E=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(gE(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}async foldMetrics(e,t){let n=this.state.get(e),r=Xr(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await fi(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(gE(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const vE=new Map;function yE(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var bE=class{async getSessionId(){if(!process.env.TMUX_PANE)return I;let e=yE(process.env.TMUX),t=vE.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await be({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?F(n.stdout.trim()):I:L(`tmux display-message: ${n.reason}`);return vE.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function xE(e){return e<32||e===127||e>=128&&e<=159}function SE(e){let t=``;for(let n of e)t+=xE(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function CE(e,t){let n=SE(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const wE=`\x1B[38;2;255;255;255m`,TE=`\x1B[48;2;200;40;40m`;function EE(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 DE={fg:EE(wE),bg:EE(TE)},OE={fg:EE(`\x1B[38;2;0;0;0m`),bg:EE(`\x1B[48;2;220;160;40m`)};function kE(e){return Math.min(20,e??20)}function AE(e,t){let[n,...r]=[jE(e,zt,DE),jE(t,Bt,OE)].flat();return n===void 0?null:{channels:[n,...r]}}function jE(e,t,n){let[r,...i]=e.split(/\r\n|\r|\n/).map(SE).filter(Boolean);return r===void 0?[]:[{verb:t,colors:n,message:e,lines:[r,...i]}]}function ME(e){return e.channels.map(e=>`${NE[e.verb]}\n${e.message}\n`).join(`
181
+ `)}const NE={[zt]:`ERROR`,[Bt]:`WARNING`};function PE(e,t,n,r){if(t===null)return e;let i=FE(r),a=t.channels.flatMap(e=>IE(e,i)),o=a.slice(0,r.rowCap-1),s=[...o,LE(t,n,a.length-o.length,i)].join(`
182
+ `);return e?`${s}\n${e}`:s}function FE(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function IE(e,t){let n=new q({bgcolor:e.colors.bg,color:e.colors.fg,link:Yt([{verb:e.verb,args:[e.message]}])}),r=W(Math.max(2,t.width-1));return e.lines.flatMap((e,i)=>hh([i===0?`⚠`:` `,...e.split(` `)].flatMap(e=>ma(e,r)).map(e=>new os(`${e} `,{style:n,end:``,noWrap:!0})),t).split(`
183
+ `))}function LE(e,t,n,r){let{colors:i}=e.channels[0],{fullText:a,failedConfigFile:o}=t,s=new q({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new os(e,{style:t,end:``,noWrap:!0}),l=[c(`↳ ${n>0?`${n} more rows · `:``}`,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${SE(a.reason)}`,s)],u=o===null?[]:[c(` · open `,s),c(SE(o),s.withLink(x(o).href))],d=[...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=os.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,hh([m],r)}var RE=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const zE=new ew;ye(zE.launchStats);const BE=new zr({counters:zE,logger:j}),VE=new Kr({watchers:BE,logger:j}),HE=new wi,UE=new rw,WE=new RE(Re()),GE=new hE,KE=new _E,qE=new bE,JE=new QC({gitService:VE,sessionState:UE,watchers:BE},{observers:{onReload:e=>j(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),YE=60*1e3,XE=hr({entryUrl:import.meta.url,intervalMs:YE,log:j});let ZE=null,QE=null,$E=0;function eD(){t.on(`uncaughtException`,e=>{j(`error`,`uncaughtException: ${e.stack||e.message}`),dD(1)}),t.on(`unhandledRejection`,e=>{j(`error`,`unhandledRejection: ${String(e)}`),dD(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{j(`info`,`received ${e}, shutting down`),dD(0)});try{$E=pt(t.env)}catch(e){j(`error`,`refusing to boot: ${e.message}`),dD(1);return}ZE=Yn(t.pid);let e=ar(sr(ZE));if(!e.decision.allow){j(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),dD(1);return}QE=e.registryPath,r.mkdirSync(De(),{recursive:!0}),A(Oe()),UE.useStorage(new ow(Me(),500,j)),Qn({anchor:Zn(t.env),isAlive:$n,onOrphaned:e=>{j(`info`,`parent watchdog: ${e}; shutting down`),dD(0)}}),tD(g.createServer({allowHalfOpen:!1},e=>{fD(e)}),Oe(),!1)}function tD(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){j(`error`,`server error: ${i.message}`),dD(1);return}if(r){j(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}nD(e,n)}),e.listen(n,()=>rD(n))}function nD(e,n){let i=Bn(V(Ae(n)),(e,t)=>Jn(e,t,{readStartTime:qn,pidAlive:$n}));if(i.kind===`attach-and-exit`){j(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}j(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){j(`error`,`cannot unlink stale socket ${n}: ${e.message}`),dD(1);return}}tD(e,n,!0)}function rD(e){let n=Un(e);if(n.kind!==`present`){j(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),dD(0);return}cD(e);try{r.chmodSync(e,384)}catch(e){j(`warn`,`chmod socket failed: ${e.message}`)}j(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round($E/1048576)}MB`),Tt();let i=WE.reset();i!==null&&j(`warn`,`diagnostic dump wipe failed: ${i}`),aD(),XE.arm(),sD(),iD(e,n.identity)}function iD(e,n){Kn({bound:n,myPid:t.pid,readIdentity:()=>Un(e),readLease:()=>V(Ae(e)),shutdown:e=>dD(e),log:j}).arm()}function aD(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(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{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){j(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),dD(0);return}}catch(e){j(`warn`,`bin stat failed: ${e.message}`)}},YE);a.unref()}let oD=null;function sD(){oD=mt(gt(zE.startedAt.getTime(),e=>dD(e),{rssLimitBytes:$E})),oD.arm()}function cD(e){let n=Vn(Ae(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:ZE});n!==null&&j(`warn`,`lease write failed: ${n}`)}let lD=0,uD=!1;function dD(e){if(!uD){uD=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{VE.close()}catch(e){j(`warn`,`gitService close failed: ${e.message}`)}try{HE.close()}catch(e){j(`warn`,`usageStore close failed: ${e.message}`)}try{BE.closeAll()}catch(e){j(`warn`,`watcherRegistry close failed: ${e.message}`)}try{UE.flush()}catch(e){j(`warn`,`sessionState flush failed: ${e.message}`)}Hn(je(),t.pid),QE!==null&&or(QE,t.pid,rr,e=>r.unlinkSync(e)),t.exit(e)}}function fD(e){lD++,zE.inFlight=lD;let t=!1,n=(n,r)=>{if(t){r!==null&&j(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>dD(r);try{e.end(Ge(n),i)}catch(e){j(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{zE.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Ke(e=>{mD(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{j(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{j(`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=>{j(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),lD=Math.max(0,lD-1),zE.inFlight=lD})}const pD=e=>({resp:e,exitAfterFlush:null});async function mD(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return pD({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?j(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):j(`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 pD({ok:!0,stats:zE.snapshot({gitCache:VE.getStats(),usageCache:HE.getStats(),renderCacheSize:JE.size,watchersActive:BE.size(),nextRestartReason:oD?.describeNextRestart()??null})});if(e.kind===`render`){zE.requestsTotal++;let t=Date.now();try{let{report:n}=eE(e.hookData);for(let e of n.unknownTopLevelFields)j(`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 zE.requestsErrored++,j(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),pD({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=hD(e.args),s=e.hookData.session_id,c=UE.get(s,`config-override`)??a,l=JE.getOrCreate(i,e.cwd,c),u=RT({projectDir:i,cwd:e.cwd,configFile:c??null});UE.get(s,`render-origin`)!==u&&UE.set(s,LT,u);let d=Be(e),f=d.termCols,p=mE(f??120),m=kE(d.termRows),h={..._D,width:p},{authoredRoots:g}=l.state,_=Vb(l.state.config,t=>UE.get(e.hookData.session_id,t),e=>g.has(e)),v=await ex(e.hookData,xD,e.cwd,l.state.neededInputPaths,_,d),y=iS(_.theme);h.style=_.style,h.separator=_.separator,h.wrap=_.autoWrap,h.padding=_.padding,h.charset=_.charset,h.colorCompatibility=_.colorCompatibility;let b=iC(l.state.config,l.state.compiled,l.state.store,l.state.registry,v,y,h,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:Uc(l.state.config.looks,_.look),preset:_.preset}),x=UE.get(e.hookData.session_id,`click.error`);x&&UE.clear(e.hookData.session_id,`click.error`);let S=[o,l.lastError,x].filter(Boolean).join(`
184
+ `),C=[XE.warning(),l.lastWarning].filter(Boolean).join(`
185
+ `),ee=l.lastError===null?null:l.configFilePath,w=AE(S,C),T=WE.sync(s,w===null?null:ME(w));T!==null&&j(`warn`,`diagnostic dump failed: ${T}`);let te=PE(b,w,{fullText:T===null?{kind:`file`,path:WE.pathFor(s)}:{kind:`unavailable`,reason:T},failedConfigFile:ee},{width:p,rowCap:m,colorCompatibility:_.colorCompatibility}),ne=Date.now()-t,re=VE.getStats(),E=HE.getStats();return j(`info`,`render sid=${e.hookData.session_id??`?`} took=${ne}ms termCols=${f??`?`} termRows=${d.termRows??`?`} width=${p} git=${re.size}/${re.hits}h/${re.misses}m usage=${E.size}/${E.hits}h/${E.misses}m err=${S?`Y`:`N`} warn=${C?`Y`:`N`}`),pD({ok:!0,output:te+`
186
+ `})}catch(e){throw zE.requestsErrored++,e}}if(e.kind===`click`)return pD(await SD(e.verb,e.value));if(e.kind===`debug`){if(!pE(e.what))return pD({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${fE.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=JE.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?bD(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):yD};return pD({ok:!0,debug:rE(e.what,n)})}return pD({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function hD(e){let{values:t,tokens:n}=S({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}`))],i=t.config;return{configFile:i===void 0?void 0:Cb(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const gD={sessionState:UE,dlog:j},_D={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},vD={..._D,width:1/0},yD=new Map;function bD(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,hh(a,{...vD,charset:t,colorCompatibility:n}));return r}const xD={gitProvider:VE,usageStore:HE,contextProvider:GE,metricsProvider:KE,tmuxService:qE,log:j,clock:()=>new Date};function SD(e,t){let n=ZT.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,gD),{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 CD={connectMs:200,budgetMs:500};async function wD(e){let n=e.includes(`--json`),r=await TD();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${et(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
187
+ `);return}t.stdout.write(kD(r.value))}function TD(){return Je({kind:`stats`},CD,e=>`stats`in e?e.stats:void 0)}function ED(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function DD(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function OD(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 kD(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 ${OD(e.uptimeSec)}`),t.push(` rss ${ED(e.rssBytes)}`),t.push(` heapUsed ${ED(e.heapUsedBytes)}`),t.push(` heapTotal ${ED(e.heapTotalBytes)}`),t.push(` external ${ED(e.externalBytes)}`),t.push(` arrayBuffers ${ED(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 ${DD(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 ${DD(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(`
188
188
  `)+`
189
- `}const DD={connectMs:200,budgetMs:500};async function OD(e,n){let r=n.includes(`--json`),i=await kD(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${et(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
190
- `);return}t.stdout.write(AD(i.value))}function kD(e){return Je({kind:`debug`,what:e},DD,e=>`debug`in e?e.debug:void 0)}function AD(e){switch(e.what){case`vars`:return jD(e.vars);case`segments`:return MD(e.segments);case`config`:return ND(e.config);default:return e}}function jD(e){if(e.length===0)return`no variables (DSL not active)
191
- `;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);for(let i of e){let e=i.ageMs===null?``:` ${FD(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${PD(i.value)}${e}${a}`)}return t.join(`
189
+ `}const AD={connectMs:200,budgetMs:500};async function jD(e,n){let r=n.includes(`--json`),i=await MD(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${et(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
190
+ `);return}t.stdout.write(ND(i.value))}function MD(e){return Je({kind:`debug`,what:e},AD,e=>`debug`in e?e.debug:void 0)}function ND(e){switch(e.what){case`vars`:return PD(e.vars);case`segments`:return FD(e.segments);case`config`:return ID(e.config);default:return e}}function PD(e){if(e.length===0)return`no variables (DSL not active)
191
+ `;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);for(let i of e){let e=i.ageMs===null?``:` ${RD(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${LD(i.value)}${e}${a}`)}return t.join(`
192
192
  `)+`
193
- `}function MD(e){if(e.length===0)return`no segments (DSL not active)
193
+ `}function FD(e){if(e.length===0)return`no segments (DSL not active)
194
194
  `;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
195
195
  `)+`
196
- `}function ND(e){return e===null?`config: DSL not active
196
+ `}function ID(e){return e===null?`config: DSL not active
197
197
  `:JSON.stringify(e,null,2)+`
198
- `}function PD(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function FD(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function ID(){let e=RD();return e===null?null:r.readFileSync(e,`utf-8`)}function LD(){let e;try{e=ID()}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 RD(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function zD(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function BD(e,n=t.cwd()){let i=e===void 0?Ob(n,n):c.resolve(Cb(e));if(e!==void 0&&i!==null){let e;try{e=r.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let a=[],o=kb(n,n);o!==null&&a.push(o);try{return{kind:`clean`,configPath:i,warnings:a,rendered:VD(i,n,a)}}catch(e){let t=e;return i!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===i&&typeof t.message==`string`?{kind:`unreadable`,path:i,message:t.message}:{kind:`fatal`,configPath:i,message:e instanceof Zm||e instanceof Error?e.message:String(e),warnings:a}}}function VD(e,t,n){let{config:r,source:i}=Ab(e,_x),a=jb(r,e??`<default>`,i),o=new WC,s=new tS(o,a.globals.default_empty_value??``,void 0,new ew);try{let e=$S(a,s,{cwd:t});n.push(...e.loadWarnings),kC(a);let r=Vb(a,()=>null,()=>!1),i=t=>{let n=new Map;return{rendered:tC(a,e,o,s,zD(t),iS(t.theme),{style:t.style,separator:t.separator,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:Uc(a.looks,t.look),preset:t.preset}),segmentErrors:n}},c=i(r),l=i({...r,presetCustomized:!0}),u=[...[...c.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...l.segmentErrors].filter(([e])=>!c.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(u.length>0)throw Error(`config renders with ${u.length} segment error${u.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+u.map(e=>` ${e}`).join(`
199
- `));return c.rendered}finally{s.dispose()}}function HD(e){return e.map(e=>`warning: ${e}\n`).join(``)}function UD(e){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`,stderr:HD(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:HD(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}function WD(e){(e.length>1||e[0]===``)&&(t.stderr.write(`check: expected at most one non-empty path
198
+ `}function LD(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function RD(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function zD(){let e=VD();return e===null?null:r.readFileSync(e,`utf-8`)}function BD(){let e;try{e=zD()}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 VD(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function HD(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function UD(e,n=t.cwd()){let i=e===void 0?Ob(n,n):c.resolve(Cb(e));if(e!==void 0&&i!==null){let e;try{e=r.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let a=[],o=kb(n,n);o!==null&&a.push(o);try{return{kind:`clean`,configPath:i,warnings:a,rendered:WD(i,n,a)}}catch(e){let t=e;return i!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===i&&typeof t.message==`string`?{kind:`unreadable`,path:i,message:t.message}:{kind:`fatal`,configPath:i,message:e instanceof Zm||e instanceof Error?e.message:String(e),warnings:a}}}function WD(e,t,n){let{config:r,source:i}=Ab(e,_x),a=jb(r,e??`<default>`,i),o=new qC,s=new tS(o,a.globals.default_empty_value??``,void 0,new rw);try{let e=nC(a,s,{cwd:t});n.push(...e.loadWarnings),MC(a);let r=Vb(a,()=>null,()=>!1),i=t=>{let n=new Map;return{rendered:iC(a,e,o,s,HD(t),iS(t.theme),{style:t.style,separator:t.separator,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:Uc(a.looks,t.look),preset:t.preset}),segmentErrors:n}},c=i(r),l=i({...r,presetCustomized:!0}),u=[...[...c.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...l.segmentErrors].filter(([e])=>!c.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(u.length>0)throw Error(`config renders with ${u.length} segment error${u.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+u.map(e=>` ${e}`).join(`
199
+ `));return c.rendered}finally{s.dispose()}}function GD(e){return e.map(e=>`warning: ${e}\n`).join(``)}function KD(e){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`,stderr:GD(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:GD(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}function qD(e){(e.length>1||e[0]===``)&&(t.stderr.write(`check: expected at most one non-empty path
200
200
  Usage: cc-candybar check [config-file]
201
- `),t.exit(2));let n=UD(BD(e[0]));t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}const GD=`${SE}${xE}`;function KD(e){return`${GD}⚠ cc-candybar: ${qD(e)}\n`}function qD(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: ${bE(e.message,60)}`;case`render_failed`:return`render failed: ${bE(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${bE(e.message,60)}`}}function JD(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
202
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:KD(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function YD(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}function XD(){return YD(t.env.COLUMNS,t.stderr.columns)}function ZD(){return YD(t.env.LINES,t.stderr.rows)}const QD=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],$D=e=>e.some(e=>t.argv.includes(e));function eO(){return QD.some(e=>(t.env[e]??``)!==``)}function tO(){console.log(Q_)}async function nO(){try{$D(Y_.help)&&(tO(),t.exit(0)),$D(Y_.version)&&(console.log(`cc-candybar ${sn}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Rn(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(B(),t.exit(0)),e===`url-handle`){await Fn(t.argv[3]);return}if(e===`daemon`){ZE();return}if(e===`daemon-stats`&&(await xD(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){WD(t.argv.slice(3));return}if(e===`schema`){LD();return}uE(e)&&(await OD(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
201
+ `),t.exit(2));let n=KD(UD(e[0]));t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}const JD=`${TE}${wE}`;function YD(e){return`${JD}⚠ cc-candybar: ${XD(e)}\n`}function XD(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: ${CE(e.message,60)}`;case`render_failed`:return`render failed: ${CE(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${CE(e.message,60)}`}}function ZD(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
202
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:YD(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function QD(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}function $D(){return QD(t.env.COLUMNS,t.stderr.columns)}function eO(){return QD(t.env.LINES,t.stderr.rows)}const tO=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],nO=e=>e.some(e=>t.argv.includes(e));function rO(){return tO.some(e=>(t.env[e]??``)!==``)}function iO(){console.log(Q_)}async function aO(){try{nO(Y_.help)&&(iO(),t.exit(0)),nO(Y_.version)&&(console.log(`cc-candybar ${sn}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Rn(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(B(),t.exit(0)),e===`url-handle`){await Fn(t.argv[3]);return}if(e===`daemon`){eD();return}if(e===`daemon-stats`&&(await wD(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){qD(t.argv.slice(3));return}if(e===`schema`){BD();return}pE(e)&&(await jD(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
203
203
 
204
204
  cc-candybar is designed to be used as a Claude Code statusLine command.
205
205
  It reads hook data from stdin and outputs formatted statusline.
@@ -215,4 +215,4 @@ Add to ~/.claude/settings.json:
215
215
  Run with --help for more options.
216
216
 
217
217
  To test output manually:
218
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),tO(),t.exit(1));let i=JD(await it(r,t.argv,t.cwd(),{termCols:XD(),termRows:ZD(),ssh:eO()}));i.debug!==null&&O(i.debug),i.kick&&_t(),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)}}nO();export{};
218
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),iO(),t.exit(1));let i=ZD(await it(r,t.argv,t.cwd(),{termCols:$D(),termRows:eO(),ssh:rO()}));i.debug!==null&&O(i.debug),i.kick&&_t(),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)}}aO();export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.46.0",
3
+ "version": "1.48.0",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -90,9 +90,9 @@
90
90
  "mobx": "^6.15.0"
91
91
  },
92
92
  "optionalDependencies": {
93
- "@promptctl/cc-candybar-darwin-arm64": "1.46.0",
94
- "@promptctl/cc-candybar-darwin-x64": "1.46.0",
95
- "@promptctl/cc-candybar-linux-x64": "1.46.0",
96
- "@promptctl/cc-candybar-linux-arm64": "1.46.0"
93
+ "@promptctl/cc-candybar-darwin-arm64": "1.48.0",
94
+ "@promptctl/cc-candybar-darwin-x64": "1.48.0",
95
+ "@promptctl/cc-candybar-linux-x64": "1.48.0",
96
+ "@promptctl/cc-candybar-linux-arm64": "1.48.0"
97
97
  }
98
98
  }