@vibeapi/api-helper 0.0.180 → 0.0.182

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/brand.json CHANGED
@@ -23,18 +23,10 @@
23
23
  "url": "https://www.vibeapi.cn",
24
24
  "label": "主站"
25
25
  },
26
- {
27
- "url": "https://www.vibeapi.si",
28
- "label": "主站备用域名"
29
- },
30
26
  {
31
27
  "url": "https://hk.vibeapi.cn",
32
28
  "label": "香港"
33
29
  },
34
- {
35
- "url": "https://us13-www.vibeapi.cn",
36
- "label": "美国"
37
- },
38
30
  {
39
31
  "url": "https://cf.vibeapi.cn",
40
32
  "label": "Cloudflare 加速"
@@ -42,6 +34,14 @@
42
34
  {
43
35
  "url": "https://api.vibecamp.cn",
44
36
  "label": "备用入口"
37
+ },
38
+ {
39
+ "url": "https://www.vibeapi.si",
40
+ "label": "主站备用域名"
41
+ },
42
+ {
43
+ "url": "https://us13-www.vibeapi.cn",
44
+ "label": "美国"
45
45
  }
46
46
  ],
47
47
  "links": {
@@ -10,10 +10,12 @@ import { type GatewayAddress, type ProbeOptions, type ProbeResult } from '../lib
10
10
  */
11
11
  export declare function baseCommand(target?: string): Promise<void>;
12
12
  /**
13
- * Before a setup writes anything: when the current address cannot be reached,
14
- * move to the first address in priority order that can, so the tools are
15
- * configured on an address that works from here. An address named with `--base`
16
- * on this run is left alone. Returns the new address, or null when nothing changed.
13
+ * Before a setup writes anything, put the profile on the first address in priority order
14
+ * that works from here: when the current address cannot be reached, move to one that can;
15
+ * when vibecli itself moved the profile to a backup earlier (an automatic fallback or
16
+ * `base auto`) and an address ahead of it works again, move back, so the main site is used
17
+ * whenever it can be (user 2026-11-16). An address the user picked (`base <n|url>`,
18
+ * `--base`) is left alone as long as it works. Returns the new address, or null when nothing changed.
17
19
  *
18
20
  * `save: false` uses the new address for this run only and leaves the profile as
19
21
  * it is until `saveGatewayFallback()`: setup calls that once the user confirmed
@@ -45,7 +47,7 @@ export interface ConfiguredTool {
45
47
  * Tools whose config still carries the key vibecli saved for them: the ones that follow
46
48
  * the address. Read it before a run saves a new key, or tools on the old key drop out.
47
49
  */
48
- export declare function toolsConfiguredByVibecli(): ConfiguredTool[];
50
+ export declare function toolsWeConfigured(): ConfiguredTool[];
49
51
  /** Rewrites the current address into each tool, keeping the key it already carries. */
50
52
  export declare function moveToolsToCurrentAddress(tools: ConfiguredTool[]): Promise<{
51
53
  applied: string[];
@@ -60,5 +62,10 @@ export declare function moveToolsToCurrentAddress(tools: ConfiguredTool[]): Prom
60
62
  * Returns the tools moved.
61
63
  */
62
64
  export declare function moveOtherToolsAfterFallback(tools: ConfiguredTool[]): Promise<string[]>;
63
- /** Saves `url` in the active profile and rewrites it into every tool vibecli configured. */
64
- export declare function switchGatewayAddress(url: string): Promise<void>;
65
+ /**
66
+ * Saves `url` in the active profile and rewrites it into every tool vibecli configured.
67
+ * `auto`: picked by priority (`base auto`), so a later setup may move back to an address ahead of it.
68
+ */
69
+ export declare function switchGatewayAddress(url: string, options?: {
70
+ auto?: boolean;
71
+ }): Promise<void>;
@@ -1 +1 @@
1
- import e from"chalk";import{configManager as r,DEFAULT_BASE_URL as o}from"../lib/config.js";import{i18n as t}from"../lib/i18n.js";import{toolManager as s}from"../lib/tool-manager.js";import{listAdapters as a}from"../lib/tools/registry.js";import{postApplyPrompts as n}from"../lib/post-apply.js";import{emitJson as l,isJsonMode as i}from"../lib/runtime-options.js";import{logger as u}from"../utils/logger.js";import{reportCliError as c,usageError as p,authenticationError as d,networkError as f,operationError as m}from"../lib/errors.js";import{gatewayAddresses as b,normalizeBaseUrl as y,probeGatewayAddress as g}from"../lib/gateway-addresses.js";import{CLI_NAME as h}from"../lib/brand.js";import{track as _}from"../lib/telemetry.js";export async function baseCommand(s){const a=r.getBaseUrl(),n=addressesWithCurrent(),u=s?.trim().toLowerCase();if(!u)return void await async function(r,o){const s=savedApiKey(),a=await probeAll(r,{apiKey:s,samples:3});i()?l({ok:!0,current:o,addresses:r.map((e,r)=>({...e,...a[r],current:e.url===o}))}):(console.log(e.bold(t.t("base.current",{url:o}))),console.log(e.gray(t.t(s?"base.probe_with_key":"base.probe_without_key"))+"\n"),v(r,a,o),console.log("\n"+e.gray(t.t("base.usage_hint"))))}(n,a);if("auto"===u){const e=await probeAll(n,{apiKey:savedApiKey()}),r=e.find(e=>e.ok);if(!r){const r=e.every(e=>"key_rejected"===e.error);return x(r?"key_rejected":"no_reachable",t.t(r?"base.key_rejected_everywhere":"base.none_reachable")),void v(n,e,a)}return void await switchGatewayAddress(r.url)}let c;if("default"===u||"reset"===u)c=o;else if(/^\d+$/.test(u)){if(c=n[Number(u)-1]?.url??null,!c)return void x("bad_index",t.t("base.bad_index",{index:u,count:String(n.length)}))}else if(c=y(s),!c)return void x("bad_url",t.t("base.bad_url",{value:s}));const p=await g(c,{apiKey:savedApiKey()});p.ok?await switchGatewayAddress(c):x("unreachable",t.t("base.unreachable",{url:c,reason:reasonText(p)}))}export async function ensureReachableGatewayAddress(s=savedApiKey(),a={}){if(r.hasRuntimeBaseUrl())return null;const n=r.getBaseUrl(),l=await g(n,{apiKey:s});if(l.ok||"key_rejected"===l.error)return null;const u=b().filter(e=>e.url!==n),c=(await probeAll(u,{apiKey:s})).find(e=>e.ok);if(!c)return null;if(_("gateway-fallback","fallback",{error:reasonText(l),detail:{from:n,to:c.url}}),!1===a.save?(r.setBaseUrl(c.url,!1),w=c.url):k(c.url),!i()){const r=c.url===o?"base.setup_fallback_main":"base.setup_fallback";console.log(e.yellow(t.t(r,{from:n,reason:reasonText(l),url:c.url})))}return c.url}let w=null;function k(e){e===o?r.resetBaseUrl():r.setBaseUrl(e,!0)}export function saveGatewayFallback(){if(!w)return;const e=w;w=null,k(e)}export function addressesWithCurrent(){const e=r.getBaseUrl(),o=b();return o.some(r=>r.url===e)||o.push({url:e,label:t.t("base.custom_label")}),o}export function savedApiKey(){return r.getApiKey()||a().map(e=>r.getApiKeyForTool(e.name)).find(Boolean)}export async function probeAll(e,r={}){return Promise.all(e.map(e=>g(e.url,r)))}export function probeSummary(r,o){if(!r.ok)return e.red(`× ${reasonText(r)}`);const s=[`${r.ms} ms`];return void 0!==r.models&&s.push(t.t("base.models_count",{count:String(r.models)})),o&&s.push(t.t("base.fastest")),e.green(`√ ${s.join(" · ")}`)}export function fastestIndex(e){let r=-1;return e.forEach((o,t)=>{o.ok&&(r<0||o.ms<e[r].ms)&&(r=t)}),r}export function reasonText(e){if(!e.error)return"";const r=t.t(`base.error_${e.error}`);return e.detail?`${r}(${e.detail})`:r}function x(e,r){const o="bad_index"===e||"bad_url"===e?p(r,t.t("errors.next_step",{command:`${h} base --help`}),e):"key_rejected"===e?d(r,t.t("errors.next_step",{command:`${h} setup --key ${t.t("errors.key_placeholder")}`}),e):f(r,t.t("base.next_addresses"),e);c(o)}function v(r,o,s){if(i())return;const a=o.length>1?fastestIndex(o):-1;r.forEach((r,n)=>{const l=r.url===s?e.cyan(` ← ${t.t("base.current_mark")}`):"";console.log(`${n+1}. ${r.url} ${e.gray(r.label)}\n ${probeSummary(o[n],n===a)}${l}`)})}export function toolsConfiguredByVibecli(){const e=[];for(const o of a()){const t=r.getApiKeyForTool(o.name);if(t)try{o.detectCurrentConfig().apiKey===t&&e.push({tool:o.name,apiKey:t})}catch(e){u.logError(`base.detectCurrentConfig(${o.name})`,e)}}return e}export async function moveToolsToCurrentAddress(e){const o=[],t=[];for(const{tool:a,apiKey:n}of e)try{await s.applyPrivateConfig(a,n,r.getModelsForTool(a)),o.push(a)}catch(e){t.push({tool:a,reason:e instanceof Error?e.message:String(e)})}return{applied:o,failed:t}}export async function moveOtherToolsAfterFallback(r){if(0===r.length)return[];const{applied:o,failed:a}=await moveToolsToCurrentAddress(r);if(_("gateway-fallback-tools",a.length>0?"fail":"ok",{detail:{applied:o,failed:a.map(e=>e.tool)}}),!i()){o.length>0&&console.log(t.t("base.other_tools_moved"));for(const e of o)s.printApplied(e);for(const{tool:r,reason:o}of a)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:r,reason:o})}`))}return o}export async function switchGatewayAddress(a){const u=r.getBaseUrl(),p=toolsConfiguredByVibecli();a===o?r.resetBaseUrl():r.setBaseUrl(a,!0);const{applied:d,failed:f}=await moveToolsToCurrentAddress(p);if(f.length>0&&c(m(f.map(({tool:e,reason:r})=>`${e}: ${r}`).join("; "),t.t("errors.next_step",{command:`${h} setup --key ${t.t("errors.key_placeholder")}`}),"config_write_failed")),i()&&0===f.length)l({ok:0===f.length,previous:u,base_url:a,applied:d,failed:f});else{console.log(e.green(t.t(a===u?"base.kept":"base.switched",{url:a}))),d.length>0&&console.log(t.t("base.tools_moved"));for(const e of d)s.printApplied(e);for(const{tool:r,reason:o}of f)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:r,reason:o})}`));0===d.length&&0===f.length&&console.log(e.yellow(t.t("base.no_tools",{url:a}))),await n(d)}}
1
+ import e from"chalk";import{configManager as o,DEFAULT_BASE_URL as r}from"../lib/config.js";import{i18n as t}from"../lib/i18n.js";import{toolManager as a}from"../lib/tool-manager.js";import{listAdapters as s}from"../lib/tools/registry.js";import{postApplyPrompts as l}from"../lib/post-apply.js";import{emitJson as n,isJsonMode as i}from"../lib/runtime-options.js";import{logger as u}from"../utils/logger.js";import{reportCliError as c,usageError as f,authenticationError as p,networkError as d,operationError as m}from"../lib/errors.js";import{gatewayAddresses as b,normalizeBaseUrl as y,probeGatewayAddress as g}from"../lib/gateway-addresses.js";import{CLI_NAME as _}from"../lib/brand.js";import{track as h}from"../lib/telemetry.js";import{forgetField as k,ownsValue as w,takeField as x}from"../lib/written-values.js";export async function baseCommand(a){const s=o.getBaseUrl(),l=addressesWithCurrent(),u=a?.trim().toLowerCase();if(!u)return void await async function(o,r){const a=savedApiKey(),s=await probeAll(o,{apiKey:a,samples:3});i()?n({ok:!0,current:r,addresses:o.map((e,o)=>({...e,...s[o],current:e.url===r}))}):(console.log(e.bold(t.t("base.current",{url:r}))),console.log(e.gray(t.t(a?"base.probe_with_key":"base.probe_without_key"))+"\n"),K(o,s,r),console.log("\n"+e.gray(t.t("base.usage_hint"))))}(l,s);if("auto"===u){const e=await probeAll(l,{apiKey:savedApiKey()}),o=e.find(e=>e.ok);if(!o){const o=e.every(e=>"key_rejected"===e.error);return j(o?"key_rejected":"no_reachable",t.t(o?"base.key_rejected_everywhere":"base.none_reachable")),void K(l,e,s)}return void await switchGatewayAddress(o.url,{auto:!0})}let c;if("default"===u||"reset"===u)c=r;else if(/^\d+$/.test(u)){if(c=l[Number(u)-1]?.url??null,!c)return void j("bad_index",t.t("base.bad_index",{index:u,count:String(l.length)}))}else if(c=y(a),!c)return void j("bad_url",t.t("base.bad_url",{value:a}));const f=await g(c,{apiKey:savedApiKey()});f.ok?await switchGatewayAddress(c):j("unreachable",t.t("base.unreachable",{url:c,reason:reasonText(f)}))}export async function ensureReachableGatewayAddress(a=savedApiKey(),s={}){if(o.hasRuntimeBaseUrl())return null;const l=o.getBaseUrl(),n=b(),u=await g(l,{apiKey:a});if("key_rejected"===u.error)return null;let c;if(u.ok){const e=n.findIndex(e=>e.url===l);if(e<=0||!w($(),l))return null;c=n.slice(0,e)}else c=n.filter(e=>e.url!==l);const f=(await probeAll(c,{apiKey:a})).find(e=>e.ok);if(!f)return null;if(u.ok?h("gateway-fallback","ok",{detail:{from:l,to:f.url,back:!0}}):h("gateway-fallback","fallback",{error:reasonText(u),detail:{from:l,to:f.url}}),!1===s.save?(o.setBaseUrl(f.url,!1),v=f.url):A(f.url,!0),!i())if(u.ok)console.log(e.yellow(t.t("base.setup_back",{from:l,url:f.url})));else{const o=f.url===r?"base.setup_fallback_main":"base.setup_fallback";console.log(e.yellow(t.t(o,{from:l,reason:reasonText(u),url:f.url})))}return f.url}let v=null;function $(){return`base_url_auto:${o.getActiveProfileName()}`}function A(e,t){e===r?o.resetBaseUrl():o.setBaseUrl(e,!0),t?x($(),e):k($())}export function saveGatewayFallback(){if(!v)return;const e=v;v=null,A(e,!0)}export function addressesWithCurrent(){const e=o.getBaseUrl(),r=b();return r.some(o=>o.url===e)||r.push({url:e,label:t.t("base.custom_label")}),r}export function savedApiKey(){return o.getApiKey()||s().map(e=>o.getApiKeyForTool(e.name)).find(Boolean)}export async function probeAll(e,o={}){return Promise.all(e.map(e=>g(e.url,o)))}export function probeSummary(o,r){if(!o.ok)return e.red(`× ${reasonText(o)}`);const a=[`${o.ms} ms`];return void 0!==o.models&&a.push(t.t("base.models_count",{count:String(o.models)})),r&&a.push(t.t("base.fastest")),e.green(`√ ${a.join(" · ")}`)}export function fastestIndex(e){let o=-1;return e.forEach((r,t)=>{r.ok&&(o<0||r.ms<e[o].ms)&&(o=t)}),o}export function reasonText(e){if(!e.error)return"";const o=t.t(`base.error_${e.error}`);return e.detail?`${o}(${e.detail})`:o}function j(e,o){const r="bad_index"===e||"bad_url"===e?f(o,t.t("errors.next_step",{command:`${_} base --help`}),e):"key_rejected"===e?p(o,t.t("errors.next_step",{command:`${_} setup --key ${t.t("errors.key_placeholder")}`}),e):d(o,t.t("base.next_addresses"),e);c(r)}function K(o,r,a){if(i())return;const s=r.length>1?fastestIndex(r):-1;o.forEach((o,l)=>{const n=o.url===a?e.cyan(` ← ${t.t("base.current_mark")}`):"";console.log(`${l+1}. ${o.url} ${e.gray(o.label)}\n ${probeSummary(r[l],l===s)}${n}`)})}export function toolsWeConfigured(){const e=[];for(const r of s()){const t=o.getApiKeyForTool(r.name);if(t)try{r.detectCurrentConfig().apiKey===t&&e.push({tool:r.name,apiKey:t})}catch(e){u.logError(`base.detectCurrentConfig(${r.name})`,e)}}return e}export async function moveToolsToCurrentAddress(e){const r=[],t=[];for(const{tool:s,apiKey:l}of e)try{await a.applyPrivateConfig(s,l,o.getModelsForTool(s)),r.push(s)}catch(e){t.push({tool:s,reason:e instanceof Error?e.message:String(e)})}return{applied:r,failed:t}}export async function moveOtherToolsAfterFallback(o){if(0===o.length)return[];const{applied:r,failed:s}=await moveToolsToCurrentAddress(o);if(h("gateway-fallback-tools",s.length>0?"fail":"ok",{detail:{applied:r,failed:s.map(e=>e.tool)}}),!i()){r.length>0&&console.log(t.t("base.other_tools_moved"));for(const e of r)a.printApplied(e);for(const{tool:o,reason:r}of s)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`))}return r}export async function switchGatewayAddress(r,s={}){const u=o.getBaseUrl(),f=toolsWeConfigured();A(r,Boolean(s.auto));const{applied:p,failed:d}=await moveToolsToCurrentAddress(f);if(d.length>0&&c(m(d.map(({tool:e,reason:o})=>`${e}: ${o}`).join("; "),t.t("errors.next_step",{command:`${_} setup --key ${t.t("errors.key_placeholder")}`}),"config_write_failed")),i()&&0===d.length)n({ok:0===d.length,previous:u,base_url:r,applied:p,failed:d});else{console.log(e.green(t.t(r===u?"base.kept":"base.switched",{url:r}))),p.length>0&&console.log(t.t("base.tools_moved"));for(const e of p)a.printApplied(e);for(const{tool:o,reason:r}of d)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`));0===p.length&&0===d.length&&console.log(e.yellow(t.t("base.no_tools",{url:r}))),await l(p)}}
@@ -1 +1 @@
1
- import o from"chalk";import{getAdapter as e}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsConfiguredByVibecli as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as d,SUPPORTED_TOOLS as p}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 _,authenticationError as h,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 K,isJsonMode as T,isNonInteractive as $,shouldAutoConfirm as M}from"../lib/runtime-options.js";import{appsForTools as G,appUpgradeCommand as I,getApp as O}from"../lib/app-update.js";import{join as S}from"path";import{confirmAction as N}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 q}from"../utils/logger.js";import{forgetInstalls as L}from"../lib/tools/tool-installs.js";import{CLI_NAME as R,brandEnv as P}from"../lib/brand.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 Y(o){const e=await u(o);if(!e.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=e.models.map(o=>o.toLowerCase());return{hasClaude:t.some(o=>o.includes("claude")),hasGpt:t.some(o=>o.startsWith("gpt")||o.includes("gpt-")||/^o\d/.test(o)),hasGrok:t.some(o=>o.includes("grok")),hasGemini:t.some(o=>o.startsWith("gemini")),probed:!0}}function z(o,e){switch(e){case"claude":return o.hasClaude;case"gpt":return o.hasGpt;case"grok":return o.hasGrok;case"gemini":return o.hasGemini;default:return!0}}export function parseOnOff(o){const e=(o??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(e)||!["off","false","hide","0","no","n"].includes(e)&&void 0}function H(e){console.log(o.green(e))}function W(e){console.log(o.yellow(e))}function U(e){console.error(o.red(e))}let V=null;function J(o){const e={operation:1,authentication:2,network:3};(!V||e[o]>e[V])&&(V=o)}async function Q(e,t){T()||console.log(o.gray(n.t("setup.validating",{label:e})));const l=await c(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===e?`${R} setup --key ${i}`:`${R} setup ${e} ${i}`;let a;if("network_error"===l.error?(J("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${R} base auto`,"network_error")):"invalid_api_key"===l.error?(J("authentication"),a=h(n.t("setup.invalid_key",{label:e,reason:l.message||"invalid"}),s,"invalid_api_key")):(J("operation"),a=_(n.t("setup.validate_failed",{label:e,reason:l.message||l.error||"unknown"}),s,l.error)),T())throw a;return U(a.message),console.log(o.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function X(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=i,g=p[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 d.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(o){if(T())throw _(o instanceof Error?o.message:String(o),`${R} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const e=(o instanceof Error?o.message:String(o)).replace(/\s+/g," ").trim();return U("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:e})),!1}return d.printApplied(t),u&&console.log(o.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(o.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),e(t)?.isInstalled&&!d.isToolInstalled(t)&&console.log(o.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function Z(o){return!e(o)?.isInstalled&&!d.isToolInstalled(o)}async function oo(o){if(C())return!0;const e=p[o]?.displayName??o;return v()?N({message:n.t("setup.ask_detected_tool",{tool:e}),defaultValue:!0}):(W(n.t("setup.detected_tool_hint",{tool:e,name:o})),!1)}export async function installMissingApps(e,t){const l=G(e).filter(o=>{const e=O(o)?.appInstaller;try{return Boolean(e&&!e.blocker()&&!e.installedPath())}catch(e){return q.logError(`setup: app installed? ${o}`,e),!1}});if(0===l.length)return!1;const i=o=>O(o)?.displayName??o;let s=t;if(void 0===s&&!T())if(M())s=!$();else if(v()){const o=l.map(i).join(n.t("setup.list_separator")),e=l.reduce((o,e)=>o+(O(e)?.appInstaller.sizeMb()??0),0);console.log(""),s=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:o,size:String(e)}),default:!0}])).go}if(!s&&!T())for(const e of l)console.log(o.gray(n.t("setup.install_app_hint",{tool:i(e),command:I(e)})));return Boolean(s)}function eo(o){W(n.t("setup.still_missing",{tools:o.map(o=>p[o].displayName).join(n.t("setup.list_separator")),commands:o.map(o=>`${R} config ${o} --yes`).join(n.t("setup.list_separator"))}))}function to(e,t,l=[]){const i=D(e),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 e=(j()?o.cyan:o=>o)(n.t("runtime.dry_run_label"));return void console.log(`${e} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function lo(){return"darwin"===process.platform||"win32"===process.platform||d.isToolInstalled("claude-desktop")}export async function setupCommand(c){V=null;const u=c.key?.trim(),y=DEDICATED_KEYS.map(o=>({...o,apiKey:c[o.option]?.trim()})).filter(o=>Boolean(o.apiKey)),k=void 0!==c.oneMillion,_=void 0!==c.claudeOfficial;let h;if(_&&(h=parseOnOff(c.claudeOfficial),void 0===h))return U(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const b=void 0!==c.desktopRegistry;let v;if(b&&(v=parseOnOff(c.desktopRegistry),void 0===v))return U(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const x=_||b,C=Boolean(u||y.length>0),j={oneMillion:c.oneMillion,officialLogin:h,desktopRegistry:v,force:c.force};if(!C&&(k||x)&&K())return void to([...k?["codex"]:[],...x?["claude-desktop"]:[]],!1);if(!C&&(k||x)){if(k){const o=r.getApiKeyForTool("codex");if(o)try{const e=!0===c.oneMillion;r.setToolSetting("codex",f,e);const t=await g(o);m(e,t??void 0),H(n.t(e?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(o){U(n.t("setup.apply_failed",{tool:p.codex.displayName,reason:o instanceof Error?o.message:String(o)})),process.exitCode=1}else U(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(x){const o=r.getApiKeyForTool("claude-desktop");o?await X("claude-desktop",o,{...j,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(U(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!C)return U(n.t("setup.usage")),void(process.exitCode=1);const G=K(),I=G?null:await l(u||y[0].apiKey,{save:!1}),O=[],N=[];let B,D=0,J=0;const io=new Set,so=y.map(o=>({tool:o.tool,label:`--${o.option}`,apiKey:o.apiKey,need:o.need}));for(const o of so){if(!await Q(o.label,o.apiKey)){J+=1;continue}const e=await Y(o.apiKey);!e.probed||z(e,o.need)?(e.probed||W(n.t("setup.probe_failed",{label:o.label})),O.push({tool:o.tool,apiKey:o.apiKey,dedicated:!0}),io.add(o.tool)):(U(n.t(`setup.key_no_${o.need}`,{label:o.label,tool:p[o.tool].displayName})),J+=1)}const ao=!!u&&await Q("--key",u);u&&!ao&&(B=w[V??"operation"]);const no=u&&ao?await Y(u):void 0;if(u&&no&&!no.probed&&W(n.t("setup.probe_failed",{label:"--key"})),!(u&&no&&no.probed)||no.hasClaude||no.hasGpt||no.hasGrok||no.hasGemini||(U(n.t("setup.key_no_family")),B=1),u&&no&&void 0===B){const o=no.hasClaude||no.hasGpt||no.hasGrok||no.hasGemini,e=[{tool:"claude-code",capable:no.hasClaude,skipMsg:n.t(lo()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:no.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:no.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:no.hasClaude&&lo(),skipMsg:"",quiet:!0},{tool:"agy",capable:no.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:o&&d.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:o&&d.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:o&&d.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const o of e)io.has(o.tool)||(o.capable?(!o.ask||G||await oo(o.tool))&&(O.push({tool:o.tool,apiKey:u,dedicated:!1}),io.add(o.tool)):o.quiet||W(o.skipMsg))}const ro=Boolean(u&&ao&&void 0===B);if(G)return to(O.filter(o=>!Z(o.tool)).map(o=>o.tool),O.length>0,O.filter(o=>Z(o.tool)).map(o=>o.tool)),void((J>0||void 0!==B)&&(process.exitCode=B??w[V??"operation"]));const po=O.filter(o=>!Z(o.tool)),co=ro||O.some(o=>o.dedicated),uo=I?a().filter(o=>!O.some(e=>e.tool===o.tool)):[],fo=!c.fromInstaller&&A();if((O.length>0||co)&&!c.fromInstaller&&!await E([...po.map(o=>o.tool),...uo.map(o=>o.tool)],{keyFile:co?S(r.getConfigDir(),"config.yaml"):void 0,installFirst:O.filter(o=>Z(o.tool)).map(o=>o.tool)}))return void(process.exitCode=w.cancelled);(O.length>0||co)&&s(),ro&&u&&r.setApiKey(u);for(const o of O)Z(o.tool)?(o.dedicated&&r.setToolApiKey(o.tool,o.apiKey),N.push({tool:o.tool,apiKey:o.apiKey})):await X(o.tool,o.apiKey,{...j,takeOver:o.dedicated||fo})?(o.dedicated&&r.setToolApiKey(o.tool,o.apiKey),D+=1):(J+=1,io.delete(o.tool));const mo=O.length>0||co?await i(uo):[];if(void 0!==B)return N.length>0&&eo(N.map(o=>o.tool)),void(process.exitCode=B);let go=[];if(N.length>0){const e=await async function(e,t,l){const i=e.map(o=>o.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(o=>p[o].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||T()||(M()?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 e of i)console.log(o.yellow("! "+n.t("setup.install_hint",{tool:p[e].displayName,install:p[e].installCommand})));return T()||console.log(o.gray(n.t("setup.install_all_hint",{cli:R}))),{still:i,applied:[],failed:[]}}const r=[];for(const e of i){console.log(o.bold(`\n${p[e].displayName}`));try{await d.installTool(e)}catch(o){q.logError(`setup: install ${e}`,o)}L(),d.isToolInstalled(e)||r.push(e)}const c=i.filter(o=>!r.includes(o));c.length>0&&console.log("");const u=[],f=[];for(const{tool:o,apiKey:t}of e.filter(o=>c.includes(o.tool)))await X(o,t,l)?u.push(o):f.push(o);return{still:r,applied:u,failed:f}}(N,c.install,j);go=e.still,D+=e.applied.length,J+=e.failed.length;for(const o of[...go,...e.failed])io.delete(o)}if(D>0){const t=[...io].filter(o=>!e(o)?.isInstalled&&!go.includes(o)),l=t.map(o=>p[o]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(D)});H("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),go.length>0&&eo(go);for(const o of t){const e=d.ensureNativeOnPath(o);e&&H(n.t("setup.path_added",{tool:p[o].displayName,dir:e}))}const s=t.filter(o=>!d.isOnPath(o));if(s.length>0&&!T()&&"1"!==P("PATH_HINT_BY_CALLER")){const e=s.map(o=>p[o].command).join(" / ");console.log(o.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:e})))}}0===D&&go.length>0&&eo(go),J>0&&(U(n.t("setup.failed_summary",{count:String(J)})),T()||console.error(`${R} setup --key ${n.t("errors.key_placeholder")}`)),await t([...io,...mo],{apps:{install:await installMissingApps([...io],c.install)}}),(J>0||0===D&&0===go.length)&&(process.exitCode=w[V??"operation"])}
1
+ import o from"chalk";import{getAdapter as e}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 d,SUPPORTED_TOOLS as p}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 _,authenticationError as h,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 K,isJsonMode as T,isNonInteractive as $,shouldAutoConfirm as M}from"../lib/runtime-options.js";import{appsForTools as G,appUpgradeCommand as I,getApp as O}from"../lib/app-update.js";import{join as S}from"path";import{confirmAction as N}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 q}from"../utils/logger.js";import{forgetInstalls as L}from"../lib/tools/tool-installs.js";import{CLI_NAME as R,brandEnv as P}from"../lib/brand.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 Y(o){const e=await u(o);if(!e.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=e.models.map(o=>o.toLowerCase());return{hasClaude:t.some(o=>o.includes("claude")),hasGpt:t.some(o=>o.startsWith("gpt")||o.includes("gpt-")||/^o\d/.test(o)),hasGrok:t.some(o=>o.includes("grok")),hasGemini:t.some(o=>o.startsWith("gemini")),probed:!0}}function z(o,e){switch(e){case"claude":return o.hasClaude;case"gpt":return o.hasGpt;case"grok":return o.hasGrok;case"gemini":return o.hasGemini;default:return!0}}export function parseOnOff(o){const e=(o??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(e)||!["off","false","hide","0","no","n"].includes(e)&&void 0}function H(e){console.log(o.green(e))}function W(e){console.log(o.yellow(e))}function U(e){console.error(o.red(e))}let V=null;function J(o){const e={operation:1,authentication:2,network:3};(!V||e[o]>e[V])&&(V=o)}async function Q(e,t){T()||console.log(o.gray(n.t("setup.validating",{label:e})));const l=await c(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===e?`${R} setup --key ${i}`:`${R} setup ${e} ${i}`;let a;if("network_error"===l.error?(J("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${R} base auto`,"network_error")):"invalid_api_key"===l.error?(J("authentication"),a=h(n.t("setup.invalid_key",{label:e,reason:l.message||"invalid"}),s,"invalid_api_key")):(J("operation"),a=_(n.t("setup.validate_failed",{label:e,reason:l.message||l.error||"unknown"}),s,l.error)),T())throw a;return U(a.message),console.log(o.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function X(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=i,g=p[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 d.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(o){if(T())throw _(o instanceof Error?o.message:String(o),`${R} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const e=(o instanceof Error?o.message:String(o)).replace(/\s+/g," ").trim();return U("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:e})),!1}return d.printApplied(t),u&&console.log(o.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(o.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),e(t)?.isInstalled&&!d.isToolInstalled(t)&&console.log(o.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function Z(o){return!e(o)?.isInstalled&&!d.isToolInstalled(o)}async function oo(o){if(C())return!0;const e=p[o]?.displayName??o;return v()?N({message:n.t("setup.ask_detected_tool",{tool:e}),defaultValue:!0}):(W(n.t("setup.detected_tool_hint",{tool:e,name:o})),!1)}export async function installMissingApps(e,t){const l=G(e).filter(o=>{const e=O(o)?.appInstaller;try{return Boolean(e&&!e.blocker()&&!e.installedPath())}catch(e){return q.logError(`setup: app installed? ${o}`,e),!1}});if(0===l.length)return!1;const i=o=>O(o)?.displayName??o;let s=t;if(void 0===s&&!T())if(M())s=!$();else if(v()){const o=l.map(i).join(n.t("setup.list_separator")),e=l.reduce((o,e)=>o+(O(e)?.appInstaller.sizeMb()??0),0);console.log(""),s=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:o,size:String(e)}),default:!0}])).go}if(!s&&!T())for(const e of l)console.log(o.gray(n.t("setup.install_app_hint",{tool:i(e),command:I(e)})));return Boolean(s)}function eo(o){W(n.t("setup.still_missing",{tools:o.map(o=>p[o].displayName).join(n.t("setup.list_separator")),commands:o.map(o=>`${R} config ${o} --yes`).join(n.t("setup.list_separator"))}))}function to(e,t,l=[]){const i=D(e),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 e=(j()?o.cyan:o=>o)(n.t("runtime.dry_run_label"));return void console.log(`${e} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function lo(){return"darwin"===process.platform||"win32"===process.platform||d.isToolInstalled("claude-desktop")}export async function setupCommand(c){V=null;const u=c.key?.trim(),y=DEDICATED_KEYS.map(o=>({...o,apiKey:c[o.option]?.trim()})).filter(o=>Boolean(o.apiKey)),k=void 0!==c.oneMillion,_=void 0!==c.claudeOfficial;let h;if(_&&(h=parseOnOff(c.claudeOfficial),void 0===h))return U(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const b=void 0!==c.desktopRegistry;let v;if(b&&(v=parseOnOff(c.desktopRegistry),void 0===v))return U(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const x=_||b,C=Boolean(u||y.length>0),j={oneMillion:c.oneMillion,officialLogin:h,desktopRegistry:v,force:c.force};if(!C&&(k||x)&&K())return void to([...k?["codex"]:[],...x?["claude-desktop"]:[]],!1);if(!C&&(k||x)){if(k){const o=r.getApiKeyForTool("codex");if(o)try{const e=!0===c.oneMillion;r.setToolSetting("codex",f,e);const t=await g(o);m(e,t??void 0),H(n.t(e?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(o){U(n.t("setup.apply_failed",{tool:p.codex.displayName,reason:o instanceof Error?o.message:String(o)})),process.exitCode=1}else U(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(x){const o=r.getApiKeyForTool("claude-desktop");o?await X("claude-desktop",o,{...j,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(U(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!C)return U(n.t("setup.usage")),void(process.exitCode=1);const G=K(),I=G?null:await l(u||y[0].apiKey,{save:!1}),O=[],N=[];let B,D=0,J=0;const io=new Set,so=y.map(o=>({tool:o.tool,label:`--${o.option}`,apiKey:o.apiKey,need:o.need}));for(const o of so){if(!await Q(o.label,o.apiKey)){J+=1;continue}const e=await Y(o.apiKey);!e.probed||z(e,o.need)?(e.probed||W(n.t("setup.probe_failed",{label:o.label})),O.push({tool:o.tool,apiKey:o.apiKey,dedicated:!0}),io.add(o.tool)):(U(n.t(`setup.key_no_${o.need}`,{label:o.label,tool:p[o.tool].displayName})),J+=1)}const ao=!!u&&await Q("--key",u);u&&!ao&&(B=w[V??"operation"]);const no=u&&ao?await Y(u):void 0;if(u&&no&&!no.probed&&W(n.t("setup.probe_failed",{label:"--key"})),!(u&&no&&no.probed)||no.hasClaude||no.hasGpt||no.hasGrok||no.hasGemini||(U(n.t("setup.key_no_family")),B=1),u&&no&&void 0===B){const o=no.hasClaude||no.hasGpt||no.hasGrok||no.hasGemini,e=[{tool:"claude-code",capable:no.hasClaude,skipMsg:n.t(lo()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:no.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:no.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:no.hasClaude&&lo(),skipMsg:"",quiet:!0},{tool:"agy",capable:no.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:o&&d.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:o&&d.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:o&&d.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const o of e)io.has(o.tool)||(o.capable?(!o.ask||G||await oo(o.tool))&&(O.push({tool:o.tool,apiKey:u,dedicated:!1}),io.add(o.tool)):o.quiet||W(o.skipMsg))}const ro=Boolean(u&&ao&&void 0===B);if(G)return to(O.filter(o=>!Z(o.tool)).map(o=>o.tool),O.length>0,O.filter(o=>Z(o.tool)).map(o=>o.tool)),void((J>0||void 0!==B)&&(process.exitCode=B??w[V??"operation"]));const po=O.filter(o=>!Z(o.tool)),co=ro||O.some(o=>o.dedicated),uo=I?a().filter(o=>!O.some(e=>e.tool===o.tool)):[],fo=!c.fromInstaller&&A();if((O.length>0||co)&&!c.fromInstaller&&!await E([...po.map(o=>o.tool),...uo.map(o=>o.tool)],{keyFile:co?S(r.getConfigDir(),"config.yaml"):void 0,installFirst:O.filter(o=>Z(o.tool)).map(o=>o.tool)}))return void(process.exitCode=w.cancelled);(O.length>0||co)&&s(),ro&&u&&r.setApiKey(u);for(const o of O)Z(o.tool)?(o.dedicated&&r.setToolApiKey(o.tool,o.apiKey),N.push({tool:o.tool,apiKey:o.apiKey})):await X(o.tool,o.apiKey,{...j,takeOver:o.dedicated||fo})?(o.dedicated&&r.setToolApiKey(o.tool,o.apiKey),D+=1):(J+=1,io.delete(o.tool));const mo=O.length>0||co?await i(uo):[];if(void 0!==B)return N.length>0&&eo(N.map(o=>o.tool)),void(process.exitCode=B);let go=[];if(N.length>0){const e=await async function(e,t,l){const i=e.map(o=>o.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(o=>p[o].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||T()||(M()?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 e of i)console.log(o.yellow("! "+n.t("setup.install_hint",{tool:p[e].displayName,install:p[e].installCommand})));return T()||console.log(o.gray(n.t("setup.install_all_hint",{cli:R}))),{still:i,applied:[],failed:[]}}const r=[];for(const e of i){console.log(o.bold(`\n${p[e].displayName}`));try{await d.installTool(e)}catch(o){q.logError(`setup: install ${e}`,o)}L(),d.isToolInstalled(e)||r.push(e)}const c=i.filter(o=>!r.includes(o));c.length>0&&console.log("");const u=[],f=[];for(const{tool:o,apiKey:t}of e.filter(o=>c.includes(o.tool)))await X(o,t,l)?u.push(o):f.push(o);return{still:r,applied:u,failed:f}}(N,c.install,j);go=e.still,D+=e.applied.length,J+=e.failed.length;for(const o of[...go,...e.failed])io.delete(o)}if(D>0){const t=[...io].filter(o=>!e(o)?.isInstalled&&!go.includes(o)),l=t.map(o=>p[o]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(D)});H("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),go.length>0&&eo(go);for(const o of t){const e=d.ensureNativeOnPath(o);e&&H(n.t("setup.path_added",{tool:p[o].displayName,dir:e}))}const s=t.filter(o=>!d.isOnPath(o));if(s.length>0&&!T()&&"1"!==P("PATH_HINT_BY_CALLER")){const e=s.map(o=>p[o].command).join(" / ");console.log(o.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:e})))}}0===D&&go.length>0&&eo(go),J>0&&(U(n.t("setup.failed_summary",{count:String(J)})),T()||console.error(`${R} setup --key ${n.t("errors.key_placeholder")}`)),await t([...io,...mo],{apps:{install:await installMissingApps([...io],c.install)}}),(J>0||0===D&&0===go.length)&&(process.exitCode=w[V??"operation"])}
@@ -27,10 +27,11 @@ export declare function parsePublishedAddresses(apiInfo: unknown): GatewayAddres
27
27
  */
