@promptctl/cc-candybar 1.208.12 → 1.209.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +3 -3
- 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,{basename as c,dirname as l,isAbsolute as u,join as d,resolve as f,sep as p}from"node:path";import m,{appendFileSync as h,closeSync as g,constants as _,existsSync as v,fstatSync as y,linkSync as b,mkdtempSync as x,openSync as S,readFileSync as C,readSync as w,rmSync as T,statSync as E,unlinkSync as ee,writeFileSync as D}from"node:fs";import{StringDecoder as te}from"node:string_decoder";import{inspect as O,parseArgs as k,types as ne}from"node:util";import{clearImmediate as A,setImmediate as re}from"node:timers";import ie from"node:net";import{spawn as ae,spawnSync as oe}from"node:child_process";import se,{createHash as ce,createHmac as le,randomBytes as ue,randomUUID as de,timingSafeEqual as fe}from"node:crypto";import pe from"node:v8";import{open as me,readFile as he,readdir as ge,stat as _e}from"node:fs/promises";import{get as ve}from"node:https";import{WriteStream as ye}from"node:tty";import{createInterface as be}from"node:readline";var xe=Object.create,Se=Object.defineProperty,Ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,De=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=we(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ee.call(e,s)&&s!==n&&Se(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ce(t,s))||r.enumerable});return e},ke=(e,t,n)=>(n=e==null?{}:xe(Te(e)),Oe(t||!e||!e.__esModule?Se(n,`default`,{value:e,enumerable:!0}):n,e));let Ae=!1;const je=()=>Ae;function Me(e){Ae=e}function Ne(e){return je()?`[DEBUG] ${e()}\n`:``}function Pe(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}function Fe(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Ie=(e,t)=>Pe(t),Le=`main`,Re=`CC_CANDYBAR_HOME`,ze=`CC_CANDYBAR_NAME`,Be=`CC_CANDYBAR_RUNTIME_DIR`,Ve=/^[a-z0-9][a-z0-9-]*$/;function He(e,t){if(!Ve.test(e))throw Error(`${t} must be lowercase letters, digits and dashes, starting with a letter or digit, got ${JSON.stringify(e)}`);if(e.length>32)throw Error(`${t} must be at most 32 characters, got ${e.length}: ${JSON.stringify(e)}`);return e}function Ue(e){let t=He(e,ze);if(t===`main`)throw Error(`${ze} may not be ${JSON.stringify(Le)}: that is the main renderer's name, which is what an unset ${Re} and ${ze} mean`);return t}function We(e){return e===`main`?Le:He(e,`a link's renderer name`)}function Ge(e){return e===`main`?`socket`:`${e}.sock`}function Ke(e,t){let n=e[t];return n&&n.length>0?n:void 0}function qe(){let e=process.getuid();return s.join(`/tmp`,`cc-candybar-${e}`)}function Je(e){let t=Ke(e.env,Be);if(t===void 0)return qe();if(!s.isAbsolute(t))throw Error(`${Be} must be an absolute path, got ${JSON.stringify(t)}`);return t}function Ye(e){let{env:t}=e,n=Ke(t,Re),r=Ke(t,ze),i=Ke(t,`CC_CANDYBAR_SOCKET`)??null,a=Je(e);if(n!==void 0&&r!==void 0){if(!s.isAbsolute(n))throw Error(`${Re} must be an absolute path, got ${JSON.stringify(n)}`);if(i!==null)throw Error(`CC_CANDYBAR_SOCKET is set beside ${Re} and ${ze}: a named renderer's socket is its name's, so unset it`);return{kind:`named`,name:Ue(r),runtime:a,root:n}}if(n!==void 0||r!==void 0){let[e,t]=n===void 0?[ze,Re]:[Re,ze];throw Error(`${e} is set without ${t}: a renderer's home is both, or neither for the main renderer`)}return{kind:`main`,name:Le,runtime:a,roots:{state:Ke(t,`XDG_STATE_HOME`)??s.join(e.home,`.local`,`state`),cache:Ke(t,`XDG_CACHE_HOME`)??s.join(e.home,`.cache`),config:Ke(t,`XDG_CONFIG_HOME`)??s.join(e.home,`.config`)},legacySocket:i}}function Xe(e,t){return e+t}function Ze(e,t){return Math.round(t-e)}function Qe(e,t){return Ze(t,e.monotonic())}const $e={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=re(e);return()=>A(t)}};function et(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 tt(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 nt(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function rt(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const it=e=>e.getTime()/1e3,at=e=>Math.round(e*1e3),ot=e=>new Date(at(e)),st=e=>it(new Date(e.now()));function ct(e,t){return ne.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!v(t)?`working directory does not exist: ${t}`:e.message:String(e)}const lt={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function ut(e,t,n){let r=lt[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 dt(e,t){return{...e.inherited,...t.envOverlay}}function ft(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 pt=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function mt(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 pt(n);let i=Math.max(n.lastIndexOf(`
|
|
3
3
|
`),n.lastIndexOf(`\r`))+1;return`${pt(n.slice(0,r).trim())} … ${pt(n.slice(i).trim())}`}function j(e,t=``){let n=mt(e,e.stderr);return`${ft(e)}${t}${n===``?``:`: ${n}`}`}const ht=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function gt(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 _t(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function vt(e,t,n){let r=yt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function yt(e,t,n){if(e.scope.signal.aborted)return ht(e.scope.signal);if(n?.aborted)return ht(n);let r=ut(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:gt(t,r.minIntervalMs,r.sinceLastMs)}const bt=`\$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 xt(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function St(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),xt(e,n))}const Ct=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,wt=e=>e===`cut`?`output cut at the ${Nt}-byte bound, so the program holding it now fails its writes`:`output failed to read`,Tt=`a launched program's pipe outlived its launch: `;function Et(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:`${Tt}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${wt(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${Tt}${n} ${wt(t)}`})}function Dt(e,t){let n=e.pipeEvent;n===null||!rt(n,t)||(e.pipeEvent={...n,answered:!0})}function Ot(e,t,n){let r=e.pipeEvent,i=r===null?`over`:nt(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:Ct(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function kt(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[bt],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,Qe(n,r)),xt(e,`did not start: ${ct(i,void 0)}`),null}t?.onEnd(`lifeline`,Qe(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>xt(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&xt(e,null)}),i.once(`error`,t=>St(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>St(e,i,`exited ${n??t}`)),a.on(`error`,t=>St(e,i,`pipe failed: ${t.message}`)),_t(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 At(e,t){e.liveGroups.add(t),e.lifeline??=kt(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function jt(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Mt(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Nt=16*1024*1024,Pt=`output exceeded ${Nt} bytes`,Ft=e=>`timed out after ${e/1e3} s`;function It(e,t,n,r){let{stats:i}=e.scope,a=new te(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?Et(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(),Et(e,`cut`,t);return}let d=Math.max(0,Nt-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||Lt(e,t,n,()=>u)}}}function Lt(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 Rt=()=>`closed`;function zt(e,t){e.on(`error`,()=>{}),e.end(t)}async function Bt(e,t){let{stats:n,clock:r}=e.scope,i=vt(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:dt(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,Qe(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(e,t.cwd)});return}let c=s.pid;c!==void 0&&At(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ee(`output-limit`),failed:e=>{d??=e.message,ee(`pipe-error`)}},p=It(e,t.category,s.stdout,f),m=It(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>ee(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&jt(e,c),n?.onEnd(t.category,Qe(r,a)),s.off(`close`,te),s.off(`error`,D),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&Lt(e,t.category,u,Rt),i())},w=e=>C(()=>i(e)),T=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),w({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},E=()=>te(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(E);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ee=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(E);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{T(t,`SIGKILL`),l.then(()=>r.defer(E))}),T(t,`SIGTERM`))},D=e=>{w({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:ct(e,t.cwd)})};s.on(`error`,D);let te=(e,n)=>{if(b!==null){w({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:Ft(t.timeoutMs??0)}:b===`output-limit`?{error:Pt}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){w({ok:!0,...h(),exitCode:e});return}w({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,te),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ee(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&zt(u,t.stdinInput)})}function Vt(e,t){let{stats:n,clock:r}=e.scope,i=vt(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:dt(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,Qe(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`?Ft(t.timeoutMs??0):ct(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,Qe(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(e,t.cwd)}}}function Ht(e,t){let{stats:n,clock:r}=e.scope,i=vt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=M(e,t);return n?.onEnd(t.category,Qe(r,a)),o}function M(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:dt(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(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 Ut=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Wt(e,t,n){let{stats:r,clock:i}=e.scope,a=vt(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:dt(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,Qe(i,o)),{ok:!1,reason:`spawn-error`,error:ct(e,t.cwd)}}r?.onEnd(t.category,Qe(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 Gt(e){let t;try{t=C(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 Kt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{D(a,`${Ut(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{b(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{T(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 qt(e,t,n){return N(e,t,n).launcher}function Jt(e,t,n){let{launcher:r,state:i}=N(e,t,n);return{...r,launchSync:e=>Vt(i,e)}}function N(e,t,n){let r={clock:t,launch:e=>_t(i,Bt(i,e)),launchDetachedSync:e=>Ht(i,e),launchJobSync:(e,t)=>Wt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Kt(n,t,e,r,i),launcherWarnings:(e,t)=>Ot(i,e,t),answeredPipeEvent:e=>Dt(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&&St(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:Ct(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>it(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()),Mt(i)},{once:!0}),{launcher:r,state:i}}const Yt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 123]\d \d\d:\d\d:\d\d \d{4}$/,Xt=e=>typeof e==`string`&&Yt.test(e)?e:void 0,Zt=2e3;async function Qt(e,t){return tn(await t($t(e)))}const $t=(e,t=Zt)=>({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:t,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});function en(e,t){if(t.kind===`unavailable`)return{pid:e,startTime:null,why:t.detail};let n=Xt(t.token);return n===void 0?{pid:e,startTime:null,why:`ps printed ${JSON.stringify(t.token)}, not a start in the form \`ps -o lstart=\` prints`}:{pid:e,startTime:n}}function tn(e){if(e.ok){let t=e.stdout.trim();return t.length>0?{kind:`start`,token:t}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:`ps ${ft(e)}`}}function nn(e){return{alive:e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}},startTime:t=>Qt(t,e.launch)}}async function rn(e,t,n){if(t===null)return n.alive(e);let r=await n.startTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.alive(e)}}async function an(e,t){let n=await t(e);return n.kind===`start`?n.token:null}const on=new Set([`ECONNREFUSED`,`ENOENT`,`ENOTSOCK`]),sn=e=>({cause:on.has(e.code??``)?`unreachable`:`io_error`,message:e.message}),cn={dial(e){let t=ie.createConnection({path:e}),n=!1;return{settled:new Promise(e=>{let r=r=>{t.off(`connect`,i),n=!0,e({ok:!1,failure:sn(r)})},i=()=>{t.off(`error`,r),n=!0,e({ok:!0,conn:t})};t.once(`error`,r),t.once(`connect`,i)}),abandon:()=>{n||(t.removeAllListeners(),t.destroy())}}}};function ln(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const un={spawn:(e,t,n)=>ae(e,t,n),spawnSync:(e,t,n)=>oe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!ln(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}}},dn=(e,t)=>qt(e,t,un),fn=(e,t)=>Jt(e,t,un);function pn(){let e=$e,t=fn({inherited:process.env},e),n={env:process.env,home:o.homedir(),tmp:o.tmpdir()};return{host:n,home:mn(n),launcher:t,clock:e,dialer:cn,parent:e=>en(process.ppid,tn(t.launchSync($t(process.ppid,e))))}}function mn(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const hn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function gn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function _n(e){return hn.test(e)?e:gn(e)}function vn(e){return`${e.dir===void 0?``:`cd ${_n(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${_n(t)} `).join(``)}${[e.program,...e.args].map(_n).join(` `)}`}const yn=`cc-extra`;function bn(e){return s.join(s.dirname(e),yn,`src`,`bun-attach.js`)}function xn(e){return s.join(s.dirname(e),`bun-graph.js`)}const Sn=`attach-preload.cjs`;function Cn(e){return s.join(s.dirname(e),Sn)}function wn(e,t){return vn({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const P=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Tn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function En(e,t,n=P){return m.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=m.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?En(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Tn(r,i)]]})}function Dn(e){let t=se.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function On(e){return Dn(En(e,e))}const kn=[`Cargo.toml`,`Cargo.lock`,`src`];function An(e){return Dn(En(e,e,e=>kn.includes(e)))}const jn=e=>e.slice(0,7),Mn=`1.208.12`;function Nn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Pn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Mn,digest:e}}function Fn(){return`56df467e3bae1c17200f9f8f42e6368d0840a93c5fdb5e292f4435ba218305c3`}function In(e){let t=JSON.parse(m.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Ln(e,t){try{let n=Nn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=On(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:In(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Rn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function zn(e,t){let n=Rn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=zn(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function Bn(e,t){let{dir:n,rest:r}=zn(e,t);return s.join(n,...r)}const Vn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,Hn=e=>({kind:Vn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),Un={statSync:e=>Hn(m.statSync(e,{bigint:!0})),lstatSync:e=>Hn(m.lstatSync(e,{bigint:!0})),readlinkSync:e=>m.readlinkSync(e),realpathSync:e=>m.realpathSync.native(e),mkdirSync:e=>void m.mkdirSync(e,{recursive:!0}),opendirSync:e=>m.opendirSync(e).closeSync(),stat:async e=>Hn(await m.promises.stat(e,{bigint:!0})),readFile:e=>m.promises.readFile(e,`utf8`),writeFile:(e,t)=>m.promises.writeFile(e,t),readdir:async e=>(await m.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:Vn(e)})),unlink:e=>m.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=m.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function Wn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function Gn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Kn(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function qn(e){return Yn(e.kind===`main`?Kn(e):e.root)}const Jn=e=>Bn(Un,e);function Yn(e){return{dir:e,onDisk:Jn}}function Xn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function Zn(e){return s.join(qe(),Ge(e))}function Qn(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function $n(e){m.mkdirSync(e,{recursive:!0,mode:448});let t=m.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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 er(e){$n(s.dirname(e));for(let t of[e,tr(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function tr(e){return`${e}.lease`}function nr(e){return tr(Xn(e))}function rr(e){return s.join(Wn(e),`session-state.json`)}function ir(e){return s.join(Wn(e),`settings-history.json`)}function ar(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function or(e){return s.join(Wn(e),`spawn.lock`)}function sr(e){return s.join(Wn(e),`spawn.cooldown`)}function cr(e){return s.join(Wn(e),`spawn.backoff`)}function lr(e){return s.join(Wn(e),`watch-probe`)}function ur(e){return s.join(Wn(e),`daemon.log`)}function dr(e){return s.join(Wn(e),`link-ids`)}function fr(e){return{socket:Xn(e),lease:nr(e),state:Wn(e),log:ur(e),sessionState:rr(e),settingsHistory:ir(e),storedRoot:qn(e),watchProbe:lr(e),spawnBackoff:cr(e),linkIds:dr(e)}}function pr(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function mr(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Kn(t),dataHome:pr(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function hr(e,t){return gr(e,t).at(-1)}function gr(e,t){let{hops:n,stopped:r}=_r(e,t);if(r!==null)throw r;return n}function _r(e,t){let n=[t];try{for(let t=0;t<yr;t++){let t=vr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${yr} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function vr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const yr=40;function br(e,t,n){let r=hr(Un,e);m.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??m.statSync(r,{throwIfNoEntry:!1})?.mode;try{let e=m.openSync(i,`w`,a);try{m.writeFileSync(e,t),m.fsyncSync(e)}finally{m.closeSync(e)}m.renameSync(i,r)}catch(e){throw m.rmSync(i,{force:!0}),e}}function xr(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const Sr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Cr(e){return Object.fromEntries(Sr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const wr=[`native`,`node`,`frames`];function Tr(e,t){return{kind:e,bundle:t,source:null}}const Er=[`ansi`,`frame`],Dr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,parent:!0,client:!0});function Or(e){let t=Lr(e.termCols),n=Lr(e.termRows),r=Rr(e.ssh),i=Fr(e.tmux),a=Pr(e.configEnv),o=Pr(e.claudeConfigDir),s=Nr(e.terminalEnv),c=zr(e.parent),l=Xr(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&&{parent:c},...l!==void 0&&{client:l}}}function kr(e,t){return Dr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ar(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 jr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Mr(e){let t=Object.keys(jr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[jr[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
4
|
+
`),withdraw:()=>l.end()})}function Gt(e){let t;try{t=C(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 Kt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{D(a,`${Ut(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{b(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{T(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 qt(e,t,n){return N(e,t,n).launcher}function Jt(e,t,n){let{launcher:r,state:i}=N(e,t,n);return{...r,launchSync:e=>Vt(i,e)}}function N(e,t,n){let r={clock:t,launch:e=>_t(i,Bt(i,e)),launchDetachedSync:e=>Ht(i,e),launchJobSync:(e,t)=>Wt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Kt(n,t,e,r,i),launcherWarnings:(e,t)=>Ot(i,e,t),answeredPipeEvent:e=>Dt(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&&St(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:Ct(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>it(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()),Mt(i)},{once:!0}),{launcher:r,state:i}}const Yt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 123]\d \d\d:\d\d:\d\d \d{4}$/,Xt=e=>typeof e==`string`&&Yt.test(e)?e:void 0,Zt=2e3;async function Qt(e,t){return tn(await t($t(e)))}const $t=(e,t=Zt)=>({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:t,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});function en(e,t){if(t.kind===`unavailable`)return{pid:e,startTime:null,why:t.detail};let n=Xt(t.token);return n===void 0?{pid:e,startTime:null,why:`ps printed ${JSON.stringify(t.token)}, not a start in the form \`ps -o lstart=\` prints`}:{pid:e,startTime:n}}function tn(e){if(e.ok){let t=e.stdout.trim();return t.length>0?{kind:`start`,token:t}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:`ps ${ft(e)}`}}function nn(e){return{alive:e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}},startTime:t=>Qt(t,e.launch)}}async function rn(e,t,n){if(t===null)return n.alive(e);let r=await n.startTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.alive(e)}}async function an(e,t){let n=await t(e);return n.kind===`start`?n.token:null}const on=new Set([`ECONNREFUSED`,`ENOENT`,`ENOTSOCK`]),sn=e=>({cause:on.has(e.code??``)?`unreachable`:`io_error`,message:e.message}),cn={dial(e){let t=ie.createConnection({path:e}),n=!1;return{settled:new Promise(e=>{let r=r=>{t.off(`connect`,i),n=!0,e({ok:!1,failure:sn(r)})},i=()=>{t.off(`error`,r),n=!0,e({ok:!0,conn:t})};t.once(`error`,r),t.once(`connect`,i)}),abandon:()=>{n||(t.removeAllListeners(),t.destroy())}}}};function ln(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const un={spawn:(e,t,n)=>ae(e,t,n),spawnSync:(e,t,n)=>oe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!ln(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}}},dn=(e,t)=>qt(e,t,un),fn=(e,t)=>Jt(e,t,un);function pn(){let e=$e,t=fn({inherited:process.env},e),n={env:process.env,home:o.homedir(),tmp:o.tmpdir()};return{host:n,home:mn(n),launcher:t,clock:e,dialer:cn,parent:e=>en(process.ppid,tn(t.launchSync($t(process.ppid,e))))}}function mn(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const hn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function gn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function _n(e){return hn.test(e)?e:gn(e)}function vn(e){return`${e.dir===void 0?``:`cd ${_n(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${_n(t)} `).join(``)}${[e.program,...e.args].map(_n).join(` `)}`}const yn=`cc-extra`;function bn(e){return s.join(s.dirname(e),yn,`src`,`bun-attach.js`)}function xn(e){return s.join(s.dirname(e),`bun-graph.js`)}const Sn=`attach-preload.cjs`;function Cn(e){return s.join(s.dirname(e),Sn)}function wn(e,t){return vn({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const P=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Tn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function En(e,t,n=P){return m.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=m.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?En(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Tn(r,i)]]})}function Dn(e){let t=se.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function On(e){return Dn(En(e,e))}const kn=[`Cargo.toml`,`Cargo.lock`,`src`];function An(e){return Dn(En(e,e,e=>kn.includes(e)))}const jn=e=>e.slice(0,7),Mn=`1.209.0`;function Nn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Pn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Mn,digest:e}}function Fn(){return`a4efcd54a18e68150e43fb9ede5ae300347d61d02e9de64ec1a4c39ea78cc4e5`}function In(e){let t=JSON.parse(m.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Ln(e,t){try{let n=Nn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=On(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:In(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Rn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function zn(e,t){let n=Rn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=zn(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function Bn(e,t){let{dir:n,rest:r}=zn(e,t);return s.join(n,...r)}const Vn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,Hn=e=>({kind:Vn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),Un={statSync:e=>Hn(m.statSync(e,{bigint:!0})),lstatSync:e=>Hn(m.lstatSync(e,{bigint:!0})),readlinkSync:e=>m.readlinkSync(e),realpathSync:e=>m.realpathSync.native(e),mkdirSync:e=>void m.mkdirSync(e,{recursive:!0}),opendirSync:e=>m.opendirSync(e).closeSync(),stat:async e=>Hn(await m.promises.stat(e,{bigint:!0})),readFile:e=>m.promises.readFile(e,`utf8`),writeFile:(e,t)=>m.promises.writeFile(e,t),readdir:async e=>(await m.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:Vn(e)})),unlink:e=>m.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=m.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function Wn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function Gn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Kn(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function qn(e){return Yn(e.kind===`main`?Kn(e):e.root)}const Jn=e=>Bn(Un,e);function Yn(e){return{dir:e,onDisk:Jn}}function Xn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function Zn(e){return s.join(qe(),Ge(e))}function Qn(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function $n(e){m.mkdirSync(e,{recursive:!0,mode:448});let t=m.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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 er(e){$n(s.dirname(e));for(let t of[e,tr(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function tr(e){return`${e}.lease`}function nr(e){return tr(Xn(e))}function rr(e){return s.join(Wn(e),`session-state.json`)}function ir(e){return s.join(Wn(e),`settings-history.json`)}function ar(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function or(e){return s.join(Wn(e),`spawn.lock`)}function sr(e){return s.join(Wn(e),`spawn.cooldown`)}function cr(e){return s.join(Wn(e),`spawn.backoff`)}function lr(e){return s.join(Wn(e),`watch-probe`)}function ur(e){return s.join(Wn(e),`daemon.log`)}function dr(e){return s.join(Wn(e),`link-ids`)}function fr(e){return{socket:Xn(e),lease:nr(e),state:Wn(e),log:ur(e),sessionState:rr(e),settingsHistory:ir(e),storedRoot:qn(e),watchProbe:lr(e),spawnBackoff:cr(e),linkIds:dr(e)}}function pr(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function mr(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Kn(t),dataHome:pr(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function hr(e,t){return gr(e,t).at(-1)}function gr(e,t){let{hops:n,stopped:r}=_r(e,t);if(r!==null)throw r;return n}function _r(e,t){let n=[t];try{for(let t=0;t<yr;t++){let t=vr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${yr} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function vr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const yr=40;function br(e,t,n){let r=hr(Un,e);m.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??m.statSync(r,{throwIfNoEntry:!1})?.mode;try{let e=m.openSync(i,`w`,a);try{m.writeFileSync(e,t),m.fsyncSync(e)}finally{m.closeSync(e)}m.renameSync(i,r)}catch(e){throw m.rmSync(i,{force:!0}),e}}function xr(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const Sr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Cr(e){return Object.fromEntries(Sr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const wr=[`native`,`node`,`frames`];function Tr(e,t){return{kind:e,bundle:t,source:null}}const Er=[`ansi`,`frame`],Dr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,parent:!0,client:!0});function Or(e){let t=Lr(e.termCols),n=Lr(e.termRows),r=Rr(e.ssh),i=Fr(e.tmux),a=Pr(e.configEnv),o=Pr(e.claudeConfigDir),s=Nr(e.terminalEnv),c=zr(e.parent),l=Xr(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&&{parent:c},...l!==void 0&&{client:l}}}function kr(e,t){return Dr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ar(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 jr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Mr(e){let t=Object.keys(jr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[jr[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
5
5
|
`)}function Nr(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Sr.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 Pr(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Fr(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 Ir=1e4;function Lr(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Ir?Ir:t}function Rr(e){return typeof e==`boolean`?e:void 0}function zr(e){if(typeof e!=`object`||!e)return;let{pid:t,startTime:n,why:r}=e;if(!Number.isSafeInteger(t)||t<=0)return;if(n===null)return typeof r==`string`&&r!==``?{pid:t,startTime:null,why:r}:void 0;let i=Xt(n);return i===void 0?void 0:{pid:t,startTime:i}}const Br=new Set([...[],1]);function Vr(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}const Hr=Math.floor((2**31-1)/1e3)-60;function Ur(e){return typeof e==`number`&&e>0&&e<=Hr?{ok:!0,seconds:e}:{ok:!1,problem:`is not a span of seconds above 0 and at most ${Hr}`}}var Wr=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},Gr=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Kr(e){return qr(JSON.stringify(e))}function qr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Jr(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 Wr(`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 Wr(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Yr(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 Gr(`deadline`))})}),l=Jr(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(Kr(t))})}function Xr(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Pr(n);return wr.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function Zr(e,t,n,r){let i=await xr(e.dialer,Xn(e.home),n.connectMs,e.clock);return i.ok?$r(i.conn,e.clock,t,n,r):Qr(i.failure)}function Qr(e){return e.cause===`timeout`?{kind:`busy`,phase:`connect`,message:new Gr(`connect`).message}:{kind:`transient`,cause:e.cause,message:e.message}}async function $r(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await Yr(e,{v:3,...o},a,t);return ni(o.kind,s,i)}catch(e){return ri(e)}finally{e.destroy()}}function ei(e,t){return typeof e==`string`?e:t}function ti(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ni(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=ei(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:ti(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 ri(e){if(e instanceof Wr||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 Gr?{kind:`busy`,phase:e.phase,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function ii(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 ai(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 oi(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 si={connectMs:50,budgetMs:150},ci={connectMs:50,budgetMs:350};function li(e){let t=e.output;return typeof t==`string`?t:void 0}function ui(e){return ni(`render`,e,li)}function di(e,t,n,r,i,a=si){return Zr(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,li)}function fi(e,t,n){return Zr(e,()=>({kind:`pane-session`,socket:t,pane:n}),ci,e=>`paneSession`in e?e.paneSession:void 0)}function pi(e,t){return Zr(e,()=>({kind:`click`,url:t}),ci,li)}const mi=5e3;async function hi(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 gi=`/usr/bin/footprint`;function _i(e,t,n){return t===`darwin`?[xi(e,gi,[`-p`,String(n)]),xi(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[Si(`/proc/self/smaps_rollup`),Si(`/proc/self/status`)]:[]}function vi(e,t,n){return t===`darwin`?yi(n,t=>e.launch({bin:gi,args:t,timeoutMs:mi,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function yi(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 ${j(r)}`};let i=bi(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 bi(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function xi(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:mi,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:j(r)}}}}function Si(e){return{name:e,read:async()=>{try{let t=m.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 Ci=`CC_CANDYBAR_RSS_LIMIT_MB`;function wi(e){let t=e[Ci];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Ci} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Ti(e){return wi(e)*2}const Ei=1024*1024,Di=e=>Math.round(e/Ei);function Oi(e){return wi(e)*Ei}const ki={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Ai(e,t){return e>t}function ji(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 Mi=.75;function Ni(e,t){return e>t*Mi}function Pi(e,t,n){let{prefix:r,suffix:i}=ki[t];return s.join(e,`${r}${n}${i}`)}function Fi(e){for(let t of Object.keys(ki)){let{prefix:n,suffix:r}=ki[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Ii(e){let t=e.limitBytes??1024*Ei,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=ji(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${zi(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Li(c)} > limit ${Di(t)} MB (rss ${Di(a)} MB, v8 heap ${Di(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Bi(e.log,`memory report`,async()=>{let t=Pi(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 Bi(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Pi(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Bi(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Vi(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Bi(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Ni(i.charge.bytes,t)?`${Li(i.charge)} approaching limit ${Di(t)} MB (v8 heap ${Di(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Vi(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 Li(e){return e.kind===`charged`?`${e.measure} ${Di(e.bytes)} MB`:`rss ${Di(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Di(e.gap)} MB gap`} (standing in: ${e.unread})`}function Ri(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function zi({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Di(e.gap)}MB`:``;return`measure=${Ri(e)} charge=${Di(e.bytes)}MB rss=${Di(t)}MB heap=${Di(n)}MB limit=${Di(r)}MB${i}`}async function Bi(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Vi(e){let t=new Map;for(let n of e){let e=s.basename(n),r=Fi(e);if(r===null)continue;let{prefix:i,suffix:a}=ki[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(ki);return[...t].sort(([e],[t])=>Ai(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function Hi(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:vi(n.launcher,process.platform,process.pid),captureMemoryReport:()=>hi(_i(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>m.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>pe.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=m.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Fi(e)!==null).map(e=>s.join(i,e))},removeFile:e=>m.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Ui(e,n={}){let{home:r,clock:i}=e;if(ree(r)!==null)return;let a=n.spawn??(()=>aee(e)),o=$i(r,i);if(o.kind===`contended`){let e=eee(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Wi(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Wi(r,i,a);return}try{Wi(r,i,a)}finally{ta()}}function Wi(e,t,n){Yi(e,t)&&tee(n)}function eee(e,t){try{let n=m.statSync(or(e));return t.now()-n.mtimeMs}catch{return null}}function tee(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 Gi(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function nee(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ki(e){try{let t=m.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function qi(e,n){try{m.mkdirSync(s.dirname(e),{recursive:!0}),m.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Ji(e){try{m.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Yi(e,n){let r=sr(e),i=cr(e),a=Ki(i),o=Gi(Xi(r,n),nee(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`),Zi(r,n),qi(i,Math.min(a+1,5)),!0)}function Xi(e,t){try{return t.now()-m.statSync(e).mtimeMs}catch{return null}}function Zi(e,n){try{m.mkdirSync(s.dirname(e),{recursive:!0}),m.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 Qi=null;function $i(e,n){let r=or(e);for(let e=0;e<2;e++){try{let e=m.openSync(r,`wx`,384);try{m.writeSync(e,JSON.stringify({pid:t.pid,ts:n.now()}))}catch{}return Qi={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(!ea(r,n))return{kind:`contended`};try{m.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function ea(e,t){try{let n=m.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function ta(){if(!Qi)return;let{fd:e,path:t}=Qi;Qi=null;try{m.closeSync(e)}catch{}try{m.unlinkSync(t)}catch{}}function ree(e){try{return m.mkdirSync(Wn(e),{recursive:!0}),null}catch(t){return`mkdir ${Wn(e)}: ${t.message}`}}function iee(e,t){return[`--max-old-space-size=${Ti(t)}`,e,`daemon`]}function aee({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:iee(i,e.env),category:`daemon-spawn`}).ok:!1}const na=`cc-candybar`,ra=`CCCandybarURLHandler`,ia=e=>e.startsWith(`${na}://`),aa=`closed`,oa=`open`,sa=`🍫`;function ca(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 la(e,t,n,r){let i=ca(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function ua(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function da(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function fa(e,...t){return`{{ and ${[e,...t].map(pa).join(` `)} }}`}function pa(e){return`(eq .${e.variable} "${ua(e.member)}")`}function ma(e,t,n){return`{{ ${ha(e,ga(t),ga(n))} }}`}function ha(e,t,n){return`action "${e}" ${t} ${n}`}function ga(e){return`"${ua(e)}"`}function _a(e,t){return{kind:`state`,key:e,default:t}}function va(e,t){return{set:e,cycle:[aa,t]}}function ya(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}var ba=De(((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]/})),xa=De(((e,t)=>{let n=ba();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)}}})),Sa=De(((e,t)=>{let n=xa(),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(),ee[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===`
|
|
@@ -490,7 +490,7 @@ function run(argv) {
|
|
|
490
490
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
491
491
|
`)){let t=f2(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function D4(e){let t=Po(e,wF+1);return t.kind===`ok`?F(E4(t.value.buf,t.value.fromStart)):t}function O4(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 k4={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function A4(e,t){if(sc(t)===void 0)return{kind:`ok`,value:null};let n=gW(await e.launch({bin:`git`,args:[...hW],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=xW(n.value);if(r===null)return{kind:`ok`,value:null};let i=mW(r);if(i===null)return{kind:`ok`,value:null};let a=lW[i],o=k4[i],s=o.loginHost(pW(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return j4(a,s,o.nonZero,c)}function j4(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):uW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:oW(r.stderr)}):{kind:`failed`,reason:aW(e,r)}}function M4(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
492
492
|
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const N4=e=>u4(()=>fee(e));function P4(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:Ro(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:N4(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 F4(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function I4(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Vne(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:Bne(t),tmuxClient:t}}}}async function L4(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(Fne(s))return{kind:`bundling`,name:s,version:c};if(!Ine(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 R4(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 z4(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function B4(e,t,n,r){return{pullRequests:await z4(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await z4(t.rateLimits,()=>r)}}function V4(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 H4(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=tJ(d.config,r,()=>!1),p=await F4(e,t.tmux),m=I4(p,t.terminalEnv),h=[...new Set([...Ene(f),...oF(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:L4(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),B4(e,Q0(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:M4(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:O4(e,o),claudeSettings:P4({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Ro(Lo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function U4(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;br(e,Za(Vo(e),t.path,JSON.stringify(t.value),La));let r=e=>({...e,sources:N4(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||Ai(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 W4={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},G4=16384;var K4=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<G4){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%G4}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:W4,file:W4,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},journalTurns:{gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0,queued: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},linkIds:{minted:0,reused:0,evicted:0,reservations:0,faults: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:Mn,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,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,linkIds:e.linkIds,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 q4={connectMs:200,budgetMs:500};async function J4(e,t){return Y4(await X4(e),t.includes(`--json`))}function Y4(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${ii(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
493
|
-
`:null,r=Z4(e.value);return r===null?{stdout:n??c3(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function X4(e){return Zr(e,()=>({kind:`stats`}),q4,e=>`stats`in e?e.stats:void 0)}function Z4(e,t=t3){let n=K4.referenceSnapshot(),r=n3(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=$4(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function Q4(e){return e.version===`1.
|
|
493
|
+
`:null,r=Z4(e.value);return r===null?{stdout:n??c3(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function X4(e){return Zr(e,()=>({kind:`stats`}),q4,e=>`stats`in e?e.stats:void 0)}function Z4(e,t=t3){let n=K4.referenceSnapshot(),r=n3(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=$4(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function Q4(e){return e.version===`1.209.0`&&e3(e)===Fn()?null:$4(e)}function $4(e){return{theirs:i3(e.version,e3(e)),mine:i3(Mn,Fn())}}const e3=e=>e.sourceDigest??null,t3=Object.keys(K4.referenceSnapshot());function n3(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!r3(e))return[];if(!r3(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(...n3(e[i],t[i],a)):r.push(a)}return r}function r3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function i3(e,t){return`${e} [${t===null?`no digest`:jn(t)}]`}function a3(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function o3(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function s3(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 c3(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${i3(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${s3(e.uptimeSec)}`),t.push(` rss ${a3(e.rssBytes)}`),t.push(` heapUsed ${a3(e.heapUsedBytes)}`),t.push(` heapTotal ${a3(e.heapTotalBytes)}`),t.push(` external ${a3(e.externalBytes)}`),t.push(` arrayBuffers ${a3(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 ${o3(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 ${o3(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 ${Ic(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 ${a3(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${a3(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(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${a3(e.renderCache.accountedBytes)} / ${a3(e.renderCache.budgetBytes)}`),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(``),t.push(`journalTurns`),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(`
|
|
494
494
|
`)+`
|
|
495
495
|
`}const l3=e=>({kind:`ok`,value:e}),u3=e=>({kind:`failed`,reason:e});var d3=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const f3=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function p3(e){return f3.test(e)?e:null}function m3(e,t){let n=e.opener(t);if(n.kind===`failed`)return n;if(n.value===null)return l3(null);let r=n.value;return l3({app:r,forwarder:e.exists(ds(r))})}async function h3(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 g3(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}; the URL handler delivers a link naming ${e.name} 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=lC(e.name,n),i=e.open(r);return(i===null?await h3(e,n):null)??{kind:`lost`,unopened:i,opener:m3(e,r),otherBuild:t.value.otherBuild}}function _3(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?l3(i.stdout):u3(j(i))}const v3=e=>`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString(${JSON.stringify(e)}));u.isNil() ? "" : u.path.js`;async function y3(e){let t=await X4(e);if(t.kind!==`ok`)return u3(ii(t).split(`
|
|
496
496
|
`).join(` — `));let n=Z4(t.value,[`handlerProbes`]);if(n!==null)return u3(n);let r=[];for(let e of t.value.handlerProbes){let t=b3(e);if(t===null)return u3(`the daemon lists its probe arrivals without who delivered them, so it is from a build before the forwarder app — restart it to run the installed one`);r.push(t)}return l3({arrivals:r,otherBuild:Q4(t.value)})}function b3(e){if(typeof e!=`object`||!e)return null;let{nonce:t,delivery:n}=e;if(typeof t!=`string`||typeof n!=`object`||!n)return null;let{kind:r,urlV:i}=n;return r===`cli`?{nonce:t,delivery:{kind:`cli`}}:r===`forwarder`&&typeof i==`number`?{nonce:t,delivery:{kind:`forwarder`,urlV:i}}:null}function x3(e,t){let{home:n,clock:r}=t;return{platform:process.platform,name:n.name,sockets:{own:Xn(n),handler:Zn(n.name)},monotonic:()=>r.monotonic(),nonce:de,daemon:()=>y3(t),open:t=>{let n=_3(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>et(r,100),opener:t=>{let n=_3(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,v3(t)]);if(n.kind===`failed`)return n;let r=n.value.trim();return l3(r===``?null:r)},exists:m.existsSync}}const S3=5e3;function C3(e,t,n){if(e.reason===`rate-limited`){n(`warn`,j(e));return}throw e.reason===`aborted`?new $s(t):Error(`${t} failed (${j(e)})`)}async function w3(e,t,n,r,i,a){let o=x(s.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:s.join(o,`stderr`),status:s.join(o,`status`)},c=e.launchJobSync(t,a);if(!c.ok){C3({...c,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}c.release();let l=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(c.pid),s=Gt(a.status);if(s!==null){if(s.kind===`exit`&&s.code===0)return;C3(s.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:C(a.stderr,`utf8`),exitCode:s.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await et(e.clock,50)}}finally{T(o,{recursive:!0,force:!0,maxRetries:3})}}function T3(e,t){E3(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function E3(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const D3=(e,[t=``],n)=>{T3(t,n)},O3=new Set([`request`,`feed`]);function k3(e){if(!O3.has(e))throw new R(`unknown renderer ${JSON.stringify(e)}`);return e}const A3=(e,t,n)=>{let[r=``,i=``]=t,a=n.diagnosticCopy(e,k3(r),i);if(a===void 0)throw new R(`that message is no longer listed in session ${e}'s diagnostics — open ⚠ again and copy from there`);T3(a,n)},j3=(e,[t=``],n)=>{E3(n,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t],category:`click.open`},`open -a "Visual Studio Code"`)},M3=(e,t,n)=>{n.navigating.get(e,`toolbar-expanded`)?n.navigating.clear(e,`toolbar-expanded`):n.navigating.set(e,`toolbar-expanded`,`1`)},N3=(e,t,n)=>{let r=n.gates.state.gateFor(G3(n,e));if(t.length===0)throw new R(`set-state: <key>/<value> is required (have keys: ${r.listKeys().join(`, `)})`);if(t.length%2!=0)throw new R(`set-state: expected even-count <key>/<value> pairs, got ${t.length} segment(s) after session id (have keys: ${r.listKeys().join(`, `)})`);let i=[];for(let e=0;e<t.length;e+=2){let n=t[e],a=t[e+1];if(!n)throw new R(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let o=r.validate(n,a);if(!o.ok)throw new R(`set-state: pair ${e/2+1}: ${o.reason}`);i.push({key:n,value:o.value})}L3(n,e,`set-state`,i),n.navigating.setBatch(e,i);let a=i.map(e=>`${e.key}=${e.value}`).join(` `);n.log(`info`,`set-state: ${a} (session=${e})`)},P3=/^-?\d+$/;function F3(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const I3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!P3.test(i))throw new R(`step-state: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=G3(n,e),s=n.gates.state.gateFor(o),c=s.rangeParamsFor(r);if(!c)throw new R(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${s.listKeys().join(`, `)})`);let l=n.sessionState.get(e,r),u=l&&P3.test(l)?R3(c,parseInt(l,10)):z3(`step-state`,r,c,N$(o,t=>n.sessionState.get(e,t),r)),d=F3(u,a,c.min,c.max),f=s.validate(r,String(d));if(!f.ok)throw new R(`step-state: ${f.reason}`);L3(n,e,`step-state`,[{key:r,value:f.value}]),n.navigating.set(e,r,f.value),n.log(`info`,`step-state: ${r} ${u}→${f.value} (by ${a}, session=${e})`)};function L3(e,t,n,r){let i=r.filter(e=>e.key.startsWith(eP));if(i.length===0)return;let a=S$(G3(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new R(`${n}: refused — ${a.join(`; `)}`)}function R3(e,t){return Math.max(e.min,Math.min(e.max,t))}function z3(e,t,n,r){if(r===null)return n.min;if(!P3.test(r))throw new R(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return R3(n,parseInt(r,10))}function B3(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function V3(e,t){let n;try{n=JSON.parse(e)}catch{throw new R(`render origin is not JSON: ${e}`)}if(typeof n!=`object`||!n)throw new R(`render origin is not an object: ${e}`);let{projectDir:r,cwd:i,configFile:a,source:o}=n;if(typeof r!=`string`||typeof i!=`string`||a===void 0)throw new R(`render origin has the wrong shape: ${e}`);let s;try{s=a===null?null:t0(t,a)}catch(e){throw e instanceof e0?new R(`render origin: ${e.message}`):e}return{projectDir:r,cwd:i,target:B3(o,s)}}function H3(e,t){let n=U3(e,t);if(n===null)throw new R(`session ${t} has not rendered yet — no config to act on`);return n}function U3(e,t){let n=e.sessionState.get(t,n$);return n===null?null:V3(n,e.storedRoot)}function W3(e,t,n){let r=U3(e,t);if(r===null)return;let{path:i}=J3(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function G3(e,t){return e.configFor(H3(e,t))}function K3(e,t){let n=U3(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function q3(e,t){let n=U3(e,t);return n===null?F$:z$(e.configFor(n))}function J3(e,t){return fU(e.locations,KU(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function Y3(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const X3=(e,t,n)=>{let[r=``,i=``]=t,a=H3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`set-config: <key>/<value> is required (have keys: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`set-config: ${c.reason}`);let l=J3(n,a),u=b$(o,t=>n.sessionState.get(e,t),r);j1(Y3(n,e),l,[[u.key,c.value]]),n.reloadConfig(a),n.log(`info`,`set-config: ${u.key}=${c.value} → ${l.path} (session=${e})`)},Z3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!P3.test(i))throw new R(`step-config: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=H3(n,e),s=n.configFor(o),c=n.gates.config.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new R(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${c.listKeys().join(`, `)})`);let u=J3(n,o),d=b$(s,t=>n.sessionState.get(e,t),r),f=A1(u.path,d.key),p=typeof f==`number`?R3(l,f):z3(`step-config`,r,l,P$(d.globals,r)),m=F3(p,a,l.min,l.max),h=c.validate(r,String(m));if(!h.ok)throw new R(`step-config: ${h.reason}`);j1(Y3(n,e),u,[[d.key,h.value]]),n.reloadConfig(o),n.log(`info`,`step-config: ${d.key} ${p}→${h.value} (by ${a}) → ${u.path} (session=${e})`)},Q3=(e,t,n)=>{let r=H3(n,e),i=n.configFor(r),a=t=>n.sessionState.get(e,t),o=v$(i,a),s=x$(i,a);if(o.length+s.length===0){n.log(`info`,`save: nothing unsaved (session=${e})`);return}let c=n.gates.state.gateFor(i),l=o.map(e=>{let t=c.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save: ${t.reason}`);return[e.target,t.value]});e6(`save`,c,s);let u=J3(n,r);M1(Y3(n,e),u,l,s),n.reloadConfig(r);for(let t of[...o.map(e=>e.sessionKey),...s.map(e=>e.key)])n.sessionState.clear(e,t);n.log(`info`,`save: ${[...l.map(([e,t])=>`${e}=${t}`),...s.map($3)].join(` `)} → ${u.path} (session=${e})`)},$3=e=>`${e.preset}/${e.id}.settings.${e.setting}=${lb(e.value)}`;function e6(e,t,n){for(let r of n){let n=t.validate(r.key,lb(r.value));if(!n.ok)throw new R(`${e}: ${n.reason}`)}}const t6=(e,t,n)=>{let r=H3(n,e),i=n.configFor(r),a=T$(i,t=>n.sessionState.get(e,t)),o=n.gates.state.gateFor(i),s=a.picks.map(e=>{let t=o.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save-preset: ${t.reason}`);return[e.configKey,t.value]});e6(`save-preset`,o,a.placements);let c=J3(n,r),l=z1(Y3(n,e),c,a.from,a.globals,s,a.placements);n.reloadConfig(r);for(let t of[...fx.map(e=>e.sessionKey),...a.placements.map(e=>e.key)])n.sessionState.clear(e,t);n.sessionState.set(e,ux.preset.sessionKey,l),n.log(`info`,`save-preset: ${[`${l} from=${a.from}`,...s.map(([e,t])=>`${e}=${t}`),...a.placements.map($3)].join(` `)} → ${c.path} (session=${e})`)},n6=(e,t,n)=>{let r=H3(n,e),i=D$(n.configFor(r),t=>n.sessionState.get(e,t));if(i.kind===`rule`)throw new R(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let a=J3(n,r);B1(Y3(n,e),a,i.theme,i.look),n.reloadConfig(r);let o=new Set(v$(n.configFor(r),t=>n.sessionState.get(e,t)).map(e=>e.sessionKey)),s=rx.map(e=>ux[e].sessionKey).filter(e=>!o.has(e));for(let t of s)n.sessionState.clear(e,t);n.log(`info`,`save-theme-default: ${i.theme} ${rx.map(e=>`${e}=${i.look[e]}`).join(` `)} → ${a.path} (session=${e})`)},r6=(e,t,n)=>{let[r=``]=t;if(!r)throw new R(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let i=H3(n,e),a=J3(n,i);V1(Y3(n,e),a,r),n.reloadConfig(i);let o=ux.preset.sessionKey;n.sessionState.get(e,o)===r&&n.sessionState.clear(e,o),n.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${e})`)},i6=(e,t,n)=>{let r=t,i=H3(n,e),a=n.gates.config.gateFor(n.configFor(i)).listKeys(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new R(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=J3(n,i),c=r.map(O$),l=c.flatMap(e=>e.fileKeys),u=c.flatMap(e=>e.sessionKeys);I1(Y3(n,e),s,l),n.reloadConfig(i);for(let t of u)n.sessionState.clear(e,t);n.log(`info`,`reset-config: ${[...l,...u.map(e=>`session:${e}`)].join(` `)} ← ${s.path} (session=${e})`)};function a6(e,t){let n=(e,t)=>[...Ky(Jx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Gx(t.presets).flatMap(e=>n(t,e).map(t=>tP(NM(e),Hy(t)))));return Gx(e.presets).flatMap(t=>n(e,t).map(e=>({member:tP(NM(t),Hy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function o6(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[ZN]:[]])}const s6=(e,t,n)=>{let[r=``,i=``]=t,a=H3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`apply-layout-op: <key>/<op> is required (have: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`apply-layout-op: ${c.reason}`);let l=sz(c.value);if(l===null)throw new R(`apply-layout-op: "${c.value}" is not a layout op token`);let u=J3(n,a),d=lre(Y3(n,e),u,r,l);n.reloadConfig(a);let f=o6(a6(o,n.configFor(a)),n.sessionState.get(e,ZN)).filter(t=>n.sessionState.get(e,t)!==null);for(let t of f)n.sessionState.clear(e,t);n.log(`info`,`apply-layout-op: ${r} ${c.value} → ${u.path} placed=${JSON.stringify(d)} released=${JSON.stringify(f)} (session=${e})`)},c6=(e,t,n)=>{n.journal.commit();let r=n.history.undo(e);n.journal.wrote(),W3(n,e,r),n.log(`info`,`undo: restored ${C0(r)} (session=${e})`)},l6=(e,t,n)=>{let{step:r,discarded:i}=n.navigation.back(e,n.sessionState,n.gates.state.gateFor(G3(n,e))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);n.log(`info`,`back: ${a} discarded=${i} (session=${e})`)},u6=(e,t,n)=>{n.journal.commit(),n.journal.wrote();let r=n.history.rewind(e);W3(n,e,r),n.log(`info`,`rewind: put back ${C0(r)||`nothing`} as edit mode found it (session=${e})`)},d6=(e,t,n)=>{n.journal.commit();let r=n.history.redo(e);n.journal.wrote(),W3(n,e,r),n.log(`info`,`redo: re-applied ${C0(r)} (session=${e})`)},f6=(e,t,n)=>{n.effect({kind:`apply-update`})};function p6(e,t){let n=e.sessionState.get(t,r$);if(n===null)throw new R(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new R(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new R(`client hints record is not an object: ${n}`);return Or(r)}function m6(e,t,n){let r=nI(n);e.sessionState.setBatch(t,yI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${oI(n.config)} ${_I(n.nerdFont,n.marks)} ${sI(n.terminal,n.clicked)} ${cI(n.terminal,n.width)} ${lI(n.install)} ${dI(n.daemon)} ${fI(n.data)} ${gI(n.transcripts)} ${pI(n.frames,n.claudeSettings)} ${hI(n.claudeSettings.origin.sources)} (session=${t})`)}function h6(e,t,n){e.effect({kind:`doctor`,session:t,step:n,arrival:e.arrival})}function g6(e,t){let n=e=>{throw Error(`doctor: the gather ${e}; a gather writes nothing`)};return{get:(n,r)=>{let i=e.get(n,r);return t.set(JSON.stringify([n,r]),{what:r,value:i,again:e=>e.get(n,r)}),i},values:()=>n(`read every key; a gather reads keys by name`),revision:t=>e.revision(t),set:(e,t)=>n(`set ${t}`),setBatch:()=>n(`wrote a batch`),clear:(e,t)=>n(`cleared ${t}`)}}function _6(e,t,n){for(let{what:t,value:r,again:i}of n.reads)if(i(e.sessionState)!==r)return t;let r=e.doctor.loadConfig(H3(e,t));return r.config===n.load.config&&r.error===n.load.error&&r.warning===n.load.warning?null:`config`}function v6(e,t){let{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}=p6({sessionState:e},t);return{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}}async function y6(e,t,n,r){let i=new Map,a={...e,sessionState:g6(e.sessionState,i)},o=e=>JSON.stringify(v6(e,t)),s=v6(e.sessionState,t);i.set(`hints`,{what:r$,value:JSON.stringify(s),again:o});let c=r.loadConfig(H3(a,t)),l={kind:`clicked`,sessionId:t,via:n.via},u=e.clients.ofSession(t,e.now()),d;try{d=await H4({...r,loadConfig:()=>c},s,H3(a,t),e=>a.sessionState.get(t,e),{kind:`ok`,value:e.serving()},{kind:`ok`,value:u.map(e=>e.rateLimits)},{kind:`ok`,value:u.map(e=>e.transcript)},l,{kind:`ok`,value:G0(l,u)},V4(t,u),m4(e.doctorStores))}catch(e){throw e instanceof V0?new R(e.message):e}return{facts:d,install:f4(r.install,e.bundle,u.map(e=>e.client)),stamp:{load:c,reads:[...i.values()]}}}async function b6(e,t){let n=h4(e.doctor),r=t.session;return e.journalTurns.gathering(async()=>{let i=await y6(e,r,t.arrival,n);return _6(e,r,i.stamp)===null?i:y6(e,r,t.arrival,n)})}function x6(e,t,n,{facts:r,install:i}){let a=m4(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:R4(n),install:i,clicked:S6(e,n,o)}}function S6(e,t,{terminal:n,clicked:r}){let i=n.kind===`seen`?yF(n.identified):null;if(i===null||t.via!==`link`)return r;try{return e.doctorStores.clicked.update(e=>z0(e,i))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(i)}: ${t instanceof Error?t.message:String(t)}`),r}}const C6={run:(e,t,n,r)=>m6(e,t,r),fix:(e,t,{check:n},r)=>{let i=n.probe(r);if(i.ok||i.fix===void 0)throw new R(`doctor-fix: ${n.label} — ${i.ok?`nothing to fix`:i.reason}`);let a=U4(e.doctorStores,i.fix,r);if(a.kind===`failed`)throw new R(`doctor-fix: ${n.label} — ${a.reason}`);e.log(`info`,`doctor-fix: ${n.name} → ${qne(i.fix)} (session=${t})`),m6(e,t,a.value)},mark:(e,t,{check:n,mark:r},i)=>{let a=n.probe(i);if(a.ok||a.sighting===void 0)throw new R(`doctor-mark: ${n.label} — ${a.ok?`nothing to mark`:`shows nothing to look at`}`);let o=e.doctorStores.marks.update(e=>I0(e,n.name,a.sighting.id,r));if(o.kind===`failed`)throw new R(`doctor-mark: ${o.reason}`);e.log(`info`,`doctor-mark: ${n.name} ${r} on ${a.sighting.id} (session=${t})`),m6(e,t,{...i,marks:o})}};function w6(e,t,n){let r=t.session,i=_6(e,r,n.stamp);if(i!==null)throw new R(`doctor: the session's ${i} changed during the doctor's probes — click again`);T6(e,r,t.step,x6(e,r,t.arrival,n))}function T6(e,t,n,r){let i=C6[n.kind];i(e,t,n,r)}const E6=(e,t,n)=>{h6(n,e,{kind:`run`})},D6=(e,t)=>{if(!e.ok)throw new R(`probe: ${e.problem}`);let n=e.value;if(t.arrival.via!==`link`)throw new R(`probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`probe: arrived nonce=${n} delivery=${r.kind}`)},O6=(e,t,n)=>{let[r=``]=t,i=rI(r);if(i===void 0)throw new R(`doctor-fix: unknown check "${r}"`);h6(n,e,{kind:`fix`,check:i})},k6=(e,t,n)=>{let[r=``,i=``]=t,a=rI(r);if(a===void 0)throw new R(`doctor-mark: unknown check "${r}"`);if(!CF.includes(i))throw new R(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${CF.join(` or `)}`);h6(n,e,{kind:`mark`,check:a,mark:i})},A6=(e,t,n)=>{let[r=``]=t,i=Object.values(n.configFor(H3(n,e)).actions).filter(e=>`slash`in e),a=i.find(e=>e.slash===r);if(a===void 0)throw new R(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(i.map(e=>e.slash))].join(`, `)||`none`})`);let o=qQ(p6(n,e).tmux);if(o.kind===`refused`)throw new R(`${r} was not typed: ${o.reason}`);n.effect({kind:`type-slash`,pane:o.hint,line:a.slash})};function j6(e,[t=``,n=``,r=``],i){let a=H3(i,e),o=i.configFor(a).actions,s=Object.hasOwn(o,t)?o[t]:void 0;if(s===void 0||!(`run`in s))throw new R(`"${t}" is not a run action this session's config declares`);let c=sS(s);if(!i.links.signer.verify({sessionId:e,action:t,declaration:c,evaluated:n},r))throw new R(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let l;try{l=JSON.parse(n)}catch{throw new R(`run ${t}: what the link carries is not JSON`)}let[u,...d]=l.run;if(u===void 0||u===``)throw new R(`run ${t}: the program evaluated to nothing`);let f=i.sourcesFor(a);return{sessionId:e,action:t,argv:[u,...d],envOverlay:{...N0({sessionId:e,projectDir:a.projectDir,claudeConfigDir:p6(i,e).claudeConfigDir}),...l.env},cwd:s.cwd??i.locations.homeDir,refreshes:s.refreshes.map(e=>({name:e,storage:f.get(e)}))}}const M6=new Map([[ES,D3,[1,1]],[DS,j3,[1,1]],[wS,N3,[0,1/0]],[TS,I3,[2,2]],[kS,X3,[2,2]],[AS,Z3,[2,2]],[FS,i6,[0,1/0]],[jS,Q3,[0,0]],[MS,t6,[0,0]],[NS,n6,[0,0]],[PS,r6,[1,1]],[IS,s6,[2,2]],[LS,c6,[0,0]],[RS,d6,[0,0]],[zS,l6,[0,0]],[BS,u6,[0,0]],[OS,M3,[0,0]],[VS,f6,[0,0]],[HS,E6,[0,0]],[US,O6,[1,1]],[WS,k6,[2,2]],[JS,A6,[1,1]],[`run`,(e,t,n)=>{let r=j6(e,t,n);n.effect({kind:`run`,id:n.runs.superseded(r),run:r})},[3,3]],[YS,(e,t,n)=>{let[r=``,i=``,a=``]=t,o=i;if(!n.links.signer.verify(JU(e,r,o),a))throw new R(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let s=qU(KU(n.stateDir),r,o);if(s.kind===`failed`)throw Error(`${r} was not ${o}: ${s.reason}`);n.journal.wrote();let{superseded:c,absent:l,unchecked:u}=s.value;n.log(`info`,`repo-config: ${r} ${o} superseded=${c.join(`,`)||`-`} absent=${l.join(`,`)||`-`} unchecked=${u.length===0?`-`:JSON.stringify(u)} (session=${e})`),n.reloadConfig(H3(n,e))},[3,3]],[XS,A3,[2,2]]].map(([e,t,n])=>[e,{handler:t,takes:n}]));new Set(M6.keys());function N6(e,t,n){let[r=``,...i]=n.split(`/`);return{verb:e,leaf:t,session:P6(r),args:tc(()=>i.map(decodeURIComponent))}}function P6(e){let t=tc(()=>decodeURIComponent(e));return t.ok?aQ(t.value):{ok:!1,problem:`has ${t.problem}`}}function F6({verb:e,value:t}){let n=M6.get(e);return n===void 0?{verb:e,leaf:n}:N6(e,n,t)}function I6(e){return e.find(e=>e.leaf!==void 0)?.session??null}function L6(e,t){return`${e}: ${t}`}function R6(e){return`unknown effect verb "${e}"`}function z6(e,t){return{kind:`refused`,reason:t,problem:L6(e,t)}}function B6(e){let t=R6(e);return{kind:`refused`,reason:t,problem:t}}function V6({verb:e},t,n){return{ok:!1,verb:e,args:t,refusal:z6(e,n)}}function H6(e,t){if(e.leaf===void 0)return{ok:!1,verb:e.verb,args:[],refusal:B6(e.verb)};let{verb:n,leaf:r,session:i,args:a}=e,o=a.ok?a.value:[];if(!i.ok)return V6(e,o,`session id ${i.problem}`);if(!t?.ok)return V6(e,o,`its click's own session is refused, so no step of it runs`);if(t.id!==i.id)return V6(e,o,`names session ${i.id}, not the session its click is in`);if(!a.ok)return V6(e,o,a.problem);let[s,c]=r.takes;return a.value.length<s||a.value.length>c?V6(e,o,`reads ${s===c?s:`${s} to ${c}`} after its session, and the link carries ${a.value.length}`):{ok:!0,verb:n,leaf:r,sid:i.id,args:a.value}}function U6(e){let t=tc(()=>decodeURIComponent(e));if(!t.ok)return t;let n=p3(t.value);return n===null?{ok:!1,problem:`the value is not a probe nonce`}:{ok:!0,value:n}}const W6={[CS]:e=>{let t=pC(dC(e)).map(F6),n=I6(t);return{kind:CS,steps:t.map(e=>H6(e,n)),session:n}},[GS]:e=>({kind:GS,nonce:U6(e)})};function G6(e,t){return qS(e)?W6[e](t):null}function K6(e){return e.kind===`dispatch`&&e.session?.ok?e.session.id:null}function q6(e,t){let n=[];try{e.leaf.handler(e.sid,e.args,{...t,effect:e=>void n.push(e)})}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof R?z6(e.verb,n):{kind:`failed`,problem:L6(e.verb,n)}}for(let e of n)t.effect(e);return{kind:`ran`}}const J6=new Map([[`run`,(e,{sid:t,args:[n],reason:r})=>e.runs.refused(t,n||`-`,r)]]);function Y6(e,t,n){let r=[],i=!1;for(let a of e){let e=a.ok?q6(a,n):a.refusal;e.kind!==`ran`&&(e.kind===`refused`?J6.get(a.verb)?.(n,{sid:t?.ok?t.id:`-`,args:a.args,reason:e.reason}):i=!0,r.push(e.problem))}if(r.length>0){t?.ok&&FZ(n.sessionState,t.id,r.join(`
|
|
@@ -504,7 +504,7 @@ function run(argv) {
|
|
|
504
504
|
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var Lae=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:this.loop.clear(),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${O(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,clear:this.deps.clock.after(this.deps.intervalMs,()=>this.ask(),{unref:!0})};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:o7(t.stdout,a7(n.stdout)),status:Iae(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!Rae(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function Rae(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}function s7(e){return`"${e.replace(/[\\"$~]/g,e=>`\\${e}`)}"`}function c7(e){return e.map(e=>e.map(l7).join(` `)).join(` ; `)}const l7=e=>typeof e==`string`?s7(e):`{ ${c7(e.block)} }`;function zae(e){return e.map(e=>e.map(l7).join(` `)).join(` \\; `)}const Bae={n:`
|
|
505
505
|
`,t:` `,r:`\r`,b:`\b`,a:`\x07`,v:`\v`,f:`\f`,0:`\0`},Vae=(e,t)=>e.startsWith(`\\;`,t)&&(e[t+2]??` `)===` `;function u7(e){let t=0,n=n=>e[t]===n&&(e[t+1]??` `)===` `,r=()=>{let n=[],r=e=>{n.push(...Buffer.from(e,`utf8`))},i=null;for(;t<e.length;){let a=e[t];if(i===null&&(a===` `||a===`;`))break;if(a===i)i=null,t++;else if(i===null&&(a===`"`||a===`'`))i=a,t++;else if(a===`\\`&&t+1<e.length){let i=/^[0-7]{3}/.exec(e.slice(t+1,t+4)),a=e[t+1];i===null?(r(Bae[a]??a),t+=2):(n.push(parseInt(i[0],8)),t+=4)}else{let n=String.fromCodePoint(e.codePointAt(t));r(n),t+=n.length}}return Buffer.from(n).toString(`utf8`)},i=a=>{let o=[[]];for(;t<e.length;)if(e[t]===` `)t++;else if(e[t]===`;`||!a&&Vae(e,t))o.push([]),t+=e[t]===`;`?1:2;else if(a&&n(`}`)){t++;break}else n(`{`)?(t++,o.at(-1).push({block:i(!0)})):o.at(-1).push(r());return o.filter(e=>e.length>0)};return i(!1)}const d7=[`-T`,`root`,`MouseDown1Status`],f7=`@cc-candybar-renderer`,p7=`@cc-candybar-click`;function Hae(e,t,n,r){return`${e} ${uC(t,ZS,oC([n,r]))}`}const m7=`#{m:ccb*,#{mouse_status_range}}`;function Uae(e){let t=`run-shell -b ${s7(`#{${p7}}/#{s/%//:pane_id}/#{q:mouse_status_range}`)}`,n=`display-message ${s7(`cc-candybar: no renderer takes clicks on this row: the one that drew it is older than this binding`)}`;return[`bind-key`,...d7,`if-shell`,`-F`,m7,`if-shell -F ${s7(`#{${p7}}`)} ${s7(t)} ${s7(n)}`,...e===null?[]:[c7(e)]]}const Wae=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m;function h7(e){let[t,...n]=e;if(t===void 0||n.length>0||t[0]!==`if-shell`)return;let r=t.slice(1);for(;typeof r[0]==`string`&&r[0].startsWith(`-`);)r=r.slice(1);if(r[0]!==m7)return;let i=r[2],a=i===void 0?[]:typeof i==`string`?u7(i):i.block;return a.length>0?a:null}function g7(e){let t=Wae.exec(e)?.[1],n=t===void 0?null:u7(t),r=n!==null&&h7(n)!==void 0;for(;n!==null;){let e=h7(n);if(e===void 0)break;n=e}return{ours:r,user:n}}const _7=`#{S:#{?#{!=:#{${f7}},},1,}}`;function Gae(e){return[`if-shell`,`-F`,_7,`${c7([Uae(e)])} ; display-message -p ccb:bound`]}function Kae(e){return[`if-shell`,`-F`,_7,`display-message -p ccb:held`,`${e===null?`unbind-key ${d7.join(` `)}`:`bind-key ${d7.join(` `)} ${zae(e)}`} ; display-message -p ccb:restored`]}const v7=zc.tmuxStatus.rows,y7=`@cc-candybar-status-prior`,b7=`@cc-candybar-status-wrote`,x7=Array.from({length:v7},(e,t)=>t),S7=e=>`@cc-candybar-row-${e}`,qae=e=>`#[fill=terminal]#{${S7(e)}}`,C7=e=>`status-format[${e}]`;function Jae(e){return e===0?`off`:e===1?`on`:String(e)}function w7(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function Yae(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function T7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}const E7={kind:`ok`,stdout:``};function D7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}const O7=`ccb:separator`;function k7(e){return D7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,O7],e]))}function A7(e,t){let n=e.split(`${O7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const j7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],Xae=e=>[`show-options`,`-g`,`-q`,`-v`,e],M7=e=>[[`show-options`,`-t`,e],j7(e,`status`),...x7.map(t=>j7(e,C7(t)))];function N7(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
506
506
|
`).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 P7(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 Zae=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...M7(e),...x7.map(e=>Xae(C7(e))),j7(e,y7),j7(e,b7)];function F7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:w7(t)}catch(e){return{kind:`theirs`,why:`${y7} 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`}}const I7=(e,t)=>[[`set-option`,`-t`,e,f7,t.name],[`set-option`,`-t`,e,p7,t.click]];function Qae(e,t,n,r){let[i=``,...a]=t,o=N7(a.slice(0,2+v7)),s=a.slice(2+v7,2+2*v7),[c=``,l=``]=a.slice(2+2*v7);if(c!==``){let t=F7(c,l,n);return t.kind===`theirs`?t:{...t,commands:I7(e,r)}}let u=w7(i),d={};for(let e=0;e<u;e++){let t=o.formats===null?s[e]:o.formats[e];t!==void 0&&t!==``&&(d[e]=t)}let f={...d,...Object.fromEntries(Array.from({length:v7-u},(e,t)=>[u+t,qae(t)]))},p={owner:n,base:u,status:o.status,formats:o.formats,wrote:f};return{kind:`lay-out`,prior:p,commands:[[`set-option`,`-t`,e,y7,JSON.stringify(p)],...I7(e,r),...P7(e,f)]}}const L7=e=>[...M7(e),j7(e,b7)];function R7(e,t,n){let r=N7(n.slice(0,2+v7)),i=n[2+v7]??``,a=[],o=[];if(Yae(r.formats,t.wrote))a.push(...P7(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,y7],[`set-option`,`-q`,`-u`,`-t`,e,b7],[`set-option`,`-q`,`-u`,`-t`,e,f7],[`set-option`,`-q`,`-u`,`-t`,e,p7]),{commands:a,kept:o}}const z7=[[`list-keys`,`-T`,`root`]];var $ae=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.kind===`runs`?t.tmux:r??null:null;if(r!==void 0&&(i===null||!yc(r,i))&&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=e.value,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 e=this.deps.sessionInPane(n);e!==null&&e!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(e)}`)}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)}if(n.binding===`none`)continue;n.binding=`none`;let r=this.askSync(e,t,z7);if(r===null)continue;let i=this.bindingRestore(t,r[0]??``);if(i===null)continue;let a=this.writeSync(e,t,[i.command]);this.saidBindingRestore(t,a,i.user)}}linkAt(e){let t=eoe(e),[n,r,i,a,...o]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a===void 0||o.length>0)return{kind:`refused`,reason:`${ZS} needs <socket>/<mac>/<pane>/<range>, got ${JSON.stringify(e)}`};if(!this.deps.signer.verifyBinding(n,r))return{kind:`refused`,reason:`a status-line click on ${JSON.stringify(n)} whose mac is not this renderer's binding's`};let s=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${i}`)?.frame?.links,c=s!==void 0&&Object.hasOwn(s,a)?s[a]:void 0;return c===void 0?{kind:`refused`,reason:`pane %${i}'s status line draws no link ${a} now`}:{kind:`link`,url:c}}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:`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,v7-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#{${y7}}\t#{${b7}}`]);if(n.kind===`ok`){let r=this.marks(e),i=[];for(let a of n.stdout.split(`
|
|
507
|
-
`)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=F7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...I7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:Hae(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,Zae(n));if(r===null||this.closed)return null;let i=Qae(n,r,this.deps.owner,this.marks(e));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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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=Jae(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,b7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,c7(a)]])).kind===`ok`)&&(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,z7);if(r===null||this.closed)return;let{user:i}=g7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[Gae(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${B7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,z7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=g7(t);return n.ours?{command:Kae(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${B7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}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){return t.length===0?E7:(this.writes++,this.run(e,D7(t)))}writeSync(e,t,n){return n.length===0?E7:(this.writes++,this.counted(t,e(t,D7(n))))}};const B7=e=>e===null?`unbound`:JSON.stringify(c7(e));function eoe(e){try{return sC(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),V7=e=>({arity:e,keep:!1}),toe={"--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":V7(`none`),"--background":V7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":V7(`optional`),"-c":V7(`none`),"--continue":V7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":V7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":V7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":V7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":V7(`optional`),"-h":V7(`none`),"--help":V7(`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":V7(`none`),"--print":V7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":V7(`optional`),"--resume":V7(`optional`),"--safe-mode":$(`none`),"--session-id":V7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":V7(`optional`),"--tmux":V7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":V7(`none`),"--version":V7(`none`),"-w":V7(`optional`),"--worktree":V7(`optional`)},noe={resume:`--resume`,fresh:`--session-id`};function roe(e){return[noe[e.kind],e.sessionId]}const H7=e=>e.startsWith(`-`)&&e!==`-`;function U7(e,t){let n=W7(t);return n===null?{dir:e??t,args:[]}:e!==null&&ioe(e,n.top)?{dir:e,args:[]}:{dir:e===null||W7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const ioe=(e,t)=>e===t||e.startsWith(t+s.sep);function aoe(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!H7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=toe[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=>!H7(e)):o.arity===`variadic`?ooe(n.slice(r),e=>!H7(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 W7(e){let t=e.split(s.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(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function ooe(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const G7=`candybar-band@cc-candybar`,soe=s.join(`bin`,`cc-candybar-native`),coe=AI(`/reload-plugins`);function loe(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=qQ(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!yc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function K7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const q7=e=>({kind:`done`,said:e});function J7(e){let t=qQ(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const uoe={band:{on:async(e,t,n)=>{let r=Nn(t.bundle);if(r===null)throw new R(`${zc.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=s.join(r,soe);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${G7} from ${r}`,finished:doe(e,r,n)}},off:async()=>q7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=J7(e.session),i=bn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${zc.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:e.inPane((e,r)=>moe(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>K7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>q7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>K7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?q7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):q7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Qn(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return q7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?q7(`no bar pane to close: ${r.reason}`):K7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>q7(`the daemon draws ${J7(e).pane}'s bar in its status line`),off:async()=>q7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function doe(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,G7],i);let a=await e.inPane((e,t)=>JQ(n.claudeInput,t,coe)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${G7} from ${t} and typed /reload-plugins into ${o.pane}`}const foe=new Set([Fo,EP]);function poe(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function moe(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,xn(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}) — ${zc.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);let o=await r.paneClaude(t);if(o.pid!==i.pid||o.startTime!==i.startTime)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}, started ${i.startTime}; now pid ${o.pid}, started ${o.startTime}), so it was not restarted under the attach launcher`);let s=yoe(await r.claudeInput.read(t));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s} — then turn ${zc.statusline.label} off and on again`);let c=hoe(e,r.presence(e.transcript));if(c!==null)throw Error(`Claude Code in ${t.pane} was left running: ${c}`);let l=aoe(i.argv);if(l.kind===`refused`)throw Error(`${l.reason} — restart it with that flag removed`);let u=poe(i.env),d=u.get(`PATH`),f=r.launcherNode(d);if(f.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${f.why}`);let p=r.onPath(`claude`,d)===i.executable?`claude`:i.executable,m=[...u].filter(([e])=>foe.has(e)),h=(e,t)=>wn(n.preload,{dir:e.dir,env:m,program:p,args:[...e.args,...l.args,...roe(t)]}),g=r.heldSession({pid:i.pid,startTime:i.startTime,configDir:Io(Object.fromEntries(u),i.cwd)});if(g.kind!==`holds`)throw Error(`Claude Code in ${t.pane} was left running: ${g.why}, so which session it runs is unknown`);if(g.sessionId!==e.sessionId)throw Error(`Claude Code in ${t.pane} now runs session ${g.sessionId}, not ${e.sessionId}, so it was not restarted under the attach launcher — turn ${zc.statusline.label} off and on again from the bar in ${t.pane} to restart that one`);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 _=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),v=goe(e,r.presence(e.transcript)),y=v.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:v,b;try{b=await r.paneDir(t,i.parent)}catch(e){throw _(`the directory it was started in could not be read (${e.message})`,h(U7(null,i.cwd),y))}let x=h(U7(b,i.cwd),y);if(v.kind===`unchecked`)throw _(`whether session ${e.sessionId} has a conversation could not be seen (${v.error})`,x);try{await r.typeShellLine(t,x)}catch(e){throw _(`the line could not be typed into its pane (${e.message})`,x)}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 \`${x}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${x}\`, ${_oe[v.kind](e.sessionId)}, and its statusline follows lane B`}function hoe(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 goe(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const _oe={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},voe={"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 yoe(e){let t=HQ(e);return t.kind===`ready`?GQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:UQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:voe[t.kind]}var boe=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=Bc.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return Y7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return Y7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new $s(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),Qs(r)},o;try{o=await uoe[t][n?`on`:`off`](loe(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new $s(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function Y7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const xoe=[`request`,`feed`],X7=new WeakMap;let Soe=0;const Z7=e=>{let t=X7.get(e);if(t!==void 0)return t;let n=Soe++;return X7.set(e,n),n};var Coe=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(Q7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Z7(n.config),i=[];for(let n of xoe){let a=this.records.get(Q7(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=Q7(e,t);this.records.delete(a),this.records.set(a,{generation:Z7(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 Q7=(e,t)=>`${t}\0${e}`,woe={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,vc(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function Toe(e){let t=woe[e.kind];return JSON.stringify(t(e))}var Eoe=class{gathers=new o5;effects=new o5;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new $s(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new $s(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run(Toe(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},Doe=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}drawn(e,t,n,r){let i=this.since(e,t),a=r(i);return this.observe(e,t,a.frame.rows.some(e=>e.kind===`menu`),n),{...a,idleSince:i}}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++;return{sessions:this.sessions.size,armed:e}}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?Lb(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,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 Ooe(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=fr(o),u=mr(c,o),d=()=>it(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new K4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),me.wakeWhere(`data`,()=>!0)}}),_=e.probe(g),v=e.storage(m),y=new Eoe,b=new K1(y,v.session),x=new l0(b,m,v.history),S=Ii({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new d3,w=new Pne,T=e.doctorStores,E=new wj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new Gj(m),D=new Mc({watchers:E,logger:m,clock:i}),te=new uM({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=Gie({launcher:g,host:c,pricing:e.pricing({cacheRoot:Gn(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{gitProvider:k,usageStore:ne,tmuxService:A,hostService:re,managedStorage:ie}=O,ae=new dae,oe=new sne,se=new Doe({clock:i,now:d,close:async(e,t)=>{await c8({kind:`menu-idle`,session:e,idle:t},Ee)},failed:(e,t)=>g8(m,`menu-idle`,`session=${e}`,t)}),ce={to:o.name,signer:e.linkSigner},le=new ac({supersede:(e,t)=>ie.supersede(e,t),launch:g.launch,log:m,clock:i}),ue=e.heldSession(c.home),de=new boe({edge:e.laneEdge(g,e=>me.following(e),f.signal,_,ue),host:{bundle:t.path,node:t.node,home:o,preload:us(t.path,c)},log:m,latest:e=>{let t=me.latest(e);return t===null?null:PQ(t)},paneOrder:(e,t)=>y.performing({kind:`pane`,tmux:e},t)}),fe=new $ae({edge:{run:(e,t)=>Xs(g,{socket:e},`tmux-status`,t)},subscribe:(e,t)=>me.subscribe(e,t),sessionInPane:e=>me.newestWhere(Zc(e,ue)),handler:[...Object.entries(Qn(o)).map(([e,t])=>`${e}=${_n(t)}`),...[...t.node,t.path].map(_n),`url-handle`].join(` `),owner:l.socket,name:o.name,signer:e.linkSigner,log:m}),pe=Pae({file:l.linkIds,clock:i,retryMs:DZ.still,log:m}),me=new NZ({render:(e,t,n)=>SQ(Ee,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>b.revision(e),t),lanes:e=>wQ(Ee,e),pin:e=>{let t=ye.pin(e);return()=>{ye.stopDrawing(e,`feed`),t()}},shown:e=>he.shown(e.hints.tmux),watching:()=>he.follow(),refreshes:()=>ee.totals(),periods:DZ,encoders:jae(pe),clock:i,instant:d,log:m}),he=new Lae({clock:i,listPanes:e=>Xs(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,r7]),listClients:e=>Xs(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,i7]),sockets:()=>new Set(me.watched().flatMap(({req:e})=>ge(e))),onAnswer:(e,t)=>fe.answered(e,t),onChange:e=>me.wakeWhere(`visibility`,t=>ge(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function ge({hints:{tmux:e}}){return e==null?[]:[e.socket]}let _e=new Coe,ve=Ure(),{cache:ye,recorder:be}=fQ(e=>new lae({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,storage:ie,links:ce,gates:s,facts:gae({providers:O,update:()=>ve.get(),runs:te}),source:vae({providers:O,sessionState:b,history:e=>x.depth(e),navigation:(e,t)=>ae.depth(e,b,s.state.gateFor(t))})},{budgetBytes:()=>Jie(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Qie(e,n,r));for(let e of t)me.wake(e,`reload`)},onViewChanged:e=>me.wake(e,`data`),...e}}),m);D.subscribe(e=>{switch(e.kind){case`period`:E.judge();return;case`caught-up`:ye.reloadEvery({kind:`events-resumed`,since:e.since}),me.wakeWhere(`data`,()=>!0);return;case`moved`:me.wakeWhere(`data`,()=>!0);return}});let xe=60*1e3,Se=Gre({clock:i,targets:t.targets,intervalMs:xe,filesystem:e.filesystem,held:()=>Ce.running(),exit:()=>a(0),log:m}),Ce=Hre({fact:ve,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:Ore(l.state,t.path),intervalMs:xe,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>Se.checkNow(),log:m}),we=new o$(y),Te={gates:s,sessionState:b,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:y,clickLanded:e=>se.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>Ce.act(),doctor:e.doctorEdge(g,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:T,probes:C,clients:w,mismatchRuns:we,bundle:t.path,serving:()=>S.serving(),claudeInput:e.claudeInput(g),history:x,navigation:ae,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:ce,runs:le,lanes:{of:(e,t)=>TQ(Ee,e,t),clicked:(e,t,n)=>FQ(Ee,e,t,n),arrived:e=>MQ(Ee,e),setup:e=>de.setup(e)},diagnosticCopy:(e,t,n)=>ye.drawnCopy(e,t,n)},Ee={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,heldSession:ue,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,mismatchRuns:we,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:(e,t,n,r)=>IQ(Ee,e,t,n,r),effectSessions:oe,menuIdle:se,journalTurns:y,links:ce,runs:le,sourceRuns:te,laneSetups:de,tmuxStatusLines:fe,frameFeeds:me,linkIds:pe,renderWarnings:_e,renderCache:ye,recorder:be,updateWatch:Ce,limits:S,verbCtx:Te};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),mre(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),q8(Ee,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),me.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Te.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),Se.arm(),Ce.arm(),S.arm()},close(e){let t=[[`journalTurns close`,()=>y.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>de.close()],[`frameFeeds close`,()=>me.close()],[`linkIds close`,()=>pe.close()],[`menuIdle dispose`,()=>se.dispose()],[`updateWatch close`,()=>Ce.close()],[`binaryWatch close`,()=>Se.close()],[`limits disarm`,()=>S.disarm()],[`recorder close`,()=>be.close()],[`renderCache close`,()=>ye.close()],[`gitService close`,()=>k.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>A.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>le.close()],[`sourceRuns close`,()=>te.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>D.close()],[`watcherRegistry close`,()=>E.closeAll()],[`sessionState close`,()=>b.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function koe(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 Aoe=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=m.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return koe(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.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=Qe(this.clock,n);try{await m.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await m.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 m.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await m.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Qe(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{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);m.writeFileSync(n,r,{mode:384}),m.chmodSync(n,384),m.rmSync(this.writingPath,{force:!0}),m.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,Qe(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=${Qe(this.clock,n)}ms held=${r}ms`)}};function joe(e,t,n){return{session:new Aoe(e.sessionState,n,500,t),history:j0(e.settingsHistory,e.storedRoot,t)}}function $7(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function e9(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Moe(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Noe(e,t,n){let r=$7(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.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 t9=2e3;async function n9(e,t,n,r){let i=await Xs(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function r9(e,t){if(t.ok)return t.stdout;let n=mt(t,t.stdout);throw Error(`${e} failed (${j(t)}${n===``?``:`: ${n}`})`)}function Poe(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 Foe=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Ioe(e,t){return e.split(`
|
|
507
|
+
`)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=F7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...I7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:Hae(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,Zae(n));if(r===null||this.closed)return null;let i=Qae(n,r,this.deps.owner,this.marks(e));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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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=Jae(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,b7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,c7(a)]])).kind===`ok`)&&(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,z7);if(r===null||this.closed)return;let{user:i}=g7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[Gae(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${B7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,z7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=g7(t);return n.ours?{command:Kae(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${B7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}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){return t.length===0?E7:(this.writes++,this.run(e,D7(t)))}writeSync(e,t,n){return n.length===0?E7:(this.writes++,this.counted(t,e(t,D7(n))))}};const B7=e=>e===null?`unbound`:JSON.stringify(c7(e));function eoe(e){try{return sC(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),V7=e=>({arity:e,keep:!1}),toe={"--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":V7(`none`),"--background":V7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":V7(`optional`),"-c":V7(`none`),"--continue":V7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":V7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":V7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":V7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":V7(`optional`),"-h":V7(`none`),"--help":V7(`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":V7(`none`),"--print":V7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":V7(`optional`),"--resume":V7(`optional`),"--safe-mode":$(`none`),"--session-id":V7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":V7(`optional`),"--tmux":V7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":V7(`none`),"--version":V7(`none`),"-w":V7(`optional`),"--worktree":V7(`optional`)},noe={resume:`--resume`,fresh:`--session-id`};function roe(e){return[noe[e.kind],e.sessionId]}const H7=e=>e.startsWith(`-`)&&e!==`-`;function U7(e,t){let n=W7(t);return n===null?{dir:e??t,args:[]}:e!==null&&ioe(e,n.top)?{dir:e,args:[]}:{dir:e===null||W7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const ioe=(e,t)=>e===t||e.startsWith(t+s.sep);function aoe(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!H7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=toe[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=>!H7(e)):o.arity===`variadic`?ooe(n.slice(r),e=>!H7(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 W7(e){let t=e.split(s.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(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function ooe(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const G7=`candybar-band@cc-candybar`,soe=s.join(`bin`,`cc-candybar-native`),coe=AI(`/reload-plugins`);function loe(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=qQ(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!yc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function K7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const q7=e=>({kind:`done`,said:e});function J7(e){let t=qQ(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const uoe={band:{on:async(e,t,n)=>{let r=Nn(t.bundle);if(r===null)throw new R(`${zc.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=s.join(r,soe);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${G7} from ${r}`,finished:doe(e,r,n)}},off:async()=>q7(`nothing to stop: the band mod ends its child once the lane is off`)},statusline:{on:async(e,t,n)=>{let r=J7(e.session),i=bn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${zc.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:e.inPane((e,r)=>moe(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>K7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>q7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>K7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?q7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):q7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Qn(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return q7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?q7(`no bar pane to close: ${r.reason}`):K7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>q7(`the daemon draws ${J7(e).pane}'s bar in its status line`),off:async()=>q7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function doe(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,G7],i);let a=await e.inPane((e,t)=>JQ(n.claudeInput,t,coe)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${G7} from ${t} and typed /reload-plugins into ${o.pane}`}const foe=new Set([Fo,EP]);function poe(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function moe(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,xn(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}) — ${zc.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);let o=await r.paneClaude(t);if(o.pid!==i.pid||o.startTime!==i.startTime)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}, started ${i.startTime}; now pid ${o.pid}, started ${o.startTime}), so it was not restarted under the attach launcher`);let s=yoe(await r.claudeInput.read(t));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s} — then turn ${zc.statusline.label} off and on again`);let c=hoe(e,r.presence(e.transcript));if(c!==null)throw Error(`Claude Code in ${t.pane} was left running: ${c}`);let l=aoe(i.argv);if(l.kind===`refused`)throw Error(`${l.reason} — restart it with that flag removed`);let u=poe(i.env),d=u.get(`PATH`),f=r.launcherNode(d);if(f.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${f.why}`);let p=r.onPath(`claude`,d)===i.executable?`claude`:i.executable,m=[...u].filter(([e])=>foe.has(e)),h=(e,t)=>wn(n.preload,{dir:e.dir,env:m,program:p,args:[...e.args,...l.args,...roe(t)]}),g=r.heldSession({pid:i.pid,startTime:i.startTime,configDir:Io(Object.fromEntries(u),i.cwd)});if(g.kind!==`holds`)throw Error(`Claude Code in ${t.pane} was left running: ${g.why}, so which session it runs is unknown`);if(g.sessionId!==e.sessionId)throw Error(`Claude Code in ${t.pane} now runs session ${g.sessionId}, not ${e.sessionId}, so it was not restarted under the attach launcher — turn ${zc.statusline.label} off and on again from the bar in ${t.pane} to restart that one`);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 _=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),v=goe(e,r.presence(e.transcript)),y=v.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:v,b;try{b=await r.paneDir(t,i.parent)}catch(e){throw _(`the directory it was started in could not be read (${e.message})`,h(U7(null,i.cwd),y))}let x=h(U7(b,i.cwd),y);if(v.kind===`unchecked`)throw _(`whether session ${e.sessionId} has a conversation could not be seen (${v.error})`,x);try{await r.typeShellLine(t,x)}catch(e){throw _(`the line could not be typed into its pane (${e.message})`,x)}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 \`${x}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${x}\`, ${_oe[v.kind](e.sessionId)}, and its statusline follows lane B`}function hoe(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 goe(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const _oe={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},voe={"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 yoe(e){let t=HQ(e);return t.kind===`ready`?GQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:UQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:voe[t.kind]}var boe=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=Bc.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return Y7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return Y7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new $s(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),Qs(r)},o;try{o=await uoe[t][n?`on`:`off`](loe(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new $s(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function Y7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const xoe=[`request`,`feed`],X7=new WeakMap;let Soe=0;const Z7=e=>{let t=X7.get(e);if(t!==void 0)return t;let n=Soe++;return X7.set(e,n),n};var Coe=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(Q7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Z7(n.config),i=[];for(let n of xoe){let a=this.records.get(Q7(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=Q7(e,t);this.records.delete(a),this.records.set(a,{generation:Z7(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 Q7=(e,t)=>`${t}\0${e}`,woe={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,vc(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function Toe(e){let t=woe[e.kind];return JSON.stringify(t(e))}var Eoe=class{gathers=new o5;effects=new o5;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new $s(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new $s(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run(Toe(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},Doe=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}drawn(e,t,n,r){let i=this.since(e,t),a=r(i);return this.observe(e,t,a.frame.rows.some(e=>e.kind===`menu`),n),{...a,idleSince:i}}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++;return{sessions:this.sessions.size,armed:e}}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?Lb(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,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 Ooe(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=fr(o),u=mr(c,o),d=()=>it(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new K4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),me.wakeWhere(`data`,()=>!0)}}),_=e.probe(g),v=e.storage(m),y=new Eoe,b=new K1(y,v.session),x=new l0(b,m,v.history),S=Ii({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new d3,w=new Pne,T=e.doctorStores,E=new wj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new Gj(m),D=new Mc({watchers:E,logger:m,clock:i}),te=new uM({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=Gie({launcher:g,host:c,pricing:e.pricing({cacheRoot:Gn(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{gitProvider:k,usageStore:ne,tmuxService:A,hostService:re,managedStorage:ie}=O,ae=new dae,oe=new sne,se=new Doe({clock:i,now:d,close:async(e,t)=>{await c8({kind:`menu-idle`,session:e,idle:t},Ee)},failed:(e,t)=>g8(m,`menu-idle`,`session=${e}`,t)}),ce={to:o.name,signer:e.linkSigner},le=new ac({supersede:(e,t)=>ie.supersede(e,t),launch:g.launch,log:m,clock:i}),ue=e.heldSession(c.home),de=new boe({edge:e.laneEdge(g,e=>me.following(e),f.signal,_,ue),host:{bundle:t.path,node:t.node,home:o,preload:us(t.path,c)},log:m,latest:e=>{let t=me.latest(e);return t===null?null:PQ(t)},paneOrder:(e,t)=>y.performing({kind:`pane`,tmux:e},t)}),fe=new $ae({edge:{run:(e,t)=>Xs(g,{socket:e},`tmux-status`,t)},subscribe:(e,t)=>me.subscribe(e,t),sessionInPane:e=>me.newestWhere(Zc(e,ue)),handler:[...Object.entries(Qn(o)).map(([e,t])=>`${e}=${_n(t)}`),...[...t.node,t.path].map(_n),`url-handle`].join(` `),owner:l.socket,name:o.name,signer:e.linkSigner,log:m}),pe=Pae({file:l.linkIds,clock:i,retryMs:DZ.still,log:m}),me=new NZ({render:(e,t,n)=>SQ(Ee,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>b.revision(e),t),lanes:e=>wQ(Ee,e),pin:e=>{let t=ye.pin(e);return()=>{ye.stopDrawing(e,`feed`),t()}},shown:e=>he.shown(e.hints.tmux),watching:()=>he.follow(),refreshes:()=>ee.totals(),periods:DZ,encoders:jae(pe),clock:i,instant:d,log:m}),he=new Lae({clock:i,listPanes:e=>Xs(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,r7]),listClients:e=>Xs(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,i7]),sockets:()=>new Set(me.watched().flatMap(({req:e})=>ge(e))),onAnswer:(e,t)=>fe.answered(e,t),onChange:e=>me.wakeWhere(`visibility`,t=>ge(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function ge({hints:{tmux:e}}){return e==null?[]:[e.socket]}let _e=new Coe,ve=Ure(),{cache:ye,recorder:be}=fQ(e=>new lae({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,storage:ie,links:ce,gates:s,facts:gae({providers:O,update:()=>ve.get(),runs:te}),source:vae({providers:O,sessionState:b,history:e=>x.depth(e),navigation:(e,t)=>ae.depth(e,b,s.state.gateFor(t))})},{budgetBytes:()=>Jie(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Qie(e,n,r));for(let e of t)me.wake(e,`reload`)},onViewChanged:e=>me.wake(e,`data`),...e}}),m);D.subscribe(e=>{switch(e.kind){case`period`:E.judge();return;case`caught-up`:ye.reloadEvery({kind:`events-resumed`,since:e.since}),me.wakeWhere(`data`,()=>!0);return;case`moved`:me.wakeWhere(`data`,()=>!0);return}});let xe=60*1e3,Se=Gre({clock:i,targets:t.targets,intervalMs:xe,filesystem:e.filesystem,held:()=>Ce.running(),exit:()=>a(0),log:m}),Ce=Hre({fact:ve,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:Ore(l.state,t.path),intervalMs:xe,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>Se.checkNow(),log:m}),we=new o$(y),Te={gates:s,sessionState:b,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:y,clickLanded:e=>se.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>Ce.act(),doctor:e.doctorEdge(g,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:T,probes:C,clients:w,mismatchRuns:we,bundle:t.path,serving:()=>S.serving(),claudeInput:e.claudeInput(g),history:x,navigation:ae,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:ce,runs:le,lanes:{of:(e,t)=>TQ(Ee,e,t),clicked:(e,t,n)=>FQ(Ee,e,t,n),arrived:e=>MQ(Ee,e),setup:e=>de.setup(e)},diagnosticCopy:(e,t,n)=>ye.drawnCopy(e,t,n)},Ee={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,heldSession:ue,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,mismatchRuns:we,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:(e,t,n,r)=>IQ(Ee,e,t,n,r),effectSessions:oe,menuIdle:se,journalTurns:y,links:ce,runs:le,sourceRuns:te,laneSetups:de,tmuxStatusLines:fe,frameFeeds:me,linkIds:pe,renderWarnings:_e,renderCache:ye,recorder:be,updateWatch:Ce,limits:S,verbCtx:Te};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),mre(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),q8(Ee,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),me.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Te.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),Se.arm(),Ce.arm(),S.arm()},close(e){let t=[[`journalTurns close`,()=>y.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>de.close()],[`frameFeeds close`,()=>me.close()],[`linkIds close`,()=>pe.close()],[`menuIdle dispose`,()=>se.dispose()],[`updateWatch close`,()=>Ce.close()],[`binaryWatch close`,()=>Se.close()],[`limits disarm`,()=>S.disarm()],[`recorder close`,()=>be.close()],[`renderCache close`,()=>ye.close()],[`gitService close`,()=>k.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>A.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>le.close()],[`sourceRuns close`,()=>te.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>D.close()],[`watcherRegistry close`,()=>E.closeAll()],[`sessionState close`,()=>b.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function koe(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 Aoe=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=m.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return koe(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.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=Qe(this.clock,n);try{await m.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await m.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 m.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await m.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Qe(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{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);m.writeFileSync(n,r,{mode:384}),m.chmodSync(n,384),m.rmSync(this.writingPath,{force:!0}),m.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,Qe(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=${Qe(this.clock,n)}ms held=${r}ms`)}};function joe(e,t,n){return{session:new Aoe(e.sessionState,n,500,t),history:j0(e.settingsHistory,e.storedRoot,t)}}function $7(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function e9(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Moe(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Noe(e,t,n){let r=$7(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.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 t9=2e3;async function n9(e,t,n,r){let i=await Xs(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function r9(e,t){if(t.ok)return t.stdout;let n=mt(t,t.stdout);throw Error(`${e} failed (${j(t)}${n===``?``:`: ${n}`})`)}function Poe(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 Foe=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Ioe(e,t){return e.split(`
|
|
508
508
|
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return Foe.exec(r.join(` `))?.[1]===t?[n]:[]})}const Loe=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Roe(e,t,n){for(let r of q0(K0(e),t)){if(r.command.split(` `).some(e=>Loe.test(e)))return!0;if(r.pid===n)return!1}return!1}const zoe=[`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(`
|
|
509
509
|
`);async function Boe(e,t){if(process.platform===`linux`)return{executable:await m.promises.readlink(`/proc/${t}/exe`),argv:(await m.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await m.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=r9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,zoe,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function i9(e,t,n){return r9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function a9(e,t){let n=await Xs(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 i9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Voe(e,t){let{panePid:n,cwd:r,foreground:i}=await a9(e,t),a=await i9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Boe(e,i),s=K0(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);let c=en(i,await Qt(i,t=>e.launch(t)));if(c.startTime===null)throw Error(`the start of pane ${t.pane}'s foreground job ${i} could not be read (${c.why})`);return{pid:i,startTime:c.startTime,executable:await m.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:Roe(a,i,n)}}function Hoe(e,t){let n=o9(e,t);return n.torn?o9(e,t).held:n.held}function o9(e,t){let n;try{n=m.readFileSync(e,`utf8`)}catch(t){return{torn:!1,held:t.code===`ENOENT`?{kind:`none`,why:`it keeps no session record at ${e} (update Claude Code with \`claude update\`: recent releases keep one)`}:{kind:`unread`,why:t.message}}}let r;try{r=JSON.parse(n)}catch(t){return{torn:!0,held:{kind:`unread`,why:`its session record ${e} is not JSON (${t.message})`}}}let{sessionId:i,procStart:a}=typeof r==`object`&&r?r:{},o=Xt(a);return{torn:!1,held:typeof i!=`string`||i===``?{kind:`unread`,why:`its session record ${e} names no session`}:a===void 0?{kind:`unread`,why:`its session record ${e} names no process start (update Claude Code with \`claude update\`: recent releases name one)`}:o===void 0?{kind:`unread`,why:`its session record ${e} names its process start as ${JSON.stringify(a)}, not in the form \`ps -o lstart=\` prints it`}:o===t.startTime?{kind:`holds`,sessionId:i}:{kind:`none`,why:`its session record ${e} was left by a Claude Code that has exited: the record names a process started ${o}, and pid ${t.pid} is a process started ${t.startTime}`}}}const Uoe=e=>t=>Hoe(s.join(Lo(t.configDir,e),`sessions`,`${t.pid}.json`),t);function Woe(e,t,n,r,i,a){let o=e=>et(r,e,n);return{claudeInput:$Q(e),barPanes:async t=>Ioe(await n9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await n9(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 n9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void r9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:N0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>m.existsSync(e),presence:Hz,paneClaude:t=>Voe(e,t),heldSession:a,paneDir:async(t,n)=>{let i=r.monotonic()+t9;for(;;){let a=await a9(e,t);if(a.foreground===n){if(a.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return a.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${t9/1e3} s`);await o(100)}},launcherNode:e=>Noe(e,e=>e9(e,m.constants.X_OK),Moe),onPath:(e,t)=>{let n=$7(e,t,e=>e9(e,m.constants.X_OK));return n===null?null:m.realpathSync(n)},followed:async(e,n,i)=>{let a=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>a)return!1;await o(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`?Poe(i.stdout):null;return a===null?(r9(`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 o(100)}return!0},typeShellLine:async(t,n)=>void await n9(e,t,ZQ(t.pane,`cc-candybar-lane`,[]),n)}}const Goe=/^[0-9a-f]{64}$/;function s9(e,t){return le(`sha256`,e).update(JSON.stringify(t)).digest()}const c9=e=>[e.sessionId,e.action,e.declaration,e.evaluated],l9=e=>[ZS,e];function Koe(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=t=>s9(e,t).toString(`hex`),n=(t,n)=>Goe.test(n)&&fe(Buffer.from(n,`hex`),s9(e,t));return{sign:e=>t(c9(e)),verify:(e,t)=>n(c9(e),t),signBinding:e=>t(l9(e)),verifyBinding:(e,t)=>n(l9(e),t)}}function u9(e){return s.join(e,`link.key`)}function d9(e){let t,n=()=>t??=qoe(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t),signBinding:e=>n().signBinding(e),verifyBinding:(e,t)=>n().verifyBinding(e,t)}}function qoe(e){let t;try{t=m.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Joe(e),t=m.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 Koe(t)}function Joe(e){m.mkdirSync(s.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ue(6).toString(`hex`)}`;m.writeFileSync(t,ue(32),{mode:384,flag:`wx`});try{m.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{m.unlinkSync(t)}}function Yoe(e,t,n){return{daemonLog:t,launcher:e=>dn(e,n),storage:t=>joe(e,t,n),doctorStores:p4(e.state),doctorEdge:T4,claudeInput:$Q,probe:nn,laneEdge:(e,t,r,i,a)=>Woe(e,t,r,n,i,a),heldSession:Uoe,linkSigner:d9(u9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Hi(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>rie({...e,clock:n}),filesystem:Un}}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 Xoe(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`);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(Kr(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),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,yQ)}),u=Jr(r=>{let i=Vr(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{c&&(e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):e.kind===`subscribe`?d(e.sessionId,e.lane):f(e.start))}).catch(t=>{e.log(`error`,`handler threw: ${O(t)}`),c&&o(bQ(t),null,yQ)}).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,yQ)}),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=>o(qr(e.json)),refused:e=>t.end(Kr(e)),drawing:()=>!0});r=!0,t.on(`close`,s)},f=n=>{if(r||t.destroyed)return;l(),t.off(`data`,u);let i=new AbortController;t.on(`close`,()=>i.abort()),n(i.signal).then(e=>o(e.resp,e.exitAfterFlush,e.delivered),t=>{e.log(`error`,`held request threw: ${O(t)}`),o(bQ(t),null,yQ)})};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 Zoe(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 Qoe(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 $oe(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:Fn(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function ese(e){let n=fr(e.home);_9={world:e,paths:n,log:new Ks(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)});tse().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${O(e)}`),C9(1)}async function tse(){let{world:e,paths:n,log:r}=v9(),{host:i,home:a}=e,o=Oi(i.env);a.kind===`main`&&a.legacySocket!==null&&y9(`warn`,`CC_CANDYBAR_SOCKET=${a.legacySocket} is honoured for one more release; a renderer is named by CC_CANDYBAR_HOME and CC_CANDYBAR_NAME instead`),m9=await an(t.pid,nn(e.launcher).startTime);let s=await Is(Rs(e,m9,ar(i),n.socket!==Zn(Le)));if(!s.decision.allow){y9(`warn`,`fork-bomb breaker: ${s.decision.reason}; refusing to boot`),C9(1);return}h9=s.registryPath,m.mkdirSync(n.state,{recursive:!0}),er(n.socket);let c=Ooe({...Yoe(n,r,e.clock),bundle:$oe(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Vz(),exit:C9});g9=c,Qoe({clock:e.clock,anchor:Zoe(i.env),probe:nn(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,ie.createServer(e=>Xoe(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}nse(e,n,r).catch(b9)}),n.listen(r,()=>rse(e,r))}async function nse(e,n,r){let i=await Ds(Os(tr(r)),(t,n)=>rn(t,n,nn(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{m.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 rse(e,n){let r=js(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}ase(n);try{m.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Di(pe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Di(e.memoryLimitBytes)}MB`),Ji(v9().paths.spawnBackoff),e.arm(),ise(n,r.identity)}function ise(e,n){vee({bound:n,myPid:t.pid,readIdentity:()=>js(e),readLease:()=>Os(tr(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function ase(e){let n=ks(tr(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const ose=e=>(t,n)=>Ys(e,{socket:t},`tmux-status`,n);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(ose(v9().world.launcher)),As(v9().paths.lease,t.pid),h9!==null&&Ls(h9,t.pid,Ps,e=>m.unlinkSync(e)),t.exit(e))}function sse(e,t){let n=[],r=10;for(let t=0;t<e.length;t++){let i=e[t];if(i===`--seconds`){let n=e[++t];if(n===void 0)return{ok:!1,problem:`--seconds needs a number after it`};let i=Ur(Number(n));if(!i.ok)return{ok:!1,problem:`--seconds ${JSON.stringify(n)} ${i.problem}`};r=i.seconds}else if(i!==void 0&&!i.startsWith(`-`))n.push(i);else return{ok:!1,problem:`unexpected argument ${JSON.stringify(i)}`}}let[i,a,...o]=n;return i===void 0||a===void 0||o.length>0?{ok:!1,problem:`usage: cc-candybar record <session-id> <path> [--seconds N]`}:{ok:!0,args:{session:i,path:f(t,a),seconds:r}}}function cse(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${ii(e)}\n`,code:1};let{path:n,lines:r,answers:i,frames:a,daemonClosed:o}=e.value,s=`the daemon closed before ${t}s ran out`;return i+a===0?{stdout:``,stderr:o?`record: ${n}: ${s}, and nothing had been drawn, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered and no lane drew a frame in ${t}s, so there is nothing to replay: the session was idle, or its bar is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers, ${a} lane frames\n`,stderr:o?`record: ${s}: the file holds what came before.\n`:``,code:0}}async function lse(e,t,n){let r=sse(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return cse(await Zr(e,()=>({kind:`record`,session:i,path:a,seconds:o}),{connectMs:200,budgetMs:o*1e3+2e3},e=>`recorded`in e?e.recorded:void 0),o)}const use={connectMs:200,budgetMs:500};async function dse(e,t,n){return fse(t,await pse(e,t),n.includes(`--json`))}function fse(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
510
510
|
`:mse(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${ii(t)}\n`,code:1}}function pse(e,t){return Zr(e,()=>({kind:`debug`,what:t}),use,e=>`debug`in e?e.debug:void 0)}function mse(e){switch(e.what){case`vars`:return hse(e.vars);case`segments`:return gse(e.segments);case`config`:return _se(e.config);default:return e}}function hse(e){if(e.length===0)return`no variables (DSL not active)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptctl/cc-candybar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.209.0",
|
|
4
4
|
"description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -110,9 +110,9 @@
|
|
|
110
110
|
"yaml": "^2.9.1"
|
|
111
111
|
},
|
|
112
112
|
"optionalDependencies": {
|
|
113
|
-
"@promptctl/cc-candybar-darwin-arm64": "1.
|
|
114
|
-
"@promptctl/cc-candybar-darwin-x64": "1.
|
|
115
|
-
"@promptctl/cc-candybar-linux-arm64": "1.
|
|
116
|
-
"@promptctl/cc-candybar-linux-x64": "1.
|
|
113
|
+
"@promptctl/cc-candybar-darwin-arm64": "1.209.0",
|
|
114
|
+
"@promptctl/cc-candybar-darwin-x64": "1.209.0",
|
|
115
|
+
"@promptctl/cc-candybar-linux-arm64": "1.209.0",
|
|
116
|
+
"@promptctl/cc-candybar-linux-x64": "1.209.0"
|
|
117
117
|
}
|
|
118
118
|
}
|