@promptctl/cc-candybar 1.32.0 → 1.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +26 -26
- package/package.json +5 -5
- package/src/check.ts +99 -30
- package/src/config/default-dsl-config.ts +38 -2
- package/src/config/edit-chrome.ts +93 -10
- package/src/config/ident.ts +22 -0
- package/src/config/loader/cross-ref.ts +51 -0
- package/src/config/loader/persist-target.ts +20 -1
- package/src/config/loader/presets.ts +14 -2
- package/src/config/menu-keys.ts +2 -8
- package/src/config/presets.ts +72 -0
- package/src/daemon/cache/render.ts +31 -1
- package/src/daemon/render-payload.ts +20 -2
- package/src/daemon/server.ts +14 -1
- package/src/daemon/verbs/config-validators.ts +47 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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{URL as _,URLSearchParams as v,fileURLToPath as y}from"node:url";import{parseArgs as b}from"node:util";import{get as x}from"node:https";import{createHash as S}from"node:crypto";import{setTimeout as C}from"node:timers/promises";import{open as ee,readFile as te,readdir as w,stat as ne}from"node:fs/promises";import{createInterface as re}from"node:readline";import{clearInterval as ie,setInterval as T}from"node:timers";import E from"node:v8";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 D(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 _e(e){he.set(e,Date.now())}function O(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 O(e.category,t.minIntervalMs,t.sinceLastMs);_e(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 O(e.category,t.minIntervalMs,t.sinceLastMs);_e(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 O(e.category,t.minIntervalMs,t.sinceLastMs);_e(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 Ae(e){ke(c.dirname(e));for(let t of[e,k(e)])try{if(r.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function k(e){return`${e}.lease`}function je(){return k(Oe())}function Me(){return c.join(Te(),`session-state.json`)}function Ne(){return c.join(Te(),`config-overrides.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(),`daemon.log`)}const ze=1e4;function Be(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>ze?ze:t}var Ve=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function He(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Ue(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 Ve(`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 Ve(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function We(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=Ue(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(He(t))})}async function Ge(e,t,n){let r=null;try{r=await Xe(Oe(),t.connectMs);let i=await We(r,{v:3,...e},t.budgetMs);return Je(e.kind,i,n)}catch(e){return Ye(e)}finally{r&&r.destroy()}}function Ke(e,t){return typeof e==`string`?e:t}function qe(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Je(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=Ke(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:qe(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 Ye(e){if(e instanceof Ve||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 Xe(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 Ze(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 Qe={connectMs:50,budgetMs:150},$e={connectMs:50,budgetMs:200};function et(e){let t=e.output;return typeof t==`string`?t:void 0}function tt(e,t,n,r){return Ge({kind:`render`,hookData:e,args:t,cwd:n,termCols:r},Qe,et)}function nt(e,t){return Ge({kind:`click`,verb:e,value:t},$e,et)}function rt(e={}){if(yt()!==null)return;let n=e.spawn??bt,r=gt();if(r.kind===`contended`){let e=at();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),it(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),it(n);return}try{it(n)}finally{vt()}}function it(e){ft()&&ot(e)}function at(){try{let e=r.statSync(Fe());return Date.now()-e.mtimeMs}catch{return null}}function ot(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
3
3
|
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function st(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ct(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function lt(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 ut(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 dt(){try{r.unlinkSync(Le())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function ft(){let e=Ie(),n=Le(),r=lt(n),i=st(pt(e),ct(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`),mt(e),ut(n,Math.min(r+1,5)),!0)}function pt(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function mt(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 ht=null;function gt(){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 ht={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(!_t(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 _t(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function vt(){if(!ht)return;let{fd:e,path:t}=ht;ht=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function yt(){try{return r.mkdirSync(De(),{recursive:!0}),null}catch(e){return`mkdir ${De()}: ${e.message}`}}function bt(){let e=t.execPath,n=t.argv[1];return n?Se({bin:e,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const xt=`cc-candybar`,St=`dispatch`,Ct=`set-state`,wt=`step-state`,Tt=`copy`,Et=`open-vscode`,Dt=`show-config-error`,Ot=`show-config-warning`,kt=`set-config`,At=`step-config`,jt=`reset-config`,Mt=`apply-layout-op`,Nt=`undo`,Pt=`redo`;function Ft(e){return e.map(encodeURIComponent).join(`/`)}function A(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function It(e){return`${xt}://${St}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Ft(e.args)}`)}`).join(`&`)}`}function j(e){return new v(e).getAll(`e`).map(Lt)}function Lt(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Rt=`closed`;function zt(e,t){return{kind:`state`,key:e,default:t}}function Bt(e,t){return{set:e,cycle:[Rt,t]}}const Vt=`@promptctl/cc-candybar`,Ht=`CCCandybarURLHandler`,Ut=[],Wt={"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 Gt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Kt(e,t){return[e,...t].map(Gt).join(` `)}function qt(){return c.join(f.homedir(),`Applications`,`${Ht}.app`)}function Jt(){return c.join(f.homedir(),`.claude`,`settings.json`)}function Yt(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Xt(){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 Zt(){return c.join(Xt(),`bin`,`cc-candybar`)}function Qt(){return c.join(Xt(),`dist`,`index.mjs`)}function $t(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
|
-
`)}function en(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 tn(t){let n=Wt[`${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 nn(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function rn(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 ${Vt}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function M(){let e=en(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=tn(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Qt()),{recursive:!0}),r.mkdirSync(c.dirname(Zt()),{recursive:!0}),nn(e,Qt()),nn(t.sourcePath,Zt()),r.chmodSync(Zt(),493),r.rmSync(c.join(Xt(),`url-handler.mjs`),{force:!0});let n=rn(Zt());return process.stdout.write(`Staged cc-candybar v1.
|
|
4
|
+
`)}function en(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 tn(t){let n=Wt[`${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 nn(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function rn(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 ${Vt}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function M(){let e=en(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=tn(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Qt()),{recursive:!0}),r.mkdirSync(c.dirname(Zt()),{recursive:!0}),nn(e,Qt()),nn(t.sourcePath,Zt()),r.chmodSync(Zt(),493),r.rmSync(c.join(Xt(),`url-handler.mjs`),{force:!0});let n=rn(Zt());return process.stdout.write(`Staged cc-candybar v1.34.0 runtime at ${Xt()}\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:Zt(),distPath:Qt(),entryKind:n}}function an(){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>${xt}</string>`,` </array>`,` </dict>`,`</array>`].join(`
|
|
5
5
|
`)}]}function on(e){let t=qt();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`,$t(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 an())xe({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of an()){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 ${xt}:// 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(`✓ ${Ht}.app installed and registered.\n`),process.stdout.write(` Test: open '${xt}://hello-world' && pbpaste\n`)}function sn(){Yt(),on(M().distPath)}function cn(e,t=xt){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:Tt,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function ln(e){e||(process.stderr.write(`url-handle: missing URL argument.
|
|
6
6
|
`),process.exit(1));let t;try{t=cn(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await nt(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(rt(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(un(n)+`
|
|
7
7
|
`),process.exit(1)}function un(e){switch(e.cause){case`version_mismatch`:return`url-handle: daemon rejected click (version mismatch: client v${e.clientV} ≠ daemon v${e.daemonV})`;case`bad_request`:return`url-handle: daemon rejected click (bad request: ${e.message})`;case`render_failed`:return`url-handle: daemon rejected click (handler failed: ${e.message})`;case`malformed_response`:return`url-handle: daemon rejected click (malformed response: ${e.message})`}}function dn(){return`✓ install complete.
|
|
@@ -97,39 +97,39 @@ Use 'override' annotation for methods overridden by subclass.`)}}var U=ca(0),ia=
|
|
|
97
97
|
`).map(e=>n+e).join(`
|
|
98
98
|
`)}function Eh(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function Dh(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw _m(`join`,2,`list of strings/primitives`,`list element of type ${Oh(e)}`);n.push(String(e))}return n.join(e)}function Oh(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function kh(e){return vh(e,`-`)}function Ah(e){return e.toLowerCase()}function jh(e,t){return`\n${Th(e,t)}`}function Mh(e){return e.replace(/\s+/g,``)}function Nh(e,t,n){return n===1?e:t}function Ph(...e){return e.map(e=>`"${e}"`).join(` `)}function Fh(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Ih(e,t){return t.repeat(Math.max(0,e))}function Lh(e,t,n){return n.split(e).join(t)}function Rh(e){return vh(e,`_`)}function zh(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Bh(e,t){return t.split(e)}function Vh(e,t,n){let r=Hh(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Hh(e,t,n){if(n===0)return[];let r=t===``?Array.from(e):e.split(t);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function Uh(...e){return e.map(e=>`'${e}'`).join(` `)}function Wh(e,t,n){let r=t<0||t>n.length?n.length:t,i=Math.min(Math.max(0,e),r);return n.slice(i,r)}function Gh(e){let t=``;for(let n of e)Kh(n)?t+=n.toLowerCase():qh(n)?t+=n.toUpperCase():t+=n;return t}function Kh(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function qh(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Jh(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Yh(e){return e.trim()}function Xh(e,t){if(e.length===0)return t;let n=new Set([...e]),r=0;for(;r<t.length&&n.has(t[r]);)r+=1;let i=t.length;for(;i>r&&n.has(t[i-1]);)--i;return t.slice(r,i)}function Zh(e,t){return t.startsWith(e)?t.slice(e.length):t}function Qh(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function $h(e,t){if(e<0){let n=-e;return n>=t.length?t:t.slice(t.length-n)}return e>=t.length?t:t.slice(0,e)}function eg(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function tg(e){return e.toUpperCase()}function ng(e,t){return rg(e,`
|
|
99
99
|
`,t)}function rg(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
100
|
-
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function ig(e,t,n){return rg(e,t,n)}function ag(){return{abbrev:{fn:(e,t)=>ih(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>ah(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>bh(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>xh(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Sh(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Ch(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>wh(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Th(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Eh(e),argTypes:[`string`]},join:{fn:(e,t)=>Dh(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>kh(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Ah(e),argTypes:[`string`]},nindent:{fn:(e,t)=>jh(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Mh(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Nh(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Ph(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Fh(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Ih(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>Lh(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>Rh(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>zh(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>Bh(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>Vh(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>Uh(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>Wh(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>Gh(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>Jh(e),argTypes:[`string`]},trim:{fn:e=>Yh(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>Xh(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>Zh(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>Qh(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>$h(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>eg(e),argTypes:[`string`]},upper:{fn:e=>tg(e),argTypes:[`string`]},wrap:{fn:(e,t)=>ng(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>ig(e,t,n),argTypes:[`int`,`string`,`string`]}}}const og=`menus.`;function sg(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function cg(e){return e}function lg(e,t,n){return n===void 0?og+sg(e)+`.`+sg(t):og+sg(n)}function ug(e,t){return e+`.`+t}function dg(e){return e+`.page`}function fg(e){for(let t of Object.keys(e))if(t!==`closeOnPick`&&t!==`paged`&&t!==`key`)throw Error(`unknown {{ menu }} option "${t}" — the options dict takes "closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping)`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n}}const pg=`menu`,mg=`the positional tail ("pageAction" closeOnPick paged "key") was removed: the page cursor is now synthesized from the menu's identity, and rare knobs are named options in ONE trailing dict — write {{ menu "applyTheme" }} or {{ menu "applyTheme" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key)`;function hg(e){let t=e=>({kind:`issue`,message:e}),[n,r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name (e.g. {{ menu "applyTheme" }})`);if(e.argExprs.length>2)return t(`with more than two arguments — ${mg}`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" }})`);if(r!==void 0&&(r.kind!==`call`||r.name!==`dict`))return t(`whose second argument is not an options (dict …) — ${mg}`);let i=r===void 0?{}:Zp(r);if(i===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);try{return{kind:`ok`,apply:n.value,options:fg(i)}}catch(e){return t(`with invalid options — ${e.message}`)}}function gg(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===pg).map(hg)}catch{return`parse-failed`}}function _g(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(pg)}catch{return!1}}function vg(e,t,n){e.issues.push({path:t,message:n,line:Y(e.source,[`root`])})}function yg(e,t){Ql(e,t,og,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))_g(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:Y(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&_g(i)&&vg(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}let r=new Map;if(t.root!==void 0)for(let n of Zr(t.root))typeof n.when==`string`&&_g(n.when)&&vg(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`),n.kind===`segment`&&r.set(n.name,(r.get(n.name)??0)+1);for(let[t,i]of Object.entries(n))_g(i.template)&&(r.get(t)??0)>1&&vg(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`);let i=new Set,a={},o=new Set,s=new Map;for(let[t,r]of Object.entries(n)){if(!_g(r.template))continue;let n=gg(r.template);if(n!==`parse-failed`)for(let r of n){if(r.kind===`issue`){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${r.message}.`);continue}let{apply:n,options:c}=r;if(n===``){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action.`);continue}let l=cg(n);if(l===`closed`){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${Rt}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=lg(t,n,c.key),d=dg(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=s.get(e);return t!==void 0&&t!==f});if(p!==void 0){vg(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}s.set(u,f),s.set(d,f);let m=ug(u,l);if(o.has(m)){vg(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}o.add(m),i.add(u),a[m]=Bt(u,l)}}if(i.size===0)return;let c={};for(let e of i){c[e]=zt(e,Rt);let t=dg(e);c[t]={kind:`state`,key:t,default:`0`},a[t]={set:t,int:!0}}t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const bg=`edit.`,xg=`edit.mode`,Sg=`open`,Cg=`{{ eq .${xg} "${Sg}" }}`;function wg(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Tg(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&wg(e))return!0;return!1}function Eg(e,t){if(Ql(e,t,bg,`edit mode`),!Tg(t))return;let n={[xg]:zt(xg,Rt)},r={"edit.toggle":Bt(xg,Sg)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Dg(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Og(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function kg(e){let t=new Set,n=e=>{if(e.kind===`segment`){t.add(e.name);return}for(let t of e.children)n(t)};return n(e),t}function Ag(e,t){return t.reduce(jg,e)}function jg(e,t){return t.op===`remove`?Mg(e,t.target):Ng(e,t.segment,t.anchor,t.relation)}function Mg(e,t){let n=!1;function r(e){if(n||e.kind===`segment`)return e;let i=[];for(let a of e.children){if(!n&&a.kind===`segment`&&a.name===t){n=!0;continue}i.push(r(a))}return{...e,children:i}}let i=r(e);return n?i:e}function Ng(e,t,n,r){let i=!1;function a(e){if(i||e.kind===`segment`)return e;let o=[];for(let s of e.children){if(!i&&s.kind===`segment`&&s.name===n){i=!0;let e={kind:`segment`,name:t};r===`before`?o.push(e,s):o.push(s,e);continue}o.push(a(s))}return{...e,children:o}}let o=a(e);return i?o:e}const Pg=`default`,Fg={};function Ig(e){return[...new Set([Pg,...Object.keys(e)])]}function Lg(e,t,n){return Sc(e,t,Pg,n)}function Rg(e,t){let n={[Pg]:Fg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Pg}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function zg(e,t){let n=Rg(e.presets,t).root;return n===void 0?{node:e.root,path:`root`}:{node:n,path:`presets.${t}.root`}}function Bg(e,t){return{...e.globals,...Rg(e.presets,t).globals}}function Vg(e,t){let n=e.preset;if(n===void 0||Ig(t).includes(n))return e;let r={...e};return delete r.preset,r}function Hg(e,t){let n=Object.entries(t).filter(([,e])=>e.length>0);if(n.length===0)return e;let r={...e.presets};for(let[t,i]of n){let n=i.map(Og).filter(e=>e!==null);if(n.length===0)continue;let{node:a}=zg(e,t);r[t]={...Rg(e.presets,t),root:Ag(a,n)}}return{...e,presets:r}}function Ug(e){return e.startsWith(`edit.`)||e.startsWith(`menus.`)||e.startsWith(`groups.`)}function Wg(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function Gg(e){return`${bg}addable.${e}`}function Kg(e){let t=Object.keys(e.segments).filter(e=>!Ug(e)),n=new Map;for(let r of Ig(e.presets)){let{node:i}=zg(e,r),a=kg(i);n.set(Gg(r),t.filter(e=>!a.has(e)))}return n}function qg(e,t,n,r){let i=`${bg}${e}.remove.${Wg(n)}`,a=`${bg}${e}.removeSeg.${Wg(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:Cg},{kind:`segment`,name:a}}function Jg(e,t,n,r,i,a,o){let s=`${bg}${e}.insert.${n}`,c=`${bg}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=cg(s),u=lg(c,s,void 0),d=dg(u),f=ug(u,l);return o.variables[u]=zt(u,Rt),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=Bt(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`+{{ menu "${s}" }}`,when:Cg},{kind:`segment`,name:c}}function Yg(e,t,n,r,i,a){let o=[];for(let s of e.children){if(s.kind===`container`){o.push(Yg(s,t,n,r,i,a));continue}if(Ug(s.name)){o.push(s);continue}o.push(Jg(t,n,String(a.n++),r,s.name,`before`,i)),o.push(s),o.push(qg(t,n,s.name,i))}let s=e.children[e.children.length-1];return s!==void 0&&s.kind===`segment`&&!Ug(s.name)&&o.push(Jg(t,n,String(a.n++),r,s.name,`after`,i)),{...e,children:o}}function Xg(e,t,n){let{node:r}=zg(e,t),i=`presets.${t}.rootOps`,a=Gg(t),o=Wg(t);return Yg(r.kind===`container`?r:{kind:`container`,direction:`horizontal`,children:[r]},o,i,a,n,{n:0})}function Zg(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},actions:{},segments:{}},n={...e.presets};for(let r of Ig(e.presets)){let i=Xg(e,r,t);n[r]={...Rg(e.presets,r),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const Qg=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`];function $g(e){return`set`in e}function e_(e){return`persist`in e}function t_(e){return`reset`in e}function n_(e){return`undo`in e}function r_(e){return`redo`in e}function i_(e,t){if(t===void 0)return{};if(!zc(t))return Q(e,`actions`,`actions must be an object, got ${Bc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=a_(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:Y(e.source,t.split(`.`))})}function a_(e,t,n){if(!zc(n))return Q(e,t,`${t} must be an action object, got ${Bc(n)}`),null;let r=Qg.filter(e=>e in n);return r.length===1?o_[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${Qg.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const o_={set:(e,t,n)=>j_(e,t,n,`set`,D_,`the SessionState key to write`),persist:(e,t,n)=>j_(e,t,n,`persist`,O_,`the config globals field to write`),copy:s_(`copy`),open:s_(`open`),reset:c_,undo:l_(`undo`),redo:l_(`redo`)};function s_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Pc(t,n,r,e);return i===null?null:{[e]:i}}}function c_(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=u_(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}function l_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the ONE global history over the whole overrides layer), got ${Vc(r[e])}`),null)}}function u_(e,t,n,r,i,a){let o=Pc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}function d_(e,t,n,r,i){return u_(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`)}function f_(e){return e===`set`?`set-state`:`set-config`}const p_={to:M_(`set`)},m_={to:M_(`persist`)},h_={from:N_(`set`)},g_={from:N_(`persist`)},__={min:R_(),max:R_(),by:R_()},v_={int:F_()},y_={cycle:P_(`set`)},b_={cycle:P_(`persist`)},x_={removeSegment:I_(`removeSegment`)},S_={insertSegment:I_(`insertSegment`),anchor:I_(`anchor`),relation:L_()},C_={insertSegmentFrom:N_(`persist`),anchor:I_(`anchor`),relation:L_()},w_={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},T_={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function E_(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=(e,n,r)=>Uc(e,t,n,r),s=tl(t);return{detect:a,allowed:[e,...i],label:i.join(`/`),json:{type:`object`,properties:{[e]:{type:`string`},...s.properties},required:[e,...s.required??[]],additionalProperties:!1},parse:n.length?Jc(o,...n):o}}const D_=[E_(`set`,p_),E_(`set`,h_),E_(`set`,__,[w_,T_]),E_(`set`,v_),E_(`set`,y_)],O_=[E_(`persist`,m_),E_(`persist`,g_),E_(`persist`,__,[w_,T_]),E_(`persist`,b_),E_(`persist`,x_),E_(`persist`,S_,[],[`insertSegment`]),E_(`persist`,C_,[],[`insertSegmentFrom`])];function k_(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function A_(e){let t=k_(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function j_(e,t,n,r,i,a){let o=d_(e,t,n,r,a),s=i.filter(e=>e.detect.some(e=>e in n));if(s.length!==1)return Q(e,t,`${A_(r)}${s.length>1?` — found: ${s.map(e=>e.label).join(`, `)}`:``}`),null;let c=s[0];for(let i of Object.keys(n))c.allowed.includes(i)||Q(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${c.allowed.join(`, `)}`);let l=c.parse(e,t,n);return o===null||l===null?null:{[r]:o,...l}}function M_(e){let t=f_(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>u_(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function N_(e){let t=f_(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Q(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Q(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Q(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Q(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Vc(o)}`)}}}function P_(e){let t=f_(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Bc(o)}`);return}let c=o;if(c.length<2){Q(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function F_(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Vc(r[n])}`);return}return!0}}}function I_(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Pc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function L_(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${Vc(i)}`);return}return i}}}function R_(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${Vc(i)}`);return}return i}}}const z_={noun:`look key`,fields:{hueShift:Zc(),chromaScale:Zc({min:0}),lightnessScale:Zc(),lightnessShift:Zc()}};function B_(e,t){if(!zc(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${Bc(t)}`,line:Y(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:Y(e.source,[`looks`,r])});continue}let t=Hc(e,z_,`looks.${r}`,i);t!==null&&(n[r]={...Da,...t})}return n}const V_={noun:`preset key`,fields:{root:{required:!1,json:{$ref:$l},parse:(e,t,n,r)=>r[n]===void 0?void 0:du(e,`${t}.${n}`,r[n])},globals:{required:!1,json:hl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:ml(e,`${t}.${n}`,r[n])}}};function H_(e,t){if(!zc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Bc(t)}`,line:Y(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty and slash-free — a preset picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:Y(e.source,[`presets`,r])});continue}let t=Hc(e,V_,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function U_(e,t){if(t===void 0)return{};if(!zc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Bc(t)}`,line:Y(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Vc(i)}`,line:Y(e.source,[`helpers`,r])});continue}n[r]=i}return n}const W_=new Map;function G_(e,t){W_.set(e,{permanent:!0,resolve:t})}G_(`themes`,()=>xc()),G_(`styles`,()=>Tc),G_(`charsets`,()=>Oc),G_(`colorCompatibilities`,()=>kc);function K_(e){return new Map([[`looks`,Object.keys(e.looks)],[`presets`,Ig(e.presets)]])}function q_(e){return[...new Set([...W_.keys(),...e.keys()])]}function J_(e,t){if(typeof e!=`string`)return e;let n=t.get(e);if(n)return n;let r=W_.get(e);if(r)return r.resolve();throw Error(`unknown option domain "${e}" (have: ${q_(t).join(`, `)})`)}const Y_=/^segments\.([^.]+)\.palette$/,X_=/^presets\.([^.]+)\.rootOps$/;function Z_(e){if(_l(e))return{scope:`globals`,field:e};let t=Y_.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=X_.exec(e);return n?{scope:`preset-root-ops`,preset:n[1]}:null}const Q_=/{{([\s\S]*?)}}/g,$_=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,ev=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function tv(e){let t=new Set,n;for(Q_.lastIndex=0;(n=Q_.exec(e))!==null;){let e=n[1].replace($_,``),r;for(ev.lastIndex=0;(r=ev.exec(e))!==null;)t.add(r[1])}return t}const nv=/\baction\s+$/;function rv(e){let t=new Set;Q_.lastIndex=0;let n;for(;(n=Q_.exec(e))!==null;){let e=n[1],r=0,i;for($_.lastIndex=0;(i=$_.exec(e))!==null;)nv.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const iv=/\b(picker|menu)\s+$/;function av(e){let t=new Set;Q_.lastIndex=0;let n;for(;(n=Q_.exec(e))!==null;){let e=n[1],r=0,i=0,a;for($_.lastIndex=0;(a=$_.exec(e))!==null;){let n=iv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function ov(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const sv={gitTaculous:`gitaculous`};function cv(e,t){t.globals.look!==void 0&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:Y(e.source,[`globals`,`look`])}),t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:Y(e.source,[`globals`,`preset`])});let n=K_(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||q_(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${q_(n).join(`, `)})`,line:Y(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=Z_(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${vl().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.rootOps" target`,line:Y(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root-ops`){lv(e,t,n,a,i,o.preset,r);continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:Y(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:Y(e.source,[`actions`,n,a])})}}let r=new Set(Object.keys(t.variables));for(let[e,n]of Object.entries(t.segments))if(n.vars)for(let t of Object.keys(n.vars))r.add(`${e}.${t}`);let i=(n,i,a)=>{for(let o of Zr(n))if(o.when!==void 0&&mv(e,`${i}.when`,o.when,r,{line:a}),o.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,o.name)){let t=sv[o.name],n=t===void 0?``:` (the built-in segment "${o.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:i,message:`${i} entry "${o.name}" does not match any declared segment${n}`,line:a})}},a=hv(e.source);i(t.root,a,Y(e.source,[a]));for(let[n,r]of Object.entries(t.presets))r.root!==void 0&&i(r.root,`presets.${n}.root`,Y(e.source,[`presets`,n,`root`]));for(let[n,i]of Object.entries(t.variables))fv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))fv(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){mv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of rv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:Y(e.source,[`segments`,n,a])});for(let r of av(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:Y(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))pv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))pv(e,`segments.${n}.vars.${t}`,a,r,n);(uv(t)||dv(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:Y(e.source,[`variables`])})}function lv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=Y(e.source,[`actions`,n,r]);if(!Ig(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Ig(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.rootOps" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function uv(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function dv(e){return Object.values(e.actions).some(e=>$g(e)||e_(e)||t_(e)||n_(e)||r_(e))}function fv(e,t,n,r,i){n.kind===`template`&&mv(e,`${t}.template`,n.template,r,{segCtx:i}),$r(n)&&n.cache&&`key`in n.cache&&mv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function pv(e,t,n,r,i){if($r(n)&&n.cache&&`depends_on`in n.cache)for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:Y(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function mv(e,t,n,r,i){for(let a of tv(n)){if(ov(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&ov(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Y(e.source,t.split(`.`))})}}function hv(e){try{let t=ci.default.parse(e);if(zc(t)&&`root`in t)return`root`}catch{}return`layout`}function gv(e,t){let{graph:n,nodeInfo:r}=_v(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:Y(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function _v(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(e,n)=>{for(let i of tv(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),$r(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const vv=[`json5`,`json`];function yv(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function bv(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[yv(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return[...e?vv.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...vv.map(e=>c.join(i,`.cc-candybar.${e}`)),...vv.map(e=>c.join(a,`cc-candybar`,`config.${e}`))]}function xv(e,t,n){return bv(e,t,n).find(r.existsSync)??null}function Sv(e,t){let n=bv(e,t),i=new Set,a=[];for(let e of n)i.has(e)||(i.add(e),r.existsSync(e)&&a.push(e));let o=new Map;for(let e of a){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),r=c.join(t,n);o.has(r)||o.set(r,[]),o.get(r).push(e)}let s=[...o.values()].filter(e=>e.length>1);return s.length===0?null:`config-extension collision: ${s.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Cv(e,t,n){let i=e===null?``:r.readFileSync(e,`utf-8`);return{config:ol(e===null?{}:Tv(e,i,n),t),source:i}}function wv(e,t=`<config>`,n=``,r=new Set(xc())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(cv(a,e),gv(a,e),i.length>0)throw new Ac(t,i);return Zg(e)}function Tv(e,t,n=new Set(xc())){let r=Ev(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!zc(r))throw new Ac(e,[{path:``,message:`Config root must be an object, got ${Bc(r)}`}]);let o=Dv(a,r);if(i.length>0)throw new Ac(e,i);return o}function Ev(e,t){try{return ci.default.parse(t)}catch(t){let n=t;throw new Ac(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Dv(e,t){for(let n of Object.keys(t))Ov.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Ov].join(`, `)}`,line:Y(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=pl(e,`globals`,t.globals)),t.variables!==void 0&&(n.variables=jl(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=Jl(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
100
|
+
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function ig(e,t,n){return rg(e,t,n)}function ag(){return{abbrev:{fn:(e,t)=>ih(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>ah(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>bh(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>xh(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Sh(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Ch(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>wh(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Th(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Eh(e),argTypes:[`string`]},join:{fn:(e,t)=>Dh(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>kh(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Ah(e),argTypes:[`string`]},nindent:{fn:(e,t)=>jh(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Mh(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Nh(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Ph(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Fh(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Ih(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>Lh(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>Rh(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>zh(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>Bh(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>Vh(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>Uh(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>Wh(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>Gh(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>Jh(e),argTypes:[`string`]},trim:{fn:e=>Yh(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>Xh(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>Zh(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>Qh(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>$h(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>eg(e),argTypes:[`string`]},upper:{fn:e=>tg(e),argTypes:[`string`]},wrap:{fn:(e,t)=>ng(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>ig(e,t,n),argTypes:[`int`,`string`,`string`]}}}function og(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const sg=`menus.`;function cg(e){return e}function lg(e,t,n){return n===void 0?sg+og(e)+`.`+og(t):sg+og(n)}function ug(e,t){return e+`.`+t}function dg(e){return e+`.page`}function fg(e){for(let t of Object.keys(e))if(t!==`closeOnPick`&&t!==`paged`&&t!==`key`)throw Error(`unknown {{ menu }} option "${t}" — the options dict takes "closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping)`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n}}const pg=`menu`,mg=`the positional tail ("pageAction" closeOnPick paged "key") was removed: the page cursor is now synthesized from the menu's identity, and rare knobs are named options in ONE trailing dict — write {{ menu "applyTheme" }} or {{ menu "applyTheme" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key)`;function hg(e){let t=e=>({kind:`issue`,message:e}),[n,r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name (e.g. {{ menu "applyTheme" }})`);if(e.argExprs.length>2)return t(`with more than two arguments — ${mg}`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" }})`);if(r!==void 0&&(r.kind!==`call`||r.name!==`dict`))return t(`whose second argument is not an options (dict …) — ${mg}`);let i=r===void 0?{}:Zp(r);if(i===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);try{return{kind:`ok`,apply:n.value,options:fg(i)}}catch(e){return t(`with invalid options — ${e.message}`)}}function gg(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===pg).map(hg)}catch{return`parse-failed`}}function _g(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(pg)}catch{return!1}}function vg(e,t,n){e.issues.push({path:t,message:n,line:Y(e.source,[`root`])})}function yg(e,t){Ql(e,t,sg,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))_g(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:Y(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&_g(i)&&vg(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}let r=new Map;if(t.root!==void 0)for(let n of Zr(t.root))typeof n.when==`string`&&_g(n.when)&&vg(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`),n.kind===`segment`&&r.set(n.name,(r.get(n.name)??0)+1);for(let[t,i]of Object.entries(n))_g(i.template)&&(r.get(t)??0)>1&&vg(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`);let i=new Set,a={},o=new Set,s=new Map;for(let[t,r]of Object.entries(n)){if(!_g(r.template))continue;let n=gg(r.template);if(n!==`parse-failed`)for(let r of n){if(r.kind===`issue`){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${r.message}.`);continue}let{apply:n,options:c}=r;if(n===``){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action.`);continue}let l=cg(n);if(l===`closed`){vg(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${Rt}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=lg(t,n,c.key),d=dg(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=s.get(e);return t!==void 0&&t!==f});if(p!==void 0){vg(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}s.set(u,f),s.set(d,f);let m=ug(u,l);if(o.has(m)){vg(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}o.add(m),i.add(u),a[m]=Bt(u,l)}}if(i.size===0)return;let c={};for(let e of i){c[e]=zt(e,Rt);let t=dg(e);c[t]={kind:`state`,key:t,default:`0`},a[t]={set:t,int:!0}}t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const bg=`edit.`,xg=`edit.mode`,Sg=`open`,Cg=`{{ eq .${xg} "${Sg}" }}`;function wg(e){let t=af({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Tg(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&wg(e))return!0;return!1}function Eg(e,t){if(Ql(e,t,bg,`edit mode`),!Tg(t))return;let n={[xg]:zt(xg,Rt)},r={"edit.toggle":Bt(xg,Sg)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Dg(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Og(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function kg(e){let t=new Set,n=e=>{if(e.kind===`segment`){t.add(e.name);return}for(let t of e.children)n(t)};return n(e),t}function Ag(e,t){return t.reduce(jg,e)}function jg(e,t){return t.op===`remove`?Mg(e,t.target):Ng(e,t.segment,t.anchor,t.relation)}function Mg(e,t){let n=!1;function r(e){if(n||e.kind===`segment`)return e;let i=[];for(let a of e.children){if(!n&&a.kind===`segment`&&a.name===t){n=!0;continue}i.push(r(a))}return{...e,children:i}}let i=r(e);return n?i:e}function Ng(e,t,n,r){let i=!1;function a(e){if(i||e.kind===`segment`)return e;let o=[];for(let s of e.children){if(!i&&s.kind===`segment`&&s.name===n){i=!0;let e={kind:`segment`,name:t};r===`before`?o.push(e,s):o.push(s,e);continue}o.push(a(s))}return{...e,children:o}}let o=a(e);return i?o:e}const Pg=`default`,Fg={};function Ig(e){return[...new Set([Pg,...Object.keys(e)])]}function Lg(e,t,n){return Sc(e,t,Pg,n)}function Rg(e,t){let n={[Pg]:Fg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Pg}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function zg(e,t){let n=Rg(e.presets,t).root;return n===void 0?{node:e.root,path:`root`}:{node:n,path:`presets.${t}.root`}}function Bg(e,t){return{...e.globals,...Rg(e.presets,t).globals}}function Vg(e,t){let n=e.preset;if(n===void 0||Ig(t).includes(n))return e;let r={...e};return delete r.preset,r}function Hg(e,t){let n=new Set(Ig(t)),r=Object.entries(e).filter(([e])=>n.has(e));return r.length===Object.keys(e).length?e:Object.fromEntries(r)}function Ug(e,t){let n=e[t];return n===void 0?!1:n.some(e=>Og(e)!==null)}function Wg(e,t){let n=Object.entries(t).filter(([,e])=>e.length>0);if(n.length===0)return e;let r={...e.presets};for(let[t,i]of n){let n=i.map(Og).filter(e=>e!==null);if(n.length===0)continue;let{node:a}=zg(e,t);r[t]={...Rg(e.presets,t),root:Ag(a,n)}}return{...e,presets:r}}const Gg=/^segments\.([^.]+)\.palette$/,Kg=/^presets\.(.+)\.rootOps$/;function qg(e){return`presets.${e}.rootOps`}function Jg(e){if(_l(e))return{scope:`globals`,field:e};let t=Gg.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Kg.exec(e);return n?{scope:`preset-root-ops`,preset:n[1]}:null}function Yg(e){return e.startsWith(`edit.`)||e.startsWith(`menus.`)||e.startsWith(`groups.`)}function Xg(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Zg(e){return`${bg}addable.${e}`}function Qg(e){let t=Object.keys(e.segments).filter(e=>!Yg(e)),n=new Map;for(let r of Ig(e.presets)){let{node:i}=zg(e,r),a=kg(i);n.set(Zg(r),t.filter(e=>!a.has(e)))}return n}function $g(e,t,n,r){let i=`${bg}${e}.remove.${og(n)}`,a=`${bg}${e}.removeSeg.${og(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:Cg},{kind:`segment`,name:a}}function e_(e,t,n,r,i,a,o){let s=`${bg}${e}.insert.${n}`,c=`${bg}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=cg(s),u=lg(c,s,void 0),d=dg(u),f=ug(u,l);return o.variables[u]=zt(u,Rt),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=Bt(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`+{{ menu "${s}" }}`,when:Cg},{kind:`segment`,name:c}}function t_(e,t,n,r,i,a){let o=[];for(let s of e.children){if(s.kind===`container`){o.push(t_(s,t,n,r,i,a));continue}if(Yg(s.name)){o.push(s);continue}o.push(e_(t,n,String(a.n++),r,s.name,`before`,i)),o.push(s),o.push($g(t,n,s.name,i))}let s=e.children[e.children.length-1];return s!==void 0&&s.kind===`segment`&&!Yg(s.name)&&o.push(e_(t,n,String(a.n++),r,s.name,`after`,i)),{...e,children:o}}function n_(e,t,n,r,i){let a=`${bg}${n}.resetLayout`,o=`${bg}${n}.customized`;i.actions[a]={reset:r};let s=Xg(t);return i.segments[o]={template:`{{ action "${a}" "↺ ${s} customized" }}`,when:`{{ .preset.customized }}`},{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:o},e],...e.when!==void 0&&{when:e.when}}}function r_(e,t,n){let{node:r}=zg(e,t),i=qg(t),a=Zg(t),o=og(t),s={n:0};return n_(t_(r.kind===`container`?r:{kind:`container`,direction:`horizontal`,children:[r],...r.when!==void 0&&{when:r.when}},o,i,a,n,s),t,o,i,n)}function i_(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},actions:{},segments:{}},n={...e.presets};for(let r of Ig(e.presets)){let i=r_(e,r,t);n[r]={...Rg(e.presets,r),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const a_=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`];function o_(e){return`set`in e}function s_(e){return`persist`in e}function c_(e){return`reset`in e}function l_(e){return`undo`in e}function u_(e){return`redo`in e}function d_(e,t){if(t===void 0)return{};if(!zc(t))return Q(e,`actions`,`actions must be an object, got ${Bc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=f_(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:Y(e.source,t.split(`.`))})}function f_(e,t,n){if(!zc(n))return Q(e,t,`${t} must be an action object, got ${Bc(n)}`),null;let r=a_.filter(e=>e in n);return r.length===1?p_[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${a_.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const p_={set:(e,t,n)=>R_(e,t,n,`set`,P_,`the SessionState key to write`),persist:(e,t,n)=>R_(e,t,n,`persist`,F_,`the config globals field to write`),copy:m_(`copy`),open:m_(`open`),reset:h_,undo:g_(`undo`),redo:g_(`redo`)};function m_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Pc(t,n,r,e);return i===null?null:{[e]:i}}}function h_(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=__(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}function g_(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the ONE global history over the whole overrides layer), got ${Vc(r[e])}`),null)}}function __(e,t,n,r,i,a){let o=Pc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}function v_(e,t,n,r,i){return __(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`)}function y_(e){return e===`set`?`set-state`:`set-config`}const b_={to:z_(`set`)},x_={to:z_(`persist`)},S_={from:B_(`set`)},C_={from:B_(`persist`)},w_={min:G_(),max:G_(),by:G_()},T_={int:H_()},E_={cycle:V_(`set`)},D_={cycle:V_(`persist`)},O_={removeSegment:U_(`removeSegment`)},k_={insertSegment:U_(`insertSegment`),anchor:U_(`anchor`),relation:W_()},A_={insertSegmentFrom:B_(`persist`),anchor:U_(`anchor`),relation:W_()},j_={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},M_={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function N_(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=(e,n,r)=>Uc(e,t,n,r),s=tl(t);return{detect:a,allowed:[e,...i],label:i.join(`/`),json:{type:`object`,properties:{[e]:{type:`string`},...s.properties},required:[e,...s.required??[]],additionalProperties:!1},parse:n.length?Jc(o,...n):o}}const P_=[N_(`set`,b_),N_(`set`,S_),N_(`set`,w_,[j_,M_]),N_(`set`,T_),N_(`set`,E_)],F_=[N_(`persist`,x_),N_(`persist`,C_),N_(`persist`,w_,[j_,M_]),N_(`persist`,D_),N_(`persist`,O_),N_(`persist`,k_,[],[`insertSegment`]),N_(`persist`,A_,[],[`insertSegmentFrom`])];function I_(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function L_(e){let t=I_(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function R_(e,t,n,r,i,a){let o=v_(e,t,n,r,a),s=i.filter(e=>e.detect.some(e=>e in n));if(s.length!==1)return Q(e,t,`${L_(r)}${s.length>1?` — found: ${s.map(e=>e.label).join(`, `)}`:``}`),null;let c=s[0];for(let i of Object.keys(n))c.allowed.includes(i)||Q(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${c.allowed.join(`, `)}`);let l=c.parse(e,t,n);return o===null||l===null?null:{[r]:o,...l}}function z_(e){let t=y_(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>__(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function B_(e){let t=y_(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Q(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Q(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Q(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Q(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Vc(o)}`)}}}function V_(e){let t=y_(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Bc(o)}`);return}let c=o;if(c.length<2){Q(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function H_(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Vc(r[n])}`);return}return!0}}}function U_(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Pc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function W_(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${Vc(i)}`);return}return i}}}function G_(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${Vc(i)}`);return}return i}}}const K_={noun:`look key`,fields:{hueShift:Zc(),chromaScale:Zc({min:0}),lightnessScale:Zc(),lightnessShift:Zc()}};function q_(e,t){if(!zc(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${Bc(t)}`,line:Y(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:Y(e.source,[`looks`,r])});continue}let t=Hc(e,K_,`looks.${r}`,i);t!==null&&(n[r]={...Da,...t})}return n}const J_={noun:`preset key`,fields:{root:{required:!1,json:{$ref:$l},parse:(e,t,n,r)=>r[n]===void 0?void 0:du(e,`${t}.${n}`,r[n])},globals:{required:!1,json:hl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:ml(e,`${t}.${n}`,r[n])}}};function Y_(e,t){if(!zc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Bc(t)}`,line:Y(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:Y(e.source,[`presets`,r])});continue}let t=Hc(e,J_,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function X_(e,t){if(t===void 0)return{};if(!zc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Bc(t)}`,line:Y(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Vc(i)}`,line:Y(e.source,[`helpers`,r])});continue}n[r]=i}return n}const Z_=new Map;function Q_(e,t){Z_.set(e,{permanent:!0,resolve:t})}Q_(`themes`,()=>xc()),Q_(`styles`,()=>Tc),Q_(`charsets`,()=>Oc),Q_(`colorCompatibilities`,()=>kc);function $_(e){return new Map([[`looks`,Object.keys(e.looks)],[`presets`,Ig(e.presets)]])}function ev(e){return[...new Set([...Z_.keys(),...e.keys()])]}function tv(e,t){if(typeof e!=`string`)return e;let n=t.get(e);if(n)return n;let r=Z_.get(e);if(r)return r.resolve();throw Error(`unknown option domain "${e}" (have: ${ev(t).join(`, `)})`)}const nv=/{{([\s\S]*?)}}/g,rv=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,iv=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function av(e){let t=new Set,n;for(nv.lastIndex=0;(n=nv.exec(e))!==null;){let e=n[1].replace(rv,``),r;for(iv.lastIndex=0;(r=iv.exec(e))!==null;)t.add(r[1])}return t}const ov=/\baction\s+$/;function sv(e){let t=new Set;nv.lastIndex=0;let n;for(;(n=nv.exec(e))!==null;){let e=n[1],r=0,i;for(rv.lastIndex=0;(i=rv.exec(e))!==null;)ov.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const cv=/\b(picker|menu)\s+$/;function lv(e){let t=new Set;nv.lastIndex=0;let n;for(;(n=nv.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(rv.lastIndex=0;(a=rv.exec(e))!==null;){let n=cv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function uv(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const dv={gitTaculous:`gitaculous`};function fv(e,t){let n=new Map;for(let e of Object.keys(t)){let t=og(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:Y(e.source,[`presets`])})}function pv(e,t){t.globals.look!==void 0&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:Y(e.source,[`globals`,`look`])}),t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:Y(e.source,[`globals`,`preset`])}),fv(e,t.presets);let n=$_(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||ev(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${ev(n).join(`, `)})`,line:Y(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=Jg(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${vl().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.rootOps" target`,line:Y(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root-ops`){mv(e,t,n,a,i,o.preset,r);continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:Y(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:Y(e.source,[`actions`,n,a])})}}let r=new Set(Object.keys(t.variables));for(let[e,n]of Object.entries(t.segments))if(n.vars)for(let t of Object.keys(n.vars))r.add(`${e}.${t}`);let i=(n,i,a)=>{for(let o of Zr(n))if(o.when!==void 0&&yv(e,`${i}.when`,o.when,r,{line:a}),o.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,o.name)){let t=dv[o.name],n=t===void 0?``:` (the built-in segment "${o.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:i,message:`${i} entry "${o.name}" does not match any declared segment${n}`,line:a})}},a=bv(e.source);i(t.root,a,Y(e.source,[a]));for(let[n,r]of Object.entries(t.presets))r.root!==void 0&&i(r.root,`presets.${n}.root`,Y(e.source,[`presets`,n,`root`]));for(let[n,i]of Object.entries(t.variables))_v(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))_v(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){yv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of sv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:Y(e.source,[`segments`,n,a])});for(let r of lv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:Y(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))vv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))vv(e,`segments.${n}.vars.${t}`,a,r,n);(hv(t)||gv(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:Y(e.source,[`variables`])})}function mv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=Y(e.source,[`actions`,n,r]);if(!Ig(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Ig(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.rootOps" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function hv(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function gv(e){return Object.values(e.actions).some(e=>o_(e)||s_(e)||c_(e)||l_(e)||u_(e))}function _v(e,t,n,r,i){n.kind===`template`&&yv(e,`${t}.template`,n.template,r,{segCtx:i}),$r(n)&&n.cache&&`key`in n.cache&&yv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function vv(e,t,n,r,i){if($r(n)&&n.cache&&`depends_on`in n.cache)for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:Y(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function yv(e,t,n,r,i){for(let a of av(n)){if(uv(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&uv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Y(e.source,t.split(`.`))})}}function bv(e){try{let t=ci.default.parse(e);if(zc(t)&&`root`in t)return`root`}catch{}return`layout`}function xv(e,t){let{graph:n,nodeInfo:r}=Sv(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:Y(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function Sv(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(e,n)=>{for(let i of av(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),$r(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const Cv=[`json5`,`json`];function wv(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function Tv(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[wv(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return[...e?Cv.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...Cv.map(e=>c.join(i,`.cc-candybar.${e}`)),...Cv.map(e=>c.join(a,`cc-candybar`,`config.${e}`))]}function Ev(e,t,n){return Tv(e,t,n).find(r.existsSync)??null}function Dv(e,t){let n=Tv(e,t),i=new Set,a=[];for(let e of n)i.has(e)||(i.add(e),r.existsSync(e)&&a.push(e));let o=new Map;for(let e of a){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),r=c.join(t,n);o.has(r)||o.set(r,[]),o.get(r).push(e)}let s=[...o.values()].filter(e=>e.length>1);return s.length===0?null:`config-extension collision: ${s.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Ov(e,t,n){let i=e===null?``:r.readFileSync(e,`utf-8`);return{config:ol(e===null?{}:Av(e,i,n),t),source:i}}function kv(e,t=`<config>`,n=``,r=new Set(xc())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(pv(a,e),xv(a,e),i.length>0)throw new Ac(t,i);return i_(e)}function Av(e,t,n=new Set(xc())){let r=jv(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!zc(r))throw new Ac(e,[{path:``,message:`Config root must be an object, got ${Bc(r)}`}]);let o=Mv(a,r);if(i.length>0)throw new Ac(e,i);return o}function jv(e,t){try{return ci.default.parse(t)}catch(t){let n=t;throw new Ac(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Mv(e,t){for(let n of Object.keys(t))Nv.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Nv].join(`, `)}`,line:Y(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=pl(e,`globals`,t.globals)),t.variables!==void 0&&(n.variables=jl(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=Jl(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
101
101
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
102
102
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
103
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:Y(e.source,[`layout`])}),t.root!==void 0&&(n.root=du(e,`root`,t.root)),t.actions!==void 0&&(n.actions=
|
|
104
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!kv.test(t))continue;let r=Av(t);if(r!=null)return r}return null}const Pv=10*1e3;function Fv(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 Iv(e,t){if(!(t<60))return e*3600/t}function Lv(e,t,n,r){let i=r-t;if(i<50||i>Pv)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Rv(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Lv(t.input,t.atMs,n.input,n.atMs),i=Lv(t.output,t.atMs,n.output,n.atMs),a=Lv(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 zv(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>Pv)continue;let o=Lv(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Bv(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 Zr(e.root)){if(t.when)for(let e of tv(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 tv(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Vv(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 tv(e.template))n.push(t)}}}return i}function Vv(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 Hv(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Uv(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 Wv(e,t,n,r,i){let a=e=>Hv(r,e),o=(t.clock??(()=>new Date))().getTime(),s=(e,t,n)=>t?n().catch(t=>Bn(`${e}: ${String(t)}`)):Promise.resolve(L),[c,l,u,d,f,p,m,h]=await Promise.all([s(`git`,a(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Uv(r),e.workspace?.project_dir)),s(`session`,a(`session.cost`)||a(`session.tokens`)||a(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),s(`today`,a(`today`),()=>t.usageStore.getTodayInfo(e)),s(`context`,a(`context`),()=>t.contextProvider.getContextInfo(e)),s(`metrics`,a(`metrics`)||a(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),s(`tmux`,a(`tmux`),()=>t.tmuxService.getSessionId()),s(`cache`,a(`cache`),()=>jv(e.transcript_path)),s(`speed`,a(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,o))]),g=[],_=e=>{if(e.kind===`failed`){g.push(e.reason);return}return e.kind===`ok`?e.value:void 0},v=qv(c);g.push(...v.failures);let y=_(l),b=_(u),x=_(d),S=_(f),C=_(p),ee=_(m);for(let e of g)t.log(`warn`,`provider fetch failed: ${e}`);let te=e.rate_limits?.five_hour,w=e.rate_limits?.seven_day,ne=te?Fv(te.used_percentage,te.resets_at,18e6,o):void 0,re=w?Fv(w.used_percentage,w.resets_at,6048e5,o):void 0,ie=y?.session.cost,T=S?.sessionDuration,E=a(`burn`)&&ie!=null&&T!=null?Iv(ie,T):void 0,ae=_(h),oe=ae===void 0?void 0:Rv(ae),se=ae===void 0?void 0:zv(ae),ce=oe!==void 0||se!==void 0?{...oe,...se!==void 0&&{history:se}}:void 0,le=Kv(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:Kv(e.workspace.current_dir)??``,project_dir:Kv(e.workspace.project_dir)??``}:e.workspace,de=y===void 0?void 0:Gv({cost:y.session.cost,tokens:y.session.tokens}),fe=b===void 0?void 0:{cost:b.cost,tokens:b.tokens},pe=S===void 0?void 0:Gv({lastResponseTime:S.lastResponseTime,responseTime:S.responseTime,sessionDuration:S.sessionDuration,messageCount:S.messageCount,linesAdded:S.linesAdded,linesRemoved:S.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},...v.git!==void 0&&{git:v.git},...C!==void 0&&{tmux:{session:C}},theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...de!==void 0&&{session:de},...fe!==void 0&&{today:fe},...E!==void 0&&{burn:{costPerHour:E}},...ce!==void 0&&{speed:ce},...a(`block`)&&te!==void 0&&{block:{nativeUtilization:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at,...re!==void 0&&{etaMinutes:re}}},...ee!==void 0&&{cache:{expiresAt:ee}},...x!==void 0&&{context:{totalTokens:x.totalTokens,contextLeft:x.contextLeftPercentage}},...pe!==void 0&&{metrics:pe}}}function Gv(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 Kv(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function qv(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 Jv=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,Yv=`{{ \$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 (${Jv}) (basename .project_dir) (ne (${Jv}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,Xv={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},Zv=(e,t)=>`{{ fg (color "${Xv[e]}") ${t} }}`,Qv=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,$v=`{{ 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 }}${Zv(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${Zv(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${Zv(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${Zv(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,ey=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${Zv(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Zv(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${Zv(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+$v+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${Zv(`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 ty(e,t){return`{{ if ge (round ${e}) ${t} }}error{{ else }}{{ if ge (round ${e}) 50 }}warning{{ else }}panel{{ end }}{{ end }}`}function ny(e){return`{{ if ge (round ${e}) 50 }}button-color-foreground{{ else }}foreground{{ end }}`}function ry(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 iy(e,t){return`{{ if lt ${e} 0 }}foreground{{ else }}{{ if lt ${e} ${t} }}button-color-foreground{{ else }}foreground{{ end }}{{ end }}`}const ay={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:``},"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:``},"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},activeStyle:{kind:`state`,key:`style`,default:``}},segments:{directory:{template:Yv,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 "" }}`},git:{template:ey,bg:`surface-active`,fg:Qv,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 }}${Zv(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${Zv(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${Zv(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${Zv(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${Zv(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Zv(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${Zv(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${Zv(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,bg:`surface-active`,fg:Qv,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 }}`,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:ty(`.block.nativeUtilization`,`.block.budget.warningThreshold`),fg:ny(`.block.nativeUtilization`),when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .weekly.resetsAt) }})`,bg:ty(`.weekly.percentage`,`.weekly.budget.warningThreshold`),fg:ny(`.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:ry(`.block.etaMinutes`,`.burn.eta.warnMinutes`,`.burn.eta.errorMinutes`),fg:iy(`.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 }}`},styleControl:{template:`✦ {{ if .activeStyle }}{{ .activeStyle }}{{ else }}(default){{ end }} {{ menu "applyStyle" }} 📌{{ menu "applyStyleForever" (dict "key" "pickersForever") }} {{ action "resetStyle" "↺" }}`,bg:`surface`,fg:`foreground`},themeControl:{template:`🎨 {{ .theme.effective }} {{ menu "applyTheme" (dict "key" "pickers") }} 📌{{ menu "applyThemeForever" (dict "key" "pickersForever") }} {{ action "resetTheme" "↺" }}`,bg:`surface`,fg:`foreground`},lookControl:{template:`◐ {{ .look.effective }} {{ menu "applyLook" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyLookForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetLook" "↺" }}`,bg:`surface`,fg:`foreground`},presetControl:{template:`▦ {{ .preset.effective }} {{ menu "applyPreset" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyPresetForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetPreset" "↺" }}`,bg:`surface`,fg:`foreground`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" }} {{ action "resetCharset" "↺" }}`,bg:`surface`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" }} {{ action "resetColorCompat" "↺" }}`,bg:`surface`,fg:`foreground`},wrapToggleControl:{template:`{{ action "toggleWrapForever" "wrap: on" "wrap: off" }} {{ action "resetAutoWrap" "↺" }}`,bg:`surface`,fg:`foreground`},paddingControl:{template:`{{ action "paddingDownForever" "◀" }} padding {{ .padding.effective }} {{ action "paddingUpForever" "▶" }} {{ action "resetPadding" "↺" }}`,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:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ settings`,direction:`horizontal`,children:[`themeControl`,`lookControl`,`presetControl`,`styleControl`,`charsetControl`,`colorCompatControl`,`wrapToggleControl`,`paddingControl`,`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 }}`},applyStyle:{set:`style`,from:`styles`},applyTheme:{set:`theme`,from:`themes`},applyLook:{set:`look`,from:`looks`},applyPreset:{set:`preset`,from:`presets`},applyThemeForever:{persist:`palette`,from:`themes`},resetTheme:{reset:`palette`},applyStyleForever:{persist:`style`,from:`styles`},resetStyle:{reset:`style`},applyLookForever:{persist:`look`,from:`looks`},resetLook:{reset:`look`},applyPresetForever:{persist:`preset`,from:`presets`},resetPreset:{reset:`preset`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},toggleWrapForever:{persist:`autoWrap`,cycle:[`true`,`false`]},resetAutoWrap:{reset:`autoWrap`},paddingDownForever:{persist:`padding`,min:0,max:16,by:-1},paddingUpForever:{persist:`padding`,min:0,max:16,by:1},resetPadding:{reset:`padding`},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`},{kind:`segment`,name:`presetControl`}]},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:`segment`,name:`presetControl`}]},{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`}]}]}}},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 }}`}},oy=new Set([ay.globals.palette,...Object.values(ay.segments).map(e=>e.palette)].filter(e=>e!==void 0)),sy=ol(Tv(`<default>`,JSON.stringify(ay),oy),ay);function cy(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 ly(e){return typeof e==`string`?e:String(e)}function uy(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 dy(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 fy=/^(?:(?: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,py=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function my(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(fy);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(py);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 hy(e){let t=e.match(py);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 gy(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 _y(e){return e.toLocaleString()}const vy=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],yy=vy.length;function by(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*(yy-1));o+=vy[t]}return o}function xy(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 Sy=xc(),Cy=[...Tc];function wy(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>gy(e),argTypes:[`string`]},int:{fn:e=>uy(e),argTypes:[`value`]},string:{fn:e=>ly(e),argTypes:[`value`]},bool:{fn:e=>dy(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>Sy,argTypes:[]},styles:{fn:()=>Cy,argTypes:[]},sparkline:{fn:(e,t)=>by(xy(e),t),argTypes:[`string`,`int`]}}}function Ty(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>_y(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>my(e),argTypes:[`string`]},shortenModelName:{fn:e=>hy(e),argTypes:[`string`]}}}function Ey(e,t=()=>new Date){return af({fromString:e=>new Ho(e),toString:e=>e.plain,clock:t,missingKey:`error`,funcs:{...Yp(),...ag(),...Fm(),...rh(),...Vp(t),...jf(),...lm(),...gc(),...wy(),...Ty(t),...e??{}}})}function Dy(e){return Oy(e,new Set(e.names()),``)}function Oy(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 Oy(e,t,a)}})}function ky(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Ay(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 jy(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 My(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(`
|
|
105
|
-
`)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const
|
|
106
|
-
`)?r.slice(0,-1):r}return $o(new Uo([...e],n),{colorSystem:t.colorCompatibility})}const Zy=new Map,Qy=new Map;function $y(e){let t=vc(e),n=Zy.get(t);if(n!==void 0)return n;let r=ao(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 Zy.set(t,r),r}function eb(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Qy.get(n);if(r!==void 0)return r;let i=vo(e,t);return Qy.set(n,i),i}function tb(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=nb(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=nb([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function nb(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>rb(e,t)):e,r=Ho.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 rb(e,t){let n=e.copy();return n.style=t.add(e.style),n}function ib(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function ab(e,t){let n=Ho.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function ob(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=ab(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 sb=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function cb(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=lb(r,a),c=s===void 0?void 0:ub(n,s,`bg`);o.bg=c;let l=lb(i,a),u=l===void 0?void 0:ub(n,l,`fg`);return new G({bgcolor:c===void 0?void 0:ua.fromRgba(c),color:u===void 0?void 0:ua.fromRgba(u)})}function lb(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function ub(e,t,n){try{return za(e,t)}catch(e){throw e instanceof Ia?new sb(t,n,e.message):e}}const db=new Map([[`palette`,`theme.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function fb(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,pb(e,a,o,n,r));return i}function pb(e,t,n,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:[...J_(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=db.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:[...J_(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:[...J_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:mb(e,n.copy,t)}:`open`in n?{kind:`open`,target:mb(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function mb(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function hb(e,t){return e.has(t)?ly(e.read(t)):``}function gb(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function _b(e,t,n){let r=new Ho(e,{style:new G({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function vb(e,t){return Math.max(e.members.indexOf(hb(t,e.stateVar)),0)}function yb(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=hb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=hb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=hb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(vb(e,r)+1)%e.members.length];return{effect:{verb:Ct,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:wt,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:Tt,args:[gb(e.text,Dy(r))]},active:!1};case`open`:return{effect:{verb:Et,args:[gb(e.target,Dy(r))]},active:!1};case`persist-literal`:{let t=hb(r,e.stateVar);return{effect:{verb:kt,args:[i,e.key,e.value]},active:t===e.value}}case`persist-option`:{let a=n??t,o=hb(r,e.stateVar);return{effect:{verb:kt,args:[i,e.key,a]},active:o===a}}case`persist-cycle`:{let t=e.members[(vb(e,r)+1)%e.members.length];return{effect:{verb:kt,args:[i,e.key,t]},active:!1}}case`persist-bounded`:return{effect:{verb:At,args:[i,e.key,String(e.by)]},active:!1};case`reset`:return{effect:{verb:jt,args:[i,e.key]},active:!1};case`undo`:return{effect:{verb:Nt,args:[i]},active:!1};case`redo`:return{effect:{verb:Pt,args:[i]},active:!1};case`layout-op`:return{effect:{verb:Mt,args:[i,e.key,Dg(e.op)]},active:!1};case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effect:{verb:Mt,args:[i,e.key,Dg(r)]},active:!1}}}}function bb(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`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[vb(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 xb(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}=bb(e,r,t,i),{effect:s,active:c}=yb(r,a,o,i,hb(i,`session.id`));return _b(a,It([s]),c)}function Sb(e){return{action:{fn:(t,...n)=>xb(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function Cb(e){return new Ho(e).cellLength}function wb(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 Tb(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ho(` `)),n.push(t);let r=Ho.fromFragments(n);return r.noWrap=t,r.end=``,r}function Eb(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 Db(e,t){let n=e.compiled.get(t);if(!n||n.kind!==`set-option`&&n.kind!==`persist-option`&&n.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 ${n?`a ${n.kind} action`:`no such action`}`);return n}function Ob(e,t,n,r,i,a){let o=Db(a,e),s=a.store,c=hb(s,`session.id`),l=`stateVar`in o?hb(s,o.stateVar):void 0,u=o.options.map(Cb),d=i?Math.max(1,uy(s.read(`term.cols`))-Yy(a.stripStyle)-2*a.padding):1/0,f=Cb(`✕`)+1,p=Cb(`←`)+1+Cb(`→`)+1,m=wb(u,d,f),h=m.length>1?wb(u,d,f+p):m,g=parseInt(hb(s,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>It([{verb:Ct,args:[c,t.key,String(e)]}]),b=n.flatMap(([e,t])=>[e,t]),x=It([{verb:Ct,args:[c,...b]}]),S=r?[{verb:Ct,args:[c,...b]}]:[],C=e=>{if(o.kind===`persist-option`)return It([{verb:kt,args:[c,o.key,e]},...S]);if(o.kind===`layout-op-option`){let t=Dg({op:`insert`,segment:e,anchor:o.anchor,relation:o.relation});return It([{verb:Mt,args:[c,o.key,t]},...S])}return It([{verb:Ct,args:[c,o.key,e,...r?b:[]]}])},ee=[_b(`✕`,x,!1)];_>0&&ee.push(_b(`←`,y(_-1),!1));for(let e of v){let t=o.options[e];ee.push(_b(t,C(t),t===l))}return _<h.length-1&&ee.push(_b(`→`,y(_+1),!1)),Tb(ee,i)}function kb(e){return{picker:{fn:(t,n,r,i)=>{let a=Eb(e,n,`set-int`,`an int action ({ set, int: true })`);return Ob(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const Ab=Symbol(`cc-candybar.menuDrop`);function jb(e){return e.flatMap(e=>e[Ab]??[])}function Mb(e,t,n){let r=n.activeSegment.current;if(r===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let i=n.action,a=lg(r.segName,e,t.key),o=dg(a),s=cg(e),c=hb(i.store,a)===s,l=hb(i.store,`session.id`),u=_b(c?`▾`:`▸`,It([{verb:Ct,args:[l,a,c?Rt:s,o,`0`]}]),!1);return u[Ab]=c?[Ob(e,{key:o,stateVar:o},[[a,Rt],[o,`0`]],t.closeOnPick,t.paged,i)]:[],u}function Nb(e){return{menu:{fn:(t,n)=>Mb(t,fg(n??{}),e),argTypes:[`string`,`dict`],returnType:`T`}}}function Pb(){return{current:null}}function Fb(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 Ib(e){let t={fn:(()=>{let t=Fb(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{...hc(()=>Fb(e,`color`).palette),bgOf:t}}function Lb(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
103
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:Y(e.source,[`layout`])}),t.root!==void 0&&(n.root=du(e,`root`,t.root)),t.actions!==void 0&&(n.actions=d_(e,t.actions)),t.looks!==void 0&&(n.looks=q_(e,t.looks)),t.presets!==void 0&&(n.presets=Y_(e,t.presets)),t.helpers!==void 0&&(n.helpers=X_(e,t.helpers)),Su(e,n),yg(e,n),Eg(e,n),n}const Nv=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`helpers`]),Pv=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Fv(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 Iv(e){let t=await Lv(e);return t.kind===`ok`?I(Math.floor((t.value+36e5)/1e3)):t}async function Lv(e){for(let t of[65536,1048576]){let n=await Or(e,t);if(n.kind!==`ok`)return n;let r=Rv(n.value.buf,n.value.fromStart);if(r!=null)return I(r);if(n.value.fromStart)return L}return L}function Rv(e,t){let n=e.toString(`utf8`).split(`
|
|
104
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Pv.test(t))continue;let r=Fv(t);if(r!=null)return r}return null}const zv=10*1e3;function Bv(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 Vv(e,t){if(!(t<60))return e*3600/t}function Hv(e,t,n,r){let i=r-t;if(i<50||i>zv)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Uv(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Hv(t.input,t.atMs,n.input,n.atMs),i=Hv(t.output,t.atMs,n.output,n.atMs),a=Hv(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 Wv(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>zv)continue;let o=Hv(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Gv(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 Zr(e.root)){if(t.when)for(let e of av(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 av(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Kv(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 av(e.template))n.push(t)}}}return i}function Kv(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 qv(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Jv(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 Yv(e,t,n,r,i){let a=e=>qv(r,e),o=(t.clock??(()=>new Date))().getTime(),s=(e,t,n)=>t?n().catch(t=>Bn(`${e}: ${String(t)}`)):Promise.resolve(L),[c,l,u,d,f,p,m,h]=await Promise.all([s(`git`,a(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Jv(r),e.workspace?.project_dir)),s(`session`,a(`session.cost`)||a(`session.tokens`)||a(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),s(`today`,a(`today`),()=>t.usageStore.getTodayInfo(e)),s(`context`,a(`context`),()=>t.contextProvider.getContextInfo(e)),s(`metrics`,a(`metrics`)||a(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),s(`tmux`,a(`tmux`),()=>t.tmuxService.getSessionId()),s(`cache`,a(`cache`),()=>Iv(e.transcript_path)),s(`speed`,a(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,o))]),g=[],_=e=>{if(e.kind===`failed`){g.push(e.reason);return}return e.kind===`ok`?e.value:void 0},v=Qv(c);g.push(...v.failures);let y=_(l),b=_(u),x=_(d),S=_(f),C=_(p),ee=_(m);for(let e of g)t.log(`warn`,`provider fetch failed: ${e}`);let te=e.rate_limits?.five_hour,w=e.rate_limits?.seven_day,ne=te?Bv(te.used_percentage,te.resets_at,18e6,o):void 0,re=w?Bv(w.used_percentage,w.resets_at,6048e5,o):void 0,ie=y?.session.cost,T=S?.sessionDuration,E=a(`burn`)&&ie!=null&&T!=null?Vv(ie,T):void 0,ae=_(h),oe=ae===void 0?void 0:Uv(ae),se=ae===void 0?void 0:Wv(ae),ce=oe!==void 0||se!==void 0?{...oe,...se!==void 0&&{history:se}}:void 0,le=Zv(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:Zv(e.workspace.current_dir)??``,project_dir:Zv(e.workspace.project_dir)??``}:e.workspace,de=y===void 0?void 0:Xv({cost:y.session.cost,tokens:y.session.tokens}),fe=b===void 0?void 0:{cost:b.cost,tokens:b.tokens},pe=S===void 0?void 0:Xv({lastResponseTime:S.lastResponseTime,responseTime:S.responseTime,sessionDuration:S.sessionDuration,messageCount:S.messageCount,linesAdded:S.linesAdded,linesRemoved:S.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},...v.git!==void 0&&{git:v.git},...C!==void 0&&{tmux:{session:C}},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},...de!==void 0&&{session:de},...fe!==void 0&&{today:fe},...E!==void 0&&{burn:{costPerHour:E}},...ce!==void 0&&{speed:ce},...a(`block`)&&te!==void 0&&{block:{nativeUtilization:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at,...re!==void 0&&{etaMinutes:re}}},...ee!==void 0&&{cache:{expiresAt:ee}},...x!==void 0&&{context:{totalTokens:x.totalTokens,contextLeft:x.contextLeftPercentage}},...pe!==void 0&&{metrics:pe}}}function Xv(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 Zv(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Qv(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 $v=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,ey=`{{ \$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 (${$v}) (basename .project_dir) (ne (${$v}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,ty={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},ny=(e,t)=>`{{ fg (color "${ty[e]}") ${t} }}`,ry=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,iy=`{{ 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 }}${ny(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${ny(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${ny(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${ny(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,ay=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${ny(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${ny(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${ny(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+iy+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${ny(`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 oy(e,t){return`{{ if ge (round ${e}) ${t} }}error{{ else }}{{ if ge (round ${e}) 50 }}warning{{ else }}panel{{ end }}{{ end }}`}function sy(e){return`{{ if ge (round ${e}) 50 }}button-color-foreground{{ else }}foreground{{ end }}`}function cy(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 ly(e,t){return`{{ if lt ${e} 0 }}foreground{{ else }}{{ if lt ${e} ${t} }}button-color-foreground{{ else }}foreground{{ end }}{{ end }}`}const uy={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:``},"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},activeStyle:{kind:`state`,key:`style`,default:``}},segments:{directory:{template:ey,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 "" }}`},git:{template:ay,bg:`surface-active`,fg:ry,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 }}${ny(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${ny(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${ny(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${ny(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${ny(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${ny(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${ny(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${ny(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,bg:`surface-active`,fg:ry,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:oy(`.block.nativeUtilization`,`.block.budget.warningThreshold`),fg:sy(`.block.nativeUtilization`),when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatLongTimeRemaining" (minutesUntilReset .weekly.resetsAt) }})`,bg:oy(`.weekly.percentage`,`.weekly.budget.warningThreshold`),fg:sy(`.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:cy(`.block.etaMinutes`,`.burn.eta.warnMinutes`,`.burn.eta.errorMinutes`),fg:ly(`.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 }}`},styleControl:{template:`✦ {{ if .activeStyle }}{{ .activeStyle }}{{ else }}(default){{ end }} {{ menu "applyStyle" }} 📌{{ menu "applyStyleForever" (dict "key" "pickersForever") }} {{ action "resetStyle" "↺" }}`,bg:`surface`,fg:`foreground`},themeControl:{template:`🎨 {{ .theme.effective }} {{ menu "applyTheme" (dict "key" "pickers") }} 📌{{ menu "applyThemeForever" (dict "key" "pickersForever") }} {{ action "resetTheme" "↺" }}`,bg:`surface`,fg:`foreground`},lookControl:{template:`◐ {{ .look.effective }} {{ menu "applyLook" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyLookForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetLook" "↺" }}`,bg:`surface`,fg:`foreground`},presetControl:{template:`▦ {{ .preset.effective }} {{ menu "applyPreset" (dict "key" "pickers" "closeOnPick" true) }} 📌{{ menu "applyPresetForever" (dict "key" "pickersForever" "closeOnPick" true) }} {{ action "resetPreset" "↺" }}`,bg:`surface`,fg:`foreground`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" }} {{ action "resetCharset" "↺" }}`,bg:`surface`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" }} {{ action "resetColorCompat" "↺" }}`,bg:`surface`,fg:`foreground`},wrapToggleControl:{template:`{{ action "toggleWrapForever" "wrap: on" "wrap: off" }} {{ action "resetAutoWrap" "↺" }}`,bg:`surface`,fg:`foreground`},paddingControl:{template:`{{ action "paddingDownForever" "◀" }} padding {{ .padding.effective }} {{ action "paddingUpForever" "▶" }} {{ action "resetPadding" "↺" }}`,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:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ settings`,direction:`horizontal`,children:[`themeControl`,`lookControl`,`presetControl`,`styleControl`,`charsetControl`,`colorCompatControl`,`wrapToggleControl`,`paddingControl`,`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 }}`},applyStyle:{set:`style`,from:`styles`},applyTheme:{set:`theme`,from:`themes`},applyLook:{set:`look`,from:`looks`},applyPreset:{set:`preset`,from:`presets`},applyThemeForever:{persist:`palette`,from:`themes`},resetTheme:{reset:`palette`},applyStyleForever:{persist:`style`,from:`styles`},resetStyle:{reset:`style`},applyLookForever:{persist:`look`,from:`looks`},resetLook:{reset:`look`},applyPresetForever:{persist:`preset`,from:`presets`},resetPreset:{reset:`preset`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},toggleWrapForever:{persist:`autoWrap`,cycle:[`true`,`false`]},resetAutoWrap:{reset:`autoWrap`},paddingDownForever:{persist:`padding`,min:0,max:16,by:-1},paddingUpForever:{persist:`padding`,min:0,max:16,by:1},resetPadding:{reset:`padding`},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`},{kind:`segment`,name:`presetControl`}]},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:`segment`,name:`presetControl`}]},{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`}]}]}}},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 }}`}},dy=new Set([uy.globals.palette,...Object.values(uy.segments).map(e=>e.palette)].filter(e=>e!==void 0)),fy=ol(Av(`<default>`,JSON.stringify(uy),dy),uy);function py(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 my(e){return typeof e==`string`?e:String(e)}function hy(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 gy(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 _y=/^(?:(?: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,vy=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function yy(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(_y);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(vy);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 by(e){let t=e.match(vy);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 xy(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 Sy(e){return e.toLocaleString()}const Cy=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],wy=Cy.length;function Ty(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*(wy-1));o+=Cy[t]}return o}function Ey(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 Dy=xc(),Oy=[...Tc];function ky(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>xy(e),argTypes:[`string`]},int:{fn:e=>hy(e),argTypes:[`value`]},string:{fn:e=>my(e),argTypes:[`value`]},bool:{fn:e=>gy(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>Dy,argTypes:[]},styles:{fn:()=>Oy,argTypes:[]},sparkline:{fn:(e,t)=>Ty(Ey(e),t),argTypes:[`string`,`int`]}}}function Ay(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>Sy(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>yy(e),argTypes:[`string`]},shortenModelName:{fn:e=>by(e),argTypes:[`string`]}}}function jy(e,t=()=>new Date){return af({fromString:e=>new Ho(e),toString:e=>e.plain,clock:t,missingKey:`error`,funcs:{...Yp(),...ag(),...Fm(),...rh(),...Vp(t),...jf(),...lm(),...gc(),...ky(),...Ay(t),...e??{}}})}function My(e){return Ny(e,new Set(e.names()),``)}function Ny(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 Ny(e,t,a)}})}function Py(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Fy(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 Iy(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 Ly(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(`
|
|
105
|
+
`)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const Ry=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],zy=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],By=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Vy=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Hy(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>Ry[e.getMonth()]],[`Monday`,e=>By[e.getDay()]],[`Jan`,e=>zy[e.getMonth()]],[`Mon`,e=>Vy[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 Uy={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Wy(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=Uy[t];try{return Jy(r,e)}catch{return Yy(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Vn(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Vn(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Vn(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Vn(e.stashCount,0)}}var Gy=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}},Ky=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:T(()=>{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&&(ie(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ie(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function qy(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Jy(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`?my(e):t===`number`?hy(e):gy(e)}function Yy(e){return e===`number`?0:e===`boolean`?!1:``}var Xy=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new Gy;ttlMgr=new Ky;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=jy();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new _r({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,py(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=Py(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=My(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 Hy(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Hy(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=Uy[t.field],r=t.varDefault===void 0?Yy(n):Jy(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,Wy(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=qy(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Jy(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,q.reaction)(()=>{let t=My(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,q.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 Iy(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 Ly(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,Jy(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Yy(t))}}defaultFor(e){try{return Jy(this.defaultEmptyValue,e)}catch{return Yy(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 Zy={unicode:{},ascii:{glyph:`>`}},Qy={unicode:{},ascii:{left:`(`,right:`)`}};function $y(e,t,n){switch(e){case`capsule`:return new Yo(Qy[t]);case`plain`:return new Xo(n===void 0?{}:{separator:n});case`powerline`:return new Jo(Zy[t]);default:return e}}function eb(e){switch(e){case`powerline`:return 1;case`capsule`:return 2;case`plain`:return 0;default:return e}}function tb(e,t){if(e.length===0)return``;let n=$y(t.style,t.charset,t.separator);if(t.wrap&&Number.isFinite(t.width)){let r=$o(new ds([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
|
|
106
|
+
`)?r.slice(0,-1):r}return $o(new Uo([...e],n),{colorSystem:t.colorCompatibility})}const nb=new Map,rb=new Map;function ib(e){let t=vc(e),n=nb.get(t);if(n!==void 0)return n;let r=ao(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 nb.set(t,r),r}function ab(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=rb.get(n);if(r!==void 0)return r;let i=vo(e,t);return rb.set(n,i),i}function ob(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=sb(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=sb([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function sb(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>cb(e,t)):e,r=Ho.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 cb(e,t){let n=e.copy();return n.style=t.add(e.style),n}function lb(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function ub(e,t){let n=Ho.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function db(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=ub(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 fb=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function pb(e,t,n,r,i,a){let o={segName:t,palette:n,bg:void 0};e.current=o;let s=mb(r,a),c=s===void 0?void 0:hb(n,s,`bg`);o.bg=c;let l=mb(i,a),u=l===void 0?void 0:hb(n,l,`fg`);return new G({bgcolor:c===void 0?void 0:ua.fromRgba(c),color:u===void 0?void 0:ua.fromRgba(u)})}function mb(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function hb(e,t,n){try{return za(e,t)}catch(e){throw e instanceof Ia?new fb(t,n,e.message):e}}const gb=new Map([[`palette`,`theme.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function _b(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,vb(e,a,o,n,r));return i}function vb(e,t,n,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:[...tv(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=gb.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:[...tv(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:[...tv(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:yb(e,n.copy,t)}:`open`in n?{kind:`open`,target:yb(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function yb(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function bb(e,t){return e.has(t)?my(e.read(t)):``}function xb(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function Sb(e,t,n){let r=new Ho(e,{style:new G({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function Cb(e,t){return Math.max(e.members.indexOf(bb(t,e.stateVar)),0)}function wb(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=bb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=bb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=bb(r,e.stateVar);return{effect:{verb:Ct,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(Cb(e,r)+1)%e.members.length];return{effect:{verb:Ct,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:wt,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:Tt,args:[xb(e.text,My(r))]},active:!1};case`open`:return{effect:{verb:Et,args:[xb(e.target,My(r))]},active:!1};case`persist-literal`:{let t=bb(r,e.stateVar);return{effect:{verb:kt,args:[i,e.key,e.value]},active:t===e.value}}case`persist-option`:{let a=n??t,o=bb(r,e.stateVar);return{effect:{verb:kt,args:[i,e.key,a]},active:o===a}}case`persist-cycle`:{let t=e.members[(Cb(e,r)+1)%e.members.length];return{effect:{verb:kt,args:[i,e.key,t]},active:!1}}case`persist-bounded`:return{effect:{verb:At,args:[i,e.key,String(e.by)]},active:!1};case`reset`:return{effect:{verb:jt,args:[i,e.key]},active:!1};case`undo`:return{effect:{verb:Nt,args:[i]},active:!1};case`redo`:return{effect:{verb:Pt,args:[i]},active:!1};case`layout-op`:return{effect:{verb:Mt,args:[i,e.key,Dg(e.op)]},active:!1};case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effect:{verb:Mt,args:[i,e.key,Dg(r)]},active:!1}}}}function Tb(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`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[Cb(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 Eb(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}=Tb(e,r,t,i),{effect:s,active:c}=wb(r,a,o,i,bb(i,`session.id`));return Sb(a,It([s]),c)}function Db(e){return{action:{fn:(t,...n)=>Eb(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function Ob(e){return new Ho(e).cellLength}function kb(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 Ab(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ho(` `)),n.push(t);let r=Ho.fromFragments(n);return r.noWrap=t,r.end=``,r}function jb(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 Mb(e,t){let n=e.compiled.get(t);if(!n||n.kind!==`set-option`&&n.kind!==`persist-option`&&n.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 ${n?`a ${n.kind} action`:`no such action`}`);return n}function Nb(e,t,n,r,i,a){let o=Mb(a,e),s=a.store,c=bb(s,`session.id`),l=`stateVar`in o?bb(s,o.stateVar):void 0,u=o.options.map(Ob),d=i?Math.max(1,hy(s.read(`term.cols`))-eb(a.stripStyle)-2*a.padding):1/0,f=Ob(`✕`)+1,p=Ob(`←`)+1+Ob(`→`)+1,m=kb(u,d,f),h=m.length>1?kb(u,d,f+p):m,g=parseInt(bb(s,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>It([{verb:Ct,args:[c,t.key,String(e)]}]),b=n.flatMap(([e,t])=>[e,t]),x=It([{verb:Ct,args:[c,...b]}]),S=r?[{verb:Ct,args:[c,...b]}]:[],C=e=>{if(o.kind===`persist-option`)return It([{verb:kt,args:[c,o.key,e]},...S]);if(o.kind===`layout-op-option`){let t=Dg({op:`insert`,segment:e,anchor:o.anchor,relation:o.relation});return It([{verb:Mt,args:[c,o.key,t]},...S])}return It([{verb:Ct,args:[c,o.key,e,...r?b:[]]}])},ee=[Sb(`✕`,x,!1)];_>0&&ee.push(Sb(`←`,y(_-1),!1));for(let e of v){let t=o.options[e];ee.push(Sb(t,C(t),t===l))}return _<h.length-1&&ee.push(Sb(`→`,y(_+1),!1)),Ab(ee,i)}function Pb(e){return{picker:{fn:(t,n,r,i)=>{let a=jb(e,n,`set-int`,`an int action ({ set, int: true })`);return Nb(t,{key:a.key,stateVar:a.stateVar},[[a.key,`-1`]],r===!0,i===!0,e)},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const Fb=Symbol(`cc-candybar.menuDrop`);function Ib(e){return e.flatMap(e=>e[Fb]??[])}function Lb(e,t,n){let r=n.activeSegment.current;if(r===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let i=n.action,a=lg(r.segName,e,t.key),o=dg(a),s=cg(e),c=bb(i.store,a)===s,l=bb(i.store,`session.id`),u=Sb(c?`▾`:`▸`,It([{verb:Ct,args:[l,a,c?Rt:s,o,`0`]}]),!1);return u[Fb]=c?[Nb(e,{key:o,stateVar:o},[[a,Rt],[o,`0`]],t.closeOnPick,t.paged,i)]:[],u}function Rb(e){return{menu:{fn:(t,n)=>Lb(t,fg(n??{}),e),argTypes:[`string`,`dict`],returnType:`T`}}}function zb(){return{current:null}}function Bb(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 Vb(e){let t={fn:(()=>{let t=Bb(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{...hc(()=>Bb(e,`color`).palette),bgOf:t}}function Hb(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
107
107
|
`)){n.push(r);continue}let e=r.split(`
|
|
108
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function
|
|
109
|
-
`)}const qb=/^-?\d+$/;function Jb(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Yb(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 Xb(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!qb.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 Zb(e,t,n){return r=>r?qb.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 Qb(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=>!qb.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:Jb(r[0].seed,t,i)}}return{kind:`int`}}function $b(e){return e===`config`?`set-config`:`set-state`}function ex(e,t,n){return t.kind===`int`?Xb(`menu page "${e}"`):t.kind===`range`?Zb(t.min,t.max,`${n} stepper "${e}"`):Yb(t.allowed,`${n} "${e}"`,$b(n))}function tx(e,t,n){return ex(e,Qb(e,t,n),n)}function nx(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:Qb(e,n,t)}))}function rx(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=tx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:tx(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=tx(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=Qb(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 ix=xc(),ax=new Set(ix),ox=new Set(Tc),sx=e=>e?ax.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${ix.join(`, `)})`}:{ok:!1,reason:`theme name is required`},cx=e=>e?ox.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Tc.join(`, `)})`}:{ok:!1,reason:`style name is required`},lx=new Set([`1`,`true`]),ux=new Set([`0`,`false`]),dx=rx({style:cx,theme:sx,"toolbar-expanded":e=>lx.has(e)?{ok:!0,value:`1`}:ux.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function fx(){return dx.listKeys()}function px(e,t){return dx.register(e,t)}function mx(e,t){return dx.validate(e,t)}function hx(e){return dx.rangeParamsFor(e)}function gx(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:J_(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:Jb(t.get(e.set),e.min,e.max)}}]:[]}function _x(e){let t=new Set(dx.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function vx(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))}return t}function yx(e){let t=vx(e),n=K_(e);return _x(Object.values(e.actions).flatMap(e=>gx(e,t,n)))}function bx(e){return nx(yx(e))}const xx=(e,t)=>D(t),Sx={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`},Cx=new Set([`1`,`true`]),wx=new Set([`0`,`false`,``]);function Tx(e,t){let n=Z_(e);if(n===null)throw Error(`coercePersistValue: "${e}" is not a valid persist target`);if(n.scope===`segment-palette`||n.scope===`preset-root-ops`)return t;let r=Sx[n.field];if(r===`string`)return t;if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`coercePersistValue: "${e}" expects a number, got "${t}"`);return n}if(Cx.has(t))return!0;if(wx.has(t))return!1;throw Error(`coercePersistValue: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function Ex(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[t,n]of Object.entries(e)){let e=Z_(t);if(e===null)return!1;let r=e.scope===`globals`?Sx[e.field]:`string`;if(r===`number`&&typeof n!=`number`||r===`boolean`&&typeof n!=`boolean`||r===`string`&&typeof n!=`string`)return!1}return!0}function Dx(e,t){let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);return Ex(e)?e:(t(`warn`,`config-overrides load: unexpected shape, starting empty`),{})}catch{return t(`warn`,`config-overrides load: corrupt JSON, starting empty`),{}}}function Ox(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))_l(n)&&(t[n]=r);return t}function kx(e){let t=Object.create(null);for(let[n,r]of Object.entries(e)){let e=Z_(n);e?.scope===`segment-palette`&&typeof r==`string`&&(t[e.segment]=r)}return t}function Ax(e,t){let n=Object.create(null);for(let[r,i]of Object.entries(e)){let e=Z_(r);if(!(e?.scope!==`preset-root-ops`||typeof i!=`string`)){try{let t=JSON.parse(i);if(Array.isArray(t)&&t.every(e=>typeof e==`string`)){n[e.preset]=t;continue}}catch{}t(`warn`,`config-overrides: "${r}" is not a valid op-token list, dropping`)}}return n}function jx(e,t=xx){return Ox(Dx(e,t))}function Mx(e,t=xx){let n=Dx(e,t);return{globals:Ox(n),segmentPalette:kx(n),presetRootOps:Ax(n,t)}}function Nx(e,t,n,i){try{r.mkdirSync(c.dirname(e),{recursive:!0});let t=`${e}.tmp`;r.writeFileSync(t,JSON.stringify(n),{mode:384}),r.chmodSync(t,384),r.renameSync(t,e)}catch(e){let n=`${t} write failed: ${e.message}`;throw i(`error`,n),Error(n)}}function Px(e,t,n){Nx(e,`config-overrides`,t,n)}function Fx(e,t,n,r){let i=Dx(e,r),a=i[t];if(n===void 0){if(!(t in i))return a;let n={...i};delete n[t],Px(e,n,r)}else Px(e,{...i,[t]:n},r);return a}function Ix(e,t,n,r=xx){qx(e,{key:t,from:Fx(e,t,n,r)??null,to:n},r)}function Lx(e,t,n=xx){t in Dx(e,n)&&qx(e,{key:t,from:Fx(e,t,void 0,n)??null,to:null},n)}function Rx(e,t,n,r){Fx(e,t,n===null?void 0:n,r)}const zx={past:[],future:[]};function Bx(e){return c.join(c.dirname(e),`config-overrides-history.json`)}function Vx(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Hx(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.key==`string`&&Vx(t.from)&&Vx(t.to)}function Ux(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.past)&&t.past.every(Hx)&&Array.isArray(t.future)&&t.future.every(Hx)}function Wx(e,t){let n=Bx(e),i;try{i=r.readFileSync(n,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides-history read failed (${n}); starting empty`),zx}try{let e=JSON.parse(i);return Ux(e)?e:(t(`warn`,`config-overrides-history load: unexpected shape, starting empty`),zx)}catch{return t(`warn`,`config-overrides-history load: corrupt JSON, starting empty`),zx}}function Gx(e,t,n){Nx(Bx(e),`config-overrides-history`,t,n)}function Kx(e,t,n){let r=[...e,t];return r.length>n?r.slice(r.length-n):r}function qx(e,t,n){Gx(e,{past:Kx(Wx(e,n).past,t,50),future:[]},n)}function Jx(e,t=xx){let n=Wx(e,t),r=n.past[n.past.length-1];return r===void 0?null:(Rx(e,r.key,r.from,t),Gx(e,{past:n.past.slice(0,-1),future:Kx(n.future,r,50)},t),r)}function Yx(e,t=xx){let n=Wx(e,t),r=n.future[n.future.length-1];return r===void 0?null:(Rx(e,r.key,r.to,t),Gx(e,{past:Kx(n.past,r,50),future:n.future.slice(0,-1)},t),r)}const Xx=rx({},`config`);function Zx(){return Xx.listKeys()}function Qx(e,t){return Xx.validate(e,t)}function $x(e){return Xx.rangeParamsFor(e)}function eS(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:J_(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:[Dg({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Dg({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:J_(e.insertSegmentFrom,n).map(t=>Dg({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:Jb(t.get(e.persist),e.min,e.max)}}]:[]}function tS(e){let t=new Map;for(let[n,r]of Object.entries(e.globals))_l(n)&&typeof r==`number`&&t.set(n,r);return t}function nS(e){let t=tS(e),n=new Map([...K_(e),...Kg(e)]);return Object.values(e.actions).flatMap(e=>eS(e,t,n))}function rS(e){return nx(nS(e),`config`)}function iS(e,t){return Xx.register(e,t)}var aS=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,sS(e,t,n,`initial value`),this.cell=q.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){sS(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},oS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,q.computed)(()=>{let e=n();return sS(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function sS(e,t,n,r){let i=cy(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var cS=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new aS(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new oS(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,q.runInAction)(()=>n.set(t))}runInAction(e){(0,q.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 lS(e,t,n){return e+`\0`+t+`\0`+(n??``)}var uS=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=lS(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=xv(e.projectDir,e.cwd,e.configFile);e.lastWarning=Sv(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof Ac||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
|
|
108
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function Ub(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 Wb={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 Ub(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(!lb(i.when,t.scope))return[];let n=i.palette===void 0?t.look:Da,o=ab(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=Hb(ob(c,u)).map(e=>db(e,d)),p=l.map(e=>db(ob([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 Ho(`⚠ ${e.name}: ${r}`)]]}}}};function Gb(e){return Wb[e]}function Kb(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Fy(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 qb(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:Kb(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:Kb(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?Fy(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 Jb(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=`{{ define "${r}" }}${i}{{ end }}`;try{e.parse(t)}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}n+=t}return n}function Yb(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=zb(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=Ig(e.presets),l=new Map([...$_(e),...Qg(e)]),u=jy({...Db(i),...Pb(i),...Rb(o),...Vb(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=Jb(u,e.helpers),f=e=>u.parse(d+e),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=_b(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{qb(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{qb(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:ib(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 Gb(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=zg(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function Xb(e){let t=e.bgcolor;return t===void 0?e:new G({bgcolor:ua.fromRgba(Ka(t.getTruecolor(),1)),color:e.color})}function Zb(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=Da,preset:f=Pg}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=My(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)=>pb(t.activeSegment,e,n,r,i,p),b=e=>(t.activeSegment.current=null,Ib(e)),x=(e,t)=>{let n={scope:p,basePalette:a,look:d,visible:t&&lb(e.when,p),padding:o.padding,nextHueShift:_,perSegmentSink:l,onSegmentError:u,enterSegment:y,exitSegment:b,focusTint:Xb,lookupSegment:v,renderChild:x};return Gb(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 "${Pg}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return x(S,!0).map(e=>tb(e,o)).join(`
|
|
109
|
+
`)}const Qb=/^-?\d+$/;function $b(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function ex(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 tx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Qb.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 nx(e,t,n){return r=>r?Qb.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 rx(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=>!Qb.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:$b(r[0].seed,t,i)}}return{kind:`int`}}function ix(e){return e===`config`?`set-config`:`set-state`}function ax(e,t,n){return t.kind===`int`?tx(`menu page "${e}"`):t.kind===`range`?nx(t.min,t.max,`${n} stepper "${e}"`):ex(t.allowed,`${n} "${e}"`,ix(n))}function ox(e,t,n){return ax(e,rx(e,t,n),n)}function sx(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:rx(e,n,t)}))}function cx(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=ox(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:ox(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=ox(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=rx(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 lx=xc(),ux=new Set(lx),dx=new Set(Tc),fx=e=>e?ux.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lx.join(`, `)})`}:{ok:!1,reason:`theme name is required`},px=e=>e?dx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Tc.join(`, `)})`}:{ok:!1,reason:`style name is required`},mx=new Set([`1`,`true`]),hx=new Set([`0`,`false`]),gx=cx({style:px,theme:fx,"toolbar-expanded":e=>mx.has(e)?{ok:!0,value:`1`}:hx.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function _x(){return gx.listKeys()}function vx(e,t){return gx.register(e,t)}function yx(e,t){return gx.validate(e,t)}function bx(e){return gx.rangeParamsFor(e)}function xx(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:tv(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:$b(t.get(e.set),e.min,e.max)}}]:[]}function Sx(e){let t=new Set(gx.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function Cx(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))}return t}function wx(e){let t=Cx(e),n=$_(e);return Sx(Object.values(e.actions).flatMap(e=>xx(e,t,n)))}function Tx(e){return sx(wx(e))}const Ex=(e,t)=>D(t),Dx={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`},Ox=new Set([`1`,`true`]),kx=new Set([`0`,`false`,``]);function Ax(e,t){let n=Jg(e);if(n===null)throw Error(`coercePersistValue: "${e}" is not a valid persist target`);if(n.scope===`segment-palette`||n.scope===`preset-root-ops`)return t;let r=Dx[n.field];if(r===`string`)return t;if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`coercePersistValue: "${e}" expects a number, got "${t}"`);return n}if(Ox.has(t))return!0;if(kx.has(t))return!1;throw Error(`coercePersistValue: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function jx(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[t,n]of Object.entries(e)){let e=Jg(t);if(e===null)return!1;let r=e.scope===`globals`?Dx[e.field]:`string`;if(r===`number`&&typeof n!=`number`||r===`boolean`&&typeof n!=`boolean`||r===`string`&&typeof n!=`string`)return!1}return!0}function Mx(e,t){let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);return jx(e)?e:(t(`warn`,`config-overrides load: unexpected shape, starting empty`),{})}catch{return t(`warn`,`config-overrides load: corrupt JSON, starting empty`),{}}}function Nx(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))_l(n)&&(t[n]=r);return t}function Px(e){let t=Object.create(null);for(let[n,r]of Object.entries(e)){let e=Jg(n);e?.scope===`segment-palette`&&typeof r==`string`&&(t[e.segment]=r)}return t}function Fx(e,t){let n=Object.create(null);for(let[r,i]of Object.entries(e)){let e=Jg(r);if(!(e?.scope!==`preset-root-ops`||typeof i!=`string`)){try{let t=JSON.parse(i);if(Array.isArray(t)&&t.every(e=>typeof e==`string`)){n[e.preset]=t;continue}}catch{}t(`warn`,`config-overrides: "${r}" is not a valid op-token list, dropping`)}}return n}function Ix(e,t=Ex){return Nx(Mx(e,t))}function Lx(e,t=Ex){let n=Mx(e,t);return{globals:Nx(n),segmentPalette:Px(n),presetRootOps:Fx(n,t)}}function Rx(e,t,n,i){try{r.mkdirSync(c.dirname(e),{recursive:!0});let t=`${e}.tmp`;r.writeFileSync(t,JSON.stringify(n),{mode:384}),r.chmodSync(t,384),r.renameSync(t,e)}catch(e){let n=`${t} write failed: ${e.message}`;throw i(`error`,n),Error(n)}}function zx(e,t,n){Rx(e,`config-overrides`,t,n)}function Bx(e,t,n,r){let i=Mx(e,r),a=i[t];if(n===void 0){if(!(t in i))return a;let n={...i};delete n[t],zx(e,n,r)}else zx(e,{...i,[t]:n},r);return a}function Vx(e,t,n,r=Ex){Qx(e,{key:t,from:Bx(e,t,n,r)??null,to:n},r)}function Hx(e,t,n=Ex){t in Mx(e,n)&&Qx(e,{key:t,from:Bx(e,t,void 0,n)??null,to:null},n)}function Ux(e,t,n,r){Bx(e,t,n===null?void 0:n,r)}const Wx={past:[],future:[]};function Gx(e){return c.join(c.dirname(e),`config-overrides-history.json`)}function Kx(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function qx(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.key==`string`&&Kx(t.from)&&Kx(t.to)}function Jx(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.past)&&t.past.every(qx)&&Array.isArray(t.future)&&t.future.every(qx)}function Yx(e,t){let n=Gx(e),i;try{i=r.readFileSync(n,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`config-overrides-history read failed (${n}); starting empty`),Wx}try{let e=JSON.parse(i);return Jx(e)?e:(t(`warn`,`config-overrides-history load: unexpected shape, starting empty`),Wx)}catch{return t(`warn`,`config-overrides-history load: corrupt JSON, starting empty`),Wx}}function Xx(e,t,n){Rx(Gx(e),`config-overrides-history`,t,n)}function Zx(e,t,n){let r=[...e,t];return r.length>n?r.slice(r.length-n):r}function Qx(e,t,n){Xx(e,{past:Zx(Yx(e,n).past,t,50),future:[]},n)}function $x(e,t=Ex){let n=Yx(e,t),r=n.past[n.past.length-1];return r===void 0?null:(Ux(e,r.key,r.from,t),Xx(e,{past:n.past.slice(0,-1),future:Zx(n.future,r,50)},t),r)}function eS(e,t=Ex){let n=Yx(e,t),r=n.future[n.future.length-1];return r===void 0?null:(Ux(e,r.key,r.to,t),Xx(e,{past:Zx(n.past,r,50),future:n.future.slice(0,-1)},t),r)}const tS=cx({},`config`);function nS(){return tS.listKeys()}function rS(e,t){return tS.validate(e,t)}function iS(e){return tS.rangeParamsFor(e)}function aS(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:tv(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:[Dg({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Dg({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:tv(e.insertSegmentFrom,n).map(t=>Dg({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:$b(t.get(e.persist),e.min,e.max)}}]:[]}function oS(e){let t=new Map;for(let[n,r]of Object.entries(e.globals))_l(n)&&typeof r==`number`&&t.set(n,r);return t}function sS(e){let t=new Set;for(let n of Object.values(e.actions)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=Jg(e);r?.scope===`preset-root-ops`&&t.add(r.preset)}return[...t].map(e=>({key:qg(e),spec:{kind:`allow-list`,allowed:[]}}))}function cS(e){let t=oS(e),n=new Map([...$_(e),...Qg(e)]);return[...sS(e),...Object.values(e.actions).flatMap(e=>aS(e,t,n))]}function lS(e){return sx(cS(e),`config`)}function uS(e,t){return tS.register(e,t)}var dS=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,pS(e,t,n,`initial value`),this.cell=q.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){pS(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},fS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,q.computed)(()=>{let e=n();return pS(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function pS(e,t,n,r){let i=py(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var mS=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new dS(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new fS(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,q.runInAction)(()=>n.set(t))}runInAction(e){(0,q.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 hS(e,t,n){return e+`\0`+t+`\0`+(n??``)}var gS=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=hS(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=Ev(e.projectDir,e.cwd,e.configFile);e.lastWarning=Dv(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof Ac||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
|
|
110
110
|
`);e.lastWarning=e.lastWarning?e.lastWarning+`
|
|
111
|
-
`+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=Cv(t,sy),i=Mx(Ne(),F),a=wv(Hg(sl(ol({globals:Vg(i.globals,n.presets)},n),i.segmentPalette),i.presetRootOps),t??`<default>`,r),o=new cS,s=new Gy(o,a.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),c,l=[];try{c=Wb(a,s,{cwd:e.cwd});for(let{key:e,spec:t}of bx(a))l.push(px(e,t));for(let{key:e,spec:t}of rS(a))l.push(iS(e,t))}catch(e){for(let e of l)e();throw s.dispose(),e}return{config:a,store:o,registry:s,compiled:c,neededInputPaths:Bv(a),lastRenderCellsBySegment:new Map,validatorDisposers:l}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let n=[...bv(e.projectDir,e.cwd,e.configFile),Ne()],i=new Map;for(let e of n){let t=c.dirname(e);if(!r.existsSync(t))continue;let n=c.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(n)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),o=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(o,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){F(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const dS=16384;var fS=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<dS){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%dS}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: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 pS=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function mS(e){let t=e.rssLimitBytes??pS,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}`),hS(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 hS(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 gS(e,t,n={}){let i=De();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:F,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>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}}const _S={load:()=>({}),save:()=>{},flush:()=>{}};function vS(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var yS=class{sessions;storage;atom=(0,q.createAtom)(`SessionState`);constructor(e=_S,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=vS(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,q.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,q.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,q.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 bS=(e,t)=>D(t);function xS(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 SS=class{timer=null;pending=null;constructor(e,t=500,n=bS){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 xS(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`}};function CS(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function wS(e){return TS(()=>decodeURIComponent(e))}function TS(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function ES(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 DS=(e,t)=>ES(wS(e),t),OS=(e,t)=>{let n=xe({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,wS(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`})`)}},kS=(e,t)=>ES(wS(e),t),AS=(e,t)=>ES(wS(e),t),jS=(e,t)=>{let n=CS(wS(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},MS=(e,t)=>{let[n=``,...r]=TS(()=>A(e)),i=CS(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${fx().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: ${fx().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=mx(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})`)},NS=/^-?\d+$/;function PS(e,t,n){return e>n?t:e<t?n:e}const FS=(e,t)=>{let[n=``,r=``,i=``]=TS(()=>A(e)),a=CS(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!NS.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=hx(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${fx().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&NS.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=PS(l+o,s.min,s.max),d=mx(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)};function IS(e){if(!_l(e))throw Error(`step-config: "${e}" validated as a bounded config-writable key but is not a Globals field — registration/loader invariant broken`)}const LS=(e,t)=>{let[n=``,r=``,i=``]=TS(()=>A(e)),a=CS(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${Zx().join(`, `)})`);let o=Qx(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=Tx(r,o.value);Ix(Ne(),r,s,t.dlog),t.dlog(`info`,`set-config: ${r}=${o.value} (session=${a})`)},RS=(e,t)=>{let[n=``,r=``,i=``]=TS(()=>A(e)),a=CS(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!NS.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=$x(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${Zx().join(`, `)})`);IS(r);let c=jx(Ne(),t.dlog)[r],l=typeof c==`number`?Math.max(s.min,Math.min(s.max,c)):s.seed,u=PS(l+o,s.min,s.max),d=Qx(r,String(u));if(!d.ok)throw new $(`step-config: ${d.reason}`);let f=Tx(r,d.value);Ix(Ne(),r,f,t.dlog),t.dlog(`info`,`step-config: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},zS=(e,t)=>{let[n=``,r=``]=TS(()=>A(e)),i=CS(n);if(!r||!Zx().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${Zx().join(`, `)})`);Lx(Ne(),r,t.dlog),t.dlog(`info`,`reset-config: ${r} (session=${i})`)},BS=(e,t)=>{let[n=``,r=``,i=``]=TS(()=>A(e)),a=CS(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${Zx().join(`, `)})`);let o=Qx(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Z_(r);if(s===null||s.scope!==`preset-root-ops`)throw new $(`apply-layout-op: "${r}" is not a "presets.<name>.rootOps" target`);let c=Mx(Ne(),t.dlog).presetRootOps[s.preset]??[],l=JSON.stringify([...c,o.value]);Ix(Ne(),r,l,t.dlog),t.dlog(`info`,`apply-layout-op: ${r} += ${o.value} (session=${a})`)},VS=(e,t)=>{let[n=``]=TS(()=>A(e)),r=CS(n),i=Jx(Ne(),t.dlog);if(i===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i.key} (session=${r})`)},HS=(e,t)=>{let[n=``]=TS(()=>A(e)),r=CS(n),i=Yx(Ne(),t.dlog);if(i===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i.key} (session=${r})`)},US=`config-override`,WS=new Map([[Tt,DS],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=CS(TS(()=>decodeURIComponent(e.slice(0,n)))),i=TS(()=>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,US),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,US,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Et,OS],[Ct,MS],[wt,FS],[kt,LS],[At,RS],[jt,zS],[Mt,BS],[Nt,VS],[Pt,HS],[Dt,kS],[Ot,AS],[`toolbar-toggle`,jS]]),GS=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of j(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=A(o);e.length>0&&e[0]&&(i=e[0])}let e=WS.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(`
|
|
112
|
-
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},KS=new Map([...WS,[St,GS]]);Object.freeze([...KS.keys()]);const qS=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`]),JS=[[`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 YS(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of JS){let i=XS(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))qS.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function XS(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 ZS(e,t){switch(e){case`vars`:return{what:e,vars:QS(t)};case`segments`:return{what:e,segments:nC(t)};case`config`:return{what:e,config:aC(t)}}}function QS(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=eC(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:$S(r.lastUpdatedMs())})}return o}function $S(e){return e===null?null:Math.max(0,Date.now()-e)}function eC(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,tC(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}`,tC(i));return t}function tC(e){return e.kind}function nC(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=rC(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:iC(t.template,i),lastRender:r.get(e)??null})}return o}function rC(e){let t=[],n=new Set;for(let r of Zr(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 iC(e,t){let n=new Set;for(let r of tv(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 aC(e){return e===null?null:e.config}const oC=[`vars`,`segments`,`config`];function sC(e){return typeof e==`string`&&oC.includes(e)}function cC(e){return Math.max(1,e-2)}var lC=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await Nr(e);if(n.length===0)return D(`No entries in transcript`),L;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),I({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),L}catch(e){return Bn(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return I(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function uC(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 dC=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(uC(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 Lr(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||(uC(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(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return L;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Bn(`metrics (${e}): ${n.reason}`):I({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 fC=new Map;function pC(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var mC=class{async getSessionId(){if(!process.env.TMUX_PANE)return L;let e=pC(process.env.TMUX),t=fC.get(e);if(t!==void 0)return t;D(`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()?I(n.stdout.trim()):L:Bn(`tmux display-message: ${n.reason}`);return fC.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function hC(e){return e<32||e===127||e>=128&&e<=159}function gC(e,t){let n=``;for(let t of e)n+=hC(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const _C=`\x1B[38;2;255;255;255m`,vC=`\x1B[48;2;200;40;40m`,yC=`\x1B[0m`,bC=new fS;ye(bC.launchStats);const xC=new ur({counters:bC,logger:F}),SC=new _r({watchers:xC,logger:F}),CC=new Yr,wC=new yS,TC=new lC,EC=new dC,DC=new mC,OC=new uS({gitService:SC,sessionState:wC,watchers:xC});let kC=null,AC=null;function jC(){t.on(`uncaughtException`,e=>{F(`error`,`uncaughtException: ${e.stack||e.message}`),HC(1)}),t.on(`unhandledRejection`,e=>{F(`error`,`unhandledRejection: ${String(e)}`),HC(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{F(`info`,`received ${e}, shutting down`),HC(0)});kC=Cn(t.pid);let e=Mn(Pn(kC));if(!e.decision.allow){F(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),HC(1);return}AC=e.registryPath,r.mkdirSync(De(),{recursive:!0}),Ae(Oe()),wC.useStorage(new SS(Me(),500,F)),Tn({anchor:P(t.env),isAlive:En,onOrphaned:e=>{F(`info`,`parent watchdog: ${e}; shutting down`),HC(0)}}),MC(g.createServer({allowHalfOpen:!1},e=>{UC(e)}),Oe(),!1)}function MC(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){F(`error`,`server error: ${i.message}`),HC(1);return}if(r){F(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}NC(e,n)}),e.listen(n,()=>PC(n))}function NC(e,n){let i=mn(hn(k(n)),(e,t)=>Sn(e,t,{readStartTime:xn,pidAlive:En}));if(i.kind===`attach-and-exit`){F(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}F(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){F(`error`,`cannot unlink stale socket ${n}: ${e.message}`),HC(1);return}}MC(e,n,!0)}function PC(e){let n=_n(e);if(n.kind!==`present`){F(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),HC(0);return}zC(e);try{r.chmodSync(e,384)}catch(e){F(`warn`,`chmod socket failed: ${e.message}`)}F(`info`,`daemon up: pid=${t.pid} v=3 sock=${e}`),dt(),IC(),RC(),FC(e,n.identity)}function FC(e,n){bn({bound:n,myPid:t.pid,readIdentity:()=>_n(e),readLease:()=>hn(k(e)),shutdown:e=>HC(e),log:F}).arm()}function IC(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(y(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){F(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),HC(0);return}}catch(e){F(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let LC=null;function RC(){LC=mS(gS(bC.startedAt.getTime(),e=>HC(e))),LC.arm()}function zC(e){let n=gn(k(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:kC});n!==null&&F(`warn`,`lease write failed: ${n}`)}let BC=0,VC=!1;function HC(e){if(!VC){VC=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{SC.close()}catch(e){F(`warn`,`gitService close failed: ${e.message}`)}try{CC.close()}catch(e){F(`warn`,`usageStore close failed: ${e.message}`)}try{xC.closeAll()}catch(e){F(`warn`,`watcherRegistry close failed: ${e.message}`)}try{wC.flush()}catch(e){F(`warn`,`sessionState flush failed: ${e.message}`)}N(je(),t.pid),AC!==null&&Nn(AC,t.pid,An,e=>r.unlinkSync(e)),zn(),t.exit(e)}}function UC(e){BC++,bC.inFlight=BC;let t=!1,n=(n,r)=>{if(t){r!==null&&F(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>HC(r);try{e.end(He(n),i)}catch(e){F(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{bC.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Ue(e=>{GC(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{F(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{F(`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=>{F(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),BC=Math.max(0,BC-1),bC.inFlight=BC})}const WC=e=>({resp:e,exitAfterFlush:null});async function GC(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return WC({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?F(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):F(`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 WC({ok:!0,stats:bC.snapshot({gitCache:SC.getStats(),usageCache:CC.getStats(),renderCacheSize:OC.size,watchersActive:xC.size(),nextRestartReason:LC?.describeNextRestart()??null})});if(e.kind===`render`){bC.requestsTotal++;let t=Date.now();try{let{report:n}=YS(e.hookData);for(let e of n.unknownTopLevelFields)F(`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 bC.requestsErrored++,F(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),WC({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=JC(e.args),s=e.hookData.session_id,c=wC.get(s,`config-override`)??a,l=OC.getOrCreate(i,e.cwd,c),u=Be(e.termCols),d=cC(u??120),f={...QC,width:d},p=``;if(l.state!==null){let t=Lg(wC.get(e.hookData.session_id,`preset`),l.state.config.globals.preset,l.state.config.presets),n=Bg(l.state.config,t),r={preset:t,theme:yc(wC.get(e.hookData.session_id,`theme`),n.palette),look:Cc(wC.get(e.hookData.session_id,`look`),n.look,l.state.config.looks),style:Dc(wC.get(e.hookData.session_id,`style`),n.style),autoWrap:n.autoWrap??!0,padding:n.padding??1,charset:n.charset??`unicode`,colorCompatibility:n.colorCompatibility??`truecolor`},i=await Wv(e.hookData,nw,e.cwd,l.state.neededInputPaths,r),a=$y(r.theme);f.style=r.style,f.wrap=r.autoWrap,f.padding=r.padding,f.charset=r.charset,f.colorCompatibility=r.colorCompatibility,p=Kb(l.state.config,l.state.compiled,l.state.store,l.state.registry,i,a,f,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:wc(l.state.config.looks,r.look),preset:r.preset})}let m=wC.get(e.hookData.session_id,`click.error`);m&&wC.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
|
|
113
|
-
`)||null,g=
|
|
114
|
-
`})}catch(e){throw
|
|
115
|
-
`)}function
|
|
116
|
-
`);return e?`${i}\n${e}`:i}const
|
|
117
|
-
`);return}t.stdout.write(
|
|
111
|
+
`+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=Ov(t,fy),i=Lx(Ne(),F),a=sl(ol({globals:Vg(i.globals,n.presets)},n),i.segmentPalette),o=Hg(i.presetRootOps,n.presets),s=kv(Wg(a,o),t??`<default>`,r),c=new mS,l=new Xy(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=Yb(s,l,{cwd:e.cwd});for(let{key:e,spec:t}of Tx(s))d.push(vx(e,t));for(let{key:e,spec:t}of lS(s))d.push(uS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:Gv(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,presetRootOps:o}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let n=[...Tv(e.projectDir,e.cwd,e.configFile),Ne()],i=new Map;for(let e of n){let t=c.dirname(e);if(!r.existsSync(t))continue;let n=c.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(n)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),o=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(o,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){F(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const _S=16384;var vS=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<_S){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%_S}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: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 yS=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function bS(e){let t=e.rssLimitBytes??yS,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}`),xS(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 xS(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 SS(e,t,n={}){let i=De();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:F,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>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}}const CS={load:()=>({}),save:()=>{},flush:()=>{}};function wS(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var TS=class{sessions;storage;atom=(0,q.createAtom)(`SessionState`);constructor(e=CS,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=wS(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,q.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,q.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,q.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 ES=(e,t)=>D(t);function DS(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 OS=class{timer=null;pending=null;constructor(e,t=500,n=ES){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 DS(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`}};function kS(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function AS(e){return jS(()=>decodeURIComponent(e))}function jS(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function MS(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 NS=(e,t)=>MS(AS(e),t),PS=(e,t)=>{let n=xe({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,AS(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`})`)}},FS=(e,t)=>MS(AS(e),t),IS=(e,t)=>MS(AS(e),t),LS=(e,t)=>{let n=kS(AS(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},RS=(e,t)=>{let[n=``,...r]=jS(()=>A(e)),i=kS(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${_x().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: ${_x().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=yx(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})`)},zS=/^-?\d+$/;function BS(e,t,n){return e>n?t:e<t?n:e}const VS=(e,t)=>{let[n=``,r=``,i=``]=jS(()=>A(e)),a=kS(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!zS.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=bx(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${_x().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&zS.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=BS(l+o,s.min,s.max),d=yx(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)};function HS(e){if(!_l(e))throw Error(`step-config: "${e}" validated as a bounded config-writable key but is not a Globals field — registration/loader invariant broken`)}const US=(e,t)=>{let[n=``,r=``,i=``]=jS(()=>A(e)),a=kS(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${nS().join(`, `)})`);let o=rS(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=Ax(r,o.value);Vx(Ne(),r,s,t.dlog),t.dlog(`info`,`set-config: ${r}=${o.value} (session=${a})`)},WS=(e,t)=>{let[n=``,r=``,i=``]=jS(()=>A(e)),a=kS(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!zS.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=iS(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${nS().join(`, `)})`);HS(r);let c=Ix(Ne(),t.dlog)[r],l=typeof c==`number`?Math.max(s.min,Math.min(s.max,c)):s.seed,u=BS(l+o,s.min,s.max),d=rS(r,String(u));if(!d.ok)throw new $(`step-config: ${d.reason}`);let f=Ax(r,d.value);Vx(Ne(),r,f,t.dlog),t.dlog(`info`,`step-config: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},GS=(e,t)=>{let[n=``,r=``]=jS(()=>A(e)),i=kS(n);if(!r||!nS().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${nS().join(`, `)})`);Hx(Ne(),r,t.dlog),t.dlog(`info`,`reset-config: ${r} (session=${i})`)},KS=(e,t)=>{let[n=``,r=``,i=``]=jS(()=>A(e)),a=kS(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${nS().join(`, `)})`);let o=rS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Jg(r);if(s===null||s.scope!==`preset-root-ops`)throw new $(`apply-layout-op: "${r}" is not a "presets.<name>.rootOps" target`);let c=Lx(Ne(),t.dlog).presetRootOps[s.preset]??[],l=JSON.stringify([...c,o.value]);Vx(Ne(),r,l,t.dlog),t.dlog(`info`,`apply-layout-op: ${r} += ${o.value} (session=${a})`)},qS=(e,t)=>{let[n=``]=jS(()=>A(e)),r=kS(n),i=$x(Ne(),t.dlog);if(i===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i.key} (session=${r})`)},JS=(e,t)=>{let[n=``]=jS(()=>A(e)),r=kS(n),i=eS(Ne(),t.dlog);if(i===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i.key} (session=${r})`)},YS=`config-override`,XS=new Map([[Tt,NS],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=kS(jS(()=>decodeURIComponent(e.slice(0,n)))),i=jS(()=>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,YS),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,YS,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Et,PS],[Ct,RS],[wt,VS],[kt,US],[At,WS],[jt,GS],[Mt,KS],[Nt,qS],[Pt,JS],[Dt,FS],[Ot,IS],[`toolbar-toggle`,LS]]),ZS=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of j(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=A(o);e.length>0&&e[0]&&(i=e[0])}let e=XS.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(`
|
|
112
|
+
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},QS=new Map([...XS,[St,ZS]]);Object.freeze([...QS.keys()]);const $S=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`]),eC=[[`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 tC(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of eC){let i=nC(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))$S.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function nC(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 rC(e,t){switch(e){case`vars`:return{what:e,vars:iC(t)};case`segments`:return{what:e,segments:cC(t)};case`config`:return{what:e,config:dC(t)}}}function iC(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=oC(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:aC(r.lastUpdatedMs())})}return o}function aC(e){return e===null?null:Math.max(0,Date.now()-e)}function oC(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,sC(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}`,sC(i));return t}function sC(e){return e.kind}function cC(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=lC(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:uC(t.template,i),lastRender:r.get(e)??null})}return o}function lC(e){let t=[],n=new Set;for(let r of Zr(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 uC(e,t){let n=new Set;for(let r of av(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 dC(e){return e===null?null:e.config}const fC=[`vars`,`segments`,`config`];function pC(e){return typeof e==`string`&&fC.includes(e)}function mC(e){return Math.max(1,e-2)}var hC=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await Nr(e);if(n.length===0)return D(`No entries in transcript`),L;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),I({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),L}catch(e){return Bn(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return I(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function gC(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 _C=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(gC(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 Lr(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||(gC(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(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return L;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Bn(`metrics (${e}): ${n.reason}`):I({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 vC=new Map;function yC(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var bC=class{async getSessionId(){if(!process.env.TMUX_PANE)return L;let e=yC(process.env.TMUX),t=vC.get(e);if(t!==void 0)return t;D(`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()?I(n.stdout.trim()):L:Bn(`tmux display-message: ${n.reason}`);return vC.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function xC(e){return e<32||e===127||e>=128&&e<=159}function SC(e,t){let n=``;for(let t of e)n+=xC(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const CC=`\x1B[38;2;255;255;255m`,wC=`\x1B[48;2;200;40;40m`,TC=`\x1B[0m`,EC=new vS;ye(EC.launchStats);const DC=new ur({counters:EC,logger:F}),OC=new _r({watchers:DC,logger:F}),kC=new Yr,AC=new TS,jC=new hC,MC=new _C,NC=new bC,PC=new gS({gitService:OC,sessionState:AC,watchers:DC});let FC=null,IC=null;function LC(){t.on(`uncaughtException`,e=>{F(`error`,`uncaughtException: ${e.stack||e.message}`),JC(1)}),t.on(`unhandledRejection`,e=>{F(`error`,`unhandledRejection: ${String(e)}`),JC(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{F(`info`,`received ${e}, shutting down`),JC(0)});FC=Cn(t.pid);let e=Mn(Pn(FC));if(!e.decision.allow){F(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),JC(1);return}IC=e.registryPath,r.mkdirSync(De(),{recursive:!0}),Ae(Oe()),AC.useStorage(new OS(Me(),500,F)),Tn({anchor:P(t.env),isAlive:En,onOrphaned:e=>{F(`info`,`parent watchdog: ${e}; shutting down`),JC(0)}}),RC(g.createServer({allowHalfOpen:!1},e=>{YC(e)}),Oe(),!1)}function RC(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){F(`error`,`server error: ${i.message}`),JC(1);return}if(r){F(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}zC(e,n)}),e.listen(n,()=>BC(n))}function zC(e,n){let i=mn(hn(k(n)),(e,t)=>Sn(e,t,{readStartTime:xn,pidAlive:En}));if(i.kind===`attach-and-exit`){F(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}F(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){F(`error`,`cannot unlink stale socket ${n}: ${e.message}`),JC(1);return}}RC(e,n,!0)}function BC(e){let n=_n(e);if(n.kind!==`present`){F(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),JC(0);return}GC(e);try{r.chmodSync(e,384)}catch(e){F(`warn`,`chmod socket failed: ${e.message}`)}F(`info`,`daemon up: pid=${t.pid} v=3 sock=${e}`),dt(),HC(),WC(),VC(e,n.identity)}function VC(e,n){bn({bound:n,myPid:t.pid,readIdentity:()=>_n(e),readLease:()=>hn(k(e)),shutdown:e=>JC(e),log:F}).arm()}function HC(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(y(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){F(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),JC(0);return}}catch(e){F(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let UC=null;function WC(){UC=bS(SS(EC.startedAt.getTime(),e=>JC(e))),UC.arm()}function GC(e){let n=gn(k(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:FC});n!==null&&F(`warn`,`lease write failed: ${n}`)}let KC=0,qC=!1;function JC(e){if(!qC){qC=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{OC.close()}catch(e){F(`warn`,`gitService close failed: ${e.message}`)}try{kC.close()}catch(e){F(`warn`,`usageStore close failed: ${e.message}`)}try{DC.closeAll()}catch(e){F(`warn`,`watcherRegistry close failed: ${e.message}`)}try{AC.flush()}catch(e){F(`warn`,`sessionState flush failed: ${e.message}`)}N(je(),t.pid),IC!==null&&Nn(IC,t.pid,An,e=>r.unlinkSync(e)),zn(),t.exit(e)}}function YC(e){KC++,EC.inFlight=KC;let t=!1,n=(n,r)=>{if(t){r!==null&&F(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>JC(r);try{e.end(He(n),i)}catch(e){F(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{EC.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Ue(e=>{ZC(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{F(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{F(`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=>{F(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),KC=Math.max(0,KC-1),EC.inFlight=KC})}const XC=e=>({resp:e,exitAfterFlush:null});async function ZC(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return XC({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?F(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):F(`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 XC({ok:!0,stats:EC.snapshot({gitCache:OC.getStats(),usageCache:kC.getStats(),renderCacheSize:PC.size,watchersActive:DC.size(),nextRestartReason:UC?.describeNextRestart()??null})});if(e.kind===`render`){EC.requestsTotal++;let t=Date.now();try{let{report:n}=tC(e.hookData);for(let e of n.unknownTopLevelFields)F(`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 EC.requestsErrored++,F(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),XC({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=ew(e.args),s=e.hookData.session_id,c=AC.get(s,`config-override`)??a,l=PC.getOrCreate(i,e.cwd,c),u=Be(e.termCols),d=mC(u??120),f={...iw,width:d},p=``;if(l.state!==null){let t=Lg(AC.get(e.hookData.session_id,`preset`),l.state.config.globals.preset,l.state.config.presets),n=Bg(l.state.config,t),r={preset:t,presetCustomized:Ug(l.state.presetRootOps,t),theme:yc(AC.get(e.hookData.session_id,`theme`),n.palette),look:Cc(AC.get(e.hookData.session_id,`look`),n.look,l.state.config.looks),style:Dc(AC.get(e.hookData.session_id,`style`),n.style),autoWrap:n.autoWrap??!0,padding:n.padding??1,charset:n.charset??`unicode`,colorCompatibility:n.colorCompatibility??`truecolor`},i=await Yv(e.hookData,cw,e.cwd,l.state.neededInputPaths,r),a=ib(r.theme);f.style=r.style,f.wrap=r.autoWrap,f.padding=r.padding,f.charset=r.charset,f.colorCompatibility=r.colorCompatibility,p=Zb(l.state.config,l.state.compiled,l.state.store,l.state.registry,i,a,f,{perSegmentSink:l.state.lastRenderCellsBySegment},{look:wc(l.state.config.looks,r.look),preset:r.preset})}let m=AC.get(e.hookData.session_id,`click.error`);m&&AC.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
|
|
113
|
+
`)||null,g=nw(p,h,l.lastWarning),_=Date.now()-t,v=OC.getStats(),y=kC.getStats();return F(`info`,`render sid=${e.hookData.session_id??`?`} took=${_}ms termCols=${u??`?`} width=${d} git=${v.size}/${v.hits}h/${v.misses}m usage=${y.size}/${y.hits}h/${y.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),XC({ok:!0,output:g+`
|
|
114
|
+
`})}catch(e){throw EC.requestsErrored++,e}}if(e.kind===`click`)return XC(await lw(e.verb,e.value));if(e.kind===`debug`){if(!pC(e.what))return XC({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${fC.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=PC.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?sw(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):ow};return XC({ok:!0,debug:rC(e.what,n)})}return XC({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const QC=`\x1B]8;;`,$C=`\x1B]8;;\x1B\\`;function ew(e){let{values:t,tokens:n}=b({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:wv(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function tw(e,t,n,r){let i=It([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>SC(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${QC}${i}\\${n}${r} ⚠ ${a[0]} ${TC}${$C}`,...a.slice(1).map(e=>`${QC}${i}\\${n}${r} ${e} ${TC}${$C}`)].join(`
|
|
115
|
+
`)}function nw(e,t,n){let r=[];if(t&&r.push(tw(Dt,t,wC,CC)),n&&r.push(tw(Ot,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
|
|
116
|
+
`);return e?`${i}\n${e}`:i}const rw={sessionState:AC,dlog:F},iw={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},aw={...iw,width:1/0},ow=new Map;function sw(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,tb(a,{...aw,charset:t,colorCompatibility:n}));return r}const cw={gitProvider:OC,usageStore:kC,contextProvider:jC,metricsProvider:MC,tmuxService:NC,log:F,clock:()=>new Date};function lw(e,t){let n=QS.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,rw),{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 uw={connectMs:200,budgetMs:500};async function dw(e){let n=e.includes(`--json`),r=await fw();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Ze(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
117
|
+
`);return}t.stdout.write(gw(r.value))}function fw(){return Ge({kind:`stats`},uw,e=>`stats`in e?e.stats:void 0)}function pw(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function mw(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function hw(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 gw(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(` startedAt ${e.startedAt}`),t.push(` uptime ${hw(e.uptimeSec)}`),t.push(` rss ${pw(e.rssBytes)}`),t.push(` heapUsed ${pw(e.heapUsedBytes)}`),t.push(` heapTotal ${pw(e.heapTotalBytes)}`),t.push(` external ${pw(e.externalBytes)}`),t.push(` arrayBuffers ${pw(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 ${mw(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 ${mw(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(`
|
|
118
118
|
`)+`
|
|
119
|
-
`}const
|
|
120
|
-
`);return}t.stdout.write(
|
|
121
|
-
`;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?``:` ${
|
|
119
|
+
`}const _w={connectMs:200,budgetMs:500};async function vw(e,n){let r=n.includes(`--json`),i=await yw(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Ze(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
120
|
+
`);return}t.stdout.write(bw(i.value))}function yw(e){return Ge({kind:`debug`,what:e},_w,e=>`debug`in e?e.debug:void 0)}function bw(e){switch(e.what){case`vars`:return xw(e.vars);case`segments`:return Sw(e.segments);case`config`:return Cw(e.config);default:return e}}function xw(e){if(e.length===0)return`no variables (DSL not active)
|
|
121
|
+
`;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?``:` ${Tw(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${ww(i.value)}${e}${a}`)}return t.join(`
|
|
122
122
|
`)+`
|
|
123
|
-
`}function
|
|
123
|
+
`}function Sw(e){if(e.length===0)return`no segments (DSL not active)
|
|
124
124
|
`;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(`
|
|
125
125
|
`)+`
|
|
126
|
-
`}function
|
|
126
|
+
`}function Cw(e){return e===null?`config: DSL not active
|
|
127
127
|
`:JSON.stringify(e,null,2)+`
|
|
128
|
-
`}function
|
|
129
|
-
`));return u}finally{s.dispose()}}function
|
|
128
|
+
`}function ww(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Tw(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Ew(){let e=Ow();return e===null?null:r.readFileSync(e,`utf-8`)}function Dw(){let e;try{e=Ew()}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 Ow(){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 kw(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`},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 Aw(e,n=t.cwd()){let i=e===void 0?Ev(n,n):c.resolve(wv(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=Dv(n,n);o!==null&&a.push(o);try{return{kind:`clean`,configPath:i,warnings:a,rendered:jw(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 Ac||e instanceof Error?e.message:String(e),warnings:a}}}function jw(e,t,n){let{config:r,source:i}=Ov(e,fy),a=kv(r,e??`<default>`,i),o=new mS,s=new Xy(o,a.globals.default_empty_value??``,void 0,new TS);try{let e=Yb(a,s,{cwd:t});n.push(...e.loadWarnings),Tx(a);let r=Lg(null,a.globals.preset,a.presets),i=Bg(a,r),c={preset:r,presetCustomized:!1,theme:yc(null,i.palette),look:Cc(null,i.look,a.looks),style:Dc(null,i.style),autoWrap:i.autoWrap??!0,padding:i.padding??1,charset:i.charset??`unicode`,colorCompatibility:i.colorCompatibility??`truecolor`},l=t=>{let n=new Map;return{rendered:Zb(a,e,o,s,kw(t),ib(t.theme),{style:t.style,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:wc(a.looks,t.look),preset:t.preset}),segmentErrors:n}},u=l(c),d=l({...c,presetCustomized:!0}),f=[...[...u.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...d.segmentErrors].filter(([e])=>!u.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(f.length>0)throw Error(`config renders with ${f.length} segment error${f.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+f.map(e=>` ${e}`).join(`
|
|
129
|
+
`));return u.rendered}finally{s.dispose()}}function Mw(e){return e.map(e=>`warning: ${e}\n`).join(``)}function Nw(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:Mw(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:Mw(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 Pw(e){(e.length>1||e[0]===``)&&(t.stderr.write(`check: expected at most one non-empty path
|
|
130
130
|
Usage: cc-candybar check [config-file]
|
|
131
|
-
`),t.exit(2));let n=
|
|
132
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:
|
|
131
|
+
`),t.exit(2));let n=Nw(Aw(e[0]));t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}const Fw=`${wC}${CC}`;function Iw(e){return`${Fw}⚠ cc-candybar: ${Lw(e)}${TC}\n`}function Lw(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: ${SC(e.message,60)}`;case`render_failed`:return`render failed: ${SC(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${SC(e.message,60)}`}}function Rw(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
132
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:Iw(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function zw(){let e=t.env.COLUMNS;if(e){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}let n=t.stderr.columns;if(n&&n>0)return n}function Bw(){console.log(`
|
|
133
133
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
134
134
|
|
|
135
135
|
Usage: cc-candybar [options]
|
|
@@ -179,7 +179,7 @@ Config tooling:
|
|
|
179
179
|
config [--json] The effective merged config. (All three query the
|
|
180
180
|
running daemon; none spawn one.)
|
|
181
181
|
|
|
182
|
-
`)}async function
|
|
182
|
+
`)}async function Vw(){try{(t.argv.includes(`--help`)||t.argv.includes(`-h`))&&(Bw(),t.exit(0));let e=t.argv[2];if(e===`install`&&(fn(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(sn(),t.exit(0)),e===`url-handle`){await ln(t.argv[3]);return}if(e===`daemon`){LC();return}if(e===`daemon-stats`&&(await dw(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){Pw(t.argv.slice(3));return}if(e===`schema`){Dw();return}pC(e)&&(await vw(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
183
183
|
|
|
184
184
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
185
185
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -195,4 +195,4 @@ Add to ~/.claude/settings.json:
|
|
|
195
195
|
Run with --help for more options.
|
|
196
196
|
|
|
197
197
|
To test output manually:
|
|
198
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
198
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),Bw(),t.exit(1));let i=Rw(await tt(r,t.argv,t.cwd(),zw()));i.debug!==null&&D(i.debug),i.kick&&rt(),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)}}Vw();export{};
|