@vibeapi/api-helper 0.0.174 → 0.0.176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/commands/base.d.ts +13 -5
  3. package/dist/commands/base.js +1 -1
  4. package/dist/commands/codex-sessions.js +1 -1
  5. package/dist/commands/components.js +1 -1
  6. package/dist/commands/doctor.js +1 -1
  7. package/dist/commands/sessions.js +1 -1
  8. package/dist/commands/setup.js +1 -1
  9. package/dist/commands/upgrade.js +1 -1
  10. package/dist/lib/app-update.js +1 -1
  11. package/dist/lib/auto-update.d.ts +7 -0
  12. package/dist/lib/auto-update.js +1 -1
  13. package/dist/lib/claude-code-manager.d.ts +2 -0
  14. package/dist/lib/claude-code-manager.js +1 -1
  15. package/dist/lib/client-config-sync.d.ts +2 -0
  16. package/dist/lib/client-config-sync.js +1 -1
  17. package/dist/lib/codex-sessions.d.ts +5 -0
  18. package/dist/lib/codex-sessions.js +1 -1
  19. package/dist/lib/command.js +1 -1
  20. package/dist/lib/components.d.ts +5 -0
  21. package/dist/lib/components.js +1 -1
  22. package/dist/lib/config.d.ts +26 -0
  23. package/dist/lib/config.js +1 -1
  24. package/dist/lib/env-cleanup.d.ts +4 -0
  25. package/dist/lib/env-cleanup.js +1 -1
  26. package/dist/lib/gateway-addresses.js +1 -1
  27. package/dist/lib/install-script.d.ts +72 -0
  28. package/dist/lib/install-script.js +1 -0
  29. package/dist/lib/model-refresh.d.ts +7 -1
  30. package/dist/lib/model-refresh.js +1 -1
  31. package/dist/lib/persistent-env.d.ts +5 -1
  32. package/dist/lib/persistent-env.js +1 -1
  33. package/dist/lib/post-apply.d.ts +4 -2
  34. package/dist/lib/post-apply.js +1 -1
  35. package/dist/lib/signals.d.ts +16 -0
  36. package/dist/lib/signals.js +1 -0
  37. package/dist/lib/system-report.d.ts +1 -0
  38. package/dist/lib/system-report.js +1 -0
  39. package/dist/lib/telemetry.d.ts +10 -0
  40. package/dist/lib/telemetry.js +1 -1
  41. package/dist/lib/tool-manager.d.ts +2 -0
  42. package/dist/lib/tool-manager.js +1 -1
  43. package/dist/lib/tool-upgrade.d.ts +21 -2
  44. package/dist/lib/tool-upgrade.js +1 -1
  45. package/dist/lib/tools/backup.d.ts +5 -0
  46. package/dist/lib/tools/backup.js +1 -1
  47. package/dist/lib/tools/claude-code.js +1 -1
  48. package/dist/lib/tools/claude-desktop-cli.d.ts +4 -0
  49. package/dist/lib/tools/claude-desktop-cli.js +1 -1
  50. package/dist/lib/tools/claude-desktop.js +1 -1
  51. package/dist/lib/tools/claude-plugins.d.ts +21 -4
  52. package/dist/lib/tools/claude-plugins.js +1 -1
  53. package/dist/lib/tools/codex.d.ts +2 -0
  54. package/dist/lib/tools/codex.js +1 -1
  55. package/dist/lib/tools/desktop-app-installer.js +1 -1
  56. package/dist/lib/tools/elevated-reg.d.ts +5 -0
  57. package/dist/lib/tools/elevated-reg.js +1 -1
  58. package/dist/lib/tools/tool-installs.js +1 -1
  59. package/dist/lib/written-values.d.ts +8 -0
  60. package/dist/lib/written-values.js +1 -1
  61. package/dist/locales/en_US.json +12 -3
  62. package/dist/locales/zh_CN.json +12 -3
  63. package/dist/utils/process-alive.d.ts +6 -0
  64. package/dist/utils/process-alive.js +1 -0
  65. package/package.json +1 -1
