@promptctl/cc-candybar 1.64.1 → 1.66.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 +22 -21
- package/package.json +5 -5
- package/schema/cc-candybar.schema.json +6 -0
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(),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 cn(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=cn(Ws(e,`surface`),Ws(e,t),.92),i=Ws(e,`foreground`),a=Array.from({length:13},(e,t)=>cn(r,i,t/12)).find(e=>n.every(t=>Rn(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)=>Rn(t,n)>Rn(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:cn(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 cn(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`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", 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 cn(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=cn(Ws(e,`surface`),Ws(e,t),.92),i=Ws(e,`foreground`),a=Array.from({length:13},(e,t)=>cn(r,i,t/12)).find(e=>n.every(t=>Rn(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)=>Rn(t,n)>Rn(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:cn(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 cn(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(`
|
|
@@ -122,7 +122,7 @@ Config tooling:
|
|
|
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(Pe(),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=Ke(),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{}}}function Zv(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
123
123
|
`)}function Qv(e,t){return e===`darwin`?[$v(`footprint`,[`-p`,String(t)]),$v(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[ey(`/proc/self/smaps_rollup`),ey(`/proc/self/status`)]:[]}function $v(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=De({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${ty(n.stderr)}`}}}}function ey(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function ty(e){let t=e.split(`
|
|
124
124
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const ny=`CC_CANDYBAR_RSS_LIMIT_MB`;function ry(e){let t=e[ny];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ny} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function iy(e){return ry(e)*2}const ay=1024*1024;function oy(e){return ry(e)*ay}const sy={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function cy(e,t,n){let{prefix:r,suffix:i}=sy[t];return c.join(e,`${r}${n}${i}`)}function ly(e){for(let t of Object.keys(sy)){let{prefix:n,suffix:r}=sy[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function uy(e){let t=e.rssLimitBytes??512*ay,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return dy(e.log,`memory report`,()=>{let t=cy(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),dy(e.log,`heap snapshot`,()=>{let t=cy(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),dy(e.log,`artifact rotation`,()=>{py(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function dy(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function fy(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=ly(t);if(n===null)return t;let{prefix:r,suffix:i}=sy[n];return t.slice(r.length,t.length-i.length)}function py(e,t,n){let r=new Map;for(let t of e){let e=fy(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function my(e,t,n={}){let i=Ne();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Y,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>Zv(Qv(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>ly(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function hy(e={}){if(jy()!==null)return;let n=e.spawn??My,r=Oy();if(r.kind===`contended`){let e=_y();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),gy(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),gy(n);return}try{gy(n)}finally{Ay()}}function gy(e){wy()&&vy(e)}function _y(){try{let e=r.statSync(He());return Date.now()-e.mtimeMs}catch{return null}}function vy(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
125
|
-
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function yy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function by(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function xy(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function Sy(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Cy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function wy(){let e=Ue(),n=We(),r=xy(n),i=yy(Ty(e),by(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`),Ey(e),Sy(n,Math.min(r+1,5)),!0)}function Ty(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ey(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 Dy=null;function Oy(){let e=He();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 Dy={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(!ky(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 ky(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ay(){if(!Dy)return;let{fd:e,path:t}=Dy;Dy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function jy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function My(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${iy(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Ny=`cc-candybar`,Py=`dispatch`,Fy=`set-state`,Iy=`step-state`,Ly=`copy`,Ry=`open-vscode`,zy=`toolbar-toggle`,By=`show-config-error`,Vy=`show-config-warning`,Hy=`set-config`,Uy=`step-config`,Wy=`reset-config`,Gy=`apply-layout-op`,Ky=`undo`,qy=`redo`,Jy=`apply-update`,Yy=`doctor-run`,Xy=`doctor-fix`;function Zy(e){return e.map(encodeURIComponent).join(`/`)}function Qy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function $y(e){return`${Ny}://${Py}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Zy(e.args)}`)}`).join(`&`)}`}function eb(e){return new y(e).getAll(`e`).map(tb)}function tb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const nb=`1.
|
|
125
|
+
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function yy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function by(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function xy(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function Sy(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Cy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function wy(){let e=Ue(),n=We(),r=xy(n),i=yy(Ty(e),by(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`),Ey(e),Sy(n,Math.min(r+1,5)),!0)}function Ty(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Ey(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 Dy=null;function Oy(){let e=He();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 Dy={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(!ky(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 ky(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ay(){if(!Dy)return;let{fd:e,path:t}=Dy;Dy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function jy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function My(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${iy(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Ny=`cc-candybar`,Py=`dispatch`,Fy=`set-state`,Iy=`step-state`,Ly=`copy`,Ry=`open-vscode`,zy=`toolbar-toggle`,By=`show-config-error`,Vy=`show-config-warning`,Hy=`set-config`,Uy=`step-config`,Wy=`reset-config`,Gy=`apply-layout-op`,Ky=`undo`,qy=`redo`,Jy=`apply-update`,Yy=`doctor-run`,Xy=`doctor-fix`;function Zy(e){return e.map(encodeURIComponent).join(`/`)}function Qy(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function $y(e){return`${Ny}://${Py}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Zy(e.args)}`)}`).join(`&`)}`}function eb(e){return new y(e).getAll(`e`).map(tb)}function tb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const nb=`1.66.0`;function rb(){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 ib(e,t){return e?.kind===`ok`?e.value:t}const ab=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function ob(e){let t=ab.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 sb(e){return e.join(`.`)}function cb([e,t,n],[r,i,a]){return e-r||t-i||n-a}const lb=`@promptctl/cc-candybar`;async function ub(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`?ob(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function db(e,t){let n=ob(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=cb(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 fb(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${sb(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${sb(t.installed)} is newer than the registry's latest release (${sb(t.latest)}): an unpublished build.\n`};case`stale`:{let n=sb(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${sb(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 pb=`CCCandybarURLHandler`,mb=[],hb={"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 gb(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function _b(e,t){return[e,...t].map(gb).join(` `)}function vb(){return c.join(f.homedir(),`Applications`,`${pb}.app`)}function yb(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function bb(){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 xb(){return c.join(bb(),`bin`,`cc-candybar`)}function Sb(){return c.join(bb(),`dist`,`index.mjs`)}function Cb(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
|
|
126
126
|
`)}function wb(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 Tb(t){let n=hb[`${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 Eb(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function Db(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 ${lb}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function Ob(){let e=wb(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=Tb(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Sb()),{recursive:!0}),r.mkdirSync(c.dirname(xb()),{recursive:!0}),Eb(e,Sb()),Eb(t.sourcePath,xb()),r.chmodSync(xb(),493),r.rmSync(c.join(bb(),`url-handler.mjs`),{force:!0});let n=Db(xb());return process.stdout.write(`Staged cc-candybar v${nb} runtime at ${bb()}\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:xb(),distPath:Sb(),entryKind:n}}function kb(){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>${Ny}</string>`,` </array>`,` </dict>`,`</array>`].join(`
|
|
127
127
|
`)}]}function Ab(e){let t=vb();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=De({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,Cb(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of kb())De({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of kb()){let n=De({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 ${Ny}:// with Launch Services\n`);let a=De({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(`✓ ${pb}.app installed and registered.\n`),process.stdout.write(` Test: open '${Ny}://hello-world' && pbpaste\n`)}function jb(){yb(),Ab(Ob().distPath)}function Mb(e,t=Ny){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:Ly,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Nb(e){e||(process.stderr.write(`url-handle: missing URL argument.
|
|
128
128
|
`),process.exit(1));let t;try{t=Mb(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`&&(hy(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Pb(n)+`
|
|
@@ -135,7 +135,7 @@ Config tooling:
|
|
|
135
135
|
`)?r.slice(0,-1):r}return Vr(new jr([...e],n),{colorSystem:t.colorCompatibility})}function bx(e){return Math.min(20,e??20)}const xx={heading:`ERROR`,glyph:`⚠`,colors:px},Sx={heading:`WARNING`,glyph:`⚠`,colors:mx},Cx={heading:`UPDATE`,glyph:`⬆`,colors:mx};function wx(e,t){return{text:cx(e),link:t}}function Tx(e,t,n){let[r,...i]=[Ex(e,xx,By),t,Ex(n,Sx,Vy)].flat();return r===void 0?null:{channels:[r,...i]}}function Ex(e,t,n){let r=$y([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>wx(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function Dx(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
|
|
136
136
|
`)}function Ox(e,t,n,r){if(t===null)return e;let i=kx(r),a=t.channels.flatMap(e=>Ax(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[jx(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
|
|
137
137
|
`);return e?`${l}\n${e}`:l}function kx(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function Ax(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=A(Math.max(2,t.width-1)),i=(e,t)=>new Ar(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>yx([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=>Vt(e,r)).map(e=>i(e,t))})],t).split(`
|
|
138
|
-
`))}function jx(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: ${cx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(cx(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,yx([m],r)}const Mx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Nx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Px(e,t){return r.readdirSync(t).filter(Mx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Px(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Nx(i,a)]]})}function Fx(e){let t=ee.createHash(`sha256`);for(let[n,r]of Px(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ix=e=>e.slice(0,7);function Lx(e){return c.dirname(c.dirname(e))}function Rx(){return{version:nb,digest:`2eab0750dab9c48d8aed6e20fb433bda5a1c73c9e556e3e5ab44a60879122b65`}}function zx(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 Bx(e,t){try{let n=Lx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Fx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:zx(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 Vx=/^-?\d+$/;function Hx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ux(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 Wx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Vx.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 Gx(e,t,n){return r=>r?Vx.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 Kx(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=>!Vx.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:Hx(r[0].seed,t,i)}}return{kind:`int`}}function qx(e){return e===`config`?`set-config`:`set-state`}function Jx(e,t,n){return t.kind===`int`?Wx(`menu page "${e}"`):t.kind===`range`?Gx(t.min,t.max,`${n} stepper "${e}"`):Ux(t.allowed,`${n} "${e}"`,qx(n))}function Yx(e,t,n){return Jx(e,Kx(e,t,n),n)}function Xx(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:Kx(e,n,t)}))}function Zx(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=Yx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Yx(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=Yx(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=Kx(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 Qx=Zx({},`config`);function $x(){return Qx.listKeys()}function eS(e,t){return Qx.validate(e,t)}function tS(e){return Qx.rangeParamsFor(e)}function nS(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:Hx(t.get(e.persist),e.min,e.max)}}]:[]}function rS(e){return ko(e.globals)}function iS(e){let t=new Set;for(let n of oS(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 aS(e){let t=rS(e),n=new Map([...j_(e),...wh(e)]);return[...iS(e),...oS(e).flatMap(e=>nS(e,t,n))]}function oS(e){return Object.values(e.actions).flatMap(Ag)}function sS(e){return Xx(aS(e),`config`)}function cS(e,t){return Qx.register(e,t)}const lS=li(),uS=new Set(lS),dS=new Set(pi),fS=e=>e?uS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pS=e=>e?dS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},mS=new Set([`1`,`true`]),hS=new Set([`0`,`false`]),gS=Zx({style:pS,theme:fS,"toolbar-expanded":e=>mS.has(e)?{ok:!0,value:`1`}:hS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function _S(){return gS.listKeys()}function vS(e,t){return gS.register(e,t)}function yS(e,t){return gS.validate(e,t)}function bS(e){return gS.rangeParamsFor(e)}function xS(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:Hx(t.get(e.set),e.min,e.max)}}]:[]}function SS(e){let t=new Set(gS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function CS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function wS(e){let t=CS(e),n=j_(e);return SS(Object.values(e.actions).flatMap(Ag).flatMap(e=>xS(e,t,n)))}function TS(e){return Xx(wS(e))}const ES=`update.dismissed`,DS=`updateNotice`;function OS(e){return e.kind===`source`?e.newer.digest:sb(e.newer)}const kS=e=>`${e.version} [${Ix(e.digest)}]`;function AS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kS(e.newer),running:kS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:sb(e.newer),running:sb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${lb}@${sb(e.newer)}`,`install`]}}}}const jS={kind:`idle`},MS={kind:`running`};function NS(e,t,n){if(e===null)return[];let r=OS(e);if(!n.enabled||n.dismissed===r)return[];let i=AS(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(`
|
|
138
|
+
`))}function jx(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: ${cx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(cx(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,yx([m],r)}const Mx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Nx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Px(e,t){return r.readdirSync(t).filter(Mx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Px(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Nx(i,a)]]})}function Fx(e){let t=ee.createHash(`sha256`);for(let[n,r]of Px(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Ix=e=>e.slice(0,7);function Lx(e){return c.dirname(c.dirname(e))}function Rx(){return{version:nb,digest:`70b902a762bb064d6d46d39703380dceb22a10e7c8aa74bef077490bc8c0b016`}}function zx(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 Bx(e,t){try{let n=Lx(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Fx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:zx(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 Vx=/^-?\d+$/;function Hx(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Ux(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 Wx(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Vx.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 Gx(e,t,n){return r=>r?Vx.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 Kx(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=>!Vx.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:Hx(r[0].seed,t,i)}}return{kind:`int`}}function qx(e){return e===`config`?`set-config`:`set-state`}function Jx(e,t,n){return t.kind===`int`?Wx(`menu page "${e}"`):t.kind===`range`?Gx(t.min,t.max,`${n} stepper "${e}"`):Ux(t.allowed,`${n} "${e}"`,qx(n))}function Yx(e,t,n){return Jx(e,Kx(e,t,n),n)}function Xx(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:Kx(e,n,t)}))}function Zx(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=Yx(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:Yx(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=Yx(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=Kx(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 Qx=Zx({},`config`);function $x(){return Qx.listKeys()}function eS(e,t){return Qx.validate(e,t)}function tS(e){return Qx.rangeParamsFor(e)}function nS(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:Hx(t.get(e.persist),e.min,e.max)}}]:[]}function rS(e){return ko(e.globals)}function iS(e){let t=new Set;for(let n of oS(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 aS(e){let t=rS(e),n=new Map([...j_(e),...wh(e)]);return[...iS(e),...oS(e).flatMap(e=>nS(e,t,n))]}function oS(e){return Object.values(e.actions).flatMap(Ag)}function sS(e){return Xx(aS(e),`config`)}function cS(e,t){return Qx.register(e,t)}const lS=li(),uS=new Set(lS),dS=new Set(pi),fS=e=>e?uS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pS=e=>e?dS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${pi.join(`, `)})`}:{ok:!1,reason:`style name is required`},mS=new Set([`1`,`true`]),hS=new Set([`0`,`false`]),gS=Zx({style:pS,theme:fS,"toolbar-expanded":e=>mS.has(e)?{ok:!0,value:`1`}:hS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function _S(){return gS.listKeys()}function vS(e,t){return gS.register(e,t)}function yS(e,t){return gS.validate(e,t)}function bS(e){return gS.rangeParamsFor(e)}function xS(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:Hx(t.get(e.set),e.min,e.max)}}]:[]}function SS(e){let t=new Set(gS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function CS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of ko(e.globals))t.set(n,r);return t}function wS(e){let t=CS(e),n=j_(e);return SS(Object.values(e.actions).flatMap(Ag).flatMap(e=>xS(e,t,n)))}function TS(e){return Xx(wS(e))}const ES=`update.dismissed`,DS=`updateNotice`;function OS(e){return e.kind===`source`?e.newer.digest:sb(e.newer)}const kS=e=>`${e.version} [${Ix(e.digest)}]`;function AS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kS(e.newer),running:kS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:sb(e.newer),running:sb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${lb}@${sb(e.newer)}`,`install`]}}}}const jS={kind:`idle`},MS={kind:`running`};function NS(e,t,n){if(e===null)return[];let r=OS(e);if(!n.enabled||n.dismissed===r)return[];let i=AS(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(`
|
|
139
139
|
`),c=$y([{verb:Vy,args:[s]}]),l=t.kind===`running`?wx(`[${i.busy}]`,c):wx(`[${i.act}]`,$y([{verb:Jy,args:[n.sessionId]}]));return[{severity:Cx,message:s,lines:[[wx(a,c),l,wx(`[dismiss]`,$y([{verb:Fy,args:[n.sessionId,ES,r]}])),wx(`[disable]`,$y([{verb:Hy,args:[n.sessionId,DS,`false`]}]))],...o.map(e=>[wx(e,c)])]}]}function PS(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 FS(e){switch(e.kind){case`current`:return[`info`,`build: current ${kS(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${kS(e.source)}, running ${kS(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function IS(e){switch(e.kind){case`current`:return[`info`,`release: current ${sb(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${sb(e.latest)}, running ${sb(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${sb(e.installed)}, latest ${sb(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function LS(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const RS=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function zS(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=RS(e.stderr)??e.error??RS(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function BS(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=jS,d=null,f=LS(s),p=LS(s),m=()=>PS(c,l);function h(){let e=m(),t=e===null?null:OS(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:vS(ES,{kind:`allow-list`,allowed:[t]})})}function g(){c=Bx(t,Rx),f(FS(c)),h()}async function _(){l=db(nb,await ub(lb,a,i)),p(IS(l)),h()}return{arm(){cS(DS,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>NS(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=AS(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=MS,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Ee({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=jS,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=zS(n);u={kind:`failed`,identity:OS(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function VS(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??HS(t.stderr)].filter(Boolean).join(`, `)}`)}function HS(e){return e.trim().split(`
|
|
140
140
|
`,1)[0]??``}function US(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Z:X(n)}function WS(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?X(t):Z}const GS=/^[A-Za-z]:[\\/]/;function KS(e){let t=e.trim();if(GS.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 qS(e){return KS(e)?.host||null}function JS(e){let t=qS(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function YS(e){let t=new Map;for(let n of e.split(`
|
|
141
141
|
`)){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 XS(e){return e.urls.find(e=>tC(e)!==null)??e.urls[0]??null}function ZS(e){return e.find(e=>e.name===`origin`)??e[0]??null}function QS(e){let t=ZS(e);return t?XS(t):null}function $S(e){let t=ZS(e);return t?t.urls.find(e=>JS(e)!==null)??XS(t):null}function eC(e){let t=(KS(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function tC(e){let t=KS(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 nC(e){let t=QS(e);return t===null?null:tC(t)}function rC(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??HS(t.stderr)].filter(Boolean).join(`, `)}`)}function iC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aC(e){let t=`detached`,n=Z,r=Z,i=Z,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
@@ -175,30 +175,31 @@ The target is already observable of different type.
|
|
|
175
175
|
Extending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);var r=t?.name??(x(e)?`ObservableObject`:e.constructor.name)+`@`+h();return ee(e,D,new Yi(e,new Map,String(r),Lt(t))),e}var Zi=ne(`ObservableObjectAdministration`,Yi);function Qi(e){return qi[e]||(qi[e]={get:function(){return this[D].getObservablePropValue_(e)},set:function(t){return this[D].setObservablePropValue_(e,t)}})}function $i(e){return b(e)?Zi(e[D]):!1}function ea(e,t,n){var r;e.appliedAnnotations_[n]=t,(r=e.target_[Ee])==null||delete r[n]}function ta(e,t,r){if(Sa(t)||n(`Cannot annotate '`+e.name_+`.`+r.toString()+`': Invalid annotation.`),!qe(t)&&ce(e.appliedAnnotations_,r)){var i=e.name_+`.`+r.toString(),a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '`+o+`' to '`+i+`':`+(`
|
|
176
176
|
The field is already annotated with '`+a+`'.`)+`
|
|
177
177
|
Re-annotating fields is not allowed.
|
|
178
|
-
Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),ia=0,aa=function(){};function oa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}oa(aa,Array.prototype);var sa=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ma(function(){var e=new Oi(r,n,i,!0);e.proxy_=a,te(a,D,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[D].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fi(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return ba({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},he(t,[{key:`length`,get:function(){return this[D].getArrayLength_()},set:function(e){this[D].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(aa);Object.entries(Ai).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&ee(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[D].get_(e)},set:function(t){this[D].set_(e,t)}}}function la(e){s(sa.prototype,``+e,ca(e))}function ua(e){if(e>ia){for(var t=ia;t<e+100;t++)la(t);ia=e}}ua(1e3);function da(e,t,n){return new sa(e,t,n)}function G(e,t){if(typeof e==`object`&&e){if(Fi(e))return t!==void 0&&n(23),e[D].atom_;if(Gi(e))return e.atom_;if(Bi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,pa(e)),r}if($i(e)){if(!t)return n(26);var i=e[D].values_.get(t);return i||n(27,t,pa(e)),i}if(Pe(e)||tn(e)||z(e))return e}else if(v(e)&&z(e[D]))return e[D];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Pe(e)||tn(e)||z(e)||Bi(e)||Gi(e))return e;if(e[D])return e[D];n(24,e)}function pa(e,t){var n;if(t!==void 0)n=G(e,t);else if(sr(e))return e.name;else n=$i(e)||Bi(e)||Gi(e)?fa(e):G(e);return n.name_}function ma(e){var t=F(),n=Xt(!0);An();try{return e()}finally{jn(),Zt(n),hn(t)}}var ha=c.toString;function ga(e,t,n){return n===void 0&&(n=-1),_a(e,t,n)}function _a(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=ha.call(e);if(o!==ha.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=va(e),t=va(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!_a(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(ce(t,m)&&_a(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function va(e){return Fi(e)?e.slice():re(e)||Bi(e)||C(e)||Gi(e)?Array.from(e.entries()):e}var ya=i().Iterator?.prototype||{};function ba(e){return e[Symbol.iterator]=xa,Object.assign(Object.create(ya),e)}function xa(){return this}function Sa(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:pa},$mobx:D}),e.$mobx=D,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=Ln,e._allowStateChanges=M,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=_n,e._allowStateReadsStart=gn,e._autoAction=ar,e._endAction=Yt,e._getAdministration=fa,e._getGlobalState=wn,e._interceptReads=Fr,e._isComputingDerivation=sn,e._resetGlobalState=Tn,e._startAction=j,e.action=ir,e.autorun=cr,e.comparer=Be,e.computed=Ht,e.configure=br,e.createAtom=Fe,e.defineProperty=Qr,e.entries=qr,e.extendObservable=U,e.flow=jr,e.flowResult=Nr,e.get=Zr,e.getAtom=G,e.getDebugName=pa,e.getDependencyTree=xr,e.getObserverTree=Cr,e.has=Xr,e.intercept=Ir,e.isAction=sr,e.isBoxedObservable=en,e.isComputed=Br,e.isComputedProp=Vr,e.isFlow=Pr,e.isFlowCancellationError=Or,e.isObservable=Ur,e.isObservableArray=Fi,e.isObservableMap=Bi,e.isObservableObject=$i,e.isObservableProp=Wr,e.isObservableSet=Gi,e.keys=Gr,e.makeAutoObservable=Ci,e.makeObservable=xi,e.observable=A,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Rn,e.override=Ke,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=Jn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=mn,e.values=Kr,e.when=li})),Mw=me(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Aw():t.exports=jw()}))();function Nw(e){if(Array.isArray(e))return Object.freeze(e.map(Nw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Nw(r);return Object.freeze(t)}return e}function Pw(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function Fw(e){return typeof e==`string`?e:String(e)}function Iw(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function Lw(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}function Rw(e,t){if(!(e instanceof Ar))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function zw(e){return{fn:(t=>Rw(t,e)),argTypes:[`liftable`],returnType:`T`}}function Bw(e){return{fn:((t,n)=>Rw(n,new H({[e]:N.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Vw(e,t){return new H({[e]:t})}function Hw(){let e={};for(let t of lr)e[t]=zw(Vw(t,!0)),e[`not_${t}`]=zw(Vw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=zw(Vw(n,!0));return e}const Uw={fn:((e,t)=>Rw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ww={fn:((e,t)=>Rw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Gw(){return{fg:Bw(`color`),bg:Bw(`bgcolor`),...Hw(),link:Ww,style:Uw}}function Kw(e,t){if(!Dn.test(e.trim()))throw TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`);return On(e)}function qw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Jw(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const Yw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`darken`),Jw(t,`darken`,`levels`)).hex)),Xw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`lighten`),-Jw(t,`lighten`,`levels`)).hex)),Zw={min:0,max:100,note:`0 = from, 100 = toward`},Qw=qw([`string`,`string`,`float`],((e,t,n)=>cn(Kw(e,`mix`),Kw(t,`mix`),Jw(n,`mix`,`percentage`,Zw)/100).hex)),$w={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},eT=qw([`string`],(e=>In(Kw(e,`contrastOn`)).hex)),tT=qw([`string`,`string`,`float`],((e,t,n)=>zn(Kw(e,`readableOn`),Kw(t,`readableOn`),Jw(n,`readableOn`,`ratio`,$w)).hex)),nT={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function rT(){let e={};for(let[t,n]of Object.entries(nT)){let r=t;e[n]=qw([`string`,`float`],((e,t)=>{let i={...gn,[r]:Jw(t,n,`amount`)};return L.fromRgba(Kw(e,n)).applyKey(i).toRgba().hex}))}return e}function iT(){return{darken:Yw,lighten:Xw,mix:Qw,contrastOn:eT,readableOn:tT,...rT()}}function aT(e,t){if(e.length===0)throw RangeError(`ramp needs at least one stop after the easing: ramp <value> <easing> <position> <color> …`);if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:kn(t,e[r+1])});return n}function oT(e){return{color:{fn:(t=>kn(e(),t).hex),argTypes:[`string`],returnType:`string`},ramp:{fn:((...t)=>{if(t.length<2)throw RangeError(`ramp needs a value and an easing before its stops (got ${t.length}): ramp <value> "linear"|"step" <position> <color> …`);let[n,r,...i]=t;return new ar(ir(r),aT(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function sT(){return{...Gw(),...iT()}}new H({color:`red`,dim:!0});const cT=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,lT=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function uT(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(cT);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(lT);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function dT(e){let t=e.match(lT);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function fT(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function pT(e){return e.toLocaleString()}const mT=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hT=mT.length;function gT(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(hT-1));o+=mT[t]}return o}function _T(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}const vT=li(),yT=[...pi];function bT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>fT(e),argTypes:[`string`]},int:{fn:e=>Iw(e),argTypes:[`value`]},string:{fn:e=>Fw(e),argTypes:[`value`]},bool:{fn:e=>Lw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>vT,argTypes:[]},styles:{fn:()=>yT,argTypes:[]},sparkline:{fn:(e,t)=>gT(_T(e),t),argTypes:[`string`,`int`]}}}function xT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>pT(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>uT(e),argTypes:[`string`]},shortenModelName:{fn:e=>dT(e),argTypes:[`string`]}}}function ST(e,t=()=>new Date){return Eu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...mf(),...wm(),...ep(),...Sp(),...of(t),...Yu(),...Of(),...sT(),...bT(),...xT(t),...e??{}}})}function CT(e){return wT(e,new Set(e.names()),``)}function wT(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?TT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return wT(e,t,a)}})}function TT(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const ET=/\r\n|\r|\n/g,DT=e=>X(e.replace(ET,` `).trim());function OT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(ET,` `))}}const kT=e=>{try{return X(JSON.parse(e))}catch(e){return Q(`JSON parse failed: ${e.message}`)}};function AT(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function jT(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}function MT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Ee({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?X(n.stdout):Q(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function NT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return X(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return Q(`file unreadable: ${e}`)}}}}function PT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?Q(`${r.reason} in ${n}`):r}const FT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],IT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],LT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],RT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function zT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>FT[e.getMonth()]],[`Monday`,e=>LT[e.getDay()]],[`Jan`,e=>IT[e.getMonth()]],[`Mon`,e=>RT[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const BT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function VT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=BT[t];try{return GT(r,e)}catch{return KT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ib(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ib(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ib(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ib(e.stashCount,0)}}var HT=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},UT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:se(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(oe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())oe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GT(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Fw(e):t===`number`?Iw(e):Lw(e)}function KT(e){return e===`number`?0:e===`boolean`?!1:``}var qT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new HT;ttlMgr=new UT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fC;abort=new AbortController;engine=ST();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pw(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,MT(t,this.abort.signal),AT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,NT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,DT,t.default,n);case`regex`:return this.scalarPublisher(e,OT(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=PT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ib(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=PT(i,kT,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=CT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return zT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,zT(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=BT[t.field],r=t.varDefault===void 0?KT(n):GT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,VT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GT(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mw.reaction)(()=>{let t=CT(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Mw.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KT(t))}}defaultFor(e){try{return GT(this.defaultEmptyValue,e)}catch{return KT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const JT=new Map,YT=new Map;function XT(e){let t=ai(e),n=JT.get(t);if(n!==void 0)return n;let r=Kn(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return JT.set(t,r),r}function ZT(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=YT.get(n);if(r!==void 0)return r;let i=tr(e,t);return YT.set(n,i),i}function QT(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=$T(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=$T([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function $T(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>eE(e,t)):e,r=Ar.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function eE(e,t){let n=e.copy();return n.style=t.add(e.style),n}function tE(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function nE(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function rE(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=nE(e,o).pad(s);return n===`auto`||(c.cellLength>n?c.truncate(n,{mode:i,marker:a}):c.cellLength<n&&c.align(r,n)),[c]}var iE=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function aE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=oE(o,c),d=u===void 0?i:sE(n,u,`bg`);l.bg=d;let f=oE(s,c),p=f===void 0?a(d):sE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function oE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function sE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new iE(t,n,e.message):e}}const cE=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function lE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,uE(e,a,o,n,r));return i}function uE(e,t,n,r,i){if(kg(n)){let[a,o]=Ag(n);return dE(r.get(n.persistWhen)??n.persistWhen,n.set,uE(e,t,a,r,i),uE(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...N_(n.from,i)]}:`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=cE.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...N_(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...N_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:pE(e,n.copy,t)}:`open`in n?{kind:`open`,target:pE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function dE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function fE(e,t){return e.kind===`dual`?Si(mE(t,e.selector))===!0?e.durable:e.session:e}function pE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function mE(e,t){return e.has(t)?Fw(e.read(t)):``}function hE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function gE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function _E(e,t){return Math.max(e.members.indexOf(mE(t,e.stateVar)),0)}function vE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=mE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=mE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=mE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(_E(e,r)+1)%e.members.length];return{effects:[{verb:Fy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Iy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ly,args:[hE(e.text,CT(r))]}],active:!1};case`open`:return{effects:[{verb:Ry,args:[hE(e.target,CT(r))]}],active:!1};case`persist-literal`:{let t=mE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=mE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(_E(e,r)+1)%e.members.length];return{effects:[{verb:Hy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Uy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Wy,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ky,args:[i]}],active:!1};case`redo`:return{effects:[{verb:qy,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Yy,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Xy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Gy,args:[i,e.key,Qm(e.op)]}],active:!1};case`dual`:{let a=fE(e,r),{effects:o,active:s}=vE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Gy,args:[i,e.key,Qm(r)]}],active:!1}}}}function yE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:cc(`action "${e}"`,n,t.members.length,_E(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]}}function bE(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=yE(e,fE(r,i),t,i),{effects:s,active:c}=vE(r,a,o,i,mE(i,`session.id`));return gE(a,$y(s),c)}function xE(e){return{action:{fn:(t,...n)=>bE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function SE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(Js(e,t))})}function CE(e,t){return SE(e.palette,ec(e.palette,e.disclosure,[t]))}function wE(){return{current:null}}function TE(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function EE(e){return new Ar(e).cellLength}function DE(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function OE(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function kE(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function AE(e,t){let n=e.compiled.get(t),r=n&&fE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function jE(e,t,n,r,i,a,o){let s=AE(a,e),c=a.compiled.get(e),l=a.store,u=mE(l,`session.id`),d=`stateVar`in s?mE(l,s.stateVar):void 0,f=s.options.map(EE),p=i?Math.max(1,Iw(l.read(`term.cols`))-vx(a.stripStyle)-2*a.padding):1/0,m=EE(`✕`)+1,h=EE(`←`)+1+EE(`→`)+1,g=DE(f,p,m),_=g.length>1?DE(f,p,m+h):g,v=parseInt(mE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>$y([{verb:Fy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),ee=$y([{verb:Fy,args:[u,...S]}]),te=r?[{verb:Fy,args:[u,...S]}]:[],ne=e=>{let{effects:t}=vE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?$y([{verb:Fy,args:[...n.args,...r?S:[]]}]):$y([...t,...te])},re=[gE(`✕`,ee,!1)];y>0&&re.push(gE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];re.push(gE(t,ne(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&re.push(gE(`→`,x(y+1),!1)),OE(re,i)}function ME(e,t){return{picker:{fn:(n,r,i,a)=>{let o=kE(e,r,`set-int`,`an int action ({ set, int: true })`);return jE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>CE(TE(t,`{{ picker }}`),{...e,distribution:Rs(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const NE=Symbol(`cc-candybar.menuDrop`);function PE(e){return e.flatMap(e=>e[NE]??[])}function FE(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Em(i.segName,e,n.key),s=km(o),c=Tm(e),l=mE(a.store,o)===c,u=mE(a.store,`session.id`),d=l?oc:c,f=gE(cc(`{{ menu "${e}" }}`,t,2,+!!l),$y([{verb:Fy,args:[u,o,d,s,`0`]}]),!1);return f[NE]=l?[jE(e,{key:s,stateVar:s},[[o,oc],[s,`0`]],n.closeOnPick,n.paged,a,e=>CE(i,{...e,distribution:n.distribution}))]:[],f}const IE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function LE(e,t){let n=t[t.length-1],r=IE(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:Nm(r??{})}}function RE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=LE(t,n);return FE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function zE(e){let t={fn:(()=>{let t=TE(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`};return{...oT(()=>TE(e,`{{ color }} / {{ ramp }}`).palette),bgOf:t}}function BE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
178
|
+
Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),ia=0,aa=function(){};function oa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}oa(aa,Array.prototype);var sa=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ma(function(){var e=new Oi(r,n,i,!0);e.proxy_=a,te(a,D,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[D].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fi(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return ba({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},he(t,[{key:`length`,get:function(){return this[D].getArrayLength_()},set:function(e){this[D].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(aa);Object.entries(Ai).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&ee(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[D].get_(e)},set:function(t){this[D].set_(e,t)}}}function la(e){s(sa.prototype,``+e,ca(e))}function ua(e){if(e>ia){for(var t=ia;t<e+100;t++)la(t);ia=e}}ua(1e3);function da(e,t,n){return new sa(e,t,n)}function G(e,t){if(typeof e==`object`&&e){if(Fi(e))return t!==void 0&&n(23),e[D].atom_;if(Gi(e))return e.atom_;if(Bi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,pa(e)),r}if($i(e)){if(!t)return n(26);var i=e[D].values_.get(t);return i||n(27,t,pa(e)),i}if(Pe(e)||tn(e)||z(e))return e}else if(v(e)&&z(e[D]))return e[D];n(28)}function fa(e,t){if(e||n(29),t!==void 0)return fa(G(e,t));if(Pe(e)||tn(e)||z(e)||Bi(e)||Gi(e))return e;if(e[D])return e[D];n(24,e)}function pa(e,t){var n;if(t!==void 0)n=G(e,t);else if(sr(e))return e.name;else n=$i(e)||Bi(e)||Gi(e)?fa(e):G(e);return n.name_}function ma(e){var t=F(),n=Xt(!0);An();try{return e()}finally{jn(),Zt(n),hn(t)}}var ha=c.toString;function ga(e,t,n){return n===void 0&&(n=-1),_a(e,t,n)}function _a(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=ha.call(e);if(o!==ha.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=va(e),t=va(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!_a(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(ce(t,m)&&_a(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function va(e){return Fi(e)?e.slice():re(e)||Bi(e)||C(e)||Gi(e)?Array.from(e.entries()):e}var ya=i().Iterator?.prototype||{};function ba(e){return e[Symbol.iterator]=xa,Object.assign(Object.create(ya),e)}function xa(){return this}function Sa(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:pa},$mobx:D}),e.$mobx=D,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=Ln,e._allowStateChanges=M,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=_n,e._allowStateReadsStart=gn,e._autoAction=ar,e._endAction=Yt,e._getAdministration=fa,e._getGlobalState=wn,e._interceptReads=Fr,e._isComputingDerivation=sn,e._resetGlobalState=Tn,e._startAction=j,e.action=ir,e.autorun=cr,e.comparer=Be,e.computed=Ht,e.configure=br,e.createAtom=Fe,e.defineProperty=Qr,e.entries=qr,e.extendObservable=U,e.flow=jr,e.flowResult=Nr,e.get=Zr,e.getAtom=G,e.getDebugName=pa,e.getDependencyTree=xr,e.getObserverTree=Cr,e.has=Xr,e.intercept=Ir,e.isAction=sr,e.isBoxedObservable=en,e.isComputed=Br,e.isComputedProp=Vr,e.isFlow=Pr,e.isFlowCancellationError=Or,e.isObservable=Ur,e.isObservableArray=Fi,e.isObservableMap=Bi,e.isObservableObject=$i,e.isObservableProp=Wr,e.isObservableSet=Gi,e.keys=Gr,e.makeAutoObservable=Ci,e.makeObservable=xi,e.observable=A,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Rn,e.override=Ke,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=Jn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=mn,e.values=Kr,e.when=li})),Mw=me(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Aw():t.exports=jw()}))();function Nw(e){if(Array.isArray(e))return Object.freeze(e.map(Nw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Nw(r);return Object.freeze(t)}return e}function Pw(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function Fw(e){return typeof e==`string`?e:String(e)}function Iw(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function Lw(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}function Rw(e,t){if(!(e instanceof Ar))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function zw(e){return{fn:(t=>Rw(t,e)),argTypes:[`liftable`],returnType:`T`}}function Bw(e){return{fn:((t,n)=>Rw(n,new H({[e]:N.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function Vw(e,t){return new H({[e]:t})}function Hw(){let e={};for(let t of lr)e[t]=zw(Vw(t,!0)),e[`not_${t}`]=zw(Vw(t,!1));for(let[t,n]of Object.entries(dr))e[t]=zw(Vw(n,!0));return e}const Uw={fn:((e,t)=>Rw(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Ww={fn:((e,t)=>Rw(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Gw(){return{fg:Bw(`color`),bg:Bw(`bgcolor`),...Hw(),link:Ww,style:Uw}}function Kw(e,t){if(!Dn.test(e.trim()))throw TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`);return On(e)}function qw(e,t){return{fn:t,argTypes:e,returnType:`string`}}function Jw(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const Yw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`darken`),Jw(t,`darken`,`levels`)).hex)),Xw=qw([`string`,`int`],((e,t)=>Fn(Kw(e,`lighten`),-Jw(t,`lighten`,`levels`)).hex)),Zw={min:0,max:100,note:`0 = from, 100 = toward`},Qw=qw([`string`,`string`,`float`],((e,t,n)=>cn(Kw(e,`mix`),Kw(t,`mix`),Jw(n,`mix`,`percentage`,Zw)/100).hex)),$w={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},eT=qw([`string`],(e=>In(Kw(e,`contrastOn`)).hex)),tT=qw([`string`,`string`,`float`],((e,t,n)=>zn(Kw(e,`readableOn`),Kw(t,`readableOn`),Jw(n,`readableOn`,`ratio`,$w)).hex)),nT={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function rT(){let e={};for(let[t,n]of Object.entries(nT)){let r=t;e[n]=qw([`string`,`float`],((e,t)=>{let i={...gn,[r]:Jw(t,n,`amount`)};return L.fromRgba(Kw(e,n)).applyKey(i).toRgba().hex}))}return e}function iT(){return{darken:Yw,lighten:Xw,mix:Qw,contrastOn:eT,readableOn:tT,...rT()}}function aT(e,t){if(e.length===0)throw RangeError(`ramp needs at least one stop after the easing: ramp <value> <easing> <position> <color> …`);if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:kn(t,e[r+1])});return n}function oT(e){return{color:{fn:(t=>kn(e(),t).hex),argTypes:[`string`],returnType:`string`},ramp:{fn:((...t)=>{if(t.length<2)throw RangeError(`ramp needs a value and an easing before its stops (got ${t.length}): ramp <value> "linear"|"step" <position> <color> …`);let[n,r,...i]=t;return new ar(ir(r),aT(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function sT(){return{...Gw(),...iT()}}new H({color:`red`,dim:!0});const cT=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,lT=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function uT(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(cT);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(lT);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function dT(e){let t=e.match(lT);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function fT(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function pT(e){return e.toLocaleString()}const mT=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hT=mT.length;function gT(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(hT-1));o+=mT[t]}return o}function _T(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}const vT=li(),yT=[...pi];function bT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>fT(e),argTypes:[`string`]},int:{fn:e=>Iw(e),argTypes:[`value`]},string:{fn:e=>Fw(e),argTypes:[`value`]},bool:{fn:e=>Lw(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>vT,argTypes:[]},styles:{fn:()=>yT,argTypes:[]},sparkline:{fn:(e,t)=>gT(_T(e),t),argTypes:[`string`,`int`]}}}function xT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>pT(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>uT(e),argTypes:[`string`]},shortenModelName:{fn:e=>dT(e),argTypes:[`string`]}}}function ST(e,t=()=>new Date){return Eu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...mf(),...wm(),...ep(),...Sp(),...of(t),...Yu(),...Of(),...sT(),...bT(),...xT(t),...e??{}}})}function CT(e){return wT(e,new Set(e.names()),``)}function wT(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?TT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return wT(e,t,a)}})}function TT(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const ET=/\r\n|\r|\n/g,DT=e=>X(e.replace(ET,` `).trim());function OT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(ET,` `))}}const kT=e=>{try{return X(JSON.parse(e))}catch(e){return Q(`JSON parse failed: ${e.message}`)}};function AT(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function jT(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}function MT(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Ee({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?X(n.stdout):Q(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function NT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await C(e,{encoding:`utf8`,signal:n});return X(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return Q(`file unreadable: ${e}`)}}}}function PT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?Q(`${r.reason} in ${n}`):r}const FT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],IT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],LT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],RT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function zT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>FT[e.getMonth()]],[`Monday`,e=>LT[e.getDay()]],[`Jan`,e=>IT[e.getMonth()]],[`Mon`,e=>RT[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const BT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function VT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=BT[t];try{return GT(r,e)}catch{return KT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ib(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ib(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ib(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ib(e.stashCount,0)}}var HT=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},UT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:se(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(oe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())oe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GT(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Fw(e):t===`number`?Iw(e):Lw(e)}function KT(e){return e===`number`?0:e===`boolean`?!1:``}var qT=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new HT;ttlMgr=new UT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fC;abort=new AbortController;engine=ST();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pw(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,MT(t,this.abort.signal),AT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,NT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,DT,t.default,n);case`regex`:return this.scalarPublisher(e,OT(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=PT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ib(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=PT(i,kT,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=CT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return zT(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,zT(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=BT[t.field],r=t.varDefault===void 0?KT(n):GT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,VT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GT(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mw.reaction)(()=>{let t=CT(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Mw.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KT(t))}}defaultFor(e){try{return GT(this.defaultEmptyValue,e)}catch{return KT(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function JT(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function YT(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function XT(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}const ZT=Symbol(`cc-candybar.fillDemand`);function QT(e,t){return e[ZT]=t,e}function $T(e){return e[ZT]}function eE(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=YT(e,o).pad(s);if(n===`auto`)return[c];let l={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[QT(c,l)]:(XT(c,n,l),[c])}const tE=/\x1b\[[0-9;]*m|\x1b\]8;;[^\x07\x1b]*(?:\x1b\\|\x07)/g;function nE(e){return k(e.replace(tE,``))}function rE(e,t){let n=[];for(let t of e){let e=$T(t);e!==void 0&&n.push({cell:t,how:e})}if(n.length===0||!Number.isFinite(t.width))return e;let r=yx(e,t).split(`
|
|
179
|
+
`);if(r.length>1)return e;let i=Math.max(0,t.width-nE(r[0]??``)),a=Math.floor(i/n.length),o=i-a*n.length;return n.forEach(({cell:e,how:t},r)=>{let i=a+(r===n.length-1?o:0);XT(e,e.cellLength+i,t)}),e}const iE=new Map,aE=new Map;function oE(e){let t=ai(e),n=iE.get(t);if(n!==void 0)return n;let r=Kn(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return iE.set(t,r),r}function sE(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=aE.get(n);if(r!==void 0)return r;let i=tr(e,t);return aE.set(n,i),i}function cE(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=lE(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=lE([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function lE(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>uE(e,t)):e,r=Ar.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function uE(e,t){let n=e.copy();return n.style=t.add(e.style),n}var dE=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function fE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=pE(o,c),d=u===void 0?i:mE(n,u,`bg`);l.bg=d;let f=pE(s,c),p=f===void 0?a(d):mE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function pE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function mE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new dE(t,n,e.message):e}}const hE=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function gE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,_E(e,a,o,n,r));return i}function _E(e,t,n,r,i){if(kg(n)){let[a,o]=Ag(n);return vE(r.get(n.persistWhen)??n.persistWhen,n.set,_E(e,t,a,r,i),_E(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...N_(n.from,i)]}:`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=hE.get(n.persist)??n.persist;return`to`in n?{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e}:`from`in n?{kind:`persist-option`,key:n.persist,stateVar:e,options:[...N_(n.from,i)]}:`cycle`in n?{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle}:`removeSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}}:`insertSegment`in n?{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}}:`insertSegmentFrom`in n?{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...N_(n.insertSegmentFrom,i)]}:{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:bE(e,n.copy,t)}:`open`in n?{kind:`open`,target:bE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function vE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function yE(e,t){return e.kind===`dual`?Si(xE(t,e.selector))===!0?e.durable:e.session:e}function bE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function xE(e,t){return e.has(t)?Fw(e.read(t)):``}function SE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function CE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function wE(e,t){return Math.max(e.members.indexOf(xE(t,e.stateVar)),0)}function TE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Fy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(wE(e,r)+1)%e.members.length];return{effects:[{verb:Fy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Iy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ly,args:[SE(e.text,CT(r))]}],active:!1};case`open`:return{effects:[{verb:Ry,args:[SE(e.target,CT(r))]}],active:!1};case`persist-literal`:{let t=xE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=xE(r,e.stateVar);return{effects:[{verb:Hy,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(wE(e,r)+1)%e.members.length];return{effects:[{verb:Hy,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Uy,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Wy,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ky,args:[i]}],active:!1};case`redo`:return{effects:[{verb:qy,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:Yy,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Xy,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:Gy,args:[i,e.key,Qm(e.op)]}],active:!1};case`dual`:{let a=yE(e,r),{effects:o,active:s}=TE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Gy,args:[i,e.key,Qm(r)]}],active:!1}}}}function EE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:cc(`action "${e}"`,n,t.members.length,wE(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]}}function DE(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=EE(e,yE(r,i),t,i),{effects:s,active:c}=TE(r,a,o,i,xE(i,`session.id`));return CE(a,$y(s),c)}function OE(e){return{action:{fn:(t,...n)=>DE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function kE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(Js(e,t))})}function AE(e,t){return kE(e.palette,ec(e.palette,e.disclosure,[t]))}function jE(){return{current:null}}function ME(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function NE(e){return new Ar(e).cellLength}function PE(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function FE(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function IE(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function LE(e,t){let n=e.compiled.get(t),r=n&&yE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function RE(e,t,n,r,i,a,o){let s=LE(a,e),c=a.compiled.get(e),l=a.store,u=xE(l,`session.id`),d=`stateVar`in s?xE(l,s.stateVar):void 0,f=s.options.map(NE),p=i?Math.max(1,Iw(l.read(`term.cols`))-vx(a.stripStyle)-2*a.padding):1/0,m=NE(`✕`)+1,h=NE(`←`)+1+NE(`→`)+1,g=PE(f,p,m),_=g.length>1?PE(f,p,m+h):g,v=parseInt(xE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>$y([{verb:Fy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),ee=$y([{verb:Fy,args:[u,...S]}]),te=r?[{verb:Fy,args:[u,...S]}]:[],ne=e=>{let{effects:t}=TE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?$y([{verb:Fy,args:[...n.args,...r?S:[]]}]):$y([...t,...te])},re=[CE(`✕`,ee,!1)];y>0&&re.push(CE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];re.push(CE(t,ne(t),t===d,o({index:e,count:s.options.length})))}return y<_.length-1&&re.push(CE(`→`,x(y+1),!1)),FE(re,i)}function zE(e,t){return{picker:{fn:(n,r,i,a)=>{let o=IE(e,r,`set-int`,`an int action ({ set, int: true })`);return RE(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,e=>AE(ME(t,`{{ picker }}`),{...e,distribution:Rs(void 0)}))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const BE=Symbol(`cc-candybar.menuDrop`);function VE(e){return e.flatMap(e=>e[BE]??[])}function HE(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Em(i.segName,e,n.key),s=km(o),c=Tm(e),l=xE(a.store,o)===c,u=xE(a.store,`session.id`),d=l?oc:c,f=CE(cc(`{{ menu "${e}" }}`,t,2,+!!l),$y([{verb:Fy,args:[u,o,d,s,`0`]}]),!1);return f[BE]=l?[RE(e,{key:s,stateVar:s},[[o,oc],[s,`0`]],n.closeOnPick,n.paged,a,e=>AE(i,{...e,distribution:n.distribution}))]:[],f}const UE=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function WE(e,t){let n=t[t.length-1],r=UE(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:Nm(r??{})}}function GE(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=WE(t,n);return HE(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function KE(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=qE(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new Ar(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=Ar.fromFragments(c);return l.end=``,l.noWrap=!0,l}function qE(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function JE(e){let t={fn:(()=>{let t=ME(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`},n=oT(()=>ME(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),r={fn:((e,t,r,i,a,o,...s)=>KE({value:e,max:t,width:r,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(n.ramp.fn(e,o,...YE(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...n,bgOf:t,gauge:r}}function YE(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function XE(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
179
180
|
`)){n.push(r);continue}let e=r.split(`
|
|
180
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function
|
|
181
|
-
`)}var
|
|
182
|
-
`)||null}var lD=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=iD(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:cD(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:cD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=gv(t,kw);n.push(...o);let s=yv(r,t??`<default>`,a),c=new rD,l=new qT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=JE(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of TS(s))d.push(vS(e,t));for(let{key:e,spec:t}of sS(s))d.push(cS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:fw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:aD(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=sD(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 uD=16384;var dD=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<uD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%uD}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:nb,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 fD={load:()=>({}),save:()=>{},flush:()=>{}};function pD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var mD=class{sessions;storage;atom=(0,Mw.createAtom)(`SessionState`);constructor(e=fD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=pD(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,Mw.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,Mw.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,Mw.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 hD=(e,t)=>E(t);function gD(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 _D=class{timer=null;pending=null;constructor(e,t=500,n=hD){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 gD(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 vD={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`},yD=new Set([`1`,`true`]),bD=new Set([`0`,`false`,``]);function xD(e,t){let n=KD(e),r=n.scope===`globals`?vD[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(yD.has(t))return`true`;if(bD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function SD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function CD(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function wD(e){return/^\s*$/.test(e)?null:ji(e)}function TD(e,t){return e!==null&&Ni(e,t)!==void 0}function ED(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(ED),...i}}return e}function DD(e){if(!ao(e))return ED(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,ED(t)])),...n}}const OD=Dw,kD=OD.segments,AD=OD.presets,jD=OD.root;function MD(e,t,n,r){if(!TD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function ND(e,t){let n=fh(t);return t.scope===`segment-palette`&&MD(e,[`segments`,t.segment],kD[t.segment],n.join(`.`)),n}function PD(e){return ji(zi(e))}function FD(){return Object.entries(jD.rows).map(([e,t])=>{let n=ED(t);return{path:[`root`],fragment:PD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function ID(e,t){let n=e===null?void 0:Ni(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function LD(e,t){if(t===void 0)return null;let n=DD(t);return{path:e,fragment:PD(n),unit:{path:e,value:n}}}function RD(e,t){let n=[`presets`,t],r=[...n,`root`],i=AD[t];MD(e,n,i,r.join(`.`));let a=ID(e,r)??LD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function zD(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 BD(e,t){return[...FD(),ID(e,[`root`]),RD(e,t)].filter(e=>e!==null).reduce(zD,new Map)}function VD(e,t,n){for(let{node:r,...i}of BD(e,t).values())if(sa(r,n))return i;throw new $(`${HD(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function HD(e,t){return RD(e,t)?.path??[`root`]}function UD(e,t){return t.scope===`preset-root`?HD(e,t.preset):fh(t)}function WD(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function GD(e){let t=dh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function KD(e){let t=GD(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function qD(e,t){let n=KD(t),r=wD(SD(e)??``),i=r===null?void 0:Ni(r,fh(n));return i!==void 0&&`value`in i?i.value:void 0}function JD(e,t,n,r){let i=KD(n),a=SD(t);iO(e,t,{before:a,after:$i(a??``,ND(wD(a??``),i),xD(n,r),Li)})}function YD(e,t,n){let r=GD(n),i=SD(t);if(i===null)return;let a=ea(i,UD(wD(i),r));a!==i&&iO(e,t,{before:i,after:a})}function XD(e,t,n,r){let i=GD(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=SD(t),o=r.op===`remove`?r.target:r.anchor,s=VD(wD(a??``),i.preset,o),c=WD(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`);iO(e,t,{before:a,after:l})}const ZD={past:[],future:[]};function QD(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function $D(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(QD)&&Array.isArray(t.future)&&t.future.every(QD)}function eO(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($D))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function tO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(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 nO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function rO(e,t,n,r,i){CD(t,n,e.logger);try{tO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function iO(e,t,n){let r=eO(e),{past:i}=r[t]??ZD;rO(e,t,n.after,{...r,[t]:{past:nO(i,n),future:[]}},`edit`)}function aO(e,t){let n=eO(e),{past:r,future:i}=n[t]??ZD,a=r[r.length-1];return a===void 0?null:(sO(t,a.after,`undo`),rO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:nO(i,a)}},`undo`),a)}function oO(e,t){let n=eO(e),{past:r,future:i}=n[t]??ZD,a=i[i.length-1];return a===void 0?null:(sO(t,a.before,`redo`),rO(e,t,a.after,{...n,[t]:{past:nO(r,a),future:i.slice(0,-1)}},`redo`),a)}function sO(e,t,n){if(SD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function cO(e){let t=De({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 lO(){return{probeTmux:cO,claudeSettingsPath:rb()}}function uO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function dO(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 fO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function pO(e){try{return dO(uO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function mO(e,t){return{tmux:fO(e,t),claudeSettingsEnv:pO(e)}}function hO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(uO(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:pO(e)}}default:return t.kind}}function gO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function _O(e){return vO(()=>decodeURIComponent(e))}function vO(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function yO(e,t){let n=De({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 bO=(e,t)=>yO(_O(e),t),xO=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,_O(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`})`)}},SO=(e,t)=>yO(_O(e),t),CO=(e,t)=>yO(_O(e),t),wO=(e,t)=>{let n=gO(_O(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},TO=(e,t)=>{let[n=``,...r]=vO(()=>Qy(e)),i=gO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${_S().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: ${_S().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=yS(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})`)},EO=/^-?\d+$/;function DO(e,t,n){return e>n?t:e<t?n:e}function OO(e,t){if(!e)return null;if(!_S().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${_S().join(`, `)})`);return e}function kO(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const AO=(e,t)=>{let[n=``,r=``,i=``]=vO(()=>Qy(e)),a=gO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!EO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=bS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${_S().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&EO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=DO(l+o,s.min,s.max),d=yS(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})`)},jO=`render-origin`;function MO(e){return JSON.stringify(e)}function NO(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 PO(e,t){let n=e.sessionState.get(t,jO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=NO(n);return fv(r.projectDir,r.cwd,r.configFile??void 0)}function FO(e){return{historyPath:Be(),logger:e.dlog}}const IO=(e,t)=>{let[n=``,r=``,i=``,a=``]=vO(()=>Qy(e)),o=gO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${$x().join(`, `)})`);let s=eS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=OO(a,`set-config`),l=PO(t,o);JD(FO(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),kO(c,o,t,`set-config`)},LO=(e,t)=>{let[n=``,r=``,i=``,a=``]=vO(()=>Qy(e)),o=gO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!EO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=OO(a,`step-config`),l=tS(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${$x().join(`, `)})`);let u=PO(t,o),d=qD(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=DO(f+s,l.min,l.max),m=eS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);JD(FO(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),kO(c,o,t,`step-config`)},RO=(e,t)=>{let[n=``,r=``]=vO(()=>Qy(e)),i=gO(n);if(!r||!$x().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${$x().join(`, `)})`);let a=PO(t,i);YD(FO(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},zO=(e,t)=>{let[n=``,r=``,i=``]=vO(()=>Qy(e)),a=gO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${$x().join(`, `)})`);let o=eS(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=PO(t,a);XD(FO(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},BO=(e,t)=>{let[n=``]=vO(()=>Qy(e)),r=gO(n),i=PO(t,r);if(aO(FO(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},VO=(e,t)=>{let[n=``]=vO(()=>Qy(e)),r=gO(n),i=PO(t,r);if(oO(FO(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},HO=(e,t)=>{gO(_O(e)),t.applyUpdate()},UO=`client-hints`;function WO(e,t){let n=e.sessionState.get(t,UO);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 GO(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 KO=(e,t)=>{let n=gO(_O(e));GO(t,n,mO(t.doctor,WO(t,n).tmux))},qO=(e,t)=>{let[n=``,r=``]=vO(()=>Qy(e)),i=gO(n),a=Lh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=mO(t.doctor,WO(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=hO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),GO(t,i,c)},JO=`config-override`,YO=new Map([[Ly,bO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=gO(vO(()=>decodeURIComponent(e.slice(0,n)))),i=vO(()=>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,JO),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,JO,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ry,xO],[Fy,TO],[Iy,AO],[Hy,IO],[Uy,LO],[Wy,RO],[Gy,zO],[Ky,BO],[qy,VO],[By,SO],[Vy,CO],[zy,wO],[Jy,HO],[Yy,KO],[Xy,qO]]),XO=new Set([Fy,Iy,Hy,Uy,Wy,Gy,Ky,qy,zy,Jy,Yy,Xy]),ZO=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of eb(e)){if(!i&&XO.has(a)){let e=Qy(o);e.length>0&&e[0]&&(i=e[0])}let e=YO.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(`
|
|
183
|
-
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},QO=new Map([...YO,[Py,ZO]]);Object.freeze([...QO.keys()]);const $O=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`]),ek=[[`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 tk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of ek){let i=rk(n,e);if(i==null)t.missingRequired.push(e);else{let n=nk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))$O.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function nk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function rk(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 ik(e,t){switch(e){case`vars`:return{what:e,vars:ak(t)};case`segments`:return{what:e,segments:uk(t)};case`config`:return{what:e,config:pk(t)}}}function ak(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=ck(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,...ok(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:sk(r.lastUpdatedMs())})}return o}function ok(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 sk(e){return e===null?null:Math.max(0,Date.now()-e)}function ck(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,lk(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}`,lk(i));return t}function lk(e){return e.kind}function uk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=dk(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:fk(t.template,i),lastRender:r.get(e)??null})}return o}function dk(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 fk(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 pk(e){return e===null?null:e.config}const mk=[`vars`,`segments`,`config`];function hk(e){return typeof e==`string`&&mk.includes(e)}function gk(e){return Math.max(1,e-2)}var _k=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 E(`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);E(`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{E(`Calculating context tokens from transcript: ${e}`);let n=await FC(e);if(n.length===0)return E(`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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`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 vk(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 yk=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(vk(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=CC(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 zC(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||(vk(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(E(`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 bk=new Map;function xk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var Sk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=xk(process.env.TMUX),t=bk.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({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 bk.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},Ck=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 wk=new dD;we(wk.launchStats);const Tk=new dC({counters:wk,logger:Y}),Ek=new yC({watchers:Tk,logger:Y}),Dk=new ZC,Ok=new mD,kk=new Ck(Ge()),Ak=new _k,jk=new yk,Mk=new Sk,Nk=new lD({gitService:Ek,sessionState:Ok,watchers:Tk},{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)}`)}}),Pk=60*1e3;function Fk(){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,Pk),a.unref())},checkNow:o}}const Ik=Fk(),Lk=BS({entryUrl:import.meta.url,intervalMs:Pk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>Ik.checkNow(),log:Y});let Rk=null,zk=null,Bk=0;function Vk(){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{Bk=oy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),Zk(1);return}Rk=Jb(t.pid);let e=ix(ox(Rk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Zk(1);return}zk=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),Ok.useStorage(new _D(ze(),500,Y)),Zb({anchor:Xb(t.env),isAlive:Qb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),Zk(0)}}),Hk(g.createServer({allowHalfOpen:!1},e=>{Qk(e)}),Pe(),!1)}function Hk(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}Uk(e,n)}),e.listen(n,()=>Wk(n))}function Uk(e,n){let i=Rb(zb(Le(n)),(e,t)=>qb(e,t,{readStartTime:Kb,pidAlive:Qb}));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}}Hk(e,n,!0)}function Wk(e){let n=Hb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Zk(0);return}Jk(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(Bk/1048576)}MB`),Cy();let i=kk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),Ik.arm(),Lk.arm(),qk(),Gk(e,n.identity)}function Gk(e,n){Gb({bound:n,myPid:t.pid,readIdentity:()=>Hb(e),readLease:()=>zb(Le(e)),shutdown:e=>Zk(e),log:Y}).arm()}let Kk=null;function qk(){Kk=uy(my(wk.startedAt.getTime(),e=>Zk(e),{rssLimitBytes:Bk})),Kk.arm()}function Jk(e){let n=Bb(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Rk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let Yk=0,Xk=!1;function Zk(e){if(!Xk){Xk=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{Ek.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{Dk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{Tk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{Ok.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Vb(Re(),t.pid),zk!==null&&ax(zk,t.pid,nx,e=>r.unlinkSync(e)),t.exit(e)}}function Qk(e){Yk++,wk.inFlight=Yk;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(()=>{wk.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{eA(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),Yk=Math.max(0,Yk-1),wk.inFlight=Yk})}const $k=e=>({resp:e,exitAfterFlush:null});async function eA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return $k({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 $k({ok:!0,stats:wk.snapshot({gitCache:Ek.getStats(),usageCache:Dk.getStats(),renderCacheSize:Nk.size,watchersActive:Tk.size(),nextRestartReason:Kk?.describeNextRestart()??null})});if(e.kind===`render`){wk.requestsTotal++;let t=Date.now();try{let{report:n}=tk(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 wk.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),$k({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=tA(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);Ok.get(s,`client-hints`)!==l&&Ok.set(s,UO,l);let u=Ok.get(s,`config-override`)??a??c.configEnv,d=Nk.getOrCreate(i,e.cwd,u),f=MO({projectDir:i,cwd:e.cwd,configFile:u??null});Ok.get(s,`render-origin`)!==f&&Ok.set(s,jO,f);let p=c.termCols,m=gk(p??120),h=bx(c.termRows),g={...rA,width:m},{authoredRoots:_}=d.state,v=rw(d.state.config,t=>Ok.get(e.hookData.session_id,t),e=>_.has(e)),y=await gw(e.hookData,sA,e.cwd,d.state.neededInputPaths,v,c),b=XT(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=YE(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=Ok.get(e.hookData.session_id,`click.error`);S&&Ok.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,S].filter(Boolean).join(`
|
|
184
|
-
`),te=
|
|
185
|
-
`})}catch(e){throw
|
|
186
|
-
`);return}t.stdout.write(
|
|
181
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function ZE(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 QE={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 ZE(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(!JT(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&&JT(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=XE(cE(o,u)).map(e=>eE(e,d)),p=s.map(e=>eE(cE([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 $E(e){return QE[e]}function eD(e){if(`ttl`in e)return{kind:`ttl`,durationMs:jT(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 tD(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 nD(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:eD(n.cache),parse:tD(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:eD(n.cache),parse:tD(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?jT(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 rD(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 iD(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,padding:1},a=jE(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=rh(e.presets),l=new Map([...j_(e),...wh(e)]),u=ST({...OE(i),...zE(i,a),...GE(o),...JE(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=rD(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=gE(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{nD(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{nD(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:oE(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 $E(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 aD(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u}=s??{},{look:d=gn,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=CT(n),m=sE(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=fE(t.activeSegment,e,n,c,o,s,i,a,p),u=Qs(n,c);return{closed:l,trigger:kE(n,u.state),band:kE(n,u.plane),disclosure:c}},_=e=>(t.activeSegment.current=null,VE(e)),v=(e,t,n)=>{let r=t&&JT(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 $E(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=>yx(rE(e,o),o)).join(`
|
|
182
|
+
`)}var oD=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,fD(e,t,n,`initial value`),this.cell=Mw.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){fD(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},sD=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Mw.computed)(()=>{let e=n();return fD(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},cD=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Mw.observable.box(dD(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=dD(e);uD(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function lD(e){return JSON.stringify(e)}function uD(e,t){return lD(e)===lD(t)}function dD(e){return e.kind===`ok`?{kind:`ok`,value:Nw(e.value)}:e}function fD(e,t,n,r){let i=Pw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var pD=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new oD(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new cD(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new sD(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,Mw.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,Mw.runInAction)(()=>n.set(t))}runInAction(e){(0,Mw.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 lD(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 mD(e,t,n){return e+`\0`+t+`\0`+(n??``)}function hD(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 gD(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 _D(e,t){let n=new Map;for(let t of lv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=gD(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 vD(e){return e.filter(Boolean).join(`
|
|
183
|
+
`)||null}var yD=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=mD(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:vD(a),state:null,error:e instanceof da||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:vD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=gv(t,kw);n.push(...o);let s=yv(r,t??`<default>`,a),c=new pD,l=new qT(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=iD(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of TS(s))d.push(vS(e,t));for(let{key:e,spec:t}of sS(s))d.push(cS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:fw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:hD(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=_D(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 bD=16384;var xD=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<bD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%bD}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:nb,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 SD={load:()=>({}),save:()=>{},flush:()=>{}};function CD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var wD=class{sessions;storage;atom=(0,Mw.createAtom)(`SessionState`);constructor(e=SD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=CD(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,Mw.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,Mw.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,Mw.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 TD=(e,t)=>E(t);function ED(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 DD=class{timer=null;pending=null;constructor(e,t=500,n=TD){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 ED(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`},kD=new Set([`1`,`true`]),AD=new Set([`0`,`false`,``]);function jD(e,t){let n=nO(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(kD.has(t))return`true`;if(AD.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function MD(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function ND(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function PD(e){return/^\s*$/.test(e)?null:ji(e)}function FD(e,t){return e!==null&&Ni(e,t)!==void 0}function ID(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(ID),...i}}return e}function LD(e){if(!ao(e))return ID(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,ID(t)])),...n}}const RD=Dw,zD=RD.segments,BD=RD.presets,VD=RD.root;function HD(e,t,n,r){if(!FD(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function UD(e,t){let n=fh(t);return t.scope===`segment-palette`&&HD(e,[`segments`,t.segment],zD[t.segment],n.join(`.`)),n}function WD(e){return ji(zi(e))}function GD(){return Object.entries(VD.rows).map(([e,t])=>{let n=ID(t);return{path:[`root`],fragment:WD({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function KD(e,t){let n=e===null?void 0:Ni(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function qD(e,t){if(t===void 0)return null;let n=LD(t);return{path:e,fragment:WD(n),unit:{path:e,value:n}}}function JD(e,t){let n=[`presets`,t],r=[...n,`root`],i=BD[t];HD(e,n,i,r.join(`.`));let a=KD(e,r)??qD(r,i?.root);return a!==null&&aa(a.fragment)?a:null}function YD(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 XD(e,t){return[...GD(),KD(e,[`root`]),JD(e,t)].filter(e=>e!==null).reduce(YD,new Map)}function ZD(e,t,n){for(let{node:r,...i}of XD(e,t).values())if(sa(r,n))return i;throw new $(`${QD(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function QD(e,t){return JD(e,t)?.path??[`root`]}function $D(e,t){return t.scope===`preset-root`?QD(e,t.preset):fh(t)}function eO(e,{unit:t}){return t===null?e:$i(e,t.path,zi(t.value),Li)}function tO(e){let t=dh(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function nO(e){let t=tO(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function rO(e,t){let n=nO(t),r=PD(MD(e)??``),i=r===null?void 0:Ni(r,fh(n));return i!==void 0&&`value`in i?i.value:void 0}function iO(e,t,n,r){let i=nO(n),a=MD(t);mO(e,t,{before:a,after:$i(a??``,UD(PD(a??``),i),jD(n,r),Li)})}function aO(e,t,n){let r=tO(n),i=MD(t);if(i===null)return;let a=ea(i,$D(PD(i),r));a!==i&&mO(e,t,{before:i,after:a})}function oO(e,t,n,r){let i=tO(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=MD(t),o=r.op===`remove`?r.target:r.anchor,s=ZD(PD(a??``),i.preset,o),c=eO(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`);mO(e,t,{before:a,after:l})}const sO={past:[],future:[]};function cO(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function lO(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(cO)&&Array.isArray(t.future)&&t.future.every(cO)}function uO(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(lO))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function dO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(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 fO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function pO(e,t,n,r,i){ND(t,n,e.logger);try{dO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function mO(e,t,n){let r=uO(e),{past:i}=r[t]??sO;pO(e,t,n.after,{...r,[t]:{past:fO(i,n),future:[]}},`edit`)}function hO(e,t){let n=uO(e),{past:r,future:i}=n[t]??sO,a=r[r.length-1];return a===void 0?null:(_O(t,a.after,`undo`),pO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:fO(i,a)}},`undo`),a)}function gO(e,t){let n=uO(e),{past:r,future:i}=n[t]??sO,a=i[i.length-1];return a===void 0?null:(_O(t,a.before,`redo`),pO(e,t,a.after,{...n,[t]:{past:fO(r,a),future:i.slice(0,-1)}},`redo`),a)}function _O(e,t,n){if(MD(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function vO(e){let t=De({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 yO(){return{probeTmux:vO,claudeSettingsPath:rb()}}function bO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function xO(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 SO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function CO(e){try{return xO(bO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function wO(e,t){return{tmux:SO(e,t),claudeSettingsEnv:CO(e)}}function TO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=$i(bO(e),[`env`,t.name],JSON.stringify(t.value),Ri);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:CO(e)}}default:return t.kind}}function EO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function DO(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 kO(e,t){let n=De({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 AO=(e,t)=>kO(DO(e),t),jO=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,DO(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`})`)}},MO=(e,t)=>kO(DO(e),t),NO=(e,t)=>kO(DO(e),t),PO=(e,t)=>{let n=EO(DO(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},FO=(e,t)=>{let[n=``,...r]=OO(()=>Qy(e)),i=EO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${_S().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: ${_S().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=yS(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})`)},IO=/^-?\d+$/;function LO(e,t,n){return e>n?t:e<t?n:e}function RO(e,t){if(!e)return null;if(!_S().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${_S().join(`, `)})`);return e}function zO(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const BO=(e,t)=>{let[n=``,r=``,i=``]=OO(()=>Qy(e)),a=EO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!IO.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=bS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${_S().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&IO.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=LO(l+o,s.min,s.max),d=yS(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})`)},VO=`render-origin`;function HO(e){return JSON.stringify(e)}function UO(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 WO(e,t){let n=e.sessionState.get(t,VO);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=UO(n);return fv(r.projectDir,r.cwd,r.configFile??void 0)}function GO(e){return{historyPath:Be(),logger:e.dlog}}const KO=(e,t)=>{let[n=``,r=``,i=``,a=``]=OO(()=>Qy(e)),o=EO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${$x().join(`, `)})`);let s=eS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=RO(a,`set-config`),l=WO(t,o);iO(GO(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),zO(c,o,t,`set-config`)},qO=(e,t)=>{let[n=``,r=``,i=``,a=``]=OO(()=>Qy(e)),o=EO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!IO.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=RO(a,`step-config`),l=tS(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${$x().join(`, `)})`);let u=WO(t,o),d=rO(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=LO(f+s,l.min,l.max),m=eS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);iO(GO(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),zO(c,o,t,`step-config`)},JO=(e,t)=>{let[n=``,r=``]=OO(()=>Qy(e)),i=EO(n);if(!r||!$x().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${$x().join(`, `)})`);let a=WO(t,i);aO(GO(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},YO=(e,t)=>{let[n=``,r=``,i=``]=OO(()=>Qy(e)),a=EO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${$x().join(`, `)})`);let o=eS(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=WO(t,a);oO(GO(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},XO=(e,t)=>{let[n=``]=OO(()=>Qy(e)),r=EO(n),i=WO(t,r);if(hO(GO(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},ZO=(e,t)=>{let[n=``]=OO(()=>Qy(e)),r=EO(n),i=WO(t,r);if(gO(GO(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},QO=(e,t)=>{EO(DO(e)),t.applyUpdate()},$O=`client-hints`;function ek(e,t){let n=e.sessionState.get(t,$O);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 tk(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 nk=(e,t)=>{let n=EO(DO(e));tk(t,n,wO(t.doctor,ek(t,n).tmux))},rk=(e,t)=>{let[n=``,r=``]=OO(()=>Qy(e)),i=EO(n),a=Lh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=wO(t.doctor,ek(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=TO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),tk(t,i,c)},ik=`config-override`,ak=new Map([[Ly,AO],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=EO(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,ik),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,ik,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ry,jO],[Fy,FO],[Iy,BO],[Hy,KO],[Uy,qO],[Wy,JO],[Gy,YO],[Ky,XO],[qy,ZO],[By,MO],[Vy,NO],[zy,PO],[Jy,QO],[Yy,nk],[Xy,rk]]),ok=new Set([Fy,Iy,Hy,Uy,Wy,Gy,Ky,qy,zy,Jy,Yy,Xy]),sk=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of eb(e)){if(!i&&ok.has(a)){let e=Qy(o);e.length>0&&e[0]&&(i=e[0])}let e=ak.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(`
|
|
184
|
+
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},ck=new Map([...ak,[Py,sk]]);Object.freeze([...ck.keys()]);const lk=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`]),uk=[[`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 dk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of uk){let i=pk(n,e);if(i==null)t.missingRequired.push(e);else{let n=fk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))lk.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function fk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function pk(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 mk(e,t){switch(e){case`vars`:return{what:e,vars:hk(t)};case`segments`:return{what:e,segments:bk(t)};case`config`:return{what:e,config:Ck(t)}}}function hk(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=vk(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,...gk(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:_k(r.lastUpdatedMs())})}return o}function gk(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 _k(e){return e===null?null:Math.max(0,Date.now()-e)}function vk(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,yk(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}`,yk(i));return t}function yk(e){return e.kind}function bk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=xk(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:Sk(t.template,i),lastRender:r.get(e)??null})}return o}function xk(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 Sk(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 Ck(e){return e===null?null:e.config}const wk=[`vars`,`segments`,`config`];function Tk(e){return typeof e==`string`&&wk.includes(e)}function Ek(e){return Math.max(1,e-2)}var Dk=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 E(`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);E(`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{E(`Calculating context tokens from transcript: ${e}`);let n=await FC(e);if(n.length===0)return E(`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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`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 kk=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=CC(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 zC(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(E(`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 Ak=new Map;function jk(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var Mk=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=jk(process.env.TMUX),t=Ak.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({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 Ak.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},Nk=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 Pk=new xD;we(Pk.launchStats);const Fk=new dC({counters:Pk,logger:Y}),Ik=new yC({watchers:Fk,logger:Y}),Lk=new ZC,Rk=new wD,zk=new Nk(Ge()),Bk=new Dk,Vk=new kk,Hk=new Mk,Uk=new yD({gitService:Ik,sessionState:Rk,watchers:Fk},{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)}`)}}),Wk=60*1e3;function Gk(){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),sA(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Wk),a.unref())},checkNow:o}}const Kk=Gk(),qk=BS({entryUrl:import.meta.url,intervalMs:Wk,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>Kk.checkNow(),log:Y});let Jk=null,Yk=null,Xk=0;function Zk(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),sA(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),sA(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),sA(0)});try{Xk=oy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),sA(1);return}Jk=Jb(t.pid);let e=ix(ox(Jk));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),sA(1);return}Yk=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),Rk.useStorage(new DD(ze(),500,Y)),Zb({anchor:Xb(t.env),isAlive:Qb,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),sA(0)}}),Qk(g.createServer({allowHalfOpen:!1},e=>{cA(e)}),Pe(),!1)}function Qk(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),sA(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}$k(e,n)}),e.listen(n,()=>eA(n))}function $k(e,n){let i=Rb(zb(Le(n)),(e,t)=>qb(e,t,{readStartTime:Kb,pidAlive:Qb}));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}`),sA(1);return}}Qk(e,n,!0)}function eA(e){let n=Hb(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),sA(0);return}iA(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(Xk/1048576)}MB`),Cy();let i=zk.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),Kk.arm(),qk.arm(),rA(),tA(e,n.identity)}function tA(e,n){Gb({bound:n,myPid:t.pid,readIdentity:()=>Hb(e),readLease:()=>zb(Le(e)),shutdown:e=>sA(e),log:Y}).arm()}let nA=null;function rA(){nA=uy(my(Pk.startedAt.getTime(),e=>sA(e),{rssLimitBytes:Xk})),nA.arm()}function iA(e){let n=Bb(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Jk});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let aA=0,oA=!1;function sA(e){if(!oA){oA=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{Ik.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{Lk.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{Fk.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{Rk.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}Vb(Re(),t.pid),Yk!==null&&ax(Yk,t.pid,nx,e=>r.unlinkSync(e)),t.exit(e)}}function cA(e){aA++,Pk.inFlight=aA;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:()=>sA(r);try{e.end(Nv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{Pk.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pv(e=>{uA(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),aA=Math.max(0,aA-1),Pk.inFlight=aA})}const lA=e=>({resp:e,exitAfterFlush:null});async function uA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return lA({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 lA({ok:!0,stats:Pk.snapshot({gitCache:Ik.getStats(),usageCache:Lk.getStats(),renderCacheSize:Uk.size,watchersActive:Fk.size(),nextRestartReason:nA?.describeNextRestart()??null})});if(e.kind===`render`){Pk.requestsTotal++;let t=Date.now();try{let{report:n}=dk(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 Pk.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),lA({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=dA(e.args),s=e.hookData.session_id,c=Ev(e),l=JSON.stringify(c);Rk.get(s,`client-hints`)!==l&&Rk.set(s,$O,l);let u=Rk.get(s,`config-override`)??a??c.configEnv,d=Uk.getOrCreate(i,e.cwd,u),f=HO({projectDir:i,cwd:e.cwd,configFile:u??null});Rk.get(s,`render-origin`)!==f&&Rk.set(s,VO,f);let p=c.termCols,m=Ek(p??120),h=bx(c.termRows),g={...pA,width:m},{authoredRoots:_}=d.state,v=rw(d.state.config,t=>Rk.get(e.hookData.session_id,t),e=>_.has(e)),y=await gw(e.hookData,_A,e.cwd,d.state.neededInputPaths,v,c),b=oE(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=aD(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=Rk.get(e.hookData.session_id,`click.error`);S&&Rk.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,S].filter(Boolean).join(`
|
|
185
|
+
`),te=qk.notice({sessionId:s,dismissed:Rk.get(s,ES),enabled:v.updateNotice}),ne=d.lastError===null?null:d.configFilePath,re=Tx(ee,te,d.lastWarning??``),ie=zk.sync(s,re===null?null:Dx(re));ie!==null&&Y(`warn`,`diagnostic dump failed: ${ie}`);let C=Ox(x,re,{fullText:ie===null?{kind:`file`,path:zk.pathFor(s)}:{kind:`unavailable`,reason:ie},failedConfigFile:ne},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),ae=Date.now()-t,w=Ik.getStats(),T=Lk.getStats();return Y(`info`,`render sid=${e.hookData.session_id??`?`} took=${ae}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${w.size}/${w.hits}h/${w.misses}m usage=${T.size}/${T.hits}h/${T.misses}m err=${ee?`Y`:`N`} upd=${te.length} warn=${d.lastWarning?`Y`:`N`}`),lA({ok:!0,output:C+`
|
|
186
|
+
`})}catch(e){throw Pk.requestsErrored++,e}}if(e.kind===`click`)return lA(await vA(e.verb,e.value));if(e.kind===`debug`){if(!Tk(e.what))return lA({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${wk.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=Uk.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?gA(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):hA};return lA({ok:!0,debug:mk(e.what,n)})}return lA({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function dA(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 fA={sessionState:Rk,dlog:Y,applyUpdate:()=>qk.act(),doctor:yO()},pA={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},mA={...pA,width:1/0},hA=new Map;function gA(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,yx(a,{...mA,charset:t,colorCompatibility:n}));return r}const _A={gitProvider:Ik,usageStore:Lk,contextProvider:Bk,metricsProvider:Vk,tmuxService:Hk,log:Y,clock:()=>new Date};function vA(e,t){let n=ck.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,fA),{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 yA={connectMs:200,budgetMs:500};async function bA(e){let n=e.includes(`--json`),r=await xA();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)+`
|
|
187
|
+
`);return}t.stdout.write(TA(r.value))}function xA(){return Iv({kind:`stats`},yA,e=>`stats`in e?e.stats:void 0)}function SA(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function CA(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function wA(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 TA(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 ${wA(e.uptimeSec)}`),t.push(` rss ${SA(e.rssBytes)}`),t.push(` heapUsed ${SA(e.heapUsedBytes)}`),t.push(` heapTotal ${SA(e.heapTotalBytes)}`),t.push(` external ${SA(e.externalBytes)}`),t.push(` arrayBuffers ${SA(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 ${CA(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 ${CA(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(`
|
|
187
188
|
`)+`
|
|
188
|
-
`}const
|
|
189
|
-
`);return}t.stdout.write(
|
|
190
|
-
`;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?``:` ${
|
|
189
|
+
`}const EA={connectMs:200,budgetMs:500};async function DA(e,n){let r=n.includes(`--json`),i=await OA(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Hv(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
190
|
+
`);return}t.stdout.write(kA(i.value))}function OA(e){return Iv({kind:`debug`,what:e},EA,e=>`debug`in e?e.debug:void 0)}function kA(e){switch(e.what){case`vars`:return AA(e.vars);case`segments`:return jA(e.segments);case`config`:return MA(e.config);default:return e}}function AA(e){if(e.length===0)return`no variables (DSL not active)
|
|
191
|
+
`;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?``:` ${PA(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${NA(a.value)}${e}${o}`)}return t.join(`
|
|
191
192
|
`)+`
|
|
192
|
-
`}function
|
|
193
|
+
`}function jA(e){if(e.length===0)return`no segments (DSL not active)
|
|
193
194
|
`;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(`
|
|
194
195
|
`)+`
|
|
195
|
-
`}function
|
|
196
|
+
`}function MA(e){return e===null?`config: DSL not active
|
|
196
197
|
`:JSON.stringify(e,null,2)+`
|
|
197
|
-
`}function
|
|
198
|
-
`));return l.rendered}finally{c.dispose()}}function
|
|
199
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:
|
|
198
|
+
`}function NA(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function PA(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function FA(){let e=LA();return e===null?null:r.readFileSync(e,`utf-8`)}function IA(){let e;try{e=FA()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function LA(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function RA(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const zA=5e3;function BA(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},theme:{effective:e.theme},look:{effective:e.look},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function VA(e,t){let n=dv(e,e),r=pv(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function HA(e,n=t.cwd()){let i=[],a=e===void 0?VA(n,i):c.resolve(cv(e));if(e!==void 0&&a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let o=hv(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await UA(a,n,i)}}catch(e){let t=e;return a!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===a&&typeof t.message==`string`?{kind:`unreadable`,path:a,message:t.message}:(e instanceof da&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof da||e instanceof Error?e.message:String(e),warnings:i})}}async function UA(e,t,n){let{config:r,source:i,warnings:a}=gv(e,kw);n.push(...a);let o=yv(r,e??`<default>`,i),s=new pD,c=new qT(s,o.globals.default_empty_value??``,void 0,new wD);try{let e=iD(o,c,{cwd:t});n.push(...e.loadWarnings);let r=await c.settled(zA);r.length>0&&n.push(`source${r.length===1?``:`s`} still running after ${zA} ms, rendered with fallback values: ${r.join(`, `)}`),TS(o);let i=rw(o,()=>null,()=>!1),a=t=>{let n=new Map;return{rendered:aD(o,e,s,c,BA(t),oE(t.theme),{style:t.style,separator:t.separator,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(e,t)},{look:fi(o.looks,t.look),preset:t.preset}),segmentErrors:n}},l=a(i),u=a({...i,presetCustomized:!0}),d=[...[...l.segmentErrors].map(([e,t])=>`segment "${e}": ${t}`),...[...u.segmentErrors].filter(([e])=>!l.segmentErrors.has(e)).map(([e,t])=>`segment "${e}": ${t} (under .preset.customized = true)`)];if(d.length>0)throw Error(`config renders with ${d.length} segment error${d.length===1?``:`s`} (the daemon would render ⚠ error cells):\n`+d.map(e=>` ${e}`).join(`
|
|
199
|
+
`));return l.rendered}finally{c.dispose()}}function WA(e){return e.map(e=>`warning: ${e}\n`).join(``)}function GA(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:WA(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:WA(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const KA=`--render`,qA=`Usage: cc-candybar check [${KA}] [config-file]\n`;function JA(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==KA);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${qA}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${qA}`}:{kind:`run`,target:n[0],render:t.includes(KA)}}async function YA(e){let n=JA(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:GA(await HA(n.target??RA(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const XA=`${dx}${ux}`;function ZA(e){return`${XA}⚠ cc-candybar: ${QA(e)}[0m\n`}function QA(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${lx(e.message,60)}`;case`render_failed`:return`render failed: ${lx(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${lx(e.message,60)}`}}function $A(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
200
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:ZA(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function ej(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}function tj({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:` (fix: click ☰ 🧰 tools ▸ 🩺 doctor, then [fix] on the bar)`}\n`}function nj(e,t){let n;try{n=wO(e,Nh(t))}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let r=Ih(n);return{stdout:r.map(tj).join(``),stderr:``,code:+!r.every(e=>e.verdict.ok)}}function rj(e){e.length>0&&(t.stderr.write(`doctor: takes no arguments
|
|
200
201
|
Usage: cc-candybar doctor
|
|
201
|
-
`),t.exit(2));let n=
|
|
202
|
+
`),t.exit(2));let n=nj(yO(),t.env);t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}function ij(){return ej(t.env.COLUMNS,t.stderr.columns)}function aj(){return ej(t.env.LINES,t.stderr.rows)}const oj=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],sj=e=>e.some(e=>t.argv.includes(e));function cj(){return oj.some(e=>(t.env[e]??``)!==``)}function lj(){console.log(yh)}async function uj(){try{sj(gh.help)&&(lj(),t.exit(0)),sj(gh.version)&&(console.log(`cc-candybar ${nb}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Ib(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(jb(),t.exit(0)),e===`url-handle`){await Nb(t.argv[3]);return}if(e===`daemon`){Zk();return}if(e===`daemon-stats`&&(await bA(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await YA(t.argv.slice(3));return}if(e===`schema`){IA();return}if(e===`doctor`){rj(t.argv.slice(3));return}Tk(e)&&(await DA(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
202
203
|
|
|
203
204
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
204
205
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -214,4 +215,4 @@ Add to ~/.claude/settings.json:
|
|
|
214
215
|
Run with --help for more options.
|
|
215
216
|
|
|
216
217
|
To test output manually:
|
|
217
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`)
|
|
218
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),lj(),t.exit(1));let i=$A(await Kv(r,t.argv,t.cwd(),{termCols:ij(),termRows:aj(),ssh:cj(),tmux:Nh(t.env),configEnv:RA(t.env)}));i.debug!==null&&E(i.debug),i.kick&&hy(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}uj();export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptctl/cc-candybar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.66.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.
|
|
94
|
-
"@promptctl/cc-candybar-darwin-x64": "1.
|
|
95
|
-
"@promptctl/cc-candybar-linux-x64": "1.
|
|
96
|
-
"@promptctl/cc-candybar-linux-arm64": "1.
|
|
93
|
+
"@promptctl/cc-candybar-darwin-arm64": "1.66.0",
|
|
94
|
+
"@promptctl/cc-candybar-darwin-x64": "1.66.0",
|
|
95
|
+
"@promptctl/cc-candybar-linux-x64": "1.66.0",
|
|
96
|
+
"@promptctl/cc-candybar-linux-arm64": "1.66.0"
|
|
97
97
|
}
|
|
98
98
|
}
|
|
@@ -1421,6 +1421,9 @@
|
|
|
1421
1421
|
{
|
|
1422
1422
|
"const": "auto"
|
|
1423
1423
|
},
|
|
1424
|
+
{
|
|
1425
|
+
"const": "fill"
|
|
1426
|
+
},
|
|
1424
1427
|
{
|
|
1425
1428
|
"type": "integer",
|
|
1426
1429
|
"minimum": 1
|
|
@@ -2060,6 +2063,9 @@
|
|
|
2060
2063
|
{
|
|
2061
2064
|
"const": "auto"
|
|
2062
2065
|
},
|
|
2066
|
+
{
|
|
2067
|
+
"const": "fill"
|
|
2068
|
+
},
|
|
2063
2069
|
{
|
|
2064
2070
|
"type": "integer",
|
|
2065
2071
|
"minimum": 1
|