@xship/cli 0.0.192 → 0.0.194
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client-config.snapshot.json +4 -4
- package/dist/client-config.snapshot.json +4 -4
- package/dist/commands/doctor.js +1 -1
- package/dist/commands/refresh.js +1 -1
- package/dist/lib/components.js +1 -1
- package/dist/lib/mirror-url.js +1 -1
- package/dist/lib/model-refresh.js +1 -1
- package/dist/lib/tools/claude-desktop-cli.js +1 -1
- package/dist/lib/tools/desktop-app-installer.js +1 -1
- package/dist/locales/en_US.json +3 -0
- package/dist/locales/zh_CN.json +3 -0
- package/package.json +1 -1
|
@@ -1082,8 +1082,8 @@
|
|
|
1082
1082
|
"context_window": 1000000,
|
|
1083
1083
|
"description": "100 万上下文 | Agent 工作流",
|
|
1084
1084
|
"endpoint_types": [
|
|
1085
|
-
"
|
|
1086
|
-
"
|
|
1085
|
+
"openai",
|
|
1086
|
+
"gemini"
|
|
1087
1087
|
],
|
|
1088
1088
|
"group": "",
|
|
1089
1089
|
"group_name": "",
|
|
@@ -2053,8 +2053,8 @@
|
|
|
2053
2053
|
"context_window": 1000000,
|
|
2054
2054
|
"description": "100 万上下文 | Agent 工作流",
|
|
2055
2055
|
"endpoint_types": [
|
|
2056
|
-
"
|
|
2057
|
-
"
|
|
2056
|
+
"openai",
|
|
2057
|
+
"gemini"
|
|
2058
2058
|
],
|
|
2059
2059
|
"group": "",
|
|
2060
2060
|
"group_name": "",
|
|
@@ -1082,8 +1082,8 @@
|
|
|
1082
1082
|
"context_window": 1000000,
|
|
1083
1083
|
"description": "100 万上下文 | Agent 工作流",
|
|
1084
1084
|
"endpoint_types": [
|
|
1085
|
-
"
|
|
1086
|
-
"
|
|
1085
|
+
"openai",
|
|
1086
|
+
"gemini"
|
|
1087
1087
|
],
|
|
1088
1088
|
"group": "",
|
|
1089
1089
|
"group_name": "",
|
|
@@ -2053,8 +2053,8 @@
|
|
|
2053
2053
|
"context_window": 1000000,
|
|
2054
2054
|
"description": "100 万上下文 | Agent 工作流",
|
|
2055
2055
|
"endpoint_types": [
|
|
2056
|
-
"
|
|
2057
|
-
"
|
|
2056
|
+
"openai",
|
|
2057
|
+
"gemini"
|
|
2058
2058
|
],
|
|
2059
2059
|
"group": "",
|
|
2060
2060
|
"group_name": "",
|
package/dist/commands/doctor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{refreshClientConfig as o}from"../lib/client-config-sync.js";import t from"chalk";import e from"ora";import{spawnSync as s}from"child_process";import{existsSync as r,readdirSync as n,readFileSync as a}from"fs";import{connect as c}from"net";import{join as i}from"path";import{configManager as l}from"../lib/config.js";import{savedApiKey as d}from"./base.js";import{toolManager as p}from"../lib/tool-manager.js";import{i18n as u}from"../lib/i18n.js";import{validateApiKey as m}from"../lib/api-validator.js";import{getAdapter as f}from"../lib/tools/registry.js";import{findInstalls as g,installLabel as _}from"../lib/tools/tool-installs.js";import{detectManagedOverrides as h}from"../lib/tools/claude-managed.js";import{codexAuthProblem as y,codexCatalogRejection as k,codexConfigPath as b,codexWorkModeOn as w}from"../lib/tools/codex.js";import{claudeAccountLoginPresent as j}from"../lib/tools/claude-code.js";import{toolHome as v}from"../lib/tools/types.js";import{gatewayAddresses as $,probeGatewayAddress as x}from"../lib/gateway-addresses.js";import{listAdapters as T}from"../lib/tools/registry.js";import{logger as A}from"../utils/logger.js";import{maskHome as P,maskSecrets as R,noteFailureReason as N,uploadReport as O}from"../lib/telemetry.js";import{systemReport as I}from"../lib/system-report.js";import{CLI_NAME as C}from"../lib/brand.js";import{appStatus as H,appStatusText as L,appTools as S,appUpgradeCommand as U,getApp as E}from"../lib/app-update.js";import{balanceLookupEnabled as K,balanceNeedsAttention as B,balanceText as G,fetchKeyBalances as D}from"../lib/key-balance.js";const q=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"];function F(o,t,e=3e3){return new Promise(s=>{const r=c({host:o,port:t}),n=o=>{r.destroy(),s(o)};r.setTimeout(e,()=>n(!1)),r.once("connect",()=>n(!0)),r.once("error",()=>n(!1))})}function M(){const o=A.getLogDir();if(!r(o))return"";const t=n(o).filter(o=>/^\d{4}-\d{2}-\d{2}\.log$/.test(o)).sort().slice(-2).map(t=>`== ${t}\n`+a(i(o,t),"utf-8")).join("\n");return R(t.slice(-15e4))}function X(){const o={};for(const t of q){const e=process.env[t]?.trim();if(e)try{const s=new URL(e.includes("://")?e:`http://${e}`);o[t]=`${s.protocol}//${s.host}`}catch{o[t]="(unparsable)"}}return o}export async function doctorCommand(r={}){const n=e(u.t("doctor.checking")).start(),c=[],A=Number(process.versions.node.split(".")[0]);c.push({name:"Node.js",status:A>=20?"pass":"fail",message:`v${process.versions.node}`}),n.text=u.t("doctor.check_proxy"),c.push(await async function(){const o=u.t("doctor.proxy"),t=new Map;for(const o of q){const e=process.env[o]?.trim();e&&!t.has(e)&&t.set(e,o)}if(0===t.size)return{name:o,status:"pass",message:u.t("doctor.proxy_none")};const e=[];for(const[o,s]of t){let t;try{t=new URL(o.includes("://")?o:`http://${o}`)}catch{e.push(`${s}=${o}`);continue}const r=Number(t.port)||("https:"===t.protocol?443:t.protocol.startsWith("socks")?1080:80);await F(t.hostname,r)||e.push(`${s}=${o}`)}return 0===e.length?{name:o,status:"pass",message:[...t.keys()].join(", ")}:{name:o,status:"fail",message:u.t("doctor.proxy_dead",{proxies:e.join(", ")})}}()),n.text=u.t("doctor.check_api_key_network");const R=d(),Y=u.t("doctor.api_key_network");if(R){const o=await m(R);o.valid?(c.push({name:Y,status:"pass"}),n.text=u.t("doctor.check_balance"),c.push(...await async function(o){if(!K())return[];const t=l.listToolApiKeys().map(o=>({tool:o,key:l.getApiKeyForTool(o)})).filter(t=>Boolean(t.key)&&t.key!==o),e=await D([o,...t.map(o=>o.key)]),s=[{name:u.t("doctor.balance"),key:o},...t.map(o=>({name:u.t("doctor.balance_tool",{tool:f(o.tool)?.displayName??o.tool}),key:o.key}))],r=[];for(const o of s){const t=e.get(o.key);t&&r.push({name:o.name,status:B(t)?"warn":"pass",message:G(t)})}return r}(R))):"invalid_api_key"===o.error?c.push({name:Y,status:"fail",message:u.t("doctor.api_key_invalid")}):(c.push({name:Y,status:"fail",message:`${u.t("doctor.network_error")}: ${o.message??o.error}`}),n.text=u.t("doctor.check_other_addresses"),c.push(await async function(){const o=u.t("doctor.other_addresses"),t=l.getBaseUrl(),e=$().filter(o=>o.url!==t),s=d(),r=await Promise.all(e.map(o=>x(o.url,{apiKey:s}))),n=e.filter((o,t)=>r[t].ok).map(o=>o.url);return 0===n.length?{name:o,status:"fail",message:u.t("doctor.other_addresses_none")}:{name:o,status:"warn",message:u.t("doctor.other_addresses_found",{urls:n.join(", ")})}}()))}else c.push({name:Y,status:"fail",message:u.t("doctor.api_key_missing")});n.text=u.t("doctor.check_client_config");const V=await o();c.push({name:u.t("doctor.client_config"),status:"cloud"===V.source||"cache"===V.source&&!V.problem?"pass":"warn",message:[V.source?u.t(`refresh.source.${V.source}`):u.t("refresh.source.none"),V.revision?u.t("doctor.client_config_revision",{revision:V.revision}):"",V.problem??""].filter(Boolean).join(" · ")}),n.text=u.t("doctor.check_tools");const W=p.getInstalledTools();c.push({name:u.t("doctor.installed_tools"),status:W.length>0?"pass":"warn",message:W.length>0?W.map(o=>f(o)?.displayName??o).join(u.t("setup.list_separator")):u.t("doctor.no_tools_installed")}),c.push(...function(){const o=[];for(const t of p.getInstalledTools()){const e=f(t);if(!e?.installSpec)continue;const s=g(e.installSpec);if(0===s.length)continue;const r=[],n=p.outdatedVersion(t);n&&r.push(u.t("doctor.tool_outdated",{min:n.min})),s.length>1&&r.push(u.t("doctor.tool_duplicates",{others:s.slice(1).map(_).join("、")})),o.push({name:e.displayName,status:r.length>0?"warn":"pass",message:[_(s[0]),...r,...r.length>0?[u.t("doctor.run_upgrade",{tool:t})]:[]].join("\n ")})}return o}()),c.push(...await async function(){const o=[];for(const t of S()){const e=await H(t,{refresh:!0});if(!e.installed||!e.current)continue;const s=u.t("doctor.app_version",{tool:e.name});if(e.outdated){const r=e.blocker?u.t(`app_update.blocked_${e.blocker}`,{tool:e.name,url:E(t)?.appInstaller.downloadPage??"",command:U(t)}):u.t("doctor.run_app_upgrade",{command:U(t)});o.push({name:s,status:"warn",message:`${L(e)}\n ${r}`})}else o.push({name:s,status:"pass",message:L(e)})}return o}());const z=function(){if(!p.isToolInstalled("claude-code"))return null;const o=u.t("doctor.claude_config"),t=h();if(t.length>0){const e=t.map(o=>`${o.source}: ${o.keys.join(", ")}`).join("; ");return{name:o,status:"fail",message:u.t("doctor.claude_managed",{detail:e})}}let e={};try{e=JSON.parse(a(i(process.env.CLAUDE_CONFIG_DIR?.trim()||i(v(),".claude"),"settings.json"),"utf-8")).env??{}}catch{}const s=l.getApiKeyForTool("claude-code");return e.ANTHROPIC_AUTH_TOKEN&&e.ANTHROPIC_BASE_URL?e.ANTHROPIC_BASE_URL!==l.getBaseUrl()||s&&e.ANTHROPIC_AUTH_TOKEN!==s?{name:o,status:"warn",message:u.t("doctor.claude_config_changed")}:{name:o,status:"pass"}:{name:o,status:"warn",message:u.t("doctor.claude_not_configured")}}();z&&c.push(z),W.includes("claude-code")&&j()&&c.push({name:u.t("doctor.claude_login"),status:"pass",message:u.t("tools.claude_code.account_login_overridden")});const J=W.includes("codex")?y():null;if(W.includes("codex")&&c.push({name:u.t("doctor.codex_auth"),status:J?"fail":"pass",message:J?u.t(`doctor.codex_${J}`,{path:P(b())}):void 0}),W.includes("codex")){const o=k();c.push({name:u.t("doctor.codex_catalog"),status:o?"fail":"pass",message:o?u.t("doctor.codex_catalog_rejected",{path:o.bin,version:o.version??"?",error:o.error}):void 0})}W.includes("codex")&&w()&&c.push({name:u.t("doctor.codex_work_mode"),status:"warn",message:u.t("tools.codex.work_mode_on")}),"win32"===process.platform&&W.includes("claude-code")&&!process.env.CLAUDE_CODE_GIT_BASH_PATH&&c.push({name:"Git for Windows",status:p.isGitInstalled()?"pass":"warn",message:p.isGitInstalled()?void 0:u.t("tools.claude_code.no_git_bash")}),r.deep&&W.includes("claude-code")&&(n.text=u.t("doctor.check_claude_request"),c.push(function(){const o=u.t("doctor.claude_request"),t=g(f("claude-code").installSpec)[0];if(!t)return{name:o,status:"warn",message:u.t("doctor.claude_request_skipped")};const e={encoding:"utf-8",timeout:12e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},r=["-p","Reply with the single word OK."],n=/\.cmd$/i.test(t.path)?s(`"${t.path}" ${r.map(o=>`"${o}"`).join(" ")}`,{...e,shell:!0}):s(t.path,r,e),a=`${n.stdout??""}`.trim();if(0===n.status&&a)return{name:o,status:"pass",message:a.slice(0,80)};const c=(`${n.stderr??""}`.trim()||a||n.error?.message||`exit ${n.status}`).slice(0,300);return{name:o,status:"fail",message:u.t("doctor.claude_request_failed",{reason:c})}}())),n.stop(),console.log("\n"+t.bold(u.t("doctor.results_title"))+"\n");const Q={pass:t.green("√"),warn:t.yellow("!"),fail:t.red("×")};for(const o of c)console.log(`${Q[o.status]} ${o.name}`),o.message&&console.log(t.gray(` ${o.message}`));if(c.every(o=>"pass"===o.status)&&console.log("\n"+t.green.bold(u.t("doctor.all_good"))),!r.deep&&W.includes("claude-code")&&console.log(t.gray("\n"+u.t("doctor.deep_hint"))),r.report){const o=e(u.t("doctor.report_uploading")).start(),t=await O(function(o,t){const e={};for(const o of T()){if(o.hidden)continue;let t=null;try{t=p.detectCurrentConfig(o.name).apiKey?"has_key":"no_key"}catch{t="unreadable"}e[o.name]={installed:p.isToolInstalled(o.name),version:p.installedVersion(o.name),copies:o.installSpec?g(o.installSpec).map(o=>({kind:o.kind,version:o.version,path:o.path})):void 0,config:t}}const s=l.getProfile();return{checks:o,tools:e,settings:{base_url:l.getBaseUrl(),profile:l.getActiveProfileName(),profiles:l.listProfiles().length,key_fingerprint:l.getApiKeyFingerprint()||null,tool_keys:Object.keys(s.tool_api_keys??{}),models:s.models,tool_models:s.tool_models??{},tool_settings:s.tool_settings??{},lang:l.getLang()},client_config:t,env:{shell:process.env.SHELL??process.env.ComSpec??null,term:process.env.TERM_PROGRAM??null,proxies:X()},system:I(),log:M()}}(c,{source:V.source??void 0,revision:V.revision,problem:V.problem}));t?o.succeed(u.t("doctor.report_done",{code:t})):o.fail(u.t("doctor.report_failed",{cli:C}))}else c.some(o=>"fail"===o.status)&&console.log(t.gray("\n"+u.t("doctor.report_hint",{cli:C})));const Z=c.filter(o=>"fail"===o.status);Z.length>0&&(N(Z.map(o=>o.message?`${o.name}: ${o.message}`:o.name).join("; ")),process.exitCode=1)}
|
|
1
|
+
import{refreshClientConfig as o}from"../lib/client-config-sync.js";import e from"chalk";import t from"ora";import{spawnSync as s}from"child_process";import{existsSync as r,readdirSync as n,readFileSync as a}from"fs";import{connect as c}from"net";import{join as i}from"path";import{configManager as l}from"../lib/config.js";import{savedApiKey as d}from"./base.js";import{toolManager as p}from"../lib/tool-manager.js";import{i18n as u}from"../lib/i18n.js";import{validateApiKey as m}from"../lib/api-validator.js";import{getAdapter as f}from"../lib/tools/registry.js";import{findInstalls as g,installLabel as _}from"../lib/tools/tool-installs.js";import{detectManagedOverrides as h}from"../lib/tools/claude-managed.js";import{codexAuthProblem as y,codexCatalogRejection as k,codexConfigPath as w,codexWorkModeOn as b}from"../lib/tools/codex.js";import{claudeAccountLoginPresent as j}from"../lib/tools/claude-code.js";import{toolHome as v}from"../lib/tools/types.js";import{gatewayAddresses as x,probeGatewayAddress as $}from"../lib/gateway-addresses.js";import{listAdapters as T}from"../lib/tools/registry.js";import{logger as A}from"../utils/logger.js";import{maskHome as P,maskSecrets as R,noteFailureReason as C,uploadReport as N}from"../lib/telemetry.js";import{systemReport as O}from"../lib/system-report.js";import{CLI_NAME as I}from"../lib/brand.js";import{appStatus as H,appStatusText as L,appTools as S,appUpgradeCommand as K,getApp as U}from"../lib/app-update.js";import{balanceLookupEnabled as E,balanceNeedsAttention as B,balanceText as G,fetchKeyBalances as D}from"../lib/key-balance.js";const F=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"];function q(o,e,t=3e3){return new Promise(s=>{const r=c({host:o,port:e}),n=o=>{r.destroy(),s(o)};r.setTimeout(t,()=>n(!1)),r.once("connect",()=>n(!0)),r.once("error",()=>n(!1))})}function M(){const o=A.getLogDir();if(!r(o))return"";const e=n(o).filter(o=>/^\d{4}-\d{2}-\d{2}\.log$/.test(o)).sort().slice(-2).map(e=>`== ${e}\n`+a(i(o,e),"utf-8")).join("\n");return R(e.slice(-15e4))}function X(){const o={};for(const e of F){const t=process.env[e]?.trim();if(t)try{const s=new URL(t.includes("://")?t:`http://${t}`);o[e]=`${s.protocol}//${s.host}`}catch{o[e]="(unparsable)"}}return o}export async function doctorCommand(r={}){const n=t(u.t("doctor.checking")).start(),c=[],A=Number(process.versions.node.split(".")[0]);c.push({name:"Node.js",status:A>=20?"pass":"fail",message:`v${process.versions.node}`}),n.text=u.t("doctor.check_proxy"),c.push(await async function(){const o=u.t("doctor.proxy"),e=new Map;for(const o of F){const t=process.env[o]?.trim();t&&!e.has(t)&&e.set(t,o)}if(0===e.size)return{name:o,status:"pass",message:u.t("doctor.proxy_none")};const t=[];for(const[o,s]of e){let e;try{e=new URL(o.includes("://")?o:`http://${o}`)}catch{t.push(`${s}=${o}`);continue}const r=Number(e.port)||("https:"===e.protocol?443:e.protocol.startsWith("socks")?1080:80);await q(e.hostname,r)||t.push(`${s}=${o}`)}return 0===t.length?{name:o,status:"pass",message:[...e.keys()].join(", ")}:{name:o,status:"fail",message:u.t("doctor.proxy_dead",{proxies:t.join(", ")})}}()),n.text=u.t("doctor.check_api_key_network");const R=d(),Y=u.t("doctor.api_key_network");if(R){const o=await m(R);o.valid?(c.push({name:Y,status:"pass"}),n.text=u.t("doctor.check_balance"),c.push(...await async function(o){if(!E())return[];const e=l.listToolApiKeys().map(o=>({tool:o,key:l.getApiKeyForTool(o)})).filter(e=>Boolean(e.key)&&e.key!==o),t=await D([o,...e.map(o=>o.key)]),s=[{name:u.t("doctor.balance"),key:o},...e.map(o=>({name:u.t("doctor.balance_tool",{tool:f(o.tool)?.displayName??o.tool}),key:o.key}))],r=[];for(const o of s){const e=t.get(o.key);e&&r.push({name:o.name,status:B(e)?"warn":"pass",message:G(e)})}return r}(R))):"invalid_api_key"===o.error?c.push({name:Y,status:"fail",message:u.t("doctor.api_key_invalid")}):(c.push({name:Y,status:"fail",message:`${u.t("doctor.network_error")}: ${o.message??o.error}`}),n.text=u.t("doctor.check_other_addresses"),c.push(await async function(){const o=u.t("doctor.other_addresses"),e=l.getBaseUrl(),t=x().filter(o=>o.url!==e),s=d(),r=await Promise.all(t.map(o=>$(o.url,{apiKey:s}))),n=t.filter((o,e)=>r[e].ok).map(o=>o.url);return 0===n.length?{name:o,status:"fail",message:u.t("doctor.other_addresses_none")}:{name:o,status:"warn",message:u.t("doctor.other_addresses_found",{urls:n.join(", ")})}}()))}else c.push({name:Y,status:"fail",message:u.t("doctor.api_key_missing")});n.text=u.t("doctor.check_client_config");const V=await o();c.push({name:u.t("doctor.client_config"),status:"cloud"===V.source||"cache"===V.source&&!V.problem?"pass":"warn",message:[V.source?u.t(`refresh.source.${V.source}`):u.t("refresh.source.none"),V.revision?u.t("doctor.client_config_revision",{revision:V.revision}):"",V.problem??""].filter(Boolean).join(" · ")}),n.text=u.t("doctor.check_tools");const W=p.getInstalledTools();c.push({name:u.t("doctor.installed_tools"),status:W.length>0?"pass":"warn",message:W.length>0?W.map(o=>f(o)?.displayName??o).join(u.t("setup.list_separator")):u.t("doctor.no_tools_installed")}),c.push(...function(){const o=[];for(const e of p.getInstalledTools()){const t=f(e);if(!t?.installSpec)continue;const s=g(t.installSpec);if(0===s.length)continue;const r=[],n=p.outdatedVersion(e);n&&r.push(u.t("doctor.tool_outdated",{min:n.min})),s.length>1&&r.push(u.t("doctor.tool_duplicates",{others:s.slice(1).map(_).join("、")})),o.push({name:t.displayName,status:r.length>0?"warn":"pass",message:[_(s[0]),...r,...r.length>0?[u.t("doctor.run_upgrade",{tool:e})]:[]].join("\n ")})}return o}()),c.push(...await async function(){const o=[];for(const e of S()){const t=await H(e,{refresh:!0});if(!t.installed||!t.current)continue;const s=u.t("doctor.app_version",{tool:t.name});if(t.outdated){const r=t.blocker?u.t(`app_update.blocked_${t.blocker}`,{tool:t.name,url:U(e)?.appInstaller.downloadPage??"",command:K(e)}):u.t("doctor.run_app_upgrade",{command:K(e)});o.push({name:s,status:"warn",message:`${L(t)}\n ${r}`})}else o.push({name:s,status:"pass",message:L(t)})}return o}());const z=function(){if(!p.isToolInstalled("claude-code"))return null;const o=u.t("doctor.claude_config"),e=h();if(e.length>0){const t=e.map(o=>`${o.source}: ${o.keys.join(", ")}`).join("; ");return{name:o,status:"fail",message:u.t("doctor.claude_managed",{detail:t})}}let t={};try{t=JSON.parse(a(i(process.env.CLAUDE_CONFIG_DIR?.trim()||i(v(),".claude"),"settings.json"),"utf-8")).env??{}}catch{}const s=l.getApiKeyForTool("claude-code");return t.ANTHROPIC_AUTH_TOKEN&&t.ANTHROPIC_BASE_URL?t.ANTHROPIC_BASE_URL!==l.getBaseUrl()||s&&t.ANTHROPIC_AUTH_TOKEN!==s?{name:o,status:"warn",message:u.t("doctor.claude_config_changed")}:{name:o,status:"pass"}:{name:o,status:"warn",message:u.t("doctor.claude_not_configured")}}();z&&c.push(z),W.includes("claude-code")&&j()&&c.push({name:u.t("doctor.claude_login"),status:"pass",message:u.t("tools.claude_code.account_login_overridden")});const J=W.includes("codex")?y():null;if(W.includes("codex")){const o=l.getApiKeyForTool("codex"),e=f("codex")?.detectCurrentConfig().apiKey,t=!J&&!!o&&!!e&&e!==o;c.push({name:u.t("doctor.codex_auth"),status:J?"fail":t?"warn":"pass",message:J?u.t(`doctor.codex_${J}`,{path:P(w())}):t?u.t("doctor.codex_key_changed"):void 0})}if(W.includes("codex")){const o=k();c.push({name:u.t("doctor.codex_catalog"),status:o?"fail":"pass",message:o?u.t("doctor.codex_catalog_rejected",{path:o.bin,version:o.version??"?",error:o.error}):void 0})}W.includes("codex")&&b()&&c.push({name:u.t("doctor.codex_work_mode"),status:"warn",message:u.t("tools.codex.work_mode_on")}),"win32"===process.platform&&W.includes("claude-code")&&!process.env.CLAUDE_CODE_GIT_BASH_PATH&&c.push({name:"Git for Windows",status:p.isGitInstalled()?"pass":"warn",message:p.isGitInstalled()?void 0:u.t("tools.claude_code.no_git_bash")}),r.deep&&W.includes("claude-code")&&(n.text=u.t("doctor.check_claude_request"),c.push(function(){const o=u.t("doctor.claude_request"),e=g(f("claude-code").installSpec)[0];if(!e)return{name:o,status:"warn",message:u.t("doctor.claude_request_skipped")};const t={encoding:"utf-8",timeout:12e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},r=["-p","Reply with the single word OK."],n=/\.cmd$/i.test(e.path)?s(`"${e.path}" ${r.map(o=>`"${o}"`).join(" ")}`,{...t,shell:!0}):s(e.path,r,t),a=`${n.stdout??""}`.trim();if(0===n.status&&a)return{name:o,status:"pass",message:a.slice(0,80)};const c=(`${n.stderr??""}`.trim()||a||n.error?.message||`exit ${n.status}`).slice(0,300);return{name:o,status:"fail",message:u.t("doctor.claude_request_failed",{reason:c})}}())),n.stop(),console.log("\n"+e.bold(u.t("doctor.results_title"))+"\n");const Q={pass:e.green("√"),warn:e.yellow("!"),fail:e.red("×")};for(const o of c)console.log(`${Q[o.status]} ${o.name}`),o.message&&console.log(e.gray(` ${o.message}`));if(c.every(o=>"pass"===o.status)&&console.log("\n"+e.green.bold(u.t("doctor.all_good"))),!r.deep&&W.includes("claude-code")&&console.log(e.gray("\n"+u.t("doctor.deep_hint"))),r.report){const o=t(u.t("doctor.report_uploading")).start(),e=await N(function(o,e){const t={};for(const o of T()){if(o.hidden)continue;let e=null;try{e=p.detectCurrentConfig(o.name).apiKey?"has_key":"no_key"}catch{e="unreadable"}t[o.name]={installed:p.isToolInstalled(o.name),version:p.installedVersion(o.name),copies:o.installSpec?g(o.installSpec).map(o=>({kind:o.kind,version:o.version,path:o.path})):void 0,config:e}}const s=l.getProfile();return{checks:o,tools:t,settings:{base_url:l.getBaseUrl(),profile:l.getActiveProfileName(),profiles:l.listProfiles().length,key_fingerprint:l.getApiKeyFingerprint()||null,tool_keys:Object.keys(s.tool_api_keys??{}),models:s.models,tool_models:s.tool_models??{},tool_settings:s.tool_settings??{},lang:l.getLang()},client_config:e,env:{shell:process.env.SHELL??process.env.ComSpec??null,term:process.env.TERM_PROGRAM??null,proxies:X()},system:O(),log:M()}}(c,{source:V.source??void 0,revision:V.revision,problem:V.problem}));e?o.succeed(u.t("doctor.report_done",{code:e})):o.fail(u.t("doctor.report_failed",{cli:I}))}else c.some(o=>"fail"===o.status)&&console.log(e.gray("\n"+u.t("doctor.report_hint",{cli:I})));const Z=c.filter(o=>"fail"===o.status);Z.length>0&&(C(Z.map(o=>o.message?`${o.name}: ${o.message}`:o.name).join("; ")),process.exitCode=1)}
|
package/dist/commands/refresh.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"chalk";import{refreshClientConfig as e}from"../lib/client-config-sync.js";import{i18n as r}from"../lib/i18n.js";import{lastModelRefreshOutcome as s,runModelRefresh as t}from"../lib/model-refresh.js";import{runPendingElevations as
|
|
1
|
+
import o from"chalk";import{refreshClientConfig as e}from"../lib/client-config-sync.js";import{i18n as r}from"../lib/i18n.js";import{lastModelRefreshOutcome as s,runModelRefresh as t}from"../lib/model-refresh.js";import{runPendingElevations as l}from"../lib/post-apply.js";import{listAdapters as c}from"../lib/tools/registry.js";export async function refreshCommand(){const n=await e({force:!0}),i=n.source?r.t(`refresh.source.${n.source}`):r.t("refresh.source.none");console.log(o.gray(r.t("refresh.config",{source:i,revision:n.revision||"-"}))+(n.problem?o.yellow(` ${r.t("refresh.problem",{problem:n.problem})}`):""));const f=await t(["refresh"],{force:!0,output:o=>console.log(o)});await l(c().map(o=>o.name));const{checked:m,failed:h,keyMismatch:a}=s();for(const e of a)console.log(o.yellow(r.t("refresh.key_mismatch",{tool:e})));f.length>0||(0===m&&0===h&&0===a.length?console.log(o.gray(r.t("refresh.nothing_checked"))):m>0&&0===h&&console.log(o.green(r.t(a.length>0?"refresh.others_up_to_date":"refresh.up_to_date"))))}
|
package/dist/lib/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{configManager as v}from"./config.js";import{npmCacheArgs as y}from"./npm-cache.js";import{i18n as b}from"./i18n.js";import{appLatest as _,appStatus as $,appStatusWith as P,cachedAppStatus as x,getApp as A}from"./app-update.js";import{compareVersions as k}from"./model-registry.js";import{isJsonMode as D}from"./runtime-options.js";import{maskSecrets as S,track as j}from"./telemetry.js";import{failureContext as L,lastCommandExit as E,lastCommandOutput as C,runWatched as R}from"./tool-upgrade.js";import{runInstallScript as M,traceSummary as T}from"./install-script.js";import{atomicWriteFile as N}from"./tools/backup.js";import{getAdapter as O}from"./tools/registry.js";import{findInstallsIncludingNative as U,forgetInstalls as I,NPM_MIRROR as B,npmMirrorVersion as F}from"./tools/tool-installs.js";import{toolHome as J}from"./tools/types.js";import{logger as V}from"../utils/logger.js";let H=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}export function setComponentManifestForTests(t){H=null===t?null:parseManifest(t)}export function listComponents(){return(H||(H=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),H).components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let W=null;export function componentPlatform(){return W??process.platform}const G=/\{(scripts|agy|devtools|claudeDesktop|chatgptDesktop)\}/g;export function devtoolsMirror(){return h().installMirror?.devtools?.replace(/\/+$/,"")||void 0}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(G,(t,n)=>{const r=e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(G,(t,e)=>{const o=h().installMirror?.[e];return o??t})}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(q??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let q=null,K=!0,X=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},Z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function z(t){try{return a(t)}catch{return t}}function Y(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=J();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(Q(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function Q(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=J();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let tt=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},et=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],i=o=>{if(!function(t){try{return s(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!Z())return;const i=z(o),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=n.exec(X(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...et??=st(()=>tt())??[]);for(const t of l)if(t&&p(t))for(const n of Y(o.command,e))i(d(t,n));for(const o of knownRuntimePaths(t.id,e))(K||o.startsWith(J()))&&i(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=J();return"node"===t?"win32"===e?d(Q(e,o),"aliases","default","node.exe"):d(Q(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=z(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,i=a(r),s=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>i.includes(a(t))||s.includes(a(t)),p=t=>i.startsWith(a(t)+l)||s.startsWith(a(t)+l),f=J(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(Q(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function ot(){return d(v.getConfigDir(),"component-releases.json")}function nt(){try{const t=JSON.parse(n(ot(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function rt(t,e){try{o(v.getConfigDir(),{recursive:!0}),l(ot(),JSON.stringify({...nt(),[t]:e},null,2))}catch(t){V.logError("components.writeCache",t)}}let at=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const it=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?it.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=nt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await at(o.url));case"devtools":if(o.platforms&&!o.platforms.includes(e))return null;{const t=devtoolsMirror();return t?devtoolsVersion(await at(`${t}/versions.txt`),o.key):null}case"npm":{if(o.staleTag){const e=O(t.adapter??"")?.installSpec,o=e?await F(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await at(`${B}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=it.exec(await at(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&rt(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return V.logError(`components.latest(${t.id})`,e),rt(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,A(t.app)?await _(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=A(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?P(t.app,e.latest):e.offline?x(t.app):await $(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?st(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,i=null,s=null;if("cli"===t.category){const e=O(t.adapter)?.installSpec,o=e?U(e)[0]:void 0;o&&(a=o.version,i=o.path,s={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,i=e.path,s=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:nt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?nt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&k(a,u.version)>=0);return{...r,installed:Boolean(i),current:a,latest:l,outdated:Boolean(a&&l&&k(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:i,managed_by:s?.by??null,auto_upgrade:s?.auto??!1,...s?.hint?{hint:s.hint}:{},...c?{error:c}:{}}}function st(t){try{return t()}catch{return null}}const lt={idleMs:18e4,timeoutMs:36e5};let ct,ut=async(t,e)=>(ct=await M({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...lt,env:e},output:C,run:(t,e,o)=>R(t,e,o)}),"ok"===ct.outcome),pt=async(t,e)=>"ok"===await R(t,e,lt);function dt(t){D()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(z(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),i=[],s=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&i.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return i}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||s(d(a,t,e),`${t}/${e}`)}catch{}else s(d(a,t),t);return i}function mt(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function ft(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),i=await componentStatus(t,{refresh:!0}),s=t.name;if(!i.supported)return dt(g.yellow(" ! "+b.t("components.unsupported_platform",{tool:s}))),mt(i,"unavailable",{reason:"unsupported_platform"});if(i.blocker)return dt(g.yellow(" ! "+function(t,e){return b.t(`components.blocked_${t}`,{tool:e})}(i.blocker,s))),mt(i,"unavailable",{reason:i.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(i.installed&&!n.force){const o=g.gray(`(${i.path})`);if(i.latest&&!i.outdated)return dt(g.green(" √ "+b.t("components.up_to_date",{tool:s,current:i.current??"?"}))+o),"upgrade"===e&&dt(g.gray(" "+b.t("components.force_hint",{command:`${ft(t.id)} --force`}))),mt(i,"install"===e?"already_installed":"up_to_date");if("install"===e)return dt(g.green(" √ "+b.t("components.already_installed",{tool:s,current:i.current??"?"}))+o),i.outdated&&dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"already_installed",i.outdated?{hint:upgradeAdvice(i)}:{});if(!i.latest)return dt(g.yellow(" ! "+b.t("components.no_latest",{tool:s,current:i.current??"?",how:ht(i)}))),mt(i,"manual",{reason:i.error??"no_latest",hint:i.hint});if(!i.auto_upgrade)return dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"manual",{hint:i.hint})}if(!l)return dt(g.yellow(" ! "+b.t("components.no_mirror",{tool:s}))),mt(i,"unavailable",{reason:"no_mirror"});i.installed&&!i.auto_upgrade&&dt(g.yellow(" ! "+b.t("components.force_beside",{tool:s,path:i.path??"?",by:i.managed_by??"?"})));const p={};i.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&i.installed&&i.auto_upgrade&&i.path&&(p.UV_INSTALL_DIR=u(i.path));const d=t.upgrade?.migrateGlobalPackages&&i.installed&&"fnm"===i.managed_by&&i.path,m=d?globalPackages(i.path,a):[],f=d?z(i.path):null;dt(g.gray(" "+b.t(i.installed?"components.upgrading":"components.installing",{tool:s,latest:i.latest??"",source:i.source}))),j(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:i.current}}),d&&m.length&&f&&function(t){try{o(v.getConfigDir(),{recursive:!0}),N(vt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){V.logError("components: note migration",t)}}({packages:m,old_node:f}),ct=void 0;const w=await ut(l,p);I(),et=null;const y=probeRuntime(t,a),_=scriptTarget(t.id,a,{...process.env,...p}),$=(_?y.find(t=>{return e=t.path,o=_,"win32"===a?z(e).toLowerCase()===z(o).toLowerCase():z(e)===z(o);var e,o}):void 0)??y.find(e=>runtimeManager(t.id,e.path,a).auto)??y[0];if(!w||!$){yt();const e=ct;return j(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(C())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...T(e.trace)}:{},...E(),...L()}}),dt(g.red(" × "+b.t("components.script_failed",{tool:s,command:(i.installed?ft:gt)(t.id)}))),mt(i,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&z($.path)!==f&&(P=await wt(m,$.path,a)?"done":"failed"),"failed"!==P&&yt();const x=y[0];x&&x.path!==$.path&&x.version&&$.version&&k(x.version,$.version)<0&&dt(g.yellow(" ! "+b.t("components.path_shadowed",{tool:s,active:x.path,version:$.version,path:$.path}))),i.latest&&$.version&&k($.version,i.latest)<0&&(rt(`${t.id}:${a}:ceiling`,{version:$.version,error:i.latest,checked_at:Date.now()}),dt(g.yellow(" ! "+b.t("components.capped",{tool:s,latest:i.latest,version:$.version})))),j(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=i.installed?n.force&&!i.outdated?"reinstalled":"upgraded":"installed";var D;return dt(g.green(" √ "+("installed"===A?b.t("components.installed",{tool:s,version:$.version??"?"}):"reinstalled"===A?b.t("components.reinstalled",{tool:s,version:$.version??"?"}):b.t("components.upgraded",{tool:s,from:i.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),D=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===D.toLowerCase():t===D)||dt(g.gray(" "+b.t("components.new_terminal"))),mt(i,A,{version_after:$.version})}function gt(t){return`${w} install ${t}`}function ht(t){return t.hint?t.hint:b.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?b.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:ft(t.id)}):b.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:ht(t),command:`${ft(t.id)} --force`})}async function wt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;dt(g.gray(" "+b.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(z(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),i=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${B}`,"--no-fund","--no-audit","--loglevel=error",...y(v.getConfigDir())];return!!await pt(a,i)||(dt(g.yellow(" ! "+b.t("components.migrate_failed",{command:[a,...i].join(" ")}))),!1)}const vt=()=>d(v.getConfigDir(),"node-migration.json");function yt(){try{i(vt(),{force:!0})}catch(t){V.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(vt()))return"none";t=JSON.parse(n(vt(),"utf-8"))}catch{return yt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||z(a.path)===t.old_node)return yt(),"none";j("component:node","start",{detail:{mode:"resume-migration"}});const i=await wt(t.packages,a.path,o);return i&&yt(),j("component:node",i?"ok":"fail",{detail:{mode:"resume-migration",migration:i?"done":"failed"}}),i?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(W=t.platform),void 0!==t.uid&&(q=t.uid),void 0!==t.systemPaths&&(K=t.systemPaths),t.registryPath&&(tt=t.registryPath,et=null),t.versionRunner&&(X=t.versionRunner),t.macDeveloperTools&&(Z=t.macDeveloperTools),t.fetchText&&(at=t.fetchText),t.scriptRunner&&(ut=t.scriptRunner),t.commandRunner&&(pt=t.commandRunner)}
|
|
1
|
+
import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{withDownloadFallback as v}from"./mirror-url.js";import{configManager as y}from"./config.js";import{npmCacheArgs as b}from"./npm-cache.js";import{i18n as _}from"./i18n.js";import{appLatest as $,appStatus as P,appStatusWith as x,cachedAppStatus as A,getApp as k}from"./app-update.js";import{compareVersions as D}from"./model-registry.js";import{isJsonMode as j}from"./runtime-options.js";import{maskSecrets as S,track as L}from"./telemetry.js";import{failureContext as E,lastCommandExit as C,lastCommandOutput as R,runWatched as M}from"./tool-upgrade.js";import{runInstallScript as T,traceSummary as N}from"./install-script.js";import{atomicWriteFile as O}from"./tools/backup.js";import{getAdapter as U}from"./tools/registry.js";import{findInstallsIncludingNative as I,forgetInstalls as B,NPM_MIRROR as F,npmMirrorVersion as J}from"./tools/tool-installs.js";import{toolHome as V}from"./tools/types.js";import{logger as H}from"../utils/logger.js";let W=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}export function setComponentManifestForTests(t){W=null===t?null:parseManifest(t)}export function listComponents(){return(W||(W=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),W).components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let G=null;export function componentPlatform(){return G??process.platform}const q=/\{(scripts|agy|devtools|claudeDesktop|chatgptDesktop)\}/g;export function devtoolsMirror(){return h().installMirror?.devtools?.replace(/\/+$/,"")||void 0}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(q,(t,n)=>{const r=e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(q,(t,e)=>{const o=h().installMirror?.[e];return o??t})}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(K??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let K=null,X=!0,Z=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function Y(t){try{return a(t)}catch{return t}}function Q(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=V();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(tt(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function tt(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=V();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let et=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},ot=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],i=o=>{if(!function(t){try{return s(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!z())return;const i=Y(o),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=n.exec(Z(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...ot??=lt(()=>et())??[]);for(const t of l)if(t&&p(t))for(const n of Q(o.command,e))i(d(t,n));for(const o of knownRuntimePaths(t.id,e))(X||o.startsWith(V()))&&i(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=V();return"node"===t?"win32"===e?d(tt(e,o),"aliases","default","node.exe"):d(tt(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=Y(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,i=a(r),s=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>i.includes(a(t))||s.includes(a(t)),p=t=>i.startsWith(a(t)+l)||s.startsWith(a(t)+l),f=V(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(tt(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function nt(){return d(y.getConfigDir(),"component-releases.json")}function rt(){try{const t=JSON.parse(n(nt(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function at(t,e){try{o(y.getConfigDir(),{recursive:!0}),l(nt(),JSON.stringify({...rt(),[t]:e},null,2))}catch(t){H.logError("components.writeCache",t)}}let it=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const st=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?st.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=rt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await it(o.url));case"devtools":if(o.platforms&&!o.platforms.includes(e))return null;{const t=devtoolsMirror();return t?devtoolsVersion(await v(`${t}/versions.txt`,void 0,t=>it(t)),o.key):null}case"npm":{if(o.staleTag){const e=U(t.adapter??"")?.installSpec,o=e?await J(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await it(`${F}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=st.exec(await it(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&at(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return H.logError(`components.latest(${t.id})`,e),at(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,k(t.app)?await $(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=k(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?x(t.app,e.latest):e.offline?A(t.app):await P(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?lt(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,i=null,s=null;if("cli"===t.category){const e=U(t.adapter)?.installSpec,o=e?I(e)[0]:void 0;o&&(a=o.version,i=o.path,s={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,i=e.path,s=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:rt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?rt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&D(a,u.version)>=0);return{...r,installed:Boolean(i),current:a,latest:l,outdated:Boolean(a&&l&&D(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:i,managed_by:s?.by??null,auto_upgrade:s?.auto??!1,...s?.hint?{hint:s.hint}:{},...c?{error:c}:{}}}function lt(t){try{return t()}catch{return null}}const ct={idleMs:18e4,timeoutMs:36e5};let ut,pt=async(t,e)=>(ut=await T({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...ct,env:e},output:R,run:(t,e,o)=>M(t,e,o)}),"ok"===ut.outcome),dt=async(t,e)=>"ok"===await M(t,e,ct);function mt(t){j()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(Y(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),i=[],s=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&i.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return i}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||s(d(a,t,e),`${t}/${e}`)}catch{}else s(d(a,t),t);return i}function ft(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function gt(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),i=await componentStatus(t,{refresh:!0}),s=t.name;if(!i.supported)return mt(g.yellow(" ! "+_.t("components.unsupported_platform",{tool:s}))),ft(i,"unavailable",{reason:"unsupported_platform"});if(i.blocker)return mt(g.yellow(" ! "+function(t,e){return _.t(`components.blocked_${t}`,{tool:e})}(i.blocker,s))),ft(i,"unavailable",{reason:i.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(i.installed&&!n.force){const o=g.gray(`(${i.path})`);if(i.latest&&!i.outdated)return mt(g.green(" √ "+_.t("components.up_to_date",{tool:s,current:i.current??"?"}))+o),"upgrade"===e&&mt(g.gray(" "+_.t("components.force_hint",{command:`${gt(t.id)} --force`}))),ft(i,"install"===e?"already_installed":"up_to_date");if("install"===e)return mt(g.green(" √ "+_.t("components.already_installed",{tool:s,current:i.current??"?"}))+o),i.outdated&&mt(g.yellow(" ! "+upgradeAdvice(i))),ft(i,"already_installed",i.outdated?{hint:upgradeAdvice(i)}:{});if(!i.latest)return mt(g.yellow(" ! "+_.t("components.no_latest",{tool:s,current:i.current??"?",how:wt(i)}))),ft(i,"manual",{reason:i.error??"no_latest",hint:i.hint});if(!i.auto_upgrade)return mt(g.yellow(" ! "+upgradeAdvice(i))),ft(i,"manual",{hint:i.hint})}if(!l)return mt(g.yellow(" ! "+_.t("components.no_mirror",{tool:s}))),ft(i,"unavailable",{reason:"no_mirror"});i.installed&&!i.auto_upgrade&&mt(g.yellow(" ! "+_.t("components.force_beside",{tool:s,path:i.path??"?",by:i.managed_by??"?"})));const p={};i.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&i.installed&&i.auto_upgrade&&i.path&&(p.UV_INSTALL_DIR=u(i.path));const d=t.upgrade?.migrateGlobalPackages&&i.installed&&"fnm"===i.managed_by&&i.path,m=d?globalPackages(i.path,a):[],f=d?Y(i.path):null;mt(g.gray(" "+_.t(i.installed?"components.upgrading":"components.installing",{tool:s,latest:i.latest??"",source:i.source}))),L(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:i.current}}),d&&m.length&&f&&function(t){try{o(y.getConfigDir(),{recursive:!0}),O(yt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){H.logError("components: note migration",t)}}({packages:m,old_node:f}),ut=void 0;const w=await pt(l,p);B(),ot=null;const v=probeRuntime(t,a),b=scriptTarget(t.id,a,{...process.env,...p}),$=(b?v.find(t=>{return e=t.path,o=b,"win32"===a?Y(e).toLowerCase()===Y(o).toLowerCase():Y(e)===Y(o);var e,o}):void 0)??v.find(e=>runtimeManager(t.id,e.path,a).auto)??v[0];if(!w||!$){bt();const e=ut;return L(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(R())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...N(e.trace)}:{},...C(),...E()}}),mt(g.red(" × "+_.t("components.script_failed",{tool:s,command:(i.installed?gt:ht)(t.id)}))),ft(i,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&Y($.path)!==f&&(P=await vt(m,$.path,a)?"done":"failed"),"failed"!==P&&bt();const x=v[0];x&&x.path!==$.path&&x.version&&$.version&&D(x.version,$.version)<0&&mt(g.yellow(" ! "+_.t("components.path_shadowed",{tool:s,active:x.path,version:$.version,path:$.path}))),i.latest&&$.version&&D($.version,i.latest)<0&&(at(`${t.id}:${a}:ceiling`,{version:$.version,error:i.latest,checked_at:Date.now()}),mt(g.yellow(" ! "+_.t("components.capped",{tool:s,latest:i.latest,version:$.version})))),L(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=i.installed?n.force&&!i.outdated?"reinstalled":"upgraded":"installed";var k;return mt(g.green(" √ "+("installed"===A?_.t("components.installed",{tool:s,version:$.version??"?"}):"reinstalled"===A?_.t("components.reinstalled",{tool:s,version:$.version??"?"}):_.t("components.upgraded",{tool:s,from:i.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),k=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===k.toLowerCase():t===k)||mt(g.gray(" "+_.t("components.new_terminal"))),ft(i,A,{version_after:$.version})}function ht(t){return`${w} install ${t}`}function wt(t){return t.hint?t.hint:_.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?_.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:gt(t.id)}):_.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:wt(t),command:`${gt(t.id)} --force`})}async function vt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;mt(g.gray(" "+_.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(Y(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),i=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${F}`,"--no-fund","--no-audit","--loglevel=error",...b(y.getConfigDir())];return!!await dt(a,i)||(mt(g.yellow(" ! "+_.t("components.migrate_failed",{command:[a,...i].join(" ")}))),!1)}const yt=()=>d(y.getConfigDir(),"node-migration.json");function bt(){try{i(yt(),{force:!0})}catch(t){H.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(yt()))return"none";t=JSON.parse(n(yt(),"utf-8"))}catch{return bt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||Y(a.path)===t.old_node)return bt(),"none";L("component:node","start",{detail:{mode:"resume-migration"}});const i=await vt(t.packages,a.path,o);return i&&bt(),L("component:node",i?"ok":"fail",{detail:{mode:"resume-migration",migration:i?"done":"failed"}}),i?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(G=t.platform),void 0!==t.uid&&(K=t.uid),void 0!==t.systemPaths&&(X=t.systemPaths),t.registryPath&&(et=t.registryPath,ot=null),t.versionRunner&&(Z=t.versionRunner),t.macDeveloperTools&&(z=t.macDeveloperTools),t.fetchText&&(it=t.fetchText),t.scriptRunner&&(pt=t.scriptRunner),t.commandRunner&&(dt=t.commandRunner)}
|
package/dist/lib/mirror-url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{brand as t}from"./brand.js";import{configManager as e}from"./config.js";const r=/\/-\/releases\/latest$/;export function mirrorFileUrl(t,e,o){const n=t.replace(/\/+$/,"");if(r.test(n)){const t=n.replace(r,"");return o?`${t}/-/releases/download/${o}/${e}`:`${t}/-/releases/latest/download/${e}`}return`${n}/${e}`}export function mirrorPageUrl(t){const e=t.replace(/\/+$/,""),r=/^(.*\/-\/releases)\/download\/([^/]+)$/.exec(e);return r?`${r[1]}/tag/${r[2]}`:e.replace(/\/-\/releases\/latest\/download$/,"/-/releases/latest")}const o=/^\/[^?#]+\/-\/releases\/(?:latest\/download|download\/[^/]+)\/[^/]+$/,n=/^\/dl\/[^/]+\/[^/]+$/;function a(t){try{const e=new URL(t);return"https:"===e.protocol&&!e.search&&n.test(e.pathname)?e:null}catch{return null}}export function downloadUrls(t,e){if(a(t))return[t,`${t}?alt=1`];if(!e||!t.startsWith("https://cnb.cool/"))return[t];const r=t.slice(16);return o.test(r)?[`${e.replace(/\/+$/,"")}${r}`,t]:[t]}export async function withDownloadFallback(t,e,r){const o=downloadUrls(t,e);for(const t of o.slice(0,-1))try{return await r(t)}catch{}return r(o[o.length-1])}export async function mirrorFetch(r,o={},n=(...t)=>fetch(...t),s=()=>e.getApiKey()?.trim()){const l=a(r.replace(/\?alt=\d+$/,"")),c=l&&function(){const e=new Set;for(const r of Object.values(t().installMirror??{}))try{const t="string"==typeof r&&r?new URL(r):null;"https:"===t?.protocol&&t.pathname.startsWith("/dl/")&&e.add(t.origin)}catch{}return e}().has(l.origin)?s():void 0;if(!c)return n(r,o);let i=new URL(r);for(let t=0;t<=5;t++){const t=new Headers(o.headers);t.set("Authorization",`Bearer ${c}`);const e=await n(i.toString(),{...o,headers:t,redirect:"manual"}),r=e.headers.get("location");if(e.status<300||e.status>=400||!r)return e;await(e.body?.cancel().catch(()=>{}));const a=new URL(r,i);if(a.origin!==i.origin)return n(a.toString(),o);i=a}throw new Error(`${r}: too many redirects`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import r from"chalk";import{configManager as n}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as
|
|
1
|
+
import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import r from"chalk";import{configManager as n}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as i}from"./model-catalog.js";import{listAdapters as l}from"./tools/registry.js";import{UserActionNeeded as f}from"./tools/types.js";import{logger as a}from"../utils/logger.js";import{resolveUpdateCachePath as c}from"./auto-update.js";import{isHelpRequest as d}from"./cli-help.js";import{brandEnvName as m}from"./brand.js";import{atomicWriteFile as u}from"./tools/backup.js";import{track as h}from"./telemetry.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const p=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),g=["--json","--dry-run","--help","-h","--version","-v"],y=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[m("DISABLE_MODEL_REFRESH")])return!0;if(g.some(o=>e.includes(o))||d(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&p.has(t)}let M={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...M,keyMismatch:[...M.keyMismatch]}}export async function refreshModelMenus(){const e=new Map,o=[];y.length=0,M={checked:0,failed:0,offline:0,keyMismatch:[]};for(const t of l())if(t.refreshModelMenu&&t.listedModels)try{const r=n.getApiKeyForTool(t.name);if(!r)continue;const s=t.detectCurrentConfig().apiKey;if(s!==r){s&&(M.keyMismatch.push(t.displayName),h(`menu-sync:${t.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const l=t.listedModels();if(null===l)continue;e.has(r)||e.set(r,await i(r));const f=e.get(r);if(!f){M.offline++;continue}t.refreshModelMenu({apiKey:r,baseUrl:n.getBaseUrl(),models:n.getModelsForTool(t.name),settings:n.getToolSettings(t.name),catalog:f}),M.checked++;const a=t.listedModels();if(null===a){o.push({tool:t.displayName,added:[],removed:[],fromGateway:!0});continue}const c=a,d=c.filter(e=>!l.includes(e)),m=l.filter(e=>!c.includes(e));(d.length>0||m.length>0)&&o.push({tool:t.displayName,added:d,removed:m})}catch(e){M.failed++,a.logError(`modelRefresh(${t.name})`,e),h(`menu-sync:${t.name}`,e instanceof f?"skip":"fail",{error:e}),e instanceof f&&y.push(e.message)}return o}export async function runModelRefresh(n,i={}){const l=i.env??process.env,f=i.now??Date.now(),d=function(e){return t(o(c(e)),"model-refresh.json")}(l);if(!i.force){if(shouldSkipModelRefresh(n,l))return[];if(f-function(o){try{const t=JSON.parse(e(o,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(d)<36e5)return[]}let m=[];try{m=await refreshModelMenus();const e=M.offline>0&&0===M.checked&&0===M.failed,o=e?f-36e5+6e5:f;e&&h("menu-sync","skip",{detail:{reason:"offline",tools:M.offline}}),u(d,JSON.stringify({refreshed_at:o})+"\n")}catch(e){a.logError("runModelRefresh",e)}const p=i.output??(e=>console.log(r.gray(e)));for(const e of y)p(e);for(const e of m){if(e.fromGateway){p(s.t("model_refresh.from_gateway",{tool:e.tool}));continue}const o=[e.added.length>0?s.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?s.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);p(s.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return m}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as r}from"child_process";import{createHash as e}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{
|
|
1
|
+
import{execFileSync as r}from"child_process";import{createHash as e}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{mirrorFetch as P,mirrorFileUrl as L,withDownloadFallback as O}from"../mirror-url.js";import{powerShellEnv as E}from"../powershell-env.js";export function readDesktopCliPin(r,e,t=!1){const o=r.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=r.lastIndexOf("JSON.parse('",o),n=r.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(r.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[e],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 e=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(e)){const r=n(e).filter(r=>/^app-\d+\.\d+\.\d+$/.test(r)).sort((r,e)=>e.localeCompare(r,void 0,{numeric:!0}));for(const t of r){const r=m(e,t,"resources","app.asar");if(s(r))return r}}try{const e=r("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(r=>`'${r}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:E()});for(const r of e.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)){const e=m(r,"app","resources","app.asar");if(s(e))return e}}catch(r){y.logError("claude-desktop-cli.windowsAsarPath",r)}return null}function F(){if($("TEST_HOME")?.trim())return null;for(const r of["/usr/lib/claude-desktop","/opt/Claude"]){const e=m(r,"resources","app.asar");if(s(e))return e}return null}function T(){for(const r of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const e=m(r,"Contents","Resources","app.asar");if(s(e))return e}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?j():"darwin"===process.platform?T():"linux"===process.platform?F():null}class K extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(r){super(),this.dest=r}_write(r,e,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,r]):r,this.drain().then(()=>t()).catch(t)}_final(r){this.remaining>0?r(new Error("archive ends inside an entry")):r()}target(r){const e=h(r);if(!e||d(e)||".."===e||e.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${r}`);return m(this.dest,e)}async closeFile(){const r=this.file;this.file=null,r&&await new Promise((e,t)=>r.end(r=>r?t(r):e()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const r=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(r.length),this.remaining-=r.length,this.collectingLongName?this.collectingLongName.push(r):this.file&&!this.file.write(r)&&await new Promise(r=>this.file.once("drain",()=>r())),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 r=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),r.every(r=>0===r))continue;const e=(e,t)=>r.subarray(e,e+t).toString("utf-8").replace(/\0.*$/s,""),t=e(345,155);let s=t?`${t}/${e(0,100)}`:e(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(e(124,12).trim()||"0",8),i=511&parseInt(e(100,8).trim()||"644",8),a=e(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 r=this.target(s);await l(m(r,".."),{recursive:!0}),this.file=o(r,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(r){const o=readDesktopCliPin(r.asar,r.platformKey,r.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(r.bundle&&!r.download)return{status:"skipped",reason:"no bundle mirror"};const n=r.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(r.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=r.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(r.bundle){if(r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version),await r.download(o.version,y),await async function(r,o,s){const n=e("sha256");if(await v(t(r),new b({write(r,e,t){n.update(r),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(r),i(),new K(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 e=r.localVersionsDir?m(r.localVersionsDir,o.version):null;if(e&&s(e))r.onStart?.(o.version,"local"),await a(e,g),n="local";else{r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version);const e=r.download??((e,t)=>C(r.platformKey,e,t));await e(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 V=(...r)=>fetch(...r);export function setDesktopCliFetchForTests(r){V=r}export async function ensureDesktopCli(r){const e=x();if(!e)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=j();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,localVersionsDir:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=T();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=r;return installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,bundle:!0,onDownload:r.onDownload,onStart:r.onStart,download:s&&n?(r,t)=>O(L(s,`d1-cli-${r}-${e}.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,r=>async function(r,e){const t=await P(r,{signal:AbortSignal.timeout(9e5)},V);if(!t.ok||!t.body)throw new Error(`${r}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(e))}(r,t)):void 0})}if("linux"===process.platform){const t=F();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e.replace(/-musl$/,""),localVersionsDir:e.endsWith("-musl")?void 0:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readdirSync as p,readFileSync as u,renameSync as d,rmSync as f,statSync as m}from"fs";import{cpus as g,tmpdir as h}from"os";import{basename as w,dirname as $,join as y}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as E}from"../../utils/logger.js";import{i18n as v}from"../i18n.js";import{powerShellEnv as k}from"../powershell-env.js";import{toolHome as P}from"./types.js";import{configManager as _}from"../config.js";import{brand as b}from"../brand.js";import{mirrorFileUrl as I,withDownloadFallback as C}from"../mirror-url.js";import{processAlive as T}from"../../utils/process-alive.js";const M=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:k()});return n.error&&E.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let j=M,R=(...t)=>fetch(...t),F=null,N=null,O=null,D=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(j=t.run??M),void 0!==t.fetch&&(R=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(F=t.platform),void 0!==t.arm64&&(N=t.arm64),void 0!==t.privileged&&(O=t.privileged),void 0!==t.remote&&(D=t.remote)}export function appPlatform(){return F??process.platform}export function isArm64Machine(){return null!==N?N:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(g()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||v.t("app_update.reason_unknown");throw new DesktopInstallError(v.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function W(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function B(t,e){const r=await R(t,{signal:AbortSignal.timeout(e)});if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function H(t,e){try{const r=u(y(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return H(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(H(t,"CFBundleShortVersionString")??"")?.[0]??null}function V(t){try{return r(t,o.W_OK),!0}catch{return!1}}const L=t=>`'${t.replace(/'/g,"''")}'`;function U(t,e=12e4){return j("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>["/Applications",y(P(),"Applications")],s=()=>{const e=[];for(const r of o()){let o;try{o=p(r)}catch{continue}for(const n of t.macApp.installedNames)for(const t of o){if(!t.startsWith(`.${n}.`))continue;const o=/^(\d+)\.(new|old)$/.exec(t.slice(n.length+2));o&&!T(Number(o[1]))&&e.push({path:y(r,t),target:y(r,n),kind:o[2]})}}return e},g=()=>{if("darwin"===appPlatform())for(const e of s())if("old"===e.kind&&!a(e.target)&&a(y(e.path,"Contents","Info.plist")))try{d(e.path,e.target),E.debug(`${t.id}: restored ${e.target} from an interrupted install`)}catch(e){E.logError(`${t.id}: restore interrupted install`,e)}},k=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(O??0===process.getuid?.())?"root":"win32"===o&&(null!==O?O:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==D?D:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},M=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await B(I(o,n),r),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},F=()=>{g();for(const e of o())for(const r of t.macApp.installedNames){const o=y(e,r);if(!a(y(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},N=e=>{const r=j("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=j("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=j("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},H=()=>{const e=F();let r=e;if(!r){const e=V("/Applications")?"/Applications":y(P(),"Applications");r=y(e,t.macApp.installedNames[0])}const o=$(r);return(a(o)&&!V(o)||e&&!V(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},G=e=>{const r=U(`$s = Get-AuthenticodeSignature -LiteralPath ${L(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},J=()=>{const e=U(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:k,latestVersion:M,installedMacApp:F,windowsPackageVersion:J,verifyMacApp:N,verifyWindowsPackage:G,install:async(o={})=>{const P=k();P&&fail("blocked",{reason:v.t(`app_update.reason_${P}`)}),(()=>{if("darwin"===appPlatform()){g();for(const e of s())try{f(e.path,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove leftover`,e)}}const e=new Set(["mnt"]);for(const r of["darwin","win32"])for(const o of[!0,!1]){const n=t.asset(r,o);n&&e.add(n)}const r=new RegExp(`^${t.id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}-[A-Za-z0-9]{6}$`);let o=[];try{o=p(h())}catch{}for(const n of o){if(!r.test(n))continue;const o=y(h(),n);try{if(!m(o).isDirectory())continue;const t=p(o);if(0===t.length||!t.every(t=>e.has(t)))continue;const r=Math.max(...[o,...t.map(t=>y(o,t))].map(t=>m(t).mtimeMs));if(Date.now()-r<864e5)continue;const n=y(o,"mnt");if("darwin"===appPlatform()&&a(n)&&(j("hdiutil",["detach",n,"-force"],{timeout:6e4}),p(n).length>0))continue;f(o,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove stale work folder`,e)}}})();const T=e(),F=r();let O;try{O=await M(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const D=e=>I(T,e,t.releaseTag?.(O)),V=b().installMirror?.downloadCounter;let X;try{X=parseSha256Sums(await C(D("SHA256SUMS"),V,t=>B(t,15e3))).get(F)}catch(e){E.logError(`${t.id}: SHA256SUMS`,e)}X||fail("no_checksum",{file:F}),"darwin"===appPlatform()&&H();const q=y(_.getConfigDir(),"downloads",t.id),z=y(q,F),K=l(y(h(),`${t.id}-`));let Q=y(K,F),Y=!1;try{a(z)&&await W(z)===X?(Q=z,o.reusing?.(O)):(o.downloading?.(O),await C(D(F),V,t=>async function(t,e,r){let o;try{o=await R(t,{signal:AbortSignal.timeout(18e5)})}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){f(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,Q,o.percent))),o.verifying?.();const e=await W(Q);e!==X&&fail("checksum",{file:F,expected:X.slice(0,12),actual:e.slice(0,12)}),o.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=y(r,"mnt");c(o,{recursive:!0});const n=j("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=y(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=H(),i=$(r),l=w(r);c(i,{recursive:!0}),s=y(i,`.${l}.${process.pid}.new`),f(s,{recursive:!0,force:!0});const p=j("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),N(s);const u=macAppVersion(s);u||fail("bad_package",{reason:"Info.plist"});const m=y(i,`.${l}.${process.pid}.old`);try{n&&d(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{d(s,r)}catch(t){throw n&&d(m,n),t}return s=null,f(m,{recursive:!0,force:!0}),{version:u,location:r}}finally{s&&f(s,{recursive:!0,force:!0}),j("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(Q,K):await(async(t,e)=>{G(t);const r=U(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=y($(t),"elevated-install.log");f(e,{force:!0});const r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${L(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=U(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=u(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),J()||fail("other_account")}const o=J();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(Q,o);return Y=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw Q!==z&&a(Q)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{f(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{d(t,r)}catch{n(t,r)}}catch(t){E.logError("desktop-app: keep package",t),f(e,{recursive:!0,force:!0})}}(Q,q,z),Q===z&&["signature","bad_package","mount"].includes(e??"")&&f(q,{recursive:!0,force:!0}),t}finally{Y&&f(q,{recursive:!0,force:!0}),f(K,{recursive:!0,force:!0})}}}}
|
|
1
|
+
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readdirSync as p,readFileSync as u,renameSync as d,rmSync as f,statSync as m}from"fs";import{cpus as g,tmpdir as h}from"os";import{basename as w,dirname as $,join as y}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as E}from"../../utils/logger.js";import{i18n as v}from"../i18n.js";import{powerShellEnv as k}from"../powershell-env.js";import{toolHome as P}from"./types.js";import{configManager as _}from"../config.js";import{brand as b}from"../brand.js";import{mirrorFetch as I,mirrorFileUrl as C,withDownloadFallback as T}from"../mirror-url.js";import{processAlive as M}from"../../utils/process-alive.js";const j=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:k()});return n.error&&E.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let R=j,F=(...t)=>fetch(...t),N=null,O=null,D=null,W=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(R=t.run??j),void 0!==t.fetch&&(F=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(N=t.platform),void 0!==t.arm64&&(O=t.arm64),void 0!==t.privileged&&(D=t.privileged),void 0!==t.remote&&(W=t.remote)}export function appPlatform(){return N??process.platform}export function isArm64Machine(){return null!==O?O:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(g()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||v.t("app_update.reason_unknown");throw new DesktopInstallError(v.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function B(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function H(t,e){const r=await I(t,{signal:AbortSignal.timeout(e)},F);if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function V(t,e){try{const r=u(y(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return V(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(V(t,"CFBundleShortVersionString")??"")?.[0]??null}function L(t){try{return r(t,o.W_OK),!0}catch{return!1}}const U=t=>`'${t.replace(/'/g,"''")}'`;function G(t,e=12e4){return R("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>["/Applications",y(P(),"Applications")],s=()=>{const e=[];for(const r of o()){let o;try{o=p(r)}catch{continue}for(const n of t.macApp.installedNames)for(const t of o){if(!t.startsWith(`.${n}.`))continue;const o=/^(\d+)\.(new|old)$/.exec(t.slice(n.length+2));o&&!M(Number(o[1]))&&e.push({path:y(r,t),target:y(r,n),kind:o[2]})}}return e},g=()=>{if("darwin"===appPlatform())for(const e of s())if("old"===e.kind&&!a(e.target)&&a(y(e.path,"Contents","Info.plist")))try{d(e.path,e.target),E.debug(`${t.id}: restored ${e.target} from an interrupted install`)}catch(e){E.logError(`${t.id}: restore interrupted install`,e)}},k=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(D??0===process.getuid?.())?"root":"win32"===o&&(null!==D?D:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==W?W:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},j=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await T(C(o,n),void 0,t=>H(t,r)),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},N=()=>{g();for(const e of o())for(const r of t.macApp.installedNames){const o=y(e,r);if(!a(y(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},O=e=>{const r=R("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=R("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=R("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},V=()=>{const e=N();let r=e;if(!r){const e=L("/Applications")?"/Applications":y(P(),"Applications");r=y(e,t.macApp.installedNames[0])}const o=$(r);return(a(o)&&!L(o)||e&&!L(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},J=e=>{const r=G(`$s = Get-AuthenticodeSignature -LiteralPath ${U(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},X=()=>{const e=G(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:k,latestVersion:j,installedMacApp:N,windowsPackageVersion:X,verifyMacApp:O,verifyWindowsPackage:J,install:async(o={})=>{const P=k();P&&fail("blocked",{reason:v.t(`app_update.reason_${P}`)}),(()=>{if("darwin"===appPlatform()){g();for(const e of s())try{f(e.path,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove leftover`,e)}}const e=new Set(["mnt"]);for(const r of["darwin","win32"])for(const o of[!0,!1]){const n=t.asset(r,o);n&&e.add(n)}const r=new RegExp(`^${t.id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}-[A-Za-z0-9]{6}$`);let o=[];try{o=p(h())}catch{}for(const n of o){if(!r.test(n))continue;const o=y(h(),n);try{if(!m(o).isDirectory())continue;const t=p(o);if(0===t.length||!t.every(t=>e.has(t)))continue;const r=Math.max(...[o,...t.map(t=>y(o,t))].map(t=>m(t).mtimeMs));if(Date.now()-r<864e5)continue;const n=y(o,"mnt");if("darwin"===appPlatform()&&a(n)&&(R("hdiutil",["detach",n,"-force"],{timeout:6e4}),p(n).length>0))continue;f(o,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove stale work folder`,e)}}})();const M=e(),N=r();let D;try{D=await j(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const W=e=>C(M,e,t.releaseTag?.(D)),L=b().installMirror?.downloadCounter;let q;try{q=parseSha256Sums(await T(W("SHA256SUMS"),L,t=>H(t,15e3))).get(N)}catch(e){E.logError(`${t.id}: SHA256SUMS`,e)}q||fail("no_checksum",{file:N}),"darwin"===appPlatform()&&V();const z=y(_.getConfigDir(),"downloads",t.id),K=y(z,N),Q=l(y(h(),`${t.id}-`));let Y=y(Q,N),Z=!1;try{a(K)&&await B(K)===q?(Y=K,o.reusing?.(D)):(o.downloading?.(D),await T(W(N),L,t=>async function(t,e,r){let o;try{o=await I(t,{signal:AbortSignal.timeout(18e5)},F)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){f(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,Y,o.percent))),o.verifying?.();const e=await B(Y);e!==q&&fail("checksum",{file:N,expected:q.slice(0,12),actual:e.slice(0,12)}),o.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=y(r,"mnt");c(o,{recursive:!0});const n=R("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=y(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=V(),i=$(r),l=w(r);c(i,{recursive:!0}),s=y(i,`.${l}.${process.pid}.new`),f(s,{recursive:!0,force:!0});const p=R("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),O(s);const u=macAppVersion(s);u||fail("bad_package",{reason:"Info.plist"});const m=y(i,`.${l}.${process.pid}.old`);try{n&&d(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{d(s,r)}catch(t){throw n&&d(m,n),t}return s=null,f(m,{recursive:!0,force:!0}),{version:u,location:r}}finally{s&&f(s,{recursive:!0,force:!0}),R("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(Y,Q):await(async(t,e)=>{J(t);const r=G(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${U(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=y($(t),"elevated-install.log");f(e,{force:!0});const r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${U(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${U(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=G(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=u(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),X()||fail("other_account")}const o=X();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(Y,o);return Z=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw Y!==K&&a(Y)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{f(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{d(t,r)}catch{n(t,r)}}catch(t){E.logError("desktop-app: keep package",t),f(e,{recursive:!0,force:!0})}}(Y,z,K),Y===K&&["signature","bad_package","mount"].includes(e??"")&&f(z,{recursive:!0,force:!0}),t}finally{Z&&f(z,{recursive:!0,force:!0}),f(Q,{recursive:!0,force:!0})}}}}
|
package/dist/locales/en_US.json
CHANGED
|
@@ -153,6 +153,7 @@
|
|
|
153
153
|
"claude_request_failed": "Request didn't succeed: {{reason}}",
|
|
154
154
|
"deep_hint": "Add --deep to send one real request through Claude Code (uses a little credit) and confirm the whole chain works",
|
|
155
155
|
"codex_auth": "Codex token",
|
|
156
|
+
"codex_key_changed": "The API key in Codex differs from the one {{product}} saved, so its model menu is not kept up to date. Run {{cli}} setup --key <your API key> to write it again",
|
|
156
157
|
"codex_work_mode": "Codex desktop mode",
|
|
157
158
|
"codex_catalog": "Codex model menu",
|
|
158
159
|
"codex_catalog_rejected": "Codex ({{version}}, {{path}}) cannot load the model menu: {{error}}. Run {{cli}} refresh to rewrite it; if it still fails, update that Codex (the desktop app's copy updates with the ChatGPT app)",
|
|
@@ -1235,6 +1236,8 @@
|
|
|
1235
1236
|
"config": "Model config: {{source}}, revision {{revision}}",
|
|
1236
1237
|
"problem": "({{problem}})",
|
|
1237
1238
|
"up_to_date": "All model menus are up to date",
|
|
1239
|
+
"others_up_to_date": "The other tools' model menus are up to date",
|
|
1240
|
+
"key_mismatch": "Could not update the {{tool}} model menu: the API key in {{tool}} differs from the one {{product}} saved. Run {{cli}} setup --key <your API key> to write it again",
|
|
1238
1241
|
"source": {
|
|
1239
1242
|
"cloud": "gateway",
|
|
1240
1243
|
"cache": "local cache",
|
package/dist/locales/zh_CN.json
CHANGED
|
@@ -153,6 +153,7 @@
|
|
|
153
153
|
"claude_request_failed": "请求未成功:{{reason}}",
|
|
154
154
|
"deep_hint": "加上 --deep 会用 Claude Code 实际发送一条请求(消耗少量额度),确认整条链路可用",
|
|
155
155
|
"codex_auth": "Codex 令牌",
|
|
156
|
+
"codex_key_changed": "Codex 里的令牌和 {{product}} 保存的不一致,模型菜单不会自动更新。请运行 {{cli}} setup --key <你的令牌> 重新写入",
|
|
156
157
|
"codex_work_mode": "Codex 桌面版模式",
|
|
157
158
|
"codex_catalog": "Codex 模型菜单",
|
|
158
159
|
"codex_catalog_rejected": "Codex({{version}},{{path}})无法读取模型菜单:{{error}}。请运行 {{cli}} refresh 重新写入;仍然不行就升级这份 Codex(桌面版自带的 Codex 随 ChatGPT 应用升级)",
|
|
@@ -1235,6 +1236,8 @@
|
|
|
1235
1236
|
"config": "模型配置:{{source}},修订 {{revision}}",
|
|
1236
1237
|
"problem": "({{problem}})",
|
|
1237
1238
|
"up_to_date": "各工具的模型菜单已是最新",
|
|
1239
|
+
"others_up_to_date": "其余工具的模型菜单已是最新",
|
|
1240
|
+
"key_mismatch": "无法更新 {{tool}} 的模型菜单:{{tool}} 里的令牌和 {{product}} 保存的不一致。请运行 {{cli}} setup --key <你的令牌> 重新写入",
|
|
1238
1241
|
"source": {
|
|
1239
1242
|
"cloud": "网关",
|
|
1240
1243
|
"cache": "本地缓存",
|