@caishenai/cli 0.0.181 → 0.0.183
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands/base.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"chalk";import{configManager as
|
|
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{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[]}}()
|
|
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{getGatewayModelRules as e}from"./model-registry.js";export function autoCompactTokens(t,o){return o&&o>0?Math.min(o,t):Math.floor(t*e().autoCompactRatio)}export function gatewayModelSpecs(o,i,d=[]){const n=e().models,c=n.filter(e=>function(e,t){return"codebuddy"===e||("codex"===e?!1!==t.codex:"grok"===e?"grok"===modelFamily(t.id):!t.id.startsWith("claude-")&&!1!==t.claudeCode)}(o,e));if(!i)return c;const r=new Set(Object.values(i).flat().filter(e=>e.hidden).map(e=>e.id)),l=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t.filter(e=>!e.hidden)])),s=new Map;for(const e of Object.values(l).flat()){const t="codex"===o&&"gpt"===modelFamily(e.id)?void 0:e.clients?.[o];void 0===t||s.has(e.id)||s.set(e.id,t)}for(const[e,t]of s)t||r.add(e);const a=new Map(("claude-code"===o?n:c).map(e=>[e.id,e])),u=(l.gemini??[]).filter(e=>s.get(e.id)??!1!==n.find(t=>t.id===e.id)?.codex),m=("codebuddy"===o?[...l.claude??[],...l.codex??[],...l.gemini??[],...l.grok??[]]:"grok"===o?l.grok??[]:"codex"===o?[...l.codex??[],...u
|
|
1
|
+
import{getGatewayModelRules as e}from"./model-registry.js";export function autoCompactTokens(t,o){return o&&o>0?Math.min(o,t):Math.floor(t*e().autoCompactRatio)}export function gatewayModelSpecs(o,i,d=[]){const n=e().models,c=n.filter(e=>function(e,t){return"codebuddy"===e||("codex"===e?!t.id.startsWith("claude-")&&!1!==t.codex:"grok"===e?"grok"===modelFamily(t.id):!t.id.startsWith("claude-")&&!1!==t.claudeCode)}(o,e));if(!i)return c;const r=new Set(Object.values(i).flat().filter(e=>e.hidden).map(e=>e.id)),l=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t.filter(e=>!e.hidden)])),s=new Map;for(const e of Object.values(l).flat()){const t="codex"===o&&"gpt"===modelFamily(e.id)?void 0:e.clients?.[o];void 0===t||s.has(e.id)||s.set(e.id,t)}for(const[e,t]of s)t||r.add(e);const a=new Map(("claude-code"===o?n:c).map(e=>[e.id,e])),u=(l.gemini??[]).filter(e=>s.get(e.id)??!1!==n.find(t=>t.id===e.id)?.codex),m=("codebuddy"===o?[...l.claude??[],...l.codex??[],...l.gemini??[],...l.grok??[]]:"grok"===o?l.grok??[]:"codex"===o?[...l.codex??[],...u].filter(e=>!e.id.startsWith("claude-")):function(e,t){return[...(e.codex??[]).filter(e=>"gpt"===modelFamily(e.id)),...e.gemini??[],...e.grok??[],...(e.claude??[]).filter(e=>!e.id.startsWith("claude-"))].filter(e=>e.clients?.["claude-code"]??t.get(e.id)?.claudeCode??!0)}(l,a)).filter(e=>!(e=>!1===s.get(e.id))(e));if(0===m.length)return c.filter(e=>!r.has(e.id));const f=new Set,g=[];for(const e of m){if(f.has(e.id))continue;f.add(e.id);const{clients:t,minClientVersion:o,rolloutPercent:i,...d}=e,n={...a.get(e.id),...d};void 0!==t?.codex&&(n.codex=t.codex),void 0!==t?.["claude-code"]&&(n.claudeCode=t["claude-code"]),g.push(n)}return t[o].some(e=>d.includes(e))?g:function(e,t,o){const i=[...e];return t.forEach((e,d)=>{if(o.has(e.id)||i.some(t=>t.id===e.id))return;const n=modelFamily(e.id),c=new Set(t.slice(d+1).filter(e=>modelFamily(e.id)===n).map(e=>e.id));let r=i.findIndex(e=>c.has(e.id));if(r<0){r=i.length;for(let e=i.length-1;e>=0;e--)if(modelFamily(i[e].id)===n){r=e+1;break}}i.splice(r,0,e)}),i}(g,c,r)}const t={grok:["grok"],codex:["codex","gemini"],"claude-code":["codex","gemini","grok","claude"],codebuddy:["claude","codex","gemini","grok"]},o={gpt:"GPT",gemini:"Gemini",glm:"GLM",deepseek:"DeepSeek",minimax:"MiniMax",qwen:"Qwen"};export function modelBlurb(e,t={}){const o=[];for(const i of(e??"").split("|")){const e=i.trim();e&&(/\d\s*万?\s*输出|output\D*\d|\d\D*output/i.test(e)||(/[\d百千]\s*万?\s*上下文|context\D*\d|\d\D*context/i.test(e)?t.millionContext&&!o.includes("百万上下文")&&o.unshift("百万上下文"):o.push(e)))}return t.millionContext&&!o.includes("百万上下文")&&o.unshift("百万上下文"),o.length>0?o.join(" | "):void 0}export function prettyModelName(e){const t=e.replace(/^([a-z]+)(\d)/i,"$1 $2").split(/[-_\s]+/).filter(Boolean),i=[];for(const e of t){const t=i[i.length-1];if(/^\d+$/.test(e)&&t&&/^\d+$/.test(t)&&e.length<=2&&!/^\d{8}$/.test(e)){i[i.length-1]=`${t}.${e}`;continue}const d=e.toLowerCase();i.push(o[d]??(/^[a-z]\d/i.test(e)?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))}return i.join(" ")}export function vendorNames(e){return[...new Set(e.map(e=>prettyModelName(e).split(" ")[0]))]}export function modelFamily(e){const t=e.toLowerCase();return t.startsWith("claude-")?"claude":t.startsWith("gemini")?"gemini":t.startsWith("grok")?"grok":/^(gpt|o\d|codex)/.test(t)?"gpt":"other"}
|
package/dist/locales/en_US.json
CHANGED
|
@@ -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": {
|
package/dist/locales/zh_CN.json
CHANGED
|
@@ -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": {
|