@vibeapi/api-helper 0.0.193 → 0.0.195
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/dist/commands/setup.js +1 -1
- package/dist/lib/components.js +1 -1
- package/dist/lib/mirror-url.d.ts +13 -5
- 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/package.json +1 -1
package/dist/commands/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"chalk";import{getAdapter as o}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsWeConfigured as n}from"./base.js";import{i18n as a}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as c,fetchModels as u}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as m}from"../lib/tools/codex.js";import{resolveModelCatalog as g}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as k}from"../lib/tools/claude-desktop.js";import{operationError as h,authenticationError as _,networkError as b,EXIT_CODES as w}from"../lib/errors.js";import{canPrompt as v,emitJson as x,hasExplicitYes as C,isColorEnabled as j,isDryRun as $,isJsonMode as T,isNonInteractive as K,shouldAutoConfirm as I}from"../lib/runtime-options.js";import{appsForTools as M,appUpgradeCommand as G,getApp as N}from"../lib/app-update.js";import{join as S}from"path";import{confirmAction as O}from"../lib/confirm.js";import{asksBeforeWriting as A,confirmWritePlan as E,printWritePlan as B,toolWritePlan as D}from"../lib/write-plan.js";import F from"inquirer";import{logger as L}from"../utils/logger.js";import{forgetInstalls as R}from"../lib/tools/tool-installs.js";import{CLI_NAME as q,brandEnv as P}from"../lib/brand.js";import{unsupportedUpgradeTargets as Y,upgradeCommand as V}from"./upgrade.js";export const DEDICATED_KEYS=[{option:"claudekey",tool:"claude-code",need:"claude"},{option:"codexkey",tool:"codex",need:"gpt"},{option:"grokkey",tool:"grok",need:"grok"},{option:"desktopkey",tool:"claude-desktop",need:"claude"},{option:"agykey",tool:"agy",need:"gemini"},{option:"openclawkey",tool:"openclaw",need:"any",hidden:!0},{option:"hermeskey",tool:"hermes",need:"any",hidden:!0},{option:"atomcodekey",tool:"atomcode",need:"any",hidden:!0},{option:"codebuddykey",tool:"codebuddy",need:"any"},{option:"workbuddykey",tool:"workbuddy",need:"any"},{option:"dshkey",tool:"dsh",need:"any"}];async function z(e){const o=await u(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=o.models.map(e=>e.toLowerCase());return{hasClaude:t.some(e=>e.includes("claude")),hasGpt:t.some(e=>e.startsWith("gpt")||e.includes("gpt-")||/^o\d/.test(e)),hasGrok:t.some(e=>e.includes("grok")),hasGemini:t.some(e=>e.startsWith("gemini")),probed:!0}}function H(e,o){switch(o){case"claude":return e.hasClaude;case"gpt":return e.hasGpt;case"grok":return e.hasGrok;case"gemini":return e.hasGemini;default:return!0}}export function parseOnOff(e){const o=(e??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(o)||!["off","false","hide","0","no","n"].includes(o)&&void 0}function U(o){console.log(e.green(o))}function W(o){console.log(e.yellow(o))}function J(o){console.error(e.red(o))}let Q=null;function X(e){const o={operation:1,authentication:2,network:3};(!Q||o[e]>o[Q])&&(Q=e)}async function Z(o,t){T()||console.log(e.gray(a.t("setup.validating",{label:o})));const l=await c(t);if(l.valid)return!0;const i=a.t("errors.key_placeholder"),s="--key"===o?`${q} setup --key ${i}`:`${q} setup ${o} ${i}`;let n;if("network_error"===l.error?(X("network"),n=b(a.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${q} base auto`,"network_error")):"invalid_api_key"===l.error?(X("authentication"),n=_(a.t("setup.invalid_key",{label:o,reason:l.message||"invalid"}),s,"invalid_api_key")):(X("operation"),n=h(a.t("setup.validate_failed",{label:o,reason:l.message||l.error||"unknown"}),s,l.error)),T())throw n;return J(n.message),console.log(e.gray(a.t("errors.next_step",{command:n.hint}))),!1}async function ee(t,l,i={}){const{oneMillion:s,officialLogin:n,desktopRegistry:c,force:u,takeOver:m}=i,g=d[t];try{"claude-desktop"===t&&void 0!==c&&r.setToolSetting("claude-desktop",y,c),"codex"===t&&void 0!==s&&r.setToolSetting("codex",f,s),"claude-desktop"===t&&void 0!==n&&r.setToolSetting("claude-desktop",k,!n),await p.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(T())throw h(e instanceof Error?e.message:String(e),`${q} setup --key ${a.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return J("× "+a.t("setup.apply_failed",{tool:g.displayName,reason:o})),!1}return p.printApplied(t),u&&console.log(e.gray(" "+a.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(e.gray(" "+a.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),o(t)?.isInstalled&&!p.isToolInstalled(t)&&console.log(e.yellow(" ! "+a.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function oe(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function te(e){if(C())return!0;const o=d[e]?.displayName??e;return v()?O({message:a.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(W(a.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,l){const i=M(o).filter(e=>{if(l&&!l.includes(e))return!1;const o=N(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return L.logError(`setup: app installed? ${e}`,o),!1}});if(0===i.length)return!1;const s=e=>N(e)?.displayName??e;let n=t;if(void 0===n&&!T())if(I())n=!K();else if(v()){const e=i.map(s).join(a.t("setup.list_separator")),o=i.reduce((e,o)=>e+(N(o)?.appInstaller.sizeMb()??0),0);console.log(""),n=(await F.prompt([{type:"confirm",name:"go",message:a.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!n&&!T())for(const o of i)console.log(e.gray(a.t("setup.install_app_hint",{tool:s(o),command:G(o)})));return Boolean(n)}function le(e){W(a.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(a.t("setup.list_separator")),commands:e.map(e=>`${q} config ${e} --yes`).join(a.t("setup.list_separator"))}))}function ie(o,t,l=[]){const i=D(o),s=S(r.getConfigDir(),"config.yaml");if(T())x({dry_run:!0,tools:i,install_first:l,key_file:t?s:null});else{if(0===i.length&&0===l.length){const o=(j()?e.cyan:e=>e)(a.t("runtime.dry_run_label"));return void console.log(`${o} ${a.t("setup.dry_run_none")}`)}B(i,{label:a.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function se(e){return Boolean(o(e)?.installSpec||N(e)?.appInstaller)}function ne(e){return M(e).filter(e=>{const o=N(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return L.logError(`setup: app blocker ${e}`,o),!1}})}function ae(e){const o=N(e);let t,l;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){L.logError(`setup: app installed? ${e}`,o),t=!1}l=t?o.installedVersion?.():null}else t=p.isToolInstalled(e),l=t?p.installedVersion(e):null;return t?l?a.t("setup.pick_installed",{version:l}):a.t("setup.pick_installed_plain"):a.t("setup.pick_not_installed")}function re(o,t){return{name:`${N(o)?.displayName??d[o]?.displayName??o} ${e.gray(ae(o))}`,value:o,checked:t}}export function parseUpgradeList(e){const o=(Array.isArray(e)?e:void 0===e?[]:[e]).flatMap(e=>e.split(/[\s,]+/));return[...new Set(o.map(e=>e.trim()).filter(Boolean))]}function pe(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function setupCommand(c){Q=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:c[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),y=void 0!==c.oneMillion||void 0!==c.claudeOfficial||void 0!==c.desktopRegistry;let k=c.key?.trim();const h=c.upgrade??[],_=Y(h);if(_.length>0)return J(a.t("upgrade.unsupported",{tool:_.join(", ")})),void(process.exitCode=w.usage);if(h.length>0&&($()?console.log(a.t("setup.dry_run_upgrade",{tools:h.join(", ")})):(await V(h),R()),!k&&0===u.length&&!y))return;k||0!==u.length||y||!A()||(k=(await F.prompt([{type:"password",name:"key",mask:"*",message:a.t("setup.ask_key")}])).key?.trim()||void 0);const b=void 0!==c.oneMillion,v=void 0!==c.claudeOfficial;let x;if(v&&(x=parseOnOff(c.claudeOfficial),void 0===x))return J(a.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const C=void 0!==c.desktopRegistry;let j;if(C&&(j=parseOnOff(c.desktopRegistry),void 0===j))return J(a.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const M=v||C,G=Boolean(k||u.length>0),O={oneMillion:c.oneMillion,officialLogin:x,desktopRegistry:j,force:c.force};if(!G&&(b||M)&&$())return void ie([...b?["codex"]:[],...M?["claude-desktop"]:[]],!1);if(!G&&(b||M)){if(b){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===c.oneMillion;r.setToolSetting("codex",f,o);const t=await g(e);m(o,t??void 0),U(a.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){J(a.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else J(a.t("setup.codex_1m_missing_key")),process.exitCode=1}if(M){const e=r.getApiKeyForTool("claude-desktop");e?await ee("claude-desktop",e,{...O,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(J(a.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!G)return J(a.t("setup.usage")),void(process.exitCode=1);const B=$(),D=B?null:await l(k||u[0].apiKey,{save:!1}),X=[],ae=[];let de,ce=0,ue=0;const fe=new Set,me=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of me){if(!await Z(e.label,e.apiKey)){ue+=1;continue}const o=await z(e.apiKey);!o.probed||H(o,e.need)?(o.probed||W(a.t("setup.probe_failed",{label:e.label})),X.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),fe.add(e.tool)):(J(a.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),ue+=1)}const ge=!!k&&await Z("--key",k);k&&!ge&&(de=w[Q??"operation"]);const ye=k&&ge?await z(k):void 0;k&&ye&&!ye.probed&&W(a.t("setup.probe_failed",{label:"--key"})),!(k&&ye&&ye.probed)||ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini||(J(a.t("setup.key_no_family")),de=1);const ke=Boolean(k)&&0===u.length&&!c.fromInstaller&&A();if(k&&ye&&void 0===de){const e=ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini,o=[{tool:"claude-code",capable:ye.hasClaude,skipMsg:a.t(pe()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:ye.hasGpt,skipMsg:a.t("setup.skip_no_gpt")},{tool:"grok",capable:ye.hasGrok,skipMsg:a.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:ye.hasClaude&&pe(),skipMsg:"",quiet:!0},{tool:"agy",capable:ye.hasGemini,skipMsg:a.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:e&&p.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:e&&p.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:e&&p.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const e of o)fe.has(e.tool)||(e.capable?(!e.ask||B||ke||await te(e.tool))&&(X.push({tool:e.tool,apiKey:k,dedicated:!1}),fe.add(e.tool)):e.quiet||W(e.skipMsg))}let he,_e=c.install,be=[];if(ke&&void 0===de&&X.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await F.prompt([{type:"checkbox",name:"configure",message:a.t("setup.pick_configure"),choices:e.map(e=>re(e,!0))}]);let l=[];const i=[...e.filter(se),...ne(e)];if(o&&i.length>0){const e=e=>N(e)?.tool??e;l=(await F.prompt([{type:"checkbox",name:"upgrade",message:a.t("setup.pick_upgrade"),choices:i.map(o=>re(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===l.length?(console.log(a.t("setup.pick_none")),null):{configure:t,upgrade:l}}(X.map(e=>e.tool),void 0===c.upgrade);if(!e)return void(process.exitCode=w.cancelled);if(0===e.configure.length)return void await V(e.upgrade);be=e.upgrade,he=[],!0!==_e&&(_e=!1);const o=e.configure.filter(e=>oe(e)&&!be.includes(e)&&!_e);if(o.length>0&&W(a.t("setup.pick_configure_skip",{tools:o.map(e=>d[e].displayName).join(a.t("setup.list_separator"))})),X.splice(0,X.length,...X.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===X.length)return void(be.length>0&&await V(be))}const we=Boolean(k&&ge&&void 0===de);if(B)return ie(X.filter(e=>!oe(e.tool)).map(e=>e.tool),X.length>0,X.filter(e=>oe(e.tool)).map(e=>e.tool)),void((ue>0||void 0!==de)&&(process.exitCode=de??w[Q??"operation"]));const ve=X.filter(e=>!oe(e.tool)),xe=we||X.some(e=>e.dedicated),Ce=D?n().filter(e=>!X.some(o=>o.tool===e.tool)):[],je=!c.fromInstaller&&A();if((X.length>0||xe)&&!c.fromInstaller&&!await E([...ve.map(e=>e.tool),...Ce.map(e=>e.tool)],{keyFile:xe?S(r.getConfigDir(),"config.yaml"):void 0,installFirst:X.filter(e=>oe(e.tool)).map(e=>e.tool)}))return void(process.exitCode=w.cancelled);be.length>0&&(await V(be),R()),(X.length>0||xe)&&s(),we&&k&&r.setApiKey(k);for(const e of X)oe(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),ae.push({tool:e.tool,apiKey:e.apiKey})):await ee(e.tool,e.apiKey,{...O,takeOver:e.dedicated||je})?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),ce+=1):(ue+=1,fe.delete(e.tool));const $e=X.length>0||xe?await i(Ce):[];if(void 0!==de)return ae.length>0&&le(ae.map(e=>e.tool)),void(process.exitCode=de);let Te=[];if(ae.length>0){const o=await async function(o,t,l){const i=o.map(e=>e.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(e=>d[e].displayName).join(a.t("setup.list_separator"));let n=t;if(void 0!==n||T()||(I()?n=!K():process.stdin.isTTY&&(console.log(""),n=(await F.prompt([{type:"confirm",name:"go",message:a.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!n){console.log("");for(const o of i)console.log(e.yellow("! "+a.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return T()||console.log(e.gray(a.t("setup.install_all_hint",{cli:q}))),{still:i,applied:[],failed:[]}}const r=[];for(const o of i){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){L.logError(`setup: install ${o}`,e)}R(),p.isToolInstalled(o)||r.push(o)}const c=i.filter(e=>!r.includes(e));c.length>0&&console.log("");const u=[],f=[];for(const{tool:e,apiKey:t}of o.filter(e=>c.includes(e.tool)))await ee(e,t,l)?u.push(e):f.push(e);return{still:r,applied:u,failed:f}}(ae,_e,O);Te=o.still,ce+=o.applied.length,ue+=o.failed.length;for(const e of[...Te,...o.failed])fe.delete(e)}if(ce>0){const t=[...fe].filter(e=>!o(e)?.isInstalled&&!Te.includes(e)),l=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),i=a.t("setup.done",{count:String(ce)});U("\n"+(l?`${i}${a.t("setup.done_commands",{commands:l})}`:i)),Te.length>0&&le(Te);for(const e of t){const o=p.ensureNativeOnPath(e);o&&U(a.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!T()&&"1"!==P("PATH_HINT_BY_CALLER")){const o=s.map(e=>d[e].command).join(" / ");console.log(e.yellow(" ! "+a.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}}0===ce&&Te.length>0&&le(Te),ue>0&&(J(a.t("setup.failed_summary",{count:String(ue)})),T()||console.error(`${q} setup --key ${a.t("errors.key_placeholder")}`)),await t([...fe,...$e],{apps:{install:await installMissingApps([...fe],_e,he)}}),(ue>0||0===ce&&0===Te.length)&&(process.exitCode=w[Q??"operation"])}
|
|
1
|
+
import e from"chalk";import{getAdapter as o}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as c,fetchModels as u}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as m}from"../lib/tools/codex.js";import{resolveModelCatalog as g}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as k}from"../lib/tools/claude-desktop.js";import{operationError as h,authenticationError as _,networkError as b,EXIT_CODES as w}from"../lib/errors.js";import{canPrompt as v,emitJson as x,hasExplicitYes as C,isColorEnabled as j,isDryRun as T,isJsonMode as K,isNonInteractive as $,shouldAutoConfirm as I}from"../lib/runtime-options.js";import{appsForTools as M,appUpgradeCommand as G,getApp as N}from"../lib/app-update.js";import{join as S}from"path";import{confirmAction as A}from"../lib/confirm.js";import{asksBeforeWriting as O,confirmWritePlan as E,printWritePlan as B,toolWritePlan as D}from"../lib/write-plan.js";import F from"inquirer";import{logger as L}from"../utils/logger.js";import{forgetInstalls as R}from"../lib/tools/tool-installs.js";import{CLI_NAME as q,brandEnv as P}from"../lib/brand.js";import{unsupportedUpgradeTargets as Y,upgradeCommand as V}from"./upgrade.js";export const DEDICATED_KEYS=[{option:"claudekey",tool:"claude-code",need:"claude"},{option:"codexkey",tool:"codex",need:"gpt"},{option:"grokkey",tool:"grok",need:"grok"},{option:"desktopkey",tool:"claude-desktop",need:"claude"},{option:"agykey",tool:"agy",need:"gemini"},{option:"openclawkey",tool:"openclaw",need:"any",hidden:!0},{option:"hermeskey",tool:"hermes",need:"any",hidden:!0},{option:"atomcodekey",tool:"atomcode",need:"any",hidden:!0},{option:"codebuddykey",tool:"codebuddy",need:"any"},{option:"workbuddykey",tool:"workbuddy",need:"any"},{option:"dshkey",tool:"dsh",need:"any"}];async function z(e){const o=await u(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=o.models.map(e=>e.toLowerCase());return{hasClaude:t.some(e=>e.includes("claude")),hasGpt:t.some(e=>e.startsWith("gpt")||e.includes("gpt-")||/^o\d/.test(e)),hasGrok:t.some(e=>e.includes("grok")),hasGemini:t.some(e=>e.startsWith("gemini")),probed:!0}}function H(e,o){switch(o){case"claude":return e.hasClaude;case"gpt":return e.hasGpt;case"grok":return e.hasGrok;case"gemini":return e.hasGemini;default:return!0}}export function parseOnOff(e){const o=(e??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(o)||!["off","false","hide","0","no","n"].includes(o)&&void 0}function U(o){console.log(e.green(o))}function W(o){console.log(e.yellow(o))}function J(o){console.error(e.red(o))}let Q=null;function X(e){const o={operation:1,authentication:2,network:3};(!Q||o[e]>o[Q])&&(Q=e)}async function Z(o,t){K()||console.log(e.gray(n.t("setup.validating",{label:o})));const l=await c(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===o?`${q} setup --key ${i}`:`${q} setup ${o} ${i}`;let a;if("network_error"===l.error?(X("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${q} base auto`,"network_error")):"invalid_api_key"===l.error?(X("authentication"),a=_(n.t("setup.invalid_key",{label:o,reason:l.message||"invalid"}),s,"invalid_api_key")):(X("operation"),a=h(n.t("setup.validate_failed",{label:o,reason:l.message||l.error||"unknown"}),s,l.error)),K())throw a;return J(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function ee(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=i,g=d[t];try{"claude-desktop"===t&&void 0!==c&&r.setToolSetting("claude-desktop",y,c),"codex"===t&&void 0!==s&&r.setToolSetting("codex",f,s),"claude-desktop"===t&&void 0!==a&&r.setToolSetting("claude-desktop",k,!a),await p.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(K())throw h(e instanceof Error?e.message:String(e),`${q} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return J("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:o})),!1}return p.printApplied(t),u&&console.log(e.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(e.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),o(t)?.isInstalled&&!p.isToolInstalled(t)&&console.log(e.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function oe(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function te(e){if(C())return!0;const o=d[e]?.displayName??e;return v()?A({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(W(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,l){const i=M(o).filter(e=>{if(l&&!l.includes(e))return!1;const o=N(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return L.logError(`setup: app installed? ${e}`,o),!1}});if(0===i.length)return!1;const s=e=>N(e)?.displayName??e;let a=t;if(void 0===a&&!K())if(I())a=!$();else if(v()){const e=i.map(s).join(n.t("setup.list_separator")),o=i.reduce((e,o)=>e+(N(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!K())for(const o of i)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:G(o)})));return Boolean(a)}function le(e){W(n.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${q} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function ie(o,t,l=[]){const i=D(o),s=S(r.getConfigDir(),"config.yaml");if(K())x({dry_run:!0,tools:i,install_first:l,key_file:t?s:null});else{if(0===i.length&&0===l.length){const o=(j()?e.cyan:e=>e)(n.t("runtime.dry_run_label"));return void console.log(`${o} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function se(e){return Boolean(o(e)?.installSpec||N(e)?.appInstaller)}function ae(e){return M(e).filter(e=>{const o=N(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return L.logError(`setup: app blocker ${e}`,o),!1}})}function ne(e){const o=N(e);let t,l;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){L.logError(`setup: app installed? ${e}`,o),t=!1}l=t?o.installedVersion?.():null}else t=p.isToolInstalled(e),l=t?p.installedVersion(e):null;return t?l?n.t("setup.pick_installed",{version:l}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function re(o,t){return{name:`${N(o)?.displayName??d[o]?.displayName??o} ${e.gray(ne(o))}`,value:o,checked:t}}export function parseUpgradeList(e){const o=(Array.isArray(e)?e:void 0===e?[]:[e]).flatMap(e=>e.split(/[\s,]+/));return[...new Set(o.map(e=>e.trim()).filter(Boolean))]}function pe(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function setupCommand(c){Q=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:c[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),y=void 0!==c.oneMillion||void 0!==c.claudeOfficial||void 0!==c.desktopRegistry;let k=c.key?.trim();const h=c.upgrade??[],_=Y(h);if(_.length>0)return J(n.t("upgrade.unsupported",{tool:_.join(", ")})),void(process.exitCode=w.usage);if(h.length>0&&(T()?console.log(n.t("setup.dry_run_upgrade",{tools:h.join(", ")})):(await V(h),R()),!k&&0===u.length&&!y))return;k||0!==u.length||y||!O()||(k=(await F.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const b=void 0!==c.oneMillion,v=void 0!==c.claudeOfficial;let x;if(v&&(x=parseOnOff(c.claudeOfficial),void 0===x))return J(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const C=void 0!==c.desktopRegistry;let j;if(C&&(j=parseOnOff(c.desktopRegistry),void 0===j))return J(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const M=v||C,G=Boolean(k||u.length>0),A={oneMillion:c.oneMillion,officialLogin:x,desktopRegistry:j,force:c.force};if(!G&&(b||M)&&T())return void ie([...b?["codex"]:[],...M?["claude-desktop"]:[]],!1);if(!G&&(b||M)){if(b){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===c.oneMillion;r.setToolSetting("codex",f,o);const t=await g(e);m(o,t??void 0),U(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){J(n.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else J(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(M){const e=r.getApiKeyForTool("claude-desktop");e?await ee("claude-desktop",e,{...A,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(J(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!G)return J(n.t("setup.usage")),void(process.exitCode=1);const B=T(),D=B?null:await l(k||u[0].apiKey,{save:!1}),X=[],ne=[];let de,ce=0,ue=0;const fe=new Set,me=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of me){if(!await Z(e.label,e.apiKey)){ue+=1;continue}const o=await z(e.apiKey);!o.probed||H(o,e.need)?(o.probed||W(n.t("setup.probe_failed",{label:e.label})),X.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),fe.add(e.tool)):(J(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),ue+=1)}const ge=!!k&&await Z("--key",k);k&&!ge&&(de=w[Q??"operation"]);const ye=k&&ge?await z(k):void 0;k&&ye&&!ye.probed&&W(n.t("setup.probe_failed",{label:"--key"})),!(k&&ye&&ye.probed)||ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini||(J(n.t("setup.key_no_family")),de=1);const ke=Boolean(k)&&0===u.length&&!c.fromInstaller&&O();if(k&&ye&&void 0===de){const e=ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini,o=[{tool:"claude-code",capable:ye.hasClaude,skipMsg:n.t(pe()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:ye.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:ye.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:ye.hasClaude&&pe(),skipMsg:"",quiet:!0},{tool:"agy",capable:ye.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:e&&p.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:e&&p.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:e&&p.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const e of o)fe.has(e.tool)||(e.capable?(!e.ask||B||ke||await te(e.tool))&&(X.push({tool:e.tool,apiKey:k,dedicated:!1}),fe.add(e.tool)):e.quiet||W(e.skipMsg))}let he,_e=c.install,be=[];if(ke&&void 0===de&&X.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await F.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>re(e,!0))}]);let l=[];const i=[...e.filter(se),...ae(e)];if(o&&i.length>0){const e=e=>N(e)?.tool??e;l=(await F.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:i.map(o=>re(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===l.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:l}}(X.map(e=>e.tool),void 0===c.upgrade);if(!e)return void(process.exitCode=w.cancelled);if(0===e.configure.length)return void await V(e.upgrade);be=e.upgrade,he=[],!0!==_e&&(_e=!1);const o=e.configure.filter(e=>oe(e)&&!be.includes(e)&&!_e);if(o.length>0&&W(n.t("setup.pick_configure_skip",{tools:o.map(e=>d[e].displayName).join(n.t("setup.list_separator"))})),X.splice(0,X.length,...X.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===X.length)return void(be.length>0&&await V(be))}const we=Boolean(k&&ge&&void 0===de);if(B)return ie(X.filter(e=>!oe(e.tool)).map(e=>e.tool),X.length>0,X.filter(e=>oe(e.tool)).map(e=>e.tool)),void((ue>0||void 0!==de)&&(process.exitCode=de??w[Q??"operation"]));const ve=X.filter(e=>!oe(e.tool)),xe=we||X.some(e=>e.dedicated),Ce=D?a().filter(e=>!X.some(o=>o.tool===e.tool)):[],je=!c.fromInstaller&&O();if((X.length>0||xe)&&!c.fromInstaller&&!await E([...ve.map(e=>e.tool),...Ce.map(e=>e.tool)],{keyFile:xe?S(r.getConfigDir(),"config.yaml"):void 0,installFirst:X.filter(e=>oe(e.tool)).map(e=>e.tool)}))return void(process.exitCode=w.cancelled);be.length>0&&(await V(be),R()),(X.length>0||xe)&&s(),we&&k&&r.setApiKey(k);for(const e of X)oe(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),ne.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await ee(e.tool,e.apiKey,{...A,takeOver:e.dedicated||je})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),ce+=1):(ue+=1,fe.delete(e.tool));const Te=X.length>0||xe?await i(Ce):[];if(void 0!==de)return ne.length>0&&le(ne.map(e=>e.tool)),void(process.exitCode=de);let Ke=[];if(ne.length>0){const o=await async function(o,t,l){const i=o.map(e=>e.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||K()||(I()?a=!$():process.stdin.isTTY&&(console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of i)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return K()||console.log(e.gray(n.t("setup.install_all_hint",{cli:q}))),{still:i,applied:[],failed:[]}}const c=[];for(const o of i){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){L.logError(`setup: install ${o}`,e)}R(),p.isToolInstalled(o)||c.push(o)}const u=i.filter(e=>!c.includes(e));u.length>0&&console.log("");const f=[],m=[];for(const{tool:e,apiKey:t,dedicated:i}of o.filter(e=>u.includes(e.tool)))await ee(e,t,l)?(f.push(e),i||r.clearToolApiKey(e)):m.push(e);return{still:c,applied:f,failed:m}}(ne,_e,A);Ke=o.still,ce+=o.applied.length,ue+=o.failed.length;for(const e of[...Ke,...o.failed])fe.delete(e)}if(ce>0){const t=[...fe].filter(e=>!o(e)?.isInstalled&&!Ke.includes(e)),l=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(ce)});U("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),Ke.length>0&&le(Ke);for(const e of t){const o=p.ensureNativeOnPath(e);o&&U(n.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!K()&&"1"!==P("PATH_HINT_BY_CALLER")){const o=s.map(e=>d[e].command).join(" / ");console.log(e.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}}0===ce&&Ke.length>0&&le(Ke),ue>0&&(J(n.t("setup.failed_summary",{count:String(ue)})),K()||console.error(`${q} setup --key ${n.t("errors.key_placeholder")}`)),await t([...fe,...Te],{apps:{install:await installMissingApps([...fe],_e,he)}}),(ue>0||0===ce&&0===Ke.length)&&(process.exitCode=w[Q??"operation"])}
|
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.d.ts
CHANGED
|
@@ -6,13 +6,21 @@ export declare function mirrorFileUrl(mirror: string, file: string, oldReleaseTa
|
|
|
6
6
|
/** A page people can open in a browser for the mirror: the release page of its tag. */
|
|
7
7
|
export declare function mirrorPageUrl(mirror: string): string;
|
|
8
8
|
/**
|
|
9
|
-
* Where to fetch a mirror file from, in order.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* Where to fetch a mirror file from, in order. A file under the site's `/dl/` is tried as is, then once more with
|
|
10
|
+
* `?alt=1`: the site skips the source it handed out first (CNB, object storage, overseas CNB…), so one broken source
|
|
11
|
+
* doesn't stop the download. With a download counter (`installMirror.downloadCounter`: it logs the download, then
|
|
12
|
+
* redirects to the same path on cnb.cool) a cnb.cool release file is tried through it first, then directly; anything
|
|
13
|
+
* else (no counter, another host, git raw files) is fetched directly.
|
|
12
14
|
*/
|
|
13
15
|
export declare function downloadUrls(url: string, counter: string | undefined): string[];
|
|
14
16
|
/**
|
|
15
|
-
* Runs `fetchOne` on each of `downloadUrls(url, counter)` until one succeeds; a failure of the
|
|
16
|
-
* an error status, a broken transfer)
|
|
17
|
+
* Runs `fetchOne` on each of `downloadUrls(url, counter)` until one succeeds; a failure of the first (unreachable,
|
|
18
|
+
* an error status, a broken transfer) moves on to the next. Throws the last one's error.
|
|
17
19
|
*/
|
|
18
20
|
export declare function withDownloadFallback<T>(url: string, counter: string | undefined, fetchOne: (url: string) => Promise<T>): Promise<T>;
|
|
21
|
+
/**
|
|
22
|
+
* Fetches a mirror file. A file under this brand's own `/dl/` carries `Authorization: Bearer <API key>`: the site gives
|
|
23
|
+
* customers it recognises a faster domestic copy. The key never leaves the site: redirects are followed here, and the
|
|
24
|
+
* first hop to another origin (CNB, object storage) goes without it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function mirrorFetch(url: string, init?: RequestInit, fetchImpl?: typeof fetch, apiKey?: () => string | undefined): Promise<Response>;
|
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 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{
|
|
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{let r=n.getApiKeyForTool(t.name);if(!r)continue;const s=t.detectCurrentConfig().apiKey;if(s&&s!==r&&s===n.getApiKey()&&(n.clearToolApiKey(t.name),r=s),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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibeapi/api-helper",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.195",
|
|
4
4
|
"description": "CLI tool for managing AI coding assistants (Claude Code, Codex, OpenClaw, Hermes, AtomCode, Grok Build) with one unified config",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|