@promptctl/cc-candybar 1.218.3 → 1.218.4

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 +4 -4
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o from"node:os";import s,{closeSync as c,constants as l,existsSync as u,fstatSync as d,linkSync as f,mkdtempSync as p,openSync as m,readFileSync as h,readSync as g,rmSync as _,statSync as v,writeFileSync as y}from"node:fs";import{StringDecoder as b}from"node:string_decoder";import{inspect as x,parseArgs as S,types as C}from"node:util";import{clearImmediate as ee,setImmediate as w}from"node:timers";import{spawn as te,spawnSync as ne}from"node:child_process";import T,{basename as re,dirname as E,isAbsolute as D,join as ie,sep as O}from"node:path";import ae,{createHash as oe,createHmac as se,randomBytes as ce,randomUUID as le,timingSafeEqual as ue}from"node:crypto";import de from"node:net";import fe from"node:v8";import{open as pe,readFile as me,readdir as he,stat as ge}from"node:fs/promises";import{get as _e}from"node:https";import{WriteStream as ve}from"node:tty";import{createInterface as ye}from"node:readline";var be=Object.create,xe=Object.defineProperty,Se=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyNames,we=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,Ee=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),De=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ce(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Te.call(e,s)&&s!==n&&xe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Se(t,s))||r.enumerable});return e},Oe=(e,t,n)=>(n=e==null?{}:be(we(e)),De(t||!e||!e.__esModule?xe(n,`default`,{value:e,enumerable:!0}):n,e));let ke=!1;const Ae=()=>ke;function je(e){ke=e}function Me(e){return Ae()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ae()&&console.error(`[DEBUG] ${e}`,...t)}function Ne(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Pe=(e,t)=>k(t);function Fe(e,t){return Math.round(t-e)}function A(e,t){return Fe(t,e.monotonic())}const Ie={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=w(e);return()=>ee(t)}};function Le(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function Re(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function ze(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function Be(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const Ve=e=>e.getTime()/1e3,He=e=>new Date(e*1e3),Ue=e=>Ve(new Date(e.now()));function We(e,t){return C.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!u(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Ge={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function Ke(e,t,n){let r=Ge[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function qe(e,t){return{...e.inherited,...t.envOverlay}}function Je(e){switch(e.reason){case`non-zero`:return`exited with code ${e.exitCode}`;case`signal`:return`killed by ${e.signal??`a signal`}`;case`timeout`:case`output-limit`:case`rate-limited`:case`pipe-error`:case`spawn-error`:return e.error??e.reason;default:return e.error===void 0?e.reason:`${e.reason}: ${e.error}`}}const Ye=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function Xe(e,t){if(e.reason===`output-limit`||e.reason===`pipe-error`)return``;let n=t.trim(),r=n.search(/[\r\n]/);if(r===-1)return Ye(n);let i=Math.max(n.lastIndexOf(`
3
3
  `),n.lastIndexOf(`\r`))+1;return`${Ye(n.slice(0,r).trim())} … ${Ye(n.slice(i).trim())}`}function Ze(e,t=``){let n=Xe(e,e.stderr);return`${Je(e)}${t}${n===``?``:`: ${n}`}`}const Qe=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function $e(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${Math.round(n)}ms ago`}}function et(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function tt(e,t,n){let r=nt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function nt(e,t,n){if(e.scope.signal.aborted)return Qe(e.scope.signal);if(n?.aborted)return Qe(n);let r=Ke(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:$e(t,r.minIntervalMs,r.sinceLastMs)}const rt=`\$1 == "+" { live[\$2] = 1; next } \$1 == "-" { delete live[\$2]; next } END { for (g in live) groups = groups " -" g; if (groups != "") system("kill -TERM" groups " 2>/dev/null; sleep ${250/1e3}; kill -KILL" groups " 2>/dev/null") }`;function it(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function at(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),it(e,n))}const ot=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,st=e=>e===`cut`?`output cut at the ${gt}-byte bound, so the program holding it now fails its writes`:`output failed to read`,ct=`a launched program's pipe outlived its launch: `;function lt(e,t,n){let r=e.pipeEvent,i=new Map(r===null||r.answered?[]:r.counts),a=`${t}\0${n}`;i.set(a,(i.get(a)??0)+1),e.pipeEvent={text:`${ct}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${st(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${ct}${n} ${st(t)}`})}function ut(e,t){let n=e.pipeEvent;n===null||!Be(n,t)||(e.pipeEvent={...n,answered:!0})}function dt(e,t,n){let r=e.pipeEvent,i=r===null?`over`:ze(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:ot(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function ft(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[rt],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,A(n,r)),it(e,`did not start: ${We(i,void 0)}`),null}t?.onEnd(`lifeline`,A(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>it(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&it(e,null)}),i.once(`error`,t=>at(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>at(e,i,`exited ${n??t}`)),a.on(`error`,t=>at(e,i,`pipe failed: ${t.message}`)),et(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function pt(e,t){e.liveGroups.add(t),e.lifeline??=ft(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function mt(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function ht(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const gt=16*1024*1024,_t=`output exceeded ${gt} bytes`,vt=e=>`timed out after ${e/1e3} s`;function yt(e,t,n,r){let{stats:i}=e.scope,a=new b(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?lt(e,`read-error`,t):l.failed(n)}),n?.on(`data`,r=>{if(l===null){if(c+=r.length,i?.onDrainRead(t,r.length),c<=16777216)return;u=`cut`,n.destroy(),lt(e,`cut`,t);return}let d=Math.max(0,gt-s);o+=a.write(r.subarray(0,d)),s+=r.length,s>16777216&&l.full()}),{take:()=>{if(l===null)return``;l=null;let e=o+a.end();return o=``,e},drain:()=>{n===null||n.destroyed||n.readableEnded||bt(e,t,n,()=>u)}}}function bt(e,t,n,r){let{stats:i}=e.scope;if(e.scope.signal.aborted){n.destroy();return}n.once(`close`,()=>{e.drains.delete(n),i?.onDrainClose(t,r())}),n.unref(),e.drains.add(n),i?.onDrainOpen(t)}const xt=()=>`closed`;function St(e,t){e.on(`error`,()=>{}),e.end(t)}async function Ct(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category,t.signal);if(i!==null)return i;let a=r.monotonic();return n?.onStart(t.category),new Promise(i=>{let{spawner:o}=e,s;try{s=o.spawn(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,A(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)});return}let c=s.pid;c!==void 0&&pt(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ne(`output-limit`),failed:e=>{d??=e.message,ne(`pipe-error`)}},p=yt(e,t.category,s.stdout,f),m=yt(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>ne(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&mt(e,c),n?.onEnd(t.category,A(r,a)),s.off(`close`,re),s.off(`error`,T),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&bt(e,t.category,u,xt),i())},ee=e=>C(()=>i(e)),w=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),ee({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},te=()=>re(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(te);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ne=e=>{if(b!==null)return;if((s.exitCode!==null||s.signalCode!==null)&&c!==void 0&&o.groupGone(c)){b=e===`timeout`?null:e,r.defer(te);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{w(t,`SIGKILL`),l.then(()=>r.defer(te))}),w(t,`SIGTERM`))},T=e=>{ee({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:We(e,t.cwd)})};s.on(`error`,T);let re=(e,n)=>{if(b!==null){ee({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:vt(t.timeoutMs??0)}:b===`output-limit`?{error:_t}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){ee({ok:!0,...h(),exitCode:e});return}ee({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,re),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ne(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&St(u,t.stdinInput)})}function wt(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);try{let i=e.spawner.spawnSync(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:[`pipe`,`pipe`,`pipe`],encoding:`utf8`});n?.onEnd(t.category,A(r,a));let o=typeof i.stdout==`string`?i.stdout:``,s=typeof i.stderr==`string`?i.stderr:``,c=i.error?.code;if(i.error&&c!==`EPIPE`&&c!==`ECONNRESET`){let e=c===`ETIMEDOUT`?`timeout`:`spawn-error`;return{ok:!1,reason:e,stdout:o,stderr:s,exitCode:null,signal:i.signal??null,error:e===`timeout`?vt(t.timeoutMs??0):We(i.error,t.cwd)}}return i.status===0?{ok:!0,stdout:o,stderr:s,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:o,stderr:s,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,A(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)}}}function Tt(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=Et(e,t);return n?.onEnd(t.category,A(r,a)),o}function Et(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const Dt=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Ot(e,t,n){let{stats:r,clock:i}=e.scope,a=tt(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.monotonic();r?.onStart(t.category);let s;try{s=e.spawner.spawn(`/bin/sh`,[`-c`,`out=$1 err=$2 status=$3; shift 3; read go || exit 0; "$@" >"$out" 2>"$err" </dev/null; echo "exit $?" >"$status.$$" && ln "$status.$$" "$status"; rm -f "$status.$$"`,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:qe(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,A(i,o)),{ok:!1,reason:`spawn-error`,error:We(e,t.cwd)}}r?.onEnd(t.category,A(i,o)),s.once(`error`,()=>{});let c=s.pid,l=s.stdin;return l.on(`error`,()=>{}),c===void 0?(l.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(s.unref(),l.unref(),{ok:!0,pid:c,release:()=>l.end(`go
4
- `),withdraw:()=>l.end()})}function kt(e){let t;try{t=h(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function At(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Dt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{f(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{_(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function jt(e,t,n){return Nt(e,t,n).launcher}function Mt(e,t,n){let{launcher:r,state:i}=Nt(e,t,n);return{...r,launchSync:e=>wt(i,e)}}function Nt(e,t,n){let r={clock:t,launch:e=>et(i,Ct(i,e)),launchDetachedSync:e=>Tt(i,e),launchJobSync:(e,t)=>Ot(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>At(n,t,e,r,i),launcherWarnings:(e,t)=>dt(i,e,t),answeredPipeEvent:e=>ut(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&at(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:ot(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>Ve(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),ht(i)},{once:!0}),{launcher:r,state:i}}function Pt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Ft={spawn:(e,t,n)=>te(e,t,n),spawnSync:(e,t,n)=>ne(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Pt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},It=(e,t)=>jt(e,t,Ft),Lt=(e,t)=>Mt(e,t,Ft);function Rt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Ie;return{host:e,launcher:Lt({inherited:process.env},t),clock:t}}const zt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Bt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Vt(e){return zt.test(e)?e:Bt(e)}function Ht(e){return`${e.dir===void 0?``:`cd ${Vt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Vt(t)} `).join(``)}${[e.program,...e.args].map(Vt).join(` `)}`}const Ut=`cc-extra`;function j(e){return T.join(T.dirname(e),Ut,`src`,`bun-attach.js`)}function Wt(e){return T.join(T.dirname(e),`bun-graph.js`)}const Gt=`attach-preload.cjs`;function Kt(e){return T.join(T.dirname(e),Gt)}function qt(e,t){return Ht({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Jt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yt(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function M(e,t,n=Jt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=T.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?M(e,r):[[T.relative(e,r).split(T.sep).join(`/`),Yt(r,i)]]})}function Xt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Zt(e){return Xt(M(e,e))}const Qt=[`Cargo.toml`,`Cargo.lock`,`src`];function $t(e){return Xt(M(e,e,e=>Qt.includes(e)))}const en=e=>e.slice(0,7),tn=`1.218.3`;function nn(e){let t=T.dirname(T.dirname(e));return s.existsSync(T.join(t,`src`))?t:null}function rn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:tn,digest:e}}function an(){return`39684c84e1fcac1d09b248e0e830a1d11f4865802125e83be9ca4b8c78e3ac30`}function on(e){let t=JSON.parse(s.readFileSync(T.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${T.join(e,`package.json`)} has no version string`);return n}function sn(e,t){try{let n=nn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Zt(T.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:on(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function cn(e,t){let n=e[t];return n&&n.length>0?n:void 0}function ln(e){let t=cn(e.env,`XDG_STATE_HOME`)??T.join(e.home,`.local`,`state`);return T.join(t,`cc-candybar`)}function un(e){let t=cn(e.env,`XDG_CACHE_HOME`)??T.join(e.home,`.cache`);return T.join(t,`cc-candybar`)}function dn(e){return ln(e)}function fn(e){return e.env.CC_CANDYBAR_SOCKET||pn()}function pn(){let e=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function mn(e){s.mkdirSync(e,{recursive:!0,mode:448});let t=s.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function hn(e){mn(T.dirname(e));for(let t of[e,gn(e)])try{if(s.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function gn(e){return`${e}.lease`}function _n(e){return gn(fn(e))}function vn(e){return T.join(ln(e),`session-state.json`)}function yn(e){return T.join(ln(e),`settings-history.json`)}function bn(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function xn(e){return T.join(ln(e),`spawn.lock`)}function Sn(e){return T.join(ln(e),`spawn.cooldown`)}function Cn(e){return T.join(ln(e),`spawn.backoff`)}function wn(e){return T.join(ln(e),`watch-probe`)}function Tn(e){return T.join(ln(e),`daemon.log`)}function N(e){return{socket:fn(e),lease:_n(e),state:ln(e),registry:bn(e),log:Tn(e),sessionState:vn(e),settingsHistory:yn(e),watchProbe:wn(e),spawnBackoff:Cn(e)}}function En(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${T.join(cn(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:cn(t,`XDG_CONFIG_HOME`)??T.join(e.home,`.config`),dataHome:cn(t,`XDG_DATA_HOME`)??T.join(e.home,`.local`,`share`),dataDirs:(cn(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function Dn(e,t,n){let r=On(e);s.mkdirSync(T.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??s.statSync(r,{throwIfNoEntry:!1})?.mode;try{s.writeFileSync(i,t,a===void 0?{}:{mode:a}),s.renameSync(i,r)}catch(e){throw s.rmSync(i,{force:!0}),e}}function On(e){return kn(e).at(-1)}function kn(e){let{hops:t,stopped:n}=An(e);if(n!==null)throw n;return t}function An(e){let t=[e];try{for(let e=0;e<Mn;e++){let e=jn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${Mn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function jn(e){try{return s.lstatSync(e).isSymbolicLink()?T.resolve(s.realpathSync(T.dirname(e)),s.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Mn=40,Nn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Pn(e){return Object.fromEntries(Nn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Fn=[`native`,`node`,`frames`];function In(e,t){return{kind:e,bundle:t,source:null}}const Ln=[`ansi`,`frame`],Rn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function zn(e){let t=Jn(e.termCols),n=Jn(e.termRows),r=Yn(e.ssh),i=Kn(e.tmux),a=Gn(e.configEnv),o=Gn(e.claudeConfigDir),s=Wn(e.terminalEnv),c=ir(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Bn(e,t){return Rn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vn(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Hn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Un(e){let t=Object.keys(Hn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Hn[t](n.join(`, `))]});return t.length===0?null:t.join(`
4
+ `),withdraw:()=>l.end()})}function kt(e){let t;try{t=h(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function At(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Dt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{f(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{_(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function jt(e,t,n){return Nt(e,t,n).launcher}function Mt(e,t,n){let{launcher:r,state:i}=Nt(e,t,n);return{...r,launchSync:e=>wt(i,e)}}function Nt(e,t,n){let r={clock:t,launch:e=>et(i,Ct(i,e)),launchDetachedSync:e=>Tt(i,e),launchJobSync:(e,t)=>Ot(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>At(n,t,e,r,i),launcherWarnings:(e,t)=>dt(i,e,t),answeredPipeEvent:e=>ut(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&at(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:ot(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>Ve(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),ht(i)},{once:!0}),{launcher:r,state:i}}function Pt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Ft={spawn:(e,t,n)=>te(e,t,n),spawnSync:(e,t,n)=>ne(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Pt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},It=(e,t)=>jt(e,t,Ft),Lt=(e,t)=>Mt(e,t,Ft);function Rt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Ie;return{host:e,launcher:Lt({inherited:process.env},t),clock:t}}const zt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Bt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Vt(e){return zt.test(e)?e:Bt(e)}function Ht(e){return`${e.dir===void 0?``:`cd ${Vt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Vt(t)} `).join(``)}${[e.program,...e.args].map(Vt).join(` `)}`}const Ut=`cc-extra`;function j(e){return T.join(T.dirname(e),Ut,`src`,`bun-attach.js`)}function Wt(e){return T.join(T.dirname(e),`bun-graph.js`)}const Gt=`attach-preload.cjs`;function Kt(e){return T.join(T.dirname(e),Gt)}function qt(e,t){return Ht({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Jt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yt(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function M(e,t,n=Jt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=T.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?M(e,r):[[T.relative(e,r).split(T.sep).join(`/`),Yt(r,i)]]})}function Xt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Zt(e){return Xt(M(e,e))}const Qt=[`Cargo.toml`,`Cargo.lock`,`src`];function $t(e){return Xt(M(e,e,e=>Qt.includes(e)))}const en=e=>e.slice(0,7),tn=`1.218.4`;function nn(e){let t=T.dirname(T.dirname(e));return s.existsSync(T.join(t,`src`))?t:null}function rn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:tn,digest:e}}function an(){return`2d36759c48c0de48043b0a82e89305e2588984f71b23bf5d195aa0c3b93fb7af`}function on(e){let t=JSON.parse(s.readFileSync(T.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${T.join(e,`package.json`)} has no version string`);return n}function sn(e,t){try{let n=nn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Zt(T.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:on(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function cn(e,t){let n=e[t];return n&&n.length>0?n:void 0}function ln(e){let t=cn(e.env,`XDG_STATE_HOME`)??T.join(e.home,`.local`,`state`);return T.join(t,`cc-candybar`)}function un(e){let t=cn(e.env,`XDG_CACHE_HOME`)??T.join(e.home,`.cache`);return T.join(t,`cc-candybar`)}function dn(e){return ln(e)}function fn(e){return e.env.CC_CANDYBAR_SOCKET||pn()}function pn(){let e=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function mn(e){s.mkdirSync(e,{recursive:!0,mode:448});let t=s.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function hn(e){mn(T.dirname(e));for(let t of[e,gn(e)])try{if(s.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function gn(e){return`${e}.lease`}function _n(e){return gn(fn(e))}function vn(e){return T.join(ln(e),`session-state.json`)}function yn(e){return T.join(ln(e),`settings-history.json`)}function bn(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function xn(e){return T.join(ln(e),`spawn.lock`)}function Sn(e){return T.join(ln(e),`spawn.cooldown`)}function Cn(e){return T.join(ln(e),`spawn.backoff`)}function wn(e){return T.join(ln(e),`watch-probe`)}function Tn(e){return T.join(ln(e),`daemon.log`)}function N(e){return{socket:fn(e),lease:_n(e),state:ln(e),registry:bn(e),log:Tn(e),sessionState:vn(e),settingsHistory:yn(e),watchProbe:wn(e),spawnBackoff:Cn(e)}}function En(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${T.join(cn(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:cn(t,`XDG_CONFIG_HOME`)??T.join(e.home,`.config`),dataHome:cn(t,`XDG_DATA_HOME`)??T.join(e.home,`.local`,`share`),dataDirs:(cn(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function Dn(e,t,n){let r=On(e);s.mkdirSync(T.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??s.statSync(r,{throwIfNoEntry:!1})?.mode;try{s.writeFileSync(i,t,a===void 0?{}:{mode:a}),s.renameSync(i,r)}catch(e){throw s.rmSync(i,{force:!0}),e}}function On(e){return kn(e).at(-1)}function kn(e){let{hops:t,stopped:n}=An(e);if(n!==null)throw n;return t}function An(e){let t=[e];try{for(let e=0;e<Mn;e++){let e=jn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${Mn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function jn(e){try{return s.lstatSync(e).isSymbolicLink()?T.resolve(s.realpathSync(T.dirname(e)),s.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Mn=40,Nn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Pn(e){return Object.fromEntries(Nn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Fn=[`native`,`node`,`frames`];function In(e,t){return{kind:e,bundle:t,source:null}}const Ln=[`ansi`,`frame`],Rn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function zn(e){let t=Jn(e.termCols),n=Jn(e.termRows),r=Yn(e.ssh),i=Kn(e.tmux),a=Gn(e.configEnv),o=Gn(e.claudeConfigDir),s=Wn(e.terminalEnv),c=ir(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Bn(e,t){return Rn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vn(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Hn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Un(e){let t=Object.keys(Hn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Hn[t](n.join(`, `))]});return t.length===0?null:t.join(`
5
5
  `)}function Wn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Nn.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function Gn(e){return typeof e==`string`&&T.isAbsolute(e)?e:void 0}function Kn(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 qn=1e4;function Jn(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>qn?qn:t}function Yn(e){return typeof e==`boolean`?e:void 0}const Xn=new Set([...[],1]);function Zn(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}var Qn=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},$n=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function er(e){return tr(JSON.stringify(e))}function tr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function nr(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 Qn(`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 Qn(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function rr(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=t=>{if(!o){o=!0,c(),e.off(`data`,l),e.off(`error`,u),e.off(`close`,d);try{t()}catch{}}},c=r.after(n-r.now(),()=>{s(()=>{e.destroy(),a(new $n(`deadline`))})}),l=nr(e=>s(()=>i(e)),e=>s(()=>a(e))),u=e=>s(()=>a(e)),d=()=>s(()=>a(Error(`socket closed before response`)));e.on(`data`,l),e.on(`error`,u),e.on(`close`,d),e.write(er(t))})}function ir(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Gn(n);return Fn.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function ar(e,t,n,r){let i;try{i=await dr(fn(e.host),n.connectMs,e.clock)}catch(e){return ur(e)}return or(i,e.clock,t,n,r)}async function or(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await rr(e,{v:3,...o},a,t);return lr(o.kind,s,i)}catch(e){return ur(e)}finally{e.destroy()}}function sr(e,t){return typeof e==`string`?e:t}function cr(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function lr(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=sr(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:cr(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,phase:`deadline`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function ur(e){if(e instanceof Qn||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 e instanceof $n?{kind:`busy`,phase:e.phase,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 dr(e,t,n){return new Promise((r,i)=>{let a=de.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new $n(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function fr(e){if(e.kind===`busy`)return`daemon busy (${e.message})`;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`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}function pr(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function mr(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-60-n.monoMs)}const hr={connectMs:50,budgetMs:150},gr={connectMs:50,budgetMs:350};function _r(e){let t=e.output;return typeof t==`string`?t:void 0}function vr(e){return lr(`render`,e,_r)}function yr(e,t,n,r,i,a=hr){return ar(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,_r)}function br(e,t,n){return ar(e,()=>({kind:`pane-session`,socket:t,pane:n}),gr,e=>`paneSession`in e?e.paneSession:void 0)}function xr(e,t,n){return ar(e,()=>({kind:`click`,verb:t,value:n}),gr,_r)}const Sr=5e3;async function Cr(e){let t=[];for(let n of e){let e=await n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
6
6
  `)}const wr=`/usr/bin/footprint`;function Tr(e,t,n){return t===`darwin`?[kr(e,wr,[`-p`,String(n)]),kr(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[Ar(`/proc/self/smaps_rollup`),Ar(`/proc/self/status`)]:[]}function Er(e,t,n){return t===`darwin`?Dr(n,t=>e.launch({bin:wr,args:t,timeoutMs:Sr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Dr(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${Ze(r)}`};let i=Or(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function Or(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function kr(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:Sr,category:`limits.memory-report`});return r.ok?r.stdout.trim().length>0?{kind:`text`,text:r.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:Ze(r)}}}}function Ar(e){return{name:e,read:async()=>{try{let t=s.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}const jr=`CC_CANDYBAR_RSS_LIMIT_MB`;function Mr(e){let t=e[jr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${jr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Nr(e){return Mr(e)*2}const Pr=1024*1024,Fr=e=>Math.round(e/Pr);function Ir(e){return Mr(e)*Pr}const Lr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Rr(e,t){return e>t}function zr(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const Br=.75;function Vr(e,t){return e>t*Br}function Hr(e,t,n){let{prefix:r,suffix:i}=Lr[t];return T.join(e,`${r}${n}${i}`)}function Ur(e){for(let t of Object.keys(Lr)){let{prefix:n,suffix:r}=Lr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Wr(e){let t=e.limitBytes??1024*Pr,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null,o=!1,s;function c(){return a??=l().finally(()=>{a=null}),a}async function l(){if(r)return!0;let{rss:a,heapTotal:s}=e.memoryBytes(),c=zr(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${qr(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Gr(c)} > limit ${Fr(t)} MB (rss ${Fr(a)} MB, v8 heap ${Fr(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Jr(e.log,`memory report`,async()=>{let t=Hr(e.snapshotDir,`memoryReport`,u),n=await e.captureMemoryReport();o||(e.writeMemoryReport(t,n),e.log(`info`,`memory report written: ${t}`))}),o?(e.log(`info`,`daemon closed during the breach: no snapshot, no exit`),!1):(await Jr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Hr(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Jr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Yr(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Jr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Vr(i.charge.bytes,t)?`${Gr(i.charge)} approaching limit ${Fr(t)} MB (v8 heap ${Fr(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Yr(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function f(t=6e4){let n=async()=>{try{if(await c())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}o||(s=e.clock.after(t,()=>void n(),{unref:!0}))};n()}function p(){o=!0,s?.()}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function Gr(e){return e.kind===`charged`?`${e.measure} ${Fr(e.bytes)} MB`:`rss ${Fr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Fr(e.gap)} MB gap`} (standing in: ${e.unread})`}function Kr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function qr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Fr(e.gap)}MB`:``;return`measure=${Kr(e)} charge=${Fr(e.bytes)}MB rss=${Fr(t)}MB heap=${Fr(n)}MB limit=${Fr(r)}MB${i}`}async function Jr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Yr(e){let t=new Map;for(let n of e){let e=T.basename(n),r=Ur(e);if(r===null)continue;let{prefix:i,suffix:a}=Lr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Lr);return[...t].sort(([e],[t])=>Rr(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function Xr(e,t,n,r={}){let i=n.snapshotDir;return{clock:n.clock,pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Er(n.launcher,process.platform,process.pid),captureMemoryReport:()=>Cr(Tr(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>s.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>fe.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=s.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Ur(e)!==null).map(e=>T.join(i,e))},removeFile:e=>s.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Zr(e,n={}){let{host:r,clock:i}=e;if(pi(r)!==null)return;let a=n.spawn??(()=>hi(e)),o=ui(r,i);if(o.kind===`contended`){let e=$r(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Qr(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Qr(r,i,a);return}try{Qr(r,i,a)}finally{fi()}}function Qr(e,t,n){oi(e,t)&&ei(n)}function $r(e,t){try{let n=s.statSync(xn(e));return t.now()-n.mtimeMs}catch{return null}}function ei(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
7
7
  `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function ti(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ni(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function ri(e){try{let t=s.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function ii(e,n){try{s.mkdirSync(T.dirname(e),{recursive:!0}),s.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function ai(e){try{s.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function oi(e,n){let r=Sn(e),i=Cn(e),a=ri(i),o=ti(si(r,n),ni(a));return o.kind===`deny`?!1:(o.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${o.futureMs}ms in the future — ignoring and spawning\n`),ci(r,n),ii(i,Math.min(a+1,5)),!0)}function si(e,t){try{return t.now()-s.statSync(e).mtimeMs}catch{return null}}function ci(e,n){try{s.mkdirSync(T.dirname(e),{recursive:!0}),s.writeFileSync(e,`${t.pid} ${n.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let li=null;function ui(e,n){let r=xn(e);for(let e=0;e<2;e++){try{let e=s.openSync(r,`wx`,384);try{s.writeSync(e,JSON.stringify({pid:t.pid,ts:n.now()}))}catch{}return li={fd:e,path:r},{kind:`held`}}catch(e){let t=e.code;if(t!==`EEXIST`)return{kind:`error`,reason:`openSync(${r}): ${t??e.message}`}}if(!di(r,n))return{kind:`contended`};try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function di(e,t){try{let n=s.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function fi(){if(!li)return;let{fd:e,path:t}=li;li=null;try{s.closeSync(e)}catch{}try{s.unlinkSync(t)}catch{}}function pi(e){try{return s.mkdirSync(dn(e),{recursive:!0}),null}catch(t){return`mkdir ${dn(e)}: ${t.message}`}}function mi(e,t){return[`--max-old-space-size=${Nr(t)}`,e,`daemon`]}function hi({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:mi(i,e.env),category:`daemon-spawn`}).ok:!1}const gi=`closed`,_i=`open`,vi=`🍫`;function yi(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function bi(e,t,n,r){let i=yi(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function xi(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Si(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function Ci(e,...t){return`{{ and ${[e,...t].map(wi).join(` `)} }}`}function wi(e){return`(eq .${e.variable} "${xi(e.member)}")`}function Ti(e,t,n){return`{{ ${Ei(e,Di(t),Di(n))} }}`}function Ei(e,t,n){return`action "${e}" ${t} ${n}`}function Di(e){return`"${xi(e)}"`}function Oi(e,t){return{kind:`state`,key:e,default:t}}function ki(e,t){return{set:e,cycle:[gi,t]}}function Ai(e){if(!(`set`in e&&`cycle`in e))return;let[t,n,...r]=e.cycle;return t===`closed`&&n!==void 0&&r.length===0?{key:e.set,member:n}:void 0}const ji=`groups.`,Mi=`menus.`,Ni=`menupages.`,Pi=`edit.`,P=`candybar.`,Fi=[ji,Mi,Ni,Pi,P];function Ii(e){return Fi.some(t=>e.startsWith(t))}const Li=`${P}menu`,Ri=_i,zi={variable:Li,key:Li,member:Ri},Bi=`${P}diagnostics`,Vi=`cc-candybar`,Hi=`CCCandybarURLHandler`,Ui=`dispatch`,Wi=`set-state`,Gi=`step-state`,Ki=`copy`,qi=`open-vscode`,Ji=`toolbar-toggle`,Yi=`load-config`,Xi=`set-config`,Zi=`step-config`,Qi=`save`,$i=`save-preset`,ea=`save-theme-default`,ta=`delete-preset`,na=`reset-config`,ra=`apply-layout-op`,ia=`undo`,aa=`redo`,oa=`back`,sa=`rewind`,ca=`apply-update`,la=`doctor-run`,ua=`doctor-fix`,da=`doctor-mark`,fa=`doctor-probe`,pa=`slash`,ma=`repo-config`,ha=`copy-diagnostic`,ga=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,_a=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function va(e,t){if(e===Bi)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!Ii(e))return n;let r=_a(_a(e,Ni),Mi);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}function ya(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const ba={[Wi]:([,...e])=>e.flatMap((t,n)=>n%2==0?[va(t,e[n+1])]:[]),[Gi]:([,e,t])=>[ga(e,t)],[Ki]:([e])=>[`copy ${ya(e)}`],[qi]:([e])=>[`open ${e} in vs code`],[Ji]:()=>[`toggle the toolbar`],[Yi]:([,e])=>[`load config ${e}`],[Xi]:([,e,t])=>[`save ${e} as ${t}`],[Zi]:([,e,t])=>[`save ${ga(e,t)}`],[Qi]:()=>[`save settings`],[$i]:()=>[`save as a new preset`],[ea]:()=>[`save this look for the theme`],[ta]:([,e])=>[`delete preset ${e}`],[na]:([,...e])=>e.map(e=>`reset ${e}`),[ra]:([,e,t])=>[`edit ${t} in ${e}`],[ia]:()=>[`undo`],[aa]:()=>[`redo`],[oa]:()=>[`go back`],[sa]:()=>[`cancel edits`],[ca]:()=>[`update cc-candybar`],[la]:()=>[`run doctor`],[ua]:([,e])=>[`fix ${e}`],[da]:([,e,t])=>[`mark ${e} ${t}`],[pa]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[ma]:([,e,t])=>[`mark config in ${e} ${t}`],[ha]:()=>[`copy diagnostic`]},xa=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function Sa(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>ba[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function Ca(e){return e.map(encodeURIComponent).join(`/`)}function wa(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function eee(e){return decodeURIComponent(e.split(`/`,1)[0])}function Ta(e,t=Sa(e)){let n=e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Ca(e.args)}`)}`);return`${Vi}://${Ui}/${[`does=${xa(t)}`,...n].join(`&`)}`}function Ea(e){return new r(e).getAll(`e`).map(Aa)}const Da=new Set([Wi,na]);function Oa(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&ka(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function ka(e,t){if(e.verb!==t.verb||!Da.has(e.verb))return;let[n,r]=[Aa(e.value),Aa(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function Aa(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function ja(e){let t=`${Vi}://`;if(!e.startsWith(t))return{ok:!1,problem:`expected a ${t} link, got: ${e}`};let n=e.slice(t.length),r=n.indexOf(`/`);if(r===-1)return{ok:!0,verb:Ki,value:n};let i=n.slice(0,r);try{return{ok:!0,verb:decodeURIComponent(i),value:n.slice(r+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${i}`}}}var Ma=Ee(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),Na=Ee(((e,t)=>{let n=Ma();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===`‌`||e===`‍`||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),Pa=Ee(((e,t)=>{let n=Na(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),ne[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
@@ -470,7 +470,7 @@ function run(argv) {
470
470
  `)+1,i=n.lastIndexOf(`
471
471
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
472
472
  `)){let t=iY(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function kZ(e){let t=qo(e,oM+1);return t.kind===`ok`?F(OZ(t.value.buf,t.value.fromStart)):t}function AZ(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const jZ={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function MZ(e,t){if(Kz(t)===void 0)return{kind:`ok`,value:null};let n=hJ(await e.launch({bin:`git`,args:[...mJ],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=bJ(n.value);if(r===null)return{kind:`ok`,value:null};let i=pJ(r);if(i===null)return{kind:`ok`,value:null};let a=cJ[i],o=jZ[i],s=o.loginHost(fJ(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return NZ(a,s,o.nonZero,c)}function NZ(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):lJ(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:aJ(r.stderr)}):{kind:`failed`,reason:iJ(e,r)}}function PZ(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
473
- `)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const FZ=e=>fZ(()=>aee(e));function IZ(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Zo(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:FZ(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function LZ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function RZ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Xj(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:Yj(t),tmuxClient:t}}}}async function zZ(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(zj(s))return{kind:`bundling`,name:s,version:c};if(!Bj(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function BZ(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function VZ(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function HZ(e,t,n,r){return{pullRequests:await VZ(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await VZ(t.rateLimits,()=>r)}}function UZ(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function WZ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=dG(d.config,r,()=>!1),p=await LZ(e,t.tmux),m=RZ(p,t.terminalEnv),h=[...new Set([...Cj(f),...Sj(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:zZ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),HZ(e,yX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:PZ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:AZ(e,o),claudeSettings:IZ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Zo(Xo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function GZ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;Dn(e,fo(es(e),t.path,JSON.stringify(t.value),Za));let r=e=>({...e,sources:FZ(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||Rr(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const KZ={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},qZ=16384;var JZ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessDraining=0;subprocessDrainedBytes=0;subprocessDrainsCut=0;subprocessPipeErrors=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}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)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)},onDrainOpen:()=>{this.subprocessDraining++},onDrainRead:(e,t)=>{this.subprocessDrainedBytes+=t},onDrainClose:(e,t)=>{this.subprocessDraining--,t===`cut`&&this.subprocessDrainsCut++},onPipeError:()=>{this.subprocessPipeErrors++}};recordRollingNow(){let e=this.clock.monotonic();if(this.rollingTimestamps.length<qZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%qZ}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=this.clock.monotonic()-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,refused:Object.fromEntries(this.subprocessRefused),draining:this.subprocessDraining,drainedBytes:this.subprocessDrainedBytes,drainsCut:this.subprocessDrainsCut,pipeErrors:this.subprocessPipeErrors,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0,monotonic:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},sourceRuns:{shell:KZ,file:KZ,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,due:0,retiredViews:0,accountedBytes:0,budgetBytes:0},collector:{sessions:0,retiring:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:tn,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.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},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,sourceRuns:e.sourceRuns,transcriptReads:e.transcriptReads,renderCache:e.renderCache,collector:e.collector,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const YZ={connectMs:200,budgetMs:500};async function XZ(e,t){return ZZ(await QZ(e),t.includes(`--json`))}function ZZ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${fr(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
473
+ `)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const FZ=e=>fZ(()=>aee(e));function IZ(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Zo(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:FZ(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function LZ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function RZ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Xj(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:Yj(t),tmuxClient:t}}}}async function zZ(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(zj(s))return{kind:`bundling`,name:s,version:c};if(!Bj(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function BZ(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function VZ(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function HZ(e,t,n,r){return{pullRequests:await VZ(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await VZ(t.rateLimits,()=>r)}}function UZ(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function WZ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=dG(d.config,r,()=>!1),p=await LZ(e,t.tmux),m=RZ(p,t.terminalEnv),h=[...new Set([...Cj(f),...Sj(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:zZ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),HZ(e,yX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:PZ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:AZ(e,o),claudeSettings:IZ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Zo(Xo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function GZ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;Dn(e,fo(es(e),t.path,JSON.stringify(t.value),Za));let r=e=>({...e,sources:FZ(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||Rr(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const KZ={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},qZ=16384;var JZ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}accepted=0;accept(){return{id:++this.accepted,at:this.clock.monotonic()}}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessDraining=0;subprocessDrainedBytes=0;subprocessDrainsCut=0;subprocessPipeErrors=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}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)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)},onDrainOpen:()=>{this.subprocessDraining++},onDrainRead:(e,t)=>{this.subprocessDrainedBytes+=t},onDrainClose:(e,t)=>{this.subprocessDraining--,t===`cut`&&this.subprocessDrainsCut++},onPipeError:()=>{this.subprocessPipeErrors++}};recordRollingNow(){let e=this.clock.monotonic();if(this.rollingTimestamps.length<qZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%qZ}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=this.clock.monotonic()-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,refused:Object.fromEntries(this.subprocessRefused),draining:this.subprocessDraining,drainedBytes:this.subprocessDrainedBytes,drainsCut:this.subprocessDrainsCut,pipeErrors:this.subprocessPipeErrors,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0,monotonic:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},sourceRuns:{shell:KZ,file:KZ,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,due:0,retiredViews:0,accountedBytes:0,budgetBytes:0},collector:{sessions:0,retiring:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:tn,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.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},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,sourceRuns:e.sourceRuns,transcriptReads:e.transcriptReads,renderCache:e.renderCache,collector:e.collector,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const YZ={connectMs:200,budgetMs:500};async function XZ(e,t){return ZZ(await QZ(e),t.includes(`--json`))}function ZZ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${fr(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
474
474
  `:null,r=$Z(e.value);return r===null?{stdout:n??sQ(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function QZ(e){return ar(e,()=>({kind:`stats`}),YZ,e=>`stats`in e?e.stats:void 0)}function $Z(e,t=eQ){let n=JZ.referenceSnapshot(),r=tQ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=rQ(e.version,e.sourceDigest??null),a=rQ(tn,an());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const eQ=Object.keys(JZ.referenceSnapshot());function tQ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!nQ(e))return[];if(!nQ(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...tQ(e[i],t[i],a)):r.push(a)}return r}function nQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rQ(e,t){return`${e} [${t===null?`no digest`:en(t)}]`}function iQ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function aQ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function oQ(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 sQ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${rQ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${oQ(e.uptimeSec)}`),t.push(` rss ${iQ(e.rssBytes)}`),t.push(` heapUsed ${iQ(e.heapUsedBytes)}`),t.push(` heapTotal ${iQ(e.heapTotalBytes)}`),t.push(` external ${iQ(e.externalBytes)}`),t.push(` arrayBuffers ${iQ(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(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${aQ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${aQ(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(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Vc(e.fileEvents)}`);for(let n of[`shell`,`file`]){let r=e.sourceRuns[n];t.push(` runs.${n.padEnd(8)} entries=${r.entries} held=${r.held} failures=${r.failures} abandoned=${r.abandoned} last=${r.lastMs===null?`-`:`${r.lastMs}ms`}`)}t.push(` runs.watches ${e.sourceRuns.watches}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${iQ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${iQ(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` due ${e.renderCache.due}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${iQ(e.renderCache.accountedBytes)} / ${iQ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`collector`),t.push(` sessions ${e.collector.sessions}`),t.push(` retiring ${e.collector.retiring}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`),t.push(` draining ${e.subprocesses.draining} (${e.subprocesses.drainedBytes} bytes dropped, ${e.subprocesses.drainsCut} cut)`),t.push(` pipeErrors ${e.subprocesses.pipeErrors}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
475
475
  `)+`
476
476
  `}const cQ=e=>({kind:`ok`,value:e}),lQ=e=>({kind:`failed`,reason:e});var uQ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const dQ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function fQ(e){return dQ.test(e)?e:null}function pQ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return cQ(null);let n=t.value;return cQ({app:n,forwarder:e.exists(ws(n))})}async function mQ(e,t){let n=e.monotonic()+5e3;for(;e.monotonic()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,delivery:r.delivery}}return null}async function hQ(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Vi}://${fa}/${n}`);return(r===null?await mQ(e,n):null)??{kind:`lost`,unopened:r,opener:pQ(e)}}function gQ(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?cQ(i.stdout):lQ(Ze(i))}const _Q=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Vi}://probe"));u.isNil() ? "" : u.path.js`;async function vQ(e){let t=await QZ(e);if(t.kind!==`ok`)return lQ(fr(t).split(`
@@ -480,7 +480,7 @@ function run(argv) {
480
480
  `),...e]));return o.overflow=`ignore`,o.end=``,o}function P2(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(oU(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=E0(e,`{{ themePreview }}`);return N2(r===void 0?a:D2(e,r,`themePreview`),o,{...d2(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),m2(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const F2=e=>e.slice(e.lastIndexOf(`.`)+1),I2=(e,t)=>{let n=new K(F2(e));return n.truncate(t,{marker:`…`}),n.plain};function L2(e,t){let n=e.map(e=>e.map(({name:e})=>f2(F2(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function R2(e,t,n,r){let i=L2(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new K(` ${I2(s,i)} `,{style:K0(Zv(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
481
481
  `),...e]));return o.overflow=`ignore`,o.end=``,o}const z2=`layoutPreview`;function B2(e,t){return{[z2]:{fn:()=>R2(D0(e,`{{ layoutPreview }}`),E0(e,`{{ layoutPreview }}`).decor,t.drawnAt(),m2(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function V2(e,t,n,r){let i=d2(r.activeSegment,`{{ menu }}`),a=r.action,o=kS(i.placementId,e,n.key),s=MS(o),c=OS(e),l=T0(a,`menu`).store,u=P0(l,o)===c,d=F0(a,`menu`),f=u?gi:c,p=L0(bi(`{{ menu "${e}" }}`,t,2,+!!u),Ta([{verb:Wi,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=zv(i.palette,i.disclosure,t).plane,l=y2(a,e,`menu`);return b2(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,gi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,$0(i,n.distribution,E0(a,`{{ menu }}`),l.paletteOf,t,c),q0(i.palette,c,t))})():[]),p}const H2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function U2(e,t){let n=t[t.length-1],r=H2(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:IS(r??{})}}function W2(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=U2(t,n);return V2(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function G2(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=K2(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new K(t?i:a,{style:l===void 0?void 0:new U({color:l})}))}let l=K.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function K2(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function q2(e){let t={fn:(()=>{let t=d2(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>d2(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=d2(e,`{{ roleTextOn }}`);return X2(r,t,Fu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=d2(e,`{{ keptOn }}`),i=Fu(r,t),a=Fu(r,n),o=xl(Ku(i,V.TRUECOLOR),Ku(a,V.TRUECOLOR)),s=Math.min(Ov,o),c=e.drawnAt(),l=Gu(i,c,(e,t)=>xl(e,t(a))>=s);if(l===void 0)throw Error(`keptOn: nothing drawn at ${V[c]} stands ${s.toFixed(2)}:1 off ${a.hex} (drawn ${Ku(a,c).hex})`);return l.hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=VH(()=>d2(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...Z2(s)];return G2({value:e,max:t,width:n,filled:r,empty:i,colourAt:c===void 0?void 0:e=>String(a.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...a,bgOf:t,tint:n,roleTextOn:r,keptOn:i,gauge:o}}const J2={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},Y2=Object.values(J2).flat();function X2(e,t,n){let r=Ku(n,V.TRUECOLOR),i=t=>{let n=Fu(e,t);return{colour:n,ratio:xl(Ku(n,V.TRUECOLOR),r)}},a=Uu(r).hex,o=J2[a];if(o===void 0)throw Error(`contrastFor named ${a} for ${n.hex}, which is neither pole`);let s=`text-${t}`,c=e=>`${t}-${e}`,l=new Map([s,t,...Y2.map(c)].map(e=>[e,i(e)]));return([s,t,...o.map(c)].map(e=>l.get(e)).find(({ratio:e})=>e>=4.5)??[...l.values()].reduce((e,t)=>t.ratio>e.ratio?t:e)).colour}function Z2(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function Q2(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>EU.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const $2={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},e4=new WeakMap;function t4(e){let t=e4.get(e);return t===void 0&&(t=n4(e),e4.set(e,t)),t}function n4(e){let t=new Map(ZR(e)),n=jU(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:$2[t.kind]])),i=new Map([...t].map(([e,t])=>[e,Q2(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function r4(e){let t=[],n=[];for(let r of e){if(!r.contains(`
482
482
  `)){n.push(r);continue}let e=r.split(`
483
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function i4(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const a4=e=>e.kind===`failed`?o0:e;function o4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function s4(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function c4(e){return{...e,cells:e.cells.map(f0)}}function l4(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...u4(e,r)]}function u4(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function d4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:l4(e.direction,e.children.map((t,i)=>n(t,[...r,f4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function f4(e,t){return e.steps[t]}function p4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=m4(e);return{width:h4(t),reach:g4(t)}}function m4(e){let t=e.children.map(p4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const h4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),g4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function _4(e,t){let n=m4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=zy[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),g4(n),h4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const v4={compile(e,t){let n=_4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Gy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),l4(e.direction,e.children.map((n,r)=>t.renderChild(n,a4(t.gate),f4(e,r))))}},y4={drop:e=>e.place,above:()=>`above`},b4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},x4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:By(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ky(t.path),void 0),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,S4(e,t))};function S4(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=b1(t.scope,e.settings);if(t.gate.kind===`failed`)return O4(e,r,t,t.gate.message);try{let i=t.placement(e),a=o4(t.gate,i.gate());if(a.kind===`failed`)return O4(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return O4(e,r,t,s.message);let c=Hx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:eA(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?C4(f.variable):w4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?T4(p.segment,u):E4(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:o0,h.disclosure).map(e=>({...e,place:y4[v.placement](e)})),b=(e,t,n)=>h0(S0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?b4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new K(` `.repeat(D4(d0(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap(d0)),[...ne,...te]}catch(n){return O4(e,r,t,n.message??String(n))}}const C4=e=>({kind:`waiting`,variable:e});function w4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=dI(e);if(t===void 0)throw e;return C4(t.variable)}}function T4(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:r4(S0(r,c)).map((e,t)=>({cells:h0(e,{...l,lead:t===0?S0(i,c):[],trail:t===0?S0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:h0(S0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function E4(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=S0(k4(e.lead,e,t,n),l),d=S0(k4(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return h0(S0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function D4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function O4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:h0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:eA(n.palette)},lead:k4(e.lead,e,t,n),trail:k4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function k4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=dI(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const A4={container:v4,segment:x4};function j4(e){return A4[e]}var M4=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?N4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const N4={kind:`hidden`},P4={palette:`theme`,style:`style`,effect:`effect`},F4=Ix.get(`colorCompatibility`),I4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function L4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function R4(e){if(e.ok)return e.value;throw e.error}const z4=e=>({read:()=>e}),B4=k_({basePalette:O_,palette:O_,decor:Wv});var V4=class{evaluated=0;memory=new M4;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&B4(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=v1(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(F4);return e.kind===`found`&&typeof e.value==`string`&&Oy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(I4,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return d4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=vF(e);return i===void 0?[]:[{name:i,address:n,palette:Hx(r.theme,t)}]}))}),t.bindInputs({session:()=>this.view.get().session,read:e=>this.inputAt(e),drawnAt:()=>ky(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=Mk(e);return t===void 0?Ak(e)===void 0?e0(this.view.get().payload(),e):e0(this.projected,e):$1(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[P4[e]];if(t.kind===`decided`)return W4(t.name,null,null);let r=K4(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=q4(this.source,e,i.name,r.where,e=>{t=e}),W4(n,t,null)}case`pending`:return W4(n??hy[e],null,i.variable);case`failed`:return n=hy[e],W4(n,gy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!G4(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??hy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return c0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>l2(this.source.activeSegment,()=>c0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new J4(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:O0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=dI(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:L4(e)}),R4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:vF(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function H4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new V4(t,n,e,r);return e.views.set(t,a),a}function U4(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const W4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),G4=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function K4(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function q4(e,t,n,r,i){switch(t){case`palette`:return qx(n,r,i).name;case`style`:return fy(n,e.styles).name;case`effect`:return Sy(n).name}}var J4=class{where=Y4(k_({palette:O_,region:Hv}));ground=Y4(k_({colours:Z4,bodyOpen:O_}));opened=Y4(k_({colours:Z4,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=b1(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?z4(s0):e.derive(`${t.id} when`,e.readsInstant(a),()=>l2(r,()=>c0(a,i))),this.open=d===void 0?z4(o0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>l2(r,()=>c0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return e3(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return t3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?z4(r3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return n3(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),a3(n,r,this.affixes.read())}};function Y4(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const X4=(e,t)=>e.hex===t.hex,Z4=k_({palette:O_,drawnAt:O_,tint:X4,text:X4,bg:X4,disclosure:Gv});function Q4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const $4=e=>zv(e.palette,e.disclosure,e.drawnAt);function e3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Zv(n,r,i)};return c2(e,Q4(t,c),e=>{let t=nA(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function t3(e,t,n,r,i,a){return c2(e,Q4(t,n),e=>(e.bg=i?$4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function n3(e,t,n,r,i,a,o){return c2(e,Q4(t,n),e=>(e.bg=r?$4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const r3={lead:[],trail:[],drops:[]};function i3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return G0(t,$4(e).state,n)},get band(){return G0(t,$4(e).plane,n)},get close(){return J0(t,$4(e).state,n)},disclosure:r}}function a3(e,t,n){return{styles:i3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function o3(e,t,n,r,i,a,o){let s=e3(e,t,n,r,i,void 0,void 0,o);return a3(s,t3(e,t,s,a,!1,o),r3)}function s3(e,t,n,r,i){return i3(e3(e,t,n,r,i,void 0,void 0,{}))}function c3(e,t,n){return{session:n,payload:()=>e,selections:()=>t}}function l3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:X1(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 u3(e,t){switch(Yy(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 d3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:l3(n.cache),parse:u3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:l3(n.cache),parse:u3(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function f3(e,t,n,r=mw.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function p3(e,t,n){let{compiled:r,loadWarnings:i}=h3(e,t,n.cwd,m3(n.signer),y3);return{...r,loadWarnings:i}}const m3=e=>(t,n)=>b3(n,e);function h3(e,t,n,r,i=y3){let a=g3(e),o=_3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:v3(e,t,n,i)}}function g3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Lx)n in t&&r.set(e,n);for(let[t,n]of nb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...FU(e)].sort(([e],[t])=>e<t?-1:1)}}function _3(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function v3(e,t,n,r){let i=t4(e),a=FU(e),o=[];for(let[s,c]of ZR(e))if(r.has(i.get(s)))try{d3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const y3=new Set([`directory`,`view`]);function b3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>T0(i,`drawnAt`).registry.drawnAt(),o=o2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=mS(e.presets),u=fF(e),d=[e=>k2(i,o,e.now)],f=DU({extraFuncs:{...U0(i),...O2(i),...x2(i,o),...w2(i),...P2(i,o),...B2(i,o),...W2(s),...q2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=f3(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=k0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:f3(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=ob(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Eee(t,e,a,t=>String(T0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return j4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=_S(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(sy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of LU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:C3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w=new Set(n.map(([e])=>e)),te={reads:OU({names:w,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:wU(d)},ne=BU(te),T=[...C.values()].flatMap(S3(y)).some(e=>ne(m.get(e))),re=T?new Set([...te.clock,z2]):te.clock,E=BU({...te,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=BU({reads:OU({names:w,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:te.projections,clock:re});for(let e of wz){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function x3(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const S3=e=>t=>{let n=[];return d4(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function C3(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const w3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function T3(e,t,n,r,i){let a=E3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function E3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??hy[e];case`failed`:return r({kind:`rule`,slot:e,message:gy(t.where,e,`the rule failed — ${n.error}`)}),hy[e]}}function D3(e){return O3(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function O3(e){return e.kind===`container`?e.children.flatMap(O3):[e,...e.opens===void 0?[]:O3(e.opens.body)]}function k3(e,t,n,r,i,a,o){let s={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return H4(e,t,n,c3(s,a,o)),s}function A3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new PA(``),h=m.clockAt(a,vy[c.animationSpeed]),g=l.u(mU(a,h.timeline)),_=U4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:yj(v),padding:v.padding,seamCols:bj(v),preset:c.preset},i);let y=_.evaluated;l.u(O0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,s4),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&te.add(n.waited),n.name;let r=q4(t,e,T3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:qx(re(`palette`),``,w3),ae=D.kind===`decided`?D:fy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Sy(re(`effect`)),se=O.value,ce=Wx(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:s4,hold:c4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,n,i)=>{let a=n.kind===`hidden`?n:o4(n,_.gate(e)),o=a.kind===`failed`?{...a,report:()=>{let t=`when over ${D3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:a.message,message:`${t}: ${a.message} — what it gates is hidden`})}}:a,s={scope:_.scope,palette:ce,gate:o,padding:v.padding,region:i,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,a,o)=>o3(t.activeSegment,e,a,i,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Yv(i,n)),renderBody:(e,t,n)=>pe(e,t,Xv(n)),closeDisclosure:e=>W0(r.session(),e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>s3(t.activeSegment,e,n,i,r.drawnAt())};return j4(e.kind).render(e,s)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${fS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=i4(pe(me,s0,Jv(S))).map(({line:e,row:t})=>{let n=b0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...Ej(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||O3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const j3={moving:1e3/30,still:1e3},M3=[`data`,`state`,`reload`,`visibility`];function N3(e){return Wb.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function P3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const F3=(e,t)=>Ub[t].handsOff?e.resp:e.statusline,I3=e=>Math.round(1e3/e);var L3=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}feedOpen(e){return this.feeds.has(e)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Wee;let r=t-1,i=this.shown(n);return Xb(e=>{let a=n.rates.get(e);if(a===void 0)return Jb;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.clock.monotonic(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&e.phase.clear(),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.clock.monotonic(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${x(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,I3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||F3(a,t)!==F3(i,t))&&P3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=F3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:eC(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=fY.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} ceiling=${I3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${M3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function R3(e,t){return Wb.filter(n=>e[n]&&Ub[n].handsOff&&t.has(n))}function z3(e,t){return{severity:jB,lines:[[NB(`[⟲ claude]`,Ta([{verb:na,args:[e,...t.map(e=>Ub[e].switch.setting)]}]))]]}}function B3(e,t){for(let n of Object.entries(t))e.push(n)}const V3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function H3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,x(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function U3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...H3(n)];return{level:V3[n.kind],line:bc(e,i)}}const W3=()=>{},G3=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),K3={ansi:e=>({ok:!0,output:cj(e)}),frame:e=>({ok:!0,frame:e})};function q3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=jo();let i=c.u(r6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=a6(e,i,{by:`feed`,fps:n}),p=K3.ansi(o.body),m=f6(t,o,R3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:K3.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=U3(`render`,s,{kind:`threw`,error:e},A(i,o)),r=G3(e);return{bar:QA(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:W3,failure:{level:t,line:`frame ${n}`}}}}function J3(e,t,n){let{sessionState:r}=e;return dG(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function Y3(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:cG(i.view.source.effective(),Tc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function X3(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return cG(J3(e,n,o.state),s===null||Tc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function Z3(e,t,n){B3(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;B3(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:Bn(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const Q3=e=>Vn(Bn(e,e.hints));function $3(e,t,n,r,i){Z3(t,r,i),B3(i,{encoding:t.encoding}),(0,X.runInAction)(()=>{o6(e,t),e.worldStates.take(n),t6(e,t)[Symbol.dispose]()})}function e6(e,t){(0,X.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function t6(e,t){let n=i$(t.requested,e.sessionState,t.hookData.session_id);return e.renderCache.holdSession(n.projectDir,n.cwd,n.target.path,t)}function n6(e,t,n,r){let i=Q3(t);return i6(e,t6(e,t),t,i,n,r)}function r6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{Z3(o,n,r),s=Q3(o)}catch(e){throw a[Symbol.dispose](),e}return i6(e,a,o,s,n,r)}function i6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{hints:l}=n,u={hookData:n.hookData,deps:o,cwd:n.cwd,hints:l};return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:s,view:c,hintsError:r,payloadInputs:u,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function a6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.payload(),C=b.source.effective(),ee=b.source.failure(),w=cG(C,S.tmux!==void 0);B3(g,{lanes:Wb.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;B3(g,{width:String(ne)});let T=_c(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({sessionId:_,dismissed:r.get(_,HF),enabled:C.updateNotice}),D=oV(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Un(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:dV(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...Bc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=PB(_,n.by,ae,[...E.offer,...D],[...E.failure,...ue.map(e=>({about:e.kind,text:e.message,copy:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),pe=b.source.facts(),me={diagnostics:WB(fe),drawing:n,feeds:i.feedsOf(_,h),today:cX(pe.builtins.today,h)},he=ko(S.metrics)?void 0:S.metrics;B3(g,iX([...b.state.sources.keys()],pe)),B3(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:LY(S.git),feeds:N3(me.feeds)});let ge=[],_e=PY(C,ne),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=A3(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:ye}),we=IB(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te);f.observe(_,h,be.rows.some(e=>e.kind===`menu`),C.menuTimeout);let De=f.since(_,h);B3(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:KB(te.termRows,n.by===`feed`?Wb.flatMap(e=>{let t=Ub[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=GB(r.get(_,Bi),fe),je=Ae===null?be:XA(be,qB(fe,Ae,_,n.by,ke)),Me=u.gitProvider.getStats(),k=u.usageStore.getStats(),Ne=ve.lastFrame(),Pe=Ne.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Fe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,A=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ie=[...E.failure.map(()=>`update-failed`),...[...ue,...ge].map(A)].join(`,`)||`-`;return B3(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${k.size}/${k.hits}h/${k.misses}m`,effect:Ne.effect,effectT:Ne.t.toFixed(3),speed:`${Ne.speed}x`,effectRows:`${Ne.made}made/${Ne.reused}reused`,effectOwn:Pe,fadeBasis:Ne.basis,stateRev:String(Ne.revision),fades:Fe(Ne.fades),leaves:Fe(Ne.leaves),motion:je.motion,evaluated:String(xe),cellBreaks:String(Se),pending:je.pending.join(`,`)||`-`,rules:[...Ce].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.offer.length),ask:String(D.length),warn:Ie,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:xe,cellBreaks:Se,clickShown:re,pipeShown:le,delivered:Ee,lanes:w}}function o6(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,JG,o);let s=i1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,qG,s)}function s6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(c6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function c6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:i$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:kj(t.hookData)}}function l6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:c6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function u6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(n6(e,t,n,i));s6(e,t,cG(l.view.source.effective(),Tc(t.hints.tmux)));let u=o.monotonic(),d=r-u;B3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await RJ(t=>Promise.all([$Y(l.payloadInputs,n,f,()=>e.worldStates.of(l.sessionId),t),l.view.registry.inFlight(t)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();B3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:GY(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=a6(e,l,Kb),b=t.hookData.session_id,S=R3(y,s.following(b)),C=jj(t.hints.client??null)===`statusline`,ee=C?f6(b,h,S):h.body;return B3(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{frame:ee,delivered:d6(e,b,v,g,_)}}catch(e){a.e=e}finally{a.d()}}function d6(e,t,n,r,i){return()=>{n(),r!==null&&pee(e.sessionState,t,r),i!==null&&e.launcher.answeredPipeEvent(i)}}function f6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:XA(t.body,JB(z3(e,[r,...i]),t.diagnostics,e,t.geometry))}const p6=e=>{};function m6(e,t,n=``){let r=G3(t);return{outcome:{kind:`threw`,error:t},resp:{...r,error:`renderer ${e.name}: ${n}${r.error}`},seen:`failed`,settled:p6}}function h6(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&T.isAbsolute(t)&&{location:nB(t)}}}}function g6(e,t){e.push(...t.kind===`answered`?t.output.record:t.record)}async function _6(e,t,n,r,i,a,o,s){let c=h6(r),l=(t,r)=>void e.deliver({kind:`event`,at:Ue(n),event:{kind:`effect-done`,of:t.id,outcome:r===null?{kind:`ok`}:{kind:`failed`,reason:r}}},[[`sid`,c.hookData.session_id],[`effect`,String(t.id)]]),u=await e.answer({kind:`event`,at:a,event:{kind:`config`,context:c,worldState:t.requested(c)}});if(g6(s,u),u.kind===`threw`)return B3(s,{renderer:e.name}),m6(e,u.error,`its config turn: `);let d=await e.answer({kind:`event`,at:a,event:{kind:`request`,id:i,context:c,waitEndsAt:o}});if(g6(s,d),d.kind===`threw`)return B3(s,{renderer:e.name}),m6(e,d.error);let{effects:f}=d.output;B3(s,{renderer:e.name,effects:f.map(e=>`${e.kind}:${e.surface}`).join(`,`)||`-`});let p=null;for(let e of f)switch(e.kind){case`present`:e.request===i?p===null?p=e:l(e,`a second statusline frame for request ${i}`):l(e,`presents request ${e.request}, not this turn's ${i}`);break}if(p===null)return m6(e,Error(`presented no statusline frame for request ${i}`));let m=p,h=n.monotonic(),g;try{g=K3[c.encoding](m.frame)}catch(t){return l(m,`encoding its frame threw: ${G3(t).error}`),m6(e,t,`its frame could not be encoded: `)}return B3(s,{encoded:`${A(n,h)}ms`}),{outcome:{kind:`ok`},resp:g,seen:m.frame.motion,settled:e=>l(m,e?null:`the client did not take the answer`)}}const v6=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`]),y6=[[`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`]],b6=[[`workspace.added_dirs`,`string-list`]];function x6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of y6){let i=w6(n,e);if(i==null)t.missingRequired.push(e);else{let n=S6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of b6){let i=w6(n,e),a=i===void 0?r:C6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))v6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function S6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function C6(e){return Array.isArray(e)&&e.every(e=>S6(e)===`string`)?`string-list`:S6(e)}function w6(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 T6(e,t,n){let{tokens:r}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:hA(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function E6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ln.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ln.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function D6(e,t,n,r){let{report:i}=x6(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=rq(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!D(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=E6(e.encoding);s.ok||a.push(s.problem);let c=pr(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=zn(e),{configFile:u,refusedArgs:d}=T6(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:Nj(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:vA(u,l.configEnv)},refusedArgs:d}}}function O6(e,t){switch(e){case`vars`:return{what:e,vars:k6(t)};case`segments`:return{what:e,segments:P6(t)};case`config`:return{what:e,config:R6(t)}}}function k6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=M6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=A6(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:j6(r.lastUpdatedMs(),t.clock)})}return o}function A6(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};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`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function j6(e,t){return e===null?null:Math.max(0,t.now()-e)}function M6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,N6(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}`,N6(i));return t}function N6(e){return e.kind}function P6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=I6(n),o=F6(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:L6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function F6(e){let t=new Map;for(let n of mS(e.presets))for(let r of Wy(_S(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=By(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function I6(e){let t=[],n=new Set;for(let r of Wy(nS(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 L6(e,t,n){let r=new Set([...IR(e,t).keys()].flatMap(e=>QR(e,n)));return Array.from(r).sort()}function R6(e){return e===null?null:e.config}const z6=[`vars`,`segments`,`config`];function B6(e){return typeof e==`string`&&z6.includes(e)}const V6=e=>({resp:e,exitAfterFlush:null,settled:p6}),H6=e=>({kind:`reply`,...e}),U6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},W6=(e,t)=>H6(V6({ok:!1,error:t,code:e,daemonV:3}));function G6(e){let t=rq(e.sessionId);if(!t.ok)return W6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return W6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Wb.join(`, `)}): it predates the lane toggles — update it`);let n=Zb(e.lane);return n===null?W6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Wb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function K6(e,t,n,r,i){if(t.kind===`url`)return H6(V6(await e8(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?W6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?G6(a):typeof a.kind!=`string`||!Object.hasOwn(U6,a.kind)?W6(`BAD_REQUEST`,`unknown kind`):H6(await q6(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,settled:p6})}async function q6(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,effectSessions:m,menuIdle:h,journalTurns:g,sessionState:_,tmuxStatusLines:v,watcherRegistry:y,limits:b,handlerProbes:S,renderSightings:C,bundle:ee,sourceDigest:w,doctorStores:te}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,settled:p6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return V6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return V6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:J6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,collector:e.collector.stats(),effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:_.size(),observers:_.observers(),revision:_.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:v.stats(),watchersActive:y.size(),dirWatchesActive:y.dirWatches(),nextRestartReason:b.describeNextRestart(),handlerProbes:S.list(),clients:C.list(Ve(new Date(o.now()))),bundle:ee,sourceDigest:w,daemon:b.serving(),doctorStores:gZ(te)})});if(t.kind===`render`){let c=new Date(o.now()),l=Ve(c),u=o.monotonic(),d=Fe(r,u),f=[],p=++a.requestsTotal,m=D6(t,a,e.log,e.home),h=(t,n)=>C.see(t.hookData.session_id,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Xo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Pj(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.hookData.session_id,m.req,p));let g=t=>{t.outcome.kind!==`ok`&&a.requestsErrored++,B3(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:r,line:s}=U3(`render`,f,t.outcome,A(o,u));return e.log(r,s),{resp:t.resp,exitAfterFlush:null,settled:t.settled}};if(!m.ok)return g(o8(m.problems));let _=await _6(e.renderer,e.collector,o,m.req,p,l,u+mr(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u}),f).catch(e=>({outcome:{kind:`threw`,error:e},resp:G3(e),seen:`failed`,settled:p6}));try{return h(m.req,_.seen),g(_)}catch(e){throw _.settled(!1),e}}if(t.kind===`click`)return V6(await Q6(e,r,n,i,(n,r)=>$6(e,t,n,r)));if(t.kind===`debug`){if(!B6(t.what))return V6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${z6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?Z6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Dx(`colorCompatibility`)):X6};return V6({ok:!0,debug:O6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function J6(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const Y6={endcaps:Dx(`endcaps`),colorCompatibility:Dx(`colorCompatibility`),wrap:Dx(`autoWrap`),padding:Dx(`padding`),width:1/0},X6=new Map;function Z6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Dj(i,{...Y6,colorCompatibility:t}));return n}async function Q6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Fe(t,o)}ms`]],c=await i(s,()=>n()||r());B3(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=U3(`click`,s,c,A(a,o));return e.log(l,u),i8(c)}async function $6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};B3(n,{via:`cli`});let{verb:a,value:o}=t;return typeof a!=`string`||typeof o!=`string`?{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof a} and ${typeof o}`]}:t8(()=>r8(e,a,o,i,n,r))}async function e8(e,t,n,r,i){return Q6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(B3(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Xn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Xn].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o=ja(a);if(!o.ok)return{kind:`bad-request`,problems:[o.problem]};let s={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return t8(()=>r8(e,o.verb,o.value,s,n,r))})}async function t8(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof XG?{kind:`closing`,error:e}:e instanceof ZG?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const n8={link:`verb`,"tmux-status":`linkVerb`};async function r8(e,t,n,r,i,a){if(t===`tmux-status-click`)return B3(i,{verb:t}),a8(e,n,i,a);B3(i,{[n8[r.via]]:t});let o=q$(t,n);o===null?B3(i,{sid:`-`}):o.ok&&B3(i,{sid:o.id});let s=o?.ok?e.collector.holding(o.id):()=>{};try{let s=await e.renderer.answer({kind:`event`,at:Ue(e.clock),event:{kind:`click`,verb:t,value:n,session:o,arrival:r,gone:a}});switch(s.kind){case`answered`:return i.push(...s.output.record),{kind:`ok`};case`threw`:throw i.push(...s.record),s.error}}finally{s()}}function i8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:return G3(e.error)}}async function a8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(B3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=ja(s.url);return t.ok?t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):r8(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await UQ(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,BQ,e.tmp),{kind:`ok`}}const o8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},settled:p6});function s8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return T.join(e,`update-act`,n)}const c8={kind:`idle`};function l8(e){if(e===null)return c8;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const u8=e=>({stdout:T.join(e,`stdout`),stderr:T.join(e,`stderr`),status:T.join(e,`status`)}),d8=e=>T.join(e,`record.json`);function f8(e){let t;try{t=s.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function p8(e){let t=qo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function m8(e,t){let n=T.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(T.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const h8=e=>e.now()-o.uptime()*1e3;async function g8(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function _8(e){try{return JSON.parse(s.readFileSync(d8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const v8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function y8(e,t,n,r){let i=null;async function a(a){let o=T.join(e,String(a)),c=_8(o);if(c===null)return null;if((i===null||!v8(i.record,c))&&(i={record:c,ours:await g8(c,t,n,h8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=u8(o),u=kt(l.status),d=u===null?null:p8(l.stderr)??p8(l.stdout);if(!s.existsSync(o))return null;let f={act:a,record:c,alive:i.ours,end:u,lastLine:d};return f.alive||(i.final=f),f}return{async read(){let t=null;for(;;){let n=f8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${T.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function b8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(T.join(e,`.claim-`));try{return s.writeFileSync(d8(r),JSON.stringify(n)),s.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{s.rmSync(r,{recursive:!0,force:!0})}}async function x8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=T.join(t,String(c)),u=e.launchJobSync(i,u8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!b8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return S8;if(f8(t).some(e=>e>c))return m8(t,c),S8;d=!0}finally{d?u.release():u.withdraw()}for(let e of f8(t).filter(e=>e<c))m8(t,e);return{ok:!0,act:c}}const S8={ok:!1,reason:`another act claimed this bundle first`};function C8(e,t,n){let r=u8(T.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function w8(e,t,n){if(t.kind===`pending`)return Oo(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}var T8=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function E8(e){return e.kind===`source`?e.newer.digest:cs(e.newer)}const D8=e=>`${e.version} [${en(e.digest)}]`;function O8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:D8(e.newer),running:D8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:cs(e.newer),running:cs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${ls}@${cs(e.newer)}`,`install`]}}}}const k8={offer:[],failure:[]};function A8(e,t,n){if(e===null)return k8;let r=E8(e);if(!n.enabled||n.dismissed===r)return k8;let i=O8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?NB(`[${i.busy}]`,null):NB(`[${i.act}]`,Ta([{verb:ca,args:[n.sessionId]}])),c=[NB(a,null),s,NB(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,HF,r]}])),NB(`[disable]`,Ta([{verb:Xi,args:[n.sessionId,UF,`false`]},{verb:Wi,args:[n.sessionId,WF,`false`]}]))];return{offer:[{severity:kB,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function j8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return M8(t)}}function M8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function N8(e){switch(e.kind){case`current`:return[`info`,`build: current ${D8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${D8(e.source)}, running ${D8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function P8(e){switch(e.kind){case`current`:return[`info`,`release: current ${cs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${cs(e.latest)}, running ${cs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${cs(e.installed)}, latest ${cs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function F8(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,gates:f,onApplied:p,log:m}=e,h=Oo(`unread`),g=Oo(`unread`),_=async e=>{let t=await i.startTime(e);if(w)throw new XG(`apply-update`);return t},v=y8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new T8,ee=e=>C.run(`acts`,e),w=!1,te=[],ne=(e,t)=>{te.push(n.every(t,e,{unref:!0}))},T=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function re(){let e=T(),t=e===null?null:E8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(HF,[t])})}function E(){let e=w?I:j8(h,g),r=w8(t.get(),e,Ue(n));(0,X.runInAction)(()=>t.set(r)),re()}function D(){let e=sn(a,()=>rn(o));return h=F(e),x(N8(e)),E(),e}async function ie(){let e=ds(tn,await us(ls,d,u,n));g=F(e),S(P8(e)),E()}let O=null,ae=Ne(m);async function oe(e){try{let t=await e();return O=null,{ok:!0,value:t}}catch(e){return e instanceof XG?{ok:!1,error:e.message}:(O=`update act files (${s}): ${e.message}`,ae([`error`,O]),{ok:!1,error:O})}}function se(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=C8(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;m(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function ce(){let e=await oe(async()=>{let e=await v.read();return w||se(e),e});if(w||!e.ok)return;let t=l8(e.value);y===null&&t.kind===`running`&&m(`info`,`apply-update: act ${t.act} is running; watching it`),y?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(m(`info`,`apply-update: act ${t.act} succeeded`),D(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await ee(ce),!w&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=D();ne(D,c),te.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),ne(()=>void ie(),l))},close(){w=!0,E(),te.forEach(e=>e())},notice:e=>A8(T(),y??c8,e),running:()=>ee(async()=>{let e=await oe(()=>v.read());return e.ok&&l8(e.value).kind===`running`}),error:()=>O,act:()=>ee(async()=>{if(w)throw new XG(`apply-update`);let e=await oe(()=>v.read());if(w)throw new XG(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=T();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=O8(t),a=e.value;if(l8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await x8(r,s,a===null?null:a.act,E8(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new Z(`apply-update: ${o.reason}`);m(`info`,`apply-update: act ${o.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),y={kind:`running`,act:o.act}})}}function I8(){return X.observable.box(Oo(`unread`),{deep:!1})}function L8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function R8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function z8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:L8(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=L8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!R8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var B8=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const V8=`pass`,H8={okMs:5*6e4,failedMs:45e3},U8=H8.okMs;function W8({failures:e}){return T1(H8,e,U8)}function G8(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function K8(e){return`git:${e}`}function q8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:T.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Ac(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${jc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function J8(e){return e.kind===`ok`?e.value.branch:void 0}function Y8(e){e.missed=!0,FJ(e,`unread`)}function X8(e,t){return e.missed&&e.reading.get().kind===`pending`&&PJ(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function Z8({value:e,pr:t}){let n=LJ(e);return n.kind===`ok`?F({...n.value,pullRequest:LJ(t)}):n}const Q8=L(`git cache closed`,`read`);function $8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var e5=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.forgeLookups=new Ao(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new pY(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new _V({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return zJ(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>Z8(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:Q8};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}built(e){let t={period:new E1(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:I,reading:MJ(),inFlight:null},n={root:e,refresh:new B8,watch:this.followWatch(e,null).watch,period:new E1(()=>{n.refresh.share(V8,()=>this.refreshPass(n))},this.clock),value:{reading:MJ(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=q8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(V8,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e){return e.holders++,e.value.missed&&(Y8(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(V8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(K8(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch($8(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,PJ(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of nJ(i.value))o.add(e);let s=J8(i),c=s===void 0?X8(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,G8(n),o.size===0?F(null):L([...o].join(`; `),`read`),A(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch($8(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(Y8(r),`owed`):(FJ(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,PJ(r,a.outcome),r.period.landed(W8(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch($8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,A(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(PJ(t,i),t.period.landed(W8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);IJ(e.value,t),IJ(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},t5=class{static usageDir(e){return T.join(e,`usage`)}static locksDir(e){return T.join(e,`locks`)}static isLocked(e,t){let n=T.join(this.locksDir(e),t);if(!s.existsSync(n))return!1;try{let e=s.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),s.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),s.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=T.join(this.locksDir(e),n),a=t.monotonic(),o=String(process.pid);for(;t.monotonic()-a<r;)try{return await s.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await Le(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=T.join(this.locksDir(e),t);try{await s.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([s.promises.mkdir(e,{recursive:!0}),s.promises.mkdir(this.usageDir(e),{recursive:!0}),s.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=T.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await Le(t,75);continue}try{let e=await s.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await Le(t,75)}}return k(`Failed to read ${n} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=T.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},c=JSON.stringify(o);await s.promises.writeFile(a,c,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const n5={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var r5=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(e,t){let n=t.now()-1440*60*1e3;return await t5.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await t5.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){k(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(n5).length} models`),this.executionCache=n5,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n5).length} models`),n5)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}},i5=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function a5(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const o5={okMs:60*1e3,failedMs:10*1e3},s5={calculatedCost:null,tokens:null,tokenBreakdown:null};function c5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function l5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const u5={entries:0,cost:0,breakdown:l5(),days:new Map};async function d5(e,t,n,r){let i=HJ(new Date(c5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await r5.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=HJ(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...BJ};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function f5(e){let t=0,n=0,r=l5(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...BJ};VJ(n,t),i.set(e,n)}}if(t===0)return{usage:s5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{usage:{calculatedCost:n,tokens:a,tokenBreakdown:r},days:i}}function p5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function m5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!p5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...BJ};VJ(r,t),n.set(e,r)}return Object.fromEntries(n)}async function h5(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function g5(e,t){(0,X.runInAction)(()=>e.set(t))}var _5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new i5;scans;daySets=new Map;speedFlight=new i5;requestFlight=new i5;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new pY(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new O1({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??o5,watch:D1,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async()=>{let e=await r().record;return e.kind===`failed`?e:F(e.kind===`ok`?e.value.usage:s5)},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e){let t=this.sessions.get(e);if(t===void 0)return Oo(`unread`);let n=t.failure.get();return n===null?F(t.record?.usage??s5):L(n,`read`)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.monotonic(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,A(this.clock,i)),g5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(e,t).today()}declareToday(e,t){if(this.closed)return zJ(L(`usage store closed`,`read`));let n=XJ(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||p5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return g5(this.hold(e).speed,t),t;let r=a5(t.kind===`ok`?t.value.usage.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return g5(this.hold(e).speed,s),s})}speedOf(e){return this.sessions.get(e)?.speed.get()??Oo(`unread`)}async ingest(e,t,n,r){let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,usage:s.value.usage,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>ie(e,`projects`)+O),i={roots:r,sums:new s1(`today over ${e.join(`,`)}`,()=>m5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await $J(e,E(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of cY(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await lY(e,r,u5,(e,t)=>d5(e,t,un(this.host),this.clock));if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of cY(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...f5(i),mainStamp:a})}async scan(e){try{let t=c5(this.clock.now()),n=await ZJ(e),r=[];for(let e of n){let n=await QJ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await QJ(Lo(n));if(a===void 0||a.mtimeMs<t)continue;let o=rq(i.slice(0,-6));if(!o.ok){this.log(`warn`,`usageStore scan: transcript ${JSON.stringify(i)} names no session: session id ${o.problem}`);continue}r.push({sessionId:o.id,path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await h5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=HJ(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}};const v5={command:null,todos:[],pending:[],done:[]};function y5(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function b5(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function x5(e,t){if(t.isSidechain)return e;let n=b5(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=y5(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function S5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>y5(e,t.name),[]),done:e.done}}var C5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new dY(v5,x5,(e.ledger??new pY(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return w5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:w5(e,t)}};function w5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(S5(t.value))}const T5=3e4;var E5=class{names;constructor(e){let t=e.logger??Pe;this.names=new O1({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>D5(e.launcher,t),every:()=>({okMs:T5,failedMs:T5}),watch:D1,maxEntries:64,logger:t,ledger:e.ledger??new pY(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function D5(e,t){let n=await pc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const O5=6e4,k5={okMs:O5,failedMs:O5};function A5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function j5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var M5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>k5,watch:D1,maxEntries:1,logger:t,ledger:e.ledger??new pY(t),clock:e.clock};this.name=new O1({...n,name:`host.name`,read:()=>j5(`name`,()=>A5(o.hostname()))}),this.user=new O1({...n,name:`host.user`,read:()=>j5(`user`,()=>o.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},N5=class{known=new uY(64);refreshes;constructor(e,t=Pe,n=new pY(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=P5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.monotonic(),i=PN(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function P5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const F5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function I5(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var L5=class{known=new uY(256);refreshes;constructor(e,t=Pe,n=new pY(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n){let r=this.clock.monotonic(),i=await R5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,A(this.clock,r)),i}};async function R5(e){let t=await z5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function z5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=B5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function B5(e,t){let n=e.toString(`utf8`).split(`
483
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function i4(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const a4=e=>e.kind===`failed`?o0:e;function o4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function s4(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function c4(e){return{...e,cells:e.cells.map(f0)}}function l4(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...u4(e,r)]}function u4(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function d4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:l4(e.direction,e.children.map((t,i)=>n(t,[...r,f4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function f4(e,t){return e.steps[t]}function p4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=m4(e);return{width:h4(t),reach:g4(t)}}function m4(e){let t=e.children.map(p4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const h4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),g4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function _4(e,t){let n=m4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=zy[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),g4(n),h4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const v4={compile(e,t){let n=_4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Gy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),l4(e.direction,e.children.map((n,r)=>t.renderChild(n,a4(t.gate),f4(e,r))))}},y4={drop:e=>e.place,above:()=>`above`},b4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},x4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:By(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ky(t.path),void 0),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,S4(e,t))};function S4(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=b1(t.scope,e.settings);if(t.gate.kind===`failed`)return O4(e,r,t,t.gate.message);try{let i=t.placement(e),a=o4(t.gate,i.gate());if(a.kind===`failed`)return O4(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return O4(e,r,t,s.message);let c=Hx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:eA(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?C4(f.variable):w4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?T4(p.segment,u):E4(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:o0,h.disclosure).map(e=>({...e,place:y4[v.placement](e)})),b=(e,t,n)=>h0(S0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?b4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new K(` `.repeat(D4(d0(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap(d0)),[...ne,...te]}catch(n){return O4(e,r,t,n.message??String(n))}}const C4=e=>({kind:`waiting`,variable:e});function w4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=dI(e);if(t===void 0)throw e;return C4(t.variable)}}function T4(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:r4(S0(r,c)).map((e,t)=>({cells:h0(e,{...l,lead:t===0?S0(i,c):[],trail:t===0?S0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:h0(S0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function E4(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=S0(k4(e.lead,e,t,n),l),d=S0(k4(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return h0(S0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function D4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function O4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:h0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:eA(n.palette)},lead:k4(e.lead,e,t,n),trail:k4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function k4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=dI(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const A4={container:v4,segment:x4};function j4(e){return A4[e]}var M4=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?N4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const N4={kind:`hidden`},P4={palette:`theme`,style:`style`,effect:`effect`},F4=Ix.get(`colorCompatibility`),I4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function L4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function R4(e){if(e.ok)return e.value;throw e.error}const z4=e=>({read:()=>e}),B4=k_({basePalette:O_,palette:O_,decor:Wv});var V4=class{evaluated=0;memory=new M4;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&B4(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=v1(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(F4);return e.kind===`found`&&typeof e.value==`string`&&Oy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(I4,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return d4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=vF(e);return i===void 0?[]:[{name:i,address:n,palette:Hx(r.theme,t)}]}))}),t.bindInputs({session:()=>this.view.get().session,read:e=>this.inputAt(e),drawnAt:()=>ky(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=Mk(e);return t===void 0?Ak(e)===void 0?e0(this.view.get().payload(),e):e0(this.projected,e):$1(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[P4[e]];if(t.kind===`decided`)return W4(t.name,null,null);let r=K4(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=q4(this.source,e,i.name,r.where,e=>{t=e}),W4(n,t,null)}case`pending`:return W4(n??hy[e],null,i.variable);case`failed`:return n=hy[e],W4(n,gy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!G4(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??hy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return c0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>l2(this.source.activeSegment,()=>c0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new J4(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:O0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=dI(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:L4(e)}),R4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:vF(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function H4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new V4(t,n,e,r);return e.views.set(t,a),a}function U4(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const W4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),G4=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function K4(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function q4(e,t,n,r,i){switch(t){case`palette`:return qx(n,r,i).name;case`style`:return fy(n,e.styles).name;case`effect`:return Sy(n).name}}var J4=class{where=Y4(k_({palette:O_,region:Hv}));ground=Y4(k_({colours:Z4,bodyOpen:O_}));opened=Y4(k_({colours:Z4,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=b1(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?z4(s0):e.derive(`${t.id} when`,e.readsInstant(a),()=>l2(r,()=>c0(a,i))),this.open=d===void 0?z4(o0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>l2(r,()=>c0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return e3(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return t3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?z4(r3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return n3(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),a3(n,r,this.affixes.read())}};function Y4(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const X4=(e,t)=>e.hex===t.hex,Z4=k_({palette:O_,drawnAt:O_,tint:X4,text:X4,bg:X4,disclosure:Gv});function Q4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const $4=e=>zv(e.palette,e.disclosure,e.drawnAt);function e3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Zv(n,r,i)};return c2(e,Q4(t,c),e=>{let t=nA(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function t3(e,t,n,r,i,a){return c2(e,Q4(t,n),e=>(e.bg=i?$4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function n3(e,t,n,r,i,a,o){return c2(e,Q4(t,n),e=>(e.bg=r?$4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const r3={lead:[],trail:[],drops:[]};function i3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return G0(t,$4(e).state,n)},get band(){return G0(t,$4(e).plane,n)},get close(){return J0(t,$4(e).state,n)},disclosure:r}}function a3(e,t,n){return{styles:i3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function o3(e,t,n,r,i,a,o){let s=e3(e,t,n,r,i,void 0,void 0,o);return a3(s,t3(e,t,s,a,!1,o),r3)}function s3(e,t,n,r,i){return i3(e3(e,t,n,r,i,void 0,void 0,{}))}function c3(e,t,n){return{session:n,payload:()=>e,selections:()=>t}}function l3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:X1(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 u3(e,t){switch(Yy(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 d3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:l3(n.cache),parse:u3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:l3(n.cache),parse:u3(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function f3(e,t,n,r=mw.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function p3(e,t,n){let{compiled:r,loadWarnings:i}=h3(e,t,n.cwd,m3(n.signer),y3);return{...r,loadWarnings:i}}const m3=e=>(t,n)=>b3(n,e);function h3(e,t,n,r,i=y3){let a=g3(e),o=_3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:v3(e,t,n,i)}}function g3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Lx)n in t&&r.set(e,n);for(let[t,n]of nb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...FU(e)].sort(([e],[t])=>e<t?-1:1)}}function _3(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function v3(e,t,n,r){let i=t4(e),a=FU(e),o=[];for(let[s,c]of ZR(e))if(r.has(i.get(s)))try{d3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const y3=new Set([`directory`,`view`]);function b3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>T0(i,`drawnAt`).registry.drawnAt(),o=o2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=mS(e.presets),u=fF(e),d=[e=>k2(i,o,e.now)],f=DU({extraFuncs:{...U0(i),...O2(i),...x2(i,o),...w2(i),...P2(i,o),...B2(i,o),...W2(s),...q2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=f3(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=k0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:f3(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=ob(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Eee(t,e,a,t=>String(T0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return j4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=_S(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(sy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of LU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:C3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w=new Set(n.map(([e])=>e)),te={reads:OU({names:w,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:wU(d)},ne=BU(te),T=[...C.values()].flatMap(S3(y)).some(e=>ne(m.get(e))),re=T?new Set([...te.clock,z2]):te.clock,E=BU({...te,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=BU({reads:OU({names:w,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:te.projections,clock:re});for(let e of wz){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function x3(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const S3=e=>t=>{let n=[];return d4(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function C3(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const w3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function T3(e,t,n,r,i){let a=E3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function E3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??hy[e];case`failed`:return r({kind:`rule`,slot:e,message:gy(t.where,e,`the rule failed — ${n.error}`)}),hy[e]}}function D3(e){return O3(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function O3(e){return e.kind===`container`?e.children.flatMap(O3):[e,...e.opens===void 0?[]:O3(e.opens.body)]}function k3(e,t,n,r,i,a,o){let s={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return H4(e,t,n,c3(s,a,o)),s}function A3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new PA(``),h=m.clockAt(a,vy[c.animationSpeed]),g=l.u(mU(a,h.timeline)),_=U4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:yj(v),padding:v.padding,seamCols:bj(v),preset:c.preset},i);let y=_.evaluated;l.u(O0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,s4),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&te.add(n.waited),n.name;let r=q4(t,e,T3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:qx(re(`palette`),``,w3),ae=D.kind===`decided`?D:fy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Sy(re(`effect`)),se=O.value,ce=Wx(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:s4,hold:c4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,n,i)=>{let a=n.kind===`hidden`?n:o4(n,_.gate(e)),o=a.kind===`failed`?{...a,report:()=>{let t=`when over ${D3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:a.message,message:`${t}: ${a.message} — what it gates is hidden`})}}:a,s={scope:_.scope,palette:ce,gate:o,padding:v.padding,region:i,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,a,o)=>o3(t.activeSegment,e,a,i,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Yv(i,n)),renderBody:(e,t,n)=>pe(e,t,Xv(n)),closeDisclosure:e=>W0(r.session(),e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>s3(t.activeSegment,e,n,i,r.drawnAt())};return j4(e.kind).render(e,s)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${fS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=i4(pe(me,s0,Jv(S))).map(({line:e,row:t})=>{let n=b0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...Ej(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||O3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const j3={moving:1e3/30,still:1e3},M3=[`data`,`state`,`reload`,`visibility`];function N3(e){return Wb.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function P3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const F3=(e,t)=>Ub[t].handsOff?e.resp:e.statusline,I3=e=>Math.round(1e3/e);var L3=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}feedOpen(e){return this.feeds.has(e)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Wee;let r=t-1,i=this.shown(n);return Xb(e=>{let a=n.rates.get(e);if(a===void 0)return Jb;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.clock.monotonic(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&e.phase.clear(),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.clock.monotonic(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${x(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,I3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||F3(a,t)!==F3(i,t))&&P3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=F3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:eC(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=fY.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} ceiling=${I3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${M3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function R3(e,t){return Wb.filter(n=>e[n]&&Ub[n].handsOff&&t.has(n))}function z3(e,t){return{severity:jB,lines:[[NB(`[⟲ claude]`,Ta([{verb:na,args:[e,...t.map(e=>Ub[e].switch.setting)]}]))]]}}function B3(e,t){for(let n of Object.entries(t))e.push(n)}const V3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function H3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,x(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function U3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...H3(n)];return{level:V3[n.kind],line:bc(e,i)}}const W3=()=>{},G3=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),K3={ansi:e=>({ok:!0,output:cj(e)}),frame:e=>({ok:!0,frame:e})};function q3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=jo();let i=c.u(r6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=a6(e,i,{by:`feed`,fps:n}),p=K3.ansi(o.body),m=f6(t,o,R3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:K3.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=U3(`render`,s,{kind:`threw`,error:e},A(i,o)),r=G3(e);return{bar:QA(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:W3,failure:{level:t,line:`frame ${n}`}}}}function J3(e,t,n){let{sessionState:r}=e;return dG(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function Y3(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:cG(i.view.source.effective(),Tc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function X3(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return cG(J3(e,n,o.state),s===null||Tc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function Z3(e,t,n){B3(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;B3(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:Bn(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const Q3=e=>Vn(Bn(e,e.hints));function $3(e,t,n,r,i){Z3(t,r,i),B3(i,{encoding:t.encoding}),(0,X.runInAction)(()=>{o6(e,t),e.worldStates.take(n),t6(e,t)[Symbol.dispose]()})}function e6(e,t){(0,X.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function t6(e,t){let n=i$(t.requested,e.sessionState,t.hookData.session_id);return e.renderCache.holdSession(n.projectDir,n.cwd,n.target.path,t)}function n6(e,t,n,r){let i=Q3(t);return i6(e,t6(e,t),t,i,n,r)}function r6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{Z3(o,n,r),s=Q3(o)}catch(e){throw a[Symbol.dispose](),e}return i6(e,a,o,s,n,r)}function i6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{hints:l}=n,u={hookData:n.hookData,deps:o,cwd:n.cwd,hints:l};return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:s,view:c,hintsError:r,payloadInputs:u,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function a6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.payload(),C=b.source.effective(),ee=b.source.failure(),w=cG(C,S.tmux!==void 0);B3(g,{lanes:Wb.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;B3(g,{width:String(ne)});let T=_c(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({sessionId:_,dismissed:r.get(_,HF),enabled:C.updateNotice}),D=oV(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Un(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:dV(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...Bc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=PB(_,n.by,ae,[...E.offer,...D],[...E.failure,...ue.map(e=>({about:e.kind,text:e.message,copy:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),pe=b.source.facts(),me={diagnostics:WB(fe),drawing:n,feeds:i.feedsOf(_,h),today:cX(pe.builtins.today,h)},he=ko(S.metrics)?void 0:S.metrics;B3(g,iX([...b.state.sources.keys()],pe)),B3(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:LY(S.git),feeds:N3(me.feeds)});let ge=[],_e=PY(C,ne),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=A3(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:ye}),we=IB(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te);f.observe(_,h,be.rows.some(e=>e.kind===`menu`),C.menuTimeout);let De=f.since(_,h);B3(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:KB(te.termRows,n.by===`feed`?Wb.flatMap(e=>{let t=Ub[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=GB(r.get(_,Bi),fe),je=Ae===null?be:XA(be,qB(fe,Ae,_,n.by,ke)),Me=u.gitProvider.getStats(),k=u.usageStore.getStats(),Ne=ve.lastFrame(),Pe=Ne.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Fe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,A=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ie=[...E.failure.map(()=>`update-failed`),...[...ue,...ge].map(A)].join(`,`)||`-`;return B3(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${k.size}/${k.hits}h/${k.misses}m`,effect:Ne.effect,effectT:Ne.t.toFixed(3),speed:`${Ne.speed}x`,effectRows:`${Ne.made}made/${Ne.reused}reused`,effectOwn:Pe,fadeBasis:Ne.basis,stateRev:String(Ne.revision),fades:Fe(Ne.fades),leaves:Fe(Ne.leaves),motion:je.motion,evaluated:String(xe),cellBreaks:String(Se),pending:je.pending.join(`,`)||`-`,rules:[...Ce].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.offer.length),ask:String(D.length),warn:Ie,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:xe,cellBreaks:Se,clickShown:re,pipeShown:le,delivered:Ee,lanes:w}}function o6(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,JG,o);let s=i1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,qG,s)}function s6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(c6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function c6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:i$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:kj(t.hookData)}}function l6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:c6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function u6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(n6(e,t,n,i));s6(e,t,cG(l.view.source.effective(),Tc(t.hints.tmux)));let u=o.monotonic(),d=r-u;B3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await RJ(t=>Promise.all([$Y(l.payloadInputs,n,f,()=>e.worldStates.of(l.sessionId),t),l.view.registry.inFlight(t)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();B3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:GY(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=a6(e,l,Kb),b=t.hookData.session_id,S=R3(y,s.following(b)),C=jj(t.hints.client??null)===`statusline`,ee=C?f6(b,h,S):h.body;return B3(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{frame:ee,delivered:d6(e,b,v,g,_)}}catch(e){a.e=e}finally{a.d()}}function d6(e,t,n,r,i){return()=>{n(),r!==null&&pee(e.sessionState,t,r),i!==null&&e.launcher.answeredPipeEvent(i)}}function f6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:XA(t.body,JB(z3(e,[r,...i]),t.diagnostics,e,t.geometry))}const p6=e=>{};function m6(e,t,n=``){let r=G3(t);return{outcome:{kind:`threw`,error:t},resp:{...r,error:`renderer ${e.name}: ${n}${r.error}`},seen:`failed`,settled:p6}}function h6(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&T.isAbsolute(t)&&{location:nB(t)}}}}function g6(e,t){e.push(...t.kind===`answered`?t.output.record:t.record)}async function _6(e,t,n,r,i,a,o,s){let c=h6(r),l=(t,r)=>void e.deliver({kind:`event`,at:Ue(n),event:{kind:`effect-done`,of:t.id,outcome:r===null?{kind:`ok`}:{kind:`failed`,reason:r}}},[[`sid`,c.hookData.session_id],[`effect`,String(t.id)]]),u=await e.answer({kind:`event`,at:a,event:{kind:`config`,context:c,worldState:t.requested(c)}});if(g6(s,u),u.kind===`threw`)return B3(s,{renderer:e.name}),m6(e,u.error,`its config turn: `);let d=await e.answer({kind:`event`,at:a,event:{kind:`request`,id:i,context:c,waitEndsAt:o}});if(g6(s,d),d.kind===`threw`)return B3(s,{renderer:e.name}),m6(e,d.error);let{effects:f}=d.output;B3(s,{renderer:e.name,effects:f.map(e=>`${e.kind}:${e.surface}`).join(`,`)||`-`});let p=null;for(let e of f)switch(e.kind){case`present`:e.request===i?p===null?p=e:l(e,`a second statusline frame for request ${i}`):l(e,`presents request ${e.request}, not this turn's ${i}`);break}if(p===null)return m6(e,Error(`presented no statusline frame for request ${i}`));let m=p,h=n.monotonic(),g;try{g=K3[c.encoding](m.frame)}catch(t){return l(m,`encoding its frame threw: ${G3(t).error}`),m6(e,t,`its frame could not be encoded: `)}return B3(s,{encoded:`${A(n,h)}ms`}),{outcome:{kind:`ok`},resp:g,seen:m.frame.motion,settled:e=>l(m,e?null:`the client did not take the answer`)}}const v6=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`]),y6=[[`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`]],b6=[[`workspace.added_dirs`,`string-list`]];function x6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of y6){let i=w6(n,e);if(i==null)t.missingRequired.push(e);else{let n=S6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of b6){let i=w6(n,e),a=i===void 0?r:C6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))v6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function S6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function C6(e){return Array.isArray(e)&&e.every(e=>S6(e)===`string`)?`string-list`:S6(e)}function w6(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 T6(e,t,n){let{tokens:r}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:hA(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function E6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ln.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ln.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function D6(e,t,n,r){let{report:i}=x6(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=rq(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!D(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=E6(e.encoding);s.ok||a.push(s.problem);let c=pr(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=zn(e),{configFile:u,refusedArgs:d}=T6(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:Nj(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:vA(u,l.configEnv)},refusedArgs:d}}}function O6(e,t){switch(e){case`vars`:return{what:e,vars:k6(t)};case`segments`:return{what:e,segments:P6(t)};case`config`:return{what:e,config:R6(t)}}}function k6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=M6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=A6(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:j6(r.lastUpdatedMs(),t.clock)})}return o}function A6(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};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`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function j6(e,t){return e===null?null:Math.max(0,t.now()-e)}function M6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,N6(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}`,N6(i));return t}function N6(e){return e.kind}function P6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=I6(n),o=F6(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:L6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function F6(e){let t=new Map;for(let n of mS(e.presets))for(let r of Wy(_S(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=By(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function I6(e){let t=[],n=new Set;for(let r of Wy(nS(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 L6(e,t,n){let r=new Set([...IR(e,t).keys()].flatMap(e=>QR(e,n)));return Array.from(r).sort()}function R6(e){return e===null?null:e.config}const z6=[`vars`,`segments`,`config`];function B6(e){return typeof e==`string`&&z6.includes(e)}const V6=e=>({resp:e,exitAfterFlush:null,settled:p6}),H6=e=>({kind:`reply`,...e}),U6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},W6=(e,t)=>H6(V6({ok:!1,error:t,code:e,daemonV:3}));function G6(e){let t=rq(e.sessionId);if(!t.ok)return W6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return W6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Wb.join(`, `)}): it predates the lane toggles — update it`);let n=Zb(e.lane);return n===null?W6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Wb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function K6(e,t,n,r,i){if(t.kind===`url`)return H6(V6(await e8(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?W6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?G6(a):typeof a.kind!=`string`||!Object.hasOwn(U6,a.kind)?W6(`BAD_REQUEST`,`unknown kind`):H6(await q6(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,settled:p6})}async function q6(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,effectSessions:m,menuIdle:h,journalTurns:g,sessionState:_,tmuxStatusLines:v,watcherRegistry:y,limits:b,handlerProbes:S,renderSightings:C,bundle:ee,sourceDigest:w,doctorStores:te}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,settled:p6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return V6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return V6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:J6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,collector:e.collector.stats(),effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:_.size(),observers:_.observers(),revision:_.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:v.stats(),watchersActive:y.size(),dirWatchesActive:y.dirWatches(),nextRestartReason:b.describeNextRestart(),handlerProbes:S.list(),clients:C.list(Ve(new Date(o.now()))),bundle:ee,sourceDigest:w,daemon:b.serving(),doctorStores:gZ(te)})});if(t.kind===`render`){let c=new Date(o.now()),l=Ve(c),u=o.monotonic(),d=Fe(r.at,u),f=[];a.requestsTotal++;let p=r.id,m=D6(t,a,e.log,e.home),h=(t,n)=>C.see(t.hookData.session_id,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Xo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Pj(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.hookData.session_id,m.req,p));let g=t=>{t.outcome.kind!==`ok`&&a.requestsErrored++,B3(f,{req:String(r.id),timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:s,line:c}=U3(`render`,f,t.outcome,A(o,u));return e.log(s,c),{resp:t.resp,exitAfterFlush:null,settled:t.settled}};if(!m.ok)return g(o8(m.problems));let _=await _6(e.renderer,e.collector,o,m.req,p,l,u+mr(m.req.deadline,r.at,{epochMs:c.getTime(),monoMs:u}),f).catch(e=>({outcome:{kind:`threw`,error:e},resp:G3(e),seen:`failed`,settled:p6}));try{return h(m.req,_.seen),g(_)}catch(e){throw _.settled(!1),e}}if(t.kind===`click`)return V6(await Q6(e,r,n,i,(n,r)=>$6(e,t,n,r)));if(t.kind===`debug`){if(!B6(t.what))return V6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${z6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?Z6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Dx(`colorCompatibility`)):X6};return V6({ok:!0,debug:O6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function J6(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const Y6={endcaps:Dx(`endcaps`),colorCompatibility:Dx(`colorCompatibility`),wrap:Dx(`autoWrap`),padding:Dx(`padding`),width:1/0},X6=new Map;function Z6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Dj(i,{...Y6,colorCompatibility:t}));return n}async function Q6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`req`,String(t.id)],[`queued`,`${Fe(t.at,o)}ms`]],c=await i(s,()=>n()||r());B3(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=U3(`click`,s,c,A(a,o));return e.log(l,u),i8(c)}async function $6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};B3(n,{via:`cli`});let{verb:a,value:o}=t;return typeof a!=`string`||typeof o!=`string`?{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof a} and ${typeof o}`]}:t8(()=>r8(e,a,o,i,n,r))}async function e8(e,t,n,r,i){return Q6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(B3(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Xn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Xn].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o=ja(a);if(!o.ok)return{kind:`bad-request`,problems:[o.problem]};let s={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return t8(()=>r8(e,o.verb,o.value,s,n,r))})}async function t8(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof XG?{kind:`closing`,error:e}:e instanceof ZG?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const n8={link:`verb`,"tmux-status":`linkVerb`};async function r8(e,t,n,r,i,a){if(t===`tmux-status-click`)return B3(i,{verb:t}),a8(e,n,i,a);B3(i,{[n8[r.via]]:t});let o=q$(t,n);o===null?B3(i,{sid:`-`}):o.ok&&B3(i,{sid:o.id});let s=o?.ok?e.collector.holding(o.id):()=>{};try{let s=await e.renderer.answer({kind:`event`,at:Ue(e.clock),event:{kind:`click`,verb:t,value:n,session:o,arrival:r,gone:a}});switch(s.kind){case`answered`:return i.push(...s.output.record),{kind:`ok`};case`threw`:throw i.push(...s.record),s.error}}finally{s()}}function i8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:return G3(e.error)}}async function a8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(B3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=ja(s.url);return t.ok?t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):r8(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await UQ(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,BQ,e.tmp),{kind:`ok`}}const o8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},settled:p6});function s8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return T.join(e,`update-act`,n)}const c8={kind:`idle`};function l8(e){if(e===null)return c8;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const u8=e=>({stdout:T.join(e,`stdout`),stderr:T.join(e,`stderr`),status:T.join(e,`status`)}),d8=e=>T.join(e,`record.json`);function f8(e){let t;try{t=s.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function p8(e){let t=qo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function m8(e,t){let n=T.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(T.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const h8=e=>e.now()-o.uptime()*1e3;async function g8(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function _8(e){try{return JSON.parse(s.readFileSync(d8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const v8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function y8(e,t,n,r){let i=null;async function a(a){let o=T.join(e,String(a)),c=_8(o);if(c===null)return null;if((i===null||!v8(i.record,c))&&(i={record:c,ours:await g8(c,t,n,h8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=u8(o),u=kt(l.status),d=u===null?null:p8(l.stderr)??p8(l.stdout);if(!s.existsSync(o))return null;let f={act:a,record:c,alive:i.ours,end:u,lastLine:d};return f.alive||(i.final=f),f}return{async read(){let t=null;for(;;){let n=f8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${T.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function b8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(T.join(e,`.claim-`));try{return s.writeFileSync(d8(r),JSON.stringify(n)),s.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{s.rmSync(r,{recursive:!0,force:!0})}}async function x8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=T.join(t,String(c)),u=e.launchJobSync(i,u8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!b8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return S8;if(f8(t).some(e=>e>c))return m8(t,c),S8;d=!0}finally{d?u.release():u.withdraw()}for(let e of f8(t).filter(e=>e<c))m8(t,e);return{ok:!0,act:c}}const S8={ok:!1,reason:`another act claimed this bundle first`};function C8(e,t,n){let r=u8(T.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function w8(e,t,n){if(t.kind===`pending`)return Oo(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}var T8=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function E8(e){return e.kind===`source`?e.newer.digest:cs(e.newer)}const D8=e=>`${e.version} [${en(e.digest)}]`;function O8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:D8(e.newer),running:D8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:cs(e.newer),running:cs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${ls}@${cs(e.newer)}`,`install`]}}}}const k8={offer:[],failure:[]};function A8(e,t,n){if(e===null)return k8;let r=E8(e);if(!n.enabled||n.dismissed===r)return k8;let i=O8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?NB(`[${i.busy}]`,null):NB(`[${i.act}]`,Ta([{verb:ca,args:[n.sessionId]}])),c=[NB(a,null),s,NB(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,HF,r]}])),NB(`[disable]`,Ta([{verb:Xi,args:[n.sessionId,UF,`false`]},{verb:Wi,args:[n.sessionId,WF,`false`]}]))];return{offer:[{severity:kB,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function j8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return M8(t)}}function M8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function N8(e){switch(e.kind){case`current`:return[`info`,`build: current ${D8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${D8(e.source)}, running ${D8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function P8(e){switch(e.kind){case`current`:return[`info`,`release: current ${cs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${cs(e.latest)}, running ${cs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${cs(e.installed)}, latest ${cs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function F8(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,gates:f,onApplied:p,log:m}=e,h=Oo(`unread`),g=Oo(`unread`),_=async e=>{let t=await i.startTime(e);if(w)throw new XG(`apply-update`);return t},v=y8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new T8,ee=e=>C.run(`acts`,e),w=!1,te=[],ne=(e,t)=>{te.push(n.every(t,e,{unref:!0}))},T=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function re(){let e=T(),t=e===null?null:E8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(HF,[t])})}function E(){let e=w?I:j8(h,g),r=w8(t.get(),e,Ue(n));(0,X.runInAction)(()=>t.set(r)),re()}function D(){let e=sn(a,()=>rn(o));return h=F(e),x(N8(e)),E(),e}async function ie(){let e=ds(tn,await us(ls,d,u,n));g=F(e),S(P8(e)),E()}let O=null,ae=Ne(m);async function oe(e){try{let t=await e();return O=null,{ok:!0,value:t}}catch(e){return e instanceof XG?{ok:!1,error:e.message}:(O=`update act files (${s}): ${e.message}`,ae([`error`,O]),{ok:!1,error:O})}}function se(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=C8(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;m(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function ce(){let e=await oe(async()=>{let e=await v.read();return w||se(e),e});if(w||!e.ok)return;let t=l8(e.value);y===null&&t.kind===`running`&&m(`info`,`apply-update: act ${t.act} is running; watching it`),y?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(m(`info`,`apply-update: act ${t.act} succeeded`),D(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await ee(ce),!w&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=D();ne(D,c),te.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),ne(()=>void ie(),l))},close(){w=!0,E(),te.forEach(e=>e())},notice:e=>A8(T(),y??c8,e),running:()=>ee(async()=>{let e=await oe(()=>v.read());return e.ok&&l8(e.value).kind===`running`}),error:()=>O,act:()=>ee(async()=>{if(w)throw new XG(`apply-update`);let e=await oe(()=>v.read());if(w)throw new XG(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=T();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=O8(t),a=e.value;if(l8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await x8(r,s,a===null?null:a.act,E8(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new Z(`apply-update: ${o.reason}`);m(`info`,`apply-update: act ${o.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),y={kind:`running`,act:o.act}})}}function I8(){return X.observable.box(Oo(`unread`),{deep:!1})}function L8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function R8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function z8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:L8(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=L8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!R8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var B8=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const V8=`pass`,H8={okMs:5*6e4,failedMs:45e3},U8=H8.okMs;function W8({failures:e}){return T1(H8,e,U8)}function G8(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function K8(e){return`git:${e}`}function q8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:T.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Ac(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${jc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function J8(e){return e.kind===`ok`?e.value.branch:void 0}function Y8(e){e.missed=!0,FJ(e,`unread`)}function X8(e,t){return e.missed&&e.reading.get().kind===`pending`&&PJ(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function Z8({value:e,pr:t}){let n=LJ(e);return n.kind===`ok`?F({...n.value,pullRequest:LJ(t)}):n}const Q8=L(`git cache closed`,`read`);function $8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var e5=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.forgeLookups=new Ao(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new pY(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new _V({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return zJ(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>Z8(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:Q8};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}built(e){let t={period:new E1(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:I,reading:MJ(),inFlight:null},n={root:e,refresh:new B8,watch:this.followWatch(e,null).watch,period:new E1(()=>{n.refresh.share(V8,()=>this.refreshPass(n))},this.clock),value:{reading:MJ(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=q8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(V8,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e){return e.holders++,e.value.missed&&(Y8(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(V8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(K8(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch($8(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,PJ(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of nJ(i.value))o.add(e);let s=J8(i),c=s===void 0?X8(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,G8(n),o.size===0?F(null):L([...o].join(`; `),`read`),A(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch($8(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(Y8(r),`owed`):(FJ(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,PJ(r,a.outcome),r.period.landed(W8(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch($8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,A(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(PJ(t,i),t.period.landed(W8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);IJ(e.value,t),IJ(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},t5=class{static usageDir(e){return T.join(e,`usage`)}static locksDir(e){return T.join(e,`locks`)}static isLocked(e,t){let n=T.join(this.locksDir(e),t);if(!s.existsSync(n))return!1;try{let e=s.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),s.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),s.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=T.join(this.locksDir(e),n),a=t.monotonic(),o=String(process.pid);for(;t.monotonic()-a<r;)try{return await s.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await Le(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=T.join(this.locksDir(e),t);try{await s.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([s.promises.mkdir(e,{recursive:!0}),s.promises.mkdir(this.usageDir(e),{recursive:!0}),s.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=T.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await Le(t,75);continue}try{let e=await s.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await Le(t,75)}}return k(`Failed to read ${n} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=T.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},c=JSON.stringify(o);await s.promises.writeFile(a,c,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const n5={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var r5=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(e,t){let n=t.now()-1440*60*1e3;return await t5.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await t5.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){k(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(n5).length} models`),this.executionCache=n5,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n5).length} models`),n5)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}},i5=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function a5(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const o5={okMs:60*1e3,failedMs:10*1e3},s5={calculatedCost:null,tokens:null,tokenBreakdown:null};function c5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function l5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const u5={entries:0,cost:0,breakdown:l5(),days:new Map};async function d5(e,t,n,r){let i=HJ(new Date(c5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await r5.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=HJ(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...BJ};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function f5(e){let t=0,n=0,r=l5(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...BJ};VJ(n,t),i.set(e,n)}}if(t===0)return{usage:s5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{usage:{calculatedCost:n,tokens:a,tokenBreakdown:r},days:i}}function p5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function m5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!p5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...BJ};VJ(r,t),n.set(e,r)}return Object.fromEntries(n)}async function h5(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function g5(e,t){(0,X.runInAction)(()=>e.set(t))}var _5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new i5;scans;daySets=new Map;speedFlight=new i5;requestFlight=new i5;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new pY(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new O1({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??o5,watch:D1,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async()=>{let e=await r().record;return e.kind===`failed`?e:F(e.kind===`ok`?e.value.usage:s5)},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e){let t=this.sessions.get(e);if(t===void 0)return Oo(`unread`);let n=t.failure.get();return n===null?F(t.record?.usage??s5):L(n,`read`)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.monotonic(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,A(this.clock,i)),g5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}declareToday(e,t){if(this.closed)return zJ(L(`usage store closed`,`read`));let n=XJ(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||p5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}async observed(e,t,n){let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return g5(this.hold(e).speed,t),t;let r=a5(t.kind===`ok`?t.value.usage.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return g5(this.hold(e).speed,s),s})}speedOf(e){return this.sessions.get(e)?.speed.get()??Oo(`unread`)}async ingest(e,t,n,r){let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,usage:s.value.usage,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>ie(e,`projects`)+O),i={roots:r,sums:new s1(`today over ${e.join(`,`)}`,()=>m5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await $J(e,E(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of cY(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await lY(e,r,u5,(e,t)=>d5(e,t,un(this.host),this.clock));if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of cY(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...f5(i),mainStamp:a})}async scan(e){try{let t=c5(this.clock.now()),n=await ZJ(e),r=[];for(let e of n){let n=await QJ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await QJ(Lo(n));if(a===void 0||a.mtimeMs<t)continue;let o=rq(i.slice(0,-6));if(!o.ok){this.log(`warn`,`usageStore scan: transcript ${JSON.stringify(i)} names no session: session id ${o.problem}`);continue}r.push({sessionId:o.id,path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await h5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=HJ(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}};const v5={command:null,todos:[],pending:[],done:[]};function y5(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function b5(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function x5(e,t){if(t.isSidechain)return e;let n=b5(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=y5(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function S5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>y5(e,t.name),[]),done:e.done}}var C5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new dY(v5,x5,(e.ledger??new pY(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return w5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:w5(e,t)}};function w5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(S5(t.value))}const T5=3e4;var E5=class{names;constructor(e){let t=e.logger??Pe;this.names=new O1({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>D5(e.launcher,t),every:()=>({okMs:T5,failedMs:T5}),watch:D1,maxEntries:64,logger:t,ledger:e.ledger??new pY(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function D5(e,t){let n=await pc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const O5=6e4,k5={okMs:O5,failedMs:O5};function A5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function j5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var M5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>k5,watch:D1,maxEntries:1,logger:t,ledger:e.ledger??new pY(t),clock:e.clock};this.name=new O1({...n,name:`host.name`,read:()=>j5(`name`,()=>A5(o.hostname()))}),this.user=new O1({...n,name:`host.user`,read:()=>j5(`user`,()=>o.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},N5=class{known=new uY(64);refreshes;constructor(e,t=Pe,n=new pY(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=P5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.monotonic(),i=PN(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function P5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const F5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function I5(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var L5=class{known=new uY(256);refreshes;constructor(e,t=Pe,n=new pY(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n){let r=this.clock.monotonic(),i=await R5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,A(this.clock,r)),i}};async function R5(e){let t=await z5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function z5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=B5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function B5(e,t){let n=e.toString(`utf8`).split(`
484
484
  `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!F5.test(t))continue;let r=I5(t);if(r!=null)return r}return null}const V5=e=>cz(e),H5=e=>T.join(e.storage.folder,V5(e.sessionId)),U5=e=>JSON.stringify([e.folder,e.generation]),W5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var G5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Dc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new O1({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(H5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:D1,maxEntries:256,logger:e.logger,ledger:e.ledger??new pY(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{s.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!Oc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(U5(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${U5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(U5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=U5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>W5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(T.join(n.folder,T.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(H5(e)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&Oc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>W5(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>W5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(U5(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=zc(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=H5(e),r;try{r=await s.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=L1(r);return i.kind===`failed`?L(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${A(this.clock,t)}ms`;try{let t=await s.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=T.join(e.folder,a.name);try{let{mtimeMs:r}=await s.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&V5(t.sessionId)===a.name);if(r>=n||o)continue;await s.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function une(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new M5({clock:n,logger:r,ledger:i}),gitProvider:new e5({inner:new AJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new _5({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new _Y({clock:n,logger:r,ledger:i}),metricsProvider:new DY({clock:n,logger:r,ledger:i}),activityProvider:new C5({clock:n,logger:r,ledger:i}),tmuxService:new E5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new N5(n,r,i),cacheExpiry:new L5(n,r,i),managedStorage:new G5({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new NY,log:e.logger,clock:n}}function*K5(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*dne(e){for(let t of Object.values(e.segments)){for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);yield*Object.values(t.partials??{})}for(let t of mS(e.presets)){for(let n of Wy(_S(e,t).node))n.when!==void 0&&(yield n.when);let n=bS(e,t);for(let e of sy){let t=n[e];cy(t)&&(yield t)}}for(let[,t]of K5(e))for(let[,e]of $y(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of YF(t))yield e}function fne(e,t,n){let r=jU(t),i=new Set,a=new Set,o=new Set;for(let e of dne(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of BR(e,t.helpers))a.add(n);for(let n of KR(e,t.helpers))o.add(n)}for(let[,e]of K5(t))for(let{reaches:t}of r.ofVariable(e))for(let e of t)i.add(e);let s=new Set(a);for(let e of a){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)s.add(e)}let c=new Set,l=new Set(n);for(let e of s){let n=t.actions[e];if(n!==void 0&&(`set`in n&&c.add(n.set),`insertSegment`in n&&l.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)l.add(e)}for(let e of mS(t.presets))for(let n of Wy(_S(t,e).node))n.kind===`segment`&&l.add(n.name);let u=(e,t)=>i.has(e)||t.kind===`state`&&c.has(t.key),d=e=>[...e].filter(e=>!Ii(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(K5(e));return[...f(`variable`,p.keys(),e=>u(e,p.get(e))),...f(`action`,Object.keys(e.actions??{}),e=>s.has(e)),...f(`helper`,Object.keys(e.helpers??{}),e=>o.has(e)),...f(`segment`,Object.keys(e.segments??{}),e=>l.has(e))]}function pne(e){return Math.floor(Math.max(e/4,e*Br-67108864))}const mne={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function q5(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=e.name===void 0?void 0:n.variables[sz(yk(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[yk(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>bk(e)(t)&&t!==sz(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${bA(e,`<default>`)}: projections=${[...FU(n).keys()].join(`,`)||`-`} instantSegments=${x3(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e.path} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}const hne=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},J5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${hne(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function gne(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(J5(t))} state=${n} files=${R(bA(e.configLayers,`<bundled default>`))} awaiting=${r(e.repos.awaiting)} declined=${r(e.repos.declined)} unproven=${e.repos.unproven.length===0?`-`:JSON.stringify(e.repos.unproven)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function _ne(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function Y5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function vne(e,t){return new Set(mS(e.presets).filter(n=>_S(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function yne(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,T.join(e.projectDir,Vz)])];return uV({named:[...pB(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:a})}function bne(e){return e.filter(Boolean).join(`
485
485
  `)||null}const X5=e=>e instanceof Error?e.message:String(e);function Z5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function xne(e){let{loaded:t,chain:n}=e;return M1({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:Z5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...Z5(t.installed),checkout:t.installed.checkout,roots:t.installed.roots,unreached:t.installed.unreached},config:t.config,dropped:t.dropped.map(e=>e.message),placed:null},sources:[...e.sources].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.folder,t.generation])})}function Sne(e,t){let n=new Map,r=new Map;for(let[i,a]of Object.entries(e.variables)){if(a.kind!==`source`)continue;let e=n.get(a.storage)??t.keyFor(a.storage);n.set(a.storage,e),r.set(i,e)}return r}function Q5(e,t,n){let r=[];try{let i=AW(t.locs,t.layers,nG,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Sne(i.config,n)};return{kind:`resolved`,...a,key:xne(a),warnings:r}}catch(e){return e instanceof pb&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function $5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??nG,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new _1(t.clock),m=new i0(t.runs,p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=h3(o,m,n,t.compile??m3(t.signer),wne),f.push(...h.loadWarnings);let r=m.view();f.push(...v3(o,r,n,r7)),r.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof pb&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:vne(l,u),fileHeldSettings:NG(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>fne(e.raw,i.placed,d)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:e.sources}}}function e7(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:A(i,e.started)},o=t=>bne([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:X5(r.cause),cause:r.cause}}}function Cne(e,t,n,r,i=null){let a=Q5(t,n,r.storage);if(a.kind===`failed`)return e7(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:$5(a,r);return e7(e,n,a.warnings,o,r.clock)}function t7(e,t,n,r,i=null){let a=r.clock.monotonic(),o=_B(r.locations,rV(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return Cne({repos:s,advisories:[wB(r.locations,e,t),SB(o),uB(s)],started:a},t,c,r,i)}function n7(e,t,n){let r=Q5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:$5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${X5(i.cause)}`,{cause:i.cause});return i.state}const wne=new Set([`directory`]),r7=new Set([`view`]);function Tne(e,t,n,{source:r,changed:i,log:a}){let o=n.hookData.session_id,s=e.registry.view();v3(e.config,s,t,r7);let c=X.observable.box(n,{deep:!1}),l;try{l=r({sessionId:o,state:e,store:s.variableStore,requested:()=>c.get()})}catch(e){throw s.dispose(),e}H4(e.compiled,s.variableStore,s,l);let u=(0,X.reaction)(()=>[l.payload(),l.selections(),s.published(),e.registry.published()],()=>i(o),{equals:X.compareShallow,fireImmediately:!0,onError:e=>a(`error`,`session view change threw sid=${JSON.stringify(o)}: ${String(e)}`)});return{sessionId:o,state:e,store:s.variableStore,registry:s,source:l,requested:e=>{e!==c.get()&&(0,X.runInAction)(()=>c.set(e))},facts:()=>c.get(),lastRenderCellsBySegment:new Map,retire:u,dispose:()=>(u(),s.dispose())}}const Ene=({sources:e})=>[...e].map(([e,t])=>({kind:`plugin`,source:e,storage:t}));var Dne=class{entries=new Map;answersWatch;closed=!1;due=new Map;walk=null;holds=new Map;views=new Map;copies=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Pe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},s.mkdirSync(tV(e.stateDir),{recursive:!0});let{dir:n,name:r}=sV(nV(e.stateDir));this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??b3(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=Y5(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n,null);a.state!==null&&this.log(`info`,q5(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??n7(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++;let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=jo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(Y5(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let i=n.hookData.session_id,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o;try{o=this.opened(e,t,n,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),o}opened(e,t,n,r){let i=n.hookData.session_id,a;try{a=Tne(t,e.cwd,n,{source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(i,{error:e,facts:n}),e}return this.openFailures.delete(i),this.views.set(i,a),this.viewHolds.set(a,{entry:e,holders:0,retired:null}),this.log(`info`,`session view opened sid=${JSON.stringify(i)} by=${r} cwd=${e.cwd} views=${this.views.size}`),a}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),this.views.has(e.sessionId)||this.copies.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}retireSession(e){this.openFailures.delete(e);let t=this.views.get(e);t!==void 0&&this.retireView(t,`idle`)}subscriptions(){return{sources:new Map([...this.views].map(([e,t])=>[e,Ene(t.state)]))}}close(){if(this.closed)return;this.closed=!0,this.walk?.(),this.walk=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n,r){if(this.closed)throw Error(`render cache used after close`);return t7(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.due.delete(t),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,due:this.due.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,_ne(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){this.due.delete(e);let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,q5(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state),this.retire(r,`reload`,{entry:e,state:i.state})),this.fit(e),this.refreshWatcher(e,i),this.observers.onReload?.(e,n,t,i.kind)}reloadEvery(e){for(let t of this.entries.values())this.due.set(t,e);this.armWalk()}armWalk(){this.walk!==null||this.due.size===0||(this.walk=this.deps.clock.defer(()=>this.walkOne()))}walkOne(){this.walk=null;let e=null;for(let t of this.entries.values()){let n=this.due.get(t);n!==void 0&&(e=[t,n])}if(e===null)return;let[t,n]=e;try{this.reloadInto(t,n)}catch(e){this.log(`error`,`every-entry reload threw projectDir=${R(t.projectDir)} cwd=${R(t.cwd)} configFile=${R(t.configFile??`-`)} cause=${R(J5(n))}: ${x(e)}`)}finally{this.armWalk()}}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=yne(e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const One=e=>!cq(e)&&!SN(e)&&e!==`update.dismissed`&&e!==Bi;var kne=class{past=X.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:eq(e,One,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new Z(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,X.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const i7=(e,t)=>e.kind===`ok`?F(t(e.value)):e;function Ane(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest}}const a7=(e,t)=>{let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>Object.is(n,Reflect.get(t,e)))};function jne({pullRequest:e,...t}){return t}function o7(e,t,n,r,i){let{lanes:a}=n,o=(e,t)=>w8(e,t,i),s=e?.builtins,c={session:o(s?.session,a.usage),today:o(s?.today,n.today),speed:o(s?.speed,a.speed),context:o(s?.context,a.context),metrics:o(s?.metrics,a.metrics),activity:o(s?.activity,a.activity),cache:o(s?.cache,a.cache),autocompact:o(s?.autocompact,a.autoCompact),git:o(s?.git,i7(a.git,jne)),pr:o(s?.pr,Ane(a.git)),tmux:o(s?.tmux,i7(a.tmuxSession,e=>({session:e}))),hostName:o(s?.hostName,a.hostName),hostUser:o(s?.hostUser,a.hostUser)},l=Object.fromEntries([...a.sources].map(([t,n])=>[t,o(e?.sources[t],n)])),u={builtins:c,sources:l,update:r,diagnostics:n.faults};return e!==void 0&&a7(c,e.builtins)&&a7(l,e.sources)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:1,session:t,seq:e===void 0?1:e.seq+1,...u}}function s7(e,t){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason===t?e:{...e,seq:e.seq+1,diagnostics:[...e.diagnostics.filter(e=>e.kind!==`stamp`),{kind:`stamp`,reason:t}]}}function c7(e){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason??null}const Mne=e=>({hookData:e.hookData,cwd:e.cwd,hints:e.hints}),Nne=e=>new Map(e.map(e=>[e.source,e.storage])),Pne=(e,t)=>e.size===t.size&&[...e].every(([e,n])=>{let r=t.get(e);return r!==void 0&&W5(n,r)});function l7({stop:e,holds:t}){e(),t.close()}var Fne=class{records=new Map;stopSweep=null;constructor(e){this.deps=e}requested(e){let t=Mne(e),n=e.hookData.session_id,r=(0,X.runInAction)(()=>{let e=this.records.get(n);if(e===void 0){let e=this.open(n,t);return this.records.set(n,e),e.stamped.document}e.active=!0;let{phase:r}=e;r.kind===`live`&&r.declared.set(this.declared({...e,locator:t},r.holds));let i=r.kind===`live`?r:this.live(e,t);return e.phase=i,this.stamp(e,i.inputs.get()),e.stamped.document});return this.armSweep(),r}subscribed({sources:e}){for(let t of e.keys())this.records.has(t)||this.deps.log(`error`,`subscriptions name session ${JSON.stringify(t)}, which the collector has no record of`);(0,X.runInAction)(()=>{for(let t of this.records.values()){let n=Nne(e.get(t.session)??[]);if(Pne(n,t.subscriptions))continue;t.subscriptions=n;let{phase:r}=t;r.kind===`live`&&r.declared.set(this.declared({...t,locator:r.declared.get().locator},r.holds))}})}holding(e){let t=this.records.get(e);return t?.phase.kind===`live`?(t.clicks++,()=>{t.clicks--,t.active=!0}):()=>{}}sweep(){for(let e of this.records.values())e.phase.kind===`live`&&(e.active?e.active=!1:e.clicks===0&&!this.deps.watched(e.session)&&this.retire(e,e.phase))}stats(){let e=[...this.records.values()];return{sessions:e.length,retiring:e.filter(e=>e.phase.kind===`retiring`).length}}close(){this.disarmSweep();for(let{phase:e}of this.records.values())e.kind===`live`&&l7(e);this.records.clear()}open(e,t){let n=new Map,r=this.reader({session:e,locator:t,subscriptions:n}),i=r.inputs.get(),a;try{if(i.kind===`failed`)throw Error(i.reason);a=o7(void 0,e,i.readings,i.update,Ue(this.deps.clock))}catch(e){throw r.holds.close(),e}let o={document:a,from:i};return{session:e,stamped:o,subscriptions:n,active:!0,clicks:0,phase:this.watch(e,o,r)}}live(e,t){return this.watch(e.session,e.stamped,this.reader({...e,locator:t}))}reader(e){let t=new C1,n=X.observable.box(this.declared(e,t),{deep:!1});return{holds:t,declared:n,inputs:(0,X.computed)(()=>this.read(n.get()))}}watch(e,t,n){let r=(0,X.reaction)(()=>n.inputs.get(),n=>(0,X.runInAction)(()=>{n!==t.from&&this.stamp({session:e,stamped:t},n)&&this.deps.deliver({kind:`world-state`,worldState:t.document})}),{onError:t=>this.deps.log(`error`,`world state stamp threw sid=${JSON.stringify(e)}: ${x(t)}`)});return{kind:`live`,...n,stop:r}}declared({session:e,locator:t,subscriptions:n},r){let i=JSON.stringify(e);try{let{result:{lanes:e,faults:a},acquired:o,released:s}=r.declare(()=>YY(this.deps.owners,r,t,n));for(let e of a)this.deps.log(`error`,`session declaration threw sid=${i} ${e}`);return o+s>0&&this.deps.log(`info`,`session declared sid=${i} acquired=${o} released=${s} held=${r.size}`),{locator:t,lanes:e}}catch(e){return this.deps.log(`error`,`session declaration threw sid=${i}: ${x(e)}`),{locator:t,lanes:qY(L(`session declaration threw: ${String(e)}`,`read`),[...n.keys()])}}}inputsOf(e){return{...e,deps:this.deps.owners}}read({locator:e,lanes:t}){try{return{kind:`read`,readings:XY(this.inputsOf(e),t),update:this.deps.update()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}}stamp({session:e,stamped:t},n){let r=t.document,i=n.kind===`failed`?s7(r,n.reason):this.assembled(r,n,Ue(this.deps.clock)),a=i===r?null:c7(i);return a!==null&&this.deps.log(`error`,`world state sid=${JSON.stringify(e)}: ${a}`),t.document=i,t.from=n,i!==r}assembled(e,t,n){try{return o7(e,e.session,t.readings,t.update,n)}catch(t){return s7(e,`stamping the world state: ${String(t)}`)}}retire(e,t){l7(t);let n={kind:`retiring`};e.phase=n,this.deps.log(`info`,`session retired sid=${JSON.stringify(e.session)}`),this.deps.deliver({kind:`retire`,session:e.session}).then(()=>{e.phase===n&&this.records.get(e.session)===e&&this.records.delete(e.session),this.records.size===0&&this.disarmSweep()})}armSweep(){this.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.sweep(),{unref:!0}))}disarmSweep(){this.stopSweep?.(),this.stopSweep=null}},Ine=class{documents=X.observable.map(void 0,{deep:!1});take(e){let t=this.documents.get(e.session);if(t!==void 0&&e.seq<=t.seq){if(e.seq===t.seq&&(0,X.compareStructural)(e,t))return;throw Error(`world state seq ${e.seq} for session ${JSON.stringify(e.session)} does not follow the held seq ${t.seq}`)}(0,X.runInAction)(()=>this.documents.set(e.session,e))}of(e){let t=this.documents.get(e);if(t===void 0)throw Error(`no world state for session ${JSON.stringify(e)}: the host hands one in with the config ahead of every request`);return t}drop(e){(0,X.runInAction)(()=>this.documents.delete(e))}};function Lne(e){return({sessionId:t,state:n,store:r,requested:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>dG(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n}=i();return{hookData:t,hints:n,home:e.home}}),c=r.derive(`session.draw`,`computed`,()=>({sources:[...n.sources.keys()],effective:o.read(),configFacts:{...PG(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),l=()=>e.worldStates.of(t),u=r.derive(`session.payload`,`computed`,()=>nX(l(),s.read(),c.read()));return{session:t,payload:()=>u.read(),effective:()=>c.read().effective,facts:l,hints:()=>s.read().hints,failure:()=>c7(l()),selections:()=>c.read().effective}}}const u7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,d7=`#{session_id} #{client_control_mode} #{pane_id}`;function f7(e){let t=new Set;for(let n of e.split(`
486
486
  `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function p7(e,t){let n=new Set;for(let r of e.split(`
@@ -490,7 +490,7 @@ function run(argv) {
490
490
  `).map(e=>e.split(` `)[0]??``),a={};for(let e of x7)i.includes(C7(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function F7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,C7(Number(t)),T7(n)])]}const Zne=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...N7(e),...x7.map(e=>M7(C7(e))),j7(e,_7),j7(e,v7)];function I7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:w7(t)}catch(e){return{kind:`theirs`,why:`${_7} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function Qne(e,t,n){let[r=``,...i]=t,a=P7(i.slice(0,2+g7)),o=i.slice(2+g7,2+2*g7),[s=``,c=``]=i.slice(2+2*g7);if(s!==``)return I7(s,c,n);let l=w7(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:g7-l},(e,t)=>[l+t,qne(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,_7,JSON.stringify(f)],...F7(e,d)]}}const L7=e=>[...N7(e),j7(e,v7)];function R7(e,t,n){let r=P7(n.slice(0,2+g7)),i=n[2+g7]??``,a=[],o=[];if(Yne(r.formats,t.wrote))a.push(...F7(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,C7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,T7(t.status)]):o.push(`status`)),a.push(...x7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,S7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,_7],[`set-option`,`-q`,`-u`,`-t`,e,v7]),{commands:a,kept:o}}const $ne=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,z7=[[`list-keys`,`-T`,`root`]];function B7(e){let t=$ne.exec(e);return t===null?null:{line:t[0],command:t[1]}}const V7=`cc-candybar://tmux-status-click/`,ere=e=>`${V7}${Ca([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,H7=e=>e?.command.includes(V7)??!1;function U7(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,y7]};return H7(B7(t))?{steps:[e===null?{command:[`unbind-key`,...b7]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var tre=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=h7(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(e){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[t,n]of this.servers){for(let[r,i]of[...n.layouts]){n.layouts.delete(r);let a=this.askSync(e,t,L7(r));if(a===null)continue;let o=R7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}let r=n.binding;if(n.binding={kind:`none`},r.kind===`ours`||r.kind===`adopted`){let n=this.askSync(e,t,z7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=nre(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,g7-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${_7}}\t#{${v7}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
491
491
  `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=I7(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[M7(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${y7} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,Zne(n));if(r===null||this.closed)return null;let i=Qne(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,S7(r),e])}),i!==n.status){let e=Jne(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,v7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,Xne(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,L7(n));if(i===null)return;let a=R7(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,z7);if(r===null||this.closed)return;let i=B7(r[0]??``);if(n.kind===`none`&&H7(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&H7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...b7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${D7(`${this.deps.handler} ${ere(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,z7);if(r===null)return;let i=U7(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n,r){let i=U7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,E7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,E7(n),r)))}};function nre(e){try{return wa(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),rre={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":W7(`none`),"--background":W7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":W7(`optional`),"-c":W7(`none`),"--continue":W7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":W7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":W7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":W7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":W7(`optional`),"-h":W7(`none`),"--help":W7(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":W7(`none`),"--print":W7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":W7(`optional`),"--resume":W7(`optional`),"--safe-mode":$(`none`),"--session-id":W7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":W7(`optional`),"--tmux":W7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":W7(`none`),"--version":W7(`none`),"-w":W7(`optional`),"--worktree":W7(`optional`)},ire={resume:`--resume`,fresh:`--session-id`};function are(e){return[ire[e.kind],e.sessionId]}const G7=e=>e.startsWith(`-`)&&e!==`-`;function K7(e,t){let n=q7(t);return n===null?{dir:e??t,args:[]}:e!==null&&ore(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const ore=(e,t)=>e===t||e.startsWith(t+T.sep);function sre(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!G7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=rre[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!G7(e)):o.arity===`variadic`?cre(n.slice(r),e=>!G7(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function q7(e){let t=e.split(T.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(T.sep),repo:t.slice(0,n-1).join(T.sep)||T.sep}}function cre(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,lre=T.join(`bin`,`cc-candybar-native`),ure=DN(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=AQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const dre={band:{on:async(e,t,n)=>{let r=nn(t.bundle);if(r===null)throw new Z(`${Ub.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=T.join(r,lre);if(!n.fileExists(i))throw new Z(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${J7} from ${r}`,finished:fre(e,r,n)}},off:async()=>Y7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=X7(e),i=j(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${Ub.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:hre(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>Y7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=X7(e),i=await n.barPanes(r);return i.length>0?Y7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Y7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=AQ(e.hints.tmux);if(r.kind===`refused`)return Y7(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return Y7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>Y7(`the daemon draws ${X7(e).pane}'s bar in its status line`),off:async()=>Y7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function fre(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,J7],r);let i=await jQ(n.claudeInput,e.hints.tmux,ure);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${J7} from ${t} and typed /reload-plugins into ${i.pane}`}const pre=new Set([Jo,gA]);function mre(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function hre(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Wt(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Ub.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=bre(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Ub.statusline.label} off and on again`);let s=gre(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=sre(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=mre(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>pre.has(e)),m=(e,t)=>qt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...are(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=_re(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(K7(null,i.cwd),_))}let y=m(K7(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${vre[g.kind](e.sessionId)}, and its statusline follows lane B`}function gre(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function _re(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const vre={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},yre={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function bre(e){let t=TQ(e);return t.kind===`ready`?OQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:EQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:yre[t.kind]}var xre=class{owed=new Map;setups=new T8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Wb.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),hc(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await dre[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};const Sre=[`request`,`feed`],Z7=new WeakMap;let Cre=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Cre++;return Z7.set(e,n),n};var wre=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get($7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Q7(n.config),i=[];for(let n of Sre){let a=this.records.get($7(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=$7(e,t);this.records.delete(a),this.records.set(a,{generation:Q7(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const $7=(e,t)=>`${t}\0${e}`;var Tre=class{queue=new T8;sessions=new T8;gathers=new T8;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new ZG(e);let a=this.deps.monotonic();t(Fe(i,a)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(A(this.deps,c)),this.refuseClosed(e),i())throw new ZG(e);let t=this.deps.monotonic(),l=await o();a(A(this.deps,t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:A(this.deps,e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new XG(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},e9=class extends Error{constructor(e,t,n){super(t instanceof Error?t.message:String(t)),this.record=e,this.thrown=t,this.subscriptions=n,this.name=`TurnThrew`}};function Ere(e,t,n,r,i){let a=async e=>{try{let t=await n.answer(e);if(i(t.subscriptions),e.event.kind!==`request`)for(let n of t.effects)o(n,`a ${e.event.kind} turn answers no request`);return{kind:`answered`,output:t}}catch(e){return e instanceof e9?(i(e.subscriptions),{kind:`threw`,error:e.thrown,record:e.record}):{kind:`threw`,error:e,record:[]}}},o=(e,n)=>void c({kind:`event`,at:Ue(t),event:{kind:`effect-done`,of:e.id,outcome:{kind:`failed`,reason:n}}},[[`sid`,e.session],[`effect`,String(e.id)]]),s=(t,n,i)=>{let a=[[`renderer`,e],[`input`,t.event.kind],...n];switch(i.kind){case`answered`:i.output.record.length>0&&r(`info`,bc(`turn`,[...a,...i.output.record]));return;case`threw`:r(`error`,bc(`turn`,[...a,...i.record,[`error`,x(i.error)]]))}},c=async(e,t)=>{let n=await a(e);return s(e,t,n),n};return{name:e,answer:a,deliver:c}}async function Dre({verbs:e,menuIdle:t},{verb:n,value:r,session:i,arrival:a,gone:o},s){let c=e.handler(n);if(c===void 0)throw new Z(`unknown click verb: ${n}`);let l=i?.ok?i.id:null;l!==null&&t.clickArrived(l);try{await c(r,{arrival:a,placeWaited:e=>B3(s,{placeWait:`${e}ms`}),gatherTook:e=>B3(s,{gather:`${e}ms`}),turnWaited:e=>B3(s,{turnWait:`${e}ms`}),clientGone:o})}finally{l!==null&&t.clickSettled(l)}}function Ore(e){let t=new Map,n=0,r=(t,n)=>({effects:t,subscriptions:e.renderCache.subscriptions(),record:n}),i=async(i,a,o)=>{switch(i.kind){case`config`:return $3(e,i.context,i.worldState,a,o),r([],o);case`request`:{let{frame:s,delivered:c}=await u6(e,i.context,a,i.waitEndsAt,o),l=++n;return t.set(l,c),r([{kind:`present`,id:l,session:i.context.hookData.session_id,surface:`statusline`,request:i.id,frame:s}],o)}case`world-state`:return e.worldStates.take(i.worldState),r([],o);case`retire`:return e6(e,i.session),r([],o);case`effect-done`:{let e=t.get(i.of);if(e===void 0)throw Error(`effect-done for effect ${i.of}, which is not a present on its way`);return t.delete(i.of),i.outcome.kind===`ok`&&e(),r([],o)}case`click`:return await Dre(e,i,o),r([],o);case`menu-idle`:return await e.verbs.closeIdle(i.session,i.idle),r([],o)}};return{answer:async({event:t,at:n})=>{let r=[];try{return await i(t,n,r)}catch(t){throw new e9(r,t,e.renderCache.subscriptions())}}}}function kre(e){return{handler:t=>{let n=n1.get(t);return n&&((t,r)=>n(t,{...e,...r}))},closeIdle:(t,n)=>r1(t,n,e)}}async function Are(e,t,n,r){let i=await e.answer({kind:`event`,at:t(),event:{kind:`menu-idle`,session:n,idle:r}});if(i.kind===`threw`)throw i.error}var jre=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?nx(t.since,t.timeoutS):null;t.timer?.at!==n&&(this.disarm(t),n!==null&&(t.timer={at:n,clear:this.deps.clock.after(Math.max(0,(n-this.deps.now())*1e3),()=>this.fire(e),{unref:!0})}))}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};function Mre(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=En(c),u=()=>Ve(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new JZ(i),h=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,now:u,observeWarnings:e=>{e.kind===`launch-pipes`?p(`warn`,e.text):p(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),pe.wakeWhere(`data`,()=>!0)}}),g=e.probe(h),_=e.storage(p),v=new nq(_.session),y=new fq(v,p,_.history),b=Wr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),S=new uQ,C=new Ij,ee=e.doctorStores,w=new _V({clock:i,counters:m,logger:p}),te=new pY(p),ne=new Lc({watchers:w,logger:p,clock:i}),T=new J1({launcher:h,clock:i,logger:p,ledger:te,watchers:w,fileEvents:ne}),re=une({launcher:h,host:c,watchers:w,fileEvents:ne,clock:i,logger:p,ledger:te}),{gitProvider:E,usageStore:D,tmuxService:ie,hostService:O,managedStorage:ae}=re,oe=new kne,se=new FA,ce=new jre({clock:i,now:u,close:(e,t)=>Are(Ee.renderer,u,e,t),failed:(e,t)=>p(t instanceof XG?`info`:`error`,`menu-idle: close failed (session=${e}): ${x(t)}`)}),le=e.linkSigner,ue=new Cc({supersede:(e,t)=>ae.supersede(e,t),launch:h.launch,state:v,log:p,now:u,clock:i}),de=new xre({edge:e.laneEdge(h,e=>pe.following(e),d.signal,g),host:{bundle:t.path,node:t.node,socket:o.socket,preload:Cs(t.path,c)},state:v,log:p,now:u,defer:e=>void i.defer(e)}),fe=new tre({edge:{run:(e,t,n)=>pc(h,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>pe.subscribe(e,t),sessionInPane:(e,t)=>pe.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Vt(o.socket)}`,...[...t.node,t.path].map(Vt),`url-handle`].join(` `),owner:o.socket,log:p}),pe=new L3({render:(e,t,n)=>q3(Ee,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>v.revision(e),t),lanes:e=>Y3(Ee,e),pin:e=>{let t=ye.pin(e);return()=>{ye.stopDrawing(e,`feed`),t()}},shown:e=>me.shown(e.hints.tmux),watching:()=>me.follow(),refreshes:()=>te.totals(),periods:j3,clock:i,instant:u,log:p}),me=new zne({clock:i,listPanes:e=>pc(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,u7]),listClients:e=>pc(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,d7]),sockets:()=>new Set(pe.watched().flatMap(({req:e})=>he(e))),onAnswer:(e,t)=>fe.answered(e,t),onChange:e=>pe.wakeWhere(`visibility`,t=>he(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function he({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ge=new wre,_e=I8(),ve=new Ine,ye=new Dne({clock:i,runs:T,stateDir:o.state,locations:l,env:c.env,sessionState:v,watchers:w,log:p,storage:ae,signer:le,gates:s,source:Lne({sessionState:v,worldStates:ve,home:c.home,history:e=>y.depth(e),navigation:(e,t)=>oe.depth(e,v,s.state.gateFor(t))})},{budgetBytes:()=>pne(n),observers:{onReload:(e,t,n,r)=>{p(`info`,gne(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`)}});ne.subscribe(e=>{switch(e.kind){case`period`:w.judge();return;case`caught-up`:ye.reloadEvery({kind:`events-resumed`,since:e.since}),pe.wakeWhere(`data`,()=>!0);return;case`moved`:pe.wakeWhere(`data`,()=>!0);return}});let be=60*1e3,xe=z8({clock:i,targets:t.targets,intervalMs:be,stat:e.stat,held:()=>Se.running(),exit:()=>a(0),log:p}),Se=F8({fact:_e,clock:i,launcher:h,probe:g,entryUrl:t.entryUrl,digest:t.digest,actsDir:s8(o.state,t.path),intervalMs:be,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>xe.checkNow(),log:p}),Ce=new Tre({log:p,monotonic:()=>i.monotonic()}),we={gates:s,sessionState:v,stateDir:o.state,locations:l,journalTurns:Ce,clickLanded:e=>ce.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>Se.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];ye.reload(...t,{kind:`doctor`});let n=ye.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:ee,probes:S,clients:C,bundle:t.path,serving:()=>b.serving(),claudeInput:e.claudeInput(h),history:y,navigation:oe,configFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>ye.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:le,runs:ue,lanes:{of:(e,t)=>X3(Ee,e,t),clicked:(e,t,n)=>l6(Ee,e,t,n)},views:{follow:(e,t)=>ye.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>ye.drawnCopy(e,t,n)},Te=new Fne({owners:re,update:()=>_e.get(),clock:i,watched:e=>pe.feedOpen(e),deliver:e=>Ee.renderer.deliver({kind:`event`,event:e,at:u()},[[`sid`,e.kind===`world-state`?e.worldState.session:e.session]]),log:p}),Ee={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:ee,stats:m,handlerProbes:S,renderSightings:C,watcherRegistry:w,refreshLedger:te,fileEvents:ne,payloadProviders:re,sessionState:v,effectSessions:se,menuIdle:ce,journalTurns:Ce,linkSigner:le,runs:ue,sourceRuns:T,laneSetups:de,tmuxStatusLines:fe,frameFeeds:pe,renderWarnings:ge,renderCache:ye,updateWatch:Se,limits:b,collector:Te,worldStates:ve,renderer:Ere(`main`,i,Ore({clock:i,log:p,sessionState:v,renderCache:ye,payloadProviders:re,worldStates:ve,linkSigner:le,renderWarnings:ge,effectSessions:se,frameFeeds:pe,updateWatch:Se,fileEvents:ne,menuIdle:ce,launcher:h,laneSetups:de,tmuxStatusLines:fe,verbs:kre(we)}),p,e=>Te.subscribed(e))};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),K6(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),q6(Ee,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),we.reloadConfig(e)},arm(){d.signal.throwIfAborted(),ne.start(o.watchProbe),xe.arm(),Se.arm(),b.arm()},close(e){let t=[[`journalTurns close`,()=>Ce.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>pe.close()],[`menuIdle dispose`,()=>ce.dispose()],[`updateWatch close`,()=>Se.close()],[`binaryWatch close`,()=>xe.close()],[`limits disarm`,()=>b.disarm()],[`collector close`,()=>Te.close()],[`renderCache close`,()=>ye.close()],[`gitService close`,()=>E.close()],[`usageStore close`,()=>D.close()],[`tmuxService close`,()=>ie.close()],[`hostService close`,()=>O.close()],[`runs close`,()=>ue.close()],[`sourceRuns close`,()=>T.close()],[`managedStorage close`,()=>ae.close()],[`fileEvents close`,()=>ne.close()],[`watcherRegistry close`,()=>w.closeAll()],[`sessionState close`,()=>v.close()]];for(let[e,n]of t)try{n()}catch(t){p(`warn`,`${e} failed: ${t.message}`)}return f=!0,h.settled()}}}function Nre(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 Pre=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Pe){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e=new Map,t;try{t=s.readFileSync(this.filePath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${n}); starting empty`),e}try{let n=JSON.parse(t);return Nre(n)?iq(n,(e,t)=>this.logger(`warn`,`session-state load: dropped session key ${JSON.stringify(e)}: session id ${t}`)):(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),e)}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),e}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=A(this.clock,n);try{await s.promises.mkdir(T.dirname(this.filePath),{recursive:!0});let o=await s.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await s.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await s.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${A(this.clock,n)}ms held=${a}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.clearTimer?.(),this.clearTimer=null,this.pending===null)return;let e=this.pending,t=this.clock.monotonic();try{s.mkdirSync(T.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);s.writeFileSync(n,r,{mode:384}),s.chmodSync(n,384),s.rmSync(this.writingPath,{force:!0}),s.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,A(this.clock,t)),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${A(this.clock,n)}ms held=${r}ms`)}};function Fre(e,t,n){return{session:new Pre(e.sessionState,n,500,t),history:Nq(e.settingsHistory,t)}}function t9(e,t,n){for(let r of(t??``).split(T.delimiter)){if(!T.isAbsolute(r))continue;let t=T.join(r,e);if(n(t))return t}return null}function n9(e,t){try{return s.accessSync(e,t),s.statSync(e).isFile()}catch{return!1}}function Ire(e){try{return s.realpathSync(e)}catch{return T.resolve(e)}}function Lre(e,t,n){let r=t9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:T.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const r9=2e3;async function i9(e,t,n,r){let i=await pc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function a9(e,t){if(t.ok)return t.stdout;let n=Xe(t,t.stdout);throw Error(`${e} failed (${Ze(t)}${n===``?``:`: ${n}`})`)}function Rre(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const zre=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Bre(e,t){return e.split(`
492
492
  `).flatMap(e=>{let[n,...r]=e.trim().split(` `);return zre.exec(r.join(` `))?.[1]===t?[n]:[]})}const Vre=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Hre(e,t,n){for(let r of Yq(Jq(e),t)){if(r.command.split(` `).some(e=>Vre.test(e)))return!0;if(r.pid===n)return!1}return!1}const Ure=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
493
- `);async function Wre(e,t){if(process.platform===`linux`)return{executable:await s.promises.readlink(`/proc/${t}/exe`),argv:(await s.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await s.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=a9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Ure,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function o9(e,t,n){return a9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function s9(e,t){let n=await pc(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await o9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Gre(e,t){let{panePid:n,cwd:r,foreground:i}=await s9(e,t),a=await o9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Wre(e,i),c=Jq(a).get(i)?.ppid;if(c===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await s.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:c,fromShell:i!==n,attached:Hre(a,i,n)}}function Kre(e,t,n,r,i){let a=e=>Le(r,e,n);return{claudeInput:IQ(e),barPanes:async t=>Bre(await i9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await i9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await i9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void a9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Fq(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:KF,paneClaude:t=>Gre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+r9;for(;;){let o=await s9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${r9/1e3} s`);await a(100)}},launcherNode:e=>Lre(e,e=>n9(e,s.constants.X_OK),Ire),onPath:(e,t)=>{let n=t9(e,t,e=>n9(e,s.constants.X_OK));return n===null?null:s.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?Rre(i.stdout):null;return a===null?(a9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(100)}return!0},typeShellLine:async(t,n)=>void await i9(e,t,PQ(t.pane,`cc-candybar-lane`,[]),n)}}const qre=/^[0-9a-f]{64}$/;function c9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Jre(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>c9(e,t).toString(`hex`),verify:(t,n)=>qre.test(n)?ue(Buffer.from(n,`hex`),c9(e,t)):!1}}function l9(e){return T.join(e,`link.key`)}function u9(e){let t,n=()=>t??=Yre(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Yre(e){let t;try{t=s.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Xre(e),t=s.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Jre(t)}function Xre(e){s.mkdirSync(T.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;s.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{s.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{s.unlinkSync(t)}}function Zre(e,t,n){return{daemonLog:t,launcher:e=>It(e,n),storage:t=>Fre(e,t,n),doctorStores:hZ(e.state),doctorEdge:DZ,claudeInput:IQ,probe:qs,laneEdge:(e,t,r,i)=>Kre(e,t,r,n,i),linkSigner:u9(l9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Xr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:s.statSync}}const Qre=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function d9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Qre[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const $re={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function eie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=d9(t),o=d9(n),s={};for(let e of r){let t=$re[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function tie(e){return{ok:!0,band:e.rows.map(e=>uj(e).map(eie))}}function nie(e){return $A(tie,e)}const rie={band:e=>JSON.stringify(nie(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:h7(e)})};function f9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function iie(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(er(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,p6)}),u=nr(r=>{let i=Zn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{if(!c){e.kind===`reply`&&e.settled(!1);return}e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.settled):d(e.sessionId,e.lane)}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(G3(t),null,p6)}).finally(()=>{c||(l(),a())})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,p6)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=f9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(tr(rie[i](e,t))),refused:e=>t.end(er(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const p9=`CC_CANDYBAR_PARENT_PID`;function aie(e){let t=e[p9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${p9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function oie(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let m9=null,h9=null,g9=null,_9=null;function v9(){if(_9===null)throw Error(`runDaemon has not started`);return _9}function y9(e,t){v9().log.log(e,t)}function sie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:an(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function cie(e){let n=N(e.host);_9={world:e,paths:n,log:new dee(n.log,e.clock)},t.on(`uncaughtException`,e=>{y9(`error`,`uncaughtException: ${e.stack||e.message}`),C9(1)}),t.on(`unhandledRejection`,e=>{y9(`error`,`unhandledRejection: ${String(e)}`),C9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{y9(`info`,`received ${e}, shutting down`),C9(0)});lie().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${x(e)}`),C9(1)}async function lie(){let{world:e,paths:n,log:r}=v9(),{host:i}=e,a=Ir(i.env);m9=await Ys(t.pid,qs(e.launcher).startTime);let o=await tc(rc(e,m9,n.registry));if(!o.decision.allow){y9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),C9(1);return}h9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),hn(n.socket);let c=Mre({...Zre(n,r,e.clock),bundle:sie(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:GF(),exit:C9});g9=c,oie({clock:e.clock,anchor:aie(i.env),probe:qs(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,de.createServer(e=>iie(c,e)),n.socket,!1)}function x9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){y9(`error`,`server error: ${a.message}`),C9(1);return}if(i){y9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}uie(e,n,r).catch(b9)}),n.listen(r,()=>die(e,r))}async function uie(e,n,r){let i=await Rs(zs(gn(r)),(t,n)=>Js(t,n,qs(e.launcher)));if(i.kind===`attach-and-exit`){y9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}y9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){y9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),C9(1);return}}x9(e,n,r,!0)}function die(e,n){let r=Hs(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}pie(n);try{s.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Fr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Fr(e.memoryLimitBytes)}MB`),ai(v9().paths.spawnBackoff),e.arm(),fie(n,r.identity)}function fie(e,n){Gs({bound:n,myPid:t.pid,readIdentity:()=>Hs(e),readLease:()=>zs(gn(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function pie(e){let n=Bs(gn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const mie=e=>(t,n,r)=>fee(e,{socket:t},`tmux-status`,n,r);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(mie(v9().world.launcher)),Vs(v9().paths.lease,t.pid),h9!==null&&nc(h9,t.pid,$s,e=>s.unlinkSync(e)),t.exit(e))}const hie={connectMs:200,budgetMs:500};async function gie(e,t,n){return _ie(t,await vie(e,t),n.includes(`--json`))}function _ie(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
493
+ `);async function Wre(e,t){if(process.platform===`linux`)return{executable:await s.promises.readlink(`/proc/${t}/exe`),argv:(await s.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await s.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=a9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Ure,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function o9(e,t,n){return a9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function s9(e,t){let n=await pc(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await o9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Gre(e,t){let{panePid:n,cwd:r,foreground:i}=await s9(e,t),a=await o9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Wre(e,i),c=Jq(a).get(i)?.ppid;if(c===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await s.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:c,fromShell:i!==n,attached:Hre(a,i,n)}}function Kre(e,t,n,r,i){let a=e=>Le(r,e,n);return{claudeInput:IQ(e),barPanes:async t=>Bre(await i9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await i9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await i9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void a9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Fq(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:KF,paneClaude:t=>Gre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+r9;for(;;){let o=await s9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${r9/1e3} s`);await a(100)}},launcherNode:e=>Lre(e,e=>n9(e,s.constants.X_OK),Ire),onPath:(e,t)=>{let n=t9(e,t,e=>n9(e,s.constants.X_OK));return n===null?null:s.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?Rre(i.stdout):null;return a===null?(a9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(100)}return!0},typeShellLine:async(t,n)=>void await i9(e,t,PQ(t.pane,`cc-candybar-lane`,[]),n)}}const qre=/^[0-9a-f]{64}$/;function c9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Jre(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>c9(e,t).toString(`hex`),verify:(t,n)=>qre.test(n)?ue(Buffer.from(n,`hex`),c9(e,t)):!1}}function l9(e){return T.join(e,`link.key`)}function u9(e){let t,n=()=>t??=Yre(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Yre(e){let t;try{t=s.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Xre(e),t=s.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Jre(t)}function Xre(e){s.mkdirSync(T.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;s.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{s.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{s.unlinkSync(t)}}function Zre(e,t,n){return{daemonLog:t,launcher:e=>It(e,n),storage:t=>Fre(e,t,n),doctorStores:hZ(e.state),doctorEdge:DZ,claudeInput:IQ,probe:qs,laneEdge:(e,t,r,i)=>Kre(e,t,r,n,i),linkSigner:u9(l9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Xr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:s.statSync}}const Qre=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function d9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Qre[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const $re={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function eie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=d9(t),o=d9(n),s={};for(let e of r){let t=$re[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function tie(e){return{ok:!0,band:e.rows.map(e=>uj(e).map(eie))}}function nie(e){return $A(tie,e)}const rie={band:e=>JSON.stringify(nie(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:h7(e)})};function f9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function iie(e,t){t.allowHalfOpen=!1;let n=e.stats.accept();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(er(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3,request:n.id},null,p6)}),u=nr(r=>{let i=Zn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{if(!c){e.kind===`reply`&&e.settled(!1);return}e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.settled):d(e.sessionId,e.lane)}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(G3(t),null,p6)}).finally(()=>{c||(l(),a())})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,p6)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=f9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(tr(rie[i](e,t))),refused:e=>t.end(er(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const p9=`CC_CANDYBAR_PARENT_PID`;function aie(e){let t=e[p9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${p9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function oie(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let m9=null,h9=null,g9=null,_9=null;function v9(){if(_9===null)throw Error(`runDaemon has not started`);return _9}function y9(e,t){v9().log.log(e,t)}function sie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:an(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function cie(e){let n=N(e.host);_9={world:e,paths:n,log:new dee(n.log,e.clock)},t.on(`uncaughtException`,e=>{y9(`error`,`uncaughtException: ${e.stack||e.message}`),C9(1)}),t.on(`unhandledRejection`,e=>{y9(`error`,`unhandledRejection: ${String(e)}`),C9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{y9(`info`,`received ${e}, shutting down`),C9(0)});lie().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${x(e)}`),C9(1)}async function lie(){let{world:e,paths:n,log:r}=v9(),{host:i}=e,a=Ir(i.env);m9=await Ys(t.pid,qs(e.launcher).startTime);let o=await tc(rc(e,m9,n.registry));if(!o.decision.allow){y9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),C9(1);return}h9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),hn(n.socket);let c=Mre({...Zre(n,r,e.clock),bundle:sie(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:GF(),exit:C9});g9=c,oie({clock:e.clock,anchor:aie(i.env),probe:qs(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,de.createServer(e=>iie(c,e)),n.socket,!1)}function x9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){y9(`error`,`server error: ${a.message}`),C9(1);return}if(i){y9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}uie(e,n,r).catch(b9)}),n.listen(r,()=>die(e,r))}async function uie(e,n,r){let i=await Rs(zs(gn(r)),(t,n)=>Js(t,n,qs(e.launcher)));if(i.kind===`attach-and-exit`){y9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}y9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){y9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),C9(1);return}}x9(e,n,r,!0)}function die(e,n){let r=Hs(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}pie(n);try{s.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Fr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Fr(e.memoryLimitBytes)}MB`),ai(v9().paths.spawnBackoff),e.arm(),fie(n,r.identity)}function fie(e,n){Gs({bound:n,myPid:t.pid,readIdentity:()=>Hs(e),readLease:()=>zs(gn(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function pie(e){let n=Bs(gn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const mie=e=>(t,n,r)=>fee(e,{socket:t},`tmux-status`,n,r);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(mie(v9().world.launcher)),Vs(v9().paths.lease,t.pid),h9!==null&&nc(h9,t.pid,$s,e=>s.unlinkSync(e)),t.exit(e))}const hie={connectMs:200,budgetMs:500};async function gie(e,t,n){return _ie(t,await vie(e,t),n.includes(`--json`))}function _ie(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
494
494
  `:yie(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${fr(t)}\n`,code:1}}function vie(e,t){return ar(e,()=>({kind:`debug`,what:t}),hie,e=>`debug`in e?e.debug:void 0)}function yie(e){switch(e.what){case`vars`:return bie(e.vars);case`segments`:return xie(e.segments);case`config`:return Sie(e.config);default:return e}}function bie(e){if(e.length===0)return`no variables (DSL not active)
495
495
  `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${wie(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${Cie(a.value)}${e}${o}`)}return t.join(`
496
496
  `)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.218.3",
3
+ "version": "1.218.4",
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",
@@ -109,9 +109,9 @@
109
109
  "yaml": "^2.9.1"
110
110
  },
111
111
  "optionalDependencies": {
112
- "@promptctl/cc-candybar-darwin-arm64": "1.218.3",
113
- "@promptctl/cc-candybar-darwin-x64": "1.218.3",
114
- "@promptctl/cc-candybar-linux-x64": "1.218.3",
115
- "@promptctl/cc-candybar-linux-arm64": "1.218.3"
112
+ "@promptctl/cc-candybar-darwin-arm64": "1.218.4",
113
+ "@promptctl/cc-candybar-darwin-x64": "1.218.4",
114
+ "@promptctl/cc-candybar-linux-x64": "1.218.4",
115
+ "@promptctl/cc-candybar-linux-arm64": "1.218.4"
116
116
  }
117
117
  }