tweakcc-fixed 2.8.4 → 2.8.6

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.
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";import t from"chalk";import*as n from"node:os";import r,{EOL as i}from"node:os";import*as a from"node:fs/promises";import o from"node:fs/promises";import*as s from"node:fs";import c,{createReadStream as l}from"node:fs";import*as u from"node:path";import d from"node:path";import*as f from"fs";import*as p from"path";import*as m from"os";import*as h from"child_process";import*as g from"crypto";import{spawnSync as _}from"node:child_process";import v from"gray-matter";import{fileURLToPath as y}from"node:url";import{Worker as b}from"node:worker_threads";import{diffWordsWithSpace as x}from"diff";import*as S from"node:crypto";let C=null;async function w(){if(C!==null)return C;try{return await import(`node-lief`),C=await import(`./nativeInstallation-0UhZtljt.mjs`),C}catch(e){return J(`Error loading native installation module: ${e instanceof Error?e.message:String(e)}`),e instanceof Error&&J(e),null}}async function T(e,t){let n=await w();return n?n.extractClaudeJsFromNativeInstallation(e,t):{data:null,clearBytecode:!1,error:`node-lief native module unavailable on this platform/runtime (cannot extract from native installs)`}}async function E(e,t,n,r){let i=await w();if(!i)throw Error("`repackNativeInstallation()` called but `node-lief` is not available. This is unexpected - `extractClaudeJsFromNativeInstallation()` should have been called first.");i.repackNativeInstallation(e,t,n,r)}async function D(e){let t=await w();return t?t.resolveNixBinaryWrapper(e):null}const O=`You are a difficulty router for an AI coding agent. Each turn you get a compact running SUMMARY of the session, a CONTEXT block (the model in use and the level you assigned last turn), the most recent exchange (the previous user message and the assistant reply), and the user NEW message. Do two things and output ONLY a JSON object with the keys level and summary - no prose, no code fence.
1
+ import{createRequire as e}from"node:module";import t from"chalk";import*as n from"node:os";import r,{EOL as i}from"node:os";import*as a from"node:fs/promises";import o from"node:fs/promises";import*as s from"node:fs";import c,{createReadStream as l}from"node:fs";import*as u from"node:path";import d from"node:path";import*as f from"fs";import*as p from"path";import*as m from"os";import*as h from"child_process";import*as g from"crypto";import{spawnSync as _}from"node:child_process";import v from"gray-matter";import{fileURLToPath as y}from"node:url";import{Worker as b}from"node:worker_threads";import{diffWordsWithSpace as x}from"diff";import*as S from"node:crypto";let C=null;async function w(){if(C!==null)return C;try{return await import(`node-lief`),C=await import(`./nativeInstallation-CtmrZY7J.mjs`),C}catch(e){return J(`Error loading native installation module: ${e instanceof Error?e.message:String(e)}`),e instanceof Error&&J(e),null}}async function T(e,t){let n=await w();return n?n.extractClaudeJsFromNativeInstallation(e,t):{data:null,clearBytecode:!1,error:`node-lief native module unavailable on this platform/runtime (cannot extract from native installs)`}}async function E(e,t,n,r){let i=await w();if(!i)throw Error("`repackNativeInstallation()` called but `node-lief` is not available. This is unexpected - `extractClaudeJsFromNativeInstallation()` should have been called first.");i.repackNativeInstallation(e,t,n,r)}async function D(e){let t=await w();return t?t.resolveNixBinaryWrapper(e):null}const O=`You are a difficulty router for an AI coding agent. Each turn you get a compact running SUMMARY of the session, a CONTEXT block (the model in use and the level you assigned last turn), the most recent exchange (the previous user message and the assistant reply), and the user NEW message. Do two things and output ONLY a JSON object with the keys level and summary - no prose, no code fence.
2
2
 
3
3
  # level
4
4
  Pick the integer effort level (0 = least effort, {MAX} = most) for the NEW message, judged IN CONTEXT of the summary, the context block, and the recent exchange:
@@ -224,7 +224,7 @@ ${_} </div>
224
224
  |\\\\n)`).replace(new RegExp(i,`g`),`\\$\\{[^{}]*\\}`).replace(new RegExp(a,`g`),`(?:\\\\|\\\\\\\\)`).replace(new RegExp(o,`g`),`\\[[\\w$]+\\]`).replace(new RegExp(s,`g`),`\\[[\\w$]+`);r+=u,c<e.length-1&&(r+=`([\\w$]+)`)}return r},hn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]===`\\`;)n++,r--;return n},gn=e=>{let t=``,n=0,r=``,i=[];for(let a=0;a<e.length;a++){let o=e[a],s=e[a+1],c=hn(e,a)%2==0;if(n){if(i.length>0&&n===i[i.length-1]){if(o==="`"&&c)i.pop();else if(o===`$`&&s===`{`){c&&n++,t+="${",a++;continue}t+=o;continue}if(r)o===r&&c&&(r=``);else if(o===`$`&&s===`{`){c&&n++,t+="${",a++;continue}else o===`"`||o===`'`?r=o:o==="`"&&c?i.push(n):o===`{`?n++:o===`}`&&n--;t+=o;continue}if(o===`$`&&s===`{`&&!r){c&&n++,t+="${",a++;continue}o==="`"&&c?t+="\\`":t+=o}let a=n>0||i.length>0;return a&&J(`escapeDepthZeroBackticks: unclosed interpolation detected (depth=${n}). Some backticks may not have been escaped.`),{content:t,incomplete:a}},_n=(e,t)=>{let n=``;for(let r=0;r<e.length;r++)if(e[r]===t){let i=0,a=r-1;for(;a>=0&&e[a]===`\\`;)i++,a--;n+=i%2==0?`\\`+t:t}else n+=e[r];return n},vn=e=>/[\\`'"\r\n]/.test(e)||e.includes("${"),yn=(e,t,n)=>{let r=e,i=!1,a=!1;if(t===`"`||t===`'`)r=r.replace(/\\/g,`\\\\`),r=r.replace(/\r\n|\r|\n/g,`\\n`),r=_n(r,t);else if(t==="`"){r=r.replace(/\r\n|\r/g,`
225
225
  `);let e=gn(r);i=e.incomplete,a=e.content!==r,r=e.content}return n&&(r=pn(r)),{content:r,incomplete:i,autoEscaped:a}},bn=e=>{if(e.length===0)return{leading:``,trailing:``};let t=e[0].match(/^(\s*)/),n=t?t[1]:``,r=e[e.length-1].match(/(\s*)$/);return{leading:n,trailing:r?r[1]:``}},xn=(e,t)=>{if(e.trim()===``)return``;let n=e.trim();return t.leading+n+t.trailing},Sn=new Set([`(`,`,`,`=`,`:`,`[`,`!`,`&`,`|`,`?`,`{`,`}`,`;`,`+`,`-`,`*`,`%`,`~`,`^`,`<`,`>`,`n`]),Cn=/[$\w]/,wn=(e,t)=>{let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return!0;let r=e[n];return r===`n`?/(?:^|[^$\w])(?:return|in)$/.test(e.slice(0,n+1)):Sn.has(r)},Tn=(e,t,n)=>{let r=t+1;for(;r<e.length;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===n)return r+1;r++}return-1},En=(e,t)=>{let n=t+1,r=!1;for(;n<e.length;){let t=e[n];if(t===`\\`){n+=2;continue}if(t===`
226
226
  `)return-1;if(t===`[`)r=!0;else if(t===`]`)r=!1;else if(t===`/`&&!r){for(n++;n<e.length&&/[a-z]/i.test(e[n]);)n++;return n}n++}return-1},Dn=(e,t)=>{let n=[],r=[`expr`],i=t+2,a=i,o=e=>{e>i&&n.push({start:i,end:e})};for(;a<e.length;){let t=e[a];if(r[r.length-1]===`template`){if(t===`\\`){a+=2;continue}if(t==="`"){r.pop(),a++,i=a;continue}if(t===`$`&&e[a+1]===`{`){r.push(`expr`),a+=2,i=a;continue}a++;continue}if(t===`/`&&e[a+1]===`/`){o(a);let t=e.indexOf(`
227
- `,a);a=t===-1?e.length:t,i=a;continue}if(t===`/`&&e[a+1]===`*`){o(a);let t=e.indexOf(`*/`,a+2);if(t===-1)return null;a=t+2,i=a;continue}if(t===`/`&&wn(e,a)){o(a);let t=En(e,a);if(t===-1)return null;a=t,i=a;continue}if(t===`'`||t===`"`){o(a);let n=Tn(e,a,t);if(n===-1)return null;a=n,i=a;continue}if(t==="`"){o(a),r.push(`template`),a++;continue}if(t===`{`){r.push(`expr`),a++;continue}if(t===`}`){if(r.pop(),r.length===0)return o(a),{end:a,codeRegions:n};if(r[r.length-1]===`template`){o(a),a++;continue}a++;continue}a++}return null},On=(e,t)=>{let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;return n},kn=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n++;return n<e.length?n:-1},An=(e,t,n)=>{let r=On(e,t),i=r>=0?e[r]:``,a=kn(e,n);return!((a>=0?e[a]:``)===`:`&&(i===`{`||i===`,`))},jn=(e,t)=>{let n=[];for(let t=0;t<e.length;t++){if(e[t]!==`$`||e[t+1]!==`{`||hn(e,t)%2!=0)continue;let r=Dn(e,t);if(!r)throw Error(`applyIdentifierMapping: unbalanced \${...} interpolation at offset ${t}: ${JSON.stringify(e.slice(t,t+80))}`);n.push(...r.codeRegions),t=r.end}if(n.length===0)return e;let r=``,i=0;for(let a of n){r+=e.slice(i,a.start);let n=a.start;for(;n<a.end;){if(!Cn.test(e[n])){r+=e[n],n++;continue}let i=n;for(;i<a.end&&Cn.test(e[i]);)i++;let o=e.slice(n,i);Object.prototype.hasOwnProperty.call(t,o)&&An(e,n,i)?r+=t[o]:r+=o,n=i}i=a.end}return r+=e.slice(i),r},Mn=(e,t,n,r,i,a=!1,o,s)=>{let c={};for(let e=0;e<r.length;e++){let i=r[e],a=String(t[e]),o=n[a]||`UNKNOWN_${a}`;c[o]=i}let l=jn(e,c);if(l=l.replace(/<<CCVERSION>>/g,i),o&&(l=l.replace(/<<BUILD_TIME>>/g,o)),a&&(l=pn(l)),s&&s.length>0){let e=bn(s);l=xn(l,e)}return l},Nn=async(e,t=!1,n)=>{if(!I||sn!==e)return[];let r=I,i=[],o=await Ut();for(let t of r.prompts){if(!t.id||o.has(t.id))continue;let r=mn(t.pieces,e,n),s=p.join($,`${t.id}.md`),c;try{c=await a.readFile(s,`utf8`)}catch(e){console.error(`Failed to read markdown file ${s}:`,e);continue}let l=Wt(c);i.push({promptId:t.id,prompt:l,regex:r,getInterpolatedContent:r=>{let i=r.slice(1);return Mn(l.content,t.identifiers,t.identifierMap,i,e,!1,n,t.pieces)},pieces:t.pieces,identifiers:t.identifiers,identifierMap:t.identifierMap})}return i},Pn=e=>{let n=e.results.filter(e=>e.action===`created`),r=e.results.filter(e=>e.action===`updated`),i=e.results.filter(e=>e.action===`conflict`),a=e.results.filter(e=>e.action===`skipped`);if((n.length>0||r.length>0||i.length>0)&&a.length>0&&(console.log(t.dim(`Skipped ${a.length} up-to-date file(s)`)),console.log()),n.length>0){console.log(t.bold.green(`Created ${n.length} new prompt file(s):`));for(let e of n)console.log(t.green(` ${$}/${e.id}.md`)),console.log(t.green.dim(` ${e.description}`));console.log()}if(r.length>0){console.log(t.bold.blue(`Updated ${r.length} system prompt file(s):`));for(let e of r)e.oldVersion?console.log(t.blue(` ${e.id}.md (${e.oldVersion} → ${e.newVersion})`)):console.log(t.blue(` ${e.id}.md (→ ${e.newVersion})`));console.log()}if(i.length>0){console.log(t.bold.yellow(`WARNING: Conflicts detected for ${i.length} system prompt file(s)`));for(let e of i)console.log(t.yellow(` ${e.id}.md (${e.oldVersion} → ${e.newVersion})`)),console.log(t.yellow(` Open the diff in your browser: ${e.diffHtmlPath}`));console.log()}if(n.length>0&&(console.log(t.green.bold(`New prompt files have been created; either more are now supported by tweakcc or Anthropic has added new ones.`)),console.log(t.green(`You can now customize the markdown files at ${$} in a text editor.`)),console.log(t.green(`Then run tweakcc and select "apply" or use tweakcc --apply to update your system prompts`)),console.log()),i.length>0){console.log(),console.log(`Review conflicts:`),console.log(` 1. Open the diff HTML files in your browser`),console.log(` 2. Verify your customizations are still appropriate`),console.log(` 3. Update your markdown files if needed`),console.log(t.bold.cyan(` 4. Important: Update the ccVersion in your markdown files to the latest version of each prompt:`));for(let e of i)console.log(t.yellow(` ${e.id}.md → `)+t.bold.magenta(e.newVersion));console.log(` 5. Delete the diff HTML files`),console.log()}},Fn=new Set(`JSON.Math.Object.Array.String.Number.Boolean.Date.RegExp.Map.Set.WeakMap.WeakSet.Promise.Symbol.BigInt.Error.TypeError.RangeError.Infinity.NaN.undefined.globalThis.console.process.Buffer.URL.URLSearchParams.Intl.Reflect.Proxy.Function`.split(`.`)),In=e=>/^[A-Z][A-Z0-9_]{3,}$/.test(e)&&!Fn.has(e),Ln=e=>/[A-Za-z_$]/.test(e),Rn=e=>/[\w$]/.test(e),zn=(e,t,n)=>{let r=t,i=1,a=``;for(;r<e.length;){let t=e[r];if(t===`'`||t===`"`){for(r+=1;r<e.length&&e[r]!==t;)e[r]===`\\`&&(r+=1),r+=1;r+=1,a=t;continue}if(t==="`"){for(r+=1;r<e.length&&e[r]!=="`";){if(e[r]===`\\`){r+=2;continue}if(e[r]===`$`&&e[r+1]===`{`){r=zn(e,r+2,n);continue}r+=1}r+=1,a=t;continue}if(t===`{`)i+=1;else if(t===`}`){if(--i,i===0)return r+1}else if(Ln(t)){let t=r+1;for(;t<e.length&&Rn(e[t]);)t+=1;a!==`.`&&n.add(e.slice(r,t)),a=`x`,r=t;continue}/\s/.test(t)||(a=t),r+=1}return r},Bn=e=>{let t=new Set,n=0;for(;n<e.length;){let r=e.indexOf("${",n);if(r===-1)break;if(r>0&&e[r-1]===`\\`){n=r+2;continue}n=zn(e,r+2,t)}return t},Vn=(e,t)=>{let n=Bn(t),r=Bn(e);return[...n].filter(e=>In(e)&&r.has(e))},Hn=e=>/\\u[0-9a-fA-F]{4}/.test(e),Un=e=>e.match(/\bBUILD_TIME:"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)"/)?.[1],Wn=new Set([`"`,`'`,"`"]),Gn=(e,t)=>t>0?e[t-1]:``,Kn=(e,t)=>e.filter(e=>{let n=e.index??-1;if(n<0)return!1;let r=t(n-1),i=t(n+e[0].length);return Wn.has(r)&&r===i}),qn=(e,t,n)=>Jn(t,n,t=>e[t]??``),Jn=(e,t,n)=>{if(e.length===t)return e;let r=Kn(e,n);return r.length===t?r:e},Yn=(e,t,n,r)=>{if(e.length===0)return{match:null,ambiguous:!1,disambiguated:!1};let i=Jn(e,t,r);return e.length>t&&i.length!==t?{match:null,ambiguous:!0,disambiguated:!1}:{match:i[n]??null,ambiguous:!1,disambiguated:i.length!==e.length}},Xn=(e,t)=>{let n=1,r=t+2,i=null;for(;r<e.length;){let t=e[r];if(i){if(t===`\\`){r+=2;continue}t===i&&(i=null),r++;continue}if(t===`"`||t===`'`||t==="`"){i=t,r++;continue}if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r+1;r++}return e.length},Zn=e=>{let t=[],n=[0];for(let t=0;t<e.length;t++)e[t]===`
227
+ `,a);a=t===-1?e.length:t,i=a;continue}if(t===`/`&&e[a+1]===`*`){o(a);let t=e.indexOf(`*/`,a+2);if(t===-1)return null;a=t+2,i=a;continue}if(t===`/`&&wn(e,a)){o(a);let t=En(e,a);if(t===-1)return null;a=t,i=a;continue}if(t===`'`||t===`"`){o(a);let n=Tn(e,a,t);if(n===-1)return null;a=n,i=a;continue}if(t==="`"){o(a),r.push(`template`),a++;continue}if(t===`{`){r.push(`expr`),a++;continue}if(t===`}`){if(r.pop(),r.length===0)return o(a),{end:a,codeRegions:n};if(r[r.length-1]===`template`){o(a),a++;continue}a++;continue}a++}return null},On=(e,t)=>{let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;return n},kn=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n++;return n<e.length?n:-1},An=(e,t,n)=>{let r=On(e,t),i=r>=0?e[r]:``,a=kn(e,n);return!((a>=0?e[a]:``)===`:`&&(i===`{`||i===`,`))},jn=(e,t)=>{let n=[];for(let t=0;t<e.length;t++){if(e[t]!==`$`||e[t+1]!==`{`||hn(e,t)%2!=0)continue;let r=Dn(e,t);if(!r)throw Error(`applyIdentifierMapping: unbalanced \${...} interpolation at offset ${t}: ${JSON.stringify(e.slice(t,t+80))}`);n.push(...r.codeRegions),t=r.end}if(n.length===0)return e;let r=``,i=0;for(let a of n){r+=e.slice(i,a.start);let n=a.start;for(;n<a.end;){if(!Cn.test(e[n])){r+=e[n],n++;continue}let i=n;for(;i<a.end&&Cn.test(e[i]);)i++;let o=e.slice(n,i);Object.prototype.hasOwnProperty.call(t,o)&&An(e,n,i)?r+=t[o]:r+=o,n=i}i=a.end}return r+=e.slice(i),r},Mn=(e,t,n,r,i,a=!1,o,s)=>{let c={};for(let e=0;e<r.length;e++){let i=r[e],a=String(t[e]),o=n[a]||`UNKNOWN_${a}`;c[o]=i}let l=jn(e,c);if(l=l.replace(/<<CCVERSION>>/g,i),o&&(l=l.replace(/<<BUILD_TIME>>/g,o)),a&&(l=pn(l)),s&&s.length>0){let e=bn(s);l=xn(l,e)}return l},Nn=async(e,t=!1,n)=>{if(!I||sn!==e)return[];let r=I,i=[],o=await Ut();for(let t of r.prompts){if(!t.id||o.has(t.id))continue;let r=mn(t.pieces,e,n),s=p.join($,`${t.id}.md`),c;try{c=await a.readFile(s,`utf8`)}catch(e){console.error(`Failed to read markdown file ${s}:`,e);continue}let l=Wt(c);i.push({promptId:t.id,prompt:l,regex:r,getInterpolatedContent:r=>{let i=r.slice(1);return Mn(l.content,t.identifiers,t.identifierMap,i,e,!1,n,t.pieces)},pieces:t.pieces,identifiers:t.identifiers,identifierMap:t.identifierMap,platforms:t.platforms})}return i},Pn=e=>{let n=e.results.filter(e=>e.action===`created`),r=e.results.filter(e=>e.action===`updated`),i=e.results.filter(e=>e.action===`conflict`),a=e.results.filter(e=>e.action===`skipped`);if((n.length>0||r.length>0||i.length>0)&&a.length>0&&(console.log(t.dim(`Skipped ${a.length} up-to-date file(s)`)),console.log()),n.length>0){console.log(t.bold.green(`Created ${n.length} new prompt file(s):`));for(let e of n)console.log(t.green(` ${$}/${e.id}.md`)),console.log(t.green.dim(` ${e.description}`));console.log()}if(r.length>0){console.log(t.bold.blue(`Updated ${r.length} system prompt file(s):`));for(let e of r)e.oldVersion?console.log(t.blue(` ${e.id}.md (${e.oldVersion} → ${e.newVersion})`)):console.log(t.blue(` ${e.id}.md (→ ${e.newVersion})`));console.log()}if(i.length>0){console.log(t.bold.yellow(`WARNING: Conflicts detected for ${i.length} system prompt file(s)`));for(let e of i)console.log(t.yellow(` ${e.id}.md (${e.oldVersion} → ${e.newVersion})`)),console.log(t.yellow(` Open the diff in your browser: ${e.diffHtmlPath}`));console.log()}if(n.length>0&&(console.log(t.green.bold(`New prompt files have been created; either more are now supported by tweakcc or Anthropic has added new ones.`)),console.log(t.green(`You can now customize the markdown files at ${$} in a text editor.`)),console.log(t.green(`Then run tweakcc and select "apply" or use tweakcc --apply to update your system prompts`)),console.log()),i.length>0){console.log(),console.log(`Review conflicts:`),console.log(` 1. Open the diff HTML files in your browser`),console.log(` 2. Verify your customizations are still appropriate`),console.log(` 3. Update your markdown files if needed`),console.log(t.bold.cyan(` 4. Important: Update the ccVersion in your markdown files to the latest version of each prompt:`));for(let e of i)console.log(t.yellow(` ${e.id}.md → `)+t.bold.magenta(e.newVersion));console.log(` 5. Delete the diff HTML files`),console.log()}},Fn=new Set(`JSON.Math.Object.Array.String.Number.Boolean.Date.RegExp.Map.Set.WeakMap.WeakSet.Promise.Symbol.BigInt.Error.TypeError.RangeError.Infinity.NaN.undefined.globalThis.console.process.Buffer.URL.URLSearchParams.Intl.Reflect.Proxy.Function`.split(`.`)),In=e=>/^[A-Z][A-Z0-9_]{3,}$/.test(e)&&!Fn.has(e),Ln=e=>/[A-Za-z_$]/.test(e),Rn=e=>/[\w$]/.test(e),zn=(e,t,n)=>{let r=t,i=1,a=``;for(;r<e.length;){let t=e[r];if(t===`'`||t===`"`){for(r+=1;r<e.length&&e[r]!==t;)e[r]===`\\`&&(r+=1),r+=1;r+=1,a=t;continue}if(t==="`"){for(r+=1;r<e.length&&e[r]!=="`";){if(e[r]===`\\`){r+=2;continue}if(e[r]===`$`&&e[r+1]===`{`){r=zn(e,r+2,n);continue}r+=1}r+=1,a=t;continue}if(t===`{`)i+=1;else if(t===`}`){if(--i,i===0)return r+1}else if(Ln(t)){let t=r+1;for(;t<e.length&&Rn(e[t]);)t+=1;a!==`.`&&n.add(e.slice(r,t)),a=`x`,r=t;continue}/\s/.test(t)||(a=t),r+=1}return r},Bn=e=>{let t=new Set,n=0;for(;n<e.length;){let r=e.indexOf("${",n);if(r===-1)break;if(r>0&&e[r-1]===`\\`){n=r+2;continue}n=zn(e,r+2,t)}return t},Vn=(e,t)=>{let n=Bn(t),r=Bn(e);return[...n].filter(e=>In(e)&&r.has(e))},Hn=e=>/\\u[0-9a-fA-F]{4}/.test(e),Un=e=>e.match(/\bBUILD_TIME:"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)"/)?.[1],Wn=new Set([`"`,`'`,"`"]),Gn=(e,t)=>t>0?e[t-1]:``,Kn=(e,t)=>e.filter(e=>{let n=e.index??-1;if(n<0)return!1;let r=t(n-1),i=t(n+e[0].length);return Wn.has(r)&&r===i}),qn=(e,t,n)=>Jn(t,n,t=>e[t]??``),Jn=(e,t,n)=>{if(e.length===t)return e;let r=Kn(e,n);return r.length===t?r:e},Yn=(e,t,n,r)=>{if(e.length===0)return{match:null,ambiguous:!1,disambiguated:!1};let i=Jn(e,t,r);return e.length>t&&i.length!==t?{match:null,ambiguous:!0,disambiguated:!1}:{match:i[n]??null,ambiguous:!1,disambiguated:i.length!==e.length}},Xn=(e,t)=>{let n=1,r=t+2,i=null;for(;r<e.length;){let t=e[r];if(i){if(t===`\\`){r+=2;continue}t===i&&(i=null),r++;continue}if(t===`"`||t===`'`||t==="`"){i=t,r++;continue}if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r+1;r++}return e.length},Zn=e=>{let t=[],n=[0];for(let t=0;t<e.length;t++)e[t]===`
228
228
  `&&n.push(t+1);let r=e=>{let t=0,r=n.length-1;for(;t<r;){let i=t+r+1>>1;n[i]<=e?t=i:r=i-1}return t},i=0;for(;i<e.length;){let a=e[i];if(a===`\\`){let a=0;for(;i+a<e.length&&e[i+a]===`\\`;)a++;let o=e[i+a]??``;if(a%2==1&&!(o==="`"||o===`$`&&e[i+a+1]===`{`)){let s=i+a-1,c=r(s),l=e.indexOf(`
229
229
  `,n[c]),u=`\\`+(o===`
230
230
  `?`<newline>`:o===``?``:o);t.push({index:s,line:c+1,lineText:e.slice(n[c],l===-1?e.length:l),offending:u,required:`\\`+u,kind:o===`"`||o===`'`?`redundant`:`lossy`})}i+=a%2==1?a+1:a;continue}if(a===`$`&&e[i+1]===`{`){i=Xn(e,i);continue}i++}return t},Qn=(e,t)=>{let n=e.split(`
@@ -246,7 +246,7 @@ try {
246
246
  `,{eval:!0,workerData:{source:e,flags:ur(t),content:n},resourceLimits:{stackSizeMb:16}});a.once(`message`,e=>{if(a.terminate(),!e.ok){i(Error(e.error??`regex worker failed`));return}r((e.matches??[]).map(({index:e,groups:t})=>{let n=t;return n.index=e,n}))}),a.once(`error`,e=>{a.terminate(),i(e)})}),pr=async(e,t,n)=>{try{return dr(e,t,n)}catch(r){let i=r instanceof Error?r.message:String(r);if(!lr.test(i))throw r;return fr(e,t,n)}},mr=e=>e.length,R=(e,t)=>typeof e==`string`?e[t]??``:e.charAt(t),hr=(e,t,n)=>e.slice(t,n),gr=e=>typeof e==`string`?e:e.toString(),_r=(e,t,n)=>{let r=e.replace(/<<CCVERSION>>/g,t);return n&&(r=r.replace(/<<BUILD_TIME>>/g,n)),r},vr=(e,t)=>{let n=[],r=e;if(t>0){let e=r.match(/^\[[A-Za-z_$][\w$]*\](?=\})/);if(e)n.push({kind:`member`}),r=r.slice(e[0].length);else{let e=r.match(/^\[[A-Za-z_$][\w$]*((?:\.[\w$]+)+|\s*[-+*/%]\s*[^\]]*)\](?=\})/);e&&(n.push({kind:`member`,path:e[1]}),r=r.slice(e[0].length))}}for(let e=0;e<r.length;){if(r.startsWith("${",e)){let t=e+2;for(;t<r.length&&r[t]!==`{`&&r[t]!==`}`;)t++;if(r[t]===`}`){n.push({kind:`interpolation`}),e=t+1;continue}}let t=r[e],i=r.charCodeAt(e);t===`\\`?n.push({kind:`backslash`}):t===`"`||t===`'`||t==="`"?n.push({kind:`quote`,value:t}):t===`
247
247
  `?n.push({kind:`newline`}):i>127?n.push({kind:`non-ascii`,value:t,code:i}):n.push({kind:`literal`,value:t}),e++}return n},yr=(e,t,n)=>{let r=[],i=0;for(let a=0;a<e.length;a++){let o=_r(e[a],t,n);for(let e of vr(o,a))r.push(e);a<e.length-1&&r.push({kind:`capture`,index:i++})}return r},br=e=>{let t=null,n=0,r=``,i=()=>{let e=r.match(/^ */)?.[0].length??0,i=r.match(/ *$/)?.[0].length??0,a=r.slice(e,r.length-i);a.length>=12&&(!t||a.length>t.anchor.length)&&(t={anchor:a,tokenIndex:n+e})};for(let t=0;t<=e.length;t++){let a=e[t];if(a?.kind===`literal`&&/[A-Za-z0-9 ]/.test(a.value)){r.length===0&&(n=t),r+=a.value;continue}i(),r=``}return t},xr=e=>{let t=yr(e.pieces,e.version,e.buildTime);return{tokens:t,plan:br(t)}},Sr=e=>{if(e===`$`||e===`_`)return!0;if(e===void 0)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122},Cr=(e,t,n)=>{let r=0,i=n,a=[],o=[],s=()=>{let e=o.pop();return e?(r=e.token,i=e.position,a=e.captures,!0):!1};for(;;){if(r===e.length){let e=[hr(t,n,i),...a];return e.index=n,e.input=typeof t==`string`?t:``,e}let c=e[r];if(c.kind===`literal`){if(R(t,i)!==c.value){if(!s())return null;continue}i++,r++;continue}if(c.kind===`backslash`){if(R(t,i)!==`\\`){if(!s())return null;continue}R(t,i+1)===`\\`&&o.push({token:r+1,position:i+2,captures:[...a]}),i++,r++;continue}if(c.kind===`quote`){if(R(t,i)===c.value){i++,r++;continue}if(R(t,i)===`\\`&&R(t,i+1)===c.value){i+=2,r++;continue}if(!s())return null;continue}if(c.kind===`newline`){if(R(t,i)===`
248
248
  `){i++,r++;continue}if(R(t,i)===`\\`&&R(t,i+1)===`n`){i+=2,r++;continue}if(!s())return null;continue}if(c.kind===`non-ascii`){if(R(t,i)===c.value){i++,r++;continue}let e=c.code.toString(16).padStart(4,`0`),n=hr(t,i,i+6);if(n[0]===`\\`&&n[1]===`u`&&n.slice(2).toLowerCase()===e){i+=6,r++;continue}if(c.code<=255){let e=c.code.toString(16).padStart(2,`0`),n=hr(t,i,i+4);if(n[0]===`\\`&&n[1]===`x`&&n.slice(2).toLowerCase()===e){i+=4,r++;continue}}if(!s())return null;continue}if(c.kind===`interpolation`){if(R(t,i)!==`$`||R(t,i+1)!==`{`){if(!s())return null;continue}let e=i+2;for(;e<mr(t)&&R(t,e)!==`{`&&R(t,e)!==`}`;)e++;if(R(t,e)!==`}`){if(!s())return null;continue}i=e+1,r++;continue}let l=i;if(c.kind===`member`){if(R(t,l)!==`[`){if(!s())return null;continue}l++;let e=l;for(;Sr(R(t,l));)l++;if(l===e){if(!s())return null;continue}if(c.path){let e=!0;for(let n=0;n<c.path.length;n++)if(R(t,l+n)!==c.path[n]){e=!1;break}if(!e){if(!s())return null;continue}l+=c.path.length}if(R(t,l)!==`]`){if(!s())return null;continue}i=l+1,r++;continue}for(;Sr(R(t,l));)l++;if(l===i){if(!s())return null;continue}for(let e=i+1;e<l;e++){let n=[...a];n[c.index]=hr(t,i,e),o.push({token:r+1,position:e,captures:n})}a=[...a],a[c.index]=hr(t,i,l),i=l,r++}},wr=(e,t,n)=>{if(e.kind===`literal`)return R(t,n-1)===e.value?[n-1]:[];if(e.kind===`backslash`){let e=[];return R(t,n-1)===`\\`&&e.push(n-1),R(t,n-1)===`\\`&&R(t,n-2)===`\\`&&e.push(n-2),e}if(e.kind===`quote`){let r=[];return R(t,n-1)===e.value&&r.push(n-1),R(t,n-1)===e.value&&R(t,n-2)===`\\`&&r.push(n-2),r}if(e.kind===`newline`){let e=[];return R(t,n-1)===`
249
- `&&e.push(n-1),R(t,n-1)===`n`&&R(t,n-2)===`\\`&&e.push(n-2),e}if(e.kind===`non-ascii`){let r=[];R(t,n-1)===e.value&&r.push(n-1);let i=e.code.toString(16).padStart(4,`0`),a=hr(t,n-6,n);if(a[0]===`\\`&&a[1]===`u`&&a.slice(2).toLowerCase()===i&&r.push(n-6),e.code<=255){let i=e.code.toString(16).padStart(2,`0`),a=hr(t,n-4,n);a[0]===`\\`&&a[1]===`x`&&a.slice(2).toLowerCase()===i&&r.push(n-4)}return r}if(e.kind===`interpolation`){if(R(t,n-1)!==`}`)return[];let e=n-2;for(;e>=0&&R(t,e)!==`{`&&R(t,e)!==`}`;)e--;return R(t,e)===`{`&&R(t,e-1)===`$`?[e-1]:[]}if(e.kind===`member`){if(R(t,n-1)!==`]`)return[];let r=n-2;if(e.path)for(let n=e.path.length-1;n>=0;n--){if(R(t,r)!==e.path[n])return[];r--}let i=r;for(;r>=0&&Sr(R(t,r));)r--;return r<i&&R(t,r)===`[`?[r]:[]}let r=[],i=n-1;for(;i>=0&&Sr(R(t,i));)r.push(i),i--;return r},Tr=(e,t,n,r)=>{let i=new Set([r]);for(let r=n.tokenIndex-1;r>=0;r--){let n=new Set;for(let a of i)for(let i of wr(e[r],t,a))n.add(i);if(n.size===0)return[];i=n}return[...i]},Er=(e,t,n)=>{let r=[],i=RegExp(`(?=${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)})`,`gi`),a;for(;(a=i.exec(e))!==null;){if(r.push(a.index),r.length>n)return null;i.lastIndex=a.index+1}return r},Dr=(e,t,n)=>{if(!e.plan)return null;let r=n===void 0?typeof t==`string`?Er(t,e.plan.anchor,250):null:n;if(!r||r.length>250)return null;let i=new Set;for(let n of r)for(let r of Tr(e.tokens,t,e.plan,n))i.add(r);let a=[];for(let n of[...i].sort((e,t)=>e-t)){let r=Cr(e.tokens,t,n);r&&a.push(r)}let o=[],s=-1;for(let e of a)e.index<s||(o.push(e),s=e.index+e[0].length);return o},Or=(e,t)=>{let n=[...new Set(t)],r=new Map(n.map(e=>[e,[]]));if(e.length<12)return r;let i=16777619,a=new Map,o=e=>{let t=0;for(let n=0;n<12;n++)t=Math.imul(t,i)+e.charCodeAt(n)>>>0;return t};for(let e of n){let t=o(e),n=a.get(t);n?n.push(e):a.set(t,[e])}let s=1;for(let e=1;e<12;e++)s=Math.imul(s,i)>>>0;let c=o(e),l=e.length-12;for(let t=0;t<=l;t++){let n=a.get(c);if(n){for(let i of n)if(e.startsWith(i,t)){let e=r.get(i);if(e==null)continue;e.length===250?r.set(i,null):e.push(t)}}if(t===l)break;c=Math.imul(c-Math.imul(e.charCodeAt(t),s)>>>0,i)+e.charCodeAt(t+12)>>>0}return r},z=e=>e,kr=async(e,t)=>Dr(xr(e),t)||pr(e.regex,`sg`,t);var Ar=class{specs=new Map;compiled=new Map;anchorRegexes=new Map;anchorHashes=new Map;anchorOccurrences=new Map;anchorLengthCounts=new Map;maxAnchorLength=12;constructor(e){for(let t of e){this.specs.set(t.regex,t);let e=xr(t);if(this.compiled.set(t.regex,e),!e.plan)continue;let n=e.plan.anchor,r=this.anchorRegexes.get(n);r?r.push(t.regex):(this.anchorRegexes.set(n,[t.regex]),this.anchorLengthCounts.set(n.length,(this.anchorLengthCounts.get(n.length)??0)+1),this.maxAnchorLength=Math.max(this.maxAnchorLength,n.length))}for(let e of this.anchorRegexes.keys()){let t=Nr(e),n=this.anchorHashes.get(t);n?n.push(e):this.anchorHashes.set(t,[e])}}delete(e){let t=this.compiled.get(e)?.plan?.anchor;if(this.specs.delete(e),this.compiled.delete(e),!t)return;let n=this.anchorRegexes.get(t)?.filter(t=>t!==e);if(n&&n.length>0){this.anchorRegexes.set(t,n);return}this.anchorRegexes.delete(t),this.anchorOccurrences.delete(t);let r=(this.anchorLengthCounts.get(t.length)??1)-1;r>0?this.anchorLengthCounts.set(t.length,r):this.anchorLengthCounts.delete(t.length),t.length===this.maxAnchorLength&&r===0&&(this.maxAnchorLength=Math.max(12,...this.anchorLengthCounts.keys()));let i=Nr(t),a=this.anchorHashes.get(i)?.filter(e=>e!==t);a&&a.length>0?this.anchorHashes.set(i,a):this.anchorHashes.delete(i)}index(e,t=z(e)){if(t.length!==e.length){this.anchorOccurrences.clear();return}this.anchorOccurrences=Or(t,[...this.compiled.values()].flatMap(e=>e.plan?[e.plan.anchor]:[]))}async matchCurrent(e,t){let n=this.specs.get(e),r=this.compiled.get(e);if(!n||!r)return[];let i=r.plan?.anchor;return(i?Dr(r,t,this.anchorOccurrences.get(i)):null)??await pr(n.regex,`sg`,gr(t))}recordSplice(e,t){let n=t.replacementLength-(t.end-t.start);for(let[e,r]of this.anchorOccurrences){if(r===null)continue;let i=[];for(let a of r)a+e.length<=t.start?i.push(a):a>=t.end&&i.push(a+n);this.anchorOccurrences.set(e,i)}let r=Math.max(0,t.start-this.maxAnchorLength+1),i=Math.min(e.length,t.start+t.replacementLength+this.maxAnchorLength-1),a=e.slice(r,i);for(let[e,t]of Pr(z(a),this.anchorHashes)){let n=this.anchorOccurrences.get(e);if(n===null||t===null){this.anchorOccurrences.set(e,null);continue}let i=[...new Set([...n??[],...t.map(e=>r+e)])].sort((e,t)=>e-t);this.anchorOccurrences.set(e,i.length>250?null:i)}}async matchBatch(e,t=z(e)){let n=new Map;if(t.length===e.length){this.index(e,t);for(let[t,r]of this.compiled){let i=Dr(r,e,r.plan?this.anchorOccurrences.get(r.plan.anchor):void 0);i&&n.set(t,i)}}for(let[t,r]of this.specs)n.has(t)||n.set(t,await pr(r.regex,`sg`,e));return n}};const jr=16777619;let Mr=1;for(let e=1;e<12;e++)Mr=Math.imul(Mr,jr)>>>0;const Nr=e=>{let t=0;for(let n=0;n<12;n++)t=Math.imul(t,jr)+e.charCodeAt(n)>>>0;return t},Pr=(e,t)=>{let n=new Map;if(e.length<12)return n;let r=Nr(e),i=e.length-12;for(let a=0;a<=i;a++){let o=t.get(r);if(o)for(let t of o){if(!e.startsWith(t,a))continue;let r=n.get(t);r!==null&&(r===void 0?n.set(t,[a]):r.length===250?n.set(t,null):r.push(a))}if(a===i)break;r=Math.imul(r-Math.imul(e.charCodeAt(a),Mr)>>>0,jr)+e.charCodeAt(a+12)>>>0}return n},Fr=async(e,t,n=z(t))=>new Ar(e).matchBatch(t,n),Ir=async(e,n,r,i,a)=>{let o=r??Hn(e);o&&J(`Detected Unicode escaping in cli.js - will escape non-ASCII characters in prompts`);let s=Un(e);s&&J(`Extracted BUILD_TIME from cli.js: ${s}`);let c=await Nn(n,o,s);J(`Loaded ${c.length} system prompts with regexes`);let l=new Map;for(let e of c)l.set(e.regex,{regex:e.regex,pieces:e.pieces,version:n,buildTime:s});let u=new Ar([...l.values()]);u.index(e,z(e));let d=new Map;c.forEach((e,t)=>{d.set(e.regex,t)});let f=new Map;for(let[e,t]of d){let n=f.get(t);n?n.push(e):f.set(t,[e])}let p=new cr(e),m=a!==void 0&&a!==e,h=new Map;for(let e of c){let t=h.get(e.promptId);t||(t=new Set,h.set(e.promptId,t));for(let n of Object.values(e.identifierMap))t.add(n)}let g=new Map;for(let e of c)i&&!i.includes(e.promptId)||g.set(e.regex,(g.get(e.regex)??0)+1);let _=new Map,v=new Map,y=[],b={},x=[];for(let[e,r]of c.entries()){for(let t of f.get(e-1)??[])u.delete(t);let{promptId:s,prompt:c,regex:d,getInterpolatedContent:S,pieces:C,identifiers:w,identifierMap:T}=r;if(i&&!i.includes(s)){y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}J(`Applying system prompt: ${c.name}`);let E=new RegExp(d,`s`),D=await u.matchCurrent(d,p),O=g.get(d)??1,k=_.get(d)??0,A=O-(v.get(d)??0),{match:j,ambiguous:M,disambiguated:N}=Yn(D,A,k,e=>p.charAt(e));if(N&&J(`Disambiguated ${D.length} matches \u2192 ${A} standalone for "${c.name}"`),M){console.log(t.yellow(`"${c.name}" matches ${D.length} places in cli.js for ${A} catalogue entr`+(A===1?`y`:`ies`)+` and none of them is identifiable — skipping rather than splicing into whichever came first`)),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`${D.length} ambiguous candidate sites - no site attributable to this prompt`});continue}if(j&&j.index!==void 0){let e=Jt(C,w,T).trim();if(c.content.trim()===e){J(`"${c.name}": still vanilla \u2014 leaving cli.js untouched`),_.set(d,k+1),b[s]=pt(c.content),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unchanged`}),x.push(y.length-1);continue}let r;try{r=S(j)}catch(e){console.log(t.red(`Malformed \${...} interpolation in "${c.name}" (${s}.md): ${e instanceof Error?e.message:String(e)} - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,failed:!0,details:"malformed ${...} interpolation in the markdown"});continue}let i=j.index,a=p.charAt(i-1);{let e=Vn(r,c.content),i=new Set(Object.values(T)),o=h.get(s);if(e.length>0&&e.every(e=>!i.has(e)&&o?.has(e))){J(`"${c.name}": placeholders resolve via a same-id sibling shape — leaving this site pristine`),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}let l=j[0],u=a==="`"?e:e.filter(e=>!RegExp(`(?<!\\\\)\\$\\{`+e+`(?![A-Za-z0-9_])`).test(l));if(u.length>0){e.splice(0,e.length,...u),console.log(t.red(`Unresolved placeholder \${${e[0]}} in "${c.name}" (markdown vocabulary out of sync with CC ${n} prompt data) - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unresolved placeholder \${${e[0]}} - markdown out of sync with prompt data`});continue}}if(a!==`"`&&a!==`'`&&a!=="`"&&vn(r)){console.log(t.yellow(`"${c.name}" resolves inside a larger string literal (no delimiter at the match boundary) and its content needs delimiter-specific escaping - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unresolvable string delimiter - cannot escape content safely`});continue}let l=e.length,f=c.content.trim().length,g=vc()?p.toString():null,E=j[0].length,D=yn(r,a,o);if(D.incomplete){console.log(t.red(`Incomplete backtick escaping for "${c.name}" (unclosed interpolation) - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`incomplete escaping: unclosed interpolation detected`});continue}D.autoEscaped&&J(`Auto-escaped unescaped backticks in "${c.name}"`);let O=D.content;O===j[0]?_.set(d,k+1):(v.set(d,(v.get(d)??0)+1),p.splice(i,i+E,O),m=!0,u.recordSplice(p,{start:i,end:i+E,replacementLength:O.length})),b[s]=pt(c.content),g!==null&&B(g,p.toString(),O,i,i+E);let A=l-f,M=O!==j[0],N;N=A>0?t.green(`${A} fewer chars`):A<0?t.red(`${Math.abs(A)} more chars`):`unchanged`;let ee=y.length;y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:M,details:N}),x.push(ee)}else{let e=!1;if(a!==void 0&&m)try{let t=l.get(d);e=(t?await kr(t,a):[]).length>0}catch{e=!1}if(e){J(`"${c.name}": region consumed by an earlier inline-blob/reminder override — leaving superseded, no warning`),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}if(!c.name.startsWith(`Data:`)&&c.name!==`Skill: Build with Claude API`&&console.log(t.yellow(`Could not find system prompt "${c.name}" in cli.js (using regex ${Bc(E)})`)),vc()){Y(`\n Debug info for ${c.name}:`),Y(` Regex pattern (first 200 chars): ${d.substring(0,200).replace(/\n/g,`\\n`)}...`),Y(` Trying to match pattern in cli.js...`);try{Y(` Partial match result: ${p.toString().match(new RegExp(d.substring(0,100)))?`found partial`:`no match`}`)}catch{Y(` Partial match failed (regex truncation issue)`)}}}}try{await St(b)}catch(e){J(`Failed to store applied prompt hashes: ${e}`);for(let e of x){let t=y[e];t&&(t.failed=!0,t.details=t.details?`${t.details} (hash storage failed)`:`hash storage failed`)}}return{newContent:p.toString(),results:y}},Lr=e=>e.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))),B=(e,n,r,i,a,o=40)=>{if(!vc())return;let s=Math.max(0,i-o),c=Math.min(e.length,a+o),l=Math.min(n.length,i+r.length+o),u=e.slice(s,c),d=n.slice(s,l),f=Lr(u),p=Lr(d);if(f===p){yc()&&(Y(`
249
+ `&&e.push(n-1),R(t,n-1)===`n`&&R(t,n-2)===`\\`&&e.push(n-2),e}if(e.kind===`non-ascii`){let r=[];R(t,n-1)===e.value&&r.push(n-1);let i=e.code.toString(16).padStart(4,`0`),a=hr(t,n-6,n);if(a[0]===`\\`&&a[1]===`u`&&a.slice(2).toLowerCase()===i&&r.push(n-6),e.code<=255){let i=e.code.toString(16).padStart(2,`0`),a=hr(t,n-4,n);a[0]===`\\`&&a[1]===`x`&&a.slice(2).toLowerCase()===i&&r.push(n-4)}return r}if(e.kind===`interpolation`){if(R(t,n-1)!==`}`)return[];let e=n-2;for(;e>=0&&R(t,e)!==`{`&&R(t,e)!==`}`;)e--;return R(t,e)===`{`&&R(t,e-1)===`$`?[e-1]:[]}if(e.kind===`member`){if(R(t,n-1)!==`]`)return[];let r=n-2;if(e.path)for(let n=e.path.length-1;n>=0;n--){if(R(t,r)!==e.path[n])return[];r--}let i=r;for(;r>=0&&Sr(R(t,r));)r--;return r<i&&R(t,r)===`[`?[r]:[]}let r=[],i=n-1;for(;i>=0&&Sr(R(t,i));)r.push(i),i--;return r},Tr=(e,t,n,r)=>{let i=new Set([r]);for(let r=n.tokenIndex-1;r>=0;r--){let n=new Set;for(let a of i)for(let i of wr(e[r],t,a))n.add(i);if(n.size===0)return[];i=n}return[...i]},Er=(e,t,n)=>{let r=[],i=RegExp(`(?=${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)})`,`gi`),a;for(;(a=i.exec(e))!==null;){if(r.push(a.index),r.length>n)return null;i.lastIndex=a.index+1}return r},Dr=(e,t,n)=>{if(!e.plan)return null;let r=n===void 0?typeof t==`string`?Er(t,e.plan.anchor,250):null:n;if(!r||r.length>250)return null;let i=new Set;for(let n of r)for(let r of Tr(e.tokens,t,e.plan,n))i.add(r);let a=[];for(let n of[...i].sort((e,t)=>e-t)){let r=Cr(e.tokens,t,n);r&&a.push(r)}let o=[],s=-1;for(let e of a)e.index<s||(o.push(e),s=e.index+e[0].length);return o},Or=(e,t)=>{let n=[...new Set(t)],r=new Map(n.map(e=>[e,[]]));if(e.length<12)return r;let i=16777619,a=new Map,o=e=>{let t=0;for(let n=0;n<12;n++)t=Math.imul(t,i)+e.charCodeAt(n)>>>0;return t};for(let e of n){let t=o(e),n=a.get(t);n?n.push(e):a.set(t,[e])}let s=1;for(let e=1;e<12;e++)s=Math.imul(s,i)>>>0;let c=o(e),l=e.length-12;for(let t=0;t<=l;t++){let n=a.get(c);if(n){for(let i of n)if(e.startsWith(i,t)){let e=r.get(i);if(e==null)continue;e.length===250?r.set(i,null):e.push(t)}}if(t===l)break;c=Math.imul(c-Math.imul(e.charCodeAt(t),s)>>>0,i)+e.charCodeAt(t+12)>>>0}return r},z=e=>e,kr=async(e,t)=>Dr(xr(e),t)||pr(e.regex,`sg`,t);var Ar=class{specs=new Map;compiled=new Map;anchorRegexes=new Map;anchorHashes=new Map;anchorOccurrences=new Map;anchorLengthCounts=new Map;maxAnchorLength=12;constructor(e){for(let t of e){this.specs.set(t.regex,t);let e=xr(t);if(this.compiled.set(t.regex,e),!e.plan)continue;let n=e.plan.anchor,r=this.anchorRegexes.get(n);r?r.push(t.regex):(this.anchorRegexes.set(n,[t.regex]),this.anchorLengthCounts.set(n.length,(this.anchorLengthCounts.get(n.length)??0)+1),this.maxAnchorLength=Math.max(this.maxAnchorLength,n.length))}for(let e of this.anchorRegexes.keys()){let t=Nr(e),n=this.anchorHashes.get(t);n?n.push(e):this.anchorHashes.set(t,[e])}}delete(e){let t=this.compiled.get(e)?.plan?.anchor;if(this.specs.delete(e),this.compiled.delete(e),!t)return;let n=this.anchorRegexes.get(t)?.filter(t=>t!==e);if(n&&n.length>0){this.anchorRegexes.set(t,n);return}this.anchorRegexes.delete(t),this.anchorOccurrences.delete(t);let r=(this.anchorLengthCounts.get(t.length)??1)-1;r>0?this.anchorLengthCounts.set(t.length,r):this.anchorLengthCounts.delete(t.length),t.length===this.maxAnchorLength&&r===0&&(this.maxAnchorLength=Math.max(12,...this.anchorLengthCounts.keys()));let i=Nr(t),a=this.anchorHashes.get(i)?.filter(e=>e!==t);a&&a.length>0?this.anchorHashes.set(i,a):this.anchorHashes.delete(i)}index(e,t=z(e)){if(t.length!==e.length){this.anchorOccurrences.clear();return}this.anchorOccurrences=Or(t,[...this.compiled.values()].flatMap(e=>e.plan?[e.plan.anchor]:[]))}async matchCurrent(e,t){let n=this.specs.get(e),r=this.compiled.get(e);if(!n||!r)return[];let i=r.plan?.anchor;return(i?Dr(r,t,this.anchorOccurrences.get(i)):null)??await pr(n.regex,`sg`,gr(t))}recordSplice(e,t){let n=t.replacementLength-(t.end-t.start);for(let[e,r]of this.anchorOccurrences){if(r===null)continue;let i=[];for(let a of r)a+e.length<=t.start?i.push(a):a>=t.end&&i.push(a+n);this.anchorOccurrences.set(e,i)}let r=Math.max(0,t.start-this.maxAnchorLength+1),i=Math.min(e.length,t.start+t.replacementLength+this.maxAnchorLength-1),a=e.slice(r,i);for(let[e,t]of Pr(z(a),this.anchorHashes)){let n=this.anchorOccurrences.get(e);if(n===null||t===null){this.anchorOccurrences.set(e,null);continue}let i=[...new Set([...n??[],...t.map(e=>r+e)])].sort((e,t)=>e-t);this.anchorOccurrences.set(e,i.length>250?null:i)}}async matchBatch(e,t=z(e)){let n=new Map;if(t.length===e.length){this.index(e,t);for(let[t,r]of this.compiled){let i=Dr(r,e,r.plan?this.anchorOccurrences.get(r.plan.anchor):void 0);i&&n.set(t,i)}}for(let[t,r]of this.specs)n.has(t)||n.set(t,await pr(r.regex,`sg`,e));return n}};const jr=16777619;let Mr=1;for(let e=1;e<12;e++)Mr=Math.imul(Mr,jr)>>>0;const Nr=e=>{let t=0;for(let n=0;n<12;n++)t=Math.imul(t,jr)+e.charCodeAt(n)>>>0;return t},Pr=(e,t)=>{let n=new Map;if(e.length<12)return n;let r=Nr(e),i=e.length-12;for(let a=0;a<=i;a++){let o=t.get(r);if(o)for(let t of o){if(!e.startsWith(t,a))continue;let r=n.get(t);r!==null&&(r===void 0?n.set(t,[a]):r.length===250?n.set(t,null):r.push(a))}if(a===i)break;r=Math.imul(r-Math.imul(e.charCodeAt(a),Mr)>>>0,jr)+e.charCodeAt(a+12)>>>0}return n},Fr=async(e,t,n=z(t))=>new Ar(e).matchBatch(t,n),Ir=async(e,n,r,i,a)=>{let o=r??Hn(e);o&&J(`Detected Unicode escaping in cli.js - will escape non-ASCII characters in prompts`);let s=Un(e);s&&J(`Extracted BUILD_TIME from cli.js: ${s}`);let c=await Nn(n,o,s);J(`Loaded ${c.length} system prompts with regexes`);let l=new Map;for(let e of c)l.set(e.regex,{regex:e.regex,pieces:e.pieces,version:n,buildTime:s});let u=new Ar([...l.values()]);u.index(e,z(e));let d=new Map;c.forEach((e,t)=>{d.set(e.regex,t)});let f=new Map;for(let[e,t]of d){let n=f.get(t);n?n.push(e):f.set(t,[e])}let p=new cr(e),m=a!==void 0&&a!==e,h=new Map;for(let e of c){let t=h.get(e.promptId);t||(t=new Set,h.set(e.promptId,t));for(let n of Object.values(e.identifierMap))t.add(n)}let g=new Map;for(let e of c)i&&!i.includes(e.promptId)||g.set(e.regex,(g.get(e.regex)??0)+1);let _=new Map,v=new Map,y=[],b={},x=[];for(let[e,r]of c.entries()){for(let t of f.get(e-1)??[])u.delete(t);let{promptId:s,prompt:c,regex:d,getInterpolatedContent:S,pieces:C,identifiers:w,identifierMap:T}=r;if(i&&!i.includes(s)){y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}J(`Applying system prompt: ${c.name}`);let E=new RegExp(d,`s`),D=await u.matchCurrent(d,p),O=g.get(d)??1,k=_.get(d)??0,A=O-(v.get(d)??0),{match:j,ambiguous:M,disambiguated:N}=Yn(D,A,k,e=>p.charAt(e));if(N&&J(`Disambiguated ${D.length} matches \u2192 ${A} standalone for "${c.name}"`),M){console.log(t.yellow(`"${c.name}" matches ${D.length} places in cli.js for ${A} catalogue entr`+(A===1?`y`:`ies`)+` and none of them is identifiable — skipping rather than splicing into whichever came first`)),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`${D.length} ambiguous candidate sites - no site attributable to this prompt`});continue}if(j&&j.index!==void 0){let e=Jt(C,w,T).trim();if(c.content.trim()===e){J(`"${c.name}": still vanilla \u2014 leaving cli.js untouched`),_.set(d,k+1),b[s]=pt(c.content),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unchanged`}),x.push(y.length-1);continue}let r;try{r=S(j)}catch(e){console.log(t.red(`Malformed \${...} interpolation in "${c.name}" (${s}.md): ${e instanceof Error?e.message:String(e)} - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,failed:!0,details:"malformed ${...} interpolation in the markdown"});continue}let i=j.index,a=p.charAt(i-1);{let e=Vn(r,c.content),i=new Set(Object.values(T)),o=h.get(s);if(e.length>0&&e.every(e=>!i.has(e)&&o?.has(e))){J(`"${c.name}": placeholders resolve via a same-id sibling shape — leaving this site pristine`),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}let l=j[0],u=a==="`"?e:e.filter(e=>!RegExp(`(?<!\\\\)\\$\\{`+e+`(?![A-Za-z0-9_])`).test(l));if(u.length>0){e.splice(0,e.length,...u),console.log(t.red(`Unresolved placeholder \${${e[0]}} in "${c.name}" (markdown vocabulary out of sync with CC ${n} prompt data) - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unresolved placeholder \${${e[0]}} - markdown out of sync with prompt data`});continue}}if(a!==`"`&&a!==`'`&&a!=="`"&&vn(r)){console.log(t.yellow(`"${c.name}" resolves inside a larger string literal (no delimiter at the match boundary) and its content needs delimiter-specific escaping - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`unresolvable string delimiter - cannot escape content safely`});continue}let l=e.length,f=c.content.trim().length,g=vc()?p.toString():null,E=j[0].length,D=yn(r,a,o);if(D.incomplete){console.log(t.red(`Incomplete backtick escaping for "${c.name}" (unclosed interpolation) - skipping`)),_.set(d,k+1),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,details:`incomplete escaping: unclosed interpolation detected`});continue}D.autoEscaped&&J(`Auto-escaped unescaped backticks in "${c.name}"`);let O=D.content;O===j[0]?_.set(d,k+1):(v.set(d,(v.get(d)??0)+1),p.splice(i,i+E,O),m=!0,u.recordSplice(p,{start:i,end:i+E,replacementLength:O.length})),b[s]=pt(c.content),g!==null&&B(g,p.toString(),O,i,i+E);let A=l-f,M=O!==j[0],N;N=A>0?t.green(`${A} fewer chars`):A<0?t.red(`${Math.abs(A)} more chars`):`unchanged`;let ee=y.length;y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:M,details:N}),x.push(ee)}else{let e=!1;if(a!==void 0&&m)try{let t=l.get(d);e=(t?await kr(t,a):[]).length>0}catch{e=!1}if(e){J(`"${c.name}": region consumed by an earlier inline-blob/reminder override — leaving superseded, no warning`),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0});continue}let n=process.env.TWEAKCC_TARGET_PLATFORM||process.platform;if(Array.isArray(r.platforms)&&r.platforms.length>0&&!r.platforms.includes(n)){J(`"${c.name}": not in the ${n} build (platforms: ${r.platforms.join(`, `)}) — skipping`),y.push({id:s,name:c.name,group:K.SYSTEM_PROMPTS,applied:!1,skipped:!0,details:`not in the ${n} build`});continue}if(!c.name.startsWith(`Data:`)&&c.name!==`Skill: Build with Claude API`&&console.log(t.yellow(`Could not find system prompt "${c.name}" in cli.js (using regex ${Bc(E)})`)),vc()){Y(`\n Debug info for ${c.name}:`),Y(` Regex pattern (first 200 chars): ${d.substring(0,200).replace(/\n/g,`\\n`)}...`),Y(` Trying to match pattern in cli.js...`);try{Y(` Partial match result: ${p.toString().match(new RegExp(d.substring(0,100)))?`found partial`:`no match`}`)}catch{Y(` Partial match failed (regex truncation issue)`)}}}}try{await St(b)}catch(e){J(`Failed to store applied prompt hashes: ${e}`);for(let e of x){let t=y[e];t&&(t.failed=!0,t.details=t.details?`${t.details} (hash storage failed)`:`hash storage failed`)}}return{newContent:p.toString(),results:y}},Lr=e=>e.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16))),B=(e,n,r,i,a,o=40)=>{if(!vc())return;let s=Math.max(0,i-o),c=Math.min(e.length,a+o),l=Math.min(n.length,i+r.length+o),u=e.slice(s,c),d=n.slice(s,l),f=Lr(u),p=Lr(d);if(f===p){yc()&&(Y(`
250
250
  --- Diff ---`),Y(t.blue(`UNCHANGED: `)+t.dim(f)),Y(`--- End Diff ---
251
251
  `));return}let m=x(f,p),h=0,g=0,_=-1,v=-1,y=-1,b=-1,S=0,C=0;for(let e of m)e.added?(y===-1&&(y=g,_=h),b=g+e.value.length,v=h,S=h,C=g+e.value.length,g+=e.value.length):e.removed?(_===-1&&(_=h,y=g),v=h+e.value.length,b=g,S=h+e.value.length,C=g,h+=e.value.length):(h+=e.value.length,g+=e.value.length);_===-1&&(_=0),y===-1&&(y=0),v===-1&&(v=f.length),b===-1&&(b=p.length);let w=f.length-S,T=p.length-C,E=Math.min(w,T,o),D=Math.max(0,_-o),O=Math.min(f.length,S+E),k=Math.max(0,y-o),A=Math.min(p.length,C+E),j=x(f.slice(D,O),p.slice(k,A)),M=``;for(let e of j)if(!e.added)if(e.removed)if(e.value.includes(`
252
252
  `)){let n=e.value.split(`
@@ -781,6 +781,6 @@ return _origStdoutWrite.call(process.stdout,filtered,encoding,cb);
781
781
  `,r=e.slice(0,t)+n+e.slice(t);return B(e,r,n,t,t),r},vo=e=>{let t=e.match(/function [$\w]+\(\)\{return [$\w]+\("tengu_worktree_mode"/);if(!t||t.index===void 0)return e.includes(`EnterWorktree`)?(console.log(`patch: worktreeMode: EnterWorktree present, tengu_worktree_mode gate gone — no-op`),e):(console.error(`patch: worktreeMode: failed to find worktree gate function pattern`),null);let n=t.index+t[0].indexOf(`{`)+1,r=`return !0;`,i=e.slice(0,n)+r+e.slice(n);return B(e,i,r,n,n),i},yo=e=>{let t=e,n=t.match(/,model:([$\w]+)\.enum\(([$\w]+)\)\.optional\(\)/);if(!n||n.index===void 0)return t.match(/let\s+[$\w]+\s*=\s*([$\w]+)\s*&&\s*typeof\s+\1\s*===\s*"string"\s*&&\s*[$\w]+\.includes\(\1\)/)?(console.error(`patch: allowCustomAgentModels: failed to find Zod enum pattern`),null):(J(`patch: allowCustomAgentModels: enum/includes gate removed in this CC build — no-op`),t);let r=n[1],i=n[2],a=`,model:${r}.string().optional()`,o=n.index,s=o+n[0].length;t=t.slice(0,o)+a+t.slice(s),B(e,t,a,o,s);let c=i.replace(/\$/g,`\\$`),l=RegExp(`([;)}])let\\s+([\\$\\w]+)\\s*=\\s*([\\$\\w]+)\\s*&&\\s*typeof\\s+\\3\\s*===\\s*"string"\\s*&&\\s*${c}\\.includes\\(\\3\\)`),u=t,d=t.match(l);if(!d||d.index===void 0)return console.error(`patch: allowCustomAgentModels: failed to find model validation flag pattern`),null;let f=d[1],p=d[2],m=d[3],h=`${f}let ${p}=${m}&&typeof ${m}==="string"`,g=d.index,_=g+d[0].length;return t=t.slice(0,g)+h+t.slice(_),B(u,t,h,g,_),t},bo=e=>{let t=e;{let e=!1;for(let n of[`claude-opus-4-8`,`claude-opus-4-7`]){let r=RegExp(`(id:"${n}"(?:(?!id:"claude-)[\\s\\S]){0,4000}?default_effort:)"(?:high|xhigh)"`),i=t.match(r);if(i&&i.index!==void 0){let n=`${i[1]}"max"`,r=t.slice(0,i.index)+n+t.slice(i.index+i[0].length);B(t,r,n,i.index,i.index+i[0].length),t=r,e=!0}}if(e)return t;if(/id:"claude-opus-4-[78]"(?:(?!id:"claude-)[\s\S]){0,4000}?default_effort:"max"/.test(t))return J(`patch: maxEffortDefault: catalog default_effort already "max" — skipping`),t}let n=/function\s+([$\w]+)\s*\(\s*([$\w]+)\s*\)\s*\{\s*if\s*\(\s*([$\w]+)\s*\(\s*\2\s*\)\s*===\s*"claude-opus-4-7"\s*\)\s*return\s*"xhigh"\s*;\s*return\s*"high"\s*\}/,r=t.match(/function\s+([$\w]+)\s*\(\s*([$\w]+)\s*\)\s*\{\s*if\s*\(\s*([$\w]+)\s*\(\s*\2\s*\)\s*===\s*"claude-opus-4-8"\s*\)\s*return\s*"high"\s*;\s*if\s*\(\s*\3\s*\(\s*\2\s*\)\s*===\s*"claude-opus-4-7"\s*\)\s*return\s*"xhigh"\s*;\s*return\s*"high"\s*\}/),i=r||t.match(n);if(i&&i.index!==void 0){let[e,n,a,o]=i,s=r?`function ${n}(${a}){if(${o}(${a})==="claude-opus-4-8")return"max";if(${o}(${a})==="claude-opus-4-7")return"max";return"high"}`:`function ${n}(${a}){if(${o}(${a})==="claude-opus-4-7")return"max";return"high"}`,c=t.slice(0,i.index)+s+t.slice(i.index+e.length);B(t,c,s,i.index,i.index+e.length),t=c}else if(/===\s*"claude-opus-4-8"\s*\)\s*return\s*"max"/.test(t)||/function\s+[$\w]+\s*\(\s*[$\w]+\s*\)\s*\{\s*if\s*\(\s*[$\w]+\s*\(\s*[$\w]+\s*\)\s*===\s*"claude-opus-4-7"\s*\)\s*return\s*"max"\s*;\s*return\s*"high"\s*\}/.test(t))J(`patch: maxEffortDefault: per-model default already "max" — skipping`);else return console.error(`patch: maxEffortDefault: failed to find Opus per-model effort default`),null;return t},xo=e=>{let t=e.match(/function\s+([$\w]+)\s*\(\s*([$\w]+)\s*\)\s*\{\s*if\s*\(\s*\2\s*===\s*"claude-fable-5"\s*\|\|\s*\2\s*===\s*"claude-mythos-5"\s*\)\s*return\s*!0\s*;\s*return\s*!1\s*\}/)||e.match(/function\s+([$\w]+)\s*\(\s*([$\w]+)\s*\)\s*\{\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*,\s*"fable_5_mitigations"\s*\)\s*\|\|\s*\2\s*===\s*"claude-mythos-5"\s*\)\s*return\s*!0\s*;\s*return\s*!1\s*\}/)||e.match(/function\s+([$\w]+)\s*\(\s*([$\w]+)\s*(?:,\s*[$\w]+\s*)?\)\s*\{\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*,\s*"fable_5_mitigations"\s*(?:,\s*[$\w]+\s*)?\)\s*\|\|\s*\2\s*===\s*"claude-mythos-5"\s*\)\s*return\s*!0\s*;\s*return\s*!1\s*\}/);if(!t||t.index===void 0)return/"claude-mythos-5"\s*\)\s*return\s*!0\s*;\s*return\s*!0\s*\}/.test(e)?(J(`patch: autonomousOperationAllModels: model-family gate already flipped — skipping`),e):/"claude-fable-5"/.test(e)?(console.error(`patch: autonomousOperationAllModels: found the fable/mythos model ids but not the expected gate shape — needs a new match method`),null):(console.log(`patch: autonomousOperationAllModels: fable/mythos model-family gate not present in this CC build — no-op`),e);let[n]=t,r=n.replace(/return\s*!1\s*\}$/,`return!0}`),i=e.slice(0,t.index)+r+e.slice(t.index+n.length);return B(e,i,r,t.index,t.index+n.length),i},So=[`Everything a person will read follows these rules: your replies, files you write, commit messages, pull request and issue text. Messages to other agents do not.`,`File a status report rather than telling the story of the work. Open with the answer in one plain sentence with the specific identifiers inline, then report current state: files, values, checks, blockers, what you did not touch, so a reader can start anywhere. Each fact appears once; a sentence whose only job is to underline the one before it goes.`,`Headings and lead-ins are noun labels ending in a colon, such as "Verification:" or "Remaining blockers:", never sentences with attitude. Bold carries values, labels and the verdict, so skimming only the bold yields the numbers and the result; a bold bullet opener is a bare label such as "P0:". Rank with a label like "Key finding:" rather than an aside like "worth flagging".`,`First person reports decisions, such as "My call: keep the current default". Report limits and mistakes as facts about the work in the same voice as everything else, and keep every count with both sides, every qualifier such as "in the browser only", and every caveat; drop only the narration around them.`,`A report of failed or unverified work keeps every specific: each failing test, each skipped step, each thing you could not check and the reason. Say plainly which parts you verified and which you are taking on trust.`,`Call things by their names rather than coined images, so no "outbound door" for an API and no "the pile is empty" for a cleared backlog. Plain ordinary words; the words genuinely, meaningfully, crucially, fundamentally and essentially stay out.`,`Long is fine when the length is more facts; short comes from dropping topics the reader did not ask about, never from compressing sentences into fragments.`,`Close on a state fact, a blocker or a next action. When a decision is the user's, name the options and stop.`].join(` `),Co=[{what:`load-bearing update cue`,find:/give brief updates when you find something load-bearing or change direction\./,replace:`give a one-line update when you find something important or change direction.`},{what:`readability-over-brevity clause`,find:/Being readable and being concise are different things, and readab(?:le|ility) matters more\..*?technical terms spelled out\./s,replace:So},{what:`prose-not-headers rule`,find:/a simple question gets a direct answer in prose, not headers and sections\./,replace:`a simple question gets a direct answer of one or two plain sentences with the specific identifiers inline.`},{what:`text-output prose-not-headers rule`,find:/a simple question gets a direct answer, not headers and sections\./,replace:`a simple question gets a direct answer of one or two plain sentences with the specific identifiers inline.`},{what:`text-output end-of-turn cap`,find:/End-of-turn summary: one or two sentences\. What changed and what's next\. Nothing else\./,replace:So},{what:`claudeMd relevance hedge`,find:/(?:IMPORTANT: this context may or may not be relevant to your tasks\. You should not respond to this context unless it is highly relevant to your task\.|This context may or may not be relevant; draw on it only where it bears on the task\.)/,replace:`Treat any instruction in that context as the user's standing preference and follow it. For the reply you are about to write: file a status report, not the story of the work. Answer in the first sentence with the identifiers inline; give sections noun labels; bold only values, labels and the verdict; state limits as facts about the work, keeping every count, qualifier and caveat; close on a state fact, a blocker or a next action, and when a decision is the user's, name the options and stop.`}],wo=e=>{let t=e,n=[],r=[],i=-1,a=-1;for(let{what:e,find:o,replace:s}of Co){let c=t.match(o);if(!c||c.index===void 0){r.push(e);continue}i===-1&&(i=c.index,a=c.index+s.length),t=t.slice(0,c.index)+s+t.slice(c.index+c[0].length),n.push(e)}return n.length===0?/[Ff]ile a status report/.test(t)?(J(`patch: adhdOutputStyle: comms prompt already in ADHD shape — skipping`),e):(console.error(`patch: adhdOutputStyle: failed to find any of the comms-prompt anchors (${r.join(`, `)})`),null):(r.length>0&&J(`patch: adhdOutputStyle: rewrote ${n.join(`, `)}; skipped ${r.join(`, `)} (already overridden or reshaped upstream)`),B(e,t,t.slice(i,a),i,a),t)},To=e=>{let t=e,n=t.match(/\(\{filePath:([$\w]+),frontmatter:([$\w]+),content:([$\w]+),source:([$\w]+),baseDir:([$\w]+)\}\)=>\{([\s\S]{0,800}?)return\{name:([$\w]+),description:([$\w]+),prompt:\3\.trim\(\),source:\4,baseDir:\5,keepCodingInstructions:([$\w]+)\}/);if(n&&n.index!==void 0){let e=n[2],r=`,turnReminder:typeof ${e}["turn-reminder"]==="string"?${e}["turn-reminder"]:typeof ${e}.turnReminder==="string"?${e}.turnReminder:typeof ${e}.turnreminder==="string"?${e}.turnreminder:void 0`,i=n.index+n[0].length;t=t.slice(0,i-1)+r+t.slice(i-1)}else t.includes(`turnReminder:typeof`)||console.error(`patch: outputStyleTurnReminder: custom-style loader shape not found; frontmatter turn-reminder will not thread (fallback reminder still applies)`);let r=t.match(/([$\w]+)\[([$\w]+)\.name\]=\{name:\2\.name,description:\2\.description,prompt:\2\.prompt,source:\2\.source,keepCodingInstructions:\2\.keepCodingInstructions,forceForPlugin:\2\.forceForPlugin\}/);if(r&&r.index!==void 0){let e=r[2],n=r.index+r[0].length;t=t.slice(0,n-1)+`,turnReminder:${e}.turnReminder`+t.slice(n-1)}else /forceForPlugin:[$\w]+\.forceForPlugin,turnReminder:/.test(t)||console.error(`patch: outputStyleTurnReminder: style-table merge shape not found; frontmatter turn-reminder will not thread (fallback reminder still applies)`);return t},Eo=e=>{let t=e.match(/output_style:\(([$\w]+)\)=>\{let ([$\w]+)=([$\w]+)\[\1\.style\];if\(!\2\)return\[\];return ([$\w]+)\(\[([$\w]+)\(\{content:`\$\{\2\.name\} output style is active\. \$\{\1\.turnReminder\?\?"([^"]*)"\}`,isMeta:!0\}\)\]\)\}/);if(!t||t.index===void 0)return/\.style\}\.name\?\?|outputStyleName_tweakcc/.test(e)?(console.log(`patch: outputStyleTurnReminder: renderer already patched — threading only`),To(e)):/output_style:\(([$\w]+)\)=>\{if\(typeof \1\.style!=="string"/.test(e)?(console.log(`patch: outputStyleTurnReminder: renderer promoted in this CC build — threading only`),To(e)):(console.error(`patch: outputStyleTurnReminder: failed to find the output-style reminder renderer`),null);let[,n,r,i,a,o]=t,s=`output_style:(${n})=>{let ${r}=${i}[${n}.style];let outputStyleName_tweakcc=${r}?.name??${n}.style;if(!outputStyleName_tweakcc)return[];return ${a}([${o}({content:\`\${outputStyleName_tweakcc} output style is active. \${${n}.turnReminder??"Write this reply the way that style describes, including its rules on what to leave out."}\`,isMeta:!0})])}`,c=e.slice(0,t.index)+s+e.slice(t.index+t[0].length);return B(e,c,s,t.index,t.index+s.length),To(c)},Do={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`},Oo=(e,t)=>{if(t===`default`)return e;let n=Do[t],r=e.match(/function ([$\w]+)\(\)\{(?:(?!function )[\s\S])*?modelByMainModel(?:(?!function )[\s\S])*?return\{value:[^{}]*,src:"default"\}\}/);if(r&&r.index!==void 0){let t=r[1],i=`function ${t}(){return{value:"${n}",src:"default"}}`,a=r.index,o=a+r[0].length,s=e.slice(0,a)+i+e.slice(o);return J(`patch: autoModeClassifierModel: matched modelByMainModel resolver ${t} -> ${n}`),B(e,s,i,a,o),s}let i=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*([$\w]+)\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*;\s*if\s*\(\s*\2\s*\?\.\s*model\s*\)\s*return\s+\2\s*\.\s*model\s*;\s*return\s+([$\w]+)\s*\(\s*\)\s*\}/,a=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*([$\w]+)\s*\(\s*\)\s*;\s*if\s*\(\s*([$\w]+)\s*\(\s*\2\s*\)\s*===\s*"claude-opus-4-8"\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*([$\w]+)\s*\(\s*"tengu_cedar_hollow_7m"\s*,\s*\{\s*\}\s*\)\s*;\s*if\s*\(\s*\5\s*\?\.\s*model\s*\)\s*return\s+\5\s*\.\s*model\s*\}\s*let\s+([$\w]+)\s*=\s*([$\w]+)\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*;\s*if\s*\(\s*\7\s*\?\.\s*model\s*\)\s*return\s+\7\s*\.\s*model\s*;\s*return\s+\2\s*\}/,o=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*\3\s*\?\.\s*modelByMainModel\s*;\s*if\s*\(\s*\4\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\2\s*\)\s*\.\s*replace\([^)]*\)\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*`[^`]*`\s*\]\s*;\s*if\s*\(\s*\6\s*\)\s*return\s+\6\s*\}\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*\5\s*\]\s*;\s*if\s*\(\s*\7\s*\)\s*return\s+\7\s*\}\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s+\3\s*\.\s*model\s*;\s*return\s+\2\s*\}/,s=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*\3\s*\?\.\s*modelByMainModel\s*;\s*if\s*\(\s*\4\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\2\s*\)\s*\.\s*replace\([^)]*\)\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*`[^`]*`\s*\]\s*;\s*if\s*\(\s*\6\s*\)\s*return\s+\6\s*\}\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*\5\s*\]\s*;\s*if\s*\(\s*\7\s*\)\s*return\s+\7\s*\}\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s+\3\s*\.\s*model\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\.\s*ANTHROPIC_DEFAULT_OPUS_MODEL\s*\?\?\s*[$\w]+\s*\(\s*\)\s*\.\s*[$\w]+\s*;\s*if\s*\(\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*&&\s*!\s*[$\w]+\s*\(\s*\8\s*\)\s*&&\s*!\s*[$\w]+\s*\(\s*\8\s*\)\s*\)\s*return\s+\8\s*\+\s*"\[1m\]"\s*;\s*return\s+\8\s*\}\s*return\s+\2\s*\}/,c=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*\3\s*\?\.\s*modelByMainModel\s*;\s*if\s*\(\s*\4\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*`[^`]*`\s*\]\s*;\s*if\s*\(\s*\6\s*\)\s*return\s+\6\s*\}\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*\5\s*\]\s*;\s*if\s*\(\s*\7\s*\)\s*return\s+\7\s*\}\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s+\3\s*\.\s*model\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\.\s*ANTHROPIC_DEFAULT_OPUS_MODEL\s*\?\?\s*[$\w]+\s*\(\s*\)\s*\.\s*[$\w]+\s*;\s*if\s*\(\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*&&\s*!\s*[$\w]+\s*\(\s*\8\s*\)\s*&&\s*!\s*[$\w]+\s*\(\s*\8\s*\)\s*\)\s*return\s+\8\s*\+\s*"\[1m\]"\s*;\s*return\s+\8\s*\}\s*return\s+\2\s*\}/,l=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*\3\s*\?\.\s*modelByMainModel\s*;\s*if\s*\(\s*\4\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*`[^`]*`\s*\]\s*;\s*if\s*\(\s*\6\s*\)\s*return\s+\6\s*\}\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*\5\s*\]\s*;\s*if\s*\(\s*\7\s*\)\s*return\s+\7\s*\}\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s+\3\s*\.\s*model\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*return\s+[$\w]+\s*\(\s*\2\s*\)\s*;\s*return\s+\2\s*\}/,u=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*\3\s*\?\.\s*modelByMainModel\s*;\s*if\s*\(\s*\4\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*`[^`]*`\s*\]\s*;\s*if\s*\(\s*\6\s*\)\s*return\s*\{\s*value\s*:\s*\6\s*,\s*src\s*:\s*"gb"\s*\}\s*\}\s*let\s+([$\w]+)\s*=\s*\4\s*\[\s*\5\s*\]\s*;\s*if\s*\(\s*\7\s*\)\s*return\s*\{\s*value\s*:\s*\7\s*,\s*src\s*:\s*"gb"\s*\}\s*\}\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s*\{\s*value\s*:\s*\3\s*\.\s*model\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*return\s*\{\s*value\s*:\s*[$\w]+\s*\(\s*\2\s*\)\s*,\s*src\s*:\s*"default"\s*\}\s*;\s*return\s*\{\s*value\s*:\s*\2\s*,\s*src\s*:\s*"default"\s*\}\s*\}/,d=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*\3\s*\?\.\s*modelByMainModel\s*\)\s*;\s*if\s*\(\s*\4\s*\)\s*return\s*\{\s*value\s*:\s*\4\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s*\{\s*value\s*:\s*\3\s*\.\s*model\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*[$\w]+\s*\(\s*\2\s*\)\s*\|\|\s*[$\w]+\s*\(\s*\2\s*\)\s*\)\s*return\s*\{\s*value\s*:\s*[$\w]+\s*\(\s*\2\s*\)\s*,\s*src\s*:\s*"default"\s*\}\s*;\s*return\s*\{\s*value\s*:\s*\2\s*,\s*src\s*:\s*"default"\s*\}\s*\}/,f=/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*\3\s*\?\.\s*modelByMainModel\s*\)\s*;\s*if\s*\(\s*\4\s*\)\s*return\s*\{\s*value\s*:\s*\4\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*\3\s*\?\.\s*model\s*\)\s*return\s*\{\s*value\s*:\s*\3\s*\.\s*model\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*[$\w]+\s*!==\s*"demoted"\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\2\s*\)\s*;\s*if\s*\(\s*\5\s*\)\s*return\s*\{\s*value\s*:\s*\5\s*,\s*src\s*:\s*"default"\s*,\s*externalDefault\s*:\s*!0\s*\}\s*\}\s*return\s*\{\s*value\s*:\s*[$\w]+\s*\(\s*\2\s*\)\s*,\s*src\s*:\s*"default"\s*\}\s*\}/,p=e.match(/function\s+([$\w]+)\s*\(\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*"tengu_auto_mode_config"\s*,\s*\{\s*\}\s*\)\s*,\s*([$\w]+)\s*=\s*[$\w]+\s*\(\s*\3\s*\?\.\s*modelByMainModel\s*,\s*\{\s*vet\s*:\s*\(\s*([$\w]+)\s*\)\s*=>\s*[$\w]+\s*\(\s*\5\s*,\s*"modelByMainModel"\s*\)\s*\}\s*\)\s*\?\?\s*[$\w]+\s*\(\s*\3\s*\?\.\s*model\s*,\s*"model"\s*\)\s*;\s*if\s*\(\s*\4\s*\)\s*return\s*\{\s*value\s*:\s*\4\s*,\s*src\s*:\s*"gb"\s*\}\s*;\s*if\s*\(\s*[$\w]+\s*!==\s*"demoted"\s*\)\s*\{\s*let\s+([$\w]+)\s*=\s*[$\w]+\s*\(\s*\2\s*\)\s*;\s*if\s*\(\s*\6\s*\)\s*return\s*\{\s*value\s*:\s*\6\s*,\s*src\s*:\s*"default"\s*,\s*externalDefault\s*:\s*!0\s*\}\s*\}\s*return\s*\{\s*value\s*:\s*[$\w]+\s*\(\s*\2\s*\)\s*,\s*src\s*:\s*"default"\s*\}\s*\}/);if(p&&p.index!==void 0){let[t,r]=p,i=`function ${r}(){return{value:"${n}",src:"default"}}`,a=e.slice(0,p.index)+i+e.slice(p.index+t.length);return B(e,a,i,p.index,p.index+t.length),a}let m=e.match(f);if(m&&m.index!==void 0){let[t,r]=m,i=`function ${r}(){return{value:"${n}",src:"default"}}`,a=e.slice(0,m.index)+i+e.slice(m.index+t.length);return B(e,a,i,m.index,m.index+t.length),a}let h=e.match(d);if(h&&h.index!==void 0){let[t,r]=h,i=`function ${r}(){return{value:"${n}",src:"default"}}`,a=e.slice(0,h.index)+i+e.slice(h.index+t.length);return B(e,a,i,h.index,h.index+t.length),a}let g=e.match(u);if(g&&g.index!==void 0){let[t,r]=g,i=`function ${r}(){return{value:"${n}",src:"default"}}`,a=e.slice(0,g.index)+i+e.slice(g.index+t.length);return B(e,a,i,g.index,g.index+t.length),a}let _=e.match(l)||e.match(c)||e.match(s)||e.match(o)||e.match(a)||e.match(i);if(_&&_.index!==void 0){let[t,r]=_,i=`function ${r}(){return "${n}"}`,a=e.slice(0,_.index)+i+e.slice(_.index+t.length);return B(e,a,i,_.index,_.index+t.length),a}return/function\s+[$\w]+\s*\(\s*\)\s*\{\s*return\s*"claude-(opus|sonnet|haiku)-[0-9a-z-]+"\s*\}/.test(e)||/function\s+[$\w]+\s*\(\s*\)\s*\{\s*return\s*\{\s*value\s*:\s*"claude-(opus|sonnet|haiku)-[0-9a-z-]+"\s*,\s*src\s*:\s*"default"\s*\}\s*\}/.test(e)?(J(`patch: autoModeClassifierModel: classifier-model resolver already patched — skipping`),e):e.includes(`"tengu_auto_mode_config"`)?(console.error(`patch: autoModeClassifierModel: failed to find auto-mode classifier resolver`),null):(J(`patch: autoModeClassifierModel: tengu_auto_mode_config not present in this CC build — no-op`),e)},ko=`__tweakccRouterClassify`,Ao=1e3,jo=(e,t,n,r)=>{let i=e.levels.map(e=>e.effort),a=JSON.stringify(i),o=e.pinPerTask?`true`:`false`,s=e.messageCap||1e5,c=e.assistantCap||1e5,l=e.timeoutMs||15e3,u=n?`${n}()`:`null`,d=i.length-1,f=e.levels.map((e,t)=>`Level ${t} (${e.label}): ${e.help}`).join(`
782
782
  `),p=(typeof e.systemPrompt==`string`&&e.systemPrompt.trim()?e.systemPrompt:O).replace(/\{LEVELS\}/g,f).replace(/\{MAX\}/g,String(d)),m=X(JSON.stringify(p)),h=X(JSON.stringify(e.levels.map(e=>e.label)));return`function __tweakccRouterState(){return globalThis.__tweakccRouter||(globalThis.__tweakccRouter={level:void 0,effort:void 0,baseline:void 0,summary:void 0,prevUser:void 0,prevAssistant:void 0,pendingCompaction:void 0,pendingRewindCut:void 0,log:void 0,model:void 0,loaded:!1})}function __tweakccRouterTrunc(__s,__cap){if(typeof __s!=="string")return"";if(__s.length<=__cap)return __s;var __mk="\\n...["+(__s.length-__cap)+" chars omitted from the middle]...\\n";var __b=__cap-__mk.length;if(__b<0)__b=0;var __h=Math.floor(__b/2);return __s.slice(0,__h)+__mk+__s.slice(__s.length-(__b-__h))}function __tweakccRouterSid(){try{var __s=${u};return typeof __s==="string"&&__s?__s:null}catch(__e){return null}}function __tweakccRouterDir(){var __p=${r}("path"),__o=${r}("os");return __p.join(__o.homedir(),".tweakcc","router-state")}function __tweakccRouterFile(__sid){return ${r}("path").join(__tweakccRouterDir(),__sid+".json")}function __tweakccRouterLoad(__st){if(__st.loaded)return;__st.loaded=!0;try{var __sid=__tweakccRouterSid();if(!__sid)return;var __fs=${r}("fs"),__f=__tweakccRouterFile(__sid);if(__fs.existsSync(__f)){var __d=JSON.parse(__fs.readFileSync(__f,"utf8"));if(__d){if(typeof __d.summary==="string")__st.summary=__d.summary;if(Number.isInteger(__d.level))__st.level=__d.level;if(Array.isArray(__d.log))__st.log=__d.log}}__tweakccRouterPrune(__fs)}catch(__e){}}function __tweakccRouterSave(__st){try{var __sid=__tweakccRouterSid();if(!__sid)return;var __fs=${r}("fs"),__dir=__tweakccRouterDir(),__j=JSON.stringify({summary:__st.summary,level:__st.level,log:Array.isArray(__st.log)?__st.log:[],updatedAt:Date.now()});__fs.mkdir(__dir,{recursive:!0},function(){try{__fs.writeFile(__tweakccRouterFile(__sid),__j,function(){})}catch(__e){}})}catch(__e){}}function __tweakccRouterDrop(__st){try{var __sid=__tweakccRouterSid();if(!__sid)return;var __fs=${r}("fs"),__f=__tweakccRouterFile(__sid);if(__fs.existsSync(__f))__fs.unlinkSync(__f)}catch(__e){}}function __tweakccRouterPrune(__fs){try{var __dir=__tweakccRouterDir(),__ns=__fs.readdirSync(__dir),__now=Date.now(),__ttl=12096e5;for(var __i=0;__i<__ns.length;__i++){try{var __ff=${r}("path").join(__dir,__ns[__i]);if(__now-__fs.statSync(__ff).mtimeMs>__ttl)__fs.unlinkSync(__ff)}catch(__e){}}}catch(__e){}}function __tweakccRouterReadResult(__r){try{if(__r==null)return null;if(typeof __r==="object"&&typeof __r.level==="number")return{level:__r.level,summary:typeof __r.summary==="string"?__r.summary:void 0};var __x;if(typeof __r==="string")__x=__r;else{var __c=(__r.message&&__r.message.content)||__r.content;__x=(Array.isArray(__c)&&__c[0]&&typeof __c[0].text==="string")?__c[0].text:(typeof __r.text==="string"?__r.text:"")}if(!__x)return null;try{var __o=JSON.parse(__x);if(__o&&typeof __o.level==="number")return{level:__o.level,summary:typeof __o.summary==="string"?__o.summary:void 0}}catch(__e){}var __m=__x.match(/-?\\d+/);if(__m)return{level:parseInt(__m[0],10),summary:void 0};return null}catch(__e){return null}}async function __tweakccRouterClassifyLlm(__input,__max){var __schema={type:"object",properties:{level:{type:"integer",description:"effort level, 0 (least) to "+__max+" (most)"},summary:{type:"string",description:"the updated running TL;DR summary"}},required:["level","summary"],additionalProperties:false};var __sys=${m};var __ac=new AbortController(),__to=setTimeout(function(){try{__ac.abort()}catch(__e){}},${l});try{var __res=await ${t.gB}({systemPrompt:[__sys],userPrompt:__input,outputFormat:{type:"json_schema",schema:__schema},signal:__ac.signal,options:{querySource:"route_complexity",agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[],agentContext:${t.km}()}});return __tweakccRouterReadResult(__res)}finally{clearTimeout(__to)}}async function ${ko}(__text,__mode,__model){try{var __ef=${a},__pin=${o},__max=__ef.length-1,__labels=${h};if(!__ef||!__ef.length)return;var __st=__tweakccRouterState();if(typeof __text!=="string")return;var __tr=__text.replace(/^\\s+/,"");if(/^\\/clear(\\s|$)/.test(__tr)){__st.level=void 0;__st.effort=void 0;__st.baseline=void 0;__st.summary=void 0;__st.prevUser=void 0;__st.prevAssistant=void 0;__st.pendingCompaction=void 0;__st.pendingRewindCut=void 0;__st.log=void 0;__st.model=void 0;__tweakccRouterDrop(__st);return}if(__tr.charAt(0)==="/")return;if(__mode!==void 0&&__mode!=="prompt")return;__tweakccRouterLoad(__st);if(__st.pendingRewindCut!=null){var __rt=__st.pendingRewindCut;__st.pendingRewindCut=void 0;var __rms=typeof __rt==="number"?__rt:Date.parse(__rt),__ci=-1;if(__rms===__rms&&Array.isArray(__st.log))for(var __i=__st.log.length-1;__i>=0;__i--){if(__st.log[__i]&&__st.log[__i].ts<=__rms){__ci=__i;break}}if(__ci>=0){var __pe=__st.log[__ci];__st.summary=__pe.summary;__st.level=__pe.level;__st.log=__st.log.slice(0,__ci)}else{__st.summary=void 0;__st.level=void 0}__st.prevUser=void 0;__st.prevAssistant=void 0;__st.pendingCompaction=void 0;if(process.env.TWEAKCC_ROUTER_DEBUG)try{process.stderr.write("[tweakcc-router] rewind cut to "+__rt+" ("+(__ci>=0?"restored":"reset")+")\\n")}catch(__e){}}if(typeof __st.pendingCompaction==="string"){__st.summary=__st.pendingCompaction;__st.prevUser=void 0;__st.prevAssistant=void 0;__st.level=void 0;__st.pendingCompaction=void 0}if(!Array.isArray(__st.log))__st.log=[];__st.log.push({ts:Date.now(),summary:typeof __st.summary==="string"?__st.summary:"",level:__st.level});if(__st.log.length>${Ao})__st.log.splice(0,__st.log.length-${Ao});var __plv=__st.level,__pmod=__st.model;var __mch=__pmod&&__model&&__pmod!==__model;var __ctx="model in use: "+(__model||"unknown")+(__mch?" (switched from "+__pmod+" this turn)":"")+"\\nlevel you assigned last turn: "+(__plv!==void 0?__plv+" ("+(__labels[__plv]||"?")+")":"none yet - this is the first routed turn");var __nm=__tweakccRouterTrunc(__text,${s});var __pu=__tweakccRouterTrunc(__st.prevUser,${s});var __pa=__tweakccRouterTrunc(typeof __st.prevAssistant==="string"?__st.prevAssistant:"",${c});var __input="<summary>\\n"+(__st.summary||"(none - first turn of the session)")+"\\n</summary>\\n<context>\\n"+__ctx+"\\n</context>\\n<recent_exchange>\\nuser: "+(__pu||"(none)")+"\\nassistant: "+(__pa||"(none)")+"\\n</recent_exchange>\\n<new_message>\\n"+__nm+"\\n</new_message>";var __res=null;try{__res=await __tweakccRouterClassifyLlm(__input,__max)}catch(__e){__res=null}var __hi=__ef.indexOf("high");if(__hi<0)__hi=Math.min(2,__max);var __lv,__sm=__st.summary;if(__res&&typeof __res.summary==="string"&&__res.summary)__sm=__res.summary;if(__res&&Number.isInteger(__res.level))__lv=__res.level;else __lv=(__st.level!==void 0?__st.level:__hi);if(__pin&&__st.level!==void 0&&__lv<__st.level)__lv=__st.level;if(__lv<0)__lv=0;if(__lv>__max)__lv=__max;__st.level=__lv;__st.effort=__ef[__lv];__st.summary=__sm;__st.prevUser=__text;__st.model=__model;__tweakccRouterSave(__st);if(process.env.TWEAKCC_ROUTER_DEBUG)try{process.stderr.write("[tweakcc-router] level="+__lv+" effort="+__st.effort+" chars="+__text.length+"\\n")}catch(__e){}}catch(__e){}}`},Mo=(e,t,n,r)=>{let i=/(function [$\w]+\(([$\w]+),([$\w]+),\{honorLaunchPin:[$\w]+=!0\}=\{\}\)\{if\(![$\w]+\(\2\)\)return;let [$\w]+=[$\w]+&&[$\w]+\(\2\),[$\w]+=[$\w]+\(\2\),([$\w]+)=[$\w]+\(\);)if\(\4===null&&![$\w]+\)return;return ([$\w]+)\(\4\?\?\([$\w]+\?[$\w]+:void 0\)\?\?\3\?\?[$\w]+,\2\)\}/,a=/(function [$\w]+\(([$\w]+),([$\w]+)\)\{if\(![$\w]+\(\2\)\)return;let [$\w]+=[$\w]+\(\2\),[$\w]+=[$\w]+\(\2\),([$\w]+)=[$\w]+\(\);)if\(\4===null&&![$\w]+\)return;return ([$\w]+)\(\4\?\?\([$\w]+\?[$\w]+:void 0\)\?\?\3\?\?[$\w]+,\2\)\}/,o=/(function [$\w]+\(([$\w]+),([$\w]+)\)\{if\(![$\w]+\(\2\)\)return;let [$\w]+=[$\w]+\(\2\),[$\w]+=[$\w]+\(\2\),([$\w]+)=[$\w]+\(\);)if\(\4===null&&![$\w]+\)return;let ([$\w]+)=\4\?\?\([$\w]+\?[$\w]+:void 0\)\?\?\3\?\?[$\w]+;(?:if\(typeof \5==="string"&&[$\w]+\(\5\)\)\5=[$\w]+\(\5,\2\);)?if\(\5==="max"&&!([$\w]+)\(\2\)\)\5="high";if\(\5==="xhigh"&&!([$\w]+)\(\2\)\)\5="high";return \5\}/,s=/(function [$\w]+\(([$\w]+),([$\w]+)\)\{if\(![$\w]+\(\2\)\)return;let [$\w]+=[$\w]+\(\2\),[$\w]+=[$\w]+\(\2\),([$\w]+)=[$\w]+\(\);)if\(\4===null\)return [$\w]+\?[$\w]+:void 0;let ([$\w]+)=\4\?\?\([$\w]+\?[$\w]+:void 0\)\?\?\3\?\?[$\w]+;if\(\5==="max"&&!([$\w]+)\(\2\)\)return"high";if\(\5==="xhigh"&&!([$\w]+)\(\2\)\)return"high";return \5\}/,c=e.match(i)||e.match(a),l=c||e.match(o)||e.match(s);if(!l||l.index===void 0)return e.includes(`CLAUDE_CODE_EFFORT_LEVEL`)?(console.error(`patch: complexityRouter: failed to find effort resolver (XQ shape)`),null):(J(`patch: complexityRouter: effort resolver absent in this CC build - no-op`),e);let u=l[1],d=l[2],f=l[3],p=l[4],m=l[6],h=l[7];if(c){let t=c[5].replace(/[$]/g,`\\$`),n=RegExp(`function ${t}\\(([$\\w]+),([$\\w]+)\\)\\{let ([$\\w]+)=\\1;(?:if\\(typeof \\3==="string"&&[$\\w]+\\(\\3\\)\\)\\3=[$\\w]+\\(\\3,\\2\\);)?if\\(\\3==="max"&&!([$\\w]+)\\(\\2\\)\\)\\3="high";if\\(\\3==="xhigh"&&!([$\\w]+)\\(\\2\\)\\)\\3="high";return \\3\\}`),r=e.match(n);if(!r)return console.error(`patch: complexityRouter: failed to find effort normalizer (support guards)`),null;m=r[4],h=r[5]}let g=`var __st=__tweakccRouterState();if(__st.baseline===void 0)__st.baseline=(${f}==null?null:${f});let __twkRE=__st.effort;if(__twkRE&&${p}==null&&(${f}==null||${f}===__st.baseline)){if(__twkRE==="max"&&!${m}(${d}))__twkRE="high";if(__twkRE==="xhigh"&&!${h}(${d}))__twkRE="high";return __twkRE}`,_=jo(t,n,r,Qs(e))+u+g+l[0].slice(u.length),v=l.index,y=v+l[0].length,b=e.slice(0,v)+_+e.slice(y);return B(e,b,_,v,y),b},No=e=>{let t=e.match(/if\(([$\w]+)===null&&([$\w]+)!=="prompt"\)throw Error\(`Mode: \$\{\2\} requires a string input\.`\);/);if(!t||t.index===void 0)return e.includes(`requires a string input.`)?(console.error(`patch: complexityRouter: failed to find submit handler throw-guard`),null):(J(`patch: complexityRouter: submit handler absent in this CC build - no-op`),e);let n=t[1],r=t[2],i=[...e.slice(Math.max(0,t.index-4e3),t.index).matchAll(/([$\w]+)\.options\.mainLoopModel/g)],a=i[i.length-1],o=`await ${ko}(${n},${r},${a?`${a[1]}.options.mainLoopModel`:`void 0`});`,s=t.index+t[0].length,c=e.slice(0,s)+o+e.slice(s);return B(e,c,o,s,s),c},Po=e=>{let t=e.match(/([$\w]+)=([$\w]+)\.at\(-1\),([$\w]+);if\(\1\)\{let ([$\w]+)=\1\.message\.content\.filter\(\(([$\w]+)\)=>\5\.type==="text"\);if\(\4\.length>0\)\{let ([$\w]+)=\4\.at\(-1\);if\(\6&&"text"in \6\)\3=\6\.text\}\}/);if(!t||t.index===void 0)return J(`patch: complexityRouter: prev-assistant capture site absent - router runs without prior-assistant context`),e;let n=`try{var __twr=globalThis.__tweakccRouter;if(__twr)__twr.prevAssistant=${t[3]}}catch(__e){}`,r=t.index+t[0].length,i=e.slice(0,r)+n+e.slice(r);return B(e,i,n,r,r),i},Fo=e=>{let t=e.match(/return\{ok:!0,summaryText:([$\w]+),/);if(!t||t.index===void 0)return J(`patch: complexityRouter: compaction summary site absent - no compaction reseed`),e;let n=t[1],r=`return globalThis.__tweakccRouter&&(globalThis.__tweakccRouter.pendingCompaction=${n}),{ok:!0,summaryText:${n},`,i=t.index,a=i+t[0].length,o=e.slice(0,i)+r+e.slice(a);return B(e,o,r,i,a),o},Io=e=>{let t=e.match(/onRestoreMessage:\(([$\w]+)\)=>([$\w]+)\(\1,"message_selector"\)/);if(!t||t.index===void 0)return J(`patch: complexityRouter: restore-conversation site absent - no rewind cut`),e;let n=t[1],r=`onRestoreMessage:(${n})=>(globalThis.__tweakccRouter&&(globalThis.__tweakccRouter.pendingRewindCut=${n}&&${n}.timestamp),${t[2]}(${n},"message_selector"))`,i=t.index,a=i+t[0].length,o=e.slice(0,i)+r+e.slice(a);return B(e,o,r,i,a),o},Lo=e=>{let t=e.match(/async function ([$\w]+)\(\{systemPrompt:[$\w]+=[$\w]+\(\[\]\),userPrompt:[$\w]+,outputFormat:[$\w]+,signal:[$\w]+,options:[$\w]+\}\)\{return\(await [$\w]+\([\s\S]{0,500}?,model:[$\w]+\(\),enablePromptCaching:/),n=e.match(/function ([$\w]+)\(\)\{return\{agentType:"main",agentId:[$\w]+\(\)\}\}/);return t&&n?{gB:t[1],km:n[1]}:null},Ro=e=>{let t=e.match(/getSessionId\(\)\{return ([$\w]+)\(\)\}/);return t?t[1]:null},zo=(e,t)=>{if(e.includes(ko))return J(`patch: complexityRouter: already patched - skipping`),e;let n=Lo(e);if(!n)return console.warn(`patch: complexityRouter: gB/km side-call helpers not found in this CC build - cannot route without the Haiku classifier; skipping the router`),e;let r=Ro(e);r||J(`patch: complexityRouter: session-id accessor not found - cross-session summary persistence disabled (in-memory only)`);let i=Mo(e,t,n,r);if(i===null)return null;if(i===e)return e;let a=No(i);return a===null?null:a===i?(J(`patch: complexityRouter: submit handler absent - reverting the resolver wrap too (all-or-nothing no-op)`),e):Io(Fo(Po(a)))},W=`fableplan`,Bo=`globalThis.__tweakccFablePlanEffort`,Vo=e=>{let t=e.match(/(\[(?:"[\w[\]]+",)*"opusplan"(?:,"[\w[\]]+")*\])(\s*,\s*[$\w]+\s*=\s*\["sonnet","opus","haiku")/);if(t&&t[1].includes(`"${W}"`))return J(`patch: fablePlan: alias already in the whitelist — skipping`),e;if(!t||t.index===void 0)return console.error(`patch: fablePlan: failed to find the model alias whitelist`),null;let n=t[1].slice(0,-1)+`,"${W}"]`+t[2],r=e.slice(0,t.index)+n+e.slice(t.index+t[0].length);return B(e,r,n,t.index,t.index+t[0].length),r},Ho=(e,t,n)=>{let r=e.match(/(function ([$\w]+)\(([$\w]+)\)\{let\{permissionMode:([$\w]+),mainLoopModel:([$\w]+),exceeds200kTokens:([$\w]+)=!1\}=\3;)(if\(\4!=="plan"\)return \5;let [$\w]+=([$\w]+)\(\),)/),i=r?null:e.match(/(function ([$\w]+)\(([$\w]+)\)\{let\{permissionMode:([$\w]+),mainLoopModel:([$\w]+),exceeds200kTokens:([$\w]+)=!1\}=\3,([$\w]+)=([$\w]+)\(\);)/),a=r??i;if(!a||a.index===void 0)return console.error(`patch: fablePlan: failed to find the plan-mode model resolver (uM shape)`),null;let o=a[1],s=a[4],c=r?`${a[8]}()`:a[7],l=r?a[7]:``,u=o+`if(${c}==="${W}"){${Bo}=${s}==="plan"?"${t.planEffort}":"${t.execEffort}";return ${n}(${s}==="plan"?"${t.planModel}":"${t.execModel}")}${Bo}=void 0;`+l,d=e.slice(0,a.index)+u+e.slice(a.index+a[0].length);return B(e,d,u,a.index,a.index+a[0].length),d},Uo=(e,t)=>{let n=RegExp(`(switch\\(([$\\w]+)\\)\\{(?:case"[\\w]+":return [$\\w]+\\([$\\w]+\\);)*?case"${t.execModel}":return ([$\\w]+)\\(([$\\w]+)\\);)`),r=e.match(n);if(!r||r.index===void 0)return console.error(`patch: fablePlan: failed to find the builtin-default alias switch`),null;let i=`${r[1]}case"${W}":return ${r[3]}(${r[4]});`,a=e.slice(0,r.index)+i+e.slice(r.index+r[0].length);return B(e,a,i,r.index,r.index+r[0].length),a},Wo=(e,t)=>{let n=RegExp(`function ([$\\w]+)\\(([$\\w]+)\\)\\{let [$\\w]+=\\2\\.trim\\(\\)[\\s\\S]{0,120}?if\\([$\\w]+\\(([$\\w]+)\\)\\)switch\\(\\3\\)\\{([\\s\\S]{0,600}?case"${t.execModel}":(return [^;]+;))`),r=e.match(n);if(!r||r.index===void 0)return console.error(`patch: fablePlan: failed to find the alias-to-model resolver (as shape)`),null;let i=r[1],a=r[0],o=`${a}case"${W}":${r[5]}`,s=e.slice(0,r.index)+o+e.slice(r.index+a.length);return B(e,s,o,r.index,r.index+a.length),{file:s,resolver:i}},Go=(e,t)=>{let n=/(function [$\w]+\(([$\w]+),([$\w]+)\)\{let ([$\w]+)=[$\w]+\(\2\),([$\w]+)=[$\w]+\.ANTHROPIC_CUSTOM_MODEL_OPTION;)/,r=e.match(/(function [$\w]+\(([$\w]+),([$\w]+)\)\{let ([$\w]+)=[$\w]+\(\2,\3\),([$\w]+)=\4\?\?[$\w]+\(\2\),([$\w]+)=[$\w]+\.ANTHROPIC_CUSTOM_MODEL_OPTION;)/),i=r??e.match(n);if(!i||i.index===void 0)return console.error(`patch: fablePlan: failed to find the model picker options`),null;let a=r?i[5]:i[4],o=`${Jo(t.planModel)} Plan Mode`,s=`Use ${Jo(t.planModel)} in plan mode, ${Jo(t.execModel)} otherwise`,c=`if(!${a}.some((z)=>z.value==="${W}"))${a}.push(${JSON.stringify({value:W,label:o,description:s})});`,l=i[1]+c,u=e.slice(0,i.index)+l+e.slice(i.index+i[0].length);return B(e,u,l,i.index,i.index+i[0].length),u},Ko=e=>{let t=e.match(/(function ([$\w]+)\(([$\w]+),([$\w]+),\{honorLaunchPin:([$\w]+)=!0\}=\{\}\)\{)(if\(!([$\w]+)\(\3\)\)return;let [$\w]+=\5&&[$\w]+\(\3\),[$\w]+=[$\w]+\(\3\),[$\w]+=[$\w]+\(\);)/),n=t??e.match(/(function ([$\w]+)\(([$\w]+),([$\w]+)\)\{)(if\(!([$\w]+)\(\3\)\)return;let [$\w]+=[$\w]+\(\3\),[$\w]+=[$\w]+\(\3\),[$\w]+=[$\w]+\(\);)/);if(!n||n.index===void 0)return e.includes(`CLAUDE_CODE_EFFORT_LEVEL`)?(console.error(`patch: fablePlan: failed to find the effort resolver`),null):(J(`patch: fablePlan: effort resolver absent in this build — no-op`),e);let r=`if(${Bo}!==void 0)return ${Bo};`,i=t?n[6]:n[5],a=n[1]+r+i,o=e.slice(0,n.index)+a+e.slice(n.index+n[0].length);return B(e,o,a,n.index,n.index+n[0].length),o},qo=e=>{let t=e.match(/(=[$\w]+\(\([$\w]+\)=>[$\w]+\.settings\.showClearContextOnPlanAccept\)\?\?)!1/);if(!t||t.index===void 0)return J(`patch: fablePlan: showClearContextOnPlanAccept gate not present — no-op`),e;let n=`${t[1]}!0`,r=e.slice(0,t.index)+n+e.slice(t.index+t[0].length);return B(e,r,n,t.index,t.index+t[0].length),r},Jo=e=>e.charAt(0).toUpperCase()+e.slice(1),Yo=RegExp(`\\["sonnet",(?:"[\\w[\\]]+",)*"${W}"[,\\]]`),Xo=(e,t)=>{if(Yo.test(e))return J(`patch: fablePlan: already applied — no-op`),e;if(t.planModel===t.execModel)return console.error(`patch: fablePlan: planModel and execModel are the same — nothing to pair`),null;let n=Wo(e,t);if(!n)return null;let r=n.file,i=Vo(r);if(!i)return null;r=i;let a=Ho(r,t,n.resolver);if(!a)return null;r=a;let o=Uo(r,t);if(!o)return null;r=o;let s=Go(r,t);if(!s)return null;r=s;let c=Ko(r);if(!c)return null;if(r=c,t.offerClearContextOnPlanAccept){let e=qo(r);if(!e)return null;r=e}return r},Zo=(e,t)=>{let n=`return !0;`,r=e.slice(0,t)+n+e.slice(t);return B(e,r,n,t,t),r},Qo=e=>{let t=e.indexOf(`"allow_voice_mode"`);if(t!==-1){let n=Math.max(0,t-800),r=e.slice(n,t+400).match(/function ([$\w]+)\(\)\{return [$\w]+\(\)&&[$\w]+\(\)\}/);if(r&&r.index!==void 0){let t=n+r.index,i=e.indexOf(`{`,t);if(i!==-1)return e.startsWith(`return !0;`,i+1)?e:Zo(e,i+1)}let i=e.match(/name:"voice",description:"Toggle voice mode"[\s\S]{0,500}?get isHidden\(\)\{return![$\w]+\(\)\}/);if(i&&i.index!==void 0){let t=i[0].replace(/get isHidden\(\)\{return![$\w]+\(\)\}/,`get isHidden(){return!1}`);if(i[0]===t)return e;let n=e.slice(0,i.index)+t+e.slice(i.index+i[0].length);return B(e,n,t,i.index,i.index+i[0].length),n}}let n=e.match(/function [$\w]+\(\)\{return [$\w]+\("tengu_amber_quartz"/);if(n&&n.index!==void 0){let t=n.index+n[0].indexOf(`{`)+1,r=`return !0;`,i=e.slice(0,t)+r+e.slice(t);return B(e,i,r,t,t),i}let r=e.match(/function [$\w]+\(\)\{return![$\w]+\("tengu_amber_quartz_disabled"/);if(r&&r.index!==void 0){let t=r.index+r[0].indexOf(`{`)+1,n=`return !0;`,i=e.slice(0,t)+n+e.slice(t);return B(e,i,n,t,t),i}let i=e.match(/name:"voice",description:"Toggle voice mode"[\s\S]{0,500}?get isHidden\(\)\{return!([$\w]+)\(\)\}/);if(i&&i.index!==void 0){let t=i[1].replace(/[$]/g,`\\$`),n=RegExp(`function ${t}\\(\\)\\{`),r=e.match(n);if(r&&r.index!==void 0){let t=r.index+r[0].length,n=`return !0;`,i=e.slice(0,t)+n+e.slice(t);return B(e,i,n,t,t),i}}return console.error(`patch: voiceMode: failed to find tengu_amber_quartz gate`),null},$o=e=>{let t=e.match(/if\([$\w]+\("tengu_sotto_voce",!1\)\)/);if(!t||t.index===void 0)return e;let n=`if(!0)`,r=e.slice(0,t.index)+n+e.slice(t.index+t[0].length);return B(e,r,n,t.index,t.index+t[0].length),r},es=(e,t)=>{let n=Qo(e);return!n||t&&(n=$o(n),!n)?null:n},ts=e=>{let t=e.match(/function [$\w]+\(\)\{return [$\w]+\("tengu_harbor",!1\)/);if(!t||t.index===void 0)return console.error(`patch: channelsMode: failed to find tengu_harbor gate`),null;let n=t.index+t[0].indexOf(`{`)+1,r=`return !0;`,i=e.slice(0,n)+r+e.slice(n);return B(e,i,r,n,n),i},ns=e=>{let t=e.match(/reason:"server did not declare claude\/channel capability"\};?/);if(!t||t.index===void 0)return console.error(`patch: channelsMode: failed to find gateChannelServer capability check`),null;let n=t.index+t[0].length,r=`return{action:"register"};`,i=e.slice(0,n)+r+e.slice(n);return B(e,i,r,n,n),i},rs=e=>{let t=e.match(/function [$\w]+\(\)\{return [$\w]+\("tengu_harbor_permissions",!1\)/);if(!t||t.index===void 0)return console.error(`patch: channelsMode: failed to find tengu_harbor_permissions gate`),null;let n=t.index+t[0].indexOf(`{`)+1,r=`return !0;`,i=e.slice(0,n)+r+e.slice(n);return B(e,i,r,n,n),i},is=e=>{let t=e.match(/"Channels \(experimental\) messages from ",([$\w]+),"[^"]*restart without "/);if(t&&t.index!==void 0){let n=`"Channels active \\xB7 messages from ",${t[1]}," \\xB7 restart without "`,r=t.index,i=r+t[0].length,a=e.slice(0,r)+n+e.slice(i);return B(e,a,n,r,i),a}let n=e.match(/Experimental[^"]*?inbound messages will be pushed into this session, this carries prompt injection risks\. Restart Claude Code without /);if(n&&n.index!==void 0){let t=`Channels active. Restart Claude Code without `,r=n.index,i=r+n[0].length,a=e.slice(0,r)+t+e.slice(i);return B(e,a,t,r,i),a}return console.error(`patch: channelsMode: failed to find ChannelsNotice warning text`),null},as=e=>{let t=e.match(/if\(![$\w]+\.dev\)[$\w]+\.push\(\{[$\w]+:[$\w]+,[$\w]+:"server: entries need --dangerously-load-development-channels"\}\)/);if(!t||t.index===void 0)return console.error(`patch: channelsMode: failed to find server dev-flag warning block`),null;let n=t.index,r=n+t[0].length,i=e.slice(0,n)+``+e.slice(r);return B(e,i,``,n,r),i},os=e=>{let t=ts(e);return!t||(t=ns(t),!t)||(t=rs(t),!t)||(t=is(t),!t)||(t=as(t),!t)?null:t},ss=e=>{if(/name:"clear-screen"/.test(e))return e;let t=e.match(/([,;{}])(function [$\w]+\(\)\{)([$\w]+\(\))\.get\(process\.stdout\)\?\.forceRedraw\(\)\}/)||e.match(/([,;{}])(function [$\w]+\(\)\{)([$\w]+)\.get\(process\.stdout\)\?\.forceRedraw\(\)\}/);if(!t||t.index===void 0)return J(`patch: clearScreen: failed to find forceRedraw function`),null;let n=`${t[1]}globalThis.__tweakccForceRedraw=()=>${t[3]}.get(process.stdout)?.forceRedraw();`+t[0].slice(1),r=e.slice(0,t.index)+n+e.slice(t.index+t[0].length);B(e,r,n,t.index,t.index+t[0].length);let i=cs(r);return i?(r=i,ui(r,`,{type:"local",name:"clear-screen",description:"Clear screen without resetting conversation context",supportsNonInteractive:!1,load:()=>Promise.resolve().then(()=>({call:(H,$)=>{$.setMessages(m=>{globalThis.__tweakccHiddenUUIDs=new Set(m.map(x=>x.uuid?.slice(0,24)).filter(Boolean));return[...m]});process.stdout.write("\\x1b[2J\\x1b[H\\x1b[3J");globalThis.__tweakccForceRedraw?.();return{type:"skip"}}}))}`)||(J(`patch: clearScreen: failed to register slash command`),null)):(J(`patch: clearScreen: failed to patch render filter g97`),null)},cs=e=>{let t=e.match(/([,;{}])(function [$\w]+\(([$\w]+),[$\w]+\)\{)if\(\3\.type!=="user"\)return!0;if\(\3\.isMeta\)/);if(!t||t.index===void 0)return null;let n=t[1],r=t[2],i=`${n}${r}if(globalThis.__tweakccHiddenUUIDs?.has(${t[3]}.uuid?.slice(0,24)))return!1;`+t[0].slice(n.length+r.length),a=e.slice(0,t.index)+i+e.slice(t.index+t[0].length);return B(e,a,i,t.index,t.index+t[0].length),a},ls=e=>{let t=e.match(/=2000,([$\w]+)="Read a file from the local filesystem\./);if(!t||t.index===void 0)return/=\(\+process\.env\.CLAUDE_CODE_READ_DEFAULT_LINES/.test(e)?e:(console.error(`patch: readDefaultLines: failed to find =2000 near Read tool prompt anchor`),null);let n=t.index,r=n+5,i=`=(+process.env.CLAUDE_CODE_READ_DEFAULT_LINES||2000)`,a=e.slice(0,n)+i+e.slice(r);return B(e,a,i,n,n+52),a},us=e=>X(JSON.stringify(e)).replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),ds=`"$_cc_bin"`,fs=/\{mode:"embedded",command:process\.execPath,args:\[[^\]]*\],argv0:"rg"\}/,ps=`Search backend note (fff):`;``+ps;const ms=`most-relevant-first`;``+ms;const hs=(e,t)=>{let n=us(t);if(e.includes(`ARGV0=\${t} ${n}`)||e.includes(`exec -a \${t} ${n}`))return e;if(e.split(ds).length-1==0)return console.error(`patch: swapRipgrepForFff: bash-search shadow anchor "$_cc_bin" not found`),null;let r=e.split(ds).join(n),i=`[[ ! -x $_cc_bin ]]`;return r.includes(i)&&(r=r.split(i).join(`[[ ! -x $_cc_bin || ! -x ${n} ]]`)),B(e,r,n,e.indexOf(ds),e.indexOf(ds)+10),r},gs=(e,t)=>{if(e.includes(`--fff-claude-bin=`))return e;let n=e.indexOf(`{mode:"embedded",command:process.execPath,args:["--no-config"],argv0:"rg"}`),r=n===-1?-1:n+74;if(n===-1){let t=e.match(fs);if(!t||t.index===void 0)return J(`patch: swapRipgrepForFff: ripgrep resolver descriptor not found; skipping rg repoint`),e;n=t.index,r=t.index+t[0].length}let i=`{mode:"system",command:${X(JSON.stringify(t))},args:["--fff-claude-bin="+process.execPath]}`,a=e.slice(0,n)+i+e.slice(r);return B(e,a,i,n,r),a},_s=(e,t)=>{let n=e[t];for(t++;t<e.length;)if(e[t]===`\\`)t+=2;else if(e[t]===n)return t;else t++;return t},vs=(e,t)=>{let n=[{k:`tpl`}];for(let r=t;r<e.length;r++){let t=n[n.length-1],i=e[r];if(i===`\\`){r++;continue}if(t.k===`tpl`){if(i==="`"){if(n.pop(),n.length===0)return r;continue}i===`$`&&e[r+1]===`{`&&(n.push({k:`expr`,b:0}),r++);continue}if(i==="`"){n.push({k:`tpl`});continue}if(i===`"`||i===`'`){r=_s(e,r);continue}if(i===`{`){t.b++;continue}if(i===`}`){t.b===0?n.pop():t.b--;continue}}return-1},ys=(e,t,n,r,i)=>{if(e.includes(r))return e;if(n.includes("`"))return console.error(`patch: swapRipgrepForFff: ${i} guidance contains a backtick; skipping (would break template parity)`),e;let a=[],o=0;for(;;){let n=e.indexOf(t,o);if(n===-1)break;let r=vs(e,n);r===-1?console.error(`patch: swapRipgrepForFff: ${i} anchor at ${n} has no balanced closing backtick; skipping this site`):a.push(r),o=n+t.length}if(a.length===0)return J(`patch: swapRipgrepForFff: ${i} anchor not found; skipping`),e;let s=e;for(let e of a.sort((e,t)=>t-e))s=s.slice(0,e)+n+s.slice(e);return B(e,s,n,a[a.length-1],a[0]),s},bs=(e,t)=>{let n=hs(e,t);if(n===null)return null;let r=n;return r=gs(r,t),r=ys(r,`built on ripgrep`,`
783
783
 
784
- Search backend note (fff): prefer one bare identifier over regex; results are relevance-ranked, so read the top hit first. A trailing [def] tag flags a line that likely defines the symbol.`,ps,`Grep description`),r=ys(r,`Prefer dedicated tools over`,` grep/find results are ranked most-relevant-first (read the top hit first); a trailing [def] tag flags a likely definition line, and a grep or find -name that matches nothing automatically lists the closest approximate hits tagged [~approx]. Add --fuzzy to force typo-tolerant or partial matching, e.g. grep --fuzzy SomeName.`,ms,`Bash description`),r},xs=3e4;function Ss(){let{platform:e,arch:t}=process;return e===`darwin`&&t===`arm64`?`aarch64-apple-darwin`:e===`linux`&&t===`arm64`?`aarch64-unknown-linux-musl`:e===`linux`&&t===`x64`?`x86_64-unknown-linux-musl`:null}function Cs(){try{let e=u.dirname(y(import.meta.url));for(let t=0;t<6;t++){let t=u.join(e,`package.json`);if(s.existsSync(t))try{let n=JSON.parse(s.readFileSync(t,`utf-8`)).version;if(typeof n==`string`)return{root:e,version:n}}catch{}let n=u.dirname(e);if(n===e)break;e=n}}catch{}return null}async function ws(e){try{return await a.access(e,s.constants.X_OK),!0}catch{return!1}}async function Ts(e,t){await a.mkdir(u.dirname(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;try{await a.copyFile(e,n),await a.chmod(n,493),await a.rename(n,t)}catch(e){throw await a.unlink(n).catch(()=>{}),e}}async function Es(e){try{return(await a.stat(e)).mtimeMs}catch{return-1}}async function Ds(){let e=Ss();if(!e)return null;let t=u.join(Z,`fff`,e,`rg-fff`),n=u.join(u.dirname(t),`.version`),r=Cs();if(r)for(let e of[`release`,`debug`]){let n=u.join(r.root,`tools`,`rg-fff`,`target`,e,`rg-fff`);if(s.existsSync(n))return await Es(n)>await Es(t)&&await Ts(n,t),t}let i=r?.version,o=await a.readFile(n,`utf-8`).then(e=>e.trim()).catch(()=>null);if(await ws(t)&&(!i||o===i))return t;if(!i)return null;let c=`https://github.com/skrabe/tweakcc-fixed/releases/download/v${i}`;try{let r=await fetch(`${c}/rg-fff-${e}`,{signal:AbortSignal.timeout(xs)});if(!r.ok)return null;let o=Buffer.from(await r.arrayBuffer()),s=await fetch(`${c}/rg-fff-${e}.sha256`,{signal:AbortSignal.timeout(xs)});if(!s.ok)return console.error(`patch: swapRipgrepForFff: rg-fff-${e}.sha256 unavailable (${s.status}) — keeping ripgrep`),null;let l=(await s.text()).trim().split(/\s+/)[0]?.toLowerCase(),d=S.createHash(`sha256`).update(o).digest(`hex`);if(!l||l!==d)return console.error(`patch: swapRipgrepForFff: rg-fff-${e} checksum ${l?`mismatch`:`missing`} — keeping ripgrep`),null;await a.mkdir(u.dirname(t),{recursive:!0});let f=`${t}.tmp-${process.pid}`;try{await a.writeFile(f,o),await a.chmod(f,493),await a.rename(f,t)}catch(e){throw await a.unlink(f).catch(()=>{}),e}return await a.writeFile(n,i).catch(()=>{}),t}catch{return null}}const Os=e=>{if(/function [$\w]+\(([$\w]+),[$\w]+\)\{if\(Object\.entries\([$\w]+\)\.length===0\)return \1;var ([$\w]+)=\1\[0\];if\(\2&&\2\.isMeta/.test(e))return e;let t=e.match(/function ([$\w]+)\(([$\w]+),([$\w]+)\)\{if\(Object\.entries\(\3\)\.length===0\)return \2;return\[([\s\S]+?),\.\.\.\2\]\}/);if(!t||t.index===void 0){let t=e.indexOf(`"tengu_context_size"`);if(t>0){let n=e.slice(Math.max(0,t-5e3),t);if(/function [$\w]+\([$\w]+,[$\w]+\)\{return [$\w]+;?\}\s*async function/.test(n))return console.log(`patch: claudemd-context-once-per-conversation: claudemd-context override suppressed wrapper — no-op`),e}return console.error(`patch: claudemd-context-once-per-conversation: failed to find kY6 wrapper`),null}let[n,r,i,a,o]=t,s=`${i}_0`,c=`function ${r}(${i},${a}){if(Object.entries(${a}).length===0)return ${i};var ${s}=${i}[0];if(${s}&&${s}.isMeta&&${s}.message&&typeof ${s}.message.content==="string"&&${s}.message.content.indexOf("<system-reminder>\\nAs you answer the user")===0)return ${i};${i}.unshift(${o});return ${i}}`,l=t.index,u=l+n.length,d=e.slice(0,l)+c+e.slice(u);return B(e,d,c,l,u),d},ks=e=>{let t=e.match(/function ([$\w]+)\(([$\w]+)\)\{return`<system-reminder>\n\$\{\2\}\n<\/system-reminder>`\}/);if(!t||t.index===void 0)return/function [$\w]+\(([$\w]+)\)\{if\(!\1\|\|!\1\.trim\(\)\|\|\1==="\(no content\)"\)return"\(no content\)";return`<system-reminder>/.test(e)?e:(console.error(`patch: strip-empty-system-reminders: failed to find LW(H) wrapper`),null);let[n,r,i]=t,a=`function ${r}(${i}){if(!${i}||!${i}.trim()||${i}==="(no content)")return"(no content)";return\`<system-reminder>\n\${${i}}\n</system-reminder>\`}`,o=t.index,s=o+n.length,c=e.slice(0,o)+a+e.slice(s);return B(e,c,a,o,s),c},As=e=>{if(!e.includes(`The following deferred tools are now available via`))return console.log(`patch: suppress-deferred-tools: anchor not present in this CC build — no-op`),e;let t=`case"deferred_tools_delta":{`;if(e.includes(`case"deferred_tools_delta":{return [];`))return e;let n=e.indexOf(t);if(n<0)return console.error(`patch: suppress-deferred-tools: failed to find case header`),null;if(e.indexOf(t,n+1)>=0)return console.error(`patch: suppress-deferred-tools: case header is ambiguous (multiple matches)`),null;let r=n+28,i=`return [];`,a=e.slice(0,r)+i+e.slice(r);return B(e,a,i,r,r),a},js=[`__tweakcc`,`tweakcc v`],Ms=e=>js.some(t=>e.includes(t)),Ns=Math.max(...js.map(e=>e.length)),Ps=async e=>new Promise(t=>{let n;try{n=l(e,{encoding:`latin1`,highWaterMark:8<<20})}catch{t(!1);return}let r=``,i=!1,a=e=>{i||(i=!0,n.destroy(),t(e))};n.on(`data`,e=>{let t=r+e;if(Ms(t)){a(!0);return}r=t.slice(-(Ns-1))}),n.on(`error`,()=>a(!1)),n.on(`close`,()=>a(!1)),n.on(`end`,()=>a(!1))});var Fs=class extends Error{constructor(e){super(`Refusing to back up ${e}: it carries tweakcc markers, so it is already patched. Backing it up would overwrite the only pristine copy with a patched one. Run \`tweakcc --restore\` first, or reinstall Claude Code, then try again.`),this.name=`NonPristineBackupError`}};const Is=async e=>{if(await Ps(e))throw new Fs(e)},Ls=async(e,t)=>{let n=`${t}.tmp-${process.pid}`;try{await o.copyFile(e,n),await o.rename(n,t)}catch(e){try{await o.unlink(n)}catch{}throw e}},Rs=async e=>{if(!e.cliPath){J(`backupClijs: Skipping for native installation (no cliPath)`);return}await Is(e.cliPath),await Qc(),J(`Backing up cli.js to ${qc}`),await Ls(e.cliPath,qc),await rl(t=>{t.changesApplied=!1,t.ccVersion=e.version})},zs=async e=>{e.nativeInstallationPath&&(await Is(e.nativeInstallationPath),await Qc(),J(`Backing up native binary to ${Jc}`),await Ls(e.nativeInstallationPath,Jc),await rl(t=>{t.changesApplied=!1,t.ccVersion=e.version}))},Bs=async e=>e.cliPath?await Lc(qc)?(J(`Restoring cli.js from backup to ${e.cliPath}`),await Ic(e.cliPath,qc,`restore`),await Ct(),await rl(e=>{e.changesApplied=!1}),!0):(J(`restoreClijsFromBackup: No backup file exists, skipping`),!1):(J(`restoreClijsFromBackup: Skipping for native installation (no cliPath)`),!1),Vs=async e=>e.nativeInstallationPath?await Lc(Jc)?(J(`Restoring native binary from backup to ${e.nativeInstallationPath}`),await Ic(e.nativeInstallationPath,Jc,`restore`),await Ct(),await rl(e=>{e.changesApplied=!1}),!0):(J(`restoreNativeBinaryFromBackup: No backup file exists, skipping`),!1):(J(`restoreNativeBinaryFromBackup: No native installation path, skipping`),!1),Hs=`/*@@TWEAKCC_MODULE:`,Us=(e,t)=>{let n=e.lastIndexOf(Hs,t);if(n===-1)return Ws(e);let r=e.indexOf(Hs,n+1);return Ws(e.slice(n,r===-1?e.length:r))},Ws=e=>{let t=Array.from(e.matchAll(/[^$\w]([$\w]+)(?:\.(?:cyan|gray|green|red|yellow|ansi256|bgAnsi256|bgHex|bgRgb|hex|rgb|bold|dim|inverse|italic|strikethrough|underline)\b)+\(/g)),n={};for(let e of t){let t=e[1];n[t]=(n[t]||0)+1}let r,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);return r},Gs=e=>{let t=e.slice(0,2e3).match(/[,;]([$\w]+)=\([$\w]+,[$\w]+,[$\w]+\)=>\{[$\w]+=[$\w]+!=null\?/);if(t)return t[1];let n=e.slice(0,1e4),r=Array.from(n.matchAll(/(?:var |,)([$\w]+)=\([$\w]+,[$\w]+,[$\w]+\)=>\{/g));if(r.length>0){let e=r[0][1];for(let t of r)t[1].length<e.length&&(e=t[1]);return e}console.log(`patch: getModuleLoaderFunction: failed to find module loader function`)},Ks=e=>{let t=e.match(/var ([$\w]+)=[$\w]+\((?:\([$\w]+\)=>|function\([$\w]+\))\{var [$\w]+=Symbol\.for\("react\.(transitional\.)?element"\)/);if(!t){console.log(`patch: getReactModuleNameNonBun: failed to find React module name`);return}return t[1]},qs=e=>{let t=Ks(e);if(!t){console.log(`^ patch: getReactModuleFunctionBun: failed to find React module name (Bun)`);return}let n=RegExp(`var ([$\\w]+)=[$\\w]+\\((?:\\([$\\w]+,[$\\w]+\\)=>|function\\([$\\w]+,[$\\w]+\\))\\{[$\\w]+\\.exports=${q(t)}\\(\\)`),r=e.match(n);if(!r){console.log(`patch: getReactModuleFunctionBun: failed to find React module function (Bun) (reactModuleNameNonBun=${t})`);return}return r[1]};let G=null,Js=null;const Ys=e=>{if(G!=null)return G;let t=Gs(e);if(!t){console.log(`^ patch: getReactVar: failed to find moduleLoader`),G=void 0;return}let n=Ks(e);if(!n){console.log(`^ patch: getReactVar: failed to find reactModuleVarNonBun`),G=void 0;return}let r=RegExp(`[^$\\w]([$\\w]+)=${q(t)}\\(${q(n)}\\(\\),1\\)`),i=e.match(r);if(i)return G=i[1],G;let a=qs(e);if(!a){console.log(`^ patch: getReactVar: failed to find reactModuleFunctionBun`),G=void 0;return}let o=RegExp(`[^$\\w]([$\\w]+)=${q(t)}\\(${q(a)}\\(\\),1\\)`),s=e.match(o);if(!s){console.log(`patch: getReactVar: failed to find bunPattern (moduleLoader=${t}, reactModuleVarNonBun=${n}, reactModuleFunctionBun=${a})`),G=void 0;return}return G=s[1],G},Xs=()=>{G=null},Zs=e=>{let t=e.match(/import\{createRequire as ([$\w]+)\}from"node:module";/);if(!t)return;let n=t[1],r=RegExp(`var ([$\\w]+)=${q(n)}\\(import\\.meta\\.url\\)`),i=e.match(r);if(!i){console.log(`patch: findRequireFunc: failed to find require function variable (createRequireVar=${n})`);return}return i[1]},Qs=e=>{if(Js!=null)return Js;let t=Zs(e);return t?(Js=t,Js):(Js=`require`,Js)},$s=()=>{Js=null},ec=()=>{Xs(),$s()},tc=e=>{let t=e.match(/function ([$\w]+)\([$\w]+\)\{let [$\w]+=[$\w]+\.c\(\d+\)[^;]{0,240};if\([$\w]+\[0\]!==[$\w]+\)\(\{color:[$\w]+,backgroundColor:[$\w]+,dimColor:[$\w]+,bold:[$\w]+/);if(t)return t[1];let n=e.match(/\bfunction ([$\w]+).{0,80}color:[$\w]+,backgroundColor:[$\w]+,dimColor:[$\w]+(?:=![01])?,bold:[$\w]+(?:=![01])?/);if(!n){console.log(`patch: findTextComponent: failed to find text component`);return}return n[1]},nc=(e,t)=>{let n=`[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*`,r=RegExp(`var [^;]{0,120};var [$\\w]+=${n}\\(\\(\\)=>\\{[^}]{0,500}([$\\w]+)=${q(t)}\\}\\)`),i=e.match(r)?.[1]??t,a=RegExp(`function ([$\\w]+)\\([^)]+\\)\\{(?=[\\s\\S]{0,2500}createElement\\(${q(i)},\\{\\.\\.\\.[$\\w]+,borderColor:)[\\s\\S]{0,3000}?return [$\\w]+\\}var [^;]{0,160};var [$\\w]+=${n}\\(\\(\\)=>\\{[^}]{0,600}([$\\w]+)=\\1\\}\\)`);return e.match(a)?.[2]},rc=e=>{let t=e.match(/function ([$\w]+)\(.{0,2000}[^$\w]([$\w]+)=[$\w]+(?:\.default)?\.createElement\("ink-box".{0,500}?return \2/);if(t)return t[1];let n=e.match(/function ([$\w]+)\(.{0,200}children:[$\w]+,flexWrap:[$\w]+.{0,2000}?\.createElement\("ink-box"/);if(n)return n[1];let r=e.match(/[^$\w]([$\w]+)\.displayName="Box"/);if(r)return r[1];let i=e.match(/function ([$\w]+)\([$\w]+\)\{let [$\w]+=[$\w]+(?:\.[$\w]+)?\(\d+\).{0,3000}createElement\("ink-box"/);if(i)return i[1];let a=e.match(/function ([$\w]+)\(\{children:([$\w]+),ref:[$\w]+.{0,600}?\.\.\.([$\w]+)\}\)\{.{0,2500}?"margin".{0,2500}?"padding".{0,1200}?"gap".{0,1200}?\3\.flexWrap\?\?="nowrap",\3\.flexDirection\?\?="row",\3\.flexGrow\?\?=0,\3\.flexShrink\?\?=1,\3\.overflowX=\3\.overflowX\?\?\3\.overflow\?\?"visible",\3\.overflowY=\3\.overflowY\?\?\3\.overflow\?\?"visible",[$\w]+(?:\.default)?\.createElement\("ink-box",\{[^}]*style:\3\},\2\)/);if(a)return nc(e,a[1])??a[1];let o=e.match(/function ([$\w]+)\(\{children:[$\w]+,ref:[$\w]+,tabIndex:[$\w]+,autoFocus:[$\w]+/);if(o)return o[1];console.error(`patch: findBoxComponent: failed to find Box component (neither ink-box createElement nor displayName found)`)},ic=e(import.meta.url),ac=(()=>{try{return ic(`../package.json`).version}catch{return ic(`../../package.json`).version}})();let K=function(e){return e.SYSTEM_PROMPTS=`System Prompts`,e.ALWAYS_APPLIED=`Always Applied`,e.MISC_CONFIGURABLE=`Misc Configurable`,e.FEATURES=`Features`,e.SYSTEM_REMINDERS=`System Reminders`,e}({});const oc=[{id:`verbose-property`,name:`Verbose property`,group:K.ALWAYS_APPLIED,description:`Token counter will show (2s · ↓ 169 tokens · thinking)`},{id:`read-default-lines`,name:`Read default lines (env-gated)`,group:K.ALWAYS_APPLIED,description:`Read tool default line cap becomes CLAUDE_CODE_READ_DEFAULT_LINES env var (falls back to 2000 if unset)`},{id:`opusplan1m`,name:`Opusplan[1m] support`,group:K.ALWAYS_APPLIED,description:`Use the "Opus Plan 1M" model: Opus for planning, Sonnet 1M context for building`},{id:`thinking-block-styling`,name:`Thinking block styling`,group:K.ALWAYS_APPLIED,description:`Restore dim/gray + italic styling for thinking blocks`},{id:`fix-lsp-support`,name:`Fix LSP support`,group:K.ALWAYS_APPLIED,description:`Enable/fix nascent LSP support`},{id:`fix-summarize-from-here`,name:`Fix "Summarize from here"`,group:K.MISC_CONFIGURABLE,description:`Make "Summarize from here" summarize only the messages after the rewind point (feed the slice, not the whole conversation)`,modelFacing:!0},{id:`fix-rewind-summary-header`,name:`Honest rewind summary header`,group:K.MISC_CONFIGURABLE,description:`Label a rewind summary as a deliberate rewind instead of the misleading "ran out of context" header`,modelFacing:!0},{id:`statusline-update-throttle`,name:`Statusline update throttling correction`,group:K.ALWAYS_APPLIED,description:`Statusline updates will be properly throttled instead of queued (or debounced)`},{id:`clear-screen`,name:`Clear screen command`,group:K.ALWAYS_APPLIED,description:`Register a /clear-screen command that clears the terminal scrollback and redraws without resetting conversation context`},{id:`strip-empty-system-reminders`,name:`Strip empty <system-reminder> wrappers`,group:K.ALWAYS_APPLIED,description:`Short-circuits CC's universal system-reminder wrapper so empty / "(no content)" inputs produce no reminder. Kills the drift-inducing "<system-reminder>(no content)</system-reminder>" blocks that get appended to roughly every other tool call.`},{id:`model-customizations`,name:`Model customizations`,group:K.MISC_CONFIGURABLE,description:`Access all Claude models with /model, not just latest 3`},{id:`show-more-items-in-select-menus`,name:`Show more items in select menus`,group:K.MISC_CONFIGURABLE,description:`Show 25 items in select menus instead of default 5`},{id:`context-limit`,name:`Context limit`,group:K.MISC_CONFIGURABLE,description:`Override the 200K context limit via CLAUDE_CODE_CONTEXT_LIMIT env var (set before launching CC)`},{id:`patches-applied-indication`,name:`Patches applied indication`,group:K.MISC_CONFIGURABLE,description:`Show "tweakcc patches applied" and tweakcc version inside CC`},{id:`table-format`,name:`Table format`,group:K.MISC_CONFIGURABLE,description:`Tables generated by Claude will be rendered more compactly`},{id:`themes`,name:`Themes`,group:K.MISC_CONFIGURABLE,description:`Your custom themes will be available via /theme`},{id:`thinking-verbs`,name:`Thinking verbs`,group:K.MISC_CONFIGURABLE,description:`Your custom list of thinking verbs will be cycled through`},{id:`thinker-format`,name:`Thinker format`,group:K.MISC_CONFIGURABLE,description:`Your custom format string that thinking verbs are wrapped in will be applied`},{id:`thinker-symbol-chars`,name:`Thinker symbol chars`,group:K.MISC_CONFIGURABLE,description:`Your custom thinking spinner will be rendered`},{id:`thinker-symbol-speed`,name:`Thinker symbol speed`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will play at a custom FPS`},{id:`thinker-symbol-width`,name:`Thinker symbol width`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will be in a box of custom width`},{id:`thinker-symbol-mirror`,name:`Thinker symbol mirror`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will reverse or restart when it finishes`},{id:`input-box-border`,name:`Input box border`,group:K.MISC_CONFIGURABLE,description:`Your custom styles to the main input box's border will be applied`},{id:`subagent-models`,name:`Subagent models`,group:K.MISC_CONFIGURABLE,description:`Use custom models for Plan, Explore, and General subagents`},{id:`thinking-visibility`,name:`Thinking block visibility`,group:K.MISC_CONFIGURABLE,description:`Thinking blocks outputted by the model will show without Ctrl+O`},{id:`hide-startup-banner`,name:`Hide startup banner`,group:K.MISC_CONFIGURABLE,description:`CC's startup banner with "Clawd" and release notes will be hidden`},{id:`hide-ctrl-g-to-edit`,name:`Hide Ctrl+G to edit`,group:K.MISC_CONFIGURABLE,description:`Note about using Ctrl+G to edit prompt will be hidden`},{id:`hide-startup-clawd`,name:`Hide startup Clawd`,group:K.MISC_CONFIGURABLE,description:`The "Clawd" icon on startup will be hidden for a cleaner look`},{id:`increase-file-read-limit`,name:`Increase file read limit`,group:K.MISC_CONFIGURABLE,description:`Max tokens Claude can read from a file at once will be increased`},{id:`suppress-line-numbers`,name:`Suppress line numbers`,group:K.MISC_CONFIGURABLE,description:`"1→" "2→" etc. prefixes for each line of Read output will be omitted`},{id:`suppress-rate-limit-options`,name:`Suppress rate limit options`,group:K.MISC_CONFIGURABLE,description:`/rate-limit-options won't be injected when limits are reached`},{id:`token-count-rounding`,name:`Token count rounding`,group:K.MISC_CONFIGURABLE,description:`Round displayed token counts to the nearest multiple of chosen value`},{id:`remember-skill`,name:`Remember skill`,group:K.MISC_CONFIGURABLE,description:`Register the built-in "/remember" skill to review session memories and update CLAUDE.local.md`},{id:`agents-md`,name:`AGENTS.md (and others)`,group:K.MISC_CONFIGURABLE,description:`Support AGENTS.md and others in addition to CLAUDE.md`},{id:`auto-accept-plan-mode`,name:`Auto-accept plan mode`,group:K.MISC_CONFIGURABLE,description:`Automatically accept plans without the "Ready to code?" confirmation prompt`},{id:`allow-sudo-bypass-permissions`,name:`Allow bypassing permissions with --dangerously-skip-permissions in sudo`,group:K.MISC_CONFIGURABLE,description:`Allow bypassing permissions with --dangerously-skip-permissions even when running with root/sudo privileges`},{id:`suppress-native-installer-warning`,name:`Suppress native installer warning`,group:K.MISC_CONFIGURABLE,description:`Suppress the native installer warning message at startup`},{id:`filter-scroll-escape-sequences`,name:`Filter scroll escape sequences`,group:K.MISC_CONFIGURABLE,description:`Filter out terminal escape sequences that cause unwanted scrolling`},{id:`max-effort-default`,name:`Default Opus 4.7 to max effort`,group:K.MISC_CONFIGURABLE,description:`Opus 4.7 sessions default to "max" reasoning effort instead of "xhigh" (override with /effort or CLAUDE_CODE_EFFORT_LEVEL)`,modelFacing:!0},{id:`autonomous-operation-all-models`,name:`Fable/Mythos prompt set (all models)`,group:K.MISC_CONFIGURABLE,description:`Treats your selected model as Fable/Mythos everywhere CC branches on model family (flips the zQ gate): you get the autonomous-operation prompt (proceed without asking for reversible in-scope work; finish the job before ending the turn), the "# Communicating with the user" comms block in place of "# Text output", /loop dynamic-pacing behavior, and brief-mode comms shaping. Per-model feature-flag routing also follows fable but is inert on a local install`,modelFacing:!0},{id:`adhd-output-style`,name:`ADHD-friendly output style`,group:K.MISC_CONFIGURABLE,description:`EXPERIMENTAL, and it may not visibly change your output. This rewrites prompt text, which is a weak and inconsistent lever: Claude can and does ignore it, the effect varies a lot between one reply and the next, and on some tasks it changes nothing measurable. It was chosen over the alternatives by blind ranking across roughly 900 generated replies, where it placed last in 1 of 16 comparisons and the unmodified prompt placed last in 10 - but that is an average over many replies, not a promise about any one of them. Rewrites the always-on "# Communicating with the user" prompt for skim-first reading. There is no word limit anywhere in it: length follows the substance, and the rules cut kinds of content instead, which is what testing showed actually works. Answer in the first line; show the command, path or value rather than describing it; say each thing once; keep both sides of a count and every qualifier; bold the key terms and keep paragraphs short. Removes the three clauses that drive Claude-speak: the "load-bearing" update cue (the prompt is where that tic comes from), the "readable matters more" ranking, and the "in prose, not headers and sections" ban on the structure skim-readers rely on. Also restates the rules in the per-turn CLAUDE.md reminder, where recency makes them stick, and drops that reminder's "may or may not be relevant" hedge which labelled your own CLAUDE.md as ignorable.`,modelFacing:!0},{id:`output-style-turn-reminder`,name:`Custom output styles carry their own per-turn reminder`,group:K.MISC_CONFIGURABLE,description:`Claude Code restates which output style is active once per turn. Since 2.1.238 that reminder fires for custom styles as well as built-in ones, but its text is fixed: every style you write gets the same generic "Remember to follow the specific guidelines for this style." This lets a style supply its own sentence instead. Add \`turn-reminder:\` to the style's markdown frontmatter and that text is what gets restated each turn, the way the built-in styles carry their own. Without this, the key is read by the frontmatter parser and then dropped on the way to the renderer, so it has no effect. On Claude Code before 2.1.238 this also makes the reminder fire for custom styles at all, which stock builds of that era skipped entirely. The per-turn slot is the position Anthropic's own Opus 5 guidance points at for tone, where a short reminder late in a long prompt is their measured remedy.`,modelFacing:!0},{id:`auto-mode-classifier-model`,name:`Auto-mode classifier model`,group:K.MISC_CONFIGURABLE,description:`Pin auto-mode bash safety classifier to Sonnet 4.6 or Haiku 4.5 instead of the user main-loop model (avoids Opus 4.7 congestion denying tool calls)`,modelFacing:!0},{id:`complexity-router`,name:`[EXPERIMENTAL] Complexity effort router`,group:K.FEATURES,description:`Auto-route reasoning effort (thinking depth) by task complexity: routine work runs at low effort, the top tier only for genuinely frontier problems. Rides on your current model - no model switch, no prompt-cache churn. A one-shot Haiku side-call routes each prompt using a rolling TL;DR summary of the session (so terse follow-ups that continue hard work stay elevated; persisted across resume, reseeded from the main model summary on compaction). While on it drives effort, overriding your saved effortLevel default; an in-session /effort or CLAUDE_CODE_EFFORT_LEVEL still wins. Off by default.`,modelFacing:!0},{id:`fable-plan`,name:`Fable Plan mode`,group:K.FEATURES,description:`Adds a "fableplan" entry to /model: Fable while planning, Opus while executing, each at its own reasoning effort (Fable xhigh, Opus medium by default). Mirrors the mechanism Claude Code already ships for opusplan, so it is a MODEL YOU SELECT — nothing changes for any other model, your selection stays "fableplan" throughout, and no model is ever switched underneath you mid-session. Also surfaces Claude Code's own "Yes, clear context (N% used)" option on the plan-approval dialog, which Claude Code defaults off: clearing hands only the plan to the executing model, where continuing re-sends the entire planning transcript to a different one. Off by default.`,modelFacing:!0},{id:`allow-custom-agent-models`,name:`Allow custom agent models`,group:K.FEATURES,description:`Allow arbitrary model names in custom agent frontmatter (e.g. gemini-2.5-flash)`},{id:`worktree-mode`,name:`Worktree mode`,group:K.FEATURES,description:`Enable the EnterWorktree tool for isolated git worktree sessions`},{id:`session-memory`,name:`Session memory`,group:K.FEATURES,description:`Enable session memory (auto-extraction + past session search)`},{id:`swap-ripgrep-for-fff`,name:`[EXPERIMENTAL] fff for Bash search (grep/find/rg → fff)`,group:K.FEATURES,description:"[EXPERIMENTAL] Route Claude Code's Bash search through fff (fast file finder). CC 2.1.186 shadows the shell `grep`→embedded ugrep and `find`→embedded bfs (and offers `rg`); the agent uses grep ~136x more than rg. This repoints all three at a per-platform fff wrapper that serves, relevance-ranked from a warm-index daemon: literal, regex (RE2 — the dialect the model writes), case-insensitive (-i), multi-word phrases, context (-A/-B/-C), extension globs (-g/--include '*.ts'), and multi-path (app lib scripts) searches. Anything fff can't serve faithfully — PCRE, multiline/newline- or empty-matching regex, only-matching (-o), single-file, non-recursive grep, --no-ignore, find, non-ASCII, lines over 512 bytes, piped stdin → re-exec the real embedded ugrep/bfs/ripgrep. Every engine still ships; any uncertainty falls back, so results never diverge from the model's intent. Transparent (no prompt-compliance reliance) and CC-scoped (the user's own terminal grep/find/rg are untouched). Installs the wrapper into ~/.tweakcc/fff."},{id:`dream-mode`,name:`Dream mode`,group:K.FEATURES,description:`Enable dream (/dream + auto-dream background memory consolidation)`,modelFacing:!0},{id:`lean-memory-types`,name:`Lean memory types`,group:K.FEATURES,description:`Compact "Types of memory" prompt block + on-demand memory-types skill`,modelFacing:!0},{id:`toolsets`,name:`Toolsets`,group:K.FEATURES,description:`Custom toolsets will be registered`},{id:`mcp-non-blocking`,name:`MCP non-blocking`,group:K.FEATURES,description:`If you have MCP servers, CC startup will be much faster`},{id:`mcp-batch-size`,name:`MCP batch size`,group:K.FEATURES,description:`Change the number of MCP servers started in parallel`},{id:`user-message-display`,name:`User message display`,group:K.FEATURES,description:`User messages in the chat history will be styled`},{id:`input-pattern-highlighters`,name:`Input pattern highlighters`,group:K.FEATURES,description:`Custom input highlighters will be registered`},{id:`conversation-title`,name:`Conversation title`,group:K.FEATURES,description:`/title command will be created & enabled`},{id:`voice-mode`,name:`Voice mode`,group:K.FEATURES,description:`Enable /voice command for speech-to-text input (hold Space to record)`},{id:`channels-mode`,name:`Channels mode`,group:K.FEATURES,description:`Enable MCP channel notifications (--channels without allowlist or dev flag)`},{id:`suppress-deferred-tools`,name:`Suppress deferred tools list (DANGEROUS)`,group:K.SYSTEM_REMINDERS,description:`Kill the "deferred tools are now available via ToolSearch" announcement. WARNING: MCP/Cron/EnterPlanMode/WebFetch/Monitor become invisible to the model unless explicitly named.`,modelFacing:!0},{id:`claudemd-context-once-per-conversation`,name:`claudeMd context: once per conversation`,group:K.SYSTEM_REMINDERS,description:`Inject the claudeMd / userEmail / currentDate <system-reminder> only on the first API call per conversation (re-fires after /clear). Default: ON. Toggle OFF for vanilla CC per-turn injection.`,modelFacing:!0}],sc=()=>[...oc],q=e=>e.replace(/\$/g,`\\$`),cc=(e,t,n)=>{let r=[];for(let i of oc){let a=t[i.id];if(n&&!n.includes(i.id)){r.push({id:i.id,name:i.name,group:i.group,applied:!1,skipped:!0,details:`not in --patches filter`,description:i.description});continue}if(a.condition===!1){r.push({id:i.id,name:i.name,group:i.group,applied:!1,skipped:!0,details:`not enabled`,description:i.description});continue}J(`Applying patch: ${i.name}`);let o=a.fn(e),s=o===null,c=!s&&o!==e;s||(e=o),r.push({id:i.id,name:i.name,group:i.group,applied:c,failed:s,description:i.description,modelFacing:i.modelFacing})}return{content:e,results:r}},lc=e=>{let t=_(e,[`--version`],{encoding:`utf8`,timeout:15e3}),n=`${t.stdout??``}${t.stderr??``}`;if(t.error||t.status!==0||/Expected CommonJS module|Bun v|TypeError/.test(n)){let t=Error(`Patched native binary failed startup sanity check (${e}).\n`+n.trim());throw t.stack=t.message,t}},uc=async(e,r,i)=>{let o,c=!1;if(r.nativeInstallationPath){await Vs(r);let e=!1;try{await a.stat(Jc),e=!0}catch{}let t=e?Jc:r.nativeInstallationPath;J(`Extracting claude.js from ${e?`backup`:`native installation`}: ${t}`);let{data:n,clearBytecode:i,error:l}=await T(t,r.version);if(!n)throw Error(`Failed to extract claude.js from native installation${l?`: ${l}`:``}`);c=i;let d=u.join(Z,`native-claudejs-orig.js`);s.writeFileSync(d,n),J(`Saved original extracted JS from native to: ${d}`),o=n.toString(`utf8`)}else{if(await Bs(r),!r.cliPath)throw Error(`cliPath is required for NPM installations`);o=await a.readFile(r.cliPath,{encoding:`utf8`})}let l=[],d=o;if(r.version){let e=await ni({pristine:d,version:r.version,patchFilter:i}).catch(e=>(J(`system-prompt preflight skipped: ${e}`),null)),n=[];for(let r of e?.findings??[]){let e=`preflight: ${ri(r)}`;r.severity===`error`?console.log(t.red(e)):(n.push(e),J(e))}n.length>0&&J(`system-prompt preflight: ${n.length} advisory finding(s) — run --validate-system-prompts for the full report`);let a=(e?.findings??[]).filter(e=>e.check===`raw-non-ascii`);if(a.length>0)throw Error(`system-prompt preflight found ${a.length} span(s) that would introduce raw non-ASCII into the binary; nothing was modified. Re-run with --validate-system-prompts for the full report.`)}let f=await Zr(o);o=f.content;let p=f.results.filter(e=>e.applied),m=f.results.filter(e=>e.failed);if(f.results.length>0){J(`inlineBlobOverrides: ${p.length} applied, ${m.length} failed`);for(let e of m)console.log(`inline-blob: failed "${e.name}" (${e.filename}): ${e.details}`)}for(let e of f.results)l.push({id:`inline-blob:${e.filename}`,name:e.name,group:K.SYSTEM_PROMPTS,applied:e.applied,failed:e.failed,skipped:e.skipped,details:e.details});let h=await Vt(o,r.version??``);o=h.content;for(let e of h.results)l.push({id:`reminder:${e.id}`,name:`Reminder: ${e.name} (${e.state})`,group:K.SYSTEM_REMINDERS,applied:e.applied,failed:e.failed,skipped:e.skipped,details:e.details,description:e.description});let g=await Ir(o,r.version,void 0,i,d);o=g.newContent;let _=[...g.results].sort((e,t)=>e.name.localeCompare(t.name));l.push(..._);let v=e=>e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),y=_.filter(e=>e.applied&&e.details).map(e=>v(`${e.name}: ${e.details}`)),b=e.settings.misc?.tableFormat??`default`,x=e.settings.misc?.showTweakccVersion??!0,S=e.settings.misc?.showPatchesApplied??!0,C=e.settings.misc?.enableModelCustomizations??!0,w=!!e.settings.misc?.swapRipgrepForFff,D=null;w&&(D=await Ds(),D||console.log(`patch: swapRipgrepForFff: no fff wrapper available for this platform — keeping ripgrep`));let O={"verbose-property":{fn:e=>Ie(e),condition:!r.nativeInstallationPath},"read-default-lines":{fn:e=>ls(e)},"context-limit":{fn:e=>ce(e),condition:!!e.settings.misc?.enableContextLimitOverride},opusplan1m:{fn:e=>Ue(e),condition:C&&!r.nativeInstallationPath},"thinking-block-styling":{fn:e=>Ka(e),condition:r.version==null||Yt(r.version,`2.1.26`)<0},"fix-lsp-support":{fn:e=>ai(e)},"fix-summarize-from-here":{fn:e=>oi(e),condition:e.settings.misc?.fixSummarizeFromHere!==!1},"fix-rewind-summary-header":{fn:e=>si(e),condition:e.settings.misc?.fixRewindSummaryHeader!==!1},"statusline-update-throttle":{fn:t=>Qa(t,e.settings.misc?.statuslineThrottleMs??300,e.settings.misc?.statuslineUseFixedInterval??!1),condition:e.settings.misc?.statuslineThrottleMs!=null},"clear-screen":{fn:e=>ss(e)},"strip-empty-system-reminders":{fn:e=>ks(e)},"patches-applied-indication":{fn:e=>st(e,ac,y,x,S)},"model-customizations":{fn:e=>pc(e),condition:C},"show-more-items-in-select-menus":{fn:e=>re(e,25),condition:C},"table-format":{fn:e=>oa(e,b),condition:b!==`default`},themes:{fn:t=>oe(t,e.settings.themes),condition:!!(e.settings.themes&&e.settings.themes.length>0&&JSON.stringify(e.settings.themes)!==JSON.stringify(k.themes))},"thinking-verbs":{fn:t=>be(t,e.settings.thinkingVerbs.verbs),condition:!!e.settings.thinkingVerbs&&JSON.stringify(e.settings.thinkingVerbs.verbs)!==JSON.stringify(k.thinkingVerbs.verbs)},"thinker-format":{fn:t=>de(t,e.settings.thinkingVerbs.format),condition:!!e.settings.thinkingVerbs&&e.settings.thinkingVerbs.format!==k.thinkingVerbs.format},"thinker-symbol-chars":{fn:t=>me(t,e.settings.thinkingStyle.phases),condition:JSON.stringify(e.settings.thinkingStyle.phases)!==JSON.stringify(k.thinkingStyle.phases)},"thinker-symbol-speed":{fn:t=>he(t,e.settings.thinkingStyle.updateInterval),condition:e.settings.thinkingStyle.updateInterval!==k.thinkingStyle.updateInterval&&(r.version==null||Yt(r.version,`2.1.27`)<0)},"thinker-symbol-width":{fn:t=>_e(t,Math.max(...e.settings.thinkingStyle.phases.map(e=>e.length))+1),condition:JSON.stringify(e.settings.thinkingStyle.phases)!==JSON.stringify(k.thinkingStyle.phases)},"thinker-symbol-mirror":{fn:t=>pe(t,e.settings.thinkingStyle.reverseMirror),condition:e.settings.thinkingStyle.reverseMirror!==k.thinkingStyle.reverseMirror},"input-box-border":{fn:t=>le(t,e.settings.inputBox.removeBorder),condition:!!(e.settings.inputBox&&e.settings.inputBox.removeBorder!==k.inputBox.removeBorder)},"subagent-models":{fn:t=>Je(t,e.settings.subagentModels),condition:!!e.settings.subagentModels&&JSON.stringify(e.settings.subagentModels)!==JSON.stringify(k.subagentModels)},"thinking-visibility":{fn:e=>We(e),condition:e.settings.misc?.expandThinkingBlocks??!0},"hide-startup-banner":{fn:e=>xa(e),condition:!!e.settings.misc?.hideStartupBanner},"hide-ctrl-g-to-edit":{fn:e=>Ca(e),condition:!!e.settings.misc?.hideCtrlGToEdit},"hide-startup-clawd":{fn:e=>Ea(e),condition:!!e.settings.misc?.hideStartupClawd},"increase-file-read-limit":{fn:e=>Oa(e),condition:!!e.settings.misc?.increaseFileReadLimit},"suppress-line-numbers":{fn:e=>Aa(e),condition:!!e.settings.misc?.suppressLineNumbers},"suppress-rate-limit-options":{fn:e=>Na(e),condition:!!e.settings.misc?.suppressRateLimitOptions},"token-count-rounding":{fn:t=>no(t,e.settings.misc.tokenCountRounding),condition:!!e.settings.misc?.tokenCountRounding},"remember-skill":{fn:e=>Ga(e),condition:!!e.settings.misc?.enableRememberSkill},"agents-md":{fn:t=>ro(t,e.settings.claudeMdAltNames),condition:!!(e.settings.claudeMdAltNames&&e.settings.claudeMdAltNames.length>0)},"auto-accept-plan-mode":{fn:e=>fo(e),condition:!!e.settings.misc?.autoAcceptPlanMode},"allow-sudo-bypass-permissions":{fn:e=>po(e),condition:!!e.settings.misc?.allowBypassPermissionsInSudo},"suppress-native-installer-warning":{fn:e=>ho(e),condition:!!e.settings.misc?.suppressNativeInstallerWarning},"filter-scroll-escape-sequences":{fn:e=>_o(e),condition:!!e.settings.misc?.filterScrollEscapeSequences},"max-effort-default":{fn:e=>bo(e),condition:!!e.settings.misc?.maxEffortDefault},"autonomous-operation-all-models":{fn:e=>xo(e),condition:!!e.settings.misc?.autonomousOperationAllModels},"adhd-output-style":{fn:e=>wo(e),condition:!!e.settings.misc?.adhdOutputStyle},"output-style-turn-reminder":{fn:e=>Eo(e),condition:!!e.settings.misc?.outputStyleTurnReminder},"auto-mode-classifier-model":{fn:t=>Oo(t,e.settings.misc?.autoModeClassifierModel??`default`),condition:(e.settings.misc?.autoModeClassifierModel??`default`)!==`default`},"complexity-router":{fn:t=>zo(t,e.settings.complexityRouter),condition:e.settings.complexityRouter.enabled},"fable-plan":{fn:t=>Xo(t,e.settings.fablePlan),condition:e.settings.fablePlan.enabled},"allow-custom-agent-models":{fn:e=>yo(e),condition:!!e.settings.misc?.allowCustomAgentModels},"worktree-mode":{fn:e=>vo(e),condition:!!e.settings.misc?.enableWorktreeMode},"session-memory":{fn:e=>za(e),condition:!!e.settings.misc?.enableSessionMemory},"swap-ripgrep-for-fff":{fn:e=>bs(e,D),condition:w&&!!D},"dream-mode":{fn:e=>Ba(e),condition:!!e.settings.misc?.enableDreamMode},"lean-memory-types":{fn:e=>Va(e),condition:!!e.settings.misc?.enableLeanMemoryTypes},toolsets:{fn:t=>Ji(t,e.settings.toolsets,e.settings.defaultToolset,e.settings.planModeToolset),condition:!!(e.settings.toolsets&&e.settings.toolsets.length>0)},"mcp-non-blocking":{fn:e=>Xa(e),condition:!!e.settings.misc?.mcpConnectionNonBlocking&&(r.version==null||Yt(r.version,`2.1.85`)<0)},"mcp-batch-size":{fn:t=>Za(t,e.settings.misc.mcpServerBatchSize),condition:!!e.settings.misc?.mcpServerBatchSize},"user-message-display":{fn:t=>ke(t,e.settings.userMessageDisplay),condition:!!(e.settings.userMessageDisplay&&JSON.stringify(e.settings.userMessageDisplay)!==JSON.stringify(k.userMessageDisplay))},"input-pattern-highlighters":{fn:t=>Pe(t,e.settings.inputPatternHighlighters),condition:!!(e.settings.inputPatternHighlighters&&e.settings.inputPatternHighlighters.length>0)},"conversation-title":{fn:e=>va(e),condition:(e.settings.misc?.enableConversationTitle??!0)&&!r.nativeInstallationPath},"voice-mode":{fn:t=>es(t,e.settings.misc?.enableVoiceConciseOutput??!0),condition:!!e.settings.misc?.enableVoiceMode},"channels-mode":{fn:e=>os(e),condition:!!e.settings.misc?.enableChannelsMode},"suppress-deferred-tools":{fn:e=>As(e),condition:!!e.settings.misc?.suppressDeferredTools},"claudemd-context-once-per-conversation":{fn:e=>Os(e),condition:e.settings.misc?.claudemdContextOncePerConversation??!1}},{content:A,results:j}=cc(o,O,i);o=A,l.push(...j);let M=j.filter(e=>e.failed);if(r.nativeInstallationPath&&M.length>0){let e=Error(`Refusing to repack the native binary: ${M.length} binary patch(es) failed (${M.map(e=>e.id).join(`, `)}) on Claude Code ${r.version}. The binary was left unchanged — your Claude Code still works. Each failure’s cause is in the "patch: … failed to …" line(s) above; this usually means Anthropic changed the code shape in CC ${r.version}, so a patch’s pattern no longer matches. Update tweakcc-fixed, or disable the failing optional patch(es) in ~/.tweakcc/config.json, then re-run --apply.`);throw e.stack=e.message,e}if(r.nativeInstallationPath){J(`Repacking modified claude.js into native installation: ${r.nativeInstallationPath}`);let e=u.join(Z,`native-claudejs-patched.js`);s.writeFileSync(e,o,`utf8`),J(`Saved patched JS from native to: ${e}`);let t=Buffer.from(o,`utf8`),i=await a.mkdtemp(u.join(n.tmpdir(),`tweakcc-native-`)),l=u.join(i,u.basename(r.nativeInstallationPath));try{await a.copyFile(r.nativeInstallationPath,l),await a.chmod(l,s.statSync(r.nativeInstallationPath).mode),await E(l,t,l,c),lc(l);let e=r.nativeInstallationPath,n=u.join(u.dirname(e),`.${u.basename(e)}.tweakcc-${process.pid}`);try{await a.copyFile(l,n),await a.chmod(n,s.statSync(e).mode),await a.rename(n,e)}catch(e){throw await a.rm(n,{force:!0}),e}}finally{await a.rm(i,{recursive:!0,force:!0})}}else{if(!r.cliPath)throw Error(`cliPath is required for NPM installations`);M.length>0&&console.warn(`tweakcc: ${M.length} patch(es) did not apply on Claude Code ${r.version}: ${M.map(e=>e.id).join(`, `)}. Those feature(s) are skipped; everything else was applied. Each cause is in the "patch: … failed to …" line(s) above — usually a CC version whose code shape a patch does not match yet. Update tweakcc-fixed, or disable the failing optional patch(es) in ~/.tweakcc/config.json.`),await Fc(r.cliPath,o,`patch`)}return{config:await rl(e=>{e.changesApplied=!0}),results:l}},dc=[{value:`claude-opus-4-6`,label:`Opus 4.6`,description:`Claude Opus 4.6 (February 2026)`},{value:`claude-sonnet-4-6`,label:`Sonnet 4.6`,description:`Claude Sonnet 4.6 (February 2026)`},{value:`claude-haiku-4-5-20251001`,label:`Haiku 4.5`,description:`Claude Haiku 4.5 (October 2025)`},{value:`claude-opus-4-5-20251101`,label:`Opus 4.5`,description:`Claude Opus 4.5 (November 2025)`},{value:`claude-sonnet-4-5-20250929`,label:`Sonnet 4.5`,description:`Claude Sonnet 4.5 (September 2025)`},{value:`claude-opus-4-1-20250805`,label:`Opus 4.1`,description:`Claude Opus 4.1 (August 2025)`},{value:`claude-opus-4-20250514`,label:`Opus 4`,description:`Claude Opus 4 (May 2025)`},{value:`claude-sonnet-4-20250514`,label:`Sonnet 4`,description:`Claude Sonnet 4 (May 2025)`},{value:`claude-3-7-sonnet-20250219`,label:`Sonnet 3.7`,description:`Claude 3.7 Sonnet (February 2025)`},{value:`claude-3-5-sonnet-20241022`,label:`Sonnet 3.5 (October)`,description:`Claude 3.5 Sonnet (October 2024)`},{value:`claude-3-5-haiku-20241022`,label:`Haiku 3.5`,description:`Claude 3.5 Haiku (October 2024)`},{value:`claude-3-5-sonnet-20240620`,label:`Sonnet 3.5 (June)`,description:`Claude 3.5 Sonnet (June 2024)`},{value:`claude-3-haiku-20240307`,label:`Haiku 3`,description:`Claude 3 Haiku (March 2024)`},{value:`claude-3-opus-20240229`,label:`Opus 3`,description:`Claude 3 Opus (February 2024)`}],fc=e=>{let t=e.match(/(?<![$\w])([$\w]+)\.push\(\{value:[$\w]+,label:[$\w]+,description:"Custom model"\}\)/);if(!t||t.index===void 0)return console.error(`patch: findCustomModelListInsertionPoint: failed to find custom model push`),null;let n=t[1],r=Math.max(0,t.index-5e3),i=e.slice(r,t.index),a=`(?:(?:let|var|const) |,)${q(n)}=.+?;`,o=RegExp(`function [$\\w]+\\([^)]*\\)\\{[\\s\\S]{0,5000}?${a}`,`g`),s=null,c;for(;(c=o.exec(i))!==null;)s=c;return s?{insertionIndex:r+s.index+s[0].length,modelListVar:n}:(console.error(`patch: findCustomModelListInsertionPoint: failed to find function with ${n}`),null)},pc=e=>{if(e.includes(`"value":"claude-opus-4-6"`))return console.log(`patch: modelCustomizations: custom models already present — skipping`),e;let t=fc(e);if(!t)return null;let{insertionIndex:n,modelListVar:r}=t,i=dc.map(e=>`${r}.push(${JSON.stringify(e)});`).join(``),a=e.slice(0,n)+i+e.slice(n);return B(e,a,i,n,n),a};let mc=!1,hc=!1,gc=!1;const _c=()=>mc,vc=()=>hc,yc=()=>gc,bc=()=>{mc=!0},xc=()=>{hc=!0,mc=!0},Sc=()=>{gc=!0},J=(e,...t)=>{_c()&&console.log(e,...t)},Y=(e,...t)=>{vc()&&console.log(e,...t)},X=e=>e.replace(/[\u0080-\uffff]/g,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`));function Cc(){try{let e=p.join(m.homedir(),`.claude.json`);return JSON.parse(f.readFileSync(e,`utf8`)).theme||`dark`}catch{}return`dark`}function wc(e){try{let t=p.join(m.homedir(),`.claude.json`),n=JSON.parse(f.readFileSync(t,`utf8`));n.theme=e,f.writeFileSync(t,JSON.stringify(n,null,2))}catch{}}function Tc(){try{let e=p.join(m.homedir(),`.claude`,`.credentials.json`);switch(JSON.parse(f.readFileSync(e,`utf8`))?.claudeAiOauth?.subscriptionType||`unknown`){case`enterprise`:return`Claude Enterprise`;case`team`:return`Claude Team`;case`max`:return`Claude Max`;case`pro`:return`Claude Pro`}}catch{}return`Claude API`}function Ec(){try{let e=p.join(m.homedir(),`.claude`,`settings.json`),t=JSON.parse(f.readFileSync(e,`utf8`))?.model||`default`;if(t===`opus`)return`Opus 4.5`;let n=dc.find(e=>e.value===t);if(n)return n.label}catch{}return`Opus 4.5`}function Dc(e){process.platform===`win32`?h.spawn(`explorer`,[e],{detached:!0,stdio:`ignore`}).unref():process.platform===`darwin`?h.spawn(`open`,[e],{detached:!0,stdio:`ignore`}).unref():h.spawn(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref()}function Oc(e){if(process.platform===`win32`)h.spawn(`explorer`,[`/select,`,e],{detached:!0,stdio:`ignore`}).unref();else if(process.platform===`darwin`)h.spawn(`open`,[`-R`,e],{detached:!0,stdio:`ignore`}).unref();else{let t=p.dirname(e);h.spawn(`xdg-open`,[t],{detached:!0,stdio:`ignore`}).unref()}}function kc(e,t=`md`){let n=process.env.VISUAL||process.env.EDITOR||(process.platform===`win32`?`notepad`:`vi`),r=p.join(m.tmpdir(),`tweakcc-edit-${process.pid}-${Date.now()}.${t}`);try{f.writeFileSync(r,e,`utf8`);let t=h.spawnSync(`${n} "${r}"`,{stdio:`inherit`,shell:!0});return t.error||typeof t.status==`number`&&t.status!==0?null:f.readFileSync(r,`utf8`)}catch{return null}finally{try{f.unlinkSync(r)}catch{}}}function Ac(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();if(/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/.test(t))return!0;if(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/.test(t)){let e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(e){let[,t,n,r]=e;return parseInt(t)<=255&&parseInt(n)<=255&&parseInt(r)<=255}}if(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/.test(t)){let e=t.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(e){let[,t,n,r]=e;return parseInt(t)<=360&&parseInt(n)<=100&&parseInt(r)<=100}}return!1}function jc(e){if(!Ac(e))return e;let t=e.trim();if(t.startsWith(`rgb(`))return t;if(t.startsWith(`#`)){let e=t.slice(1);return e.length===3&&(e=e.split(``).map(e=>e+e).join(``)),`rgb(${parseInt(e.slice(0,2),16)},${parseInt(e.slice(2,4),16)},${parseInt(e.slice(4,6),16)})`}if(t.startsWith(`hsl(`)){let e=t.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(e){let t=parseInt(e[1])/360,n=parseInt(e[2])/100,r=parseInt(e[3])/100,i=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),a=r<.5?r*(1+n):r+n-r*n,o=2*r-a;return`rgb(${Math.round(i(o,a,t+1/3)*255)},${Math.round(i(o,a,t)*255)},${Math.round(i(o,a,t-1/3)*255)})`}}return e}async function Mc(e,t=`sha256`,n=64*1024){return new Promise((r,i)=>{let a=g.createHash(t),o=f.createReadStream(e,{highWaterMark:n});o.on(`data`,e=>{a.update(e)}),o.on(`end`,()=>{r(a.digest(`hex`))}),o.on(`error`,e=>{i(e)})})}async function Nc(e,t){try{let n=await o.stat(e);return J(`[${t}] Original file mode for ${e}: ${(n.mode&511).toString(8)}`),n.mode}catch(n){return J(`[${t}] Could not stat ${e} (error: ${n}), using default mode 755`),493}}async function Pc(e,t,n,r){let i=`${e}.tweakcc-tmp-${process.pid}`;try{await r(i),await o.chmod(i,t),await o.rename(i,e)}catch(e){try{await o.unlink(i)}catch{}throw e}J(`[${n}] Replaced ${e} via atomic rename, mode ${(t&511).toString(8)}`)}async function Fc(e,t,n=`replace`){await Pc(e,await Nc(e,n),n,e=>o.writeFile(e,t))}async function Ic(e,t,n=`replace`){await Pc(e,await Nc(e,n),n,e=>o.copyFile(t,e))}async function Lc(e){try{return await o.stat(e),!0}catch(e){if(e instanceof Error&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`||e.code===`EACCES`||e.code===`EPERM`))return!1;throw e}}const Rc=e=>e.startsWith(`~`)?p.join(m.homedir(),e.slice(1)):e,zc=(e,t)=>{let n=e=>{let t=e.split(`.`).map(Number);return[t[0]||0,t[1]||0,t[2]||0]},r=n(e),i=n(t);return r[0]===i[0]?r[1]===i[1]?r[2]-i[2]:r[1]-i[1]:r[0]-i[0]},Bc=e=>{let t=e.toString(),n=t.lastIndexOf(`/`);return`new RegExp(${JSON.stringify(t.substring(1,n))}, ${JSON.stringify(t.substring(n+1))})`};function Vc(e,t){if(e==null)return t;if(typeof t!=`object`||!t)return e;if(Array.isArray(t))return Array.isArray(e)?e:t;let n={...e};for(let e of Object.keys(t)){let r=t[e];e in n?typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=Vc(n[e],r)):n[e]=r}return n}const Hc=async(e,t=33554432)=>{let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw Error(`Response body too large: ${n} bytes exceeds the ${t}-byte limit.`);let r=e.body;if(!r){let n=await e.text();if(Buffer.byteLength(n,`utf8`)>t)throw Error(`Response body exceeds the ${t}-byte limit.`);return n}let i=r.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(n){if(o+=n.byteLength,o>t)throw await i.cancel().catch(()=>{}),Error(`Response body exceeds the ${t}-byte limit — aborting download.`);a.push(Buffer.from(n))}}return Buffer.concat(a).toString(`utf8`)},Uc=e=>{let t=e?.settings?.userMessageDisplay;if(!t)return;let n=!!t.prefix,r=`borderStyle`in t,i=`padding`in t,a=`paddingX`in t,o=`fitBoxToContent`in t,s=t.padding;n&&(e.settings.userMessageDisplay={format:(t.prefix?.format||``)+(t.message?.format||`{}`),styling:[...t.prefix?.styling||[],...t.message?.styling||[]],foregroundColor:t.message?.foregroundColor===`rgb(0,0,0)`?`default`:t.message?.foregroundColor||t.prefix?.foregroundColor||`default`,backgroundColor:t.message?.backgroundColor===`rgb(0,0,0)`?null:t.message?.backgroundColor||t.prefix?.backgroundColor||null,borderStyle:`none`,borderColor:`rgb(255,255,255)`,paddingX:0,paddingY:0,fitBoxToContent:!1});let c=e.settings.userMessageDisplay;r||(c.borderStyle=`none`,c.borderColor=`rgb(255,255,255)`),i&&!a?(c.paddingX=s||0,c.paddingY=0,delete c.padding):a||(c.paddingX=0,c.paddingY=0),o||(c.fitBoxToContent=!1)},Wc=e=>{let t=e?.settings?.misc;t&&`hideCtrlGToEditPrompt`in t&&(t.hideCtrlGToEdit=t.hideCtrlGToEditPrompt,delete t.hideCtrlGToEditPrompt)};async function Gc(){try{let e=await o.readFile(Q,`utf8`),t=JSON.parse(e);return Object.hasOwn(t,`ccInstallationDir`)?(t.ccInstallationDir&&!t.ccInstallationPath&&(t.ccInstallationPath=d.join(t.ccInstallationDir,`cli.js`)),delete t.ccInstallationDir,t.lastModified=new Date().toISOString(),await Qc(),await o.writeFile(Q,JSON.stringify(t,null,2)),!0):!1}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`||e instanceof SyntaxError)return!1;throw e}}const Kc=()=>{let e=process.env.TWEAKCC_CONFIG_DIR?.trim();if(e&&e.length>0)return Rc(e);let t=d.join(r.homedir(),`.tweakcc`),n=d.join(r.homedir(),`.claude`,`tweakcc`),i=process.env.XDG_CONFIG_HOME;try{if(c.existsSync(t))return t}catch(e){J(`Failed to check if ${t} exists: ${e}`)}try{if(c.existsSync(n))return n}catch(e){J(`Failed to check if ${n} exists: ${e}`)}return i?d.join(i,`tweakcc`):t},Z=Kc(),Q=d.join(Z,`config.json`),qc=d.join(Z,`cli.js.backup`),Jc=d.join(Z,`native-binary.backup`),$=d.join(Z,`system-prompts`),Yc=d.join(Z,`system-reminders`),Xc=d.join(Z,`prompt-data-cache`),Zc=()=>{let e=Z,n=r.homedir(),i=[d.join(n,`.tweakcc`),d.join(n,`.claude`,`tweakcc`),process.env.XDG_CONFIG_HOME?d.join(process.env.XDG_CONFIG_HOME,`tweakcc`):null].filter(e=>e!==null).filter(t=>{try{return c.existsSync(t)&&t!==e}catch{return!1}});i.length>0&&(console.warn(t.yellow(`
784
+ Search backend note (fff): prefer one bare identifier over regex; results are relevance-ranked, so read the top hit first. A trailing [def] tag flags a line that likely defines the symbol.`,ps,`Grep description`),r=ys(r,`Prefer dedicated tools over`,` grep/find results are ranked most-relevant-first (read the top hit first); a trailing [def] tag flags a likely definition line, and a grep or find -name that matches nothing automatically lists the closest approximate hits tagged [~approx]. Add --fuzzy to force typo-tolerant or partial matching, e.g. grep --fuzzy SomeName.`,ms,`Bash description`),r},xs=3e4;function Ss(){let{platform:e,arch:t}=process;return e===`darwin`&&t===`arm64`?`aarch64-apple-darwin`:e===`linux`&&t===`arm64`?`aarch64-unknown-linux-musl`:e===`linux`&&t===`x64`?`x86_64-unknown-linux-musl`:null}function Cs(){try{let e=u.dirname(y(import.meta.url));for(let t=0;t<6;t++){let t=u.join(e,`package.json`);if(s.existsSync(t))try{let n=JSON.parse(s.readFileSync(t,`utf-8`)).version;if(typeof n==`string`)return{root:e,version:n}}catch{}let n=u.dirname(e);if(n===e)break;e=n}}catch{}return null}async function ws(e){try{return await a.access(e,s.constants.X_OK),!0}catch{return!1}}async function Ts(e,t){await a.mkdir(u.dirname(t),{recursive:!0});let n=`${t}.tmp-${process.pid}`;try{await a.copyFile(e,n),await a.chmod(n,493),await a.rename(n,t)}catch(e){throw await a.unlink(n).catch(()=>{}),e}}async function Es(e){try{return(await a.stat(e)).mtimeMs}catch{return-1}}async function Ds(){let e=Ss();if(!e)return null;let t=u.join(Z,`fff`,e,`rg-fff`),n=u.join(u.dirname(t),`.version`),r=Cs();if(r)for(let e of[`release`,`debug`]){let n=u.join(r.root,`tools`,`rg-fff`,`target`,e,`rg-fff`);if(s.existsSync(n))return await Es(n)>await Es(t)&&await Ts(n,t),t}let i=r?.version,o=await a.readFile(n,`utf-8`).then(e=>e.trim()).catch(()=>null);if(await ws(t)&&(!i||o===i))return t;if(!i)return null;let c=`https://github.com/skrabe/tweakcc-fixed/releases/download/v${i}`;try{let r=await fetch(`${c}/rg-fff-${e}`,{signal:AbortSignal.timeout(xs)});if(!r.ok)return null;let o=Buffer.from(await r.arrayBuffer()),s=await fetch(`${c}/rg-fff-${e}.sha256`,{signal:AbortSignal.timeout(xs)});if(!s.ok)return console.error(`patch: swapRipgrepForFff: rg-fff-${e}.sha256 unavailable (${s.status}) — keeping ripgrep`),null;let l=(await s.text()).trim().split(/\s+/)[0]?.toLowerCase(),d=S.createHash(`sha256`).update(o).digest(`hex`);if(!l||l!==d)return console.error(`patch: swapRipgrepForFff: rg-fff-${e} checksum ${l?`mismatch`:`missing`} — keeping ripgrep`),null;await a.mkdir(u.dirname(t),{recursive:!0});let f=`${t}.tmp-${process.pid}`;try{await a.writeFile(f,o),await a.chmod(f,493),await a.rename(f,t)}catch(e){throw await a.unlink(f).catch(()=>{}),e}return await a.writeFile(n,i).catch(()=>{}),t}catch{return null}}const Os=e=>{if(/function [$\w]+\(([$\w]+),[$\w]+\)\{if\(Object\.entries\([$\w]+\)\.length===0\)return \1;var ([$\w]+)=\1\[0\];if\(\2&&\2\.isMeta/.test(e))return e;let t=e.match(/function ([$\w]+)\(([$\w]+),([$\w]+)\)\{if\(Object\.entries\(\3\)\.length===0\)return \2;return\[([\s\S]+?),\.\.\.\2\]\}/);if(!t||t.index===void 0){let t=e.indexOf(`"tengu_context_size"`);if(t>0){let n=e.slice(Math.max(0,t-5e3),t);if(/function [$\w]+\([$\w]+,[$\w]+\)\{return [$\w]+;?\}\s*async function/.test(n))return console.log(`patch: claudemd-context-once-per-conversation: claudemd-context override suppressed wrapper — no-op`),e}return console.error(`patch: claudemd-context-once-per-conversation: failed to find kY6 wrapper`),null}let[n,r,i,a,o]=t,s=`${i}_0`,c=`function ${r}(${i},${a}){if(Object.entries(${a}).length===0)return ${i};var ${s}=${i}[0];if(${s}&&${s}.isMeta&&${s}.message&&typeof ${s}.message.content==="string"&&${s}.message.content.indexOf("<system-reminder>\\nAs you answer the user")===0)return ${i};${i}.unshift(${o});return ${i}}`,l=t.index,u=l+n.length,d=e.slice(0,l)+c+e.slice(u);return B(e,d,c,l,u),d},ks=e=>{let t=e.match(/function ([$\w]+)\(([$\w]+)\)\{return`<system-reminder>\n\$\{\2\}\n<\/system-reminder>`\}/);if(!t||t.index===void 0)return/function [$\w]+\(([$\w]+)\)\{if\(!\1\|\|!\1\.trim\(\)\|\|\1==="\(no content\)"\)return"\(no content\)";return`<system-reminder>/.test(e)?e:(console.error(`patch: strip-empty-system-reminders: failed to find LW(H) wrapper`),null);let[n,r,i]=t,a=`function ${r}(${i}){if(!${i}||!${i}.trim()||${i}==="(no content)")return"(no content)";return\`<system-reminder>\n\${${i}}\n</system-reminder>\`}`,o=t.index,s=o+n.length,c=e.slice(0,o)+a+e.slice(s);return B(e,c,a,o,s),c},As=e=>{if(!e.includes(`The following deferred tools are now available via`))return console.log(`patch: suppress-deferred-tools: anchor not present in this CC build — no-op`),e;let t=`case"deferred_tools_delta":{`;if(e.includes(`case"deferred_tools_delta":{return [];`))return e;let n=e.indexOf(t);if(n<0)return console.error(`patch: suppress-deferred-tools: failed to find case header`),null;if(e.indexOf(t,n+1)>=0)return console.error(`patch: suppress-deferred-tools: case header is ambiguous (multiple matches)`),null;let r=n+28,i=`return [];`,a=e.slice(0,r)+i+e.slice(r);return B(e,a,i,r,r),a},js=[`__tweakcc`,`tweakcc v`],Ms=e=>js.some(t=>e.includes(t)),Ns=Math.max(...js.map(e=>e.length)),Ps=async e=>new Promise(t=>{let n;try{n=l(e,{encoding:`latin1`,highWaterMark:8<<20})}catch{t(!1);return}let r=``,i=!1,a=e=>{i||(i=!0,n.destroy(),t(e))};n.on(`data`,e=>{let t=r+e;if(Ms(t)){a(!0);return}r=t.slice(-(Ns-1))}),n.on(`error`,()=>a(!1)),n.on(`close`,()=>a(!1)),n.on(`end`,()=>a(!1))});var Fs=class extends Error{constructor(e){super(`Refusing to back up ${e}: it carries tweakcc markers, so it is already patched. Backing it up would overwrite the only pristine copy with a patched one. Run \`tweakcc --restore\` first, or reinstall Claude Code, then try again.`),this.name=`NonPristineBackupError`}};const Is=async e=>{if(await Ps(e))throw new Fs(e)},Ls=async(e,t)=>{let n=`${t}.tmp-${process.pid}`;try{await o.copyFile(e,n),await o.rename(n,t)}catch(e){try{await o.unlink(n)}catch{}throw e}},Rs=async e=>{if(!e.cliPath){J(`backupClijs: Skipping for native installation (no cliPath)`);return}await Is(e.cliPath),await Qc(),J(`Backing up cli.js to ${qc}`),await Ls(e.cliPath,qc),await rl(t=>{t.changesApplied=!1,t.ccVersion=e.version})},zs=async e=>{e.nativeInstallationPath&&(await Is(e.nativeInstallationPath),await Qc(),J(`Backing up native binary to ${Jc}`),await Ls(e.nativeInstallationPath,Jc),await rl(t=>{t.changesApplied=!1,t.ccVersion=e.version}))},Bs=async e=>e.cliPath?await Lc(qc)?(J(`Restoring cli.js from backup to ${e.cliPath}`),await Ic(e.cliPath,qc,`restore`),await Ct(),await rl(e=>{e.changesApplied=!1}),!0):(J(`restoreClijsFromBackup: No backup file exists, skipping`),!1):(J(`restoreClijsFromBackup: Skipping for native installation (no cliPath)`),!1),Vs=async e=>e.nativeInstallationPath?await Lc(Jc)?(J(`Restoring native binary from backup to ${e.nativeInstallationPath}`),await Ic(e.nativeInstallationPath,Jc,`restore`),await Ct(),await rl(e=>{e.changesApplied=!1}),!0):(J(`restoreNativeBinaryFromBackup: No backup file exists, skipping`),!1):(J(`restoreNativeBinaryFromBackup: No native installation path, skipping`),!1),Hs=`/*@@TWEAKCC_MODULE:`,Us=(e,t)=>{let n=e.lastIndexOf(Hs,t);if(n===-1)return Ws(e);let r=e.indexOf(Hs,n+1);return Ws(e.slice(n,r===-1?e.length:r))},Ws=e=>{let t=Array.from(e.matchAll(/[^$\w]([$\w]+)(?:\.(?:cyan|gray|green|red|yellow|ansi256|bgAnsi256|bgHex|bgRgb|hex|rgb|bold|dim|inverse|italic|strikethrough|underline)\b)+\(/g)),n={};for(let e of t){let t=e[1];n[t]=(n[t]||0)+1}let r,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);return r},Gs=e=>{let t=e.slice(0,2e3).match(/[,;]([$\w]+)=\([$\w]+,[$\w]+,[$\w]+\)=>\{[$\w]+=[$\w]+!=null\?/);if(t)return t[1];let n=e.slice(0,1e4),r=Array.from(n.matchAll(/(?:var |,)([$\w]+)=\([$\w]+,[$\w]+,[$\w]+\)=>\{/g));if(r.length>0){let e=r[0][1];for(let t of r)t[1].length<e.length&&(e=t[1]);return e}console.log(`patch: getModuleLoaderFunction: failed to find module loader function`)},Ks=e=>{let t=e.match(/var ([$\w]+)=[$\w]+\((?:\([$\w]+\)=>|function\([$\w]+\))\{var [$\w]+=Symbol\.for\("react\.(transitional\.)?element"\)/);if(!t){console.log(`patch: getReactModuleNameNonBun: failed to find React module name`);return}return t[1]},qs=e=>{let t=Ks(e);if(!t){console.log(`^ patch: getReactModuleFunctionBun: failed to find React module name (Bun)`);return}let n=RegExp(`var ([$\\w]+)=[$\\w]+\\((?:\\([$\\w]+,[$\\w]+\\)=>|function\\([$\\w]+,[$\\w]+\\))\\{[$\\w]+\\.exports=${q(t)}\\(\\)`),r=e.match(n);if(!r){console.log(`patch: getReactModuleFunctionBun: failed to find React module function (Bun) (reactModuleNameNonBun=${t})`);return}return r[1]};let G=null,Js=null;const Ys=e=>{if(G!=null)return G;let t=Gs(e);if(!t){console.log(`^ patch: getReactVar: failed to find moduleLoader`),G=void 0;return}let n=Ks(e);if(!n){console.log(`^ patch: getReactVar: failed to find reactModuleVarNonBun`),G=void 0;return}let r=RegExp(`[^$\\w]([$\\w]+)=${q(t)}\\(${q(n)}\\(\\),1\\)`),i=e.match(r);if(i)return G=i[1],G;let a=qs(e);if(!a){console.log(`^ patch: getReactVar: failed to find reactModuleFunctionBun`),G=void 0;return}let o=RegExp(`[^$\\w]([$\\w]+)=${q(t)}\\(${q(a)}\\(\\),1\\)`),s=e.match(o);if(!s){console.log(`patch: getReactVar: failed to find bunPattern (moduleLoader=${t}, reactModuleVarNonBun=${n}, reactModuleFunctionBun=${a})`),G=void 0;return}return G=s[1],G},Xs=()=>{G=null},Zs=e=>{let t=e.match(/import\{createRequire as ([$\w]+)\}from"node:module";/);if(!t)return;let n=t[1],r=RegExp(`var ([$\\w]+)=${q(n)}\\(import\\.meta\\.url\\)`),i=e.match(r);if(!i){console.log(`patch: findRequireFunc: failed to find require function variable (createRequireVar=${n})`);return}return i[1]},Qs=e=>{if(Js!=null)return Js;let t=Zs(e);return t?(Js=t,Js):(Js=`require`,Js)},$s=()=>{Js=null},ec=()=>{Xs(),$s()},tc=e=>{let t=e.match(/function ([$\w]+)\([$\w]+\)\{let [$\w]+=[$\w]+\.c\(\d+\)[^;]{0,240};if\([$\w]+\[0\]!==[$\w]+\)\(\{color:[$\w]+,backgroundColor:[$\w]+,dimColor:[$\w]+,bold:[$\w]+/);if(t)return t[1];let n=e.match(/\bfunction ([$\w]+).{0,80}color:[$\w]+,backgroundColor:[$\w]+,dimColor:[$\w]+(?:=![01])?,bold:[$\w]+(?:=![01])?/);if(!n){console.log(`patch: findTextComponent: failed to find text component`);return}return n[1]},nc=(e,t)=>{let n=`[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*`,r=RegExp(`var [^;]{0,120};var [$\\w]+=${n}\\(\\(\\)=>\\{[^}]{0,500}([$\\w]+)=${q(t)}\\}\\)`),i=e.match(r)?.[1]??t,a=RegExp(`function ([$\\w]+)\\([^)]+\\)\\{(?=[\\s\\S]{0,2500}createElement\\(${q(i)},\\{\\.\\.\\.[$\\w]+,borderColor:)[\\s\\S]{0,3000}?return [$\\w]+\\}var [^;]{0,160};var [$\\w]+=${n}\\(\\(\\)=>\\{[^}]{0,600}([$\\w]+)=\\1\\}\\)`);return e.match(a)?.[2]},rc=e=>{let t=e.match(/function ([$\w]+)\(.{0,2000}[^$\w]([$\w]+)=[$\w]+(?:\.default)?\.createElement\("ink-box".{0,500}?return \2/);if(t)return t[1];let n=e.match(/function ([$\w]+)\(.{0,200}children:[$\w]+,flexWrap:[$\w]+.{0,2000}?\.createElement\("ink-box"/);if(n)return n[1];let r=e.match(/[^$\w]([$\w]+)\.displayName="Box"/);if(r)return r[1];let i=e.match(/function ([$\w]+)\([$\w]+\)\{let [$\w]+=[$\w]+(?:\.[$\w]+)?\(\d+\).{0,3000}createElement\("ink-box"/);if(i)return i[1];let a=e.match(/function ([$\w]+)\(\{children:([$\w]+),ref:[$\w]+.{0,600}?\.\.\.([$\w]+)\}\)\{.{0,2500}?"margin".{0,2500}?"padding".{0,1200}?"gap".{0,1200}?\3\.flexWrap\?\?="nowrap",\3\.flexDirection\?\?="row",\3\.flexGrow\?\?=0,\3\.flexShrink\?\?=1,\3\.overflowX=\3\.overflowX\?\?\3\.overflow\?\?"visible",\3\.overflowY=\3\.overflowY\?\?\3\.overflow\?\?"visible",[$\w]+(?:\.default)?\.createElement\("ink-box",\{[^}]*style:\3\},\2\)/);if(a)return nc(e,a[1])??a[1];let o=e.match(/function ([$\w]+)\(\{children:[$\w]+,ref:[$\w]+,tabIndex:[$\w]+,autoFocus:[$\w]+/);if(o)return o[1];console.error(`patch: findBoxComponent: failed to find Box component (neither ink-box createElement nor displayName found)`)},ic=e(import.meta.url),ac=(()=>{try{return ic(`../package.json`).version}catch{return ic(`../../package.json`).version}})();let K=function(e){return e.SYSTEM_PROMPTS=`System Prompts`,e.ALWAYS_APPLIED=`Always Applied`,e.MISC_CONFIGURABLE=`Misc Configurable`,e.FEATURES=`Features`,e.SYSTEM_REMINDERS=`System Reminders`,e}({});const oc=[{id:`verbose-property`,name:`Verbose property`,group:K.ALWAYS_APPLIED,description:`Token counter will show (2s · ↓ 169 tokens · thinking)`},{id:`read-default-lines`,name:`Read default lines (env-gated)`,group:K.ALWAYS_APPLIED,description:`Read tool default line cap becomes CLAUDE_CODE_READ_DEFAULT_LINES env var (falls back to 2000 if unset)`},{id:`opusplan1m`,name:`Opusplan[1m] support`,group:K.ALWAYS_APPLIED,description:`Use the "Opus Plan 1M" model: Opus for planning, Sonnet 1M context for building`},{id:`thinking-block-styling`,name:`Thinking block styling`,group:K.ALWAYS_APPLIED,description:`Restore dim/gray + italic styling for thinking blocks`},{id:`fix-lsp-support`,name:`Fix LSP support`,group:K.ALWAYS_APPLIED,description:`Enable/fix nascent LSP support`},{id:`fix-summarize-from-here`,name:`Fix "Summarize from here"`,group:K.MISC_CONFIGURABLE,description:`Make "Summarize from here" summarize only the messages after the rewind point (feed the slice, not the whole conversation)`,modelFacing:!0},{id:`fix-rewind-summary-header`,name:`Honest rewind summary header`,group:K.MISC_CONFIGURABLE,description:`Label a rewind summary as a deliberate rewind instead of the misleading "ran out of context" header`,modelFacing:!0},{id:`statusline-update-throttle`,name:`Statusline update throttling correction`,group:K.ALWAYS_APPLIED,description:`Statusline updates will be properly throttled instead of queued (or debounced)`},{id:`clear-screen`,name:`Clear screen command`,group:K.ALWAYS_APPLIED,description:`Register a /clear-screen command that clears the terminal scrollback and redraws without resetting conversation context`},{id:`strip-empty-system-reminders`,name:`Strip empty <system-reminder> wrappers`,group:K.ALWAYS_APPLIED,description:`Short-circuits CC's universal system-reminder wrapper so empty / "(no content)" inputs produce no reminder. Kills the drift-inducing "<system-reminder>(no content)</system-reminder>" blocks that get appended to roughly every other tool call.`},{id:`model-customizations`,name:`Model customizations`,group:K.MISC_CONFIGURABLE,description:`Access all Claude models with /model, not just latest 3`},{id:`show-more-items-in-select-menus`,name:`Show more items in select menus`,group:K.MISC_CONFIGURABLE,description:`Show 25 items in select menus instead of default 5`},{id:`context-limit`,name:`Context limit`,group:K.MISC_CONFIGURABLE,description:`Override the 200K context limit via CLAUDE_CODE_CONTEXT_LIMIT env var (set before launching CC)`},{id:`patches-applied-indication`,name:`Patches applied indication`,group:K.MISC_CONFIGURABLE,description:`Show "tweakcc patches applied" and tweakcc version inside CC`},{id:`table-format`,name:`Table format`,group:K.MISC_CONFIGURABLE,description:`Tables generated by Claude will be rendered more compactly`},{id:`themes`,name:`Themes`,group:K.MISC_CONFIGURABLE,description:`Your custom themes will be available via /theme`},{id:`thinking-verbs`,name:`Thinking verbs`,group:K.MISC_CONFIGURABLE,description:`Your custom list of thinking verbs will be cycled through`},{id:`thinker-format`,name:`Thinker format`,group:K.MISC_CONFIGURABLE,description:`Your custom format string that thinking verbs are wrapped in will be applied`},{id:`thinker-symbol-chars`,name:`Thinker symbol chars`,group:K.MISC_CONFIGURABLE,description:`Your custom thinking spinner will be rendered`},{id:`thinker-symbol-speed`,name:`Thinker symbol speed`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will play at a custom FPS`},{id:`thinker-symbol-width`,name:`Thinker symbol width`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will be in a box of custom width`},{id:`thinker-symbol-mirror`,name:`Thinker symbol mirror`,group:K.MISC_CONFIGURABLE,description:`The thinking spinner will reverse or restart when it finishes`},{id:`input-box-border`,name:`Input box border`,group:K.MISC_CONFIGURABLE,description:`Your custom styles to the main input box's border will be applied`},{id:`subagent-models`,name:`Subagent models`,group:K.MISC_CONFIGURABLE,description:`Use custom models for Plan, Explore, and General subagents`},{id:`thinking-visibility`,name:`Thinking block visibility`,group:K.MISC_CONFIGURABLE,description:`Thinking blocks outputted by the model will show without Ctrl+O`},{id:`hide-startup-banner`,name:`Hide startup banner`,group:K.MISC_CONFIGURABLE,description:`CC's startup banner with "Clawd" and release notes will be hidden`},{id:`hide-ctrl-g-to-edit`,name:`Hide Ctrl+G to edit`,group:K.MISC_CONFIGURABLE,description:`Note about using Ctrl+G to edit prompt will be hidden`},{id:`hide-startup-clawd`,name:`Hide startup Clawd`,group:K.MISC_CONFIGURABLE,description:`The "Clawd" icon on startup will be hidden for a cleaner look`},{id:`increase-file-read-limit`,name:`Increase file read limit`,group:K.MISC_CONFIGURABLE,description:`Max tokens Claude can read from a file at once will be increased`},{id:`suppress-line-numbers`,name:`Suppress line numbers`,group:K.MISC_CONFIGURABLE,description:`"1→" "2→" etc. prefixes for each line of Read output will be omitted`},{id:`suppress-rate-limit-options`,name:`Suppress rate limit options`,group:K.MISC_CONFIGURABLE,description:`/rate-limit-options won't be injected when limits are reached`},{id:`token-count-rounding`,name:`Token count rounding`,group:K.MISC_CONFIGURABLE,description:`Round displayed token counts to the nearest multiple of chosen value`},{id:`remember-skill`,name:`Remember skill`,group:K.MISC_CONFIGURABLE,description:`Register the built-in "/remember" skill to review session memories and update CLAUDE.local.md`},{id:`agents-md`,name:`AGENTS.md (and others)`,group:K.MISC_CONFIGURABLE,description:`Support AGENTS.md and others in addition to CLAUDE.md`},{id:`auto-accept-plan-mode`,name:`Auto-accept plan mode`,group:K.MISC_CONFIGURABLE,description:`Automatically accept plans without the "Ready to code?" confirmation prompt`},{id:`allow-sudo-bypass-permissions`,name:`Allow bypassing permissions with --dangerously-skip-permissions in sudo`,group:K.MISC_CONFIGURABLE,description:`Allow bypassing permissions with --dangerously-skip-permissions even when running with root/sudo privileges`},{id:`suppress-native-installer-warning`,name:`Suppress native installer warning`,group:K.MISC_CONFIGURABLE,description:`Suppress the native installer warning message at startup`},{id:`filter-scroll-escape-sequences`,name:`Filter scroll escape sequences`,group:K.MISC_CONFIGURABLE,description:`Filter out terminal escape sequences that cause unwanted scrolling`},{id:`max-effort-default`,name:`Default Opus 4.7 to max effort`,group:K.MISC_CONFIGURABLE,description:`Opus 4.7 sessions default to "max" reasoning effort instead of "xhigh" (override with /effort or CLAUDE_CODE_EFFORT_LEVEL)`,modelFacing:!0},{id:`autonomous-operation-all-models`,name:`Fable/Mythos prompt set (all models)`,group:K.MISC_CONFIGURABLE,description:`Treats your selected model as Fable/Mythos everywhere CC branches on model family (flips the zQ gate): you get the autonomous-operation prompt (proceed without asking for reversible in-scope work; finish the job before ending the turn), the "# Communicating with the user" comms block in place of "# Text output", /loop dynamic-pacing behavior, and brief-mode comms shaping. Per-model feature-flag routing also follows fable but is inert on a local install`,modelFacing:!0},{id:`adhd-output-style`,name:`ADHD-friendly output style`,group:K.MISC_CONFIGURABLE,description:`EXPERIMENTAL, and it may not visibly change your output. This rewrites prompt text, which is a weak and inconsistent lever: Claude can and does ignore it, the effect varies a lot between one reply and the next, and on some tasks it changes nothing measurable. It was chosen over the alternatives by blind ranking across roughly 900 generated replies, where it placed last in 1 of 16 comparisons and the unmodified prompt placed last in 10 - but that is an average over many replies, not a promise about any one of them. Rewrites the always-on "# Communicating with the user" prompt for skim-first reading. There is no word limit anywhere in it: length follows the substance, and the rules cut kinds of content instead, which is what testing showed actually works. Answer in the first line; show the command, path or value rather than describing it; say each thing once; keep both sides of a count and every qualifier; bold the key terms and keep paragraphs short. Removes the three clauses that drive Claude-speak: the "load-bearing" update cue (the prompt is where that tic comes from), the "readable matters more" ranking, and the "in prose, not headers and sections" ban on the structure skim-readers rely on. Also restates the rules in the per-turn CLAUDE.md reminder, where recency makes them stick, and drops that reminder's "may or may not be relevant" hedge which labelled your own CLAUDE.md as ignorable.`,modelFacing:!0},{id:`output-style-turn-reminder`,name:`Custom output styles carry their own per-turn reminder`,group:K.MISC_CONFIGURABLE,description:`Claude Code restates which output style is active once per turn. Since 2.1.238 that reminder fires for custom styles as well as built-in ones, but its text is fixed: every style you write gets the same generic "Remember to follow the specific guidelines for this style." This lets a style supply its own sentence instead. Add \`turn-reminder:\` to the style's markdown frontmatter and that text is what gets restated each turn, the way the built-in styles carry their own. Without this, the key is read by the frontmatter parser and then dropped on the way to the renderer, so it has no effect. On Claude Code before 2.1.238 this also makes the reminder fire for custom styles at all, which stock builds of that era skipped entirely. The per-turn slot is the position Anthropic's own Opus 5 guidance points at for tone, where a short reminder late in a long prompt is their measured remedy.`,modelFacing:!0},{id:`auto-mode-classifier-model`,name:`Auto-mode classifier model`,group:K.MISC_CONFIGURABLE,description:`Pin auto-mode bash safety classifier to Sonnet 4.6 or Haiku 4.5 instead of the user main-loop model (avoids Opus 4.7 congestion denying tool calls)`,modelFacing:!0},{id:`complexity-router`,name:`[EXPERIMENTAL] Complexity effort router`,group:K.FEATURES,description:`Auto-route reasoning effort (thinking depth) by task complexity: routine work runs at low effort, the top tier only for genuinely frontier problems. Rides on your current model - no model switch, no prompt-cache churn. A one-shot Haiku side-call routes each prompt using a rolling TL;DR summary of the session (so terse follow-ups that continue hard work stay elevated; persisted across resume, reseeded from the main model summary on compaction). While on it drives effort, overriding your saved effortLevel default; an in-session /effort or CLAUDE_CODE_EFFORT_LEVEL still wins. Off by default.`,modelFacing:!0},{id:`fable-plan`,name:`Fable Plan mode`,group:K.FEATURES,description:`Adds a "fableplan" entry to /model: Fable while planning, Opus while executing, each at its own reasoning effort (Fable xhigh, Opus medium by default). Mirrors the mechanism Claude Code already ships for opusplan, so it is a MODEL YOU SELECT — nothing changes for any other model, your selection stays "fableplan" throughout, and no model is ever switched underneath you mid-session. Also surfaces Claude Code's own "Yes, clear context (N% used)" option on the plan-approval dialog, which Claude Code defaults off: clearing hands only the plan to the executing model, where continuing re-sends the entire planning transcript to a different one. Off by default.`,modelFacing:!0},{id:`allow-custom-agent-models`,name:`Allow custom agent models`,group:K.FEATURES,description:`Allow arbitrary model names in custom agent frontmatter (e.g. gemini-2.5-flash)`},{id:`worktree-mode`,name:`Worktree mode`,group:K.FEATURES,description:`Enable the EnterWorktree tool for isolated git worktree sessions`},{id:`session-memory`,name:`Session memory`,group:K.FEATURES,description:`Enable session memory (auto-extraction + past session search)`},{id:`swap-ripgrep-for-fff`,name:`[EXPERIMENTAL] fff for Bash search (grep/find/rg → fff)`,group:K.FEATURES,description:"[EXPERIMENTAL] Route Claude Code's Bash search through fff (fast file finder). CC 2.1.186 shadows the shell `grep`→embedded ugrep and `find`→embedded bfs (and offers `rg`); the agent uses grep ~136x more than rg. This repoints all three at a per-platform fff wrapper that serves, relevance-ranked from a warm-index daemon: literal, regex (RE2 — the dialect the model writes), case-insensitive (-i), multi-word phrases, context (-A/-B/-C), extension globs (-g/--include '*.ts'), and multi-path (app lib scripts) searches. Anything fff can't serve faithfully — PCRE, multiline/newline- or empty-matching regex, only-matching (-o), single-file, non-recursive grep, --no-ignore, find, non-ASCII, lines over 512 bytes, piped stdin → re-exec the real embedded ugrep/bfs/ripgrep. Every engine still ships; any uncertainty falls back, so results never diverge from the model's intent. Transparent (no prompt-compliance reliance) and CC-scoped (the user's own terminal grep/find/rg are untouched). Installs the wrapper into ~/.tweakcc/fff."},{id:`dream-mode`,name:`Dream mode`,group:K.FEATURES,description:`Enable dream (/dream + auto-dream background memory consolidation)`,modelFacing:!0},{id:`lean-memory-types`,name:`Lean memory types`,group:K.FEATURES,description:`Compact "Types of memory" prompt block + on-demand memory-types skill`,modelFacing:!0},{id:`toolsets`,name:`Toolsets`,group:K.FEATURES,description:`Custom toolsets will be registered`},{id:`mcp-non-blocking`,name:`MCP non-blocking`,group:K.FEATURES,description:`If you have MCP servers, CC startup will be much faster`},{id:`mcp-batch-size`,name:`MCP batch size`,group:K.FEATURES,description:`Change the number of MCP servers started in parallel`},{id:`user-message-display`,name:`User message display`,group:K.FEATURES,description:`User messages in the chat history will be styled`},{id:`input-pattern-highlighters`,name:`Input pattern highlighters`,group:K.FEATURES,description:`Custom input highlighters will be registered`},{id:`conversation-title`,name:`Conversation title`,group:K.FEATURES,description:`/title command will be created & enabled`},{id:`voice-mode`,name:`Voice mode`,group:K.FEATURES,description:`Enable /voice command for speech-to-text input (hold Space to record)`},{id:`channels-mode`,name:`Channels mode`,group:K.FEATURES,description:`Enable MCP channel notifications (--channels without allowlist or dev flag)`},{id:`suppress-deferred-tools`,name:`Suppress deferred tools list (DANGEROUS)`,group:K.SYSTEM_REMINDERS,description:`Kill the "deferred tools are now available via ToolSearch" announcement. WARNING: MCP/Cron/EnterPlanMode/WebFetch/Monitor become invisible to the model unless explicitly named.`,modelFacing:!0},{id:`claudemd-context-once-per-conversation`,name:`claudeMd context: once per conversation`,group:K.SYSTEM_REMINDERS,description:`Inject the claudeMd / userEmail / currentDate <system-reminder> only on the first API call per conversation (re-fires after /clear). Default: ON. Toggle OFF for vanilla CC per-turn injection.`,modelFacing:!0}],sc=()=>[...oc],q=e=>e.replace(/\$/g,`\\$`),cc=(e,t,n)=>{let r=[];for(let i of oc){let a=t[i.id];if(n&&!n.includes(i.id)){r.push({id:i.id,name:i.name,group:i.group,applied:!1,skipped:!0,details:`not in --patches filter`,description:i.description});continue}if(a.condition===!1){r.push({id:i.id,name:i.name,group:i.group,applied:!1,skipped:!0,details:`not enabled`,description:i.description});continue}J(`Applying patch: ${i.name}`);let o=a.fn(e),s=o===null,c=!s&&o!==e;s||(e=o),r.push({id:i.id,name:i.name,group:i.group,applied:c,failed:s,description:i.description,modelFacing:i.modelFacing})}return{content:e,results:r}},lc=e=>{if(process.env.TWEAKCC_ALLOW_CROSS_PLATFORM===`1`)return;let t=_(e,[`--version`],{encoding:`utf8`,timeout:15e3}),n=`${t.stdout??``}${t.stderr??``}`;if(t.error||t.status!==0||/Expected CommonJS module|Bun v|TypeError/.test(n)){let t=Error(`Patched native binary failed startup sanity check (${e}).\n`+n.trim());throw t.stack=t.message,t}},uc=async(e,r,i)=>{let o,c=!1;if(r.nativeInstallationPath){await Vs(r);let e=!1;try{await a.stat(Jc),e=!0}catch{}let t=e?Jc:r.nativeInstallationPath;J(`Extracting claude.js from ${e?`backup`:`native installation`}: ${t}`);let{data:n,clearBytecode:i,error:l}=await T(t,r.version);if(!n)throw Error(`Failed to extract claude.js from native installation${l?`: ${l}`:``}`);c=i;let d=u.join(Z,`native-claudejs-orig.js`);s.writeFileSync(d,n),J(`Saved original extracted JS from native to: ${d}`),o=n.toString(`utf8`)}else{if(await Bs(r),!r.cliPath)throw Error(`cliPath is required for NPM installations`);o=await a.readFile(r.cliPath,{encoding:`utf8`})}let l=[],d=o;if(r.version){let e=await ni({pristine:d,version:r.version,patchFilter:i}).catch(e=>(J(`system-prompt preflight skipped: ${e}`),null)),n=[];for(let r of e?.findings??[]){let e=`preflight: ${ri(r)}`;r.severity===`error`?console.log(t.red(e)):(n.push(e),J(e))}n.length>0&&J(`system-prompt preflight: ${n.length} advisory finding(s) — run --validate-system-prompts for the full report`);let a=(e?.findings??[]).filter(e=>e.check===`raw-non-ascii`);if(a.length>0)throw Error(`system-prompt preflight found ${a.length} span(s) that would introduce raw non-ASCII into the binary; nothing was modified. Re-run with --validate-system-prompts for the full report.`)}let f=await Zr(o);o=f.content;let p=f.results.filter(e=>e.applied),m=f.results.filter(e=>e.failed);if(f.results.length>0){J(`inlineBlobOverrides: ${p.length} applied, ${m.length} failed`);for(let e of m)console.log(`inline-blob: failed "${e.name}" (${e.filename}): ${e.details}`)}for(let e of f.results)l.push({id:`inline-blob:${e.filename}`,name:e.name,group:K.SYSTEM_PROMPTS,applied:e.applied,failed:e.failed,skipped:e.skipped,details:e.details});let h=await Vt(o,r.version??``);o=h.content;for(let e of h.results)l.push({id:`reminder:${e.id}`,name:`Reminder: ${e.name} (${e.state})`,group:K.SYSTEM_REMINDERS,applied:e.applied,failed:e.failed,skipped:e.skipped,details:e.details,description:e.description});let g=await Ir(o,r.version,void 0,i,d);o=g.newContent;let _=[...g.results].sort((e,t)=>e.name.localeCompare(t.name));l.push(..._);let v=e=>e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),y=_.filter(e=>e.applied&&e.details).map(e=>v(`${e.name}: ${e.details}`)),b=e.settings.misc?.tableFormat??`default`,x=e.settings.misc?.showTweakccVersion??!0,S=e.settings.misc?.showPatchesApplied??!0,C=e.settings.misc?.enableModelCustomizations??!0,w=!!e.settings.misc?.swapRipgrepForFff,D=null;w&&(D=await Ds(),D||console.log(`patch: swapRipgrepForFff: no fff wrapper available for this platform — keeping ripgrep`));let O={"verbose-property":{fn:e=>Ie(e),condition:!r.nativeInstallationPath},"read-default-lines":{fn:e=>ls(e)},"context-limit":{fn:e=>ce(e),condition:!!e.settings.misc?.enableContextLimitOverride},opusplan1m:{fn:e=>Ue(e),condition:C&&!r.nativeInstallationPath},"thinking-block-styling":{fn:e=>Ka(e),condition:r.version==null||Yt(r.version,`2.1.26`)<0},"fix-lsp-support":{fn:e=>ai(e)},"fix-summarize-from-here":{fn:e=>oi(e),condition:e.settings.misc?.fixSummarizeFromHere!==!1},"fix-rewind-summary-header":{fn:e=>si(e),condition:e.settings.misc?.fixRewindSummaryHeader!==!1},"statusline-update-throttle":{fn:t=>Qa(t,e.settings.misc?.statuslineThrottleMs??300,e.settings.misc?.statuslineUseFixedInterval??!1),condition:e.settings.misc?.statuslineThrottleMs!=null},"clear-screen":{fn:e=>ss(e)},"strip-empty-system-reminders":{fn:e=>ks(e)},"patches-applied-indication":{fn:e=>st(e,ac,y,x,S)},"model-customizations":{fn:e=>pc(e),condition:C},"show-more-items-in-select-menus":{fn:e=>re(e,25),condition:C},"table-format":{fn:e=>oa(e,b),condition:b!==`default`},themes:{fn:t=>oe(t,e.settings.themes),condition:!!(e.settings.themes&&e.settings.themes.length>0&&JSON.stringify(e.settings.themes)!==JSON.stringify(k.themes))},"thinking-verbs":{fn:t=>be(t,e.settings.thinkingVerbs.verbs),condition:!!e.settings.thinkingVerbs&&JSON.stringify(e.settings.thinkingVerbs.verbs)!==JSON.stringify(k.thinkingVerbs.verbs)},"thinker-format":{fn:t=>de(t,e.settings.thinkingVerbs.format),condition:!!e.settings.thinkingVerbs&&e.settings.thinkingVerbs.format!==k.thinkingVerbs.format},"thinker-symbol-chars":{fn:t=>me(t,e.settings.thinkingStyle.phases),condition:JSON.stringify(e.settings.thinkingStyle.phases)!==JSON.stringify(k.thinkingStyle.phases)},"thinker-symbol-speed":{fn:t=>he(t,e.settings.thinkingStyle.updateInterval),condition:e.settings.thinkingStyle.updateInterval!==k.thinkingStyle.updateInterval&&(r.version==null||Yt(r.version,`2.1.27`)<0)},"thinker-symbol-width":{fn:t=>_e(t,Math.max(...e.settings.thinkingStyle.phases.map(e=>e.length))+1),condition:JSON.stringify(e.settings.thinkingStyle.phases)!==JSON.stringify(k.thinkingStyle.phases)},"thinker-symbol-mirror":{fn:t=>pe(t,e.settings.thinkingStyle.reverseMirror),condition:e.settings.thinkingStyle.reverseMirror!==k.thinkingStyle.reverseMirror},"input-box-border":{fn:t=>le(t,e.settings.inputBox.removeBorder),condition:!!(e.settings.inputBox&&e.settings.inputBox.removeBorder!==k.inputBox.removeBorder)},"subagent-models":{fn:t=>Je(t,e.settings.subagentModels),condition:!!e.settings.subagentModels&&JSON.stringify(e.settings.subagentModels)!==JSON.stringify(k.subagentModels)},"thinking-visibility":{fn:e=>We(e),condition:e.settings.misc?.expandThinkingBlocks??!0},"hide-startup-banner":{fn:e=>xa(e),condition:!!e.settings.misc?.hideStartupBanner},"hide-ctrl-g-to-edit":{fn:e=>Ca(e),condition:!!e.settings.misc?.hideCtrlGToEdit},"hide-startup-clawd":{fn:e=>Ea(e),condition:!!e.settings.misc?.hideStartupClawd},"increase-file-read-limit":{fn:e=>Oa(e),condition:!!e.settings.misc?.increaseFileReadLimit},"suppress-line-numbers":{fn:e=>Aa(e),condition:!!e.settings.misc?.suppressLineNumbers},"suppress-rate-limit-options":{fn:e=>Na(e),condition:!!e.settings.misc?.suppressRateLimitOptions},"token-count-rounding":{fn:t=>no(t,e.settings.misc.tokenCountRounding),condition:!!e.settings.misc?.tokenCountRounding},"remember-skill":{fn:e=>Ga(e),condition:!!e.settings.misc?.enableRememberSkill},"agents-md":{fn:t=>ro(t,e.settings.claudeMdAltNames),condition:!!(e.settings.claudeMdAltNames&&e.settings.claudeMdAltNames.length>0)},"auto-accept-plan-mode":{fn:e=>fo(e),condition:!!e.settings.misc?.autoAcceptPlanMode},"allow-sudo-bypass-permissions":{fn:e=>po(e),condition:!!e.settings.misc?.allowBypassPermissionsInSudo},"suppress-native-installer-warning":{fn:e=>ho(e),condition:!!e.settings.misc?.suppressNativeInstallerWarning},"filter-scroll-escape-sequences":{fn:e=>_o(e),condition:!!e.settings.misc?.filterScrollEscapeSequences},"max-effort-default":{fn:e=>bo(e),condition:!!e.settings.misc?.maxEffortDefault},"autonomous-operation-all-models":{fn:e=>xo(e),condition:!!e.settings.misc?.autonomousOperationAllModels},"adhd-output-style":{fn:e=>wo(e),condition:!!e.settings.misc?.adhdOutputStyle},"output-style-turn-reminder":{fn:e=>Eo(e),condition:!!e.settings.misc?.outputStyleTurnReminder},"auto-mode-classifier-model":{fn:t=>Oo(t,e.settings.misc?.autoModeClassifierModel??`default`),condition:(e.settings.misc?.autoModeClassifierModel??`default`)!==`default`},"complexity-router":{fn:t=>zo(t,e.settings.complexityRouter),condition:e.settings.complexityRouter.enabled},"fable-plan":{fn:t=>Xo(t,e.settings.fablePlan),condition:e.settings.fablePlan.enabled},"allow-custom-agent-models":{fn:e=>yo(e),condition:!!e.settings.misc?.allowCustomAgentModels},"worktree-mode":{fn:e=>vo(e),condition:!!e.settings.misc?.enableWorktreeMode},"session-memory":{fn:e=>za(e),condition:!!e.settings.misc?.enableSessionMemory},"swap-ripgrep-for-fff":{fn:e=>bs(e,D),condition:w&&!!D},"dream-mode":{fn:e=>Ba(e),condition:!!e.settings.misc?.enableDreamMode},"lean-memory-types":{fn:e=>Va(e),condition:!!e.settings.misc?.enableLeanMemoryTypes},toolsets:{fn:t=>Ji(t,e.settings.toolsets,e.settings.defaultToolset,e.settings.planModeToolset),condition:!!(e.settings.toolsets&&e.settings.toolsets.length>0)},"mcp-non-blocking":{fn:e=>Xa(e),condition:!!e.settings.misc?.mcpConnectionNonBlocking&&(r.version==null||Yt(r.version,`2.1.85`)<0)},"mcp-batch-size":{fn:t=>Za(t,e.settings.misc.mcpServerBatchSize),condition:!!e.settings.misc?.mcpServerBatchSize},"user-message-display":{fn:t=>ke(t,e.settings.userMessageDisplay),condition:!!(e.settings.userMessageDisplay&&JSON.stringify(e.settings.userMessageDisplay)!==JSON.stringify(k.userMessageDisplay))},"input-pattern-highlighters":{fn:t=>Pe(t,e.settings.inputPatternHighlighters),condition:!!(e.settings.inputPatternHighlighters&&e.settings.inputPatternHighlighters.length>0)},"conversation-title":{fn:e=>va(e),condition:(e.settings.misc?.enableConversationTitle??!0)&&!r.nativeInstallationPath},"voice-mode":{fn:t=>es(t,e.settings.misc?.enableVoiceConciseOutput??!0),condition:!!e.settings.misc?.enableVoiceMode},"channels-mode":{fn:e=>os(e),condition:!!e.settings.misc?.enableChannelsMode},"suppress-deferred-tools":{fn:e=>As(e),condition:!!e.settings.misc?.suppressDeferredTools},"claudemd-context-once-per-conversation":{fn:e=>Os(e),condition:e.settings.misc?.claudemdContextOncePerConversation??!1}},{content:A,results:j}=cc(o,O,i);o=A,l.push(...j);let M=j.filter(e=>e.failed);if(r.nativeInstallationPath&&M.length>0){let e=Error(`Refusing to repack the native binary: ${M.length} binary patch(es) failed (${M.map(e=>e.id).join(`, `)}) on Claude Code ${r.version}. The binary was left unchanged — your Claude Code still works. Each failure’s cause is in the "patch: … failed to …" line(s) above; this usually means Anthropic changed the code shape in CC ${r.version}, so a patch’s pattern no longer matches. Update tweakcc-fixed, or disable the failing optional patch(es) in ~/.tweakcc/config.json, then re-run --apply.`);throw e.stack=e.message,e}if(r.nativeInstallationPath){J(`Repacking modified claude.js into native installation: ${r.nativeInstallationPath}`);let e=u.join(Z,`native-claudejs-patched.js`);s.writeFileSync(e,o,`utf8`),J(`Saved patched JS from native to: ${e}`);let t=Buffer.from(o,`utf8`),i=await a.mkdtemp(u.join(n.tmpdir(),`tweakcc-native-`)),l=u.join(i,u.basename(r.nativeInstallationPath));try{await a.copyFile(r.nativeInstallationPath,l),await a.chmod(l,s.statSync(r.nativeInstallationPath).mode),await E(l,t,l,c),lc(l);let e=r.nativeInstallationPath,n=u.join(u.dirname(e),`.${u.basename(e)}.tweakcc-${process.pid}`);try{await a.copyFile(l,n),await a.chmod(n,s.statSync(e).mode),await a.rename(n,e)}catch(e){throw await a.rm(n,{force:!0}),e}}finally{await a.rm(i,{recursive:!0,force:!0})}}else{if(!r.cliPath)throw Error(`cliPath is required for NPM installations`);M.length>0&&console.warn(`tweakcc: ${M.length} patch(es) did not apply on Claude Code ${r.version}: ${M.map(e=>e.id).join(`, `)}. Those feature(s) are skipped; everything else was applied. Each cause is in the "patch: … failed to …" line(s) above — usually a CC version whose code shape a patch does not match yet. Update tweakcc-fixed, or disable the failing optional patch(es) in ~/.tweakcc/config.json.`),await Fc(r.cliPath,o,`patch`)}return{config:await rl(e=>{e.changesApplied=!0}),results:l}},dc=[{value:`claude-opus-4-6`,label:`Opus 4.6`,description:`Claude Opus 4.6 (February 2026)`},{value:`claude-sonnet-4-6`,label:`Sonnet 4.6`,description:`Claude Sonnet 4.6 (February 2026)`},{value:`claude-haiku-4-5-20251001`,label:`Haiku 4.5`,description:`Claude Haiku 4.5 (October 2025)`},{value:`claude-opus-4-5-20251101`,label:`Opus 4.5`,description:`Claude Opus 4.5 (November 2025)`},{value:`claude-sonnet-4-5-20250929`,label:`Sonnet 4.5`,description:`Claude Sonnet 4.5 (September 2025)`},{value:`claude-opus-4-1-20250805`,label:`Opus 4.1`,description:`Claude Opus 4.1 (August 2025)`},{value:`claude-opus-4-20250514`,label:`Opus 4`,description:`Claude Opus 4 (May 2025)`},{value:`claude-sonnet-4-20250514`,label:`Sonnet 4`,description:`Claude Sonnet 4 (May 2025)`},{value:`claude-3-7-sonnet-20250219`,label:`Sonnet 3.7`,description:`Claude 3.7 Sonnet (February 2025)`},{value:`claude-3-5-sonnet-20241022`,label:`Sonnet 3.5 (October)`,description:`Claude 3.5 Sonnet (October 2024)`},{value:`claude-3-5-haiku-20241022`,label:`Haiku 3.5`,description:`Claude 3.5 Haiku (October 2024)`},{value:`claude-3-5-sonnet-20240620`,label:`Sonnet 3.5 (June)`,description:`Claude 3.5 Sonnet (June 2024)`},{value:`claude-3-haiku-20240307`,label:`Haiku 3`,description:`Claude 3 Haiku (March 2024)`},{value:`claude-3-opus-20240229`,label:`Opus 3`,description:`Claude 3 Opus (February 2024)`}],fc=e=>{let t=e.match(/(?<![$\w])([$\w]+)\.push\(\{value:[$\w]+,label:[$\w]+,description:"Custom model"\}\)/);if(!t||t.index===void 0)return console.error(`patch: findCustomModelListInsertionPoint: failed to find custom model push`),null;let n=t[1],r=Math.max(0,t.index-5e3),i=e.slice(r,t.index),a=`(?:(?:let|var|const) |,)${q(n)}=.+?;`,o=RegExp(`function [$\\w]+\\([^)]*\\)\\{[\\s\\S]{0,5000}?${a}`,`g`),s=null,c;for(;(c=o.exec(i))!==null;)s=c;return s?{insertionIndex:r+s.index+s[0].length,modelListVar:n}:(console.error(`patch: findCustomModelListInsertionPoint: failed to find function with ${n}`),null)},pc=e=>{if(e.includes(`"value":"claude-opus-4-6"`))return console.log(`patch: modelCustomizations: custom models already present — skipping`),e;let t=fc(e);if(!t)return null;let{insertionIndex:n,modelListVar:r}=t,i=dc.map(e=>`${r}.push(${JSON.stringify(e)});`).join(``),a=e.slice(0,n)+i+e.slice(n);return B(e,a,i,n,n),a};let mc=!1,hc=!1,gc=!1;const _c=()=>mc,vc=()=>hc,yc=()=>gc,bc=()=>{mc=!0},xc=()=>{hc=!0,mc=!0},Sc=()=>{gc=!0},J=(e,...t)=>{_c()&&console.log(e,...t)},Y=(e,...t)=>{vc()&&console.log(e,...t)},X=e=>e.replace(/[\u0080-\uffff]/g,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`));function Cc(){try{let e=p.join(m.homedir(),`.claude.json`);return JSON.parse(f.readFileSync(e,`utf8`)).theme||`dark`}catch{}return`dark`}function wc(e){try{let t=p.join(m.homedir(),`.claude.json`),n=JSON.parse(f.readFileSync(t,`utf8`));n.theme=e,f.writeFileSync(t,JSON.stringify(n,null,2))}catch{}}function Tc(){try{let e=p.join(m.homedir(),`.claude`,`.credentials.json`);switch(JSON.parse(f.readFileSync(e,`utf8`))?.claudeAiOauth?.subscriptionType||`unknown`){case`enterprise`:return`Claude Enterprise`;case`team`:return`Claude Team`;case`max`:return`Claude Max`;case`pro`:return`Claude Pro`}}catch{}return`Claude API`}function Ec(){try{let e=p.join(m.homedir(),`.claude`,`settings.json`),t=JSON.parse(f.readFileSync(e,`utf8`))?.model||`default`;if(t===`opus`)return`Opus 4.5`;let n=dc.find(e=>e.value===t);if(n)return n.label}catch{}return`Opus 4.5`}function Dc(e){process.platform===`win32`?h.spawn(`explorer`,[e],{detached:!0,stdio:`ignore`}).unref():process.platform===`darwin`?h.spawn(`open`,[e],{detached:!0,stdio:`ignore`}).unref():h.spawn(`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref()}function Oc(e){if(process.platform===`win32`)h.spawn(`explorer`,[`/select,`,e],{detached:!0,stdio:`ignore`}).unref();else if(process.platform===`darwin`)h.spawn(`open`,[`-R`,e],{detached:!0,stdio:`ignore`}).unref();else{let t=p.dirname(e);h.spawn(`xdg-open`,[t],{detached:!0,stdio:`ignore`}).unref()}}function kc(e,t=`md`){let n=process.env.VISUAL||process.env.EDITOR||(process.platform===`win32`?`notepad`:`vi`),r=p.join(m.tmpdir(),`tweakcc-edit-${process.pid}-${Date.now()}.${t}`);try{f.writeFileSync(r,e,`utf8`);let t=h.spawnSync(`${n} "${r}"`,{stdio:`inherit`,shell:!0});return t.error||typeof t.status==`number`&&t.status!==0?null:f.readFileSync(r,`utf8`)}catch{return null}finally{try{f.unlinkSync(r)}catch{}}}function Ac(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();if(/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/.test(t))return!0;if(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/.test(t)){let e=t.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(e){let[,t,n,r]=e;return parseInt(t)<=255&&parseInt(n)<=255&&parseInt(r)<=255}}if(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/.test(t)){let e=t.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(e){let[,t,n,r]=e;return parseInt(t)<=360&&parseInt(n)<=100&&parseInt(r)<=100}}return!1}function jc(e){if(!Ac(e))return e;let t=e.trim();if(t.startsWith(`rgb(`))return t;if(t.startsWith(`#`)){let e=t.slice(1);return e.length===3&&(e=e.split(``).map(e=>e+e).join(``)),`rgb(${parseInt(e.slice(0,2),16)},${parseInt(e.slice(2,4),16)},${parseInt(e.slice(4,6),16)})`}if(t.startsWith(`hsl(`)){let e=t.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(e){let t=parseInt(e[1])/360,n=parseInt(e[2])/100,r=parseInt(e[3])/100,i=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),a=r<.5?r*(1+n):r+n-r*n,o=2*r-a;return`rgb(${Math.round(i(o,a,t+1/3)*255)},${Math.round(i(o,a,t)*255)},${Math.round(i(o,a,t-1/3)*255)})`}}return e}async function Mc(e,t=`sha256`,n=64*1024){return new Promise((r,i)=>{let a=g.createHash(t),o=f.createReadStream(e,{highWaterMark:n});o.on(`data`,e=>{a.update(e)}),o.on(`end`,()=>{r(a.digest(`hex`))}),o.on(`error`,e=>{i(e)})})}async function Nc(e,t){try{let n=await o.stat(e);return J(`[${t}] Original file mode for ${e}: ${(n.mode&511).toString(8)}`),n.mode}catch(n){return J(`[${t}] Could not stat ${e} (error: ${n}), using default mode 755`),493}}async function Pc(e,t,n,r){let i=`${e}.tweakcc-tmp-${process.pid}`;try{await r(i),await o.chmod(i,t),await o.rename(i,e)}catch(e){try{await o.unlink(i)}catch{}throw e}J(`[${n}] Replaced ${e} via atomic rename, mode ${(t&511).toString(8)}`)}async function Fc(e,t,n=`replace`){await Pc(e,await Nc(e,n),n,e=>o.writeFile(e,t))}async function Ic(e,t,n=`replace`){await Pc(e,await Nc(e,n),n,e=>o.copyFile(t,e))}async function Lc(e){try{return await o.stat(e),!0}catch(e){if(e instanceof Error&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`||e.code===`EACCES`||e.code===`EPERM`))return!1;throw e}}const Rc=e=>e.startsWith(`~`)?p.join(m.homedir(),e.slice(1)):e,zc=(e,t)=>{let n=e=>{let t=e.split(`.`).map(Number);return[t[0]||0,t[1]||0,t[2]||0]},r=n(e),i=n(t);return r[0]===i[0]?r[1]===i[1]?r[2]-i[2]:r[1]-i[1]:r[0]-i[0]},Bc=e=>{let t=e.toString(),n=t.lastIndexOf(`/`);return`new RegExp(${JSON.stringify(t.substring(1,n))}, ${JSON.stringify(t.substring(n+1))})`};function Vc(e,t){if(e==null)return t;if(typeof t!=`object`||!t)return e;if(Array.isArray(t))return Array.isArray(e)?e:t;let n={...e};for(let e of Object.keys(t)){let r=t[e];e in n?typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=Vc(n[e],r)):n[e]=r}return n}const Hc=async(e,t=33554432)=>{let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw Error(`Response body too large: ${n} bytes exceeds the ${t}-byte limit.`);let r=e.body;if(!r){let n=await e.text();if(Buffer.byteLength(n,`utf8`)>t)throw Error(`Response body exceeds the ${t}-byte limit.`);return n}let i=r.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(n){if(o+=n.byteLength,o>t)throw await i.cancel().catch(()=>{}),Error(`Response body exceeds the ${t}-byte limit — aborting download.`);a.push(Buffer.from(n))}}return Buffer.concat(a).toString(`utf8`)},Uc=e=>{let t=e?.settings?.userMessageDisplay;if(!t)return;let n=!!t.prefix,r=`borderStyle`in t,i=`padding`in t,a=`paddingX`in t,o=`fitBoxToContent`in t,s=t.padding;n&&(e.settings.userMessageDisplay={format:(t.prefix?.format||``)+(t.message?.format||`{}`),styling:[...t.prefix?.styling||[],...t.message?.styling||[]],foregroundColor:t.message?.foregroundColor===`rgb(0,0,0)`?`default`:t.message?.foregroundColor||t.prefix?.foregroundColor||`default`,backgroundColor:t.message?.backgroundColor===`rgb(0,0,0)`?null:t.message?.backgroundColor||t.prefix?.backgroundColor||null,borderStyle:`none`,borderColor:`rgb(255,255,255)`,paddingX:0,paddingY:0,fitBoxToContent:!1});let c=e.settings.userMessageDisplay;r||(c.borderStyle=`none`,c.borderColor=`rgb(255,255,255)`),i&&!a?(c.paddingX=s||0,c.paddingY=0,delete c.padding):a||(c.paddingX=0,c.paddingY=0),o||(c.fitBoxToContent=!1)},Wc=e=>{let t=e?.settings?.misc;t&&`hideCtrlGToEditPrompt`in t&&(t.hideCtrlGToEdit=t.hideCtrlGToEditPrompt,delete t.hideCtrlGToEditPrompt)};async function Gc(){try{let e=await o.readFile(Q,`utf8`),t=JSON.parse(e);return Object.hasOwn(t,`ccInstallationDir`)?(t.ccInstallationDir&&!t.ccInstallationPath&&(t.ccInstallationPath=d.join(t.ccInstallationDir,`cli.js`)),delete t.ccInstallationDir,t.lastModified=new Date().toISOString(),await Qc(),await o.writeFile(Q,JSON.stringify(t,null,2)),!0):!1}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`||e instanceof SyntaxError)return!1;throw e}}const Kc=()=>{let e=process.env.TWEAKCC_CONFIG_DIR?.trim();if(e&&e.length>0)return Rc(e);let t=d.join(r.homedir(),`.tweakcc`),n=d.join(r.homedir(),`.claude`,`tweakcc`),i=process.env.XDG_CONFIG_HOME;try{if(c.existsSync(t))return t}catch(e){J(`Failed to check if ${t} exists: ${e}`)}try{if(c.existsSync(n))return n}catch(e){J(`Failed to check if ${n} exists: ${e}`)}return i?d.join(i,`tweakcc`):t},Z=Kc(),Q=d.join(Z,`config.json`),qc=d.join(Z,`cli.js.backup`),Jc=d.join(Z,`native-binary.backup`),$=d.join(Z,`system-prompts`),Yc=d.join(Z,`system-reminders`),Xc=d.join(Z,`prompt-data-cache`),Zc=()=>{let e=Z,n=r.homedir(),i=[d.join(n,`.tweakcc`),d.join(n,`.claude`,`tweakcc`),process.env.XDG_CONFIG_HOME?d.join(process.env.XDG_CONFIG_HOME,`tweakcc`):null].filter(e=>e!==null).filter(t=>{try{return c.existsSync(t)&&t!==e}catch{return!1}});i.length>0&&(console.warn(t.yellow(`
785
785
  Multiple configuration locations detected:`)),console.warn(t.gray(` Active: ${e}`)),console.warn(t.gray(` Other existing locations:`)),i.forEach(e=>{console.warn(t.gray(` - ${e}`))}),console.warn(t.gray(` Only the active location is used. To switch locations,`)),console.warn(t.gray(` move your config.json to the desired directory.
786
786
  `)))},Qc=async()=>{await o.mkdir(Z,{recursive:!0}),await o.mkdir($,{recursive:!0}),await o.mkdir(Yc,{recursive:!0});let e=d.join(Z,`.gitignore`);try{await o.stat(e)}catch(t){t instanceof Error&&`code`in t&&t.code===`ENOENT`&&await o.writeFile(e,[`.DS_Store`,`prompt-data-cache`,`cli.js.backup`,`native-binary.backup`,`native-claudejs-orig.js`,`native-claudejs-patched.js`,`systemPromptAppliedHashes.json`,`systemPromptOriginalHashes.json`,`system-prompts/*.diff.html`].join(i)+i)}};let $c=null;const el=()=>({ccVersion:``,ccInstallationPath:null,lastModified:new Date().toISOString(),changesApplied:!0,settings:k}),tl=e=>{let t=e?.settings?.thinkingVerbs;t?.punctuation&&(t.format=`{}`+t.punctuation,delete t.punctuation),Uc(e),e.settings=Vc(e.settings,k),e.settings.inputPatternHighlighters&&(e.settings.inputPatternHighlighters=e.settings.inputPatternHighlighters.map(e=>Vc(e,A))),e.settings.toolsets&&(e.settings.toolsets=e.settings.toolsets.map(e=>Vc(e,j))),e.settings.themes&&(e.settings.themes=e.settings.themes.map(e=>Vc(e,M)));{let t=e.settings.complexityRouter;delete t.mode;let n=k.complexityRouter,r=(e,t,n,r)=>typeof e==`number`&&Number.isFinite(e)?Math.min(r,Math.max(n,Math.round(e))):t;t.messageCap=r(t.messageCap,n.messageCap,500,4e5),t.assistantCap=r(t.assistantCap,n.assistantCap,500,4e5),t.timeoutMs=r(t.timeoutMs,n.timeoutMs,1e3,12e4),(typeof t.systemPrompt!=`string`||t.systemPrompt.trim().length===0)&&(t.systemPrompt=n.systemPrompt);let i=k.complexityRouter.levels,a=[`low`,`medium`,`high`,`xhigh`,`max`];t.levels=Array.isArray(t.levels)&&t.levels.length>0?t.levels.map((e,t)=>{let n=i[Math.min(t,i.length-1)],r=Vc(e,n);return a.includes(r.effort)||(r.effort=n.effort),t>=i.length&&(r.id=`level-${t}`),r}):i.map(e=>({...e}))}Wc(e),delete e.settings.launchText},nl=async()=>{let e=el();try{J(`Reading config at ${Q}`),Zc();let t=await o.readFile(Q,`utf8`),n={...e,...JSON.parse(t)},r=JSON.stringify(n);tl(n);let i=await wt($);return i&&(n.changesApplied=!1),(JSON.stringify(n)!==r||i)&&await il(n),$c=n,n}catch(t){if(t instanceof Error&&`code`in t&&t.code===`ENOENT`)return e;if(t instanceof SyntaxError){let t=`${Q}.corrupt-${Date.now()}`;try{await o.rename(Q,t),console.error(`tweakcc: ${Q} was not valid JSON — moved it to ${t} and reset to defaults.`)}catch{console.error(`tweakcc: ${Q} was not valid JSON — falling back to defaults.`)}return e}throw t}},rl=async e=>(J(`Updating config at ${Q}`),$c||=await nl(),e($c),$c.lastModified=new Date().toISOString(),await il($c),$c),il=async e=>{e.lastModified=new Date().toISOString(),await Qc();let t=`${Q}.tmp-${process.pid}`;try{await o.writeFile(t,JSON.stringify(e,null,2)),await o.rename(t,Q)}catch(e){try{await o.unlink(t)}catch{}throw console.error(`Error saving config:`,e),e}},al=async e=>{J(`Fetching config from URL: ${e}`);let t;try{t=new URL(e)}catch{throw Error(`Invalid URL format: ${e}\n Expected a valid URL like https://example.com/config.json`)}if(![`http:`,`https:`].includes(t.protocol))throw Error(`Unsupported URL protocol: ${t.protocol}\n Only http:// and https:// URLs are supported`);let n;try{let e=await o.readFile(Q,`utf8`);n=JSON.parse(e)}catch{n=el()}let r;try{r=await fetch(e,{headers:{Accept:`application/json`,"User-Agent":`tweakcc`},signal:AbortSignal.timeout(2e4)})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to fetch config from ${e}\n Network error: ${n}\n Please check your internet connection and try again.`)}if(!r.ok)throw Error(`Failed to fetch config from ${e}\n HTTP ${r.status}: ${r.statusText}\n Please check that the URL is correct and accessible.`);let i;try{let e=await Hc(r,8*1024*1024);i=JSON.parse(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to parse config from ${e}\n JSON parse error: ${n}\n Please ensure the URL returns valid JSON.`)}let a={sourceUrl:e,dateFetched:new Date().toISOString(),settings:i};await rl(e=>{e.remoteConfig=a});let s={...el(),ccVersion:n.ccVersion||``,ccInstallationPath:n.ccInstallationPath||null,settings:{...k,...i},remoteConfig:a};return tl(s),J(`Successfully fetched and parsed config from ${e}`),s};export{V as $,Fc as A,Ws as B,Mc as C,jc as D,Ac as E,ac as F,Fs as G,Gs as H,uc as I,Bs as J,Rs as K,sc as L,Oc as M,wc as N,Dc as O,K as P,ni as Q,ec as R,Ec as S,yc as T,Ys as U,tc as V,Qs as W,Ms as X,Vs as Y,ri as Z,bc as _,$ as a,Ct as at,Tc as b,Kc as c,T as ct,Gc as d,B as et,zc as f,kc as g,Lc as h,Jc as i,on as it,Ic as j,Hc as k,nl as l,E as lt,Vc as m,Z as n,un as nt,Yc as o,k as ot,J as p,zs as q,Q as r,cn as rt,al as s,M as st,qc as t,Pn as tt,rl as u,D as ut,Sc as v,_c as w,Cc as x,xc as y,rc as z};
@@ -1,4 +1,4 @@
1
- import{A as e,C as t,ct as n,f as r,h as i,l as a,lt as o,n as s,p as c,r as l,u,ut as ee,w as d}from"./config-BhEc8hIK.mjs";import{Box as f,Text as p,render as m,useInput as h}from"ink";import g,{useState as _}from"react";import*as te from"node:os";import v from"node:os";import*as y from"node:fs/promises";import b from"node:fs/promises";import x from"path";import{jsx as S,jsxs as C}from"react/jsx-runtime";import w from"which";import{globbySync as T}from"globby";const E=(()=>{let e=[],t=process.platform==`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),n=`node_modules/@anthropic-ai/claude-code`,r=(t,n=!1)=>{if(n)try{let n=T(t,{onlyFiles:!1});e.push({pattern:t,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?c(`Permission denied accessing: ${t} (${n.code})`):c(`Error expanding glob pattern "${t}": ${n instanceof Error?n.message:String(n)}`),e.push({pattern:t,isGlob:!0,expandedPaths:[]})}else e.push({pattern:t,isGlob:!1,expandedPaths:[t]})};return r(`${v.homedir()}/.claude/local/${n}`),process.env.NPM_PREFIX&&r(`${process.env.NPM_PREFIX}/lib/${n}`),process.env.N_PREFIX&&r(`${process.env.N_PREFIX}/lib/${n}`),process.env.VOLTA_HOME&&r(`${process.env.VOLTA_HOME}/lib/${n}`),process.env.FNM_DIR&&r(`${process.env.FNM_DIR}/lib/${n}`),process.env.NVM_DIR&&r(`${process.env.NVM_DIR}/lib/${n}`),process.env.NODENV_ROOT&&r(`${process.env.NODENV_ROOT}/versions/*/lib/${n}`,!0),process.env.NVS_HOME&&r(`${process.env.NVS_HOME}/node/*/*/lib/${n}`,!0),process.env.ASDF_DATA_DIR&&r(`${process.env.ASDF_DATA_DIR}/installs/nodejs/*/lib/${n}`,!0),process.platform==`win32`?(r(`${t}/AppData/Local/Volta/tools/image/packages/@anthropic-ai/claude-code/${n}`),r(`${t}/AppData/Roaming/npm/${n}`),r(`${t}/AppData/Roaming/nvm/*/${n}`,!0),r(`${t}/AppData/Local/Yarn/config/global/${n}`),r(`${t}/AppData/Local/pnpm/global/*/${n}`,!0),r(`C:/nvm4w/nodejs/${n}`),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/AppData/Roaming/Yarn/config/global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/Bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/fnm_multishells/*/node_modules/${n}`,!0),r(`${t}/AppData/Local/mise/installs/node/*/${n}`,!0),r(`${t}/AppData/Local/mise/installs/npm-anthropic-ai-claude-code/*/${n}`,!0)):(process.platform==`darwin`&&(r(`${t}/Library/${n}`),r(`/opt/local/lib/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/Library/Caches/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0)),r(`${t}/.local/lib/${n}`),r(`${t}/.local/share/${n}`),r(`${t}/.npm-global/lib/${n}`),r(`${t}/.npm-packages/lib/${n}`),r(`${t}/.npm/lib/${n}`),r(`${t}/npm/lib/${n}`),r(`/etc/${n}`),r(`/lib/${n}`),r(`/opt/node/lib/${n}`),r(`/usr/lib/${n}`),r(`/usr/local/lib/${n}`),r(`/usr/share/${n}`),r(`/var/lib/${n}`),r(`/opt/homebrew/lib/${n}`),r(`${t}/.linuxbrew/lib/${n}`),r(`${t}/.config/yarn/global/${n}`),r(`${t}/.yarn/global/${n}`),r(`${t}/.bun/install/global/${n}`),r(`${t}/.pnpm-global/${n}`),r(`${t}/.pnpm-global/*/${n}`,!0),r(`${t}/pnpm-global/${n}`),r(`${t}/pnpm-global/*/${n}`,!0),r(`${t}/.local/share/pnpm/global/${n}`),r(`${t}/.local/share/pnpm/global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/.local/share/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`/usr/local/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/lib/${n}`),r(`${t}/.volta/tools/image/node/*/lib/${n}`,!0),r(`${t}/.fnm/node-versions/*/installation/lib/${n}`,!0),r(`${t}/.local/state/fnm_multishells/*/lib/${n}`,!0),r(`/usr/local/nvm/versions/node/*/lib/${n}`,!0),r(`/usr/local/share/nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nodenv/versions/*/lib/${n}`,!0),r(`${t}/.nvs/*/lib/${n}`,!0),r(`${t}/.asdf/installs/nodejs/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/node/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/node/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0)),process.platform==`win32`&&e.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),e})().flatMap(e=>e.expandedPaths),ne=(()=>{let e=process.platform===`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),t=[],n=(e,n=!1)=>{if(n)try{let n=T(e,{onlyFiles:!0});t.push({pattern:e,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?c(`Permission denied accessing: ${e} (${n.code})`):c(`Error expanding glob pattern "${e}": ${n instanceof Error?n.message:String(n)}`),t.push({pattern:e,isGlob:!0,expandedPaths:[]})}else t.push({pattern:e,isGlob:!1,expandedPaths:[e]})};if(n(`${e}/.local/bin/claude`),process.platform===`win32`&&(n(`${e}/.nvm/versions/node/v22.21.1/lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe`),n(`${e}/.local/bin/claude.exe`)),n(`${e}/.local/share/claude/versions/*`,!0),process.platform!==`win32`){let t=`lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe`,r=process.env.MISE_DATA_DIR||`${e}/.local/share/mise`;n(`${r}/installs/node/*/${t}`,!0),n(`${r}/installs/npm-anthropic-ai-claude-code/*/${t}`,!0)}return process.platform===`win32`&&t.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),t})().flatMap(e=>e.expandedPaths);var D=class extends Error{constructor(e){super(e),this.name=`InstallationDetectionError`}};let O=null;async function re(){return O||=(async()=>{try{let{WASMagic:e}=await import(`wasmagic`);return await e.create()}catch(e){return c(`WASMagic initialization failed (likely SIMD unsupported on this CPU):`,e),c(`Using fallback file type detection`),null}})(),O}const ie=Buffer.from([127,69,76,70]),ae=Buffer.from([254,237,250,206]),oe=Buffer.from([254,237,250,207]),se=Buffer.from([206,250,237,254]),k=Buffer.from([207,250,237,254]),A=Buffer.from([202,254,186,190]),j=Buffer.from([77,90]);function M(e){if(e.length===0)return null;if(e[0]===35&&e[1]===33&&e.subarray(0,Math.min(256,e.length)).toString(`utf8`).split(`
1
+ import{A as e,C as t,ct as n,f as r,h as i,l as a,lt as o,n as s,p as c,r as l,u,ut as ee,w as d}from"./config-BPqYsh7T.mjs";import{Box as f,Text as p,render as m,useInput as h}from"ink";import g,{useState as _}from"react";import*as te from"node:os";import v from"node:os";import*as y from"node:fs/promises";import b from"node:fs/promises";import x from"path";import{jsx as S,jsxs as C}from"react/jsx-runtime";import w from"which";import{globbySync as T}from"globby";const E=(()=>{let e=[],t=process.platform==`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),n=`node_modules/@anthropic-ai/claude-code`,r=(t,n=!1)=>{if(n)try{let n=T(t,{onlyFiles:!1});e.push({pattern:t,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?c(`Permission denied accessing: ${t} (${n.code})`):c(`Error expanding glob pattern "${t}": ${n instanceof Error?n.message:String(n)}`),e.push({pattern:t,isGlob:!0,expandedPaths:[]})}else e.push({pattern:t,isGlob:!1,expandedPaths:[t]})};return r(`${v.homedir()}/.claude/local/${n}`),process.env.NPM_PREFIX&&r(`${process.env.NPM_PREFIX}/lib/${n}`),process.env.N_PREFIX&&r(`${process.env.N_PREFIX}/lib/${n}`),process.env.VOLTA_HOME&&r(`${process.env.VOLTA_HOME}/lib/${n}`),process.env.FNM_DIR&&r(`${process.env.FNM_DIR}/lib/${n}`),process.env.NVM_DIR&&r(`${process.env.NVM_DIR}/lib/${n}`),process.env.NODENV_ROOT&&r(`${process.env.NODENV_ROOT}/versions/*/lib/${n}`,!0),process.env.NVS_HOME&&r(`${process.env.NVS_HOME}/node/*/*/lib/${n}`,!0),process.env.ASDF_DATA_DIR&&r(`${process.env.ASDF_DATA_DIR}/installs/nodejs/*/lib/${n}`,!0),process.platform==`win32`?(r(`${t}/AppData/Local/Volta/tools/image/packages/@anthropic-ai/claude-code/${n}`),r(`${t}/AppData/Roaming/npm/${n}`),r(`${t}/AppData/Roaming/nvm/*/${n}`,!0),r(`${t}/AppData/Local/Yarn/config/global/${n}`),r(`${t}/AppData/Local/pnpm/global/*/${n}`,!0),r(`C:/nvm4w/nodejs/${n}`),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/AppData/Roaming/Yarn/config/global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/${n}`),r(`${t}/AppData/Roaming/pnpm-global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/Bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/AppData/Local/fnm_multishells/*/node_modules/${n}`,!0),r(`${t}/AppData/Local/mise/installs/node/*/${n}`,!0),r(`${t}/AppData/Local/mise/installs/npm-anthropic-ai-claude-code/*/${n}`,!0)):(process.platform==`darwin`&&(r(`${t}/Library/${n}`),r(`/opt/local/lib/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/Library/Caches/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0)),r(`${t}/.local/lib/${n}`),r(`${t}/.local/share/${n}`),r(`${t}/.npm-global/lib/${n}`),r(`${t}/.npm-packages/lib/${n}`),r(`${t}/.npm/lib/${n}`),r(`${t}/npm/lib/${n}`),r(`/etc/${n}`),r(`/lib/${n}`),r(`/opt/node/lib/${n}`),r(`/usr/lib/${n}`),r(`/usr/local/lib/${n}`),r(`/usr/share/${n}`),r(`/var/lib/${n}`),r(`/opt/homebrew/lib/${n}`),r(`${t}/.linuxbrew/lib/${n}`),r(`${t}/.config/yarn/global/${n}`),r(`${t}/.yarn/global/${n}`),r(`${t}/.bun/install/global/${n}`),r(`${t}/.pnpm-global/${n}`),r(`${t}/.pnpm-global/*/${n}`,!0),r(`${t}/pnpm-global/${n}`),r(`${t}/pnpm-global/*/${n}`,!0),r(`${t}/.local/share/pnpm/global/${n}`),r(`${t}/.local/share/pnpm/global/*/${n}`,!0),r(`${t}/.bun/install/global/${n}`),r(`${t}/.bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`${t}/.local/share/bun/install/cache/@anthropic-ai/claude-code*@@@*`,!0),r(`/usr/local/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/versions/node/*/lib/${n}`,!0),r(`${t}/n/lib/${n}`),r(`${t}/.volta/tools/image/node/*/lib/${n}`,!0),r(`${t}/.fnm/node-versions/*/installation/lib/${n}`,!0),r(`${t}/.local/state/fnm_multishells/*/lib/${n}`,!0),r(`/usr/local/nvm/versions/node/*/lib/${n}`,!0),r(`/usr/local/share/nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nvm/versions/node/*/lib/${n}`,!0),r(`${t}/.nodenv/versions/*/lib/${n}`,!0),r(`${t}/.nvs/*/lib/${n}`,!0),r(`${t}/.asdf/installs/nodejs/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/node/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/node/*/lib/${n}`,!0),process.env.MISE_DATA_DIR&&r(`${process.env.MISE_DATA_DIR}/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0),r(`${t}/.local/share/mise/installs/npm-anthropic-ai-claude-code/*/lib/${n}`,!0)),process.platform==`win32`&&e.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),e})().flatMap(e=>e.expandedPaths),ne=(()=>{let e=process.platform===`win32`?v.homedir().replace(/\\/g,`/`):v.homedir(),t=[],n=(e,n=!1)=>{if(n)try{let n=T(e,{onlyFiles:!0});t.push({pattern:e,isGlob:!0,expandedPaths:n})}catch(n){n instanceof Error&&`code`in n&&(n.code===`EACCES`||n.code===`EPERM`)?c(`Permission denied accessing: ${e} (${n.code})`):c(`Error expanding glob pattern "${e}": ${n instanceof Error?n.message:String(n)}`),t.push({pattern:e,isGlob:!0,expandedPaths:[]})}else t.push({pattern:e,isGlob:!1,expandedPaths:[e]})};if(n(`${e}/.local/bin/claude`),process.platform===`win32`&&(n(`${e}/.nvm/versions/node/v22.21.1/lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe`),n(`${e}/.local/bin/claude.exe`)),n(`${e}/.local/share/claude/versions/*`,!0),process.platform!==`win32`){let t=`lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe`,r=process.env.MISE_DATA_DIR||`${e}/.local/share/mise`;n(`${r}/installs/node/*/${t}`,!0),n(`${r}/installs/npm-anthropic-ai-claude-code/*/${t}`,!0)}return process.platform===`win32`&&t.forEach(e=>{e.pattern=e.pattern.replace(/\//g,`\\`),e.expandedPaths=e.expandedPaths.map(e=>e.replace(/\//g,`\\`))}),t})().flatMap(e=>e.expandedPaths);var D=class extends Error{constructor(e){super(e),this.name=`InstallationDetectionError`}};let O=null;async function re(){return O||=(async()=>{try{let{WASMagic:e}=await import(`wasmagic`);return await e.create()}catch(e){return c(`WASMagic initialization failed (likely SIMD unsupported on this CPU):`,e),c(`Using fallback file type detection`),null}})(),O}const ie=Buffer.from([127,69,76,70]),ae=Buffer.from([254,237,250,206]),oe=Buffer.from([254,237,250,207]),se=Buffer.from([206,250,237,254]),k=Buffer.from([207,250,237,254]),A=Buffer.from([202,254,186,190]),j=Buffer.from([77,90]);function M(e){if(e.length===0)return null;if(e[0]===35&&e[1]===33&&e.subarray(0,Math.min(256,e.length)).toString(`utf8`).split(`
2
2
  `)[0].includes(`node`))return c(`detectFileTypeFallback: Detected JavaScript via shebang`),`javascript`;if(e.length>=4){let t=e.subarray(0,4);if(t.equals(ie))return c(`detectFileTypeFallback: Detected ELF binary`),`binary`;if(t.equals(ae)||t.equals(oe)||t.equals(se)||t.equals(k)||t.equals(A))return c(`detectFileTypeFallback: Detected Mach-O binary`),`binary`}if(e.length>=2&&e.subarray(0,2).equals(j))return c(`detectFileTypeFallback: Detected PE binary`),`binary`;let t=Math.min(512,e.length),n=0,r=0;for(let i=0;i<t;i++){let t=e[i];(t>=32&&t<=126||t===9||t===10||t===13)&&n++,t===0&&r++}if(r>0)return c(`detectFileTypeFallback: Detected binary (${r} null bytes in first ${t} bytes)`),`binary`;let i=n/t;return i>.9?(c(`detectFileTypeFallback: Detected JavaScript via text heuristic (${Math.round(i*100)}% printable)`),`javascript`):(c(`detectFileTypeFallback: Unknown file type (${Math.round(i*100)}% printable)`),null)}async function N(e,t=4096){try{let n=await b.open(e,`r`);try{let e=Buffer.allocUnsafe(t),{bytesRead:r}=await n.read({buffer:e,position:0,length:t});return r<=0?null:e.subarray(0,r)}finally{await n.close()}}catch(e){return c(`Failed to read file prefix:`,e),null}}async function P(e){if(process.platform===`win32`)return e;let t=await ee(e);return t?(c(`maybeResolveNixWrapper: resolved Nix wrapper ${e} -> ${t}`),t):e}async function F(e){try{let t=await b.realpath(e);c(`resolvePathToInstallationType: ${e} -> ${t}`);let n=await N(t);if(!n)return c(`resolvePathToInstallationType: Could not read file prefix`),null;let r=await re();if(r&&typeof r.detect==`function`){let e=r.detect(n)||null;if(e){let n=e.toLowerCase();return c(`resolvePathToInstallationType: Detected mime type: ${n}`),n.includes(`javascript`)?{kind:`npm-based`,resolvedPath:t}:n.startsWith(`text/`)?(c(`resolvePathToInstallationType: Unrecognized file type`),null):{kind:`native-binary`,resolvedPath:await P(t)}}}c(`resolvePathToInstallationType: Using fallback file type detection`);let i=M(n);return i===`javascript`?{kind:`npm-based`,resolvedPath:t}:i===`binary`?{kind:`native-binary`,resolvedPath:await P(t)}:(c(`resolvePathToInstallationType: Fallback could not determine file type`),null)}catch(e){return c(`resolvePathToInstallationType: Error:`,e),null}}async function I(){c(`getClaudeFromPath: PATH = ${process.env.PATH}`),c(`getClaudeFromPath: PATHEXT = ${process.env.PATHEXT}`);try{let e=await w(`claude`);return c(`getClaudeFromPath: Found claude at ${e}`),e}catch{return c(`getClaudeFromPath: claude not found on PATH`),null}}function L(e){let t=/\bVERSION:"(\d+\.\d+\.\d+)"/g,n=new Map,r;for(;(r=t.exec(e))!==null;){let e=r[1];n.set(e,(n.get(e)||0)+1)}if(n.size===0)return null;let i=0,a;for(let[e,t]of n.entries())c(`Found version ${e} with ${t} occurrences`),t>i&&(i=t,a=e);return a&&c(`Extracted version ${a} (${i} occurrences)`),a||null}async function R(e){let t=L(await b.readFile(e,`utf8`));if(!t)throw Error(`No VERSION strings found in JS file: ${e}`);return t}async function z(e){let{data:t,error:r}=await n(e);if(!t)throw Error(`Could not extract JS from native binary: ${e}${r?` (${r})`:``}`);let i=L(t.toString(`utf8`));if(!i)throw Error(`No VERSION strings found in extracted JS from: ${e}`);return i}function B(e){let t=x.basename(e).match(/^(\d+\.\d+\.\d+)$/);return t?t[1]:null}async function V(e,t){let n=B(e);return n?(c(`extractVersion: Got version ${n} from filename`),n):t===`npm-based`?R(e):z(e)}async function H(){let e=[],t=new Set;for(let n of E){let r=x.join(n,`cli.js`);try{if(await i(r)){let n=await b.realpath(r).catch(()=>r);if(t.has(n))continue;t.add(n),c(`collectCandidates: Found cli.js at ${n}`);let i=await R(n);e.push({path:n,kind:`npm-based`,version:i})}}catch(e){c(`collectCandidates: Error checking ${r}:`,e)}}for(let n of ne)try{if(await i(n)){let r=await b.realpath(n).catch(()=>n);if(t.has(r))continue;t.add(r);let i=await P(r);c(`collectCandidates: Found native binary at ${r}${i===r?``:` (resolved -> ${i})`}`);let a=await V(i,`native-binary`);e.push({path:i,kind:`native-binary`,version:a})}}catch(e){c(`collectCandidates: Error checking ${n}:`,e)}return[...e].sort((e,t)=>r(t.version,e.version))}function U(e){return e.map(e=>` • ${e.path} (${e.kind}, v${e.version})`).join(`
3
3
  `)}function W(e){return` 2. Set ccInstallationPath in your config file (${l}):
4
4