@@ -1 +1 @@
1
- import o from"chalk";import t from"inquirer";import{i18n as n}from"./i18n.js";import{canPrompt as e,hasExplicitYes as r,shouldAutoConfirm as i}from"./runtime-options.js";import{toolManager as s}from"./tool-manager.js";import{getAdapter as a}from"./tools/registry.js";import{upgradeTool as l}from"./tool-upgrade.js";import{appsForTools as p,upgradeApp as c}from"./app-update.js";import{logger as f}from"../utils/logger.js";async function u(o){const{ok:n}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return n}export async function runPendingElevations(t){const r=e();for(const e of t){const t=a(e)?.pendingElevation?.();if(!t)continue;if(!(i()||r&&await u(t.prompt)))continue;const s=a(e)?.displayName??e;console.log(o.gray(" "+n.t("setup.elevation_running"))),console.log(t.run()?o.green(" √ "+n.t("setup.elevation_done",{tool:s})):o.yellow(" ! "+n.t("setup.elevation_failed",{tool:s})))}}export async function runFollowUps(t){const n=e();for(const e of t){let t;try{t=await(a(e)?.followUp?.())}catch(o){f.logError(`postApplyPrompts.followUp(${e})`,o);continue}if(t)if("run"in t&&(r()||n))if(r()||await u(t.prompt))for(const n of await t.run())console.log("action"===n.kind?o.yellow(" ! "+n.text):o.green(" √ "+n.text));else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,i={}){const m=new Set;for(const o of i.apps?p(t):[])try{const t=await c(o,{install:i.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&m.add(o)}catch(t){f.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const n of t){const t=await(a(n)?.prepareRuntime?.())??[];for(const n of t)console.log("action"===n.kind?o.yellow(" ! "+n.text):o.green(" √ "+n.text))}await runPendingElevations(t),await runFollowUps(t);const g=e(),d=r(),y=g||d?t.filter(o=>a(o)?.installSpec&&s.outdatedVersion(o)):[];if(y.length>0){const o=y.map(o=>a(o)?.displayName??o).join("、");if(d||await u(n.t("setup.offer_upgrade",{tools:o})))for(const o of y)await l(o)}for(const e of t){const t=a(e);if(m.has(e)||!t?.runningApp?.isRunning())continue;if(d||!g){console.log(o.yellow(" ! "+n.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await u(n.t("setup.offer_restart",{tool:t.displayName})))continue;const r=t.runningApp.restart();console.log(r?o.green(" √ "+n.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+n.t("setup.restart_failed",{tool:t.displayName})))}}
1
+ import o from"chalk";import t from"inquirer";import{i18n as e}from"./i18n.js";import{canPrompt as n,hasExplicitYes as r}from"./runtime-options.js";import{flushTelemetry as l,track as i}from"./telemetry.js";import{toolManager as a}from"./tool-manager.js";import{getAdapter as s}from"./tools/registry.js";import{upgradeTool as p}from"./tool-upgrade.js";import{appsForTools as c,upgradeApp as f}from"./app-update.js";import{logger as u}from"../utils/logger.js";async function m(o){const{ok:e}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return e}export async function runPendingElevations(t){const a=n(),p=r();for(const n of t){const t=s(n)?.pendingElevation?.();if(!t)continue;const r=s(n)?.displayName??n;if(!p&&!a){console.log(o.yellow(" ! "+e.t("setup.elevation_skipped",{tool:r}))),i("elevate-registry","skip",{detail:{tool:n,reason:"no_terminal"}});continue}if(!p&&!await m(t.prompt)){i("elevate-registry","cancel",{detail:{tool:n,reason:"declined"}});continue}console.log(o.gray(" "+e.t("setup.elevation_running")));const c=Date.now();i("elevate-registry","start",{detail:{tool:n,asked:!p}}),await l();const f=t.run();i("elevate-registry",f?"ok":"fail",{duration_ms:Date.now()-c,detail:{tool:n,asked:!p}}),console.log(f?o.green(" √ "+e.t("setup.elevation_done",{tool:r})):o.yellow(" ! "+e.t("setup.elevation_failed",{tool:r})))}}export async function runFollowUps(t){const e=n();for(const n of t){let t,l;try{t=await(s(n)?.followUp?.())}catch(o){u.logError(`postApplyPrompts.followUp(${n})`,o);continue}if(t)if("run"in t&&(r()||e))if(r()||await m(t.prompt)){try{l=await t.run()}catch(e){u.logError(`postApplyPrompts.followUp.run(${n})`,e),i(`follow-up:${n}`,"fail",{error:e}),console.log(o.yellow(" ! "+t.hint));continue}for(const t of l)console.log("action"===t.kind?o.yellow(" ! "+t.text):o.green(" √ "+t.text))}else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,l={}){const i=new Set;for(const o of l.apps?c(t):[])try{const t=await f(o,{install:l.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&i.add(o)}catch(t){u.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const e of t){const t=await(s(e)?.prepareRuntime?.())??[];for(const e of t)console.log("action"===e.kind?o.yellow(" ! "+e.text):o.green(" √ "+e.text))}await runPendingElevations(t),await runFollowUps(t);const g=n(),d=r(),y=g||d?t.filter(o=>s(o)?.installSpec&&a.outdatedVersion(o)):[];if(y.length>0){const o=y.map(o=>s(o)?.displayName??o).join("、");if(d||await m(e.t("setup.offer_upgrade",{tools:o})))for(const o of y)await p(o)}for(const n of t){const t=s(n);if(i.has(n)||!t?.runningApp?.isRunning())continue;if(d||!g){console.log(o.yellow(" ! "+e.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await m(e.t("setup.offer_restart",{tool:t.displayName})))continue;const r=t.runningApp.restart();console.log(r?o.green(" √ "+e.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+e.t("setup.restart_failed",{tool:t.displayName})))}}
@@ -0,0 +1,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>;
@@ -0,0 +1 @@
1
+ import{spawnSync as e}from"child_process";import{accessSync as t,constants as r,existsSync as o,readdirSync as n,readFileSync as s,statSync as i}from"fs";import{delimiter as c,dirname as l,join as a}from"path";import{CLI_NAME as p}from"./brand.js";import{configManager as u}from"./config.js";import{savedTraces as m}from"./install-script.js";import{powerShellEnv as d}from"./powershell-env.js";import{maskSecrets as f}from"./telemetry.js";import{windowsSecurityProducts as h}from"./windows-security.js";function $(e){try{return e()}catch(e){return{error:f(e instanceof Error?e.message:String(e)).slice(0,200)}}}function g(e){const t="win32"===process.platform?["",".exe",".cmd",".bat"]:[""];for(const r of(process.env.PATH??process.env.Path??"").split(c))if(r)for(const o of t){const t=a(r.replace(/^"|"$/g,""),e+o);try{if(i(t).isFile())return t}catch{}}return null}function w(t,r){const o=e(t,r,{encoding:"utf-8",timeout:8e3,windowsHide:!0,shell:"win32"===process.platform&&!/\.exe$/i.test(t),.../powershell(\.exe)?$/i.test(t)?{env:d()}:{}});return String(o.stdout??"").trim()}function y(e){let n=e;for(;n&&!o(n);){const e=l(n);if(e===n)return!1;n=e}try{return t(n,r.W_OK),!0}catch{return!1}}function x(){const e=g("npm"),t=e&&w(e,["prefix","-g"]).split(/\r?\n/).pop()?.trim()||null;return{node:f(process.execPath),node_on_path:f(g("node")??""),version:process.version,npm:e?f(e):null,npm_prefix:t?f(t):null,npm_prefix_writable:t?y(t):null}}function v(){const e="win32"===process.platform?["powershell","pwsh","cmd","bash","git","curl"]:["sh","bash","zsh","fish","git","curl"];return Object.fromEntries(e.map(e=>[e,g(e)?f(g(e)):null]))}function _(){const e=u.getConfigDir(),t=(t,r)=>{const n=a(e,t);return o(n)?f(s(n,"utf-8")).split(/\r?\n/).filter(Boolean).slice(-r):null},r=t=>{const r=a(e,t);return o(r)?n(r).slice(0,30).map(e=>{const t=i(a(r,e));return`${e} ${t.isDirectory()?"dir":t.size}`}):null};return{progress:t("install-progress.txt",60),avoid:t("install-avoid.txt",20),traces:m(),self_update:t("update-state.json",20),node_migration:o(a(e,"node-migration.json")),downloads:r("downloads"),install_scripts:r("install-scripts")}}function E(){const e=w("powershell.exe",["-NoProfile","-NonInteractive","-Command",["[Console]::OutputEncoding = [Text.Encoding]::UTF8","$out = @{}",'try { $d = Get-MpComputerStatus -ErrorAction Stop; $out.defender = @{ mode = "$($d.AMRunningMode)"; realtime = [bool]$d.RealTimeProtectionEnabled } } catch { $out.defender = $null }',"try { $out.elevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch {}",'try { $out.execution_policy = @(Get-ExecutionPolicy -List | ForEach-Object { "$($_.Scope)=$($_.ExecutionPolicy)" }) } catch {}',`$out.crashes = @(Get-WinEvent -FilterHashtable @{ LogName = 'Application'; ProviderName = @('Application Error', 'Windows Error Reporting', '.NET Runtime'); StartTime = (Get-Date).AddDays(-2) } -MaxEvents 200 -ErrorAction SilentlyContinue | Where-Object { "$($_.Message)" -match 'powershell|pwsh|node\\.exe|npm|git|bash\\.exe|cmd\\.exe|conhost|fnm|claude|codex|grok|agy|${p}' } | Select-Object -First 8 | ForEach-Object { $m = ("$($_.Message)" -replace '\\s+', ' '); "$($_.TimeCreated.ToUniversalTime().ToString('s'))Z $($_.ProviderName) $($_.Id): " + $m.Substring(0, [Math]::Min(220, $m.Length)) })`,"$out | ConvertTo-Json -Depth 4 -Compress"].join("; ")]),t=JSON.parse(e||"{}");return Array.isArray(t.crashes)&&(t.crashes=t.crashes.map(e=>f(String(e)))),t}export function systemReport(){return{platform:`${process.platform} ${process.arch}`,security:$(()=>h()),path:$(()=>(process.env.PATH??process.env.Path??"").split(c).filter(Boolean).slice(0,80).map(e=>f(e))),node:$(x),shells:$(v),installer:$(_),..."win32"===process.platform?{windows:$(E)}:{}}}
@@ -65,6 +65,16 @@ export declare function flushTelemetry(timeoutMs?: number): Promise<void>;
65
65
  * Recorded as the command's failure, typed `crash`, with the first stack frame, and sent before the process goes.
66
66
  */
67
67
  export declare function reportCrash(error: unknown, timeoutMs?: number): Promise<void>;
68
+ /** The command has reported its start and not yet its end. */
69
+ export declare function commandInProgress(): boolean;
70
+ /**
71
+ * The process is ending on a signal (Ctrl+C outside a prompt, a closed terminal window, `kill`): none of the
72
+ * command's own handlers or `finally` blocks run, so until now such a run left a start and nothing else.
73
+ * Records the command's end as `cancel` with the signal and the step it was in, and sends what is queued
74
+ * (at most `timeoutMs`). Nothing is recorded when the command wasn't tracked (help, version) or has already
75
+ * reported its end.
76
+ */
77
+ export declare function reportSignal(signal: string, exitCode: number, timeoutMs?: number): Promise<void>;
68
78
  /**
69
79
  * Uploads a diagnostic report (the user asked for it, so `<PREFIX>_TELEMETRY=0` doesn't apply);
70
80
  * resolves to the code support looks it up by, or null when it didn't go through.
@@ -1 +1 @@
1
- import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as o}from"os";import{format as n,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as u}from"./client-config.js";import{configManager as p}from"./config.js";import{gatewayAddresses as f}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as d,REPORT_PATH as m,TELEMETRY_PATH as h}from"./gateway-protocol.js";const g=e();let y="wizard",w=[];const T=new Set;let k=null,x=E;export function telemetryEnabled(){if(process.env.VITEST&&!$)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let S,$=!1;export function setTelemetrySenderForTests(e){x=e??E,$=null!==e,w=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${o()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[d]:u()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const o=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([p.getBaseUrl(),...f().map(e=>e.url)].map(e=>new URL(e).host)).has(o.host)){const o=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))o.has(e)||o.set(e,t);return e(t,{...r,headers:o})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return T.size>0}function _(){return{install_id:u(),cli_version:l(),brand:a().id,os:process.platform,os_release:o(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const o=new Set([t,t.replace(/\\/g,"/")]);let n=e;for(const e of o)n=n.split(e).join("~");return n}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}let b=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(S=t)}export function lastFailureReason(){return S}export function watchConsoleErrors(){if(b)return;b=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(n(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}export function track(e,t,r={}){if(!telemetryEnabled())return;const o=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:g,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...o?{error:o}:{},...r.detail?{detail:r.detail}:{}}),"start"===t?z():k||(k=setTimeout(z,500),k.unref())}export async function trackStep(e,t,r){const o=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-o}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-o,error:t}),t}}function z(){if(k&&(clearTimeout(k),k=null),0===w.length)return;const e=w.splice(0,50),t=x(h,{..._(),events:e},3e3).then(()=>{},()=>{}).finally(()=>T.delete(t));T.add(t),w.length>0&&z()}export async function flushTelemetry(e=1500){z(),0!==T.size&&await Promise.race([Promise.allSettled([...T]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export async function uploadReport(e){try{const t=await x(m,{..._(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function E(e,t,r){const o=p.getApiKey()?.trim(),n=await fetch(new URL(e,p.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json().catch(()=>null)}
1
+ import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as o}from"os";import{format as n,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as u}from"./client-config.js";import{configManager as m}from"./config.js";import{gatewayAddresses as p}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as d,REPORT_PATH as f,TELEMETRY_PATH as g}from"./gateway-protocol.js";const h=e();let y="wizard",w=[];const x=new Set;let T=null,k=H;export function telemetryEnabled(){if(process.env.VITEST&&!_)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let S,_=!1;export function setTelemetrySenderForTests(e){k=e??H,_=null!==e,w=[],z=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${o()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[d]:u()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const o=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([m.getBaseUrl(),...p().map(e=>e.url)].map(e=>new URL(e).host)).has(o.host)){const o=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))o.has(e)||o.set(e,t);return e(t,{...r,headers:o})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return x.size>0}function $(){return{install_id:u(),cli_version:l(),brand:a().id,os:process.platform,os_release:o(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const o=new Set([t,t.replace(/\\/g,"/")]);let n=e;for(const e of o)n=n.split(e).join("~");return n}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}let b=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(S=t)}export function lastFailureReason(){return S}export function watchConsoleErrors(){if(b)return;b=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(n(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}let z=[],E=0;export function track(e,t,r={}){if("start"===t)z.push(e),"command"===e&&(E=Date.now());else{const t=z.lastIndexOf(e);t>=0&&z.splice(t,1)}if(!telemetryEnabled())return;const o=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:h,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...o?{error:o}:{},...r.detail?{detail:r.detail}:{}}),"start"===t?v():T||(T=setTimeout(v,500),T.unref())}export async function trackStep(e,t,r){const o=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-o}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-o,error:t}),t}}function v(){if(T&&(clearTimeout(T),T=null),0===w.length)return;const e=w.splice(0,50),t=k(g,{...$(),events:e},3e3).then(()=>{},()=>{}).finally(()=>x.delete(t));x.add(t),w.length>0&&v()}export async function flushTelemetry(e=1500){v(),0!==x.size&&await Promise.race([Promise.allSettled([...x]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export function commandInProgress(){return z.includes("command")}export async function reportSignal(e,t,r=1500){if(commandInProgress()){const r=z.filter(e=>"command"!==e).pop();track("command","cancel",{duration_ms:Date.now()-E,detail:{signal:e,exit_code:t,...r?{during:r}:{}}})}await flushTelemetry(r)}export async function uploadReport(e){try{const t=await k(f,{...$(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function H(e,t,r){const o=m.getApiKey()?.trim(),n=await fetch(new URL(e,m.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json().catch(()=>null)}
@@ -48,6 +48,8 @@ export declare class ToolManager {
48
48
  * Returns the directory when it was added.
49
49
  */
50
50
  ensureNativeOnPath(toolName: string): string | null;
51
+ /** Puts a directory on PATH for this process and, on Windows, for new terminals; false when it couldn't. */
52
+ private addToPath;
51
53
  installTool(toolName: string): Promise<void>;
52
54
  private installToolNow;
53
55
  getToolConfig(toolName: string): any;
@@ -1 +1 @@
1
- import{execSync as o,spawnSync as t}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as g}from"./tools/backup.js";import{existsSync as h,rmSync as w}from"fs";import{dirname as y,join as P}from"path";import{toolHome as $}from"./tools/types.js";import{stringWidth as v}from"../utils/string-width.js";import{resolveModelCatalog as k}from"./model-catalog.js";import{compareVersions as T,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{failureContext as M,lastCommandExit as U,lastCommandOutput as b,mirrorInstall as x}from"./tool-upgrade.js";import{upgradeApp as I}from"./app-update.js";import{CLI_NAME as R}from"./brand.js";import{track as F,trackStep as L}from"./telemetry.js";import{addUserPathDir as V,broadcastEnvChange as D}from"./windows-env.js";export{T as compareVersions};function z(o){const t=u[o];return{name:t.name,command:t.command,installCommand:t.installCommand,configPath:t.configPath,displayName:t.displayName,...t.hidden?{hidden:!0}:{},...t.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(o=>[o,z(o)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(o){if(!SUPPORTED_TOOLS[o])return!1;const t=d(o);if(t?.isInstalled)try{return t.isInstalled()}catch{return!1}return this.isOnPath(o)||null!==this.nativeLauncher(o)}isOnPath(t){const n=SUPPORTED_TOOLS[t];if(!n)return!1;try{const t="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return o(t,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(o){const t=d(o),n=t?.installSpec?.native?.binDir;if(!t||!n)return null;const e="win32"===process.platform?`${t.command}.exe`:t.command,r=P($(),...n,e);return h(r)?r:null}ensureNativeOnPath(o){if("win32"!==process.platform||this.isOnPath(o))return null;const t=this.nativeLauncher(o);if(!t)return null;const n=y(t);try{if(!V(n))return null}catch(t){return a.logError(`ensureNativeOnPath: ${o}`,t),null}return D(),process.env.Path=`${process.env.Path??""};${n}`,n}async installTool(o){return L(`install:${o}`,()=>this.installToolNow(o))}async installToolNow(t){const a=SUPPORTED_TOOLS[t];if(!a)throw new Error(`Unknown tool: ${t}`);const s=d(t)?.appInstaller;if(s&&!s.blocker()){const o=await I(t,{install:!0});if("failed"===o.result||"unavailable"===o.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(t)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const o=S(c);if(await x(c)){if(O(),this.isToolInstalled(t))return void console.log(r.green("√ "+n.t("wizard.tool_installed")));F(`install-script:${c.command}`,"fail",{error:b()||"(no output)",detail:{reason:"not_found_after_ok",...U(),...M()}})}throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:o}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return o(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(o){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${o?.message??""}${o?.stderr??""}`)&&243!==o?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${o}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(t))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);try{return t.getConfig()}catch(t){return a.warn(`Failed to read config for ${o}:`,t),a.logError(`ToolManager.getToolConfig(${o})`,t),null}}updateToolConfig(o,t){const n=d(o);if(!n)throw new Error(`Unknown tool: ${o}`);if(!n.updateConfig)throw new Error(`Tool ${o} does not support raw config updates`);n.updateConfig(t)}forceResetConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);const n=t.forceResetPaths?t.forceResetPaths():this.backupPathsFor(t),e=[];for(const o of n)h(o)&&(m(o),w(o,{force:!0}),e.push(o));return e}loadPrivateConfig(o,t,n,e,r={}){const i=d(o);if(!i)throw new Error(`Unknown tool: ${o}`);r.force&&this.forceResetConfig(o),i.loadPrivateConfig({apiKey:t,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(o),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(o,t,n,e={}){const r=this.installedVersion(o);return L(`apply:${o}`,()=>this.applyPrivateConfigNow(o,t,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(o,t,n,e){const r=d(o);if(!r)throw new Error(`Unknown tool: ${o}`);const i=r.wantsModelCatalog?await k(t):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(o,t,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(o,t,n,i):this.loadPrivateConfig(o,t,n)}applyNotes(o){const t=d(o);if(!t)return[];const e=[];try{t.applyNotes&&e.push(...t.applyNotes())}catch(t){a.logError(`ToolManager.applyNotes(${o})`,t)}const r=this.outdatedVersion(o);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:t.installSpec?`${R} upgrade ${o}`:t.upgradeCommand||t.installCommand})});for(const o of t.upgradeHints?.(r.min)??[])e.push({kind:"action",text:o})}const i=t.installSpec?E(t.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:o})}),e}printApplied(o,t=16){const n=SUPPORTED_TOOLS[o]?.displayName??o,e=this.applyNotes(o);for(const o of e.filter(o=>"detail"===o.kind))a.record(`${n}: ${o.text}`);const i=e.filter(o=>"summary"===o.kind).map(o=>o.text).join(";"),l=" ".repeat(Math.max(1,t-v(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const o of e.filter(o=>"action"===o.kind))console.log(r.yellow(" ! "+o.text))}installedVersion(o){const n=d(o);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(t){return a.logError(`ToolManager.installedVersion(${o})`,t),null}if(n.isInstalled)return null;try{const o={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?t(`${n.command} --version`,{...o,shell:!0}):t(n.command,["--version"],o)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(o){const t=C(o);if(!t)return null;const n=this.installedVersion(o);return n&&T(n,t)<0?{current:n,min:t}:null}unloadPrivateConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);try{t.unloadPrivateConfig({savedKeys:c()}),F(`remove:${o}`,"ok")}catch(t){throw F(`remove:${o}`,"fail",{error:t}),t}let e=[];try{e=t.unloadNotes?.()??[]}catch(t){a.logError(`ToolManager.unloadNotes(${o})`,t)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:t.displayName})}]}async clearPinnedModels(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);if(s.setToolModel(o,null),!t.clearPinnedModels)return[];const n=s.getApiKeyForTool(o),e=t.wantsModelCatalog&&n?await k(n):null;return t.clearPinnedModels(e??void 0)}supportsClearPinnedModels(o){return Boolean(d(o)?.clearPinnedModels)}holdsOurConfig(o){const t=d(o);if(!t)return!1;const n=c();return t.holdsOurConfig?t.holdsOurConfig(n):Boolean(t.detectCurrentConfig().apiKey)}detectCurrentConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return t.detectCurrentConfig()}backupPathsFor(o){return o.backupPaths?o.backupPaths():[o.configPath]}listToolBackups(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return this.backupPathsFor(t).map(o=>({file:o,backups:f(o)}))}restorePrivateConfig(o){const t=d(o);if(!t)throw new Error(`Unknown tool: ${o}`);return this.backupPathsFor(t).map(o=>({file:o,result:g(o)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(o=>this.isToolInstalled(o))}getSupportedTools(){return p().filter(o=>!o.hidden).map(o=>z(o.name))}isGitInstalled(){try{const t="win32"===process.platform?"where git":"which git";return o(t,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
1
+ import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as k,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{k as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=S(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=C(t);if(!o)return null;const n=this.installedVersion(t);return n&&k(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
@@ -1,4 +1,5 @@
1
1
  import { type ToolInstallSpec } from './tools/tool-installs.js';
2
+ import { type MissingReason } from './install-script.js';
2
3
  /** How the last runCommand ended (for the support events and the fallback message). */
3
4
  export type RunOutcome = 'ok' | 'fail' | 'timeout' | 'stalled';
4
5
  /** How the last command's process ended: its exit code, the signal that ended it, or why it couldn't start. */
@@ -21,6 +22,11 @@ export interface RunLimits {
21
22
  /** Extra environment variables for the command (install scripts' NODE_INSTALL_FORCE …). */
22
23
  env?: Record<string, string>;
23
24
  }
25
+ /**
26
+ * The last command was ended by Ctrl+C. This process is no longer killed along with its child (see signals.ts),
27
+ * so a chain of fallbacks (vendor updater → mirror → npm) has to stop here instead of trying the next source.
28
+ */
29
+ export declare function lastCommandInterrupted(): boolean;
24
30
  /**
25
31
  * Runs a command with its output passed through to the terminal, stopping it once it goes quiet
26
32
  * for `idleMs`: a slow network keeps printing download progress and gets all the time it needs,
@@ -29,13 +35,26 @@ export interface RunLimits {
29
35
  export declare function runWatched(command: string, args: string[], limits: RunLimits): Promise<RunOutcome>;
30
36
  /** Tests replace the process runner. */
31
37
  export declare function setUpgradeRunnerForTests(fake: (command: string, args: string[], limits?: RunLimits) => boolean | RunOutcome | Promise<boolean | RunOutcome>): void;
38
+ /** How to tell whether the tool is there after its script ran, and how to put its directory on PATH. */
39
+ export interface InstallCheck {
40
+ installed(): boolean;
41
+ /** Where this tool's installs go (the vendor layout), for scripts that keep no step records. */
42
+ expectedPaths: string[];
43
+ /** Adds a directory to PATH (this process and new terminals); false when it couldn't. */
44
+ addToPath?(dir: string): boolean;
45
+ }
46
+ export declare function lastInstallMissing(): {
47
+ reason: MissingReason;
48
+ path?: string;
49
+ } | undefined;
32
50
  /**
33
51
  * Fresh install / last-resort fallback: our install script when the tool has one, else npm
34
52
  * from npmmirror. A script that fails or stalls falls back to npm when the tool is on npm
35
53
  * (it reaches npmmirror through npm's own proxy settings, which often work where
36
- * PowerShell / curl don't).
54
+ * PowerShell / curl don't). With `check`, a script that reports success without the tool being
55
+ * there counts as failed, and the event says which of the three ways that happened.
37
56
  */
38
- export declare function mirrorInstall(spec: ToolInstallSpec): Promise<boolean>;
57
+ export declare function mirrorInstall(spec: ToolInstallSpec, check?: InstallCheck): Promise<boolean>;
39
58
  /** What else a failed install's event carries: the security software on Windows (it ends installers silently). */
40
59
  export declare function failureContext(): Record<string, unknown>;
41
60
  /**
@@ -1 +1 @@
1
- import{spawn as t,spawnSync as e}from"child_process";import{rmSync as o}from"fs";import{join as r}from"path";import n from"chalk";import i from"inquirer";import{i18n as s}from"./i18n.js";import{logger as a}from"../utils/logger.js";import{compareVersions as l,getToolMinVersion as c}from"./model-registry.js";import{getAdapter as p}from"./tools/registry.js";import{findInstalls as u,findInstallsIncludingNative as m,forgetInstalls as d,installLabel as g,npmMirrorInstallCommand as f,npmMirrorVersion as w,npmUninstallCommand as h}from"./tools/tool-installs.js";import{toolHome as y}from"./tools/types.js";import{isJsonMode as v,isNonInteractive as _,shouldAutoConfirm as k}from"./runtime-options.js";import{maskSecrets as x,track as b}from"./telemetry.js";import{windowsSecurityProducts as $}from"./windows-security.js";import{isWindowsPowerShell as j,powerShellEnv as T}from"./powershell-env.js";let E="ok",C={};export function lastCommandExit(){return C}let M="";const S=t=>{M=(M+t.toString("utf-8")).slice(-3e3)};export function outputTail(t){return t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").split(/\r?\n/).map(t=>t.split("\r").pop().trimEnd()).filter(Boolean).join("\n").slice(-1500)}export function lastCommandOutput(){return outputTail(M)}let D=async(t,o,r={})=>(console.log(n.gray("$ ")+[t,...o].join(" ")),M="",C={},E=r.idleMs?await runWatched(t,o,r):function(t,o,r){const n=P(t)?e(I(t,o),{stdio:U(),shell:!0,timeout:r}):e(t,o,{stdio:U(),timeout:r,env:O(t)});return n.error&&a.logError(`upgrade: ${t}`,n.error),C={exit_code:n.status,signal:n.signal,...n.error?{spawn_error:String(n.error.message)}:{}},"ETIMEDOUT"===n.error?.code?"timeout":0===n.status?"ok":"fail"}(t,o,r.timeoutMs),"ok"===E);const P=t=>"win32"===process.platform&&!/\.exe$/i.test(t),O=t=>j(t)?T():process.env,I=(t,e)=>[t,...e].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),U=()=>["inherit",v()?2:"inherit","inherit"];export function runWatched(e,o,r){return new Promise(n=>{const i=r.env?{...O(e),...r.env}:O(e),s=P(e)?t(I(e,o),{stdio:["inherit","pipe","pipe"],shell:!0,env:i}):t(e,o,{stdio:["inherit","pipe","pipe"],env:i});let l;const c=t=>{l=t,s.kill()};let p;const u=()=>{clearTimeout(p),r.idleMs&&(p=setTimeout(()=>c("stalled"),r.idleMs))},m=r.timeoutMs?setTimeout(()=>c("timeout"),r.timeoutMs):void 0;u(),s.stdout?.on("data",t=>{(v()?process.stderr:process.stdout).write(t),S(t),u()}),s.stderr?.on("data",t=>{process.stderr.write(t),S(t),u()});const d=t=>{clearTimeout(p),clearTimeout(m),n(t)};s.on("error",t=>{a.logError(`upgrade: ${e}`,t),C={...C,spawn_error:String(t.message)},d(l??"fail")}),s.on("close",(t,e)=>{C={...C,exit_code:t,signal:e},l&&(v()?process.stderr:process.stdout).write("\n"),d(l??(0===t?"ok":"fail"))})})}export function setUpgradeRunnerForTests(t){D=async(e,o,r)=>{const n=await t(e,o,r);return E="string"==typeof n?n:n?"ok":"fail","ok"===E}}const A={ok:"install.script_failed_npm",fail:"install.script_failed_npm",stalled:"install.script_stalled_npm",timeout:"install.script_timeout_npm"};export async function mirrorInstall(t){if(!t.mirrorScript)return B(t);console.log(n.gray(s.t("install.downloading")));const e=`install-script:${t.command}`,o=Date.now();b(e,"start");const r={idleMs:18e4,timeoutMs:36e5},i="win32"===process.platform?await D("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${t.mirrorScript.ps1} -TimeoutSec 30 | iex`],r):await D("sh",["-c",`script=$(curl -fsSL --connect-timeout 15 --max-time 60 ${t.mirrorScript.sh}) && printf '%s\\n' "$script" | sh`],r),a=E;return b(e,"stalled"===a?"timeout":a,{duration_ms:Date.now()-o,detail:{..."stalled"===a||"timeout"===a?{reason:a}:{},...lastCommandExit(),..."ok"===a?{output:x(lastCommandOutput())}:{},..."ok"!==a?failureContext():{}},..."ok"!==a&&lastCommandOutput()?{error:lastCommandOutput()}:{}}),i||!t.npmPackage?i:(console.log(n.yellow(" ! "+s.t(A[a],{minutes:String(3)}))),b(e,"fallback"),B(t))}export function failureContext(){const t=$();return t.length?{security:t}:{}}async function B(t){const e=f(t,await w(t)),[o,...r]=e.split(" "),i=`install-npm:${t.command}`,a=Date.now();b(i,"start");const l=await D(o,r);return b(i,l?"ok":"fail",{duration_ms:Date.now()-a,detail:{...lastCommandExit(),...l?{}:failureContext()}}),l||"win32"===process.platform||console.log(n.yellow(" ! "+s.t("upgrade.npm_permission",{command:e}))),l}async function N(t,e){switch(e.kind){case"npm":t.npmPackage&&await D("npm",["uninstall","-g",t.npmPackage]);break;case"brew":t.brew&&await D("brew",["uninstall",t.brew]);break;case"native":try{o(e.path,{force:!0});for(const e of t.native?.dataDirs??[])o(r(y(),...e),{recursive:!0,force:!0})}catch(t){a.logError("upgrade: remove native copy",t)}break;default:return!1}return d(),!u(t).some(t=>t.path===e.path)}function W(t,e){switch(e.kind){case"npm":return h(t);case"brew":return`brew uninstall ${t.brew}`;case"native":return s.t("upgrade.delete_paths",{paths:[e.path,...(t.native?.dataDirs??[]).map(t=>r(y(),...t))].join("、")});default:return s.t("upgrade.delete_paths",{paths:e.path})}}export async function upgradeTool(t){const e=Date.now();b(`upgrade:${t}`,"start");try{const o=await async function(t){const e=p(t),o=e?.installSpec;if(!e||!o)throw new Error(s.t("upgrade.unsupported",{tool:t}));const r=e.displayName;d();const f=u(o);if(console.log(n.bold(`\n${r}`)),0===f.length)console.log(s.t("upgrade.not_installed_installing",{tool:r})),await mirrorInstall(o);else{const t=f[0];console.log(n.gray(" "+s.t("upgrade.current",{copy:g(t)})));const e=await async function(t,e){switch(e.kind){case"native":return D(e.path,t.native?.updateArgs??["update"],{timeoutMs:t.native?.updateTimeoutMs});case"npm":return B(t);case"brew":return!!t.brew&&D("brew",["upgrade",t.brew]);default:return!1}}(o,t);e||"other"!==t.kind?e||"npm"===t.kind||"native"===t.kind&&await async function(t){const e=t.native?.mirrorUpdate;if(!e)return!1;console.log(n.yellow(" ! "+s.t("upgrade.native_mirror_trying")));try{const{version:t,manifestVerified:o}=await e();return console.log(n.green(" √ "+s.t(o?"upgrade.native_mirror_done_verified":"upgrade.native_mirror_done",{version:t}))),!0}catch(t){return a.logError("upgrade: native mirror",t),console.log(n.yellow(" ! "+s.t("upgrade.native_mirror_failed",{reason:t instanceof Error?t.message:String(t)}))),!1}}(o)||(console.log(n.yellow(" ! "+s.t("upgrade.fallback_mirror"))),await mirrorInstall(o)):console.log(n.yellow(" ! "+s.t("upgrade.unknown_install",{path:t.path})))}d(),await async function(t,e){const o=u(t);if(o.length<2)return;const r=function(t){return t.reduce((t,e)=>e.version&&(!t.version||l(e.version,t.version)>0)?e:t)}(o),a=o.filter(t=>t!==r);console.log(n.yellow(" ! "+s.t("upgrade.duplicates",{tool:e,keep:g(r),others:a.map(g).join("、")})));let c=k();c||_()||!process.stdin.isTTY||(c=(await i.prompt([{type:"confirm",name:"remove",message:s.t("upgrade.confirm_remove"),default:!0}])).remove);for(const e of a)c&&await N(t,e)?console.log(n.green(" √ "+s.t("upgrade.removed",{copy:g(e)}))):console.log(n.yellow(" ! "+s.t("upgrade.remove_by_hand",{how:W(t,e)})))}(o,r),d();const w=m(o)[0];if(!w)return console.log(n.red(" × "+s.t("upgrade.still_missing",{tool:r}))),!1;w.onPath||console.log(n.gray(" "+s.t("components.new_terminal")));const h=c(t);if(h&&w.version&&l(w.version,h)<0){console.log(n.yellow(" ! "+s.t("upgrade.still_old",{copy:g(w),min:h})));for(const t of e.upgradeHints?.(h)??[])console.log(n.yellow(" ! "+t));return!1}return console.log(n.green(" √ "+s.t("upgrade.done",{copy:g(w)}))),!0}(t);return b(`upgrade:${t}`,o?"ok":"fail",{duration_ms:Date.now()-e}),o}catch(o){throw b(`upgrade:${t}`,"fail",{duration_ms:Date.now()-e,error:o}),o}}
1
+ import{spawn as t,spawnSync as e}from"child_process";import{rmSync as o}from"fs";import{dirname as r,join as n}from"path";import a from"chalk";import i from"inquirer";import{i18n as s}from"./i18n.js";import{logger as l}from"../utils/logger.js";import{compareVersions as p,getToolMinVersion as c}from"./model-registry.js";import{getAdapter as u}from"./tools/registry.js";import{findInstalls as m,findInstallsIncludingNative as d,forgetInstalls as g,installLabel as f,npmMirrorInstallCommand as w,npmMirrorVersion as h,npmUninstallCommand as _}from"./tools/tool-installs.js";import{toolHome as v}from"./tools/types.js";import{isJsonMode as y,isNonInteractive as k,shouldAutoConfirm as b}from"./runtime-options.js";import{flushTelemetry as x,maskHome as j,maskSecrets as T,track as C}from"./telemetry.js";import{windowsSecurityProducts as D}from"./windows-security.js";import{isWindowsPowerShell as $,powerShellEnv as E}from"./powershell-env.js";import{diagnoseMissing as M,runInstallScript as P,traceSummary as S}from"./install-script.js";import{endedByInterrupt as I}from"./signals.js";let O="ok",U={};export function lastCommandExit(){return U}let A="";const W=t=>{A=(A+t.toString("utf-8")).slice(-3e3)};export function outputTail(t){return t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").split(/\r?\n/).map(t=>t.split("\r").pop().trimEnd()).filter(Boolean).join("\n").slice(-1500)}export function lastCommandOutput(){return outputTail(A)}export function lastCommandInterrupted(){return I({status:U.exit_code,signal:U.signal})}let q=async(t,o,r={})=>(console.log(a.gray("$ ")+[t,...o].join(" ")),A="",U={},r.idleMs?O=await runWatched(t,o,r):(await x(1e3),O=function(t,o,r){const n=z(t)?e(F(t,o),{stdio:H(),shell:!0,timeout:r}):e(t,o,{stdio:H(),timeout:r,env:B(t)});return n.error&&l.logError(`upgrade: ${t}`,n.error),U={exit_code:n.status,signal:n.signal,...n.error?{spawn_error:String(n.error.message)}:{}},"ETIMEDOUT"===n.error?.code?"timeout":0===n.status?"ok":"fail"}(t,o,r.timeoutMs)),"ok"===O);const z=t=>"win32"===process.platform&&!/\.exe$/i.test(t),B=t=>$(t)?E():process.env,F=(t,e)=>[t,...e].map(t=>/\s/.test(t)?`"${t}"`:t).join(" "),H=()=>["inherit",y()?2:"inherit","inherit"];export function runWatched(e,o,r){return new Promise(n=>{const a=r.env?{...B(e),...r.env}:B(e),i=z(e)?t(F(e,o),{stdio:["inherit","pipe","pipe"],shell:!0,env:a}):t(e,o,{stdio:["inherit","pipe","pipe"],env:a});let s;const p=t=>{s=t,i.kill()};let c;const u=()=>{clearTimeout(c),r.idleMs&&(c=setTimeout(()=>p("stalled"),r.idleMs))},m=r.timeoutMs?setTimeout(()=>p("timeout"),r.timeoutMs):void 0;u(),i.stdout?.on("data",t=>{(y()?process.stderr:process.stdout).write(t),W(t),u()}),i.stderr?.on("data",t=>{process.stderr.write(t),W(t),u()});const d=t=>{clearTimeout(c),clearTimeout(m),n(t)};i.on("error",t=>{l.logError(`upgrade: ${e}`,t),U={...U,spawn_error:String(t.message)},d(s??"fail")}),i.on("close",(t,e)=>{U={...U,exit_code:t,signal:e},s&&(y()?process.stderr:process.stdout).write("\n"),d(s??(0===t?"ok":"fail"))})})}export function setUpgradeRunnerForTests(t){q=async(e,o,r)=>{const n=await t(e,o,r);return O="string"==typeof n?n:n?"ok":"fail","ok"===O}}const N={ok:"install.script_failed_npm",fail:"install.script_failed_npm",stalled:"install.script_stalled_npm",timeout:"install.script_timeout_npm"};let R;export function lastInstallMissing(){return R}export async function mirrorInstall(t,e){if(R=void 0,!t.mirrorScript)return V(t);console.log(a.gray(s.t("install.downloading")));const o=`install-script:${t.command}`,n=Date.now();C(o,"start");const i=await P({name:t.command,url:"win32"===process.platform?t.mirrorScript.ps1:t.mirrorScript.sh,limits:{idleMs:18e4,timeoutMs:36e5},output:lastCommandOutput,run:async(t,e,o)=>(await q(t,e,o),O)});let l,p=i.outcome;if("ok"===p&&e&&(g(),!e.installed())){const t=M(i.trace,e.expectedPaths);"not_on_path"===t.reason&&t.path&&e.addToPath?.(r(t.path))&&e.installed()?l=r(t.path):(R=t,p="fail")}const c="ok"===p;if(C(o,"stalled"===p?"timeout":p,{duration_ms:Date.now()-n,detail:{..."stalled"===p||"timeout"===p?{reason:p}:{},...R?{reason:R.reason,...R.path?{path:j(R.path)}:{}}:{},...l?{path_added:j(l)}:{},how:i.how,...i.fileProblem?{file_problem:i.fileProblem}:{},...S(i.trace),...lastCommandExit(),...c?{output:T(lastCommandOutput())}:{},...c?{}:failureContext()},...c?{}:{error:lastCommandOutput()||(R?"(no output)":void 0)}}),R&&console.log(a.yellow(" ! "+function(t,e){const o=D().join("、");switch(e.reason){case"removed_after_install":return s.t(o?"install.missing_removed_by":"install.missing_removed",{tool:t,path:e.path??"",security:o});case"not_on_path":return s.t("install.missing_not_on_path",{tool:t,path:e.path??""});case"not_downloaded":return s.t("install.missing_not_downloaded",{tool:t});default:return s.t("install.missing_unknown",{tool:t})}}(t.command,R))),c||!t.npmPackage||lastCommandInterrupted())return c;console.log(a.yellow(" ! "+s.t(N[i.outcome],{minutes:String(3)}))),C(o,"fallback");const u=await V(t);return u&&e&&(g(),e.installed()&&(R=void 0)),u&&!R}export function failureContext(){const t=D();return t.length?{security:t}:{}}async function V(t){const e=w(t,await h(t)),[o,...r]=e.split(" "),n=`install-npm:${t.command}`,i=Date.now();C(n,"start");const l=await q(o,r);return C(n,l?"ok":"fail",{duration_ms:Date.now()-i,detail:{...lastCommandExit(),...l?{}:failureContext()}}),l||"win32"===process.platform||console.log(a.yellow(" ! "+s.t("upgrade.npm_permission",{command:e}))),l}async function Y(t,e){switch(e.kind){case"npm":t.npmPackage&&await q("npm",["uninstall","-g",t.npmPackage]);break;case"brew":t.brew&&await q("brew",["uninstall",t.brew]);break;case"native":try{o(e.path,{force:!0});for(const e of t.native?.dataDirs??[])o(n(v(),...e),{recursive:!0,force:!0})}catch(t){l.logError("upgrade: remove native copy",t)}break;default:return!1}return g(),!m(t).some(t=>t.path===e.path)}function Z(t,e){switch(e.kind){case"npm":return _(t);case"brew":return`brew uninstall ${t.brew}`;case"native":return s.t("upgrade.delete_paths",{paths:[e.path,...(t.native?.dataDirs??[]).map(t=>n(v(),...t))].join("、")});default:return s.t("upgrade.delete_paths",{paths:e.path})}}export async function upgradeTool(t){const e=Date.now();C(`upgrade:${t}`,"start");try{const o=await async function(t){const e=u(t),o=e?.installSpec;if(!e||!o)throw new Error(s.t("upgrade.unsupported",{tool:t}));const r=e.displayName;g();const n=m(o);if(console.log(a.bold(`\n${r}`)),0===n.length)console.log(s.t("upgrade.not_installed_installing",{tool:r})),await mirrorInstall(o);else{const t=n[0];console.log(a.gray(" "+s.t("upgrade.current",{copy:f(t)})));const e=await async function(t,e){switch(e.kind){case"native":return q(e.path,t.native?.updateArgs??["update"],{timeoutMs:t.native?.updateTimeoutMs});case"npm":return V(t);case"brew":return!!t.brew&&q("brew",["upgrade",t.brew]);default:return!1}}(o,t);!e&&lastCommandInterrupted()||(e||"other"!==t.kind?e||"npm"===t.kind||"native"===t.kind&&await async function(t){const e=t.native?.mirrorUpdate;if(!e)return!1;console.log(a.yellow(" ! "+s.t("upgrade.native_mirror_trying")));const o=`native-mirror:${t.command}`,r=Date.now();C(o,"start");try{const{version:t,manifestVerified:n}=await e();return C(o,"ok",{duration_ms:Date.now()-r,detail:{version:t,manifest_verified:n}}),console.log(a.green(" √ "+s.t(n?"upgrade.native_mirror_done_verified":"upgrade.native_mirror_done",{version:t}))),!0}catch(t){return l.logError("upgrade: native mirror",t),C(o,"fail",{duration_ms:Date.now()-r,error:t,detail:failureContext()}),console.log(a.yellow(" ! "+s.t("upgrade.native_mirror_failed",{reason:t instanceof Error?t.message:String(t)}))),!1}}(o)||(console.log(a.yellow(" ! "+s.t("upgrade.fallback_mirror"))),await mirrorInstall(o)):console.log(a.yellow(" ! "+s.t("upgrade.unknown_install",{path:t.path}))))}g(),await async function(t,e){const o=m(t);if(o.length<2)return;const r=function(t){return t.reduce((t,e)=>e.version&&(!t.version||p(e.version,t.version)>0)?e:t)}(o),n=o.filter(t=>t!==r);console.log(a.yellow(" ! "+s.t("upgrade.duplicates",{tool:e,keep:f(r),others:n.map(f).join("、")})));let l=b();l||k()||!process.stdin.isTTY||(l=(await i.prompt([{type:"confirm",name:"remove",message:s.t("upgrade.confirm_remove"),default:!0}])).remove);for(const e of n)l&&await Y(t,e)?console.log(a.green(" √ "+s.t("upgrade.removed",{copy:f(e)}))):console.log(a.yellow(" ! "+s.t("upgrade.remove_by_hand",{how:Z(t,e)})))}(o,r),g();const w=d(o)[0];if(!w)return console.log(a.red(" × "+s.t("upgrade.still_missing",{tool:r}))),!1;w.onPath||console.log(a.gray(" "+s.t("components.new_terminal")));const h=c(t);if(h&&w.version&&p(w.version,h)<0){console.log(a.yellow(" ! "+s.t("upgrade.still_old",{copy:f(w),min:h})));for(const t of e.upgradeHints?.(h)??[])console.log(a.yellow(" ! "+t));return!1}return console.log(a.green(" √ "+s.t("upgrade.done",{copy:f(w)}))),!0}(t);return C(`upgrade:${t}`,o?"ok":"fail",{duration_ms:Date.now()-e}),o}catch(o){throw C(`upgrade:${t}`,"fail",{duration_ms:Date.now()-e,error:o}),o}}
@@ -3,6 +3,9 @@
3
3
  * over the target (rename is atomic on the same filesystem). A crash mid-write
4
4
  * leaves the original intact instead of a half-written config. Cleans up the
5
5
  * temp file on failure and rethrows.
6
+ *
7
+ * Without `mode` the file keeps the permission bits it had: the rename replaces the file, so a 0600 file
8
+ * holding a token would otherwise come back with the umask's default (readable by others).
6
9
  */
7
10
  export declare function atomicWriteFile(filePath: string, content: string, mode?: number): void;
8
11
  /** How many timestamped backups to keep per file before the oldest are pruned. */
@@ -26,6 +29,8 @@ export interface BackupEntry {
26
29
  mtimeMs: number;
27
30
  /** Within-millisecond sequence from `uniqueBackupPath` (0 when absent). */
28
31
  seq: number;
32
+ /** The time in the file name (ms), what snapshots are ordered by; 0 when it can't be read. */
33
+ timestampMs: number;
29
34
  }
30
35
  /**
31
36
  * List a file's snapshots, newest first. The filename timestamp is authoritative:
@@ -1 +1 @@
1
- import{existsSync as t,copyFileSync as r,readdirSync as e,statSync as o,unlinkSync as s,writeFileSync as c,renameSync as n,mkdirSync as a}from"fs";import{dirname as i,basename as u,join as m}from"path";import{logger as p}from"../../utils/logger.js";export function atomicWriteFile(r,e,o){const u=i(r);t(u)||a(u,{recursive:!0});const m=`${r}.tmp-${process.pid}-${Date.now()}`;try{c(m,e,void 0===o?"utf-8":{encoding:"utf-8",mode:o}),n(m,r)}catch(r){try{t(m)&&s(m)}catch{}throw r}}export const MAX_TOOL_BACKUPS=10;const f=".bak-";function h(r){const e=`${r}${f}${(new Date).toISOString().replace(/[:.]/g,"-")}`;let o=e,s=1;for(;t(o);)o=`${e}-${s++}`;return o}export function backupBeforeWrite(e,o=10){try{if(!t(e))return;r(e,h(e)),b(e,o)}catch(t){p.logError("backupBeforeWrite",t)}}function d(t){const r=t.match(/Z-(\d+)$/);return r?Number(r[1]):0}function l(t){const r=t.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z(?:-\d+)?$/);if(!r)return 0;const[,e,o,s,c,n,a,i]=r;return Date.UTC(Number(e),Number(o)-1,Number(s),Number(c),Number(n),Number(a),Number(i))}export function listBackups(t){const r=i(t),s=u(t)+f;try{return e(r).filter(t=>t.startsWith(s)).map(t=>{const e=m(r,t);return{path:e,name:t,mtimeMs:o(e).mtimeMs,seq:d(t),timestampMs:l(t)}}).sort((t,r)=>r.timestampMs-t.timestampMs||r.seq-t.seq||r.mtimeMs-t.mtimeMs)}catch{return[]}}export function restoreBackup(e,o){const s=o?listBackups(e).find(t=>t.path===o||t.name===o)?.path:listBackups(e)[0]?.path;if(!s||!t(s))return{restored:!1,reason:"no_backup"};let c;if(t(e)){const t=h(e);try{r(e,t),c=u(t)}catch(t){p.logError("restoreBackup.snapshot",t)}}return r(s,e),b(e,10),{restored:!0,from:u(s),snapshot:c}}function b(t,r){for(const e of listBackups(t).slice(Math.max(0,r)))try{s(e.path)}catch(t){p.logError("backupBeforeWrite.rotate",t)}}
1
+ import{chmodSync as t,existsSync as r,copyFileSync as e,readdirSync as o,statSync as s,unlinkSync as c,writeFileSync as n,renameSync as i,mkdirSync as a}from"fs";import{dirname as m,basename as u,join as p}from"path";import{logger as f}from"../../utils/logger.js";import{processAlive as h}from"../../utils/process-alive.js";const d=".tmp-";export function atomicWriteFile(e,f,l){const b=m(e);r(b)||a(b,{recursive:!0}),function(t){try{const r=m(t),e=u(t)+d;for(const t of o(r)){if(!t.startsWith(e))continue;const o=/^(\d+)-\d+$/.exec(t.slice(e.length))?.[1];o&&!h(Number(o))&&c(p(r,t))}}catch{}}(e);let k=l;if(void 0===k)try{k=511&s(e).mode}catch{}const $=`${e}${d}${process.pid}-${Date.now()}`;try{n($,f,void 0===k?"utf-8":{encoding:"utf-8",mode:k}),void 0===l&&void 0!==k&&"win32"!==process.platform&&t($,k),i($,e)}catch(t){try{r($)&&c($)}catch{}throw t}}export const MAX_TOOL_BACKUPS=10;const l=".bak-";function b(t){const e=Date.now(),o=listBackups(t)[0]?.timestampMs??0,s=`${t}${l}${c=o>e?o+1:e,new Date(c).toISOString().replace(/[:.]/g,"-")}`;var c;let n=s,i=1;for(;r(n);)n=`${s}-${i++}`;return n}export function backupBeforeWrite(t,o=10){try{if(!r(t))return;e(t,b(t)),B(t,o)}catch(t){f.logError("backupBeforeWrite",t)}}function k(t){const r=t.match(/Z-(\d+)$/);return r?Number(r[1]):0}function $(t){const r=t.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z(?:-\d+)?$/);if(!r)return 0;const[,e,o,s,c,n,i,a]=r;return Date.UTC(Number(e),Number(o)-1,Number(s),Number(c),Number(n),Number(i),Number(a))}export function listBackups(t){const r=m(t),e=u(t)+l;try{return o(r).filter(t=>t.startsWith(e)).map(t=>{const e=p(r,t);return{path:e,name:t,mtimeMs:s(e).mtimeMs,seq:k(t),timestampMs:$(t)}}).sort((t,r)=>r.timestampMs-t.timestampMs||r.seq-t.seq||r.mtimeMs-t.mtimeMs)}catch{return[]}}export function restoreBackup(t,o){const s=o?listBackups(t).find(t=>t.path===o||t.name===o)?.path:listBackups(t)[0]?.path;if(!s||!r(s))return{restored:!1,reason:"no_backup"};let c;if(r(t)){const r=b(t);try{e(t,r),c=u(r)}catch(t){f.logError("restoreBackup.snapshot",t)}}return e(s,t),B(t,10),{restored:!0,from:u(s),snapshot:c}}function B(t,r){for(const e of listBackups(t).slice(Math.max(0,r)))try{c(e.path)}catch(t){f.logError("backupBeforeWrite.rotate",t)}}
@@ -1 +1 @@
1
- import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as m,savedApiKeys as p}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as h,hasExplicitYes as v}from"../runtime-options.js";import{maskHome as C}from"../telemetry.js";import{spawnSync as j}from"child_process";import{existsSync as y,readFileSync as k}from"fs";import{detectManagedOverrides as A}from"./claude-managed.js";import{installOfficialPlugins as O}from"./claude-plugins.js";import{findInstalls as P,mirrorInstallCommand as S,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as w}from"../sessions/formats.js";const H=e(c(),".claude","settings.json"),L=e(c(),".claude.json");let R,U=null,E=()=>0===j("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(y(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(k(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function D(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(p())?null:e.trim():null}let B=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return h()&&!v()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:S(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:H,sessions:{format:N,files:()=>w(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){B=D(),n(H),n(L),R=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,R);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=P(claudeCodeAdapter.installSpec)[0]?.path??(y(s)?s:null);U=a?O(a):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(m.getBaseUrl()))},planNotes(){const e=[],t=D();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:C(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(H),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(H),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(H),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${C(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>C(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:C(e.location),vars:Object.keys(e.vars).join(", ")})}));return t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})}),o},decline(){}}},applyNotes(){const e=[];U?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(U.installed.length)})}),e.push({kind:"detail",text:U.installed.join(", ")})),"git"===U?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===U?.skipped||U?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),R&&R.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(R.length),vendors:l(R.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:R.map(e=>e.name||i(e.id)).join(", ")})),B&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:B})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:C(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:C(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===j("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of A())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[H,L],forceResetPaths:()=>[H]};
1
+ import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as p,savedApiKeys as m}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as v,hasExplicitYes as h}from"../runtime-options.js";import{maskHome as j}from"../telemetry.js";import{spawnSync as k}from"child_process";import{existsSync as C,readFileSync as y}from"fs";import{detectManagedOverrides as O}from"./claude-managed.js";import{installOfficialPlugins as A}from"./claude-plugins.js";import{findInstalls as P,mirrorInstallCommand as S,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as U}from"../sessions/formats.js";const w=e(c(),".claude","settings.json"),H=e(c(),".claude.json");let L,R=null,E=()=>0===k("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(C(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(y(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function B(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(m())?null:e.trim():null}let D=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return v()&&!h()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:S(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:w,sessions:{format:N,files:()=>U(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){D=B(),n(w),n(H),L=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,L);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=P(claudeCodeAdapter.installSpec)[0]?.path??(C(s)?s:null);R=a?A(a,{retry:Boolean(t.takeOver)}):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(p.getBaseUrl()))},planNotes(){const e=[],t=B();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:j(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(w),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(w),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(w),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${j(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>j(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})}));t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const e of t.notBackedUp)o.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})});return o},decline(){}}},applyNotes(){const e=[];R?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(R.installed.length)})}),e.push({kind:"detail",text:R.installed.join(", ")})),"git"===R?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===R?.skipped||"recent_failure"===R?.skipped||R?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),L&&L.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(L.length),vendors:l(L.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:L.map(e=>e.name||i(e.id)).join(", ")})),D&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:D})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:j(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const o of t.notBackedUp)e.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===k("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of O())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[w,H],forceResetPaths:()=>[w]};
@@ -29,6 +29,8 @@ export interface DesktopCliOptions {
29
29
  localVersionsDir?: string;
30
30
  /** Called before a download (not for a local copy), e.g. to tell the user why setup pauses. */
31
31
  onDownload?: (version: string) => void;
32
+ /** Called once before anything is copied or downloaded (not when the build is already in place). */
33
+ onStart?: (version: string, source: 'local' | 'mirror') => void;
32
34
  /** Writes the binary of `version` (a bundle: its `.tar.zst`) to the given path. Default: npmmirror for binaries; required for bundles. */
33
35
  download?: (version: string, outPath: string) => Promise<void>;
34
36
  }
@@ -39,6 +41,8 @@ export declare function setDesktopCliFetchForTests(fake: typeof fetch): void;
39
41
  export interface EnsureDesktopCliOptions {
40
42
  userDataDir: string;
41
43
  onDownload?: (version: string) => void;
44
+ /** Called once before anything is copied or downloaded. */
45
+ onStart?: (version: string, source: 'local' | 'mirror') => void;
42
46
  /** macOS: the installed app's version (on an old per-tool mirror repository it names the release carrying its bundle). */
43
47
  desktopVersion?: string | null;
44
48
  /** macOS: the brand's Claude Desktop download mirror (`installMirror.claudeDesktop`, see mirror-url.ts). */
@@ -1 +1 @@
1
- import{execFileSync as e}from"child_process";import{createHash as r}from"crypto";import{createReadStream as t,createWriteStream as s,existsSync as o,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as D}from"stream/promises";import*as v from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as x,nativePlatformKey as N}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as A}from"./desktop-process.js";import{toolHome as P}from"./types.js";import{mirrorFileUrl as L,withDownloadFallback as O}from"../mirror-url.js";import{powerShellEnv as E}from"../powershell-env.js";export function readDesktopCliPin(e,r,t=!1){const s=e.indexOf('claude-code-releases","sdkWrapperVersion"');if(s<0)return null;const o=e.lastIndexOf("JSON.parse('",s),n=e.indexOf("')",s);if(o<0||n<0)return null;try{const s=JSON.parse(e.subarray(o+12,n).toString("utf-8")),i="string"==typeof s.version?s.version:"",a=s.manifest?.platforms?.[r],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function j(){const r=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&o(r)){const e=n(r).filter(e=>/^app-\d+\.\d+\.\d+$/.test(e)).sort((e,r)=>r.localeCompare(e,void 0,{numeric:!0}));for(const t of e){const e=m(r,t,"resources","app.asar");if(o(e))return e}}try{const r=e("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${A.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:E()});for(const e of r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)){const r=m(e,"app","resources","app.asar");if(o(r))return r}}catch(e){y.logError("claude-desktop-cli.windowsAsarPath",e)}return null}function S(){if($("TEST_HOME")?.trim())return null;for(const e of["/usr/lib/claude-desktop","/opt/Claude"]){const r=m(e,"resources","app.asar");if(o(r))return r}return null}function F(){for(const e of["/Applications/Claude.app",m(P(),"Applications","Claude.app")]){const r=m(e,"Contents","Resources","app.asar");if(o(r))return r}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?j():"darwin"===process.platform?F():"linux"===process.platform?S():null}class T extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(e){super(),this.dest=e}_write(e,r,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,e]):e,this.drain().then(()=>t()).catch(t)}_final(e){this.remaining>0?e(new Error("archive ends inside an entry")):e()}target(e){const r=h(e);if(!r||d(r)||".."===r||r.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${e}`);return m(this.dest,r)}async closeFile(){const e=this.file;this.file=null,e&&await new Promise((r,t)=>e.end(e=>e?t(e):r()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const e=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(e.length),this.remaining-=e.length,this.collectingLongName?this.collectingLongName.push(e):this.file&&!this.file.write(e)&&await new Promise(e=>this.file.once("drain",()=>e())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const e=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),e.every(e=>0===e))continue;const r=(r,t)=>e.subarray(r,r+t).toString("utf-8").replace(/\0.*$/s,""),t=r(345,155);let o=t?`${t}/${r(0,100)}`:r(0,100);null!==this.longName&&(o=this.longName,this.longName=null);const n=parseInt(r(124,12).trim()||"0",8),i=511&parseInt(r(100,8).trim()||"644",8),a=r(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(o),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${o}`);{const e=this.target(o);await l(m(e,".."),{recursive:!0}),this.file=s(e,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(e){const s=readDesktopCliPin(e.asar,e.platformKey,e.bundle);if(!s)return{status:"skipped",reason:"unknown app layout"};if(e.bundle&&!e.download)return{status:"skipped",reason:"no bundle mirror"};const n=e.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(e.userDataDir,"claude-code",s.version),d=m(i,s.checksum.slice(0,12)),h=e.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(o(h)&&(await c(w,"utf-8")).trim()===s.checksum)return{status:"present",version:s.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${s.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(e.bundle){if(e.onDownload?.(s.version),await e.download(s.version,y),await async function(e,s,o){const n=r("sha256");if(await D(t(e),new b({write(e,r,t){n.update(e),t()}})),n.digest("hex")!==s)throw new Error("downloaded bundle does not match the app's checksum");const i=v.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await D(t(e),i(),new T(o))}(y,s.checksum,g),!o(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const r=e.localVersionsDir?m(e.localVersionsDir,s.version):null;if(r&&o(r))await a(r,g),n="local";else{e.onDownload?.(s.version);const r=e.download??((r,t)=>C(e.platformKey,r,t));await r(s.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,s.checksum),{status:"installed",version:s.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let K=(...e)=>fetch(...e);export function setDesktopCliFetchForTests(e){K=e}export async function ensureDesktopCli(e){const r=N();if(!r)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=j();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,localVersionsDir:x().versionsDir,onDownload:e.onDownload}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=F();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:o,desktopVersion:n}=e;return installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,bundle:!0,onDownload:e.onDownload,download:o&&n?(e,t)=>O(L(o,`claude-code-${e}-${r}.app.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,e=>async function(e,r){const t=await K(e,{signal:AbortSignal.timeout(9e5)});if(!t.ok||!t.body)throw new Error(`${e}: HTTP ${t.status}`);await D(g.fromWeb(t.body),s(r))}(e,t)):void 0})}if("linux"===process.platform){const t=S();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r.replace(/-musl$/,""),localVersionsDir:r.endsWith("-musl")?void 0:x().versionsDir,onDownload:e.onDownload}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
1
+ import{execFileSync as e}from"child_process";import{createHash as r}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{mirrorFileUrl as P,withDownloadFallback as L}from"../mirror-url.js";import{powerShellEnv as O}from"../powershell-env.js";export function readDesktopCliPin(e,r,t=!1){const o=e.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=e.lastIndexOf("JSON.parse('",o),n=e.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(e.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[r],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function E(){const r=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(r)){const e=n(r).filter(e=>/^app-\d+\.\d+\.\d+$/.test(e)).sort((e,r)=>r.localeCompare(e,void 0,{numeric:!0}));for(const t of e){const e=m(r,t,"resources","app.asar");if(s(e))return e}}try{const r=e("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:O()});for(const e of r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)){const r=m(e,"app","resources","app.asar");if(s(r))return r}}catch(e){y.logError("claude-desktop-cli.windowsAsarPath",e)}return null}function j(){if($("TEST_HOME")?.trim())return null;for(const e of["/usr/lib/claude-desktop","/opt/Claude"]){const r=m(e,"resources","app.asar");if(s(r))return r}return null}function F(){for(const e of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const r=m(e,"Contents","Resources","app.asar");if(s(r))return r}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?E():"darwin"===process.platform?F():"linux"===process.platform?j():null}class T extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(e){super(),this.dest=e}_write(e,r,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,e]):e,this.drain().then(()=>t()).catch(t)}_final(e){this.remaining>0?e(new Error("archive ends inside an entry")):e()}target(e){const r=h(e);if(!r||d(r)||".."===r||r.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${e}`);return m(this.dest,r)}async closeFile(){const e=this.file;this.file=null,e&&await new Promise((r,t)=>e.end(e=>e?t(e):r()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const e=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(e.length),this.remaining-=e.length,this.collectingLongName?this.collectingLongName.push(e):this.file&&!this.file.write(e)&&await new Promise(e=>this.file.once("drain",()=>e())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const e=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),e.every(e=>0===e))continue;const r=(r,t)=>e.subarray(r,r+t).toString("utf-8").replace(/\0.*$/s,""),t=r(345,155);let s=t?`${t}/${r(0,100)}`:r(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(r(124,12).trim()||"0",8),i=511&parseInt(r(100,8).trim()||"644",8),a=r(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(s),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${s}`);{const e=this.target(s);await l(m(e,".."),{recursive:!0}),this.file=o(e,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(e){const o=readDesktopCliPin(e.asar,e.platformKey,e.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(e.bundle&&!e.download)return{status:"skipped",reason:"no bundle mirror"};const n=e.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(e.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=e.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(s(h)&&(await c(w,"utf-8")).trim()===o.checksum)return{status:"present",version:o.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${o.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(e.bundle){if(e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version),await e.download(o.version,y),await async function(e,o,s){const n=r("sha256");if(await v(t(e),new b({write(e,r,t){n.update(e),t()}})),n.digest("hex")!==o)throw new Error("downloaded bundle does not match the app's checksum");const i=D.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await v(t(e),i(),new T(s))}(y,o.checksum,g),!s(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const r=e.localVersionsDir?m(e.localVersionsDir,o.version):null;if(r&&s(r))e.onStart?.(o.version,"local"),await a(r,g),n="local";else{e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version);const r=e.download??((r,t)=>C(e.platformKey,r,t));await r(o.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,o.checksum),{status:"installed",version:o.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let K=(...e)=>fetch(...e);export function setDesktopCliFetchForTests(e){K=e}export async function ensureDesktopCli(e){const r=x();if(!r)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=E();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,localVersionsDir:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=F();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=e;return installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,bundle:!0,onDownload:e.onDownload,onStart:e.onStart,download:s&&n?(e,t)=>L(P(s,`claude-code-${e}-${r}.app.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,e=>async function(e,r){const t=await K(e,{signal:AbortSignal.timeout(9e5)});if(!t.ok||!t.body)throw new Error(`${e}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(r))}(e,t)):void 0})}if("linux"===process.platform){const t=j();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r.replace(/-musl$/,""),localVersionsDir:r.endsWith("-musl")?void 0:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
@@ -1 +1 @@
1
- import{chmodSync as e,existsSync as t,mkdirSync as o,readdirSync as n,readFileSync as r,rmSync as s}from"fs";import{dirname as i}from"path";import{join as l}from"path";import{randomUUID as a}from"crypto";import{execFileSync as c}from"child_process";import{userInfo as d}from"os";import u from"chalk";import{logger as p}from"../../utils/logger.js";import{track as f}from"../telemetry.js";import{ensureDesktopCli as m,installedDesktopAsarPath as g}from"./claude-desktop-cli.js";import{i18n as y}from"../i18n.js";import{BRAND_NAME as h,brand as k,brandEnv as _,CLI_NAME as w}from"../brand.js";import{mirrorPageUrl as b}from"../mirror-url.js";import{backupBeforeWrite as D,atomicWriteFile as A}from"./backup.js";import{toolHome as C}from"./types.js";import{canRestartDesktop as v,desktopQuitRefused as E,isDesktopRunning as M,launchDesktop as O,quitDesktop as S,restartDesktop as x,WINDOWS_PACKAGE_FAMILIES as j}from"./desktop-process.js";import{desktopInstallBlocker as P,fetchLatestDesktopVersion as I,installedMacApp as L,installLatestDesktop as T}from"./claude-desktop-app.js";import{setUserRegistryElevated as $}from"./elevated-reg.js";import{UserActionNeeded as G}from"./types.js";import{savedApiKeys as N}from"../config.js";import{isOurGatewayUrl as U,noteWrittenGatewayUrl as K}from"../gateway-addresses.js";import{baseModelId as R,isClaudeModel as F}from"../model-catalog.js";import{getDefaultModels as B}from"../model-registry.js";import{claudeFormat as H,nestedClaudeProjectFiles as J}from"../sessions/formats.js";import{powerShellEnv as V}from"../powershell-env.js";const W=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const z=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const o=C(),n=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(o,"Library","Application Support","Claude-3p");case"win32":{const e=!n&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(o,"AppData","Local");return j.map(t=>l(e,"Packages",t,"LocalCache","Local","Claude-3p")).find(e=>t(e))??l(e,"Claude-3p")}default:{const e=!n&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(o,".config");return l(e,"Claude-3p")}}}const X=()=>l(claudeDesktopUserDataDir(),"configLibrary"),Z=()=>l(X(),"_meta.json"),Y=e=>l(X(),`${e}.json`),Q=()=>l(claudeDesktopUserDataDir(),"claude_desktop_config.json");function ee(e){if(!t(e))return null;const o=r(e,"utf-8");if(!o.trim())return null;try{const e=JSON.parse(o);return q(e)?e:null}catch(t){throw new Error(`Existing ${e} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}function te(n,r){const s=i(n);t(s)||o(s,{recursive:!0,mode:448}),D(n),A(n,JSON.stringify(r,null,2)+"\n");try{e(n,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function oe(){const e=ee(Z());if(!e)return null;const t=Array.isArray(e.entries)?e.entries.filter(e=>q(e)&&"string"==typeof e.id&&"string"==typeof e.name):[];return{...e,appliedId:"string"==typeof e.appliedId?e.appliedId:"",entries:t}}function ne(e){return e?.entries.find(e=>e.name===W&&z.test(e.id))}const re={opus:0,fable:1,sonnet:2,haiku:3};function se(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=se(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ie(e){return se(e)?.family}export function buildInferenceModels(e,t){const{primary:o,bySlot:n}=function(e){const t=["opus","sonnet","haiku","reasoning"].map(t=>R(e[t]||"")).filter(Boolean);return{primary:t[0]??"",bySlot:t}}(e),r=new Set,s=t?.labels??{};let i;if(t&&t.models.some(F)){i=[...new Set(t.models.filter(F).map(R))];for(const e of t.oneMillion)r.add(e)}else{i=[];for(const t of["opus","sonnet","haiku","reasoning"]){const o=(e[t]||"").trim(),n=R(o);n&&(i.includes(n)||i.push(n),/\[1m\]/i.test(o)&&r.add(n))}}const l=e=>re[ie(e)??""]??9;i.sort((e,t)=>{if(e===o)return-1;if(t===o)return 1;const n=l(e)-l(t);if(0!==n)return n;const r=se(e),s=se(t);return r&&s?function(e,t){const o=Math.max(e.length,t.length);for(let n=0;n<o;n++){const o=(t[n]??0)-(e[n]??0);if(0!==o)return o}return 0}(r.version,s.version):e.localeCompare(t)});const a=new Set,c=new Map,d=new Set(Object.values(B()).map(e=>R(e||"")));for(const e of n){const t=ie(e);t&&i.includes(e)&&!d.has(e)&&!c.has(t)&&c.set(t,e)}return i.map(e=>{const t=ie(e),o={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(o.supports1m=!0,o.prefer1m=!0),t){o.anthropicFamilyTier=t;const n=c.get(t);n&&n!==e||a.has(t)||(o.isFamilyDefault=!0,a.add(t))}return o})}let le=null,ae=null,ce=null,de=null,ue=null;function pe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,inferenceModels:buildInferenceModels(e.models,e.catalog),disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const fe={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},me=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ge=me,ye=null;export function setDesktopAsarForTests(e){ge=void 0===e?me:()=>e,ye=null}function he(){if(ye)return ye;let e=null;try{e=ge()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return ye=new Set(e?Object.keys(fe).filter(t=>!e.includes(t)):[]),ye}function ke(e){const t=he();return Object.fromEntries(Object.entries(fe).filter(([o])=>!e(o)&&!t.has(o)))}function _e(e){const t={...ke(t=>t in e),...e};for(const e of he())e in t&&JSON.stringify(t[e])===JSON.stringify(fe[e])&&delete t[e];return t}const we="SOFTWARE\\Policies\\Claude",be=`HKCU\\${we}`,De="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ce=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let ve=Ce;export function setRegRunnerForTests(e){ve=e??Ce}function Ee(){return"win32"===process.platform}function Me(e){let t;try{t=ve(["query",e])}catch{return null}const o=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&o.set(t[1],t[3])}return o}function Oe(){if(null===Me(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),D(e),ve(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function Se(e){Oe();for(const[t,o]of Object.entries(e)){const[e,n]="boolean"==typeof o?["REG_DWORD",o?"1":"0"]:"number"==typeof o?["REG_DWORD",String(o)]:"string"==typeof o?["REG_SZ",o]:["REG_SZ",JSON.stringify(o)];ve(["add",be,"/v",t,"/t",e,"/d",n,"/f"])}}function xe(e){const t=Me(be);if(!t)return;Oe();let o=t.size;for(const n of e)t.has(n)&&(ve(["delete",be,"/v",n,"/f"]),o-=1);o<=0&&ve(["delete",be,"/f"])}function je(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(C(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Pe=[...Object.keys(pe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(fe)];function Ie(e){if(!e||!Pe.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&N().includes(t)?"ours":"foreign"}function Le(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=oe(),o=t?.entries.find(e=>e.id===t.appliedId);if(!o||o.id===ne(t)?.id)return null;const n=ee(Y(o.id));return n&&(n.inferenceProvider||n.inferenceGatewayBaseUrl)?{kind:"entry",name:o.name}:null}function Te(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let $e=null,Ge=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return Me(De)?De:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Ne(){const e=C();let o;switch(process.platform){case"darwin":o=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");o=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...j.map(e=>l(t,"Packages",e))];break}default:o=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return o.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),o.some(e=>t(e))}const Ue=/\d+\.\d+\.\d+/;function Ke(e){const t=e=>e.split(".").map(Number);return e.sort((e,o)=>{const[n,r]=[t(e),t(o)];for(let e=0;e<3;e++)if(n[e]!==r[e])return r[e]-n[e];return 0})[0]??null}function Re(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(C(),"Applications","Claude.app")]){const o=l(e,"Contents","Info.plist");if(!t(o))continue;const n=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(o,"utf-8")),s=n?Ue.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(C(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Ke(t)}const o=j.map(e=>`'${e}'`).join(",");return Ke(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${o}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:V()}).split(/\r?\n/).flatMap(e=>Ue.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return Ue.exec(e)?.[0]??null}catch{return null}return null}const Fe="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Be="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),He="darwin"===process.platform?`open ${Be}`:"win32"===process.platform?`start ${Be}`:`xdg-open ${Be}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:Fe,installCommand:He,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ne,installedVersion:Re,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ne())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),desktopVersion:"darwin"===process.platform?Re():null,mirror:k().installMirror?.claudeDesktop??null});return f("desktop-code-cli","skipped"===t.status?"skip":"ok",{duration_ms:Date.now()-e,detail:{...t}}),"installed"!==t.status?[]:[{kind:"summary",text:y.t("tools.claude_desktop.code_cli_installed",{version:t.version})}]}catch(t){return p.logError("claude-desktop.prepareCodeTabCli",t),f("desktop-code-cli","fail",{duration_ms:Date.now()-e,error:t}),[{kind:"action",text:y.t("tools.claude_desktop.code_cli_failed",{reason:t instanceof Error?t.message:String(t)})}]}},runningApp:v()?{isRunning:M,restart:x,quit:S,quitRefused:E,launch:O}:void 0,appInstaller:{vendor:"Anthropic",sizeMb:()=>300,downloadPage:"https://claude.ai/download",blocker:P,latestVersion:()=>I(),installedPath(){if("darwin"===process.platform)return L();if("win32"!==process.platform)return null;try{return Re()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=oe()??{appliedId:"",entries:[]};let o=ne(t);o||(o={id:a(),name:W},t.entries.push(o));const n=pe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser,le={models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]};const r=ee(Y(o.id))??{};te(Y(o.id),{..._e(r),...n});const s=Le();$e=s&&!e.takeOver?Te(s):null,$e||(t.appliedId=o.id),te(Z(),t);const i=ee(Q())??{};$e||"3p"===i.deploymentMode||te(Q(),{...i,deploymentMode:"3p"}),de=null,ue=null,ce=null,Ge=null;const l=!0===e.settings?.force_registry,c=Ee()?Me(be):null;if(Ee()&&"foreign"===Ie(c)&&!l)Ge=c?.get("inferenceGatewayBaseUrl")||be;else if(Ee()){const t=Me(be),o=Pe.filter(e=>t?.has(e)),r={...ke(e=>t?.has(e)??!1),...n},s=!0===e.settings?.force_registry,i=!s&&je();try{i?xe(Pe):Se(r),ce=i?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),de=e instanceof Error?e.message.trim():String(e),(o.length>0||s)&&(ue=i?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:r,deleteKey:!1})}}},pendingElevation(){const e=ue;return e?{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),run:()=>{if(!$(we,e.values,e.deleteKey))return!1;const t=Me(be),o="remove"===e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return o&&(ue=null,de=null),o}}:null},unloadPrivateConfig(){if(Ee()&&"ours"===Ie(Me(be)))try{xe(Pe)}catch(e){p.logError("claude-desktop.removePolicy",e)}const e=oe(),t=ne(e);if(!e||!t)return;D(Y(t.id)),s(Y(t.id),{force:!0});const o=e.entries.filter(e=>e.id!==t.id);0===o.length?(D(Z()),s(Z(),{force:!0})):te(Z(),{...e,entries:o,appliedId:e.appliedId===t.id?o[0].id:e.appliedId})},listedModels(){const e=oe(),t=ne(e);if(!t||e?.appliedId!==t.id)return null;const o=ee(Y(t.id))?.inferenceModels;return Array.isArray(o)?o.map(e=>String(e.name)):null},refreshModelMenu(e){const t=oe(),o=ne(t);if(!o||t?.appliedId!==o.id)return;const n=ee(Y(o.id));if(!n)return;const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={..._e(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);ue=null;const a=Ee()?Me(be):null,c="foreign"===Ie(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Pe.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&je();if(l&&te(Y(o.id),i),u||s)try{u?xe(Pe):Se({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),ue=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new G(y.t("tools.claude_desktop.refresh_needs_admin"))}},detectCurrentConfig(){try{if(Ee()){const e=Me(be)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=ne(oe());if(!e)return{apiKey:null};const t=ee(Y(e.id)),o=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof o&&o?o:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=oe(),t=ne(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Ee()?{policy:Object.fromEntries(Me(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ee()&&Me(be)?.has("inferenceModels")&&(Oe(),ve(["delete",be,"/v","inferenceModels","/f"]),e=!0);const t=ne(oe()),o=t?ee(Y(t.id)):null;if(t&&o&&void 0!==o.inferenceModels){const{inferenceModels:n,...r}=o;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(le&&le.models.length>0){const{models:t,source:o,groups:n}=le;e.push({kind:"summary",text:y.t("tools.claude_desktop.models_summary",{count:String(t.length),default:t[0].labelOverride??t[0].name})}),e.push({kind:"detail",text:y.t(`tools.claude_desktop.models_written_${o}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:n.join(" / ")})})}null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),v()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),ue?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${ue.action}`)}),e.push({kind:"detail",text:de??""})):de?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:de})):Ee()&&ce&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${ce}`,{key:be})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ge})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Le();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Te(t)})),Ee()){const t=Me(be);"foreign"===Ie(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:be,url:t?.get("inferenceGatewayBaseUrl")||"-"}))}return e},forceResetPaths(){const e=[Z(),Q()];try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Ee()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e}};
1
+ import{chmodSync as e,existsSync as t,mkdirSync as o,readdirSync as n,readFileSync as r,rmSync as s}from"fs";import{dirname as i}from"path";import{join as l}from"path";import{randomUUID as a}from"crypto";import{execFileSync as c}from"child_process";import{userInfo as d}from"os";import u from"chalk";import{logger as p}from"../../utils/logger.js";import{track as f}from"../telemetry.js";import{ensureDesktopCli as m,installedDesktopAsarPath as g}from"./claude-desktop-cli.js";import{i18n as y}from"../i18n.js";import{BRAND_NAME as h,brand as k,brandEnv as _,CLI_NAME as w}from"../brand.js";import{mirrorPageUrl as b}from"../mirror-url.js";import{backupBeforeWrite as D,atomicWriteFile as A}from"./backup.js";import{toolHome as C}from"./types.js";import{canRestartDesktop as v,desktopQuitRefused as E,isDesktopRunning as M,launchDesktop as O,quitDesktop as S,restartDesktop as x,WINDOWS_PACKAGE_FAMILIES as j}from"./desktop-process.js";import{desktopInstallBlocker as P,fetchLatestDesktopVersion as I,installedMacApp as L,installLatestDesktop as T}from"./claude-desktop-app.js";import{setUserRegistryElevated as $}from"./elevated-reg.js";import{UserActionNeeded as G}from"./types.js";import{savedApiKeys as N}from"../config.js";import{isOurGatewayUrl as U,noteWrittenGatewayUrl as K}from"../gateway-addresses.js";import{baseModelId as R,isClaudeModel as F}from"../model-catalog.js";import{getDefaultModels as B}from"../model-registry.js";import{claudeFormat as H,nestedClaudeProjectFiles as J}from"../sessions/formats.js";import{powerShellEnv as V}from"../powershell-env.js";const W=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const z=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const o=C(),n=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(o,"Library","Application Support","Claude-3p");case"win32":{const e=!n&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(o,"AppData","Local");return j.map(t=>l(e,"Packages",t,"LocalCache","Local","Claude-3p")).find(e=>t(e))??l(e,"Claude-3p")}default:{const e=!n&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(o,".config");return l(e,"Claude-3p")}}}const X=()=>l(claudeDesktopUserDataDir(),"configLibrary"),Z=()=>l(X(),"_meta.json"),Y=e=>l(X(),`${e}.json`),Q=()=>l(claudeDesktopUserDataDir(),"claude_desktop_config.json");function ee(e){if(!t(e))return null;const o=r(e,"utf-8");if(!o.trim())return null;try{const e=JSON.parse(o);return q(e)?e:null}catch(t){throw new Error(`Existing ${e} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}function te(n,r){const s=i(n);t(s)||o(s,{recursive:!0,mode:448}),D(n),A(n,JSON.stringify(r,null,2)+"\n");try{e(n,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function oe(){const e=ee(Z());if(!e)return null;const t=Array.isArray(e.entries)?e.entries.filter(e=>q(e)&&"string"==typeof e.id&&"string"==typeof e.name):[];return{...e,appliedId:"string"==typeof e.appliedId?e.appliedId:"",entries:t}}function ne(e){return e?.entries.find(e=>e.name===W&&z.test(e.id))}const re={opus:0,fable:1,sonnet:2,haiku:3};function se(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=se(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ie(e){return se(e)?.family}export function buildInferenceModels(e,t){const{primary:o,bySlot:n}=function(e){const t=["opus","sonnet","haiku","reasoning"].map(t=>R(e[t]||"")).filter(Boolean);return{primary:t[0]??"",bySlot:t}}(e),r=new Set,s=t?.labels??{};let i;if(t&&t.models.some(F)){i=[...new Set(t.models.filter(F).map(R))];for(const e of t.oneMillion)r.add(e)}else{i=[];for(const t of["opus","sonnet","haiku","reasoning"]){const o=(e[t]||"").trim(),n=R(o);n&&(i.includes(n)||i.push(n),/\[1m\]/i.test(o)&&r.add(n))}}const l=e=>re[ie(e)??""]??9;i.sort((e,t)=>{if(e===o)return-1;if(t===o)return 1;const n=l(e)-l(t);if(0!==n)return n;const r=se(e),s=se(t);return r&&s?function(e,t){const o=Math.max(e.length,t.length);for(let n=0;n<o;n++){const o=(t[n]??0)-(e[n]??0);if(0!==o)return o}return 0}(r.version,s.version):e.localeCompare(t)});const a=new Set,c=new Map,d=new Set(Object.values(B()).map(e=>R(e||"")));for(const e of n){const t=ie(e);t&&i.includes(e)&&!d.has(e)&&!c.has(t)&&c.set(t,e)}return i.map(e=>{const t=ie(e),o={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(o.supports1m=!0,o.prefer1m=!0),t){o.anthropicFamilyTier=t;const n=c.get(t);n&&n!==e||a.has(t)||(o.isFamilyDefault=!0,a.add(t))}return o})}let le=null,ae=null,ce=null,de=null,ue=null;function pe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,inferenceModels:buildInferenceModels(e.models,e.catalog),disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const fe={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},me=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ge=me,ye=null;export function setDesktopAsarForTests(e){ge=void 0===e?me:()=>e,ye=null}function he(){if(ye)return ye;let e=null;try{e=ge()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return ye=new Set(e?Object.keys(fe).filter(t=>!e.includes(t)):[]),ye}function ke(e){const t=he();return Object.fromEntries(Object.entries(fe).filter(([o])=>!e(o)&&!t.has(o)))}function _e(e){const t={...ke(t=>t in e),...e};for(const e of he())e in t&&JSON.stringify(t[e])===JSON.stringify(fe[e])&&delete t[e];return t}const we="SOFTWARE\\Policies\\Claude",be=`HKCU\\${we}`,De="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ce=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let ve=Ce;export function setRegRunnerForTests(e){ve=e??Ce}function Ee(){return"win32"===process.platform}function Me(e){let t;try{t=ve(["query",e])}catch{return null}const o=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&o.set(t[1],t[3])}return o}function Oe(){if(null===Me(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),D(e),ve(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function Se(e){Oe();for(const[t,o]of Object.entries(e)){const[e,n]="boolean"==typeof o?["REG_DWORD",o?"1":"0"]:"number"==typeof o?["REG_DWORD",String(o)]:"string"==typeof o?["REG_SZ",o]:["REG_SZ",JSON.stringify(o)];ve(["add",be,"/v",t,"/t",e,"/d",n,"/f"])}}function xe(e){const t=Me(be);if(!t)return;Oe();let o=t.size;for(const n of e)t.has(n)&&(ve(["delete",be,"/v",n,"/f"]),o-=1);o<=0&&ve(["delete",be,"/f"])}function je(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(C(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Pe=[...Object.keys(pe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(fe)];function Ie(e){if(!e||!Pe.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&N().includes(t)?"ours":"foreign"}function Le(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=oe(),o=t?.entries.find(e=>e.id===t.appliedId);if(!o||o.id===ne(t)?.id)return null;const n=ee(Y(o.id));return n&&(n.inferenceProvider||n.inferenceGatewayBaseUrl)?{kind:"entry",name:o.name}:null}function Te(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let $e=null,Ge=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return Me(De)?De:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Ne(){const e=C();let o;switch(process.platform){case"darwin":o=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");o=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...j.map(e=>l(t,"Packages",e))];break}default:o=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return o.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),o.some(e=>t(e))}const Ue=/\d+\.\d+\.\d+/;function Ke(e){const t=e=>e.split(".").map(Number);return e.sort((e,o)=>{const[n,r]=[t(e),t(o)];for(let e=0;e<3;e++)if(n[e]!==r[e])return r[e]-n[e];return 0})[0]??null}function Re(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(C(),"Applications","Claude.app")]){const o=l(e,"Contents","Info.plist");if(!t(o))continue;const n=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(o,"utf-8")),s=n?Ue.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(C(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Ke(t)}const o=j.map(e=>`'${e}'`).join(",");return Ke(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${o}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:V()}).split(/\r?\n/).flatMap(e=>Ue.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return Ue.exec(e)?.[0]??null}catch{return null}return null}const Fe="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Be="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),He="darwin"===process.platform?`open ${Be}`:"win32"===process.platform?`start ${Be}`:`xdg-open ${Be}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:Fe,installCommand:He,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ne,installedVersion:Re,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ne())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),onStart:(e,t)=>f("desktop-code-cli","start",{detail:{version:e,source:t}}),desktopVersion:"darwin"===process.platform?Re():null,mirror:k().installMirror?.claudeDesktop??null});return f("desktop-code-cli","skipped"===t.status?"skip":"ok",{duration_ms:Date.now()-e,detail:{...t}}),"installed"!==t.status?[]:[{kind:"summary",text:y.t("tools.claude_desktop.code_cli_installed",{version:t.version})}]}catch(t){return p.logError("claude-desktop.prepareCodeTabCli",t),f("desktop-code-cli","fail",{duration_ms:Date.now()-e,error:t}),[{kind:"action",text:y.t("tools.claude_desktop.code_cli_failed",{reason:t instanceof Error?t.message:String(t)})}]}},runningApp:v()?{isRunning:M,restart:x,quit:S,quitRefused:E,launch:O}:void 0,appInstaller:{vendor:"Anthropic",sizeMb:()=>300,downloadPage:"https://claude.ai/download",blocker:P,latestVersion:()=>I(),installedPath(){if("darwin"===process.platform)return L();if("win32"!==process.platform)return null;try{return Re()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=oe()??{appliedId:"",entries:[]};let o=ne(t);o||(o={id:a(),name:W},t.entries.push(o));const n=pe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser,le={models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]};const r=ee(Y(o.id))??{};te(Y(o.id),{..._e(r),...n});const s=Le();$e=s&&!e.takeOver?Te(s):null,$e||(t.appliedId=o.id),te(Z(),t);const i=ee(Q())??{};$e||"3p"===i.deploymentMode||te(Q(),{...i,deploymentMode:"3p"}),de=null,ue=null,ce=null,Ge=null;const l=!0===e.settings?.force_registry,c=Ee()?Me(be):null;if(Ee()&&"foreign"===Ie(c)&&!l)Ge=c?.get("inferenceGatewayBaseUrl")||be;else if(Ee()){const t=Me(be),o=Pe.filter(e=>t?.has(e)),r={...ke(e=>t?.has(e)??!1),...n},s=!0===e.settings?.force_registry,i=!s&&je();try{i?xe(Pe):Se(r),ce=i?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),de=e instanceof Error?e.message.trim():String(e),(o.length>0||s)&&(ue=i?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:r,deleteKey:!1})}}},pendingElevation(){const e=ue;return e?{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),run:()=>{if(!$(we,e.values,e.deleteKey))return!1;const t=Me(be),o="remove"===e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return o&&(ue=null,de=null),o}}:null},unloadPrivateConfig(){if(Ee()&&"ours"===Ie(Me(be)))try{xe(Pe)}catch(e){p.logError("claude-desktop.removePolicy",e)}const e=oe(),t=ne(e);if(!e||!t)return;D(Y(t.id)),s(Y(t.id),{force:!0});const o=e.entries.filter(e=>e.id!==t.id);0===o.length?(D(Z()),s(Z(),{force:!0})):te(Z(),{...e,entries:o,appliedId:e.appliedId===t.id?o[0].id:e.appliedId})},listedModels(){const e=oe(),t=ne(e);if(!t||e?.appliedId!==t.id)return null;const o=ee(Y(t.id))?.inferenceModels;return Array.isArray(o)?o.map(e=>String(e.name)):null},refreshModelMenu(e){const t=oe(),o=ne(t);if(!o||t?.appliedId!==o.id)return;const n=ee(Y(o.id));if(!n)return;const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={..._e(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);ue=null;const a=Ee()?Me(be):null,c="foreign"===Ie(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Pe.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&je();if(l&&te(Y(o.id),i),u||s)try{u?xe(Pe):Se({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),ue=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new G(y.t("tools.claude_desktop.refresh_needs_admin"))}},detectCurrentConfig(){try{if(Ee()){const e=Me(be)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=ne(oe());if(!e)return{apiKey:null};const t=ee(Y(e.id)),o=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof o&&o?o:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=oe(),t=ne(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Ee()?{policy:Object.fromEntries(Me(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ee()&&Me(be)?.has("inferenceModels")&&(Oe(),ve(["delete",be,"/v","inferenceModels","/f"]),e=!0);const t=ne(oe()),o=t?ee(Y(t.id)):null;if(t&&o&&void 0!==o.inferenceModels){const{inferenceModels:n,...r}=o;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(le&&le.models.length>0){const{models:t,source:o,groups:n}=le;e.push({kind:"summary",text:y.t("tools.claude_desktop.models_summary",{count:String(t.length),default:t[0].labelOverride??t[0].name})}),e.push({kind:"detail",text:y.t(`tools.claude_desktop.models_written_${o}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:n.join(" / ")})})}null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),v()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),ue?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${ue.action}`)}),e.push({kind:"detail",text:de??""})):de?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:de})):Ee()&&ce&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${ce}`,{key:be})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ge})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Le();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Te(t)})),Ee()){const t=Me(be);"foreign"===Ie(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:be,url:t?.get("inferenceGatewayBaseUrl")||"-"}))}return e},forceResetPaths(){const e=[Z(),Q()];try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Ee()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e}};
@@ -18,17 +18,34 @@ export declare const PLUGIN_SOURCES: ReadonlyArray<{
18
18
  probe: string;
19
19
  }>;
20
20
  export declare const OFFICIAL_PLUGINS: string[];
21
+ /**
22
+ * The whole round. A source that answers the probe but hangs on install used to cost 120 s per
23
+ * plugin, ten plugins in a row, on every config write.
24
+ */
25
+ export declare const PLUGIN_ROUND_LIMIT_MS = 240000;
26
+ /** After a round that left plugins uninstalled, config writes do not try again for this long. */
27
+ export declare const PLUGIN_RETRY_AFTER_MS: number;
21
28
  export interface PluginInstallResult {
22
29
  installed: string[];
23
30
  failed: string[];
24
- /** Why nothing was attempted (no source reachable, disabled); null otherwise. */
31
+ /** Why nothing was attempted (no source reachable, disabled, failed recently); null otherwise. */
25
32
  skipped: string | null;
26
33
  /** Marketplace the plugins came from. */
27
34
  source?: string;
28
35
  }
29
36
  /** Tests replace the CLI runner. */
30
- export declare function setClaudePluginRunnerForTests(fake: (claude: string, args: string[]) => boolean): void;
37
+ export declare function setClaudePluginRunnerForTests(fake: (claude: string, args: string[], timeoutMs?: number) => boolean): void;
31
38
  /** Tests replace the reachability probe. */
32
39
  export declare function setPluginSourceProbeForTests(fake: (url: string) => boolean): void;
33
- /** Install the official plugins not offered before, using `claude` at `claudePath`. */
34
- export declare function installOfficialPlugins(claudePath: string): PluginInstallResult;
40
+ /**
41
+ * Install the official plugins not offered before, using `claude` at `claudePath`.
42
+ *
43
+ * What was offered is a machine mark (any profile's old copy counts): a new profile must not put
44
+ * back plugins the user removed. A round is limited to `PLUGIN_ROUND_LIMIT_MS`; one that leaves
45
+ * plugins uninstalled is not repeated by config writes for a day, unless `retry` (the user asked:
46
+ * `config claude-code`, the wizard, a tool-specific key).
47
+ */
48
+ export declare function installOfficialPlugins(claudePath: string, options?: {
49
+ retry?: boolean;
50
+ now?: () => number;
51
+ }): PluginInstallResult;