@vibeapi/api-helper 0.0.174 → 0.0.177
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/client-config.snapshot.json +983 -983
- package/dist/brand.json +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-config.snapshot.json +983 -983
- package/dist/commands/base.d.ts +13 -5
- package/dist/commands/base.js +1 -1
- package/dist/commands/codex-sessions.js +1 -1
- package/dist/commands/components.js +1 -1
- package/dist/commands/doctor.js +1 -1
- package/dist/commands/sessions.js +1 -1
- package/dist/commands/setup.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/lib/app-update.js +1 -1
- package/dist/lib/auto-update.d.ts +7 -0
- package/dist/lib/auto-update.js +1 -1
- package/dist/lib/claude-code-manager.d.ts +2 -0
- package/dist/lib/claude-code-manager.js +1 -1
- package/dist/lib/client-config-sync.d.ts +2 -0
- package/dist/lib/client-config-sync.js +1 -1
- package/dist/lib/codex-sessions.d.ts +5 -0
- package/dist/lib/codex-sessions.js +1 -1
- package/dist/lib/command.js +1 -1
- package/dist/lib/components.d.ts +5 -0
- package/dist/lib/components.js +1 -1
- package/dist/lib/config.d.ts +26 -0
- package/dist/lib/config.js +1 -1
- package/dist/lib/env-cleanup.d.ts +4 -0
- package/dist/lib/env-cleanup.js +1 -1
- package/dist/lib/gateway-addresses.js +1 -1
- package/dist/lib/install-script.d.ts +72 -0
- package/dist/lib/install-script.js +1 -0
- package/dist/lib/model-refresh.d.ts +7 -1
- package/dist/lib/model-refresh.js +1 -1
- package/dist/lib/persistent-env.d.ts +5 -1
- package/dist/lib/persistent-env.js +1 -1
- package/dist/lib/post-apply.d.ts +4 -2
- package/dist/lib/post-apply.js +1 -1
- package/dist/lib/signals.d.ts +16 -0
- package/dist/lib/signals.js +1 -0
- package/dist/lib/system-report.d.ts +1 -0
- package/dist/lib/system-report.js +1 -0
- package/dist/lib/telemetry.d.ts +10 -0
- package/dist/lib/telemetry.js +1 -1
- package/dist/lib/tool-manager.d.ts +2 -0
- package/dist/lib/tool-manager.js +1 -1
- package/dist/lib/tool-upgrade.d.ts +21 -2
- package/dist/lib/tool-upgrade.js +1 -1
- package/dist/lib/tools/backup.d.ts +5 -0
- package/dist/lib/tools/backup.js +1 -1
- package/dist/lib/tools/claude-code.js +1 -1
- package/dist/lib/tools/claude-desktop-cli.d.ts +4 -0
- package/dist/lib/tools/claude-desktop-cli.js +1 -1
- package/dist/lib/tools/claude-desktop.js +1 -1
- package/dist/lib/tools/claude-plugins.d.ts +21 -4
- package/dist/lib/tools/claude-plugins.js +1 -1
- package/dist/lib/tools/codex.d.ts +2 -0
- package/dist/lib/tools/codex.js +1 -1
- package/dist/lib/tools/desktop-app-installer.js +1 -1
- package/dist/lib/tools/elevated-reg.d.ts +5 -0
- package/dist/lib/tools/elevated-reg.js +1 -1
- package/dist/lib/tools/tool-installs.js +1 -1
- package/dist/lib/written-values.d.ts +8 -0
- package/dist/lib/written-values.js +1 -1
- package/dist/locales/en_US.json +12 -3
- package/dist/locales/zh_CN.json +12 -3
- package/dist/utils/process-alive.d.ts +6 -0
- package/dist/utils/process-alive.js +1 -0
- package/package.json +1 -1
package/dist/lib/command.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i18n as n,detectSystemLang as o}from"./i18n.js";import{configManager as r}from"./config.js";import{runModelRefresh as t}from"./model-refresh.js";import{refreshClientConfig as e}from"./client-config-sync.js";import{normalizeBaseUrl as i}from"./gateway-addresses.js";import s from"chalk";import{setRuntimeOptions as m,detectColorPreferenceFromEnv as a,isDryRun as c}from"./runtime-options.js";import{runStartupUpdate as
|
|
1
|
+
import{i18n as n,detectSystemLang as o}from"./i18n.js";import{configManager as r}from"./config.js";import{runModelRefresh as t}from"./model-refresh.js";import{refreshClientConfig as e}from"./client-config-sync.js";import{normalizeBaseUrl as i}from"./gateway-addresses.js";import s from"chalk";import{setRuntimeOptions as m,detectColorPreferenceFromEnv as a,isDryRun as c}from"./runtime-options.js";import{runStartupUpdate as l}from"./auto-update.js";import{buildProgram as d}from"./program.js";import{firstCommandWord as u,isHelpRequest as p,renderHelpTopic as g}from"./cli-help.js";import{reportCliError as f,usageError as h,CliError as _,EXIT_CODES as y}from"./errors.js";import{brandEnv as w,CLI_NAME as j}from"./brand.js";import{dryRunUnsupportedCommand as k}from"./dry-run.js";import{flushTelemetry as v,installClientHeaders as C,lastFailureReason as x,maskSecrets as A,setTelemetryCommand as O,track as b,watchConsoleErrors as D}from"./telemetry.js";export{buildProgram}from"./program.js";const M=new Set(["setup","init","auth","enter","config"]);export class Command{program;configuring=!1;constructor(){const t=r.isLangChosen()?r.getLang():o();n.loadFromConfig(t),this.program=d()}preflightArgs(n){const o=o=>n.includes(o),t=!o("--no-color")&&a();if(m({nonInteractive:o("--non-interactive"),json:o("--json"),yes:o("--yes")||o("-y"),dryRun:o("--dry-run"),color:t}),t||(s.level=0),this.configuring=!1,p(n))return;let e;for(let o=0;o<n.length;o+=1){const r=n[o];"--base"===r&&n[o+1]?(e=n[o+1],o+=1):r.startsWith("--base=")&&(e=r.slice(7))}const c=u(n),l=void 0===c&&!["--version","-v"].some(o);this.configuring=l||void 0!==c&&M.has(c),e&&r.setBaseUrl(i(e)??e,this.configuring&&!o("--dry-run"))}async execute(n){const o=Date.now();let r=!1;try{if(this.preflightArgs(n),C(),!p(n)&&!["--version","-v"].some(o=>n.includes(o))){O(u(n)??"wizard");const o=w("INSTALLER_NOTE")?.trim();b("command","start",{detail:{args:n.filter(n=>n.startsWith("-")&&!/key/i.test(n)),...o?{installer:A(o).slice(0,400)}:{}}}),r=!0,D()}if("help"===n[0]&&n[1]){const o=g(n[1]);if(o)return void process.stdout.write(o)}if(this.rejectUnknownCommand(n),!p(n)){if(c()&&this.rejectUnsupportedDryRun(n),(await l(n)).handled)return;this.configuring&&await e({timeoutMs:5e3}),await t(n)}if(await this.program.parseAsync(n,{from:"user"}),r){const n=Boolean(process.exitCode)&&0!==process.exitCode,r=Number(process.exitCode)===y.cancelled;b("command",r?"cancel":n?"fail":"ok",{duration_ms:Date.now()-o,...n?{error:x(),detail:{exit_code:process.exitCode}}:{}})}}catch(t){if("commander.helpDisplayed"===t?.code||"commander.version"===t?.code)return;const e=this.normalizeCommanderError(t,n),i=f(e);if(r){const n=e instanceof _?`${e.type}${e.subtype?"/"+e.subtype:""}`:void 0;b("command",130===i?"cancel":"fail",{duration_ms:Date.now()-o,error:e,detail:{exit_code:i,...n?{type:n}:{}}})}}finally{r&&await v()}}rejectUnsupportedDryRun(o){const r=k(o);if(null!==r)throw h(n.t("runtime.dry_run_unsupported",{command:r,cli:j}),n.t("runtime.dry_run_unsupported_hint",{cli:j}),"dry_run_unsupported")}rejectUnknownCommand(o){const r=u(o);if(!r||"help"===r)return;if(this.program.commands.some(n=>n.name()===r))return;const t=this.suggestCommand(r),e=t?n.t("cli.unknown_hint_suggestion",{command:t}):n.t("cli.unknown_hint");throw h(n.t("cli.error_unknown",{command:r}),e,"unknown_command")}suggestCommand(n){const o=(n,o)=>{const r=Array.from({length:o.length+1},(n,o)=>o);for(let t=1;t<=n.length;t+=1){let e=r[0];r[0]=t;for(let i=1;i<=o.length;i+=1){const s=r[i];r[i]=Math.min(r[i]+1,r[i-1]+1,e+(n[t-1]===o[i-1]?0:1)),e=s}}return r[o.length]};return this.program.commands.map(n=>n.name()).map(r=>({name:r,score:o(n,r)})).filter(({score:o})=>o<=Math.max(2,Math.floor(n.length/2))).sort((n,o)=>n.score-o.score)[0]?.name}normalizeCommanderError(o,r){if(o instanceof _)return o;const t=o?.code,e=o instanceof Error?o.message:String(o);if("commander.unknownOption"===t||"commander.missingArgument"===t||"commander.missingMandatoryOption"===t||"commander.invalidArgument"===t){const o=u(r),i=/'([^']+)'/.exec(e)?.[1]??"",s="commander.unknownOption"===t?"cli.err_unknown_option":"commander.missingArgument"===t?"cli.err_missing_argument":"commander.missingMandatoryOption"===t?"cli.err_missing_option":null,m="commander.unknownOption"===t?this.gluedOption(i):void 0,a=A(i),c=m?n.t("cli.err_glued_option",{name:a,option:m}):s&&i?n.t(s,{name:a}):A(e.replace(/^error:\s*/,""));return h(c,o?n.t("cli.unknown_option_hint",{command:o}):n.t("cli.unknown_option_hint_root"),t)}return o}gluedOption(n){const o=new Set,r=n=>{for(const r of n.options)r.long&&o.add(r.long);for(const o of n.commands)r(o)};return r(this.program),[...o].filter(o=>n.length>o.length&&n.startsWith(o)).sort((n,o)=>o.length-n.length)[0]}getProgram(){return this.program}}
|
package/dist/lib/components.d.ts
CHANGED
|
@@ -190,6 +190,11 @@ export declare function runRuntime(spec: ComponentSpec, mode: 'install' | 'upgra
|
|
|
190
190
|
}): Promise<ComponentResult>;
|
|
191
191
|
/** "x a → b: run …" for an outdated copy. */
|
|
192
192
|
export declare function upgradeAdvice(status: ComponentStatus): string;
|
|
193
|
+
/**
|
|
194
|
+
* Finishes a move of global npm packages that a Node upgrade started and didn't complete (the process was ended
|
|
195
|
+
* after the script switched fnm's default Node). Called by `list` / `install` / `upgrade`; quiet when there is nothing to do.
|
|
196
|
+
*/
|
|
197
|
+
export declare function resumePendingMigration(): Promise<'none' | 'done' | 'failed'>;
|
|
193
198
|
export declare function setComponentDepsForTests(deps: {
|
|
194
199
|
platform?: NodeJS.Platform | null;
|
|
195
200
|
uid?: number | null;
|
package/dist/lib/components.js
CHANGED
|
@@ -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)}
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -39,6 +39,11 @@ export interface VibecliConfig {
|
|
|
39
39
|
active_profile?: string;
|
|
40
40
|
profiles?: Record<string, VibecliProfile>;
|
|
41
41
|
presets?: Record<string, VibecliPreset>;
|
|
42
|
+
/**
|
|
43
|
+
* Per-tool marks that belong to this machine, not to a profile: things done once (plugins
|
|
44
|
+
* offered, an old default undone) must not be done again after switching profiles.
|
|
45
|
+
*/
|
|
46
|
+
machine_settings?: Record<string, VibecliToolSettings>;
|
|
42
47
|
api_key?: string;
|
|
43
48
|
base_url?: string;
|
|
44
49
|
models?: VibecliModels;
|
|
@@ -78,7 +83,20 @@ export declare class ConfigManager {
|
|
|
78
83
|
private loadConfig;
|
|
79
84
|
private needsMigration;
|
|
80
85
|
private migrateOldConfig;
|
|
86
|
+
/**
|
|
87
|
+
* Temp file + rename. The temp name carries the pid and a counter: with one fixed name, two
|
|
88
|
+
* processes saving at once (the wizard open, `setup` in another terminal) wrote into the same
|
|
89
|
+
* file and one could rename the other's half-written content into place.
|
|
90
|
+
*/
|
|
81
91
|
private atomicWrite;
|
|
92
|
+
/** Temp files a killed save left behind hold the keys: remove them once they are clearly not in use. */
|
|
93
|
+
private removeStaleTempFiles;
|
|
94
|
+
/**
|
|
95
|
+
* config.yaml that cannot be parsed: keep the file as `config.yaml.corrupt-<time>` (0600, only
|
|
96
|
+
* the latest one) before defaults take over. The rolling backups would hold it too, but only
|
|
97
|
+
* until ten later saves pushed it out, a few setups.
|
|
98
|
+
*/
|
|
99
|
+
private keepCorruptConfig;
|
|
82
100
|
private backupConfig;
|
|
83
101
|
private rotateBackups;
|
|
84
102
|
saveConfig(config?: VibecliConfig): void;
|
|
@@ -124,6 +142,14 @@ export declare class ConfigManager {
|
|
|
124
142
|
getToolSettings(toolName: string): VibecliToolSettings;
|
|
125
143
|
getToolSetting(toolName: string, key: string): VibecliToolSettingValue | undefined;
|
|
126
144
|
setToolSetting(toolName: string, key: string, value: VibecliToolSettingValue): void;
|
|
145
|
+
/**
|
|
146
|
+
* A mark that holds for this machine whatever profile is active. Marks from versions that kept
|
|
147
|
+
* them per profile still count: the active profile's first, then any other profile's.
|
|
148
|
+
*/
|
|
149
|
+
getMachineSetting(toolName: string, key: string): VibecliToolSettingValue | undefined;
|
|
150
|
+
/** Every recorded value of a machine mark: the machine-level one first, then each profile's old copy. */
|
|
151
|
+
machineSettingValues(toolName: string, key: string): VibecliToolSettingValue[];
|
|
152
|
+
setMachineSetting(toolName: string, key: string, value: VibecliToolSettingValue): void;
|
|
127
153
|
getCustomPresets(): Record<string, VibecliPreset>;
|
|
128
154
|
saveCustomPreset(name: string, models: typeof DEFAULT_MODELS): void;
|
|
129
155
|
deleteCustomPreset(name: string): void;
|
package/dist/lib/config.js
CHANGED
|
@@ -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]}
|
|
@@ -23,6 +23,8 @@ export interface EnvSource {
|
|
|
23
23
|
* (macOS / Linux), Windows user and system environment variables and PowerShell profiles.
|
|
24
24
|
*/
|
|
25
25
|
export declare function anthropicEnvSources(): EnvSource[];
|
|
26
|
+
/** How many `windows-env-<scope>-*.json` files are kept per scope. */
|
|
27
|
+
export declare const MAX_WINDOWS_ENV_BACKUPS = 10;
|
|
26
28
|
export interface EnvCleanupResult {
|
|
27
29
|
/** Sources that pointed at this gateway, with what was removed from each. */
|
|
28
30
|
removed: EnvSource[];
|
|
@@ -30,6 +32,8 @@ export interface EnvCleanupResult {
|
|
|
30
32
|
foreign: EnvSource[];
|
|
31
33
|
/** System-scope names that need an elevated run to delete. */
|
|
32
34
|
machineLeft: string[];
|
|
35
|
+
/** Sources left as they were because their values couldn't be backed up first. */
|
|
36
|
+
notBackedUp: EnvSource[];
|
|
33
37
|
}
|
|
34
38
|
/**
|
|
35
39
|
* Removes ANTHROPIC_* settings that point at this gateway from shell profiles and the Windows
|
package/dist/lib/env-cleanup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,
|
|
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,
|
|
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,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs an install script (ours on the brand's script mirror, or a download mirror's own) from a file.
|
|
3
|
+
*
|
|
4
|
+
* Until 0.0.174 the script's text went straight into the interpreter (`irm <url> | iex`, `curl | sh`). That leaves
|
|
5
|
+
* nothing to look at when it ends early: 11-12 a script "succeeded" in 3 s on a Windows with 360 and installed
|
|
6
|
+
* nothing. Saved to a file first, three more things are visible: a file that security software removes before it
|
|
7
|
+
* runs (`removed`), a policy that refuses script files (`policy`), and the script's own step records
|
|
8
|
+
* (`INSTALL_TRACE`, one line per step), which say how far it got and where it put the program.
|
|
9
|
+
* Either problem with the file falls back to the old way, so nothing that worked before stops working.
|
|
10
|
+
*
|
|
11
|
+
* No evidence says a file is less likely to be stopped than `iex` (docs/research/install-self-heal-2026-11-12.md):
|
|
12
|
+
* on-access scanners read the file, and 火绒 quarantined a script of ours that collected machine facts. The gain
|
|
13
|
+
* is that every such stop now has a name in the support events.
|
|
14
|
+
*/
|
|
15
|
+
export type ScriptOutcome = 'ok' | 'fail' | 'timeout' | 'stalled';
|
|
16
|
+
export interface ScriptLimits {
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
idleMs?: number;
|
|
19
|
+
env?: Record<string, string>;
|
|
20
|
+
}
|
|
21
|
+
/** Runs a command with the terminal attached and reports how it ended. */
|
|
22
|
+
export type ScriptRunner = (command: string, args: string[], limits: ScriptLimits) => Promise<ScriptOutcome>;
|
|
23
|
+
/** One step record written by an install script: `<unix ms> <step> <start|ok|fail> [detail]`. */
|
|
24
|
+
export interface TraceLine {
|
|
25
|
+
at: number;
|
|
26
|
+
step: string;
|
|
27
|
+
status: string;
|
|
28
|
+
detail: string;
|
|
29
|
+
}
|
|
30
|
+
export interface ScriptRun {
|
|
31
|
+
outcome: ScriptOutcome;
|
|
32
|
+
/** `file`: saved and run from a file; `inline`: handed to the interpreter as text (the fallback). */
|
|
33
|
+
how: 'file' | 'inline';
|
|
34
|
+
/** Why the file way wasn't used or didn't work. */
|
|
35
|
+
fileProblem?: 'download' | 'removed' | 'policy';
|
|
36
|
+
trace: TraceLine[];
|
|
37
|
+
}
|
|
38
|
+
export declare function parseTrace(text: string): TraceLine[];
|
|
39
|
+
/** The step a script was in when it stopped writing: its last record, unless that one closed the run. */
|
|
40
|
+
export declare function lastStep(trace: TraceLine[]): string | undefined;
|
|
41
|
+
/** Where the script says it put the program (`place ok <path>`, or `end ok <path>`). */
|
|
42
|
+
export declare function placedPath(trace: TraceLine[]): string | undefined;
|
|
43
|
+
/** What the trace adds to a support event: the step it stopped in and the failure it recorded (paths stay out). */
|
|
44
|
+
export declare function traceSummary(trace: TraceLine[]): Record<string, unknown>;
|
|
45
|
+
export type MissingReason = 'not_downloaded' | 'removed_after_install' | 'not_on_path' | 'not_found';
|
|
46
|
+
/**
|
|
47
|
+
* A script said it worked and the command still isn't there. Which of three things happened:
|
|
48
|
+
* `not_on_path` the program is where the script put it (or where this tool's installs go), only PATH lacks it;
|
|
49
|
+
* `removed_after_install` the script put it somewhere and it is gone again: quarantined, most likely;
|
|
50
|
+
* `not_downloaded` the script never got as far as a download;
|
|
51
|
+
* `not_found` no step records (an older script): nothing to tell them apart.
|
|
52
|
+
*/
|
|
53
|
+
export declare function diagnoseMissing(trace: TraceLine[], expectedPaths: string[]): {
|
|
54
|
+
reason: MissingReason;
|
|
55
|
+
path?: string;
|
|
56
|
+
};
|
|
57
|
+
/** The step records of the last run of each script (`<config dir>/install-traces/<name>.log`), for `doctor --report`. */
|
|
58
|
+
export declare function savedTraces(): Record<string, string[]>;
|
|
59
|
+
/** Tests replace the download (and with it turn the file way on, whatever `<PREFIX>_SCRIPT_INLINE` says). */
|
|
60
|
+
export declare function setScriptFetcherForTests(fake: ((url: string) => Promise<string>) | null): void;
|
|
61
|
+
export interface RunScriptOptions {
|
|
62
|
+
/** Short name for the file and the saved trace (`claude`, `node`). */
|
|
63
|
+
name: string;
|
|
64
|
+
url: string;
|
|
65
|
+
run: ScriptRunner;
|
|
66
|
+
limits?: ScriptLimits;
|
|
67
|
+
/** What the run printed last (to recognise a policy refusal). */
|
|
68
|
+
output?: () => string;
|
|
69
|
+
platform?: NodeJS.Platform;
|
|
70
|
+
}
|
|
71
|
+
/** Saves the script, runs it from the file with step records on, and falls back to the inline way when the file can't be used. */
|
|
72
|
+
export declare function runInstallScript(options: RunScriptOptions): Promise<ScriptRun>;
|
|
@@ -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})}}
|
|
@@ -5,16 +5,22 @@
|
|
|
5
5
|
* use the key vibecli saved are touched; offline nothing changes.
|
|
6
6
|
*/
|
|
7
7
|
export declare const MODEL_REFRESH_INTERVAL_MS: number;
|
|
8
|
+
/** A round that reached no model list at all (offline) is tried again this soon, not an hour later. */
|
|
9
|
+
export declare const MODEL_REFRESH_OFFLINE_RETRY_MS: number;
|
|
8
10
|
export interface ModelMenuChange {
|
|
9
11
|
tool: string;
|
|
10
12
|
added: string[];
|
|
11
13
|
removed: string[];
|
|
12
14
|
}
|
|
13
15
|
export declare function shouldSkipModelRefresh(args: string[], env?: NodeJS.ProcessEnv): boolean;
|
|
14
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* How the last refresh went: menus actually checked against the gateway, tools that failed, and
|
|
18
|
+
* tools left alone because their key's model list could not be fetched.
|
|
19
|
+
*/
|
|
15
20
|
export declare function lastModelRefreshOutcome(): {
|
|
16
21
|
checked: number;
|
|
17
22
|
failed: number;
|
|
23
|
+
offline: number;
|
|
18
24
|
};
|
|
19
25
|
/** Rewrites the menus that differ from the gateway's current list; returns what changed per tool. */
|
|
20
26
|
export declare function refreshModelMenus(): Promise<ModelMenuChange[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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}
|
|
@@ -7,7 +7,11 @@ export interface PersistentEnvResult {
|
|
|
7
7
|
* 同时更新本进程的 process.env,让 vibecli 随后启动的子进程立即可用。
|
|
8
8
|
*/
|
|
9
9
|
export declare function writePersistentEnv(id: string, envFile: string, vars: Record<string, string>): PersistentEnvResult;
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* 删掉 rc 里我们加的那一行、Windows 用户环境变量里我们写的值,最后才删 env 文件。
|
|
12
|
+
* env 文件是「哪些值是我们写的」的唯一凭证:先删它再被中断,下次就认不出用户环境变量里的令牌,它会一直留着。
|
|
13
|
+
* 有值没删掉时 env 文件留下,下次再删。
|
|
14
|
+
*/
|
|
11
15
|
export declare function removePersistentEnv(id: string, envFile: string, names: readonly string[]): void;
|
|
12
16
|
/** 读回 env 文件里的变量;文件不存在或没有内容时为空对象。 */
|
|
13
17
|
export declare function readPersistentEnvFile(envFile: string): Record<string, string>;
|
|
@@ -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
|
|
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}
|
package/dist/lib/post-apply.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Changes that need an administrator, left by the last apply or menu refresh: one
|
|
3
|
-
*
|
|
2
|
+
* Changes that need an administrator, left by the last apply or menu refresh: one UAC prompt each. Asked in
|
|
3
|
+
* a terminal; an explicit `--yes` runs them without asking; otherwise (`--json`, `--non-interactive`, no
|
|
4
|
+
* terminal) only the command is shown: a UAC prompt nobody is there to answer would hold the command for
|
|
5
|
+
* minutes. Same rule as the adapters' follow-ups below.
|
|
4
6
|
*/
|
|
5
7
|
export declare function runPendingElevations(tools: string[]): Promise<void>;
|
|
6
8
|
/**
|
package/dist/lib/post-apply.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"chalk";import t from"inquirer";import{i18n as
|
|
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,16 @@
|
|
|
1
|
+
/** Runs `fn` while a child owns the terminal: Ctrl+C during it (and just after) belongs to the child. */
|
|
2
|
+
export declare function handTerminalOver<T>(fn: () => T): T;
|
|
3
|
+
/**
|
|
4
|
+
* A child run with a synchronous spawn ended because of Ctrl+C (killed by SIGINT, exit code 130, or Windows'
|
|
5
|
+
* STATUS_CONTROL_C_EXIT). With the handlers above this process is no longer killed along with it, and its
|
|
6
|
+
* own handler only runs at the next `await`: loops that would try the next source must stop on this.
|
|
7
|
+
*/
|
|
8
|
+
export declare function endedByInterrupt(result: {
|
|
9
|
+
status?: number | null;
|
|
10
|
+
signal?: string | null;
|
|
11
|
+
}): boolean;
|
|
12
|
+
/** What a signal does; `exit` is injected by tests. */
|
|
13
|
+
export declare function handleSignal(signal: string, exit?: (code: number) => void): Promise<void>;
|
|
14
|
+
export declare function resetSignalStateForTests(): void;
|
|
15
|
+
/** Installed once by the CLI entry point; never under the test runner (it would swallow the runner's own Ctrl+C). */
|
|
16
|
+
export declare function installSignalHandlers(): void;
|
|
@@ -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
|
+
export declare function systemReport(): Record<string, unknown>;
|