@ai-vibeway/cli 0.0.202 → 0.0.203

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.
@@ -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 i,moveOtherToolsAfterFallback as l,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r,savedApiKeys as c}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as u,fetchModels as f}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as m,setCodexOneMillionContext as g}from"../lib/tools/codex.js";import{resolveModelCatalog as h}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as _}from"../lib/tools/claude-desktop.js";import{operationError as k,authenticationError as w,networkError as b,EXIT_CODES as v}from"../lib/errors.js";import{canPrompt as C,emitJson as x,hasExplicitYes as S,isColorEnabled as j,isDryRun as K,isJsonMode as $,isNonInteractive as T,shouldAutoConfirm as M}from"../lib/runtime-options.js";import{appsForTools as I,appUpgradeCommand as A,getApp as O}from"../lib/app-update.js";import{join as N}from"path";import{confirmAction as E}from"../lib/confirm.js";import{asksBeforeWriting as G,confirmWritePlan as B,printWritePlan as F,toolWritePlan as P}from"../lib/write-plan.js";import D from"inquirer";import{logger as q}from"../utils/logger.js";import{forgetInstalls as L}from"../lib/tools/tool-installs.js";import{CLI_NAME as R,brandEnv as V}from"../lib/brand.js";import{unsupportedUpgradeTargets as Y,upgradeCommand as U}from"./upgrade.js";import{track as z}from"../lib/telemetry.js";import{CCSWITCH_SETTING as H,buildCcSwitchCards as W,ccSwitchContext as J,ccSwitchSelector as Q,ourCcSwitchCards as X,removeCcSwitchCards as Z,isAdditiveCcSwitchApp as ee,inspectCcSwitch as oe,quitCcSwitch as te,writeCcSwitchCards as ie}from"../lib/ccswitch.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 le(e){const o=await f(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 se(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 ae(o){console.log(e.green(o))}function ne(o){console.log(e.yellow(o))}function re(o){console.error(e.red(o))}let ce=null;function pe(e){const o={operation:1,authentication:2,network:3};(!ce||o[e]>o[ce])&&(ce=e)}async function de(o,t){$()||console.log(e.gray(n.t("setup.validating",{label:o})));const i=await u(t);if(i.valid)return!0;const l=n.t("errors.key_placeholder"),s="--key"===o?`${R} setup --key ${l}`:`${R} setup ${o} ${l}`;let a;if("network_error"===i.error?(pe("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:i.message||"network error"}),`${R} base auto`,"network_error")):"invalid_api_key"===i.error?(pe("authentication"),a=w(n.t("setup.invalid_key",{label:o,reason:i.message||"invalid"}),s,"invalid_api_key")):(pe("operation"),a=k(n.t("setup.validate_failed",{label:o,reason:i.message||i.error||"unknown"}),s,i.error)),$())throw a;return re(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function ue(t,i,l={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:f}=l,g=d[t];try{"claude-desktop"===t&&void 0!==c&&r.setToolSetting("claude-desktop",y,c),"codex"===t&&void 0!==s&&r.setToolSetting("codex",m,s),"claude-desktop"===t&&void 0!==a&&r.setToolSetting("claude-desktop",_,!a),await p.applyPrivateConfig(t,i,r.getModelsForTool(t),{force:u,takeOver:f})}catch(e){if($())throw k(e instanceof Error?e.message:String(e),`${R} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return re("× "+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 fe(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function me(e){if(S())return!0;const o=d[e]?.displayName??e;return C()?E({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(ne(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,i){const l=I(o).filter(e=>{if(i&&!i.includes(e))return!1;const o=O(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return q.logError(`setup: app installed? ${e}`,o),!1}});if(0===l.length)return!1;const s=e=>O(e)?.displayName??e;let a=t;if(void 0===a&&!$())if(M())a=!T();else if(C()){const e=l.map(s).join(n.t("setup.list_separator")),o=l.reduce((e,o)=>e+(O(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await D.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!$())for(const o of l)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:A(o)})));return Boolean(a)}function ge(e){ne(n.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${R} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function he(o,t,i=[]){const l=P(o),s=N(r.getConfigDir(),"config.yaml");if($())x({dry_run:!0,tools:l,install_first:i,key_file:t?s:null});else{if(0===l.length&&0===i.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")}`)}F(l,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:i})}}function ye(e){return Boolean(o(e)?.installSpec||O(e)?.appInstaller)}function _e(e){return I(e).filter(e=>{const o=O(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return q.logError(`setup: app blocker ${e}`,o),!1}})}function ke(e){const o=O(e);let t,i;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){q.logError(`setup: app installed? ${e}`,o),t=!1}i=t?o.installedVersion?.():null}else t=p.isToolInstalled(e),i=t?p.installedVersion(e):null;return t?i?n.t("setup.pick_installed",{version:i}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function we(o,t){return{name:`${O(o)?.displayName??d[o]?.displayName??o} ${e.gray(ke(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 be(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function prepareCcSwitch(){let e,o=await oe();if("running"===o.problem&&!K()&&(S()||C())&&(S()||await E({message:n.t("ccswitch.ask_quit"),defaultValue:!0}))){const t=te();t&&(e=t.reopen,o=await oe())}if(o.ok||K()&&"running"===o.problem)return{state:o,reopen:e};const t=n.t(`ccswitch.problem_${o.problem}`,{path:o.dbPath,schema:String(o.schema??"?"),node:process.versions.node});if(z("ccswitch","unsupported_schema"===o.problem||"unexpected_tables"===o.problem||"unreadable"===o.problem?"fail":"skip",{detail:{problem:o.problem,schema:o.schema,detail:o.detail,platform:process.platform}}),$())throw k(t,`${R} setup --key ${n.t("errors.key_placeholder")}`,`ccswitch_${o.problem}`);return re(t),e?.(),null}export async function removeFromCcSwitch(t){const i=o(t)?.ccSwitch;if(!i)return"none";const l=d[t].displayName;let s=!1;try{s=i.unloadAsCards?.({savedKeys:c()})??!1}catch(e){q.logError(`removeFromCcSwitch(${t})`,e)}const a=Q(t);if(0===(await X(a)).length)return r.setMachineSetting(t,H,""),s?"removed":"none";const p=await prepareCcSwitch();if(!p)return"blocked";try{const o=await Z(a);return r.setMachineSetting(t,H,""),z("ccswitch","ok",{detail:{mode:"remove",schema:p.state.schema,tools:[t],cards:o}}),console.log(e.green(n.t("ccswitch.removed_cards",{tool:l,count:String(o)}))),"removed"}catch(e){return z("ccswitch","fail",{error:e,detail:{mode:"remove",schema:p.state.schema}}),re("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),"blocked"}finally{p.reopen?.()}}export async function setupCommand(c){ce=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:c[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),f=void 0!==c.oneMillion||void 0!==c.claudeOfficial||void 0!==c.desktopRegistry;let y=c.key?.trim();const _=c.upgrade??[],k=Y(_);if(k.length>0)return re(n.t("upgrade.unsupported",{tool:k.join(", ")})),void(process.exitCode=v.usage);if(_.length>0&&(K()?console.log(n.t("setup.dry_run_upgrade",{tools:_.join(", ")})):(await U(_),L()),!y&&0===u.length&&!f))return;y||0!==u.length||f||!G()||(y=(await D.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const w=void 0!==c.oneMillion,b=void 0!==c.claudeOfficial;let C;if(b&&(C=parseOnOff(c.claudeOfficial),void 0===C))return re(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const x=void 0!==c.desktopRegistry;let S;if(x&&(S=parseOnOff(c.desktopRegistry),void 0===S))return re(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const j=b||x,I=Boolean(y||u.length>0),A={oneMillion:c.oneMillion,officialLogin:C,desktopRegistry:S,force:c.force};if(!I&&(w||j)&&K())return void he([...w?["codex"]:[],...j?["claude-desktop"]:[]],!1);if(!I&&(w||j)){if(w){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===c.oneMillion;r.setToolSetting("codex",m,o);const t=await h(e);g(o,t??void 0),ae(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){re(n.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else re(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(j){const e=r.getApiKeyForTool("claude-desktop");e?await ue("claude-desktop",e,{...A,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(re(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!I)return re(n.t("setup.usage")),void(process.exitCode=1);const F=c.ccswitchUse?"use":c.ccswitch?"add":null,P=F?await prepareCcSwitch():null;if(F&&!P)return void(process.exitCode=1);const Q=K(),X=Q?null:await i(y||u[0].apiKey,{save:!1}),Z=[],oe=[];let te,pe=0,ke=0;const ve=new Set,Ce=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of Ce){if(!await de(e.label,e.apiKey)){ke+=1;continue}const o=await le(e.apiKey);!o.probed||se(o,e.need)?(o.probed||ne(n.t("setup.probe_failed",{label:e.label})),Z.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),ve.add(e.tool)):(re(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),ke+=1)}const xe=!!y&&await de("--key",y);y&&!xe&&(te=v[ce??"operation"]);const Se=y&&xe?await le(y):void 0;y&&Se&&!Se.probed&&ne(n.t("setup.probe_failed",{label:"--key"})),!(y&&Se&&Se.probed)||Se.hasClaude||Se.hasGpt||Se.hasGrok||Se.hasGemini||(re(n.t("setup.key_no_family")),te=1);const je=Boolean(y)&&0===u.length&&!c.fromInstaller&&G()&&!F;if(y&&Se&&void 0===te){const e=Se.hasClaude||Se.hasGpt||Se.hasGrok||Se.hasGemini,o=[{tool:"claude-code",capable:Se.hasClaude,skipMsg:n.t(be()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:Se.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:Se.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:Se.hasClaude&&be(),skipMsg:"",quiet:!0},{tool:"agy",capable:Se.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)ve.has(e.tool)||(e.capable?(!e.ask||Q||je||await me(e.tool))&&(Z.push({tool:e.tool,apiKey:y,dedicated:!1}),ve.add(e.tool)):e.quiet||ne(e.skipMsg))}let Ke,$e=c.install,Te=[];if(je&&void 0===te&&Z.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await D.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>we(e,!0))}]);let i=[];const l=[...e.filter(ye),..._e(e)];if(o&&l.length>0){const e=e=>O(e)?.tool??e;i=(await D.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:l.map(o=>we(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===i.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:i}}(Z.map(e=>e.tool),void 0===c.upgrade);if(!e)return void(process.exitCode=v.cancelled);if(0===e.configure.length)return void await U(e.upgrade);Te=e.upgrade,Ke=[],!0!==$e&&($e=!1);const o=e.configure.filter(e=>fe(e)&&!Te.includes(e)&&!$e);if(o.length>0&&ne(n.t("setup.pick_configure_skip",{tools:o.map(e=>d[e].displayName).join(n.t("setup.list_separator"))})),Z.splice(0,Z.length,...Z.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===Z.length)return void(Te.length>0&&await U(Te))}const Me=Boolean(y&&xe&&void 0===te);if(F&&P)return void 0!==te&&0===Z.length?(P.reopen?.(),void(process.exitCode=te)):(await async function(i,l,a,c,u,f){const m=i.filter(e=>p.supportsCcSwitch(e.tool)),g=i.filter(e=>!p.supportsCcSwitch(e.tool)),h=e=>e.map(e=>d[e.tool].displayName).join(n.t("setup.list_separator"));if(g.length>0&&ne(n.t("ccswitch.not_supported",{tools:h(g)})),0===m.length)return re(n.t("ccswitch.nothing")),a.reopen?.(),void(process.exitCode=1);const y=m.filter(e=>o(e.tool)?.ccSwitch?.handOver&&!r.getMachineSetting(e.tool,H)&&p.holdsOurConfig(e.tool)),_=n.t(l?"ccswitch.plan_use":"ccswitch.plan_add",{tools:h(m),path:a.state.dbPath})+(y.length>0?"\n"+n.t("ccswitch.plan_handover",{tools:h(y)}):"");if(K())return void console.log(_);if(!f&&G()&&(console.log(_),!await E({message:n.t("ccswitch.confirm"),defaultValue:!0})))return a.reopen?.(),void(process.exitCode=v.cancelled);s(),c();const k=[],w=[];for(const t of m){const i=d[t.tool].displayName,s=o(t.tool).ccSwitch;try{const o=await J(t.tool,t.apiKey,r.getModelsForTool(t.tool)),a=W(t.tool,o);if(0===a.cards.length){ne(n.t("ccswitch.no_models",{tool:i}));continue}if(s.handOver&&p.holdsOurConfig(t.tool)&&(p.unloadPrivateConfig(t.tool),r.getMachineSetting(t.tool,H)||console.log(e.gray(" "+n.t("ccswitch.handed_over",{tool:i})))),l&&fe(t.tool))ne(n.t("ccswitch.not_installed_card_only",{tool:i}));else if(l&&s.applyAsCards)s.applyAsCards({...o,takeOver:!0},a.cards),k.push(t.tool);else if(l){if(!await ue(t.tool,t.apiKey,{...u,takeOver:!0}))continue;k.push(t.tool)}w.push({tool:t.tool,group:{...a,current:k.includes(t.tool)}})}catch(e){re("× "+n.t("ccswitch.card_failed",{tool:i,reason:e instanceof Error?e.message:String(e)}))}}try{const o=w.length>0?await ie(w.map(e=>e.group)):[];o.forEach((e,o)=>{const t=w[o].tool,i=d[t].displayName;r.setMachineSetting(t,H,k.includes(t)?"use":"add");const l=String(e.written),s=e.current?ee(e.app)?"ccswitch.done_enabled":"ccswitch.done_use":k.includes(t)&&e.proxyMode?"ccswitch.done_proxy":e.written>1?"ccswitch.done_add_many":"ccswitch.done_add";ae(n.t(s,{tool:i,count:l})),e.skipped.length>0&&ne(n.t("ccswitch.skipped_foreign",{tool:i,ids:e.skipped.join(", ")}))}),z("ccswitch","ok",{detail:{mode:l?"use":"add",schema:a.state.schema,tools:w.map(e=>e.tool)}}),o.some(e=>!e.current)&&console.log(e.gray(" "+n.t("ccswitch.switch_hint")))}catch(e){z("ccswitch","fail",{error:e,detail:{mode:l?"use":"add",schema:a.state.schema}}),re("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}a.reopen?.(),k.length>0&&await t(k,{apps:{install:!1}}),w.length<m.length&&(process.exitCode=1)}(Z,"use"===F,P,()=>{Me&&y&&r.setApiKey(y);for(const e of Z)e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool)},A,Boolean(c.fromInstaller)),void(void 0!==te&&(process.exitCode=te)));if(Q)return he(Z.filter(e=>!fe(e.tool)).map(e=>e.tool),Z.length>0,Z.filter(e=>fe(e.tool)).map(e=>e.tool)),void((ke>0||void 0!==te)&&(process.exitCode=te??v[ce??"operation"]));const Ie=Z.filter(e=>!fe(e.tool)),Ae=Me||Z.some(e=>e.dedicated),Oe=X?a().filter(e=>!Z.some(o=>o.tool===e.tool)):[],Ne=!c.fromInstaller&&G();if((Z.length>0||Ae)&&!c.fromInstaller&&!await B([...Ie.map(e=>e.tool),...Oe.map(e=>e.tool)],{keyFile:Ae?N(r.getConfigDir(),"config.yaml"):void 0,installFirst:Z.filter(e=>fe(e.tool)).map(e=>e.tool)}))return void(process.exitCode=v.cancelled);Te.length>0&&(await U(Te),L()),(Z.length>0||Ae)&&s(),Me&&y&&r.setApiKey(y);for(const e of Z)fe(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),oe.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await ue(e.tool,e.apiKey,{...A,takeOver:e.dedicated||Ne})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),pe+=1):(ke+=1,ve.delete(e.tool));const Ee=Z.length>0||Ae?await l(Oe):[];if(void 0!==te)return oe.length>0&&ge(oe.map(e=>e.tool)),void(process.exitCode=te);let Ge=[];if(oe.length>0){const o=await async function(o,t,i){const l=o.map(e=>e.tool);if(0===l.length)return{still:[],applied:[],failed:[]};const s=l.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||$()||(M()?a=!T():process.stdin.isTTY&&(console.log(""),a=(await D.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of l)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return $()||console.log(e.gray(n.t("setup.install_all_hint",{cli:R}))),{still:l,applied:[],failed:[]}}const c=[];for(const o of l){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){q.logError(`setup: install ${o}`,e)}L(),p.isToolInstalled(o)||c.push(o)}const u=l.filter(e=>!c.includes(e));u.length>0&&console.log("");const f=[],m=[];for(const{tool:e,apiKey:t,dedicated:l}of o.filter(e=>u.includes(e.tool)))await ue(e,t,i)?(f.push(e),l||r.clearToolApiKey(e)):m.push(e);return{still:c,applied:f,failed:m}}(oe,$e,A);Ge=o.still,pe+=o.applied.length,ke+=o.failed.length;for(const e of[...Ge,...o.failed])ve.delete(e)}if(pe>0){const t=[...ve].filter(e=>!o(e)?.isInstalled&&!Ge.includes(e)),i=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),l=n.t("setup.done",{count:String(pe)});ae("\n"+(i?`${l}${n.t("setup.done_commands",{commands:i})}`:l)),Ge.length>0&&ge(Ge);for(const e of t){const o=p.ensureNativeOnPath(e);o&&ae(n.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!$()&&"1"!==V("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===pe&&Ge.length>0&&ge(Ge),ke>0&&(re(n.t("setup.failed_summary",{count:String(ke)})),$()||console.error(`${R} setup --key ${n.t("errors.key_placeholder")}`)),await t([...ve,...Ee],{apps:{install:await installMissingApps([...ve],$e,Ke)}}),(ke>0||0===pe&&0===Ge.length)&&(process.exitCode=v[ce??"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 i,moveOtherToolsAfterFallback as l,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r,savedApiKeys as c}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as u,fetchModels as m}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as g}from"../lib/tools/codex.js";import{resolveModelCatalog as h}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as w}from"../lib/tools/claude-desktop.js";import{operationError as _,authenticationError as k,networkError as b,EXIT_CODES as v}from"../lib/errors.js";import{canPrompt as C,emitJson as x,hasExplicitYes as S,isColorEnabled as j,isDryRun as K,isJsonMode as M,isNonInteractive as $,shouldAutoConfirm as T}from"../lib/runtime-options.js";import{appsForTools as N,appUpgradeCommand as A,getApp as I}from"../lib/app-update.js";import{join as O}from"path";import{confirmAction as E}from"../lib/confirm.js";import{asksBeforeWriting as G,confirmWritePlan as B,printWritePlan as F,toolWritePlan as P}from"../lib/write-plan.js";import q from"inquirer";import{logger as D}from"../utils/logger.js";import{forgetInstalls as L}from"../lib/tools/tool-installs.js";import{CLI_NAME as R,brandEnv as V}from"../lib/brand.js";import{unsupportedUpgradeTargets as Y,upgradeCommand as U}from"./upgrade.js";import{track as z}from"../lib/telemetry.js";import{CCSWITCH_SETTING as H,buildCcSwitchCards as W,ccSwitchContext as J,ccSwitchSelector as Q,ourCcSwitchCards as X,removeCcSwitchCards as Z,isAdditiveCcSwitchApp as ee,inspectCcSwitch as oe,quitCcSwitch as te,writeCcSwitchCards as ie}from"../lib/ccswitch.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 le(e){const o=await m(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 se(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 ae(o){console.log(e.green(o))}function ne(o){console.log(e.yellow(o))}function re(o){console.error(e.red(o))}let ce=null;function pe(e){const o={operation:1,authentication:2,network:3};(!ce||o[e]>o[ce])&&(ce=e)}async function de(o,t){M()||console.log(e.gray(n.t("setup.validating",{label:o})));const i=await u(t);if(i.valid)return!0;const l=n.t("errors.key_placeholder"),s="--key"===o?`${R} setup --key ${l}`:`${R} setup ${o} ${l}`;let a;if("network_error"===i.error?(pe("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:i.message||"network error"}),`${R} base auto`,"network_error")):"invalid_api_key"===i.error?(pe("authentication"),a=k(n.t("setup.invalid_key",{label:o,reason:i.message||"invalid"}),s,"invalid_api_key")):(pe("operation"),a=_(n.t("setup.validate_failed",{label:o,reason:i.message||i.error||"unknown"}),s,i.error)),M())throw a;return re(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function ue(t,i,l={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=l,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",w,!a),await p.applyPrivateConfig(t,i,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(M())throw _(e instanceof Error?e.message:String(e),`${R} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return re("× "+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 me(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function fe(e){if(S())return!0;const o=d[e]?.displayName??e;return C()?E({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(ne(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,i){const l=N(o).filter(e=>{if(i&&!i.includes(e))return!1;const o=I(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return D.logError(`setup: app installed? ${e}`,o),!1}});if(0===l.length)return!1;const s=e=>I(e)?.displayName??e;let a=t;if(void 0===a&&!M())if(T())a=!$();else if(C()){const e=l.map(s).join(n.t("setup.list_separator")),o=l.reduce((e,o)=>e+(I(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await q.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!M())for(const o of l)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:A(o)})));return Boolean(a)}function ge(e){ne(n.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${R} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function he(o,t,i=[]){const l=P(o),s=O(r.getConfigDir(),"config.yaml");if(M())x({dry_run:!0,tools:l,install_first:i,key_file:t?s:null});else{if(0===l.length&&0===i.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")}`)}F(l,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:i})}}function ye(e){return Boolean(o(e)?.installSpec||I(e)?.appInstaller)}function we(e){return N(e).filter(e=>{const o=I(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return D.logError(`setup: app blocker ${e}`,o),!1}})}function _e(e){const o=I(e);let t,i;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){D.logError(`setup: app installed? ${e}`,o),t=!1}i=t?o.installedVersion?.():null}else t=p.isToolInstalled(e),i=t?p.installedVersion(e):null;return t?i?n.t("setup.pick_installed",{version:i}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function ke(o,t){return{name:`${I(o)?.displayName??d[o]?.displayName??o} ${e.gray(_e(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 be(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function prepareCcSwitch(){let e,o=await oe();if("running"===o.problem&&!K()&&(S()||C())&&(S()||await E({message:n.t("ccswitch.ask_quit"),defaultValue:!0}))){const t=te();t&&(e=t.reopen,o=await oe())}if(o.ok||K()&&"running"===o.problem)return{state:o,reopen:e};const t=n.t(`ccswitch.problem_${o.problem}`,{path:o.dbPath,schema:String(o.schema??"?"),node:process.versions.node});if(z("ccswitch","unsupported_schema"===o.problem||"unexpected_tables"===o.problem||"unreadable"===o.problem?"fail":"skip",{detail:{problem:o.problem,schema:o.schema,detail:o.detail,platform:process.platform}}),M())throw _(t,`${R} setup --key ${n.t("errors.key_placeholder")}`,`ccswitch_${o.problem}`);return re(t),e?.(),null}export async function removeFromCcSwitch(t){const i=o(t)?.ccSwitch;if(!i)return"none";const l=d[t].displayName;let s=!1;try{s=i.unloadAsCards?.({savedKeys:c()})??!1}catch(e){D.logError(`removeFromCcSwitch(${t})`,e)}const a=Q(t);if(0===(await X(a)).length)return r.setMachineSetting(t,H,""),s?"removed":"none";const p=await prepareCcSwitch();if(!p)return"blocked";try{const o=await Z(a);return r.setMachineSetting(t,H,""),z("ccswitch","ok",{detail:{mode:"remove",schema:p.state.schema,tools:[t],cards:o}}),console.log(e.green(n.t("ccswitch.removed_cards",{tool:l,count:String(o)}))),"removed"}catch(e){return z("ccswitch","fail",{error:e,detail:{mode:"remove",schema:p.state.schema}}),re("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),"blocked"}finally{p.reopen?.()}}export async function setupCommand(u){ce=null;const m=DEDICATED_KEYS.map(e=>({...e,apiKey:u[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),y=void 0!==u.oneMillion||void 0!==u.claudeOfficial||void 0!==u.desktopRegistry;let w=u.key?.trim();const _=u.upgrade??[],k=Y(_);if(k.length>0)return re(n.t("upgrade.unsupported",{tool:k.join(", ")})),void(process.exitCode=v.usage);if(_.length>0&&(K()?console.log(n.t("setup.dry_run_upgrade",{tools:_.join(", ")})):(await U(_),L()),!w&&0===m.length&&!y))return;w||0!==m.length||y||!G()||(w=(await q.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const b=void 0!==u.oneMillion,x=void 0!==u.claudeOfficial;let j;if(x&&(j=parseOnOff(u.claudeOfficial),void 0===j))return re(n.t("setup.claude_official_invalid",{value:String(u.claudeOfficial)})),void(process.exitCode=1);const N=void 0!==u.desktopRegistry;let A;if(N&&(A=parseOnOff(u.desktopRegistry),void 0===A))return re(n.t("setup.desktop_registry_invalid",{value:String(u.desktopRegistry)})),void(process.exitCode=1);const F=x||N,P=Boolean(w||m.length>0),pe={oneMillion:u.oneMillion,officialLogin:j,desktopRegistry:A,force:u.force};if(!P&&(b||F)&&K())return void he([...b?["codex"]:[],...F?["claude-desktop"]:[]],!1);if(!P&&(b||F)){if(b){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===u.oneMillion;r.setToolSetting("codex",f,o);const t=await h(e);g(o,t??void 0),ae(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){re(n.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else re(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(F){const e=r.getApiKeyForTool("claude-desktop");e?await ue("claude-desktop",e,{...pe,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(re(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!P)return re(n.t("setup.usage")),void(process.exitCode=1);const _e=u.ccswitchUse?"use":u.ccswitch?"add":null,ve=_e?await prepareCcSwitch():null;if(_e&&!ve)return void(process.exitCode=1);const Ce=K(),xe=Ce?null:await i(w||m[0].apiKey,{save:!1}),Se=[],je=[];let Ke,Me=0,$e=0;const Te=new Set,Ne=m.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of Ne){if(!await de(e.label,e.apiKey)){$e+=1;continue}const o=await le(e.apiKey);!o.probed||se(o,e.need)?(o.probed||ne(n.t("setup.probe_failed",{label:e.label})),Se.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),Te.add(e.tool)):(re(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),$e+=1)}const Ae=!!w&&await de("--key",w);w&&!Ae&&(Ke=v[ce??"operation"]);const Ie=w&&Ae?await le(w):void 0;w&&Ie&&!Ie.probed&&ne(n.t("setup.probe_failed",{label:"--key"})),!(w&&Ie&&Ie.probed)||Ie.hasClaude||Ie.hasGpt||Ie.hasGrok||Ie.hasGemini||(re(n.t("setup.key_no_family")),Ke=1);const Oe=Boolean(w)&&0===m.length&&!u.fromInstaller&&G()&&!_e;if(w&&Ie&&void 0===Ke){const e=Ie.hasClaude||Ie.hasGpt||Ie.hasGrok||Ie.hasGemini,o=[{tool:"claude-code",capable:Ie.hasClaude,skipMsg:n.t(be()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:Ie.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:Ie.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:Ie.hasClaude&&be(),skipMsg:"",quiet:!0},{tool:"agy",capable:Ie.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)Te.has(e.tool)||(e.capable?(!e.ask||Ce||Oe||await fe(e.tool))&&(Se.push({tool:e.tool,apiKey:w,dedicated:!1}),Te.add(e.tool)):e.quiet||ne(e.skipMsg))}let Ee,Ge=u.install,Be=[];if(Oe&&void 0===Ke&&Se.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await q.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>ke(e,!0))}]);let i=[];const l=[...e.filter(ye),...we(e)];if(o&&l.length>0){const e=e=>I(e)?.tool??e;i=(await q.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:l.map(o=>ke(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===i.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:i}}(Se.map(e=>e.tool),void 0===u.upgrade);if(!e)return void(process.exitCode=v.cancelled);if(0===e.configure.length)return void await U(e.upgrade);Be=e.upgrade,Ee=[],!0!==Ge&&(Ge=!1);const o=e.configure.filter(e=>me(e)&&!Be.includes(e)&&!Ge);if(o.length>0&&ne(n.t("setup.pick_configure_skip",{tools:o.map(e=>d[e].displayName).join(n.t("setup.list_separator"))})),Se.splice(0,Se.length,...Se.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===Se.length)return void(Be.length>0&&await U(Be))}const Fe=Boolean(w&&Ae&&void 0===Ke);if(_e&&ve)return void 0!==Ke&&0===Se.length?(ve.reopen?.(),void(process.exitCode=Ke)):(await async function(i,l,a,c,u,m){const f=i.filter(e=>p.supportsCcSwitch(e.tool)),g=i.filter(e=>!p.supportsCcSwitch(e.tool)),h=e=>e.map(e=>d[e.tool].displayName).join(n.t("setup.list_separator"));if(g.length>0&&ne(n.t("ccswitch.not_supported",{tools:h(g)})),0===f.length)return re(n.t("ccswitch.nothing")),a.reopen?.(),void(process.exitCode=1);const y=f.filter(e=>o(e.tool)?.ccSwitch?.handOver&&!r.getMachineSetting(e.tool,H)&&p.holdsOurConfig(e.tool)),w=n.t(l?"ccswitch.plan_use":"ccswitch.plan_add",{tools:h(f),path:a.state.dbPath})+(y.length>0?"\n"+n.t("ccswitch.plan_handover",{tools:h(y)}):"");if(K())return void console.log(w);if(!m&&G()&&(console.log(w),!await E({message:n.t("ccswitch.confirm"),defaultValue:!0})))return a.reopen?.(),void(process.exitCode=v.cancelled);s(),c();const _=[],k=[];for(const t of f){const i=d[t.tool].displayName,s=o(t.tool).ccSwitch;try{const o=await J(t.tool,t.apiKey,r.getModelsForTool(t.tool)),a=W(t.tool,o);if(0===a.cards.length){ne(n.t("ccswitch.no_models",{tool:i}));continue}if(s.handOver&&p.holdsOurConfig(t.tool)&&(p.unloadPrivateConfig(t.tool),r.getMachineSetting(t.tool,H)||console.log(e.gray(" "+n.t("ccswitch.handed_over",{tool:i})))),l&&me(t.tool))ne(n.t("ccswitch.not_installed_card_only",{tool:i}));else if(l&&s.applyAsCards)s.applyAsCards({...o,takeOver:!0},a.cards),_.push(t.tool);else if(l){if(!await ue(t.tool,t.apiKey,{...u,takeOver:!0}))continue;_.push(t.tool)}k.push({tool:t.tool,group:{...a,current:_.includes(t.tool)}})}catch(e){re("× "+n.t("ccswitch.card_failed",{tool:i,reason:e instanceof Error?e.message:String(e)}))}}try{const o=k.length>0?await ie(k.map(e=>e.group)):[];o.forEach((e,o)=>{const t=k[o].tool,i=d[t].displayName;r.setMachineSetting(t,H,_.includes(t)?"use":"add");const l=String(e.written),s=e.current?ee(e.app)?"ccswitch.done_enabled":"ccswitch.done_use":_.includes(t)&&e.proxyMode?"ccswitch.done_proxy":e.written>1?"ccswitch.done_add_many":"ccswitch.done_add";ae(n.t(s,{tool:i,count:l})),e.skipped.length>0&&ne(n.t("ccswitch.skipped_foreign",{tool:i,ids:e.skipped.join(", ")}))}),z("ccswitch","ok",{detail:{mode:l?"use":"add",schema:a.state.schema,tools:k.map(e=>e.tool)}}),o.some(e=>!e.current)&&console.log(e.gray(" "+n.t("ccswitch.switch_hint")))}catch(e){z("ccswitch","fail",{error:e,detail:{mode:l?"use":"add",schema:a.state.schema}}),re("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}a.reopen?.(),_.length>0&&await t(_,{apps:{install:!1}}),k.length<f.length&&(process.exitCode=1)}(Se,"use"===_e,ve,()=>{Fe&&w&&r.setApiKey(w);for(const e of Se)e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool)},pe,Boolean(u.fromInstaller)),void(void 0!==Ke&&(process.exitCode=Ke)));if(Ce)return he(Se.filter(e=>!me(e.tool)).map(e=>e.tool),Se.length>0,Se.filter(e=>me(e.tool)).map(e=>e.tool)),void(($e>0||void 0!==Ke)&&(process.exitCode=Ke??v[ce??"operation"]));const Pe=Se.filter(e=>!me(e.tool)),qe=Fe||Se.some(e=>e.dedicated),De=xe?a().filter(e=>!Se.some(o=>o.tool===e.tool)):[],Le=!u.fromInstaller&&G(),Re=Pe.filter(e=>o(e.tool)?.ccSwitch&&r.getMachineSetting(e.tool,H));if(Le&&Re.length>0&&console.log(e.yellow(n.t("ccswitch.plan_reclaim",{tools:Re.map(e=>d[e.tool].displayName).join(n.t("setup.list_separator"))}))),(Se.length>0||qe)&&!u.fromInstaller&&!await B([...Pe.map(e=>e.tool),...De.map(e=>e.tool)],{keyFile:qe?O(r.getConfigDir(),"config.yaml"):void 0,installFirst:Se.filter(e=>me(e.tool)).map(e=>e.tool)}))return void(process.exitCode=v.cancelled);Be.length>0&&(await U(Be),L()),(Se.length>0||qe)&&s(),Fe&&w&&r.setApiKey(w);for(const e of Se)me(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),je.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await ue(e.tool,e.apiKey,{...pe,takeOver:e.dedicated||Le})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),Me+=1):($e+=1,Te.delete(e.tool));const Ve=Se.length>0||qe?await l(De):[];if(void 0!==Ke)return je.length>0&&ge(je.map(e=>e.tool)),void(process.exitCode=Ke);let Ye=[];if(je.length>0){const o=await async function(o,t,i){const l=o.map(e=>e.tool);if(0===l.length)return{still:[],applied:[],failed:[]};const s=l.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||M()||(T()?a=!$():process.stdin.isTTY&&(console.log(""),a=(await q.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of l)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return M()||console.log(e.gray(n.t("setup.install_all_hint",{cli:R}))),{still:l,applied:[],failed:[]}}const c=[];for(const o of l){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){D.logError(`setup: install ${o}`,e)}L(),p.isToolInstalled(o)||c.push(o)}const u=l.filter(e=>!c.includes(e));u.length>0&&console.log("");const m=[],f=[];for(const{tool:e,apiKey:t,dedicated:l}of o.filter(e=>u.includes(e.tool)))await ue(e,t,i)?(m.push(e),l||r.clearToolApiKey(e)):f.push(e);return{still:c,applied:m,failed:f}}(je,Ge,pe);Ye=o.still,Me+=o.applied.length,$e+=o.failed.length;for(const e of[...Ye,...o.failed])Te.delete(e)}if(await async function(t){const i=t.filter(e=>o(e)?.ccSwitch&&r.getMachineSetting(e,H));if(0===i.length)return;const l=[];for(const e of i){r.setMachineSetting(e,H,"");try{o(e).ccSwitch.unloadAsCards?.({savedKeys:c()})}catch(o){D.logError(`reclaimFromCcSwitch(${e})`,o)}(await X(Q(e))).length>0&&l.push(e)}if(0===l.length)return;const s=l.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a,p=await oe();if("running"===p.problem&&(S()||C())&&(S()||await E({message:n.t("ccswitch.ask_quit_reclaim",{tools:s}),defaultValue:!0}))){const e=te();e&&(a=e.reopen,p=await oe())}if(!p.ok)return ne(n.t("ccswitch.reclaim_left",{tools:s})),z("ccswitch","skip",{detail:{mode:"reclaim",problem:p.problem,schema:p.schema,tools:l}}),void a?.();try{for(const o of l){const t=await Z(Q(o));console.log(e.gray(" "+n.t("ccswitch.reclaimed",{tool:d[o].displayName,count:String(t)})))}z("ccswitch","ok",{detail:{mode:"reclaim",schema:p.schema,tools:l}})}catch(e){z("ccswitch","fail",{error:e,detail:{mode:"reclaim",schema:p.schema}}),ne(n.t("ccswitch.reclaim_left",{tools:s}))}finally{a?.()}}([...Te].filter(e=>!Ye.includes(e))),Me>0){const t=[...Te].filter(e=>!o(e)?.isInstalled&&!Ye.includes(e)),i=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),l=n.t("setup.done",{count:String(Me)});ae("\n"+(i?`${l}${n.t("setup.done_commands",{commands:i})}`:l)),Ye.length>0&&ge(Ye);for(const e of t){const o=p.ensureNativeOnPath(e);o&&ae(n.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!M()&&"1"!==V("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===Me&&Ye.length>0&&ge(Ye),$e>0&&(re(n.t("setup.failed_summary",{count:String($e)})),M()||console.error(`${R} setup --key ${n.t("errors.key_placeholder")}`)),await t([...Te,...Ve],{apps:{install:await installMissingApps([...Te],Ge,Ee)}}),($e>0||0===Me&&0===Ye.length)&&(process.exitCode=v[ce??"operation"])}
@@ -1 +1 @@
1
- import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import n from"chalk";import{configManager as r}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as i}from"./model-catalog.js";import{listAdapters as c}from"./tools/registry.js";import{UserActionNeeded as a}from"./tools/types.js";import{logger as l}from"../utils/logger.js";import{resolveUpdateCachePath as f}from"./auto-update.js";import{isHelpRequest as m}from"./cli-help.js";import{brandEnvName as d}from"./brand.js";import{atomicWriteFile as h}from"./tools/backup.js";import{track as u}from"./telemetry.js";import{CCSWITCH_SETTING as p,buildCcSwitchCards as g,ccSwitchContext as y,hasCcSwitchCards as M,inspectCcSwitch as w,writeCcSwitchCards as k}from"./ccswitch.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const _=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),j=["--json","--dry-run","--help","-h","--version","-v"],E=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[d("DISABLE_MODEL_REFRESH")])return!0;if(j.some(o=>e.includes(o))||m(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&_.has(t)}let R={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...R,keyMismatch:[...R.keyMismatch]}}export async function refreshModelMenus(e={}){const o=[],t=new Map,n=[];E.length=0,R={checked:0,failed:0,offline:0,keyMismatch:[]};for(const e of c())if(e.refreshModelMenu&&e.listedModels)try{let s=r.getApiKeyForTool(e.name);if(!s)continue;const c=e.detectCurrentConfig().apiKey;if(c&&c!==s&&c===r.getApiKey()&&(r.clearToolApiKey(e.name),s=c),e.ccSwitch&&r.getMachineSetting(e.name,p)&&(o.push({name:e.name,apiKey:s}),c!==s||e.ccSwitch.handOver))continue;if(c!==s){c&&(R.keyMismatch.push(e.displayName),u(`menu-sync:${e.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const a=e.listedModels();if(null===a)continue;t.has(s)||t.set(s,await i(s));const l=t.get(s);if(!l){R.offline++;continue}e.refreshModelMenu({apiKey:s,baseUrl:r.getBaseUrl(),models:r.getModelsForTool(e.name),settings:r.getToolSettings(e.name),catalog:l}),R.checked++;const f=e.listedModels();if(null===f){n.push({tool:e.displayName,added:[],removed:[],fromGateway:!0});continue}const m=f,d=m.filter(e=>!a.includes(e)),h=a.filter(e=>!m.includes(e));(d.length>0||h.length>0)&&n.push({tool:e.displayName,added:d,removed:h})}catch(o){R.failed++,l.logError(`modelRefresh(${e.name})`,o),u(`menu-sync:${e.name}`,o instanceof a?"skip":"fail",{error:o}),o instanceof a&&E.push(o.message)}return await async function(e,o){if(0===e.length)return;const t=await w();if(!t.ok)return void("running"===t.problem&&o&&E.push(s.t("ccswitch.refresh_running")));const n=[];for(const o of e){const e=g(o.name,await y(o.name,o.apiKey,r.getModelsForTool(o.name)));e&&e.cards.length>0&&await M(e)&&n.push(e)}if(0!==n.length)try{await k(n),u("menu-sync:ccswitch","ok",{detail:{apps:n.map(e=>e.app),schema:t.schema}})}catch(e){l.logError("modelRefresh(ccswitch)",e),u("menu-sync:ccswitch","fail",{error:e})}}(o,Boolean(e.explicit)),n}export async function runModelRefresh(r,i={}){const c=i.env??process.env,a=i.now??Date.now(),m=function(e){return t(o(f(e)),"model-refresh.json")}(c);if(!i.force){if(shouldSkipModelRefresh(r,c))return[];if(a-function(o){try{const t=JSON.parse(e(o,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(m)<36e5)return[]}let d=[];try{d=await refreshModelMenus({explicit:Boolean(i.force)});const e=R.offline>0&&0===R.checked&&0===R.failed,o=e?a-36e5+6e5:a;e&&u("menu-sync","skip",{detail:{reason:"offline",tools:R.offline}}),h(m,JSON.stringify({refreshed_at:o})+"\n")}catch(e){l.logError("runModelRefresh",e)}const p=i.output??(e=>console.log(n.gray(e)));for(const e of E)p(e);for(const e of d){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 d}
1
+ import{existsSync as e,readFileSync as o}from"fs";import{dirname as t,join as n}from"path";import r from"chalk";import{configManager as s}from"./config.js";import{i18n as i}from"./i18n.js";import{resolveModelCatalog as c}from"./model-catalog.js";import{listAdapters as a}from"./tools/registry.js";import{UserActionNeeded as l}from"./tools/types.js";import{logger as f}from"../utils/logger.js";import{resolveUpdateCachePath as m}from"./auto-update.js";import{isHelpRequest as d}from"./cli-help.js";import{brandEnvName as h}from"./brand.js";import{atomicWriteFile as u}from"./tools/backup.js";import{track as p}from"./telemetry.js";import{CCSWITCH_SETTING as g,buildCcSwitchCards as y,ccSwitchContext as M,ccSwitchDbPath as w,hasCcSwitchCards as k,inspectCcSwitch as S,writeCcSwitchCards as _}from"./ccswitch.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const j=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),E=["--json","--dry-run","--help","-h","--version","-v"],R=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[h("DISABLE_MODEL_REFRESH")])return!0;if(E.some(o=>e.includes(o))||d(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&j.has(t)}let v={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...v,keyMismatch:[...v.keyMismatch]}}export async function refreshModelMenus(o={}){const t=[],n=new Map,r=[];R.length=0,v={checked:0,failed:0,offline:0,keyMismatch:[]};for(const o of a())if(o.refreshModelMenu&&o.listedModels)try{let i=s.getApiKeyForTool(o.name);if(!i)continue;const a=o.detectCurrentConfig().apiKey;if(a&&a!==i&&a===s.getApiKey()&&(s.clearToolApiKey(o.name),i=a),o.ccSwitch&&s.getMachineSetting(o.name,g)&&!e(w())&&(s.setMachineSetting(o.name,g,""),p(`menu-sync:${o.name}`,"ok",{detail:{ccswitch:"gone"}})),o.ccSwitch&&s.getMachineSetting(o.name,g)&&(t.push({name:o.name,apiKey:i}),a!==i||o.ccSwitch.handOver))continue;if(a!==i){a&&(v.keyMismatch.push(o.displayName),p(`menu-sync:${o.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const l=o.listedModels();if(null===l)continue;n.has(i)||n.set(i,await c(i));const f=n.get(i);if(!f){v.offline++;continue}o.refreshModelMenu({apiKey:i,baseUrl:s.getBaseUrl(),models:s.getModelsForTool(o.name),settings:s.getToolSettings(o.name),catalog:f}),v.checked++;const m=o.listedModels();if(null===m){r.push({tool:o.displayName,added:[],removed:[],fromGateway:!0});continue}const d=m,h=d.filter(e=>!l.includes(e)),u=l.filter(e=>!d.includes(e));(h.length>0||u.length>0)&&r.push({tool:o.displayName,added:h,removed:u})}catch(e){v.failed++,f.logError(`modelRefresh(${o.name})`,e),p(`menu-sync:${o.name}`,e instanceof l?"skip":"fail",{error:e}),e instanceof l&&R.push(e.message)}return await async function(e,o){if(0===e.length)return;const t=await S();if(!t.ok)return void("running"===t.problem&&o&&R.push(i.t("ccswitch.refresh_running")));const n=[];for(const o of e){const e=y(o.name,await M(o.name,o.apiKey,s.getModelsForTool(o.name)));e&&e.cards.length>0&&await k(e)&&n.push(e)}if(0!==n.length)try{await _(n),p("menu-sync:ccswitch","ok",{detail:{apps:n.map(e=>e.app),schema:t.schema}})}catch(e){f.logError("modelRefresh(ccswitch)",e),p("menu-sync:ccswitch","fail",{error:e})}}(t,Boolean(o.explicit)),r}export async function runModelRefresh(e,s={}){const c=s.env??process.env,a=s.now??Date.now(),l=function(e){return n(t(m(e)),"model-refresh.json")}(c);if(!s.force){if(shouldSkipModelRefresh(e,c))return[];if(a-function(e){try{const t=JSON.parse(o(e,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(l)<36e5)return[]}let d=[];try{d=await refreshModelMenus({explicit:Boolean(s.force)});const e=v.offline>0&&0===v.checked&&0===v.failed,o=e?a-36e5+6e5:a;e&&p("menu-sync","skip",{detail:{reason:"offline",tools:v.offline}}),u(l,JSON.stringify({refreshed_at:o})+"\n")}catch(e){f.logError("runModelRefresh",e)}const h=s.output??(e=>console.log(r.gray(e)));for(const e of R)h(e);for(const e of d){if(e.fromGateway){h(i.t("model_refresh.from_gateway",{tool:e.tool}));continue}const o=[e.added.length>0?i.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?i.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);h(i.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return d}
@@ -348,7 +348,11 @@
348
348
  "done_add_many": "Added {{count}} {{brand}} cards for {{tool}} to CC Switch",
349
349
  "done_enabled": "Added the {{brand}} cards for {{tool}} to CC Switch and turned them on",
350
350
  "skipped_foreign": "{{tool}}: CC Switch already has other cards with these ids, left as they are: {{ids}}",
351
- "removed_cards": "Removed {{count}} {{brand}} card(s) for {{tool}} from CC Switch"
351
+ "removed_cards": "Removed {{count}} {{brand}} card(s) for {{tool}} from CC Switch",
352
+ "ask_quit_reclaim": "{{tools}} go back to being configured by {{cli}}, so the {{brand}} cards in CC Switch go: quit CC Switch now and reopen it when done?",
353
+ "plan_reclaim": "These tools go back to being configured by {{cli}}, and their {{brand}} cards in CC Switch are deleted: {{tools}}",
354
+ "reclaimed": "Deleted {{count}} {{brand}} card(s) for {{tool}} from CC Switch; {{cli}} configures it directly again",
355
+ "reclaim_left": "{{tools}} are configured by {{cli}} directly again, but their {{brand}} cards in CC Switch weren't deleted this time. Quit CC Switch and run the same command again to delete them"
352
356
  },
353
357
  "setup": {
354
358
  "dry_run_tool": "Would configure {{tool}}, writing:",
@@ -348,7 +348,11 @@
348
348
  "done_add_many": "已把 {{tool}} 的 {{count}} 张 {{brand}} 卡片加进 CC Switch",
349
349
  "done_enabled": "已把 {{tool}} 的 {{brand}} 卡片加进 CC Switch 并启用",
350
350
  "skipped_foreign": "{{tool}}:CC Switch 里已有同名的其他卡片,没有覆盖:{{ids}}",
351
- "removed_cards": "已从 CC Switch 删除 {{tool}} 的 {{count}} 张 {{brand}} 卡片"
351
+ "removed_cards": "已从 CC Switch 删除 {{tool}} 的 {{count}} 张 {{brand}} 卡片",
352
+ "ask_quit_reclaim": "{{tools}} 改回由 {{cli}} 直接配置,要删掉 CC Switch 里的 {{brand}} 卡片:先退出 CC Switch,删完再自动打开?",
353
+ "plan_reclaim": "这些工具改回由 {{cli}} 直接配置,CC Switch 里的 {{brand}} 卡片会删掉:{{tools}}",
354
+ "reclaimed": "已删掉 CC Switch 里 {{tool}} 的 {{count}} 张 {{brand}} 卡片,改回由 {{cli}} 直接配置",
355
+ "reclaim_left": "{{tools}} 已改回由 {{cli}} 直接配置,但 CC Switch 里的 {{brand}} 卡片这次没删掉。退出 CC Switch 后再运行一次刚才的命令即可删掉"
352
356
  },
353
357
  "setup": {
354
358
  "dry_run_tool": "将配置 {{tool}},写入:",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-vibeway/cli",
3
- "version": "0.0.202",
3
+ "version": "0.0.203",
4
4
  "description": "Configure Claude Code, Codex, Grok Build and other coding tools for VibeWay with one command",
5
5
  "main": "dist/index.js",
6
6
  "bin": {