@promptctl/cc-candybar 1.66.0 → 1.67.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 +22 -22
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -122,7 +122,7 @@ Config tooling:
|
|
|
122
122
|
Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Mc(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Lg(e,t.actions)),t.looks!==void 0&&(r.looks=T_(e,t.looks)),t.presets!==void 0&&(r.presets=D_(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=wo(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=O_(e,t.helpers)),Bc(e,r),Um(e,r),Zm(e,r),bs(e,r,gs,`the global settings menu`),r}const Tv=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function Ev(e){let t=Av(e.termCols),n=Av(e.termRows),r=jv(e.ssh),i=Ov(e.tmux),a=Dv(e.configEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a}}}function Dv(e){return typeof e==`string`&&e!==``?cv(e):void 0}function Ov(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const kv=1e4;function Av(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>kv?kv:t}function jv(e){return typeof e==`boolean`?e:void 0}var Mv=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Nv(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Pv(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 Mv(`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 Mv(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Fv(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=Pv(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(Nv(t))})}async function Iv(e,t,n){let r=null;try{r=await Vv(Pe(),t.connectMs);let i=await Fv(r,{v:3,...e},t.budgetMs);return zv(e.kind,i,n)}catch(e){return Bv(e)}finally{r&&r.destroy()}}function Lv(e,t){return typeof e==`string`?e:t}function Rv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function zv(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=Lv(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Rv(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 Bv(e){if(e instanceof Mv||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 Vv(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 Hv(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 Uv={connectMs:50,budgetMs:150},Wv={connectMs:50,budgetMs:200};function Gv(e){let t=e.output;return typeof t==`string`?t:void 0}function Kv(e,t,n,r){return Iv({kind:`render`,hookData:e,args:t,cwd:n,...r},Uv,Gv)}function qv(e,t){return Iv({kind:`click`,verb:e,value:t},Wv,Gv)}let Jv=null;function Yv(e){if(Jv!==null)return Jv;r.mkdirSync(c.dirname(e),{recursive:!0});try{Jv=r.statSync(e).size}catch{Jv=0}return Jv}function Xv(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}Jv=0}function Y(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ke(),t=Yv(e);r.appendFileSync(e,n),Jv=t+Buffer.byteLength(n,`utf8`),Jv>=5242880&&Xv(e)}catch(e){Jv=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function Zv(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
123
123
|
`)}function Qv(e,t){return e===`darwin`?[$v(`footprint`,[`-p`,String(t)]),$v(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[ey(`/proc/self/smaps_rollup`),ey(`/proc/self/status`)]:[]}function $v(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=De({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${ty(n.stderr)}`}}}}function ey(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function ty(e){let t=e.split(`
|
|
124
124
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const ny=`CC_CANDYBAR_RSS_LIMIT_MB`;function ry(e){let t=e[ny];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ny} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function iy(e){return ry(e)*2}const ay=1024*1024;function oy(e){return ry(e)*ay}const sy={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function cy(e,t,n){let{prefix:r,suffix:i}=sy[t];return c.join(e,`${r}${n}${i}`)}function ly(e){for(let t of Object.keys(sy)){let{prefix:n,suffix:r}=sy[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function uy(e){let t=e.rssLimitBytes??512*ay,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return dy(e.log,`memory report`,()=>{let t=cy(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),dy(e.log,`heap snapshot`,()=>{let t=cy(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),dy(e.log,`artifact rotation`,()=>{py(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function dy(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function fy(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=ly(t);if(n===null)return t;let{prefix:r,suffix:i}=sy[n];return t.slice(r.length,t.length-i.length)}function py(e,t,n){let r=new Map;for(let t of e){let e=fy(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function my(e,t,n={}){let i=Ne();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Y,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>Zv(Qv(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>ly(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function hy(e={}){if(jy()!==null)return;let n=e.spawn??My,r=Oy();if(r.kind===`contended`){let e=_y();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),gy(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),gy(n);return}try{gy(n)}finally{Ay()}}function gy(e){wy()&&vy(e)}function _y(){try{let e=r.statSync(He());return Date.now()-e.mtimeMs}catch{return null}}function vy(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
125
|
-
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function yy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function by(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function xy(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 Sy(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 Cy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function wy(){let e=Ue(),n=We(),r=xy(n),i=yy(Ty(e),by(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`),Ey(e),Sy(n,Math.min(r+1,5)),!0)}function Ty(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ey(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 Dy=null;function Oy(){let e=He();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 Dy={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(!ky(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 ky(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ay(){if(!Dy)return;let{fd:e,path:t}=Dy;Dy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function jy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function My(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${iy(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Ny=`cc-candybar`,Py=`dispatch`,Fy=`set-state`,Iy=`step-state`,Ly=`copy`,Ry=`open-vscode`,zy=`toolbar-toggle`,By=`show-config-error`,Vy=`show-config-warning`,Hy=`set-config`,Uy=`step-config`,Wy=`reset-config`,Gy=`apply-layout-op`,Ky=`undo`,qy=`redo`,Jy=`apply-update`,Yy=`doctor-run`,Xy=`doctor-fix`;function Zy(e){return e.map(encodeURIComponent).join(`/`)}function Qy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function $y(e){return`${Ny}://${Py}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Zy(e.args)}`)}`).join(`&`)}`}function eb(e){return new y(e).getAll(`e`).map(tb)}function tb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const nb=`1.
|
|
125
|
+
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function yy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function by(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function xy(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 Sy(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 Cy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function wy(){let e=Ue(),n=We(),r=xy(n),i=yy(Ty(e),by(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`),Ey(e),Sy(n,Math.min(r+1,5)),!0)}function Ty(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ey(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 Dy=null;function Oy(){let e=He();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 Dy={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(!ky(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 ky(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ay(){if(!Dy)return;let{fd:e,path:t}=Dy;Dy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function jy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function My(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${iy(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Ny=`cc-candybar`,Py=`dispatch`,Fy=`set-state`,Iy=`step-state`,Ly=`copy`,Ry=`open-vscode`,zy=`toolbar-toggle`,By=`show-config-error`,Vy=`show-config-warning`,Hy=`set-config`,Uy=`step-config`,Wy=`reset-config`,Gy=`apply-layout-op`,Ky=`undo`,qy=`redo`,Jy=`apply-update`,Yy=`doctor-run`,Xy=`doctor-fix`;function Zy(e){return e.map(encodeURIComponent).join(`/`)}function Qy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function $y(e){return`${Ny}://${Py}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Zy(e.args)}`)}`).join(`&`)}`}function eb(e){return new y(e).getAll(`e`).map(tb)}function tb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const nb=`1.67.0`;function rb(){return c.join(f.homedir(),`.claude`,`settings.json`)}function X(e){return{kind:`ok`,value:e}}const Z={kind:`absent`};function Q(e){return{kind:`failed`,reason:e}}function ib(e,t){return e?.kind===`ok`?e.value:t}const ab=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function ob(e){let t=ab.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function sb(e){return e.join(`.`)}function cb([e,t,n],[r,i,a]){return e-r||t-i||n-a}const lb=`@promptctl/cc-candybar`;async function ub(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return Q(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?ob(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function db(e,t){let n=ob(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=cb(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function fb(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${sb(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${sb(t.installed)} is newer than the registry's latest release (${sb(t.latest)}): an unpublished build.\n`};case`stale`:{let n=sb(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${sb(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const pb=`CCCandybarURLHandler`,mb=[],hb={"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 gb(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function _b(e,t){return[e,...t].map(gb).join(` `)}function vb(){return c.join(f.homedir(),`Applications`,`${pb}.app`)}function yb(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function bb(){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 xb(){return c.join(bb(),`bin`,`cc-candybar`)}function Sb(){return c.join(bb(),`dist`,`index.mjs`)}function Cb(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(`
|
|
126
126
|
`)}function wb(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 Tb(t){let n=hb[`${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 Eb(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function Db(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 ${lb}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function Ob(){let e=wb(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=Tb(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Sb()),{recursive:!0}),r.mkdirSync(c.dirname(xb()),{recursive:!0}),Eb(e,Sb()),Eb(t.sourcePath,xb()),r.chmodSync(xb(),493),r.rmSync(c.join(bb(),`url-handler.mjs`),{force:!0});let n=Db(xb());return process.stdout.write(`Staged cc-candybar v${nb} runtime at ${bb()}\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:xb(),distPath:Sb(),entryKind:n}}function kb(){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>${Ny}</string>`,` </array>`,` </dict>`,`</array>`].join(`
|
|
127
127
|
`)}]}function Ab(e){let t=vb();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=De({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,Cb(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 kb())De({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of kb()){let n=De({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 ${Ny}:// with Launch Services\n`);let a=De({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(`✓ ${pb}.app installed and registered.\n`),process.stdout.write(` Test: open '${Ny}://hello-world' && pbpaste\n`)}function jb(){yb(),Ab(Ob().distPath)}function Mb(e,t=Ny){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:Ly,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Nb(e){e||(process.stderr.write(`url-handle: missing URL argument.
|
|
128
128
|
`),process.exit(1));let t;try{t=Mb(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await qv(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(hy(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Pb(n)+`
|
|
@@ -135,7 +135,7 @@ Config tooling:
|
|
|
135
135
|
`)?r.slice(0,-1):r}return Vr(new jr([...e],n),{colorSystem:t.colorCompatibility})}function bx(e){return Math.min(20,e??20)}const xx={heading:`ERROR`,glyph:`⚠`,colors:px},Sx={heading:`WARNING`,glyph:`⚠`,colors:mx},Cx={heading:`UPDATE`,glyph:`⬆`,colors:mx};function wx(e,t){return{text:cx(e),link:t}}function Tx(e,t,n){let[r,...i]=[Ex(e,xx,By),t,Ex(n,Sx,Vy)].flat();return r===void 0?null:{channels:[r,...i]}}function Ex(e,t,n){let r=$y([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>wx(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function Dx(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
|
|
136
136
|
`)}function Ox(e,t,n,r){if(t===null)return e;let i=kx(r),a=t.channels.flatMap(e=>Ax(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[jx(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
|
|
137
137
|
`);return e?`${l}\n${e}`:l}function kx(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function Ax(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=A(Math.max(2,t.width-1)),i=(e,t)=>new Ar(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>yx([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Vt(e,r)).map(e=>i(e,t))})],t).split(`
|
|
138
|
-
`))}function jx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${cx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(cx(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,yx([m],r)}const Mx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Nx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Px(e,t){return r.readdirSync(t).filter(Mx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Px(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Nx(i,a)]]})}function Fx(e){let t=ee.createHash(`sha256`);for(let[n,r]of Px(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ix=e=>e.slice(0,7);function Lx(e){return c.dirname(c.dirname(e))}function Rx(){return{version:nb,digest:`70b902a762bb064d6d46d39703380dceb22a10e7c8aa74bef077490bc8c0b016`}}function zx(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Bx(e,t){try{let n=Lx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Fx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:zx(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const Vx=/^-?\d+$/;function Hx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ux(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 Wx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Vx.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 Gx(e,t,n){return r=>r?Vx.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 Kx(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=>!Vx.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:Hx(r[0].seed,t,i)}}return{kind:`int`}}function qx(e){return e===`config`?`set-config`:`set-state`}function Jx(e,t,n){return t.kind===`int`?Wx(`menu page "${e}"`):t.kind===`range`?Gx(t.min,t.max,`${n} stepper "${e}"`):Ux(t.allowed,`${n} "${e}"`,qx(n))}function Yx(e,t,n){return Jx(e,Kx(e,t,n),n)}function Xx(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:Kx(e,n,t)}))}function Zx(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=Yx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Yx(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=Yx(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=Kx(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 Qx=Zx({},`config`);function $x(){return Qx.listKeys()}function eS(e,t){return Qx.validate(e,t)}function tS(e){return Qx.rangeParamsFor(e)}function nS(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:N_(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:[Qm({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.insertSegmentFrom,n).map(t=>Qm({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:Hx(t.get(e.persist),e.min,e.max)}}]:[]}function rS(e){return ko(e.globals)}function iS(e){let t=new Set;for(let n of oS(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=dh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:uh(e),spec:{kind:`allow-list`,allowed:[]}}))}function aS(e){let t=rS(e),n=new Map([...j_(e),...wh(e)]);return[...iS(e),...oS(e).flatMap(e=>nS(e,t,n))]}function oS(e){return Object.values(e.actions).flatMap(Ag)}function sS(e){return Xx(aS(e),`config`)}function cS(e,t){return Qx.register(e,t)}const lS=li(),uS=new Set(lS),dS=new Set(pi),fS=e=>e?uS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pS=e=>e?dS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},mS=new Set([`1`,`true`]),hS=new Set([`0`,`false`]),gS=Zx({style:pS,theme:fS,"toolbar-expanded":e=>mS.has(e)?{ok:!0,value:`1`}:hS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function _S(){return gS.listKeys()}function vS(e,t){return gS.register(e,t)}function yS(e,t){return gS.validate(e,t)}function bS(e){return gS.rangeParamsFor(e)}function xS(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:N_(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:Hx(t.get(e.set),e.min,e.max)}}]:[]}function SS(e){let t=new Set(gS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function CS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function wS(e){let t=CS(e),n=j_(e);return SS(Object.values(e.actions).flatMap(Ag).flatMap(e=>xS(e,t,n)))}function TS(e){return Xx(wS(e))}const ES=`update.dismissed`,DS=`updateNotice`;function OS(e){return e.kind===`source`?e.newer.digest:sb(e.newer)}const kS=e=>`${e.version} [${Ix(e.digest)}]`;function AS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kS(e.newer),running:kS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:sb(e.newer),running:sb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${lb}@${sb(e.newer)}`,`install`]}}}}const jS={kind:`idle`},MS={kind:`running`};function NS(e,t,n){if(e===null)return[];let r=OS(e);if(!n.enabled||n.dismissed===r)return[];let i=AS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
138
|
+
`))}function jx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${cx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(cx(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,yx([m],r)}const Mx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Nx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Px(e,t){return r.readdirSync(t).filter(Mx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Px(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Nx(i,a)]]})}function Fx(e){let t=ee.createHash(`sha256`);for(let[n,r]of Px(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ix=e=>e.slice(0,7);function Lx(e){return c.dirname(c.dirname(e))}function Rx(){return{version:nb,digest:`6828d712ce25cbd7fe91784003db86c8cd7a8627cfa75a9e9b108e998fec9dda`}}function zx(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Bx(e,t){try{let n=Lx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Fx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:zx(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const Vx=/^-?\d+$/;function Hx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ux(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 Wx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Vx.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 Gx(e,t,n){return r=>r?Vx.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 Kx(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=>!Vx.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:Hx(r[0].seed,t,i)}}return{kind:`int`}}function qx(e){return e===`config`?`set-config`:`set-state`}function Jx(e,t,n){return t.kind===`int`?Wx(`menu page "${e}"`):t.kind===`range`?Gx(t.min,t.max,`${n} stepper "${e}"`):Ux(t.allowed,`${n} "${e}"`,qx(n))}function Yx(e,t,n){return Jx(e,Kx(e,t,n),n)}function Xx(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:Kx(e,n,t)}))}function Zx(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=Yx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Yx(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=Yx(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=Kx(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 Qx=Zx({},`config`);function $x(){return Qx.listKeys()}function eS(e,t){return Qx.validate(e,t)}function tS(e){return Qx.rangeParamsFor(e)}function nS(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:N_(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:[Qm({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.insertSegmentFrom,n).map(t=>Qm({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:Hx(t.get(e.persist),e.min,e.max)}}]:[]}function rS(e){return ko(e.globals)}function iS(e){let t=new Set;for(let n of oS(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=dh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:uh(e),spec:{kind:`allow-list`,allowed:[]}}))}function aS(e){let t=rS(e),n=new Map([...j_(e),...wh(e)]);return[...iS(e),...oS(e).flatMap(e=>nS(e,t,n))]}function oS(e){return Object.values(e.actions).flatMap(Ag)}function sS(e){return Xx(aS(e),`config`)}function cS(e,t){return Qx.register(e,t)}const lS=li(),uS=new Set(lS),dS=new Set(pi),fS=e=>e?uS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pS=e=>e?dS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},mS=new Set([`1`,`true`]),hS=new Set([`0`,`false`]),gS=Zx({style:pS,theme:fS,"toolbar-expanded":e=>mS.has(e)?{ok:!0,value:`1`}:hS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function _S(){return gS.listKeys()}function vS(e,t){return gS.register(e,t)}function yS(e,t){return gS.validate(e,t)}function bS(e){return gS.rangeParamsFor(e)}function xS(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:N_(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:Hx(t.get(e.set),e.min,e.max)}}]:[]}function SS(e){let t=new Set(gS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function CS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function wS(e){let t=CS(e),n=j_(e);return SS(Object.values(e.actions).flatMap(Ag).flatMap(e=>xS(e,t,n)))}function TS(e){return Xx(wS(e))}const ES=`update.dismissed`,DS=`updateNotice`;function OS(e){return e.kind===`source`?e.newer.digest:sb(e.newer)}const kS=e=>`${e.version} [${Ix(e.digest)}]`;function AS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kS(e.newer),running:kS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:sb(e.newer),running:sb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${lb}@${sb(e.newer)}`,`install`]}}}}const jS={kind:`idle`},MS={kind:`running`};function NS(e,t,n){if(e===null)return[];let r=OS(e);if(!n.enabled||n.dismissed===r)return[];let i=AS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
139
139
|
`),c=$y([{verb:Vy,args:[s]}]),l=t.kind===`running`?wx(`[${i.busy}]`,c):wx(`[${i.act}]`,$y([{verb:Jy,args:[n.sessionId]}]));return[{severity:Cx,message:s,lines:[[wx(a,c),l,wx(`[dismiss]`,$y([{verb:Fy,args:[n.sessionId,ES,r]}])),wx(`[disable]`,$y([{verb:Hy,args:[n.sessionId,DS,`false`]}]))],...o.map(e=>[wx(e,c)])]}]}function PS(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function FS(e){switch(e.kind){case`current`:return[`info`,`build: current ${kS(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${kS(e.source)}, running ${kS(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function IS(e){switch(e.kind){case`current`:return[`info`,`release: current ${sb(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${sb(e.latest)}, running ${sb(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${sb(e.installed)}, latest ${sb(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function LS(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const RS=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function zS(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=RS(e.stderr)??e.error??RS(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function BS(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=jS,d=null,f=LS(s),p=LS(s),m=()=>PS(c,l);function h(){let e=m(),t=e===null?null:OS(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:vS(ES,{kind:`allow-list`,allowed:[t]})})}function g(){c=Bx(t,Rx),f(FS(c)),h()}async function _(){l=db(nb,await ub(lb,a,i)),p(IS(l)),h()}return{arm(){cS(DS,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>NS(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=AS(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=MS,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Ee({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=jS,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=zS(n);u={kind:`failed`,identity:OS(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function VS(e,t,n){return t.ok?X(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??HS(t.stderr)].filter(Boolean).join(`, `)}`)}function HS(e){return e.trim().split(`
|
|
140
140
|
`,1)[0]??``}function US(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Z:X(n)}function WS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?X(t):Z}const GS=/^[A-Za-z]:[\\/]/;function KS(e){let t=e.trim();if(GS.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function qS(e){return KS(e)?.host||null}function JS(e){let t=qS(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function YS(e){let t=new Map;for(let n of e.split(`
|
|
141
141
|
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function XS(e){return e.urls.find(e=>tC(e)!==null)??e.urls[0]??null}function ZS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function QS(e){let t=ZS(e);return t?XS(t):null}function $S(e){let t=ZS(e);return t?t.urls.find(e=>JS(e)!==null)??XS(t):null}function eC(e){let t=(KS(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function tC(e){let t=KS(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function nC(e){let t=QS(e);return t===null?null:tC(t)}function rC(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??HS(t.stderr)].filter(Boolean).join(`, `)}`)}function iC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aC(e){let t=`detached`,n=Z,r=Z,i=Z,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
@@ -143,7 +143,7 @@ Config tooling:
|
|
|
143
143
|
`).length:0)}async getRemotesAsync(e){let t=cC(c.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=VS(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:X(t.kind===`ok`?YS(t.value):[])}repoNameFrom(e,t){let n=QS(e);return(n===null?null:eC(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=$S(t.value);return n===null?Z:X(n)}async execForgeAsync(e,t,n){return Ee({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JS(t);return n===`github`?rC(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,oC):n===`gitlab`?rC(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,sC):Z}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=VS(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?X(aC(t.value)):t}};const uC=(e,t)=>E(t);var dC=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??uC}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},fC=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const pC=(e,t)=>E(t),mC={showSha:!0,showStashCount:!0};function hC(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function gC(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function _C(e,t){return e.head!==t.head||e.index!==t.index}function vC(e){let t=[],n=c.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[c.join(e,`HEAD`),c.join(e,`index`)],dirs:t}}var yC=class extends lC{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new fC;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new lC,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??pC,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new dC({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${hC(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(X(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=gC(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,vC(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Z;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,vC(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...mC});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...mC}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=gC(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),_C(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},bC=class{static CACHE_DIR=D();static USAGE_CACHE_DIR=c.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=c.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=c.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return E(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(E(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=c.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await re(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=c.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=c.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){E(`Cache for ${e} is locked, waiting...`),await re(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(E(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await re(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=c.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const xC={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var SC=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await bC.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await bC.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new v(this.GITHUB_PRICING_URL),n=ne({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});n.on(`error`,t=>{E(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{E(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(xC).length} models`),this.executionCache=xC,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(xC).length} models`),xC)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};function CC(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const wC=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function TC(e){return((...t)=>wC.run(()=>e(...t)))}const EC=TC(ae),DC=TC(C),OC=TC(w);async function kC(e,t){return wC.run(async()=>{let n=null;try{n=await ie(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return X({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return X({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Z:Q(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{E(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function AC(e,t){return wC.run(async()=>{let n=null;try{n=await ie(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return X({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Z:Q(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{E(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}function jC(){let e=[],t=process.env.CLAUDE_CONFIG_DIR;if(t&&t.split(`,`).forEach(t=>{let n=t.trim();a(n)&&e.push(n)}),e.length===0){let t=p(),n=d(t,`.config`,`claude`),r=d(t,`.claude`);a(n)&&e.push(n),a(r)&&e.push(r)}return e}async function MC(e){let t=[];for(let n of e){let e=d(n,`projects`);if(a(e))try{let n=await EC(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){E(`Failed to read projects directory ${e}:`,t)}}return t}async function NC(e,t,n){let r=[],i=d(t,e,`subagents`);try{let t=(await EC(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=d(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await DC(t,`utf-8`)).split(`
|
|
144
144
|
`)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{E(`Failed to check agent file ${t}`)}}}catch(e){E(`Failed to read subagents directory ${i}:`,e)}return r}const PC=new Map;async function FC(e){try{let t=await OC(e),n=t.size,r=PC.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return E(`[parse-cache] hit ${e}`),PC.delete(e),PC.set(e,r),r.entries;let i;return n>1048576?(E(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await BC(e)):i=await RC(e),E(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(PC.delete(e),PC.size>=16&&PC.delete(PC.keys().next().value),PC.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return E(`Transcript not present yet: ${e}`),[];throw t}}function IC(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function LC(e){let t=[];for(let n of e.split(`
|
|
145
145
|
`))if(n.trim())try{let e=IC(JSON.parse(n));e&&t.push(e)}catch(e){E(`Failed to parse JSONL line: ${e}`);continue}return t}async function RC(e){return LC(await DC(e,`utf-8`))}async function zC(e,t){let n=await kC(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return X(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:LC(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function BC(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=T({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=IC(JSON.parse(t));e&&r.push(e)}catch(e){E(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{E(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{E(`File stream error for ${e}:`,t),n(t)})})}var VC=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function HC(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const UC={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},WC={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function GC(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function KC(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function qC(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function JC(e,t,n,r){let i=GC(new Date(KC())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:qC(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await SC.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=GC(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...UC};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function YC(e){let t=0,n=0,r=qC(),i=new Map;for(let a of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...UC};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:WC,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function XC(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var ZC=class{entries=new Map;flight=new VC;seeded=new Map;speedRings=new Map;speedFlight=new VC;maxEntries;staleAgeMs;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:WC,i=t?.cost?.total_cost_usd??null;return X({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e){let t=GC(new Date);try{await this.ensureSeeded(t)}catch(e){return Q(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let n=await this.ingest(e?.session_id??``,e?.transcript_path);if(n.kind===`failed`)return n;let r={...UC},i=!1;for(let e of this.entries.values()){i||=e.days.has(t);let n=e.days.get(t)??UC;r.cost+=n.cost,r.input+=n.input,r.output+=n.output,r.cacheCreation+=n.cacheCreation,r.cacheRead+=n.cacheRead}return i?X({cost:r.cost,tokens:r.input+r.output+r.cacheCreation+r.cacheRead,tokenBreakdown:{input:r.input,output:r.output,cacheCreation:r.cacheCreation,cacheRead:r.cacheRead},date:t}):Z}async observeSpeed(e,t,n){let r=CC(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=HC(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),X({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Z;let r=n??CC(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,X(i);if(!t)return i?X(i):Z;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return Q(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),X(o)}async refold(e,t,n){let r=await NC(e,u(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await zC(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await JC(r,l,s,c)),e===t&&(a=c.mtimeMs)}return X({files:i,...YC(i),mainMtime:a})}ensureSeeded(e){let t=this.seeded.get(e);if(t)return t;this.seeded.clear();let n=this.seed(e);return this.seeded.set(e,n),n.catch(()=>{this.seeded.get(e)===n&&this.seeded.delete(e)}),n}async seed(e){let t=KC(),n=await MC(jC()),r=[];for(let e of n){let n;try{n=await EC(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a;try{a=(await OC(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await XC(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&Y(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,Y(`info`,`usageStore seed sessions=${r.length}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,Y(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),Y(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}};const QC=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function $C(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 ew(e){let t=await tw(e);return t.kind===`ok`?X(Math.floor((t.value+36e5)/1e3)):t}async function tw(e){for(let t of[65536,1048576]){let n=await AC(e,t);if(n.kind!==`ok`)return n;let r=nw(n.value.buf,n.value.fromStart);if(r!=null)return X(r);if(n.value.fromStart)return Z}return Z}function nw(e,t){let n=e.toString(`utf8`).split(`
|
|
146
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!QC.test(t))continue;let r=$C(t);if(r!=null)return r}return null}function rw(e,t,n){let r=ih(t(`preset`),e.globals.preset,e.presets),i=sh(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:si(a.palette,t(`theme`),i.palette),look:di(a.look,t(`look`),i.look,e.looks),style:hi(a.style,t(`style`),i.style),separator:a.default_separator??i.default_separator,autoWrap:wi(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Ti(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}const iw=10*1e3;function aw(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 ow(e,t){if(!(t<60))return e*3600/t}function sw(e,t,n,r){let i=r-t;if(i<50||i>iw)return;let a=n-e;if(!(a<=0))return a*1e3/i}function cw(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=sw(t.input,t.atMs,n.input,n.atMs),i=sw(t.output,t.atMs,n.output,n.atMs),a=sw(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 lw(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>iw)continue;let o=sw(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function uw(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function dw(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>uw(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function fw(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 va(co(e.root))){if(t.when)for(let e of L_(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 L_(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of pw(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 L_(e.template))n.push(t)}}}return i}function pw(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 mw(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function hw(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 gw(e,t,n,r,i,a){let o=e=>mw(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Q(`${e}: ${String(t)}`)):Promise.resolve(Z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,hw(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>ew(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=yw(l);_.push(...y.failures);let b=dw(a);_.push(...b.failures);let x=v(u),S=v(d),ee=v(f),te=v(p),ne=v(m),re=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let ie=e.rate_limits?.five_hour,C=e.rate_limits?.seven_day,ae=ie?aw(ie.used_percentage,ie.resets_at,18e6,s):void 0,w=C?aw(C.used_percentage,C.resets_at,6048e5,s):void 0,T=x?.session.cost,oe=te?.sessionDuration,se=o(`burn`)&&T!=null&&oe!=null?ow(T,oe):void 0,ce=v(g),le=ce===void 0?void 0:cw(ce),ue=ce===void 0?void 0:lw(ce),de=le!==void 0||ue!==void 0?{...le,...ue!==void 0&&{history:ue}}:void 0,fe=vw(process.env.HOME??process.env.USERPROFILE),pe=e.workspace?{...e.workspace,current_dir:vw(e.workspace.current_dir)??``,project_dir:vw(e.workspace.project_dir)??``}:e.workspace,me=x===void 0?void 0:_w({cost:x.session.cost,tokens:x.session.tokens}),he=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},ge=te===void 0?void 0:_w({lastResponseTime:te.lastResponseTime,responseTime:te.responseTime,sessionDuration:te.sessionDuration,messageCount:te.messageCount,linesAdded:te.linesAdded,linesRemoved:te.linesRemoved});return{...e,...pe!==void 0&&{workspace:pe},...fe!==void 0&&{home:fe},...y.git!==void 0&&{git:y.git},...ne!==void 0&&{tmux:{session:ne}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...me!==void 0&&{session:me},...he!==void 0&&{today:he},...se!==void 0&&{burn:{costPerHour:se}},...de!==void 0&&{speed:de},...o(`block`)&&ie!==void 0&&{block:{nativeUtilization:ie.used_percentage,resetsAt:ie.resets_at,...ae!==void 0&&{etaMinutes:ae}}},...C!==void 0&&{weekly:{percentage:C.used_percentage,resetsAt:C.resets_at,...w!==void 0&&{etaMinutes:w}}},...re!==void 0&&{cache:{expiresAt:re}},...ee!==void 0&&{context:{totalTokens:ee.totalTokens,contextLeft:ee.contextLeftPercentage}},...ge!==void 0&&{metrics:ge}}}function _w(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 vw(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function yw(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 bw=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,xw=`{{ \$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 (${bw}) (basename .project_dir) (ne (${bw}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,Sw={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},Cw=(e,t)=>`{{ fg (color "${Sw[e]}") ${t} }}`,ww=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,Tw=`{{ 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 }}${Cw(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${Cw(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${Cw(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${Cw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,Ew=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${Cw(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Cw(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${Cw(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+Tw+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${Cw(`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 }}`,Dw={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},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0}},segments:{directory:{description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project.",template:xw,fg:`foreground`},model:{description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{description:`Branch, sha, ahead/behind, staged/unstaged/untracked/conflict counts, upstream, stash count, and a clean/dirty/conflict glyph.`,template:Ew,fg:ww,when:`{{ ne .git.branch "" }}`},gitaculous:{description:`The same git state in asyncgit's compact spelling: repo, in-progress operation, sha, S/U/? flags, branch, upstream ±, stash count, and time since the last commit.`,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 }}${Cw(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${Cw(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${Cw(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${Cw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${Cw(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Cw(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${Cw(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${Cw(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,fg:ww,when:`{{ ne .git.branch "" }}`},gitPr:{description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{description:`Quick actions: copy the session id, open the project, transcript or repo, and toggle edit mode.`,template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,fg:`foreground`},session:{description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,fg:`foreground`},today:{description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,fg:`foreground`},block:{description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 "panel" .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .block.nativeUtilization) "step" 0 "foreground" .block.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 "panel" .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .weekly.percentage) "step" 0 "foreground" .weekly.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 "panel" 0 "error" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes "panel" }}`,fg:`{{ ramp .block.etaMinutes "step" -1 "foreground" 0 "button-color-foreground" .burn.eta.warnMinutes "foreground" }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ 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:{description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 "surface-active" }}`,fg:`{{ ramp .context.contextLeft "step" 0 "button-color-foreground" 41 "foreground" }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},charsetControl:{description:"The `⚙ terminal` drawer's control for `globals.charset` — the joiner glyph vocabulary.",template:`{{ .charset.effective }} {{ menu "applyCharsetForever" "▸" "▾" }} {{ action "resetCharset" "↺" }}`,fg:`foreground`},colorCompatControl:{description:"The `⚙ terminal` drawer's control for `globals.colorCompatibility` — the colour depth.",template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" "▸" "▾" }} {{ action "resetColorCompat" "↺" }}`,fg:`foreground`},directoryPaletteControl:{description:"The `⚙ terminal` drawer's control pinning the directory segment's own palette.",template:`🎨 directory {{ menu "applyDirectoryPaletteForever" "▸" "▾" }} {{ action "resetDirectoryPalette" "↺" }}`,fg:`foreground`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ terminal`,direction:`horizontal`,children:[`charsetControl`,`colorCompatControl`,`directoryPaletteControl`]}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}}},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`},{kind:`segment`,name:`toolbar`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},Ow=new Set([Dw.globals.palette,...Object.values(Dw.segments).map(e=>e.palette)].filter(e=>e!==void 0)),kw=po(bv(`<default>`,JSON.stringify(Dw),Ow),Dw);var Aw=me((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:tn}function r(){cn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===ln}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){rn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){rn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return an.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(ie())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&C(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ae(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function ee(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
146
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!QC.test(t))continue;let r=$C(t);if(r!=null)return r}return null}function rw(e,t,n){let r=ih(t(`preset`),e.globals.preset,e.presets),i=sh(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:si(a.palette,t(`theme`),i.palette),look:di(a.look,t(`look`),i.look,e.looks),style:hi(a.style,t(`style`),i.style),separator:a.default_separator??i.default_separator,autoWrap:wi(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Ti(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}const iw=10*1e3;function aw(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 ow(e,t){if(!(t<60))return e*3600/t}function sw(e,t,n,r){let i=r-t;if(i<50||i>iw)return;let a=n-e;if(!(a<=0))return a*1e3/i}function cw(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=sw(t.input,t.atMs,n.input,n.atMs),i=sw(t.output,t.atMs,n.output,n.atMs),a=sw(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 lw(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>iw)continue;let o=sw(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function uw(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function dw(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>uw(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function fw(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 va(co(e.root))){if(t.when)for(let e of L_(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 L_(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of pw(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 L_(e.template))n.push(t)}}}return i}function pw(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 mw(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function hw(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 gw(e,t,n,r,i,a){let o=e=>mw(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Q(`${e}: ${String(t)}`)):Promise.resolve(Z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,hw(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>ew(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=yw(l);_.push(...y.failures);let b=dw(a);_.push(...b.failures);let x=v(u),S=v(d),ee=v(f),te=v(p),ne=v(m),re=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let ie=e.rate_limits?.five_hour,C=e.rate_limits?.seven_day,ae=ie?aw(ie.used_percentage,ie.resets_at,18e6,s):void 0,w=C?aw(C.used_percentage,C.resets_at,6048e5,s):void 0,T=x?.session.cost,oe=te?.sessionDuration,se=o(`burn`)&&T!=null&&oe!=null?ow(T,oe):void 0,ce=v(g),le=ce===void 0?void 0:cw(ce),ue=ce===void 0?void 0:lw(ce),de=le!==void 0||ue!==void 0?{...le,...ue!==void 0&&{history:ue}}:void 0,fe=vw(process.env.HOME??process.env.USERPROFILE),pe=e.workspace?{...e.workspace,current_dir:vw(e.workspace.current_dir)??``,project_dir:vw(e.workspace.project_dir)??``}:e.workspace,me=x===void 0?void 0:_w({cost:x.session.cost,tokens:x.session.tokens}),he=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},ge=te===void 0?void 0:_w({lastResponseTime:te.lastResponseTime,responseTime:te.responseTime,sessionDuration:te.sessionDuration,messageCount:te.messageCount,linesAdded:te.linesAdded,linesRemoved:te.linesRemoved});return{...e,...pe!==void 0&&{workspace:pe},...fe!==void 0&&{home:fe},...y.git!==void 0&&{git:y.git},...ne!==void 0&&{tmux:{session:ne}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...me!==void 0&&{session:me},...he!==void 0&&{today:he},...se!==void 0&&{burn:{costPerHour:se}},...de!==void 0&&{speed:de},...o(`block`)&&ie!==void 0&&{block:{nativeUtilization:ie.used_percentage,resetsAt:ie.resets_at,...ae!==void 0&&{etaMinutes:ae}}},...C!==void 0&&{weekly:{percentage:C.used_percentage,resetsAt:C.resets_at,...w!==void 0&&{etaMinutes:w}}},...re!==void 0&&{cache:{expiresAt:re}},...ee!==void 0&&{context:{totalTokens:ee.totalTokens,contextLeft:ee.contextLeftPercentage}},...ge!==void 0&&{metrics:ge}}}function _w(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 vw(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function yw(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 bw=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,xw=`{{ \$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 (${bw}) (basename .project_dir) (ne (${bw}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,Sw={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},Cw=(e,t)=>`{{ fg (color "${Sw[e]}") ${t} }}`,ww=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,Tw=`{{ 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 }}${Cw(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${Cw(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${Cw(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${Cw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,Ew=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${Cw(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Cw(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${Cw(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+Tw+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${Cw(`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 }}`,Dw={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},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0}},segments:{directory:{description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project.",template:xw,fg:`foreground`},model:{description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{description:`Branch, sha, ahead/behind, staged/unstaged/untracked/conflict counts, upstream, stash count, and a clean/dirty/conflict glyph.`,template:Ew,fg:ww,when:`{{ ne .git.branch "" }}`},gitaculous:{description:`The same git state in asyncgit's compact spelling: repo, in-progress operation, sha, S/U/? flags, branch, upstream ±, stash count, and time since the last commit.`,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 }}${Cw(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${Cw(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${Cw(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${Cw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${Cw(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${Cw(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${Cw(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${Cw(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,fg:ww,when:`{{ ne .git.branch "" }}`},gitPr:{description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{description:`Quick actions: copy the session id, open the project, transcript or repo, and toggle edit mode.`,template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,fg:`foreground`},session:{description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,fg:`foreground`},today:{description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,fg:`foreground`},block:{description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 "panel" .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .block.nativeUtilization) "step" 0 "foreground" .block.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 "panel" .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .weekly.percentage) "step" 0 "foreground" .weekly.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 "panel" 0 "error" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes "panel" }}`,fg:`{{ ramp .block.etaMinutes "step" -1 "foreground" 0 "button-color-foreground" .burn.eta.warnMinutes "foreground" }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground" }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 "surface-active" }}`,fg:`{{ ramp .context.contextLeft "step" 0 "button-color-foreground" 41 "foreground" }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},charsetControl:{description:"The `⚙ terminal` drawer's control for `globals.charset` — the joiner glyph vocabulary.",template:`{{ .charset.effective }} {{ menu "applyCharsetForever" "▸" "▾" }} {{ action "resetCharset" "↺" }}`,fg:`foreground`},colorCompatControl:{description:"The `⚙ terminal` drawer's control for `globals.colorCompatibility` — the colour depth.",template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" "▸" "▾" }} {{ action "resetColorCompat" "↺" }}`,fg:`foreground`},directoryPaletteControl:{description:"The `⚙ terminal` drawer's control pinning the directory segment's own palette.",template:`🎨 directory {{ menu "applyDirectoryPaletteForever" "▸" "▾" }} {{ action "resetDirectoryPalette" "↺" }}`,fg:`foreground`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ terminal`,direction:`horizontal`,children:[`charsetControl`,`colorCompatControl`,`directoryPaletteControl`]}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}}},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`},{kind:`segment`,name:`toolbar`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},Ow=new Set([Dw.globals.palette,...Object.values(Dw.segments).map(e=>e.palette)].filter(e=>e!==void 0)),kw=po(bv(`<default>`,JSON.stringify(Dw),Ow),Dw);var Aw=me((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:tn}function r(){cn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===ln}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){rn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){rn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return an.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(ie())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&C(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ae(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function ee(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
147
147
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function te(){return(te=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(null,arguments)}function ne(e){return(ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function re(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,C(e,t)}function ie(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(ie=function(){return!!e})()}function C(e,t){return(C=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function ae(e){var t=function(e){if(typeof e!=`object`||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var n=t.call(e,`string`);if(typeof n!=`object`)return n;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e);return typeof t==`symbol`?t:t+``}function w(e){var t=typeof Map==`function`?new Map:void 0;return(w=function(e){function n(){return b(e,arguments,ne(this).constructor)}if(e===null||!function(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),C(n,e)})(e)}function T(e){return Object.assign((function(t,n){if(se(n))return e.t(t,n);oe(t,n,e)}),e)}function oe(e,t,n){g(e,mn)||u(e,mn,te({},e[mn])),function(e){return e.i===`override`}(n)||(e[mn][t]=n)}function se(e){return typeof e==`object`&&typeof e.kind==`string`}function ce(e,t,n){t===void 0&&(t=un),n===void 0&&(n=un);var r=new hn(e);return t!==un&&ft(r,t),n!==un&&pt(r,n),r}function le(e,t,n){return St(e)?e:Array.isArray(e)?L.array(e,{name:n}):c(e)?L.object(e,void 0,{name:n}):p(e)?L.map(e,{name:n}):m(e)?L.set(e,{name:n}):typeof e!=`function`||lt(e)||yt(e)?e:l(e)?tr(e):Xn(n,e)}function ue(e){return e}function de(e,t){return{i:e,u:t,o:fe,s:pe,t:me}}function fe(e,t,n,r){var i;return(i=this.u)!=null&&i.bound?this.s(e,t,n,!1)===null?0:1:r===e.h?this.s(e,t,n,!1)===null?0:2:lt(n.value)?1:(rn(r,t,he(e,this,t,n,!1)),2)}function pe(e,t,n,r){var i=he(e,this,t,n);return e.l(t,i,r)}function me(e,n){var r,i=n.kind,a=n.name,o=n.addInitializer,s=this,c=function(e){var t;return Pe(s.u?.name??a.toString(),e,(t=s.u?.autoAction)!=null&&t)};return i==`field`?function(e){var t,n=e;return lt(n)||(n=c(n)),(t=s.u)!=null&&t.bound&&((n=n.bind(this)).isMobxAction=!0),n}:i==`method`?(lt(e)||(e=c(e)),(r=this.u)!=null&&r.bound&&o((function(){var e=this[a].bind(this);e.isMobxAction=!0,this[a]=e})),e):void t(`Cannot apply '`+s.i+`' to '`+String(a)+`' (kind: `+i+`):
|
|
148
148
|
'`+s.i+`' can only be used on properties with a function value.`)}function he(e,t,n,r,i){var a,o,s;i===void 0&&(i=z.safeDescriptors);var c=r.value;return(a=t.u)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:Pe(t.u?.name??n.toString(),c,(o=t.u?.autoAction)!=null&&o,(s=t.u)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function ge(e,t){return{i:e,u:t,o:E,s:_e,t:ve}}function E(e,t,n,r){var i;return r===e.h?this.s(e,t,n,!1)===null?0:2:(i=this.u)!=null&&i.bound&&(!g(e.h,t)||!yt(e.h[t]))&&this.s(e,t,n,!1)===null?0:yt(n.value)?1:(rn(r,t,ye(e,0,0,n,!1,!1)),2)}function _e(e,t,n,r){var i=ye(e,0,0,n,this.u?.bound);return e.l(t,i,r)}function ve(e,t){var n,r=t.name,i=t.addInitializer;return yt(e)||(e=tr(e)),(n=this.u)!=null&&n.bound&&i((function(){var e=this[r].bind(this);e.isMobXFlow=!0,this[r]=e})),e}function ye(e,t,n,r,i,a){a===void 0&&(a=z.safeDescriptors);var o=r.value;return yt(o)||(o=tr(o)),i&&((o=o.bind(e.v??e.h)).isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function be(e,t){return{i:e,u:t,o:xe,s:Se,t:Ce}}function xe(e,t,n){return this.s(e,t,n,!1)===null?0:1}function Se(e,t,n,r){return e.m(t,te({},this.u,{get:n.get,set:n.set}),r)}function Ce(e,t){var n=this,r=t.name;return(0,t.addInitializer)((function(){var t=Ht(this)[F],i=te({},n.u,{get:e,context:this});i.name||=`ObservableObject.`+r.toString(),t.j.set(r,new Fn(i))})),function(){return this[F].O(r)}}function we(e,t){return{i:e,u:t,o:Te,s:Ee,t:De}}function Te(e,t,n){return this.s(e,t,n,!1)===null?0:1}function Ee(e,t,n,r){return e.g(t,n.value,this.u?.enhancer??le,r)}function De(e,t){function n(e,t){var n=Ht(e)[F],i=new Nn(t,r.u?.enhancer??le,`ObservableObject.`+a.toString(),!1);n.j.set(a,i),o.add(e)}var r=this,i=t.kind,a=t.name,o=new WeakSet;if(i==`accessor`)return{get:function(){return o.has(this)||n(this,e.get.call(this)),this[F].O(a)},set:function(e){return o.has(this)||n(this,e),this[F].S(a,e)},init:function(e){return o.has(this)||n(this,e),e}}}function Oe(e){return{i:`true`,u:e,o:ke,s:Ae,t:je}}function ke(e,t,n,r){var i,a,o;if(n.get)return On.o(e,t,n,r);if(n.set){var s=lt(n.set)?n.set:Pe(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!z.safeDescriptors||e.p,set:s})===null?0:2:(rn(r,t,{configurable:!0,set:s}),2)}if(r!==e.h&&typeof n.value==`function`)return l(n.value)?((o=this.u)!=null&&o.autoBind?tr.bound:tr).o(e,t,n,r):((a=this.u)!=null&&a.autoBind?Xn.bound:Xn).o(e,t,n,r);var c=!1===this.u?.deep?L.ref:L;return typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function Ae(e,t,n,r){var i;return n.get?On.s(e,t,n,r):n.set?e.l(t,{configurable:!z.safeDescriptors||e.p,set:Pe(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.u?.deep?L.ref:L).s(e,t,n,r))}function je(){t(`'`+this.i+`' cannot be used as a decorator`)}function Me(e){return e||bn}function D(e){return!0===e.deep?le:!1===e.deep?ue:(t=e.defaultDecorator)&&(n=(r=t.u)?.enhancer)!=null?n:le;var t,n,r}function Ne(e,t,n){return se(t)?xn.t(e,t):o(t)?void oe(e,t,xn):St(e)?e:c(e)?L.object(e,t,n):Array.isArray(e)?L.array(e,t):p(e)?L.map(e,t):m(e)?L.set(e,t):typeof e==`object`&&e?e:L.box(e,t)}function Pe(e,t,n,r){function i(){return Fe(0,n,t,r||this,arguments)}return n===void 0&&(n=!1),i.isMobxAction=!0,i.toString=function(){return t.toString()},jn&&(Mn.value=e,rn(i,`name`,Mn)),i}function Fe(e,t,n,r,i){var a=Ie(0,t);try{return n.apply(r,i)}catch(e){throw a._=e,e}finally{Le(a)}}function Ie(e,t){var n=z.trackingDerivation,r=!t||!n;et();var i=z.allowStateChanges;r&&(Ke(),i=ze(!0));var a={A:r,k:n,M:i,V:Je(!0),R:!1,N:0,T:An++,C:kn};return kn=a.T,a}function Le(e){kn!==e.T&&t(30),kn=e.C,e._!==void 0&&(z.suppressReactionErrors=!0),Be(e.M),Ye(e.V),tt(),e.A&&qe(e.k),z.suppressReactionErrors=!1}function Re(e,t){var n=ze(e);try{return t()}finally{Be(n)}}function ze(e){var t=z.allowStateChanges;return z.allowStateChanges=e,t}function Be(e){z.allowStateChanges=e}function Ve(e){return e instanceof Rn}function He(e){switch(e.I){case R.L:return!1;case R.P:case R.K:return!0;case R.B:for(var t=Je(!0),n=Ke(),r=e.D,i=r.length,a=0;a<i;a++){var o=r[a];if(Ln(o)){if(z.disableErrorBoundaries)o.get();else try{o.get()}catch{return qe(n),Ye(t),!0}if(e.I===R.K)return qe(n),Ye(t),!0}}return Xe(e),qe(n),Ye(t),!1}}function Ue(e,t,n){var r=Je(!0);Xe(e),e.W=Array(e.q===0?100:e.D.length),e.G=0,e.q=++z.runId;var i,a=z.trackingDerivation;if(z.trackingDerivation=e,z.inBatch++,!0===z.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Rn(e)}return z.inBatch--,z.trackingDerivation=a,function(e){for(var t=e.D,n=e.D=e.W,r=R.L,i=0,a=e.G,o=0;o<a;o++){var s=n[o];s.diffValue===0&&(s.diffValue=1,i!==o&&(n[i]=s),i++),s.I>r&&(r=s.I)}for(n.length=i,e.W=null,a=t.length;a--;){var c=t[a];c.diffValue===0&&Qe(c,e),c.diffValue=0}for(;i--;){var l=n[i];l.diffValue===1&&(l.diffValue=0,Ze(l,e))}r!==R.L&&(e.I=r,e.H())}(e),Ye(r),i}function We(e){var t=e.D;e.D=[];for(var n=t.length;n--;)Qe(t[n],e);e.I=R.P}function Ge(e){var t=Ke();try{return e()}finally{qe(t)}}function Ke(){var e=z.trackingDerivation;return z.trackingDerivation=null,e}function qe(e){z.trackingDerivation=e}function Je(e){var t=z.allowStateReads;return z.allowStateReads=e,t}function Ye(e){z.allowStateReads=e}function Xe(e){if(e.I!==R.L){e.I=R.L;for(var t=e.D,n=t.length;n--;)t[n].U=R.L}}function Ze(e,t){e.F.add(t),e.U>t.I&&(e.U=t.I)}function Qe(e,t){e.F.delete(t),e.F.size===0&&$e(e)}function $e(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,z.pendingUnobservations.push(e))}function et(){z.inBatch++}function tt(){if(--z.inBatch==0){it();for(var e=z.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,n.F.size===0&&(n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof Fn&&n.X())}z.pendingUnobservations=[]}}function nt(e){var t=z.trackingDerivation;return t===null?(e.F.size===0&&z.inBatch>0&&$e(e),!1):(t.q!==e.$&&(e.$=t.q,t.W[t.G++]=e,!e.isBeingObserved&&z.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function rt(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(e){e.I===R.L&&e.H(),e.I=R.K})))}function it(){z.inBatch>0||z.isRunningReactions||Wn(at)}function at(){z.isRunningReactions=!0;for(var e=z.pendingReactions,t=0;e.length>0;){++t==100&&(console.error(`[mobx] cycle in reaction: `+e[0]),e.splice(0));for(var n=e.splice(0),r=0,i=n.length;r<i;r++)n[r].J()}z.isRunningReactions=!1}function ot(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}}function st(e){return function(t,n){return a(t)?Pe(t.name||`<unnamed action>`,t,e):a(n)?Pe(t,n,e):se(n)?(e?B:Kn).t(t,n):o(n)?oe(t,n,e?B:Kn):o(t)?T(de(e?`autoAction`:`action`,{name:t,autoAction:e})):void 0}}function ct(e){return Fe(0,!1,e,this,void 0)}function lt(e){return a(e)&&!0===e.isMobxAction}function ut(e,t){function n(){e(i)}var r;t===void 0&&(t=sn);var i,a=t?.name??`Autorun`;if(t.scheduler||t.delay){var o=dt(t),s=!1;i=new Un(a,(function(){s||(s=!0,o((function(){s=!1,i.isDisposed||i.track(n)})))}),t.onError,t.requiresObservable)}else i=new Un(a,(function(){this.track(n)}),t.onError,t.requiresObservable);return(r=t)!=null&&(r=r.signal)!=null&&r.aborted||i.Y(),i.Z(t?.signal)}function dt(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:Zn}function ft(e,t,n){return mt(`onBO`,e,t,n)}function pt(e,t,n){return mt(`onBUO`,e,t,n)}function mt(e,t,n,r){var i=typeof r==`function`?Yt(t,n):Yt(t),o=a(r)?r:n,s=e+`L`;return i[s]?i[s].add(o):i[s]=new Set([o]),function(){var e=i[s];e&&(e.delete(o),e.size===0&&delete i[s])}}function ht(e,t,n,r){var i=pn(t);return Zt((function(){var t=Ht(e,r)[F];fn(i).forEach((function(e){t.s(e,i[e],!n||!(e in n)||n[e])}))})),e}function gt(e){var t,n={name:e.tt};return e.D&&e.D.length>0&&(n.dependencies=(t=e.D,Array.from(new Set(t))).map(gt)),n}function _t(e){var t={name:e.tt};return function(e){return e.F&&e.F.size>0}(e)&&(t.observers=Array.from(function(e){return e.F}(e)).map(_t)),t}function vt(e){a(e.cancel)&&e.cancel()}function yt(e){return!0===e?.isMobXFlow}function bt(e,t){return t===void 0?Ln(e):!1===Wt(e)||!e[F].j.has(t)?!1:Ln(Yt(e,t))}function xt(e,t){return!!e&&(t===void 0?Wt(e)||!!e[F]||gn(e)||Gn(e)||Ln(e):!!Wt(e)&&e[F].j.has(t))}function St(e){return xt(e)}function Ct(e){return Wt(e)?e[F].nt():H(e)||gr(e)?Array.from(e.keys()):zt(e)?e.map((function(e,t){return t})):void t(5)}function wt(e,n){return Wt(e)?e[F].it(n):H(e)||gr(e)?e.has(n):zt(e)?n>=0&&n<e.length:void t(10)}function Tt(e){if(Wt(e))return e[F].rt();t(38)}function Et(e,t,n){return e.set(t,n),n}function Dt(e,t){t===void 0&&(t=void 0),et();try{return e.apply(t)}finally{tt()}}function Ot(e,t,n){var r;if(typeof n.timeout==`number`){var i=Error(`WHEN_TIMEOUT`);r=setTimeout((function(){if(!o[F].isDisposed){if(o(),!n.onError)throw i;n.onError(i)}}),n.timeout)}n.name=`When`;var a=Pe(`When-effect`,t),o=ut((function(t){Re(!1,e)&&(t.dispose(),r&&clearTimeout(r),a())}),n);return o}function kt(e,t){var n,r,i;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Object.assign(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:function(){return null}});var a=new Promise((function(n,a){var o,s=Ot(e,n,te({},t,{onError:a}));r=function(){s(),a(Error(`WHEN_CANCELLED`))},i=function(){s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)})).finally((function(){var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)}));return a.cancel=r,a}function At(e){return e[F]}function jt(e){return e.et!==void 0&&e.et.length>0}function Mt(e,t){var n=e.et||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Nt(e,n){var r=Ke();try{for(var i=[].concat(e.et||[]),a=0,o=i.length;a<o&&((n=i[a](n))&&!n.type&&t(14),n);a++);return n}finally{qe(r)}}function Pt(e){return e.ut!==void 0&&e.ut.length>0}function Ft(e,t){var n=e.ut||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function It(e,t){var n=Ke(),r=e.ut;if(r){for(var i=0,a=(r=r.slice()).length;i<a;i++)r[i](t);qe(n)}}function Lt(e,t,n,i){return n===void 0&&(n=`ObservableArray`),i===void 0&&(i=!1),r(),Zt((function(){var r=new or(n,t,i,!1);d(r.j,F,r);var a=new Proxy(r.j,ar);return r.v=a,e&&e.length&&r.ot(0,0,e),a}))}function O(e,t){typeof Array.prototype[e]==`function`&&(sr[e]=t(e))}function k(e){return function(){var t=this[F];t.st.reportObserved();var n=t.ft(t.j);return n[e].apply(n,arguments)}}function A(e){return function(t,n){var r=this,i=this[F];return i.st.reportObserved(),i.ft(i.j)[e]((function(e,i){return t.call(n,e,i,r)}))}}function Rt(e){return function(){var t=this,n=this[F];n.st.reportObserved();var r=n.ft(n.j),i=arguments[0];return arguments[0]=function(e,n,r){return i(e,n,r,t)},r[e].apply(r,arguments)}}function zt(e){return s(e)&&ur(e[F])}function Bt(e){return e[Symbol.toStringTag]=`MapIterator`,en(e)}function Vt(e){return e[Symbol.toStringTag]=`SetIterator`,en(e)}function Ht(e,t){if(g(e,F))return e;var n=t?.name??`ObservableObject`;return u(e,F,new vr(e,new Map,String(n),function(e){return e?e.defaultDecorator??Oe(e):void 0}(t))),e}function Ut(e){return _r[e]||(_r[e]={get:function(){return this[F].O(e)},set:function(t){return this[F].S(e,t)}})}function Wt(e){return!!s(e)&&yr(e[F])}function Gt(e,t,n){var r;(r=e.h[mn])==null||delete r[n]}function Kt(e){return{enumerable:!1,configurable:!0,get:function(){return this[F].ct(e)},set:function(t){this[F].ht(e,t)}}}function qt(e){rn(Cr.prototype,``+e,Kt(e))}function Jt(e){if(e>xr){for(var t=xr;t<e+100;t++)qt(t);xr=e}}function j(e,t,n){return new Cr(e,t,n)}function Yt(e,n){if(typeof e==`object`&&e){if(zt(e))return n!==void 0&&t(23),e[F].st;if(gr(e))return e.st;if(H(e)){if(n===void 0)return e.lt;var r=e.vt.get(n)||e.dt.get(n);return r||t(25,n,Xt(e)),r}if(Wt(e)){if(!n)return t(26);var i=e[F].j.get(n);return i||t(27,n,Xt(e)),i}if(gn(e)||Ln(e)||Gn(e))return e}else if(a(e)&&Gn(e[F]))return e[F];t(28)}function M(e,n){return e||t(29),n===void 0?gn(e)||Ln(e)||Gn(e)||H(e)||gr(e)?e:e[F]?e[F]:void t(24,e):M(Yt(e,n))}function Xt(e,t){var n;if(t!==void 0)n=Yt(e,t);else{if(lt(e))return e.name;n=Wt(e)||H(e)||gr(e)?M(e):Yt(e)}return n.tt}function Zt(e){var t=Ke(),n=ze(!0);et();try{return e()}finally{tt(),Be(n),qe(t)}}function Qt(e,t,n){return n===void 0&&(n=-1),function e(t,n,r,i,o){if(t===n)return t!==0||1/t==1/n;if(t==null||n==null)return!1;if(t!=t)return n!=n;var s=typeof t;if(s!==`function`&&s!==`object`&&typeof n!=`object`)return!1;var c=wr.call(t);if(c!==wr.call(n))return!1;switch(c){case`[object RegExp]`:case`[object String]`:return``+t==``+n;case`[object Number]`:return+t==+t?+t==0?1/t==1/n:+t==+n:+n!=+n;case`[object Date]`:case`[object Boolean]`:return+t==+n;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(t)===Symbol.valueOf.call(n);case`[object Map]`:case`[object Set]`:r>=0&&r++}t=$t(t),n=$t(n);var l=c===`[object Array]`;if(!l){if(typeof t!=`object`||typeof n!=`object`)return!1;var u=t.constructor,d=n.constructor;if(u!==d&&!(a(u)&&u instanceof u&&a(d)&&d instanceof d)&&`constructor`in t&&`constructor`in n)return!1}if(r===0)return!1;r<0&&(r=-1),o||=[];for(var f=(i||=[]).length;f--;)if(i[f]===t)return o[f]===n;if(i.push(t),o.push(n),l){if((f=t.length)!==n.length)return!1;for(;f--;)if(!e(t[f],n[f],r-1,i,o))return!1}else{var p=Object.keys(t),m=p.length;if(Object.keys(n).length!==m)return!1;for(var h=0;h<m;h++){var _=p[h];if(!g(n,_)||!e(t[_],n[_],r-1,i,o))return!1}}return i.pop(),o.pop(),!0}(e,t,n)}function $t(e){return zt(e)?e.slice():p(e)||H(e)||m(e)||gr(e)?Array.from(e.entries()):e}function en(e){return e[Symbol.iterator]=N,Object.assign(Object.create(Tr),e)}function N(){return this}Object.defineProperty(e,`__esModule`,{value:!0});var tn={},P=Object.assign,nn=Object.getOwnPropertyDescriptor,rn=Object.defineProperty,an=Object.prototype,on=[];Object.freeze(on);var sn={};Object.freeze(sn);var cn=typeof Proxy<`u`,ln=Object.toString(),un=function(){},dn=Object.getOwnPropertySymbols!==void 0,fn=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:dn?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,pn=Object.getOwnPropertyDescriptors||function(e){var t={};return fn(e).forEach((function(n){t[n]=nn(e,n)})),t},mn=Symbol(`mobx-stored-annotations`),F=Symbol(`mobx administration`),hn=function(){function e(e){e===void 0&&(e=`Atom`),this.tt=void 0,this.bt=0,this.F=new Set,this.$=0,this.U=R.P,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return nt(this)},t.reportChanged=function(){et(),rt(this),tt()},t.toString=function(){return this.tt},S(e,[{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();hn.pt=1,hn.yt=2,hn.wt=4;var gn=f(`Atom`,hn),_n={identity:function(e,t){return e===t},structural:function(e,t){return Qt(e,t)},default:function(e,t){return Object.is?Object.is(e,t):e===t?e!==0||1/e==1/t:e!=e&&t!=t},shallow:function(e,t){return Qt(e,t,1)}},vn=T({i:`override`,o:function(){return 0},s:function(){t(`'`+this.i+`' can only be used with 'makeObservable'`)},t:function(){console.warn(`'`+this.i+`' cannot be used with decorators - this is a no-op`)}}),yn=Oe(),bn={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};Object.freeze(bn);var xn=we(`observable`),Sn=we(`observable.ref`,{enhancer:ue}),I=we(`observable.shallow`,{enhancer:function(e,t,n){return e==null||Wt(e)||zt(e)||H(e)||gr(e)?e:Array.isArray(e)?L.array(e,{name:n,deep:!1}):c(e)?L.object(e,void 0,{name:n,deep:!1}):p(e)?L.map(e,{name:n,deep:!1}):m(e)?L.set(e,{name:n,deep:!1}):void 0}}),Cn=we(`observable.struct`,{enhancer:function(e,t){return Qt(e,t)?t:e}}),wn=T(xn);P(Ne,wn);var Tn,L=P(Ne,{box:function(e,t){var n=Me(t);return new Nn(e,D(n),n.name,!0,n.equals)},array:function(e,t){var n=Me(t);return(!1===z.useProxies||!1===n.proxy?j:Lt)(e,D(n),n.name)},map:function(e,t){var n=Me(t);return new pr(e,D(n),n.name)},set:function(e,t){var n=Me(t);return new hr(e,D(n),n.name)},object:function(e,t,n){return Zt((function(){return ht(!1===z.useProxies||!1===n?.proxy?Ht({},n):function(e,t){var n;return r(),(n=(e=Ht(e,t))[F]).v??(n.v=new Proxy(e,nr))}({},n),e,t)}))},ref:T(Sn),shallow:T(I),deep:wn,struct:T(Cn)}),En=be(`computed`),Dn=be(`computed.struct`,{equals:_n.structural}),On=function(e,t){if(se(t))return En.t(e,t);if(o(t))return oe(e,t,En);if(c(e))return T(be(`computed`,e));var n=c(t)?t:{};return n.get=e,n.name||=e.name||``,new Fn(n)};Object.assign(On,En),On.struct=T(Dn);var kn=0,An=1,jn=(Tn=nn((function(){}),`name`)?.configurable)!=null&&Tn,Mn={value:`action`,configurable:!0,writable:!1,enumerable:!1},Nn=function(e){function t(t,n,r,i,a){var o;return r===void 0&&(r=`ObservableValue`),a===void 0&&(a=_n.default),(o=e.call(this,r)||this).enhancer=void 0,o.tt=void 0,o.equals=void 0,o.jt=!1,o.et=void 0,o.ut=void 0,o.Ot=void 0,o.dehancer=void 0,o.enhancer=n,o.tt=r,o.equals=a,o.Ot=n(t,void 0,r),o}re(t,e);var n=t.prototype;return n.dehanceValue=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.set=function(e){(e=this.xt(e))!==z.UNCHANGED&&this.gt(e)},n.xt=function(e){if(jt(this)){var t=Nt(this,{object:this,type:ir,newValue:e});if(!t)return z.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.Ot,this.tt),this.equals(this.Ot,e)?z.UNCHANGED:e},n.gt=function(e){var t=this.Ot;this.Ot=e,this.reportChanged(),Pt(this)&&It(this,{type:ir,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.Ot)},n.St=function(e){return Mt(this,e)},n._t=function(e,t){return t&&e({observableKind:`value`,debugObjectName:this.tt,object:this,type:ir,newValue:this.Ot,oldValue:void 0}),Ft(this,e)},n.raw=function(){return this.Ot},n.toJSON=function(){return this.get()},n.toString=function(){return this.tt+`[`+this.Ot+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},t}(hn),Pn=f(`ObservableValue`,Nn),Fn=function(){function e(e){this.I=R.P,this.D=[],this.W=null,this.F=new Set,this.q=0,this.$=0,this.U=R.L,this.G=0,this.Ot=new Rn(null),this.tt=void 0,this.At=void 0,this.bt=0,this.derivation=void 0,this.kt=void 0,this.Mt=In.NONE,this.Et=void 0,this.Vt=void 0,this.Rt=void 0,this.Nt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.kt=Pe(`ComputedValue-setter`,e.set)),this.Vt=e.equals||(e.compareStructural||e.struct?_n.structural:_n.default),this.Et=e.context,this.Rt=e.requiresReaction,this.Nt=!!e.keepAlive}var n=e.prototype;return n.H=function(){(function(e){e.U===R.L&&(e.U=R.B,e.F.forEach((function(e){e.I===R.L&&(e.I=R.B,e.H())})))})(this)},n.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},n.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},n.get=function(){if(this.isComputing&&t(32,this.tt,this.derivation),z.inBatch!==0||this.F.size!==0||this.Nt){if(nt(this),He(this)){var e=z.trackingContext;this.Nt&&!e&&(z.trackingContext=this),this.trackAndCompute()&&function(e){e.U!==R.K&&(e.U=R.K,e.F.forEach((function(t){t.I===R.B?t.I=R.K:t.I===R.L&&(e.U=R.L)})))}(this),z.trackingContext=e}}else He(this)&&(this.Tt(),et(),this.Ot=this.Ct(!1),tt());var n=this.Ot;if(Ve(n))throw n.cause;return n},n.set=function(e){if(this.kt){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.kt.call(this.Et,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)},n.trackAndCompute=function(){var e=this.Ot,t=this.I===R.P,n=this.Ct(!0),r=t||Ve(e)||Ve(n)||!this.Vt(e,n);return r&&(this.Ot=n),r},n.Ct=function(e){this.isComputing=!0;var t,n=ze(!1);if(e)t=Ue(this,this.derivation,this.Et);else if(!0===z.disableErrorBoundaries)t=this.derivation.call(this.Et);else try{t=this.derivation.call(this.Et)}catch(e){t=new Rn(e)}return Be(n),this.isComputing=!1,t},n.X=function(){this.Nt||(We(this),this.Ot=void 0)},n._t=function(e,t){var n=this,r=!0,i=void 0;return ut((function(){var a=n.get();if(!r||t){var o=Ke();e({observableKind:`computed`,debugObjectName:n.tt,type:ir,object:n,newValue:a,oldValue:i}),qe(o)}r=!1,i=a}))},n.Tt=function(){},n.toString=function(){return this.tt+`[`+this.derivation.toString()+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},S(e,[{key:`isComputing`,get:function(){return _(this.bt,e.It)},set:function(t){this.bt=v(this.bt,e.It,t)}},{key:`isRunningSetter`,get:function(){return _(this.bt,e.Lt)},set:function(t){this.bt=v(this.bt,e.Lt,t)}},{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Fn.It=1,Fn.Lt=2,Fn.pt=4,Fn.yt=8,Fn.wt=16;var R,In,Ln=f(`ComputedValue`,Fn);(function(e){e[e.P=-1]=`NOT_TRACKING_`,e[e.L=0]=`UP_TO_DATE_`,e[e.B=1]=`POSSIBLY_STALE_`,e[e.K=2]=`STALE_`})(R||={}),function(e){e[e.NONE=0]=`NONE`,e[e.LOG=1]=`LOG`,e[e.BREAK=2]=`BREAK`}(In||={});var Rn=function(e){this.cause=void 0,this.cause=e},zn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`,`useProxies`],Bn=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Vn=!0,Hn=!1,z=function(){var e=n();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Vn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==new Bn().version&&(Vn=!1),Vn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Bn):(setTimeout((function(){Hn||t(35)}),1),new Bn)}(),Un=function(){function e(e,t,n,r){e===void 0&&(e=`Reaction`),this.tt=void 0,this.Pt=void 0,this.Kt=void 0,this.Bt=void 0,this.D=[],this.W=[],this.I=R.P,this.q=0,this.G=0,this.bt=0,this.Mt=In.NONE,this.tt=e,this.Pt=t,this.Kt=n,this.Bt=r}var t=e.prototype;return t.H=function(){this.Y()},t.Y=function(){this.isScheduled||(this.isScheduled=!0,z.pendingReactions.push(this),it())},t.J=function(){if(!this.isDisposed){et(),this.isScheduled=!1;var e=z.trackingContext;if(z.trackingContext=this,He(this)){this.isTrackPending=!0;try{this.Pt()}catch(e){this.Dt(e)}}z.trackingContext=e,tt()}},t.track=function(e){if(!this.isDisposed){et(),this.isRunning=!0;var t=z.trackingContext;z.trackingContext=this;var n=Ue(this,e,void 0);z.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&We(this),Ve(n)&&this.Dt(n.cause),tt()}},t.Dt=function(e){var t=this;if(this.Kt)this.Kt(e,this);else{if(z.disableErrorBoundaries)throw e;z.suppressReactionErrors||console.error(`[mobx] uncaught error in '`+this+`'`,e),z.globalReactionErrorHandlers.forEach((function(n){return n(e,t)}))}},t.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.isRunning||(et(),We(this),tt()))},t.Z=function(e){var t=this,n=function n(){t.dispose(),e==null||e.removeEventListener==null||e.removeEventListener(`abort`,n)};return e==null||e.addEventListener==null||e.addEventListener(`abort`,n),n[F]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(n[Symbol.dispose]=n),n},t.toString=function(){return`Reaction[`+this.tt+`]`},t.trace=function(){},S(e,[{key:`isDisposed`,get:function(){return _(this.bt,e.Wt)},set:function(t){this.bt=v(this.bt,e.Wt,t)}},{key:`isScheduled`,get:function(){return _(this.bt,e.qt)},set:function(t){this.bt=v(this.bt,e.qt,t)}},{key:`isTrackPending`,get:function(){return _(this.bt,e.Gt)},set:function(t){this.bt=v(this.bt,e.Gt,t)}},{key:`isRunning`,get:function(){return _(this.bt,e.Ht)},set:function(t){this.bt=v(this.bt,e.Ht,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Un.Wt=1,Un.qt=2,Un.Gt=4,Un.Ht=8,Un.wt=16;var Wn=function(e){return e()},Gn=f(`Reaction`,Un),Kn=de(`action`),qn=de(`action.bound`,{bound:!0}),B=de(`autoAction`,{autoAction:!0}),Jn=de(`autoAction.bound`,{autoAction:!0,bound:!0}),Yn=st(!1);Object.assign(Yn,Kn);var Xn=st(!0);Object.assign(Xn,B),Yn.bound=T(qn),Xn.bound=T(Jn);var Zn=function(e){return e()},V=0,Qn=function(e){function t(){var n;return n=e.call(this,`FLOW_CANCELLED`)||this,Object.setPrototypeOf(n,(this instanceof t?this.constructor:void 0).prototype),n.name=`FlowCancellationError`,n}return re(t,e),t.prototype.toString=function(){return`Error: `+this.message},t}(w(Error)),$n=ge(`flow`),er=ge(`flow.bound`,{bound:!0}),tr=Object.assign((function(e,t){if(se(t))return $n.t(e,t);if(o(t))return oe(e,t,$n);var n=e,r=n.name||`<unnamed flow>`,i=function(){var e,t=this,i=arguments,o=++V,s=Yn(r+` - runid: `+o+` - init`,n).apply(t,i),c=void 0,l=new Promise((function(t,n){function i(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.next).call(s,e)}catch(e){return n(e)}u(t)}function l(e){var t;c=void 0;try{t=Yn(r+` - runid: `+o+` - yield `+ d++,s.throw).call(s,e)}catch(e){return n(e)}u(t)}function u(e){if(!a(e?.then))return e.done?t(e.value):(c=Promise.resolve(e.value)).then(i,l);e.then(u,n)}var d=0;e=n,i(void 0)}));return l.cancel=Yn(r+` - runid: `+o+` - cancel`,(function(){try{c&&vt(c);var t=s.return(void 0),n=Promise.resolve(t.value);n.then(un,un),vt(n),e(new Qn)}catch(t){e(t)}})),l};return i.isMobXFlow=!0,i}),$n);tr.bound=T(er);var nr={has:function(e,t){return At(e).it(t)},get:function(e,t){return At(e).ct(t)},set:function(e,t,n){var r;return!!o(t)&&((r=At(e).ht(t,n,!0))==null||r)},deleteProperty:function(e,t){var n;return!!o(t)&&((n=At(e).Ut(t,!0))==null||n)},defineProperty:function(e,t,n){var r;return(r=At(e).l(t,n))==null||r},ownKeys:function(e){return At(e).rt()},preventExtensions:function(){t(13)}},rr=Symbol(`mobx-keys`),ir=`update`,ar={get:function(e,t){var n=e[F];return t===F?n:t===`length`?n.Ft():typeof t!=`string`||isNaN(t)?g(sr,t)?sr[t]:e[t]:n.ct(parseInt(t))},set:function(e,t,n){var r=e[F];return t===`length`&&r.Xt(n),typeof t==`symbol`||isNaN(t)?e[t]=n:r.ht(parseInt(t),n),!0},preventExtensions:function(){t(15)}},or=function(){function e(e,t,n,r){e===void 0&&(e=`ObservableArray`),this.zt=void 0,this.$t=void 0,this.st=void 0,this.j=[],this.et=void 0,this.ut=void 0,this.Jt=void 0,this.dehancer=void 0,this.v=void 0,this.Yt=0,this.zt=n,this.$t=r,this.st=new hn(e),this.Jt=function(e,n){return t(e,n,`ObservableArray[..]`)}}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.ft=function(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e},n.St=function(e){return Mt(this,e)},n._t=function(e,t){return t===void 0&&(t=!1),t&&e({observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:0,added:this.j.slice(),addedCount:this.j.length,removed:[],removedCount:0}),Ft(this,e)},n.Ft=function(){return this.st.reportObserved(),this.j.length},n.Xt=function(e){(typeof e!=`number`||isNaN(e)||e<0)&&t(`Out of range: `+e);var n=this.j.length;if(e!==n)if(e>n){for(var r=Array(e-n),i=0;i<e-n;i++)r[i]=void 0;this.ot(n,0,r)}else this.ot(e,n-e)},n.Zt=function(e,n){e!==this.Yt&&t(16),this.Yt+=n,this.$t&&n>0&&Jt(e+n+1)},n.ot=function(e,t,n){var r=this,i=this.j.length;if(e===void 0?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=arguments.length===1?i-e:t==null?0:Math.max(0,Math.min(t,i-e)),n===void 0&&(n=on),jt(this)){var a=Nt(this,{object:this.v,type:`splice`,index:e,removedCount:t,added:n});if(!a)return on;t=a.removedCount,n=a.added}if(n=n.length===0?n:n.map((function(e){return r.Jt(e,void 0)})),this.$t){var o=n.length-t;this.Zt(i,o)}var s=this.tn(e,t,n);return t===0&&n.length===0||this.nn(e,n,s),this.ft(s)},n.tn=function(e,t,n){var r;if(n.length<1e4)return(r=this.j).splice.apply(r,[e,t].concat(n));var i=this.j.slice(e,e+t),a=this.j.slice(e+t);this.j.length+=n.length-t;for(var o=0;o<n.length;o++)this.j[e+o]=n[o];for(var s=0;s<a.length;s++)this.j[e+n.length+s]=a[s];return i},n.in=function(e,t,n){var r=!this.zt&&!1,i=Pt(this),a=i||r?{observableKind:`array`,object:this.v,type:ir,debugObjectName:this.st.tt,index:e,newValue:t,oldValue:n}:null;this.st.reportChanged(),i&&It(this,a)},n.nn=function(e,t,n){var r=!this.zt&&!1,i=Pt(this),a=i||r?{observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.st.reportChanged(),i&&It(this,a)},n.ct=function(e){if(!(this.$t&&e>=this.j.length))return this.st.reportObserved(),this.Qt(this.j[e]);console.warn(`[mobx] Out of bounds read: `+e)},n.ht=function(e,n){var r=this.j;if(this.$t&&e>r.length&&t(17,e,r.length),e<r.length){var i=r[e];if(jt(this)){var a=Nt(this,{type:ir,object:this.v,index:e,newValue:n});if(!a)return;n=a.newValue}(n=this.Jt(n,i))!==i&&(r[e]=n,this.in(e,n,i))}else{for(var o=Array(e+1-r.length),s=0;s<o.length-1;s++)o[s]=void 0;o[o.length-1]=n,this.ot(r.length,0,o)}},e}(),sr={clear:function(){return this.splice(0)},replace:function(e){var t=this[F];return t.ot(0,t.j.length,e)},toJSON:function(){return this.slice()},splice:function(e,t){var n=[...arguments].slice(2),r=this[F];switch(arguments.length){case 0:return[];case 1:return r.ot(e);case 2:return r.ot(e,t)}return r.ot(e,t,n)},spliceWithArray:function(e,t,n){return this[F].ot(e,t,n)},push:function(){for(var e=this[F],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(e.j.length,0,n),e.j.length},pop:function(){return this.splice(Math.max(this[F].j.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=this[F],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(0,0,n),e.j.length},reverse:function(){return z.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort:function(){z.trackingDerivation&&t(37,`sort`);var e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove:function(e){var t=this[F],n=t.ft(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};O(`at`,k),O(`concat`,k),O(`flat`,k),O(`includes`,k),O(`indexOf`,k),O(`join`,k),O(`lastIndexOf`,k),O(`slice`,k),O(`toString`,k),O(`toLocaleString`,k),O(`toSorted`,k),O(`toSpliced`,k),O(`with`,k),O(`every`,A),O(`filter`,A),O(`find`,A),O(`findIndex`,A),O(`findLast`,A),O(`findLastIndex`,A),O(`flatMap`,A),O(`forEach`,A),O(`map`,A),O(`some`,A),O(`toReversed`,A),O(`reduce`,Rt),O(`reduceRight`,Rt);var cr,lr,ur=f(`ObservableArrayAdministration`,or),dr={},fr=`add`,pr=function(){function e(e,n,r){var i=this;n===void 0&&(n=le),r===void 0&&(r=`ObservableMap`),this.Jt=void 0,this.tt=void 0,this[F]=dr,this.vt=void 0,this.dt=void 0,this.lt=void 0,this.et=void 0,this.ut=void 0,this.dehancer=void 0,this.Jt=n,this.tt=r,a(Map)||t(18),Zt((function(){i.lt=ce(`ObservableMap.keys()`),i.vt=new Map,i.dt=new Map,e&&i.merge(e)}))}var n=e.prototype;return n.it=function(e){return this.vt.has(e)},n.has=function(e){var t=this;if(!z.trackingDerivation)return this.it(e);var n=this.dt.get(e);if(!n){var r=n=new Nn(this.it(e),ue,`ObservableMap.key?`,!1);this.dt.set(e,r),pt(r,(function(){return t.dt.delete(e)}))}return n.get()},n.set=function(e,t){var n=this.it(e);if(jt(this)){var r=Nt(this,{type:n?ir:fr,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.rn(e,t):this.en(e,t),this},n.delete=function(e){var t=this;if(jt(this)&&!Nt(this,{type:`delete`,object:this,name:e}))return!1;if(this.it(e)){var n=Pt(this),r=n?{observableKind:`map`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:this.vt.get(e).Ot,name:e}:null;return Dt((function(){var n;t.lt.reportChanged(),(n=t.dt.get(e))==null||n.gt(!1),t.vt.get(e).gt(void 0),t.vt.delete(e)})),n&&It(this,r),!0}return!1},n.rn=function(e,t){var n=this.vt.get(e);if((t=n.xt(t))!==z.UNCHANGED){var r=Pt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:ir,object:this,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),r&&It(this,i)}},n.en=function(e,t){var n=this;Dt((function(){var r,i=new Nn(t,n.Jt,`ObservableMap.key`,!1);n.vt.set(e,i),t=i.Ot,(r=n.dt.get(e))==null||r.gt(!0),n.lt.reportChanged()}));var r=Pt(this);r&&It(this,r?{observableKind:`map`,debugObjectName:this.tt,type:fr,object:this,name:e,newValue:t}:null)},n.get=function(e){return this.has(e)?this.Qt(this.vt.get(e).get()):this.Qt(void 0)},n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.keys=function(){return this.lt.reportObserved(),this.vt.keys()},n.values=function(){var e=this,t=this.keys();return Bt({next:function(){var n=t.next(),r=n.done;return{done:r,value:r?void 0:e.get(n.value)}}})},n.entries=function(){var e=this,t=this.keys();return Bt({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:[i,e.get(i)]}}})},n[Symbol.iterator]=function(){return this.entries()},n.forEach=function(e,t){for(var n,r=ee(this);!(n=r()).done;){var i=n.value;e.call(t,i[1],i[0],this)}},n.merge=function(e){var n=this;return H(e)&&(e=new Map(e)),Dt((function(){var r,i;c(e)?function(e){var t=Object.keys(e);if(!dn)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter((function(t){return an.propertyIsEnumerable.call(e,t)}))):t}(e).forEach((function(t){return n.set(t,e[t])})):Array.isArray(e)?e.forEach((function(e){return n.set(e[0],e[1])})):p(e)?(r=Object.getPrototypeOf(e),i=Object.getPrototypeOf(r),Object.getPrototypeOf(i)!==null&&t(19,e),e.forEach((function(e,t){return n.set(t,e)}))):e!=null&&t(20,e)})),this},n.clear=function(){var e=this;Dt((function(){Ge((function(){for(var t,n=ee(e.keys());!(t=n()).done;)e.delete(t.value)}))}))},n.replace=function(e){var n=this;return Dt((function(){for(var r,i=function(e){if(p(e)||H(e))return e;if(Array.isArray(e))return new Map(e);if(c(e)){var n=new Map;for(var r in e)n.set(r,e[r]);return n}return t(21,e)}(e),a=new Map,o=!1,s=ee(n.vt.keys());!(r=s()).done;){var l=r.value;if(!i.has(l))if(n.delete(l))o=!0;else{var u=n.vt.get(l);a.set(l,u)}}for(var d,f=ee(i.entries());!(d=f()).done;){var m=d.value,h=m[0],g=m[1],_=n.vt.has(h);if(n.set(h,g),n.vt.has(h)){var v=n.vt.get(h);a.set(h,v),_||(o=!0)}}if(!o)if(n.vt.size!==a.size)n.lt.reportChanged();else for(var y=n.vt.keys(),b=a.keys(),x=y.next(),S=b.next();!x.done;){if(x.value!==S.value){n.lt.reportChanged();break}x=y.next(),S=b.next()}n.vt=a})),this},n.toString=function(){return`[object ObservableMap]`},n.toJSON=function(){return Array.from(this)},n._t=function(e){return Ft(this,e)},n.St=function(e){return Mt(this,e)},S(e,[{key:`size`,get:function(){return this.lt.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Map`}}])}(),H=f(`ObservableMap`,pr),mr={},hr=function(){function e(e,n,r){var i=this;n===void 0&&(n=le),r===void 0&&(r=`ObservableSet`),this.tt=void 0,this[F]=mr,this.vt=new Set,this.st=void 0,this.ut=void 0,this.et=void 0,this.dehancer=void 0,this.Jt=void 0,this.tt=r,a(Set)||t(22),this.Jt=function(e,t){return n(e,t,r)},Zt((function(){i.st=ce(i.tt),e&&i.replace(e)}))}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.clear=function(){var e=this;Dt((function(){Ge((function(){for(var t,n=ee(e.vt.values());!(t=n()).done;)e.delete(t.value)}))}))},n.forEach=function(e,t){for(var n,r=ee(this);!(n=r()).done;){var i=n.value;e.call(t,i,i,this)}},n.add=function(e){var t=this;if(jt(this)){var n=Nt(this,{type:fr,object:this,newValue:e});if(!n)return this;e=n.newValue}if(!this.has(e)){Dt((function(){t.vt.add(t.Jt(e,void 0)),t.st.reportChanged()}));var r=Pt(this);r&&It(this,r?{observableKind:`set`,debugObjectName:this.tt,type:fr,object:this,newValue:e}:null)}return this},n.delete=function(e){var t=this;if(jt(this)&&!Nt(this,{type:`delete`,object:this,oldValue:e}))return!1;if(this.has(e)){var n=Pt(this),r=n?{observableKind:`set`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:e}:null;return Dt((function(){t.st.reportChanged(),t.vt.delete(e)})),n&&It(this,r),!0}return!1},n.has=function(e){return this.st.reportObserved(),this.vt.has(this.Qt(e))},n.entries=function(){var e=this.values();return Vt({next:function(){var t=e.next(),n=t.value,r=t.done;return r?{value:void 0,done:r}:{value:[n,n],done:r}}})},n.keys=function(){return this.values()},n.values=function(){this.st.reportObserved();var e=this,t=this.vt.values();return Vt({next:function(){var n=t.next(),r=n.done;return r?{value:void 0,done:r}:{value:e.Qt(n.value),done:r}}})},n.intersection=function(e){return m(e)&&!gr(e)?e.intersection(this):new Set(this).intersection(e)},n.union=function(e){return m(e)&&!gr(e)?e.union(this):new Set(this).union(e)},n.difference=function(e){return new Set(this).difference(e)},n.symmetricDifference=function(e){return m(e)&&!gr(e)?e.symmetricDifference(this):new Set(this).symmetricDifference(e)},n.isSubsetOf=function(e){return new Set(this).isSubsetOf(e)},n.isSupersetOf=function(e){return new Set(this).isSupersetOf(e)},n.isDisjointFrom=function(e){return m(e)&&!gr(e)?e.isDisjointFrom(this):new Set(this).isDisjointFrom(e)},n.replace=function(e){var n=this;return gr(e)&&(e=new Set(e)),Dt((function(){Array.isArray(e)||m(e)?(n.clear(),e.forEach((function(e){return n.add(e)}))):e!=null&&t(`Cannot initialize set from `+e)})),this},n._t=function(e){return Ft(this,e)},n.St=function(e){return Mt(this,e)},n.toJSON=function(){return Array.from(this)},n.toString=function(){return`[object ObservableSet]`},n[Symbol.iterator]=function(){return this.values()},S(e,[{key:`size`,get:function(){return this.st.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Set`}}])}(),gr=f(`ObservableSet`,hr),_r=Object.create(null),vr=function(){function e(e,t,n,r){t===void 0&&(t=new Map),r===void 0&&(r=yn),this.h=void 0,this.j=void 0,this.tt=void 0,this.un=void 0,this.lt=void 0,this.ut=void 0,this.et=void 0,this.v=void 0,this.p=void 0,this.on=void 0,this.sn=void 0,this.h=e,this.j=t,this.tt=n,this.un=r,this.lt=new hn(`ObservableObject.keys`),this.p=c(this.h)}var n=e.prototype;return n.O=function(e){return this.j.get(e).get()},n.S=function(e,t){var n=this.j.get(e);if(n instanceof Fn)return n.set(t),!0;if(jt(this)){var r=Nt(this,{type:ir,object:this.v||this.h,name:e,newValue:t});if(!r)return null;t=r.newValue}if((t=n.xt(t))!==z.UNCHANGED){var i=Pt(this),a=i?{type:ir,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),i&&It(this,a)}return!0},n.ct=function(e){return z.trackingDerivation&&!g(this.h,e)&&this.it(e),this.h[e]},n.ht=function(e,t,n){return n===void 0&&(n=!1),g(this.h,e)?this.j.has(e)?this.S(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.s(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.un,n)},n.it=function(e){if(!z.trackingDerivation)return e in this.h;this.sn||=new Map;var t=this.sn.get(e);return t||(t=new Nn(e in this.h,ue,`ObservableObject.key?`,!1),this.sn.set(e,t)),t.get()},n.o=function(e,n){if(!0===n&&(n=this.un),!1!==n){if(!(e in this.h)){var r;if((r=this.h[mn])!=null&&r[e])return;t(1,n.i,this.tt+`.`+e.toString())}for(var i=this.h;i&&i!==an;){var a=nn(i,e);if(a){var o=n.o(this,e,a,i);if(o===0)return;if(o===1)break}i=Object.getPrototypeOf(i)}Gt(this,0,e)}},n.s=function(e,t,n,r){if(r===void 0&&(r=!1),!0===n&&(n=this.un),!1===n)return this.l(e,t,r);var i=n.s(this,e,t,r);return i&&Gt(this,0,e),i},n.l=function(e,t,n){n===void 0&&(n=!1);try{et();var r=this.Ut(e);if(!r)return r;if(jt(this)){var i=Nt(this,{object:this.v||this.h,name:e,type:fr,newValue:t.value});if(!i)return null;var a=i.newValue;t.value!==a&&(t=te({},t,{value:a}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else rn(this.h,e,t);this.fn(e,t.value)}finally{tt()}return!0},n.g=function(e,t,n,r){r===void 0&&(r=!1);try{et();var i=this.Ut(e);if(!i)return i;if(jt(this)){var a=Nt(this,{object:this.v||this.h,name:e,type:fr,newValue:t});if(!a)return null;t=a.newValue}var o=Ut(e),s={configurable:!z.safeDescriptors||this.p,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.h,e,s))return!1}else rn(this.h,e,s);var c=new Nn(t,n,`ObservableObject.key`,!1);this.j.set(e,c),this.fn(e,c.Ot)}finally{tt()}return!0},n.m=function(e,t,n){n===void 0&&(n=!1);try{et();var r=this.Ut(e);if(!r)return r;if(jt(this)&&!Nt(this,{object:this.v||this.h,name:e,type:fr,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;var i=Ut(e),a={configurable:!z.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else rn(this.h,e,a);this.j.set(e,new Fn(t)),this.fn(e,void 0)}finally{tt()}return!0},n.Ut=function(e,t){if(t===void 0&&(t=!1),!g(this.h,e))return!0;if(jt(this)&&!Nt(this,{object:this.v||this.h,name:e,type:`remove`}))return null;try{var n;et();var r=Pt(this),i=this.j.get(e),a=void 0;if(!i&&r&&(a=nn(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof Nn&&(a=i.Ot),rt(i)),this.lt.reportChanged(),(n=this.sn)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&It(this,{type:`remove`,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{tt()}return!0},n._t=function(e){return Ft(this,e)},n.St=function(e){return Mt(this,e)},n.fn=function(e,t){var n,r=Pt(this);r&&r&&It(this,r?{type:fr,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.sn)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()},n.rt=function(){return this.lt.reportObserved(),fn(this.h)},n.nt=function(){return this.lt.reportObserved(),Object.keys(this.h)},e}(),yr=f(`ObservableObjectAdministration`,vr),br=Kt(0),U=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,!1===e}(),xr=0,Sr=function(){};cr=Sr,lr=Array.prototype,Object.setPrototypeOf?Object.setPrototypeOf(cr.prototype,lr):cr.prototype.__proto__===void 0?cr.prototype=lr:cr.prototype.__proto__=lr;var Cr=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray`),i===void 0&&(i=!1),a=e.call(this)||this,Zt((function(){var e=new or(r,n,i,!0);e.v=a,d(a,F,e),t&&t.length&&a.spliceWithArray(0,0,t),U&&Object.defineProperty(a,`0`,br)})),a}re(t,e);var n=t.prototype;return n.concat=function(){this[F].st.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map((function(e){return zt(e)?e.slice():e})))},n[Symbol.iterator]=function(){var e=this,t=0;return en({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},S(t,[{key:`length`,get:function(){return this[F].Ft()},set:function(e){this[F].Xt(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(Sr);Object.entries(sr).forEach((function(e){var t=e[0];t!==`concat`&&u(Cr.prototype,t,e[1])})),Jt(1e3);var wr=an.toString,Tr=n().Iterator?.prototype||{};[`Symbol`,`Map`,`Set`].forEach((function(e){n()[e]===void 0&&t(`MobX requires global '`+e+`' to be available or polyfilled`)})),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:ot,extras:{getDebugName:Xt},$mobx:F}),e.$mobx=F,e.FlowCancellationError=Qn,e.ObservableMap=pr,e.ObservableSet=hr,e.Reaction=Un,e._allowStateChanges=Re,e._allowStateChangesInsideComputed=ct,e._allowStateReadsEnd=Ye,e._allowStateReadsStart=Je,e._autoAction=Xn,e._endAction=Le,e._getAdministration=M,e._getGlobalState=function(){return z},e._interceptReads=function(e,t,n){var r;return H(e)||zt(e)||Pn(e)?r=M(e):Wt(e)&&(r=M(e,t)),r.dehancer=typeof t==`function`?t:n,function(){r.dehancer=void 0}},e._isComputingDerivation=function(){return z.trackingDerivation!==null},e._resetGlobalState=function(){var e=new Bn;for(var t in e)zn.indexOf(t)===-1&&(z[t]=e[t]);z.allowStateChanges=!z.enforceActions},e._startAction=Ie,e.action=Yn,e.autorun=ut,e.comparer=_n,e.computed=On,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((z.pendingReactions.length||z.inBatch||z.isRunningReactions)&&t(36),Hn=!0,Vn){var e=n();--e.__mobxInstanceCount==0&&(e.__mobxGlobals=void 0),z=new Bn}}();var r,i,a=e.useProxies,o=e.enforceActions;if(a!==void 0&&(z.useProxies=a===`always`||a!==`never`&&typeof Proxy<`u`),a===`ifavailable`&&(z.verifyProxies=!0),o!==void 0){var s=o===`always`?`always`:o===`observed`;z.enforceActions=s,z.allowStateChanges=!0!==s&&s!==`always`}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach((function(t){t in e&&(z[t]=!!e[t])})),z.allowStateReads=!z.observableRequiresReaction,e.reactionScheduler&&(r=e.reactionScheduler,i=Wn,Wn=function(e){return r((function(){return i(e)}))})},e.createAtom=ce,e.defineProperty=function(e,n,r){if(Wt(e))return e[F].l(n,r);t(39)},e.entries=function(e){return Wt(e)?Ct(e).map((function(t){return[t,e[t]]})):H(e)?Ct(e).map((function(t){return[t,e.get(t)]})):gr(e)?Array.from(e.entries()):zt(e)?e.map((function(e,t){return[t,e]})):void t(7)},e.extendObservable=ht,e.flow=tr,e.flowResult=function(e){return e},e.get=function(e,n){if(wt(e,n))return Wt(e)?e[F].ct(n):H(e)?e.get(n):zt(e)?e[n]:void t(11)},e.getAtom=Yt,e.getDebugName=Xt,e.getDependencyTree=function(e,t){return gt(Yt(e,t))},e.getObserverTree=function(e,t){return _t(Yt(e,t))},e.has=wt,e.intercept=function(e,t,n){return a(n)?function(e,t,n){return M(e,t).St(n)}(e,t,n):function(e,t){return M(e).St(t)}(e,t)},e.isAction=lt,e.isBoxedObservable=Pn,e.isComputed=function(e){return bt(e)},e.isComputedProp=function(e,t){return bt(e,t)},e.isFlow=yt,e.isFlowCancellationError=function(e){return e instanceof Qn},e.isObservable=St,e.isObservableArray=zt,e.isObservableMap=H,e.isObservableObject=Wt,e.isObservableProp=function(e,t){return xt(e,t)},e.isObservableSet=gr,e.keys=Ct,e.makeAutoObservable=function(e,t,n){return c(e)?ht(e,e,t,n):(Zt((function(){var r=Ht(e,n)[F];if(!e[rr]){var i=Object.getPrototypeOf(e),a=new Set([].concat(fn(e),fn(i)));a.delete(`constructor`),a.delete(F),u(i,rr,a)}e[rr].forEach((function(e){return r.o(e,!t||!(e in t)||t[e])}))})),e)},e.makeObservable=function(e,t,n){return Zt((function(){var r=Ht(e,n)[F];t??=function(e){return g(e,mn)||u(e,mn,te({},e[mn])),e[mn]}(e),fn(t).forEach((function(e){return r.o(e,t[e])}))})),e},e.observable=L,e.observe=function(e,t,n,r){return a(n)?function(e,t,n,r){return M(e,t)._t(n,r)}(e,t,n,r):function(e,t,n){return M(e)._t(t,n)}(e,t,n)},e.onBecomeObserved=ft,e.onBecomeUnobserved=pt,e.onReactionError=function(e){return z.globalReactionErrorHandlers.push(e),function(){var t=z.globalReactionErrorHandlers.indexOf(e);t>=0&&z.globalReactionErrorHandlers.splice(t,1)}},e.override=vn,e.ownKeys=Tt,e.reaction=function(e,t,n){function r(){if(p=!1,!h.isDisposed){var t=!1,r=s;h.track((function(){var n=Re(!1,(function(){return e(h)}));t=f||!m(s,n),s=n})),(f&&n.fireImmediately||!f&&t)&&l(s,r,h),f=!1}}var i;n===void 0&&(n=sn);var a,o,s,c=n.name??`Reaction`,l=Yn(c,n.onError?(a=n.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){a.call(this,e)}}):t),u=!n.scheduler&&!n.delay,d=dt(n),f=!0,p=!1,m=n.compareStructural?_n.structural:n.equals||_n.default,h=new Un(c,(function(){f||u?r():p||(p=!0,d(r))}),n.onError,n.requiresObservable);return(i=n)!=null&&(i=i.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Wt(e)?e[F].Ut(n):H(e)||gr(e)?e.delete(n):zt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=ct,e.set=function e(n,r,i){if(arguments.length!==2||gr(n))Wt(n)?n[F].ht(r,i):H(n)?n.set(r,i):gr(n)?n.add(r):zt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(`Invalid index: '`+r+`'`),et(),r>=n.length&&(n.length=r+1),n[r]=i,tt()):t(8);else{et();var a=r;try{for(var o in a)e(n,o,a[o])}finally{tt()}}},e.spy=ot,e.toJS=function(e){return function e(t,n){if(typeof t!=`object`||!t||t instanceof Date||!St(t))return t;if(Pn(t)||Ln(t))return e(t.get(),n);if(n.has(t))return n.get(t);if(zt(t)){var r=Et(n,t,Array(t.length));return t.forEach((function(t,i){r[i]=e(t,n)})),r}if(gr(t)){var i=Et(n,t,new Set);return t.forEach((function(t){i.add(e(t,n))})),i}if(H(t)){var a=Et(n,t,new Map);return t.forEach((function(t,r){a.set(r,e(t,n))})),a}var o=Et(n,t,{});return Tt(t).forEach((function(r){an.propertyIsEnumerable.call(t,r)&&(o[r]=e(t[r],n))})),o}(e,new Map)},e.trace=function(){},e.transaction=Dt,e.untracked=Ge,e.values=function(e){return Wt(e)?Ct(e).map((function(t){return e[t]})):H(e)?Ct(e).map((function(t){return e.get(t)})):gr(e)?Array.from(e.values()):zt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?kt(e,t):Ot(e,t,n||{})}})),jw=me((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1:function(e,t){return`Cannot apply '`+e+`' to '`+t.toString()+`': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,17:function(e,t){return`[mobx.array] Index out of bounds, `+e+` is larger than `+t},18:`mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js`,19:function(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20:function(e){return`Cannot initialize map from `+e},21:function(e){return`Cannot convert to map from '`+e+`'`},22:`mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js`,23:`It is not possible to get index atoms from arrays`,24:function(e){return`Cannot obtain administration from `+e},25:function(e,t){return`the entry '`+e+`' does not exist in the observable map '`+t+`'`},26:`please specify a property`,27:function(e,t){return`no observable property '`+e.toString()+`' found on the observable object '`+t+`'`},28:function(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32:function(e,t){return`Cycle detected in computation `+e+`: `+t},33:function(e){return`The setter of computed value '`+e+`' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34:function(e){return`[ComputedValue '`+e+`'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37:function(e){return"[mobx] `observableArray."+e+"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()."+e+"()` instead"},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`};function n(e){var n=[...arguments].slice(1),r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] `+r)}var r={};function i(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:r}var a=Object.assign,o=Object.getOwnPropertyDescriptor,s=Object.defineProperty,c=Object.prototype,l=[];Object.freeze(l);var u={};Object.freeze(u);var d=typeof Proxy<`u`,f=Object.toString();function p(){d||n("`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`")}function m(e){I.verifyProxies&&n(`MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to `+e)}function h(){return++I.mobxGuid}function g(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var _=function(){};function v(e){return typeof e==`function`}function y(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===f}function S(e){var t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function ee(e,t,n){s(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function te(e,t,n){s(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function ne(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return b(e)&&e[n]===!0}}function re(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function ie(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}var ae=Object.getOwnPropertySymbols!==void 0;function w(e){var t=Object.keys(e);if(!ae)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter(function(t){return c.propertyIsEnumerable.call(e,t)})):t}var T=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:ae?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function oe(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function se(e){return e===null?null:typeof e==`object`?``+e:e}function ce(e,t){return c.hasOwnProperty.call(e,t)}var le=Object.getOwnPropertyDescriptors||function(e){var t={};return T(e).forEach(function(n){t[n]=o(e,n)}),t};function ue(e,t){return!!(e&t)}function de(e,t,n){return n?e|=t:e&=~t,e}function fe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function pe(e,t,n){if(be())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&xe(i,n.prototype),i}function me(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,Ce(r.key),r)}}function he(e,t,n){return t&&me(e.prototype,t),n&&me(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function ge(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=we(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
149
149
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function E(){return E=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},E.apply(null,arguments)}function _e(e){return _e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_e(e)}function ve(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,xe(e,t)}function ye(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function be(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(be=function(){return!!e})()}function xe(e,t){return xe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},xe(e,t)}function Se(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ce(e){var t=Se(e,`string`);return typeof t==`symbol`?t:t+``}function we(e,t){if(e){if(typeof e==`string`)return fe(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?fe(e,t):void 0}}function Te(e){var t=typeof Map==`function`?new Map:void 0;return Te=function(e){if(e===null||!ye(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return pe(e,arguments,_e(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),xe(n,e)},Te(e)}var Ee=Symbol(`mobx-stored-annotations`);function De(e){function t(t,n){if(je(n))return e.decorate_20223_(t,n);Oe(t,n,e)}return Object.assign(t,e)}function Oe(e,t,r){ce(e,Ee)||ee(e,Ee,E({},e[Ee])),qe(r)&&!ce(e[Ee],t)&&n(`'`+(e.constructor.name+`.prototype.`+t.toString())+`' is decorated with 'override', but no such decorated member was found on prototype.`),ke(e,r,t),qe(r)||(e[Ee][t]=r)}function ke(e,t,r){if(!qe(t)&&ce(e[Ee],r)){var i=e.constructor.name+`.prototype.`+r.toString(),a=e[Ee][r].annotationType_,o=t.annotationType_;n(`Cannot apply '@`+o+`' to '`+i+`':`+(`
|
|
@@ -175,31 +175,31 @@ The target is already observable of different type.
|
|
|
175
175
|
Extending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);var r=t?.name??(x(e)?`ObservableObject`:e.constructor.name)+`@`+h();return ee(e,D,new Yi(e,new Map,String(r),Lt(t))),e}var Zi=ne(`ObservableObjectAdministration`,Yi);function Qi(e){return qi[e]||(qi[e]={get:function(){return this[D].getObservablePropValue_(e)},set:function(t){return this[D].setObservablePropValue_(e,t)}})}function $i(e){return b(e)?Zi(e[D]):!1}function ea(e,t,n){var r;e.appliedAnnotations_[n]=t,(r=e.target_[Ee])==null||delete r[n]}function ta(e,t,r){if(Sa(t)||n(`Cannot annotate '`+e.name_+`.`+r.toString()+`': Invalid annotation.`),!qe(t)&&ce(e.appliedAnnotations_,r)){var i=e.name_+`.`+r.toString(),a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '`+o+`' to '`+i+`':`+(`
|
|
176
176
|
The field is already annotated with '`+a+`'.`)+`
|
|
177
177
|
Re-annotating fields is not allowed.
|
|
178
|
-
Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),ia=0,aa=function(){};function oa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}oa(aa,Array.prototype);var sa=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ma(function(){var e=new Oi(r,n,i,!0);e.proxy_=a,te(a,D,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[D].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fi(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return ba({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},he(t,[{key:`length`,get:function(){return this[D].getArrayLength_()},set:function(e){this[D].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(aa);Object.entries(Ai).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&ee(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[D].get_(e)},set:function(t){this[D].set_(e,t)}}}function la(e){s(sa.prototype,``+e,ca(e))}function ua(e){if(e>ia){for(var t=ia;t<e+100;t++)la(t);ia=e}}ua(1e3);function da(e,t,n){return new sa(e,t,n)}function G(e,t){if(typeof e==`object`&&e){if(Fi(e))return t!==void 0&&n(23),e[D].atom_;if(Gi(e))return e.atom_;if(Bi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,pa(e)),r}if($i(e)){if(!t)return n(26);var i=e[D].values_.get(t);return i||n(27,t,pa(e)),i}if(Pe(e)||tn(e)||z(e))return e}else if(v(e)&&z(e[D]))return e[D];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Pe(e)||tn(e)||z(e)||Bi(e)||Gi(e))return e;if(e[D])return e[D];n(24,e)}function pa(e,t){var n;if(t!==void 0)n=G(e,t);else if(sr(e))return e.name;else n=$i(e)||Bi(e)||Gi(e)?fa(e):G(e);return n.name_}function ma(e){var t=F(),n=Xt(!0);An();try{return e()}finally{jn(),Zt(n),hn(t)}}var ha=c.toString;function ga(e,t,n){return n===void 0&&(n=-1),_a(e,t,n)}function _a(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=ha.call(e);if(o!==ha.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=va(e),t=va(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!_a(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(ce(t,m)&&_a(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function va(e){return Fi(e)?e.slice():re(e)||Bi(e)||C(e)||Gi(e)?Array.from(e.entries()):e}var ya=i().Iterator?.prototype||{};function ba(e){return e[Symbol.iterator]=xa,Object.assign(Object.create(ya),e)}function xa(){return this}function Sa(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:pa},$mobx:D}),e.$mobx=D,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=Ln,e._allowStateChanges=M,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=_n,e._allowStateReadsStart=gn,e._autoAction=ar,e._endAction=Yt,e._getAdministration=fa,e._getGlobalState=wn,e._interceptReads=Fr,e._isComputingDerivation=sn,e._resetGlobalState=Tn,e._startAction=j,e.action=ir,e.autorun=cr,e.comparer=Be,e.computed=Ht,e.configure=br,e.createAtom=Fe,e.defineProperty=Qr,e.entries=qr,e.extendObservable=U,e.flow=jr,e.flowResult=Nr,e.get=Zr,e.getAtom=G,e.getDebugName=pa,e.getDependencyTree=xr,e.getObserverTree=Cr,e.has=Xr,e.intercept=Ir,e.isAction=sr,e.isBoxedObservable=en,e.isComputed=Br,e.isComputedProp=Vr,e.isFlow=Pr,e.isFlowCancellationError=Or,e.isObservable=Ur,e.isObservableArray=Fi,e.isObservableMap=Bi,e.isObservableObject=$i,e.isObservableProp=Wr,e.isObservableSet=Gi,e.keys=Gr,e.makeAutoObservable=Ci,e.makeObservable=xi,e.observable=A,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Rn,e.override=Ke,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=Jn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=mn,e.values=Kr,e.when=li})),Mw=me(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Aw():t.exports=jw()}))();function Nw(e){if(Array.isArray(e))return Object.freeze(e.map(Nw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Nw(r);return Object.freeze(t)}return e}function Pw(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 Fw(e){return typeof e==`string`?e:String(e)}function Iw(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 Lw(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")`)}function Rw(e,t){if(!(e instanceof Ar))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function zw(e){return{fn:(t=>Rw(t,e)),argTypes:[`liftable`],returnType:`T`}}function Bw(e){return{fn:((t,n)=>Rw(n,new H({[e]:N.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Vw(e,t){return new H({[e]:t})}function Hw(){let e={};for(let t of lr)e[t]=zw(Vw(t,!0)),e[`not_${t}`]=zw(Vw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=zw(Vw(n,!0));return e}const Uw={fn:((e,t)=>Rw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ww={fn:((e,t)=>Rw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Gw(){return{fg:Bw(`color`),bg:Bw(`bgcolor`),...Hw(),link:Ww,style:Uw}}function Kw(e,t){if(!Dn.test(e.trim()))throw TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`);return On(e)}function qw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Jw(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const Yw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`darken`),Jw(t,`darken`,`levels`)).hex)),Xw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`lighten`),-Jw(t,`lighten`,`levels`)).hex)),Zw={min:0,max:100,note:`0 = from, 100 = toward`},Qw=qw([`string`,`string`,`float`],((e,t,n)=>cn(Kw(e,`mix`),Kw(t,`mix`),Jw(n,`mix`,`percentage`,Zw)/100).hex)),$w={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},eT=qw([`string`],(e=>In(Kw(e,`contrastOn`)).hex)),tT=qw([`string`,`string`,`float`],((e,t,n)=>zn(Kw(e,`readableOn`),Kw(t,`readableOn`),Jw(n,`readableOn`,`ratio`,$w)).hex)),nT={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function rT(){let e={};for(let[t,n]of Object.entries(nT)){let r=t;e[n]=qw([`string`,`float`],((e,t)=>{let i={...gn,[r]:Jw(t,n,`amount`)};return L.fromRgba(Kw(e,n)).applyKey(i).toRgba().hex}))}return e}function iT(){return{darken:Yw,lighten:Xw,mix:Qw,contrastOn:eT,readableOn:tT,...rT()}}function aT(e,t){if(e.length===0)throw RangeError(`ramp needs at least one stop after the easing: ramp <value> <easing> <position> <color> …`);if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:kn(t,e[r+1])});return n}function oT(e){return{color:{fn:(t=>kn(e(),t).hex),argTypes:[`string`],returnType:`string`},ramp:{fn:((...t)=>{if(t.length<2)throw RangeError(`ramp needs a value and an easing before its stops (got ${t.length}): ramp <value> "linear"|"step" <position> <color> …`);let[n,r,...i]=t;return new ar(ir(r),aT(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function sT(){return{...Gw(),...iT()}}new H({color:`red`,dim:!0});const cT=/^(?:(?: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,lT=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function uT(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(cT);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(lT);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 dT(e){let t=e.match(lT);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 fT(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 pT(e){return e.toLocaleString()}const mT=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hT=mT.length;function gT(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*(hT-1));o+=mT[t]}return o}function _T(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 vT=li(),yT=[...pi];function bT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>fT(e),argTypes:[`string`]},int:{fn:e=>Iw(e),argTypes:[`value`]},string:{fn:e=>Fw(e),argTypes:[`value`]},bool:{fn:e=>Lw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>vT,argTypes:[]},styles:{fn:()=>yT,argTypes:[]},sparkline:{fn:(e,t)=>gT(_T(e),t),argTypes:[`string`,`int`]}}}function xT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>pT(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>uT(e),argTypes:[`string`]},shortenModelName:{fn:e=>dT(e),argTypes:[`string`]}}}function ST(e,t=()=>new Date){return Eu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...mf(),...wm(),...ep(),...Sp(),...of(t),...Yu(),...Of(),...sT(),...bT(),...xT(t),...e??{}}})}function CT(e){return wT(e,new Set(e.names()),``)}function wT(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.getKind(a)===`document`?TT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return wT(e,t,a)}})}function TT(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const ET=/\r\n|\r|\n/g,DT=e=>X(e.replace(ET,` `).trim());function OT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(ET,` `))}}const kT=e=>{try{return X(JSON.parse(e))}catch(e){return Q(`JSON parse failed: ${e.message}`)}};function AT(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function jT(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]}"`)}}function MT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Ee({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?X(n.stdout):Q(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function NT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return X(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return Q(`file unreadable: ${e}`)}}}}function PT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?Q(`${r.reason} in ${n}`):r}const FT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],IT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],LT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],RT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function zT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>FT[e.getMonth()]],[`Monday`,e=>LT[e.getDay()]],[`Jan`,e=>IT[e.getMonth()]],[`Mon`,e=>RT[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 BT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function VT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=BT[t];try{return GT(r,e)}catch{return KT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ib(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ib(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ib(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ib(e.stashCount,0)}}var HT=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}},UT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:se(()=>{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&&(oe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())oe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GT(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`?Fw(e):t===`number`?Iw(e):Lw(e)}function KT(e){return e===`number`?0:e===`boolean`?!1:``}var qT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new HT;ttlMgr=new UT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fC;abort=new AbortController;engine=ST();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pw(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,MT(t,this.abort.signal),AT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,NT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,DT,t.default,n);case`regex`:return this.scalarPublisher(e,OT(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=PT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ib(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=PT(i,kT,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=CT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return zT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,zT(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=BT[t.field],r=t.varDefault===void 0?KT(n):GT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,VT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`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=WT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GT(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(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mw.reaction)(()=>{let t=CT(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,Mw.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KT(t))}}defaultFor(e){try{return GT(this.defaultEmptyValue,e)}catch{return KT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function JT(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function YT(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function XT(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}const ZT=Symbol(`cc-candybar.fillDemand`);function QT(e,t){return e[ZT]=t,e}function $T(e){return e[ZT]}function eE(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=YT(e,o).pad(s);if(n===`auto`)return[c];let l={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[QT(c,l)]:(XT(c,n,l),[c])}const tE=/\x1b\[[0-9;]*m|\x1b\]8;;[^\x07\x1b]*(?:\x1b\\|\x07)/g;function nE(e){return k(e.replace(tE,``))}function rE(e,t){let n=[];for(let t of e){let e=$T(t);e!==void 0&&n.push({cell:t,how:e})}if(n.length===0||!Number.isFinite(t.width))return e;let r=yx(e,t).split(`
|
|
179
|
-
`);if(r.length>1)return e;let i=Math.max(0,t.width-nE(r[0]??``)),a=Math.floor(i/n.length),o=i-a*n.length;return n.forEach(({cell:e,how:t},r)=>{let i=a+(r===n.length-1?o:0);XT(e,e.cellLength+i,t)}),e}const iE=new Map,aE=new Map;function oE(e){let t=ai(e),n=iE.get(t);if(n!==void 0)return n;let r=Kn(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 iE.set(t,r),r}function sE(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=aE.get(n);if(r!==void 0)return r;let i=tr(e,t);return aE.set(n,i),i}function cE(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=lE(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=lE([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function lE(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>uE(e,t)):e,r=Ar.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 uE(e,t){let n=e.copy();return n.style=t.add(e.style),n}var dE=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function fE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=pE(o,c),d=u===void 0?i:mE(n,u,`bg`);l.bg=d;let f=pE(s,c),p=f===void 0?a(d):mE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function pE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function mE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new dE(t,n,e.message):e}}const hE=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function gE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,_E(e,a,o,n,r));return i}function _E(e,t,n,r,i){if(kg(n)){let[a,o]=Ag(n);return vE(r.get(n.persistWhen)??n.persistWhen,n.set,_E(e,t,a,r,i),_E(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...N_(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=hE.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:[...N_(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:[...N_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:bE(e,n.copy,t)}:`open`in n?{kind:`open`,target:bE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function vE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function yE(e,t){return e.kind===`dual`?Si(xE(t,e.selector))===!0?e.durable:e.session:e}function bE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function xE(e,t){return e.has(t)?Fw(e.read(t)):``}function SE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function CE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function wE(e,t){return Math.max(e.members.indexOf(xE(t,e.stateVar)),0)}function TE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(wE(e,r)+1)%e.members.length];return{effects:[{verb:Fy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Iy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ly,args:[SE(e.text,CT(r))]}],active:!1};case`open`:return{effects:[{verb:Ry,args:[SE(e.target,CT(r))]}],active:!1};case`persist-literal`:{let t=xE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(wE(e,r)+1)%e.members.length];return{effects:[{verb:Hy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Uy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Wy,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ky,args:[i]}],active:!1};case`redo`:return{effects:[{verb:qy,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Yy,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Xy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Gy,args:[i,e.key,Qm(e.op)]}],active:!1};case`dual`:{let a=yE(e,r),{effects:o,active:s}=TE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Gy,args:[i,e.key,Qm(r)]}],active:!1}}}}function EE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:cc(`action "${e}"`,n,t.members.length,wE(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 DE(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}=EE(e,yE(r,i),t,i),{effects:s,active:c}=TE(r,a,o,i,xE(i,`session.id`));return CE(a,$y(s),c)}function OE(e){return{action:{fn:(t,...n)=>DE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function kE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(Js(e,t))})}function AE(e,t){return kE(e.palette,ec(e.palette,e.disclosure,[t]))}function jE(){return{current:null}}function ME(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 NE(e){return new Ar(e).cellLength}function PE(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 FE(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function IE(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 LE(e,t){let n=e.compiled.get(t),r=n&&yE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function RE(e,t,n,r,i,a,o){let s=LE(a,e),c=a.compiled.get(e),l=a.store,u=xE(l,`session.id`),d=`stateVar`in s?xE(l,s.stateVar):void 0,f=s.options.map(NE),p=i?Math.max(1,Iw(l.read(`term.cols`))-vx(a.stripStyle)-2*a.padding):1/0,m=NE(`✕`)+1,h=NE(`←`)+1+NE(`→`)+1,g=PE(f,p,m),_=g.length>1?PE(f,p,m+h):g,v=parseInt(xE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>$y([{verb:Fy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),ee=$y([{verb:Fy,args:[u,...S]}]),te=r?[{verb:Fy,args:[u,...S]}]:[],ne=e=>{let{effects:t}=TE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?$y([{verb:Fy,args:[...n.args,...r?S:[]]}]):$y([...t,...te])},re=[CE(`✕`,ee,!1)];y>0&&re.push(CE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];re.push(CE(t,ne(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&re.push(CE(`→`,x(y+1),!1)),FE(re,i)}function zE(e,t){return{picker:{fn:(n,r,i,a)=>{let o=IE(e,r,`set-int`,`an int action ({ set, int: true })`);return RE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>AE(ME(t,`{{ picker }}`),{...e,distribution:Rs(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const BE=Symbol(`cc-candybar.menuDrop`);function VE(e){return e.flatMap(e=>e[BE]??[])}function HE(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Em(i.segName,e,n.key),s=km(o),c=Tm(e),l=xE(a.store,o)===c,u=xE(a.store,`session.id`),d=l?oc:c,f=CE(cc(`{{ menu "${e}" }}`,t,2,+!!l),$y([{verb:Fy,args:[u,o,d,s,`0`]}]),!1);return f[BE]=l?[RE(e,{key:s,stateVar:s},[[o,oc],[s,`0`]],n.closeOnPick,n.paged,a,e=>AE(i,{...e,distribution:n.distribution}))]:[],f}const UE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function WE(e,t){let n=t[t.length-1],r=UE(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:Nm(r??{})}}function GE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=WE(t,n);return HE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function KE(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=qE(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new Ar(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=Ar.fromFragments(c);return l.end=``,l.noWrap=!0,l}function qE(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function JE(e){let t={fn:(()=>{let t=ME(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`},n=oT(()=>ME(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),r={fn:((e,t,r,i,a,o,...s)=>KE({value:e,max:t,width:r,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(n.ramp.fn(e,o,...YE(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...n,bgOf:t,gauge:r}}function YE(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function XE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
178
|
+
Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),ia=0,aa=function(){};function oa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}oa(aa,Array.prototype);var sa=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ma(function(){var e=new Oi(r,n,i,!0);e.proxy_=a,te(a,D,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[D].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fi(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return ba({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},he(t,[{key:`length`,get:function(){return this[D].getArrayLength_()},set:function(e){this[D].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(aa);Object.entries(Ai).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&ee(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[D].get_(e)},set:function(t){this[D].set_(e,t)}}}function la(e){s(sa.prototype,``+e,ca(e))}function ua(e){if(e>ia){for(var t=ia;t<e+100;t++)la(t);ia=e}}ua(1e3);function da(e,t,n){return new sa(e,t,n)}function G(e,t){if(typeof e==`object`&&e){if(Fi(e))return t!==void 0&&n(23),e[D].atom_;if(Gi(e))return e.atom_;if(Bi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,pa(e)),r}if($i(e)){if(!t)return n(26);var i=e[D].values_.get(t);return i||n(27,t,pa(e)),i}if(Pe(e)||tn(e)||z(e))return e}else if(v(e)&&z(e[D]))return e[D];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Pe(e)||tn(e)||z(e)||Bi(e)||Gi(e))return e;if(e[D])return e[D];n(24,e)}function pa(e,t){var n;if(t!==void 0)n=G(e,t);else if(sr(e))return e.name;else n=$i(e)||Bi(e)||Gi(e)?fa(e):G(e);return n.name_}function ma(e){var t=F(),n=Xt(!0);An();try{return e()}finally{jn(),Zt(n),hn(t)}}var ha=c.toString;function ga(e,t,n){return n===void 0&&(n=-1),_a(e,t,n)}function _a(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=ha.call(e);if(o!==ha.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=va(e),t=va(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!_a(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(ce(t,m)&&_a(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function va(e){return Fi(e)?e.slice():re(e)||Bi(e)||C(e)||Gi(e)?Array.from(e.entries()):e}var ya=i().Iterator?.prototype||{};function ba(e){return e[Symbol.iterator]=xa,Object.assign(Object.create(ya),e)}function xa(){return this}function Sa(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:pa},$mobx:D}),e.$mobx=D,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=Ln,e._allowStateChanges=M,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=_n,e._allowStateReadsStart=gn,e._autoAction=ar,e._endAction=Yt,e._getAdministration=fa,e._getGlobalState=wn,e._interceptReads=Fr,e._isComputingDerivation=sn,e._resetGlobalState=Tn,e._startAction=j,e.action=ir,e.autorun=cr,e.comparer=Be,e.computed=Ht,e.configure=br,e.createAtom=Fe,e.defineProperty=Qr,e.entries=qr,e.extendObservable=U,e.flow=jr,e.flowResult=Nr,e.get=Zr,e.getAtom=G,e.getDebugName=pa,e.getDependencyTree=xr,e.getObserverTree=Cr,e.has=Xr,e.intercept=Ir,e.isAction=sr,e.isBoxedObservable=en,e.isComputed=Br,e.isComputedProp=Vr,e.isFlow=Pr,e.isFlowCancellationError=Or,e.isObservable=Ur,e.isObservableArray=Fi,e.isObservableMap=Bi,e.isObservableObject=$i,e.isObservableProp=Wr,e.isObservableSet=Gi,e.keys=Gr,e.makeAutoObservable=Ci,e.makeObservable=xi,e.observable=A,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Rn,e.override=Ke,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=Jn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=mn,e.values=Kr,e.when=li})),Mw=me(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Aw():t.exports=jw()}))();function Nw(e){if(Array.isArray(e))return Object.freeze(e.map(Nw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Nw(r);return Object.freeze(t)}return e}function Pw(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 Fw(e){return typeof e==`string`?e:String(e)}function Iw(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 Lw(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")`)}function Rw(e,t){if(!(e instanceof Ar))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function zw(e){return{fn:(t=>Rw(t,e)),argTypes:[`liftable`],returnType:`T`}}function Bw(e){return{fn:((t,n)=>Rw(n,new H({[e]:N.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Vw(e,t){return new H({[e]:t})}function Hw(){let e={};for(let t of lr)e[t]=zw(Vw(t,!0)),e[`not_${t}`]=zw(Vw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=zw(Vw(n,!0));return e}const Uw={fn:((e,t)=>Rw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ww={fn:((e,t)=>Rw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Gw(){return{fg:Bw(`color`),bg:Bw(`bgcolor`),...Hw(),link:Ww,style:Uw}}function Kw(e,t){if(!Dn.test(e.trim()))throw TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`);return On(e)}function qw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Jw(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const Yw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`darken`),Jw(t,`darken`,`levels`)).hex)),Xw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`lighten`),-Jw(t,`lighten`,`levels`)).hex)),Zw={min:0,max:100,note:`0 = from, 100 = toward`},Qw=qw([`string`,`string`,`float`],((e,t,n)=>cn(Kw(e,`mix`),Kw(t,`mix`),Jw(n,`mix`,`percentage`,Zw)/100).hex)),$w={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},eT=qw([`string`],(e=>In(Kw(e,`contrastOn`)).hex)),tT=qw([`string`,`string`,`float`],((e,t,n)=>zn(Kw(e,`readableOn`),Kw(t,`readableOn`),Jw(n,`readableOn`,`ratio`,$w)).hex)),nT={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function rT(){let e={};for(let[t,n]of Object.entries(nT)){let r=t;e[n]=qw([`string`,`float`],((e,t)=>{let i={...gn,[r]:Jw(t,n,`amount`)};return L.fromRgba(Kw(e,n)).applyKey(i).toRgba().hex}))}return e}function iT(){return{darken:Yw,lighten:Xw,mix:Qw,contrastOn:eT,readableOn:tT,...rT()}}function aT(e,t){if(e.length===0)throw RangeError(`ramp needs at least one stop after the easing: ramp <value> <easing> <position> <color> …`);if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:kn(t,e[r+1])});return n}function oT(e){return{color:{fn:(t=>kn(e(),t).hex),argTypes:[`string`],returnType:`string`},ramp:{fn:((...t)=>{if(t.length<2)throw RangeError(`ramp needs a value and an easing before its stops (got ${t.length}): ramp <value> "linear"|"step" <position> <color> …`);let[n,r,...i]=t;return new ar(ir(r),aT(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function sT(){return{...Gw(),...iT()}}new H({color:`red`,dim:!0});const cT=/^(?:(?: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,lT=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function uT(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(cT);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(lT);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 dT(e){let t=e.match(lT);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 fT(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 pT(e){return e.toLocaleString()}function mT(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function hT(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const gT=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],_T=gT.length;function vT(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*(_T-1));o+=gT[t]}return o}function yT(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 bT=li(),xT=[...pi];function ST(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>fT(e),argTypes:[`string`]},int:{fn:e=>Iw(e),argTypes:[`value`]},string:{fn:e=>Fw(e),argTypes:[`value`]},bool:{fn:e=>Lw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>bT,argTypes:[]},styles:{fn:()=>xT,argTypes:[]},sparkline:{fn:(e,t)=>vT(yT(e),t),argTypes:[`string`,`int`]},cascade:{fn:(e,...t)=>hT(e,mT(t)),argTypes:[`float`,`string`]}}}function CT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>pT(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>uT(e),argTypes:[`string`]},shortenModelName:{fn:e=>dT(e),argTypes:[`string`]}}}function wT(e,t=()=>new Date){return Eu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...mf(),...wm(),...ep(),...Sp(),...of(t),...Yu(),...Of(),...sT(),...ST(),...CT(t),...e??{}}})}function TT(e){return ET(e,new Set(e.names()),``)}function ET(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.getKind(a)===`document`?DT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return ET(e,t,a)}})}function DT(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const OT=/\r\n|\r|\n/g,kT=e=>X(e.replace(OT,` `).trim());function AT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(OT,` `))}}const jT=e=>{try{return X(JSON.parse(e))}catch(e){return Q(`JSON parse failed: ${e.message}`)}};function MT(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function NT(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]}"`)}}function PT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Ee({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?X(n.stdout):Q(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function FT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return X(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return Q(`file unreadable: ${e}`)}}}}function IT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?Q(`${r.reason} in ${n}`):r}const LT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],RT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],zT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],BT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function VT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>LT[e.getMonth()]],[`Monday`,e=>zT[e.getDay()]],[`Jan`,e=>RT[e.getMonth()]],[`Mon`,e=>BT[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 HT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function UT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=HT[t];try{return qT(r,e)}catch{return JT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ib(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ib(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ib(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ib(e.stashCount,0)}}var WT=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}},GT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:se(()=>{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&&(oe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())oe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function KT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function qT(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`?Fw(e):t===`number`?Iw(e):Lw(e)}function JT(e){return e===`number`?0:e===`boolean`?!1:``}var YT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new WT;ttlMgr=new GT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fC;abort=new AbortController;engine=wT();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pw(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,PT(t,this.abort.signal),MT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,FT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,kT,t.default,n);case`regex`:return this.scalarPublisher(e,AT(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=IT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ib(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=IT(i,jT,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=TT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return VT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,VT(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=HT[t.field],r=t.varDefault===void 0?JT(n):qT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,UT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`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=KT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,qT(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(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mw.reaction)(()=>{let t=TT(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,Mw.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,qT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,JT(t))}}defaultFor(e){try{return qT(this.defaultEmptyValue,e)}catch{return JT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function XT(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function ZT(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function QT(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}const $T=Symbol(`cc-candybar.fillDemand`);function eE(e,t){return e[$T]=t,e}function tE(e){return e[$T]}function nE(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=ZT(e,o).pad(s);if(n===`auto`)return[c];let l={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[eE(c,l)]:(QT(c,n,l),[c])}const rE=/\x1b\[[0-9;]*m|\x1b\]8;;[^\x07\x1b]*(?:\x1b\\|\x07)/g;function iE(e){return k(e.replace(rE,``))}function aE(e,t){let n=[];for(let t of e){let e=tE(t);e!==void 0&&n.push({cell:t,how:e})}if(n.length===0||!Number.isFinite(t.width))return e;let r=yx(e,t).split(`
|
|
179
|
+
`);if(r.length>1)return e;let i=Math.max(0,t.width-iE(r[0]??``)),a=Math.floor(i/n.length),o=i-a*n.length;return n.forEach(({cell:e,how:t},r)=>{let i=a+(r===n.length-1?o:0);QT(e,e.cellLength+i,t)}),e}const oE=new Map,sE=new Map;function cE(e){let t=ai(e),n=oE.get(t);if(n!==void 0)return n;let r=Kn(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 oE.set(t,r),r}function lE(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=sE.get(n);if(r!==void 0)return r;let i=tr(e,t);return sE.set(n,i),i}function uE(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=dE(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=dE([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function dE(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>fE(e,t)):e,r=Ar.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 fE(e,t){let n=e.copy();return n.style=t.add(e.style),n}var pE=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function mE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=hE(o,c),d=u===void 0?i:gE(n,u,`bg`);l.bg=d;let f=hE(s,c),p=f===void 0?a(d):gE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function hE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function gE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new pE(t,n,e.message):e}}const _E=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function vE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,yE(e,a,o,n,r));return i}function yE(e,t,n,r,i){if(kg(n)){let[a,o]=Ag(n);return bE(r.get(n.persistWhen)??n.persistWhen,n.set,yE(e,t,a,r,i),yE(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...N_(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=_E.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:[...N_(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:[...N_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:SE(e,n.copy,t)}:`open`in n?{kind:`open`,target:SE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function bE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function xE(e,t){return e.kind===`dual`?Si(CE(t,e.selector))===!0?e.durable:e.session:e}function SE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function CE(e,t){return e.has(t)?Fw(e.read(t)):``}function wE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function TE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function EE(e,t){return Math.max(e.members.indexOf(CE(t,e.stateVar)),0)}function DE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=CE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=CE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=CE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(EE(e,r)+1)%e.members.length];return{effects:[{verb:Fy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Iy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ly,args:[wE(e.text,TT(r))]}],active:!1};case`open`:return{effects:[{verb:Ry,args:[wE(e.target,TT(r))]}],active:!1};case`persist-literal`:{let t=CE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=CE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(EE(e,r)+1)%e.members.length];return{effects:[{verb:Hy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Uy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Wy,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ky,args:[i]}],active:!1};case`redo`:return{effects:[{verb:qy,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Yy,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Xy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Gy,args:[i,e.key,Qm(e.op)]}],active:!1};case`dual`:{let a=xE(e,r),{effects:o,active:s}=DE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Gy,args:[i,e.key,Qm(r)]}],active:!1}}}}function OE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:cc(`action "${e}"`,n,t.members.length,EE(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 kE(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}=OE(e,xE(r,i),t,i),{effects:s,active:c}=DE(r,a,o,i,CE(i,`session.id`));return TE(a,$y(s),c)}function AE(e){return{action:{fn:(t,...n)=>kE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function jE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(Js(e,t))})}function ME(e,t){return jE(e.palette,ec(e.palette,e.disclosure,[t]))}function NE(){return{current:null}}function PE(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 FE(e){return new Ar(e).cellLength}function IE(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 LE(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function RE(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 zE(e,t){let n=e.compiled.get(t),r=n&&xE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function BE(e,t,n,r,i,a,o){let s=zE(a,e),c=a.compiled.get(e),l=a.store,u=CE(l,`session.id`),d=`stateVar`in s?CE(l,s.stateVar):void 0,f=s.options.map(FE),p=i?Math.max(1,Iw(l.read(`term.cols`))-vx(a.stripStyle)-2*a.padding):1/0,m=FE(`✕`)+1,h=FE(`←`)+1+FE(`→`)+1,g=IE(f,p,m),_=g.length>1?IE(f,p,m+h):g,v=parseInt(CE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>$y([{verb:Fy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),ee=$y([{verb:Fy,args:[u,...S]}]),te=r?[{verb:Fy,args:[u,...S]}]:[],ne=e=>{let{effects:t}=DE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?$y([{verb:Fy,args:[...n.args,...r?S:[]]}]):$y([...t,...te])},re=[TE(`✕`,ee,!1)];y>0&&re.push(TE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];re.push(TE(t,ne(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&re.push(TE(`→`,x(y+1),!1)),LE(re,i)}function VE(e,t){return{picker:{fn:(n,r,i,a)=>{let o=RE(e,r,`set-int`,`an int action ({ set, int: true })`);return BE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>ME(PE(t,`{{ picker }}`),{...e,distribution:Rs(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const HE=Symbol(`cc-candybar.menuDrop`);function UE(e){return e.flatMap(e=>e[HE]??[])}function WE(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Em(i.segName,e,n.key),s=km(o),c=Tm(e),l=CE(a.store,o)===c,u=CE(a.store,`session.id`),d=l?oc:c,f=TE(cc(`{{ menu "${e}" }}`,t,2,+!!l),$y([{verb:Fy,args:[u,o,d,s,`0`]}]),!1);return f[HE]=l?[BE(e,{key:s,stateVar:s},[[o,oc],[s,`0`]],n.closeOnPick,n.paged,a,e=>ME(i,{...e,distribution:n.distribution}))]:[],f}const GE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function KE(e,t){let n=t[t.length-1],r=GE(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:Nm(r??{})}}function qE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=KE(t,n);return WE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function JE(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=YE(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new Ar(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=Ar.fromFragments(c);return l.end=``,l.noWrap=!0,l}function YE(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function XE(e){let t={fn:(()=>{let t=PE(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`},n=oT(()=>PE(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),r={fn:((e,t,r,i,a,o,...s)=>JE({value:e,max:t,width:r,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(n.ramp.fn(e,o,...ZE(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...n,bgOf:t,gauge:r}}function ZE(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function QE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
180
180
|
`)){n.push(r);continue}let e=r.split(`
|
|
181
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function
|
|
182
|
-
`)}var
|
|
183
|
-
`)||null}var yD=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=mD(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=dv(e,t,n),i=r.kind===`file`?r.path:null,a=[hv(e,t),pv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof da&&a.push(...e.warnings),{resolvedPath:i,warning:vD(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:vD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=gv(t,kw);n.push(...o);let s=yv(r,t??`<default>`,a),c=new pD,l=new qT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=iD(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of TS(s))d.push(vS(e,t));for(let{key:e,spec:t}of sS(s))d.push(cS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:fw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:hD(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=_D(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Y(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const bD=16384;var xD=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<bD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%bD}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:nb,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const SD={load:()=>({}),save:()=>{},flush:()=>{}};function CD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var wD=class{sessions;storage;atom=(0,Mw.createAtom)(`SessionState`);constructor(e=SD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=CD(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,Mw.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,Mw.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,Mw.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 TD=(e,t)=>E(t);function ED(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 DD=class{timer=null;pending=null;constructor(e,t=500,n=TD){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 ED(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const OD={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`,updateNotice:`boolean`,colorCompatibility:`string`},kD=new Set([`1`,`true`]),AD=new Set([`0`,`false`,``]);function jD(e,t){let n=nO(e),r=n.scope===`globals`?OD[n.field]:`string`;if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(kD.has(t))return`true`;if(AD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function MD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function ND(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function PD(e){return/^\s*$/.test(e)?null:ji(e)}function FD(e,t){return e!==null&&Ni(e,t)!==void 0}function ID(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(ID),...i}}return e}function LD(e){if(!ao(e))return ID(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,ID(t)])),...n}}const RD=Dw,zD=RD.segments,BD=RD.presets,VD=RD.root;function HD(e,t,n,r){if(!FD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function UD(e,t){let n=fh(t);return t.scope===`segment-palette`&&HD(e,[`segments`,t.segment],zD[t.segment],n.join(`.`)),n}function WD(e){return ji(zi(e))}function GD(){return Object.entries(VD.rows).map(([e,t])=>{let n=ID(t);return{path:[`root`],fragment:WD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function KD(e,t){let n=e===null?void 0:Ni(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function qD(e,t){if(t===void 0)return null;let n=LD(t);return{path:e,fragment:WD(n),unit:{path:e,value:n}}}function JD(e,t){let n=[`presets`,t],r=[...n,`root`],i=BD[t];HD(e,n,i,r.join(`.`));let a=KD(e,r)??qD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function YD(e,t){let n=ia(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function XD(e,t){return[...GD(),KD(e,[`root`]),JD(e,t)].filter(e=>e!==null).reduce(YD,new Map)}function ZD(e,t,n){for(let{node:r,...i}of XD(e,t).values())if(sa(r,n))return i;throw new $(`${QD(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function QD(e,t){return JD(e,t)?.path??[`root`]}function $D(e,t){return t.scope===`preset-root`?QD(e,t.preset):fh(t)}function eO(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function tO(e){let t=dh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function nO(e){let t=tO(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function rO(e,t){let n=nO(t),r=PD(MD(e)??``),i=r===null?void 0:Ni(r,fh(n));return i!==void 0&&`value`in i?i.value:void 0}function iO(e,t,n,r){let i=nO(n),a=MD(t);mO(e,t,{before:a,after:$i(a??``,UD(PD(a??``),i),jD(n,r),Li)})}function aO(e,t,n){let r=tO(n),i=MD(t);if(i===null)return;let a=ea(i,$D(PD(i),r));a!==i&&mO(e,t,{before:i,after:a})}function oO(e,t,n,r){let i=tO(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=MD(t),o=r.op===`remove`?r.target:r.anchor,s=ZD(PD(a??``),i.preset,o),c=eO(a??``,s),l=r.op===`remove`?la(c,s.path,r.target):ua(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);mO(e,t,{before:a,after:l})}const sO={past:[],future:[]};function cO(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function lO(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(cO)&&Array.isArray(t.future)&&t.future.every(cO)}function uO(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(lO))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function dO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function fO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function pO(e,t,n,r,i){ND(t,n,e.logger);try{dO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function mO(e,t,n){let r=uO(e),{past:i}=r[t]??sO;pO(e,t,n.after,{...r,[t]:{past:fO(i,n),future:[]}},`edit`)}function hO(e,t){let n=uO(e),{past:r,future:i}=n[t]??sO,a=r[r.length-1];return a===void 0?null:(_O(t,a.after,`undo`),pO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:fO(i,a)}},`undo`),a)}function gO(e,t){let n=uO(e),{past:r,future:i}=n[t]??sO,a=i[i.length-1];return a===void 0?null:(_O(t,a.before,`redo`),pO(e,t,a.after,{...n,[t]:{past:fO(r,a),future:i.slice(0,-1)}},`redo`),a)}function _O(e,t,n){if(MD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function vO(e){let t=De({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function yO(){return{probeTmux:vO,claudeSettingsPath:rb()}}function bO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function xO(e){if(/^\s*$/.test(e))return{};let t=Ri.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function SO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function CO(e){try{return xO(bO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function wO(e,t){return{tmux:SO(e,t),claudeSettingsEnv:CO(e)}}function TO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(bO(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:CO(e)}}default:return t.kind}}function EO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function DO(e){return OO(()=>decodeURIComponent(e))}function OO(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function kO(e,t){let n=De({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 AO=(e,t)=>kO(DO(e),t),jO=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,DO(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`})`)}},MO=(e,t)=>kO(DO(e),t),NO=(e,t)=>kO(DO(e),t),PO=(e,t)=>{let n=EO(DO(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},FO=(e,t)=>{let[n=``,...r]=OO(()=>Qy(e)),i=EO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${_S().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: ${_S().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=yS(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})`)},IO=/^-?\d+$/;function LO(e,t,n){return e>n?t:e<t?n:e}function RO(e,t){if(!e)return null;if(!_S().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${_S().join(`, `)})`);return e}function zO(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const BO=(e,t)=>{let[n=``,r=``,i=``]=OO(()=>Qy(e)),a=EO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!IO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=bS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${_S().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&IO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=LO(l+o,s.min,s.max),d=yS(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})`)},VO=`render-origin`;function HO(e){return JSON.stringify(e)}function UO(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function WO(e,t){let n=e.sessionState.get(t,VO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=UO(n);return fv(r.projectDir,r.cwd,r.configFile??void 0)}function GO(e){return{historyPath:Be(),logger:e.dlog}}const KO=(e,t)=>{let[n=``,r=``,i=``,a=``]=OO(()=>Qy(e)),o=EO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${$x().join(`, `)})`);let s=eS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=RO(a,`set-config`),l=WO(t,o);iO(GO(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),zO(c,o,t,`set-config`)},qO=(e,t)=>{let[n=``,r=``,i=``,a=``]=OO(()=>Qy(e)),o=EO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!IO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=RO(a,`step-config`),l=tS(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${$x().join(`, `)})`);let u=WO(t,o),d=rO(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=LO(f+s,l.min,l.max),m=eS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);iO(GO(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),zO(c,o,t,`step-config`)},JO=(e,t)=>{let[n=``,r=``]=OO(()=>Qy(e)),i=EO(n);if(!r||!$x().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${$x().join(`, `)})`);let a=WO(t,i);aO(GO(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},YO=(e,t)=>{let[n=``,r=``,i=``]=OO(()=>Qy(e)),a=EO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${$x().join(`, `)})`);let o=eS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=$m(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=WO(t,a);oO(GO(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},XO=(e,t)=>{let[n=``]=OO(()=>Qy(e)),r=EO(n),i=WO(t,r);if(hO(GO(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},ZO=(e,t)=>{let[n=``]=OO(()=>Qy(e)),r=EO(n),i=WO(t,r);if(gO(GO(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},QO=(e,t)=>{EO(DO(e)),t.applyUpdate()},$O=`client-hints`;function ek(e,t){let n=e.sessionState.get(t,$O);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return Ev(r)}function tk(e,t,n){let r=Ih(n);e.sessionState.setBatch(t,zh(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const nk=(e,t)=>{let n=EO(DO(e));tk(t,n,wO(t.doctor,ek(t,n).tmux))},rk=(e,t)=>{let[n=``,r=``]=OO(()=>Qy(e)),i=EO(n),a=Lh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=wO(t.doctor,ek(t,i).tmux),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=TO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),tk(t,i,c)},ik=`config-override`,ak=new Map([[Ly,AO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=EO(OO(()=>decodeURIComponent(e.slice(0,n)))),i=OO(()=>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,ik),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,ik,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ry,jO],[Fy,FO],[Iy,BO],[Hy,KO],[Uy,qO],[Wy,JO],[Gy,YO],[Ky,XO],[qy,ZO],[By,MO],[Vy,NO],[zy,PO],[Jy,QO],[Yy,nk],[Xy,rk]]),ok=new Set([Fy,Iy,Hy,Uy,Wy,Gy,Ky,qy,zy,Jy,Yy,Xy]),sk=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of eb(e)){if(!i&&ok.has(a)){let e=Qy(o);e.length>0&&e[0]&&(i=e[0])}let e=ak.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(`
|
|
184
|
-
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},ck=new Map([...ak,[Py,sk]]);Object.freeze([...ck.keys()]);const lk=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`]),uk=[[`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 dk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of uk){let i=pk(n,e);if(i==null)t.missingRequired.push(e);else{let n=fk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))lk.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function fk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function pk(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 mk(e,t){switch(e){case`vars`:return{what:e,vars:hk(t)};case`segments`:return{what:e,segments:bk(t)};case`config`:return{what:e,config:Ck(t)}}}function hk(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=vk(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,...gk(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:_k(r.lastUpdatedMs())})}return o}function gk(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function _k(e){return e===null?null:Math.max(0,Date.now()-e)}function vk(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,yk(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}`,yk(i));return t}function yk(e){return e.kind}function bk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=xk(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:Sk(t.template,i),lastRender:r.get(e)??null})}return o}function xk(e){let t=[],n=new Set;for(let r of va(co(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 Sk(e,t){let n=new Set;for(let r of L_(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 Ck(e){return e===null?null:e.config}const wk=[`vars`,`segments`,`config`];function Tk(e){return typeof e==`string`&&wk.includes(e)}function Ek(e){return Math.max(1,e-2)}var Dk=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 E(`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);E(`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{E(`Calculating context tokens from transcript: ${e}`);let n=await FC(e);if(n.length===0)return E(`No entries in transcript`),Z;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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function Ok(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 kk=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(Ok(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=CC(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 zC(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||(Ok(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(E(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({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 Ak=new Map;function jk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var Mk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=jk(process.env.TMUX),t=Ak.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return Ak.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},Nk=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const Pk=new xD;we(Pk.launchStats);const Fk=new dC({counters:Pk,logger:Y}),Ik=new yC({watchers:Fk,logger:Y}),Lk=new ZC,Rk=new wD,zk=new Nk(Ge()),Bk=new Dk,Vk=new kk,Hk=new Mk,Uk=new yD({gitService:Ik,sessionState:Rk,watchers:Fk},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),Wk=60*1e3;function Gk(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),sA(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Wk),a.unref())},checkNow:o}}const Kk=Gk(),qk=BS({entryUrl:import.meta.url,intervalMs:Wk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>Kk.checkNow(),log:Y});let Jk=null,Yk=null,Xk=0;function Zk(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),sA(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),sA(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),sA(0)});try{Xk=oy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),sA(1);return}Jk=Jb(t.pid);let e=ix(ox(Jk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),sA(1);return}Yk=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),Rk.useStorage(new DD(ze(),500,Y)),Zb({anchor:Xb(t.env),isAlive:Qb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),sA(0)}}),Qk(g.createServer({allowHalfOpen:!1},e=>{cA(e)}),Pe(),!1)}function Qk(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),sA(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}$k(e,n)}),e.listen(n,()=>eA(n))}function $k(e,n){let i=Rb(zb(Le(n)),(e,t)=>qb(e,t,{readStartTime:Kb,pidAlive:Qb}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),sA(1);return}}Qk(e,n,!0)}function eA(e){let n=Hb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),sA(0);return}iA(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(Xk/1048576)}MB`),Cy();let i=zk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),Kk.arm(),qk.arm(),rA(),tA(e,n.identity)}function tA(e,n){Gb({bound:n,myPid:t.pid,readIdentity:()=>Hb(e),readLease:()=>zb(Le(e)),shutdown:e=>sA(e),log:Y}).arm()}let nA=null;function rA(){nA=uy(my(Pk.startedAt.getTime(),e=>sA(e),{rssLimitBytes:Xk})),nA.arm()}function iA(e){let n=Bb(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Jk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let aA=0,oA=!1;function sA(e){if(!oA){oA=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{Ik.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{Lk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{Fk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{Rk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Vb(Re(),t.pid),Yk!==null&&ax(Yk,t.pid,nx,e=>r.unlinkSync(e)),t.exit(e)}}function cA(e){aA++,Pk.inFlight=aA;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>sA(r);try{e.end(Nv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{Pk.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{uA(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`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=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),aA=Math.max(0,aA-1),Pk.inFlight=aA})}const lA=e=>({resp:e,exitAfterFlush:null});async function uA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return lA({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`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 lA({ok:!0,stats:Pk.snapshot({gitCache:Ik.getStats(),usageCache:Lk.getStats(),renderCacheSize:Uk.size,watchersActive:Fk.size(),nextRestartReason:nA?.describeNextRestart()??null})});if(e.kind===`render`){Pk.requestsTotal++;let t=Date.now();try{let{report:n}=dk(e.hookData);for(let e of n.unknownTopLevelFields)Y(`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 Pk.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),lA({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=dA(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);Rk.get(s,`client-hints`)!==l&&Rk.set(s,$O,l);let u=Rk.get(s,`config-override`)??a??c.configEnv,d=Uk.getOrCreate(i,e.cwd,u),f=HO({projectDir:i,cwd:e.cwd,configFile:u??null});Rk.get(s,`render-origin`)!==f&&Rk.set(s,VO,f);let p=c.termCols,m=Ek(p??120),h=bx(c.termRows),g={...pA,width:m},{authoredRoots:_}=d.state,v=rw(d.state.config,t=>Rk.get(e.hookData.session_id,t),e=>_.has(e)),y=await gw(e.hookData,_A,e.cwd,d.state.neededInputPaths,v,c),b=oE(v.theme);g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=aD(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,b,g,{perSegmentSink:d.state.lastRenderCellsBySegment},{look:fi(d.state.config.looks,v.look),preset:v.preset}),S=Rk.get(e.hookData.session_id,`click.error`);S&&Rk.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,S].filter(Boolean).join(`
|
|
185
|
-
`),te=
|
|
186
|
-
`})}catch(e){throw
|
|
187
|
-
`);return}t.stdout.write(
|
|
181
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function $E(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 eD={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Rs(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return $E(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,{index:r,count:e.children.length,distribution:e.distribution})))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name,...e.opens!==void 0&&{opens:{open:t.parse(dc(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,`${t.path}.opens.body`)}}}},render(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];try{if(!XT(i.when,t.scope))return[];let n=i.palette??t.palette,a=t.enterSegment(e.name,n,t.region,i.bg,i.fg),o=i.template.evaluate(t.scope),s=t.exitSegment(o),c=e.opens!==void 0&&XT(e.opens.open,t.scope),l=e.opens===void 0?[]:t.renderBody(e.opens.body,c,a.disclosure),u=s.length>0||c?a.trigger:a.closed,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=QE(uE(o,u)).map(e=>nE(e,d)),p=s.map(e=>nE(uE([e],a.band),{...d,baseStyle:a.band})),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),[...m,...l]}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new Ar(`⚠ ${e.name}: ${r}`)]]}}}};function tD(e){return eD[e]}function nD(e){if(`ttl`in e)return{kind:`ttl`,durationMs:NT(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 rD(e,t){switch(ba(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function iD(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:nD(n.cache),parse:rD(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:nD(n.cache),parse:rD(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?NT(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 aD(e,t){let n=pl.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function oD(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=NE(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=rh(e.presets),l=new Map([...j_(e),...wh(e)]),u=wT({...AE(i),...VE(i,a),...qE(o),...XE(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=aD(u,e.helpers),f=e=>u.parse(e,d),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=vE(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{iD(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{iD(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:cE(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`),parse:(e,n)=>g(e,t,n),compileChild:_};return tD(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=oh(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function sD(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=gn,preset:f=th}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=TT(n),m=lE(a,d);l?.clear();let h=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},g=(e,n,r,i,a)=>{let{tint:o,text:s,disclosure:c}=ac(n,r),l=mE(t.activeSegment,e,n,c,o,s,i,a,p),u=Qs(n,c);return{closed:l,trigger:jE(n,u.state),band:jE(n,u.plane),disclosure:c}},_=e=>(t.activeSegment.current=null,UE(e)),v=(e,t,n)=>{let r=t&&XT(e.when,p),i={scope:p,palette:m,visible:r,padding:o.padding,region:n,perSegmentSink:l,onSegmentError:u,enterSegment:g,exitSegment:_,lookupSegment:h,renderChild:(e,t,r)=>v(e,t,nc(n,r)),renderBody:(e,t,n)=>v(e,r&&t,rc(n))};return tD(e.kind).render(e,i)},y=t.roots.get(f);if(y===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${th}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return v(y,!0,tc).map(e=>yx(aE(e,o),o)).join(`
|
|
182
|
+
`)}var cD=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,mD(e,t,n,`initial value`),this.cell=Mw.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){mD(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},lD=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Mw.computed)(()=>{let e=n();return mD(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},uD=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Mw.observable.box(pD(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=pD(e);fD(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function dD(e){return JSON.stringify(e)}function fD(e,t){return dD(e)===dD(t)}function pD(e){return e.kind===`ok`?{kind:`ok`,value:Nw(e.value)}:e}function mD(e,t,n,r){let i=Pw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var hD=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new cD(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new uD(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new lD(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Mw.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Mw.runInAction)(()=>n.set(t))}runInAction(e){(0,Mw.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return dD(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function gD(e,t,n){return e+`\0`+t+`\0`+(n??``)}function _D(e,t){return new Set(rh(e.presets).filter(n=>oh(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function vD(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function yD(e,t){let n=new Map;for(let t of lv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=vD(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}function bD(e){return e.filter(Boolean).join(`
|
|
183
|
+
`)||null}var xD=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=gD(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=dv(e,t,n),i=r.kind===`file`?r.path:null,a=[hv(e,t),pv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof da&&a.push(...e.warnings),{resolvedPath:i,warning:bD(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:bD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=gv(t,kw);n.push(...o);let s=yv(r,t??`<default>`,a),c=new hD,l=new YT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=oD(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of TS(s))d.push(vS(e,t));for(let{key:e,spec:t}of sS(s))d.push(cS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:fw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:_D(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=yD(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Y(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const SD=16384;var CD=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<SD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%SD}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:nb,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const wD={load:()=>({}),save:()=>{},flush:()=>{}};function TD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var ED=class{sessions;storage;atom=(0,Mw.createAtom)(`SessionState`);constructor(e=wD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=TD(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,Mw.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,Mw.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,Mw.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 DD=(e,t)=>E(t);function OD(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 kD=class{timer=null;pending=null;constructor(e,t=500,n=DD){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 OD(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const AD={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`,updateNotice:`boolean`,colorCompatibility:`string`},jD=new Set([`1`,`true`]),MD=new Set([`0`,`false`,``]);function ND(e,t){let n=iO(e),r=n.scope===`globals`?AD[n.field]:`string`;if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(jD.has(t))return`true`;if(MD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function PD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function FD(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function ID(e){return/^\s*$/.test(e)?null:ji(e)}function LD(e,t){return e!==null&&Ni(e,t)!==void 0}function RD(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(RD),...i}}return e}function zD(e){if(!ao(e))return RD(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,RD(t)])),...n}}const BD=Dw,VD=BD.segments,HD=BD.presets,UD=BD.root;function WD(e,t,n,r){if(!LD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function GD(e,t){let n=fh(t);return t.scope===`segment-palette`&&WD(e,[`segments`,t.segment],VD[t.segment],n.join(`.`)),n}function KD(e){return ji(zi(e))}function qD(){return Object.entries(UD.rows).map(([e,t])=>{let n=RD(t);return{path:[`root`],fragment:KD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function JD(e,t){let n=e===null?void 0:Ni(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function YD(e,t){if(t===void 0)return null;let n=zD(t);return{path:e,fragment:KD(n),unit:{path:e,value:n}}}function XD(e,t){let n=[`presets`,t],r=[...n,`root`],i=HD[t];WD(e,n,i,r.join(`.`));let a=JD(e,r)??YD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function ZD(e,t){let n=ia(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function QD(e,t){return[...qD(),JD(e,[`root`]),XD(e,t)].filter(e=>e!==null).reduce(ZD,new Map)}function $D(e,t,n){for(let{node:r,...i}of QD(e,t).values())if(sa(r,n))return i;throw new $(`${eO(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function eO(e,t){return XD(e,t)?.path??[`root`]}function tO(e,t){return t.scope===`preset-root`?eO(e,t.preset):fh(t)}function nO(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function rO(e){let t=dh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function iO(e){let t=rO(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function aO(e,t){let n=iO(t),r=ID(PD(e)??``),i=r===null?void 0:Ni(r,fh(n));return i!==void 0&&`value`in i?i.value:void 0}function oO(e,t,n,r){let i=iO(n),a=PD(t);gO(e,t,{before:a,after:$i(a??``,GD(ID(a??``),i),ND(n,r),Li)})}function sO(e,t,n){let r=rO(n),i=PD(t);if(i===null)return;let a=ea(i,tO(ID(i),r));a!==i&&gO(e,t,{before:i,after:a})}function cO(e,t,n,r){let i=rO(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=PD(t),o=r.op===`remove`?r.target:r.anchor,s=$D(ID(a??``),i.preset,o),c=nO(a??``,s),l=r.op===`remove`?la(c,s.path,r.target):ua(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);gO(e,t,{before:a,after:l})}const lO={past:[],future:[]};function uO(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function dO(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(uO)&&Array.isArray(t.future)&&t.future.every(uO)}function fO(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(dO))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function pO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function mO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function hO(e,t,n,r,i){FD(t,n,e.logger);try{pO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function gO(e,t,n){let r=fO(e),{past:i}=r[t]??lO;hO(e,t,n.after,{...r,[t]:{past:mO(i,n),future:[]}},`edit`)}function _O(e,t){let n=fO(e),{past:r,future:i}=n[t]??lO,a=r[r.length-1];return a===void 0?null:(yO(t,a.after,`undo`),hO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:mO(i,a)}},`undo`),a)}function vO(e,t){let n=fO(e),{past:r,future:i}=n[t]??lO,a=i[i.length-1];return a===void 0?null:(yO(t,a.before,`redo`),hO(e,t,a.after,{...n,[t]:{past:mO(r,a),future:i.slice(0,-1)}},`redo`),a)}function yO(e,t,n){if(PD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function bO(e){let t=De({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function xO(){return{probeTmux:bO,claudeSettingsPath:rb()}}function SO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function CO(e){if(/^\s*$/.test(e))return{};let t=Ri.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function wO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function TO(e){try{return CO(SO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function EO(e,t){return{tmux:wO(e,t),claudeSettingsEnv:TO(e)}}function DO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(SO(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:TO(e)}}default:return t.kind}}function OO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function kO(e){return AO(()=>decodeURIComponent(e))}function AO(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function jO(e,t){let n=De({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 MO=(e,t)=>jO(kO(e),t),NO=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,kO(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`})`)}},PO=(e,t)=>jO(kO(e),t),FO=(e,t)=>jO(kO(e),t),IO=(e,t)=>{let n=OO(kO(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},LO=(e,t)=>{let[n=``,...r]=AO(()=>Qy(e)),i=OO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${_S().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: ${_S().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=yS(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})`)},RO=/^-?\d+$/;function zO(e,t,n){return e>n?t:e<t?n:e}function BO(e,t){if(!e)return null;if(!_S().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${_S().join(`, `)})`);return e}function VO(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const HO=(e,t)=>{let[n=``,r=``,i=``]=AO(()=>Qy(e)),a=OO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!RO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=bS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${_S().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&RO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=zO(l+o,s.min,s.max),d=yS(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})`)},UO=`render-origin`;function WO(e){return JSON.stringify(e)}function GO(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function KO(e,t){let n=e.sessionState.get(t,UO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=GO(n);return fv(r.projectDir,r.cwd,r.configFile??void 0)}function qO(e){return{historyPath:Be(),logger:e.dlog}}const JO=(e,t)=>{let[n=``,r=``,i=``,a=``]=AO(()=>Qy(e)),o=OO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${$x().join(`, `)})`);let s=eS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=BO(a,`set-config`),l=KO(t,o);oO(qO(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),VO(c,o,t,`set-config`)},YO=(e,t)=>{let[n=``,r=``,i=``,a=``]=AO(()=>Qy(e)),o=OO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!RO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=BO(a,`step-config`),l=tS(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${$x().join(`, `)})`);let u=KO(t,o),d=aO(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=zO(f+s,l.min,l.max),m=eS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);oO(qO(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),VO(c,o,t,`step-config`)},XO=(e,t)=>{let[n=``,r=``]=AO(()=>Qy(e)),i=OO(n);if(!r||!$x().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${$x().join(`, `)})`);let a=KO(t,i);sO(qO(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},ZO=(e,t)=>{let[n=``,r=``,i=``]=AO(()=>Qy(e)),a=OO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${$x().join(`, `)})`);let o=eS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=$m(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=KO(t,a);cO(qO(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},QO=(e,t)=>{let[n=``]=AO(()=>Qy(e)),r=OO(n),i=KO(t,r);if(_O(qO(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},$O=(e,t)=>{let[n=``]=AO(()=>Qy(e)),r=OO(n),i=KO(t,r);if(vO(qO(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},ek=(e,t)=>{OO(kO(e)),t.applyUpdate()},tk=`client-hints`;function nk(e,t){let n=e.sessionState.get(t,tk);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return Ev(r)}function rk(e,t,n){let r=Ih(n);e.sessionState.setBatch(t,zh(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const ik=(e,t)=>{let n=OO(kO(e));rk(t,n,EO(t.doctor,nk(t,n).tmux))},ak=(e,t)=>{let[n=``,r=``]=AO(()=>Qy(e)),i=OO(n),a=Lh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=EO(t.doctor,nk(t,i).tmux),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=DO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),rk(t,i,c)},ok=`config-override`,sk=new Map([[Ly,MO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=OO(AO(()=>decodeURIComponent(e.slice(0,n)))),i=AO(()=>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,ok),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,ok,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ry,NO],[Fy,LO],[Iy,HO],[Hy,JO],[Uy,YO],[Wy,XO],[Gy,ZO],[Ky,QO],[qy,$O],[By,PO],[Vy,FO],[zy,IO],[Jy,ek],[Yy,ik],[Xy,ak]]),ck=new Set([Fy,Iy,Hy,Uy,Wy,Gy,Ky,qy,zy,Jy,Yy,Xy]),lk=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of eb(e)){if(!i&&ck.has(a)){let e=Qy(o);e.length>0&&e[0]&&(i=e[0])}let e=sk.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(`
|
|
184
|
+
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},uk=new Map([...sk,[Py,lk]]);Object.freeze([...uk.keys()]);const dk=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`]),fk=[[`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 pk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of fk){let i=hk(n,e);if(i==null)t.missingRequired.push(e);else{let n=mk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))dk.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function mk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function hk(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 gk(e,t){switch(e){case`vars`:return{what:e,vars:_k(t)};case`segments`:return{what:e,segments:Sk(t)};case`config`:return{what:e,config:Tk(t)}}}function _k(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=bk(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,...vk(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:yk(r.lastUpdatedMs())})}return o}function vk(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function yk(e){return e===null?null:Math.max(0,Date.now()-e)}function bk(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,xk(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}`,xk(i));return t}function xk(e){return e.kind}function Sk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Ck(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:wk(t.template,i),lastRender:r.get(e)??null})}return o}function Ck(e){let t=[],n=new Set;for(let r of va(co(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 wk(e,t){let n=new Set;for(let r of L_(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 Tk(e){return e===null?null:e.config}const Ek=[`vars`,`segments`,`config`];function Dk(e){return typeof e==`string`&&Ek.includes(e)}function Ok(e){return Math.max(1,e-2)}var kk=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 E(`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);E(`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{E(`Calculating context tokens from transcript: ${e}`);let n=await FC(e);if(n.length===0)return E(`No entries in transcript`),Z;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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function Ak(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 jk=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(Ak(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=CC(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 zC(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||(Ak(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(E(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({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 Mk=new Map;function Nk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var Pk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=Nk(process.env.TMUX),t=Mk.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return Mk.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},Fk=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const Ik=new CD;we(Ik.launchStats);const Lk=new dC({counters:Ik,logger:Y}),Rk=new yC({watchers:Lk,logger:Y}),zk=new ZC,Bk=new ED,Vk=new Fk(Ge()),Hk=new kk,Uk=new jk,Wk=new Pk,Gk=new xD({gitService:Rk,sessionState:Bk,watchers:Lk},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),Kk=60*1e3;function qk(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),lA(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Kk),a.unref())},checkNow:o}}const Jk=qk(),Yk=BS({entryUrl:import.meta.url,intervalMs:Kk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>Jk.checkNow(),log:Y});let Xk=null,Zk=null,Qk=0;function $k(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),lA(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),lA(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),lA(0)});try{Qk=oy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),lA(1);return}Xk=Jb(t.pid);let e=ix(ox(Xk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),lA(1);return}Zk=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),Bk.useStorage(new kD(ze(),500,Y)),Zb({anchor:Xb(t.env),isAlive:Qb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),lA(0)}}),eA(g.createServer({allowHalfOpen:!1},e=>{uA(e)}),Pe(),!1)}function eA(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),lA(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}tA(e,n)}),e.listen(n,()=>nA(n))}function tA(e,n){let i=Rb(zb(Le(n)),(e,t)=>qb(e,t,{readStartTime:Kb,pidAlive:Qb}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),lA(1);return}}eA(e,n,!0)}function nA(e){let n=Hb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),lA(0);return}oA(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(Qk/1048576)}MB`),Cy();let i=Vk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),Jk.arm(),Yk.arm(),aA(),rA(e,n.identity)}function rA(e,n){Gb({bound:n,myPid:t.pid,readIdentity:()=>Hb(e),readLease:()=>zb(Le(e)),shutdown:e=>lA(e),log:Y}).arm()}let iA=null;function aA(){iA=uy(my(Ik.startedAt.getTime(),e=>lA(e),{rssLimitBytes:Qk})),iA.arm()}function oA(e){let n=Bb(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Xk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let sA=0,cA=!1;function lA(e){if(!cA){cA=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{Rk.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{zk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{Lk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{Bk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Vb(Re(),t.pid),Zk!==null&&ax(Zk,t.pid,nx,e=>r.unlinkSync(e)),t.exit(e)}}function uA(e){sA++,Ik.inFlight=sA;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>lA(r);try{e.end(Nv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{Ik.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{fA(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`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=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),sA=Math.max(0,sA-1),Ik.inFlight=sA})}const dA=e=>({resp:e,exitAfterFlush:null});async function fA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return dA({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`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 dA({ok:!0,stats:Ik.snapshot({gitCache:Rk.getStats(),usageCache:zk.getStats(),renderCacheSize:Gk.size,watchersActive:Lk.size(),nextRestartReason:iA?.describeNextRestart()??null})});if(e.kind===`render`){Ik.requestsTotal++;let t=Date.now();try{let{report:n}=pk(e.hookData);for(let e of n.unknownTopLevelFields)Y(`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 Ik.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),dA({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=pA(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);Bk.get(s,`client-hints`)!==l&&Bk.set(s,tk,l);let u=Bk.get(s,`config-override`)??a??c.configEnv,d=Gk.getOrCreate(i,e.cwd,u),f=WO({projectDir:i,cwd:e.cwd,configFile:u??null});Bk.get(s,`render-origin`)!==f&&Bk.set(s,UO,f);let p=c.termCols,m=Ok(p??120),h=bx(c.termRows),g={...hA,width:m},{authoredRoots:_}=d.state,v=rw(d.state.config,t=>Bk.get(e.hookData.session_id,t),e=>_.has(e)),y=await gw(e.hookData,yA,e.cwd,d.state.neededInputPaths,v,c),b=cE(v.theme);g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=sD(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,b,g,{perSegmentSink:d.state.lastRenderCellsBySegment},{look:fi(d.state.config.looks,v.look),preset:v.preset}),S=Bk.get(e.hookData.session_id,`click.error`);S&&Bk.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,S].filter(Boolean).join(`
|
|
185
|
+
`),te=Yk.notice({sessionId:s,dismissed:Bk.get(s,ES),enabled:v.updateNotice}),ne=d.lastError===null?null:d.configFilePath,re=Tx(ee,te,d.lastWarning??``),ie=Vk.sync(s,re===null?null:Dx(re));ie!==null&&Y(`warn`,`diagnostic dump failed: ${ie}`);let C=Ox(x,re,{fullText:ie===null?{kind:`file`,path:Vk.pathFor(s)}:{kind:`unavailable`,reason:ie},failedConfigFile:ne},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),ae=Date.now()-t,w=Rk.getStats(),T=zk.getStats();return Y(`info`,`render sid=${e.hookData.session_id??`?`} took=${ae}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${w.size}/${w.hits}h/${w.misses}m usage=${T.size}/${T.hits}h/${T.misses}m err=${ee?`Y`:`N`} upd=${te.length} warn=${d.lastWarning?`Y`:`N`}`),dA({ok:!0,output:C+`
|
|
186
|
+
`})}catch(e){throw Ik.requestsErrored++,e}}if(e.kind===`click`)return dA(await bA(e.verb,e.value));if(e.kind===`debug`){if(!Dk(e.what))return dA({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${Ek.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=Gk.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?vA(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):_A};return dA({ok:!0,debug:gk(e.what,n)})}return dA({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function pA(e){let{values:t,tokens:n}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:Dv(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const mA={sessionState:Bk,dlog:Y,applyUpdate:()=>Yk.act(),doctor:xO()},hA={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},gA={...hA,width:1/0},_A=new Map;function vA(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,yx(a,{...gA,charset:t,colorCompatibility:n}));return r}const yA={gitProvider:Rk,usageStore:zk,contextProvider:Hk,metricsProvider:Uk,tmuxService:Wk,log:Y,clock:()=>new Date};function bA(e,t){let n=uk.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,mA),{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 xA={connectMs:200,budgetMs:500};async function SA(e){let n=e.includes(`--json`),r=await CA();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Hv(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
187
|
+
`);return}t.stdout.write(DA(r.value))}function CA(){return Iv({kind:`stats`},xA,e=>`stats`in e?e.stats:void 0)}function wA(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function TA(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function EA(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 DA(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${EA(e.uptimeSec)}`),t.push(` rss ${wA(e.rssBytes)}`),t.push(` heapUsed ${wA(e.heapUsedBytes)}`),t.push(` heapTotal ${wA(e.heapTotalBytes)}`),t.push(` external ${wA(e.externalBytes)}`),t.push(` arrayBuffers ${wA(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 ${TA(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 ${TA(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
188
188
|
`)+`
|
|
189
|
-
`}const
|
|
190
|
-
`);return}t.stdout.write(
|
|
191
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
189
|
+
`}const OA={connectMs:200,budgetMs:500};async function kA(e,n){let r=n.includes(`--json`),i=await AA(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Hv(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
190
|
+
`);return}t.stdout.write(jA(i.value))}function AA(e){return Iv({kind:`debug`,what:e},OA,e=>`debug`in e?e.debug:void 0)}function jA(e){switch(e.what){case`vars`:return MA(e.vars);case`segments`:return NA(e.segments);case`config`:return PA(e.config);default:return e}}function MA(e){if(e.length===0)return`no variables (DSL not active)
|
|
191
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${IA(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${FA(a.value)}${e}${o}`)}return t.join(`
|
|
192
192
|
`)+`
|
|
193
|
-
`}function
|
|
193
|
+
`}function NA(e){if(e.length===0)return`no segments (DSL not active)
|
|
194
194
|
`;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
|
|
195
195
|
`)+`
|
|
196
|
-
`}function
|
|
196
|
+
`}function PA(e){return e===null?`config: DSL not active
|
|
197
197
|
`:JSON.stringify(e,null,2)+`
|
|
198
|
-
`}function
|
|
199
|
-
`));return l.rendered}finally{c.dispose()}}function
|
|
200
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output
|
|
198
|
+
`}function FA(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function IA(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function LA(){let e=zA();return e===null?null:r.readFileSync(e,`utf-8`)}function RA(){let e;try{e=LA()}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 zA(){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 BA(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const VA=5e3;function HA(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function UA(e,t){let n=dv(e,e),r=pv(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function WA(e,n=t.cwd()){let i=[],a=e===void 0?UA(n,i):c.resolve(cv(e));if(e!==void 0&&a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let o=hv(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await GA(a,n,i)}}catch(e){let t=e;return a!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===a&&typeof t.message==`string`?{kind:`unreadable`,path:a,message:t.message}:(e instanceof da&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof da||e instanceof Error?e.message:String(e),warnings:i})}}async function GA(e,t,n){let{config:r,source:i,warnings:a}=gv(e,kw);n.push(...a);let o=yv(r,e??`<default>`,i),s=new hD,c=new YT(s,o.globals.default_empty_value??``,void 0,new ED);try{let e=oD(o,c,{cwd:t});n.push(...e.loadWarnings);let r=await c.settled(VA);r.length>0&&n.push(`source${r.length===1?``:`s`} still running after ${VA} ms, rendered with fallback values: ${r.join(`, `)}`),TS(o);let i=rw(o,()=>null,()=>!1),a=t=>{let n=new Map;return{rendered:sD(o,e,s,c,HA(t),cE(t.theme),{style:t.style,separator:t.separator,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:fi(o.looks,t.look),preset:t.preset}),segmentErrors:n}},l=a(i),u=a({...i,presetCustomized:!0}),d=[...[...l.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...u.segmentErrors].filter(([e])=>!l.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(d.length>0)throw Error(`config renders with ${d.length} segment error${d.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+d.map(e=>` ${e}`).join(`
|
|
199
|
+
`));return l.rendered}finally{c.dispose()}}function KA(e){return e.map(e=>`warning: ${e}\n`).join(``)}function qA(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:KA(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:KA(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const JA=`--render`,YA=`Usage: cc-candybar check [${JA}] [config-file]\n`;function XA(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==JA);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${YA}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${YA}`}:{kind:`run`,target:n[0],render:t.includes(JA)}}async function ZA(e){let n=XA(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:qA(await WA(n.target??BA(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const QA=`${dx}${ux}`;function $A(e){return`${QA}⚠ cc-candybar: ${ej(e)}[0m\n`}function ej(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: ${lx(e.message,60)}`;case`render_failed`:return`render failed: ${lx(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${lx(e.message,60)}`}}function tj(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
200
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:$A(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function nj(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}function rj({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:` (fix: click ☰ 🧰 tools ▸ 🩺 doctor, then [fix] on the bar)`}\n`}function ij(e,t){let n;try{n=EO(e,Nh(t))}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let r=Ih(n);return{stdout:r.map(rj).join(``),stderr:``,code:+!r.every(e=>e.verdict.ok)}}function aj(e){e.length>0&&(t.stderr.write(`doctor: takes no arguments
|
|
201
201
|
Usage: cc-candybar doctor
|
|
202
|
-
`),t.exit(2));let n=
|
|
202
|
+
`),t.exit(2));let n=ij(xO(),t.env);t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}function oj(){return nj(t.env.COLUMNS,t.stderr.columns)}function sj(){return nj(t.env.LINES,t.stderr.rows)}const cj=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],lj=e=>e.some(e=>t.argv.includes(e));function uj(){return cj.some(e=>(t.env[e]??``)!==``)}function dj(){console.log(yh)}async function fj(){try{lj(gh.help)&&(dj(),t.exit(0)),lj(gh.version)&&(console.log(`cc-candybar ${nb}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Ib(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(jb(),t.exit(0)),e===`url-handle`){await Nb(t.argv[3]);return}if(e===`daemon`){$k();return}if(e===`daemon-stats`&&(await SA(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await ZA(t.argv.slice(3));return}if(e===`schema`){RA();return}if(e===`doctor`){aj(t.argv.slice(3));return}Dk(e)&&(await kA(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
203
203
|
|
|
204
204
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
205
205
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -215,4 +215,4 @@ Add to ~/.claude/settings.json:
|
|
|
215
215
|
Run with --help for more options.
|
|
216
216
|
|
|
217
217
|
To test output manually:
|
|
218
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
218
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),dj(),t.exit(1));let i=tj(await Kv(r,t.argv,t.cwd(),{termCols:oj(),termRows:sj(),ssh:uj(),tmux:Nh(t.env),configEnv:BA(t.env)}));i.debug!==null&&E(i.debug),i.kick&&hy(),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)}}fj();export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptctl/cc-candybar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.67.0",
|
|
4
4
|
"description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -90,9 +90,9 @@
|
|
|
90
90
|
"mobx": "^6.15.0"
|
|
91
91
|
},
|
|
92
92
|
"optionalDependencies": {
|
|
93
|
-
"@promptctl/cc-candybar-darwin-arm64": "1.
|
|
94
|
-
"@promptctl/cc-candybar-darwin-x64": "1.
|
|
95
|
-
"@promptctl/cc-candybar-linux-x64": "1.
|
|
96
|
-
"@promptctl/cc-candybar-linux-arm64": "1.
|
|
93
|
+
"@promptctl/cc-candybar-darwin-arm64": "1.67.0",
|
|
94
|
+
"@promptctl/cc-candybar-darwin-x64": "1.67.0",
|
|
95
|
+
"@promptctl/cc-candybar-linux-x64": "1.67.0",
|
|
96
|
+
"@promptctl/cc-candybar-linux-arm64": "1.67.0"
|
|
97
97
|
}
|
|
98
98
|
}
|