@promptctl/cc-candybar 1.62.0 → 1.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -36,7 +36,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{j
36
36
  `).join(`${n}${t}`)}function Hi(e,t,n){let[r,...i]=e,a=i.length===0?t:`{\n ${Vi(Hi(i,t,n),` `,`
37
37
  `)}${n.trailingComma}\n}`;return`${n.key(r)}: ${a}`}function Ui(e,t,n,r){return e.slice(0,t)+r+e.slice(n)}function Wi(e,t){return e.lastIndexOf(`
38
38
  `,t-1)+1}function Gi(e){return/^[ \t]*$/.test(e)}function Ki(e,t){let n=Wi(e,t);return/^[ \t]*/.exec(e.slice(n))[0]}function qi(e,t){return Gi(e.slice(Wi(e,t),t))}const Ji=/(?:\/\/[^\n]*?)?(\r\n|\n|$)/y;function Yi(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n++;let r=e[n]===`,`?n+1:-1;for(r!==-1&&(n=r);n<e.length&&(e[n]===` `||e[n]===` `);)n++;Ji.lastIndex=n;let i=Ji.exec(e);if(i===null)return{commaEnd:r,line:null};let a=n+i[0].length;return{commaEnd:r,line:{at:a-i[1].length,next:a}}}function Xi(e,t){let{commaEnd:n,line:r}=Yi(e,t.end);if(qi(e,t.start)&&r!==null)return Ui(e,Wi(e,t.start),r.next,``);if(n!==-1){let r=n;for(;r<e.length&&e[r]===` `;)r++;return Ui(e,t.start,r,``)}let i=t.start;for(;i>0&&(e[i-1]===` `||e[i-1]===` `);)i--;return e[i-1]===`,`?Ui(e,i-1,t.end,``):Ui(e,t.start,t.end,``)}function Zi(e,t,n,r,i){let a=n.commaEnd!==-1,o=a?e:Ui(e,t.end,t.end,`,`),s=n.line.at+ +!a,c=Bi(e);return Ui(o,s,s,`${c}${i}${Vi(r,i,c)}${a?`,`:``}`)}function Qi(e,t,n,r){let i=t.kind===`object`?t.entries:t.elements,a=i[i.length-1],o=Ki(e,t.span.start);if(a===void 0){let i=o+` `,a=Bi(e);return Ui(e,t.span.start+1,t.span.end-1,`${a}${i}${Vi(n,i,a)}${r.trailingComma}${a}${o}`)}let{commaEnd:s,line:c}=Yi(e,a.span.end);if(qi(e,a.span.start)&&c!==null){let t=e.slice(Wi(e,a.span.start),a.span.start);return Zi(e,a.span,{commaEnd:s,line:c},n,t)}let l=s===-1?a.span.end:s;return Ui(e,l,l,`${s===-1?`, `:` `}${n}${s===-1?``:`,`}`)}function $i(e,t,n,r){if(t.length===0)throw new Ei(`setValue needs a non-empty path`,0);if(/^\s*$/.test(e)){let i=Bi(e);return`{${i} ${Vi(Hi(t,n,r),` `,i)}${r.trailingComma}${i}}${i}`}let i=ji(e);for(let a=0;a<t.length;a++){if(i.kind!==`object`)throw new Ei(`cannot set ${t.join(`.`)}: ${t.slice(0,a).join(`.`)||`the document`} is not an object`,i.span.start);let o=Mi(i,t[a]);if(o===void 0)return Qi(e,i,Hi(t.slice(a),n,r),r);if(a===t.length-1){let t=Ki(e,o.keySpan.start);return Ui(e,o.value.span.start,o.value.span.end,Vi(n,t,Bi(e)))}i=o.value}throw new Ei(`unreachable: path exhausted`,0)}function ea(e,t){if(t.length===0)throw new Ei(`deleteValue needs a non-empty path`,0);if(/^\s*$/.test(e))return e;let n=t.slice(0,-1),r=Ni(ji(e),n),i=r===void 0?void 0:Mi(r,t[t.length-1]);if(i===void 0||r?.kind!==`object`)return e;let a=Xi(e,i.span);return n.length>0&&r.entries.length===1?ea(a,n):a}const ta=[`h`,`v`,`children`];function na(e){if(e.kind===`string`)return e.value;if(e.kind!==`object`)return;let t=Mi(e,`seg`)?.value;if(t?.kind===`string`)return t.value;let n=Mi(e,`kind`)?.value,r=Mi(e,`name`)?.value;return n?.kind===`string`&&n.value===`segment`&&r?.kind===`string`?r.value:void 0}function ra(e){return e.kind===`object`?ta.map(t=>Mi(e,t)?.value).filter(e=>e?.kind===`array`):[]}function ia(e){let t=Mi(e,`rows`)?.value;return t?.kind===`object`?t.entries:null}function aa(e){if(e.kind!==`object`)return!0;let t=ia(e);return t===null||t.length>0||e.entries.some(e=>e.key!==`rows`)}function*oa(e,t){yield{node:e,bareAt:t};for(let t of ra(e))for(let e of t.elements)yield*oa(e,null);for(let n of ia(e)??[])yield*oa(n.value,t===null?null:[...t,`rows`,n.key])}function sa(e,t){for(let{node:n}of oa(e,null))if(na(n)===t)return!0;return!1}function ca(e,t,n){let r=Ni(ji(e),t);if(r===void 0)return null;for(let{node:i,bareAt:a}of oa(r,t))if(na(i)===n)return a===null?{text:e,ref:i}:ca($i(e,a,`{ h: [${Pi(e,i)}] }`,Li),t,n);return null}function la(e,t,n){let r=ca(e,t,n);return r===null?null:Xi(r.text,r.ref.span)}function ua(e,t,n,r,i){let a=ca(e,t,r);if(a===null)return null;let{text:o,ref:s}=a,c=JSON.stringify(n),{commaEnd:l,line:u}=Yi(o,s.span.end);if(qi(o,s.span.start)&&u!==null){let e=o.slice(Wi(o,s.span.start),s.span.start);return i===`after`?Zi(o,s.span,{commaEnd:l,line:u},c,e):Ui(o,s.span.start,s.span.start,`${c},${Bi(o)}${e}`)}let d=Pi(o,s),f=i===`before`?`${c}, ${d}`:`${d}, ${c}`;return Ui(o,s.span.start,s.span.end,f)}var da=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(ha(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function G(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=fa(e,n,i);if(t===-1)return r===void 0?void 0:pa(e,r);n=t,r=t}return r===void 0?void 0:pa(e,r)}function fa(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function pa(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function ma(e,t){try{return ji(t),null}catch(n){if(!(n instanceof Ei))throw n;return`${e}:${pa(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function ha(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
39
- `)}const ga=[`vertical`,`horizontal`];function _a(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*va(e){yield e;for(let t of ya(e))yield*va(t)}function ya(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function ba(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const xa=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Sa(e){return e.kind!==`literal`&&e.kind!==`input`&&e.kind!==`env`&&e.kind!==`state`}const Ca=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],wa=[`file`,`shell`,`git`],Ta=[`left`,`center`,`right`],Ea=[`right`,`left`,`middle`];function Da(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),r])}),null)}function Oa(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),`default`])});return}return i}}function ka(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),r])});return}return i}}function Aa(e,t,n){let r=ka(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[...t.split(`.`),`palette`])});return}return r}}function ja(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Pa(a)}`,line:G(e.source,[...t.split(`.`),r])});return}return a}}function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Na(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Pa(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Fa(e,t,n,r){return Ma(r)?(Ra(e,n,r,t.noun,new Set(Object.keys(t.fields))),Ia(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null)}function Ia(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const La=new Set;function Ra(e,t,n,r,i,a=La){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:G(e.source,[...t.split(`.`),o])})}function za(e,t,n){return e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))}),null}function Ba(e,t,n,r){if(!Ma(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:G(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:G(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:G(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Va(e,t,n,r){if(!Ma(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Na(i)}`,line:G(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:G(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return Ra(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Ha(e,t,n){return{json:$a(Za(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Ua(e){return(...t)=>e()(...t)}function Wa(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:G(n.source,o.split(`.`))}),null}return a}}function K(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ka(e,t,r,n)}}function Ga(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Na(i)}`,line:G(e.source,[n])});return}return i}}}}function Ka(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Pa(o)}`,line:G(e.source,[i])});return}return o}}}}function qa(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Pa(a)}`,line:G(e.source,[r])});return}return a}}}}function Ja(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Aa(e,t,r)}}function Ya(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Da(e,t,r,n)??void 0}}function Xa(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>ja(t,n,i,r,e)}}function Za(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function Qa(e){return Za(e.fields)}function $a(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function eo(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function to(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const no=/^[A-Za-z_][A-Za-z0-9_]*$/;function ro(e){return`#${e+1}`}const io={rows:{}};function ao(e){return`rows`in e}function oo(e){return Object.fromEntries(e.map((e,t)=>[ro(t),e]))}function so(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:oo(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:oo([n])}}function co(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function lo(e){return ao(e)?co(e):e}function uo(e,t){return ao(e)?{...t,...e,rows:{...t.rows,...e.rows}}:so(e)}function fo(e){if(!ao(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}function po(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:mo(t.segments,e.segments??{}),root:uo(e.root??io,t.root),actions:{...t.actions,...e.actions??{}},looks:{...t.looks,...e.looks??{}},presets:mo(t.presets,e.presets??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function mo(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const ho={required:!1,json:{enum:[..._i]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${_i.join(`, `)}`,line:G(e.source,[...t.split(`.`),n])});return}return ja(e,t,r,n,_i)}},go={default_bg:K(),default_fg:K(),default_empty_value:K(),default_separator:K(),default_truncate_marker:K(),palette:Ja(),look:K(),preset:K(),style:Xa(pi),autoWrap:Ga(),padding:Ka(xi),charset:Xa(gi),updateNotice:Ga(),colorCompatibility:ho},_o={noun:`globals key`,fields:go};function vo(e){return{required:!1,json:{not:{},description:`not allowed here — ${e} cannot select a preset`},parse:(t,n,r,i)=>{i[r]!==void 0&&t.issues.push({path:`${n}.${r}`,message:`${n}.${r}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`,line:G(t.source,[...n.split(`.`),r])})}}}const yo={noun:`preset globals key`,fields:{...go,preset:vo(`a preset`)}},bo={noun:`editGlobals key`,fields:{...go,preset:vo(`the editGlobals fragment`)}};function xo(e,t,n){return n===void 0?{}:Fa(e,_o,t,n)??{}}function So(e,t,n){return Fa(e,yo,t,n)??{}}function Co(){return Qa(yo)}function wo(e,t,n){return Fa(e,bo,t,n)??{}}const To=new Set(Object.keys(_o.fields));function Eo(e){return To.has(e)}function Do(){return[...To]}const Oo={padding:1};function ko(e){let t=new Map;for(let[n,r]of Object.entries(Oo)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}function Ao(e,t,n,r){return n.cache===void 0?(wa.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${xa.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):Fo(e,`${t}.cache`,n.cache)}function jo(e,t,n){if(n.cache!==void 0)return Fo(e,`${t}.cache`,n.cache)??void 0}function Mo(e){return{required:!0,json:Ro(),parse:(t,n,r,i)=>Ao(t,n,i,e)??void 0}}function No(){return{required:!1,json:Ro(),parse:(e,t,n,r)=>jo(e,t,r)}}const Po={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Bo(n)?{ttl:n}:za(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Pa(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:za(e,t,`cache.watch_file must be a non-empty path string, got ${Pa(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:za(e,t,`cache.depends_on must be an array of variable-name strings, got ${Pa(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:za(e,t,`cache.key must be a non-empty template string, got ${Pa(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:za(e,t,`cache.never must be the literal boolean true, got ${Pa(n)}`)}}};function Fo(e,t,n){return Ba(e,Po,t,n)}const Io={noun:`time-variable cache`,arms:{ttl:Po.arms.ttl}};function Lo(){return{required:!1,json:to(Io),parse:(e,t,n,r)=>r.cache===void 0?void 0:Ba(e,Io,`${t}.cache`,r.cache)??void 0}}function Ro(){return to(Po)}const zo=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Bo(e){return zo.test(e)}function Vo(e,t,n){if(n===void 0)return{};if(!Ma(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Na(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Va(e,ls,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Ho(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Na(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function Uo(){return{required:!0,json:{enum:[...Ca]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Ca.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Ca.join(`, `)}, got ${JSON.stringify(i)}`,line:G(e.source,[...t.split(`.`),`field`])});return}return i}}}function Wo(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Oa(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Go={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:za(e,t,`parse.text must be the literal boolean true, got ${Pa(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Ko(e,t,n):za(e,t,`parse.regex must be a pattern string, got ${Pa(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:za(e,t,`parse.json must be the literal boolean true, got ${Pa(n)}`)}}};function Ko(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return za(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:za(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function qo(){return{required:!1,json:to(Go),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ba(e,Go,`${t}.parse`,r.parse)??void 0)}}function Jo(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Ma(r.parse)&&`json`in r.parse?Yo(e,t,r.default):ka(e,t,r,`default`)}}function Yo(e,t,n){if(n!==void 0)return Xo(n)?n:za(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Pa(n)}`)??void 0}function Xo(e){return e!==null&&Zo(e)}function Zo(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(Zo);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(Zo)}default:return!1}}const Qo={value:Ho(),default:K()},$o={path:Ya(),type:Xa([`string`,`number`,`boolean`]),default:Wo()},es={name:Ya(),default:K()},ts={path:Ya(),readMode:Xa([`whole`,`first-line`]),parse:qo(),cache:Mo(`file`),default:Jo()},ns={command:Ya(),parse:qo(),cache:Mo(`shell`),default:Jo()},rs={template:Ya(),cache:No(),default:K()},is={layout:Ya(),cache:Lo(),default:K()},as={field:Uo(),cache:Mo(`git`),default:K()},os={key:Ya(),default:K()},ss=`kind`;function cs(e,t){return{...Ha(ss,e,t),parse:(n,r,i)=>{let a=Ia(n,t,r,i);return a===null?null:{kind:e,...a}}}}const ls={tag:ss,noun:`source kind`,memberNoun:`variable`,arms:{literal:cs(`literal`,Qo),input:cs(`input`,$o),env:cs(`env`,es),file:cs(`file`,ts),shell:cs(`shell`,ns),template:cs(`template`,rs),time:cs(`time`,is),git:cs(`git`,as),state:cs(`state`,os)}};function us(){return eo(ls)}function ds(){return{type:`object`,additionalProperties:us()}}function fs(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ps=`groups.`,ms=`menus.`,hs=`edit.`,gs=`settings.`,_s=[ps,ms,hs,gs];function vs(e){return _s.some(t=>e.startsWith(t))}function ys(e){let t=fs(e);return _s.find(e=>t.startsWith(fs(e)))}function bs(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function xs(e){return new Set(Object.keys(e.segments).filter(e=>!vs(e)))}function Ss(e,t,n){if(t===void 0)return{};if(!Ma(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Na(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Fa(e,n.has(i)?Os:Ds,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function Cs(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?za(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own`)??void 0:Da(e,t,r,n)??void 0}}function ws(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${Pa(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function Ts(){return{required:!1,json:ds(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Vo(e,`${t}.${n}`,i)}}}const Es={template:Cs(),width:ws(),justify:Xa(Ta),truncate:Xa(Ea),bg:K(),fg:K(),when:K(),palette:Ja(),vars:Ts()},Ds={noun:`segment key`,fields:Es},Os={noun:`segment key`,fields:{...Es,template:K()}},ks=[`primary`,`secondary`,`accent`],As=[`surface`,`panel`,`surface-lighten-1`],js=[.16,.3],Ms=js.reduce((e,t)=>t>e?t:e),Ns=js.flatMap(e=>ks.flatMap(t=>As.map(n=>({base:n,hue:t,amount:e})))),Ps=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},Fs=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Is=e=>typeof e==`string`&&Fs.includes(e),Ls={"van-der-corput":Ps,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Rs=e=>Ls[e??`van-der-corput`],zs=.37;function Bs(e,t){let n=0,r=1;for(let{index:i,count:a,distribution:o}of e)n+=o(i,a)*r*t,r*=zs;let i=Math.round(n)%t;return i<0?i+t:i}function Vs(e){let t=0,n=1;for(let{index:r,count:i,distribution:a}of e)t+=a(r,i)*n,n*=zs;return t%1}function Hs(e,t){let n=e[Bs(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}const Us=e=>Hs(Ns,e);function Ws(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}function Gs(e,{base:t,hue:n,amount:r}){return sn(Ws(e,t),Ws(e,n),r)}const Ks=2.2;function qs(e,t){let n=Ns.filter(e=>e.hue===t&&e.amount===Ms).map(t=>Gs(e,t)),r=sn(Ws(e,`surface`),Ws(e,t),.92),i=Ws(e,`foreground`),a=Array.from({length:13},(e,t)=>sn(r,i,t/12)).find(e=>n.every(t=>Ln(e,t)>=Ks));if(a===void 0)throw Error(`palette "${e.name}": "${t}" cannot clear the ${Ks} state floor even at foreground`);return a}function Js(e,t){return[`background`,`foreground`].map(t=>Ws(e,t)).reduce((e,n)=>Ln(t,n)>Ln(t,e)?n:e)}const Ys={base:.42,perDepth:.14,cap:.75},Xs={floor:.12,span:.8};function Zs(e,t){return ks[(ks.indexOf(e)+t)%ks.length]}function Qs(e,t){let n=`${t.hue}|${t.depth}`,r=$s.get(e);r===void 0&&(r=new Map,$s.set(e,r));let i=r.get(n);if(i!==void 0)return i;let a=qs(e,Zs(t.hue,t.depth)),o=Math.min(Ys.cap,Ys.base+Ys.perDepth*t.depth),s={state:a,plane:sn(a,Ws(e,`background`),o)};return r.set(n,s),s}const $s=new WeakMap;function ec(e,t,n){let{state:r,plane:i}=Qs(e,t);return sn(i,r,Xs.floor+Xs.span*Vs(n))}const tc={kind:`bar`,address:[]},nc=(e,t)=>({...e,address:[...e.address,t]}),rc=e=>({kind:`band`,band:e,address:[]}),ic=()=>void 0;function ac(e,t){switch(t.kind){case`bar`:{let n=Us(t.address);return{tint:Gs(e,n),text:ic,disclosure:{hue:n.hue,depth:0}}}case`band`:return{tint:ec(e,t.band,t.address),text:t=>Js(e,t),disclosure:{hue:t.band.hue,depth:t.band.depth+1}}}}const oc=`closed`;function sc(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function cc(e,t,n,r){let i=sc(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function lc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function uc(e,t,n,r){return{kind:`segment`,name:e,opens:{ref:t,body:n},...r!==void 0&&{when:r}}}function dc(e,...t){return`{{ and ${[e,...t].map(fc).join(` `)} }}`}function fc(e){return`(eq .${e.variable} "${lc(e.member)}")`}function pc(e,t,n){return`{{ action "${e}" "${lc(t)}" "${lc(n)}" }}`}function mc(e,t){return{kind:`state`,key:e,default:t}}function hc(e,t){return{set:e,cycle:[oc,t]}}const gc=`#/definitions/LayoutNode`,_c={kind:`container`,direction:`vertical`,children:[]};function vc(e){return{required:!0,json:{const:e},parse:()=>e}}function yc(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${Pa(i)}`,line:G(e.source,[`root`])}),``)}}}function bc(){return{required:!0,json:{enum:[...ga]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ga.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${ga.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function xc(e){return{required:!0,json:{type:`array`,items:{$ref:gc}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Na(a)}`,line:G(t.source,[`root`])}),[])}}}const Sc={noun:`layout-node key`,fields:{kind:vc(`segment`),name:yc(),when:K()}},Cc=()=>Xa(Fs),wc={noun:`layout-node key`,fields:{kind:vc(`container`),direction:bc(),children:xc(Ua(()=>kc)),when:K(),distribution:Cc()}};function Tc(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${Pa(i)}`,line:G(e.source,[`root`])}),``)}}}const Ec={noun:`layout-node key`,fields:{seg:Tc(),when:K()}},Dc={noun:`layout-node key`,fields:{h:xc(Ua(()=>kc)),when:K(),distribution:Cc()}},Oc={noun:`layout-node key`,fields:{v:xc(Ua(()=>kc)),when:K(),distribution:Cc()}},kc=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),_c):{kind:`segment`,name:n};if(!Ma(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Na(n)}`,line:G(e.source,[`root`])}),_c;if(n.kind===`container`)return Fa(e,wc,t,n)??_c;if(n.kind===`segment`)return Fa(e,Sc,t,n)??_c;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
39
+ `)}const ga=[`vertical`,`horizontal`];function _a(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*va(e){yield e;for(let t of ya(e))yield*va(t)}function ya(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function ba(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const xa=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Sa(e){return e.kind!==`literal`&&e.kind!==`input`&&e.kind!==`env`&&e.kind!==`state`}const Ca=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],wa=[`file`,`shell`,`git`],Ta=[`left`,`center`,`right`],Ea=[`right`,`left`,`middle`];function Da(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),r])}),null)}function Oa(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),`default`])});return}return i}}function ka(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),r])});return}return i}}function Aa(e,t,n){let r=ka(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[...t.split(`.`),`palette`])});return}return r}}function ja(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Pa(a)}`,line:G(e.source,[...t.split(`.`),r])});return}return a}}function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Na(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Pa(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Fa(e,t,n,r){return Ma(r)?(Ra(e,n,r,t.noun,new Set(Object.keys(t.fields))),Ia(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null)}function Ia(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const La=new Set;function Ra(e,t,n,r,i,a=La){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:G(e.source,[...t.split(`.`),o])})}function za(e,t,n){return e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))}),null}function Ba(e,t,n,r){if(!Ma(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:G(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:G(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:G(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Va(e,t,n,r){if(!Ma(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Na(r)}`,line:G(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Na(i)}`,line:G(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:G(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return Ra(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Ha(e,t,n){return{json:$a(Za(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Ua(e){return(...t)=>e()(...t)}function Wa(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:G(n.source,o.split(`.`))}),null}return a}}function K(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ka(e,t,r,n)}}function Ga(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Na(i)}`,line:G(e.source,[n])});return}return i}}}}function Ka(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Pa(o)}`,line:G(e.source,[i])});return}return o}}}}function qa(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Pa(a)}`,line:G(e.source,[r])});return}return a}}}}function Ja(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Aa(e,t,r)}}function Ya(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Da(e,t,r,n)??void 0}}function Xa(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>ja(t,n,i,r,e)}}function Za(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function Qa(e){return Za(e.fields)}function $a(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function eo(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function to(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const no=/^[A-Za-z_][A-Za-z0-9_]*$/;function ro(e){return`#${e+1}`}const io={rows:{}};function ao(e){return`rows`in e}function oo(e){return Object.fromEntries(e.map((e,t)=>[ro(t),e]))}function so(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:oo(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:oo([n])}}function co(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function lo(e){return ao(e)?co(e):e}function uo(e,t){return ao(e)?{...t,...e,rows:{...t.rows,...e.rows}}:so(e)}function fo(e){if(!ao(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}function po(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:mo(t.segments,e.segments??{}),root:uo(e.root??io,t.root),actions:{...t.actions,...e.actions??{}},looks:{...t.looks,...e.looks??{}},presets:mo(t.presets,e.presets??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function mo(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const ho={required:!1,json:{enum:[..._i]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${_i.join(`, `)}`,line:G(e.source,[...t.split(`.`),n])});return}return ja(e,t,r,n,_i)}},go={default_bg:K(),default_fg:K(),default_empty_value:K(),default_separator:K(),default_truncate_marker:K(),palette:Ja(),look:K(),preset:K(),style:Xa(pi),autoWrap:Ga(),padding:Ka(xi),charset:Xa(gi),updateNotice:Ga(),colorCompatibility:ho},_o={noun:`globals key`,fields:go};function vo(e){return{required:!1,json:{not:{},description:`not allowed here — ${e} cannot select a preset`},parse:(t,n,r,i)=>{i[r]!==void 0&&t.issues.push({path:`${n}.${r}`,message:`${n}.${r}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`,line:G(t.source,[...n.split(`.`),r])})}}}const yo={noun:`preset globals key`,fields:{...go,preset:vo(`a preset`)}},bo={noun:`editGlobals key`,fields:{...go,preset:vo(`the editGlobals fragment`)}};function xo(e,t,n){return n===void 0?{}:Fa(e,_o,t,n)??{}}function So(e,t,n){return Fa(e,yo,t,n)??{}}function Co(){return Qa(yo)}function wo(e,t,n){return Fa(e,bo,t,n)??{}}const To=new Set(Object.keys(_o.fields));function Eo(e){return To.has(e)}function Do(){return[...To]}const Oo={padding:1};function ko(e){let t=new Map;for(let[n,r]of Object.entries(Oo)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}function Ao(e,t,n,r){return n.cache===void 0?(wa.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${xa.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):Fo(e,`${t}.cache`,n.cache)}function jo(e,t,n){if(n.cache!==void 0)return Fo(e,`${t}.cache`,n.cache)??void 0}function Mo(e){return{required:!0,json:Ro(),parse:(t,n,r,i)=>Ao(t,n,i,e)??void 0}}function No(){return{required:!1,json:Ro(),parse:(e,t,n,r)=>jo(e,t,r)}}const Po={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Bo(n)?{ttl:n}:za(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Pa(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:za(e,t,`cache.watch_file must be a non-empty path string, got ${Pa(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:za(e,t,`cache.depends_on must be an array of variable-name strings, got ${Pa(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:za(e,t,`cache.key must be a non-empty template string, got ${Pa(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:za(e,t,`cache.never must be the literal boolean true, got ${Pa(n)}`)}}};function Fo(e,t,n){return Ba(e,Po,t,n)}const Io={noun:`time-variable cache`,arms:{ttl:Po.arms.ttl}};function Lo(){return{required:!1,json:to(Io),parse:(e,t,n,r)=>r.cache===void 0?void 0:Ba(e,Io,`${t}.cache`,r.cache)??void 0}}function Ro(){return to(Po)}const zo=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Bo(e){return zo.test(e)}function Vo(e,t,n){if(n===void 0)return{};if(!Ma(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Na(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Va(e,ls,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Ho(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Na(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function Uo(){return{required:!0,json:{enum:[...Ca]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Ca.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Ca.join(`, `)}, got ${JSON.stringify(i)}`,line:G(e.source,[...t.split(`.`),`field`])});return}return i}}}function Wo(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Oa(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Go={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:za(e,t,`parse.text must be the literal boolean true, got ${Pa(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Ko(e,t,n):za(e,t,`parse.regex must be a pattern string, got ${Pa(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:za(e,t,`parse.json must be the literal boolean true, got ${Pa(n)}`)}}};function Ko(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return za(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:za(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function qo(){return{required:!1,json:to(Go),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ba(e,Go,`${t}.parse`,r.parse)??void 0)}}function Jo(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Ma(r.parse)&&`json`in r.parse?Yo(e,t,r.default):ka(e,t,r,`default`)}}function Yo(e,t,n){if(n!==void 0)return Xo(n)?n:za(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Pa(n)}`)??void 0}function Xo(e){return e!==null&&Zo(e)}function Zo(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(Zo);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(Zo)}default:return!1}}const Qo={value:Ho(),default:K()},$o={path:Ya(),type:Xa([`string`,`number`,`boolean`]),default:Wo()},es={name:Ya(),default:K()},ts={path:Ya(),readMode:Xa([`whole`,`first-line`]),parse:qo(),cache:Mo(`file`),default:Jo()},ns={command:Ya(),parse:qo(),cache:Mo(`shell`),default:Jo()},rs={template:Ya(),cache:No(),default:K()},is={layout:Ya(),cache:Lo(),default:K()},as={field:Uo(),cache:Mo(`git`),default:K()},os={key:Ya(),default:K()},ss=`kind`;function cs(e,t){return{...Ha(ss,e,t),parse:(n,r,i)=>{let a=Ia(n,t,r,i);return a===null?null:{kind:e,...a}}}}const ls={tag:ss,noun:`source kind`,memberNoun:`variable`,arms:{literal:cs(`literal`,Qo),input:cs(`input`,$o),env:cs(`env`,es),file:cs(`file`,ts),shell:cs(`shell`,ns),template:cs(`template`,rs),time:cs(`time`,is),git:cs(`git`,as),state:cs(`state`,os)}};function us(){return eo(ls)}function ds(){return{type:`object`,additionalProperties:us()}}function fs(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ps=`groups.`,ms=`menus.`,hs=`edit.`,gs=`settings.`,_s=[ps,ms,hs,gs];function vs(e){return _s.some(t=>e.startsWith(t))}function ys(e){let t=fs(e);return _s.find(e=>t.startsWith(fs(e)))}function bs(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function xs(e){return new Set(Object.keys(e.segments).filter(e=>!vs(e)))}function Ss(e,t,n){if(t===void 0)return{};if(!Ma(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Na(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Fa(e,n.has(i)?Os:Ds,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function Cs(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?za(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own`)??void 0:Da(e,t,r,n)??void 0}}function ws(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${Pa(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function Ts(){return{required:!1,json:ds(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Vo(e,`${t}.${n}`,i)}}}const Es={template:Cs(),description:K(),width:ws(),justify:Xa(Ta),truncate:Xa(Ea),bg:K(),fg:K(),when:K(),palette:Ja(),vars:Ts()},Ds={noun:`segment key`,fields:Es},Os={noun:`segment key`,fields:{...Es,template:K()}},ks=[`primary`,`secondary`,`accent`],As=[`surface`,`panel`,`surface-lighten-1`],js=[.16,.3],Ms=js.reduce((e,t)=>t>e?t:e),Ns=js.flatMap(e=>ks.flatMap(t=>As.map(n=>({base:n,hue:t,amount:e})))),Ps=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},Fs=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Is=e=>typeof e==`string`&&Fs.includes(e),Ls={"van-der-corput":Ps,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Rs=e=>Ls[e??`van-der-corput`],zs=.37;function Bs(e,t){let n=0,r=1;for(let{index:i,count:a,distribution:o}of e)n+=o(i,a)*r*t,r*=zs;let i=Math.round(n)%t;return i<0?i+t:i}function Vs(e){let t=0,n=1;for(let{index:r,count:i,distribution:a}of e)t+=a(r,i)*n,n*=zs;return t%1}function Hs(e,t){let n=e[Bs(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}const Us=e=>Hs(Ns,e);function Ws(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}function Gs(e,{base:t,hue:n,amount:r}){return sn(Ws(e,t),Ws(e,n),r)}const Ks=2.2;function qs(e,t){let n=Ns.filter(e=>e.hue===t&&e.amount===Ms).map(t=>Gs(e,t)),r=sn(Ws(e,`surface`),Ws(e,t),.92),i=Ws(e,`foreground`),a=Array.from({length:13},(e,t)=>sn(r,i,t/12)).find(e=>n.every(t=>Ln(e,t)>=Ks));if(a===void 0)throw Error(`palette "${e.name}": "${t}" cannot clear the ${Ks} state floor even at foreground`);return a}function Js(e,t){return[`background`,`foreground`].map(t=>Ws(e,t)).reduce((e,n)=>Ln(t,n)>Ln(t,e)?n:e)}const Ys={base:.42,perDepth:.14,cap:.75},Xs={floor:.12,span:.8};function Zs(e,t){return ks[(ks.indexOf(e)+t)%ks.length]}function Qs(e,t){let n=`${t.hue}|${t.depth}`,r=$s.get(e);r===void 0&&(r=new Map,$s.set(e,r));let i=r.get(n);if(i!==void 0)return i;let a=qs(e,Zs(t.hue,t.depth)),o=Math.min(Ys.cap,Ys.base+Ys.perDepth*t.depth),s={state:a,plane:sn(a,Ws(e,`background`),o)};return r.set(n,s),s}const $s=new WeakMap;function ec(e,t,n){let{state:r,plane:i}=Qs(e,t);return sn(i,r,Xs.floor+Xs.span*Vs(n))}const tc={kind:`bar`,address:[]},nc=(e,t)=>({...e,address:[...e.address,t]}),rc=e=>({kind:`band`,band:e,address:[]}),ic=()=>void 0;function ac(e,t){switch(t.kind){case`bar`:{let n=Us(t.address);return{tint:Gs(e,n),text:ic,disclosure:{hue:n.hue,depth:0}}}case`band`:return{tint:ec(e,t.band,t.address),text:t=>Js(e,t),disclosure:{hue:t.band.hue,depth:t.band.depth+1}}}}const oc=`closed`;function sc(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function cc(e,t,n,r){let i=sc(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function lc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function uc(e,t,n,r){return{kind:`segment`,name:e,opens:{ref:t,body:n},...r!==void 0&&{when:r}}}function dc(e,...t){return`{{ and ${[e,...t].map(fc).join(` `)} }}`}function fc(e){return`(eq .${e.variable} "${lc(e.member)}")`}function pc(e,t,n){return`{{ action "${e}" "${lc(t)}" "${lc(n)}" }}`}function mc(e,t){return{kind:`state`,key:e,default:t}}function hc(e,t){return{set:e,cycle:[oc,t]}}const gc=`#/definitions/LayoutNode`,_c={kind:`container`,direction:`vertical`,children:[]};function vc(e){return{required:!0,json:{const:e},parse:()=>e}}function yc(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${Pa(i)}`,line:G(e.source,[`root`])}),``)}}}function bc(){return{required:!0,json:{enum:[...ga]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ga.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${ga.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function xc(e){return{required:!0,json:{type:`array`,items:{$ref:gc}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Na(a)}`,line:G(t.source,[`root`])}),[])}}}const Sc={noun:`layout-node key`,fields:{kind:vc(`segment`),name:yc(),when:K()}},Cc=()=>Xa(Fs),wc={noun:`layout-node key`,fields:{kind:vc(`container`),direction:bc(),children:xc(Ua(()=>kc)),when:K(),distribution:Cc()}};function Tc(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${Pa(i)}`,line:G(e.source,[`root`])}),``)}}}const Ec={noun:`layout-node key`,fields:{seg:Tc(),when:K()}},Dc={noun:`layout-node key`,fields:{h:xc(Ua(()=>kc)),when:K(),distribution:Cc()}},Oc={noun:`layout-node key`,fields:{v:xc(Ua(()=>kc)),when:K(),distribution:Cc()}},kc=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),_c):{kind:`segment`,name:n};if(!Ma(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Na(n)}`,line:G(e.source,[`root`])}),_c;if(n.kind===`container`)return Fa(e,wc,t,n)??_c;if(n.kind===`segment`)return Fa(e,Sc,t,n)??_c;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
40
40
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
41
41
  New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),_c;if(n.kind===`group`){let r=Fa(e,Ic,t,n);return r===null?_c:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),Rc(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),_c}if(a){let r=Fa(e,Ec,t,n);return r===null?_c:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Fa(e,Dc,t,n);return r===null?_c:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=Fa(e,Oc,t,n);return r===null?_c:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),_c};function Ac(){return{required:!0,json:{type:`object`,propertyNames:{pattern:no.source},additionalProperties:{$ref:gc}},parse:(e,t,n,r)=>{let i=r[n];if(!Ma(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Na(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!no.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=kc(e,`${t}.${n}.${r}`,o)}return a}}}const jc={noun:`root key`,fields:{rows:Ac(),when:K(),distribution:Cc()}};function Mc(e,t,n){return Ma(n)&&`rows`in n?Fa(e,jc,t,n)??{rows:{}}:kc(e,t,n)}function Nc(){return{required:!0,json:{type:`string`,pattern:no.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!no.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${oc}", got ${Pa(i)}`,line:G(e.source,[`root`])});return}return i}}}function Pc(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${Pa(i)}`,line:G(e.source,[`root`])});return}return i}}}}function Fc(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Da(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const Ic={noun:`layout-node key`,fields:{kind:vc(`group`),name:Nc(),label:Fc(),open:Ga(),direction:Xa(ga),key:Pc(),bg:K(),fg:K(),when:K(),distribution:Cc(),children:xc(Ua(()=>kc))}};function Lc(e){return e.key??`groups.`+e.name}function Rc(e){let t=ps+e.name;return uc(t,{variable:t,member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},e.when)}function zc(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Bc(e,t){bs(e,t,ps,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&zc(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&Lc(t)===Lc(r)&&zc(e,t.path,`group "${t.name}" shares key "${Lc(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=Lc(t);if(i.has(n)||i.set(n,oc),t.open===!0){let r=i.get(n);r!==`closed`&&zc(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=ps+e.name,r=Lc(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=mc(r,i.get(r)),o[t]=hc(r,e.name),s[t]={template:pc(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}var Vc=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Jc(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Hc=class extends Vc{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Uc=class extends Vc{name=`EvalError`;kind=`EvalError`},Wc=class extends Uc{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Yc(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},Gc=class extends Uc{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},Kc=class extends Uc{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},qc=class extends Uc{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Jc(e,t){let n=e.split(`
42
42
  `),r=t.line-1,i=[];if(r-1>=0&&r-1<n.length&&i.push({num:r,text:n[r-1]??``}),r>=0&&r<n.length&&i.push({num:r+1,text:n[r]??``}),r+1<n.length&&i.push({num:r+2,text:n[r+1]??``}),i.length===0)return``;let a=String(i[i.length-1]?.num??1).length,o=[];for(let e of i)if(o.push(` ${String(e.num).padStart(a,` `)} | ${e.text}`),e.num===t.line){let e=` ${` `.repeat(a)} | `,n=` `.repeat(Math.max(0,t.column-1));o.push(`${e}${n}^`)}return o.join(`
@@ -120,7 +120,7 @@ Config tooling:
120
120
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
121
121
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
122
122
  Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Mc(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Lg(e,t.actions)),t.looks!==void 0&&(r.looks=T_(e,t.looks)),t.presets!==void 0&&(r.presets=D_(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=wo(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=O_(e,t.helpers)),Bc(e,r),Um(e,r),Zm(e,r),bs(e,r,gs,`the global settings menu`),r}const Tv=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function Ev(e){let t=Av(e.termCols),n=Av(e.termRows),r=jv(e.ssh),i=Ov(e.tmux),a=Dv(e.configEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a}}}function Dv(e){return typeof e==`string`&&e!==``?cv(e):void 0}function Ov(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const kv=1e4;function Av(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>kv?kv:t}function jv(e){return typeof e==`boolean`?e:void 0}var Mv=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Nv(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Pv(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new Mv(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new Mv(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Fv(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=Pv(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(Nv(t))})}async function Iv(e,t,n){let r=null;try{r=await Vv(Ne(),t.connectMs);let i=await Fv(r,{v:3,...e},t.budgetMs);return zv(e.kind,i,n)}catch(e){return Bv(e)}finally{r&&r.destroy()}}function Lv(e,t){return typeof e==`string`?e:t}function Rv(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function zv(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=Lv(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Rv(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function Bv(e){if(e instanceof Mv||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function Vv(e,t){return new Promise((n,r)=>{let i=g.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function Hv(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const Uv={connectMs:50,budgetMs:150},Wv={connectMs:50,budgetMs:200};function Gv(e){let t=e.output;return typeof t==`string`?t:void 0}function Kv(e,t,n,r){return Iv({kind:`render`,hookData:e,args:t,cwd:n,...r},Uv,Gv)}function qv(e,t){return Iv({kind:`click`,verb:e,value:t},Wv,Gv)}let Jv=null;function Yv(e){if(Jv!==null)return Jv;r.mkdirSync(c.dirname(e),{recursive:!0});try{Jv=r.statSync(e).size}catch{Jv=0}return Jv}function Xv(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}Jv=0}function Y(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ge(),t=Yv(e);r.appendFileSync(e,n),Jv=t+Buffer.byteLength(n,`utf8`),Jv>=5242880&&Xv(e)}catch(e){Jv=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const Zv=`CC_CANDYBAR_RSS_LIMIT_MB`;function Qv(e){let t=e[Zv];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Zv} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function $v(e){return Qv(e)*2}const ey=1024*1024;function ty(e){return Qv(e)*ey}function ny(e){let t=e.rssLimitBytes??512*ey,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=c.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),ry(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function ry(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function iy(e,t,n={}){let i=Me();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Y,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listSnapshots:()=>{try{return r.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function ay(e={}){if(xy()!==null)return;let n=e.spawn??Sy,r=vy();if(r.kind===`contended`){let e=sy();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),oy(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),oy(n);return}try{oy(n)}finally{by()}}function oy(e){my()&&cy(e)}function sy(){try{let e=r.statSync(Ve());return Date.now()-e.mtimeMs}catch{return null}}function cy(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
123
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function ly(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function uy(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function dy(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function fy(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function py(){try{r.unlinkSync(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function my(){let e=He(),n=Ue(),r=dy(n),i=ly(hy(e),uy(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),gy(e),fy(n,Math.min(r+1,5)),!0)}function hy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function gy(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let _y=null;function vy(){let e=Ve();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return _y={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!yy(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function yy(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function by(){if(!_y)return;let{fd:e,path:t}=_y;_y=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function xy(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function Sy(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${$v(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Cy=`cc-candybar`,wy=`dispatch`,Ty=`set-state`,Ey=`step-state`,Dy=`copy`,Oy=`open-vscode`,ky=`toolbar-toggle`,Ay=`show-config-error`,jy=`show-config-warning`,My=`set-config`,Ny=`step-config`,Py=`reset-config`,Fy=`apply-layout-op`,Iy=`undo`,Ly=`redo`,Ry=`apply-update`,zy=`doctor-run`,By=`doctor-fix`;function Vy(e){return e.map(encodeURIComponent).join(`/`)}function Hy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Uy(e){return`${Cy}://${wy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Vy(e.args)}`)}`).join(`&`)}`}function Wy(e){return new y(e).getAll(`e`).map(Gy)}function Gy(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Ky=`1.62.0`;function qy(){return c.join(f.homedir(),`.claude`,`settings.json`)}function X(e){return{kind:`ok`,value:e}}const Z={kind:`absent`};function Q(e){return{kind:`failed`,reason:e}}function Jy(e,t){return e?.kind===`ok`?e.value:t}const Yy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Xy(e){let t=Yy.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function Zy(e){return e.join(`.`)}function Qy([e,t,n],[r,i,a]){return e-r||t-i||n-a}const $y=`@promptctl/cc-candybar`;async function eb(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return Q(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?Xy(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function tb(e,t){let n=Xy(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=Qy(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function nb(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Zy(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Zy(t.installed)} is newer than the registry's latest release (${Zy(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Zy(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Zy(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const rb=`CCCandybarURLHandler`,ib=[],ab={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function ob(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function sb(e,t){return[e,...t].map(ob).join(` `)}function cb(){return c.join(f.homedir(),`Applications`,`${rb}.app`)}function lb(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function ub(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function db(){return c.join(ub(),`bin`,`cc-candybar`)}function fb(){return c.join(ub(),`dist`,`index.mjs`)}function pb(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
123
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function ly(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function uy(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function dy(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function fy(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function py(){try{r.unlinkSync(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function my(){let e=He(),n=Ue(),r=dy(n),i=ly(hy(e),uy(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),gy(e),fy(n,Math.min(r+1,5)),!0)}function hy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function gy(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let _y=null;function vy(){let e=Ve();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return _y={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!yy(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function yy(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function by(){if(!_y)return;let{fd:e,path:t}=_y;_y=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function xy(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function Sy(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${$v(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Cy=`cc-candybar`,wy=`dispatch`,Ty=`set-state`,Ey=`step-state`,Dy=`copy`,Oy=`open-vscode`,ky=`toolbar-toggle`,Ay=`show-config-error`,jy=`show-config-warning`,My=`set-config`,Ny=`step-config`,Py=`reset-config`,Fy=`apply-layout-op`,Iy=`undo`,Ly=`redo`,Ry=`apply-update`,zy=`doctor-run`,By=`doctor-fix`;function Vy(e){return e.map(encodeURIComponent).join(`/`)}function Hy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Uy(e){return`${Cy}://${wy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Vy(e.args)}`)}`).join(`&`)}`}function Wy(e){return new y(e).getAll(`e`).map(Gy)}function Gy(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Ky=`1.63.0`;function qy(){return c.join(f.homedir(),`.claude`,`settings.json`)}function X(e){return{kind:`ok`,value:e}}const Z={kind:`absent`};function Q(e){return{kind:`failed`,reason:e}}function Jy(e,t){return e?.kind===`ok`?e.value:t}const Yy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Xy(e){let t=Yy.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function Zy(e){return e.join(`.`)}function Qy([e,t,n],[r,i,a]){return e-r||t-i||n-a}const $y=`@promptctl/cc-candybar`;async function eb(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return Q(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?Xy(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function tb(e,t){let n=Xy(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=Qy(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function nb(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Zy(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Zy(t.installed)} is newer than the registry's latest release (${Zy(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Zy(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Zy(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const rb=`CCCandybarURLHandler`,ib=[],ab={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function ob(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function sb(e,t){return[e,...t].map(ob).join(` `)}function cb(){return c.join(f.homedir(),`Applications`,`${rb}.app`)}function lb(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function ub(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function db(){return c.join(ub(),`bin`,`cc-candybar`)}function fb(){return c.join(ub(),`dist`,`index.mjs`)}function pb(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
124
124
  `)}function mb(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function hb(t){let n=ab[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function gb(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function _b(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${$y}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function vb(){let e=mb(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=hb(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(fb()),{recursive:!0}),r.mkdirSync(c.dirname(db()),{recursive:!0}),gb(e,fb()),gb(t.sourcePath,db()),r.chmodSync(db(),493),r.rmSync(c.join(ub(),`url-handler.mjs`),{force:!0});let n=_b(db());return process.stdout.write(`Staged cc-candybar v${Ky} runtime at ${ub()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:db(),distPath:fb(),entryKind:n}}function yb(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${Cy}</string>`,` </array>`,` </dict>`,`</array>`].join(`
125
125
  `)}]}function bb(e){let t=cb();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=Ee({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,pb(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of yb())Ee({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of yb()){let n=Ee({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${Cy}:// with Launch Services\n`);let a=Ee({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${rb}.app installed and registered.\n`),process.stdout.write(` Test: open '${Cy}://hello-world' && pbpaste\n`)}function xb(){lb(),bb(vb().distPath)}function Sb(e,t=Cy){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:Dy,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Cb(e){e||(process.stderr.write(`url-handle: missing URL argument.
126
126
  `),process.exit(1));let t;try{t=Sb(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await qv(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(ay(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(wb(n)+`
@@ -133,7 +133,7 @@ Config tooling:
133
133
  `)?r.slice(0,-1):r}return Vr(new jr([...e],n),{colorSystem:t.colorCompatibility})}function ux(e){return Math.min(20,e??20)}const dx={heading:`ERROR`,glyph:`⚠`,colors:rx},fx={heading:`WARNING`,glyph:`⚠`,colors:ix},px={heading:`UPDATE`,glyph:`⬆`,colors:ix};function mx(e,t){return{text:Qb(e),link:t}}function hx(e,t,n){let[r,...i]=[gx(e,dx,Ay),t,gx(n,fx,jy)].flat();return r===void 0?null:{channels:[r,...i]}}function gx(e,t,n){let r=Uy([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>mx(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function _x(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
134
134
  `)}function vx(e,t,n,r){if(t===null)return e;let i=yx(r),a=t.channels.flatMap(e=>bx(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[xx(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
135
135
  `);return e?`${l}\n${e}`:l}function yx(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function bx(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=j(Math.max(2,t.width-1)),i=(e,t)=>new Ar(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>lx([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Bt(e,r)).map(e=>i(e,t))})],t).split(`
136
- `))}function xx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${Qb(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(Qb(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,lx([m],r)}const Sx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Cx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function wx(e,t){return r.readdirSync(t).filter(Sx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?wx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Cx(i,a)]]})}function Tx(e){let t=C.createHash(`sha256`);for(let[n,r]of wx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ex=e=>e.slice(0,7);function Dx(e){return c.dirname(c.dirname(e))}function Ox(){return{version:Ky,digest:`afa7ba179f67110be71f37cb431d0b9b762ce5701f53773359ad21fd91ed13f4`}}function kx(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Ax(e,t){try{let n=Dx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Tx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:kx(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const jx=/^-?\d+$/;function Mx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Nx(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function Px(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!jx.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function Fx(e,t,n){return r=>r?jx.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function Ix(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!jx.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:Mx(r[0].seed,t,i)}}return{kind:`int`}}function Lx(e){return e===`config`?`set-config`:`set-state`}function Rx(e,t,n){return t.kind===`int`?Px(`menu page "${e}"`):t.kind===`range`?Fx(t.min,t.max,`${n} stepper "${e}"`):Nx(t.allowed,`${n} "${e}"`,Lx(n))}function zx(e,t,n){return Rx(e,Ix(e,t,n),n)}function Bx(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:Ix(e,n,t)}))}function Vx(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=zx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:zx(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=zx(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=Ix(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Hx=Vx({},`config`);function Ux(){return Hx.listKeys()}function Wx(e,t){return Hx.validate(e,t)}function Gx(e){return Hx.rangeParamsFor(e)}function Kx(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.insertSegmentFrom,n).map(t=>Qm({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:Mx(t.get(e.persist),e.min,e.max)}}]:[]}function qx(e){return ko(e.globals)}function Jx(e){let t=new Set;for(let n of Xx(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=dh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:uh(e),spec:{kind:`allow-list`,allowed:[]}}))}function Yx(e){let t=qx(e),n=new Map([...j_(e),...wh(e)]);return[...Jx(e),...Xx(e).flatMap(e=>Kx(e,t,n))]}function Xx(e){return Object.values(e.actions).flatMap(Ag)}function Zx(e){return Bx(Yx(e),`config`)}function Qx(e,t){return Hx.register(e,t)}const $x=li(),eS=new Set($x),tS=new Set(pi),nS=e=>e?eS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${$x.join(`, `)})`}:{ok:!1,reason:`theme name is required`},rS=e=>e?tS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},iS=new Set([`1`,`true`]),aS=new Set([`0`,`false`]),oS=Vx({style:rS,theme:nS,"toolbar-expanded":e=>iS.has(e)?{ok:!0,value:`1`}:aS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function sS(){return oS.listKeys()}function cS(e,t){return oS.register(e,t)}function lS(e,t){return oS.validate(e,t)}function uS(e){return oS.rangeParamsFor(e)}function dS(e,t,n){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:N_(e.from,n)}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:Mx(t.get(e.set),e.min,e.max)}}]:[]}function fS(e){let t=new Set(oS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function pS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function mS(e){let t=pS(e),n=j_(e);return fS(Object.values(e.actions).flatMap(Ag).flatMap(e=>dS(e,t,n)))}function hS(e){return Bx(mS(e))}const gS=`update.dismissed`,_S=`updateNotice`;function vS(e){return e.kind===`source`?e.newer.digest:Zy(e.newer)}const yS=e=>`${e.version} [${Ex(e.digest)}]`;function bS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:yS(e.newer),running:yS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Zy(e.newer),running:Zy(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${$y}@${Zy(e.newer)}`,`install`]}}}}const xS={kind:`idle`},SS={kind:`running`};function CS(e,t,n){if(e===null)return[];let r=vS(e);if(!n.enabled||n.dismissed===r)return[];let i=bS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
136
+ `))}function xx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${Qb(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(Qb(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,lx([m],r)}const Sx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Cx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function wx(e,t){return r.readdirSync(t).filter(Sx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?wx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Cx(i,a)]]})}function Tx(e){let t=C.createHash(`sha256`);for(let[n,r]of wx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ex=e=>e.slice(0,7);function Dx(e){return c.dirname(c.dirname(e))}function Ox(){return{version:Ky,digest:`85d00d91319b1f3092c102be3247ae414a5eda9661385420ee756302bd60830c`}}function kx(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Ax(e,t){try{let n=Dx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Tx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:kx(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const jx=/^-?\d+$/;function Mx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Nx(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function Px(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!jx.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function Fx(e,t,n){return r=>r?jx.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function Ix(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!jx.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:Mx(r[0].seed,t,i)}}return{kind:`int`}}function Lx(e){return e===`config`?`set-config`:`set-state`}function Rx(e,t,n){return t.kind===`int`?Px(`menu page "${e}"`):t.kind===`range`?Fx(t.min,t.max,`${n} stepper "${e}"`):Nx(t.allowed,`${n} "${e}"`,Lx(n))}function zx(e,t,n){return Rx(e,Ix(e,t,n),n)}function Bx(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:Ix(e,n,t)}))}function Vx(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=zx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:zx(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=zx(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=Ix(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const Hx=Vx({},`config`);function Ux(){return Hx.listKeys()}function Wx(e,t){return Hx.validate(e,t)}function Gx(e){return Hx.rangeParamsFor(e)}function Kx(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.from,n)}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Qm({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:N_(e.insertSegmentFrom,n).map(t=>Qm({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:Mx(t.get(e.persist),e.min,e.max)}}]:[]}function qx(e){return ko(e.globals)}function Jx(e){let t=new Set;for(let n of Xx(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=dh(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:uh(e),spec:{kind:`allow-list`,allowed:[]}}))}function Yx(e){let t=qx(e),n=new Map([...j_(e),...wh(e)]);return[...Jx(e),...Xx(e).flatMap(e=>Kx(e,t,n))]}function Xx(e){return Object.values(e.actions).flatMap(Ag)}function Zx(e){return Bx(Yx(e),`config`)}function Qx(e,t){return Hx.register(e,t)}const $x=li(),eS=new Set($x),tS=new Set(pi),nS=e=>e?eS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${$x.join(`, `)})`}:{ok:!1,reason:`theme name is required`},rS=e=>e?tS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},iS=new Set([`1`,`true`]),aS=new Set([`0`,`false`]),oS=Vx({style:rS,theme:nS,"toolbar-expanded":e=>iS.has(e)?{ok:!0,value:`1`}:aS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function sS(){return oS.listKeys()}function cS(e,t){return oS.register(e,t)}function lS(e,t){return oS.validate(e,t)}function uS(e){return oS.rangeParamsFor(e)}function dS(e,t,n){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:N_(e.from,n)}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:Mx(t.get(e.set),e.min,e.max)}}]:[]}function fS(e){let t=new Set(oS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function pS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function mS(e){let t=pS(e),n=j_(e);return fS(Object.values(e.actions).flatMap(Ag).flatMap(e=>dS(e,t,n)))}function hS(e){return Bx(mS(e))}const gS=`update.dismissed`,_S=`updateNotice`;function vS(e){return e.kind===`source`?e.newer.digest:Zy(e.newer)}const yS=e=>`${e.version} [${Ex(e.digest)}]`;function bS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:yS(e.newer),running:yS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Zy(e.newer),running:Zy(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${$y}@${Zy(e.newer)}`,`install`]}}}}const xS={kind:`idle`},SS={kind:`running`};function CS(e,t,n){if(e===null)return[];let r=vS(e);if(!n.enabled||n.dismissed===r)return[];let i=bS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
137
137
  `),c=Uy([{verb:jy,args:[s]}]),l=t.kind===`running`?mx(`[${i.busy}]`,c):mx(`[${i.act}]`,Uy([{verb:Ry,args:[n.sessionId]}]));return[{severity:px,message:s,lines:[[mx(a,c),l,mx(`[dismiss]`,Uy([{verb:Ty,args:[n.sessionId,gS,r]}])),mx(`[disable]`,Uy([{verb:My,args:[n.sessionId,_S,`false`]}]))],...o.map(e=>[mx(e,c)])]}]}function wS(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function TS(e){switch(e.kind){case`current`:return[`info`,`build: current ${yS(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${yS(e.source)}, running ${yS(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function ES(e){switch(e.kind){case`current`:return[`info`,`release: current ${Zy(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Zy(e.latest)}, running ${Zy(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Zy(e.installed)}, latest ${Zy(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function DS(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const OS=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function kS(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=OS(e.stderr)??e.error??OS(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function AS(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=xS,d=null,f=DS(s),p=DS(s),m=()=>wS(c,l);function h(){let e=m(),t=e===null?null:vS(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:cS(gS,{kind:`allow-list`,allowed:[t]})})}function g(){c=Ax(t,Ox),f(TS(c)),h()}async function _(){l=tb(Ky,await eb($y,a,i)),p(ES(l)),h()}return{arm(){Qx(_S,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>CS(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=bS(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=SS,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Te({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=xS,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=kS(n);u={kind:`failed`,identity:vS(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function jS(e,t,n){return t.ok?X(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??MS(t.stderr)].filter(Boolean).join(`, `)}`)}function MS(e){return e.trim().split(`
138
138
  `,1)[0]??``}function NS(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Z:X(n)}function PS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?X(t):Z}const FS=/^[A-Za-z]:[\\/]/;function IS(e){let t=e.trim();if(FS.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function LS(e){return IS(e)?.host||null}function RS(e){let t=LS(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function zS(e){let t=new Map;for(let n of e.split(`
139
139
  `)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function BS(e){return e.urls.find(e=>GS(e)!==null)??e.urls[0]??null}function VS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function HS(e){let t=VS(e);return t?BS(t):null}function US(e){let t=VS(e);return t?t.urls.find(e=>RS(e)!==null)??BS(t):null}function WS(e){let t=(IS(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function GS(e){let t=IS(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function KS(e){let t=HS(e);return t===null?null:GS(t)}function qS(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??MS(t.stderr)].filter(Boolean).join(`, `)}`)}function JS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function YS(e){let t=`detached`,n=Z,r=Z,i=Z,a=0,o=0,s=0,c=0;for(let l of e.split(`
@@ -141,7 +141,7 @@ Config tooling:
141
141
  `).length:0)}async getRemotesAsync(e){let t=QS(c.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=jS(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:X(t.kind===`ok`?zS(t.value):[])}repoNameFrom(e,t){let n=HS(e);return(n===null?null:WS(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=US(t.value);return n===null?Z:X(n)}async execForgeAsync(e,t,n){return Te({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=RS(t);return n===`github`?qS(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,XS):n===`gitlab`?qS(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,ZS):Z}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=jS(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?X(YS(t.value)):t}};const eC=(e,t)=>D(t);var tC=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??eC}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},nC=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const rC=(e,t)=>D(t),iC={showSha:!0,showStashCount:!0};function aC(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function oC(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function sC(e,t){return e.head!==t.head||e.index!==t.index}function cC(e){let t=[],n=c.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[c.join(e,`HEAD`),c.join(e,`index`)],dirs:t}}var lC=class extends $S{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new nC;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new $S,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??rC,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new tC({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${aC(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(X(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=oC(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,cC(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Z;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,cC(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...iC});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...iC}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=oC(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),sC(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},uC=class{static CACHE_DIR=O();static USAGE_CACHE_DIR=c.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=c.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=c.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return D(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=c.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ne(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=c.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return ee(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=c.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){D(`Cache for ${e} is locked, waiting...`),await ne(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ne(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=c.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const dC={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var fC=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await uC.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await uC.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new v(this.GITHUB_PRICING_URL),n=te({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(dC).length} models`),this.executionCache=dC,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(dC).length} models`),dC)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};function pC(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const mC=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function hC(e){return((...t)=>mC.run(()=>e(...t)))}const gC=hC(ie),_C=hC(w),vC=hC(T);async function yC(e,t){return mC.run(async()=>{let n=null;try{n=await re(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return X({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return X({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Z:Q(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function bC(e,t){return mC.run(async()=>{let n=null;try{n=await re(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return X({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Z:Q(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}function xC(){let e=[],t=process.env.CLAUDE_CONFIG_DIR;if(t&&t.split(`,`).forEach(t=>{let n=t.trim();a(n)&&e.push(n)}),e.length===0){let t=p(),n=d(t,`.config`,`claude`),r=d(t,`.claude`);a(n)&&e.push(n),a(r)&&e.push(r)}return e}async function SC(e){let t=[];for(let n of e){let e=d(n,`projects`);if(a(e))try{let n=await gC(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function CC(e,t,n){let r=[],i=d(t,e,`subagents`);try{let t=(await gC(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=d(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await _C(t,`utf-8`)).split(`
142
142
  `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}const wC=new Map;async function TC(e){try{let t=await vC(e),n=t.size,r=wC.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),wC.delete(e),wC.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await AC(e)):i=await OC(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(wC.delete(e),wC.size>=16&&wC.delete(wC.keys().next().value),wC.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function EC(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function DC(e){let t=[];for(let n of e.split(`
143
143
  `))if(n.trim())try{let e=EC(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function OC(e){return DC(await _C(e,`utf-8`))}async function kC(e,t){let n=await yC(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return X(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:DC(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function AC(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=E({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=EC(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var jC=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function MC(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const NC={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},PC={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function FC(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function IC(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function LC(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function RC(e,t,n,r){let i=FC(new Date(IC())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:LC(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await fC.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=FC(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...NC};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function zC(e){let t=0,n=0,r=LC(),i=new Map;for(let a of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...NC};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:PC,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function BC(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var VC=class{entries=new Map;flight=new jC;seeded=new Map;speedRings=new Map;speedFlight=new jC;maxEntries;staleAgeMs;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:PC,i=t?.cost?.total_cost_usd??null;return X({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e){let t=FC(new Date);try{await this.ensureSeeded(t)}catch(e){return Q(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let n=await this.ingest(e?.session_id??``,e?.transcript_path);if(n.kind===`failed`)return n;let r={...NC},i=!1;for(let e of this.entries.values()){i||=e.days.has(t);let n=e.days.get(t)??NC;r.cost+=n.cost,r.input+=n.input,r.output+=n.output,r.cacheCreation+=n.cacheCreation,r.cacheRead+=n.cacheRead}return i?X({cost:r.cost,tokens:r.input+r.output+r.cacheCreation+r.cacheRead,tokenBreakdown:{input:r.input,output:r.output,cacheCreation:r.cacheCreation,cacheRead:r.cacheRead},date:t}):Z}async observeSpeed(e,t,n){let r=pC(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=MC(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),X({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Z;let r=n??pC(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,X(i);if(!t)return i?X(i):Z;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return Q(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),X(o)}async refold(e,t,n){let r=await CC(e,u(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await kC(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await RC(r,l,s,c)),e===t&&(a=c.mtimeMs)}return X({files:i,...zC(i),mainMtime:a})}ensureSeeded(e){let t=this.seeded.get(e);if(t)return t;this.seeded.clear();let n=this.seed(e);return this.seeded.set(e,n),n.catch(()=>{this.seeded.get(e)===n&&this.seeded.delete(e)}),n}async seed(e){let t=IC(),n=await SC(xC()),r=[];for(let e of n){let n;try{n=await gC(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a;try{a=(await vC(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await BC(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&Y(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,Y(`info`,`usageStore seed sessions=${r.length}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,Y(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),Y(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}};const HC=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function UC(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function WC(e){let t=await GC(e);return t.kind===`ok`?X(Math.floor((t.value+36e5)/1e3)):t}async function GC(e){for(let t of[65536,1048576]){let n=await bC(e,t);if(n.kind!==`ok`)return n;let r=KC(n.value.buf,n.value.fromStart);if(r!=null)return X(r);if(n.value.fromStart)return Z}return Z}function KC(e,t){let n=e.toString(`utf8`).split(`
144
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!HC.test(t))continue;let r=UC(t);if(r!=null)return r}return null}function qC(e,t,n){let r=ih(t(`preset`),e.globals.preset,e.presets),i=sh(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:si(a.palette,t(`theme`),i.palette),look:di(a.look,t(`look`),i.look,e.looks),style:hi(a.style,t(`style`),i.style),separator:a.default_separator??i.default_separator,autoWrap:wi(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Ti(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}const JC=10*1e3;function YC(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function XC(e,t){if(!(t<60))return e*3600/t}function ZC(e,t,n,r){let i=r-t;if(i<50||i>JC)return;let a=n-e;if(!(a<=0))return a*1e3/i}function QC(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=ZC(t.input,t.atMs,n.input,n.atMs),i=ZC(t.output,t.atMs,n.output,n.atMs),a=ZC(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function $C(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>JC)continue;let o=ZC(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function ew(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function tw(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>ew(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function nw(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,r);for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,i);let n=[],r=new Set;for(let t of va(co(e.root))){if(t.when)for(let e of L_(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of L_(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of rw(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of L_(e.template))n.push(t)}}}return i}function rw(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function iw(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function aw(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function ow(e,t,n,r,i,a){let o=e=>iw(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Q(`${e}: ${String(t)}`)):Promise.resolve(Z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,aw(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>WC(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=lw(l);_.push(...y.failures);let b=tw(a);_.push(...b.failures);let x=v(u),S=v(d),C=v(f),ee=v(p),te=v(m),ne=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let re=e.rate_limits?.five_hour,w=e.rate_limits?.seven_day,ie=re?YC(re.used_percentage,re.resets_at,18e6,s):void 0,T=w?YC(w.used_percentage,w.resets_at,6048e5,s):void 0,E=x?.session.cost,ae=ee?.sessionDuration,oe=o(`burn`)&&E!=null&&ae!=null?XC(E,ae):void 0,se=v(g),ce=se===void 0?void 0:QC(se),le=se===void 0?void 0:$C(se),ue=ce!==void 0||le!==void 0?{...ce,...le!==void 0&&{history:le}}:void 0,de=cw(process.env.HOME??process.env.USERPROFILE),fe=e.workspace?{...e.workspace,current_dir:cw(e.workspace.current_dir)??``,project_dir:cw(e.workspace.project_dir)??``}:e.workspace,pe=x===void 0?void 0:sw({cost:x.session.cost,tokens:x.session.tokens}),me=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},he=ee===void 0?void 0:sw({lastResponseTime:ee.lastResponseTime,responseTime:ee.responseTime,sessionDuration:ee.sessionDuration,messageCount:ee.messageCount,linesAdded:ee.linesAdded,linesRemoved:ee.linesRemoved});return{...e,...fe!==void 0&&{workspace:fe},...de!==void 0&&{home:de},...y.git!==void 0&&{git:y.git},...te!==void 0&&{tmux:{session:te}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...pe!==void 0&&{session:pe},...me!==void 0&&{today:me},...oe!==void 0&&{burn:{costPerHour:oe}},...ue!==void 0&&{speed:ue},...o(`block`)&&re!==void 0&&{block:{nativeUtilization:re.used_percentage,resetsAt:re.resets_at,...ie!==void 0&&{etaMinutes:ie}}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at,...T!==void 0&&{etaMinutes:T}}},...ne!==void 0&&{cache:{expiresAt:ne}},...C!==void 0&&{context:{totalTokens:C.totalTokens,contextLeft:C.contextLeftPercentage}},...he!==void 0&&{metrics:he}}}function sw(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function cw(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function lw(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const uw=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,dw=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${uw}) (basename .project_dir) (ne (${uw}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,fw={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},pw=(e,t)=>`{{ fg (color "${fw[e]}") ${t} }}`,mw=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,hw=`{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} ({{ \$first := true }}{{ if gt .git.staged 0 }}${pw(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${pw(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${pw(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${pw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,gw=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${pw(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${pw(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${pw(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+hw+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${pw(`stash`,`(printf "⧇ %v" .git.stash)`)}{{ end }} {{ if eq .git.status "conflicts" }}{{ fg (color "error") "⚠" }}{{ else }}{{ if eq .git.status "dirty" }}{{ fg (color "warning") "●" }}{{ else }}{{ fg (color "success") "✓" }}{{ end }}{{ end }}`,_w={globals:{palette:`tokyo-night`},variables:{current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},version:{kind:`input`,path:`version`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"style.effective":{kind:`input`,path:`style.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0}},segments:{directory:{template:dw,fg:`foreground`},model:{template:`✱ {{ formatModelName .model.display_name }}`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{template:`⌗{{ trunc 8 .session.id }}`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{template:`◈ v{{ .version }}`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{template:`tmux:{{ .tmux.session | default "none" }}`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{template:gw,fg:mw,when:`{{ ne .git.branch "" }}`},gitaculous:{template:`(git){{ if ne .git.repoName "" }} {{ .git.repoName }}{{ end }}{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} {{ if gt .git.staged 0 }}${pw(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${pw(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${pw(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${pw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${pw(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${pw(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${pw(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${pw(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,fg:mw,when:`{{ ne .git.branch "" }}`},gitPr:{template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,fg:`foreground`},session:{template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,fg:`foreground`},today:{template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,fg:`foreground`},block:{template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 "panel" .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .block.nativeUtilization) "step" 0 "foreground" .block.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 "panel" .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .weekly.percentage) "step" 0 "foreground" .weekly.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 "panel" 0 "error" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes "panel" }}`,fg:`{{ ramp .block.etaMinutes "step" -1 "foreground" 0 "button-color-foreground" .burn.eta.warnMinutes "foreground" }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{template:`⚡ {{ sparkline .speed.history 24 }}`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ if le (minutesUntilReset .cache.expiresAt) 8 }}error{{ else }}{{ if le (minutesUntilReset .cache.expiresAt) 20 }}warning{{ else }}foreground{{ end }}{{ end }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 "surface-active" }}`,fg:`{{ ramp .context.contextLeft "step" 0 "button-color-foreground" 41 "foreground" }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},charsetControl:{template:`{{ .charset.effective }} {{ menu "applyCharsetForever" "▸" "▾" }} {{ action "resetCharset" "↺" }}`,fg:`foreground`},colorCompatControl:{template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" "▸" "▾" }} {{ action "resetColorCompat" "↺" }}`,fg:`foreground`},directoryPaletteControl:{template:`🎨 directory {{ menu "applyDirectoryPaletteForever" "▸" "▾" }} {{ action "resetDirectoryPalette" "↺" }}`,fg:`foreground`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ terminal`,direction:`horizontal`,children:[`charsetControl`,`colorCompatControl`,`directoryPaletteControl`]}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}}},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`},{kind:`segment`,name:`toolbar`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},vw=new Set([_w.globals.palette,...Object.values(_w.segments).map(e=>e.palette)].filter(e=>e!==void 0)),yw=po(bv(`<default>`,JSON.stringify(_w),vw),_w);var bw=pe((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:en}function r(){sn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===cn}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){nn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){nn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return rn.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(re())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&w(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ie(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function C(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
144
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!HC.test(t))continue;let r=UC(t);if(r!=null)return r}return null}function qC(e,t,n){let r=ih(t(`preset`),e.globals.preset,e.presets),i=sh(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:si(a.palette,t(`theme`),i.palette),look:di(a.look,t(`look`),i.look,e.looks),style:hi(a.style,t(`style`),i.style),separator:a.default_separator??i.default_separator,autoWrap:wi(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Ti(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}const JC=10*1e3;function YC(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function XC(e,t){if(!(t<60))return e*3600/t}function ZC(e,t,n,r){let i=r-t;if(i<50||i>JC)return;let a=n-e;if(!(a<=0))return a*1e3/i}function QC(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=ZC(t.input,t.atMs,n.input,n.atMs),i=ZC(t.output,t.atMs,n.output,n.atMs),a=ZC(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function $C(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>JC)continue;let o=ZC(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function ew(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function tw(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>ew(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function nw(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,r);for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,i);let n=[],r=new Set;for(let t of va(co(e.root))){if(t.when)for(let e of L_(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of L_(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of rw(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of L_(e.template))n.push(t)}}}return i}function rw(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function iw(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function aw(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function ow(e,t,n,r,i,a){let o=e=>iw(r,e),s=(t.clock??(()=>new Date))().getTime(),c=(e,t,n)=>t?n().catch(t=>Q(`${e}: ${String(t)}`)):Promise.resolve(Z),[l,u,d,f,p,m,h,g]=await Promise.all([c(`git`,o(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,aw(r),e.workspace?.project_dir)),c(`session`,o(`session.cost`)||o(`session.tokens`)||o(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),c(`today`,o(`today`),()=>t.usageStore.getTodayInfo(e)),c(`context`,o(`context`),()=>t.contextProvider.getContextInfo(e)),c(`metrics`,o(`metrics`)||o(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),c(`tmux`,o(`tmux`),()=>t.tmuxService.getSessionId()),c(`cache`,o(`cache`),()=>WC(e.transcript_path)),c(`speed`,o(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,s))]),_=[],v=e=>{if(e.kind===`failed`){_.push(e.reason);return}return e.kind===`ok`?e.value:void 0},y=lw(l);_.push(...y.failures);let b=tw(a);_.push(...b.failures);let x=v(u),S=v(d),C=v(f),ee=v(p),te=v(m),ne=v(h);for(let e of _)t.log(`warn`,`provider fetch failed: ${e}`);let re=e.rate_limits?.five_hour,w=e.rate_limits?.seven_day,ie=re?YC(re.used_percentage,re.resets_at,18e6,s):void 0,T=w?YC(w.used_percentage,w.resets_at,6048e5,s):void 0,E=x?.session.cost,ae=ee?.sessionDuration,oe=o(`burn`)&&E!=null&&ae!=null?XC(E,ae):void 0,se=v(g),ce=se===void 0?void 0:QC(se),le=se===void 0?void 0:$C(se),ue=ce!==void 0||le!==void 0?{...ce,...le!==void 0&&{history:le}}:void 0,de=cw(process.env.HOME??process.env.USERPROFILE),fe=e.workspace?{...e.workspace,current_dir:cw(e.workspace.current_dir)??``,project_dir:cw(e.workspace.project_dir)??``}:e.workspace,pe=x===void 0?void 0:sw({cost:x.session.cost,tokens:x.session.tokens}),me=S===void 0?void 0:{cost:S.cost,tokens:S.tokens},he=ee===void 0?void 0:sw({lastResponseTime:ee.lastResponseTime,responseTime:ee.responseTime,sessionDuration:ee.sessionDuration,messageCount:ee.messageCount,linesAdded:ee.linesAdded,linesRemoved:ee.linesRemoved});return{...e,...fe!==void 0&&{workspace:fe},...de!==void 0&&{home:de},...y.git!==void 0&&{git:y.git},...te!==void 0&&{tmux:{session:te}},host:b.host,theme:{effective:i.theme},look:{effective:i.look},preset:{effective:i.preset,customized:i.presetCustomized},style:{effective:i.style},charset:{effective:i.charset},colorCompatibility:{effective:i.colorCompatibility},autoWrap:{effective:i.autoWrap},padding:{effective:i.padding},...pe!==void 0&&{session:pe},...me!==void 0&&{today:me},...oe!==void 0&&{burn:{costPerHour:oe}},...ue!==void 0&&{speed:ue},...o(`block`)&&re!==void 0&&{block:{nativeUtilization:re.used_percentage,resetsAt:re.resets_at,...ie!==void 0&&{etaMinutes:ie}}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at,...T!==void 0&&{etaMinutes:T}}},...ne!==void 0&&{cache:{expiresAt:ne}},...C!==void 0&&{context:{totalTokens:C.totalTokens,contextLeft:C.contextLeftPercentage}},...he!==void 0&&{metrics:he}}}function sw(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function cw(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function lw(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const uw=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,dw=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${uw}) (basename .project_dir) (ne (${uw}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,fw={branch:`primary`,staged:`success`,unstaged:`warning`,untracked:`accent`,conflicts:`error`,ahead:`success`,behind:`warning`,stash:`accent`},pw=(e,t)=>`{{ fg (color "${fw[e]}") ${t} }}`,mw=`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,hw=`{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} ({{ \$first := true }}{{ if gt .git.staged 0 }}${pw(`staged`,`(printf "+%v" .git.staged)`)}{{ $first = false }}{{ end }}{{ if gt .git.unstaged 0 }}{{ if not $first }} {{ end }}${pw(`unstaged`,`(printf "~%v" .git.unstaged)`)}{{ $first = false }}{{ end }}{{ if gt .git.untracked 0 }}{{ if not $first }} {{ end }}${pw(`untracked`,`(printf "?%v" .git.untracked)`)}{{ $first = false }}{{ end }}{{ if gt .git.conflicts 0 }}{{ if not $first }} {{ end }}${pw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ $first = false }}{{ end }}){{ end }}`,gw=`{{ if ne .git.repoName "" }}{{ .git.repoName }} {{ end }}⎇ ${pw(`branch`,`.git.branch`)}{{ if .git.sha }} ♯ {{ .git.sha }}{{ end }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${pw(`ahead`,`(printf "↑%v" .git.ahead)`)}{{ end }}{{ if gt .git.behind 0 }}${pw(`behind`,`(printf "↓%v" .git.behind)`)}{{ end }}{{ end }}`+hw+`{{ if .git.upstream }} →{{ .git.upstream }}{{ end }}{{ if gt .git.stash 0 }} ${pw(`stash`,`(printf "⧇ %v" .git.stash)`)}{{ end }} {{ if eq .git.status "conflicts" }}{{ fg (color "error") "⚠" }}{{ else }}{{ if eq .git.status "dirty" }}{{ fg (color "warning") "●" }}{{ else }}{{ fg (color "success") "✓" }}{{ end }}{{ end }}`,_w={globals:{palette:`tokyo-night`},variables:{current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},version:{kind:`input`,path:`version`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"style.effective":{kind:`input`,path:`style.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0}},segments:{directory:{description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project.",template:dw,fg:`foreground`},model:{description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,fg:`foreground`,when:`{{ ne .model.display_name "" }}`},sessionId:{description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,fg:`foreground`,when:`{{ ne .session.id "" }}`},version:{description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,fg:`foreground`,when:`{{ ne .version "" }}`},tmux:{description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,fg:`foreground`,when:`{{ ne .tmux.session "" }}`},host:{description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,fg:`{{ contrastOn (bgOf) }}`,when:`{{ .host.ssh }}`},git:{description:`Branch, sha, ahead/behind, staged/unstaged/untracked/conflict counts, upstream, stash count, and a clean/dirty/conflict glyph.`,template:gw,fg:mw,when:`{{ ne .git.branch "" }}`},gitaculous:{description:`The same git state in asyncgit's compact spelling: repo, in-progress operation, sha, S/U/? flags, branch, upstream ±, stash count, and time since the last commit.`,template:`(git){{ if ne .git.repoName "" }} {{ .git.repoName }}{{ end }}{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}{{ if or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0) }} {{ if gt .git.staged 0 }}${pw(`staged`,`"S"`)}{{ end }}{{ if gt .git.unstaged 0 }}${pw(`unstaged`,`"U"`)}{{ end }}{{ if gt .git.untracked 0 }}${pw(`untracked`,`"?"`)}{{ end }}{{ if gt .git.conflicts 0 }}${pw(`conflicts`,`(printf "!%v" .git.conflicts)`)}{{ end }}{{ end }} ⎇ ${pw(`branch`,`.git.branch`)}{{ if ne .git.upstream "" }} [{{ .git.upstream }}{{ if or (gt .git.ahead 0) (gt .git.behind 0) }} {{ if gt .git.ahead 0 }}${pw(`ahead`,`(printf "+%v" .git.ahead)`)}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}${pw(`behind`,`(printf "-%v" .git.behind)`)}{{ end }}{{ end }}]{{ end }}{{ if gt .git.stash 0 }} ${pw(`stash`,`(printf "(%v stashed)" .git.stash)`)}{{ end }}{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,fg:mw,when:`{{ ne .git.branch "" }}`},gitPr:{description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,fg:`foreground`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{description:`Quick actions: copy the session id, open the project, transcript or repo, and toggle edit mode.`,template:`{{ action "copySession" "⎘ id" }} {{ action "openProject" "↗ proj" }} {{ action "openTranscript" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }} {{ action "edit.toggle" "✎ edit" "✎ done" }}`,fg:`foreground`},session:{description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .session.budget.amount "warn" .session.budget.warningThreshold) }}`,fg:`foreground`},today:{description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .today.budget.amount "warn" .today.budget.warningThreshold) }}`,fg:`foreground`},block:{description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 "panel" .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .block.nativeUtilization) "step" 0 "foreground" .block.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 "panel" .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,fg:`{{ ramp (round .weekly.percentage) "step" 0 "foreground" .weekly.budget.heatThreshold "button-color-foreground" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 "panel" 0 "error" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes "panel" }}`,fg:`{{ ramp .block.etaMinutes "step" -1 "foreground" 0 "button-color-foreground" .burn.eta.warnMinutes "foreground" }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,fg:`foreground`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,fg:`foreground`,when:`{{ ne .speed.history "" }}`},cacheTimer:{description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ if le (minutesUntilReset .cache.expiresAt) 8 }}error{{ else }}{{ if le (minutesUntilReset .cache.expiresAt) 20 }}warning{{ else }}foreground{{ end }}{{ end }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 "surface-active" }}`,fg:`{{ ramp .context.contextLeft "step" 0 "button-color-foreground" 41 "foreground" }}`,when:`{{ gt .context.totalTokens 0 }}`},metrics:{description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,fg:`foreground`,when:`{{ or .metrics.lastResponseTime .metrics.responseTime .metrics.sessionDuration .metrics.messageCount .metrics.linesAdded .metrics.linesRemoved }}`},charsetControl:{description:"The `⚙ terminal` drawer's control for `globals.charset` — the joiner glyph vocabulary.",template:`{{ .charset.effective }} {{ menu "applyCharsetForever" "▸" "▾" }} {{ action "resetCharset" "↺" }}`,fg:`foreground`},colorCompatControl:{description:"The `⚙ terminal` drawer's control for `globals.colorCompatibility` — the colour depth.",template:`{{ .colorCompatibility.effective }} {{ menu "applyColorCompatForever" "▸" "▾" }} {{ action "resetColorCompat" "↺" }}`,fg:`foreground`},directoryPaletteControl:{description:"The `⚙ terminal` drawer's control pinning the directory segment's own palette.",template:`🎨 directory {{ menu "applyDirectoryPaletteForever" "▸" "▾" }} {{ action "resetDirectoryPalette" "↺" }}`,fg:`foreground`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`toolbar`},{kind:`group`,name:`settings`,label:`⚙ terminal`,direction:`horizontal`,children:[`charsetControl`,`colorCompatControl`,`directoryPaletteControl`]}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`}]}}},actions:{copySession:{copy:`{{ .session.id }}`},copyDir:{copy:`{{ .current_dir }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},applyCharsetForever:{persist:`charset`,from:`charsets`},resetCharset:{reset:`charset`},applyColorCompatForever:{persist:`colorCompatibility`,from:`colorCompatibilities`},resetColorCompat:{reset:`colorCompatibility`},applyDirectoryPaletteForever:{persist:`segments.directory.palette`,from:`themes`},resetDirectoryPalette:{reset:`segments.directory.palette`}},looks:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`git`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`},{kind:`segment`,name:`toolbar`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},vw=new Set([_w.globals.palette,...Object.values(_w.segments).map(e=>e.palette)].filter(e=>e!==void 0)),yw=po(bv(`<default>`,JSON.stringify(_w),vw),_w);var bw=pe((e=>{function t(e){var t=[...arguments].slice(1);throw Error(typeof e==`number`?`[MobX] minified error nr: `+e+(t.length?` `+t.map(String).join(`,`):``)+`. Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts`:`[MobX] `+e)}function n(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:en}function r(){sn||t(`Proxy not available`)}function i(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function a(e){return typeof e==`function`}function o(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function s(e){return typeof e==`object`&&!!e}function c(e){if(!s(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===cn}function l(e){var t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function u(e,t,n){nn(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function d(e,t,n){nn(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function f(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return s(e)&&!0===e[n]}}function p(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function m(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function h(e){return e===null?null:typeof e==`object`?``+e:e}function g(e,t){return rn.hasOwnProperty.call(e,t)}function _(e,t){return!!(e&t)}function v(e,t,n){return n?e|=t:e&=~t,e}function y(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b(e,t,n){if(re())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&w(i,n.prototype),i}function x(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,ie(r.key),r)}}function S(e,t,n){return t&&x(e.prototype,t),n&&x(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function C(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if(typeof e==`string`)return y(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
145
145
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ee(){return(ee=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(null,arguments)}function te(e){return(te=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function ne(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,w(e,t)}function re(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(re=function(){return!!e})()}function w(e,t){return(w=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function ie(e){var t=function(e){if(typeof e!=`object`||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var n=t.call(e,`string`);if(typeof n!=`object`)return n;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e);return typeof t==`symbol`?t:t+``}function T(e){var t=typeof Map==`function`?new Map:void 0;return(T=function(e){function n(){return b(e,arguments,te(this).constructor)}if(e===null||!function(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),w(n,e)})(e)}function E(e){return Object.assign((function(t,n){if(oe(n))return e.t(t,n);ae(t,n,e)}),e)}function ae(e,t,n){g(e,pn)||u(e,pn,ee({},e[pn])),function(e){return e.i===`override`}(n)||(e[pn][t]=n)}function oe(e){return typeof e==`object`&&typeof e.kind==`string`}function se(e,t,n){t===void 0&&(t=ln),n===void 0&&(n=ln);var r=new mn(e);return t!==ln&&dt(r,t),n!==ln&&ft(r,n),r}function ce(e,t,n){return xt(e)?e:Array.isArray(e)?R.array(e,{name:n}):c(e)?R.object(e,void 0,{name:n}):p(e)?R.map(e,{name:n}):m(e)?R.set(e,{name:n}):typeof e!=`function`||ct(e)||vt(e)?e:l(e)?tr(e):Yn(n,e)}function le(e){return e}function ue(e,t){return{i:e,u:t,o:de,s:fe,t:pe}}function de(e,t,n,r){var i;return(i=this.u)!=null&&i.bound?this.s(e,t,n,!1)===null?0:1:r===e.h?this.s(e,t,n,!1)===null?0:2:ct(n.value)?1:(nn(r,t,me(e,this,t,n,!1)),2)}function fe(e,t,n,r){var i=me(e,this,t,n);return e.l(t,i,r)}function pe(e,n){var r,i=n.kind,a=n.name,o=n.addInitializer,s=this,c=function(e){var t;return Ne(s.u?.name??a.toString(),e,(t=s.u?.autoAction)!=null&&t)};return i==`field`?function(e){var t,n=e;return ct(n)||(n=c(n)),(t=s.u)!=null&&t.bound&&((n=n.bind(this)).isMobxAction=!0),n}:i==`method`?(ct(e)||(e=c(e)),(r=this.u)!=null&&r.bound&&o((function(){var e=this[a].bind(this);e.isMobxAction=!0,this[a]=e})),e):void t(`Cannot apply '`+s.i+`' to '`+String(a)+`' (kind: `+i+`):
146
146
  '`+s.i+`' can only be used on properties with a function value.`)}function me(e,t,n,r,i){var a,o,s;i===void 0&&(i=B.safeDescriptors);var c=r.value;return(a=t.u)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:Ne(t.u?.name??n.toString(),c,(o=t.u?.autoAction)!=null&&o,(s=t.u)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function he(e,t){return{i:e,u:t,o:D,s:ge,t:_e}}function D(e,t,n,r){var i;return r===e.h?this.s(e,t,n,!1)===null?0:2:(i=this.u)!=null&&i.bound&&(!g(e.h,t)||!vt(e.h[t]))&&this.s(e,t,n,!1)===null?0:vt(n.value)?1:(nn(r,t,ve(e,0,0,n,!1,!1)),2)}function ge(e,t,n,r){var i=ve(e,0,0,n,this.u?.bound);return e.l(t,i,r)}function _e(e,t){var n,r=t.name,i=t.addInitializer;return vt(e)||(e=tr(e)),(n=this.u)!=null&&n.bound&&i((function(){var e=this[r].bind(this);e.isMobXFlow=!0,this[r]=e})),e}function ve(e,t,n,r,i,a){a===void 0&&(a=B.safeDescriptors);var o=r.value;return vt(o)||(o=tr(o)),i&&((o=o.bind(e.v??e.h)).isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function ye(e,t){return{i:e,u:t,o:be,s:xe,t:Se}}function be(e,t,n){return this.s(e,t,n,!1)===null?0:1}function xe(e,t,n,r){return e.m(t,ee({},this.u,{get:n.get,set:n.set}),r)}function Se(e,t){var n=this,r=t.name;return(0,t.addInitializer)((function(){var t=Vt(this)[I],i=ee({},n.u,{get:e,context:this});i.name||=`ObservableObject.`+r.toString(),t.j.set(r,new Pn(i))})),function(){return this[I].O(r)}}function Ce(e,t){return{i:e,u:t,o:we,s:Te,t:Ee}}function we(e,t,n){return this.s(e,t,n,!1)===null?0:1}function Te(e,t,n,r){return e.g(t,n.value,this.u?.enhancer??ce,r)}function Ee(e,t){function n(e,t){var n=Vt(e)[I],i=new Mn(t,r.u?.enhancer??ce,`ObservableObject.`+a.toString(),!1);n.j.set(a,i),o.add(e)}var r=this,i=t.kind,a=t.name,o=new WeakSet;if(i==`accessor`)return{get:function(){return o.has(this)||n(this,e.get.call(this)),this[I].O(a)},set:function(e){return o.has(this)||n(this,e),this[I].S(a,e)},init:function(e){return o.has(this)||n(this,e),e}}}function De(e){return{i:`true`,u:e,o:Oe,s:ke,t:Ae}}function Oe(e,t,n,r){var i,a,o;if(n.get)return Dn.o(e,t,n,r);if(n.set){var s=ct(n.set)?n.set:Ne(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!B.safeDescriptors||e.p,set:s})===null?0:2:(nn(r,t,{configurable:!0,set:s}),2)}if(r!==e.h&&typeof n.value==`function`)return l(n.value)?((o=this.u)!=null&&o.autoBind?tr.bound:tr).o(e,t,n,r):((a=this.u)!=null&&a.autoBind?Yn.bound:Yn).o(e,t,n,r);var c=!1===this.u?.deep?R.ref:R;return typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function ke(e,t,n,r){var i;return n.get?Dn.s(e,t,n,r):n.set?e.l(t,{configurable:!B.safeDescriptors||e.p,set:Ne(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.u)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.u?.deep?R.ref:R).s(e,t,n,r))}function Ae(){t(`'`+this.i+`' cannot be used as a decorator`)}function je(e){return e||yn}function O(e){return!0===e.deep?ce:!1===e.deep?le:(t=e.defaultDecorator)&&(n=(r=t.u)?.enhancer)!=null?n:ce;var t,n,r}function Me(e,t,n){return oe(t)?bn.t(e,t):o(t)?void ae(e,t,bn):xt(e)?e:c(e)?R.object(e,t,n):Array.isArray(e)?R.array(e,t):p(e)?R.map(e,t):m(e)?R.set(e,t):typeof e==`object`&&e?e:R.box(e,t)}function Ne(e,t,n,r){function i(){return Pe(0,n,t,r||this,arguments)}return n===void 0&&(n=!1),i.isMobxAction=!0,i.toString=function(){return t.toString()},An&&(jn.value=e,nn(i,`name`,jn)),i}function Pe(e,t,n,r,i){var a=Fe(0,t);try{return n.apply(r,i)}catch(e){throw a._=e,e}finally{Ie(a)}}function Fe(e,t){var n=B.trackingDerivation,r=!t||!n;$e();var i=B.allowStateChanges;r&&(Ge(),i=Re(!0));var a={A:r,k:n,M:i,V:qe(!0),R:!1,N:0,T:kn++,C:On};return On=a.T,a}function Ie(e){On!==e.T&&t(30),On=e.C,e._!==void 0&&(B.suppressReactionErrors=!0),ze(e.M),Je(e.V),et(),e.A&&Ke(e.k),B.suppressReactionErrors=!1}function Le(e,t){var n=Re(e);try{return t()}finally{ze(n)}}function Re(e){var t=B.allowStateChanges;return B.allowStateChanges=e,t}function ze(e){B.allowStateChanges=e}function Be(e){return e instanceof Ln}function Ve(e){switch(e.I){case z.L:return!1;case z.P:case z.K:return!0;case z.B:for(var t=qe(!0),n=Ge(),r=e.D,i=r.length,a=0;a<i;a++){var o=r[a];if(In(o)){if(B.disableErrorBoundaries)o.get();else try{o.get()}catch{return Ke(n),Je(t),!0}if(e.I===z.K)return Ke(n),Je(t),!0}}return Ye(e),Ke(n),Je(t),!1}}function He(e,t,n){var r=qe(!0);Ye(e),e.W=Array(e.q===0?100:e.D.length),e.G=0,e.q=++B.runId;var i,a=B.trackingDerivation;if(B.trackingDerivation=e,B.inBatch++,!0===B.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Ln(e)}return B.inBatch--,B.trackingDerivation=a,function(e){for(var t=e.D,n=e.D=e.W,r=z.L,i=0,a=e.G,o=0;o<a;o++){var s=n[o];s.diffValue===0&&(s.diffValue=1,i!==o&&(n[i]=s),i++),s.I>r&&(r=s.I)}for(n.length=i,e.W=null,a=t.length;a--;){var c=t[a];c.diffValue===0&&Ze(c,e),c.diffValue=0}for(;i--;){var l=n[i];l.diffValue===1&&(l.diffValue=0,Xe(l,e))}r!==z.L&&(e.I=r,e.H())}(e),Je(r),i}function Ue(e){var t=e.D;e.D=[];for(var n=t.length;n--;)Ze(t[n],e);e.I=z.P}function We(e){var t=Ge();try{return e()}finally{Ke(t)}}function Ge(){var e=B.trackingDerivation;return B.trackingDerivation=null,e}function Ke(e){B.trackingDerivation=e}function qe(e){var t=B.allowStateReads;return B.allowStateReads=e,t}function Je(e){B.allowStateReads=e}function Ye(e){if(e.I!==z.L){e.I=z.L;for(var t=e.D,n=t.length;n--;)t[n].U=z.L}}function Xe(e,t){e.F.add(t),e.U>t.I&&(e.U=t.I)}function Ze(e,t){e.F.delete(t),e.F.size===0&&Qe(e)}function Qe(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,B.pendingUnobservations.push(e))}function $e(){B.inBatch++}function et(){if(--B.inBatch==0){rt();for(var e=B.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,n.F.size===0&&(n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof Pn&&n.X())}B.pendingUnobservations=[]}}function tt(e){var t=B.trackingDerivation;return t===null?(e.F.size===0&&B.inBatch>0&&Qe(e),!1):(t.q!==e.$&&(e.$=t.q,t.W[t.G++]=e,!e.isBeingObserved&&B.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function nt(e){e.U!==z.K&&(e.U=z.K,e.F.forEach((function(e){e.I===z.L&&e.H(),e.I=z.K})))}function rt(){B.inBatch>0||B.isRunningReactions||Un(it)}function it(){B.isRunningReactions=!0;for(var e=B.pendingReactions,t=0;e.length>0;){++t==100&&(console.error(`[mobx] cycle in reaction: `+e[0]),e.splice(0));for(var n=e.splice(0),r=0,i=n.length;r<i;r++)n[r].J()}B.isRunningReactions=!1}function at(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}}function ot(e){return function(t,n){return a(t)?Ne(t.name||`<unnamed action>`,t,e):a(n)?Ne(t,n,e):oe(n)?(e?V:Gn).t(t,n):o(n)?ae(t,n,e?V:Gn):o(t)?E(ue(e?`autoAction`:`action`,{name:t,autoAction:e})):void 0}}function st(e){return Pe(0,!1,e,this,void 0)}function ct(e){return a(e)&&!0===e.isMobxAction}function lt(e,t){function n(){e(i)}var r;t===void 0&&(t=on);var i,a=t?.name??`Autorun`;if(t.scheduler||t.delay){var o=ut(t),s=!1;i=new Hn(a,(function(){s||(s=!0,o((function(){s=!1,i.isDisposed||i.track(n)})))}),t.onError,t.requiresObservable)}else i=new Hn(a,(function(){this.track(n)}),t.onError,t.requiresObservable);return(r=t)!=null&&(r=r.signal)!=null&&r.aborted||i.Y(),i.Z(t?.signal)}function ut(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:Xn}function dt(e,t,n){return pt(`onBO`,e,t,n)}function ft(e,t,n){return pt(`onBUO`,e,t,n)}function pt(e,t,n,r){var i=typeof r==`function`?Jt(t,n):Jt(t),o=a(r)?r:n,s=e+`L`;return i[s]?i[s].add(o):i[s]=new Set([o]),function(){var e=i[s];e&&(e.delete(o),e.size===0&&delete i[s])}}function mt(e,t,n,r){var i=fn(t);return Xt((function(){var t=Vt(e,r)[I];dn(i).forEach((function(e){t.s(e,i[e],!n||!(e in n)||n[e])}))})),e}function ht(e){var t,n={name:e.tt};return e.D&&e.D.length>0&&(n.dependencies=(t=e.D,Array.from(new Set(t))).map(ht)),n}function gt(e){var t={name:e.tt};return function(e){return e.F&&e.F.size>0}(e)&&(t.observers=Array.from(function(e){return e.F}(e)).map(gt)),t}function _t(e){a(e.cancel)&&e.cancel()}function vt(e){return!0===e?.isMobXFlow}function yt(e,t){return t===void 0?In(e):!1===Ut(e)||!e[I].j.has(t)?!1:In(Jt(e,t))}function bt(e,t){return!!e&&(t===void 0?Ut(e)||!!e[I]||hn(e)||Wn(e)||In(e):!!Ut(e)&&e[I].j.has(t))}function xt(e){return bt(e)}function St(e){return Ut(e)?e[I].nt():H(e)||gr(e)?Array.from(e.keys()):Rt(e)?e.map((function(e,t){return t})):void t(5)}function Ct(e,n){return Ut(e)?e[I].it(n):H(e)||gr(e)?e.has(n):Rt(e)?n>=0&&n<e.length:void t(10)}function wt(e){if(Ut(e))return e[I].rt();t(38)}function Tt(e,t,n){return e.set(t,n),n}function Et(e,t){t===void 0&&(t=void 0),$e();try{return e.apply(t)}finally{et()}}function Dt(e,t,n){var r;if(typeof n.timeout==`number`){var i=Error(`WHEN_TIMEOUT`);r=setTimeout((function(){if(!o[I].isDisposed){if(o(),!n.onError)throw i;n.onError(i)}}),n.timeout)}n.name=`When`;var a=Ne(`When-effect`,t),o=lt((function(t){Le(!1,e)&&(t.dispose(),r&&clearTimeout(r),a())}),n);return o}function Ot(e,t){var n,r,i;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Object.assign(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:function(){return null}});var a=new Promise((function(n,a){var o,s=Dt(e,n,ee({},t,{onError:a}));r=function(){s(),a(Error(`WHEN_CANCELLED`))},i=function(){s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)})).finally((function(){var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)}));return a.cancel=r,a}function kt(e){return e[I]}function At(e){return e.et!==void 0&&e.et.length>0}function jt(e,t){var n=e.et||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Mt(e,n){var r=Ge();try{for(var i=[].concat(e.et||[]),a=0,o=i.length;a<o&&((n=i[a](n))&&!n.type&&t(14),n);a++);return n}finally{Ke(r)}}function Nt(e){return e.ut!==void 0&&e.ut.length>0}function Pt(e,t){var n=e.ut||=[];return n.push(t),i((function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)}))}function Ft(e,t){var n=Ge(),r=e.ut;if(r){for(var i=0,a=(r=r.slice()).length;i<a;i++)r[i](t);Ke(n)}}function It(e,t,n,i){return n===void 0&&(n=`ObservableArray`),i===void 0&&(i=!1),r(),Xt((function(){var r=new or(n,t,i,!1);d(r.j,I,r);var a=new Proxy(r.j,ar);return r.v=a,e&&e.length&&r.ot(0,0,e),a}))}function k(e,t){typeof Array.prototype[e]==`function`&&(sr[e]=t(e))}function A(e){return function(){var t=this[I];t.st.reportObserved();var n=t.ft(t.j);return n[e].apply(n,arguments)}}function j(e){return function(t,n){var r=this,i=this[I];return i.st.reportObserved(),i.ft(i.j)[e]((function(e,i){return t.call(n,e,i,r)}))}}function Lt(e){return function(){var t=this,n=this[I];n.st.reportObserved();var r=n.ft(n.j),i=arguments[0];return arguments[0]=function(e,n,r){return i(e,n,r,t)},r[e].apply(r,arguments)}}function Rt(e){return s(e)&&ur(e[I])}function zt(e){return e[Symbol.toStringTag]=`MapIterator`,$t(e)}function Bt(e){return e[Symbol.toStringTag]=`SetIterator`,$t(e)}function Vt(e,t){if(g(e,I))return e;var n=t?.name??`ObservableObject`;return u(e,I,new vr(e,new Map,String(n),function(e){return e?e.defaultDecorator??De(e):void 0}(t))),e}function Ht(e){return _r[e]||(_r[e]={get:function(){return this[I].O(e)},set:function(t){return this[I].S(e,t)}})}function Ut(e){return!!s(e)&&yr(e[I])}function Wt(e,t,n){var r;(r=e.h[pn])==null||delete r[n]}function Gt(e){return{enumerable:!1,configurable:!0,get:function(){return this[I].ct(e)},set:function(t){this[I].ht(e,t)}}}function Kt(e){nn(Cr.prototype,``+e,Gt(e))}function qt(e){if(e>xr){for(var t=xr;t<e+100;t++)Kt(t);xr=e}}function M(e,t,n){return new Cr(e,t,n)}function Jt(e,n){if(typeof e==`object`&&e){if(Rt(e))return n!==void 0&&t(23),e[I].st;if(gr(e))return e.st;if(H(e)){if(n===void 0)return e.lt;var r=e.vt.get(n)||e.dt.get(n);return r||t(25,n,Yt(e)),r}if(Ut(e)){if(!n)return t(26);var i=e[I].j.get(n);return i||t(27,n,Yt(e)),i}if(hn(e)||In(e)||Wn(e))return e}else if(a(e)&&Wn(e[I]))return e[I];t(28)}function N(e,n){return e||t(29),n===void 0?hn(e)||In(e)||Wn(e)||H(e)||gr(e)?e:e[I]?e[I]:void t(24,e):N(Jt(e,n))}function Yt(e,t){var n;if(t!==void 0)n=Jt(e,t);else{if(ct(e))return e.name;n=Ut(e)||H(e)||gr(e)?N(e):Jt(e)}return n.tt}function Xt(e){var t=Ge(),n=Re(!0);$e();try{return e()}finally{et(),ze(n),Ke(t)}}function Zt(e,t,n){return n===void 0&&(n=-1),function e(t,n,r,i,o){if(t===n)return t!==0||1/t==1/n;if(t==null||n==null)return!1;if(t!=t)return n!=n;var s=typeof t;if(s!==`function`&&s!==`object`&&typeof n!=`object`)return!1;var c=wr.call(t);if(c!==wr.call(n))return!1;switch(c){case`[object RegExp]`:case`[object String]`:return``+t==``+n;case`[object Number]`:return+t==+t?+t==0?1/t==1/n:+t==+n:+n!=+n;case`[object Date]`:case`[object Boolean]`:return+t==+n;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(t)===Symbol.valueOf.call(n);case`[object Map]`:case`[object Set]`:r>=0&&r++}t=Qt(t),n=Qt(n);var l=c===`[object Array]`;if(!l){if(typeof t!=`object`||typeof n!=`object`)return!1;var u=t.constructor,d=n.constructor;if(u!==d&&!(a(u)&&u instanceof u&&a(d)&&d instanceof d)&&`constructor`in t&&`constructor`in n)return!1}if(r===0)return!1;r<0&&(r=-1),o||=[];for(var f=(i||=[]).length;f--;)if(i[f]===t)return o[f]===n;if(i.push(t),o.push(n),l){if((f=t.length)!==n.length)return!1;for(;f--;)if(!e(t[f],n[f],r-1,i,o))return!1}else{var p=Object.keys(t),m=p.length;if(Object.keys(n).length!==m)return!1;for(var h=0;h<m;h++){var _=p[h];if(!g(n,_)||!e(t[_],n[_],r-1,i,o))return!1}}return i.pop(),o.pop(),!0}(e,t,n)}function Qt(e){return Rt(e)?e.slice():p(e)||H(e)||m(e)||gr(e)?Array.from(e.entries()):e}function $t(e){return e[Symbol.iterator]=P,Object.assign(Object.create(Tr),e)}function P(){return this}Object.defineProperty(e,`__esModule`,{value:!0});var en={},F=Object.assign,tn=Object.getOwnPropertyDescriptor,nn=Object.defineProperty,rn=Object.prototype,an=[];Object.freeze(an);var on={};Object.freeze(on);var sn=typeof Proxy<`u`,cn=Object.toString(),ln=function(){},un=Object.getOwnPropertySymbols!==void 0,dn=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:un?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames,fn=Object.getOwnPropertyDescriptors||function(e){var t={};return dn(e).forEach((function(n){t[n]=tn(e,n)})),t},pn=Symbol(`mobx-stored-annotations`),I=Symbol(`mobx administration`),mn=function(){function e(e){e===void 0&&(e=`Atom`),this.tt=void 0,this.bt=0,this.F=new Set,this.$=0,this.U=z.P,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}var t=e.prototype;return t.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},t.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},t.reportObserved=function(){return tt(this)},t.reportChanged=function(){$e(),nt(this),et()},t.toString=function(){return this.tt},S(e,[{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();mn.pt=1,mn.yt=2,mn.wt=4;var hn=f(`Atom`,mn),gn={identity:function(e,t){return e===t},structural:function(e,t){return Zt(e,t)},default:function(e,t){return Object.is?Object.is(e,t):e===t?e!==0||1/e==1/t:e!=e&&t!=t},shallow:function(e,t){return Zt(e,t,1)}},_n=E({i:`override`,o:function(){return 0},s:function(){t(`'`+this.i+`' can only be used with 'makeObservable'`)},t:function(){console.warn(`'`+this.i+`' cannot be used with decorators - this is a no-op`)}}),vn=De(),yn={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};Object.freeze(yn);var bn=Ce(`observable`),xn=Ce(`observable.ref`,{enhancer:le}),L=Ce(`observable.shallow`,{enhancer:function(e,t,n){return e==null||Ut(e)||Rt(e)||H(e)||gr(e)?e:Array.isArray(e)?R.array(e,{name:n,deep:!1}):c(e)?R.object(e,void 0,{name:n,deep:!1}):p(e)?R.map(e,{name:n,deep:!1}):m(e)?R.set(e,{name:n,deep:!1}):void 0}}),Sn=Ce(`observable.struct`,{enhancer:function(e,t){return Zt(e,t)?t:e}}),Cn=E(bn);F(Me,Cn);var wn,R=F(Me,{box:function(e,t){var n=je(t);return new Mn(e,O(n),n.name,!0,n.equals)},array:function(e,t){var n=je(t);return(!1===B.useProxies||!1===n.proxy?M:It)(e,O(n),n.name)},map:function(e,t){var n=je(t);return new pr(e,O(n),n.name)},set:function(e,t){var n=je(t);return new hr(e,O(n),n.name)},object:function(e,t,n){return Xt((function(){return mt(!1===B.useProxies||!1===n?.proxy?Vt({},n):function(e,t){var n;return r(),(n=(e=Vt(e,t))[I]).v??(n.v=new Proxy(e,nr))}({},n),e,t)}))},ref:E(xn),shallow:E(L),deep:Cn,struct:E(Sn)}),Tn=ye(`computed`),En=ye(`computed.struct`,{equals:gn.structural}),Dn=function(e,t){if(oe(t))return Tn.t(e,t);if(o(t))return ae(e,t,Tn);if(c(e))return E(ye(`computed`,e));var n=c(t)?t:{};return n.get=e,n.name||=e.name||``,new Pn(n)};Object.assign(Dn,Tn),Dn.struct=E(En);var On=0,kn=1,An=(wn=tn((function(){}),`name`)?.configurable)!=null&&wn,jn={value:`action`,configurable:!0,writable:!1,enumerable:!1},Mn=function(e){function t(t,n,r,i,a){var o;return r===void 0&&(r=`ObservableValue`),a===void 0&&(a=gn.default),(o=e.call(this,r)||this).enhancer=void 0,o.tt=void 0,o.equals=void 0,o.jt=!1,o.et=void 0,o.ut=void 0,o.Ot=void 0,o.dehancer=void 0,o.enhancer=n,o.tt=r,o.equals=a,o.Ot=n(t,void 0,r),o}ne(t,e);var n=t.prototype;return n.dehanceValue=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.set=function(e){(e=this.xt(e))!==B.UNCHANGED&&this.gt(e)},n.xt=function(e){if(At(this)){var t=Mt(this,{object:this,type:ir,newValue:e});if(!t)return B.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.Ot,this.tt),this.equals(this.Ot,e)?B.UNCHANGED:e},n.gt=function(e){var t=this.Ot;this.Ot=e,this.reportChanged(),Nt(this)&&Ft(this,{type:ir,object:this,newValue:e,oldValue:t})},n.get=function(){return this.reportObserved(),this.dehanceValue(this.Ot)},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t&&e({observableKind:`value`,debugObjectName:this.tt,object:this,type:ir,newValue:this.Ot,oldValue:void 0}),Pt(this,e)},n.raw=function(){return this.Ot},n.toJSON=function(){return this.get()},n.toString=function(){return this.tt+`[`+this.Ot+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},t}(mn),Nn=f(`ObservableValue`,Mn),Pn=function(){function e(e){this.I=z.P,this.D=[],this.W=null,this.F=new Set,this.q=0,this.$=0,this.U=z.L,this.G=0,this.Ot=new Ln(null),this.tt=void 0,this.At=void 0,this.bt=0,this.derivation=void 0,this.kt=void 0,this.Mt=Fn.NONE,this.Et=void 0,this.Vt=void 0,this.Rt=void 0,this.Nt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.kt=Ne(`ComputedValue-setter`,e.set)),this.Vt=e.equals||(e.compareStructural||e.struct?gn.structural:gn.default),this.Et=e.context,this.Rt=e.requiresReaction,this.Nt=!!e.keepAlive}var n=e.prototype;return n.H=function(){(function(e){e.U===z.L&&(e.U=z.B,e.F.forEach((function(e){e.I===z.L&&(e.I=z.B,e.H())})))})(this)},n.onBO=function(){this.onBOL&&this.onBOL.forEach((function(e){return e()}))},n.onBUO=function(){this.onBUOL&&this.onBUOL.forEach((function(e){return e()}))},n.get=function(){if(this.isComputing&&t(32,this.tt,this.derivation),B.inBatch!==0||this.F.size!==0||this.Nt){if(tt(this),Ve(this)){var e=B.trackingContext;this.Nt&&!e&&(B.trackingContext=this),this.trackAndCompute()&&function(e){e.U!==z.K&&(e.U=z.K,e.F.forEach((function(t){t.I===z.B?t.I=z.K:t.I===z.L&&(e.U=z.L)})))}(this),B.trackingContext=e}}else Ve(this)&&(this.Tt(),$e(),this.Ot=this.Ct(!1),et());var n=this.Ot;if(Be(n))throw n.cause;return n},n.set=function(e){if(this.kt){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.kt.call(this.Et,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)},n.trackAndCompute=function(){var e=this.Ot,t=this.I===z.P,n=this.Ct(!0),r=t||Be(e)||Be(n)||!this.Vt(e,n);return r&&(this.Ot=n),r},n.Ct=function(e){this.isComputing=!0;var t,n=Re(!1);if(e)t=He(this,this.derivation,this.Et);else if(!0===B.disableErrorBoundaries)t=this.derivation.call(this.Et);else try{t=this.derivation.call(this.Et)}catch(e){t=new Ln(e)}return ze(n),this.isComputing=!1,t},n.X=function(){this.Nt||(Ue(this),this.Ot=void 0)},n._t=function(e,t){var n=this,r=!0,i=void 0;return lt((function(){var a=n.get();if(!r||t){var o=Ge();e({observableKind:`computed`,debugObjectName:n.tt,type:ir,object:n,newValue:a,oldValue:i}),Ke(o)}r=!1,i=a}))},n.Tt=function(){},n.toString=function(){return this.tt+`[`+this.derivation.toString()+`]`},n.valueOf=function(){return h(this.get())},n[Symbol.toPrimitive]=function(){return this.valueOf()},S(e,[{key:`isComputing`,get:function(){return _(this.bt,e.It)},set:function(t){this.bt=v(this.bt,e.It,t)}},{key:`isRunningSetter`,get:function(){return _(this.bt,e.Lt)},set:function(t){this.bt=v(this.bt,e.Lt,t)}},{key:`isBeingObserved`,get:function(){return _(this.bt,e.pt)},set:function(t){this.bt=v(this.bt,e.pt,t)}},{key:`isPendingUnobservation`,get:function(){return _(this.bt,e.yt)},set:function(t){this.bt=v(this.bt,e.yt,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Pn.It=1,Pn.Lt=2,Pn.pt=4,Pn.yt=8,Pn.wt=16;var z,Fn,In=f(`ComputedValue`,Pn);(function(e){e[e.P=-1]=`NOT_TRACKING_`,e[e.L=0]=`UP_TO_DATE_`,e[e.B=1]=`POSSIBLY_STALE_`,e[e.K=2]=`STALE_`})(z||={}),function(e){e[e.NONE=0]=`NONE`,e[e.LOG=1]=`LOG`,e[e.BREAK=2]=`BREAK`}(Fn||={});var Ln=function(e){this.cause=void 0,this.cause=e},Rn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`,`useProxies`],zn=function(){this.version=6,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.useProxies=!0,this.verifyProxies=!1,this.safeDescriptors=!0},Bn=!0,Vn=!1,B=function(){var e=n();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Bn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==new zn().version&&(Bn=!1),Bn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new zn):(setTimeout((function(){Vn||t(35)}),1),new zn)}(),Hn=function(){function e(e,t,n,r){e===void 0&&(e=`Reaction`),this.tt=void 0,this.Pt=void 0,this.Kt=void 0,this.Bt=void 0,this.D=[],this.W=[],this.I=z.P,this.q=0,this.G=0,this.bt=0,this.Mt=Fn.NONE,this.tt=e,this.Pt=t,this.Kt=n,this.Bt=r}var t=e.prototype;return t.H=function(){this.Y()},t.Y=function(){this.isScheduled||(this.isScheduled=!0,B.pendingReactions.push(this),rt())},t.J=function(){if(!this.isDisposed){$e(),this.isScheduled=!1;var e=B.trackingContext;if(B.trackingContext=this,Ve(this)){this.isTrackPending=!0;try{this.Pt()}catch(e){this.Dt(e)}}B.trackingContext=e,et()}},t.track=function(e){if(!this.isDisposed){$e(),this.isRunning=!0;var t=B.trackingContext;B.trackingContext=this;var n=He(this,e,void 0);B.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ue(this),Be(n)&&this.Dt(n.cause),et()}},t.Dt=function(e){var t=this;if(this.Kt)this.Kt(e,this);else{if(B.disableErrorBoundaries)throw e;B.suppressReactionErrors||console.error(`[mobx] uncaught error in '`+this+`'`,e),B.globalReactionErrorHandlers.forEach((function(n){return n(e,t)}))}},t.dispose=function(){this.isDisposed||(this.isDisposed=!0,this.isRunning||($e(),Ue(this),et()))},t.Z=function(e){var t=this,n=function n(){t.dispose(),e==null||e.removeEventListener==null||e.removeEventListener(`abort`,n)};return e==null||e.addEventListener==null||e.addEventListener(`abort`,n),n[I]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(n[Symbol.dispose]=n),n},t.toString=function(){return`Reaction[`+this.tt+`]`},t.trace=function(){},S(e,[{key:`isDisposed`,get:function(){return _(this.bt,e.Wt)},set:function(t){this.bt=v(this.bt,e.Wt,t)}},{key:`isScheduled`,get:function(){return _(this.bt,e.qt)},set:function(t){this.bt=v(this.bt,e.qt,t)}},{key:`isTrackPending`,get:function(){return _(this.bt,e.Gt)},set:function(t){this.bt=v(this.bt,e.Gt,t)}},{key:`isRunning`,get:function(){return _(this.bt,e.Ht)},set:function(t){this.bt=v(this.bt,e.Ht,t)}},{key:`diffValue`,get:function(){return+!!_(this.bt,e.wt)},set:function(t){this.bt=v(this.bt,e.wt,t===1)}}])}();Hn.Wt=1,Hn.qt=2,Hn.Gt=4,Hn.Ht=8,Hn.wt=16;var Un=function(e){return e()},Wn=f(`Reaction`,Hn),Gn=ue(`action`),Kn=ue(`action.bound`,{bound:!0}),V=ue(`autoAction`,{autoAction:!0}),qn=ue(`autoAction.bound`,{autoAction:!0,bound:!0}),Jn=ot(!1);Object.assign(Jn,Gn);var Yn=ot(!0);Object.assign(Yn,V),Jn.bound=E(Kn),Yn.bound=E(qn);var Xn=function(e){return e()},Zn=0,Qn=function(e){function t(){var n;return n=e.call(this,`FLOW_CANCELLED`)||this,Object.setPrototypeOf(n,(this instanceof t?this.constructor:void 0).prototype),n.name=`FlowCancellationError`,n}return ne(t,e),t.prototype.toString=function(){return`Error: `+this.message},t}(T(Error)),$n=he(`flow`),er=he(`flow.bound`,{bound:!0}),tr=Object.assign((function(e,t){if(oe(t))return $n.t(e,t);if(o(t))return ae(e,t,$n);var n=e,r=n.name||`<unnamed flow>`,i=function(){var e,t=this,i=arguments,o=++Zn,s=Jn(r+` - runid: `+o+` - init`,n).apply(t,i),c=void 0,l=new Promise((function(t,n){function i(e){var t;c=void 0;try{t=Jn(r+` - runid: `+o+` - yield `+ d++,s.next).call(s,e)}catch(e){return n(e)}u(t)}function l(e){var t;c=void 0;try{t=Jn(r+` - runid: `+o+` - yield `+ d++,s.throw).call(s,e)}catch(e){return n(e)}u(t)}function u(e){if(!a(e?.then))return e.done?t(e.value):(c=Promise.resolve(e.value)).then(i,l);e.then(u,n)}var d=0;e=n,i(void 0)}));return l.cancel=Jn(r+` - runid: `+o+` - cancel`,(function(){try{c&&_t(c);var t=s.return(void 0),n=Promise.resolve(t.value);n.then(ln,ln),_t(n),e(new Qn)}catch(t){e(t)}})),l};return i.isMobXFlow=!0,i}),$n);tr.bound=E(er);var nr={has:function(e,t){return kt(e).it(t)},get:function(e,t){return kt(e).ct(t)},set:function(e,t,n){var r;return!!o(t)&&((r=kt(e).ht(t,n,!0))==null||r)},deleteProperty:function(e,t){var n;return!!o(t)&&((n=kt(e).Ut(t,!0))==null||n)},defineProperty:function(e,t,n){var r;return(r=kt(e).l(t,n))==null||r},ownKeys:function(e){return kt(e).rt()},preventExtensions:function(){t(13)}},rr=Symbol(`mobx-keys`),ir=`update`,ar={get:function(e,t){var n=e[I];return t===I?n:t===`length`?n.Ft():typeof t!=`string`||isNaN(t)?g(sr,t)?sr[t]:e[t]:n.ct(parseInt(t))},set:function(e,t,n){var r=e[I];return t===`length`&&r.Xt(n),typeof t==`symbol`||isNaN(t)?e[t]=n:r.ht(parseInt(t),n),!0},preventExtensions:function(){t(15)}},or=function(){function e(e,t,n,r){e===void 0&&(e=`ObservableArray`),this.zt=void 0,this.$t=void 0,this.st=void 0,this.j=[],this.et=void 0,this.ut=void 0,this.Jt=void 0,this.dehancer=void 0,this.v=void 0,this.Yt=0,this.zt=n,this.$t=r,this.st=new mn(e),this.Jt=function(e,n){return t(e,n,`ObservableArray[..]`)}}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.ft=function(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e},n.St=function(e){return jt(this,e)},n._t=function(e,t){return t===void 0&&(t=!1),t&&e({observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:0,added:this.j.slice(),addedCount:this.j.length,removed:[],removedCount:0}),Pt(this,e)},n.Ft=function(){return this.st.reportObserved(),this.j.length},n.Xt=function(e){(typeof e!=`number`||isNaN(e)||e<0)&&t(`Out of range: `+e);var n=this.j.length;if(e!==n)if(e>n){for(var r=Array(e-n),i=0;i<e-n;i++)r[i]=void 0;this.ot(n,0,r)}else this.ot(e,n-e)},n.Zt=function(e,n){e!==this.Yt&&t(16),this.Yt+=n,this.$t&&n>0&&qt(e+n+1)},n.ot=function(e,t,n){var r=this,i=this.j.length;if(e===void 0?e=0:e>i?e=i:e<0&&(e=Math.max(0,i+e)),t=arguments.length===1?i-e:t==null?0:Math.max(0,Math.min(t,i-e)),n===void 0&&(n=an),At(this)){var a=Mt(this,{object:this.v,type:`splice`,index:e,removedCount:t,added:n});if(!a)return an;t=a.removedCount,n=a.added}if(n=n.length===0?n:n.map((function(e){return r.Jt(e,void 0)})),this.$t){var o=n.length-t;this.Zt(i,o)}var s=this.tn(e,t,n);return t===0&&n.length===0||this.nn(e,n,s),this.ft(s)},n.tn=function(e,t,n){var r;if(n.length<1e4)return(r=this.j).splice.apply(r,[e,t].concat(n));var i=this.j.slice(e,e+t),a=this.j.slice(e+t);this.j.length+=n.length-t;for(var o=0;o<n.length;o++)this.j[e+o]=n[o];for(var s=0;s<a.length;s++)this.j[e+n.length+s]=a[s];return i},n.in=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,type:ir,debugObjectName:this.st.tt,index:e,newValue:t,oldValue:n}:null;this.st.reportChanged(),i&&Ft(this,a)},n.nn=function(e,t,n){var r=!this.zt&&!1,i=Nt(this),a=i||r?{observableKind:`array`,object:this.v,debugObjectName:this.st.tt,type:`splice`,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.st.reportChanged(),i&&Ft(this,a)},n.ct=function(e){if(!(this.$t&&e>=this.j.length))return this.st.reportObserved(),this.Qt(this.j[e]);console.warn(`[mobx] Out of bounds read: `+e)},n.ht=function(e,n){var r=this.j;if(this.$t&&e>r.length&&t(17,e,r.length),e<r.length){var i=r[e];if(At(this)){var a=Mt(this,{type:ir,object:this.v,index:e,newValue:n});if(!a)return;n=a.newValue}(n=this.Jt(n,i))!==i&&(r[e]=n,this.in(e,n,i))}else{for(var o=Array(e+1-r.length),s=0;s<o.length-1;s++)o[s]=void 0;o[o.length-1]=n,this.ot(r.length,0,o)}},e}(),sr={clear:function(){return this.splice(0)},replace:function(e){var t=this[I];return t.ot(0,t.j.length,e)},toJSON:function(){return this.slice()},splice:function(e,t){var n=[...arguments].slice(2),r=this[I];switch(arguments.length){case 0:return[];case 1:return r.ot(e);case 2:return r.ot(e,t)}return r.ot(e,t,n)},spliceWithArray:function(e,t,n){return this[I].ot(e,t,n)},push:function(){for(var e=this[I],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(e.j.length,0,n),e.j.length},pop:function(){return this.splice(Math.max(this[I].j.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=this[I],t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.ot(0,0,n),e.j.length},reverse:function(){return B.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort:function(){B.trackingDerivation&&t(37,`sort`);var e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove:function(e){var t=this[I],n=t.ft(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};k(`at`,A),k(`concat`,A),k(`flat`,A),k(`includes`,A),k(`indexOf`,A),k(`join`,A),k(`lastIndexOf`,A),k(`slice`,A),k(`toString`,A),k(`toLocaleString`,A),k(`toSorted`,A),k(`toSpliced`,A),k(`with`,A),k(`every`,j),k(`filter`,j),k(`find`,j),k(`findIndex`,j),k(`findLast`,j),k(`findLastIndex`,j),k(`flatMap`,j),k(`forEach`,j),k(`map`,j),k(`some`,j),k(`toReversed`,j),k(`reduce`,Lt),k(`reduceRight`,Lt);var cr,lr,ur=f(`ObservableArrayAdministration`,or),dr={},fr=`add`,pr=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableMap`),this.Jt=void 0,this.tt=void 0,this[I]=dr,this.vt=void 0,this.dt=void 0,this.lt=void 0,this.et=void 0,this.ut=void 0,this.dehancer=void 0,this.Jt=n,this.tt=r,a(Map)||t(18),Xt((function(){i.lt=se(`ObservableMap.keys()`),i.vt=new Map,i.dt=new Map,e&&i.merge(e)}))}var n=e.prototype;return n.it=function(e){return this.vt.has(e)},n.has=function(e){var t=this;if(!B.trackingDerivation)return this.it(e);var n=this.dt.get(e);if(!n){var r=n=new Mn(this.it(e),le,`ObservableMap.key?`,!1);this.dt.set(e,r),ft(r,(function(){return t.dt.delete(e)}))}return n.get()},n.set=function(e,t){var n=this.it(e);if(At(this)){var r=Mt(this,{type:n?ir:fr,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.rn(e,t):this.en(e,t),this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,name:e}))return!1;if(this.it(e)){var n=Nt(this),r=n?{observableKind:`map`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:this.vt.get(e).Ot,name:e}:null;return Et((function(){var n;t.lt.reportChanged(),(n=t.dt.get(e))==null||n.gt(!1),t.vt.get(e).gt(void 0),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.rn=function(e,t){var n=this.vt.get(e);if((t=n.xt(t))!==B.UNCHANGED){var r=Nt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:ir,object:this,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),r&&Ft(this,i)}},n.en=function(e,t){var n=this;Et((function(){var r,i=new Mn(t,n.Jt,`ObservableMap.key`,!1);n.vt.set(e,i),t=i.Ot,(r=n.dt.get(e))==null||r.gt(!0),n.lt.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`map`,debugObjectName:this.tt,type:fr,object:this,name:e,newValue:t}:null)},n.get=function(e){return this.has(e)?this.Qt(this.vt.get(e).get()):this.Qt(void 0)},n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.keys=function(){return this.lt.reportObserved(),this.vt.keys()},n.values=function(){var e=this,t=this.keys();return zt({next:function(){var n=t.next(),r=n.done;return{done:r,value:r?void 0:e.get(n.value)}}})},n.entries=function(){var e=this,t=this.keys();return zt({next:function(){var n=t.next(),r=n.done,i=n.value;return{done:r,value:r?void 0:[i,e.get(i)]}}})},n[Symbol.iterator]=function(){return this.entries()},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i[1],i[0],this)}},n.merge=function(e){var n=this;return H(e)&&(e=new Map(e)),Et((function(){var r,i;c(e)?function(e){var t=Object.keys(e);if(!un)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter((function(t){return rn.propertyIsEnumerable.call(e,t)}))):t}(e).forEach((function(t){return n.set(t,e[t])})):Array.isArray(e)?e.forEach((function(e){return n.set(e[0],e[1])})):p(e)?(r=Object.getPrototypeOf(e),i=Object.getPrototypeOf(r),Object.getPrototypeOf(i)!==null&&t(19,e),e.forEach((function(e,t){return n.set(t,e)}))):e!=null&&t(20,e)})),this},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.keys());!(t=n()).done;)e.delete(t.value)}))}))},n.replace=function(e){var n=this;return Et((function(){for(var r,i=function(e){if(p(e)||H(e))return e;if(Array.isArray(e))return new Map(e);if(c(e)){var n=new Map;for(var r in e)n.set(r,e[r]);return n}return t(21,e)}(e),a=new Map,o=!1,s=C(n.vt.keys());!(r=s()).done;){var l=r.value;if(!i.has(l))if(n.delete(l))o=!0;else{var u=n.vt.get(l);a.set(l,u)}}for(var d,f=C(i.entries());!(d=f()).done;){var m=d.value,h=m[0],g=m[1],_=n.vt.has(h);if(n.set(h,g),n.vt.has(h)){var v=n.vt.get(h);a.set(h,v),_||(o=!0)}}if(!o)if(n.vt.size!==a.size)n.lt.reportChanged();else for(var y=n.vt.keys(),b=a.keys(),x=y.next(),S=b.next();!x.done;){if(x.value!==S.value){n.lt.reportChanged();break}x=y.next(),S=b.next()}n.vt=a})),this},n.toString=function(){return`[object ObservableMap]`},n.toJSON=function(){return Array.from(this)},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},S(e,[{key:`size`,get:function(){return this.lt.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Map`}}])}(),H=f(`ObservableMap`,pr),mr={},hr=function(){function e(e,n,r){var i=this;n===void 0&&(n=ce),r===void 0&&(r=`ObservableSet`),this.tt=void 0,this[I]=mr,this.vt=new Set,this.st=void 0,this.ut=void 0,this.et=void 0,this.dehancer=void 0,this.Jt=void 0,this.tt=r,a(Set)||t(22),this.Jt=function(e,t){return n(e,t,r)},Xt((function(){i.st=se(i.tt),e&&i.replace(e)}))}var n=e.prototype;return n.Qt=function(e){return this.dehancer===void 0?e:this.dehancer(e)},n.clear=function(){var e=this;Et((function(){We((function(){for(var t,n=C(e.vt.values());!(t=n()).done;)e.delete(t.value)}))}))},n.forEach=function(e,t){for(var n,r=C(this);!(n=r()).done;){var i=n.value;e.call(t,i,i,this)}},n.add=function(e){var t=this;if(At(this)){var n=Mt(this,{type:fr,object:this,newValue:e});if(!n)return this;e=n.newValue}if(!this.has(e)){Et((function(){t.vt.add(t.Jt(e,void 0)),t.st.reportChanged()}));var r=Nt(this);r&&Ft(this,r?{observableKind:`set`,debugObjectName:this.tt,type:fr,object:this,newValue:e}:null)}return this},n.delete=function(e){var t=this;if(At(this)&&!Mt(this,{type:`delete`,object:this,oldValue:e}))return!1;if(this.has(e)){var n=Nt(this),r=n?{observableKind:`set`,debugObjectName:this.tt,type:`delete`,object:this,oldValue:e}:null;return Et((function(){t.st.reportChanged(),t.vt.delete(e)})),n&&Ft(this,r),!0}return!1},n.has=function(e){return this.st.reportObserved(),this.vt.has(this.Qt(e))},n.entries=function(){var e=this.values();return Bt({next:function(){var t=e.next(),n=t.value,r=t.done;return r?{value:void 0,done:r}:{value:[n,n],done:r}}})},n.keys=function(){return this.values()},n.values=function(){this.st.reportObserved();var e=this,t=this.vt.values();return Bt({next:function(){var n=t.next(),r=n.done;return r?{value:void 0,done:r}:{value:e.Qt(n.value),done:r}}})},n.intersection=function(e){return m(e)&&!gr(e)?e.intersection(this):new Set(this).intersection(e)},n.union=function(e){return m(e)&&!gr(e)?e.union(this):new Set(this).union(e)},n.difference=function(e){return new Set(this).difference(e)},n.symmetricDifference=function(e){return m(e)&&!gr(e)?e.symmetricDifference(this):new Set(this).symmetricDifference(e)},n.isSubsetOf=function(e){return new Set(this).isSubsetOf(e)},n.isSupersetOf=function(e){return new Set(this).isSupersetOf(e)},n.isDisjointFrom=function(e){return m(e)&&!gr(e)?e.isDisjointFrom(this):new Set(this).isDisjointFrom(e)},n.replace=function(e){var n=this;return gr(e)&&(e=new Set(e)),Et((function(){Array.isArray(e)||m(e)?(n.clear(),e.forEach((function(e){return n.add(e)}))):e!=null&&t(`Cannot initialize set from `+e)})),this},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.toJSON=function(){return Array.from(this)},n.toString=function(){return`[object ObservableSet]`},n[Symbol.iterator]=function(){return this.values()},S(e,[{key:`size`,get:function(){return this.st.reportObserved(),this.vt.size}},{key:Symbol.toStringTag,get:function(){return`Set`}}])}(),gr=f(`ObservableSet`,hr),_r=Object.create(null),vr=function(){function e(e,t,n,r){t===void 0&&(t=new Map),r===void 0&&(r=vn),this.h=void 0,this.j=void 0,this.tt=void 0,this.un=void 0,this.lt=void 0,this.ut=void 0,this.et=void 0,this.v=void 0,this.p=void 0,this.on=void 0,this.sn=void 0,this.h=e,this.j=t,this.tt=n,this.un=r,this.lt=new mn(`ObservableObject.keys`),this.p=c(this.h)}var n=e.prototype;return n.O=function(e){return this.j.get(e).get()},n.S=function(e,t){var n=this.j.get(e);if(n instanceof Pn)return n.set(t),!0;if(At(this)){var r=Mt(this,{type:ir,object:this.v||this.h,name:e,newValue:t});if(!r)return null;t=r.newValue}if((t=n.xt(t))!==B.UNCHANGED){var i=Nt(this),a=i?{type:ir,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.Ot,name:e,newValue:t}:null;n.gt(t),i&&Ft(this,a)}return!0},n.ct=function(e){return B.trackingDerivation&&!g(this.h,e)&&this.it(e),this.h[e]},n.ht=function(e,t,n){return n===void 0&&(n=!1),g(this.h,e)?this.j.has(e)?this.S(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.s(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.un,n)},n.it=function(e){if(!B.trackingDerivation)return e in this.h;this.sn||=new Map;var t=this.sn.get(e);return t||(t=new Mn(e in this.h,le,`ObservableObject.key?`,!1),this.sn.set(e,t)),t.get()},n.o=function(e,n){if(!0===n&&(n=this.un),!1!==n){if(!(e in this.h)){var r;if((r=this.h[pn])!=null&&r[e])return;t(1,n.i,this.tt+`.`+e.toString())}for(var i=this.h;i&&i!==rn;){var a=tn(i,e);if(a){var o=n.o(this,e,a,i);if(o===0)return;if(o===1)break}i=Object.getPrototypeOf(i)}Wt(this,0,e)}},n.s=function(e,t,n,r){if(r===void 0&&(r=!1),!0===n&&(n=this.un),!1===n)return this.l(e,t,r);var i=n.s(this,e,t,r);return i&&Wt(this,0,e),i},n.l=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)){var i=Mt(this,{object:this.v||this.h,name:e,type:fr,newValue:t.value});if(!i)return null;var a=i.newValue;t.value!==a&&(t=ee({},t,{value:a}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else nn(this.h,e,t);this.fn(e,t.value)}finally{et()}return!0},n.g=function(e,t,n,r){r===void 0&&(r=!1);try{$e();var i=this.Ut(e);if(!i)return i;if(At(this)){var a=Mt(this,{object:this.v||this.h,name:e,type:fr,newValue:t});if(!a)return null;t=a.newValue}var o=Ht(e),s={configurable:!B.safeDescriptors||this.p,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.h,e,s))return!1}else nn(this.h,e,s);var c=new Mn(t,n,`ObservableObject.key`,!1);this.j.set(e,c),this.fn(e,c.Ot)}finally{et()}return!0},n.m=function(e,t,n){n===void 0&&(n=!1);try{$e();var r=this.Ut(e);if(!r)return r;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:fr,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;var i=Ht(e),a={configurable:!B.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else nn(this.h,e,a);this.j.set(e,new Pn(t)),this.fn(e,void 0)}finally{et()}return!0},n.Ut=function(e,t){if(t===void 0&&(t=!1),!g(this.h,e))return!0;if(At(this)&&!Mt(this,{object:this.v||this.h,name:e,type:`remove`}))return null;try{var n;$e();var r=Nt(this),i=this.j.get(e),a=void 0;if(!i&&r&&(a=tn(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof Mn&&(a=i.Ot),nt(i)),this.lt.reportChanged(),(n=this.sn)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&Ft(this,{type:`remove`,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{et()}return!0},n._t=function(e){return Pt(this,e)},n.St=function(e){return jt(this,e)},n.fn=function(e,t){var n,r=Nt(this);r&&r&&Ft(this,r?{type:fr,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.sn)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()},n.rt=function(){return this.lt.reportObserved(),dn(this.h)},n.nt=function(){return this.lt.reportObserved(),Object.keys(this.h)},e}(),yr=f(`ObservableObjectAdministration`,vr),br=Gt(0),U=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,!1===e}(),xr=0,Sr=function(){};cr=Sr,lr=Array.prototype,Object.setPrototypeOf?Object.setPrototypeOf(cr.prototype,lr):cr.prototype.__proto__===void 0?cr.prototype=lr:cr.prototype.__proto__=lr;var Cr=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray`),i===void 0&&(i=!1),a=e.call(this)||this,Xt((function(){var e=new or(r,n,i,!0);e.v=a,d(a,I,e),t&&t.length&&a.spliceWithArray(0,0,t),U&&Object.defineProperty(a,`0`,br)})),a}ne(t,e);var n=t.prototype;return n.concat=function(){this[I].st.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map((function(e){return Rt(e)?e.slice():e})))},n[Symbol.iterator]=function(){var e=this,t=0;return $t({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},S(t,[{key:`length`,get:function(){return this[I].Ft()},set:function(e){this[I].Xt(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(Sr);Object.entries(sr).forEach((function(e){var t=e[0];t!==`concat`&&u(Cr.prototype,t,e[1])})),qt(1e3);var wr=rn.toString,Tr=n().Iterator?.prototype||{};[`Symbol`,`Map`,`Set`].forEach((function(e){n()[e]===void 0&&t(`MobX requires global '`+e+`' to be available or polyfilled`)})),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:at,extras:{getDebugName:Yt},$mobx:I}),e.$mobx=I,e.FlowCancellationError=Qn,e.ObservableMap=pr,e.ObservableSet=hr,e.Reaction=Hn,e._allowStateChanges=Le,e._allowStateChangesInsideComputed=st,e._allowStateReadsEnd=Je,e._allowStateReadsStart=qe,e._autoAction=Yn,e._endAction=Ie,e._getAdministration=N,e._getGlobalState=function(){return B},e._interceptReads=function(e,t,n){var r;return H(e)||Rt(e)||Nn(e)?r=N(e):Ut(e)&&(r=N(e,t)),r.dehancer=typeof t==`function`?t:n,function(){r.dehancer=void 0}},e._isComputingDerivation=function(){return B.trackingDerivation!==null},e._resetGlobalState=function(){var e=new zn;for(var t in e)Rn.indexOf(t)===-1&&(B[t]=e[t]);B.allowStateChanges=!B.enforceActions},e._startAction=Fe,e.action=Jn,e.autorun=lt,e.comparer=gn,e.computed=Dn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((B.pendingReactions.length||B.inBatch||B.isRunningReactions)&&t(36),Vn=!0,Bn){var e=n();--e.__mobxInstanceCount==0&&(e.__mobxGlobals=void 0),B=new zn}}();var r,i,a=e.useProxies,o=e.enforceActions;if(a!==void 0&&(B.useProxies=a===`always`||a!==`never`&&typeof Proxy<`u`),a===`ifavailable`&&(B.verifyProxies=!0),o!==void 0){var s=o===`always`?`always`:o===`observed`;B.enforceActions=s,B.allowStateChanges=!0!==s&&s!==`always`}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach((function(t){t in e&&(B[t]=!!e[t])})),B.allowStateReads=!B.observableRequiresReaction,e.reactionScheduler&&(r=e.reactionScheduler,i=Un,Un=function(e){return r((function(){return i(e)}))})},e.createAtom=se,e.defineProperty=function(e,n,r){if(Ut(e))return e[I].l(n,r);t(39)},e.entries=function(e){return Ut(e)?St(e).map((function(t){return[t,e[t]]})):H(e)?St(e).map((function(t){return[t,e.get(t)]})):gr(e)?Array.from(e.entries()):Rt(e)?e.map((function(e,t){return[t,e]})):void t(7)},e.extendObservable=mt,e.flow=tr,e.flowResult=function(e){return e},e.get=function(e,n){if(Ct(e,n))return Ut(e)?e[I].ct(n):H(e)?e.get(n):Rt(e)?e[n]:void t(11)},e.getAtom=Jt,e.getDebugName=Yt,e.getDependencyTree=function(e,t){return ht(Jt(e,t))},e.getObserverTree=function(e,t){return gt(Jt(e,t))},e.has=Ct,e.intercept=function(e,t,n){return a(n)?function(e,t,n){return N(e,t).St(n)}(e,t,n):function(e,t){return N(e).St(t)}(e,t)},e.isAction=ct,e.isBoxedObservable=Nn,e.isComputed=function(e){return yt(e)},e.isComputedProp=function(e,t){return yt(e,t)},e.isFlow=vt,e.isFlowCancellationError=function(e){return e instanceof Qn},e.isObservable=xt,e.isObservableArray=Rt,e.isObservableMap=H,e.isObservableObject=Ut,e.isObservableProp=function(e,t){return bt(e,t)},e.isObservableSet=gr,e.keys=St,e.makeAutoObservable=function(e,t,n){return c(e)?mt(e,e,t,n):(Xt((function(){var r=Vt(e,n)[I];if(!e[rr]){var i=Object.getPrototypeOf(e),a=new Set([].concat(dn(e),dn(i)));a.delete(`constructor`),a.delete(I),u(i,rr,a)}e[rr].forEach((function(e){return r.o(e,!t||!(e in t)||t[e])}))})),e)},e.makeObservable=function(e,t,n){return Xt((function(){var r=Vt(e,n)[I];t??=function(e){return g(e,pn)||u(e,pn,ee({},e[pn])),e[pn]}(e),dn(t).forEach((function(e){return r.o(e,t[e])}))})),e},e.observable=R,e.observe=function(e,t,n,r){return a(n)?function(e,t,n,r){return N(e,t)._t(n,r)}(e,t,n,r):function(e,t,n){return N(e)._t(t,n)}(e,t,n)},e.onBecomeObserved=dt,e.onBecomeUnobserved=ft,e.onReactionError=function(e){return B.globalReactionErrorHandlers.push(e),function(){var t=B.globalReactionErrorHandlers.indexOf(e);t>=0&&B.globalReactionErrorHandlers.splice(t,1)}},e.override=_n,e.ownKeys=wt,e.reaction=function(e,t,n){function r(){if(p=!1,!h.isDisposed){var t=!1,r=s;h.track((function(){var n=Le(!1,(function(){return e(h)}));t=f||!m(s,n),s=n})),(f&&n.fireImmediately||!f&&t)&&l(s,r,h),f=!1}}var i;n===void 0&&(n=on);var a,o,s,c=n.name??`Reaction`,l=Jn(c,n.onError?(a=n.onError,o=t,function(){try{return o.apply(this,arguments)}catch(e){a.call(this,e)}}):t),u=!n.scheduler&&!n.delay,d=ut(n),f=!0,p=!1,m=n.compareStructural?gn.structural:n.equals||gn.default,h=new Hn(c,(function(){f||u?r():p||(p=!0,d(r))}),n.onError,n.requiresObservable);return(i=n)!=null&&(i=i.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Ut(e)?e[I].Ut(n):H(e)||gr(e)?e.delete(n):Rt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=st,e.set=function e(n,r,i){if(arguments.length!==2||gr(n))Ut(n)?n[I].ht(r,i):H(n)?n.set(r,i):gr(n)?n.add(r):Rt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(`Invalid index: '`+r+`'`),$e(),r>=n.length&&(n.length=r+1),n[r]=i,et()):t(8);else{$e();var a=r;try{for(var o in a)e(n,o,a[o])}finally{et()}}},e.spy=at,e.toJS=function(e){return function e(t,n){if(typeof t!=`object`||!t||t instanceof Date||!xt(t))return t;if(Nn(t)||In(t))return e(t.get(),n);if(n.has(t))return n.get(t);if(Rt(t)){var r=Tt(n,t,Array(t.length));return t.forEach((function(t,i){r[i]=e(t,n)})),r}if(gr(t)){var i=Tt(n,t,new Set);return t.forEach((function(t){i.add(e(t,n))})),i}if(H(t)){var a=Tt(n,t,new Map);return t.forEach((function(t,r){a.set(r,e(t,n))})),a}var o=Tt(n,t,{});return wt(t).forEach((function(r){rn.propertyIsEnumerable.call(t,r)&&(o[r]=e(t[r],n))})),o}(e,new Map)},e.trace=function(){},e.transaction=Et,e.untracked=We,e.values=function(e){return Ut(e)?St(e).map((function(t){return e[t]})):H(e)?St(e).map((function(t){return e.get(t)})):gr(e)?Array.from(e.values()):Rt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ot(e,t):Dt(e,t,n||{})}})),xw=pe((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1:function(e,t){return`Cannot apply '`+e+`' to '`+t.toString()+`': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,17:function(e,t){return`[mobx.array] Index out of bounds, `+e+` is larger than `+t},18:`mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js`,19:function(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20:function(e){return`Cannot initialize map from `+e},21:function(e){return`Cannot convert to map from '`+e+`'`},22:`mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js`,23:`It is not possible to get index atoms from arrays`,24:function(e){return`Cannot obtain administration from `+e},25:function(e,t){return`the entry '`+e+`' does not exist in the observable map '`+t+`'`},26:`please specify a property`,27:function(e,t){return`no observable property '`+e.toString()+`' found on the observable object '`+t+`'`},28:function(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32:function(e,t){return`Cycle detected in computation `+e+`: `+t},33:function(e){return`The setter of computed value '`+e+`' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34:function(e){return`[ComputedValue '`+e+`'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37:function(e){return"[mobx] `observableArray."+e+"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()."+e+"()` instead"},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`};function n(e){var n=[...arguments].slice(1),r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] `+r)}var r={};function i(){return typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:r}var a=Object.assign,o=Object.getOwnPropertyDescriptor,s=Object.defineProperty,c=Object.prototype,l=[];Object.freeze(l);var u={};Object.freeze(u);var d=typeof Proxy<`u`,f=Object.toString();function p(){d||n("`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`")}function m(e){L.verifyProxies&&n(`MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to `+e)}function h(){return++L.mobxGuid}function g(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var _=function(){};function v(e){return typeof e==`function`}function y(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return!1;var t=Object.getPrototypeOf(e);if(t==null)return!0;var n=Object.hasOwnProperty.call(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===f}function S(e){var t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function C(e,t,n){s(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function ee(e,t,n){s(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function te(e,t){var n=`isMobX`+e;return t.prototype[n]=!0,function(e){return b(e)&&e[n]===!0}}function ne(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function re(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function w(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}var ie=Object.getOwnPropertySymbols!==void 0;function T(e){var t=Object.keys(e);if(!ie)return t;var n=Object.getOwnPropertySymbols(e);return n.length?[].concat(t,n.filter(function(t){return c.propertyIsEnumerable.call(e,t)})):t}var E=typeof Reflect<`u`&&Reflect.ownKeys?Reflect.ownKeys:ie?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Object.getOwnPropertyNames;function ae(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function oe(e){return e===null?null:typeof e==`object`?``+e:e}function se(e,t){return c.hasOwnProperty.call(e,t)}var ce=Object.getOwnPropertyDescriptors||function(e){var t={};return E(e).forEach(function(n){t[n]=o(e,n)}),t};function le(e,t){return!!(e&t)}function ue(e,t,n){return n?e|=t:e&=~t,e}function de(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function fe(e,t,n){if(ye())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&be(i,n.prototype),i}function pe(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,Se(r.key),r)}}function me(e,t,n){return t&&pe(e.prototype,t),n&&pe(e,n),Object.defineProperty(e,`prototype`,{writable:!1}),e}function he(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=Ce(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
147
147
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function D(){return D=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},D.apply(null,arguments)}function ge(e){return ge=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ge(e)}function _e(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,be(e,t)}function ve(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function ye(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ye=function(){return!!e})()}function be(e,t){return be=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},be(e,t)}function xe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Se(e){var t=xe(e,`string`);return typeof t==`symbol`?t:t+``}function Ce(e,t){if(e){if(typeof e==`string`)return de(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?de(e,t):void 0}}function we(e){var t=typeof Map==`function`?new Map:void 0;return we=function(e){if(e===null||!ve(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return fe(e,arguments,ge(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),be(n,e)},we(e)}var Te=Symbol(`mobx-stored-annotations`);function Ee(e){function t(t,n){if(Ae(n))return e.decorate_20223_(t,n);De(t,n,e)}return Object.assign(t,e)}function De(e,t,r){se(e,Te)||C(e,Te,D({},e[Te])),Ke(r)&&!se(e[Te],t)&&n(`'`+(e.constructor.name+`.prototype.`+t.toString())+`' is decorated with 'override', but no such decorated member was found on prototype.`),Oe(e,r,t),Ke(r)||(e[Te][t]=r)}function Oe(e,t,r){if(!Ke(t)&&se(e[Te],r)){var i=e.constructor.name+`.prototype.`+r.toString(),a=e[Te][r].annotationType_,o=t.annotationType_;n(`Cannot apply '@`+o+`' to '`+i+`':`+(`
@@ -178,7 +178,7 @@ Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra
178
178
  `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function jE(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const ME={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Rs(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return jE(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,{index:r,count:e.children.length,distribution:e.distribution})))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name,...e.opens!==void 0&&{opens:{open:t.parse(dc(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,`${t.path}.opens.body`)}}}},render(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];try{if(!GT(i.when,t.scope))return[];let n=i.palette??t.palette,a=t.enterSegment(e.name,n,t.region,i.bg,i.fg),o=i.template.evaluate(t.scope),s=t.exitSegment(o),c=e.opens!==void 0&&GT(e.opens.open,t.scope),l=e.opens===void 0?[]:t.renderBody(e.opens.body,c,a.disclosure),u=s.length>0||c?a.trigger:a.closed,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=AE(HT(o,u)).map(e=>qT(e,d)),p=s.map(e=>qT(HT([e],a.band),{...d,baseStyle:a.band})),m=[...f,...p];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,m.flat()),[...m,...l]}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[[new Ar(`⚠ ${e.name}: ${r}`)]]}}}};function NE(e){return ME[e]}function PE(e){if(`ttl`in e)return{kind:`ttl`,durationMs:xT(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function FE(e,t){switch(ba(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function IE(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:PE(n.cache),parse:FE(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:PE(n.cache),parse:FE(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?xT(n.cache.ttl):void 0,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function LE(e,t){let n=pl.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function RE(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=mE(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=rh(e.presets),l=new Map([...j_(e),...wh(e)]),u=fT({...dE(i),...SE(i,a),...OE(o),...kE(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=LE(u,e.helpers),f=e=>u.parse(e,d),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=$T(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{IE(t,n,i,r)}catch(e){m.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{IE(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[t]={when:n.when===void 0?void 0:e(n.when,`when`),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`),palette:n.palette===void 0?void 0:BT(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),parse:(e,n)=>g(e,t,n),compileChild:_};return NE(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=oh(e,t);v.set(t,_(n,r))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,loadWarnings:m}}function zE(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=hn,preset:f=th}=c??{};r.applyInput({...i,term:{cols:o.width}}),t.menuRuntime.action.stripStyle=o.style,t.menuRuntime.action.padding=o.padding;let p=pT(n),m=VT(a,d);l?.clear();let h=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},g=(e,n,r,i,a)=>{let{tint:o,text:s,disclosure:c}=ac(n,r),l=YT(t.activeSegment,e,n,c,o,s,i,a,p),u=Qs(n,c);return{closed:l,trigger:fE(n,u.state),band:fE(n,u.plane),disclosure:c}},_=e=>(t.activeSegment.current=null,wE(e)),v=(e,t,n)=>{let r=t&&GT(e.when,p),i={scope:p,palette:m,visible:r,padding:o.padding,region:n,perSegmentSink:l,onSegmentError:u,enterSegment:g,exitSegment:_,lookupSegment:h,renderChild:(e,t,r)=>v(e,t,nc(n,r)),renderBody:(e,t,n)=>v(e,r&&t,rc(n))};return NE(e.kind).render(e,i)},y=t.roots.get(f);if(y===void 0)throw Error(`Preset "${f}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${th}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return v(y,!0,tc).map(e=>lx(e,o)).join(`
179
179
  `)}var BE=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,WE(e,t,n,`initial value`),this.cell=Sw.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){WE(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},VE=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Sw.computed)(()=>{let e=n();return WE(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},HE=class{kind=`document`;cell;lastSetAt;constructor(e,t){this.name=e,this.cell=Sw.observable.box(UE(t),{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){this.cell.set(UE(e)),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}};function UE(e){return e.kind===`ok`?{kind:`ok`,value:Cw(e.value)}:e}function WE(e,t,n,r){let i=ww(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var GE=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new BE(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new HE(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new VE(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Sw.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Sw.runInAction)(()=>n.set(t))}runInAction(e){(0,Sw.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return JSON.stringify(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function KE(e,t,n){return e+`\0`+t+`\0`+(n??``)}function qE(e,t){return new Set(rh(e.presets).filter(n=>oh(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function JE(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function YE(e,t){let n=new Map;for(let t of lv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=JE(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}function XE(e){return e.filter(Boolean).join(`
180
180
  `)||null}var ZE=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=KE(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=dv(e,t,n),i=r.kind===`file`?r.path:null,a=[hv(e,t),pv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof da&&a.push(...e.warnings),{resolvedPath:i,warning:XE(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:XE(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=gv(t,yw);n.push(...o);let s=yv(r,t??`<default>`,a),c=new GE,l=new LT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=RE(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of hS(s))d.push(cS(e,t));for(let{key:e,spec:t}of Zx(s))d.push(Qx(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:nw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:qE(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=YE(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Y(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const QE=16384;var $E=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<QE){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%QE}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ky,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const eD={load:()=>({}),save:()=>{},flush:()=>{}};function tD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var nD=class{sessions;storage;atom=(0,Sw.createAtom)(`SessionState`);constructor(e=eD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=tD(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Sw.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Sw.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Sw.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const rD=(e,t)=>D(t);function iD(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 aD=class{timer=null;pending=null;constructor(e,t=500,n=rD){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return iD(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const oD={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`},sD=new Set([`1`,`true`]),cD=new Set([`0`,`false`,``]);function lD(e,t){let n=PD(e),r=n.scope===`globals`?oD[n.field]:`string`;if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(sD.has(t))return`true`;if(cD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function uD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function dD(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),ke(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function fD(e){return/^\s*$/.test(e)?null:ji(e)}function pD(e,t){return e!==null&&Ni(e,t)!==void 0}function mD(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(mD),...i}}return e}function hD(e){if(!ao(e))return mD(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,mD(t)])),...n}}const gD=_w,_D=gD.segments,vD=gD.presets,yD=gD.root;function bD(e,t,n,r){if(!pD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function xD(e,t){let n=fh(t);return t.scope===`segment-palette`&&bD(e,[`segments`,t.segment],_D[t.segment],n.join(`.`)),n}function SD(e){return ji(zi(e))}function CD(){return Object.entries(yD.rows).map(([e,t])=>{let n=mD(t);return{path:[`root`],fragment:SD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function wD(e,t){let n=e===null?void 0:Ni(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function TD(e,t){if(t===void 0)return null;let n=hD(t);return{path:e,fragment:SD(n),unit:{path:e,value:n}}}function ED(e,t){let n=[`presets`,t],r=[...n,`root`],i=vD[t];bD(e,n,i,r.join(`.`));let a=wD(e,r)??TD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function DD(e,t){let n=ia(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function OD(e,t){return[...CD(),wD(e,[`root`]),ED(e,t)].filter(e=>e!==null).reduce(DD,new Map)}function kD(e,t,n){for(let{node:r,...i}of OD(e,t).values())if(sa(r,n))return i;throw new $(`${AD(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function AD(e,t){return ED(e,t)?.path??[`root`]}function jD(e,t){return t.scope===`preset-root`?AD(e,t.preset):fh(t)}function MD(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function ND(e){let t=dh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function PD(e){let t=ND(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function FD(e,t){let n=PD(t),r=fD(uD(e)??``),i=r===null?void 0:Ni(r,fh(n));return i!==void 0&&`value`in i?i.value:void 0}function ID(e,t,n,r){let i=PD(n),a=uD(t);KD(e,t,{before:a,after:$i(a??``,xD(fD(a??``),i),lD(n,r),Li)})}function LD(e,t,n){let r=ND(n),i=uD(t);if(i===null)return;let a=ea(i,jD(fD(i),r));a!==i&&KD(e,t,{before:i,after:a})}function RD(e,t,n,r){let i=ND(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=uD(t),o=r.op===`remove`?r.target:r.anchor,s=kD(fD(a??``),i.preset,o),c=MD(a??``,s),l=r.op===`remove`?la(c,s.path,r.target):ua(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);KD(e,t,{before:a,after:l})}const zD={past:[],future:[]};function BD(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function VD(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(BD)&&Array.isArray(t.future)&&t.future.every(BD)}function HD(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(VD))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function UD(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),ke(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function WD(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function GD(e,t,n,r,i){dD(t,n,e.logger);try{UD(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function KD(e,t,n){let r=HD(e),{past:i}=r[t]??zD;GD(e,t,n.after,{...r,[t]:{past:WD(i,n),future:[]}},`edit`)}function qD(e,t){let n=HD(e),{past:r,future:i}=n[t]??zD,a=r[r.length-1];return a===void 0?null:(YD(t,a.after,`undo`),GD(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:WD(i,a)}},`undo`),a)}function JD(e,t){let n=HD(e),{past:r,future:i}=n[t]??zD,a=i[i.length-1];return a===void 0?null:(YD(t,a.before,`redo`),GD(e,t,a.after,{...n,[t]:{past:WD(r,a),future:i.slice(0,-1)}},`redo`),a)}function YD(e,t,n){if(uD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function XD(e){let t=Ee({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function ZD(){return{probeTmux:XD,claudeSettingsPath:qy()}}function QD(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function $D(e){if(/^\s*$/.test(e))return{};let t=Ri.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function eO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function tO(e){try{return $D(QD(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function nO(e,t){return{tmux:eO(e,t),claudeSettingsEnv:tO(e)}}function rO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(QD(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),ke(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:tO(e)}}default:return t.kind}}function iO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function aO(e){return oO(()=>decodeURIComponent(e))}function oO(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function sO(e,t){let n=Ee({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const cO=(e,t)=>sO(aO(e),t),lO=(e,t)=>{let n=Ee({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,aO(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},uO=(e,t)=>sO(aO(e),t),dO=(e,t)=>sO(aO(e),t),fO=(e,t)=>{let n=iO(aO(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},pO=(e,t)=>{let[n=``,...r]=oO(()=>Hy(e)),i=iO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${sS().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${sS().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=lS(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},mO=/^-?\d+$/;function hO(e,t,n){return e>n?t:e<t?n:e}function gO(e,t){if(!e)return null;if(!sS().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${sS().join(`, `)})`);return e}function _O(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const vO=(e,t)=>{let[n=``,r=``,i=``]=oO(()=>Hy(e)),a=iO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!mO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=uS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${sS().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&mO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=hO(l+o,s.min,s.max),d=lS(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},yO=`render-origin`;function bO(e){return JSON.stringify(e)}function xO(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function SO(e,t){let n=e.sessionState.get(t,yO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=xO(n);return fv(r.projectDir,r.cwd,r.configFile??void 0)}function CO(e){return{historyPath:ze(),logger:e.dlog}}const wO=(e,t)=>{let[n=``,r=``,i=``,a=``]=oO(()=>Hy(e)),o=iO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${Ux().join(`, `)})`);let s=Wx(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=gO(a,`set-config`),l=SO(t,o);ID(CO(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),_O(c,o,t,`set-config`)},TO=(e,t)=>{let[n=``,r=``,i=``,a=``]=oO(()=>Hy(e)),o=iO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!mO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=gO(a,`step-config`),l=Gx(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${Ux().join(`, `)})`);let u=SO(t,o),d=FD(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=hO(f+s,l.min,l.max),m=Wx(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);ID(CO(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),_O(c,o,t,`step-config`)},EO=(e,t)=>{let[n=``,r=``]=oO(()=>Hy(e)),i=iO(n);if(!r||!Ux().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${Ux().join(`, `)})`);let a=SO(t,i);LD(CO(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},DO=(e,t)=>{let[n=``,r=``,i=``]=oO(()=>Hy(e)),a=iO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${Ux().join(`, `)})`);let o=Wx(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=$m(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=SO(t,a);RD(CO(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},OO=(e,t)=>{let[n=``]=oO(()=>Hy(e)),r=iO(n),i=SO(t,r);if(qD(CO(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},kO=(e,t)=>{let[n=``]=oO(()=>Hy(e)),r=iO(n),i=SO(t,r);if(JD(CO(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},AO=(e,t)=>{iO(aO(e)),t.applyUpdate()},jO=`client-hints`;function MO(e,t){let n=e.sessionState.get(t,jO);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return Ev(r)}function NO(e,t,n){let r=Ih(n);e.sessionState.setBatch(t,zh(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const PO=(e,t)=>{let n=iO(aO(e));NO(t,n,nO(t.doctor,MO(t,n).tmux))},FO=(e,t)=>{let[n=``,r=``]=oO(()=>Hy(e)),i=iO(n),a=Lh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=nO(t.doctor,MO(t,i).tmux),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=rO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),NO(t,i,c)},IO=`config-override`,LO=new Map([[Dy,cO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=iO(oO(()=>decodeURIComponent(e.slice(0,n)))),i=oO(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,IO),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,IO,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Oy,lO],[Ty,pO],[Ey,vO],[My,wO],[Ny,TO],[Py,EO],[Fy,DO],[Iy,OO],[Ly,kO],[Ay,uO],[jy,dO],[ky,fO],[Ry,AO],[zy,PO],[By,FO]]),RO=new Set([Ty,Ey,My,Ny,Py,Fy,Iy,Ly,ky,Ry,zy,By]),zO=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Wy(e)){if(!i&&RO.has(a)){let e=Hy(o);e.length>0&&e[0]&&(i=e[0])}let e=LO.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
181
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},BO=new Map([...LO,[wy,zO]]);Object.freeze([...BO.keys()]);const VO=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),HO=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]];function UO(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of HO){let i=GO(n,e);if(i==null)t.missingRequired.push(e);else{let n=WO(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))VO.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function WO(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function GO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function KO(e,t){switch(e){case`vars`:return{what:e,vars:qO(t)};case`segments`:return{what:e,segments:QO(t)};case`config`:return{what:e,config:tk(t)}}}function qO(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=XO(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...JO(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:YO(r.lastUpdatedMs())})}return o}function JO(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function YO(e){return e===null?null:Math.max(0,Date.now()-e)}function XO(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,ZO(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,ZO(i));return t}function ZO(e){return e.kind}function QO(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=$O(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:ek(t.template,i),lastRender:r.get(e)??null})}return o}function $O(e){let t=[],n=new Set;for(let r of va(co(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function ek(e,t){let n=new Set;for(let r of L_(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function tk(e){return e===null?null:e.config}const nk=[`vars`,`segments`,`config`];function rk(e){return typeof e==`string`&&nk.includes(e)}function ik(e){return Math.max(1,e-2)}var ak=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await TC(e);if(n.length===0)return D(`No entries in transcript`),Z;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function ok(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var sk=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(ok(r))t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}async foldMetrics(e,t){let n=this.state.get(e),r=pC(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await kC(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(ok(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const ck=new Map;function lk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var uk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=lk(process.env.TMUX),t=ck.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return ck.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},dk=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const fk=new $E;Ce(fk.launchStats);const pk=new tC({counters:fk,logger:Y}),mk=new lC({watchers:pk,logger:Y}),hk=new VC,gk=new nD,_k=new dk(We()),vk=new ak,yk=new sk,bk=new uk,xk=new ZE({gitService:mk,sessionState:gk,watchers:pk},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),Sk=60*1e3;function Ck(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),zk(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Sk),a.unref())},checkNow:o}}const wk=Ck(),Tk=AS({entryUrl:import.meta.url,intervalMs:Sk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>wk.checkNow(),log:Y});let Ek=null,Dk=null,Ok=0;function kk(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),zk(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),zk(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),zk(0)});try{Ok=ty(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),zk(1);return}Ek=Rb(t.pid);let e=Jb(Xb(Ek));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),zk(1);return}Dk=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),gk.useStorage(new aD(Re(),500,Y)),Vb({anchor:Bb(t.env),isAlive:Hb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),zk(0)}}),Ak(g.createServer({allowHalfOpen:!1},e=>{Bk(e)}),Ne(),!1)}function Ak(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),zk(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}jk(e,n)}),e.listen(n,()=>Mk(n))}function jk(e,n){let i=Ob(kb(Ie(n)),(e,t)=>Lb(e,t,{readStartTime:Ib,pidAlive:Hb}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),zk(1);return}}Ak(e,n,!0)}function Mk(e){let n=Mb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),zk(0);return}Ik(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(Ok/1048576)}MB`),py();let i=_k.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),wk.arm(),Tk.arm(),Fk(),Nk(e,n.identity)}function Nk(e,n){Fb({bound:n,myPid:t.pid,readIdentity:()=>Mb(e),readLease:()=>kb(Ie(e)),shutdown:e=>zk(e),log:Y}).arm()}let Pk=null;function Fk(){Pk=ny(iy(fk.startedAt.getTime(),e=>zk(e),{rssLimitBytes:Ok})),Pk.arm()}function Ik(e){let n=Ab(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Ek});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let Lk=0,Rk=!1;function zk(e){if(!Rk){Rk=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{mk.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{hk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{pk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{gk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}jb(Le(),t.pid),Dk!==null&&Yb(Dk,t.pid,Kb,e=>r.unlinkSync(e)),t.exit(e)}}function Bk(e){Lk++,fk.inFlight=Lk;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>zk(r);try{e.end(Nv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{fk.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{Hk(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Lk=Math.max(0,Lk-1),fk.inFlight=Lk})}const Vk=e=>({resp:e,exitAfterFlush:null});async function Hk(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Vk({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return Vk({ok:!0,stats:fk.snapshot({gitCache:mk.getStats(),usageCache:hk.getStats(),renderCacheSize:xk.size,watchersActive:pk.size(),nextRestartReason:Pk?.describeNextRestart()??null})});if(e.kind===`render`){fk.requestsTotal++;let t=Date.now();try{let{report:n}=UO(e.hookData);for(let e of n.unknownTopLevelFields)Y(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return fk.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Vk({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Uk(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);gk.get(s,`client-hints`)!==l&&gk.set(s,jO,l);let u=gk.get(s,`config-override`)??a??c.configEnv,d=xk.getOrCreate(i,e.cwd,u),f=bO({projectDir:i,cwd:e.cwd,configFile:u??null});gk.get(s,`render-origin`)!==f&&gk.set(s,yO,f);let p=c.termCols,m=ik(p??120),h=ux(c.termRows),g={...Gk,width:m},{authoredRoots:_}=d.state,v=qC(d.state.config,t=>gk.get(e.hookData.session_id,t),e=>_.has(e)),y=await ow(e.hookData,Yk,e.cwd,d.state.neededInputPaths,v,c),b=BT(v.theme);g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=zE(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,b,g,{perSegmentSink:d.state.lastRenderCellsBySegment},{look:fi(d.state.config.looks,v.look),preset:v.preset}),S=gk.get(e.hookData.session_id,`click.error`);S&&gk.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
181
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},BO=new Map([...LO,[wy,zO]]);Object.freeze([...BO.keys()]);const VO=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),HO=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]];function UO(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of HO){let i=GO(n,e);if(i==null)t.missingRequired.push(e);else{let n=WO(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))VO.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function WO(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function GO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function KO(e,t){switch(e){case`vars`:return{what:e,vars:qO(t)};case`segments`:return{what:e,segments:QO(t)};case`config`:return{what:e,config:tk(t)}}}function qO(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=XO(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...JO(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:YO(r.lastUpdatedMs())})}return o}function JO(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function YO(e){return e===null?null:Math.max(0,Date.now()-e)}function XO(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,ZO(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,ZO(i));return t}function ZO(e){return e.kind}function QO(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=$O(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:ek(t.template,i),lastRender:r.get(e)??null})}return o}function $O(e){let t=[],n=new Set;for(let r of va(co(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function ek(e,t){let n=new Set;for(let r of L_(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function tk(e){return e===null?null:e.config}const nk=[`vars`,`segments`,`config`];function rk(e){return typeof e==`string`&&nk.includes(e)}function ik(e){return Math.max(1,e-2)}var ak=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{D(`Calculating context tokens from transcript: ${e}`);let n=await TC(e);if(n.length===0)return D(`No entries in transcript`),Z;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}};function ok(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var sk=class{state=new Map;calculateLastResponseTime(e){if(e.length===0)return null;let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(ok(r))t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}async foldMetrics(e,t){let n=this.state.get(e),r=pC(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.state.delete(e),this.state.set(e,n),{kind:`ok`,value:{messageCount:n.messageCount,recent:[...n.recent]}};let i=await kC(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:{messageCount:n?.messageCount??0,recent:[...n?.recent??[]]}};let{entries:a,cursor:o,reset:s}=i.value,c=n&&!s?n:void 0,l=c?.messageCount??0,u=c?[...c.recent]:[];for(let e of a)e.isSidechain||(ok(e)&&l++,u.push(e));for(u.length>20&&(u=u.slice(-20)),this.state.delete(e),this.state.set(e,{cursor:o,messageCount:l,recent:u});this.state.size>256;){let e=this.state.keys().next().value;if(e===void 0)break;this.state.delete(e)}return{kind:`ok`,value:{messageCount:l,recent:[...u]}}}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.foldMetrics(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:this.calculateLastResponseTime(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const ck=new Map;function lk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var uk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=lk(process.env.TMUX),t=ck.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return ck.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},dk=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const fk=new $E;Ce(fk.launchStats);const pk=new tC({counters:fk,logger:Y}),mk=new lC({watchers:pk,logger:Y}),hk=new VC,gk=new nD,_k=new dk(We()),vk=new ak,yk=new sk,bk=new uk,xk=new ZE({gitService:mk,sessionState:gk,watchers:pk},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),Sk=60*1e3;function Ck(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),zk(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Sk),a.unref())},checkNow:o}}const wk=Ck(),Tk=AS({entryUrl:import.meta.url,intervalMs:Sk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>wk.checkNow(),log:Y});let Ek=null,Dk=null,Ok=0;function kk(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),zk(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),zk(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),zk(0)});try{Ok=ty(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),zk(1);return}Ek=Rb(t.pid);let e=Jb(Xb(Ek));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),zk(1);return}Dk=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),gk.useStorage(new aD(Re(),500,Y)),Vb({anchor:Bb(t.env),isAlive:Hb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),zk(0)}}),Ak(g.createServer({allowHalfOpen:!1},e=>{Bk(e)}),Ne(),!1)}function Ak(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),zk(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}jk(e,n)}),e.listen(n,()=>Mk(n))}function jk(e,n){let i=Ob(kb(Ie(n)),(e,t)=>Lb(e,t,{readStartTime:Ib,pidAlive:Hb}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),zk(1);return}}Ak(e,n,!0)}function Mk(e){let n=Mb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),zk(0);return}Ik(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(Ok/1048576)}MB`),py();let i=_k.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),wk.arm(),Tk.arm(),Fk(),Nk(e,n.identity)}function Nk(e,n){Fb({bound:n,myPid:t.pid,readIdentity:()=>Mb(e),readLease:()=>kb(Ie(e)),shutdown:e=>zk(e),log:Y}).arm()}let Pk=null;function Fk(){Pk=ny(iy(fk.startedAt.getTime(),e=>zk(e),{rssLimitBytes:Ok})),Pk.arm()}function Ik(e){let n=Ab(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Ek});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let Lk=0,Rk=!1;function zk(e){if(!Rk){Rk=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{mk.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{hk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{pk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{gk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}jb(Le(),t.pid),Dk!==null&&Yb(Dk,t.pid,Kb,e=>r.unlinkSync(e)),t.exit(e)}}function Bk(e){Lk++,fk.inFlight=Lk;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>zk(r);try{e.end(Nv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{fk.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{Hk(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Lk=Math.max(0,Lk-1),fk.inFlight=Lk})}const Vk=e=>({resp:e,exitAfterFlush:null});async function Hk(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Vk({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return Vk({ok:!0,stats:fk.snapshot({gitCache:mk.getStats(),usageCache:hk.getStats(),renderCacheSize:xk.size,watchersActive:pk.size(),nextRestartReason:Pk?.describeNextRestart()??null})});if(e.kind===`render`){fk.requestsTotal++;let t=Date.now();try{let{report:n}=UO(e.hookData);for(let e of n.unknownTopLevelFields)Y(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return fk.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Vk({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Uk(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);gk.get(s,`client-hints`)!==l&&gk.set(s,jO,l);let u=gk.get(s,`config-override`)??a??c.configEnv,d=xk.getOrCreate(i,e.cwd,u),f=bO({projectDir:i,cwd:e.cwd,configFile:u??null});gk.get(s,`render-origin`)!==f&&gk.set(s,yO,f);let p=c.termCols,m=ik(p??120),h=ux(c.termRows),g={...Gk,width:m},{authoredRoots:_}=d.state,v=qC(d.state.config,t=>gk.get(e.hookData.session_id,t),e=>_.has(e)),y=await ow(e.hookData,Yk,e.cwd,d.state.neededInputPaths,v,c),b=BT(v.theme);g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=zE(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,b,g,{perSegmentSink:d.state.lastRenderCellsBySegment},{look:fi(d.state.config.looks,v.look),preset:v.preset}),S=gk.get(e.hookData.session_id,`click.error`);S&&gk.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
182
182
  `),ee=Tk.notice({sessionId:s,dismissed:gk.get(s,gS),enabled:v.updateNotice}),te=d.lastError===null?null:d.configFilePath,ne=hx(C,ee,d.lastWarning??``),re=_k.sync(s,ne===null?null:_x(ne));re!==null&&Y(`warn`,`diagnostic dump failed: ${re}`);let w=vx(x,ne,{fullText:re===null?{kind:`file`,path:_k.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),ie=Date.now()-t,T=mk.getStats(),E=hk.getStats();return Y(`info`,`render sid=${e.hookData.session_id??`?`} took=${ie}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${T.size}/${T.hits}h/${T.misses}m usage=${E.size}/${E.hits}h/${E.misses}m err=${C?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),Vk({ok:!0,output:w+`
183
183
  `})}catch(e){throw fk.requestsErrored++,e}}if(e.kind===`click`)return Vk(await Xk(e.verb,e.value));if(e.kind===`debug`){if(!rk(e.what))return Vk({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${nk.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=xk.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Jk(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):qk};return Vk({ok:!0,debug:KO(e.what,n)})}return Vk({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function Uk(e){let{values:t,tokens:n}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:Dv(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const Wk={sessionState:gk,dlog:Y,applyUpdate:()=>Tk.act(),doctor:ZD()},Gk={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},Kk={...Gk,width:1/0},qk=new Map;function Jk(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,lx(a,{...Kk,charset:t,colorCompatibility:n}));return r}const Yk={gitProvider:mk,usageStore:hk,contextProvider:vk,metricsProvider:yk,tmuxService:bk,log:Y,clock:()=>new Date};function Xk(e,t){let n=BO.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Wk),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const Zk={connectMs:200,budgetMs:500};async function Qk(e){let n=e.includes(`--json`),r=await $k();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Hv(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
184
184
  `);return}t.stdout.write(rA(r.value))}function $k(){return Iv({kind:`stats`},Zk,e=>`stats`in e?e.stats:void 0)}function eA(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function tA(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function nA(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function rA(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${nA(e.uptimeSec)}`),t.push(` rss ${eA(e.rssBytes)}`),t.push(` heapUsed ${eA(e.heapUsedBytes)}`),t.push(` heapTotal ${eA(e.heapTotalBytes)}`),t.push(` external ${eA(e.externalBytes)}`),t.push(` arrayBuffers ${eA(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${tA(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${tA(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
@@ -188,7 +188,7 @@ Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra
188
188
  `;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?``:` ${fA(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${dA(a.value)}${e}${o}`)}return t.join(`
189
189
  `)+`
190
190
  `}function lA(e){if(e.length===0)return`no segments (DSL not active)
191
- `;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
191
+ `;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
192
192
  `)+`
193
193
  `}function uA(e){return e===null?`config: DSL not active
194
194
  `:JSON.stringify(e,null,2)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.62.0",
3
+ "version": "1.63.0",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -90,9 +90,9 @@
90
90
  "mobx": "^6.15.0"
91
91
  },
92
92
  "optionalDependencies": {
93
- "@promptctl/cc-candybar-darwin-arm64": "1.62.0",
94
- "@promptctl/cc-candybar-darwin-x64": "1.62.0",
95
- "@promptctl/cc-candybar-linux-x64": "1.62.0",
96
- "@promptctl/cc-candybar-linux-arm64": "1.62.0"
93
+ "@promptctl/cc-candybar-darwin-arm64": "1.63.0",
94
+ "@promptctl/cc-candybar-darwin-x64": "1.63.0",
95
+ "@promptctl/cc-candybar-linux-x64": "1.63.0",
96
+ "@promptctl/cc-candybar-linux-arm64": "1.63.0"
97
97
  }
98
98
  }
@@ -1413,6 +1413,9 @@
1413
1413
  "template": {
1414
1414
  "type": "string"
1415
1415
  },
1416
+ "description": {
1417
+ "type": "string"
1418
+ },
1416
1419
  "width": {
1417
1420
  "anyOf": [
1418
1421
  {
@@ -2049,6 +2052,9 @@
2049
2052
  "template": {
2050
2053
  "type": "string"
2051
2054
  },
2055
+ "description": {
2056
+ "type": "string"
2057
+ },
2052
2058
  "width": {
2053
2059
  "anyOf": [
2054
2060
  {