@vibeapi/api-helper 0.0.181 → 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
@@ -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 toolsWeConfigured(){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=toolsWeConfigured();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)}}
@@ -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)}}
@@ -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.181",
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",