@aizoo321/cli 0.0.174 → 0.0.176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/commands/base.js +1 -1
  3. package/dist/commands/codex-sessions.js +1 -1
  4. package/dist/commands/components.js +1 -1
  5. package/dist/commands/doctor.js +1 -1
  6. package/dist/commands/sessions.js +1 -1
  7. package/dist/commands/setup.js +1 -1
  8. package/dist/commands/upgrade.js +1 -1
  9. package/dist/lib/app-update.js +1 -1
  10. package/dist/lib/auto-update.js +1 -1
  11. package/dist/lib/claude-code-manager.js +1 -1
  12. package/dist/lib/client-config-sync.js +1 -1
  13. package/dist/lib/codex-sessions.js +1 -1
  14. package/dist/lib/command.js +1 -1
  15. package/dist/lib/components.js +1 -1
  16. package/dist/lib/config.js +1 -1
  17. package/dist/lib/env-cleanup.js +1 -1
  18. package/dist/lib/gateway-addresses.js +1 -1
  19. package/dist/lib/install-script.js +1 -0
  20. package/dist/lib/model-refresh.js +1 -1
  21. package/dist/lib/persistent-env.js +1 -1
  22. package/dist/lib/post-apply.js +1 -1
  23. package/dist/lib/signals.js +1 -0
  24. package/dist/lib/system-report.js +1 -0
  25. package/dist/lib/telemetry.js +1 -1
  26. package/dist/lib/tool-manager.js +1 -1
  27. package/dist/lib/tool-upgrade.js +1 -1
  28. package/dist/lib/tools/backup.js +1 -1
  29. package/dist/lib/tools/claude-code.js +1 -1
  30. package/dist/lib/tools/claude-desktop-cli.js +1 -1
  31. package/dist/lib/tools/claude-desktop.js +1 -1
  32. package/dist/lib/tools/claude-plugins.js +1 -1
  33. package/dist/lib/tools/codex.js +1 -1
  34. package/dist/lib/tools/desktop-app-installer.js +1 -1
  35. package/dist/lib/tools/elevated-reg.js +1 -1
  36. package/dist/lib/tools/tool-installs.js +1 -1
  37. package/dist/lib/written-values.js +1 -1
  38. package/dist/locales/en_US.json +12 -3
  39. package/dist/locales/zh_CN.json +12 -3
  40. package/dist/utils/process-alive.js +1 -0
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as n,readFileSync as o,readdirSync as r,realpathSync as s,statSync as a,writeFileSync as i}from"fs";import{delimiter as l,dirname as c,isAbsolute as u,join as p,sep as d}from"path";import{fileURLToPath as m}from"url";import f from"chalk";import{brand as g,CLI_NAME as h}from"./brand.js";import{configManager as w}from"./config.js";import{i18n as v}from"./i18n.js";import{appLatest as y,appStatus as b,appStatusWith as $,cachedAppStatus as _,getApp as P}from"./app-update.js";import{compareVersions as x}from"./model-registry.js";import{isJsonMode as A}from"./runtime-options.js";import{track as k}from"./telemetry.js";import{runWatched as S}from"./tool-upgrade.js";import{getAdapter as D}from"./tools/registry.js";import{findInstallsIncludingNative as L,forgetInstalls as j,NPM_MIRROR as E,npmMirrorVersion as R}from"./tools/tool-installs.js";import{toolHome as C}from"./tools/types.js";import{logger as T}from"../utils/logger.js";let M=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const n=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(n.has(e))throw new Error(`components.json: duplicate name ${e}`);n.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!n.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}function N(){return M||(M=parseManifest(o(function(){const t=c(m(import.meta.url)),n=[p(t,"..","..","components.json"),p(t,"..","components.json"),p(t,"components.json")],o=n.find(t=>e(t));if(!o)throw new Error(`components.json not found, searched: ${n.join(", ")}`);return o}(),"utf-8"))),M}export function setComponentManifestForTests(t){M=null===t?null:parseManifest(t)}export function listComponents(){return N().components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let O=null;export function componentPlatform(){return O??process.platform}export function expandUrl(t){const e=g().installMirror??{};let n=!1;const o=t.replace(/\{(scripts|agy|devtools)\}/g,(t,o)=>{const r="devtools"===o?N().devtools:e[o];return r||(n=!0),r??""});return n?null:o}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(/\{(scripts|agy|devtools)\}/g,(t,e)=>("devtools"===e?N().devtools:g().installMirror?.[e])??t)}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(U??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let U=null,I=!0,B=e=>{const n=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${n.stdout??""}${n.stderr??""}`},F=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function V(t){try{return s(t)}catch{return t}}function H(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),n=process.env){const o=C();if("node"===t){if("win32"===e){const t=n.FNM_DIR||p(n.APPDATA||p(o,"AppData","Roaming"),"fnm");return[p(t,"aliases","default","node.exe"),p(n.LOCALAPPDATA||p(o,"AppData","Local"),"Programs","nodejs","node.exe")]}return[p(W(e,n),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[p(o,".local","bin","uv.exe"),p(o,".cargo","bin","uv.exe")]:[p(n.UV_INSTALL_DIR||p(o,".local","bin"),"uv"),p(o,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=n.LOCALAPPDATA||p(o,"AppData","Local");return[p(t,"Programs","Git","cmd","git.exe"),p(n.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function W(t,n){if(n.FNM_DIR)return n.FNM_DIR;const o=C();if("win32"===t)return p(n.APPDATA||p(o,"AppData","Roaming"),"fnm");const r=p(o,".local","share","fnm"),s=p(o,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(s)?s:r}let G=()=>{const e=e=>{const n=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return n?n.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},J=null;export function probeRuntime(t,e=componentPlatform()){const n=t.detect,o=new RegExp(n.pattern),r=new Set,s=[],i=n=>{if(!function(t){try{return a(t).isFile()}catch{return!1}}(n))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===n&&!F())return;const i=V(n),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=o.exec(B(n));c&&s.push({path:n,version:c[1]??null})},c=(process.env.PATH??"").split("win32"===e?";":l);"win32"===e&&c.push(...J??=z(()=>G())??[]);for(const t of c)if(t&&u(t))for(const o of H(n.command,e))i(p(t,o));for(const n of knownRuntimePaths(t.id,e))(I||n.startsWith(C()))&&i(n);return s}export function scriptTarget(t,e=componentPlatform(),n=process.env){const o=C();return"node"===t?"win32"===e?p(W(e,n),"aliases","default","node.exe"):p(W(e,n),"aliases","default","bin","node"):"uv"===t?p(n.UV_INSTALL_DIR||p(o,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?p(n.LOCALAPPDATA||p(o,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,n=componentPlatform(),o=process.env){const r=V(e),s=t=>"win32"===n?t.replace(/\//g,"\\").toLowerCase():t,a=s(r),i=s(e),l="win32"===n?"\\":"\\"===d?"/":d,u=t=>a.includes(s(t))||i.includes(s(t)),m=t=>a.startsWith(s(t)+l)||i.startsWith(s(t)+l),f=C(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return u(`${l}fnm${l}`)||m(W(n,o))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:u(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:u(`${l}nvm${l}`)&&"win32"===n?{by:"nvm",auto:!1,hint:"nvm install lts"}:u(`${l}.volta${l}`)||u(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:u(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:u(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:u(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[o.UV_INSTALL_DIR,p(f,".local","bin"),p(f,".cargo","bin")].filter(Boolean).some(t=>s(c(e))===s(t)||s(c(r))===s(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:u("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:u(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:u("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:u("site-packages")||u(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===n){const t=o.LOCALAPPDATA||p(f,"AppData","Local");return m(p(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:u(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===n?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function q(){return p(w.getConfigDir(),"component-releases.json")}function K(){try{const t=JSON.parse(o(q(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function X(t,e){try{n(w.getConfigDir(),{recursive:!0}),i(q(),JSON.stringify({...K(),[t]:e},null,2))}catch(t){T.logError("components.writeCache",t)}}let Z=async(t,e=15e3)=>{const n=await fetch(t,{signal:AbortSignal.timeout(e)});if(!n.ok)throw new Error(`HTTP ${n.status} ${t}`);return n.text()};const Y=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const n=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),o=n?Y.exec(n.slice(e.length+1)):null;if(!o)throw new Error(`${e} is not in versions.txt`);return o[1]}export async function latestVersion(t,e={}){const n=componentPlatform(),o=`${t.id}:${n}`,r=K()[o],s=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&s&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const n=t.latest;switch(n.type){case"node-lts":return latestNodeLts(await Z(n.url));case"devtools":return n.platforms&&!n.platforms.includes(e)?null:devtoolsVersion(await Z(`${N().devtools}/versions.txt`),n.key);case"npm":{if(n.staleTag){const e=D(t.adapter??"")?.installSpec,n=e?await R(e):"latest";if("latest"!==n)return n}const e=JSON.parse(await Z(`${E}/${n.package}/latest`));if(!e.version)throw new Error(`no version for ${n.package}`);return e.version}case"version-file":{const t=expandUrl(n.url);if(!t)return null;const e=Y.exec(await Z(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,n);return e&&X(o,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const n=e instanceof Error?e.message:String(e);return T.logError(`components.latest(${t.id})`,e),X(o,{error:n,checked_at:Date.now()}),{version:r?.version??null,error:n}}}export async function prefetchLatest(t,e={}){const n=componentPlatform(),o=await Promise.all(t.map(async t=>t.platforms.includes(n)?"app"===t.category?[t.id,P(t.app)?await y(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(o)}export async function componentStatus(t,e={}){const n=componentPlatform(),o={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(n),source:componentSource(t,n)},r={...o,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:o.supported?installBlocker():"unsupported_platform"};if(!o.supported)return r;if("app"===t.category){const n=P(t.app);if(!n)return{...r,blocker:"unsupported_platform"};const o=e.latest?$(t.app,e.latest):e.offline?_(t.app):await b(t.app,{refresh:e.refresh});return{...r,installed:o.installed,current:o.current,latest:o.latest,outdated:o.outdated,path:o.installed?z(()=>n.appInstaller.installedPath()):null,managed_by:o.installed?"app":null,auto_upgrade:o.installed&&!o.blocker,blocker:o.blocker??installBlocker(),...o.error?{error:o.error}:{}}}let s=null,a=null,i=null;if("cli"===t.category){const e=D(t.adapter)?.installSpec,n=e?L(e)[0]:void 0;n&&(s=n.version,a=n.path,i={by:n.kind,auto:!0})}else{const e=probeRuntime(t,n)[0];e&&(s=e.version,a=e.path,i=runtimeManager(t.id,e.path,n))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:K()[`${t.id}:${n}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?K()[`${t.id}:${n}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&s&&x(s,u.version)>=0);return{...r,installed:Boolean(a),current:s,latest:l,outdated:Boolean(s&&l&&x(s,l)<0&&!p),...p?{capped_at:u.version}:{},path:a,managed_by:i?.by??null,auto_upgrade:i?.auto??!1,...i?.hint?{hint:i.hint}:{},...c?{error:c}:{}}}function z(t){try{return t()}catch{return null}}const Q={idleMs:18e4,timeoutMs:36e5};let tt=async(t,e)=>{const n={...Q,env:e};return"ok"===("win32"===componentPlatform()?await S("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${t} -TimeoutSec 30 | iex`],n):await S("sh",["-c",'script=$(curl -fsSL --connect-timeout 15 --max-time 60 "$0") && printf \'%s\\n\' "$script" | sh',t],n))},et=async(t,e)=>"ok"===await S(t,e,Q);function nt(t){A()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const n=c(V(t)),s="win32"===e?p(n,"node_modules"):p(c(n),"lib","node_modules"),a=[],i=(t,e)=>{try{const n=JSON.parse(o(p(t,"package.json"),"utf-8"));n.version&&a.push({name:e,version:n.version})}catch{}};let l=[];try{l=r(s)}catch{return a}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(p(s,t)))e.startsWith(".")||i(p(s,t,e),`${t}/${e}`)}catch{}else i(p(s,t),t);return a}function ot(t,e,n={}){const o=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:o,...n}}function rt(t){return`${h} upgrade ${t}`}export async function runRuntime(t,e,n={}){const o=Date.now(),r=componentPlatform(),s=await componentStatus(t,{refresh:!0}),a=t.name;if(!s.supported)return nt(f.yellow(" ! "+v.t("components.unsupported_platform",{tool:a}))),ot(s,"unavailable",{reason:"unsupported_platform"});if(s.blocker)return nt(f.yellow(" ! "+function(t,e){return v.t(`components.blocked_${t}`,{tool:e})}(s.blocker,a))),ot(s,"unavailable",{reason:s.blocker});const i=function(t){if("script"!==t.install.type)return null;const e=g().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(s.installed&&!n.force){const n=f.gray(`(${s.path})`);if(s.latest&&!s.outdated)return nt(f.green(" √ "+v.t("components.up_to_date",{tool:a,current:s.current??"?"}))+n),"upgrade"===e&&nt(f.gray(" "+v.t("components.force_hint",{command:`${rt(t.id)} --force`}))),ot(s,"install"===e?"already_installed":"up_to_date");if("install"===e)return nt(f.green(" √ "+v.t("components.already_installed",{tool:a,current:s.current??"?"}))+n),s.outdated&&nt(f.yellow(" ! "+upgradeAdvice(s))),ot(s,"already_installed",s.outdated?{hint:upgradeAdvice(s)}:{});if(!s.latest)return nt(f.yellow(" ! "+v.t("components.no_latest",{tool:a,current:s.current??"?",how:at(s)}))),ot(s,"manual",{reason:s.error??"no_latest",hint:s.hint});if(!s.auto_upgrade)return nt(f.yellow(" ! "+upgradeAdvice(s))),ot(s,"manual",{hint:s.hint})}if(!i)return nt(f.yellow(" ! "+v.t("components.no_mirror",{tool:a}))),ot(s,"unavailable",{reason:"no_mirror"});s.installed&&!s.auto_upgrade&&nt(f.yellow(" ! "+v.t("components.force_beside",{tool:a,path:s.path??"?",by:s.managed_by??"?"})));const u={};s.installed&&"script"===t.install.type&&Object.assign(u,t.install.forceEnv??{}),"uv"===t.id&&s.installed&&s.auto_upgrade&&s.path&&(u.UV_INSTALL_DIR=c(s.path));const d=t.upgrade?.migrateGlobalPackages&&s.installed&&"fnm"===s.managed_by&&s.path,m=d?globalPackages(s.path,r):[],h=d?V(s.path):null;nt(f.gray(" "+v.t(s.installed?"components.upgrading":"components.installing",{tool:a,latest:s.latest??"",source:s.source}))),k(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:s.current}});const w=await tt(i,u);j(),J=null;const y=probeRuntime(t,r),b=scriptTarget(t.id,r,{...process.env,...u}),$=(b?y.find(t=>{return e=t.path,n=b,"win32"===r?V(e).toLowerCase()===V(n).toLowerCase():V(e)===V(n);var e,n}):void 0)??y.find(e=>runtimeManager(t.id,e.path,r).auto)??y[0];if(!w||!$)return k(`component:${t.id}`,"fail",{duration_ms:Date.now()-o}),nt(f.red(" × "+v.t("components.script_failed",{tool:a,command:(s.installed?rt:st)(t.id)}))),ot(s,"failed",{reason:w?"not_found_after":"script_failed"});d&&m.length&&h&&V($.path)!==h&&await async function(t,e,n){const o=new Set(globalPackages(e,n).map(t=>t.name)),r=t.filter(t=>!o.has(t.name));if(!r.length)return;nt(f.gray(" "+v.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const s=function(t,e){const n=c(V(t));return p(n,"win32"===e?"npm.cmd":"npm")}(e,n),a=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${E}`,"--no-fund","--no-audit","--loglevel=error"];await et(s,a)||nt(f.yellow(" ! "+v.t("components.migrate_failed",{command:[s,...a].join(" ")})))}(m,$.path,r);const _=y[0];_&&_.path!==$.path&&_.version&&$.version&&x(_.version,$.version)<0&&nt(f.yellow(" ! "+v.t("components.path_shadowed",{tool:a,active:_.path,version:$.version,path:$.path}))),s.latest&&$.version&&x($.version,s.latest)<0&&(X(`${t.id}:${r}:ceiling`,{version:$.version,error:s.latest,checked_at:Date.now()}),nt(f.yellow(" ! "+v.t("components.capped",{tool:a,latest:s.latest,version:$.version})))),k(`component:${t.id}`,"ok",{duration_ms:Date.now()-o,detail:{version:$.version}});const P=s.installed?n.force&&!s.outdated?"reinstalled":"upgraded":"installed";var A;return nt(f.green(" √ "+("installed"===P?v.t("components.installed",{tool:a,version:$.version??"?"}):"reinstalled"===P?v.t("components.reinstalled",{tool:a,version:$.version??"?"}):v.t("components.upgraded",{tool:a,from:s.current??"?",to:$.version??"?"})))+f.gray(`(${$.path})`)),A=c($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":l).some(t=>"win32"===componentPlatform()?t.toLowerCase()===A.toLowerCase():t===A)||nt(f.gray(" "+v.t("components.new_terminal"))),ot(s,P,{version_after:$.version})}function st(t){return`${h} install ${t}`}function at(t){return t.hint?t.hint:v.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?v.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:rt(t.id)}):v.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:at(t),command:`${rt(t.id)} --force`})}export function setComponentDepsForTests(t){void 0!==t.platform&&(O=t.platform),void 0!==t.uid&&(U=t.uid),void 0!==t.systemPaths&&(I=t.systemPaths),t.registryPath&&(G=t.registryPath,J=null),t.versionRunner&&(B=t.versionRunner),t.macDeveloperTools&&(F=t.macDeveloperTools),t.fetchText&&(Z=t.fetchText),t.scriptRunner&&(tt=t.scriptRunner),t.commandRunner&&(et=t.commandRunner)}
1
+ import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as s,statSync as i,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{configManager as v}from"./config.js";import{i18n as y}from"./i18n.js";import{appLatest as b,appStatus as _,appStatusWith as $,cachedAppStatus as P,getApp as x}from"./app-update.js";import{compareVersions as A}from"./model-registry.js";import{isJsonMode as k}from"./runtime-options.js";import{maskSecrets as D,track as S}from"./telemetry.js";import{failureContext as j,lastCommandExit as L,lastCommandOutput as E,runWatched as C}from"./tool-upgrade.js";import{runInstallScript as R,traceSummary as T}from"./install-script.js";import{atomicWriteFile as M}from"./tools/backup.js";import{getAdapter as N}from"./tools/registry.js";import{findInstallsIncludingNative as O,forgetInstalls as U,NPM_MIRROR as I,npmMirrorVersion as B}from"./tools/tool-installs.js";import{toolHome as F}from"./tools/types.js";import{logger as J}from"../utils/logger.js";let V=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}function H(){return V||(V=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),V}export function setComponentManifestForTests(t){V=null===t?null:parseManifest(t)}export function listComponents(){return H().components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let W=null;export function componentPlatform(){return W??process.platform}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(/\{(scripts|agy|devtools)\}/g,(t,n)=>{const r="devtools"===n?H().devtools:e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(/\{(scripts|agy|devtools)\}/g,(t,e)=>("devtools"===e?H().devtools:h().installMirror?.[e])??t)}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(G??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let G=null,q=!0,K=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},X=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function Z(t){try{return a(t)}catch{return t}}function z(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=F();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(Y(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function Y(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=F();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let Q=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},tt=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],s=o=>{if(!function(t){try{return i(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!X())return;const s=Z(o),l="win32"===e?s.toLowerCase():s;if(r.has(l))return;r.add(l);const c=n.exec(K(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...tt??=st(()=>Q())??[]);for(const t of l)if(t&&p(t))for(const n of z(o.command,e))s(d(t,n));for(const o of knownRuntimePaths(t.id,e))(q||o.startsWith(F()))&&s(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=F();return"node"===t?"win32"===e?d(Y(e,o),"aliases","default","node.exe"):d(Y(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=Z(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,s=a(r),i=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>s.includes(a(t))||i.includes(a(t)),p=t=>s.startsWith(a(t)+l)||i.startsWith(a(t)+l),f=F(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(Y(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function et(){return d(v.getConfigDir(),"component-releases.json")}function ot(){try{const t=JSON.parse(n(et(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function nt(t,e){try{o(v.getConfigDir(),{recursive:!0}),l(et(),JSON.stringify({...ot(),[t]:e},null,2))}catch(t){J.logError("components.writeCache",t)}}let rt=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const at=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?at.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=ot()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await rt(o.url));case"devtools":return o.platforms&&!o.platforms.includes(e)?null:devtoolsVersion(await rt(`${H().devtools}/versions.txt`),o.key);case"npm":{if(o.staleTag){const e=N(t.adapter??"")?.installSpec,o=e?await B(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await rt(`${I}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=at.exec(await rt(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&nt(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return J.logError(`components.latest(${t.id})`,e),nt(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,x(t.app)?await b(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=x(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?$(t.app,e.latest):e.offline?P(t.app):await _(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?st(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,s=null,i=null;if("cli"===t.category){const e=N(t.adapter)?.installSpec,o=e?O(e)[0]:void 0;o&&(a=o.version,s=o.path,i={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,s=e.path,i=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:ot()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?ot()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&A(a,u.version)>=0);return{...r,installed:Boolean(s),current:a,latest:l,outdated:Boolean(a&&l&&A(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:s,managed_by:i?.by??null,auto_upgrade:i?.auto??!1,...i?.hint?{hint:i.hint}:{},...c?{error:c}:{}}}function st(t){try{return t()}catch{return null}}const it={idleMs:18e4,timeoutMs:36e5};let lt,ct=async(t,e)=>(lt=await R({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...it,env:e},output:E,run:(t,e,o)=>C(t,e,o)}),"ok"===lt.outcome),ut=async(t,e)=>"ok"===await C(t,e,it);function pt(t){k()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(Z(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),s=[],i=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&s.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return s}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||i(d(a,t,e),`${t}/${e}`)}catch{}else i(d(a,t),t);return s}function dt(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function mt(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),s=await componentStatus(t,{refresh:!0}),i=t.name;if(!s.supported)return pt(g.yellow(" ! "+y.t("components.unsupported_platform",{tool:i}))),dt(s,"unavailable",{reason:"unsupported_platform"});if(s.blocker)return pt(g.yellow(" ! "+function(t,e){return y.t(`components.blocked_${t}`,{tool:e})}(s.blocker,i))),dt(s,"unavailable",{reason:s.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(s.installed&&!n.force){const o=g.gray(`(${s.path})`);if(s.latest&&!s.outdated)return pt(g.green(" √ "+y.t("components.up_to_date",{tool:i,current:s.current??"?"}))+o),"upgrade"===e&&pt(g.gray(" "+y.t("components.force_hint",{command:`${mt(t.id)} --force`}))),dt(s,"install"===e?"already_installed":"up_to_date");if("install"===e)return pt(g.green(" √ "+y.t("components.already_installed",{tool:i,current:s.current??"?"}))+o),s.outdated&&pt(g.yellow(" ! "+upgradeAdvice(s))),dt(s,"already_installed",s.outdated?{hint:upgradeAdvice(s)}:{});if(!s.latest)return pt(g.yellow(" ! "+y.t("components.no_latest",{tool:i,current:s.current??"?",how:gt(s)}))),dt(s,"manual",{reason:s.error??"no_latest",hint:s.hint});if(!s.auto_upgrade)return pt(g.yellow(" ! "+upgradeAdvice(s))),dt(s,"manual",{hint:s.hint})}if(!l)return pt(g.yellow(" ! "+y.t("components.no_mirror",{tool:i}))),dt(s,"unavailable",{reason:"no_mirror"});s.installed&&!s.auto_upgrade&&pt(g.yellow(" ! "+y.t("components.force_beside",{tool:i,path:s.path??"?",by:s.managed_by??"?"})));const p={};s.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&s.installed&&s.auto_upgrade&&s.path&&(p.UV_INSTALL_DIR=u(s.path));const d=t.upgrade?.migrateGlobalPackages&&s.installed&&"fnm"===s.managed_by&&s.path,m=d?globalPackages(s.path,a):[],f=d?Z(s.path):null;pt(g.gray(" "+y.t(s.installed?"components.upgrading":"components.installing",{tool:i,latest:s.latest??"",source:s.source}))),S(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:s.current}}),d&&m.length&&f&&function(t){try{o(v.getConfigDir(),{recursive:!0}),M(wt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){J.logError("components: note migration",t)}}({packages:m,old_node:f}),lt=void 0;const w=await ct(l,p);U(),tt=null;const b=probeRuntime(t,a),_=scriptTarget(t.id,a,{...process.env,...p}),$=(_?b.find(t=>{return e=t.path,o=_,"win32"===a?Z(e).toLowerCase()===Z(o).toLowerCase():Z(e)===Z(o);var e,o}):void 0)??b.find(e=>runtimeManager(t.id,e.path,a).auto)??b[0];if(!w||!$){vt();const e=lt;return S(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:D(E())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...T(e.trace)}:{},...L(),...j()}}),pt(g.red(" × "+y.t("components.script_failed",{tool:i,command:(s.installed?mt:ft)(t.id)}))),dt(s,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&Z($.path)!==f&&(P=await ht(m,$.path,a)?"done":"failed"),"failed"!==P&&vt();const x=b[0];x&&x.path!==$.path&&x.version&&$.version&&A(x.version,$.version)<0&&pt(g.yellow(" ! "+y.t("components.path_shadowed",{tool:i,active:x.path,version:$.version,path:$.path}))),s.latest&&$.version&&A($.version,s.latest)<0&&(nt(`${t.id}:${a}:ceiling`,{version:$.version,error:s.latest,checked_at:Date.now()}),pt(g.yellow(" ! "+y.t("components.capped",{tool:i,latest:s.latest,version:$.version})))),S(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const k=s.installed?n.force&&!s.outdated?"reinstalled":"upgraded":"installed";var C;return pt(g.green(" √ "+("installed"===k?y.t("components.installed",{tool:i,version:$.version??"?"}):"reinstalled"===k?y.t("components.reinstalled",{tool:i,version:$.version??"?"}):y.t("components.upgraded",{tool:i,from:s.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),C=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===C.toLowerCase():t===C)||pt(g.gray(" "+y.t("components.new_terminal"))),dt(s,k,{version_after:$.version})}function ft(t){return`${w} install ${t}`}function gt(t){return t.hint?t.hint:y.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?y.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:mt(t.id)}):y.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:gt(t),command:`${mt(t.id)} --force`})}async function ht(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;pt(g.gray(" "+y.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(Z(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),s=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${I}`,"--no-fund","--no-audit","--loglevel=error"];return!!await ut(a,s)||(pt(g.yellow(" ! "+y.t("components.migrate_failed",{command:[a,...s].join(" ")}))),!1)}const wt=()=>d(v.getConfigDir(),"node-migration.json");function vt(){try{s(wt(),{force:!0})}catch(t){J.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(wt()))return"none";t=JSON.parse(n(wt(),"utf-8"))}catch{return vt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||Z(a.path)===t.old_node)return vt(),"none";S("component:node","start",{detail:{mode:"resume-migration"}});const s=await ht(t.packages,a.path,o);return s&&vt(),S("component:node",s?"ok":"fail",{detail:{mode:"resume-migration",migration:s?"done":"failed"}}),s?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(W=t.platform),void 0!==t.uid&&(G=t.uid),void 0!==t.systemPaths&&(q=t.systemPaths),t.registryPath&&(Q=t.registryPath,tt=null),t.versionRunner&&(K=t.versionRunner),t.macDeveloperTools&&(X=t.macDeveloperTools),t.fetchText&&(rt=t.fetchText),t.scriptRunner&&(ct=t.scriptRunner),t.commandRunner&&(ut=t.commandRunner)}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as i,writeFileSync as o,renameSync as s,unlinkSync as r,readdirSync as n,rmdirSync as a,statSync as c,chmodSync as l}from"fs";import{join as f,dirname as g}from"path";import{homedir as h}from"os";import{createHash as p}from"crypto";import*as m from"js-yaml";import{logger as u}from"../utils/logger.js";import{getDefaultModels as d,isRetiredDefaultModel as y}from"./model-registry.js";import{readLegacySecretsFile as _}from"./secret-store.js";import{brand as k,brandEnv as b}from"./brand.js";export const DEFAULT_BASE_URL=k().gatewayAddresses[0].url;export const DEFAULT_MODELS=d();export const DEFAULT_PROFILE_NAME="default";const v="plaintext";export class ConfigManager{static instance;configDir;configPath;config;runtimeBaseUrl;constructor(){this.configDir=this.resolveConfigDir(),this.migrateLegacyConfigDir(),this.configPath=f(this.configDir,"config.yaml"),this.config=this.loadConfig()}migrateLegacyConfigDir(){try{const t=f(g(this.configDir),".chelper");if(t===this.configDir||!e(t))return;if(["config.yaml","secrets.enc"].some(t=>e(f(this.configDir,t))))return;if(e(this.configDir)){for(const i of n(t)){const o=f(this.configDir,i);e(o)||s(f(t,i),o)}0===n(t).length&&a(t)}else s(t,this.configDir);u.record(`Migrated config dir: ${t} -> ${this.configDir}`)}catch(e){u.warn("Failed to migrate legacy .chelper config dir:",e)}}resolveConfigDir(){const e=b("CONFIG_DIR");if(e&&e.trim())return e.trim();const t=b("TEST_HOME");return t&&t.trim()?f(t.trim(),k().configDirName):f(h(),k().configDirName)}createDefaultConfig(){return this.syncLegacyFields({lang:"en_US",active_profile:"default",profiles:{[DEFAULT_PROFILE_NAME]:{}},presets:{}})}normalizeModels(e){const t=t=>{const i=e?.[t]?.trim();return i&&!y(t,i)?i:DEFAULT_MODELS[t]},i={haiku:t("haiku"),sonnet:t("sonnet"),opus:t("opus"),reasoning:t("reasoning")};if(e&&"object"==typeof e)for(const[t,o]of Object.entries(e))t in i||"string"==typeof o&&o.trim()&&(i[t]=o.trim());return i}normalizeToolModels(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||"string"!=typeof e||!t||"object"!=typeof t)return[];const i={};for(const[e,o]of Object.entries(t))"string"==typeof o&&o.trim()&&(i[e]=o.trim());return Object.keys(i).length>0?[[e,i]]:[]});return Object.fromEntries(t)}normalizeToolSettings(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||!t||"object"!=typeof t||Array.isArray(t))return[];const i=Object.fromEntries(Object.entries(t).filter(([,e])=>"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)));return Object.keys(i).length>0?[[e,i]]:[]});return Object.fromEntries(t)}normalizeStringRecord(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]&&Boolean(e[1].trim())).map(([e,t])=>[e,t.trim()]))}normalizeProfile(e){if(!e)return{};const t=this.normalizeToolModels(e.tool_models),i=this.normalizeToolSettings(e.tool_settings),o=this.normalizeStringRecord(e.tool_api_keys);return{..."string"==typeof e.api_key&&e.api_key?{api_key:e.api_key}:{},...Object.keys(o).length>0?{tool_api_keys:o}:{},..."string"==typeof e.base_url&&e.base_url?{base_url:e.base_url}:{},...e.models?{models:this.normalizeModels(e.models)}:{},...Object.keys(t).length>0?{tool_models:t}:{},...Object.keys(i).length>0?{tool_settings:i}:{}}}normalizeProfiles(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>e&&"string"==typeof e&&t&&"object"==typeof t?[[e,this.normalizeProfile(t)]]:[]);return Object.fromEntries(t)}normalizePresets(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||"string"!=typeof e||!t||"object"!=typeof t)return[];const i=t;return i.models?[[e,{models:this.normalizeModels(i.models),updated_at:i.updated_at||new Date(0).toISOString()}]]:[]});return Object.fromEntries(t)}getResolvedActiveProfile(e){const t=e.active_profile||"default";return e.profiles?.[t]||{}}syncLegacyFields(e){const t=this.normalizeProfiles(e.profiles),i=e.active_profile?.trim()||Object.keys(t)[0]||"default",o=t[i]?t:{...t,[i]:{}},s=this.getResolvedActiveProfile({...e,profiles:o,active_profile:i});return{...e,lang:e.lang||"en_US",active_profile:i,profiles:o,presets:this.normalizePresets(e.presets),api_key:s.api_key,base_url:s.base_url,models:s.models?this.normalizeModels(s.models):DEFAULT_MODELS}}sanitizeBackupLabel(e){return(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}getBackupDir(){return f(this.configDir,"backups")}getLegacySecretsPath(){return f(this.configDir,"secrets.enc")}getSecretsBackupPath(e){return e.replace(/\.yaml$/,".secrets.enc")}static getInstance(){return ConfigManager.instance||(ConfigManager.instance=new ConfigManager),ConfigManager.instance}ensureConfigDir(){e(this.configDir)||t(this.configDir,{recursive:!0})}loadConfig(){try{if(e(this.configPath)){const t=i(this.configPath,"utf-8"),o=m.load(t);let s=this.migrateOldConfig(o||{lang:"en_US"}),n=!1;const a=this.getLegacySecretsPath();if(e(a)&&o?.credential_store!==v)try{s=this.mergeLegacySecrets(s,_(a)),n=!0}catch(e){u.warn("Legacy secrets.enc is unreadable on this host; it was kept for recovery and will not block new credentials."),u.logError("ConfigManager.migrateLegacySecrets",e)}if((this.needsMigration(o)||n)&&(this.backupConfig(),this.atomicWrite(this.configPath,m.dump(this.prepareForPersistence(s))),n))try{r(a)}catch(e){u.logError("ConfigManager.removeLegacySecrets",e)}try{l(this.configPath,384)}catch{}return s}const t=this.getLegacySecretsPath();if(e(t))try{const e=this.mergeLegacySecrets(this.createDefaultConfig(),_(t));this.ensureConfigDir(),this.atomicWrite(this.configPath,m.dump(this.prepareForPersistence(e)));try{r(t)}catch(e){u.logError("ConfigManager.removeLegacySecrets",e)}return e}catch(e){u.warn("Legacy secrets.enc is unreadable on this host; it was kept for recovery and will not block new credentials."),u.logError("ConfigManager.migrateLegacySecretsWithoutConfig",e)}}catch(e){u.warn("Failed to load config, using defaults:",e),u.logError("ConfigManager.loadConfig",e)}return this.createDefaultConfig()}needsMigration(e){return!(!e||"object"!=typeof e)&&("plan"in e||!("profiles"in e)||!("active_profile"in e)||!("presets"in e))}migrateOldConfig(e){if(!e||"object"!=typeof e)return this.createDefaultConfig();const t=e,{plan:i,...o}=t,s=this.normalizeProfiles(o.profiles),r=this.normalizeProfile({api_key:"string"==typeof o.api_key?o.api_key:void 0,base_url:"string"==typeof o.base_url?o.base_url:void 0,models:o.models}),n=Object.keys(s).length>0?s:{[DEFAULT_PROFILE_NAME]:r},a="string"==typeof o.active_profile&&o.active_profile.trim()?o.active_profile.trim():Object.keys(n)[0]||"default";return this.syncLegacyFields({lang:"string"==typeof o.lang&&o.lang?o.lang:"en_US",...!0===o.lang_chosen?{lang_chosen:!0}:{},...o.credential_store===v?{credential_store:v}:{},active_profile:a,profiles:n,presets:this.normalizePresets(o.presets)})}atomicWrite(t,i){const n=`${t}.tmp`;try{o(n,i,{encoding:"utf-8",mode:384}),s(n,t);try{l(t,384)}catch{}}catch(t){if(e(n))try{r(n)}catch{}throw t}}backupConfig(){if(!e(this.configPath))return;const s=this.getBackupDir();e(s)||t(s,{recursive:!0});const r=(new Date).toISOString().replace(/[:.]/g,"-"),n=f(s,`config-${r}.yaml`);try{const e=i(this.configPath,"utf-8");o(n,e,{encoding:"utf-8",mode:384}),this.rotateBackups(s,10,30)}catch(e){u.logError("ConfigManager.backupConfig",e)}}rotateBackups(t,i,o){try{const s=Date.now()-24*o*60*60*1e3,a=n(t).filter(e=>e.startsWith("config-")&&e.endsWith(".yaml")).map(e=>({name:e,path:f(t,e),mtime:c(f(t,e)).mtime})).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()),l=new Set;a.slice(i).forEach(e=>l.add(e.path)),a.forEach(e=>{e.mtime.getTime()<s&&l.add(e.path)});for(const t of l){let i=!1;try{r(t),i=!0}catch(e){u.logError("ConfigManager.rotateBackups",e)}if(i){const i=this.getSecretsBackupPath(t);if(e(i))try{r(i)}catch(e){u.logError("ConfigManager.rotateBackups.secrets",e)}}}}catch(e){u.logError("ConfigManager.rotateBackups",e)}}saveConfig(e){try{this.ensureConfigDir(),this.backupConfig();const t=this.syncLegacyFields(this.migrateOldConfig(e||this.config)),i=this.prepareForPersistence(t),o=m.dump(i);this.atomicWrite(this.configPath,o),this.config=t}catch(e){throw u.error("Failed to save config:",e),u.logError("ConfigManager.saveConfig",e),e}}prepareForPersistence(e){const t={...e,credential_store:v};return delete t.api_key,delete t.base_url,delete t.models,t}mergeLegacySecrets(e,t){const i={...e.profiles||{}},o=new Set([...Object.keys(t.api_keys||{}),...Object.keys(t.tool_api_keys||{})]);for(const e of o){const o=i[e]||{},s=o.api_key||t.api_keys?.[e],r={...t.tool_api_keys?.[e]||{},...o.tool_api_keys||{}};i[e]={...o,...s?{api_key:s}:{},...Object.keys(r).length>0?{tool_api_keys:r}:{}}}return this.syncLegacyFields({...e,profiles:i})}getConfig(){return this.syncLegacyFields({...this.config})}updateConfig(e){this.saveConfig({...this.config,...e})}isFirstRun(){return!e(this.configPath)}getLang(){return this.config.lang||"en_US"}isLangChosen(){return!0===this.config.lang_chosen}setLang(e){this.updateConfig({lang:e,lang_chosen:!0})}getActiveProfileName(){return this.config.active_profile||"default"}listProfiles(){return Object.keys(this.config.profiles||{}).sort()}getProfile(e=this.getActiveProfileName()){const t=this.config.profiles?.[e]||{};return{...t.api_key?{api_key:t.api_key}:{},...t.tool_api_keys&&Object.keys(t.tool_api_keys).length>0?{tool_api_keys:this.normalizeStringRecord(t.tool_api_keys)}:{},...t.base_url?{base_url:t.base_url}:{},models:t.models?this.normalizeModels(t.models):DEFAULT_MODELS,...t.tool_models&&Object.keys(t.tool_models).length>0?{tool_models:this.normalizeToolModels(t.tool_models)}:{},...t.tool_settings&&Object.keys(t.tool_settings).length>0?{tool_settings:this.normalizeToolSettings(t.tool_settings)}:{}}}createProfile(e,t=this.getActiveProfileName()){const i=this.getProfile(t),o={...this.config.profiles||{},[e]:{...i.api_key?{api_key:i.api_key}:{},...i.base_url?{base_url:i.base_url}:{},models:this.normalizeModels(i.models)}};this.saveConfig({...this.config,profiles:o})}setActiveProfile(e){if(!this.config.profiles?.[e])throw new Error(`Profile not found: ${e}`);this.saveConfig({...this.config,active_profile:e})}updateProfile(e,t){const i=this.config.profiles?.[e]||{},o=t.models?this.normalizeModels({...i.models,...t.models}):i.models?this.normalizeModels(i.models):void 0,s={...i,...void 0!==t.api_key?{api_key:t.api_key}:{},...void 0!==t.base_url?{base_url:t.base_url}:{},...o?{models:o}:{}},r={...this.config.profiles||{},[e]:s};this.saveConfig({...this.config,profiles:r})}deleteProfile(e){const t={...this.config.profiles||{}};if(!t[e])return;const i=Object.keys(t).filter(t=>t!==e);if(0===i.length)throw new Error("At least one profile must remain");delete t[e];const o=this.getActiveProfileName()===e?i[0]:this.getActiveProfileName();this.saveConfig({...this.config,profiles:t,active_profile:o})}getApiKey(){return this.config.profiles?.[this.getActiveProfileName()]?.api_key}setApiKey(e){this.updateProfile(this.getActiveProfileName(),{api_key:e})}revokeApiKey(){const e=this.config.profiles?.[this.getActiveProfileName()]||{},{api_key:t,tool_api_keys:i,...o}=e,s={...this.config.profiles||{},[this.getActiveProfileName()]:o};this.saveConfig({...this.config,profiles:s})}getApiKeyFingerprint(){const e=this.getApiKey();return e?p("sha256").update(e).digest("hex").slice(0,12):""}getApiKeyForTool(e){const t=this.config.profiles?.[this.getActiveProfileName()];return t?.tool_api_keys?.[e]||t?.api_key||void 0}setToolApiKey(e,t){const i=this.getActiveProfileName(),o=this.config.profiles?.[i]||{},s={...this.config.profiles||{},[i]:{...o,tool_api_keys:{...o.tool_api_keys||{},[e]:t}}};this.saveConfig({...this.config,profiles:s})}clearToolApiKey(e){const t=this.getActiveProfileName(),i=this.config.profiles?.[t]||{},{[e]:o,...s}=i.tool_api_keys||{},r={...i};Object.keys(s).length>0?r.tool_api_keys=s:delete r.tool_api_keys,this.saveConfig({...this.config,profiles:{...this.config.profiles||{},[t]:r}})}listToolApiKeys(){return Object.keys(this.config.profiles?.[this.getActiveProfileName()]?.tool_api_keys||{}).sort()}getToolApiKeyFingerprint(e){const t=this.config.profiles?.[this.getActiveProfileName()]?.tool_api_keys?.[e];return t?p("sha256").update(t).digest("hex").slice(0,12):""}getModels(){const e=this.config.profiles?.[this.getActiveProfileName()]?.models;return e?this.normalizeModels(e):DEFAULT_MODELS}setModels(e){this.updateProfile(this.getActiveProfileName(),{models:this.normalizeModels(e)})}updateModels(e){this.setModels(this.normalizeModels({...this.getModels(),...e}))}getModelsForTool(e){const t=this.getModels(),i=this.config.profiles?.[this.getActiveProfileName()]?.tool_models?.[e];return i?this.normalizeModels({...t,...i}):t}setToolModel(e,t){const i=this.getActiveProfileName(),o=this.config.profiles?.[i]||{},s={...o.tool_models||{}};t&&0!==Object.keys(t).length?s[e]=t:delete s[e];const r={...o};Object.keys(s).length>0?r.tool_models=s:delete r.tool_models;const n={...this.config.profiles||{},[i]:r};this.saveConfig({...this.config,profiles:n})}getToolSettings(e){const t=this.config.profiles?.[this.getActiveProfileName()]?.tool_settings?.[e];return t?{...t}:{}}getToolSetting(e,t){return this.config.profiles?.[this.getActiveProfileName()]?.tool_settings?.[e]?.[t]}setToolSetting(e,t,i){if(this.getToolSetting(e,t)===i)return;const o=this.getActiveProfileName(),s=this.config.profiles?.[o]||{},r={...s.tool_settings||{}};r[e]={...r[e]||{},[t]:i};const n={...this.config.profiles||{},[o]:{...s,tool_settings:r}};this.saveConfig({...this.config,profiles:n})}getCustomPresets(){return{...this.config.presets||{}}}saveCustomPreset(e,t){const i={...this.config.presets||{},[e]:{models:this.normalizeModels(t),updated_at:(new Date).toISOString()}};this.saveConfig({...this.config,presets:i})}deleteCustomPreset(e){const t={...this.config.presets||{}};t[e]&&(delete t[e],this.saveConfig({...this.config,presets:t}))}listBackups(){const t=this.getBackupDir();return e(t)?n(t).filter(e=>e.startsWith("config-")&&e.endsWith(".yaml")).map(e=>{const i=f(t,e);return{name:e,path:i,mtimeMs:c(i).mtimeMs}}).sort((e,t)=>t.mtimeMs-e.mtimeMs):[]}createBackup(s){this.ensureConfigDir();const r=this.getBackupDir();e(r)||t(r,{recursive:!0});const n=(new Date).toISOString().replace(/[:.]/g,"-"),a=this.sanitizeBackupLabel(s),c=f(r,a?`config-${n}-${a}.yaml`:`config-${n}.yaml`),l=e(this.configPath)?i(this.configPath,"utf-8"):m.dump(this.prepareForPersistence(this.getConfig()));return o(c,l,{encoding:"utf-8",mode:384}),this.rotateBackups(r,10,30),c}restoreBackup(t){if(!t||"."===t||".."===t||/[/\\]|\.\./.test(t))throw new Error(`Invalid backup name: ${t}`);const o=this.getBackupDir(),s=f(o,t);if(!e(s))throw new Error(`Backup not found: ${t}`);const r=i(s,"utf-8"),n=m.load(r),a=this.getSecretsBackupPath(s);let c=this.migrateOldConfig(n||this.createDefaultConfig());if(n?.credential_store!==v&&e(a))try{c=this.mergeLegacySecrets(c,_(a))}catch(e){throw new Error(`Legacy backup credentials could not be decrypted: ${a}`,{cause:e})}this.saveConfig(c)}getConfigDir(){return this.configDir}getBaseUrl(){return this.runtimeBaseUrl||this.config.profiles?.[this.getActiveProfileName()]?.base_url||DEFAULT_BASE_URL}hasRuntimeBaseUrl(){return Boolean(this.runtimeBaseUrl)}setBaseUrl(e,t=!1){this.runtimeBaseUrl=e,t&&this.updateProfile(this.getActiveProfileName(),{base_url:e})}resetBaseUrl(){this.runtimeBaseUrl=void 0;const e=this.config.profiles?.[this.getActiveProfileName()]||{},{base_url:t,...i}=e,o={...this.config.profiles||{},[this.getActiveProfileName()]:i};this.saveConfig({...this.config,profiles:o})}}export const configManager=ConfigManager.getInstance();export function savedApiKeys(){const e=new Set;for(const t of configManager.listProfiles()){const i=configManager.getProfile(t);for(const t of[i.api_key,...Object.values(i.tool_api_keys??{})])t?.trim()&&e.add(t.trim())}return[...e]}
1
+ import{existsSync as e,mkdirSync as t,readFileSync as i,writeFileSync as o,renameSync as s,unlinkSync as r,readdirSync as n,rmdirSync as a,statSync as c,chmodSync as l}from"fs";import{join as f,dirname as g,basename as h}from"path";import{homedir as p}from"os";import{createHash as m}from"crypto";import*as u from"js-yaml";import{logger as y}from"../utils/logger.js";import{getDefaultModels as d,isRetiredDefaultModel as _}from"./model-registry.js";import{readLegacySecretsFile as k}from"./secret-store.js";import{brand as b,brandEnv as v}from"./brand.js";export const DEFAULT_BASE_URL=b().gatewayAddresses[0].url;export const DEFAULT_MODELS=d();export const DEFAULT_PROFILE_NAME="default";const P="plaintext";let C=0;export class ConfigManager{static instance;configDir;configPath;config;runtimeBaseUrl;constructor(){this.configDir=this.resolveConfigDir(),this.migrateLegacyConfigDir(),this.configPath=f(this.configDir,"config.yaml"),this.config=this.loadConfig()}migrateLegacyConfigDir(){try{const t=f(g(this.configDir),".chelper");if(t===this.configDir||!e(t))return;if(["config.yaml","secrets.enc"].some(t=>e(f(this.configDir,t))))return;if(e(this.configDir)){for(const i of n(t)){const o=f(this.configDir,i);e(o)||s(f(t,i),o)}0===n(t).length&&a(t)}else s(t,this.configDir);y.record(`Migrated config dir: ${t} -> ${this.configDir}`)}catch(e){y.warn("Failed to migrate legacy .chelper config dir:",e)}}resolveConfigDir(){const e=v("CONFIG_DIR");if(e&&e.trim())return e.trim();const t=v("TEST_HOME");return t&&t.trim()?f(t.trim(),b().configDirName):f(p(),b().configDirName)}createDefaultConfig(){return this.syncLegacyFields({lang:"en_US",active_profile:"default",profiles:{[DEFAULT_PROFILE_NAME]:{}},presets:{}})}normalizeModels(e){const t=t=>{const i=e?.[t]?.trim();return i&&!_(t,i)?i:DEFAULT_MODELS[t]},i={haiku:t("haiku"),sonnet:t("sonnet"),opus:t("opus"),reasoning:t("reasoning")};if(e&&"object"==typeof e)for(const[t,o]of Object.entries(e))t in i||"string"==typeof o&&o.trim()&&(i[t]=o.trim());return i}normalizeToolModels(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||"string"!=typeof e||!t||"object"!=typeof t)return[];const i={};for(const[e,o]of Object.entries(t))"string"==typeof o&&o.trim()&&(i[e]=o.trim());return Object.keys(i).length>0?[[e,i]]:[]});return Object.fromEntries(t)}normalizeToolSettings(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||!t||"object"!=typeof t||Array.isArray(t))return[];const i=Object.fromEntries(Object.entries(t).filter(([,e])=>"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)));return Object.keys(i).length>0?[[e,i]]:[]});return Object.fromEntries(t)}normalizeStringRecord(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]&&Boolean(e[1].trim())).map(([e,t])=>[e,t.trim()]))}normalizeProfile(e){if(!e)return{};const t=this.normalizeToolModels(e.tool_models),i=this.normalizeToolSettings(e.tool_settings),o=this.normalizeStringRecord(e.tool_api_keys);return{..."string"==typeof e.api_key&&e.api_key?{api_key:e.api_key}:{},...Object.keys(o).length>0?{tool_api_keys:o}:{},..."string"==typeof e.base_url&&e.base_url?{base_url:e.base_url}:{},...e.models?{models:this.normalizeModels(e.models)}:{},...Object.keys(t).length>0?{tool_models:t}:{},...Object.keys(i).length>0?{tool_settings:i}:{}}}normalizeProfiles(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>e&&"string"==typeof e&&t&&"object"==typeof t?[[e,this.normalizeProfile(t)]]:[]);return Object.fromEntries(t)}normalizePresets(e){if(!e||"object"!=typeof e)return{};const t=Object.entries(e).flatMap(([e,t])=>{if(!e||"string"!=typeof e||!t||"object"!=typeof t)return[];const i=t;return i.models?[[e,{models:this.normalizeModels(i.models),updated_at:i.updated_at||new Date(0).toISOString()}]]:[]});return Object.fromEntries(t)}getResolvedActiveProfile(e){const t=e.active_profile||"default";return e.profiles?.[t]||{}}syncLegacyFields(e){const t=this.normalizeProfiles(e.profiles),i=e.active_profile?.trim()||Object.keys(t)[0]||"default",o=t[i]?t:{...t,[i]:{}},s=this.getResolvedActiveProfile({...e,profiles:o,active_profile:i});return{...e,lang:e.lang||"en_US",active_profile:i,profiles:o,presets:this.normalizePresets(e.presets),api_key:s.api_key,base_url:s.base_url,models:s.models?this.normalizeModels(s.models):DEFAULT_MODELS}}sanitizeBackupLabel(e){return(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}getBackupDir(){return f(this.configDir,"backups")}getLegacySecretsPath(){return f(this.configDir,"secrets.enc")}getSecretsBackupPath(e){return e.replace(/\.yaml$/,".secrets.enc")}static getInstance(){return ConfigManager.instance||(ConfigManager.instance=new ConfigManager),ConfigManager.instance}ensureConfigDir(){e(this.configDir)||t(this.configDir,{recursive:!0})}loadConfig(){try{if(e(this.configPath)){const t=i(this.configPath,"utf-8");let o;try{if(o=u.load(t),null!=o&&("object"!=typeof o||Array.isArray(o)))throw new Error("config.yaml is not a mapping")}catch(e){throw this.keepCorruptConfig(),e}let s=this.migrateOldConfig(o||{lang:"en_US"}),n=!1;const a=this.getLegacySecretsPath();if(e(a)&&o?.credential_store!==P)try{s=this.mergeLegacySecrets(s,k(a)),n=!0}catch(e){y.warn("Legacy secrets.enc is unreadable on this host; it was kept for recovery and will not block new credentials."),y.logError("ConfigManager.migrateLegacySecrets",e)}if((this.needsMigration(o)||n)&&(this.backupConfig(),this.atomicWrite(this.configPath,u.dump(this.prepareForPersistence(s))),n))try{r(a)}catch(e){y.logError("ConfigManager.removeLegacySecrets",e)}try{l(this.configPath,384)}catch{}return s}const t=this.getLegacySecretsPath();if(e(t))try{const e=this.mergeLegacySecrets(this.createDefaultConfig(),k(t));this.ensureConfigDir(),this.atomicWrite(this.configPath,u.dump(this.prepareForPersistence(e)));try{r(t)}catch(e){y.logError("ConfigManager.removeLegacySecrets",e)}return e}catch(e){y.warn("Legacy secrets.enc is unreadable on this host; it was kept for recovery and will not block new credentials."),y.logError("ConfigManager.migrateLegacySecretsWithoutConfig",e)}}catch(e){y.warn("Failed to load config, using defaults:",e),y.logError("ConfigManager.loadConfig",e)}return this.createDefaultConfig()}needsMigration(e){return!(!e||"object"!=typeof e)&&("plan"in e||!("profiles"in e)||!("active_profile"in e)||!("presets"in e))}migrateOldConfig(e){if(!e||"object"!=typeof e)return this.createDefaultConfig();const t=e,{plan:i,...o}=t,s=this.normalizeProfiles(o.profiles),r=this.normalizeProfile({api_key:"string"==typeof o.api_key?o.api_key:void 0,base_url:"string"==typeof o.base_url?o.base_url:void 0,models:o.models}),n=Object.keys(s).length>0?s:{[DEFAULT_PROFILE_NAME]:r},a="string"==typeof o.active_profile&&o.active_profile.trim()?o.active_profile.trim():Object.keys(n)[0]||"default";return this.syncLegacyFields({lang:"string"==typeof o.lang&&o.lang?o.lang:"en_US",...!0===o.lang_chosen?{lang_chosen:!0}:{},...o.credential_store===P?{credential_store:P}:{},active_profile:a,profiles:n,presets:this.normalizePresets(o.presets),...o.machine_settings&&"object"==typeof o.machine_settings&&Object.keys(o.machine_settings).length>0?{machine_settings:this.normalizeToolSettings(o.machine_settings)}:{}})}atomicWrite(t,i){const n=`${t}.${process.pid}.${C+=1}.tmp`;try{o(n,i,{encoding:"utf-8",mode:384}),s(n,t);try{l(t,384)}catch{}this.removeStaleTempFiles(t)}catch(t){if(e(n))try{r(n)}catch{}throw t}}removeStaleTempFiles(e){try{const t=g(e),i=`${h(e)}.`,o=Date.now()-6e5;for(const e of n(t)){if(!e.startsWith(i)||!/^(\d+\.\d+\.)?tmp$/.test(e.slice(i.length)))continue;const s=f(t,e);c(s).mtimeMs<o&&r(s)}}catch{}}keepCorruptConfig(){try{const e=g(this.configPath),t=`${h(this.configPath)}.corrupt-`,s=i(this.configPath);for(const o of n(e))if(o.startsWith(t)){if(i(f(e,o)).equals(s))return;r(f(e,o))}const a=f(e,`${t}${(new Date).toISOString().replace(/[:.]/g,"-")}`);o(a,s,{mode:384}),y.warn(`Unreadable config kept as ${a}`)}catch(e){y.logError("ConfigManager.keepCorruptConfig",e)}}backupConfig(){if(!e(this.configPath))return;const s=this.getBackupDir();e(s)||t(s,{recursive:!0});const r=(new Date).toISOString().replace(/[:.]/g,"-"),n=f(s,`config-${r}.yaml`);try{const e=i(this.configPath,"utf-8");o(n,e,{encoding:"utf-8",mode:384}),this.rotateBackups(s,10,30)}catch(e){y.logError("ConfigManager.backupConfig",e)}}rotateBackups(t,i,o){try{const s=Date.now()-24*o*60*60*1e3,a=n(t).filter(e=>e.startsWith("config-")&&e.endsWith(".yaml")).map(e=>({name:e,path:f(t,e),mtime:c(f(t,e)).mtime})).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()),l=new Set;a.slice(i).forEach(e=>l.add(e.path)),a.forEach(e=>{e.mtime.getTime()<s&&l.add(e.path)});for(const t of l){let i=!1;try{r(t),i=!0}catch(e){y.logError("ConfigManager.rotateBackups",e)}if(i){const i=this.getSecretsBackupPath(t);if(e(i))try{r(i)}catch(e){y.logError("ConfigManager.rotateBackups.secrets",e)}}}}catch(e){y.logError("ConfigManager.rotateBackups",e)}}saveConfig(e){try{this.ensureConfigDir(),this.backupConfig();const t=this.syncLegacyFields(this.migrateOldConfig(e||this.config)),i=this.prepareForPersistence(t),o=u.dump(i);this.atomicWrite(this.configPath,o),this.config=t}catch(e){throw y.error("Failed to save config:",e),y.logError("ConfigManager.saveConfig",e),e}}prepareForPersistence(e){const t={...e,credential_store:P};return delete t.api_key,delete t.base_url,delete t.models,t}mergeLegacySecrets(e,t){const i={...e.profiles||{}},o=new Set([...Object.keys(t.api_keys||{}),...Object.keys(t.tool_api_keys||{})]);for(const e of o){const o=i[e]||{},s=o.api_key||t.api_keys?.[e],r={...t.tool_api_keys?.[e]||{},...o.tool_api_keys||{}};i[e]={...o,...s?{api_key:s}:{},...Object.keys(r).length>0?{tool_api_keys:r}:{}}}return this.syncLegacyFields({...e,profiles:i})}getConfig(){return this.syncLegacyFields({...this.config})}updateConfig(e){this.saveConfig({...this.config,...e})}isFirstRun(){return!e(this.configPath)}getLang(){return this.config.lang||"en_US"}isLangChosen(){return!0===this.config.lang_chosen}setLang(e){this.updateConfig({lang:e,lang_chosen:!0})}getActiveProfileName(){return this.config.active_profile||"default"}listProfiles(){return Object.keys(this.config.profiles||{}).sort()}getProfile(e=this.getActiveProfileName()){const t=this.config.profiles?.[e]||{};return{...t.api_key?{api_key:t.api_key}:{},...t.tool_api_keys&&Object.keys(t.tool_api_keys).length>0?{tool_api_keys:this.normalizeStringRecord(t.tool_api_keys)}:{},...t.base_url?{base_url:t.base_url}:{},models:t.models?this.normalizeModels(t.models):DEFAULT_MODELS,...t.tool_models&&Object.keys(t.tool_models).length>0?{tool_models:this.normalizeToolModels(t.tool_models)}:{},...t.tool_settings&&Object.keys(t.tool_settings).length>0?{tool_settings:this.normalizeToolSettings(t.tool_settings)}:{}}}createProfile(e,t=this.getActiveProfileName()){const i=this.getProfile(t),o={...this.config.profiles||{},[e]:{...i.api_key?{api_key:i.api_key}:{},...i.base_url?{base_url:i.base_url}:{},models:this.normalizeModels(i.models)}};this.saveConfig({...this.config,profiles:o})}setActiveProfile(e){if(!this.config.profiles?.[e])throw new Error(`Profile not found: ${e}`);this.saveConfig({...this.config,active_profile:e})}updateProfile(e,t){const i=this.config.profiles?.[e]||{},o=t.models?this.normalizeModels({...i.models,...t.models}):i.models?this.normalizeModels(i.models):void 0,s={...i,...void 0!==t.api_key?{api_key:t.api_key}:{},...void 0!==t.base_url?{base_url:t.base_url}:{},...o?{models:o}:{}},r={...this.config.profiles||{},[e]:s};this.saveConfig({...this.config,profiles:r})}deleteProfile(e){const t={...this.config.profiles||{}};if(!t[e])return;const i=Object.keys(t).filter(t=>t!==e);if(0===i.length)throw new Error("At least one profile must remain");delete t[e];const o=this.getActiveProfileName()===e?i[0]:this.getActiveProfileName();this.saveConfig({...this.config,profiles:t,active_profile:o})}getApiKey(){return this.config.profiles?.[this.getActiveProfileName()]?.api_key}setApiKey(e){this.updateProfile(this.getActiveProfileName(),{api_key:e})}revokeApiKey(){const e=this.config.profiles?.[this.getActiveProfileName()]||{},{api_key:t,tool_api_keys:i,...o}=e,s={...this.config.profiles||{},[this.getActiveProfileName()]:o};this.saveConfig({...this.config,profiles:s})}getApiKeyFingerprint(){const e=this.getApiKey();return e?m("sha256").update(e).digest("hex").slice(0,12):""}getApiKeyForTool(e){const t=this.config.profiles?.[this.getActiveProfileName()];return t?.tool_api_keys?.[e]||t?.api_key||void 0}setToolApiKey(e,t){const i=this.getActiveProfileName(),o=this.config.profiles?.[i]||{},s={...this.config.profiles||{},[i]:{...o,tool_api_keys:{...o.tool_api_keys||{},[e]:t}}};this.saveConfig({...this.config,profiles:s})}clearToolApiKey(e){const t=this.getActiveProfileName(),i=this.config.profiles?.[t]||{},{[e]:o,...s}=i.tool_api_keys||{},r={...i};Object.keys(s).length>0?r.tool_api_keys=s:delete r.tool_api_keys,this.saveConfig({...this.config,profiles:{...this.config.profiles||{},[t]:r}})}listToolApiKeys(){return Object.keys(this.config.profiles?.[this.getActiveProfileName()]?.tool_api_keys||{}).sort()}getToolApiKeyFingerprint(e){const t=this.config.profiles?.[this.getActiveProfileName()]?.tool_api_keys?.[e];return t?m("sha256").update(t).digest("hex").slice(0,12):""}getModels(){const e=this.config.profiles?.[this.getActiveProfileName()]?.models;return e?this.normalizeModels(e):DEFAULT_MODELS}setModels(e){this.updateProfile(this.getActiveProfileName(),{models:this.normalizeModels(e)})}updateModels(e){this.setModels(this.normalizeModels({...this.getModels(),...e}))}getModelsForTool(e){const t=this.getModels(),i=this.config.profiles?.[this.getActiveProfileName()]?.tool_models?.[e];return i?this.normalizeModels({...t,...i}):t}setToolModel(e,t){const i=this.getActiveProfileName(),o=this.config.profiles?.[i]||{},s={...o.tool_models||{}};t&&0!==Object.keys(t).length?s[e]=t:delete s[e];const r={...o};Object.keys(s).length>0?r.tool_models=s:delete r.tool_models;const n={...this.config.profiles||{},[i]:r};this.saveConfig({...this.config,profiles:n})}getToolSettings(e){const t=this.config.profiles?.[this.getActiveProfileName()]?.tool_settings?.[e];return t?{...t}:{}}getToolSetting(e,t){return this.config.profiles?.[this.getActiveProfileName()]?.tool_settings?.[e]?.[t]}setToolSetting(e,t,i){if(this.getToolSetting(e,t)===i)return;const o=this.getActiveProfileName(),s=this.config.profiles?.[o]||{},r={...s.tool_settings||{}};r[e]={...r[e]||{},[t]:i};const n={...this.config.profiles||{},[o]:{...s,tool_settings:r}};this.saveConfig({...this.config,profiles:n})}getMachineSetting(e,t){return this.machineSettingValues(e,t)[0]}machineSettingValues(e,t){const i=this.getActiveProfileName(),o=[i,...Object.keys(this.config.profiles||{}).filter(e=>e!==i)];return[this.config.machine_settings?.[e]?.[t],...o.map(i=>this.config.profiles?.[i]?.tool_settings?.[e]?.[t])].filter(e=>void 0!==e)}setMachineSetting(e,t,i){if(this.config.machine_settings?.[e]?.[t]===i)return;const o={...this.config.machine_settings||{}};o[e]={...o[e]||{},[t]:i},this.saveConfig({...this.config,machine_settings:o})}getCustomPresets(){return{...this.config.presets||{}}}saveCustomPreset(e,t){const i={...this.config.presets||{},[e]:{models:this.normalizeModels(t),updated_at:(new Date).toISOString()}};this.saveConfig({...this.config,presets:i})}deleteCustomPreset(e){const t={...this.config.presets||{}};t[e]&&(delete t[e],this.saveConfig({...this.config,presets:t}))}listBackups(){const t=this.getBackupDir();return e(t)?n(t).filter(e=>e.startsWith("config-")&&e.endsWith(".yaml")).map(e=>{const i=f(t,e);return{name:e,path:i,mtimeMs:c(i).mtimeMs}}).sort((e,t)=>t.mtimeMs-e.mtimeMs):[]}createBackup(s){this.ensureConfigDir();const r=this.getBackupDir();e(r)||t(r,{recursive:!0});const n=(new Date).toISOString().replace(/[:.]/g,"-"),a=this.sanitizeBackupLabel(s),c=f(r,a?`config-${n}-${a}.yaml`:`config-${n}.yaml`),l=e(this.configPath)?i(this.configPath,"utf-8"):u.dump(this.prepareForPersistence(this.getConfig()));return o(c,l,{encoding:"utf-8",mode:384}),this.rotateBackups(r,10,30),c}restoreBackup(t){if(!t||"."===t||".."===t||/[/\\]|\.\./.test(t))throw new Error(`Invalid backup name: ${t}`);const o=this.getBackupDir(),s=f(o,t);if(!e(s))throw new Error(`Backup not found: ${t}`);const r=i(s,"utf-8"),n=u.load(r),a=this.getSecretsBackupPath(s);let c=this.migrateOldConfig(n||this.createDefaultConfig());if(n?.credential_store!==P&&e(a))try{c=this.mergeLegacySecrets(c,k(a))}catch(e){throw new Error(`Legacy backup credentials could not be decrypted: ${a}`,{cause:e})}this.saveConfig(c)}getConfigDir(){return this.configDir}getBaseUrl(){return this.runtimeBaseUrl||this.config.profiles?.[this.getActiveProfileName()]?.base_url||DEFAULT_BASE_URL}hasRuntimeBaseUrl(){return Boolean(this.runtimeBaseUrl)}setBaseUrl(e,t=!1){this.runtimeBaseUrl=e,t&&this.updateProfile(this.getActiveProfileName(),{base_url:e})}resetBaseUrl(){this.runtimeBaseUrl=void 0;const e=this.config.profiles?.[this.getActiveProfileName()]||{},{base_url:t,...i}=e,o={...this.config.profiles||{},[this.getActiveProfileName()]:i};this.saveConfig({...this.config,profiles:o})}}export const configManager=ConfigManager.getInstance();export function savedApiKeys(){const e=new Set;for(const t of configManager.listProfiles()){const i=configManager.getProfile(t);for(const t of[i.api_key,...Object.values(i.tool_api_keys??{})])t?.trim()&&e.add(t.trim())}return[...e]}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as r,writeFileSync as n}from"fs";import{join as t}from"path";import{logger as s}from"../utils/logger.js";import{toolHome as c}from"./tools/types.js";import{backupBeforeWrite as i}from"./tools/backup.js";import{configManager as u,savedApiKeys as f}from"./config.js";import{isOurGatewayUrl as l}from"./gateway-addresses.js";import{broadcastEnvChange as a,deleteWindowsEnv as p,readWindowsEnv as m}from"./windows-env.js";export const ANTHROPIC_ENV_VARS=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];export function getShellRcFilePath(){if("win32"===process.platform)return null;const e=c();switch((process.env.SHELL||"").split("/").pop()||""){case"bash":return t(e,".bashrc");case"zsh":return t(e,".zshrc");case"fish":return t(e,".config","fish","config.fish");default:return t(e,".profile")}}function h(e){const o=e.trim().replace(/\s+#.*$/,""),r=o.match(/^(['"])(.*)\1$/);return r?r[2]:o}const v=e=>new RegExp(String.raw`^\s*export\s+${e}=(.*)$`,"gm"),E=e=>new RegExp(String.raw`^[ \t]*\$env:${e}[ \t]*=(.*)$`,"gim");function g(e){if(l(e.ANTHROPIC_BASE_URL))return!0;const o=f();return[e.ANTHROPIC_API_KEY,e.ANTHROPIC_AUTH_TOKEN].some(e=>Boolean(e)&&o.includes(e.trim()))}export function anthropicEnvSources(){const o=[],n=(n,t)=>{if(n&&e(n))try{const e=function(e,o){const r={};for(const n of ANTHROPIC_ENV_VARS)for(const t of e.matchAll(o(n)))r[n]=h(t[1]);return r}(r(n,"utf-8"),t);Object.keys(e).length>0&&o.push({kind:"file",location:n,vars:e,ours:g(e)})}catch(e){s.logError("envCleanup.read",e)}};if("win32"!==process.platform)return n(getShellRcFilePath(),v),o;for(const e of["user","machine"]){const r={};for(const o of ANTHROPIC_ENV_VARS){const n=m(e,o);void 0!==n&&(r[o]=n)}Object.keys(r).length>0&&o.push({kind:"user"===e?"windows-user":"windows-machine",location:"user"===e?"HKCU\\Environment":"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",vars:r,ours:g(r)})}for(const e of function(){const e=c(),o=[];for(const r of[t(e,"Documents"),t(e,"OneDrive","Documents"),t(e,"OneDrive","文档")])for(const e of["PowerShell","WindowsPowerShell"])o.push(t(r,e,"Microsoft.PowerShell_profile.ps1"),t(r,e,"profile.ps1"));return o}())n(e,E);return o}function O(e,o,t){const c=r(e,"utf-8");let u=c;for(const e of o)u=u.replace(new RegExp(t(e).source+String.raw`(\r?\n)?`,t(e).flags),"");return t===v&&(u=u.replace(/^\s*#\s*Claude Code environment variables\s*$\n?/gm,"")),u!==c&&(i(e),n(e,u,"utf-8"),s.debug(`Removed ${o.join(", ")} from ${e}`),!0)}function _(e,r){try{const s=t(u.getConfigDir(),"backups");o(s,{recursive:!0});const c=t(s,`windows-env-${e}-${(new Date).toISOString().replace(/[:.]/g,"-")}.json`);return n(c,JSON.stringify(r,null,2)+"\n",{mode:384}),c}catch(e){return s.logError("envCleanup.backupWindowsValues",e),null}}let A={removed:[],foreign:[],machineLeft:[]};export function cleanupAnthropicEnvVars(){const e=anthropicEnvSources(),o=removeEnvSources(e.filter(e=>e.ours));return o.foreign=e.filter(e=>!e.ours),A=o,o}export function removeEnvSources(e){const o={removed:[],foreign:[],machineLeft:[]};let r=!1;for(const n of e){const e=Object.keys(n.vars);try{if("file"===n.kind){O(n.location,e,n.location.endsWith(".ps1")?E:v)&&o.removed.push(n);continue}const t="windows-user"===n.kind?"user":"machine";_(t,n.vars);const c=[];for(const r of e)try{p(t,r),c.push(r)}catch(e){"machine"===t&&o.machineLeft.push(r),s.logError("envCleanup.deleteWindowsEnv",e)}c.length>0&&(r=!0,o.removed.push({...n,vars:Object.fromEntries(c.map(e=>[e,n.vars[e]]))}))}catch(e){s.logError("envCleanup.removeEnvSources",e)}}r&&a();for(const e of o.removed)for(const[o,r]of Object.entries(e.vars))process.env[o]===r&&delete process.env[o];return o}export function lastEnvCleanup(){return A}export function envCleanupPlan(){return anthropicEnvSources().filter(e=>e.ours)}
1
+ import{existsSync as e,mkdirSync as o,readdirSync as r,readFileSync as n,realpathSync as t,rmSync as s,writeFileSync as c}from"fs";import{join as i}from"path";import{logger as f}from"../utils/logger.js";import{toolHome as u}from"./tools/types.js";import{atomicWriteFile as a,backupBeforeWrite as l}from"./tools/backup.js";import{configManager as p,savedApiKeys as m}from"./config.js";import{isOurGatewayUrl as h}from"./gateway-addresses.js";import{broadcastEnvChange as v,deleteWindowsEnv as E,readWindowsEnv as _}from"./windows-env.js";export const ANTHROPIC_ENV_VARS=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];export function getShellRcFilePath(){if("win32"===process.platform)return null;const e=u();switch((process.env.SHELL||"").split("/").pop()||""){case"bash":return i(e,".bashrc");case"zsh":return i(e,".zshrc");case"fish":return i(e,".config","fish","config.fish");default:return i(e,".profile")}}function g(e){const o=e.trim().replace(/\s+#.*$/,""),r=o.match(/^(['"])(.*)\1$/);return r?r[2]:o}const O=e=>new RegExp(String.raw`^\s*export\s+${e}=(.*)$`,"gm"),d=e=>new RegExp(String.raw`^[ \t]*\$env:${e}[ \t]*=(.*)$`,"gim");function A(e){if(h(e.ANTHROPIC_BASE_URL))return!0;const o=m();return[e.ANTHROPIC_API_KEY,e.ANTHROPIC_AUTH_TOKEN].some(e=>Boolean(e)&&o.includes(e.trim()))}export function anthropicEnvSources(){const o=[],r=(r,t)=>{if(r&&e(r))try{const e=function(e,o){const r={};for(const n of ANTHROPIC_ENV_VARS)for(const t of e.matchAll(o(n)))r[n]=g(t[1]);return r}(n(r,"utf-8"),t);Object.keys(e).length>0&&o.push({kind:"file",location:r,vars:e,ours:A(e)})}catch(e){f.logError("envCleanup.read",e)}};if("win32"!==process.platform)return r(getShellRcFilePath(),O),o;for(const e of["user","machine"]){const r={};for(const o of ANTHROPIC_ENV_VARS){const n=_(e,o);void 0!==n&&(r[o]=n)}Object.keys(r).length>0&&o.push({kind:"user"===e?"windows-user":"windows-machine",location:"user"===e?"HKCU\\Environment":"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",vars:r,ours:A(r)})}for(const e of function(){const e=u(),o=[];for(const r of[i(e,"Documents"),i(e,"OneDrive","Documents"),i(e,"OneDrive","文档")])for(const e of["PowerShell","WindowsPowerShell"])o.push(i(r,e,"Microsoft.PowerShell_profile.ps1"),i(r,e,"profile.ps1"));return o}())r(e,d);return o}function S(e,o,r){const s=n(e,"utf-8");let c=s;for(const e of o)c=c.replace(new RegExp(r(e).source+String.raw`(\r?\n)?`,r(e).flags),"");return r===O&&(c=c.replace(/^\s*#\s*Claude Code environment variables\s*$\n?/gm,"")),c!==s&&(l(e),a(t(e),c),f.debug(`Removed ${o.join(", ")} from ${e}`),!0)}export const MAX_WINDOWS_ENV_BACKUPS=10;function C(e,n){try{const t=i(p.getConfigDir(),"backups");o(t,{recursive:!0});const f=`windows-env-${e}-`,u=i(t,`${f}${(new Date).toISOString().replace(/[:.]/g,"-")}.json`);c(u,JSON.stringify(n,null,2)+"\n",{mode:384});const a=r(t).filter(e=>e.startsWith(f)&&e.endsWith(".json")&&i(t,e)!==u).sort().reverse();for(const e of a.slice(9))s(i(t,e),{force:!0});return u}catch(e){return f.logError("envCleanup.backupWindowsValues",e),null}}let w={removed:[],foreign:[],machineLeft:[],notBackedUp:[]};export function cleanupAnthropicEnvVars(){const e=anthropicEnvSources(),o=removeEnvSources(e.filter(e=>e.ours));return o.foreign=e.filter(e=>!e.ours),w=o,o}export function removeEnvSources(e){const o={removed:[],foreign:[],machineLeft:[],notBackedUp:[]};let r=!1;for(const n of e){const e=Object.keys(n.vars);try{if("file"===n.kind){S(n.location,e,n.location.endsWith(".ps1")?d:O)&&o.removed.push(n);continue}const t="windows-user"===n.kind?"user":"machine",c=C(t,n.vars);if(!c){o.notBackedUp.push(n);continue}const i=[];for(const r of e)try{E(t,r),i.push(r)}catch(e){"machine"===t&&o.machineLeft.push(r),f.logError("envCleanup.deleteWindowsEnv",e)}0===i.length&&s(c,{force:!0}),i.length>0&&(r=!0,o.removed.push({...n,vars:Object.fromEntries(i.map(e=>[e,n.vars[e]]))}))}catch(e){f.logError("envCleanup.removeEnvSources",e)}}r&&v();for(const e of o.removed)for(const[o,r]of Object.entries(e.vars))process.env[o]===r&&delete process.env[o];return o}export function lastEnvCleanup(){return w}export function envCleanupPlan(){return anthropicEnvSources().filter(e=>e.ours)}
@@ -1 +1 @@
1
- import{existsSync as r,mkdirSync as e,readFileSync as t,writeFileSync as o}from"fs";import{join as s}from"path";import{configManager as n}from"./config.js";import{noteGatewayUrl as a,wroteGatewayUrl as i}from"./written-values.js";import{getBuiltinGatewayAddresses as l}from"./model-registry.js";import{logger as u}from"../utils/logger.js";const c=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]);function f(){return s(n.getConfigDir(),"gateway-addresses.json")}export function normalizeBaseUrl(r){let e,t=r.trim();if(!t)return null;/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||(t=`https://${t}`);try{e=new URL(t)}catch{return null}if("https:"!==e.protocol&&"http:"!==e.protocol)return null;const o=e.pathname.replace(/\/+$/,"").replace(/\/v1$/i,"");return`${e.protocol}//${e.host}${o}`}export function parsePublishedAddresses(r){if(!Array.isArray(r))return[];const e=new Set,t=[];for(const o of r){if(!o||"object"!=typeof o)continue;const{url:r,route:s,description:n}=o,a="string"==typeof r?normalizeBaseUrl(r):null;if(!a?.startsWith("https://")||e.has(a))continue;e.add(a);const i="string"==typeof s?s.trim():"",l="string"==typeof n?n.trim():"";t.push({url:a,label:i&&l?`${i}(${l})`:i||l})}return t}export function rememberPublishedAddresses(r,t){if(!r||"object"!=typeof r)return;if(!l().some(r=>normalizeBaseUrl(r.url)===t))return;const s=r;if(!1===s.api_info_enabled)return;const a=parsePublishedAddresses(s.api_info);if(0!==a.length)try{e(n.getConfigDir(),{recursive:!0}),o(f(),JSON.stringify({addresses:a},null,2)+"\n")}catch(r){u.logError("rememberPublishedAddresses",r)}}export function gatewayAddresses(){const e=function(){const e=f();if(!r(e))return[];try{const r=JSON.parse(t(e,"utf-8"));return(Array.isArray(r.addresses)?r.addresses:[]).flatMap(r=>{const e="string"==typeof r?.url?normalizeBaseUrl(r.url):null;return e?[{url:e,label:"string"==typeof r.label?r.label:""}]:[]})}catch{return[]}}(),o=[];for(const r of l()){const t=normalizeBaseUrl(r.url);if(!t||o.some(r=>r.url===t))continue;const s=e.find(r=>r.url===t)?.label||r.label;o.push({url:t,label:s})}for(const r of e)o.some(e=>e.url===r.url)||o.push(r);return o}export function isOurGatewayUrl(r){if("string"!=typeof r)return!1;const e=normalizeBaseUrl(r);return!!e&&(gatewayAddresses().some(r=>r.url===e)||e===normalizeBaseUrl(n.getBaseUrl())||i(e))}export function noteWrittenGatewayUrl(r){const e=normalizeBaseUrl(r);e&&a(e)}function m(r){const e=r?.cause,t="string"==typeof e?.code?e.code:"",o="string"==typeof e?.message?e.message:r instanceof Error?r.message:String(r);return r instanceof Error&&"AbortError"===r.name?{error:"timeout",detail:o}:c.has(t)||/certificate/i.test(o)?{error:"certificate",detail:t||o}:{error:"network",detail:t||o}}export async function probeGatewayAddress(r,e={}){e.apiKey&&!function(r){return r===n.getBaseUrl()||l().some(e=>normalizeBaseUrl(e.url)===r)}(r)&&(e={...e,apiKey:void 0});const t=Math.max(1,e.samples??1),o=[];let s;for(let n=0;n<t;n+=1){const t=await d(r,e);if(!t.ok)return t;o.push(t.ms),s=t.models}return o.sort((r,e)=>r-e),{url:r,ok:!0,ms:o[Math.floor(o.length/2)],...void 0===s?{}:{models:s}}}async function d(r,e){const{apiKey:t,timeoutMs:o=8e3,fetchFn:s=fetch}=e,n=new AbortController,a=setTimeout(()=>n.abort(),o),i=Date.now();try{const e=await s(t?`${r}/v1/models`:`${r}/api/status`,{method:"GET",headers:t?{Authorization:`Bearer ${t}`}:void 0,signal:n.signal});let o;try{o=(await e.json())?.data}catch{o=void 0}const a=Date.now()-i;return!t||401!==e.status&&403!==e.status?t?e.ok&&Array.isArray(o)?{url:r,ok:!0,ms:a,models:o.length}:{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:e.ok&&o&&"object"==typeof o?(rememberPublishedAddresses(o,r),{url:r,ok:!0,ms:a}):{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:{url:r,ok:!1,ms:a,error:"key_rejected",detail:`HTTP ${e.status}`}}catch(e){return{url:r,ok:!1,ms:Date.now()-i,...m(e)}}finally{clearTimeout(a)}}
1
+ import{existsSync as r,readFileSync as e}from"fs";import{join as t}from"path";import{configManager as o}from"./config.js";import{noteGatewayUrl as s,wroteGatewayUrl as n}from"./written-values.js";import{getBuiltinGatewayAddresses as a}from"./model-registry.js";import{atomicWriteFile as i}from"./tools/backup.js";import{logger as l}from"../utils/logger.js";const u=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]);function c(){return t(o.getConfigDir(),"gateway-addresses.json")}export function normalizeBaseUrl(r){let e,t=r.trim();if(!t)return null;/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||(t=`https://${t}`);try{e=new URL(t)}catch{return null}if("https:"!==e.protocol&&"http:"!==e.protocol)return null;const o=e.pathname.replace(/\/+$/,"").replace(/\/v1$/i,"");return`${e.protocol}//${e.host}${o}`}export function parsePublishedAddresses(r){if(!Array.isArray(r))return[];const e=new Set,t=[];for(const o of r){if(!o||"object"!=typeof o)continue;const{url:r,route:s,description:n}=o,a="string"==typeof r?normalizeBaseUrl(r):null;if(!a?.startsWith("https://")||e.has(a))continue;e.add(a);const i="string"==typeof s?s.trim():"",l="string"==typeof n?n.trim():"";t.push({url:a,label:i&&l?`${i}(${l})`:i||l})}return t}export function rememberPublishedAddresses(r,e){if(!r||"object"!=typeof r)return;if(!a().some(r=>normalizeBaseUrl(r.url)===e))return;const t=r;if(!1===t.api_info_enabled)return;const o=parsePublishedAddresses(t.api_info);if(0!==o.length)try{i(c(),JSON.stringify({addresses:o},null,2)+"\n")}catch(r){l.logError("rememberPublishedAddresses",r)}}export function gatewayAddresses(){const t=function(){const t=c();if(!r(t))return[];try{const r=JSON.parse(e(t,"utf-8"));return(Array.isArray(r.addresses)?r.addresses:[]).flatMap(r=>{const e="string"==typeof r?.url?normalizeBaseUrl(r.url):null;return e?[{url:e,label:"string"==typeof r.label?r.label:""}]:[]})}catch{return[]}}(),o=[];for(const r of a()){const e=normalizeBaseUrl(r.url);if(!e||o.some(r=>r.url===e))continue;const s=t.find(r=>r.url===e)?.label||r.label;o.push({url:e,label:s})}for(const r of t)o.some(e=>e.url===r.url)||o.push(r);return o}export function isOurGatewayUrl(r){if("string"!=typeof r)return!1;const e=normalizeBaseUrl(r);return!!e&&(gatewayAddresses().some(r=>r.url===e)||e===normalizeBaseUrl(o.getBaseUrl())||n(e))}export function noteWrittenGatewayUrl(r){const e=normalizeBaseUrl(r);e&&s(e)}function f(r){const e=r?.cause,t="string"==typeof e?.code?e.code:"",o="string"==typeof e?.message?e.message:r instanceof Error?r.message:String(r);return r instanceof Error&&"AbortError"===r.name?{error:"timeout",detail:o}:u.has(t)||/certificate/i.test(o)?{error:"certificate",detail:t||o}:{error:"network",detail:t||o}}export async function probeGatewayAddress(r,e={}){e.apiKey&&!function(r){return r===o.getBaseUrl()||a().some(e=>normalizeBaseUrl(e.url)===r)}(r)&&(e={...e,apiKey:void 0});const t=Math.max(1,e.samples??1),s=[];let n;for(let o=0;o<t;o+=1){const t=await m(r,e);if(!t.ok)return t;s.push(t.ms),n=t.models}return s.sort((r,e)=>r-e),{url:r,ok:!0,ms:s[Math.floor(s.length/2)],...void 0===n?{}:{models:n}}}async function m(r,e){const{apiKey:t,timeoutMs:o=8e3,fetchFn:s=fetch}=e,n=new AbortController,a=setTimeout(()=>n.abort(),o),i=Date.now();try{const e=await s(t?`${r}/v1/models`:`${r}/api/status`,{method:"GET",headers:t?{Authorization:`Bearer ${t}`}:void 0,signal:n.signal});let o;try{o=(await e.json())?.data}catch{o=void 0}const a=Date.now()-i;return!t||401!==e.status&&403!==e.status?t?e.ok&&Array.isArray(o)?{url:r,ok:!0,ms:a,models:o.length}:{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:e.ok&&o&&"object"==typeof o?(rememberPublishedAddresses(o,r),{url:r,ok:!0,ms:a}):{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:{url:r,ok:!1,ms:a,error:"key_rejected",detail:`HTTP ${e.status}`}}catch(e){return{url:r,ok:!1,ms:Date.now()-i,...f(e)}}finally{clearTimeout(a)}}
@@ -0,0 +1 @@
1
+ import{chmodSync as t,copyFileSync as e,existsSync as r,mkdirSync as n,readFileSync as o,rmSync as s,statSync as i,writeFileSync as a}from"fs";import{join as c}from"path";import{brandEnv as l}from"./brand.js";import{configManager as u}from"./config.js";import{logger as f}from"../utils/logger.js";import{maskSecrets as p}from"./telemetry.js";export function parseTrace(t){const e=[];for(const r of t.split(/\r?\n/)){const t=/^(\d{10,})\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(r.trim());t&&e.push({at:Number(t[1]),step:t[2],status:t[3],detail:(t[4]??"").trim()})}return e.slice(-200)}export function lastStep(t){const e=t[t.length-1];if(e&&"end"!==e.step)return`${e.step} ${e.status}`}export function placedPath(t){for(let e=t.length-1;e>=0;e--){const r=t[e];if(("place"===r.step||"end"===r.step)&&"ok"===r.status&&r.detail)return r.detail}}export function traceSummary(t){if(0===t.length)return{};const e=[...t].reverse().find(t=>"fail"===t.status),r=lastStep(t);return{trace_steps:t.length,...r?{last_step:r}:{},...e?{failed_step:e.step,failed_reason:e.detail.slice(0,300)}:{}}}export function diagnoseMissing(t,e){const n=placedPath(t);if(n)return r(n)?{reason:"not_on_path",path:n}:{reason:"removed_after_install",path:n};const o=e.find(t=>r(t));return o?{reason:"not_on_path",path:o}:0===t.length?{reason:"not_found"}:t.some(t=>"download"===t.step&&"ok"===t.status)?{reason:"removed_after_install",path:e[0]}:{reason:"not_downloaded"}}const m=()=>c(u.getConfigDir(),"install-traces");export function savedTraces(){const t={};try{const e=m();if(!r(e))return t;for(const n of["claude","codex","grok","agy","node","git","uv"]){const s=c(e,`${n}.log`);r(s)&&(t[n]=p(o(s,"utf-8")).split(/\r?\n/).filter(Boolean).slice(-40))}}catch(t){f.logError("install-script: traces",t)}return t}const d=async t=>{const e=await fetch(t,{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.text()};let h=d;export function setScriptFetcherForTests(t){h=t??d}const g=/PSSecurityException|UnauthorizedAccess|execution polic|AuthorizationManager|running scripts is disabled|禁止运行脚本|执行策略/i;export async function runInstallScript(p){const w=p.platform??process.platform,x=p.limits??{},y=async(t,e=[])=>{const[r,n]=function(t,e){return"win32"===t?["powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${e} -TimeoutSec 30 | iex`]]:["sh",["-c",'script=$(curl -fsSL --connect-timeout 15 --max-time 60 "$0") && printf \'%s\\n\' "$script" | sh',e]]}(w,p.url);return{outcome:await p.run(r,n,x),how:"inline",fileProblem:t,trace:e}};if("1"===l("SCRIPT_INLINE")&&h===d)return y(void 0);const $=c(u.getConfigDir(),"install-scripts"),_=`${p.name}-${process.pid}`,v=c($,`${_}.${"win32"===w?"ps1":"sh"}`),S=c($,`${_}.trace`);try{const t=await h(p.url);if(!function(t){return t.trim().length>40&&!/^\s*<(!doctype|html)/i.test(t)}(t))return y("download");n($,{recursive:!0,mode:448});const e="win32"===w&&/[^\x00-\x7f]/.test(t)&&!t.startsWith("\ufeff");a(v,(e?"\ufeff":"")+t,{mode:448}),s(S,{force:!0})}catch(t){return f.logError(`install-script: save ${p.name}`,t),y("download")}try{if(!r(v))return await y("removed");const s={...x.env,INSTALL_TRACE:S},a="win32"===w?await p.run("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-File",v],{...x,env:s}):await p.run("sh",[v],{...x,env:s}),l=function(t){try{return!r(t)||i(t).size>262144?[]:parseTrace(o(t,"utf-8"))}catch{return[]}}(S);if("fail"===a&&0===l.length){if(!r(v))return await y("removed");if("win32"===w&&g.test(p.output?.()??""))return await y("policy")}return function(o,s){try{if(!r(s))return;const i=m();n(i,{recursive:!0,mode:448});const a=c(i,`${o}.log`);e(s,a),t(a,384)}catch(t){f.logError(`install-script: keep trace ${o}`,t)}}(p.name,S),{outcome:a,how:"file",trace:l}}finally{s(v,{force:!0}),s(S,{force:!0})}}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as r,writeFileSync as t}from"fs";import{dirname as n,join as s}from"path";import i from"chalk";import{configManager as l}from"./config.js";import{i18n as f}from"./i18n.js";import{resolveModelCatalog as d}from"./model-catalog.js";import{listAdapters as c}from"./tools/registry.js";import{UserActionNeeded as a}from"./tools/types.js";import{logger as u}from"../utils/logger.js";import{resolveUpdateCachePath as m}from"./auto-update.js";import{isHelpRequest as h}from"./cli-help.js";import{brandEnvName as p}from"./brand.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;const g=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),M=["--json","--dry-run","--help","-h","--version","-v"],y=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[p("DISABLE_MODEL_REFRESH")])return!0;if(M.some(o=>e.includes(o))||h(e))return!0;const r=e.find(e=>!e.startsWith("-"));return void 0!==r&&g.has(r)}let j={checked:0,failed:0};export function lastModelRefreshOutcome(){return{...j}}export async function refreshModelMenus(){const e=new Map,o=[];y.length=0,j={checked:0,failed:0};for(const r of c())if(r.refreshModelMenu&&r.listedModels)try{const t=l.getApiKeyForTool(r.name);if(!t||r.detectCurrentConfig().apiKey!==t)continue;const n=r.listedModels();if(null===n)continue;e.has(t)||e.set(t,await d(t));const s=e.get(t);if(!s)continue;r.refreshModelMenu({apiKey:t,baseUrl:l.getBaseUrl(),models:l.getModelsForTool(r.name),settings:l.getToolSettings(r.name),catalog:s}),j.checked++;const i=r.listedModels()??[],f=i.filter(e=>!n.includes(e)),c=n.filter(e=>!i.includes(e));(f.length>0||c.length>0)&&o.push({tool:r.displayName,added:f,removed:c})}catch(e){j.failed++,u.logError(`modelRefresh(${r.name})`,e),e instanceof a&&y.push(e.message)}return o}export async function runModelRefresh(l,d={}){const c=d.env??process.env,a=d.now??Date.now(),h=function(e){return s(n(m(e)),"model-refresh.json")}(c);if(!d.force){if(shouldSkipModelRefresh(l,c))return[];if(a-function(e){try{const o=JSON.parse(r(e,"utf-8")).refreshed_at;return"number"==typeof o?o:0}catch{return 0}}(h)<36e5)return[]}let p=[];try{p=await refreshModelMenus(),e(n(h))||o(n(h),{recursive:!0}),t(h,JSON.stringify({refreshed_at:a})+"\n")}catch(e){u.logError("runModelRefresh",e)}const g=d.output??(e=>console.log(i.gray(e)));for(const e of y)g(e);for(const e of p){const o=[e.added.length>0?f.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?f.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);g(f.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return p}
1
+ import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import r from"chalk";import{configManager as n}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as i}from"./model-catalog.js";import{listAdapters as l}from"./tools/registry.js";import{UserActionNeeded as f}from"./tools/types.js";import{logger as d}from"../utils/logger.js";import{resolveUpdateCachePath as c}from"./auto-update.js";import{isHelpRequest as a}from"./cli-help.js";import{brandEnvName as m}from"./brand.js";import{atomicWriteFile as u}from"./tools/backup.js";import{track as p}from"./telemetry.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const h=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),g=["--json","--dry-run","--help","-h","--version","-v"],M=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[m("DISABLE_MODEL_REFRESH")])return!0;if(g.some(o=>e.includes(o))||a(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&h.has(t)}let y={checked:0,failed:0,offline:0};export function lastModelRefreshOutcome(){return{...y}}export async function refreshModelMenus(){const e=new Map,o=[];M.length=0,y={checked:0,failed:0,offline:0};for(const t of l())if(t.refreshModelMenu&&t.listedModels)try{const r=n.getApiKeyForTool(t.name);if(!r||t.detectCurrentConfig().apiKey!==r)continue;const s=t.listedModels();if(null===s)continue;e.has(r)||e.set(r,await i(r));const l=e.get(r);if(!l){y.offline++;continue}t.refreshModelMenu({apiKey:r,baseUrl:n.getBaseUrl(),models:n.getModelsForTool(t.name),settings:n.getToolSettings(t.name),catalog:l}),y.checked++;const f=t.listedModels()??[],d=f.filter(e=>!s.includes(e)),c=s.filter(e=>!f.includes(e));(d.length>0||c.length>0)&&o.push({tool:t.displayName,added:d,removed:c})}catch(e){y.failed++,d.logError(`modelRefresh(${t.name})`,e),p(`menu-sync:${t.name}`,e instanceof f?"skip":"fail",{error:e}),e instanceof f&&M.push(e.message)}return o}export async function runModelRefresh(n,i={}){const l=i.env??process.env,f=i.now??Date.now(),a=function(e){return t(o(c(e)),"model-refresh.json")}(l);if(!i.force){if(shouldSkipModelRefresh(n,l))return[];if(f-function(o){try{const t=JSON.parse(e(o,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(a)<36e5)return[]}let m=[];try{m=await refreshModelMenus();const e=y.offline>0&&0===y.checked&&0===y.failed,o=e?f-36e5+6e5:f;e&&p("menu-sync","skip",{detail:{reason:"offline",tools:y.offline}}),u(a,JSON.stringify({refreshed_at:o})+"\n")}catch(e){d.logError("runModelRefresh",e)}const h=i.output??(e=>console.log(r.gray(e)));for(const e of M)h(e);for(const e of m){const o=[e.added.length>0?s.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?s.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);h(s.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return m}
@@ -1 +1 @@
1
- import{chmodSync as t,existsSync as n,readFileSync as o,realpathSync as r,unlinkSync as e}from"fs";import{join as s}from"path";import{logger as i}from"../utils/logger.js";import{getShellRcFilePath as c}from"./env-cleanup.js";import{broadcastEnvChange as f,deleteWindowsEnv as u,readWindowsEnv as p,setUserEnv as l}from"./windows-env.js";import{atomicWriteFile as m,backupBeforeWrite as a}from"./tools/backup.js";import{toolHome as $}from"./tools/types.js";import{CLI_NAME as d}from"./brand.js";const h=t=>`# ${d}:${t}`;function v(){const t=$(),o=new Set,r=c();r&&o.add(r);for(const r of[".zshrc",".bashrc"]){const e=s(t,r);n(e)&&o.add(e)}return[...o]}function j(t,n,o){const r=`"${function(t){const n=$();return t.startsWith(n+"/")?`$HOME/${t.slice(n.length+1)}`:t}(n)}"`;return t.endsWith(".fish")?`test -f ${r}; and source ${r} ${h(o)}`:`[ -f ${r} ] && . ${r} ${h(o)}`}function w(t,o){const e=n(t)?r(t):t;a(e),m(e,o)}function E(t,n){return t.split("\n").filter(t=>!t.trimEnd().endsWith(h(n))).join("\n")}function b(t,n){if(/['\r\n]/.test(n))throw new Error(`${t} contains a quote or newline and cannot be written to a shell env file`)}export function writePersistentEnv(r,e,s){for(const[t,n]of Object.entries(s))b(t,n);const i=Object.entries(s).map(([t,n])=>`export ${t}='${n}'`).join("\n");a(e),m(e,`# Written by ${d}. Loaded from your shell profile.\n${i}\n`,384),t(e,384);for(const[t,n]of Object.entries(s))process.env[t]=n;if("win32"===process.platform){for(const[t,n]of Object.entries(s))l(t,n);return f(),{rcFiles:[]}}const c=[];for(const t of v()){const s=n(t)?o(t,"utf-8"):"",i=j(t,e,r);if(s.split("\n").some(t=>t.trimEnd()===i)){c.push(t);continue}const f=E(s,r).replace(/\n*$/,"");w(t,`${f?f+"\n\n":""}${i}\n`),c.push(t)}return{rcFiles:c}}export function removePersistentEnv(t,r,s){const c=readPersistentEnvFile(r);if(n(r)&&(a(r),e(r)),"win32"===process.platform){let t=!1;for(const n of s)if(void 0!==c[n]&&p("user",n)===c[n])try{u("user",n),t=!0}catch(t){i.logError("persistentEnv.remove",t)}return void(t&&f())}for(const r of v()){if(!n(r))continue;const e=o(r,"utf-8"),s=E(e,t);s!==e&&w(r,s)}}export function readPersistentEnvFile(t){const r={};if(!n(t))return r;for(const n of o(t,"utf-8").split("\n")){const t=n.match(/^export ([A-Z_][A-Z0-9_]*)='([^']*)'$/);t&&(r[t[1]]=t[2])}return r}
1
+ import{chmodSync as t,existsSync as n,readFileSync as o,realpathSync as r,unlinkSync as e}from"fs";import{join as s}from"path";import{logger as i}from"../utils/logger.js";import{getShellRcFilePath as c}from"./env-cleanup.js";import{broadcastEnvChange as f,deleteWindowsEnv as u,readWindowsEnv as p,setUserEnv as l}from"./windows-env.js";import{atomicWriteFile as m,backupBeforeWrite as a}from"./tools/backup.js";import{toolHome as $}from"./tools/types.js";import{CLI_NAME as d}from"./brand.js";const h=t=>`# ${d}:${t}`;function j(){const t=$(),o=new Set,r=c();r&&o.add(r);for(const r of[".zshrc",".bashrc"]){const e=s(t,r);n(e)&&o.add(e)}return[...o]}function v(t,n,o){const r=`"${function(t){const n=$();return t.startsWith(n+"/")?`$HOME/${t.slice(n.length+1)}`:t}(n)}"`;return t.endsWith(".fish")?`test -f ${r}; and source ${r} ${h(o)}`:`[ -f ${r} ] && . ${r} ${h(o)}`}function w(t,o){const e=n(t)?r(t):t;a(e),m(e,o)}function E(t,n){return t.split("\n").filter(t=>!t.trimEnd().endsWith(h(n))).join("\n")}function b(t,n){if(/['\r\n]/.test(n))throw new Error(`${t} contains a quote or newline and cannot be written to a shell env file`)}export function writePersistentEnv(r,e,s){for(const[t,n]of Object.entries(s))b(t,n);const i=Object.entries(s).map(([t,n])=>`export ${t}='${n}'`).join("\n");a(e),m(e,`# Written by ${d}. Loaded from your shell profile.\n${i}\n`,384),t(e,384);for(const[t,n]of Object.entries(s))process.env[t]=n;if("win32"===process.platform){for(const[t,n]of Object.entries(s))l(t,n);return f(),{rcFiles:[]}}const c=[];for(const t of j()){const s=n(t)?o(t,"utf-8"):"",i=v(t,e,r);if(s.split("\n").some(t=>t.trimEnd()===i)){c.push(t);continue}const f=E(s,r).replace(/\n*$/,"");w(t,`${f?f+"\n\n":""}${i}\n`),c.push(t)}return{rcFiles:c}}export function removePersistentEnv(t,r,s){const c=readPersistentEnvFile(r);let l=!1;if("win32"===process.platform){let t=!1;for(const n of s)if(void 0!==c[n]&&p("user",n)===c[n])try{u("user",n),t=!0}catch(t){l=!0,i.logError("persistentEnv.remove",t)}t&&f()}else for(const r of j()){if(!n(r))continue;const e=o(r,"utf-8"),s=E(e,t);s!==e&&w(r,s)}!l&&n(r)&&(a(r),e(r))}export function readPersistentEnvFile(t){const r={};if(!n(t))return r;for(const n of o(t,"utf-8").split("\n")){const t=n.match(/^export ([A-Z_][A-Z0-9_]*)='([^']*)'$/);t&&(r[t[1]]=t[2])}return r}
@@ -1 +1 @@
1
- import o from"chalk";import t from"inquirer";import{i18n as n}from"./i18n.js";import{canPrompt as e,hasExplicitYes as r,shouldAutoConfirm as i}from"./runtime-options.js";import{toolManager as s}from"./tool-manager.js";import{getAdapter as a}from"./tools/registry.js";import{upgradeTool as l}from"./tool-upgrade.js";import{appsForTools as p,upgradeApp as c}from"./app-update.js";import{logger as f}from"../utils/logger.js";async function u(o){const{ok:n}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return n}export async function runPendingElevations(t){const r=e();for(const e of t){const t=a(e)?.pendingElevation?.();if(!t)continue;if(!(i()||r&&await u(t.prompt)))continue;const s=a(e)?.displayName??e;console.log(o.gray(" "+n.t("setup.elevation_running"))),console.log(t.run()?o.green(" √ "+n.t("setup.elevation_done",{tool:s})):o.yellow(" ! "+n.t("setup.elevation_failed",{tool:s})))}}export async function runFollowUps(t){const n=e();for(const e of t){let t;try{t=await(a(e)?.followUp?.())}catch(o){f.logError(`postApplyPrompts.followUp(${e})`,o);continue}if(t)if("run"in t&&(r()||n))if(r()||await u(t.prompt))for(const n of await t.run())console.log("action"===n.kind?o.yellow(" ! "+n.text):o.green(" √ "+n.text));else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,i={}){const m=new Set;for(const o of i.apps?p(t):[])try{const t=await c(o,{install:i.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&m.add(o)}catch(t){f.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const n of t){const t=await(a(n)?.prepareRuntime?.())??[];for(const n of t)console.log("action"===n.kind?o.yellow(" ! "+n.text):o.green(" √ "+n.text))}await runPendingElevations(t),await runFollowUps(t);const g=e(),d=r(),y=g||d?t.filter(o=>a(o)?.installSpec&&s.outdatedVersion(o)):[];if(y.length>0){const o=y.map(o=>a(o)?.displayName??o).join("、");if(d||await u(n.t("setup.offer_upgrade",{tools:o})))for(const o of y)await l(o)}for(const e of t){const t=a(e);if(m.has(e)||!t?.runningApp?.isRunning())continue;if(d||!g){console.log(o.yellow(" ! "+n.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await u(n.t("setup.offer_restart",{tool:t.displayName})))continue;const r=t.runningApp.restart();console.log(r?o.green(" √ "+n.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+n.t("setup.restart_failed",{tool:t.displayName})))}}
1
+ import o from"chalk";import t from"inquirer";import{i18n as e}from"./i18n.js";import{canPrompt as n,hasExplicitYes as r}from"./runtime-options.js";import{flushTelemetry as l,track as i}from"./telemetry.js";import{toolManager as a}from"./tool-manager.js";import{getAdapter as s}from"./tools/registry.js";import{upgradeTool as p}from"./tool-upgrade.js";import{appsForTools as c,upgradeApp as f}from"./app-update.js";import{logger as u}from"../utils/logger.js";async function m(o){const{ok:e}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return e}export async function runPendingElevations(t){const a=n(),p=r();for(const n of t){const t=s(n)?.pendingElevation?.();if(!t)continue;const r=s(n)?.displayName??n;if(!p&&!a){console.log(o.yellow(" ! "+e.t("setup.elevation_skipped",{tool:r}))),i("elevate-registry","skip",{detail:{tool:n,reason:"no_terminal"}});continue}if(!p&&!await m(t.prompt)){i("elevate-registry","cancel",{detail:{tool:n,reason:"declined"}});continue}console.log(o.gray(" "+e.t("setup.elevation_running")));const c=Date.now();i("elevate-registry","start",{detail:{tool:n,asked:!p}}),await l();const f=t.run();i("elevate-registry",f?"ok":"fail",{duration_ms:Date.now()-c,detail:{tool:n,asked:!p}}),console.log(f?o.green(" √ "+e.t("setup.elevation_done",{tool:r})):o.yellow(" ! "+e.t("setup.elevation_failed",{tool:r})))}}export async function runFollowUps(t){const e=n();for(const n of t){let t,l;try{t=await(s(n)?.followUp?.())}catch(o){u.logError(`postApplyPrompts.followUp(${n})`,o);continue}if(t)if("run"in t&&(r()||e))if(r()||await m(t.prompt)){try{l=await t.run()}catch(e){u.logError(`postApplyPrompts.followUp.run(${n})`,e),i(`follow-up:${n}`,"fail",{error:e}),console.log(o.yellow(" ! "+t.hint));continue}for(const t of l)console.log("action"===t.kind?o.yellow(" ! "+t.text):o.green(" √ "+t.text))}else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,l={}){const i=new Set;for(const o of l.apps?c(t):[])try{const t=await f(o,{install:l.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&i.add(o)}catch(t){u.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const e of t){const t=await(s(e)?.prepareRuntime?.())??[];for(const e of t)console.log("action"===e.kind?o.yellow(" ! "+e.text):o.green(" √ "+e.text))}await runPendingElevations(t),await runFollowUps(t);const g=n(),d=r(),y=g||d?t.filter(o=>s(o)?.installSpec&&a.outdatedVersion(o)):[];if(y.length>0){const o=y.map(o=>s(o)?.displayName??o).join("、");if(d||await m(e.t("setup.offer_upgrade",{tools:o})))for(const o of y)await p(o)}for(const n of t){const t=s(n);if(i.has(n)||!t?.runningApp?.isRunning())continue;if(d||!g){console.log(o.yellow(" ! "+e.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await m(e.t("setup.offer_restart",{tool:t.displayName})))continue;const r=t.runningApp.restart();console.log(r?o.green(" √ "+e.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+e.t("setup.restart_failed",{tool:t.displayName})))}}
@@ -0,0 +1 @@
1
+ import{commandInProgress as t,reportSignal as e}from"./telemetry.js";const n={SIGHUP:129,SIGINT:130,SIGBREAK:149,SIGTERM:143};let o=!1,r=0,s=!1;export function handTerminalOver(t){o=!0;try{return t()}finally{o=!1,r=Date.now()+500}}export function endedByInterrupt(t){return"SIGINT"===t.signal||130===t.status||3221225786===t.status}export async function handleSignal(t,i=t=>process.exit(t)){const a=n[t]??1;if("SIGINT"!==t||!(o||Date.now()<r))if(s)i(a);else{s=!0,process.exitCode=a;try{await e(t,a)}finally{i(a)}}}export function resetSignalStateForTests(){o=!1,r=0,s=!1}export function installSignalHandlers(){if(process.env.VITEST)return;const e=["SIGINT","SIGTERM","SIGHUP",..."win32"===process.platform?["SIGBREAK"]:[]];for(const t of e)try{process.on(t,()=>{handleSignal(t)})}catch{}process.once("beforeExit",()=>{t()&&setTimeout(()=>{},20)})}
@@ -0,0 +1 @@
1
+ import{spawnSync as e}from"child_process";import{accessSync as t,constants as r,existsSync as o,readdirSync as n,readFileSync as s,statSync as i}from"fs";import{delimiter as c,dirname as l,join as a}from"path";import{CLI_NAME as p}from"./brand.js";import{configManager as u}from"./config.js";import{savedTraces as m}from"./install-script.js";import{powerShellEnv as d}from"./powershell-env.js";import{maskSecrets as f}from"./telemetry.js";import{windowsSecurityProducts as h}from"./windows-security.js";function $(e){try{return e()}catch(e){return{error:f(e instanceof Error?e.message:String(e)).slice(0,200)}}}function g(e){const t="win32"===process.platform?["",".exe",".cmd",".bat"]:[""];for(const r of(process.env.PATH??process.env.Path??"").split(c))if(r)for(const o of t){const t=a(r.replace(/^"|"$/g,""),e+o);try{if(i(t).isFile())return t}catch{}}return null}function w(t,r){const o=e(t,r,{encoding:"utf-8",timeout:8e3,windowsHide:!0,shell:"win32"===process.platform&&!/\.exe$/i.test(t),.../powershell(\.exe)?$/i.test(t)?{env:d()}:{}});return String(o.stdout??"").trim()}function y(e){let n=e;for(;n&&!o(n);){const e=l(n);if(e===n)return!1;n=e}try{return t(n,r.W_OK),!0}catch{return!1}}function x(){const e=g("npm"),t=e&&w(e,["prefix","-g"]).split(/\r?\n/).pop()?.trim()||null;return{node:f(process.execPath),node_on_path:f(g("node")??""),version:process.version,npm:e?f(e):null,npm_prefix:t?f(t):null,npm_prefix_writable:t?y(t):null}}function v(){const e="win32"===process.platform?["powershell","pwsh","cmd","bash","git","curl"]:["sh","bash","zsh","fish","git","curl"];return Object.fromEntries(e.map(e=>[e,g(e)?f(g(e)):null]))}function _(){const e=u.getConfigDir(),t=(t,r)=>{const n=a(e,t);return o(n)?f(s(n,"utf-8")).split(/\r?\n/).filter(Boolean).slice(-r):null},r=t=>{const r=a(e,t);return o(r)?n(r).slice(0,30).map(e=>{const t=i(a(r,e));return`${e} ${t.isDirectory()?"dir":t.size}`}):null};return{progress:t("install-progress.txt",60),avoid:t("install-avoid.txt",20),traces:m(),self_update:t("update-state.json",20),node_migration:o(a(e,"node-migration.json")),downloads:r("downloads"),install_scripts:r("install-scripts")}}function E(){const e=w("powershell.exe",["-NoProfile","-NonInteractive","-Command",["[Console]::OutputEncoding = [Text.Encoding]::UTF8","$out = @{}",'try { $d = Get-MpComputerStatus -ErrorAction Stop; $out.defender = @{ mode = "$($d.AMRunningMode)"; realtime = [bool]$d.RealTimeProtectionEnabled } } catch { $out.defender = $null }',"try { $out.elevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch {}",'try { $out.execution_policy = @(Get-ExecutionPolicy -List | ForEach-Object { "$($_.Scope)=$($_.ExecutionPolicy)" }) } catch {}',`$out.crashes = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = @('Application Error', 'Windows Error Reporting', '.NET Runtime'); StartTime = (Get-Date).AddDays(-2) } -MaxEvents 200 -ErrorAction SilentlyContinue | Where-Object { "$($_.Message)" -match 'powershell|pwsh|node\\.exe|npm|git|bash\\.exe|cmd\\.exe|conhost|fnm|claude|codex|grok|agy|${p}' } | Select-Object -First 8 | ForEach-Object { $m = ("$($_.Message)" -replace '\\s+', ' '); "$($_.TimeCreated.ToUniversalTime().ToString('s'))Z $($_.ProviderName) $($_.Id): " + $m.Substring(0, [Math]::Min(220, $m.Length)) })`,"$out | ConvertTo-Json -Depth 4 -Compress"].join("; ")]),t=JSON.parse(e||"{}");return Array.isArray(t.crashes)&&(t.crashes=t.crashes.map(e=>f(String(e)))),t}export function systemReport(){return{platform:`${process.platform} ${process.arch}`,security:$(()=>h()),path:$(()=>(process.env.PATH??process.env.Path??"").split(c).filter(Boolean).slice(0,80).map(e=>f(e))),node:$(x),shells:$(v),installer:$(_),..."win32"===process.platform?{windows:$(E)}:{}}}
@@ -1 +1 @@
1
- import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as o}from"os";import{format as n,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as u}from"./client-config.js";import{configManager as p}from"./config.js";import{gatewayAddresses as f}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as d,REPORT_PATH as m,TELEMETRY_PATH as h}from"./gateway-protocol.js";const g=e();let y="wizard",w=[];const T=new Set;let k=null,x=E;export function telemetryEnabled(){if(process.env.VITEST&&!$)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let S,$=!1;export function setTelemetrySenderForTests(e){x=e??E,$=null!==e,w=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${o()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[d]:u()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const o=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([p.getBaseUrl(),...f().map(e=>e.url)].map(e=>new URL(e).host)).has(o.host)){const o=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))o.has(e)||o.set(e,t);return e(t,{...r,headers:o})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return T.size>0}function _(){return{install_id:u(),cli_version:l(),brand:a().id,os:process.platform,os_release:o(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const o=new Set([t,t.replace(/\\/g,"/")]);let n=e;for(const e of o)n=n.split(e).join("~");return n}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}let b=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(S=t)}export function lastFailureReason(){return S}export function watchConsoleErrors(){if(b)return;b=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(n(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}export function track(e,t,r={}){if(!telemetryEnabled())return;const o=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:g,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...o?{error:o}:{},...r.detail?{detail:r.detail}:{}}),"start"===t?z():k||(k=setTimeout(z,500),k.unref())}export async function trackStep(e,t,r){const o=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-o}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-o,error:t}),t}}function z(){if(k&&(clearTimeout(k),k=null),0===w.length)return;const e=w.splice(0,50),t=x(h,{..._(),events:e},3e3).then(()=>{},()=>{}).finally(()=>T.delete(t));T.add(t),w.length>0&&z()}export async function flushTelemetry(e=1500){z(),0!==T.size&&await Promise.race([Promise.allSettled([...T]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export async function uploadReport(e){try{const t=await x(m,{..._(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function E(e,t,r){const o=p.getApiKey()?.trim(),n=await fetch(new URL(e,p.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json().catch(()=>null)}
1
+ import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as o}from"os";import{format as n,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as u}from"./client-config.js";import{configManager as m}from"./config.js";import{gatewayAddresses as p}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as d,REPORT_PATH as f,TELEMETRY_PATH as g}from"./gateway-protocol.js";const h=e();let y="wizard",w=[];const x=new Set;let T=null,k=H;export function telemetryEnabled(){if(process.env.VITEST&&!_)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let S,_=!1;export function setTelemetrySenderForTests(e){k=e??H,_=null!==e,w=[],z=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${o()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[d]:u()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const o=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([m.getBaseUrl(),...p().map(e=>e.url)].map(e=>new URL(e).host)).has(o.host)){const o=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))o.has(e)||o.set(e,t);return e(t,{...r,headers:o})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return x.size>0}function $(){return{install_id:u(),cli_version:l(),brand:a().id,os:process.platform,os_release:o(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const o=new Set([t,t.replace(/\\/g,"/")]);let n=e;for(const e of o)n=n.split(e).join("~");return n}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}let b=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(S=t)}export function lastFailureReason(){return S}export function watchConsoleErrors(){if(b)return;b=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(n(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}let z=[],E=0;export function track(e,t,r={}){if("start"===t)z.push(e),"command"===e&&(E=Date.now());else{const t=z.lastIndexOf(e);t>=0&&z.splice(t,1)}if(!telemetryEnabled())return;const o=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:h,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...o?{error:o}:{},...r.detail?{detail:r.detail}:{}}),"start"===t?v():T||(T=setTimeout(v,500),T.unref())}export async function trackStep(e,t,r){const o=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-o}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-o,error:t}),t}}function v(){if(T&&(clearTimeout(T),T=null),0===w.length)return;const e=w.splice(0,50),t=k(g,{...$(),events:e},3e3).then(()=>{},()=>{}).finally(()=>x.delete(t));x.add(t),w.length>0&&v()}export async function flushTelemetry(e=1500){v(),0!==x.size&&await Promise.race([Promise.allSettled([...x]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export function commandInProgress(){return z.includes("command")}export async function reportSignal(e,t,r=1500){if(commandInProgress()){const r=z.filter(e=>"command"!==e).pop();track("command","cancel",{duration_ms:Date.now()-E,detail:{signal:e,exit_code:t,...r?{during:r}:{}}})}await flushTelemetry(r)}export async function uploadReport(e){try{const t=await k(f,{...$(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function H(e,t,r){const o=m.getApiKey()?.trim(),n=await fetch(new URL(e,m.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json().catch(()=>null)}
@@ -1 +1 @@
1
- import{execSync as o,spawnSync as t}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as g}from"./tools/backup.js";import{existsSync as h,rmSync as w}from"fs";import{dirname as y,join as P}from"path";import{toolHome as $}from"./tools/types.js";import{stringWidth as v}from"../utils/string-width.js";import{resolveModelCatalog as k}from"./model-catalog.js";import{compareVersions as T,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{failureContext as M,lastCommandExit as U,lastCommandOutput as b,mirrorInstall as x}from"./tool-upgrade.js";import{upgradeApp as I}from"./app-update.js";import{CLI_NAME as R}from"./brand.js";import{track as F,trackStep as L}from"./telemetry.js";import{addUserPathDir as V,broadcastEnvChange as D}from"./windows-env.js";export{T as compareVersions};function z(o){const t=u[o];return{name:t.name,command:t.command,installCommand:t.installCommand,configPath:t.configPath,displayName:t.displayName,...t.hidden?{hidden:!0}:{},...t.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(o=>[o,z(o)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(o){if(!SUPPORTED_TOOLS[o])return!1;const t=d(o);if(t?.isInstalled)try{return t.isInstalled()}catch{return!1}return this.isOnPath(o)||null!==this.nativeLauncher(o)}isOnPath(t){const n=SUPPORTED_TOOLS[t];if(!n)return!1;try{const t="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return o(t,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(o){const t=d(o),n=t?.installSpec?.native?.binDir;if(!t||!n)return null;const e="win32"===process.platform?`${t.command}.exe`:t.command,r=P($(),...n,e);return h(r)?r:null}ensureNativeOnPath(o){if("win32"!==process.platform||this.isOnPath(o))return null;const t=this.nativeLauncher(o);if(!t)return null;const n=y(t);try{if(!V(n))return null}catch(t){return a.logError(`ensureNativeOnPath: ${o}`,t),null}return D(),process.env.Path=`${process.env.Path??""};${n}`,n}async installTool(o){return L(`install:${o}`,()=>this.installToolNow(o))}async installToolNow(t){const a=SUPPORTED_TOOLS[t];if(!a)throw new Error(`Unknown tool: ${t}`);const s=d(t)?.appInstaller;if(s&&!s.blocker()){const o=await I(t,{install:!0});if("failed"===o.result||"unavailable"===o.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(t)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const o=S(c);if(await x(c)){if(O(),this.isToolInstalled(t))return void console.log(r.green("√ "+n.t("wizard.tool_installed")));F(`install-script:${c.command}`,"fail",{error:b()||"(no output)",detail:{reason:"not_found_after_ok",...U(),...M()}})}throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:o}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return o(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(o){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${o?.message??""}${o?.stderr??""}`)&&243!==o?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${o}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(t))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);try{return t.getConfig()}catch(t){return a.warn(`Failed to read config for ${o}:`,t),a.logError(`ToolManager.getToolConfig(${o})`,t),null}}updateToolConfig(o,t){const n=d(o);if(!n)throw new Error(`Unknown tool: ${o}`);if(!n.updateConfig)throw new Error(`Tool ${o} does not support raw config updates`);n.updateConfig(t)}forceResetConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);const n=t.forceResetPaths?t.forceResetPaths():this.backupPathsFor(t),e=[];for(const o of n)h(o)&&(m(o),w(o,{force:!0}),e.push(o));return e}loadPrivateConfig(o,t,n,e,r={}){const i=d(o);if(!i)throw new Error(`Unknown tool: ${o}`);r.force&&this.forceResetConfig(o),i.loadPrivateConfig({apiKey:t,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(o),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(o,t,n,e={}){const r=this.installedVersion(o);return L(`apply:${o}`,()=>this.applyPrivateConfigNow(o,t,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(o,t,n,e){const r=d(o);if(!r)throw new Error(`Unknown tool: ${o}`);const i=r.wantsModelCatalog?await k(t):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(o,t,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(o,t,n,i):this.loadPrivateConfig(o,t,n)}applyNotes(o){const t=d(o);if(!t)return[];const e=[];try{t.applyNotes&&e.push(...t.applyNotes())}catch(t){a.logError(`ToolManager.applyNotes(${o})`,t)}const r=this.outdatedVersion(o);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:t.installSpec?`${R} upgrade ${o}`:t.upgradeCommand||t.installCommand})});for(const o of t.upgradeHints?.(r.min)??[])e.push({kind:"action",text:o})}const i=t.installSpec?E(t.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:o})}),e}printApplied(o,t=16){const n=SUPPORTED_TOOLS[o]?.displayName??o,e=this.applyNotes(o);for(const o of e.filter(o=>"detail"===o.kind))a.record(`${n}: ${o.text}`);const i=e.filter(o=>"summary"===o.kind).map(o=>o.text).join(";"),l=" ".repeat(Math.max(1,t-v(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const o of e.filter(o=>"action"===o.kind))console.log(r.yellow(" ! "+o.text))}installedVersion(o){const n=d(o);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(t){return a.logError(`ToolManager.installedVersion(${o})`,t),null}if(n.isInstalled)return null;try{const o={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?t(`${n.command} --version`,{...o,shell:!0}):t(n.command,["--version"],o)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(o){const t=C(o);if(!t)return null;const n=this.installedVersion(o);return n&&T(n,t)<0?{current:n,min:t}:null}unloadPrivateConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);try{t.unloadPrivateConfig({savedKeys:c()}),F(`remove:${o}`,"ok")}catch(t){throw F(`remove:${o}`,"fail",{error:t}),t}let e=[];try{e=t.unloadNotes?.()??[]}catch(t){a.logError(`ToolManager.unloadNotes(${o})`,t)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:t.displayName})}]}async clearPinnedModels(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);if(s.setToolModel(o,null),!t.clearPinnedModels)return[];const n=s.getApiKeyForTool(o),e=t.wantsModelCatalog&&n?await k(n):null;return t.clearPinnedModels(e??void 0)}supportsClearPinnedModels(o){return Boolean(d(o)?.clearPinnedModels)}holdsOurConfig(o){const t=d(o);if(!t)return!1;const n=c();return t.holdsOurConfig?t.holdsOurConfig(n):Boolean(t.detectCurrentConfig().apiKey)}detectCurrentConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return t.detectCurrentConfig()}backupPathsFor(o){return o.backupPaths?o.backupPaths():[o.configPath]}listToolBackups(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return this.backupPathsFor(t).map(o=>({file:o,backups:f(o)}))}restorePrivateConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return this.backupPathsFor(t).map(o=>({file:o,result:g(o)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(o=>this.isToolInstalled(o))}getSupportedTools(){return p().filter(o=>!o.hidden).map(o=>z(o.name))}isGitInstalled(){try{const t="win32"===process.platform?"where git":"which git";return o(t,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
1
+ import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as k,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{k as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=S(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=C(t);if(!o)return null;const n=this.installedVersion(t);return n&&k(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
@@ -1 +1 @@
1
- import{spawn as t,spawnSync as e}from"child_process";import{rmSync as o}from"fs";import{join as r}from"path";import n from"chalk";import i from"inquirer";import{i18n as s}from"./i18n.js";import{logger as a}from"../utils/logger.js";import{compareVersions as l,getToolMinVersion as c}from"./model-registry.js";import{getAdapter as p}from"./tools/registry.js";import{findInstalls as u,findInstallsIncludingNative as m,forgetInstalls as d,installLabel as g,npmMirrorInstallCommand as f,npmMirrorVersion as w,npmUninstallCommand as h}from"./tools/tool-installs.js";import{toolHome as y}from"./tools/types.js";import{isJsonMode as v,isNonInteractive as _,shouldAutoConfirm as k}from"./runtime-options.js";import{maskSecrets as x,track as b}from"./telemetry.js";import{windowsSecurityProducts as $}from"./windows-security.js";import{isWindowsPowerShell as j,powerShellEnv as T}from"./powershell-env.js";let E="ok",C={};export function lastCommandExit(){return C}let M="";const S=t=>{M=(M+t.toString("utf-8")).slice(-3e3)};export function outputTail(t){return t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").split(/\r?\n/).map(t=>t.split("\r").pop().trimEnd()).filter(Boolean).join("\n").slice(-1500)}export function lastCommandOutput(){return outputTail(M)}let D=async(t,o,r={})=>(console.log(n.gray("$ ")+[t,...o].join(" ")),M="",C={},E=r.idleMs?await runWatched(t,o,r):function(t,o,r){const n=P(t)?e(I(t,o),{stdio:U(),shell:!0,timeout:r}):e(t,o,{stdio:U(),timeout:r,env:O(t)});return n.error&&a.logError(`upgrade: ${t}`,n.error),C={exit_code:n.status,signal:n.signal,...n.error?{spawn_error:String(n.error.message)}:{}},"ETIMEDOUT"===n.error?.code?"timeout":0===n.status?"ok":"fail"}(t,o,r.timeoutMs),"ok"===E);const P=t=>"win32"===process.platform&&!/\.exe$/i.test(t),O=t=>j(t)?T():process.env,I=(t,e)=>[t,...e].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),U=()=>["inherit",v()?2:"inherit","inherit"];export function runWatched(e,o,r){return new Promise(n=>{const i=r.env?{...O(e),...r.env}:O(e),s=P(e)?t(I(e,o),{stdio:["inherit","pipe","pipe"],shell:!0,env:i}):t(e,o,{stdio:["inherit","pipe","pipe"],env:i});let l;const c=t=>{l=t,s.kill()};let p;const u=()=>{clearTimeout(p),r.idleMs&&(p=setTimeout(()=>c("stalled"),r.idleMs))},m=r.timeoutMs?setTimeout(()=>c("timeout"),r.timeoutMs):void 0;u(),s.stdout?.on("data",t=>{(v()?process.stderr:process.stdout).write(t),S(t),u()}),s.stderr?.on("data",t=>{process.stderr.write(t),S(t),u()});const d=t=>{clearTimeout(p),clearTimeout(m),n(t)};s.on("error",t=>{a.logError(`upgrade: ${e}`,t),C={...C,spawn_error:String(t.message)},d(l??"fail")}),s.on("close",(t,e)=>{C={...C,exit_code:t,signal:e},l&&(v()?process.stderr:process.stdout).write("\n"),d(l??(0===t?"ok":"fail"))})})}export function setUpgradeRunnerForTests(t){D=async(e,o,r)=>{const n=await t(e,o,r);return E="string"==typeof n?n:n?"ok":"fail","ok"===E}}const A={ok:"install.script_failed_npm",fail:"install.script_failed_npm",stalled:"install.script_stalled_npm",timeout:"install.script_timeout_npm"};export async function mirrorInstall(t){if(!t.mirrorScript)return B(t);console.log(n.gray(s.t("install.downloading")));const e=`install-script:${t.command}`,o=Date.now();b(e,"start");const r={idleMs:18e4,timeoutMs:36e5},i="win32"===process.platform?await D("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${t.mirrorScript.ps1} -TimeoutSec 30 | iex`],r):await D("sh",["-c",`script=$(curl -fsSL --connect-timeout 15 --max-time 60 ${t.mirrorScript.sh}) && printf '%s\\n' "$script" | sh`],r),a=E;return b(e,"stalled"===a?"timeout":a,{duration_ms:Date.now()-o,detail:{..."stalled"===a||"timeout"===a?{reason:a}:{},...lastCommandExit(),..."ok"===a?{output:x(lastCommandOutput())}:{},..."ok"!==a?failureContext():{}},..."ok"!==a&&lastCommandOutput()?{error:lastCommandOutput()}:{}}),i||!t.npmPackage?i:(console.log(n.yellow(" ! "+s.t(A[a],{minutes:String(3)}))),b(e,"fallback"),B(t))}export function failureContext(){const t=$();return t.length?{security:t}:{}}async function B(t){const e=f(t,await w(t)),[o,...r]=e.split(" "),i=`install-npm:${t.command}`,a=Date.now();b(i,"start");const l=await D(o,r);return b(i,l?"ok":"fail",{duration_ms:Date.now()-a,detail:{...lastCommandExit(),...l?{}:failureContext()}}),l||"win32"===process.platform||console.log(n.yellow(" ! "+s.t("upgrade.npm_permission",{command:e}))),l}async function N(t,e){switch(e.kind){case"npm":t.npmPackage&&await D("npm",["uninstall","-g",t.npmPackage]);break;case"brew":t.brew&&await D("brew",["uninstall",t.brew]);break;case"native":try{o(e.path,{force:!0});for(const e of t.native?.dataDirs??[])o(r(y(),...e),{recursive:!0,force:!0})}catch(t){a.logError("upgrade: remove native copy",t)}break;default:return!1}return d(),!u(t).some(t=>t.path===e.path)}function W(t,e){switch(e.kind){case"npm":return h(t);case"brew":return`brew uninstall ${t.brew}`;case"native":return s.t("upgrade.delete_paths",{paths:[e.path,...(t.native?.dataDirs??[]).map(t=>r(y(),...t))].join("、")});default:return s.t("upgrade.delete_paths",{paths:e.path})}}export async function upgradeTool(t){const e=Date.now();b(`upgrade:${t}`,"start");try{const o=await async function(t){const e=p(t),o=e?.installSpec;if(!e||!o)throw new Error(s.t("upgrade.unsupported",{tool:t}));const r=e.displayName;d();const f=u(o);if(console.log(n.bold(`\n${r}`)),0===f.length)console.log(s.t("upgrade.not_installed_installing",{tool:r})),await mirrorInstall(o);else{const t=f[0];console.log(n.gray(" "+s.t("upgrade.current",{copy:g(t)})));const e=await async function(t,e){switch(e.kind){case"native":return D(e.path,t.native?.updateArgs??["update"],{timeoutMs:t.native?.updateTimeoutMs});case"npm":return B(t);case"brew":return!!t.brew&&D("brew",["upgrade",t.brew]);default:return!1}}(o,t);e||"other"!==t.kind?e||"npm"===t.kind||"native"===t.kind&&await async function(t){const e=t.native?.mirrorUpdate;if(!e)return!1;console.log(n.yellow(" ! "+s.t("upgrade.native_mirror_trying")));try{const{version:t,manifestVerified:o}=await e();return console.log(n.green(" √ "+s.t(o?"upgrade.native_mirror_done_verified":"upgrade.native_mirror_done",{version:t}))),!0}catch(t){return a.logError("upgrade: native mirror",t),console.log(n.yellow(" ! "+s.t("upgrade.native_mirror_failed",{reason:t instanceof Error?t.message:String(t)}))),!1}}(o)||(console.log(n.yellow(" ! "+s.t("upgrade.fallback_mirror"))),await mirrorInstall(o)):console.log(n.yellow(" ! "+s.t("upgrade.unknown_install",{path:t.path})))}d(),await async function(t,e){const o=u(t);if(o.length<2)return;const r=function(t){return t.reduce((t,e)=>e.version&&(!t.version||l(e.version,t.version)>0)?e:t)}(o),a=o.filter(t=>t!==r);console.log(n.yellow(" ! "+s.t("upgrade.duplicates",{tool:e,keep:g(r),others:a.map(g).join("、")})));let c=k();c||_()||!process.stdin.isTTY||(c=(await i.prompt([{type:"confirm",name:"remove",message:s.t("upgrade.confirm_remove"),default:!0}])).remove);for(const e of a)c&&await N(t,e)?console.log(n.green(" √ "+s.t("upgrade.removed",{copy:g(e)}))):console.log(n.yellow(" ! "+s.t("upgrade.remove_by_hand",{how:W(t,e)})))}(o,r),d();const w=m(o)[0];if(!w)return console.log(n.red(" × "+s.t("upgrade.still_missing",{tool:r}))),!1;w.onPath||console.log(n.gray(" "+s.t("components.new_terminal")));const h=c(t);if(h&&w.version&&l(w.version,h)<0){console.log(n.yellow(" ! "+s.t("upgrade.still_old",{copy:g(w),min:h})));for(const t of e.upgradeHints?.(h)??[])console.log(n.yellow(" ! "+t));return!1}return console.log(n.green(" √ "+s.t("upgrade.done",{copy:g(w)}))),!0}(t);return b(`upgrade:${t}`,o?"ok":"fail",{duration_ms:Date.now()-e}),o}catch(o){throw b(`upgrade:${t}`,"fail",{duration_ms:Date.now()-e,error:o}),o}}
1
+ import{spawn as t,spawnSync as e}from"child_process";import{rmSync as o}from"fs";import{dirname as r,join as n}from"path";import a from"chalk";import i from"inquirer";import{i18n as s}from"./i18n.js";import{logger as l}from"../utils/logger.js";import{compareVersions as p,getToolMinVersion as c}from"./model-registry.js";import{getAdapter as u}from"./tools/registry.js";import{findInstalls as m,findInstallsIncludingNative as d,forgetInstalls as g,installLabel as f,npmMirrorInstallCommand as w,npmMirrorVersion as h,npmUninstallCommand as _}from"./tools/tool-installs.js";import{toolHome as v}from"./tools/types.js";import{isJsonMode as y,isNonInteractive as k,shouldAutoConfirm as b}from"./runtime-options.js";import{flushTelemetry as x,maskHome as j,maskSecrets as T,track as C}from"./telemetry.js";import{windowsSecurityProducts as D}from"./windows-security.js";import{isWindowsPowerShell as $,powerShellEnv as E}from"./powershell-env.js";import{diagnoseMissing as M,runInstallScript as P,traceSummary as S}from"./install-script.js";import{endedByInterrupt as I}from"./signals.js";let O="ok",U={};export function lastCommandExit(){return U}let A="";const W=t=>{A=(A+t.toString("utf-8")).slice(-3e3)};export function outputTail(t){return t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").split(/\r?\n/).map(t=>t.split("\r").pop().trimEnd()).filter(Boolean).join("\n").slice(-1500)}export function lastCommandOutput(){return outputTail(A)}export function lastCommandInterrupted(){return I({status:U.exit_code,signal:U.signal})}let q=async(t,o,r={})=>(console.log(a.gray("$ ")+[t,...o].join(" ")),A="",U={},r.idleMs?O=await runWatched(t,o,r):(await x(1e3),O=function(t,o,r){const n=z(t)?e(F(t,o),{stdio:H(),shell:!0,timeout:r}):e(t,o,{stdio:H(),timeout:r,env:B(t)});return n.error&&l.logError(`upgrade: ${t}`,n.error),U={exit_code:n.status,signal:n.signal,...n.error?{spawn_error:String(n.error.message)}:{}},"ETIMEDOUT"===n.error?.code?"timeout":0===n.status?"ok":"fail"}(t,o,r.timeoutMs)),"ok"===O);const z=t=>"win32"===process.platform&&!/\.exe$/i.test(t),B=t=>$(t)?E():process.env,F=(t,e)=>[t,...e].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),H=()=>["inherit",y()?2:"inherit","inherit"];export function runWatched(e,o,r){return new Promise(n=>{const a=r.env?{...B(e),...r.env}:B(e),i=z(e)?t(F(e,o),{stdio:["inherit","pipe","pipe"],shell:!0,env:a}):t(e,o,{stdio:["inherit","pipe","pipe"],env:a});let s;const p=t=>{s=t,i.kill()};let c;const u=()=>{clearTimeout(c),r.idleMs&&(c=setTimeout(()=>p("stalled"),r.idleMs))},m=r.timeoutMs?setTimeout(()=>p("timeout"),r.timeoutMs):void 0;u(),i.stdout?.on("data",t=>{(y()?process.stderr:process.stdout).write(t),W(t),u()}),i.stderr?.on("data",t=>{process.stderr.write(t),W(t),u()});const d=t=>{clearTimeout(c),clearTimeout(m),n(t)};i.on("error",t=>{l.logError(`upgrade: ${e}`,t),U={...U,spawn_error:String(t.message)},d(s??"fail")}),i.on("close",(t,e)=>{U={...U,exit_code:t,signal:e},s&&(y()?process.stderr:process.stdout).write("\n"),d(s??(0===t?"ok":"fail"))})})}export function setUpgradeRunnerForTests(t){q=async(e,o,r)=>{const n=await t(e,o,r);return O="string"==typeof n?n:n?"ok":"fail","ok"===O}}const N={ok:"install.script_failed_npm",fail:"install.script_failed_npm",stalled:"install.script_stalled_npm",timeout:"install.script_timeout_npm"};let R;export function lastInstallMissing(){return R}export async function mirrorInstall(t,e){if(R=void 0,!t.mirrorScript)return V(t);console.log(a.gray(s.t("install.downloading")));const o=`install-script:${t.command}`,n=Date.now();C(o,"start");const i=await P({name:t.command,url:"win32"===process.platform?t.mirrorScript.ps1:t.mirrorScript.sh,limits:{idleMs:18e4,timeoutMs:36e5},output:lastCommandOutput,run:async(t,e,o)=>(await q(t,e,o),O)});let l,p=i.outcome;if("ok"===p&&e&&(g(),!e.installed())){const t=M(i.trace,e.expectedPaths);"not_on_path"===t.reason&&t.path&&e.addToPath?.(r(t.path))&&e.installed()?l=r(t.path):(R=t,p="fail")}const c="ok"===p;if(C(o,"stalled"===p?"timeout":p,{duration_ms:Date.now()-n,detail:{..."stalled"===p||"timeout"===p?{reason:p}:{},...R?{reason:R.reason,...R.path?{path:j(R.path)}:{}}:{},...l?{path_added:j(l)}:{},how:i.how,...i.fileProblem?{file_problem:i.fileProblem}:{},...S(i.trace),...lastCommandExit(),...c?{output:T(lastCommandOutput())}:{},...c?{}:failureContext()},...c?{}:{error:lastCommandOutput()||(R?"(no output)":void 0)}}),R&&console.log(a.yellow(" ! "+function(t,e){const o=D().join("、");switch(e.reason){case"removed_after_install":return s.t(o?"install.missing_removed_by":"install.missing_removed",{tool:t,path:e.path??"",security:o});case"not_on_path":return s.t("install.missing_not_on_path",{tool:t,path:e.path??""});case"not_downloaded":return s.t("install.missing_not_downloaded",{tool:t});default:return s.t("install.missing_unknown",{tool:t})}}(t.command,R))),c||!t.npmPackage||lastCommandInterrupted())return c;console.log(a.yellow(" ! "+s.t(N[i.outcome],{minutes:String(3)}))),C(o,"fallback");const u=await V(t);return u&&e&&(g(),e.installed()&&(R=void 0)),u&&!R}export function failureContext(){const t=D();return t.length?{security:t}:{}}async function V(t){const e=w(t,await h(t)),[o,...r]=e.split(" "),n=`install-npm:${t.command}`,i=Date.now();C(n,"start");const l=await q(o,r);return C(n,l?"ok":"fail",{duration_ms:Date.now()-i,detail:{...lastCommandExit(),...l?{}:failureContext()}}),l||"win32"===process.platform||console.log(a.yellow(" ! "+s.t("upgrade.npm_permission",{command:e}))),l}async function Y(t,e){switch(e.kind){case"npm":t.npmPackage&&await q("npm",["uninstall","-g",t.npmPackage]);break;case"brew":t.brew&&await q("brew",["uninstall",t.brew]);break;case"native":try{o(e.path,{force:!0});for(const e of t.native?.dataDirs??[])o(n(v(),...e),{recursive:!0,force:!0})}catch(t){l.logError("upgrade: remove native copy",t)}break;default:return!1}return g(),!m(t).some(t=>t.path===e.path)}function Z(t,e){switch(e.kind){case"npm":return _(t);case"brew":return`brew uninstall ${t.brew}`;case"native":return s.t("upgrade.delete_paths",{paths:[e.path,...(t.native?.dataDirs??[]).map(t=>n(v(),...t))].join("、")});default:return s.t("upgrade.delete_paths",{paths:e.path})}}export async function upgradeTool(t){const e=Date.now();C(`upgrade:${t}`,"start");try{const o=await async function(t){const e=u(t),o=e?.installSpec;if(!e||!o)throw new Error(s.t("upgrade.unsupported",{tool:t}));const r=e.displayName;g();const n=m(o);if(console.log(a.bold(`\n${r}`)),0===n.length)console.log(s.t("upgrade.not_installed_installing",{tool:r})),await mirrorInstall(o);else{const t=n[0];console.log(a.gray(" "+s.t("upgrade.current",{copy:f(t)})));const e=await async function(t,e){switch(e.kind){case"native":return q(e.path,t.native?.updateArgs??["update"],{timeoutMs:t.native?.updateTimeoutMs});case"npm":return V(t);case"brew":return!!t.brew&&q("brew",["upgrade",t.brew]);default:return!1}}(o,t);!e&&lastCommandInterrupted()||(e||"other"!==t.kind?e||"npm"===t.kind||"native"===t.kind&&await async function(t){const e=t.native?.mirrorUpdate;if(!e)return!1;console.log(a.yellow(" ! "+s.t("upgrade.native_mirror_trying")));const o=`native-mirror:${t.command}`,r=Date.now();C(o,"start");try{const{version:t,manifestVerified:n}=await e();return C(o,"ok",{duration_ms:Date.now()-r,detail:{version:t,manifest_verified:n}}),console.log(a.green(" √ "+s.t(n?"upgrade.native_mirror_done_verified":"upgrade.native_mirror_done",{version:t}))),!0}catch(t){return l.logError("upgrade: native mirror",t),C(o,"fail",{duration_ms:Date.now()-r,error:t,detail:failureContext()}),console.log(a.yellow(" ! "+s.t("upgrade.native_mirror_failed",{reason:t instanceof Error?t.message:String(t)}))),!1}}(o)||(console.log(a.yellow(" ! "+s.t("upgrade.fallback_mirror"))),await mirrorInstall(o)):console.log(a.yellow(" ! "+s.t("upgrade.unknown_install",{path:t.path}))))}g(),await async function(t,e){const o=m(t);if(o.length<2)return;const r=function(t){return t.reduce((t,e)=>e.version&&(!t.version||p(e.version,t.version)>0)?e:t)}(o),n=o.filter(t=>t!==r);console.log(a.yellow(" ! "+s.t("upgrade.duplicates",{tool:e,keep:f(r),others:n.map(f).join("、")})));let l=b();l||k()||!process.stdin.isTTY||(l=(await i.prompt([{type:"confirm",name:"remove",message:s.t("upgrade.confirm_remove"),default:!0}])).remove);for(const e of n)l&&await Y(t,e)?console.log(a.green(" √ "+s.t("upgrade.removed",{copy:f(e)}))):console.log(a.yellow(" ! "+s.t("upgrade.remove_by_hand",{how:Z(t,e)})))}(o,r),g();const w=d(o)[0];if(!w)return console.log(a.red(" × "+s.t("upgrade.still_missing",{tool:r}))),!1;w.onPath||console.log(a.gray(" "+s.t("components.new_terminal")));const h=c(t);if(h&&w.version&&p(w.version,h)<0){console.log(a.yellow(" ! "+s.t("upgrade.still_old",{copy:f(w),min:h})));for(const t of e.upgradeHints?.(h)??[])console.log(a.yellow(" ! "+t));return!1}return console.log(a.green(" √ "+s.t("upgrade.done",{copy:f(w)}))),!0}(t);return C(`upgrade:${t}`,o?"ok":"fail",{duration_ms:Date.now()-e}),o}catch(o){throw C(`upgrade:${t}`,"fail",{duration_ms:Date.now()-e,error:o}),o}}
@@ -1 +1 @@
1
- import{existsSync as t,copyFileSync as r,readdirSync as e,statSync as o,unlinkSync as s,writeFileSync as c,renameSync as n,mkdirSync as a}from"fs";import{dirname as i,basename as u,join as m}from"path";import{logger as p}from"../../utils/logger.js";export function atomicWriteFile(r,e,o){const u=i(r);t(u)||a(u,{recursive:!0});const m=`${r}.tmp-${process.pid}-${Date.now()}`;try{c(m,e,void 0===o?"utf-8":{encoding:"utf-8",mode:o}),n(m,r)}catch(r){try{t(m)&&s(m)}catch{}throw r}}export const MAX_TOOL_BACKUPS=10;const f=".bak-";function h(r){const e=`${r}${f}${(new Date).toISOString().replace(/[:.]/g,"-")}`;let o=e,s=1;for(;t(o);)o=`${e}-${s++}`;return o}export function backupBeforeWrite(e,o=10){try{if(!t(e))return;r(e,h(e)),b(e,o)}catch(t){p.logError("backupBeforeWrite",t)}}function d(t){const r=t.match(/Z-(\d+)$/);return r?Number(r[1]):0}function l(t){const r=t.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z(?:-\d+)?$/);if(!r)return 0;const[,e,o,s,c,n,a,i]=r;return Date.UTC(Number(e),Number(o)-1,Number(s),Number(c),Number(n),Number(a),Number(i))}export function listBackups(t){const r=i(t),s=u(t)+f;try{return e(r).filter(t=>t.startsWith(s)).map(t=>{const e=m(r,t);return{path:e,name:t,mtimeMs:o(e).mtimeMs,seq:d(t),timestampMs:l(t)}}).sort((t,r)=>r.timestampMs-t.timestampMs||r.seq-t.seq||r.mtimeMs-t.mtimeMs)}catch{return[]}}export function restoreBackup(e,o){const s=o?listBackups(e).find(t=>t.path===o||t.name===o)?.path:listBackups(e)[0]?.path;if(!s||!t(s))return{restored:!1,reason:"no_backup"};let c;if(t(e)){const t=h(e);try{r(e,t),c=u(t)}catch(t){p.logError("restoreBackup.snapshot",t)}}return r(s,e),b(e,10),{restored:!0,from:u(s),snapshot:c}}function b(t,r){for(const e of listBackups(t).slice(Math.max(0,r)))try{s(e.path)}catch(t){p.logError("backupBeforeWrite.rotate",t)}}
1
+ import{chmodSync as t,existsSync as r,copyFileSync as e,readdirSync as o,statSync as s,unlinkSync as c,writeFileSync as n,renameSync as i,mkdirSync as a}from"fs";import{dirname as m,basename as u,join as p}from"path";import{logger as f}from"../../utils/logger.js";import{processAlive as h}from"../../utils/process-alive.js";const d=".tmp-";export function atomicWriteFile(e,f,l){const b=m(e);r(b)||a(b,{recursive:!0}),function(t){try{const r=m(t),e=u(t)+d;for(const t of o(r)){if(!t.startsWith(e))continue;const o=/^(\d+)-\d+$/.exec(t.slice(e.length))?.[1];o&&!h(Number(o))&&c(p(r,t))}}catch{}}(e);let k=l;if(void 0===k)try{k=511&s(e).mode}catch{}const $=`${e}${d}${process.pid}-${Date.now()}`;try{n($,f,void 0===k?"utf-8":{encoding:"utf-8",mode:k}),void 0===l&&void 0!==k&&"win32"!==process.platform&&t($,k),i($,e)}catch(t){try{r($)&&c($)}catch{}throw t}}export const MAX_TOOL_BACKUPS=10;const l=".bak-";function b(t){const e=Date.now(),o=listBackups(t)[0]?.timestampMs??0,s=`${t}${l}${c=o>e?o+1:e,new Date(c).toISOString().replace(/[:.]/g,"-")}`;var c;let n=s,i=1;for(;r(n);)n=`${s}-${i++}`;return n}export function backupBeforeWrite(t,o=10){try{if(!r(t))return;e(t,b(t)),B(t,o)}catch(t){f.logError("backupBeforeWrite",t)}}function k(t){const r=t.match(/Z-(\d+)$/);return r?Number(r[1]):0}function $(t){const r=t.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z(?:-\d+)?$/);if(!r)return 0;const[,e,o,s,c,n,i,a]=r;return Date.UTC(Number(e),Number(o)-1,Number(s),Number(c),Number(n),Number(i),Number(a))}export function listBackups(t){const r=m(t),e=u(t)+l;try{return o(r).filter(t=>t.startsWith(e)).map(t=>{const e=p(r,t);return{path:e,name:t,mtimeMs:s(e).mtimeMs,seq:k(t),timestampMs:$(t)}}).sort((t,r)=>r.timestampMs-t.timestampMs||r.seq-t.seq||r.mtimeMs-t.mtimeMs)}catch{return[]}}export function restoreBackup(t,o){const s=o?listBackups(t).find(t=>t.path===o||t.name===o)?.path:listBackups(t)[0]?.path;if(!s||!r(s))return{restored:!1,reason:"no_backup"};let c;if(r(t)){const r=b(t);try{e(t,r),c=u(r)}catch(t){f.logError("restoreBackup.snapshot",t)}}return e(s,t),B(t,10),{restored:!0,from:u(s),snapshot:c}}function B(t,r){for(const e of listBackups(t).slice(Math.max(0,r)))try{c(e.path)}catch(t){f.logError("backupBeforeWrite.rotate",t)}}
@@ -1 +1 @@
1
- import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as m,savedApiKeys as p}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as h,hasExplicitYes as v}from"../runtime-options.js";import{maskHome as C}from"../telemetry.js";import{spawnSync as j}from"child_process";import{existsSync as y,readFileSync as k}from"fs";import{detectManagedOverrides as A}from"./claude-managed.js";import{installOfficialPlugins as O}from"./claude-plugins.js";import{findInstalls as P,mirrorInstallCommand as S,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as w}from"../sessions/formats.js";const H=e(c(),".claude","settings.json"),L=e(c(),".claude.json");let R,U=null,E=()=>0===j("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(y(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(k(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function D(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(p())?null:e.trim():null}let B=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return h()&&!v()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:S(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:H,sessions:{format:N,files:()=>w(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){B=D(),n(H),n(L),R=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,R);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=P(claudeCodeAdapter.installSpec)[0]?.path??(y(s)?s:null);U=a?O(a):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(m.getBaseUrl()))},planNotes(){const e=[],t=D();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:C(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(H),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(H),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(H),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${C(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>C(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:C(e.location),vars:Object.keys(e.vars).join(", ")})}));return t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})}),o},decline(){}}},applyNotes(){const e=[];U?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(U.installed.length)})}),e.push({kind:"detail",text:U.installed.join(", ")})),"git"===U?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===U?.skipped||U?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),R&&R.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(R.length),vendors:l(R.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:R.map(e=>e.name||i(e.id)).join(", ")})),B&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:B})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:C(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:C(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===j("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of A())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[H,L],forceResetPaths:()=>[H]};
1
+ import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as p,savedApiKeys as m}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as v,hasExplicitYes as h}from"../runtime-options.js";import{maskHome as j}from"../telemetry.js";import{spawnSync as k}from"child_process";import{existsSync as C,readFileSync as y}from"fs";import{detectManagedOverrides as O}from"./claude-managed.js";import{installOfficialPlugins as A}from"./claude-plugins.js";import{findInstalls as P,mirrorInstallCommand as S,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as U}from"../sessions/formats.js";const w=e(c(),".claude","settings.json"),H=e(c(),".claude.json");let L,R=null,E=()=>0===k("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(C(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(y(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function B(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(m())?null:e.trim():null}let D=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return v()&&!h()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:S(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:w,sessions:{format:N,files:()=>U(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){D=B(),n(w),n(H),L=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,L);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=P(claudeCodeAdapter.installSpec)[0]?.path??(C(s)?s:null);R=a?A(a,{retry:Boolean(t.takeOver)}):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(p.getBaseUrl()))},planNotes(){const e=[],t=B();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:j(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(w),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(w),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(w),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${j(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>j(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})}));t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const e of t.notBackedUp)o.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})});return o},decline(){}}},applyNotes(){const e=[];R?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(R.installed.length)})}),e.push({kind:"detail",text:R.installed.join(", ")})),"git"===R?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===R?.skipped||"recent_failure"===R?.skipped||R?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),L&&L.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(L.length),vendors:l(L.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:L.map(e=>e.name||i(e.id)).join(", ")})),D&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:D})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:j(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const o of t.notBackedUp)e.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===k("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of O())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[w,H],forceResetPaths:()=>[w]};