@promptctl/cc-candybar 1.225.0 → 1.225.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +3 -3
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire}from"node:module";import process$1 from"node:process";import{URL as URL$1,URLSearchParams,fileURLToPath}from"node:url";import{json}from"node:stream/consumers";import os from"node:os";import fs,{closeSync,constants,existsSync,fstatSync,linkSync,mkdtempSync,openSync,readFileSync,readSync,rmSync,statSync,writeFileSync}from"node:fs";import{StringDecoder}from"node:string_decoder";import{inspect,parseArgs,types}from"node:util";import{clearImmediate,setImmediate}from"node:timers";import{spawn,spawnSync}from"node:child_process";import path,{basename,dirname,isAbsolute,join,sep}from"node:path";import crypto,{createHash,createHmac,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import net from"node:net";import v8 from"node:v8";import{open,readFile,readdir,stat}from"node:fs/promises";import{get}from"node:https";import{WriteStream}from"node:tty";import{createInterface}from"node:readline";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=__getOwnPropNames(t),a=0,o=i.length,s;a<o;a++)s=i[a],!__hasOwnProp.call(e,s)&&s!==n&&__defProp(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(n,`default`,{value:e,enumerable:!0}):n,e));let debugEnabled=!1;const debugOn=()=>debugEnabled;function setDebug(e){debugEnabled=e}function debugText(e){return debugOn()?`[DEBUG] ${e()}\n`:``}function debug(e,...t){debugOn()&&console.error(`[DEBUG] ${e}`,...t)}function changeLogger(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const quietLogger=(e,t)=>debug(t);function spanMs(e,t){return Math.round(t-e)}function elapsedMs(e,t){return spanMs(t,e.monotonic())}const systemTimekeeper={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=setImmediate(e);return()=>clearImmediate(t)}};function sleep(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 timeoutSignal(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 eventHoldAt(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function joinedEvent(e,t,n){return{text:e===null||e.answered?t:`${e.text}\n${t}`,at:n,answered:!1}}function answeredBy(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const instantOf=e=>e.getTime()/1e3,dateOf=e=>new Date(e*1e3),instantAt=e=>instantOf(new Date(e.now()));function spawnErrorText(e,t){return types.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!existsSync(t)?`working directory does not exist: ${t}`:e.message:String(e)}const RATE_LIMITS={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function checkRateLimit(e,t,n){let r=RATE_LIMITS[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 childEnv(e,t){let n={...e.inherited};for(let[e,r]of Object.entries(t.envOverlay??{}))n[e]=r??void 0;return n}const refusedAsAborted=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function rateLimitedResult(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 track(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function admit(e,t,n){let r=refusalOf$2(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function refusalOf$2(e,t,n){if(e.scope.signal.aborted)return refusedAsAborted(e.scope.signal);if(n?.aborted)return refusedAsAborted(n);let r=checkRateLimit(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:rateLimitedResult(t,r.minIntervalMs,r.sinceLastMs)}const TIMEOUT_KILL_GRACE_MS=250,GROUP_END_POLL_MIN_MS=25,GROUP_END_POLL_MAX_MS=1e3,LIFELINE_PROGRAM=`\$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 ${TIMEOUT_KILL_GRACE_MS/1e3}; kill -KILL" groups " 2>/dev/null") }`;function setFault(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function lose(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),setFault(e,n))}const lifelineMessage=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,pipeEventWords=e=>e===`cut`?`output cut at the ${MAX_CAPTURED_BYTES}-byte bound, so the program holding it now fails its writes`:`output failed to read`,PIPE_EVENT_LEAD=`a launched program's pipe outlived its launch: `;function pipeEvent(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:`${PIPE_EVENT_LEAD}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${pipeEventWords(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${PIPE_EVENT_LEAD}${n} ${pipeEventWords(t)}`})}function answeredPipeEvent(e,t){let n=e.pipeEvent;n===null||!answeredBy(n,t)||(e.pipeEvent={...n,answered:!0})}function standing(e){let t=e.pipeEvent;return[...e.fault===null?[]:[{kind:`lifeline`,message:lifelineMessage(e.fault)}],...t===null?[]:[{kind:`launch-pipes`,event:{text:t.text,at:t.at,answered:t.answered}}]]}function spawnLifeline(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[LIFELINE_PROGRAM],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,elapsedMs(n,r)),setFault(e,`did not start: ${spawnErrorText(i,void 0)}`),null}t?.onEnd(`lifeline`,elapsedMs(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>setFault(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&setFault(e,null)}),i.once(`error`,t=>lose(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>lose(e,i,`exited ${n??t}`)),a.on(`error`,t=>lose(e,i,`pipe failed: ${t.message}`)),track(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 guard(e,t){e.liveGroups.add(t),e.lifeline??=spawnLifeline(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function unguard(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function endLifeline(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const MAX_CAPTURED_BYTES=16*1024*1024,OUTPUT_LIMIT_ERROR=`output exceeded ${MAX_CAPTURED_BYTES} bytes`,timedOutError=e=>`timed out after ${e/1e3} s`;function capture(e,t,n,r){let{stats:i}=e.scope,a=new StringDecoder(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?pipeEvent(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(),pipeEvent(e,`cut`,t);return}let d=Math.max(0,MAX_CAPTURED_BYTES-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||hold(e,t,n,()=>u)}}}function hold(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 inputEnd=()=>`closed`;function feed(e,t){e.on(`error`,()=>{}),e.end(t)}const captured=e=>({read:(e,t,n,r)=>capture(e,t,n,r),opened:t=>{t!==null&&feed(t,e)}});function relay(e,t,n,r,i){let a=new StringDecoder(`utf8`);return n?.on(`error`,n=>{e.scope.stats?.onPipeError(t),r.failed(n)}),n?.on(`data`,e=>{let t=a.write(e);t!==``&&i(t)}),{take:()=>{let e=a.end();return e!==``&&i(e),``},drain:()=>{n===null||n.destroyed||n.readableEnded||hold(e,t,n,()=>`closed`)}}}function launchChannel(e,t){let n=null,r=null;return{get pid(){return r},write:e=>{n!==null&&!n.writableEnded&&!n.destroyed&&n.write(e)},end:()=>{n?.end()},ended:track(e,launchPiped(e,t,{read:(e,n,r,i,a)=>relay(e,n,r,i,t.heard[a]),opened:(e,t)=>{n=e,r=t,e?.on(`error`,()=>{})}}))}}function launchWaited(e,t){return launchPiped(e,t,captured(t.stdinInput))}async function launchPiped(e,t,n){let{stats:r,clock:i}=e.scope,a=admit(e,t.category,t.signal);if(a!==null)return a;let o=i.monotonic();return r?.onStart(t.category),new Promise(a=>{let{spawner:s}=e,c;try{c=s.spawn(t.bin,t.args??[],{cwd:t.cwd,env:childEnv(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){r?.onEnd(t.category,elapsedMs(i,o)),a({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)});return}let l=c.pid;l!==void 0&&guard(e,l);let u=new Promise(e=>c.once(`exit`,e)),d=c.stdin;c.stdin=null;let f=null,p={full:()=>O(`output-limit`),failed:e=>{f??=e.message,O(`pipe-error`)}},m=n.read(e,t.category,c.stdout,p,`stdout`),h=n.read(e,t.category,c.stderr,p,`stderr`),g=()=>({stdout:m.take(),stderr:h.take()}),_=!1,v=null,y=null,b=null,x=null,S=()=>O(`aborted`),C=()=>{t.signal?.removeEventListener(`abort`,S),e.inFlight.delete(S)},w=n=>{_||(_=!0,v?.(),y?.(),b?.(),C(),l!==void 0&&unguard(e,l),r?.onEnd(t.category,elapsedMs(i,o)),c.off(`close`,A),c.off(`error`,k),m.drain(),h.drain(),d!==null&&!d.destroyed&&!d.writableFinished&&hold(e,t.category,d,inputEnd),n())},T=e=>w(()=>a(e)),E=(n,r)=>{try{s.signalGroup(n,r)}catch(n){e.unreaped.set(c,t.category),u.then(()=>e.unreaped.delete(c)),T({ok:!1,reason:`signal-refused`,...g(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},D=()=>A(c.exitCode,c.signalCode);if(l!==void 0){let e=t=>{if(!_){if(s.groupGone(l)){i.defer(D);return}b=i.after(t,()=>e(Math.min(t*2,GROUP_END_POLL_MAX_MS)))}};u.then(()=>i.defer(()=>e(GROUP_END_POLL_MIN_MS)))}let O=e=>{if(x!==null)return;if((c.exitCode!==null||c.signalCode!==null)&&l!==void 0&&s.groupGone(l)){x=e===`timeout`?null:e,i.defer(D);return}x=e,v?.(),C();let t=c.pid;t!==void 0&&(y=i.after(TIMEOUT_KILL_GRACE_MS,()=>{E(t,`SIGKILL`),u.then(()=>i.defer(D))}),E(t,`SIGTERM`))},k=e=>{T({ok:!1,reason:`spawn-error`,...g(),exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)})};c.on(`error`,k);let A=(e,n)=>{if(x!==null){T({ok:!1,reason:x,...g(),exitCode:e,signal:n,...x===`timeout`?{error:timedOutError(t.timeoutMs??0)}:x===`output-limit`?{error:OUTPUT_LIMIT_ERROR}:x===`pipe-error`?{error:`a pipe failed to read: ${f}`}:{}});return}if(e===0){T({ok:!0,...g(),exitCode:e});return}T({ok:!1,reason:n?`signal`:`non-zero`,...g(),exitCode:e,signal:n})};c.on(`close`,A),t.timeoutMs&&t.timeoutMs>0&&(v=i.after(t.timeoutMs,()=>O(`timeout`))),t.signal?.addEventListener(`abort`,S,{once:!0}),e.inFlight.add(S),n.opened(d,l??null)})}function launchBlocking(e,t){let{stats:n,clock:r}=e.scope,i=admit(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:childEnv(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,elapsedMs(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`?timedOutError(t.timeoutMs??0):spawnErrorText(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,elapsedMs(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)}}}function launchOrphan(e,t){let{stats:n,clock:r}=e.scope,i=admit(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=launchDetachedSyncInner(e,t);return n?.onEnd(t.category,elapsedMs(r,a)),o}function launchDetachedSyncInner(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:childEnv(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(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 formatJobEnd=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`,JOB_SCRIPT=`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.$$"`;function launchJob(e,t,n){let{stats:r,clock:i}=e.scope,a=admit(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`,JOB_SCRIPT,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:childEnv(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,elapsedMs(i,o)),{ok:!1,reason:`spawn-error`,error:spawnErrorText(e,t.cwd)}}r?.onEnd(t.category,elapsedMs(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
3
3
  `),withdraw:()=>l.end()})}function readJobEnd(e){let t;try{t=readFileSync(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 endJob(e,t,n,r,i){let a=`${r}.${process.pid}`;try{writeFileSync(a,`${formatJobEnd(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{linkSync(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{rmSync(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(TIMEOUT_KILL_GRACE_MS,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function createLauncher(e,t,n){return launcherWithState(e,t,n).launcher}function createOneShotLauncher(e,t,n){let{launcher:r,state:i}=launcherWithState(e,t,n);return{...r,launchSync:e=>launchBlocking(i,e)}}function launcherWithState(e,t,n){let r={clock:t,launch:e=>track(i,launchWaited(i,e)),launchChannel:e=>launchChannel(i,e),launchDetachedSync:e=>launchOrphan(i,e),launchJobSync:(e,t)=>launchJob(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>endJob(n,t,e,r,i),standing:()=>standing(i),answeredPipeEvent:e=>answeredPipeEvent(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&&lose(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:lifelineMessage(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>instantOf(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()),endLifeline(i)},{once:!0}),{launcher:r,state:i}}function leaderRefuses(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const systemSpawner={spawn:(e,t,n)=>spawn(e,t,n),spawnSync:(e,t,n)=>spawnSync(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!leaderRefuses(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}}},systemLauncher=(e,t)=>createLauncher(e,t,systemSpawner),systemOneShotLauncher=(e,t)=>createOneShotLauncher(e,t,systemSpawner);function processWorld(){let e={env:process.env,home:os.homedir(),tmp:os.tmpdir()},t=systemTimekeeper;return{host:e,launcher:systemOneShotLauncher({inherited:process.env},t),clock:t}}function whyFailed(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 SAID_LINE_CHARS=200,clipped=e=>{let t=[];for(let n of e){if(t.length===SAID_LINE_CHARS)return`${t.join(``)}…`;t.push(n)}return e};function saidBy(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 clipped(n);let i=Math.max(n.lastIndexOf(`
4
- `),n.lastIndexOf(`\r`))+1;return`${clipped(n.slice(0,r).trim())} … ${clipped(n.slice(i).trim())}`}function failureText(e,t=``){let n=saidBy(e,e.stderr);return`${whyFailed(e)}${t}${n===``?``:`: ${n}`}`}function launcherWarningsAt(e,t,n){return e.flatMap(e=>{if(e.kind===`lifeline`)return[e];let r=eventHoldAt(e.event,60,t,n);return r===`over`?[]:[{...e,message:e.event.text,hold:r}]})}const SHELL_SAFE=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function singleQuoted(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function shellWord(e){return SHELL_SAFE.test(e)?e:singleQuoted(e)}function claudeCommandLine(e){return`${e.dir===void 0?``:`cd ${shellWord(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${shellWord(t)} `).join(``)}${[e.program,...e.args].map(shellWord).join(` `)}`}const ATTACH_DIR=`cc-extra`;function attachLauncherOf(e){return path.join(path.dirname(e),ATTACH_DIR,`src`,`bun-attach.js`)}function moduleGraphReaderOf(e){return path.join(path.dirname(e),`bun-graph.js`)}const ATTACH_PRELOAD=`attach-preload.cjs`;function attachPreloadOf(e){return path.join(path.dirname(e),ATTACH_PRELOAD)}const PRELOAD_VARIABLE=`BUN_OPTIONS`;function attachCommandLine(e,t){return claudeCommandLine({...t,env:[...t.env,[PRELOAD_VARIABLE,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const isSourceEntry=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function entryBytes(e,t){return t.isSymbolicLink()?Buffer.from(fs.readlinkSync(e)):fs.readFileSync(e)}function sourceEntries(e,t,n=isSourceEntry){return fs.readdirSync(t).filter(n).sort().flatMap(n=>{let r=path.join(t,n),i=fs.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?sourceEntries(e,r):[[path.relative(e,r).split(path.sep).join(`/`),entryBytes(r,i)]]})}function digestOf$1(e){let t=crypto.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function sourceDigest(e){return digestOf$1(sourceEntries(e,e))}const CRATE_SOURCE=[`Cargo.toml`,`Cargo.lock`,`src`];function crateDigest(e){return digestOf$1(sourceEntries(e,e,e=>CRATE_SOURCE.includes(e)))}const PACKAGE_VERSION=`1.225.0`;function sourceCheckoutOf(e){let t=path.dirname(path.dirname(e));return fs.existsSync(path.join(t,`src`))?t:null}function bundleStamp(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:PACKAGE_VERSION,digest:e}}function bakedDigest(){return`203b515ee34809f7686ade79401c534738cd6b6a420eb1a19e3318aa575e99c8`}function checkoutVersion(e){let t=JSON.parse(fs.readFileSync(path.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${path.join(e,`package.json`)} has no version string`);return n}function assessBuild(e,t){try{let n=sourceCheckoutOf(fileURLToPath(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),i=sourceDigest(path.join(n,`src`));return i===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:checkoutVersion(n),digest:i},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function xdgEnv(e,t){let n=e[t];return n&&n.length>0?n:void 0}function stateDir(e){let t=xdgEnv(e.env,`XDG_STATE_HOME`)??path.join(e.home,`.local`,`state`);return path.join(t,`cc-candybar`)}function cacheDir(e){let t=xdgEnv(e.env,`XDG_CACHE_HOME`)??path.join(e.home,`.cache`);return path.join(t,`cc-candybar`)}function daemonDir(e){return stateDir(e)}function socketPath(e){return e.env.CC_CANDYBAR_SOCKET||defaultSocketPath()}function defaultSocketPath(){let e=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function ensureOwnedPrivateDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});let t=fs.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=os.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function ensureSocketParentSafe(e){ensureOwnedPrivateDir(path.dirname(e));for(let t of[e,leasePathFor(e)])try{if(fs.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function leasePathFor(e){return`${e}.lease`}function leasePath(e){return leasePathFor(socketPath(e))}function sessionStatePath(e){return path.join(stateDir(e),`session-state.json`)}function settingsHistoryPath(e){return path.join(stateDir(e),`settings-history.json`)}function daemonRegistryDir(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function spawnLockPath(e){return path.join(stateDir(e),`spawn.lock`)}const SPAWN_COOLDOWN_FILE=`spawn.cooldown`;function spawnCooldownPath(e){return path.join(stateDir(e),SPAWN_COOLDOWN_FILE)}const SPAWN_BACKOFF_FILE=`spawn.backoff`;function spawnBackoffPath(e){return path.join(stateDir(e),SPAWN_BACKOFF_FILE)}function watchProbeDir(e){return path.join(stateDir(e),`watch-probe`)}function logPath(e){return path.join(stateDir(e),`daemon.log`)}function daemonPaths(e){return{socket:socketPath(e),lease:leasePath(e),state:stateDir(e),registry:daemonRegistryDir(e),log:logPath(e),sessionState:sessionStatePath(e),settingsHistory:settingsHistoryPath(e),watchProbe:watchProbeDir(e),spawnBackoff:spawnBackoffPath(e)}}function locations(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${path.join(xdgEnv(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:xdgEnv(t,`XDG_CONFIG_HOME`)??path.join(e.home,`.config`),dataHome:xdgEnv(t,`XDG_DATA_HOME`)??path.join(e.home,`.local`,`share`),dataDirs:(xdgEnv(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function writeAtomic(e,t,n){let r=resolvedTarget(e);fs.mkdirSync(path.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??fs.statSync(r,{throwIfNoEntry:!1})?.mode;try{fs.writeFileSync(i,t,a===void 0?{}:{mode:a}),fs.renameSync(i,r)}catch(e){throw fs.rmSync(i,{force:!0}),e}}function readConfigText(e){try{return fs.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function resolvedTarget(e){return linkChain(e).at(-1)}function linkChain(e){let{hops:t,stopped:n}=walkLinks(e);if(n!==null)throw n;return t}function walkLinks(e){let t=[e];try{for(let e=0;e<MAX_LINK_HOPS;e++){let e=linkTarget(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${MAX_LINK_HOPS} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function linkTarget(e){try{return fs.lstatSync(e).isSymbolicLink()?path.resolve(fs.realpathSync(path.dirname(e)),fs.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const MAX_LINK_HOPS=40,TERMINAL_ENV_VARS=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function detectTerminalEnv(e){return Object.fromEntries(TERMINAL_ENV_VARS.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const CLIENT_KINDS=[`native`,`node`,`frames`];function nodeClientHint(e,t){return{kind:e,bundle:t,source:null}}const RENDER_ENCODINGS=[`ansi`,`frame`],CLIENT_HINT_FIELDS=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function parseClientHints(e){let t=sanitizeTermExtent(e.termCols),n=sanitizeTermExtent(e.termRows),r=sanitizeSsh(e.ssh),i=sanitizeTmux(e.tmux),a=sanitizeAbsolutePath(e.configEnv),o=sanitizeAbsolutePath(e.claudeConfigDir),s=sanitizeTerminalEnv(e.terminalEnv),c=sanitizeClient(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function refusedHints(e,t){return CLIENT_HINT_FIELDS.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function refusedHintsError(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 REFUSAL_LINES={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function refusedArgsError(e){let t=Object.keys(REFUSAL_LINES).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[REFUSAL_LINES[t](n.join(`, `))]});return t.length===0?null:t.join(`
4
+ `),n.lastIndexOf(`\r`))+1;return`${clipped(n.slice(0,r).trim())} … ${clipped(n.slice(i).trim())}`}function failureText(e,t=``){let n=saidBy(e,e.stderr);return`${whyFailed(e)}${t}${n===``?``:`: ${n}`}`}function launcherWarningsAt(e,t,n){return e.flatMap(e=>{if(e.kind===`lifeline`)return[e];let r=eventHoldAt(e.event,60,t,n);return r===`over`?[]:[{...e,message:e.event.text,hold:r}]})}const SHELL_SAFE=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function singleQuoted(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function shellWord(e){return SHELL_SAFE.test(e)?e:singleQuoted(e)}function claudeCommandLine(e){return`${e.dir===void 0?``:`cd ${shellWord(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${shellWord(t)} `).join(``)}${[e.program,...e.args].map(shellWord).join(` `)}`}const ATTACH_DIR=`cc-extra`;function attachLauncherOf(e){return path.join(path.dirname(e),ATTACH_DIR,`src`,`bun-attach.js`)}function moduleGraphReaderOf(e){return path.join(path.dirname(e),`bun-graph.js`)}const ATTACH_PRELOAD=`attach-preload.cjs`;function attachPreloadOf(e){return path.join(path.dirname(e),ATTACH_PRELOAD)}const PRELOAD_VARIABLE=`BUN_OPTIONS`;function attachCommandLine(e,t){return claudeCommandLine({...t,env:[...t.env,[PRELOAD_VARIABLE,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const isSourceEntry=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function entryBytes(e,t){return t.isSymbolicLink()?Buffer.from(fs.readlinkSync(e)):fs.readFileSync(e)}function sourceEntries(e,t,n=isSourceEntry){return fs.readdirSync(t).filter(n).sort().flatMap(n=>{let r=path.join(t,n),i=fs.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?sourceEntries(e,r):[[path.relative(e,r).split(path.sep).join(`/`),entryBytes(r,i)]]})}function digestOf$1(e){let t=crypto.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function sourceDigest(e){return digestOf$1(sourceEntries(e,e))}const CRATE_SOURCE=[`Cargo.toml`,`Cargo.lock`,`src`];function crateDigest(e){return digestOf$1(sourceEntries(e,e,e=>CRATE_SOURCE.includes(e)))}const PACKAGE_VERSION=`1.225.1`;function sourceCheckoutOf(e){let t=path.dirname(path.dirname(e));return fs.existsSync(path.join(t,`src`))?t:null}function bundleStamp(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:PACKAGE_VERSION,digest:e}}function bakedDigest(){return`d53af89220dc79d7347c75f59c137982fc6666ff07b47c4a897fa47980ec3447`}function checkoutVersion(e){let t=JSON.parse(fs.readFileSync(path.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${path.join(e,`package.json`)} has no version string`);return n}function assessBuild(e,t){try{let n=sourceCheckoutOf(fileURLToPath(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),i=sourceDigest(path.join(n,`src`));return i===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:checkoutVersion(n),digest:i},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function xdgEnv(e,t){let n=e[t];return n&&n.length>0?n:void 0}function stateDir(e){let t=xdgEnv(e.env,`XDG_STATE_HOME`)??path.join(e.home,`.local`,`state`);return path.join(t,`cc-candybar`)}function cacheDir(e){let t=xdgEnv(e.env,`XDG_CACHE_HOME`)??path.join(e.home,`.cache`);return path.join(t,`cc-candybar`)}function daemonDir(e){return stateDir(e)}function socketPath(e){return e.env.CC_CANDYBAR_SOCKET||defaultSocketPath()}function defaultSocketPath(){let e=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function ensureOwnedPrivateDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});let t=fs.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=os.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function ensureSocketParentSafe(e){ensureOwnedPrivateDir(path.dirname(e));for(let t of[e,leasePathFor(e)])try{if(fs.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function leasePathFor(e){return`${e}.lease`}function leasePath(e){return leasePathFor(socketPath(e))}function sessionStatePath(e){return path.join(stateDir(e),`session-state.json`)}function settingsHistoryPath(e){return path.join(stateDir(e),`settings-history.json`)}function daemonRegistryDir(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function spawnLockPath(e){return path.join(stateDir(e),`spawn.lock`)}const SPAWN_COOLDOWN_FILE=`spawn.cooldown`;function spawnCooldownPath(e){return path.join(stateDir(e),SPAWN_COOLDOWN_FILE)}const SPAWN_BACKOFF_FILE=`spawn.backoff`;function spawnBackoffPath(e){return path.join(stateDir(e),SPAWN_BACKOFF_FILE)}function watchProbeDir(e){return path.join(stateDir(e),`watch-probe`)}function logPath(e){return path.join(stateDir(e),`daemon.log`)}function daemonPaths(e){return{socket:socketPath(e),lease:leasePath(e),state:stateDir(e),registry:daemonRegistryDir(e),log:logPath(e),sessionState:sessionStatePath(e),settingsHistory:settingsHistoryPath(e),watchProbe:watchProbeDir(e),spawnBackoff:spawnBackoffPath(e)}}function locations(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${path.join(xdgEnv(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:xdgEnv(t,`XDG_CONFIG_HOME`)??path.join(e.home,`.config`),dataHome:xdgEnv(t,`XDG_DATA_HOME`)??path.join(e.home,`.local`,`share`),dataDirs:(xdgEnv(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function writeAtomic(e,t,n){let r=resolvedTarget(e);fs.mkdirSync(path.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??fs.statSync(r,{throwIfNoEntry:!1})?.mode;try{fs.writeFileSync(i,t,a===void 0?{}:{mode:a}),fs.renameSync(i,r)}catch(e){throw fs.rmSync(i,{force:!0}),e}}function readConfigText(e){try{return fs.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function resolvedTarget(e){return linkChain(e).at(-1)}function linkChain(e){let{hops:t,stopped:n}=walkLinks(e);if(n!==null)throw n;return t}function walkLinks(e){let t=[e];try{for(let e=0;e<MAX_LINK_HOPS;e++){let e=linkTarget(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${MAX_LINK_HOPS} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function linkTarget(e){try{return fs.lstatSync(e).isSymbolicLink()?path.resolve(fs.realpathSync(path.dirname(e)),fs.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const MAX_LINK_HOPS=40,TERMINAL_ENV_VARS=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function detectTerminalEnv(e){return Object.fromEntries(TERMINAL_ENV_VARS.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const CLIENT_KINDS=[`native`,`node`,`frames`];function nodeClientHint(e,t){return{kind:e,bundle:t,source:null}}const RENDER_ENCODINGS=[`ansi`,`frame`],CLIENT_HINT_FIELDS=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function parseClientHints(e){let t=sanitizeTermExtent(e.termCols),n=sanitizeTermExtent(e.termRows),r=sanitizeSsh(e.ssh),i=sanitizeTmux(e.tmux),a=sanitizeAbsolutePath(e.configEnv),o=sanitizeAbsolutePath(e.claudeConfigDir),s=sanitizeTerminalEnv(e.terminalEnv),c=sanitizeClient(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function refusedHints(e,t){return CLIENT_HINT_FIELDS.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function refusedHintsError(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 REFUSAL_LINES={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function refusedArgsError(e){let t=Object.keys(REFUSAL_LINES).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[REFUSAL_LINES[t](n.join(`, `))]});return t.length===0?null:t.join(`
5
5
  `)}function sanitizeTerminalEnv(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=TERMINAL_ENV_VARS.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 sanitizeAbsolutePath(e){return typeof e==`string`&&path.isAbsolute(e)?e:void 0}function sanitizeTmux(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 MAX_TERM_EXTENT=1e4;function sanitizeTermExtent(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>MAX_TERM_EXTENT?MAX_TERM_EXTENT:t}function sanitizeSsh(e){return typeof e==`boolean`?e:void 0}const URL_FRAME_KIND=`url`,URL_FRAME_VERSION=2,EARLIER_URL_FRAME_VERSIONS=[1],URL_FRAME_VERSIONS=new Set([...EARLIER_URL_FRAME_VERSIONS,2]),awaitsVerdict=e=>typeof e==`number`&&e>=2;function classifyInbound(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}var ProtocolError=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},ClientTimeoutError=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};const FRAME_HEADER_BYTES=4,MAX_FRAME_BYTES=16*1024*1024;function encodeFrame(e){return encodeJsonFrame(JSON.stringify(e))}function encodeJsonFrame(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function makeFrameReader(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 ProtocolError(`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 ProtocolError(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function sendOne(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 ClientTimeoutError(`deadline`))})}),l=makeFrameReader(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(encodeFrame(t))})}function sanitizeClient(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=sanitizeAbsolutePath(n);return CLIENT_KINDS.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function requestOutcome(e,t,n,r){let i;try{i=await connectWithTimeout(socketPath(e.host),n.connectMs,e.clock)}catch(e){return interpretException(e)}return exchangeOutcome(i,e.clock,t,n,r)}async function exchangeOutcome(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await sendOne(e,{v:3,...o},a,t);return interpretResponse(o.kind,s,i)}catch(e){return interpretException(e)}finally{e.destroy()}}function asString(e,t){return typeof e==`string`?e:t}function asProtocolVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function interpretResponse(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=asString(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:asProtocolVersion(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 interpretException(e){if(e instanceof ProtocolError||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 ClientTimeoutError?{kind:`busy`,phase:e.phase,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function connectWithTimeout(e,t,n){return new Promise((r,i)=>{let a=net.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new ClientTimeoutError(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function describeFailure(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}`}}const REQUEST_TIMEOUT_MS=200,DRAW_RESERVE_MS=60;function parseClientDeadline(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 waitBudgetMs(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 RENDER_BUDGETS={connectMs:50,budgetMs:150},CLICK_BUDGETS={connectMs:50,budgetMs:350};function projectOutput(e){let t=e.output;return typeof t==`string`?t:void 0}function renderOutcomeOf(e){return interpretResponse(`render`,e,projectOutput)}function tryRenderViaDaemon(e,t,n,r,i,a=RENDER_BUDGETS){return requestOutcome(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,projectOutput)}function trySessionInPane(e,t,n){return requestOutcome(e,()=>({kind:`pane-session`,socket:t,pane:n}),CLICK_BUDGETS,e=>`paneSession`in e?e.paneSession:void 0)}function tryClickViaDaemon(e,t){return requestOutcome(e,()=>({kind:`click`,url:t}),CLICK_BUDGETS,projectOutput)}const PROBE_TIMEOUT_MS=5e3;async function memoryReport(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
  `)}async function memoryReports(e){return(await Promise.all(e.map(memoryReport))).join(`
7
7
 
@@ -510,10 +510,10 @@ function run(argv) {
510
510
  `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function ownsEntry(e){let t;try{t=fs.realpathSync(e)}catch{return!1}let n=DAEMON_ENTRY.exec(t)?.[1];return n!==void 0&&fs.existsSync(path.join(n,`bin`,`cc-candybar`))}async function daemons(e){let t=await e.launch({bin:`ps`,args:[`-U`,String(os.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});return t.ok?{kind:`ok`,value:daemonProcesses(t.stdout,ownsEntry)}:{kind:`failed`,reason:`ps failed (${failureText(t)})`}}async function probeTmux(e,t){let n=await runTmuxAsync(e,t,`doctor.tmux`,[`display`,`-p`,`-t`,t.pane,TMUX_CLIENT_FORMAT]);return n.kind===`rate-limited`?busy(`tmux`):n.kind===`failed`?{kind:`failed`,reason:n.reason}:parseTmuxClient(n.stdout)}function productionMachineEdge(e,t){return{probeTmux:t=>probeTmux(e,t),remoteLogin:t=>remoteLogin(e,t),fontInUse:(n,r,i)=>fontInUse(e,n,r,i,t.home),daemons:()=>daemons(e),forge:t=>forgeLogin(e,t),transcript:async e=>readTranscriptWindow(e),install:productionInstallEdge}}function productionEdge(e,t,n){return{...productionMachineEdge(e,n),loadConfig:t,home:n.home,managedSettingsDir:claudeManagedSettingsDirIn(n.env)}}function transcriptWindow(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
511
511
  `)+1,i=n.lastIndexOf(`
512
512
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
513
- `)){let t=jsonLine(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function readTranscriptWindow(e){let t=readTailSync(e,TRANSCRIPT_WINDOW_BYTES+1);return t.kind===`ok`?ok$1(transcriptWindow(t.value.buf,t.value.fromStart)):t}const FORGE_PROBE={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function forgeLogin(e,t){if(gitRootOf(t)===void 0)return{kind:`ok`,value:null};let n=remotesOf(await e.launch({bin:`git`,args:[...REMOTES_ARGS],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=forgeRemoteUrl(n.value);if(r===null)return{kind:`ok`,value:null};let i=detectForge(r);if(i===null)return{kind:`ok`,value:null};let a=FORGE_CLI[i],o=FORGE_PROBE[i],s=o.loginHost(remoteHost(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return forgeLoginOf(a,s,o.nonZero,c)}function forgeLoginOf(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):isMissingCommand(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:firstLine(r.stderr)}):{kind:`failed`,reason:launchFailure(e,r)}}var ClicksInFlight=class{held=new Map;hold({id:e,gone:t}){return this.held.set(e,t),{[Symbol.dispose]:()=>void this.held.delete(e)}}gone(e){let t=this.held.get(e);if(t===void 0)throw Error(`click ${e} is not in flight`);return t()}};async function closeByTurn(e,t,n,r,i){let a=await e.answer({kind:`event`,at:t(),event:{kind:`menu-idle`,session:n,idle:r,latest:i}});return a.kind===`threw`?a.failure:null}const MAX_SESSIONS=256;var MenuIdle=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}confirmClose(e,t){let n=this.sessions.get(e);return n?.closing!==t||this.pending.has(e)?!1:(this.shut(n,t),!0)}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=MAX_SESSIONS)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&t.closing===null&&!this.disposed&&!this.pending.has(e)?closesAt(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})}))}shut(e,t){e.since=t,e.shown=!1}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now();t.closing=n,this.deps.close(e,{firedAt:n,idleS:n-t.since,timeoutS:t.timeoutS}).then(r=>{r!==null&&(this.shut(t,n),this.deps.failed(e,r))}).finally(()=>{t.closing=null,this.sessions.get(e)===t&&this.settle(e)})}};function createDaemon(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=locations(c),u=()=>instantAt(i),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new RuntimeStats(i),h=new WatcherRegistry({clock:i,counters:m,logger:p}),g=new FileEventDelivery({watchers:h,logger:p,clock:i}),_=import_dist$1.observable.box({fileEvents:[],launcher:[],rendererEnded:null,actFailed:null},{deep:!1,equals:import_dist$1.compareStructural}),v=null,y=null;function b(){(0,import_dist$1.runInAction)(()=>_.set({fileEvents:fileEventsWarnings(g.delivery()),launcher:x.standing(),rendererEnded:v,actFailed:y}))}let x=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,now:u,observeWarnings:e=>{e.kind===`launch-pipes`?p(`warn`,e.text):p(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),b()}}),S=e.probe(x),C=linkSignerOver(e.linkKey),w=e.renderer({load:()=>loadMainRenderer({clock:i,now:u,storage:{...e.storage(p),doctor:e.doctorStores},linkSigner:C,stateDir:o.state,locations:l,env:c.env,home:c.home,gates:s,bundle:t.path,memoryLimitBytes:n}),boot:()=>{let r=e.linkKey();return{digest:t.digest,host:{...c,env:bootEnv(c.env)},bundle:t.path,memoryLimitBytes:n,linkKey:r.kind===`ok`?{kind:`ok`,value:r.value.toString(`base64`)}:r}},node:t.node}),T=makeLimits({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:x,log:p}),limitBytes:n,renderer:()=>fe.process()}),E=new ProbeArrivals,D=new RenderSightings,O=e.doctorStores,k=new RefreshLedger(p);b();let A=new SourceRuns({launcher:x,clock:i,logger:p,ledger:k,watchers:h,fileEvents:g}),j=createPayloadProviders({launcher:x,host:c,watchers:h,fileEvents:g,clock:i,logger:p,ledger:k,sourceRuns:A}),{managedStorage:M}=j,N=new MenuIdle({clock:i,now:u,close:(e,t)=>closeByTurn(B.renderer,u,e,t,I.latest(e)),failed:(e,t)=>p(LEVEL[t.kind],`menu-idle: close failed (session=${e}): ${t.detail}`)}),F=new Runs({supersede:(e,t)=>M.supersede(e,t),launch:x.launch,clock:i}),ee=new Acts({launch:clickLaunchVia(x),type:typeInPane(e.claudeInput(x)),run:e=>F.start(e),applyUpdate:()=>se.act(),lanes:{edge:e.laneEdge(x,e=>I.following(e),d.signal,S),host:{bundle:t.path,node:t.node,socket:o.socket,preload:stableAttachPreload(t.path,c)}},closing:()=>d.signal.aborted,log:p}),te=new TmuxStatusLines({edge:{run:(e,t,n)=>runTmuxAsync(x,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>I.subscribe(e,t),sessionInPane:(e,t)=>I.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${shellWord(o.socket)}`,...[...t.node,t.path].map(shellWord),`url-handle`].join(` `),owner:o.socket,log:p}),ne=new DeclaredStatusLines(te,e=>I.latest(e)?.hints.tmux),I=new FrameFeeds({frame:async(e,t,n,r,i)=>{let{frame:a}=await B.renderer.ask({kind:`frame`,session:e,fps:t,following:r,feeds:i,idleSince:N.since(e,n)??null},n);return a===null?null:{...a,bar:parseFrame(a.bar)}},lanes:async e=>(await B.renderer.ask({kind:`lanes`,session:e},u())).lanes,pin:e=>B.renderer.tell({kind:`pin`,session:e},u()),unpin:e=>B.renderer.tell({kind:`unpin`,session:e},u()),shown:e=>re.shown(e.hints.tmux),watching:()=>re.follow(),refreshes:()=>k.totals(),periods:FEED_PERIODS,clock:i,instant:u,log:p}),re=new PaneVisibility({clock:i,listPanes:e=>runTmuxAsync(x,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,LIST_PANES_FORMAT]),listClients:e=>runTmuxAsync(x,{socket:e},`frames.visibility`,[`list-clients`,`-F`,LIST_CLIENTS_FORMAT]),sockets:()=>new Set(I.watched().flatMap(({req:e})=>ie(e))),onAnswer:(e,t)=>te.answered(e,t),onChange:e=>I.wakeWhere(`visibility`,t=>ie(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function ie({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ae=newUpdateFact();g.subscribe(e=>{switch(e.kind){case`period`:h.judge();return;case`caught-up`:b(),B.renderer.tell({kind:`reload-every`,since:e.since},u());return;case`moved`:b();return}});let oe=60*1e3,L=360*60*1e3,R=makeBinaryWatch({clock:i,targets:t.targets,intervalMs:oe,stat:e.stat,held:()=>se.running(),exit:()=>a(0),log:p}),se=makeUpdateWatch({fact:ae,clock:i,launcher:x,probe:S,entryUrl:t.entryUrl,digest:t.digest,actsDir:actsDir(o.state,t.path),intervalMs:oe,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,onApplied:()=>R.checkNow(),log:p}),ce=new Collector({owners:j,daemon:()=>({update:{newer:ae.get(),...se.acts()},..._.get()}),clock:i,watched:e=>I.feedOpen(e),deliver:e=>B.renderer.deliver({kind:`event`,event:e,at:u()},[]),log:p}),le=new ClicksInFlight,ue=new Map,z=e.doctorEdge(x,c),de={wake:(e,t)=>I.wake(e,t),log:p,doctor:{...z,install:async(e,t)=>installFacts(z.install,e,t)},menuIdle:{clicked:(e,t)=>N.clicked(e,t),clickArrived:e=>N.clickArrived(e),clickSettled:e=>N.clickSettled(e),observe:(e,t,n,r)=>N.observe(e,t,n,r),confirmClose:async(e,t)=>N.confirmClose(e,t)},clicks:{gone:async e=>le.gone(e)},serving:async()=>T.serving(),renderSightings:{ofSession:async(e,t)=>D.ofSession(e,t)},eventAnswered:e=>{x.answeredPipeEvent(e),v!==null&&answeredBy(v,e)&&(v={...v,answered:!0}),y!==null&&answeredBy(y,e)&&(y={...y,answered:!0}),b()},watches:{watch:(e,t,n)=>{let r=t=>B.renderer.tell({kind:`watch`,id:e,heard:t,deaf:a.deaf},u()),a=h.acquire(t,n,r);ue.set(e,a),i.defer(()=>{ue.get(e)===a&&r(null)})},unwatch:e=>{ue.get(e)?.release(),ue.delete(e)}},storage:{hold:(e,t)=>M.hold(e,t),release:e=>M.release(e)}},fe=w.start({reaches:de,log:p,clock:i,start:async()=>{let e=u();for(let t of I.openFeeds())B.renderer.tell({kind:`pin`,session:t},e);let t=[...ce.liveDocuments()].flatMap(([e,t])=>{let n=I.latest(e);return n===null?[]:[{context:located(n),worldState:t}]});await B.renderer.deliver({kind:`event`,at:e,event:{kind:`start`,sessions:t}},[[`why`,`renderer-start`]])},ended:e=>{v=e,b()}}),B={clicks:le,home:c.home,tmp:c.tmp,launcher:x,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:O,stats:m,handlerProbes:E,linkSigner:C,renderSightings:D,watcherRegistry:h,refreshLedger:k,fileEvents:g,payloadProviders:j,menuIdle:N,runs:F,sourceRuns:A,tmuxStatusLines:te,declaredStatusLines:ne,frameFeeds:I,updateWatch:se,limits:T,collector:ce,renderer:rendererHost(`main`,i,fe.renderer,p,{subscribed:e=>{ce.subscribed(e),ne.declare(e.tmuxStatus)},holding:e=>ce.holding(e)},{perform:e=>ee.perform(e),stateDir:o.state,closing:()=>d.signal.aborted,unheard:e=>{y=joinedEvent(y,e,u()),b()}})};return{stats:m,launcher:x,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),handleRequest(B,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),replyTo(B,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),I.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),B.renderer.tell({kind:`reload-config`,origin:e},u())},arm(){d.signal.throwIfAborted(),g.start(o.watchProbe),R.arm(),se.arm(),T.arm(),fe.arm()},async close(){let e=e=>()=>B.renderer.ask({kind:e},u());return await runTeardown([[`tmuxStatusLines close`,()=>te.close()],[`journalTurns close`,e(`close-journal`)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>I.close()],[`menuIdle dispose`,()=>N.dispose()],[`updateWatch close`,()=>se.close()],[`binaryWatch close`,()=>R.close()],[`limits disarm`,()=>T.disarm()],[`collector close`,()=>ce.close()],[`renderer views close`,e(`close-views`)],...j.closes,[`runs close`,()=>F.close()],[`sourceRuns close`,()=>A.close()],[`fileEvents close`,()=>g.close()],[`watcherRegistry close`,()=>h.closeAll()],[`sessionState close`,e(`close-session-state`)],[`renderer process close`,()=>fe.close()]],p),f=!0,{settled:x.settled()}}}}const THEN=`;`,BUFFER=`cc-candybar-slash`;async function tmux$1(e,t,n,r,i){let a=await runTmuxAsync(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function read(e,t){let n=await tmux$1(e,t,`claude-input.read`,[`display`,`-p`,`-t`,t.pane,`#{pane_in_mode}`,THEN,`capture-pane`,`-p`,`-t`,t.pane]);if(n.kind===`rate-limited`)throw Error(n.reason);let[r=``,...i]=n.stdout.split(`
513
+ `)){let t=jsonLine(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function readTranscriptWindow(e){let t=readTailSync(e,TRANSCRIPT_WINDOW_BYTES+1);return t.kind===`ok`?ok$1(transcriptWindow(t.value.buf,t.value.fromStart)):t}const FORGE_PROBE={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function forgeLogin(e,t){if(gitRootOf(t)===void 0)return{kind:`ok`,value:null};let n=remotesOf(await e.launch({bin:`git`,args:[...REMOTES_ARGS],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=forgeRemoteUrl(n.value);if(r===null)return{kind:`ok`,value:null};let i=detectForge(r);if(i===null)return{kind:`ok`,value:null};let a=FORGE_CLI[i],o=FORGE_PROBE[i],s=o.loginHost(remoteHost(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return forgeLoginOf(a,s,o.nonZero,c)}function forgeLoginOf(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):isMissingCommand(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:firstLine(r.stderr)}):{kind:`failed`,reason:launchFailure(e,r)}}var ClicksInFlight=class{held=new Map;hold({id:e,gone:t}){return this.held.set(e,t),{[Symbol.dispose]:()=>void this.held.delete(e)}}gone(e){let t=this.held.get(e);if(t===void 0)throw Error(`click ${e} is not in flight`);return t()}};async function closeByTurn(e,t,n,r,i){let a=await e.answer({kind:`event`,at:t(),event:{kind:`menu-idle`,session:n,idle:r,latest:i}});return a.kind===`threw`?a.failure:null}const MAX_SESSIONS=256;var MenuIdle=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}confirmClose(e,t){let n=this.sessions.get(e);return n?.closing!==t||this.pending.has(e)?!1:(this.shut(n,t),!0)}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=MAX_SESSIONS)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&t.closing===null&&!this.disposed&&!this.pending.has(e)?closesAt(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})}))}shut(e,t){e.since=t,e.shown=!1}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now();t.closing=n,this.deps.close(e,{firedAt:n,idleS:n-t.since,timeoutS:t.timeoutS}).then(r=>{r!==null&&(this.shut(t,n),this.deps.failed(e,r))}).finally(()=>{t.closing=null,this.sessions.get(e)===t&&this.settle(e)})}};function createDaemon(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=locations(c),u=()=>instantAt(i),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new RuntimeStats(i),h=new WatcherRegistry({clock:i,counters:m,logger:p}),g=new FileEventDelivery({watchers:h,logger:p,clock:i}),_=import_dist$1.observable.box({fileEvents:[],launcher:[],rendererEnded:null,actFailed:null},{deep:!1,equals:import_dist$1.compareStructural}),v=null,y=null;function b(){(0,import_dist$1.runInAction)(()=>_.set({fileEvents:fileEventsWarnings(g.delivery()),launcher:x.standing(),rendererEnded:v,actFailed:y}))}let x=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,now:u,observeWarnings:e=>{e.kind===`launch-pipes`?p(`warn`,e.text):p(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),b()}}),S=e.probe(x),C=linkSignerOver(e.linkKey),w=e.renderer({load:()=>loadMainRenderer({clock:i,now:u,storage:{...e.storage(p),doctor:e.doctorStores},linkSigner:C,stateDir:o.state,locations:l,env:c.env,home:c.home,gates:s,bundle:t.path,memoryLimitBytes:n}),boot:()=>{let r=e.linkKey();return{digest:t.digest,host:{...c,env:bootEnv(c.env)},bundle:t.path,memoryLimitBytes:n,linkKey:r.kind===`ok`?{kind:`ok`,value:r.value.toString(`base64`)}:r}},node:t.node}),T=makeLimits({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:x,log:p}),limitBytes:n,renderer:()=>fe.process()}),E=new ProbeArrivals,D=new RenderSightings,O=e.doctorStores,k=new RefreshLedger(p);b();let A=new SourceRuns({launcher:x,clock:i,logger:p,ledger:k,watchers:h,fileEvents:g}),j=createPayloadProviders({launcher:x,host:c,watchers:h,fileEvents:g,clock:i,logger:p,ledger:k,sourceRuns:A}),{managedStorage:M}=j,N=new MenuIdle({clock:i,now:u,close:(e,t)=>closeByTurn(B.renderer,u,e,t,I.latest(e)),failed:(e,t)=>p(LEVEL[t.kind],`menu-idle: close failed (session=${e}): ${t.detail}`)}),F=new Runs({supersede:(e,t)=>M.supersede(e,t),launch:x.launch,clock:i}),ee=new Acts({launch:clickLaunchVia(x),type:typeInPane(e.claudeInput(x)),run:e=>F.start(e),applyUpdate:()=>se.act(),lanes:{edge:e.laneEdge(x,e=>I.following(e),d.signal,S),host:{bundle:t.path,node:t.node,socket:o.socket,preload:stableAttachPreload(t.path,c)}},closing:()=>d.signal.aborted,log:p}),te=new TmuxStatusLines({edge:{run:(e,t,n)=>runTmuxAsync(x,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>I.subscribe(e,t),sessionInPane:(e,t)=>I.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${shellWord(o.socket)}`,...[...t.node,t.path].map(shellWord),`url-handle`].join(` `),owner:o.socket,log:p}),ne=new DeclaredStatusLines(te,e=>I.latest(e)?.hints.tmux),I=new FrameFeeds({frame:async(e,t,n,r,i)=>{let{frame:a}=await B.renderer.ask({kind:`frame`,session:e,fps:t,following:r,feeds:i,idleSince:N.since(e,n)??null},n);return a===null?null:{...a,bar:parseFrame(a.bar)}},lanes:async e=>(await B.renderer.ask({kind:`lanes`,session:e},u())).lanes,pin:e=>B.renderer.tell({kind:`pin`,session:e},u()),unpin:e=>B.renderer.tell({kind:`unpin`,session:e},u()),shown:e=>re.shown(e.hints.tmux),watching:()=>re.follow(),refreshes:()=>k.totals(),periods:FEED_PERIODS,clock:i,instant:u,log:p}),re=new PaneVisibility({clock:i,listPanes:e=>runTmuxAsync(x,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,LIST_PANES_FORMAT]),listClients:e=>runTmuxAsync(x,{socket:e},`frames.visibility`,[`list-clients`,`-F`,LIST_CLIENTS_FORMAT]),sockets:()=>new Set(I.watched().flatMap(({req:e})=>ie(e))),onAnswer:(e,t)=>te.answered(e,t),onChange:e=>I.wakeWhere(`visibility`,t=>ie(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function ie({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ae=newUpdateFact();g.subscribe(e=>{switch(e.kind){case`period`:h.judge();return;case`caught-up`:b(),B.renderer.tell({kind:`reload-every`,since:e.since},u());return;case`moved`:b();return}});let oe=60*1e3,L=360*60*1e3,R=makeBinaryWatch({clock:i,targets:t.targets,intervalMs:oe,stat:e.stat,held:()=>se.running(),exit:()=>a(0),log:p}),se=makeUpdateWatch({fact:ae,clock:i,launcher:x,probe:S,entryUrl:t.entryUrl,digest:t.digest,actsDir:actsDir(o.state,t.path),intervalMs:oe,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,onApplied:()=>R.checkNow(),log:p}),ce=new Collector({owners:j,daemon:()=>({update:{newer:ae.get(),...se.acts()},..._.get()}),clock:i,watched:e=>I.feedOpen(e),deliver:e=>B.renderer.deliver({kind:`event`,event:e,at:u()},[]),log:p}),le=new ClicksInFlight,ue=new Map,z=e.doctorEdge(x,c),de={wake:(e,t)=>I.wake(e,t),log:p,doctor:{...z,install:async(e,t)=>installFacts(z.install,e,t)},menuIdle:{clicked:(e,t)=>N.clicked(e,t),clickArrived:e=>N.clickArrived(e),clickSettled:e=>N.clickSettled(e),observe:(e,t,n,r)=>N.observe(e,t,n,r),confirmClose:async(e,t)=>N.confirmClose(e,t)},clicks:{gone:async e=>le.gone(e)},serving:async()=>T.serving(),renderSightings:{ofSession:async(e,t)=>D.ofSession(e,t)},eventAnswered:e=>{x.answeredPipeEvent(e),v!==null&&answeredBy(v,e)&&(v={...v,answered:!0}),y!==null&&answeredBy(y,e)&&(y={...y,answered:!0}),b()},watches:{watch:(e,t,n)=>{let r=t=>B.renderer.tell({kind:`watch`,id:e,heard:t,deaf:a.deaf},u()),a=h.acquire(t,n,r);ue.set(e,a),i.defer(()=>{ue.get(e)===a&&r(null)})},unwatch:e=>{ue.get(e)?.release(),ue.delete(e)}},storage:{hold:(e,t)=>M.hold(e,t),release:e=>M.release(e)}},fe=w.start({reaches:de,log:p,clock:i,start:async()=>{let e=u();for(let t of I.openFeeds())B.renderer.tell({kind:`pin`,session:t},e);let t=[...ce.liveDocuments()].flatMap(([e,t])=>{let n=I.latest(e);return n===null?[]:[{context:located(n),worldState:t}]});await B.renderer.deliver({kind:`event`,at:e,event:{kind:`start`,sessions:t}},[[`why`,`renderer-start`]])},ended:e=>{v=e,b()}}),B={clicks:le,home:c.home,tmp:c.tmp,launcher:x,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:O,stats:m,handlerProbes:E,linkSigner:C,renderSightings:D,watcherRegistry:h,refreshLedger:k,fileEvents:g,payloadProviders:j,menuIdle:N,runs:F,sourceRuns:A,tmuxStatusLines:te,declaredStatusLines:ne,frameFeeds:I,updateWatch:se,limits:T,collector:ce,renderer:rendererHost(`main`,i,fe.renderer,p,{subscribed:e=>{ce.subscribed(e),ne.declare(e.tmuxStatus)},holding:e=>ce.holding(e)},{perform:e=>ee.perform(e),stateDir:o.state,closing:()=>d.signal.aborted,unheard:e=>{y=joinedEvent(y,e,u()),b()}})};return{stats:m,launcher:x,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),handleRequest(B,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),replyTo(B,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),I.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),B.renderer.tell({kind:`reload-config`,origin:e},u())},arm(){d.signal.throwIfAborted(),g.start(o.watchProbe),R.arm(),se.arm(),T.arm(),fe.arm()},async close(){let e=e=>()=>B.renderer.ask({kind:e},u());return await runTeardown([[`renderer close begins`,()=>fe.beginClose()],[`tmuxStatusLines close`,()=>te.close()],[`journalTurns close`,e(`close-journal`)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>I.close()],[`menuIdle dispose`,()=>N.dispose()],[`updateWatch close`,()=>se.close()],[`binaryWatch close`,()=>R.close()],[`limits disarm`,()=>T.disarm()],[`collector close`,()=>ce.close()],[`renderer views close`,e(`close-views`)],...j.closes,[`runs close`,()=>F.close()],[`sourceRuns close`,()=>A.close()],[`fileEvents close`,()=>g.close()],[`watcherRegistry close`,()=>h.closeAll()],[`sessionState close`,e(`close-session-state`)],[`renderer process close`,()=>fe.close()]],p),f=!0,{settled:x.settled()}}}}const THEN=`;`,BUFFER=`cc-candybar-slash`;async function tmux$1(e,t,n,r,i){let a=await runTmuxAsync(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function read(e,t){let n=await tmux$1(e,t,`claude-input.read`,[`display`,`-p`,`-t`,t.pane,`#{pane_in_mode}`,THEN,`capture-pane`,`-p`,`-t`,t.pane]);if(n.kind===`rate-limited`)throw Error(n.reason);let[r=``,...i]=n.stdout.split(`
514
514
  `);return{inMode:r!==`0`,screen:i}}function pasteLineArgs(e,t,n){return[`load-buffer`,`-b`,t,`-`,THEN,...n.length===0?[]:[`send-keys`,`-t`,e,...n,THEN],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,THEN,`send-keys`,`-t`,e,`Enter`]}async function type(e,t,n){let r=await tmux$1(e,t,`claude-input.type`,pasteLineArgs(t.pane,BUFFER,[`C-s`]),n);return r.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${r.reason})`}}function productionClaudeInputEdge(e){return{read:t=>read(e,t),type:(t,n)=>type(e,t,n)}}function isSnapshot(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 FileSessionStorage=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=quietLogger){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e=new Map,t;try{t=fs.readFileSync(this.filePath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${n}); starting empty`),e}try{let n=JSON.parse(t);return isSnapshot(n)?sessionKeyed(n,(e,t)=>this.logger(`warn`,`session-state load: dropped session key ${JSON.stringify(e)}: session id ${t}`)):(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),e)}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),e}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=elapsedMs(this.clock,n);try{await fs.promises.mkdir(path.dirname(this.filePath),{recursive:!0});let o=await fs.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let s=!1;if(t===this.generation)try{await fs.promises.rename(i,this.filePath),s=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){s||await fs.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${s} took=${elapsedMs(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{fs.mkdirSync(path.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);fs.writeFileSync(n,r,{mode:384}),fs.chmodSync(n,384),fs.rmSync(this.writingPath,{force:!0}),fs.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,elapsedMs(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=${elapsedMs(this.clock,n)}ms held=${r}ms`)}};function isChange(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function isSteps(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(isChange))}function isSavepoint(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(isChange)&&isSteps(t.below)}function isSessionHistory(e){if(typeof e!=`object`||!e)return!1;let t=e;return isSteps(t.past)&&isSteps(t.future)&&(t.savepoint===void 0||isSavepoint(t.savepoint))}function withoutRetiredKeys(e,t){let n=e=>e.kind===`file`||isSettingKey(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function fileHistoryStorage(e,t){return{load:()=>{let n=new Map,r;try{r=fs.readFileSync(e,`utf8`)}catch(e){let r=e.code;return r!==`ENOENT`&&t(`warn`,`settings-history read failed (${r}); starting empty`),n}try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(isSessionHistory)){let r=new Set,i=sessionKeyed(e,(e,n)=>t(`warn`,`settings-history load: dropped session key ${JSON.stringify(e)}: session id ${n}`));for(let[e,t]of i)n.set(e,withoutRetiredKeys(t,r));return r.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...r].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),n}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),n},save:n=>{try{fs.mkdirSync(path.dirname(e),{recursive:!0}),writeAtomic(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}function fileStorage(e,t,n){return{session:new FileSessionStorage(e.sessionState,n,500,t),history:fileHistoryStorage(e.settingsHistory,t)}}function executableOn(e,t,n){for(let r of(t??``).split(path.delimiter)){if(!path.isAbsolute(r))continue;let t=path.join(r,e);if(n(t))return t}return null}function regularFileWith(e,t){try{return fs.accessSync(e,t),fs.statSync(e).isFile()}catch{return!1}}function canonical(e){try{return fs.realpathSync(e)}catch{return path.resolve(e)}}function launcherNode(e,t,n){let r=executableOn(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:path.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 SHELL_BUFFER=`cc-candybar-lane`,EXIT_POLL_MS=100,SHELL_PATIENCE_MS=2e3;async function tmux(e,t,n,r){let i=await runTmuxAsync(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function ran(e,t){if(t.ok)return t.stdout;let n=saidBy(t,t.stdout);throw Error(`${e} failed (${failureText(t)}${n===``?``:`: ${n}`})`)}function refusalOf(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 PANE_STARTS_FORMAT=`#{pane_id} #{pane_start_command}`,BAR_PANE_START=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function barPanesOf(e,t){return e.split(`
515
515
  `).flatMap(e=>{let[n,...r]=e.trim().split(` `);return BAR_PANE_START.exec(r.join(` `))?.[1]===t?[n]:[]})}const ATTACH=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function runsAttached(e,t,n){for(let r of lineage(processTable(e),t)){if(r.command.split(` `).some(e=>ATTACH.test(e)))return!0;if(r.pid===n)return!1}return!1}const PROCARGS2=[`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(`
516
- `);async function imageOf(e,t){if(process.platform===`linux`)return{executable:await fs.promises.readlink(`/proc/${t}/exe`),argv:(await fs.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await fs.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=ran(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,PROCARGS2,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function ps(e,t,n){return ran(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function paneForeground(e,t){let n=await runTmuxAsync(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 ps(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function paneClaude(e,t){let{panePid:n,cwd:r,foreground:i}=await paneForeground(e,t),a=await ps(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await imageOf(e,i),s=processTable(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await fs.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:runsAttached(a,i,n)}}const FOLLOW_POLL_MS=200;function productionLaneEdge(e,t,n,r,i){let a=e=>sleep(r,e,n);return{claudeInput:productionClaudeInputEdge(e),barPanes:async t=>barPanesOf(await tmux(e,t,[`list-panes`,`-a`,`-F`,PANE_STARTS_FORMAT]),t.pane),openBarPane:async(t,n,r)=>(await tmux(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 tmux(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void ran(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:sessionEnv(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>fs.existsSync(e),presence,paneClaude:t=>paneClaude(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+SHELL_PATIENCE_MS;for(;;){let o=await paneForeground(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${SHELL_PATIENCE_MS/1e3} s`);await a(EXIT_POLL_MS)}},launcherNode:e=>launcherNode(e,e=>regularFileWith(e,fs.constants.X_OK),canonical),onPath:(e,t)=>{let n=executableOn(e,t,e=>regularFileWith(e,fs.constants.X_OK));return n===null?null:fs.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(FOLLOW_POLL_MS)}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`?refusalOf(i.stdout):null;return a===null?(ran(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(EXIT_POLL_MS)}return!0},typeShellLine:async(t,n)=>void await tmux(e,t,pasteLineArgs(t.pane,SHELL_BUFFER,[]),n)}}function linkKeyFile(e){return path.join(e,`link.key`)}function linkKeyFromFile(e){let t;return()=>{try{return t??=readOrCreate(e),{kind:`ok`,value:t}}catch(e){return{kind:`failed`,reason:e.message}}}}function readOrCreate(e){let t;try{t=fs.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;create(e),t=fs.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 t}function create(e){fs.mkdirSync(path.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${randomBytes(6).toString(`hex`)}`;fs.writeFileSync(t,randomBytes(32),{mode:384,flag:`wx`});try{fs.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{fs.unlinkSync(t)}}const inProcessPort=({load:e})=>{let t=e();return{start:e=>inProcessRenderer(t,e.reaches)}};function processPort(e){return({boot:t,node:n})=>({start:r=>processRenderer({...r,...e,node:n,boot:t})})}function inProcessRenderer(e,t){return{renderer:e.start(t),arm:()=>{},close:async()=>{},process:()=>null}}const PING_PERIOD_MS=1e4,HUNG_AFTER_MS=6e4,YOUNG_MS=6e4,BACKOFF_FIRST_MS=1e3,BACKOFF_MAX_MS=6e4,CLOSE_GRACE_MS=250;function rendererNodeArgs(e,t){return[...e.filter(e=>!e.startsWith(`--max-old-space-size`)&&!e.startsWith(`--inspect`)),`--max-old-space-size=${t}`]}function backoffMs(e){return e===0?0:Math.min(BACKOFF_FIRST_MS*2**(e-1),BACKOFF_MAX_MS)}function processRenderer(e){let{clock:t,log:n}=e,r={kind:`idle`},i=0,a=0,o=0,s=[],c=0,l=()=>++c,u=new Map,d=new Map,f=()=>r.kind===`starting`||r.kind===`live`?r.link:null,p=()=>new RendererDown(r.kind===`down`?`renderer main is down: ${r.why}`:r.kind===`closed`?`renderer main is closed`:`renderer main has not started`),m=t=>({...e.reaches,watches:{watch:(n,r,i)=>{let a=l();d.set(a,{by:t,id:n}),t.watches.set(n,a),e.reaches.watches.watch(a,r,i)},unwatch:n=>{let r=hostIdOf(t.watches,n);d.delete(r),t.watches.delete(n),e.reaches.watches.unwatch(r)}},storage:{hold:(n,r)=>{let i=t.holds.get(n)??l();t.holds.set(n,i),e.reaches.storage.hold(i,r)},release:n=>{let r=hostIdOf(t.holds,n);t.holds.delete(n),e.reaches.storage.release(r)}}}),h=({held:t})=>{for(let n of t.watches.values())d.delete(n),e.reaches.watches.unwatch(n);for(let n of t.holds.values())e.reaches.storage.release(n);for(let[e,n]of u)n.by===t&&u.delete(e)},g=()=>s.splice(0).forEach(h),_=(e,t)=>e.write(`${JSON.stringify(t)}\n`),v=()=>{let a=++i,o=new AbortController,s=()=>{},c=lineSplitter(e=>s(e)),l=lineSplitter(e=>n(`warn`,`renderer main[${a}]: ${e}`)),u=e.launcher.launchChannel({bin:e.node[0],args:[...rendererNodeArgs(e.node.slice(1),e.heapCapMb),e.entry,`renderer`],cwd:e.cwd,category:`renderer`,signal:o.signal,heard:{stdout:c.push,stderr:l.push}}),d={watches:new Map,holds:new Map},f={generation:a,channel:u,kill:o,spawnedAt:t.monotonic(),hung:!1,refusal:null,tookOver:!1,held:d,usage:null,pingSentAt:null,lines:rendererOverLines({send:e=>_(u,e),host:m(d),fault:e=>n(`error`,`renderer main[${a}]: ${e}`)})};r={kind:`starting`,link:f,queued:[]},_(u,{kind:`boot`,boot:e.boot()});let p=e.start().catch(e=>n(`error`,`renderer main[${a}] start failed: ${failureOf(e).detail}`));s=e=>y(f,p,e),u.ended.then(e=>{c.end(),l.end(),x(f,f.hung?`stopped answering for ${HUNG_AFTER_MS/1e3} s`:f.refusal===null?e.ok?`exited`:whyFailed(e):`refused its boot: ${f.refusal}`)})},y=(e,t,r)=>{let i;try{i=JSON.parse(r)}catch{n(`warn`,`renderer main[${e.generation}]: ${r}`);return}switch(i.kind){case`started`:b(e,t);return;case`refused`:e.refusal=i.failure.message,n(`error`,`renderer main[${e.generation}] refused its boot: ${i.failure.detail}`);return;default:e.lines.heard(i)}},b=(e,t)=>{if(r.kind!==`starting`||r.link!==e)return;let{queued:i}=r;r={kind:`live`,link:e},n(`info`,`renderer main[${e.generation}] started pid=${e.channel.pid??`-`} refused-while-down=${o}`),o=0;for(let e of i)e();t.then(()=>{f()===e&&(e.tookOver=!0,g())}),C(e)},x=(i,o)=>{if(i.lines.ended(new RendererDown(`renderer main ${o}`)),i.tookOver?s.push(i):h(i),r.kind===`closed`)return;let c=r.kind===`live`,l=r.kind===`starting`?r.queued:[],u=t.monotonic()-i.spawnedAt;a=c&&u>=6e4?0:a+1;let d=backoffMs(a),f=`renderer main[${i.generation}] ${o}`;r={kind:`down`,why:o,cancelRetry:t.after(d,()=>{r.kind===`down`&&v()})};for(let e of l)e();let p={text:`${f}; it restarts, and unsaved state (open menus, armed confirms) is lost`,at:instantAt(t),answered:!1};n(`warn`,`${f} after ${Math.round(u/1e3)} s; next start in ${Math.round(d/1e3)} s`),e.ended(p)},S=()=>{let e=f();if(e===null)return;let n=t.monotonic(),i=r.kind===`starting`?e.spawnedAt:e.pingSentAt;if(i!==null&&n-i>6e4){e.hung=!0,e.kill.abort(Error(`the renderer stopped answering`));return}r.kind===`live`&&e.pingSentAt===null&&C(e)},C=e=>{e.pingSentAt=t.monotonic(),e.lines.ping().then(t=>{e.usage=t,e.pingSentAt=null},()=>{})},w=()=>{},T=e=>(o++,e),E=e=>{if(r.kind===`live`)return e(r.link);if(r.kind===`starting`){let{queued:t}=r;return new Promise((n,i)=>t.push(()=>{(r.kind===`live`?e(r.link):Promise.reject(T(p()))).then(n,i)}))}return Promise.reject(T(p()))};return{renderer:rendererOf({event:e=>E(async t=>{let{event:n}=e,r=e;if(n.kind===`effect-done`){let i=u.get(n.of);if(i===void 0||i.by!==t.held)throw new RendererDown(`renderer main: effect ${n.of} was returned by a renderer that has ended`);u.delete(n.of),r={...e,event:{...n,of:i.id}}}let i=await t.lines.renderer.answer(r);return{...i,effects:i.effects.map(e=>{let n=l();return u.set(n,{by:t.held,id:e.id}),{...e,id:n}})}}),adapter:e=>E(async t=>{let{push:n}=e;if(n.kind!==`watch`)return t.lines.renderer.answer(e);let r=d.get(n.id);if(r===void 0||r.by!==t.held)throw new RendererDown(`renderer main: watch ${n.id} was held by a renderer that has ended`);return t.lines.renderer.answer({...e,push:{...n,id:r.id}})})}),arm:()=>{r.kind===`idle`&&(v(),w=t.every(PING_PERIOD_MS,S,{unref:!0}))},close:async()=>{let e=f(),n=r.kind===`starting`?r.queued:[];r.kind===`down`&&r.cancelRetry(),r={kind:`closed`};for(let e of n)e();if(w(),e!==null){e.channel.end();let n=t.after(250,()=>e.kill.abort(Error(`the daemon closed`)));await e.channel.ended,n()}g()},process:()=>{let e=f(),t=e===null?null:e.channel.pid;return e===null||t===null?null:{pid:t,usage:e.usage,heapSnapshot:t=>r.kind===`live`&&r.link===e?e.lines.heapSnapshot(t):Promise.reject(Error(`renderer main[${e.generation}] is not live, so its heap was not written`))}}}}function hostIdOf(e,t){let n=e.get(t);if(n===void 0)throw Error(`renderer main named ${String(t)}, which it holds none of`);return n}function rendererAdapters(e,t){return{storage:n=>fileStorage(e,n,t),doctorStores:fileStores(e.state)}}function productionAdapters(e,t,n){return{daemonLog:t,launcher:e=>systemLauncher(e,n),...rendererAdapters(e,n),linkKey:linkKeyFromFile(linkKeyFile(e.state)),doctorEdge:productionMachineEdge,claudeInput:productionClaudeInputEdge,probe:systemProbe,laneEdge:(e,t,r,i)=>productionLaneEdge(e,t,r,n,i),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>realLimitsDeps(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),renderer:inProcessPort,fetch,stat:fs.statSync}}const STANDARD_NAMES=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function runColor(e){if(e===void 0)return;let t=ColorSpec.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===ColorDepth.STANDARD&&t.number!==void 0?STANDARD_NAMES[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const ATTRIBUTES={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function bandRun({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=runColor(t),o=runColor(n),s={};for(let e of r){let t=ATTRIBUTES[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function encode(e){return{ok:!0,band:e.rows.map(e=>mergedRuns(e).map(bandRun))}}function bandFrame(e){return laneEncoded(encode,e)}const LANE_FRAMES={band:e=>JSON.stringify(bandFrame(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:tmuxStatusFrame(e)})};function newestWins(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 handleConnection(e,t){t.allowHalfOpen=!1;let n=e.stats.accept();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(encodeFrame(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3,request:n.id},null,NOTHING_TO_SETTLE)}),u=makeFrameReader(i=>{let u=classifyInbound(i);c=u.kind===`request`;let f=()=>{l(),a()};e.handle(u,()=>s,n,()=>c&&t.destroyed).then(n=>{n.kind===`url`?(r=!0,n.awaitsVerdict&&t.end(encodeFrame(n.verdict)),n.land().catch(t=>e.log(`error`,`url click threw: ${inspect(t)}`)).finally(f)):n.kind===`reply`?o(n.resp,n.exitAfterFlush,n.settled):d(n.sessionId,n.lane)}).catch(t=>{e.log(`error`,`handler threw: ${inspect(t)}`),o(renderFailed(t),null,NOTHING_TO_SETTLE),c||f()})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,NOTHING_TO_SETTLE)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=newestWins(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(encodeJsonFrame(LANE_FRAMES[i](e,t))),refused:e=>t.end(encodeFrame(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const PARENT_PID_ENV=`CC_CANDYBAR_PARENT_PID`,DEFAULT_POLL_INTERVAL_MS=250;function anchorFromEnv(e){let t=e[PARENT_PID_ENV];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${PARENT_PID_ENV} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function armParentWatchdog(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??DEFAULT_POLL_INTERVAL_MS,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let myStartTime=null,breakerRegistryPath=null,serving=null,thisProcess=null;function daemonProcess(){if(thisProcess===null)throw Error(`runDaemon has not started`);return thisProcess}function serverLog(e,t){daemonProcess().log.log(e,t)}function runningBundle(){let e=fileURLToPath(import.meta.url);return{entryUrl:import.meta.url,digest:bakedDigest(),path:e,node:[process$1.execPath,...process$1.execArgv],targets:[...new Set([e,...process$1.argv[1]?[process$1.argv[1]]:[]])]}}function processEntry(){let e=process$1.argv[1];if(e===void 0)throw Error(`the daemon was run with no entry`);return e}function runDaemon(e){let t=daemonPaths(e.host);thisProcess={world:e,paths:t,log:new DaemonLog(t.log,e.clock)},process$1.on(`uncaughtException`,e=>{serverLog(`error`,`uncaughtException: ${e.stack||e.message}`),shutdown(1)}),process$1.on(`unhandledRejection`,e=>{serverLog(`error`,`unhandledRejection: ${String(e)}`),shutdown(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process$1.on(e,()=>{serverLog(`info`,`received ${e}, shutting down`),shutdown(0)});boot().catch(refuseBoot)}function refuseBoot(e){serverLog(`error`,`refusing to boot: ${inspect(e)}`),shutdown(1)}async function boot(){let{world:e,paths:t,log:n}=daemonProcess(),{host:r}=e,i=memoryLimitBytes(r.env);myStartTime=await readOwnStartTime(process$1.pid,systemProbe(e.launcher).startTime);let a=await admitDaemon(realBreakerDeps(e,myStartTime,t.registry));if(!a.decision.allow){serverLog(`warn`,`fork-bomb breaker: ${a.decision.reason}; refusing to boot`),shutdown(1);return}breakerRegistryPath=a.registryPath,fs.mkdirSync(t.state,{recursive:!0}),ensureSocketParentSafe(t.socket);let o=createDaemon({...productionAdapters(t,n,e.clock),renderer:processPort({launcher:e.launcher,entry:processEntry(),cwd:t.state,heapCapMb:heapCapMb(r.env)}),bundle:runningBundle(),host:r,paths:t,memoryLimitBytes:i,registryUrl:r.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:daemonGates(),exit:shutdown});serving=o,armParentWatchdog({clock:e.clock,anchor:anchorFromEnv(r.env),probe:systemProbe(e.launcher),onOrphaned:e=>{serverLog(`info`,`parent watchdog: ${e}; shutting down`),shutdown(0)}}),bindOrAttachAndExit(o,net.createServer(e=>handleConnection(o,e)),t.socket,!1)}function bindOrAttachAndExit(e,t,n,r){t.removeAllListeners(`error`),t.removeAllListeners(`listening`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){serverLog(`error`,`server error: ${i.message}`),shutdown(1);return}if(r){serverLog(`info`,`lost rebind race; another daemon is alive — exiting`),process$1.exit(0);return}handleAddressInUse(e,t,n).catch(refuseBoot)}),t.listen(n,()=>onListening(e,n))}async function handleAddressInUse(e,t,n){let r=await arbitrateSocket(readLease(leasePathFor(n)),(t,n)=>sameLiveProcess(t,n,systemProbe(e.launcher)));if(r.kind===`attach-and-exit`){serverLog(`info`,`EADDRINUSE: ${r.reason} — exiting`),process$1.exit(0);return}serverLog(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{fs.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){serverLog(`error`,`cannot unlink stale socket ${n}: ${e.message}`),shutdown(1);return}}bindOrAttachAndExit(e,t,n,!0)}function onListening(e,t){let n=readSocketIdentity(t);if(n.kind!==`present`){serverLog(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),shutdown(0);return}writeLeaseFile(t);try{fs.chmodSync(t,384)}catch(e){serverLog(`warn`,`chmod socket failed: ${e.message}`)}serverLog(`info`,`daemon up: pid=${process$1.pid} v=3 sock=${t} heapCap=${mb(v8.getHeapStatistics().heap_size_limit)}MB memoryLimit=${mb(e.memoryLimitBytes)}MB`),resetSpawnBackoff(daemonProcess().paths.spawnBackoff),e.arm(),armOwnershipWatch(t,n.identity)}function armOwnershipWatch(e,t){makeOwnershipWatch({bound:t,myPid:process$1.pid,readIdentity:()=>readSocketIdentity(e),readLease:()=>readLease(leasePathFor(e)),shutdown:e=>shutdown(e),log:serverLog,clock:daemonProcess().world.clock}).arm()}function writeLeaseFile(e){let t=writeLease(leasePathFor(e),{pid:process$1.pid,version:3,binPath:process$1.argv[1],startTime:myStartTime});t!==null&&serverLog(`warn`,`lease write failed: ${t}`)}let shuttingDown=!1;function shutdown(e){shuttingDown||(shuttingDown=!0,daemonProcess().world.clock.after(500,()=>process$1.kill(process$1.pid,`SIGKILL`)),closeThenExit(e))}async function closeThenExit(e){let t=[[`close`,()=>serving?.close()],[`lease removal`,()=>removeLeaseIfOwned(daemonProcess().paths.lease,process$1.pid)],[`registry release`,()=>breakerRegistryPath!==null&&releaseRegistration(breakerRegistryPath,process$1.pid,readRegistryEntry,e=>fs.unlinkSync(e))]];for(let[e,n]of t)try{await n()}catch(t){serverLog(`error`,`shutdown ${e} failed: ${inspect(t)}`)}process$1.exit(e)}function runRenderer(e){let t=e=>{process$1.stdout.write(`${JSON.stringify(e)}\n`)},n=hostOverLines(t),r=null,i=!1,a=async t=>{i||(i=!0,r!==null&&await r.answer({kind:`adapter`,push:{kind:`close-session-state`},at:instantAt(e.clock)}).catch(e=>process$1.stderr.write(`the session state did not flush: ${failureOf(e).detail}\n`)),process$1.stdout.write(``,()=>process$1.exit(t)))};process$1.on(`uncaughtException`,e=>{process$1.stderr.write(`uncaughtException: ${e.stack??e.message}\n`),a(1)}),process$1.on(`unhandledRejection`,e=>{process$1.stderr.write(`unhandledRejection: ${inspect(e)}\n`),a(1)});for(let e of[`SIGINT`,`SIGHUP`])process$1.on(e,()=>{});process$1.on(`SIGTERM`,()=>void a(0));let o=null,s=lineSplitter(i=>{let s=JSON.parse(i);if(o!==null){o(s);return}if(s.kind!==`boot`)throw Error(`a ${s.kind} before the boot`);try{r=booted(e,s.boot,n.host)}catch(e){t({kind:`refused`,failure:failureOf(e)}),a(1);return}o=serveRenderer({renderer:r,host:n,send:t,memory:()=>{let{rss:e,heapTotal:t}=process$1.memoryUsage();return{rss:e,heapTotal:t}},heapSnapshot:e=>void v8.writeHeapSnapshot(e)}),t({kind:`started`,pid:process$1.pid})});process$1.stdin.setEncoding(`utf8`),process$1.stdin.on(`data`,e=>s.push(e)),process$1.stdin.on(`end`,()=>{s.end(),a(0)})}function booted(e,t,n){let r=bakedDigest();if(t.digest!==r)throw Error(`the host was built from source ${t.digest??`of no digest`}; this renderer from ${r??`source of no digest`}, which the next daemon runs`);if(t.linkKey.kind===`failed`)throw Error(`the link key could not be read: ${t.linkKey.reason}`);let{host:i}=t,a=daemonPaths(i),{clock:o}=e,s=rendererAdapters(a,o);return loadMainRenderer({clock:o,now:()=>instantAt(o),storage:{...s.storage(n.log),doctor:s.doctorStores},linkSigner:linkSigner(Buffer.from(t.linkKey.value,`base64`)),stateDir:a.state,locations:locations(i),env:i.env,home:i.home,gates:daemonGates(),bundle:t.bundle,memoryLimitBytes:t.memoryLimitBytes}).start(n)}const BUDGETS={connectMs:200,budgetMs:500};async function debugCommandPlan(e,t,n){return debugPlan(t,await fetchDebug(e,t),n.includes(`--json`))}function debugPlan(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
516
+ `);async function imageOf(e,t){if(process.platform===`linux`)return{executable:await fs.promises.readlink(`/proc/${t}/exe`),argv:(await fs.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await fs.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=ran(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,PROCARGS2,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function ps(e,t,n){return ran(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function paneForeground(e,t){let n=await runTmuxAsync(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 ps(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function paneClaude(e,t){let{panePid:n,cwd:r,foreground:i}=await paneForeground(e,t),a=await ps(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await imageOf(e,i),s=processTable(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await fs.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:runsAttached(a,i,n)}}const FOLLOW_POLL_MS=200;function productionLaneEdge(e,t,n,r,i){let a=e=>sleep(r,e,n);return{claudeInput:productionClaudeInputEdge(e),barPanes:async t=>barPanesOf(await tmux(e,t,[`list-panes`,`-a`,`-F`,PANE_STARTS_FORMAT]),t.pane),openBarPane:async(t,n,r)=>(await tmux(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 tmux(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void ran(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:sessionEnv(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>fs.existsSync(e),presence,paneClaude:t=>paneClaude(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+SHELL_PATIENCE_MS;for(;;){let o=await paneForeground(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${SHELL_PATIENCE_MS/1e3} s`);await a(EXIT_POLL_MS)}},launcherNode:e=>launcherNode(e,e=>regularFileWith(e,fs.constants.X_OK),canonical),onPath:(e,t)=>{let n=executableOn(e,t,e=>regularFileWith(e,fs.constants.X_OK));return n===null?null:fs.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(FOLLOW_POLL_MS)}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`?refusalOf(i.stdout):null;return a===null?(ran(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(EXIT_POLL_MS)}return!0},typeShellLine:async(t,n)=>void await tmux(e,t,pasteLineArgs(t.pane,SHELL_BUFFER,[]),n)}}function linkKeyFile(e){return path.join(e,`link.key`)}function linkKeyFromFile(e){let t;return()=>{try{return t??=readOrCreate(e),{kind:`ok`,value:t}}catch(e){return{kind:`failed`,reason:e.message}}}}function readOrCreate(e){let t;try{t=fs.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;create(e),t=fs.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 t}function create(e){fs.mkdirSync(path.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${randomBytes(6).toString(`hex`)}`;fs.writeFileSync(t,randomBytes(32),{mode:384,flag:`wx`});try{fs.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{fs.unlinkSync(t)}}const inProcessPort=({load:e})=>{let t=e();return{start:e=>inProcessRenderer(t,e.reaches)}};function processPort(e){return({boot:t,node:n})=>({start:r=>processRenderer({...r,...e,node:n,boot:t})})}function inProcessRenderer(e,t){return{renderer:e.start(t),arm:()=>{},beginClose:()=>{},close:async()=>{},process:()=>null}}const PING_PERIOD_MS=1e4,HUNG_AFTER_MS=6e4,YOUNG_MS=6e4,BACKOFF_FIRST_MS=1e3,BACKOFF_MAX_MS=6e4,CLOSE_GRACE_MS=250;function rendererNodeArgs(e,t){return[...e.filter(e=>!e.startsWith(`--max-old-space-size`)&&!e.startsWith(`--inspect`)),`--max-old-space-size=${t}`]}function backoffMs(e){return e===0?0:Math.min(BACKOFF_FIRST_MS*2**(e-1),BACKOFF_MAX_MS)}function processRenderer(e){let{clock:t,log:n}=e,r={kind:`idle`},i=0,a=0,o=0,s=[],c=0,l=()=>++c,u=new Map,d=new Map,f=()=>r.kind===`starting`||r.kind===`live`||r.kind===`closing`?r.link:null,p=()=>new RendererDown(r.kind===`down`?`renderer main is down: ${r.why}`:r.kind===`closed`?`renderer main is closed`:`renderer main has not started`),m=t=>({...e.reaches,watches:{watch:(n,r,i)=>{let a=l();d.set(a,{by:t,id:n}),t.watches.set(n,a),e.reaches.watches.watch(a,r,i)},unwatch:n=>{let r=hostIdOf(t.watches,n);d.delete(r),t.watches.delete(n),e.reaches.watches.unwatch(r)}},storage:{hold:(n,r)=>{let i=t.holds.get(n)??l();t.holds.set(n,i),e.reaches.storage.hold(i,r)},release:n=>{let r=hostIdOf(t.holds,n);t.holds.delete(n),e.reaches.storage.release(r)}}}),h=({held:t})=>{for(let n of t.watches.values())d.delete(n),e.reaches.watches.unwatch(n);for(let n of t.holds.values())e.reaches.storage.release(n);for(let[e,n]of u)n.by===t&&u.delete(e)},g=()=>s.splice(0).forEach(h),_=(e,t)=>e.write(`${JSON.stringify(t)}\n`),v=()=>{let a=++i,o=new AbortController,s=()=>{},c=lineSplitter(e=>s(e)),l=lineSplitter(e=>n(`warn`,`renderer main[${a}]: ${e}`)),u=e.launcher.launchChannel({bin:e.node[0],args:[...rendererNodeArgs(e.node.slice(1),e.heapCapMb),e.entry,`renderer`],cwd:e.cwd,category:`renderer`,signal:o.signal,heard:{stdout:c.push,stderr:l.push}}),d={watches:new Map,holds:new Map},f={generation:a,channel:u,kill:o,spawnedAt:t.monotonic(),hung:!1,refusal:null,tookOver:!1,held:d,usage:null,pingSentAt:null,lines:rendererOverLines({send:e=>_(u,e),host:m(d),fault:e=>n(`error`,`renderer main[${a}]: ${e}`)})};r={kind:`starting`,link:f,queued:[]},_(u,{kind:`boot`,boot:e.boot()});let p=e.start().catch(e=>n(`error`,`renderer main[${a}] start failed: ${failureOf(e).detail}`));s=e=>y(f,p,e),u.ended.then(e=>{c.end(),l.end(),x(f,f.hung?`stopped answering for ${HUNG_AFTER_MS/1e3} s`:f.refusal===null?e.ok?`exited`:whyFailed(e):`refused its boot: ${f.refusal}`)})},y=(e,t,r)=>{let i;try{i=JSON.parse(r)}catch{n(`warn`,`renderer main[${e.generation}]: ${r}`);return}switch(i.kind){case`started`:b(e,t);return;case`refused`:e.refusal=i.failure.message,n(`error`,`renderer main[${e.generation}] refused its boot: ${i.failure.detail}`);return;default:e.lines.heard(i)}},b=(e,t)=>{if(r.kind!==`starting`||r.link!==e)return;let{queued:i}=r;r={kind:`live`,link:e},n(`info`,`renderer main[${e.generation}] started pid=${e.channel.pid??`-`} refused-while-down=${o}`),o=0;for(let e of i)e();t.then(()=>{f()===e&&(e.tookOver=!0,g())}),C(e)},x=(i,o)=>{i.lines.ended(new RendererDown(`renderer main ${o}`)),i.tookOver?s.push(i):h(i);let c=r.kind===`closing`||o!==`exited`?`warn`:`info`;if(r.kind===`closing`&&(r={kind:`closed`,ended:i.channel.ended}),r.kind===`closed`){n(c,`renderer main[${i.generation}] ${o} in the daemon's close`);return}let l=r.kind===`live`,u=r.kind===`starting`?r.queued:[],d=t.monotonic()-i.spawnedAt;a=l&&d>=6e4?0:a+1;let f=backoffMs(a),p=`renderer main[${i.generation}] ${o}`;r={kind:`down`,why:o,cancelRetry:t.after(f,()=>{r.kind===`down`&&v()})};for(let e of u)e();let m={text:`${p}; it restarts, and unsaved state (open menus, armed confirms) is lost`,at:instantAt(t),answered:!1};n(`warn`,`${p} after ${Math.round(d/1e3)} s; next start in ${Math.round(f/1e3)} s`),e.ended(m)},S=()=>{let e=f();if(e===null)return;let n=t.monotonic(),i=r.kind===`starting`?e.spawnedAt:e.pingSentAt;if(i!==null&&n-i>6e4){e.hung=!0,e.kill.abort(Error(`the renderer stopped answering`));return}r.kind!==`starting`&&e.pingSentAt===null&&C(e)},C=e=>{e.pingSentAt=t.monotonic(),e.lines.ping().then(t=>{e.usage=t,e.pingSentAt=null},()=>{})},w=()=>{},T=async e=>{e.channel.end();let n=t.after(250,()=>e.kill.abort(Error(`the daemon closed`)));await e.channel.ended,n()},E=()=>{switch(r.kind){case`live`:return r={kind:`closing`,link:r.link};case`starting`:{let{link:e,queued:t}=r,n={kind:`closed`,ended:T(e)};r=n;for(let e of t)e();return n}case`down`:return r.cancelRetry(),r={kind:`closed`,ended:Promise.resolve()};case`idle`:return r={kind:`closed`,ended:Promise.resolve()};case`closing`:case`closed`:return r}},D=e=>(o++,e),O=e=>{if(r.kind===`live`||r.kind===`closing`)return e(r.link);if(r.kind===`starting`){let{queued:t}=r;return new Promise((n,i)=>t.push(()=>{(r.kind===`live`?e(r.link):Promise.reject(D(p()))).then(n,i)}))}return Promise.reject(D(p()))};return{renderer:rendererOf({event:e=>O(async t=>{let{event:n}=e,r=e;if(n.kind===`effect-done`){let i=u.get(n.of);if(i===void 0||i.by!==t.held)throw new RendererDown(`renderer main: effect ${n.of} was returned by a renderer that has ended`);u.delete(n.of),r={...e,event:{...n,of:i.id}}}let i=await t.lines.renderer.answer(r);return{...i,effects:i.effects.map(e=>{let n=l();return u.set(n,{by:t.held,id:e.id}),{...e,id:n}})}}),adapter:e=>O(async t=>{let{push:n}=e;if(n.kind!==`watch`)return t.lines.renderer.answer(e);let r=d.get(n.id);if(r===void 0||r.by!==t.held)throw new RendererDown(`renderer main: watch ${n.id} was held by a renderer that has ended`);return t.lines.renderer.answer({...e,push:{...n,id:r.id}})})}),arm:()=>{r.kind===`idle`&&(v(),w=t.every(PING_PERIOD_MS,S,{unref:!0}))},beginClose:E,close:async()=>{let e=E(),t=e.kind===`closing`?T(e.link):e.ended;r={kind:`closed`,ended:t},w(),await t,g()},process:()=>{let e=f(),t=e===null?null:e.channel.pid;return e===null||t===null?null:{pid:t,usage:e.usage,heapSnapshot:t=>r.kind===`live`&&r.link===e?e.lines.heapSnapshot(t):Promise.reject(Error(`renderer main[${e.generation}] is not live, so its heap was not written`))}}}}function hostIdOf(e,t){let n=e.get(t);if(n===void 0)throw Error(`renderer main named ${String(t)}, which it holds none of`);return n}function rendererAdapters(e,t){return{storage:n=>fileStorage(e,n,t),doctorStores:fileStores(e.state)}}function productionAdapters(e,t,n){return{daemonLog:t,launcher:e=>systemLauncher(e,n),...rendererAdapters(e,n),linkKey:linkKeyFromFile(linkKeyFile(e.state)),doctorEdge:productionMachineEdge,claudeInput:productionClaudeInputEdge,probe:systemProbe,laneEdge:(e,t,r,i)=>productionLaneEdge(e,t,r,n,i),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>realLimitsDeps(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),renderer:inProcessPort,fetch,stat:fs.statSync}}const STANDARD_NAMES=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function runColor(e){if(e===void 0)return;let t=ColorSpec.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===ColorDepth.STANDARD&&t.number!==void 0?STANDARD_NAMES[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const ATTRIBUTES={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function bandRun({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=runColor(t),o=runColor(n),s={};for(let e of r){let t=ATTRIBUTES[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function encode(e){return{ok:!0,band:e.rows.map(e=>mergedRuns(e).map(bandRun))}}function bandFrame(e){return laneEncoded(encode,e)}const LANE_FRAMES={band:e=>JSON.stringify(bandFrame(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:tmuxStatusFrame(e)})};function newestWins(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 handleConnection(e,t){t.allowHalfOpen=!1;let n=e.stats.accept();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(encodeFrame(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3,request:n.id},null,NOTHING_TO_SETTLE)}),u=makeFrameReader(i=>{let u=classifyInbound(i);c=u.kind===`request`;let f=()=>{l(),a()};e.handle(u,()=>s,n,()=>c&&t.destroyed).then(n=>{n.kind===`url`?(r=!0,n.awaitsVerdict&&t.end(encodeFrame(n.verdict)),n.land().catch(t=>e.log(`error`,`url click threw: ${inspect(t)}`)).finally(f)):n.kind===`reply`?o(n.resp,n.exitAfterFlush,n.settled):d(n.sessionId,n.lane)}).catch(t=>{e.log(`error`,`handler threw: ${inspect(t)}`),o(renderFailed(t),null,NOTHING_TO_SETTLE),c||f()})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,NOTHING_TO_SETTLE)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=newestWins(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(encodeJsonFrame(LANE_FRAMES[i](e,t))),refused:e=>t.end(encodeFrame(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const PARENT_PID_ENV=`CC_CANDYBAR_PARENT_PID`,DEFAULT_POLL_INTERVAL_MS=250;function anchorFromEnv(e){let t=e[PARENT_PID_ENV];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${PARENT_PID_ENV} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function armParentWatchdog(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??DEFAULT_POLL_INTERVAL_MS,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let myStartTime=null,breakerRegistryPath=null,serving=null,thisProcess=null;function daemonProcess(){if(thisProcess===null)throw Error(`runDaemon has not started`);return thisProcess}function serverLog(e,t){daemonProcess().log.log(e,t)}function runningBundle(){let e=fileURLToPath(import.meta.url);return{entryUrl:import.meta.url,digest:bakedDigest(),path:e,node:[process$1.execPath,...process$1.execArgv],targets:[...new Set([e,...process$1.argv[1]?[process$1.argv[1]]:[]])]}}function processEntry(){let e=process$1.argv[1];if(e===void 0)throw Error(`the daemon was run with no entry`);return e}function runDaemon(e){let t=daemonPaths(e.host);thisProcess={world:e,paths:t,log:new DaemonLog(t.log,e.clock)},process$1.on(`uncaughtException`,e=>{serverLog(`error`,`uncaughtException: ${e.stack||e.message}`),shutdown(1)}),process$1.on(`unhandledRejection`,e=>{serverLog(`error`,`unhandledRejection: ${String(e)}`),shutdown(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process$1.on(e,()=>{serverLog(`info`,`received ${e}, shutting down`),shutdown(0)});boot().catch(refuseBoot)}function refuseBoot(e){serverLog(`error`,`refusing to boot: ${inspect(e)}`),shutdown(1)}async function boot(){let{world:e,paths:t,log:n}=daemonProcess(),{host:r}=e,i=memoryLimitBytes(r.env);myStartTime=await readOwnStartTime(process$1.pid,systemProbe(e.launcher).startTime);let a=await admitDaemon(realBreakerDeps(e,myStartTime,t.registry));if(!a.decision.allow){serverLog(`warn`,`fork-bomb breaker: ${a.decision.reason}; refusing to boot`),shutdown(1);return}breakerRegistryPath=a.registryPath,fs.mkdirSync(t.state,{recursive:!0}),ensureSocketParentSafe(t.socket);let o=createDaemon({...productionAdapters(t,n,e.clock),renderer:processPort({launcher:e.launcher,entry:processEntry(),cwd:t.state,heapCapMb:heapCapMb(r.env)}),bundle:runningBundle(),host:r,paths:t,memoryLimitBytes:i,registryUrl:r.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:daemonGates(),exit:shutdown});serving=o,armParentWatchdog({clock:e.clock,anchor:anchorFromEnv(r.env),probe:systemProbe(e.launcher),onOrphaned:e=>{serverLog(`info`,`parent watchdog: ${e}; shutting down`),shutdown(0)}}),bindOrAttachAndExit(o,net.createServer(e=>handleConnection(o,e)),t.socket,!1)}function bindOrAttachAndExit(e,t,n,r){t.removeAllListeners(`error`),t.removeAllListeners(`listening`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){serverLog(`error`,`server error: ${i.message}`),shutdown(1);return}if(r){serverLog(`info`,`lost rebind race; another daemon is alive — exiting`),process$1.exit(0);return}handleAddressInUse(e,t,n).catch(refuseBoot)}),t.listen(n,()=>onListening(e,n))}async function handleAddressInUse(e,t,n){let r=await arbitrateSocket(readLease(leasePathFor(n)),(t,n)=>sameLiveProcess(t,n,systemProbe(e.launcher)));if(r.kind===`attach-and-exit`){serverLog(`info`,`EADDRINUSE: ${r.reason} — exiting`),process$1.exit(0);return}serverLog(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{fs.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){serverLog(`error`,`cannot unlink stale socket ${n}: ${e.message}`),shutdown(1);return}}bindOrAttachAndExit(e,t,n,!0)}function onListening(e,t){let n=readSocketIdentity(t);if(n.kind!==`present`){serverLog(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),shutdown(0);return}writeLeaseFile(t);try{fs.chmodSync(t,384)}catch(e){serverLog(`warn`,`chmod socket failed: ${e.message}`)}serverLog(`info`,`daemon up: pid=${process$1.pid} v=3 sock=${t} heapCap=${mb(v8.getHeapStatistics().heap_size_limit)}MB memoryLimit=${mb(e.memoryLimitBytes)}MB`),resetSpawnBackoff(daemonProcess().paths.spawnBackoff),e.arm(),armOwnershipWatch(t,n.identity)}function armOwnershipWatch(e,t){makeOwnershipWatch({bound:t,myPid:process$1.pid,readIdentity:()=>readSocketIdentity(e),readLease:()=>readLease(leasePathFor(e)),shutdown:e=>shutdown(e),log:serverLog,clock:daemonProcess().world.clock}).arm()}function writeLeaseFile(e){let t=writeLease(leasePathFor(e),{pid:process$1.pid,version:3,binPath:process$1.argv[1],startTime:myStartTime});t!==null&&serverLog(`warn`,`lease write failed: ${t}`)}let shuttingDown=!1;function shutdown(e){shuttingDown||(shuttingDown=!0,daemonProcess().world.clock.after(500,()=>process$1.kill(process$1.pid,`SIGKILL`)),closeThenExit(e))}async function closeThenExit(e){let t=[[`close`,()=>serving?.close()],[`lease removal`,()=>removeLeaseIfOwned(daemonProcess().paths.lease,process$1.pid)],[`registry release`,()=>breakerRegistryPath!==null&&releaseRegistration(breakerRegistryPath,process$1.pid,readRegistryEntry,e=>fs.unlinkSync(e))]];for(let[e,n]of t)try{await n()}catch(t){serverLog(`error`,`shutdown ${e} failed: ${inspect(t)}`)}process$1.exit(e)}function runRenderer(e){let t=e=>{process$1.stdout.write(`${JSON.stringify(e)}\n`)},n=hostOverLines(t),r=null,i=!1,a=async t=>{if(!i){if(i=!0,r!==null){let t=await r.answer({kind:`adapter`,push:{kind:`close-session-state`},at:instantAt(e.clock)}).catch(e=>({kind:`threw`,failure:failureOf(e)}));t.kind===`threw`&&process$1.stderr.write(`the session state did not flush: ${t.failure.detail}\n`)}process$1.stdout.write(``,()=>process$1.exit(t))}};process$1.on(`uncaughtException`,e=>{process$1.stderr.write(`uncaughtException: ${e.stack??e.message}\n`),a(1)}),process$1.on(`unhandledRejection`,e=>{process$1.stderr.write(`unhandledRejection: ${inspect(e)}\n`),a(1)});for(let e of[`SIGINT`,`SIGHUP`])process$1.on(e,()=>{});process$1.on(`SIGTERM`,()=>void a(0));let o=null,s=lineSplitter(i=>{let s=JSON.parse(i);if(o!==null){o(s);return}if(s.kind!==`boot`)throw Error(`a ${s.kind} before the boot`);try{r=booted(e,s.boot,n.host)}catch(e){t({kind:`refused`,failure:failureOf(e)}),a(1);return}o=serveRenderer({renderer:r,host:n,send:t,memory:()=>{let{rss:e,heapTotal:t}=process$1.memoryUsage();return{rss:e,heapTotal:t}},heapSnapshot:e=>void v8.writeHeapSnapshot(e)}),t({kind:`started`,pid:process$1.pid})});process$1.stdin.setEncoding(`utf8`),process$1.stdin.on(`data`,e=>s.push(e)),process$1.stdin.on(`end`,()=>{s.end(),a(0)})}function booted(e,t,n){let r=bakedDigest();if(t.digest!==r)throw Error(`the host was built from source ${t.digest??`of no digest`}; this renderer from ${r??`source of no digest`}, which the next daemon runs`);if(t.linkKey.kind===`failed`)throw Error(`the link key could not be read: ${t.linkKey.reason}`);let{host:i}=t,a=daemonPaths(i),{clock:o}=e,s=rendererAdapters(a,o);return loadMainRenderer({clock:o,now:()=>instantAt(o),storage:{...s.storage(n.log),doctor:s.doctorStores},linkSigner:linkSigner(Buffer.from(t.linkKey.value,`base64`)),stateDir:a.state,locations:locations(i),env:i.env,home:i.home,gates:daemonGates(),bundle:t.bundle,memoryLimitBytes:t.memoryLimitBytes}).start(n)}const BUDGETS={connectMs:200,budgetMs:500};async function debugCommandPlan(e,t,n){return debugPlan(t,await fetchDebug(e,t),n.includes(`--json`))}function debugPlan(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
517
517
  `:formatDebug(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${describeFailure(t)}\n`,code:1}}function fetchDebug(e,t){return requestOutcome(e,()=>({kind:`debug`,what:t}),BUDGETS,e=>`debug`in e?e.debug:void 0)}function formatDebug(e){switch(e.what){case`vars`:return formatVars(e.vars);case`segments`:return formatSegments(e.segments);case`config`:return formatConfig(e.config);default:return e}}function formatVars(e){if(e.length===0)return`no variables (DSL not active)
518
518
  `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${fmtAge(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${fmtValue(a.value)}${e}${o}`)}return t.join(`
519
519
  `)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.225.0",
3
+ "version": "1.225.1",
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",
@@ -108,9 +108,9 @@
108
108
  "yaml": "^2.9.1"
109
109
  },
110
110
  "optionalDependencies": {
111
- "@promptctl/cc-candybar-darwin-arm64": "1.225.0",
112
- "@promptctl/cc-candybar-darwin-x64": "1.225.0",
113
- "@promptctl/cc-candybar-linux-x64": "1.225.0",
114
- "@promptctl/cc-candybar-linux-arm64": "1.225.0"
111
+ "@promptctl/cc-candybar-darwin-arm64": "1.225.1",
112
+ "@promptctl/cc-candybar-darwin-x64": "1.225.1",
113
+ "@promptctl/cc-candybar-linux-x64": "1.225.1",
114
+ "@promptctl/cc-candybar-linux-arm64": "1.225.1"
115
115
  }
116
116
  }