28
28
  export declare function rememberPublishedAddresses(statusData: unknown, source: string): void;
29
29
  /**
30
- * Addresses to offer, in priority order: the built-in list (`models.json` →
31
- * `gatewayAddresses`, which is also what `vibecli base auto` tries first to
32
- * last), then addresses the gateway publishes that are not built in, in the
33
- * gateway's order. A built-in address takes the gateway's label when it has one.
30
+ * Addresses to offer, in priority order (what `vibecli base auto` tries first to last):
31
+ * the gateway's published list in the console's order, then built-in addresses it does
32
+ * not list, in built-in order. The console's order wins so operators can reorder the
33
+ * backups without a release (user 2026-11-16). Only built-in addresses may publish a list
34
+ * (`rememberPublishedAddresses`), so another gateway cannot put itself in front.
34
35
  */
35
36
  export declare function gatewayAddresses(): GatewayAddress[];
36
37
  /** `url` is one of this gateway's addresses (built-in, published, or the configured one). */
@@ -1 +1 @@
1
- import{existsSync as r,readFileSync as e}from"fs";import{join as t}from"path";import{configManager as o}from"./config.js";import{noteGatewayUrl as s,wroteGatewayUrl as n}from"./written-values.js";import{getBuiltinGatewayAddresses as a}from"./model-registry.js";import{atomicWriteFile as i}from"./tools/backup.js";import{logger as l}from"../utils/logger.js";const u=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]);function c(){return t(o.getConfigDir(),"gateway-addresses.json")}export function normalizeBaseUrl(r){let e,t=r.trim();if(!t)return null;/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||(t=`https://${t}`);try{e=new URL(t)}catch{return null}if("https:"!==e.protocol&&"http:"!==e.protocol)return null;const o=e.pathname.replace(/\/+$/,"").replace(/\/v1$/i,"");return`${e.protocol}//${e.host}${o}`}export function parsePublishedAddresses(r){if(!Array.isArray(r))return[];const e=new Set,t=[];for(const o of r){if(!o||"object"!=typeof o)continue;const{url:r,route:s,description:n}=o,a="string"==typeof r?normalizeBaseUrl(r):null;if(!a?.startsWith("https://")||e.has(a))continue;e.add(a);const i="string"==typeof s?s.trim():"",l="string"==typeof n?n.trim():"";t.push({url:a,label:i&&l?`${i}(${l})`:i||l})}return t}export function rememberPublishedAddresses(r,e){if(!r||"object"!=typeof r)return;if(!a().some(r=>normalizeBaseUrl(r.url)===e))return;const t=r;if(!1===t.api_info_enabled)return;const o=parsePublishedAddresses(t.api_info);if(0!==o.length)try{i(c(),JSON.stringify({addresses:o},null,2)+"\n")}catch(r){l.logError("rememberPublishedAddresses",r)}}export function gatewayAddresses(){const t=function(){const t=c();if(!r(t))return[];try{const r=JSON.parse(e(t,"utf-8"));return(Array.isArray(r.addresses)?r.addresses:[]).flatMap(r=>{const e="string"==typeof r?.url?normalizeBaseUrl(r.url):null;return e?[{url:e,label:"string"==typeof r.label?r.label:""}]:[]})}catch{return[]}}(),o=[];for(const r of a()){const e=normalizeBaseUrl(r.url);if(!e||o.some(r=>r.url===e))continue;const s=t.find(r=>r.url===e)?.label||r.label;o.push({url:e,label:s})}for(const r of t)o.some(e=>e.url===r.url)||o.push(r);return o}export function isOurGatewayUrl(r){if("string"!=typeof r)return!1;const e=normalizeBaseUrl(r);return!!e&&(gatewayAddresses().some(r=>r.url===e)||e===normalizeBaseUrl(o.getBaseUrl())||n(e))}export function noteWrittenGatewayUrl(r){const e=normalizeBaseUrl(r);e&&s(e)}function f(r){const e=r?.cause,t="string"==typeof e?.code?e.code:"",o="string"==typeof e?.message?e.message:r instanceof Error?r.message:String(r);return r instanceof Error&&"AbortError"===r.name?{error:"timeout",detail:o}:u.has(t)||/certificate/i.test(o)?{error:"certificate",detail:t||o}:{error:"network",detail:t||o}}export async function probeGatewayAddress(r,e={}){e.apiKey&&!function(r){return r===o.getBaseUrl()||a().some(e=>normalizeBaseUrl(e.url)===r)}(r)&&(e={...e,apiKey:void 0});const t=Math.max(1,e.samples??1),s=[];let n;for(let o=0;o<t;o+=1){const t=await m(r,e);if(!t.ok)return t;s.push(t.ms),n=t.models}return s.sort((r,e)=>r-e),{url:r,ok:!0,ms:s[Math.floor(s.length/2)],...void 0===n?{}:{models:n}}}async function m(r,e){const{apiKey:t,timeoutMs:o=8e3,fetchFn:s=fetch}=e,n=new AbortController,a=setTimeout(()=>n.abort(),o),i=Date.now();try{const e=await s(t?`${r}/v1/models`:`${r}/api/status`,{method:"GET",headers:t?{Authorization:`Bearer ${t}`}:void 0,signal:n.signal});let o;try{o=(await e.json())?.data}catch{o=void 0}const a=Date.now()-i;return!t||401!==e.status&&403!==e.status?t?e.ok&&Array.isArray(o)?{url:r,ok:!0,ms:a,models:o.length}:{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:e.ok&&o&&"object"==typeof o?(rememberPublishedAddresses(o,r),{url:r,ok:!0,ms:a}):{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:{url:r,ok:!1,ms:a,error:"key_rejected",detail:`HTTP ${e.status}`}}catch(e){return{url:r,ok:!1,ms:Date.now()-i,...f(e)}}finally{clearTimeout(a)}}
1
+ import{existsSync as r,readFileSync as e}from"fs";import{join as t}from"path";import{configManager as o}from"./config.js";import{noteGatewayUrl as s,wroteGatewayUrl as n}from"./written-values.js";import{getBuiltinGatewayAddresses as a}from"./model-registry.js";import{atomicWriteFile as i}from"./tools/backup.js";import{logger as l}from"../utils/logger.js";const u=new Set(["SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_HAS_EXPIRED","CERT_NOT_YET_VALID","ERR_TLS_CERT_ALTNAME_INVALID"]);function c(){return t(o.getConfigDir(),"gateway-addresses.json")}export function normalizeBaseUrl(r){let e,t=r.trim();if(!t)return null;/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||(t=`https://${t}`);try{e=new URL(t)}catch{return null}if("https:"!==e.protocol&&"http:"!==e.protocol)return null;const o=e.pathname.replace(/\/+$/,"").replace(/\/v1$/i,"");return`${e.protocol}//${e.host}${o}`}export function parsePublishedAddresses(r){if(!Array.isArray(r))return[];const e=new Set,t=[];for(const o of r){if(!o||"object"!=typeof o)continue;const{url:r,route:s,description:n}=o,a="string"==typeof r?normalizeBaseUrl(r):null;if(!a?.startsWith("https://")||e.has(a))continue;e.add(a);const i="string"==typeof s?s.trim():"",l="string"==typeof n?n.trim():"";t.push({url:a,label:i&&l?`${i}(${l})`:i||l})}return t}export function rememberPublishedAddresses(r,e){if(!r||"object"!=typeof r)return;if(!a().some(r=>normalizeBaseUrl(r.url)===e))return;const t=r;if(!1===t.api_info_enabled)return;const o=parsePublishedAddresses(t.api_info);if(0!==o.length)try{i(c(),JSON.stringify({addresses:o},null,2)+"\n")}catch(r){l.logError("rememberPublishedAddresses",r)}}export function gatewayAddresses(){const t=[];for(const o of function(){const t=c();if(!r(t))return[];try{const r=JSON.parse(e(t,"utf-8"));return(Array.isArray(r.addresses)?r.addresses:[]).flatMap(r=>{const e="string"==typeof r?.url?normalizeBaseUrl(r.url):null;return e?[{url:e,label:"string"==typeof r.label?r.label:""}]:[]})}catch{return[]}}())t.some(r=>r.url===o.url)||t.push(o);for(const r of a()){const e=normalizeBaseUrl(r.url);e&&!t.some(r=>r.url===e)&&t.push({url:e,label:r.label})}return t}export function isOurGatewayUrl(r){if("string"!=typeof r)return!1;const e=normalizeBaseUrl(r);return!!e&&(gatewayAddresses().some(r=>r.url===e)||e===normalizeBaseUrl(o.getBaseUrl())||n(e))}export function noteWrittenGatewayUrl(r){const e=normalizeBaseUrl(r);e&&s(e)}function f(r){const e=r?.cause,t="string"==typeof e?.code?e.code:"",o="string"==typeof e?.message?e.message:r instanceof Error?r.message:String(r);return r instanceof Error&&"AbortError"===r.name?{error:"timeout",detail:o}:u.has(t)||/certificate/i.test(o)?{error:"certificate",detail:t||o}:{error:"network",detail:t||o}}export async function probeGatewayAddress(r,e={}){e.apiKey&&!function(r){return r===o.getBaseUrl()||a().some(e=>normalizeBaseUrl(e.url)===r)}(r)&&(e={...e,apiKey:void 0});const t=Math.max(1,e.samples??1),s=[];let n;for(let o=0;o<t;o+=1){const t=await m(r,e);if(!t.ok)return t;s.push(t.ms),n=t.models}return s.sort((r,e)=>r-e),{url:r,ok:!0,ms:s[Math.floor(s.length/2)],...void 0===n?{}:{models:n}}}async function m(r,e){const{apiKey:t,timeoutMs:o=8e3,fetchFn:s=fetch}=e,n=new AbortController,a=setTimeout(()=>n.abort(),o),i=Date.now();try{const e=await s(t?`${r}/v1/models`:`${r}/api/status`,{method:"GET",headers:t?{Authorization:`Bearer ${t}`}:void 0,signal:n.signal});let o;try{o=(await e.json())?.data}catch{o=void 0}const a=Date.now()-i;return!t||401!==e.status&&403!==e.status?t?e.ok&&Array.isArray(o)?{url:r,ok:!0,ms:a,models:o.length}:{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:e.ok&&o&&"object"==typeof o?(rememberPublishedAddresses(o,r),{url:r,ok:!0,ms:a}):{url:r,ok:!1,ms:a,error:"not_gateway",detail:`HTTP ${e.status}`}:{url:r,ok:!1,ms:a,error:"key_rejected",detail:`HTTP ${e.status}`}}catch(e){return{url:r,ok:!1,ms:Date.now()-i,...f(e)}}finally{clearTimeout(a)}}
@@ -1 +1 @@
1
- import e from"inquirer";import t from"chalk";import a from"ora";import{configManager as o,DEFAULT_MODELS as i}from"./config.js";import{getPresets as n,resolvePreset as r,getToolDefaultModel as s}from"./model-registry.js";import{toolManager as l,SUPPORTED_TOOLS as c}from"./tool-manager.js";import{confirmWritePlan as d}from"./write-plan.js";import{postApplyPrompts as p}from"./post-apply.js";import{appStatus as m,appStatusText as u,appTools as _,appsForTools as g,cachedAppStatus as w,upgradeApp as f}from"./app-update.js";import{i18n as y,detectSystemLang as h}from"./i18n.js";import{createBorderLine as z,createContentLine as v}from"../utils/string-width.js";import{validateApiKey as k,fetchModels as x}from"./api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as b}from"./tools/codex.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as S}from"./tools/claude-desktop.js";import{addressesWithCurrent as C,ensureReachableGatewayAddress as M,moveOtherToolsAfterFallback as T,toolsConfiguredByVibecli as A,fastestIndex as K,probeAll as N,probeSummary as B,reasonText as O,savedApiKey as P,switchGatewayAddress as W}from"../commands/base.js";import{readFileSync as j}from"fs";import{dirname as H,join as L}from"path";import{fileURLToPath as $}from"url";import{brand as F}from"./brand.js";const I=H($(import.meta.url)),E=t.hex("#FF8700");export class Wizard{static instance;BOX_WIDTH=63;validatedApiKeys=new Set;constructor(){}static getInstance(){return Wizard.instance||(Wizard.instance=new Wizard),Wizard.instance}createBox(e){console.log(E.bold("\n"+z("╔","╗","═",this.BOX_WIDTH))),console.log(E.bold(v(e,"║","║",this.BOX_WIDTH,"center"))),console.log(E.bold(z("╚","╝","═",this.BOX_WIDTH))),console.log("")}showOperationHints(){const e=[t.gray(y.t("wizard.hint_navigate")),t.gray(y.t("wizard.hint_confirm"))];console.log(t.gray("💡 ")+e.join(t.gray(" | "))+"\n")}async promptWithHints(t){this.showOperationHints();const a=t.map(e=>"list"!==e.type||e.pageSize?e:{...e,pageSize:20});return e.prompt(a)}printBanner(){const e=60,t=y.t("wizard.banner_subtitle"),a=v(t,"║","║",e,"center"),o=v("","║","║",e,"center"),i=v(`${F().productName} v${function(){try{return JSON.parse(j(L(I,"..","..","package.json"),"utf-8")).version}catch{return"0.0.0"}}()}`,"║","║",e,"center"),n=[String.raw`__ ___ _ ____ _ ___ `,String.raw`\ \ / (_) |__ ___ / ___| | |_ _|`,String.raw` \ \ / /| | '_ \ / _ \ | | | | | `,String.raw` \ V / | | |_) | __/ |___| |___ | | `,String.raw` \_/ |_|_.__/ \___|\____|_____|___|`],r=Math.max(...n.map(e=>e.length)),s=" ".repeat(Math.floor((58-r)/2)),l=n.map(t=>v(s+t,"║","║",e,"left")),c=[z("╔","╗","═",e),o,...l,o,i,a,z("╚","╝","═",e)];console.log(E.bold("\n"+c.join("\n")))}resetScreen(){console.clear(),this.printBanner()}printGoodbye(){const e=l.getSupportedTools().filter(e=>{if(e.gui)return!1;try{return Boolean(l.detectCurrentConfig(e.name).apiKey)&&l.isToolInstalled(e.name)}catch{return!1}});let a;if(e.length>0){const t=e.map(e=>e.command).join(" / ");a=y.t("wizard.goodbye_message_tools",{commands:t}),e.some(e=>"claude-code"===e.name)&&(a+=" "+y.t("wizard.goodbye_claude_hint"))}else a=y.t("wizard.goodbye_message");console.log(t.green("\n👋 "+a)),this.printPathReloadHint(e.map(e=>e.name))}printPathReloadHint(e){const a=e.filter(e=>!l.isOnPath(e));if(0===a.length)return;const o=a.map(e=>c[e].command).join(" / ");console.log(t.yellow(" ! "+y.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}async runFirstTimeSetup(){const e="zh_CN"===h();if(e&&(o.setLang("zh_CN"),y.setLocale("zh_CN")),this.resetScreen(),console.log(E.bold("\n"+y.t("wizard.welcome"))),console.log(t.gray(y.t("wizard.privacy_note")+"\n")),e?console.log(t.gray(y.t("wizard.lang_auto_zh")+"\n")):await this.configLanguage(),await M()){const e=A();e.length>0&&await d(e.map(e=>e.tool))&&await p(await T(e))}await this.configApiKey()&&await this.selectAndConfigureTool(!0)}async configLanguage(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_language"));const a=y.getLocale(),{language:i}=await this.promptWithHints([{type:"list",name:"language",message:"✨ "+y.t("wizard.select_language"),choices:[{name:"[EN] English"+("en_US"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"en_US"},{name:"[CN] 中文"+("zh_CN"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"zh_CN"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}],default:"zh_CN"}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;return o.setLang(i),void y.setLocale(i)}}buildPresetChoices(){const a=n(),o=a.filter(e=>e.recommended),i=a.filter(e=>!e.recommended),r=e=>({name:(y.t(e.name)!==e.name?y.t(e.name):e.name)+(e.models?t.gray(` [H:${e.models.haiku} S:${e.models.sonnet} O:${e.models.opus}]`):""),value:{type:"preset",preset:e}}),s=[];return o.length>0&&(s.push(new e.Separator(t.hex("#FF8700")("── "+y.t("wizard.recommended")+" ──"))),s.push(...o.map(r))),i.length>0&&(s.push(new e.Separator(t.gray("── "+y.t("wizard.other_models")+" ──"))),s.push(...i.map(r))),s}async handleCustomModelInput(){const a=o.getModels(),{customMode:n}=await e.prompt([{type:"list",name:"customMode",message:y.t("wizard.custom_model_mode"),choices:[{name:y.t("wizard.custom_model_single"),value:"single"},{name:y.t("wizard.custom_model_per_role"),value:"per_role"}]}]);if("single"===n){const{customModel:t}=await e.prompt([{type:"input",name:"customModel",message:y.t("wizard.input_custom_model"),default:i.sonnet}]);o.setModels({haiku:t,sonnet:t,opus:t,reasoning:t})}else{const t=await e.prompt([{type:"input",name:"haiku",message:y.t("wizard.model_haiku"),default:a.haiku},{type:"input",name:"sonnet",message:y.t("wizard.model_sonnet"),default:a.sonnet},{type:"input",name:"opus",message:y.t("wizard.model_opus"),default:a.opus},{type:"input",name:"reasoning",message:y.t("wizard.model_reasoning"),default:a.reasoning}]);o.setModels(t)}console.log(t.green("\n✓ "+y.t("wizard.models_saved")))}async configModels(a){const i=o.getApiKey();if(await this.validatedKeyForConfiguration(i))for(;;){this.resetScreen(),this.createBox(y.t("wizard.config_models"));const i=[...this.buildPresetChoices()];i.push(new e.Separator),i.push({name:"✏️ "+y.t("wizard.custom_model_input"),value:{type:"custom_input"}}),i.push(new e.Separator),i.push({name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}),i.push({name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}});const{modelChoice:n}=await this.promptWithHints([{type:"list",name:"modelChoice",message:y.t("wizard.select_model_config"),choices:i}]);if("exit"===n.type)this.printGoodbye(),process.exit(0);else{if("back"===n.type)return;if("custom_input"===n.type)return await this.handleCustomModelInput(),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig());if("preset"===n.type){const e=r(n.preset);return o.setModels(e),console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig())}}}else await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async promptLoadAfterModelConfig(){const{shouldLoad:t}=await e.prompt([{type:"list",name:"shouldLoad",message:y.t("wizard.load_config_now"),choices:[{name:y.t("wizard.load_config_yes"),value:!0},{name:y.t("wizard.load_config_later"),value:!1}]}]);t&&await this.selectAndConfigureTool()}async configBaseUrl(){const i=o.getBaseUrl(),n=C(),r=a(y.t("wizard.base_testing")).start(),s=await N(n,{apiKey:P(),samples:3});r.stop();const l=K(s),c=n.map((e,a)=>{const o=e.url===i?t.cyan(` ← ${y.t("base.current_mark")}`):"";return{name:`${e.url} ${t.gray(e.label)} ${B(s[a],a===l)}${o}`,value:e.url}});c.push(new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"});const{url:d}=await this.promptWithHints([{type:"list",name:"url",message:y.t("wizard.base_select"),choices:c,default:i}]);if("__back__"===d)return;const p=s[n.findIndex(e=>e.url===d)];p.ok?await W(d):console.log(t.red(y.t("base.unreachable",{url:d,reason:O(p)}))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async configApiKey(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.input_api_key")),console.log(t.gray("\n💡 "+y.t("wizard.api_key_input_hint"))),console.log(t.gray(" "+y.t("wizard.api_key_get_hint",{url:F().links.tokenPage}))),console.log();const{apiKey:i}=await e.prompt([{type:"password",name:"apiKey",message:y.t("wizard.input_your_api_key"),mask:"*"}]);if(!i||""===i.trim()){const{action:t}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===t)return!1;continue}const n=a(y.t("wizard.validating_api_key")).start(),r=await k(i.trim());if(n.stop(),r.valid)return o.setApiKey(i.trim()),this.validatedApiKeys.add(i.trim()),console.log(t.green("\n✓ "+y.t("wizard.api_key_valid"))),!0;{this.validatedApiKeys.delete(i.trim()),"invalid_api_key"===r.error?console.log(t.red("\n✗ "+y.t("wizard.api_key_invalid"))):console.log(t.red("\n✗ "+y.t("wizard.api_key_network_error")));const{action:a}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===a)return!1}}}async selectAndConfigureTool(a=!1){for(const e of _())await m(e).catch(()=>{});for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_tool"));const o=l.getSupportedTools().map(e=>{const a=g([e.name]).map(e=>w(e)).find(e=>e.outdated);return{name:e.displayName+(a?t.yellow(" "+(a.tool===e.name?"":`${a.name} `)+u(a)):""),value:e.name}}),{tool:i}=await this.promptWithHints([{type:"list",name:"tool",message:"🛠️ "+y.t("wizard.select_tool"),choices:[...o,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}]}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;await this.configureTool(i,a)}}async configureTool(a,o=!1){const i=c[a];if(i){if(!l.isToolInstalled(a)){console.log(t.yellow("\n"+y.t("wizard.tool_not_installed",{tool:i.displayName})));const{install:o}=await e.prompt([{type:"confirm",name:"install",message:y.t("wizard.install_tool_confirm"),default:!0}]);if(!o)return;try{await l.installTool(a)}catch{return void console.log(t.red(y.t("wizard.install_failed")))}}o?await this.configureToolModel(a)&&await this.loadConfig(a):await this.showToolMenu(a)}}async showToolMenu(t){for(;;){this.resetScreen();const a=c[t];if(!a)return;this.createBox(a.displayName+" "+y.t("wizard.menu_title"));const o=[{name:"📥 "+y.t("wizard.action_load_config",{tool:a.displayName}),value:"load"},{name:"📤 "+y.t("wizard.action_unload_config",{tool:a.displayName}),value:"unload"}];l.supportsClearPinnedModels(t)&&o.push({name:"🧹 "+y.t("wizard.action_clear_model",{tool:a.displayName}),value:"clear-model"});for(const e of g([t]).map(e=>w(e)).reverse()){if(e.blocker||!e.latest||!e.outdated&&e.installed)continue;const t=e.installed?y.t("wizard.action_upgrade_app",{tool:e.name,current:e.current??"?",latest:e.latest}):y.t("wizard.action_install_app",{tool:e.name,latest:e.latest});o.unshift({name:"↑ "+t,value:`upgrade-app:${e.tool}`})}o.push({name:"🧨 "+y.t("wizard.action_force_config",{tool:a.displayName}),value:"force"},{name:"↩️ "+y.t("wizard.action_restore_config",{tool:a.displayName}),value:"restore"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"});const{action:i}=await this.promptWithHints([{type:"list",name:"action",message:"⚙️ "+y.t("wizard.select_action"),choices:o}]);if("exit"===i)this.printGoodbye(),process.exit(0);else{if("back"===i)return;"load"===i?await this.configureToolModel(t)&&await this.loadConfig(t):"force"===i?await this.forceConfig(t):"unload"===i?await this.unloadConfig(t):"string"==typeof i&&i.startsWith("upgrade-app:")?(await f(i.slice(12),{install:!0}),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])):"clear-model"===i?await this.clearPinnedModels(t):"restore"===i&&await this.restoreConfig(t)}}}singleModelOverride(e){const t=e.trim();return/claude/i.test(t)?{opus:t}:{haiku:t,sonnet:t,opus:t,reasoning:t}}hasConfiguredApiKey(){return!!o.getApiKey()?.trim()||o.listToolApiKeys().some(e=>Boolean(o.getApiKeyForTool(e)?.trim()))}async validatedKeyForConfiguration(e){const o=e?.trim();if(!o)return console.log(t.red("\n"+y.t("wizard.api_key_required"))),console.log(t.yellow(y.t("wizard.please_config_api_key_first"))),null;if(this.validatedApiKeys.has(o))return o;const i=a(y.t("wizard.validating_api_key")).start(),n=await k(o);if(n.valid)return this.validatedApiKeys.add(o),i.succeed(y.t("wizard.api_key_valid")),o;this.validatedApiKeys.delete(o);const r="invalid_api_key"===n.error?y.t("wizard.api_key_invalid"):y.t("wizard.api_key_network_error");return i.fail(r),console.log(t.red("\n"+y.t("wizard.please_reconfig_api_key"))),null}async configureToolModel(i){const n=c[i];if(!n)return!1;const l=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!l)return await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]),!1;const d="claude-code"===i,p=d||"claude-desktop"===i||"agy"===i,m=s(i),u=p||!m?y.t("wizard.model_builtin_default"):m;this.resetScreen(),this.createBox(n.displayName+" · "+y.t("wizard.config_models"));const _=[{name:"✅ "+y.t("wizard.use_default_model",{model:u}),value:{type:"default"}},{name:"🌐 "+y.t("wizard.fetch_models_from_api"),value:{type:"fetch"}},...this.buildPresetChoices(),new e.Separator,{name:"✏️ "+y.t("wizard.input_custom_model"),value:{type:"custom"}},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}],{choice:g}=await this.promptWithHints([{type:"list",name:"choice",message:y.t("wizard.select_tool_model",{tool:n.displayName}),choices:_}]);if("back"===g.type)return!1;if("default"===g.type)o.setToolModel(i,null);else if("preset"===g.type)o.setToolModel(i,r(g.preset));else if("custom"===g.type){const{model:t}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]),a=(t||"").trim();o.setToolModel(i,a?this.singleModelOverride(a):null)}else if("fetch"===g.type){const n=a(y.t("wizard.fetching_models")).start(),r=await x(l);let s;if(n.stop(),r.ok&&r.models.length>0){const{model:t}=await e.prompt([{type:"list",name:"model",message:y.t("wizard.select_fetched_model"),pageSize:20,choices:[...r.models,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"}]}]);if("__back__"===t)return!1;s=t}else{console.log(t.yellow("\n"+y.t("wizard.fetch_models_failed")));const{model:a}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]);s=(a||"").trim()}o.setToolModel(i,s?this.singleModelOverride(s):null)}if("codex"===i){const t=o.getToolSetting(i,b),{enableOneMillionContext:a}=await e.prompt([{type:"confirm",name:"enableOneMillionContext",message:y.t("wizard.codex_enable_1m_context"),default:!1!==t}]);o.setToolSetting(i,b,Boolean(a))}if("claude-desktop"===i){const t=o.getToolSetting(i,S),{hideOfficialLogin:a}=await e.prompt([{type:"confirm",name:"hideOfficialLogin",message:y.t("wizard.desktop_hide_official_login"),default:!1!==t}]);o.setToolSetting(i,S,Boolean(a))}return console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),d&&console.log(t.gray("💡 "+y.t("wizard.claude_model_hint"))),!0}async forceConfig(t){const a=c[t]?.displayName||t,{confirm:o}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("config.confirm_force",{tool:a}),default:!1}]);o&&await this.loadConfig(t,{force:!0})}async loadConfig(i,n={}){const r=o.getModelsForTool(i),s=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!s)return void await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]);if(!n.force&&!await d([i]))return;const m=a(y.t("wizard.loading_config")).start();try{await l.applyPrivateConfig(i,s,r,{...n,takeOver:!0}),m.stop(),l.printApplied(i),await p([i],{apps:{install:!1}}),n.force&&console.log(t.yellow(y.t("config.force_done",{tool:c[i]?.displayName||i,name:i})));const a=c[i];a&&!a.gui&&(l.isOnPath(i)&&console.log(t.green("\n"+y.t("wizard.run_tool_hint",{command:a.command}))),this.printPathReloadHint([i]));const{nextAction:o}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.exit_and_start"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===o&&(this.printGoodbye(),process.exit(0))}catch(a){m.fail(y.t("wizard.config_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async clearPinnedModels(a){const o=c[a]?.displayName||a,{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_clear_model",{tool:o}),default:!1}]);if(i){try{const e=await l.clearPinnedModels(a);0===e.length?console.log(t.yellow("\n"+y.t("config.clear_model_none",{tool:o}))):(console.log(t.green("\n✓ "+y.t("config.clear_model_done",{tool:o}))),e.forEach(e=>console.log(t.gray(` - ${e}`))),console.log(t.gray(y.t("config.clear_model_restart_hint",{tool:o}))))}catch(e){console.log(t.red("\n"+(e instanceof Error?e.message:String(e))))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async unloadConfig(o){const{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_unload_config",{tool:c[o]?.displayName||o}),default:!1}]);if(!i)return;const n=a(y.t("wizard.unloading_config")).start();try{const a=l.holdsOurConfig(o),i=l.unloadPrivateConfig(o);if(!a)return void n.info(y.t("config.remove_nothing",{tool:c[o]?.displayName||o}));n.succeed(y.t("wizard.config_unloaded")),i.forEach(e=>console.log(t.yellow(" ! "+e.text)));const{nextAction:r}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.nav_exit"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===r&&(this.printGoodbye(),process.exit(0))}catch(a){n.fail(y.t("wizard.config_unload_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async restoreConfig(o){const i=c[o]?.displayName||o,{confirm:n}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_restore_config",{tool:i}),default:!1}]);if(!n)return;const r=a(y.t("wizard.restoring_config")).start();try{const e=l.restorePrivateConfig(o).filter(e=>e.result.restored);0===e.length?r.warn(y.t("wizard.restore_no_backup")):(r.succeed(y.t("wizard.config_restored",{tool:i})),e.forEach(e=>console.log(t.gray(` ${e.file} ← ${e.result.from}`))),console.log(t.yellow(" ! "+y.t("config.reopen_hint",{tool:i}))))}catch(e){r.fail(y.t("wizard.config_restore_failed")),console.log(t.red(e instanceof Error?e.message:String(e)))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async run(){await this.showMainMenu()}async showMainMenu(){if(this.hasConfiguredApiKey())for(;;){this.resetScreen();const a=o.getApiKey()||"",i=a.length>4?"sk-****"+a.slice(-4):"****";console.log(t.gray(` 🔑 API Key: ${i}`)+t.green(" ✓")),console.log("");const n=l.getSupportedTools().map(e=>({name:"🛠️ "+e.displayName,value:{type:"tool",tool:e.name}})),r=[new e.Separator(E("── "+y.t("wizard.select_tool")+" ──")),...n,new e.Separator(t.gray("── "+y.t("wizard.settings")+" ──")),{name:"🔑 "+y.t("wizard.menu_change_api_key"),value:{type:"apikey"}},{name:"🔗 "+y.t("wizard.menu_base_url",{url:o.getBaseUrl()}),value:{type:"base"}},{name:"🌐 "+y.t("wizard.menu_config_language"),value:{type:"language"}},new e.Separator,{name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}}],{action:s}=await this.promptWithHints([{type:"list",name:"action",message:"🛠️ "+y.t("wizard.select_tool"),choices:r}]);"exit"===s.type?(this.printGoodbye(),process.exit(0)):"tool"===s.type?await this.configureTool(s.tool):"apikey"===s.type?await this.configApiKey():"base"===s.type?await this.configBaseUrl():"language"===s.type&&await this.configLanguage()}else await this.runFirstTimeSetup()}}export const wizard=Wizard.getInstance();
1
+ import e from"inquirer";import t from"chalk";import a from"ora";import{configManager as o,DEFAULT_MODELS as i}from"./config.js";import{getPresets as n,resolvePreset as r,getToolDefaultModel as s}from"./model-registry.js";import{toolManager as l,SUPPORTED_TOOLS as c}from"./tool-manager.js";import{confirmWritePlan as d}from"./write-plan.js";import{postApplyPrompts as p}from"./post-apply.js";import{appStatus as m,appStatusText as u,appTools as _,appsForTools as g,cachedAppStatus as w,upgradeApp as f}from"./app-update.js";import{i18n as y,detectSystemLang as h}from"./i18n.js";import{createBorderLine as z,createContentLine as v}from"../utils/string-width.js";import{validateApiKey as k,fetchModels as x}from"./api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as b}from"./tools/codex.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as S}from"./tools/claude-desktop.js";import{addressesWithCurrent as C,ensureReachableGatewayAddress as M,moveOtherToolsAfterFallback as T,toolsWeConfigured as A,fastestIndex as K,probeAll as N,probeSummary as B,reasonText as O,savedApiKey as P,switchGatewayAddress as W}from"../commands/base.js";import{readFileSync as j}from"fs";import{dirname as H,join as L}from"path";import{fileURLToPath as $}from"url";import{brand as F}from"./brand.js";const I=H($(import.meta.url)),E=t.hex("#FF8700");export class Wizard{static instance;BOX_WIDTH=63;validatedApiKeys=new Set;constructor(){}static getInstance(){return Wizard.instance||(Wizard.instance=new Wizard),Wizard.instance}createBox(e){console.log(E.bold("\n"+z("╔","╗","═",this.BOX_WIDTH))),console.log(E.bold(v(e,"║","║",this.BOX_WIDTH,"center"))),console.log(E.bold(z("╚","╝","═",this.BOX_WIDTH))),console.log("")}showOperationHints(){const e=[t.gray(y.t("wizard.hint_navigate")),t.gray(y.t("wizard.hint_confirm"))];console.log(t.gray("💡 ")+e.join(t.gray(" | "))+"\n")}async promptWithHints(t){this.showOperationHints();const a=t.map(e=>"list"!==e.type||e.pageSize?e:{...e,pageSize:20});return e.prompt(a)}printBanner(){const e=60,t=y.t("wizard.banner_subtitle"),a=v(t,"║","║",e,"center"),o=v("","║","║",e,"center"),i=v(`${F().productName} v${function(){try{return JSON.parse(j(L(I,"..","..","package.json"),"utf-8")).version}catch{return"0.0.0"}}()}`,"║","║",e,"center"),n=[String.raw`__ ___ _ ____ _ ___ `,String.raw`\ \ / (_) |__ ___ / ___| | |_ _|`,String.raw` \ \ / /| | '_ \ / _ \ | | | | | `,String.raw` \ V / | | |_) | __/ |___| |___ | | `,String.raw` \_/ |_|_.__/ \___|\____|_____|___|`],r=Math.max(...n.map(e=>e.length)),s=" ".repeat(Math.floor((58-r)/2)),l=n.map(t=>v(s+t,"║","║",e,"left")),c=[z("╔","╗","═",e),o,...l,o,i,a,z("╚","╝","═",e)];console.log(E.bold("\n"+c.join("\n")))}resetScreen(){console.clear(),this.printBanner()}printGoodbye(){const e=l.getSupportedTools().filter(e=>{if(e.gui)return!1;try{return Boolean(l.detectCurrentConfig(e.name).apiKey)&&l.isToolInstalled(e.name)}catch{return!1}});let a;if(e.length>0){const t=e.map(e=>e.command).join(" / ");a=y.t("wizard.goodbye_message_tools",{commands:t}),e.some(e=>"claude-code"===e.name)&&(a+=" "+y.t("wizard.goodbye_claude_hint"))}else a=y.t("wizard.goodbye_message");console.log(t.green("\n👋 "+a)),this.printPathReloadHint(e.map(e=>e.name))}printPathReloadHint(e){const a=e.filter(e=>!l.isOnPath(e));if(0===a.length)return;const o=a.map(e=>c[e].command).join(" / ");console.log(t.yellow(" ! "+y.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}async runFirstTimeSetup(){const e="zh_CN"===h();if(e&&(o.setLang("zh_CN"),y.setLocale("zh_CN")),this.resetScreen(),console.log(E.bold("\n"+y.t("wizard.welcome"))),console.log(t.gray(y.t("wizard.privacy_note")+"\n")),e?console.log(t.gray(y.t("wizard.lang_auto_zh")+"\n")):await this.configLanguage(),await M()){const e=A();e.length>0&&await d(e.map(e=>e.tool))&&await p(await T(e))}await this.configApiKey()&&await this.selectAndConfigureTool(!0)}async configLanguage(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_language"));const a=y.getLocale(),{language:i}=await this.promptWithHints([{type:"list",name:"language",message:"✨ "+y.t("wizard.select_language"),choices:[{name:"[EN] English"+("en_US"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"en_US"},{name:"[CN] 中文"+("zh_CN"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"zh_CN"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}],default:"zh_CN"}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;return o.setLang(i),void y.setLocale(i)}}buildPresetChoices(){const a=n(),o=a.filter(e=>e.recommended),i=a.filter(e=>!e.recommended),r=e=>({name:(y.t(e.name)!==e.name?y.t(e.name):e.name)+(e.models?t.gray(` [H:${e.models.haiku} S:${e.models.sonnet} O:${e.models.opus}]`):""),value:{type:"preset",preset:e}}),s=[];return o.length>0&&(s.push(new e.Separator(t.hex("#FF8700")("── "+y.t("wizard.recommended")+" ──"))),s.push(...o.map(r))),i.length>0&&(s.push(new e.Separator(t.gray("── "+y.t("wizard.other_models")+" ──"))),s.push(...i.map(r))),s}async handleCustomModelInput(){const a=o.getModels(),{customMode:n}=await e.prompt([{type:"list",name:"customMode",message:y.t("wizard.custom_model_mode"),choices:[{name:y.t("wizard.custom_model_single"),value:"single"},{name:y.t("wizard.custom_model_per_role"),value:"per_role"}]}]);if("single"===n){const{customModel:t}=await e.prompt([{type:"input",name:"customModel",message:y.t("wizard.input_custom_model"),default:i.sonnet}]);o.setModels({haiku:t,sonnet:t,opus:t,reasoning:t})}else{const t=await e.prompt([{type:"input",name:"haiku",message:y.t("wizard.model_haiku"),default:a.haiku},{type:"input",name:"sonnet",message:y.t("wizard.model_sonnet"),default:a.sonnet},{type:"input",name:"opus",message:y.t("wizard.model_opus"),default:a.opus},{type:"input",name:"reasoning",message:y.t("wizard.model_reasoning"),default:a.reasoning}]);o.setModels(t)}console.log(t.green("\n✓ "+y.t("wizard.models_saved")))}async configModels(a){const i=o.getApiKey();if(await this.validatedKeyForConfiguration(i))for(;;){this.resetScreen(),this.createBox(y.t("wizard.config_models"));const i=[...this.buildPresetChoices()];i.push(new e.Separator),i.push({name:"✏️ "+y.t("wizard.custom_model_input"),value:{type:"custom_input"}}),i.push(new e.Separator),i.push({name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}),i.push({name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}});const{modelChoice:n}=await this.promptWithHints([{type:"list",name:"modelChoice",message:y.t("wizard.select_model_config"),choices:i}]);if("exit"===n.type)this.printGoodbye(),process.exit(0);else{if("back"===n.type)return;if("custom_input"===n.type)return await this.handleCustomModelInput(),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig());if("preset"===n.type){const e=r(n.preset);return o.setModels(e),console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig())}}}else await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async promptLoadAfterModelConfig(){const{shouldLoad:t}=await e.prompt([{type:"list",name:"shouldLoad",message:y.t("wizard.load_config_now"),choices:[{name:y.t("wizard.load_config_yes"),value:!0},{name:y.t("wizard.load_config_later"),value:!1}]}]);t&&await this.selectAndConfigureTool()}async configBaseUrl(){const i=o.getBaseUrl(),n=C(),r=a(y.t("wizard.base_testing")).start(),s=await N(n,{apiKey:P(),samples:3});r.stop();const l=K(s),c=n.map((e,a)=>{const o=e.url===i?t.cyan(` ← ${y.t("base.current_mark")}`):"";return{name:`${e.url} ${t.gray(e.label)} ${B(s[a],a===l)}${o}`,value:e.url}});c.push(new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"});const{url:d}=await this.promptWithHints([{type:"list",name:"url",message:y.t("wizard.base_select"),choices:c,default:i}]);if("__back__"===d)return;const p=s[n.findIndex(e=>e.url===d)];p.ok?await W(d):console.log(t.red(y.t("base.unreachable",{url:d,reason:O(p)}))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async configApiKey(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.input_api_key")),console.log(t.gray("\n💡 "+y.t("wizard.api_key_input_hint"))),console.log(t.gray(" "+y.t("wizard.api_key_get_hint",{url:F().links.tokenPage}))),console.log();const{apiKey:i}=await e.prompt([{type:"password",name:"apiKey",message:y.t("wizard.input_your_api_key"),mask:"*"}]);if(!i||""===i.trim()){const{action:t}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===t)return!1;continue}const n=a(y.t("wizard.validating_api_key")).start(),r=await k(i.trim());if(n.stop(),r.valid)return o.setApiKey(i.trim()),this.validatedApiKeys.add(i.trim()),console.log(t.green("\n✓ "+y.t("wizard.api_key_valid"))),!0;{this.validatedApiKeys.delete(i.trim()),"invalid_api_key"===r.error?console.log(t.red("\n✗ "+y.t("wizard.api_key_invalid"))):console.log(t.red("\n✗ "+y.t("wizard.api_key_network_error")));const{action:a}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===a)return!1}}}async selectAndConfigureTool(a=!1){for(const e of _())await m(e).catch(()=>{});for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_tool"));const o=l.getSupportedTools().map(e=>{const a=g([e.name]).map(e=>w(e)).find(e=>e.outdated);return{name:e.displayName+(a?t.yellow(" "+(a.tool===e.name?"":`${a.name} `)+u(a)):""),value:e.name}}),{tool:i}=await this.promptWithHints([{type:"list",name:"tool",message:"🛠️ "+y.t("wizard.select_tool"),choices:[...o,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}]}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;await this.configureTool(i,a)}}async configureTool(a,o=!1){const i=c[a];if(i){if(!l.isToolInstalled(a)){console.log(t.yellow("\n"+y.t("wizard.tool_not_installed",{tool:i.displayName})));const{install:o}=await e.prompt([{type:"confirm",name:"install",message:y.t("wizard.install_tool_confirm"),default:!0}]);if(!o)return;try{await l.installTool(a)}catch{return void console.log(t.red(y.t("wizard.install_failed")))}}o?await this.configureToolModel(a)&&await this.loadConfig(a):await this.showToolMenu(a)}}async showToolMenu(t){for(;;){this.resetScreen();const a=c[t];if(!a)return;this.createBox(a.displayName+" "+y.t("wizard.menu_title"));const o=[{name:"📥 "+y.t("wizard.action_load_config",{tool:a.displayName}),value:"load"},{name:"📤 "+y.t("wizard.action_unload_config",{tool:a.displayName}),value:"unload"}];l.supportsClearPinnedModels(t)&&o.push({name:"🧹 "+y.t("wizard.action_clear_model",{tool:a.displayName}),value:"clear-model"});for(const e of g([t]).map(e=>w(e)).reverse()){if(e.blocker||!e.latest||!e.outdated&&e.installed)continue;const t=e.installed?y.t("wizard.action_upgrade_app",{tool:e.name,current:e.current??"?",latest:e.latest}):y.t("wizard.action_install_app",{tool:e.name,latest:e.latest});o.unshift({name:"↑ "+t,value:`upgrade-app:${e.tool}`})}o.push({name:"🧨 "+y.t("wizard.action_force_config",{tool:a.displayName}),value:"force"},{name:"↩️ "+y.t("wizard.action_restore_config",{tool:a.displayName}),value:"restore"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"});const{action:i}=await this.promptWithHints([{type:"list",name:"action",message:"⚙️ "+y.t("wizard.select_action"),choices:o}]);if("exit"===i)this.printGoodbye(),process.exit(0);else{if("back"===i)return;"load"===i?await this.configureToolModel(t)&&await this.loadConfig(t):"force"===i?await this.forceConfig(t):"unload"===i?await this.unloadConfig(t):"string"==typeof i&&i.startsWith("upgrade-app:")?(await f(i.slice(12),{install:!0}),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])):"clear-model"===i?await this.clearPinnedModels(t):"restore"===i&&await this.restoreConfig(t)}}}singleModelOverride(e){const t=e.trim();return/claude/i.test(t)?{opus:t}:{haiku:t,sonnet:t,opus:t,reasoning:t}}hasConfiguredApiKey(){return!!o.getApiKey()?.trim()||o.listToolApiKeys().some(e=>Boolean(o.getApiKeyForTool(e)?.trim()))}async validatedKeyForConfiguration(e){const o=e?.trim();if(!o)return console.log(t.red("\n"+y.t("wizard.api_key_required"))),console.log(t.yellow(y.t("wizard.please_config_api_key_first"))),null;if(this.validatedApiKeys.has(o))return o;const i=a(y.t("wizard.validating_api_key")).start(),n=await k(o);if(n.valid)return this.validatedApiKeys.add(o),i.succeed(y.t("wizard.api_key_valid")),o;this.validatedApiKeys.delete(o);const r="invalid_api_key"===n.error?y.t("wizard.api_key_invalid"):y.t("wizard.api_key_network_error");return i.fail(r),console.log(t.red("\n"+y.t("wizard.please_reconfig_api_key"))),null}async configureToolModel(i){const n=c[i];if(!n)return!1;const l=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!l)return await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]),!1;const d="claude-code"===i,p=d||"claude-desktop"===i||"agy"===i,m=s(i),u=p||!m?y.t("wizard.model_builtin_default"):m;this.resetScreen(),this.createBox(n.displayName+" · "+y.t("wizard.config_models"));const _=[{name:"✅ "+y.t("wizard.use_default_model",{model:u}),value:{type:"default"}},{name:"🌐 "+y.t("wizard.fetch_models_from_api"),value:{type:"fetch"}},...this.buildPresetChoices(),new e.Separator,{name:"✏️ "+y.t("wizard.input_custom_model"),value:{type:"custom"}},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}],{choice:g}=await this.promptWithHints([{type:"list",name:"choice",message:y.t("wizard.select_tool_model",{tool:n.displayName}),choices:_}]);if("back"===g.type)return!1;if("default"===g.type)o.setToolModel(i,null);else if("preset"===g.type)o.setToolModel(i,r(g.preset));else if("custom"===g.type){const{model:t}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]),a=(t||"").trim();o.setToolModel(i,a?this.singleModelOverride(a):null)}else if("fetch"===g.type){const n=a(y.t("wizard.fetching_models")).start(),r=await x(l);let s;if(n.stop(),r.ok&&r.models.length>0){const{model:t}=await e.prompt([{type:"list",name:"model",message:y.t("wizard.select_fetched_model"),pageSize:20,choices:[...r.models,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"}]}]);if("__back__"===t)return!1;s=t}else{console.log(t.yellow("\n"+y.t("wizard.fetch_models_failed")));const{model:a}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]);s=(a||"").trim()}o.setToolModel(i,s?this.singleModelOverride(s):null)}if("codex"===i){const t=o.getToolSetting(i,b),{enableOneMillionContext:a}=await e.prompt([{type:"confirm",name:"enableOneMillionContext",message:y.t("wizard.codex_enable_1m_context"),default:!1!==t}]);o.setToolSetting(i,b,Boolean(a))}if("claude-desktop"===i){const t=o.getToolSetting(i,S),{hideOfficialLogin:a}=await e.prompt([{type:"confirm",name:"hideOfficialLogin",message:y.t("wizard.desktop_hide_official_login"),default:!1!==t}]);o.setToolSetting(i,S,Boolean(a))}return console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),d&&console.log(t.gray("💡 "+y.t("wizard.claude_model_hint"))),!0}async forceConfig(t){const a=c[t]?.displayName||t,{confirm:o}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("config.confirm_force",{tool:a}),default:!1}]);o&&await this.loadConfig(t,{force:!0})}async loadConfig(i,n={}){const r=o.getModelsForTool(i),s=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!s)return void await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]);if(!n.force&&!await d([i]))return;const m=a(y.t("wizard.loading_config")).start();try{await l.applyPrivateConfig(i,s,r,{...n,takeOver:!0}),m.stop(),l.printApplied(i),await p([i],{apps:{install:!1}}),n.force&&console.log(t.yellow(y.t("config.force_done",{tool:c[i]?.displayName||i,name:i})));const a=c[i];a&&!a.gui&&(l.isOnPath(i)&&console.log(t.green("\n"+y.t("wizard.run_tool_hint",{command:a.command}))),this.printPathReloadHint([i]));const{nextAction:o}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.exit_and_start"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===o&&(this.printGoodbye(),process.exit(0))}catch(a){m.fail(y.t("wizard.config_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async clearPinnedModels(a){const o=c[a]?.displayName||a,{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_clear_model",{tool:o}),default:!1}]);if(i){try{const e=await l.clearPinnedModels(a);0===e.length?console.log(t.yellow("\n"+y.t("config.clear_model_none",{tool:o}))):(console.log(t.green("\n✓ "+y.t("config.clear_model_done",{tool:o}))),e.forEach(e=>console.log(t.gray(` - ${e}`))),console.log(t.gray(y.t("config.clear_model_restart_hint",{tool:o}))))}catch(e){console.log(t.red("\n"+(e instanceof Error?e.message:String(e))))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async unloadConfig(o){const{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_unload_config",{tool:c[o]?.displayName||o}),default:!1}]);if(!i)return;const n=a(y.t("wizard.unloading_config")).start();try{const a=l.holdsOurConfig(o),i=l.unloadPrivateConfig(o);if(!a)return void n.info(y.t("config.remove_nothing",{tool:c[o]?.displayName||o}));n.succeed(y.t("wizard.config_unloaded")),i.forEach(e=>console.log(t.yellow(" ! "+e.text)));const{nextAction:r}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.nav_exit"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===r&&(this.printGoodbye(),process.exit(0))}catch(a){n.fail(y.t("wizard.config_unload_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async restoreConfig(o){const i=c[o]?.displayName||o,{confirm:n}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_restore_config",{tool:i}),default:!1}]);if(!n)return;const r=a(y.t("wizard.restoring_config")).start();try{const e=l.restorePrivateConfig(o).filter(e=>e.result.restored);0===e.length?r.warn(y.t("wizard.restore_no_backup")):(r.succeed(y.t("wizard.config_restored",{tool:i})),e.forEach(e=>console.log(t.gray(` ${e.file} ← ${e.result.from}`))),console.log(t.yellow(" ! "+y.t("config.reopen_hint",{tool:i}))))}catch(e){r.fail(y.t("wizard.config_restore_failed")),console.log(t.red(e instanceof Error?e.message:String(e)))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async run(){await this.showMainMenu()}async showMainMenu(){if(this.hasConfiguredApiKey())for(;;){this.resetScreen();const a=o.getApiKey()||"",i=a.length>4?"sk-****"+a.slice(-4):"****";console.log(t.gray(` 🔑 API Key: ${i}`)+t.green(" ✓")),console.log("");const n=l.getSupportedTools().map(e=>({name:"🛠️ "+e.displayName,value:{type:"tool",tool:e.name}})),r=[new e.Separator(E("── "+y.t("wizard.select_tool")+" ──")),...n,new e.Separator(t.gray("── "+y.t("wizard.settings")+" ──")),{name:"🔑 "+y.t("wizard.menu_change_api_key"),value:{type:"apikey"}},{name:"🔗 "+y.t("wizard.menu_base_url",{url:o.getBaseUrl()}),value:{type:"base"}},{name:"🌐 "+y.t("wizard.menu_config_language"),value:{type:"language"}},new e.Separator,{name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}}],{action:s}=await this.promptWithHints([{type:"list",name:"action",message:"🛠️ "+y.t("wizard.select_tool"),choices:r}]);"exit"===s.type?(this.printGoodbye(),process.exit(0)):"tool"===s.type?await this.configureTool(s.tool):"apikey"===s.type?await this.configApiKey():"base"===s.type?await this.configBaseUrl():"language"===s.type&&await this.configLanguage()}else await this.runFirstTimeSetup()}}export const wizard=Wizard.getInstance();
@@ -689,6 +689,7 @@
689
689
  "probe_with_key": "Listing models with your saved API key on the built-in and current addresses (others only check that the gateway answers), median of 3 per address",
690
690
  "probe_without_key": "No API key saved yet, so only checking that the gateway answers; after {{cli}} setup --key <your API key> the model list is fetched instead",
691
691
  "setup_fallback_main": "{{from}} cannot be reached: {{reason}}. Switched back to the main site {{url}}",
692
+ "setup_back": "{{url}} can be reached again; switched back to it from {{from}}, which was picked when it could not be reached",
692
693
  "next_addresses": "Next: run {{cli}} base to see the addresses, or {{cli}} base auto to switch."
693
694
  },
694
695
  "help": {
@@ -689,6 +689,7 @@
689
689
  "probe_with_key": "用你保存的令牌在内置地址和当前地址上获取模型列表(其他地址只测试网关能否打开),每个地址测 3 次取中位数",
690
690
  "probe_without_key": "还没有保存令牌,只测试网关能否打开;运行 {{cli}} setup --key <你的令牌> 后会改为实际获取模型列表",
691
691
  "setup_fallback_main": "无法连接 {{from}}:{{reason}}。已改回主站 {{url}}",
692
+ "setup_back": "{{url}} 已经可以连接,改回使用它(之前连不上时自动换到了 {{from}})",
692
693
  "next_addresses": "下一步:运行 {{cli}} base 查看可用的接入地址,或运行 {{cli}} base auto 自动切换。"
693
694
  },
694
695
  "help": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibeapi/api-helper",
3
- "version": "0.0.180",
3
+ "version": "0.0.182",
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",