@promptctl/cc-candybar 1.61.2 → 1.61.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +5 -5
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -118,7 +118,7 @@ Config tooling:
118
118
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
119
119
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
120
120
  Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Dc(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Mg(e,t.actions)),t.looks!==void 0&&(r.looks=b_(e,t.looks)),t.presets!==void 0&&(r.presets=S_(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=So(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=C_(e,t.helpers)),Fc(e,r),Rm(e,r),Km(e,r),hs(e,r,fs,`the global settings menu`),r}const bv=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function xv(e){let t=Tv(e.termCols),n=Tv(e.termRows),r=Ev(e.ssh),i=Cv(e.tmux),a=Sv(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 Sv(e){return typeof e==`string`&&e!==``?rv(e):void 0}function Cv(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 wv=1e4;function Tv(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>wv?wv:t}function Ev(e){return typeof e==`boolean`?e:void 0}var Dv=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Ov(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function kv(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 Dv(`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 Dv(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Av(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=kv(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(Ov(t))})}async function jv(e,t,n){let r=null;try{r=await Iv(Ne(),t.connectMs);let i=await Av(r,{v:3,...e},t.budgetMs);return Pv(e.kind,i,n)}catch(e){return Fv(e)}finally{r&&r.destroy()}}function Mv(e,t){return typeof e==`string`?e:t}function Nv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Pv(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=Mv(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Nv(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 Fv(e){if(e instanceof Dv||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 Iv(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 Lv(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 Rv={connectMs:50,budgetMs:150},zv={connectMs:50,budgetMs:200};function Bv(e){let t=e.output;return typeof t==`string`?t:void 0}function Vv(e,t,n,r){return jv({kind:`render`,hookData:e,args:t,cwd:n,...r},Rv,Bv)}function Hv(e,t){return jv({kind:`click`,verb:e,value:t},zv,Bv)}let Uv=null;function Wv(e){if(Uv!==null)return Uv;r.mkdirSync(c.dirname(e),{recursive:!0});try{Uv=r.statSync(e).size}catch{Uv=0}return Uv}function Gv(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{}Uv=0}function Y(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ge(),t=Wv(e);r.appendFileSync(e,n),Uv=t+Buffer.byteLength(n,`utf8`),Uv>=5242880&&Gv(e)}catch(e){Uv=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const Kv=`CC_CANDYBAR_RSS_LIMIT_MB`;function qv(e){let t=e[Kv];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Kv} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Jv(e){return qv(e)*2}const Yv=1024*1024;function Xv(e){return qv(e)*Yv}function Zv(e){let t=e.rssLimitBytes??512*Yv,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=c.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),Qv(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function Qv(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function $v(e,t,n={}){let i=Me();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Y,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listSnapshots:()=>{try{return r.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function ey(e={}){if(gy()!==null)return;let n=e.spawn??_y,r=py();if(r.kind===`contended`){let e=ny();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),ty(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),ty(n);return}try{ty(n)}finally{hy()}}function ty(e){ly()&&ry(e)}function ny(){try{let e=r.statSync(Ve());return Date.now()-e.mtimeMs}catch{return null}}function ry(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
121
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function iy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ay(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function oy(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(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function ly(){let e=He(),n=Ue(),r=oy(n),i=iy(uy(e),ay(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`),dy(e),sy(n,Math.min(r+1,5)),!0)}function uy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function dy(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 fy=null;function py(){let e=Ve();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return fy={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(!my(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 my(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function hy(){if(!fy)return;let{fd:e,path:t}=fy;fy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function gy(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function _y(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${Jv(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const vy=`cc-candybar`,yy=`dispatch`,by=`set-state`,xy=`step-state`,Sy=`copy`,Cy=`open-vscode`,wy=`toolbar-toggle`,Ty=`show-config-error`,Ey=`show-config-warning`,Dy=`set-config`,Oy=`step-config`,ky=`reset-config`,Ay=`apply-layout-op`,jy=`undo`,My=`redo`,Ny=`apply-update`,Py=`doctor-run`,Fy=`doctor-fix`;function Iy(e){return e.map(encodeURIComponent).join(`/`)}function Ly(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Ry(e){return`${vy}://${yy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Iy(e.args)}`)}`).join(`&`)}`}function zy(e){return new y(e).getAll(`e`).map(By)}function By(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Vy=`1.61.2`;function Hy(){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 Uy(e,t){return e?.kind===`ok`?e.value:t}const Wy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Gy(e){let t=Wy.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 Ky(e){return e.join(`.`)}function qy([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Jy=`@promptctl/cc-candybar`;async function Yy(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`?Gy(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function Xy(e,t){let n=Gy(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=qy(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 Zy(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Ky(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Ky(t.installed)} is newer than the registry's latest release (${Ky(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Ky(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Ky(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 Qy=`CCCandybarURLHandler`,$y=[],eb={"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 tb(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function nb(e,t){return[e,...t].map(tb).join(` `)}function rb(){return c.join(f.homedir(),`Applications`,`${Qy}.app`)}function ib(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function ab(){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 ob(){return c.join(ab(),`bin`,`cc-candybar`)}function sb(){return c.join(ab(),`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(`
121
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function iy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ay(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function oy(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(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function ly(){let e=He(),n=Ue(),r=oy(n),i=iy(uy(e),ay(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`),dy(e),sy(n,Math.min(r+1,5)),!0)}function uy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function dy(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 fy=null;function py(){let e=Ve();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return fy={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(!my(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 my(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function hy(){if(!fy)return;let{fd:e,path:t}=fy;fy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function gy(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function _y(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${Jv(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const vy=`cc-candybar`,yy=`dispatch`,by=`set-state`,xy=`step-state`,Sy=`copy`,Cy=`open-vscode`,wy=`toolbar-toggle`,Ty=`show-config-error`,Ey=`show-config-warning`,Dy=`set-config`,Oy=`step-config`,ky=`reset-config`,Ay=`apply-layout-op`,jy=`undo`,My=`redo`,Ny=`apply-update`,Py=`doctor-run`,Fy=`doctor-fix`;function Iy(e){return e.map(encodeURIComponent).join(`/`)}function Ly(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Ry(e){return`${vy}://${yy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Iy(e.args)}`)}`).join(`&`)}`}function zy(e){return new y(e).getAll(`e`).map(By)}function By(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Vy=`1.61.3`;function Hy(){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 Uy(e,t){return e?.kind===`ok`?e.value:t}const Wy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Gy(e){let t=Wy.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 Ky(e){return e.join(`.`)}function qy([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Jy=`@promptctl/cc-candybar`;async function Yy(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`?Gy(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function Xy(e,t){let n=Gy(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=qy(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 Zy(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Ky(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Ky(t.installed)} is newer than the registry's latest release (${Ky(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Ky(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Ky(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 Qy=`CCCandybarURLHandler`,$y=[],eb={"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 tb(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function nb(e,t){return[e,...t].map(tb).join(` `)}function rb(){return c.join(f.homedir(),`Applications`,`${Qy}.app`)}function ib(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function ab(){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 ob(){return c.join(ab(),`bin`,`cc-candybar`)}function sb(){return c.join(ab(),`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(`
122
122
  `)}function lb(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 ub(t){let n=eb[`${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 db(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function fb(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 ${Jy}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function pb(){let e=lb(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=ub(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(ob()),{recursive:!0}),db(e,sb()),db(t.sourcePath,ob()),r.chmodSync(ob(),493),r.rmSync(c.join(ab(),`url-handler.mjs`),{force:!0});let n=fb(ob());return process.stdout.write(`Staged cc-candybar v${Vy} runtime at ${ab()}\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:ob(),distPath:sb(),entryKind:n}}function mb(){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>${vy}</string>`,` </array>`,` </dict>`,`</array>`].join(`
123
123
  `)}]}function hb(e){let t=rb();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=Ee({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,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 mb())Ee({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of mb()){let n=Ee({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${vy}:// with Launch Services\n`);let a=Ee({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${Qy}.app installed and registered.\n`),process.stdout.write(` Test: open '${vy}://hello-world' && pbpaste\n`)}function gb(){ib(),hb(pb().distPath)}function _b(e,t=vy){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:Sy,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function vb(e){e||(process.stderr.write(`url-handle: missing URL argument.
124
124
  `),process.exit(1));let t;try{t=_b(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await Hv(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(ey(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(yb(n)+`
@@ -131,7 +131,7 @@ Config tooling:
131
131
  `)?r.slice(0,-1):r}return Vr(new jr([...e],n),{colorSystem:t.colorCompatibility})}function ax(e){return Math.min(20,e??20)}const ox={heading:`ERROR`,glyph:`⚠`,colors:Qb},sx={heading:`WARNING`,glyph:`⚠`,colors:$b},cx={heading:`UPDATE`,glyph:`⬆`,colors:$b};function lx(e,t){return{text:qb(e),link:t}}function ux(e,t,n){let[r,...i]=[dx(e,ox,Ty),t,dx(n,sx,Ey)].flat();return r===void 0?null:{channels:[r,...i]}}function dx(e,t,n){let r=Ry([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>lx(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function fx(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
132
132
  `)}function px(e,t,n,r){if(t===null)return e;let i=mx(r),a=t.channels.flatMap(e=>hx(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[gx(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
133
133
  `);return e?`${l}\n${e}`:l}function mx(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function hx(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=j(Math.max(2,t.width-1)),i=(e,t)=>new Ar(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>ix([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Bt(e,r)).map(e=>i(e,t))})],t).split(`
134
- `))}function gx(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: ${qb(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(qb(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,ix([m],r)}const _x=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function vx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function yx(e,t){return r.readdirSync(t).filter(_x).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?yx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),vx(i,a)]]})}function bx(e){let t=C.createHash(`sha256`);for(let[n,r]of yx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const xx=e=>e.slice(0,7);function Sx(e){return c.dirname(c.dirname(e))}function Cx(){return{version:Vy,digest:`e75baf58dbcde89ab29c419addbff8fbf8d1b68027099846befc2ae4df6464a3`}}function wx(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 Tx(e,t){try{let n=Sx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=bx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:wx(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 Ex=/^-?\d+$/;function Dx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ox(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 kx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Ex.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 Ax(e,t,n){return r=>r?Ex.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 jx(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=>!Ex.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:Dx(r[0].seed,t,i)}}return{kind:`int`}}function Mx(e){return e===`config`?`set-config`:`set-state`}function Nx(e,t,n){return t.kind===`int`?kx(`menu page "${e}"`):t.kind===`range`?Ax(t.min,t.max,`${n} stepper "${e}"`):Ox(t.allowed,`${n} "${e}"`,Mx(n))}function Px(e,t,n){return Nx(e,jx(e,t,n),n)}function Fx(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:jx(e,n,t)}))}function Ix(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=Px(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Px(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=Px(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=jx(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Lx=Ix({},`config`);function Rx(){return Lx.listKeys()}function zx(e,t){return Lx.validate(e,t)}function Bx(e){return Lx.rangeParamsFor(e)}function Vx(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:O_(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:O_(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:Dx(t.get(e.persist),e.min,e.max)}}]:[]}function Hx(e){return Do(e.globals)}function Ux(e){let t=new Set;for(let n of Gx(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=oh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:ah(e),spec:{kind:`allow-list`,allowed:[]}}))}function Wx(e){let t=Hx(e),n=new Map([...E_(e),...yh(e)]);return[...Ux(e),...Gx(e).flatMap(e=>Vx(e,t,n))]}function Gx(e){return Object.values(e.actions).flatMap(Tg)}function Kx(e){return Fx(Wx(e),`config`)}function qx(e,t){return Lx.register(e,t)}const Jx=li(),Yx=new Set(Jx),Xx=new Set(pi),Zx=e=>e?Yx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Jx.join(`, `)})`}:{ok:!1,reason:`theme name is required`},Qx=e=>e?Xx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},$x=new Set([`1`,`true`]),eS=new Set([`0`,`false`]),tS=Ix({style:Qx,theme:Zx,"toolbar-expanded":e=>$x.has(e)?{ok:!0,value:`1`}:eS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function nS(){return tS.listKeys()}function rS(e,t){return tS.register(e,t)}function iS(e,t){return tS.validate(e,t)}function aS(e){return tS.rangeParamsFor(e)}function oS(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:O_(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:Dx(t.get(e.set),e.min,e.max)}}]:[]}function sS(e){let t=new Set(tS.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 Do(e.globals))t.set(n,r);return t}function lS(e){let t=cS(e),n=E_(e);return sS(Object.values(e.actions).flatMap(Tg).flatMap(e=>oS(e,t,n)))}function uS(e){return Fx(lS(e))}const dS=`update.dismissed`,fS=`updateNotice`;function pS(e){return e.kind===`source`?e.newer.digest:Ky(e.newer)}const mS=e=>`${e.version} [${xx(e.digest)}]`;function hS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:mS(e.newer),running:mS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Ky(e.newer),running:Ky(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Jy}@${Ky(e.newer)}`,`install`]}}}}const gS={kind:`idle`},_S={kind:`running`};function vS(e,t,n){if(e===null)return[];let r=pS(e);if(!n.enabled||n.dismissed===r)return[];let i=hS(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(`
134
+ `))}function gx(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: ${qb(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(qb(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,ix([m],r)}const _x=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function vx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function yx(e,t){return r.readdirSync(t).filter(_x).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?yx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),vx(i,a)]]})}function bx(e){let t=C.createHash(`sha256`);for(let[n,r]of yx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const xx=e=>e.slice(0,7);function Sx(e){return c.dirname(c.dirname(e))}function Cx(){return{version:Vy,digest:`5dcb0f8ad0746da4553992762aa11807dd37f948ed88151119f4d22501a7b012`}}function wx(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 Tx(e,t){try{let n=Sx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=bx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:wx(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 Ex=/^-?\d+$/;function Dx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ox(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 kx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Ex.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 Ax(e,t,n){return r=>r?Ex.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 jx(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=>!Ex.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:Dx(r[0].seed,t,i)}}return{kind:`int`}}function Mx(e){return e===`config`?`set-config`:`set-state`}function Nx(e,t,n){return t.kind===`int`?kx(`menu page "${e}"`):t.kind===`range`?Ax(t.min,t.max,`${n} stepper "${e}"`):Ox(t.allowed,`${n} "${e}"`,Mx(n))}function Px(e,t,n){return Nx(e,jx(e,t,n),n)}function Fx(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:jx(e,n,t)}))}function Ix(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=Px(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Px(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=Px(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=jx(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Lx=Ix({},`config`);function Rx(){return Lx.listKeys()}function zx(e,t){return Lx.validate(e,t)}function Bx(e){return Lx.rangeParamsFor(e)}function Vx(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:O_(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:O_(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:Dx(t.get(e.persist),e.min,e.max)}}]:[]}function Hx(e){return Do(e.globals)}function Ux(e){let t=new Set;for(let n of Gx(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=oh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:ah(e),spec:{kind:`allow-list`,allowed:[]}}))}function Wx(e){let t=Hx(e),n=new Map([...E_(e),...yh(e)]);return[...Ux(e),...Gx(e).flatMap(e=>Vx(e,t,n))]}function Gx(e){return Object.values(e.actions).flatMap(Tg)}function Kx(e){return Fx(Wx(e),`config`)}function qx(e,t){return Lx.register(e,t)}const Jx=li(),Yx=new Set(Jx),Xx=new Set(pi),Zx=e=>e?Yx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Jx.join(`, `)})`}:{ok:!1,reason:`theme name is required`},Qx=e=>e?Xx.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},$x=new Set([`1`,`true`]),eS=new Set([`0`,`false`]),tS=Ix({style:Qx,theme:Zx,"toolbar-expanded":e=>$x.has(e)?{ok:!0,value:`1`}:eS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function nS(){return tS.listKeys()}function rS(e,t){return tS.register(e,t)}function iS(e,t){return tS.validate(e,t)}function aS(e){return tS.rangeParamsFor(e)}function oS(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:O_(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:Dx(t.get(e.set),e.min,e.max)}}]:[]}function sS(e){let t=new Set(tS.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 Do(e.globals))t.set(n,r);return t}function lS(e){let t=cS(e),n=E_(e);return sS(Object.values(e.actions).flatMap(Tg).flatMap(e=>oS(e,t,n)))}function uS(e){return Fx(lS(e))}const dS=`update.dismissed`,fS=`updateNotice`;function pS(e){return e.kind===`source`?e.newer.digest:Ky(e.newer)}const mS=e=>`${e.version} [${xx(e.digest)}]`;function hS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:mS(e.newer),running:mS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Ky(e.newer),running:Ky(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Jy}@${Ky(e.newer)}`,`install`]}}}}const gS={kind:`idle`},_S={kind:`running`};function vS(e,t,n){if(e===null)return[];let r=pS(e);if(!n.enabled||n.dismissed===r)return[];let i=hS(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(`
135
135
  `),c=Ry([{verb:Ey,args:[s]}]),l=t.kind===`running`?lx(`[${i.busy}]`,c):lx(`[${i.act}]`,Ry([{verb:Ny,args:[n.sessionId]}]));return[{severity:cx,message:s,lines:[[lx(a,c),l,lx(`[dismiss]`,Ry([{verb:by,args:[n.sessionId,dS,r]}])),lx(`[disable]`,Ry([{verb:Dy,args:[n.sessionId,fS,`false`]}]))],...o.map(e=>[lx(e,c)])]}]}function yS(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 bS(e){switch(e.kind){case`current`:return[`info`,`build: current ${mS(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${mS(e.source)}, running ${mS(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function xS(e){switch(e.kind){case`current`:return[`info`,`release: current ${Ky(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Ky(e.latest)}, running ${Ky(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Ky(e.installed)}, latest ${Ky(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function SS(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const CS=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function wS(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=CS(e.stderr)??e.error??CS(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function TS(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=gS,d=null,f=SS(s),p=SS(s),m=()=>yS(c,l);function h(){let e=m(),t=e===null?null:pS(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:rS(dS,{kind:`allow-list`,allowed:[t]})})}function g(){c=Tx(t,Cx),f(bS(c)),h()}async function _(){l=Xy(Vy,await Yy(Jy,a,i)),p(xS(l)),h()}return{arm(){qx(fS,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>vS(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=hS(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=_S,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Te({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=gS,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=wS(n);u={kind:`failed`,identity:pS(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function ES(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??DS(t.stderr)].filter(Boolean).join(`, `)}`)}function DS(e){return e.trim().split(`
136
136
  `,1)[0]??``}function OS(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Z:X(n)}function kS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?X(t):Z}const AS=/^[A-Za-z]:[\\/]/;function jS(e){let t=e.trim();if(AS.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 MS(e){return jS(e)?.host||null}function NS(e){let t=MS(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function PS(e){let t=new Map;for(let n of e.split(`
137
137
  `)){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 FS(e){return e.urls.find(e=>BS(e)!==null)??e.urls[0]??null}function IS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function LS(e){let t=IS(e);return t?FS(t):null}function RS(e){let t=IS(e);return t?t.urls.find(e=>NS(e)!==null)??FS(t):null}function zS(e){let t=(jS(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function BS(e){let t=jS(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 VS(e){let t=LS(e);return t===null?null:BS(t)}function HS(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??DS(t.stderr)].filter(Boolean).join(`, `)}`)}function US(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function WS(e){let t=`detached`,n=Z,r=Z,i=Z,a=0,o=0,s=0,c=0;for(let l of e.split(`
@@ -171,12 +171,12 @@ The target is already observable of different type.
171
171
  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 C(e,O,new Yi(e,new Map,String(r),It(t))),e}var Zi=te(`ObservableObjectAdministration`,Yi);function Qi(e){return qi[e]||(qi[e]={get:function(){return this[O].getObservablePropValue_(e)},set:function(t){return this[O].setObservablePropValue_(e,t)}})}function $i(e){return b(e)?Zi(e[O]):!1}function ea(e,t,n){var r;e.appliedAnnotations_[n]=t,(r=e.target_[Te])==null||delete r[n]}function ta(e,t,r){if(Sa(t)||n(`Cannot annotate '`+e.name_+`.`+r.toString()+`': Invalid annotation.`),!Ke(t)&&se(e.appliedAnnotations_,r)){var i=e.name_+`.`+r.toString(),a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '`+o+`' to '`+i+`':`+(`
172
172
  The field is already annotated with '`+a+`'.`)+`
173
173
  Re-annotating fields is not allowed.
174
- 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,ee(a,O,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}_e(t,e);var n=t.prototype;return n.concat=function(){this[O].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}}})},me(t,[{key:`length`,get:function(){return this[O].getArrayLength_()},set:function(e){this[O].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`&&C(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[O].get_(e)},set:function(t){this[O].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[O].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[O].values_.get(t);return i||n(27,t,pa(e)),i}if(Ne(e)||en(e)||B(e))return e}else if(v(e)&&B(e[O]))return e[O];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Ne(e)||en(e)||B(e)||Bi(e)||Gi(e))return e;if(e[O])return e[O];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=I(),n=Yt(!0);kn();try{return e()}finally{An(),Xt(n),mn(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(!(se(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():ne(e)||Bi(e)||w(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:qn,extras:{getDebugName:pa},$mobx:O}),e.$mobx=O,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=In,e._allowStateChanges=N,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=gn,e._allowStateReadsStart=hn,e._autoAction=ar,e._endAction=Jt,e._getAdministration=fa,e._getGlobalState=Cn,e._interceptReads=Fr,e._isComputingDerivation=on,e._resetGlobalState=wn,e._startAction=M,e.action=ir,e.autorun=cr,e.comparer=ze,e.computed=Vt,e.configure=br,e.createAtom=Pe,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=$t,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=j,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Ln,e.override=Ge,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=qn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=pn,e.values=Kr,e.when=li})),gw=pe(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=mw():t.exports=hw()}))();function _w(e){if(Array.isArray(e))return Object.freeze(e.map(_w));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]=_w(r);return Object.freeze(t)}return e}function vw(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 yw(e){return typeof e==`string`?e:String(e)}function bw(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 xw(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 Sw(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 Cw(e){return{fn:(t=>Sw(t,e)),argTypes:[`liftable`],returnType:`T`}}function ww(e){return{fn:((t,n)=>Sw(n,new H({[e]:P.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Tw(e,t){return new H({[e]:t})}function Ew(){let e={};for(let t of lr)e[t]=Cw(Tw(t,!0)),e[`not_${t}`]=Cw(Tw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=Cw(Tw(n,!0));return e}const Dw={fn:((e,t)=>Sw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ow={fn:((e,t)=>Sw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function kw(){return{fg:ww(`color`),bg:ww(`bgcolor`),...Ew(),link:Ow,style:Dw}}function Aw(e,t){if(!En.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 Dn(e)}function jw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Mw(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 Nw=jw([`string`,`int`],((e,t)=>Pn(Aw(e,`darken`),Mw(t,`darken`,`levels`)).hex)),Pw=jw([`string`,`int`],((e,t)=>Pn(Aw(e,`lighten`),-Mw(t,`lighten`,`levels`)).hex)),Fw={min:0,max:100,note:`0 = from, 100 = toward`},Iw=jw([`string`,`string`,`float`],((e,t,n)=>sn(Aw(e,`mix`),Aw(t,`mix`),Mw(n,`mix`,`percentage`,Fw)/100).hex)),Lw={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},Rw=jw([`string`],(e=>Fn(Aw(e,`contrastOn`)).hex)),zw=jw([`string`,`string`,`float`],((e,t,n)=>Rn(Aw(e,`readableOn`),Aw(t,`readableOn`),Mw(n,`readableOn`,`ratio`,Lw)).hex)),Bw={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function Vw(){let e={};for(let[t,n]of Object.entries(Bw)){let r=t;e[n]=jw([`string`,`float`],((e,t)=>{let i={...hn,[r]:Mw(t,n,`amount`)};return R.fromRgba(Aw(e,n)).applyKey(i).toRgba().hex}))}return e}function Hw(){return{darken:Nw,lighten:Pw,mix:Iw,contrastOn:Rw,readableOn:zw,...Vw()}}function Uw(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:On(t,e[r+1])});return n}function Ww(e){return{color:{fn:(t=>On(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),Uw(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function Gw(){return{...kw(),...Hw()}}new H({color:`red`,dim:!0});const Kw=/^(?:(?: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,qw=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function Jw(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(Kw);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(qw);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 Yw(e){let t=e.match(qw);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 Xw(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 Zw(e){return e.toLocaleString()}const Qw=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],$w=Qw.length;function eT(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*($w-1));o+=Qw[t]}return o}function tT(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 nT=li(),rT=[...pi];function iT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>Xw(e),argTypes:[`string`]},int:{fn:e=>bw(e),argTypes:[`value`]},string:{fn:e=>yw(e),argTypes:[`value`]},bool:{fn:e=>xw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>nT,argTypes:[]},styles:{fn:()=>rT,argTypes:[]},sparkline:{fn:(e,t)=>eT(tT(e),t),argTypes:[`string`,`int`]}}}function aT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>Zw(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>Jw(e),argTypes:[`string`]},shortenModelName:{fn:e=>Yw(e),argTypes:[`string`]}}}function oT(e,t=()=>new Date){return xu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...lf(),...ym(),...Yf(),..._p(),...ef(t),...Wu(),...Cf(),...Gw(),...iT(),...aT(t),...e??{}}})}function sT(e){return cT(e,new Set(e.names()),``)}function cT(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`?lT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return cT(e,t,a)}})}function lT(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 uT=/\r\n|\r|\n/g,dT=e=>X(e.replace(uT,` `).trim());function fT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(uT,` `))}}const pT=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:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function hT(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 gT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Te({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?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 _T(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await w(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 vT(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 yT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],bT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],xT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],ST=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function CT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>yT[e.getMonth()]],[`Monday`,e=>xT[e.getDay()]],[`Jan`,e=>bT[e.getMonth()]],[`Mon`,e=>ST[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 wT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function TT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=wT[t];try{return kT(r,e)}catch{return AT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Uy(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Uy(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Uy(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Uy(e.stashCount,0)}}var ET=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}},DT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:oe(()=>{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&&(ae(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ae(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function OT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function kT(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`?yw(e):t===`number`?bw(e):xw(e)}function AT(e){return e===`number`?0:e===`boolean`?!1:``}var jT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new ET;ttlMgr=new DT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new XS;abort=new AbortController;engine=oT();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new rC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,vw(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,gT(t,this.abort.signal),mT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,_T(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,fT(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=vT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,Uy(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=vT(i,pT,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=sT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return CT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,CT(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=wT[t.field],r=t.varDefault===void 0?AT(n):kT(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,TT(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=OT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,kT(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,gw.reaction)(()=>{let t=sT(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,gw.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,kT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,AT(t))}}defaultFor(e){try{return kT(this.defaultEmptyValue,e)}catch{return AT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const MT=new Map,NT=new Map;function PT(e){let t=ai(e),n=MT.get(t);if(n!==void 0)return n;let r=Gn(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 MT.set(t,r),r}function FT(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=NT.get(n);if(r!==void 0)return r;let i=tr(e,t);return NT.set(n,i),i}function IT(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=LT(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=LT([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function LT(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>RT(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 RT(e,t){let n=e.copy();return n.style=t.add(e.style),n}function zT(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function BT(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function VT(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=BT(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var HT=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function UT(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=WT(o,c),d=u===void 0?i:GT(n,u,`bg`);l.bg=d;let f=WT(s,c),p=f===void 0?a(d):GT(n,f,`fg`);return new H({bgcolor:P.fromRgba(d),color:p===void 0?void 0:P.fromRgba(p)})}function WT(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function GT(e,t,n){try{return On(e,t)}catch(e){throw e instanceof Tn?new HT(t,n,e.message):e}}const KT=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 qT(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,JT(e,a,o,n,r));return i}function JT(e,t,n,r,i){if(wg(n)){let[a,o]=Tg(n);return YT(r.get(n.persistWhen)??n.persistWhen,n.set,JT(e,t,a,r,i),JT(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:[...O_(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=KT.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:[...O_(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:[...O_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:ZT(e,n.copy,t)}:`open`in n?{kind:`open`,target:ZT(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 YT(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 XT(e,t){return e.kind===`dual`?Si(QT(t,e.selector))===!0?e.durable:e.session:e}function ZT(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function QT(e,t){return e.has(t)?yw(e.read(t)):``}function $T(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function eE(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 tE(e,t){return Math.max(e.members.indexOf(QT(t,e.stateVar)),0)}function nE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(tE(e,r)+1)%e.members.length];return{effects:[{verb:by,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:xy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Sy,args:[$T(e.text,sT(r))]}],active:!1};case`open`:return{effects:[{verb:Cy,args:[$T(e.target,sT(r))]}],active:!1};case`persist-literal`:{let t=QT(r,e.stateVar);return{effects:[{verb:Dy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:Dy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(tE(e,r)+1)%e.members.length];return{effects:[{verb:Dy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Oy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ky,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:jy,args:[i]}],active:!1};case`redo`:return{effects:[{verb:My,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Py,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Ay,args:[i,e.key,qm(e.op)]}],active:!1};case`dual`:{let a=XT(e,r),{effects:o,active:s}=nE(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:Ay,args:[i,e.key,qm(r)]}],active:!1}}}}function rE(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:rc(`action "${e}"`,n,t.members.length,tE(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 iE(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}=rE(e,XT(r,i),t,i),{effects:s,active:c}=nE(r,a,o,i,QT(i,`session.id`));return eE(a,Ry(s),c)}function aE(e){return{action:{fn:(t,...n)=>iE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function oE(e,t){return new H({bgcolor:P.fromRgba(t),color:P.fromRgba(Us(e,t))})}function sE(e,t){return oE(e.palette,Ys(e.palette,e.disclosure,[t]))}function cE(){return{current:null}}function lE(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 uE(e){return new Ar(e).cellLength}function dE(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 pE(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 mE(e,t){let n=e.compiled.get(t),r=n&&XT(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 hE(e,t,n,r,i,a,o){let s=mE(a,e),c=a.compiled.get(e),l=a.store,u=QT(l,`session.id`),d=`stateVar`in s?QT(l,s.stateVar):void 0,f=s.options.map(uE),p=i?Math.max(1,bw(l.read(`term.cols`))-rx(a.stripStyle)-2*a.padding):1/0,m=uE(`✕`)+1,h=uE(`←`)+1+uE(`→`)+1,g=dE(f,p,m),_=g.length>1?dE(f,p,m+h):g,v=parseInt(QT(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>Ry([{verb:by,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=Ry([{verb:by,args:[u,...S]}]),ee=r?[{verb:by,args:[u,...S]}]:[],te=e=>{let{effects:t}=nE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?Ry([{verb:by,args:[...n.args,...r?S:[]]}]):Ry([...t,...ee])},ne=[eE(`✕`,C,!1)];y>0&&ne.push(eE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];ne.push(eE(t,te(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&ne.push(eE(`→`,x(y+1),!1)),fE(ne,i)}function gE(e,t){return{picker:{fn:(n,r,i,a)=>{let o=pE(e,r,`set-int`,`an int action ({ set, int: true })`);return hE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>sE(lE(t,`{{ picker }}`),{...e,distribution:Ns(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const _E=Symbol(`cc-candybar.menuDrop`);function vE(e){return e.flatMap(e=>e[_E]??[])}function yE(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=Sm(i.segName,e,n.key),s=wm(o),c=xm(e),l=QT(a.store,o)===c,u=QT(a.store,`session.id`),d=l?tc:c,f=eE(rc(`{{ menu "${e}" }}`,t,2,+!!l),Ry([{verb:by,args:[u,o,d,s,`0`]}]),!1);return f[_E]=l?[hE(e,{key:s,stateVar:s},[[o,tc],[s,`0`]],n.closeOnPick,n.paged,a,e=>sE(i,{...e,distribution:n.distribution}))]:[],f}const bE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function xE(e,t){let n=t[t.length-1],r=bE(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:Om(r??{})}}function SE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=xE(t,n);return yE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function CE(e){let t={fn:(()=>{let t=lE(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`};return{...Ww(()=>lE(e,`{{ color }} / {{ ramp }}`).palette),bgOf:t}}function wE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
174
+ 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,ee(a,O,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}_e(t,e);var n=t.prototype;return n.concat=function(){this[O].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}}})},me(t,[{key:`length`,get:function(){return this[O].getArrayLength_()},set:function(e){this[O].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`&&C(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[O].get_(e)},set:function(t){this[O].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[O].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[O].values_.get(t);return i||n(27,t,pa(e)),i}if(Ne(e)||en(e)||B(e))return e}else if(v(e)&&B(e[O]))return e[O];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Ne(e)||en(e)||B(e)||Bi(e)||Gi(e))return e;if(e[O])return e[O];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=I(),n=Yt(!0);kn();try{return e()}finally{An(),Xt(n),mn(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(!(se(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():ne(e)||Bi(e)||w(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:qn,extras:{getDebugName:pa},$mobx:O}),e.$mobx=O,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=In,e._allowStateChanges=N,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=gn,e._allowStateReadsStart=hn,e._autoAction=ar,e._endAction=Jt,e._getAdministration=fa,e._getGlobalState=Cn,e._interceptReads=Fr,e._isComputingDerivation=on,e._resetGlobalState=wn,e._startAction=M,e.action=ir,e.autorun=cr,e.comparer=ze,e.computed=Vt,e.configure=br,e.createAtom=Pe,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=$t,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=j,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Ln,e.override=Ge,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=qn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=pn,e.values=Kr,e.when=li})),gw=pe(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=mw():t.exports=hw()}))();function _w(e){if(Array.isArray(e))return Object.freeze(e.map(_w));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]=_w(r);return Object.freeze(t)}return e}function vw(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 yw(e){return typeof e==`string`?e:String(e)}function bw(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 xw(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 Sw(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 Cw(e){return{fn:(t=>Sw(t,e)),argTypes:[`liftable`],returnType:`T`}}function ww(e){return{fn:((t,n)=>Sw(n,new H({[e]:P.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Tw(e,t){return new H({[e]:t})}function Ew(){let e={};for(let t of lr)e[t]=Cw(Tw(t,!0)),e[`not_${t}`]=Cw(Tw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=Cw(Tw(n,!0));return e}const Dw={fn:((e,t)=>Sw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ow={fn:((e,t)=>Sw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function kw(){return{fg:ww(`color`),bg:ww(`bgcolor`),...Ew(),link:Ow,style:Dw}}function Aw(e,t){if(!En.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 Dn(e)}function jw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Mw(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 Nw=jw([`string`,`int`],((e,t)=>Pn(Aw(e,`darken`),Mw(t,`darken`,`levels`)).hex)),Pw=jw([`string`,`int`],((e,t)=>Pn(Aw(e,`lighten`),-Mw(t,`lighten`,`levels`)).hex)),Fw={min:0,max:100,note:`0 = from, 100 = toward`},Iw=jw([`string`,`string`,`float`],((e,t,n)=>sn(Aw(e,`mix`),Aw(t,`mix`),Mw(n,`mix`,`percentage`,Fw)/100).hex)),Lw={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},Rw=jw([`string`],(e=>Fn(Aw(e,`contrastOn`)).hex)),zw=jw([`string`,`string`,`float`],((e,t,n)=>Rn(Aw(e,`readableOn`),Aw(t,`readableOn`),Mw(n,`readableOn`,`ratio`,Lw)).hex)),Bw={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function Vw(){let e={};for(let[t,n]of Object.entries(Bw)){let r=t;e[n]=jw([`string`,`float`],((e,t)=>{let i={...hn,[r]:Mw(t,n,`amount`)};return R.fromRgba(Aw(e,n)).applyKey(i).toRgba().hex}))}return e}function Hw(){return{darken:Nw,lighten:Pw,mix:Iw,contrastOn:Rw,readableOn:zw,...Vw()}}function Uw(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:On(t,e[r+1])});return n}function Ww(e){return{color:{fn:(t=>On(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),Uw(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function Gw(){return{...kw(),...Hw()}}new H({color:`red`,dim:!0});const Kw=/^(?:(?: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,qw=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function Jw(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(Kw);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(qw);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 Yw(e){let t=e.match(qw);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 Xw(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 Zw(e){return e.toLocaleString()}const Qw=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],$w=Qw.length;function eT(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*($w-1));o+=Qw[t]}return o}function tT(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 nT=li(),rT=[...pi];function iT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>Xw(e),argTypes:[`string`]},int:{fn:e=>bw(e),argTypes:[`value`]},string:{fn:e=>yw(e),argTypes:[`value`]},bool:{fn:e=>xw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>nT,argTypes:[]},styles:{fn:()=>rT,argTypes:[]},sparkline:{fn:(e,t)=>eT(tT(e),t),argTypes:[`string`,`int`]}}}function aT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>Zw(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>Jw(e),argTypes:[`string`]},shortenModelName:{fn:e=>Yw(e),argTypes:[`string`]}}}function oT(e,t=()=>new Date){return xu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...lf(),...ym(),...Yf(),..._p(),...ef(t),...Wu(),...Cf(),...Gw(),...iT(),...aT(t),...e??{}}})}function sT(e){return cT(e,new Set(e.names()),``)}function cT(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`?lT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return cT(e,t,a)}})}function lT(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 uT=/\r\n|\r|\n/g,dT=e=>X(e.replace(uT,` `).trim());function fT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(uT,` `))}}const pT=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:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function hT(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 gT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Te({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?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 _T(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await w(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 vT(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 yT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],bT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],xT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],ST=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function CT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>yT[e.getMonth()]],[`Monday`,e=>xT[e.getDay()]],[`Jan`,e=>bT[e.getMonth()]],[`Mon`,e=>ST[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 wT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function TT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=wT[t];try{return kT(r,e)}catch{return AT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Uy(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Uy(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Uy(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Uy(e.stashCount,0)}}var ET=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}},DT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:oe(()=>{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&&(ae(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ae(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function OT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function kT(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`?yw(e):t===`number`?bw(e):xw(e)}function AT(e){return e===`number`?0:e===`boolean`?!1:``}var jT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new ET;ttlMgr=new DT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new XS;abort=new AbortController;engine=oT();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new rC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,vw(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,gT(t,this.abort.signal),mT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,_T(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,fT(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=vT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,Uy(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=vT(i,pT,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=sT(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 CT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,CT(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=wT[t.field],r=t.varDefault===void 0?AT(n):kT(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,TT(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=OT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,kT(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,gw.reaction)(()=>{let t=sT(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,gw.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,kT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,AT(t))}}defaultFor(e){try{return kT(this.defaultEmptyValue,e)}catch{return AT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const MT=new Map,NT=new Map;function PT(e){let t=ai(e),n=MT.get(t);if(n!==void 0)return n;let r=Gn(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 MT.set(t,r),r}function FT(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=NT.get(n);if(r!==void 0)return r;let i=tr(e,t);return NT.set(n,i),i}function IT(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=LT(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=LT([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function LT(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>RT(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 RT(e,t){let n=e.copy();return n.style=t.add(e.style),n}function zT(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function BT(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function VT(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=BT(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var HT=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function UT(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=WT(o,c),d=u===void 0?i:GT(n,u,`bg`);l.bg=d;let f=WT(s,c),p=f===void 0?a(d):GT(n,f,`fg`);return new H({bgcolor:P.fromRgba(d),color:p===void 0?void 0:P.fromRgba(p)})}function WT(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function GT(e,t,n){try{return On(e,t)}catch(e){throw e instanceof Tn?new HT(t,n,e.message):e}}const KT=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 qT(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,JT(e,a,o,n,r));return i}function JT(e,t,n,r,i){if(wg(n)){let[a,o]=Tg(n);return YT(r.get(n.persistWhen)??n.persistWhen,n.set,JT(e,t,a,r,i),JT(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:[...O_(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=KT.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:[...O_(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:[...O_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:ZT(e,n.copy,t)}:`open`in n?{kind:`open`,target:ZT(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 YT(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 XT(e,t){return e.kind===`dual`?Si(QT(t,e.selector))===!0?e.durable:e.session:e}function ZT(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function QT(e,t){return e.has(t)?yw(e.read(t)):``}function $T(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function eE(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 tE(e,t){return Math.max(e.members.indexOf(QT(t,e.stateVar)),0)}function nE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:by,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(tE(e,r)+1)%e.members.length];return{effects:[{verb:by,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:xy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Sy,args:[$T(e.text,sT(r))]}],active:!1};case`open`:return{effects:[{verb:Cy,args:[$T(e.target,sT(r))]}],active:!1};case`persist-literal`:{let t=QT(r,e.stateVar);return{effects:[{verb:Dy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=QT(r,e.stateVar);return{effects:[{verb:Dy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(tE(e,r)+1)%e.members.length];return{effects:[{verb:Dy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Oy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ky,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:jy,args:[i]}],active:!1};case`redo`:return{effects:[{verb:My,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Py,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Ay,args:[i,e.key,qm(e.op)]}],active:!1};case`dual`:{let a=XT(e,r),{effects:o,active:s}=nE(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:Ay,args:[i,e.key,qm(r)]}],active:!1}}}}function rE(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:rc(`action "${e}"`,n,t.members.length,tE(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 iE(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}=rE(e,XT(r,i),t,i),{effects:s,active:c}=nE(r,a,o,i,QT(i,`session.id`));return eE(a,Ry(s),c)}function aE(e){return{action:{fn:(t,...n)=>iE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function oE(e,t){return new H({bgcolor:P.fromRgba(t),color:P.fromRgba(Us(e,t))})}function sE(e,t){return oE(e.palette,Ys(e.palette,e.disclosure,[t]))}function cE(){return{current:null}}function lE(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 uE(e){return new Ar(e).cellLength}function dE(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 pE(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 mE(e,t){let n=e.compiled.get(t),r=n&&XT(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 hE(e,t,n,r,i,a,o){let s=mE(a,e),c=a.compiled.get(e),l=a.store,u=QT(l,`session.id`),d=`stateVar`in s?QT(l,s.stateVar):void 0,f=s.options.map(uE),p=i?Math.max(1,bw(l.read(`term.cols`))-rx(a.stripStyle)-2*a.padding):1/0,m=uE(`✕`)+1,h=uE(`←`)+1+uE(`→`)+1,g=dE(f,p,m),_=g.length>1?dE(f,p,m+h):g,v=parseInt(QT(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>Ry([{verb:by,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=Ry([{verb:by,args:[u,...S]}]),ee=r?[{verb:by,args:[u,...S]}]:[],te=e=>{let{effects:t}=nE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?Ry([{verb:by,args:[...n.args,...r?S:[]]}]):Ry([...t,...ee])},ne=[eE(`✕`,C,!1)];y>0&&ne.push(eE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];ne.push(eE(t,te(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&ne.push(eE(`→`,x(y+1),!1)),fE(ne,i)}function gE(e,t){return{picker:{fn:(n,r,i,a)=>{let o=pE(e,r,`set-int`,`an int action ({ set, int: true })`);return hE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>sE(lE(t,`{{ picker }}`),{...e,distribution:Ns(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const _E=Symbol(`cc-candybar.menuDrop`);function vE(e){return e.flatMap(e=>e[_E]??[])}function yE(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=Sm(i.segName,e,n.key),s=wm(o),c=xm(e),l=QT(a.store,o)===c,u=QT(a.store,`session.id`),d=l?tc:c,f=eE(rc(`{{ menu "${e}" }}`,t,2,+!!l),Ry([{verb:by,args:[u,o,d,s,`0`]}]),!1);return f[_E]=l?[hE(e,{key:s,stateVar:s},[[o,tc],[s,`0`]],n.closeOnPick,n.paged,a,e=>sE(i,{...e,distribution:n.distribution}))]:[],f}const bE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function xE(e,t){let n=t[t.length-1],r=bE(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:Om(r??{})}}function SE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=xE(t,n);return yE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function CE(e){let t={fn:(()=>{let t=lE(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`};return{...Ww(()=>lE(e,`{{ color }} / {{ ramp }}`).palette),bgOf:t}}function wE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
175
175
  `)){n.push(r);continue}let e=r.split(`
176
176
  `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function TE(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 EE={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ns(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return TE(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(oc(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(!zT(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&&zT(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=wE(IT(o,u)).map(e=>VT(e,d)),p=s.map(e=>VT(IT([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 DE(e){return EE[e]}function OE(e){if(`ttl`in e)return{kind:`ttl`,durationMs:hT(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 kE(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 AE(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:OE(n.cache),parse:kE(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:OE(n.cache),parse:kE(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?hT(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 jE(e,t){let n=cl.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 ME(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=cE(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=Qm(e.presets),l=new Map([...E_(e),...yh(e)]),u=oT({...aE(i),...gE(i,a),...SE(o),...CE(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=jE(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=qT(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{AE(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{AE(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:PT(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 DE(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=th(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function NE(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=hn,preset:f=Xm}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=sT(n),m=FT(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}=ec(n,r),l=UT(t.activeSegment,e,n,c,o,s,i,a,p),u=qs(n,c);return{closed:l,trigger:oE(n,u.state),band:oE(n,u.plane),disclosure:c}},_=e=>(t.activeSegment.current=null,vE(e)),v=(e,t,n)=>{let r=t&&zT(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,Zs(n,r)),renderBody:(e,t,n)=>v(e,r&&t,Qs(n))};return DE(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 "${Xm}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return v(y,!0,Xs).map(e=>ix(e,o)).join(`
177
- `)}var PE=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,RE(e,t,n,`initial value`),this.cell=gw.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){RE(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},FE=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,gw.computed)(()=>{let e=n();return RE(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},IE=class{kind=`document`;cell;lastSetAt;constructor(e,t){this.name=e,this.cell=gw.observable.box(LE(t),{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){this.cell.set(LE(e)),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}};function LE(e){return e.kind===`ok`?{kind:`ok`,value:_w(e.value)}:e}function RE(e,t,n,r){let i=vw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var zE=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new PE(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new IE(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new FE(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,gw.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,gw.runInAction)(()=>n.set(t))}runInAction(e){(0,gw.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);return t.kind===`document`?JSON.stringify(t.read()):String(t.read())}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 BE(e,t,n){return e+`\0`+t+`\0`+(n??``)}function VE(e,t){return new Set(Qm(e.presets).filter(n=>th(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function HE(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 UE(e,t){let n=new Map;for(let t of iv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=HE(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 WE(e){return e.filter(Boolean).join(`
177
+ `)}var PE=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,RE(e,t,n,`initial value`),this.cell=gw.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){RE(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},FE=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,gw.computed)(()=>{let e=n();return RE(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},IE=class{kind=`document`;cell;lastSetAt;constructor(e,t){this.name=e,this.cell=gw.observable.box(LE(t),{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){this.cell.set(LE(e)),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}};function LE(e){return e.kind===`ok`?{kind:`ok`,value:_w(e.value)}:e}function RE(e,t,n,r){let i=vw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var zE=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new PE(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new IE(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new FE(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,gw.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,gw.runInAction)(()=>n.set(t))}runInAction(e){(0,gw.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 JSON.stringify(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 BE(e,t,n){return e+`\0`+t+`\0`+(n??``)}function VE(e,t){return new Set(Qm(e.presets).filter(n=>th(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function HE(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 UE(e,t){let n=new Map;for(let t of iv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=HE(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 WE(e){return e.filter(Boolean).join(`
178
178
  `)||null}var GE=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=BE(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=ov(e,t,n),i=r.kind===`file`?r.path:null,a=[uv(e,t),cv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof da&&a.push(...e.warnings),{resolvedPath:i,warning:WE(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:WE(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=dv(t,pw);n.push(...o);let s=mv(r,t??`<default>`,a),c=new zE,l=new jT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=ME(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of uS(s))d.push(rS(e,t));for(let{key:e,spec:t}of Kx(s))d.push(qx(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:XC(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:VE(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=UE(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 KE=16384;var qE=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<KE){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%KE}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:Vy,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 JE={load:()=>({}),save:()=>{},flush:()=>{}};function YE(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var XE=class{sessions;storage;atom=(0,gw.createAtom)(`SessionState`);constructor(e=JE,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=YE(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,gw.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,gw.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,gw.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 ZE=(e,t)=>D(t);function QE(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 $E=class{timer=null;pending=null;constructor(e,t=500,n=ZE){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 QE(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 eD={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`},tD=new Set([`1`,`true`]),nD=new Set([`0`,`false`,``]);function rD(e,t){let n=OD(e),r=n.scope===`globals`?eD[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(tD.has(t))return`true`;if(nD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function iD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function aD(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),ke(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function oD(e){return/^\s*$/.test(e)?null:ji(e)}function sD(e,t){return e!==null&&Ni(e,t)!==void 0}function cD(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(cD),...i}}return e}function lD(e){if(!ro(e))return cD(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,cD(t)])),...n}}const uD=dw,dD=uD.segments,fD=uD.presets,pD=uD.root;function mD(e,t,n,r){if(!sD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function hD(e,t){let n=sh(t);return t.scope===`segment-palette`&&mD(e,[`segments`,t.segment],dD[t.segment],n.join(`.`)),n}function gD(e){return ji(zi(e))}function _D(){return Object.entries(pD.rows).map(([e,t])=>{let n=cD(t);return{path:[`root`],fragment:gD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function vD(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=lD(t);return{path:e,fragment:gD(n),unit:{path:e,value:n}}}function bD(e,t){let n=[`presets`,t],r=[...n,`root`],i=fD[t];mD(e,n,i,r.join(`.`));let a=vD(e,r)??yD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function xD(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 SD(e,t){return[..._D(),vD(e,[`root`]),bD(e,t)].filter(e=>e!==null).reduce(xD,new Map)}function CD(e,t,n){for(let{node:r,...i}of SD(e,t).values())if(sa(r,n))return i;throw new $(`${wD(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function wD(e,t){return bD(e,t)?.path??[`root`]}function TD(e,t){return t.scope===`preset-root`?wD(e,t.preset):sh(t)}function ED(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function DD(e){let t=oh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function OD(e){let t=DD(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function kD(e,t){let n=OD(t),r=oD(iD(e)??``),i=r===null?void 0:Ni(r,sh(n));return i!==void 0&&`value`in i?i.value:void 0}function AD(e,t,n,r){let i=OD(n),a=iD(t);BD(e,t,{before:a,after:$i(a??``,hD(oD(a??``),i),rD(n,r),Li)})}function jD(e,t,n){let r=DD(n),i=iD(t);if(i===null)return;let a=ea(i,TD(oD(i),r));a!==i&&BD(e,t,{before:i,after:a})}function MD(e,t,n,r){let i=DD(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=iD(t),o=r.op===`remove`?r.target:r.anchor,s=CD(oD(a??``),i.preset,o),c=ED(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`);BD(e,t,{before:a,after:l})}const ND={past:[],future:[]};function PD(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function FD(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(PD)&&Array.isArray(t.future)&&t.future.every(PD)}function ID(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(FD))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function LD(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),ke(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 RD(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function zD(e,t,n,r,i){aD(t,n,e.logger);try{LD(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function BD(e,t,n){let r=ID(e),{past:i}=r[t]??ND;zD(e,t,n.after,{...r,[t]:{past:RD(i,n),future:[]}},`edit`)}function VD(e,t){let n=ID(e),{past:r,future:i}=n[t]??ND,a=r[r.length-1];return a===void 0?null:(UD(t,a.after,`undo`),zD(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:RD(i,a)}},`undo`),a)}function HD(e,t){let n=ID(e),{past:r,future:i}=n[t]??ND,a=i[i.length-1];return a===void 0?null:(UD(t,a.before,`redo`),zD(e,t,a.after,{...n,[t]:{past:RD(r,a),future:i.slice(0,-1)}},`redo`),a)}function UD(e,t,n){if(iD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function WD(e){let t=Ee({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function GD(){return{probeTmux:WD,claudeSettingsPath:Hy()}}function KD(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function qD(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 JD(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function YD(e){try{return qD(KD(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function XD(e,t){return{tmux:JD(e,t),claudeSettingsEnv:YD(e)}}function ZD(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(KD(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),ke(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:YD(e)}}default:return t.kind}}function QD(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function $D(e){return eO(()=>decodeURIComponent(e))}function eO(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function tO(e,t){let n=Ee({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const nO=(e,t)=>tO($D(e),t),rO=(e,t)=>{let n=Ee({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,$D(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`})`)}},iO=(e,t)=>tO($D(e),t),aO=(e,t)=>tO($D(e),t),oO=(e,t)=>{let n=QD($D(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},sO=(e,t)=>{let[n=``,...r]=eO(()=>Ly(e)),i=QD(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${nS().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: ${nS().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=iS(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})`)},cO=/^-?\d+$/;function lO(e,t,n){return e>n?t:e<t?n:e}function uO(e,t){if(!e)return null;if(!nS().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${nS().join(`, `)})`);return e}function dO(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const fO=(e,t)=>{let[n=``,r=``,i=``]=eO(()=>Ly(e)),a=QD(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!cO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=aS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${nS().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&cO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=lO(l+o,s.min,s.max),d=iS(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})`)},pO=`render-origin`;function mO(e){return JSON.stringify(e)}function hO(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 gO(e,t){let n=e.sessionState.get(t,pO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=hO(n);return sv(r.projectDir,r.cwd,r.configFile??void 0)}function _O(e){return{historyPath:ze(),logger:e.dlog}}const vO=(e,t)=>{let[n=``,r=``,i=``,a=``]=eO(()=>Ly(e)),o=QD(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${Rx().join(`, `)})`);let s=zx(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=uO(a,`set-config`),l=gO(t,o);AD(_O(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),dO(c,o,t,`set-config`)},yO=(e,t)=>{let[n=``,r=``,i=``,a=``]=eO(()=>Ly(e)),o=QD(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!cO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=uO(a,`step-config`),l=Bx(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${Rx().join(`, `)})`);let u=gO(t,o),d=kD(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=zx(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);AD(_O(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),dO(c,o,t,`step-config`)},bO=(e,t)=>{let[n=``,r=``]=eO(()=>Ly(e)),i=QD(n);if(!r||!Rx().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${Rx().join(`, `)})`);let a=gO(t,i);jD(_O(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},xO=(e,t)=>{let[n=``,r=``,i=``]=eO(()=>Ly(e)),a=QD(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${Rx().join(`, `)})`);let o=zx(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Jm(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=gO(t,a);MD(_O(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},SO=(e,t)=>{let[n=``]=eO(()=>Ly(e)),r=QD(n),i=gO(t,r);if(VD(_O(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},CO=(e,t)=>{let[n=``]=eO(()=>Ly(e)),r=QD(n),i=gO(t,r);if(HD(_O(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},wO=(e,t)=>{QD($D(e)),t.applyUpdate()},TO=`client-hints`;function EO(e,t){let n=e.sessionState.get(t,TO);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 xv(r)}function DO(e,t,n){let r=jh(n);e.sessionState.setBatch(t,Ph(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const OO=(e,t)=>{let n=QD($D(e));DO(t,n,XD(t.doctor,EO(t,n).tmux))},kO=(e,t)=>{let[n=``,r=``]=eO(()=>Ly(e)),i=QD(n),a=Mh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=XD(t.doctor,EO(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=ZD(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),DO(t,i,c)},AO=`config-override`,jO=new Map([[Sy,nO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=QD(eO(()=>decodeURIComponent(e.slice(0,n)))),i=eO(()=>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,AO),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,AO,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Cy,rO],[by,sO],[xy,fO],[Dy,vO],[Oy,yO],[ky,bO],[Ay,xO],[jy,SO],[My,CO],[Ty,iO],[Ey,aO],[wy,oO],[Ny,wO],[Py,OO],[Fy,kO]]),MO=new Set([by,xy,Dy,Oy,ky,Ay,jy,My,wy,Ny,Py,Fy]),NO=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of zy(e)){if(!i&&MO.has(a)){let e=Ly(o);e.length>0&&e[0]&&(i=e[0])}let e=jO.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(`
179
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},PO=new Map([...jO,[yy,NO]]);Object.freeze([...PO.keys()]);const FO=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`]),IO=[[`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 LO(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of IO){let i=zO(n,e);if(i==null)t.missingRequired.push(e);else{let n=RO(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))FO.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function RO(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function zO(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 BO(e,t){switch(e){case`vars`:return{what:e,vars:VO(t)};case`segments`:return{what:e,segments:KO(t)};case`config`:return{what:e,config:YO(t)}}}function VO(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=WO(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,...HO(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:UO(r.lastUpdatedMs())})}return o}function HO(e){if(e.kind!==`document`)return{type:e.type,value:e.read()};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 UO(e){return e===null?null:Math.max(0,Date.now()-e)}function WO(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,GO(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}`,GO(i));return t}function GO(e){return e.kind}function KO(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=qO(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:JO(t.template,i),lastRender:r.get(e)??null})}return o}function qO(e){let t=[],n=new Set;for(let r of va(oo(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 JO(e,t){let n=new Set;for(let r of M_(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 YO(e){return e===null?null:e.config}const XO=[`vars`,`segments`,`config`];function ZO(e){return typeof e==`string`&&XO.includes(e)}function QO(e){return Math.max(1,e-2)}var $O=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await yC(e);if(n.length===0)return D(`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,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`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 ek(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 tk=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(ek(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=sC(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 CC(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||(ek(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return 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 nk=new Map;function rk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var ik=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=rk(process.env.TMUX),t=nk.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return nk.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},ak=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 ok=new qE;Ce(ok.launchStats);const sk=new YS({counters:ok,logger:Y}),ck=new rC({watchers:sk,logger:Y}),lk=new FC,uk=new XE,dk=new ak(We()),fk=new $O,pk=new tk,mk=new ik,hk=new GE({gitService:ck,sessionState:uk,watchers:sk},{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)}`)}}),gk=60*1e3;function _k(){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),Nk(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,gk),a.unref())},checkNow:o}}const vk=_k(),yk=TS({entryUrl:import.meta.url,intervalMs:gk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>vk.checkNow(),log:Y});let bk=null,xk=null,Sk=0;function Ck(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),Nk(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),Nk(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),Nk(0)});try{Sk=Xv(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),Nk(1);return}bk=Nb(t.pid);let e=Ub(Gb(bk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Nk(1);return}xk=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),uk.useStorage(new $E(Re(),500,Y)),Ib({anchor:Fb(t.env),isAlive:Lb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),Nk(0)}}),wk(g.createServer({allowHalfOpen:!1},e=>{Pk(e)}),Ne(),!1)}function wk(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),Nk(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Tk(e,n)}),e.listen(n,()=>Ek(n))}function Tk(e,n){let i=Cb(wb(Ie(n)),(e,t)=>Mb(e,t,{readStartTime:jb,pidAlive:Lb}));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}`),Nk(1);return}}wk(e,n,!0)}function Ek(e){let n=Db(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Nk(0);return}Ak(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(Sk/1048576)}MB`),cy();let i=dk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),vk.arm(),yk.arm(),kk(),Dk(e,n.identity)}function Dk(e,n){Ab({bound:n,myPid:t.pid,readIdentity:()=>Db(e),readLease:()=>wb(Ie(e)),shutdown:e=>Nk(e),log:Y}).arm()}let Ok=null;function kk(){Ok=Zv($v(ok.startedAt.getTime(),e=>Nk(e),{rssLimitBytes:Sk})),Ok.arm()}function Ak(e){let n=Tb(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:bk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let jk=0,Mk=!1;function Nk(e){if(!Mk){Mk=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{ck.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{lk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{sk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{uk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Eb(Le(),t.pid),xk!==null&&Wb(xk,t.pid,Vb,e=>r.unlinkSync(e)),t.exit(e)}}function Pk(e){jk++,ok.inFlight=jk;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:()=>Nk(r);try{e.end(Ov(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{ok.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=kv(e=>{Ik(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),jk=Math.max(0,jk-1),ok.inFlight=jk})}const Fk=e=>({resp:e,exitAfterFlush:null});async function Ik(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Fk({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 Fk({ok:!0,stats:ok.snapshot({gitCache:ck.getStats(),usageCache:lk.getStats(),renderCacheSize:hk.size,watchersActive:sk.size(),nextRestartReason:Ok?.describeNextRestart()??null})});if(e.kind===`render`){ok.requestsTotal++;let t=Date.now();try{let{report:n}=LO(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 ok.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Fk({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Lk(e.args),s=e.hookData.session_id,c=xv(e),l=JSON.stringify(c);uk.get(s,`client-hints`)!==l&&uk.set(s,TO,l);let u=uk.get(s,`config-override`)??a??c.configEnv,d=hk.getOrCreate(i,e.cwd,u),f=mO({projectDir:i,cwd:e.cwd,configFile:u??null});uk.get(s,`render-origin`)!==f&&uk.set(s,pO,f);let p=c.termCols,m=QO(p??120),h=ax(c.termRows),g={...zk,width:m},{authoredRoots:_}=d.state,v=VC(d.state.config,t=>uk.get(e.hookData.session_id,t),e=>_.has(e)),y=await ew(e.hookData,Uk,e.cwd,d.state.neededInputPaths,v,c),b=PT(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=NE(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=uk.get(e.hookData.session_id,`click.error`);S&&uk.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
179
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},PO=new Map([...jO,[yy,NO]]);Object.freeze([...PO.keys()]);const FO=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`]),IO=[[`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 LO(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of IO){let i=zO(n,e);if(i==null)t.missingRequired.push(e);else{let n=RO(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))FO.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function RO(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function zO(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 BO(e,t){switch(e){case`vars`:return{what:e,vars:VO(t)};case`segments`:return{what:e,segments:KO(t)};case`config`:return{what:e,config:YO(t)}}}function VO(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=WO(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,...HO(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:UO(r.lastUpdatedMs())})}return o}function HO(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 UO(e){return e===null?null:Math.max(0,Date.now()-e)}function WO(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,GO(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}`,GO(i));return t}function GO(e){return e.kind}function KO(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=qO(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:JO(t.template,i),lastRender:r.get(e)??null})}return o}function qO(e){let t=[],n=new Set;for(let r of va(oo(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 JO(e,t){let n=new Set;for(let r of M_(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 YO(e){return e===null?null:e.config}const XO=[`vars`,`segments`,`config`];function ZO(e){return typeof e==`string`&&XO.includes(e)}function QO(e){return Math.max(1,e-2)}var $O=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await yC(e);if(n.length===0)return D(`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,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`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 ek(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 tk=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(ek(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=sC(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 CC(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||(ek(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return 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 nk=new Map;function rk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var ik=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=rk(process.env.TMUX),t=nk.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return nk.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},ak=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 ok=new qE;Ce(ok.launchStats);const sk=new YS({counters:ok,logger:Y}),ck=new rC({watchers:sk,logger:Y}),lk=new FC,uk=new XE,dk=new ak(We()),fk=new $O,pk=new tk,mk=new ik,hk=new GE({gitService:ck,sessionState:uk,watchers:sk},{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)}`)}}),gk=60*1e3;function _k(){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),Nk(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,gk),a.unref())},checkNow:o}}const vk=_k(),yk=TS({entryUrl:import.meta.url,intervalMs:gk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>vk.checkNow(),log:Y});let bk=null,xk=null,Sk=0;function Ck(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),Nk(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),Nk(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),Nk(0)});try{Sk=Xv(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),Nk(1);return}bk=Nb(t.pid);let e=Ub(Gb(bk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Nk(1);return}xk=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),uk.useStorage(new $E(Re(),500,Y)),Ib({anchor:Fb(t.env),isAlive:Lb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),Nk(0)}}),wk(g.createServer({allowHalfOpen:!1},e=>{Pk(e)}),Ne(),!1)}function wk(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),Nk(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Tk(e,n)}),e.listen(n,()=>Ek(n))}function Tk(e,n){let i=Cb(wb(Ie(n)),(e,t)=>Mb(e,t,{readStartTime:jb,pidAlive:Lb}));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}`),Nk(1);return}}wk(e,n,!0)}function Ek(e){let n=Db(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Nk(0);return}Ak(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(Sk/1048576)}MB`),cy();let i=dk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),vk.arm(),yk.arm(),kk(),Dk(e,n.identity)}function Dk(e,n){Ab({bound:n,myPid:t.pid,readIdentity:()=>Db(e),readLease:()=>wb(Ie(e)),shutdown:e=>Nk(e),log:Y}).arm()}let Ok=null;function kk(){Ok=Zv($v(ok.startedAt.getTime(),e=>Nk(e),{rssLimitBytes:Sk})),Ok.arm()}function Ak(e){let n=Tb(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:bk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let jk=0,Mk=!1;function Nk(e){if(!Mk){Mk=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{ck.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{lk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{sk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{uk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Eb(Le(),t.pid),xk!==null&&Wb(xk,t.pid,Vb,e=>r.unlinkSync(e)),t.exit(e)}}function Pk(e){jk++,ok.inFlight=jk;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:()=>Nk(r);try{e.end(Ov(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{ok.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=kv(e=>{Ik(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),jk=Math.max(0,jk-1),ok.inFlight=jk})}const Fk=e=>({resp:e,exitAfterFlush:null});async function Ik(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Fk({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 Fk({ok:!0,stats:ok.snapshot({gitCache:ck.getStats(),usageCache:lk.getStats(),renderCacheSize:hk.size,watchersActive:sk.size(),nextRestartReason:Ok?.describeNextRestart()??null})});if(e.kind===`render`){ok.requestsTotal++;let t=Date.now();try{let{report:n}=LO(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 ok.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Fk({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Lk(e.args),s=e.hookData.session_id,c=xv(e),l=JSON.stringify(c);uk.get(s,`client-hints`)!==l&&uk.set(s,TO,l);let u=uk.get(s,`config-override`)??a??c.configEnv,d=hk.getOrCreate(i,e.cwd,u),f=mO({projectDir:i,cwd:e.cwd,configFile:u??null});uk.get(s,`render-origin`)!==f&&uk.set(s,pO,f);let p=c.termCols,m=QO(p??120),h=ax(c.termRows),g={...zk,width:m},{authoredRoots:_}=d.state,v=VC(d.state.config,t=>uk.get(e.hookData.session_id,t),e=>_.has(e)),y=await ew(e.hookData,Uk,e.cwd,d.state.neededInputPaths,v,c),b=PT(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=NE(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=uk.get(e.hookData.session_id,`click.error`);S&&uk.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
180
180
  `),ee=yk.notice({sessionId:s,dismissed:uk.get(s,dS),enabled:v.updateNotice}),te=d.lastError===null?null:d.configFilePath,ne=ux(C,ee,d.lastWarning??``),re=dk.sync(s,ne===null?null:fx(ne));re!==null&&Y(`warn`,`diagnostic dump failed: ${re}`);let w=px(x,ne,{fullText:re===null?{kind:`file`,path:dk.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),ie=Date.now()-t,T=ck.getStats(),E=lk.getStats();return Y(`info`,`render sid=${e.hookData.session_id??`?`} took=${ie}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${T.size}/${T.hits}h/${T.misses}m usage=${E.size}/${E.hits}h/${E.misses}m err=${C?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),Fk({ok:!0,output:w+`
181
181
  `})}catch(e){throw ok.requestsErrored++,e}}if(e.kind===`click`)return Fk(await Wk(e.verb,e.value));if(e.kind===`debug`){if(!ZO(e.what))return Fk({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${XO.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=hk.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Hk(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):Vk};return Fk({ok:!0,debug:BO(e.what,n)})}return Fk({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function Lk(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:Sv(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const Rk={sessionState:uk,dlog:Y,applyUpdate:()=>yk.act(),doctor:GD()},zk={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},Bk={...zk,width:1/0},Vk=new Map;function Hk(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,ix(a,{...Bk,charset:t,colorCompatibility:n}));return r}const Uk={gitProvider:ck,usageStore:lk,contextProvider:fk,metricsProvider:pk,tmuxService:mk,log:Y,clock:()=>new Date};function Wk(e,t){let n=PO.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Rk),{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 Gk={connectMs:200,budgetMs:500};async function Kk(e){let n=e.includes(`--json`),r=await qk();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Lv(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
182
182
  `);return}t.stdout.write(Zk(r.value))}function qk(){return jv({kind:`stats`},Gk,e=>`stats`in e?e.stats:void 0)}function Jk(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function Yk(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function Xk(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 Zk(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 ${Xk(e.uptimeSec)}`),t.push(` rss ${Jk(e.rssBytes)}`),t.push(` heapUsed ${Jk(e.heapUsedBytes)}`),t.push(` heapTotal ${Jk(e.heapTotalBytes)}`),t.push(` external ${Jk(e.externalBytes)}`),t.push(` arrayBuffers ${Jk(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 ${Yk(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 ${Yk(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(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.61.2",
3
+ "version": "1.61.3",
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.61.2",
94
- "@promptctl/cc-candybar-darwin-x64": "1.61.2",
95
- "@promptctl/cc-candybar-linux-x64": "1.61.2",
96
- "@promptctl/cc-candybar-linux-arm64": "1.61.2"
93
+ "@promptctl/cc-candybar-darwin-arm64": "1.61.3",
94
+ "@promptctl/cc-candybar-darwin-x64": "1.61.3",
95
+ "@promptctl/cc-candybar-linux-x64": "1.61.3",
96
+ "@promptctl/cc-candybar-linux-arm64": "1.61.3"
97
97
  }
98
98
  }