@vibeapi/api-helper 0.0.182 → 0.0.184

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.
@@ -50,6 +50,9 @@
50
50
  "video": false,
51
51
  "vision": true
52
52
  },
53
+ "clients": {
54
+ "codex": false
55
+ },
53
56
  "context_window": 1000000,
54
57
  "description": "100 万上下文 | 长时 Agent 编程 | 知识工作",
55
58
  "endpoint_types": [
@@ -89,6 +92,9 @@
89
92
  "video": false,
90
93
  "vision": true
91
94
  },
95
+ "clients": {
96
+ "codex": false
97
+ },
92
98
  "context_window": 1000000,
93
99
  "description": "100 万上下文 | Agent 编程 | 速度与成本均衡",
94
100
  "endpoint_types": [
@@ -128,6 +134,9 @@
128
134
  "video": false,
129
135
  "vision": true
130
136
  },
137
+ "clients": {
138
+ "codex": false
139
+ },
131
140
  "context_window": 1000000,
132
141
  "description": "100 万上下文 | 高难度推理 | 长时 Agent 与多步研究",
133
142
  "endpoint_types": [
@@ -168,6 +177,9 @@
168
177
  "video": false,
169
178
  "vision": true
170
179
  },
180
+ "clients": {
181
+ "codex": false
182
+ },
171
183
  "context_window": 1000000,
172
184
  "description": "100 万上下文 | 长时 Agent 与多步研究",
173
185
  "endpoint_types": [
@@ -207,6 +219,9 @@
207
219
  "video": false,
208
220
  "vision": true
209
221
  },
222
+ "clients": {
223
+ "codex": false
224
+ },
210
225
  "context_window": 1000000,
211
226
  "description": "100 万上下文 | 高强度推理 | 长时 Agent",
212
227
  "endpoint_types": [
@@ -246,6 +261,9 @@
246
261
  "video": false,
247
262
  "vision": true
248
263
  },
264
+ "clients": {
265
+ "codex": false
266
+ },
249
267
  "context_window": 1000000,
250
268
  "description": "100 万上下文 | Agent 编程",
251
269
  "endpoint_types": [
@@ -285,6 +303,9 @@
285
303
  "video": false,
286
304
  "vision": true
287
305
  },
306
+ "clients": {
307
+ "codex": false
308
+ },
288
309
  "context_window": 1000000,
289
310
  "description": "100 万上下文 | Agent 编程 | 工具调用",
290
311
  "endpoint_types": [
@@ -324,6 +345,9 @@
324
345
  "video": false,
325
346
  "vision": true
326
347
  },
348
+ "clients": {
349
+ "codex": false
350
+ },
327
351
  "context_window": 1000000,
328
352
  "description": "100 万上下文 | 推理 | 编程",
329
353
  "endpoint_types": [
@@ -363,6 +387,9 @@
363
387
  "video": false,
364
388
  "vision": true
365
389
  },
390
+ "clients": {
391
+ "codex": false
392
+ },
366
393
  "context_window": 1000000,
367
394
  "description": "100 万上下文 | 推理 | 编程",
368
395
  "endpoint_types": [
@@ -401,6 +428,9 @@
401
428
  "video": false,
402
429
  "vision": true
403
430
  },
431
+ "clients": {
432
+ "codex": false
433
+ },
404
434
  "context_window": 200000,
405
435
  "description": "20 万上下文(部分分组无 1M)| 推理 | 编程",
406
436
  "endpoint_types": [
@@ -439,6 +469,9 @@
439
469
  "video": false,
440
470
  "vision": true
441
471
  },
472
+ "clients": {
473
+ "codex": false
474
+ },
442
475
  "context_window": 200000,
443
476
  "description": "20 万上下文(部分分组无 1M)| Agent 编程",
444
477
  "endpoint_types": [
@@ -2135,7 +2168,7 @@
2135
2168
  "tool": "gemini"
2136
2169
  }
2137
2170
  ],
2138
- "revision": "2026-11-11T08:32:41Z-17",
2171
+ "revision": "2026-11-16T16:50:03Z-1",
2139
2172
  "schema": 1,
2140
2173
  "tools": {
2141
2174
  "claude": {
@@ -50,6 +50,9 @@
50
50
  "video": false,
51
51
  "vision": true
52
52
  },
53
+ "clients": {
54
+ "codex": false
55
+ },
53
56
  "context_window": 1000000,
54
57
  "description": "100 万上下文 | 长时 Agent 编程 | 知识工作",
55
58
  "endpoint_types": [
@@ -89,6 +92,9 @@
89
92
  "video": false,
90
93
  "vision": true
91
94
  },
95
+ "clients": {
96
+ "codex": false
97
+ },
92
98
  "context_window": 1000000,
93
99
  "description": "100 万上下文 | Agent 编程 | 速度与成本均衡",
94
100
  "endpoint_types": [
@@ -128,6 +134,9 @@
128
134
  "video": false,
129
135
  "vision": true
130
136
  },
137
+ "clients": {
138
+ "codex": false
139
+ },
131
140
  "context_window": 1000000,
132
141
  "description": "100 万上下文 | 高难度推理 | 长时 Agent 与多步研究",
133
142
  "endpoint_types": [
@@ -168,6 +177,9 @@
168
177
  "video": false,
169
178
  "vision": true
170
179
  },
180
+ "clients": {
181
+ "codex": false
182
+ },
171
183
  "context_window": 1000000,
172
184
  "description": "100 万上下文 | 长时 Agent 与多步研究",
173
185
  "endpoint_types": [
@@ -207,6 +219,9 @@
207
219
  "video": false,
208
220
  "vision": true
209
221
  },
222
+ "clients": {
223
+ "codex": false
224
+ },
210
225
  "context_window": 1000000,
211
226
  "description": "100 万上下文 | 高强度推理 | 长时 Agent",
212
227
  "endpoint_types": [
@@ -246,6 +261,9 @@
246
261
  "video": false,
247
262
  "vision": true
248
263
  },
264
+ "clients": {
265
+ "codex": false
266
+ },
249
267
  "context_window": 1000000,
250
268
  "description": "100 万上下文 | Agent 编程",
251
269
  "endpoint_types": [
@@ -285,6 +303,9 @@
285
303
  "video": false,
286
304
  "vision": true
287
305
  },
306
+ "clients": {
307
+ "codex": false
308
+ },
288
309
  "context_window": 1000000,
289
310
  "description": "100 万上下文 | Agent 编程 | 工具调用",
290
311
  "endpoint_types": [
@@ -324,6 +345,9 @@
324
345
  "video": false,
325
346
  "vision": true
326
347
  },
348
+ "clients": {
349
+ "codex": false
350
+ },
327
351
  "context_window": 1000000,
328
352
  "description": "100 万上下文 | 推理 | 编程",
329
353
  "endpoint_types": [
@@ -363,6 +387,9 @@
363
387
  "video": false,
364
388
  "vision": true
365
389
  },
390
+ "clients": {
391
+ "codex": false
392
+ },
366
393
  "context_window": 1000000,
367
394
  "description": "100 万上下文 | 推理 | 编程",
368
395
  "endpoint_types": [
@@ -401,6 +428,9 @@
401
428
  "video": false,
402
429
  "vision": true
403
430
  },
431
+ "clients": {
432
+ "codex": false
433
+ },
404
434
  "context_window": 200000,
405
435
  "description": "20 万上下文(部分分组无 1M)| 推理 | 编程",
406
436
  "endpoint_types": [
@@ -439,6 +469,9 @@
439
469
  "video": false,
440
470
  "vision": true
441
471
  },
472
+ "clients": {
473
+ "codex": false
474
+ },
442
475
  "context_window": 200000,
443
476
  "description": "20 万上下文(部分分组无 1M)| Agent 编程",
444
477
  "endpoint_types": [
@@ -2135,7 +2168,7 @@
2135
2168
  "tool": "gemini"
2136
2169
  }
2137
2170
  ],
2138
- "revision": "2026-11-11T08:32:41Z-17",
2171
+ "revision": "2026-11-16T16:50:03Z-1",
2139
2172
  "schema": 1,
2140
2173
  "tools": {
2141
2174
  "claude": {
@@ -109,5 +109,5 @@ export declare function parseOnOff(raw: string | undefined): boolean | undefined
109
109
  * installer should bring them along): `--install`, `--yes` (one-line installers pass it) or yes at the prompt
110
110
  * (default yes); `--no-install`, a no, `--non-interactive` / `--json` or no terminal only print the command.
111
111
  */
112
- export declare function installMissingApps(tools: string[], install: boolean | undefined): Promise<boolean>;
112
+ export declare function installMissingApps(tools: string[], install: boolean | undefined, onlyApps?: string[]): Promise<boolean>;
113
113
  export declare function setupCommand(options: SetupCommandOptions): Promise<void>;
@@ -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,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"])}
1
+ import e from"chalk";import{getAdapter as o}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as c,fetchModels as u}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as m}from"../lib/tools/codex.js";import{resolveModelCatalog as g}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as k}from"../lib/tools/claude-desktop.js";import{operationError as _,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 $,isJsonMode as T,isNonInteractive as I,shouldAutoConfirm as K}from"../lib/runtime-options.js";import{appsForTools as M,appUpgradeCommand as G,getApp as N}from"../lib/app-update.js";import{join as O}from"path";import{confirmAction as S}from"../lib/confirm.js";import{asksBeforeWriting as E,confirmWritePlan as A,printWritePlan as B,toolWritePlan as D}from"../lib/write-plan.js";import F from"inquirer";import{logger as R}from"../utils/logger.js";import{forgetInstalls as q}from"../lib/tools/tool-installs.js";import{CLI_NAME as L,brandEnv as P}from"../lib/brand.js";import{upgradeCommand as Y}from"./upgrade.js";export const DEDICATED_KEYS=[{option:"claudekey",tool:"claude-code",need:"claude"},{option:"codexkey",tool:"codex",need:"gpt"},{option:"grokkey",tool:"grok",need:"grok"},{option:"desktopkey",tool:"claude-desktop",need:"claude"},{option:"agykey",tool:"agy",need:"gemini"},{option:"openclawkey",tool:"openclaw",need:"any",hidden:!0},{option:"hermeskey",tool:"hermes",need:"any",hidden:!0},{option:"atomcodekey",tool:"atomcode",need:"any",hidden:!0},{option:"codebuddykey",tool:"codebuddy",need:"any"},{option:"workbuddykey",tool:"workbuddy",need:"any"},{option:"dshkey",tool:"dsh",need:"any"}];async function V(e){const o=await u(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=o.models.map(e=>e.toLowerCase());return{hasClaude:t.some(e=>e.includes("claude")),hasGpt:t.some(e=>e.startsWith("gpt")||e.includes("gpt-")||/^o\d/.test(e)),hasGrok:t.some(e=>e.includes("grok")),hasGemini:t.some(e=>e.startsWith("gemini")),probed:!0}}function z(e,o){switch(o){case"claude":return e.hasClaude;case"gpt":return e.hasGpt;case"grok":return e.hasGrok;case"gemini":return e.hasGemini;default:return!0}}export function parseOnOff(e){const o=(e??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(o)||!["off","false","hide","0","no","n"].includes(o)&&void 0}function H(o){console.log(e.green(o))}function W(o){console.log(e.yellow(o))}function U(o){console.error(e.red(o))}let J=null;function Q(e){const o={operation:1,authentication:2,network:3};(!J||o[e]>o[J])&&(J=e)}async function X(o,t){T()||console.log(e.gray(n.t("setup.validating",{label:o})));const l=await c(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===o?`${L} setup --key ${i}`:`${L} setup ${o} ${i}`;let a;if("network_error"===l.error?(Q("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${L} base auto`,"network_error")):"invalid_api_key"===l.error?(Q("authentication"),a=h(n.t("setup.invalid_key",{label:o,reason:l.message||"invalid"}),s,"invalid_api_key")):(Q("operation"),a=_(n.t("setup.validate_failed",{label:o,reason:l.message||l.error||"unknown"}),s,l.error)),T())throw a;return U(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function Z(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=i,g=d[t];try{"claude-desktop"===t&&void 0!==c&&r.setToolSetting("claude-desktop",y,c),"codex"===t&&void 0!==s&&r.setToolSetting("codex",f,s),"claude-desktop"===t&&void 0!==a&&r.setToolSetting("claude-desktop",k,!a),await p.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(T())throw _(e instanceof Error?e.message:String(e),`${L} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return U("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:o})),!1}return p.printApplied(t),u&&console.log(e.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(e.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),o(t)?.isInstalled&&!p.isToolInstalled(t)&&console.log(e.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function ee(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function oe(e){if(C())return!0;const o=d[e]?.displayName??e;return v()?S({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(W(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,l){const i=M(o).filter(e=>{if(l&&!l.includes(e))return!1;const o=N(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return R.logError(`setup: app installed? ${e}`,o),!1}});if(0===i.length)return!1;const s=e=>N(e)?.displayName??e;let a=t;if(void 0===a&&!T())if(K())a=!I();else if(v()){const e=i.map(s).join(n.t("setup.list_separator")),o=i.reduce((e,o)=>e+(N(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!T())for(const o of i)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:G(o)})));return Boolean(a)}function te(e){W(n.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${L} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function le(o,t,l=[]){const i=D(o),s=O(r.getConfigDir(),"config.yaml");if(T())x({dry_run:!0,tools:i,install_first:l,key_file:t?s:null});else{if(0===i.length&&0===l.length){const o=(j()?e.cyan:e=>e)(n.t("runtime.dry_run_label"));return void console.log(`${o} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function ie(e){return Boolean(o(e)?.installSpec||N(e)?.appInstaller)}function se(e){return e?n.t("setup.pick_installed",{version:e}):n.t("setup.pick_installed_plain")}function ae(o){const t=N(o);let l;if(t&&t.tool!==o){let e=null;try{e=t.appInstaller.installedPath()}catch(e){R.logError(`setup: app installed? ${o}`,e)}l=e?se(t.installedVersion?.()):n.t("setup.pick_will_install")}else l=p.isToolInstalled(o)?se(p.installedVersion(o)):n.t("setup.pick_will_install");return{name:`${t?.displayName??d[o]?.displayName??o} ${e.gray(l)}`,value:o,checked:!0}}function ne(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function setupCommand(c){J=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:c[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),y=void 0!==c.oneMillion||void 0!==c.claudeOfficial||void 0!==c.desktopRegistry;let k=c.key?.trim();k||0!==u.length||y||!E()||(k=(await F.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const _=void 0!==c.oneMillion,h=void 0!==c.claudeOfficial;let b;if(h&&(b=parseOnOff(c.claudeOfficial),void 0===b))return U(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const v=void 0!==c.desktopRegistry;let x;if(v&&(x=parseOnOff(c.desktopRegistry),void 0===x))return U(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const C=h||v,j=Boolean(k||u.length>0),G={oneMillion:c.oneMillion,officialLogin:b,desktopRegistry:x,force:c.force};if(!j&&(_||C)&&$())return void le([..._?["codex"]:[],...C?["claude-desktop"]:[]],!1);if(!j&&(_||C)){if(_){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===c.oneMillion;r.setToolSetting("codex",f,o);const t=await g(e);m(o,t??void 0),H(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){U(n.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else U(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(C){const e=r.getApiKeyForTool("claude-desktop");e?await Z("claude-desktop",e,{...G,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(!j)return U(n.t("setup.usage")),void(process.exitCode=1);const S=$(),B=S?null:await l(k||u[0].apiKey,{save:!1}),D=[],Q=[];let se,re=0,pe=0;const de=new Set,ce=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of ce){if(!await X(e.label,e.apiKey)){pe+=1;continue}const o=await V(e.apiKey);!o.probed||z(o,e.need)?(o.probed||W(n.t("setup.probe_failed",{label:e.label})),D.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),de.add(e.tool)):(U(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),pe+=1)}const ue=!!k&&await X("--key",k);k&&!ue&&(se=w[J??"operation"]);const fe=k&&ue?await V(k):void 0;k&&fe&&!fe.probed&&W(n.t("setup.probe_failed",{label:"--key"})),!(k&&fe&&fe.probed)||fe.hasClaude||fe.hasGpt||fe.hasGrok||fe.hasGemini||(U(n.t("setup.key_no_family")),se=1);const me=Boolean(k)&&0===u.length&&!c.fromInstaller&&E();if(k&&fe&&void 0===se){const e=fe.hasClaude||fe.hasGpt||fe.hasGrok||fe.hasGemini,o=[{tool:"claude-code",capable:fe.hasClaude,skipMsg:n.t(ne()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:fe.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:fe.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:fe.hasClaude&&ne(),skipMsg:"",quiet:!0},{tool:"agy",capable:fe.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:e&&p.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:e&&p.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:e&&p.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const e of o)de.has(e.tool)||(e.capable?(!e.ask||S||me||await oe(e.tool))&&(D.push({tool:e.tool,apiKey:k,dedicated:!1}),de.add(e.tool)):e.quiet||W(e.skipMsg))}let ge,ye=c.install;if(me&&void 0===se&&D.length>0){const e=await async function(e,o){const t=function(e){return M(e).filter(e=>{const o=N(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return R.logError(`setup: app blocker ${e}`,o),!1}})}(e);console.log("");const{picked:l}=await F.prompt([{type:"checkbox",name:"picked",message:n.t("setup.pick_tools"),choices:[...e,...t].map(ae)}]);if(0===l.length)return console.log(n.t("setup.pick_none")),null;let i=!1===o?"configure":"install";return void 0===o&&(i=(await F.prompt([{type:"list",name:"mode",message:n.t("setup.pick_mode"),default:"install",choices:["install","configure","upgrade"].map(e=>({name:n.t(`setup.pick_mode_${e}`),value:e}))}])).mode),{tools:l.filter(o=>e.includes(o)),apps:l.filter(e=>t.includes(e)),mode:i}}(D.map(e=>e.tool),c.install);if(!e)return void(process.exitCode=w.cancelled);if("upgrade"===e.mode){const o=[...e.tools,...e.apps];for(const e of o.filter(e=>!ie(e)))W(n.t("setup.pick_upgrade_skip",{tool:d[e]?.displayName??e}));const t=o.filter(ie);return void(t.length>0&&await Y(t))}ye="install"===e.mode,ge=e.apps;const o=e.tools.filter(o=>"install"===e.mode||p.isToolInstalled(o)),t=e.tools.filter(e=>!o.includes(e));if(t.length>0&&W(n.t("setup.pick_configure_skip",{tools:t.map(e=>d[e].displayName).join(n.t("setup.list_separator"))})),D.splice(0,D.length,...D.filter(e=>o.includes(e.tool))),0===D.length)return}const ke=Boolean(k&&ue&&void 0===se);if(S)return le(D.filter(e=>!ee(e.tool)).map(e=>e.tool),D.length>0,D.filter(e=>ee(e.tool)).map(e=>e.tool)),void((pe>0||void 0!==se)&&(process.exitCode=se??w[J??"operation"]));const _e=D.filter(e=>!ee(e.tool)),he=ke||D.some(e=>e.dedicated),be=B?a().filter(e=>!D.some(o=>o.tool===e.tool)):[],we=!c.fromInstaller&&E();if((D.length>0||he)&&!c.fromInstaller&&!await A([..._e.map(e=>e.tool),...be.map(e=>e.tool)],{keyFile:he?O(r.getConfigDir(),"config.yaml"):void 0,installFirst:D.filter(e=>ee(e.tool)).map(e=>e.tool)}))return void(process.exitCode=w.cancelled);(D.length>0||he)&&s(),ke&&k&&r.setApiKey(k);for(const e of D)ee(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),Q.push({tool:e.tool,apiKey:e.apiKey})):await Z(e.tool,e.apiKey,{...G,takeOver:e.dedicated||we})?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),re+=1):(pe+=1,de.delete(e.tool));const ve=D.length>0||he?await i(be):[];if(void 0!==se)return Q.length>0&&te(Q.map(e=>e.tool)),void(process.exitCode=se);let xe=[];if(Q.length>0){const o=await async function(o,t,l){const i=o.map(e=>e.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||T()||(K()?a=!I():process.stdin.isTTY&&(console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of i)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return T()||console.log(e.gray(n.t("setup.install_all_hint",{cli:L}))),{still:i,applied:[],failed:[]}}const r=[];for(const o of i){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){R.logError(`setup: install ${o}`,e)}q(),p.isToolInstalled(o)||r.push(o)}const c=i.filter(e=>!r.includes(e));c.length>0&&console.log("");const u=[],f=[];for(const{tool:e,apiKey:t}of o.filter(e=>c.includes(e.tool)))await Z(e,t,l)?u.push(e):f.push(e);return{still:r,applied:u,failed:f}}(Q,ye,G);xe=o.still,re+=o.applied.length,pe+=o.failed.length;for(const e of[...xe,...o.failed])de.delete(e)}if(re>0){const t=[...de].filter(e=>!o(e)?.isInstalled&&!xe.includes(e)),l=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(re)});H("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),xe.length>0&&te(xe);for(const e of t){const o=p.ensureNativeOnPath(e);o&&H(n.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!T()&&"1"!==P("PATH_HINT_BY_CALLER")){const o=s.map(e=>d[e].command).join(" / ");console.log(e.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}}0===re&&xe.length>0&&te(xe),pe>0&&(U(n.t("setup.failed_summary",{count:String(pe)})),T()||console.error(`${L} setup --key ${n.t("errors.key_placeholder")}`)),await t([...de,...ve],{apps:{install:await installMissingApps([...de],ye,ge)}}),(pe>0||0===re&&0===xe.length)&&(process.exitCode=w[J??"operation"])}
@@ -1,3 +1,4 @@
1
+ import { type SpawnSyncReturns } from 'child_process';
1
2
  import { type LocalPackageInfo, type UpdateCheckResult } from '../commands/update.js';
2
3
  export declare const INSTALL_RETRY_INTERVAL_MS: number;
3
4
  export declare const INSTALL_TIMEOUT_MS = 45000;
@@ -38,6 +39,8 @@ export declare function shouldSkipStartupUpdate(args: string[], env?: NodeJS.Pro
38
39
  * npm-cli.js under the current directory (MODULE_NOT_FOUND, seen on Windows 11 with Node 24.11.1).
39
40
  */
40
41
  export declare function windowsShellCommand(command: string, args: string[]): string;
42
+ /** Exported for the Windows regression test (12e1591: .cmd must start through a shell). */
43
+ export declare const defaultInstallRunner: (command: string, args: string[]) => SpawnSyncReturns<Buffer>;
41
44
  /**
42
45
  * An update killed between its two renames leaves no package folder, only `.cli-update-old-<pid>`: put that
43
46
  * one back. The CLI itself can't start in that state, so this helps whatever runs next from somewhere else
@@ -1 +1 @@
1
- import{chmodSync as e,copyFileSync as t,existsSync as r,lstatSync as o,mkdirSync as n,readdirSync as s,readFileSync as a,readlinkSync as i,renameSync as l,rmSync as c,symlinkSync as u,writeFileSync as p}from"fs";import{homedir as d}from"os";import{basename as m,dirname as f,join as h,sep as g}from"path";import{spawnSync as _}from"child_process";import y from"chalk";import{checkForUpdate as v,readLocalPackage as x,UPDATE_SOURCES as w}from"../commands/update.js";import{i18n as k}from"./i18n.js";import{isColorEnabled as S}from"./runtime-options.js";import{logger as b}from"../utils/logger.js";import{isHelpRequest as $}from"./cli-help.js";import{brand as I,brandEnvName as E}from"./brand.js";import{flushTelemetry as P,track as j}from"./telemetry.js";import{processAlive as N}from"../utils/process-alive.js";import{endedByInterrupt as A}from"./signals.js";export const INSTALL_RETRY_INTERVAL_MS=36e5;export const INSTALL_TIMEOUT_MS=45e3;function T(e,t){return S()?e(t):t}export function resolveUpdateCachePath(e=process.env){const t=e[E("CONFIG_DIR")]?.trim();if(t)return h(t,"update-state.json");const r=e[E("TEST_HOME")]?.trim();return h(r||d(),I().configDirName,"update-state.json")}export function isGlobalPackageInstall(e){return e.split(g).includes("node_modules")}export function isNpxExecution(e=process.env){return"exec"===e.npm_command||"npx"===e.npm_lifecycle_event}export function isPnpmGlobalInstall(e){return e.includes(`${g}.pnpm${g}`)||e.includes(`${g}pnpm${g}global${g}`)}export function resolveNpmGlobalPrefix(e){const t=`${g}node_modules${g}`,r=e.indexOf(t);if(r<0)return null;const o=e.slice(0,r);return o.endsWith(`${g}lib`)?f(o):o}export function shouldSkipStartupUpdate(e,t=process.env){return"1"===t[E("SKIP_AUTO_UPDATE")]||"1"===t[E("DISABLE_AUTO_UPDATE")]||(!(!["--json","--non-interactive","--dry-run","--help","-h","--version","-v"].some(t=>e.includes(t))&&!$(e))||e.includes("update")||e.includes("completion"))}function U(t,r,o,s,a){try{n(f(t),{recursive:!0,mode:448});const i=`${t}.tmp-${process.pid}`,c={package_name:r,checked_at:o,latest:s.latest,source:s.source,registry:s.registry,errors:s.errors,...void 0===a?{}:{install_attempted_at:a,install_attempted_version:s.latest||void 0}};p(i,JSON.stringify(c),{encoding:"utf-8",mode:384}),l(i,t),e(t,384)}catch(e){b.warn("Failed to persist update check cache:",e)}}export function windowsShellCommand(e,t){return[e,...t.map(e=>`"${e}"`)].join(" ")}const D=(e,t)=>{const r={stdio:"inherit",timeout:45e3,killSignal:"SIGTERM"};return"win32"===process.platform?_(windowsShellCommand(e,t),{...r,shell:!0}):_(e,t,r)},O=(e,t)=>_(process.execPath,[process.argv[1],...e],{stdio:"inherit",env:t}),R="-update-";function C(e,t){const r=`.${t}${R}`;return s(e).filter(e=>e.startsWith(r)).map(t=>{const o=/^(old-)?(\d+)$/.exec(t.slice(r.length));return{path:h(e,t),old:Boolean(o?.[1]),pid:o?Number(o[2]):null}})}export function recoverInterruptedSwap(e){try{if(r(e)||!r(f(e)))return!1;const t=C(f(e),m(e)).filter(e=>e.old&&null!==e.pid&&!N(e.pid)).filter(e=>r(h(e.path,"package.json"))).sort((e,t)=>o(t.path).mtimeMs-o(e.path).mtimeMs);return 0!==t.length&&(M(t[0].path,e),!0)}catch(e){return b.warn("Failed to restore the package an interrupted update moved aside:",e),!1}}function M(e,t){for(let r=0;;r++)try{return void l(e,t)}catch(e){const t=e.code;if(r>=9||"EPERM"!==t&&"EACCES"!==t&&"EBUSY"!==t)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,200)}}export function swapStagedPackage(e,s,l,p,d){const g=p.split("/"),_=[h(e,"node_modules",...g),h(e,"lib","node_modules",...g)].find(e=>r(h(e,"package.json")));if(!_)return!1;const y=JSON.parse(a(h(_,"package.json"),"utf-8"));if(y.version!==d)return!1;recoverInterruptedSwap(l);const v=h(f(l),`.${m(l)}${R}old-${process.pid}`),x=r(l);x&&M(l,v);try{M(_,l)}catch(e){throw x&&M(v,l),e}c(v,{recursive:!0,force:!0,maxRetries:3});const w="string"==typeof y.bin?[g[g.length-1]]:Object.keys(y.bin||{});for(const[r,a]of[[h(e,"bin"),h(s,"bin")],[e,s]])for(const e of w.flatMap(e=>["",".cmd",".ps1"].map(t=>e+t))){const s=h(r,e),l=h(a,e),c=o(s,{throwIfNoEntry:!1});if(!o(l,{throwIfNoEntry:!1})&&c&&!c.isDirectory())try{n(a,{recursive:!0}),c.isSymbolicLink()?u(i(s),l):t(s,l)}catch(e){b.warn("Failed to restore command shim:",e)}}return!0}export async function runStartupUpdate(e,t={}){const o=t.env||process.env,n=t.localPackage||x(),s=t.globalInstall??isGlobalPackageInstall(n.root),i=t.npx??isNpxExecution(o);if(!s||i||shouldSkipStartupUpdate(e,o))return{status:"skipped",handled:!1,source:null};const l=t.now??Date.now(),u=t.cachePath||resolveUpdateCachePath(o),p=function(e,t){try{if(!r(e))return null;const o=JSON.parse(a(e,"utf-8"));return o.package_name===t.name&&Number.isFinite(o.checked_at)?o:null}catch{return null}}(u,n);let d=function(e,t,r){if(!e||e.latest)return null;const o=r-e.checked_at;if(o<0||o>=6e5)return null;const n=Array.isArray(e.errors)?e.errors:[];return{current:t.version,latest:null,up_to_date:null,source:e.source,registry:e.registry,errors:n,error:n.map(e=>`${e.source}: ${e.error}`).join("; ")||"unknown"}}(p,n,l),_=null;if(d||(d=await v({localPackage:n,fetchFn:t.fetchFn}),d.latest&&p?.install_attempted_version===d.latest&&Number.isFinite(p.install_attempted_at)&&(_=p.install_attempted_at),U(u,n.name,l,d,_??void 0)),!d.latest)return{status:"unavailable",handled:!1,source:null};if(d.up_to_date)return{status:"current",handled:!1,source:d.source};if(null!==_&&l>=_&&l-_<36e5)return{status:"update_failed",handled:!1,source:d.source};const S=t.output||console.log,b=t.errorOutput||console.error,$=t.installRunner||D,I=isPnpmGlobalInstall(n.root),M=I?"win32"===process.platform?"pnpm.cmd":"pnpm":"win32"===process.platform?"npm.cmd":"npm",F=I?null:resolveNpmGlobalPrefix(n.root),G=n.root,L=F&&G.endsWith(g+n.name.split("/").join(g))?h(f(G),`.${m(G)}${R}${process.pid}`):null;L&&(recoverInterruptedSwap(G),function(e,t){try{for(const r of C(e,t))null!==r.pid&&r.pid!==process.pid&&N(r.pid)||c(r.path,{recursive:!0,force:!0})}catch{}}(f(G),m(G))),U(u,n.name,l,d,l),S(T(y.cyan,k.t("update.auto_installing",{version:d.latest})));const B={from:n.version,to:d.latest,staged:Boolean(L)};j("self-update","start",{detail:B}),await P();const J=[...d.registry?[d.registry]:[],...w.map(e=>e.registry).filter(e=>e!==d.registry)],W=Date.now();let K=null,Y="unknown",H=0;for(const e of J){if(Date.now()-W>=45e3)break;H++;const t=$(M,I?["add","--global",`${n.name}@${d.latest}`,"--registry",e]:["install","--global",...L?["--prefix",L]:F?["--prefix",F]:[],`${n.name}@${d.latest}`,"--registry",e,"--no-audit","--no-fund","--fetch-timeout=15000","--fetch-retries=1","--fetch-retry-mintimeout=1000","--fetch-retry-maxtimeout=3000"]);if(0===t.status){if(!L){K=e;break}try{if(!swapStagedPackage(L,F,G,n.name,d.latest)){Y="staged install incomplete";continue}K=e;break}catch(e){Y=e instanceof Error?e.message:String(e);break}finally{c(L,{recursive:!0,force:!0,maxRetries:3})}}else if(Y=t.error?.message||`exit ${t.status??"unknown"}`,L&&c(L,{recursive:!0,force:!0,maxRetries:3}),A(t)){Y="interrupted";break}}const V=Date.now()-W;if(j("self-update",K?"ok":V>=45e3?"timeout":"fail",{duration_ms:V,...K?{}:{error:Y},detail:{...B,attempts:H,registry:K}}),await P(),!K)return b(T(y.yellow,k.t("update.auto_failed",{error:Y}))),{status:"update_failed",handled:!1,source:d.source};S(T(y.green,k.t("update.auto_installed",{version:d.latest})));const q=(t.reexecRunner||O)(e,{...o,[E("SKIP_AUTO_UPDATE")]:"1"});return q.error?(b(T(y.yellow,k.t("update.reexec_failed",{error:q.error.message}))),{status:"update_failed",handled:!1,source:d.source}):(process.exitCode=q.status??1,j("command","skip",{duration_ms:Date.now()-W,detail:{reason:"self-update-rerun",exit_code:process.exitCode}}),{status:"reexecuted",handled:!0,source:d.source})}
1
+ import{chmodSync as e,copyFileSync as t,existsSync as r,lstatSync as n,mkdirSync as o,readdirSync as s,readFileSync as a,readlinkSync as i,renameSync as l,rmSync as c,symlinkSync as u,writeFileSync as p}from"fs";import{homedir as d}from"os";import{basename as m,dirname as f,join as h,sep as g}from"path";import{spawnSync as _}from"child_process";import y from"chalk";import{checkForUpdate as v,readLocalPackage as x,UPDATE_SOURCES as w}from"../commands/update.js";import{i18n as k}from"./i18n.js";import{isColorEnabled as S}from"./runtime-options.js";import{logger as b}from"../utils/logger.js";import{isHelpRequest as $}from"./cli-help.js";import{brand as I,brandEnvName as E}from"./brand.js";import{flushTelemetry as P,track as j}from"./telemetry.js";import{processAlive as N}from"../utils/process-alive.js";import{endedByInterrupt as A}from"./signals.js";export const INSTALL_RETRY_INTERVAL_MS=36e5;export const INSTALL_TIMEOUT_MS=45e3;function T(e,t){return S()?e(t):t}export function resolveUpdateCachePath(e=process.env){const t=e[E("CONFIG_DIR")]?.trim();if(t)return h(t,"update-state.json");const r=e[E("TEST_HOME")]?.trim();return h(r||d(),I().configDirName,"update-state.json")}export function isGlobalPackageInstall(e){return e.split(g).includes("node_modules")}export function isNpxExecution(e=process.env){return"exec"===e.npm_command||"npx"===e.npm_lifecycle_event}export function isPnpmGlobalInstall(e){return e.includes(`${g}.pnpm${g}`)||e.includes(`${g}pnpm${g}global${g}`)}export function resolveNpmGlobalPrefix(e){const t=`${g}node_modules${g}`,r=e.indexOf(t);if(r<0)return null;const n=e.slice(0,r);return n.endsWith(`${g}lib`)?f(n):n}export function shouldSkipStartupUpdate(e,t=process.env){return"1"===t[E("SKIP_AUTO_UPDATE")]||"1"===t[E("DISABLE_AUTO_UPDATE")]||(!(!["--json","--non-interactive","--dry-run","--help","-h","--version","-v"].some(t=>e.includes(t))&&!$(e))||e.includes("update")||e.includes("completion"))}function R(t,r,n,s,a){try{o(f(t),{recursive:!0,mode:448});const i=`${t}.tmp-${process.pid}`,c={package_name:r,checked_at:n,latest:s.latest,source:s.source,registry:s.registry,errors:s.errors,...void 0===a?{}:{install_attempted_at:a,install_attempted_version:s.latest||void 0}};p(i,JSON.stringify(c),{encoding:"utf-8",mode:384}),l(i,t),e(t,384)}catch(e){b.warn("Failed to persist update check cache:",e)}}export function windowsShellCommand(e,t){return[e,...t.map(e=>`"${e}"`)].join(" ")}export const defaultInstallRunner=(e,t)=>{const r={stdio:"inherit",timeout:45e3,killSignal:"SIGTERM"};return"win32"===process.platform?_(windowsShellCommand(e,t),{...r,shell:!0}):_(e,t,r)};const U=(e,t)=>_(process.execPath,[process.argv[1],...e],{stdio:"inherit",env:t}),D="-update-";function O(e,t){const r=`.${t}${D}`;return s(e).filter(e=>e.startsWith(r)).map(t=>{const n=/^(old-)?(\d+)$/.exec(t.slice(r.length));return{path:h(e,t),old:Boolean(n?.[1]),pid:n?Number(n[2]):null}})}export function recoverInterruptedSwap(e){try{if(r(e)||!r(f(e)))return!1;const t=O(f(e),m(e)).filter(e=>e.old&&null!==e.pid&&!N(e.pid)).filter(e=>r(h(e.path,"package.json"))).sort((e,t)=>n(t.path).mtimeMs-n(e.path).mtimeMs);return 0!==t.length&&(C(t[0].path,e),!0)}catch(e){return b.warn("Failed to restore the package an interrupted update moved aside:",e),!1}}function C(e,t){for(let r=0;;r++)try{return void l(e,t)}catch(e){const t=e.code;if(r>=9||"EPERM"!==t&&"EACCES"!==t&&"EBUSY"!==t)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,200)}}export function swapStagedPackage(e,s,l,p,d){const g=p.split("/"),_=[h(e,"node_modules",...g),h(e,"lib","node_modules",...g)].find(e=>r(h(e,"package.json")));if(!_)return!1;const y=JSON.parse(a(h(_,"package.json"),"utf-8"));if(y.version!==d)return!1;recoverInterruptedSwap(l);const v=h(f(l),`.${m(l)}${D}old-${process.pid}`),x=r(l);x&&C(l,v);try{C(_,l)}catch(e){throw x&&C(v,l),e}c(v,{recursive:!0,force:!0,maxRetries:3});const w="string"==typeof y.bin?[g[g.length-1]]:Object.keys(y.bin||{});for(const[r,a]of[[h(e,"bin"),h(s,"bin")],[e,s]])for(const e of w.flatMap(e=>["",".cmd",".ps1"].map(t=>e+t))){const s=h(r,e),l=h(a,e),c=n(s,{throwIfNoEntry:!1});if(!n(l,{throwIfNoEntry:!1})&&c&&!c.isDirectory())try{o(a,{recursive:!0}),c.isSymbolicLink()?u(i(s),l):t(s,l)}catch(e){b.warn("Failed to restore command shim:",e)}}return!0}export async function runStartupUpdate(e,t={}){const n=t.env||process.env,o=t.localPackage||x(),s=t.globalInstall??isGlobalPackageInstall(o.root),i=t.npx??isNpxExecution(n);if(!s||i||shouldSkipStartupUpdate(e,n))return{status:"skipped",handled:!1,source:null};const l=t.now??Date.now(),u=t.cachePath||resolveUpdateCachePath(n),p=function(e,t){try{if(!r(e))return null;const n=JSON.parse(a(e,"utf-8"));return n.package_name===t.name&&Number.isFinite(n.checked_at)?n:null}catch{return null}}(u,o);let d=function(e,t,r){if(!e||e.latest)return null;const n=r-e.checked_at;if(n<0||n>=6e5)return null;const o=Array.isArray(e.errors)?e.errors:[];return{current:t.version,latest:null,up_to_date:null,source:e.source,registry:e.registry,errors:o,error:o.map(e=>`${e.source}: ${e.error}`).join("; ")||"unknown"}}(p,o,l),_=null;if(d||(d=await v({localPackage:o,fetchFn:t.fetchFn}),d.latest&&p?.install_attempted_version===d.latest&&Number.isFinite(p.install_attempted_at)&&(_=p.install_attempted_at),R(u,o.name,l,d,_??void 0)),!d.latest)return{status:"unavailable",handled:!1,source:null};if(d.up_to_date)return{status:"current",handled:!1,source:d.source};if(null!==_&&l>=_&&l-_<36e5)return{status:"update_failed",handled:!1,source:d.source};const S=t.output||console.log,b=t.errorOutput||console.error,$=t.installRunner||defaultInstallRunner,I=isPnpmGlobalInstall(o.root),C=I?"win32"===process.platform?"pnpm.cmd":"pnpm":"win32"===process.platform?"npm.cmd":"npm",M=I?null:resolveNpmGlobalPrefix(o.root),F=o.root,G=M&&F.endsWith(g+o.name.split("/").join(g))?h(f(F),`.${m(F)}${D}${process.pid}`):null;G&&(recoverInterruptedSwap(F),function(e,t){try{for(const r of O(e,t))null!==r.pid&&r.pid!==process.pid&&N(r.pid)||c(r.path,{recursive:!0,force:!0})}catch{}}(f(F),m(F))),R(u,o.name,l,d,l),S(T(y.cyan,k.t("update.auto_installing",{version:d.latest})));const L={from:o.version,to:d.latest,staged:Boolean(G)};j("self-update","start",{detail:L}),await P();const B=[...d.registry?[d.registry]:[],...w.map(e=>e.registry).filter(e=>e!==d.registry)],J=Date.now();let W=null,K="unknown",Y=0;for(const e of B){if(Date.now()-J>=45e3)break;Y++;const t=$(C,I?["add","--global",`${o.name}@${d.latest}`,"--registry",e]:["install","--global",...G?["--prefix",G]:M?["--prefix",M]:[],`${o.name}@${d.latest}`,"--registry",e,"--no-audit","--no-fund","--fetch-timeout=15000","--fetch-retries=1","--fetch-retry-mintimeout=1000","--fetch-retry-maxtimeout=3000"]);if(0===t.status){if(!G){W=e;break}try{if(!swapStagedPackage(G,M,F,o.name,d.latest)){K="staged install incomplete";continue}W=e;break}catch(e){K=e instanceof Error?e.message:String(e);break}finally{c(G,{recursive:!0,force:!0,maxRetries:3})}}else if(K=t.error?.message||`exit ${t.status??"unknown"}`,G&&c(G,{recursive:!0,force:!0,maxRetries:3}),A(t)){K="interrupted";break}}const H=Date.now()-J;if(j("self-update",W?"ok":H>=45e3?"timeout":"fail",{duration_ms:H,...W?{}:{error:K},detail:{...L,attempts:Y,registry:W}}),await P(),!W)return b(T(y.yellow,k.t("update.auto_failed",{error:K}))),{status:"update_failed",handled:!1,source:d.source};S(T(y.green,k.t("update.auto_installed",{version:d.latest})));const V=(t.reexecRunner||U)(e,{...n,[E("SKIP_AUTO_UPDATE")]:"1"});return V.error?(b(T(y.yellow,k.t("update.reexec_failed",{error:V.error.message}))),{status:"update_failed",handled:!1,source:d.source}):(process.exitCode=V.status??1,j("command","skip",{duration_ms:Date.now()-J,detail:{reason:"self-update-rerun",exit_code:process.exitCode}}),{status:"reexecuted",handled:!0,source:d.source})}
@@ -11,8 +11,7 @@ export declare function autoCompactTokens(window: number, explicit?: number): nu
11
11
  /**
12
12
  * The models to add for `tool`. When the gateway publishes its client config
13
13
  * (`/api/platform/vibecode/config`) its lists come first — fields it leaves out keep
14
- * the built-in values, and Claude models only come from it when `models.json` lists
15
- * them too (so a model removed there, like Haiku for Codex, stays out); Codex also
14
+ * the built-in values; Codex never gets Claude models (they belong to Claude Code and Claude Desktop); Codex also
16
15
  * gets the `gemini` list, Grok Build only the `grok` list. Built-in entries the lists lack are added (see
17
16
  * `withBuiltInExtras`); a `hidden` row on the gateway keeps one out. Without the
18
17
  * config, the built-in list from `models.json` → `gatewayModels`. When the key's owner chose
@@ -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,...(l.claude??[]).filter(e=>e.id.startsWith("claude-")&&(s.get(e.id)??a.has(e.id)))]: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"],"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"}
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"}
@@ -1 +1 @@
1
- import{Command as e,Option as o}from"commander";import{readFileSync as s}from"fs";import{join as t,dirname as n}from"path";import{fileURLToPath as a}from"url";import{i18n as i}from"./i18n.js";import{wizard as r}from"./wizard.js";import{SUPPORTED_TOOLS as c}from"./tool-manager.js";import{DEFAULT_BASE_URL as l}from"./config.js";import{attachCommandHelp as p,helpConfiguration as m}from"./cli-help.js";import{langCommand as u,authCommand as d,doctorCommand as f,configCommand as g,statusCommand as x,refreshCommand as h}from"../commands/index.js";import{logsCommand as y}from"../commands/logs.js";import{completionCommand as $}from"../commands/completion.js";import{benchCommand as b}from"../commands/bench.js";import{updateCommand as k}from"../commands/update.js";import{upgradeCommand as _}from"../commands/upgrade.js";import{installCommand as w,listCommand as v}from"../commands/components.js";import{codexSessionsCommand as j}from"../commands/codex-sessions.js";import{sessionsExportCommand as O,sessionsListCommand as S,sessionsResumeCommand as A,sessionsShowCommand as E}from"../commands/sessions.js";import{setupCommand as G,DEDICATED_KEYS as z}from"../commands/setup.js";import{baseCommand as C}from"../commands/base.js";import{usageError as R}from"./errors.js";import{requireTerminal as B}from"./confirm.js";import{brand as I,brandEnv as L,CLI_NAME as N}from"./brand.js";const P=(I().gatewayAddresses[1]??I().gatewayAddresses[0]).url,T=(I().gatewayAddresses[2]??I().gatewayAddresses[0]).url;function U(e,o){return i.t(`help.${e}`,o)}function H(e,o){return{command:e,note:U(o)}}function K(e){const o=U(e);return o===`help.${e}`?"":o}function M(e,o=[]){return{when:K(`${e}.when`),prerequisites:K(`${e}.needs`).split("\n").filter(Boolean),alternatives:o.map(([e,o])=>H(e,o))}}function q(e){return e.helpCommand("help [command]",U("help_command"))}export function buildProgram(){const I=new e;I.name(`${N}`).summary(U("root.summary")).description(U("root.description")).configureHelp(m()).allowExcessArguments(!0).optionsGroup(U("group.global_options")).helpOption("-h, --help",U("global.help")).version(function(){try{const e=n(a(import.meta.url));return JSON.parse(s(t(e,"../../package.json"),"utf-8")).version}catch{return"1.0.0"}}(),"-v, --version",U("global.version")).option("--base <url>",U("global.base")).option("--non-interactive",U("global.non_interactive")).option("--json",U("global.json")).option("-y, --yes",U("global.yes")).option("--dry-run",U("global.dry_run")).option("--no-color",U("global.no_color")),I.configureOutput({writeErr:()=>{},outputError:()=>{}}),I.showSuggestionAfterError(),I.exitOverride(e=>{throw e}),I.commandsGroup(U("group.configure"));const K=I.command("setup").summary(U("setup.summary")).description(U("setup.description")).option("--key <key>",U("setup.opt.key"));for(const e of z){const s=new o(`--${e.option} <key>`,U(`setup.opt.${e.option}`));e.hidden&&s.hideHelp(),K.addOption(s)}K.option("--1m",U("setup.opt.one_m")).option("--no-1m",U("setup.opt.no_one_m")).option("--claude-official <on|off>",U("setup.opt.claude_official")).option("--desktop-registry <on|off>",U("setup.opt.desktop_registry")).option("--force",U("setup.opt.force")).option("--install",U("setup.opt.install")).option("--no-install",U("setup.opt.no_install")).option("--all",U("setup.opt.all")).action(async e=>{e.key||z.some(o=>e[o.option])||(e.key=L("SETUP_KEY")?.trim()||void 0,e.fromInstaller=Boolean(e.key));const o=Boolean(e.key||z.some(o=>e[o.option])),s=void 0!==e["1m"]||void 0!==e.claudeOfficial||void 0!==e.desktopRegistry,t=i.t("errors.key_placeholder");if(!o&&!s)throw R(i.t("setup.usage"),`${N} setup --key ${t}`,"missing_key");if(void 0!==e.claudeOfficial&&!["on","off"].includes(String(e.claudeOfficial).toLowerCase()))throw R(i.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)}),`${N} setup --claude-official on|off`,"invalid_value");if(void 0!==e.desktopRegistry&&!["on","off"].includes(String(e.desktopRegistry).toLowerCase()))throw R(i.t("setup.desktop_registry_invalid",{value:String(e.desktopRegistry)}),`${N} setup --desktop-registry on|off`,"invalid_value");await G({key:e.key,...Object.fromEntries(z.map(o=>[o.option,e[o.option]])),all:e.all,oneMillion:e["1m"],claudeOfficial:e.claudeOfficial,desktopRegistry:e.desktopRegistry,force:e.force,install:e.install,fromInstaller:e.fromInstaller})}),p(K,{...M("setup",[[`${N} init`,"setup.alt.init"],[`${N} config <tool>`,"setup.alt.config"],[`${N} auth <key>`,"setup.alt.auth"]]),sections:[{title:U("setup.autodetect_title"),rows:[["Claude",U("setup.autodetect.claude")],["GPT",U("setup.autodetect.gpt")],["Grok",U("setup.autodetect.grok")],["Gemini",U("setup.autodetect.gemini")],[U("setup.autodetect.any_label"),U("setup.autodetect.any")]]}],examples:[H(`${N} setup --key sk-xxx`,"setup.ex.key"),H(`${N} setup --install --key sk-xxx`,"setup.ex.install"),H(`${N} setup --claudekey sk-a --codexkey sk-b --agykey sk-g`,"setup.ex.split"),H(`${N} setup --force --key sk-xxx`,"setup.ex.force"),H(`${N} setup --base ${P} --key sk-xxx`,"setup.ex.base")]});const D=I.command("init").summary(U("init.summary")).description(U("init.description")).action(async()=>{B(),await r.runFirstTimeSetup()});p(D,{...M("init",[[`${N} setup --key <key>`,"init.alt.setup"],[`${N}`,"init.alt.menu"]]),examples:[H(`${N} init`,"init.ex.run"),H(`${N} init --base ${P}`,"init.ex.base"),H(`${N}`,"init.ex.menu")]});const F=I.command("auth").summary(U("auth.summary")).description(U("auth.description")).argument("[token]",U("auth.arg.token")).action(async e=>{const o=[];e&&o.push(e),await d(o)});q(F);const J=F.command("revoke").description(U("auth.revoke")).action(async()=>{await d(["revoke"])});p(J,{examples:[H(`${N} auth revoke`,"auth.ex.revoke_ask"),H(`${N} auth revoke --yes`,"auth.ex.revoke")]});const Y=F.command("reload <tool>").description(U("auth.reload")).action(async e=>{await d(["reload",e])});p(Y,{examples:[H(`${N} auth reload claude-code`,"auth.ex.reload"),H(`${N} auth reload claude-code --json`,"auth.ex.reload_json")]}),p(F,{...M("auth",[[`${N} setup --key <key>`,"auth.alt.setup"]]),examples:[H(`${N} auth`,"auth.ex.prompt"),H(`${N} auth sk-xxx --non-interactive`,"auth.ex.save"),H(`${N} auth revoke --yes`,"auth.ex.revoke"),H(`${N} auth reload claude-code`,"auth.ex.reload")]});const Q=I.command("config").summary(U("config.summary")).description(U("config.description")).argument("[args...]",U("config.arg.args")).option("-f, --force",U("config.opt.force")).allowUnknownOption(!0).action(async(e=[],o={})=>{await g(o.force?[...e,"--force"]:e)});p(Q,{...M("config",[[`${N} setup --force --key <key>`,"config.alt.setup"],[`${N} status`,"config.alt.status"]]),sections:[{title:U("config.subcommands_title"),rows:[["<tool>",U("config.sub.tool")],["<tool> --force",U("config.sub.tool_force")],["<tool> --non-interactive",U("config.sub.tool_non_interactive")],["<tool> remove",U("config.sub.tool_remove")],["<tool> restore",U("config.sub.tool_restore")],["<tool> backups",U("config.sub.tool_backups")],["<tool> clear-model",U("config.sub.tool_clear_model")],["tool-model list",U("config.sub.tool_model_list")],["tool-model set <tool> [slot] <model>",U("config.sub.tool_model_set")],["tool-model clear <tool>",U("config.sub.tool_model_clear")],["profile list",U("config.sub.profile_list")],["profile create <name>",U("config.sub.profile_create")],["profile use <name>",U("config.sub.profile_use")],["profile delete <name>",U("config.sub.profile_delete")],["preset list",U("config.sub.preset_list")],["preset save <name>",U("config.sub.preset_save")],["preset use <name>",U("config.sub.preset_use")],["preset delete <name>",U("config.sub.preset_delete")],["backup list",U("config.sub.backup_list")],["backup create [label]",U("config.sub.backup_create")],["backup restore <name>",U("config.sub.backup_restore")]]},{title:U("config.tools_title"),rows:Object.values(c).filter(e=>!e.hidden).map(e=>[e.name,e.displayName])}],examples:[H(`${N} config codex`,"config.ex.menu"),H(`${N} config claude-code --force`,"config.ex.force"),H(`${N} config tool-model set codex gpt-6-astra`,"config.ex.tool_model"),H(`${N} config profile create work`,"config.ex.profile"),H(`${N} config codex remove`,"config.ex.remove")]});const V=I.command("base").summary(U("base.summary")).description(U("base.description")).argument("[target]",U("base.arg.target")).action(async e=>{await C(e)});p(V,{...M("base",[[`${N} doctor`,"base.alt.doctor"],[`${N} bench`,"base.alt.bench"]]),sections:[{title:U("base.targets_title"),rows:[[U("base.target.none_term"),U("base.target.none")],[U("base.target.index_term"),U("base.target.index")],[U("base.target.url_term"),U("base.target.url")],["auto",U("base.target.auto")],["default",U("base.target.default",{url:l})]]}],examples:[H(`${N} base`,"base.ex.list"),H(`${N} base auto`,"base.ex.auto"),H(`${N} base 2`,"base.ex.index"),H(`${N} base ${P}`,"base.ex.url"),H(`${N} base default`,"base.ex.default")]}),I.commandsGroup(U("group.diagnose"));const W=I.command("status").summary(U("status.summary")).description(U("status.description")).action(async()=>{await x()});p(W,{...M("status",[[`${N} doctor`,"status.alt.doctor"]]),examples:[H(`${N} status`,"status.ex.show"),H(`${N} status --json`,"status.ex.json")]});const X=I.command("doctor").summary(U("doctor.summary")).description(U("doctor.description")).option("--deep",U("doctor.opt.deep")).option("--report",U("doctor.opt.report")).action(async e=>{await f({deep:e.deep,report:e.report})});p(X,{...M("doctor",[[`${N} base auto`,"doctor.alt.base"],[`${N} logs tail`,"doctor.alt.logs"]]),examples:[H(`${N} doctor`,"doctor.ex.run"),H(`${N} doctor --deep`,"doctor.ex.deep"),H(`${N} doctor --report`,"doctor.ex.report")]});const Z=I.command("bench").summary(U("bench.summary")).description(U("bench.description")).option("--samples <n>",U("bench.opt.samples"),"5").option("--stream",U("bench.opt.stream")).option("--model <model>",U("bench.opt.model")).action(async e=>{const o=[];e.samples&&o.push("--samples",e.samples),e.stream&&o.push("--stream"),e.model&&o.push("--model",e.model),await b(o)});p(Z,{...M("bench",[[`${N} base`,"bench.alt.base"]]),examples:[H(`${N} bench`,"bench.ex.run"),H(`${N} bench --samples 3`,"bench.ex.samples"),H(`${N} bench --stream`,"bench.ex.stream"),H(`${N} bench --stream --model gpt-6-astra`,"bench.ex.stream_model"),H(`${N} bench --json`,"bench.ex.json")]});const ee=I.command("logs").summary(U("logs.summary")).description(U("logs.description")).argument("[action]",U("logs.arg.action")).argument("[file]",U("logs.arg.file")).action(async(e,o)=>{const s=[];e&&s.push(e),o&&s.push(o),await y(s)});p(ee,{...M("logs",[[`${N} doctor`,"logs.alt.doctor"]]),sections:[{title:U("logs.actions_title"),rows:[["list",U("logs.action.list")],["tail [file]",U("logs.action.tail")],["path",U("logs.action.path")]]}],examples:[H(`${N} logs`,"logs.ex.list"),H(`${N} logs tail`,"logs.ex.tail"),H(`${N} logs path`,"logs.ex.path")]}),I.commandsGroup(U("group.maintain"));const oe=I.command("list").summary(U("list.summary")).description(U("list.description")).option("--refresh",U("list.opt.refresh")).action(async(e={})=>{await v({refresh:e.refresh})});p(oe,{...M("list",[[`${N} doctor`,"list.alt.doctor"]]),examples:[H(`${N} list`,"list.ex.all"),H(`${N} list --refresh`,"list.ex.refresh"),H(`${N} list --json`,"list.ex.json")]});const se=I.command("install").summary(U("install.summary")).description(U("install.description")).argument("<components...>",U("install.arg.components")).option("--force",U("install.opt.force")).action(async(e,o={})=>{await w(e,{force:o.force})});p(se,{...M("install",[[`${N} upgrade`,"install.alt.upgrade"],[`${N} setup --key ${i.t("errors.key_placeholder")}`,"install.alt.setup"]]),examples:[H(`${N} install node uv`,"install.ex.runtimes"),H(`${N} install claude-code codex`,"install.ex.clis"),H(`${N} install chatgpt`,"install.ex.app"),H(`${N} install uv --force`,"install.ex.force"),H(`${N} install node uv --yes --json`,"install.ex.json")]});const te=I.command("upgrade").summary(U("upgrade.summary")).description(U("upgrade.description")).argument("[tools...]",U("upgrade.arg.tools")).option("--force",U("upgrade.opt.force")).action(async(e=[],o={})=>{await _(e,{force:o.force})});p(te,{...M("upgrade",[[`${N} update`,"upgrade.alt.update"]]),examples:[H(`${N} upgrade`,"upgrade.ex.all"),H(`${N} upgrade codex agy`,"upgrade.ex.many"),H(`${N} upgrade claude-desktop`,"upgrade.ex.desktop"),H(`${N} upgrade chatgpt --force`,"upgrade.ex.force"),H(`${N} upgrade node`,"upgrade.ex.runtime")]});const ne=I.command("refresh").summary(U("refresh.summary")).description(U("refresh.description")).action(async()=>{await h()});p(ne,{...M("refresh",[[`${N} setup --key ${i.t("errors.key_placeholder")}`,"refresh.alt.setup"]]),examples:[H(`${N} refresh`,"refresh.ex.run"),H(`${N} refresh --base ${T}`,"refresh.ex.base")]});const ae=I.command("update").summary(U("update.summary")).description(U("update.description")).action(async()=>{await k()});p(ae,{...M("update",[[`${N} upgrade`,"update.alt.upgrade"]]),examples:[H(`${N} update`,"update.ex.check"),H(`${N} update --json`,"update.ex.json")]});const ie=I.command("codex").summary(U("codex.summary")).description(U("codex.description"));q(ie);const re=ie.command("sessions").summary(U("codex_sessions.summary")).description(U("codex_sessions.description")).option("--to <provider>",U("codex_sessions.opt.to")).option("--undo <dir>",U("codex_sessions.opt.undo")).action(async e=>{await j(e)});p(ie,{...M("codex"),examples:[H(`${N} codex sessions`,"codex_sessions.ex.move"),H(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]}),p(re,{...M("codex_sessions",[[`${N} codex sessions --undo <dir>`,"codex_sessions.alt.undo"]]),examples:[H(`${N} codex sessions`,"codex_sessions.ex.move"),H(`${N} codex sessions --to custom`,"codex_sessions.ex.to"),H(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]});const ce=I.command("sessions").summary(U("sessions.summary")).description(U("sessions.description"));q(ce);const le=ce.command("list",{isDefault:!0}).description(U("sessions.list")).option("--tool <tool>",U("sessions.opt.tool")).option("--dir <path>",U("sessions.opt.dir")).option("--here",U("sessions.opt.here")).option("-n, --limit <count>",U("sessions.opt.limit")).option("--all",U("sessions.opt.all")).action(async e=>{await S(e)}),pe=ce.command("show <id>").description(U("sessions.show")).option("-m, --messages <count>",U("sessions.opt.messages")).action(async(e,o)=>{await E(e,o)}),me=ce.command("resume <id>").description(U("sessions.resume")).option("--run",U("sessions.opt.run")).action(async(e,o)=>{await A(e,o)}),ue=ce.command("export <ids...>").description(U("sessions.export")).option("-o, --output <dir>",U("sessions.opt.output")).option("--tools",U("sessions.opt.tools")).action(async(e,o)=>{await O(e,o)});p(le,{examples:[H(`${N} sessions list`,"sessions.ex.list"),H(`${N} sessions list --tool codex`,"sessions.ex.codex"),H(`${N} sessions list --here --all`,"sessions.ex.here"),H(`${N} sessions list --json`,"sessions.ex.json")]}),p(pe,{examples:[H(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),H(`${N} sessions show 01a0f5fe -m 20`,"sessions.ex.show_more")]}),p(me,{examples:[H(`${N} sessions resume 01a0f5fe`,"sessions.ex.resume_print"),H(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume")]}),p(ue,{examples:[H(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export"),H(`${N} sessions export 01a0f5fe -o ./sessions --tools`,"sessions.ex.export_tools")]}),p(ce,{...M("sessions",[[`${N} codex sessions`,"sessions.alt.codex_sessions"]]),examples:[H(`${N} sessions`,"sessions.ex.list"),H(`${N} sessions --tool codex --here`,"sessions.ex.here"),H(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),H(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume"),H(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export")]});const de=I.command("lang").summary(U("lang.summary")).description(U("lang.description"));q(de);const fe=de.command("show").description(U("lang.show")).action(async()=>{await u(["show"])}),ge=de.command("set <locale>").description(U("lang.set")).action(async e=>{await u(["set",e])}),xe=[H(`${N} lang show`,"lang.ex.show"),H(`${N} lang set en_US`,"lang.ex.set_en"),H(`${N} lang set zh_CN`,"lang.ex.set_zh")];p(de,{...M("lang",[[`${N} enter lang`,"lang.alt.enter"]]),examples:xe}),p(fe,{examples:[xe[0],H(`${N} lang show --json`,"lang.ex.show_json")]}),p(ge,{examples:xe.slice(1)});const he=I.command("completion").summary(U("completion.summary")).description(U("completion.description")).argument("<shell>",U("completion.arg.shell")).action(async e=>{await $([e])});p(he,{...M("completion"),examples:[H(`${N} completion bash > ~/.${N}-completion.bash`,"completion.ex.bash"),H(`${N} completion zsh > ~/.${N}-completion.zsh`,"completion.ex.zsh"),H(`${N} completion fish > ~/.config/fish/completions/${N}.fish`,"completion.ex.fish")]});const ye=I.command("enter").summary(U("enter.summary")).description(U("enter.description")).argument("[option]",U("enter.arg.option")).action(async e=>{if(e&&!["lang","language","apikey","api-key","models"].includes(e)||B(),e)switch(e){case"lang":case"language":await r.configLanguage();break;case"apikey":case"api-key":await r.configApiKey();break;case"models":await r.configModels();break;default:await g([e])}else await r.run()});p(ye,{...M("enter",[[`${N}`,"enter.alt.menu"],[`${N} config <tool>`,"enter.alt.config"]]),sections:[{title:U("enter.options_title"),rows:[[U("enter.option.none_term"),U("enter.option.none")],["lang",U("enter.option.lang")],["apikey",U("enter.option.apikey")],["models",U("enter.option.models")],["<tool>",U("enter.option.tool")]]}],examples:[H(`${N} enter`,"enter.ex.menu"),H(`${N} enter models`,"enter.ex.models"),H(`${N} enter codex`,"enter.ex.tool")]}),q(I),I.action(async()=>{B(),await r.run()}),p(I,{examples:[H(`${N}`,"root.ex.menu"),H(`${N} setup --key sk-xxx`,"root.ex.setup"),H(`${N} doctor`,"root.ex.doctor"),H(`${N} base auto`,"root.ex.base"),H(`${N} config codex`,"root.ex.config")]});const $e=e=>{for(const o of e.commands)o.helpOption("-h, --help",U("global.help")),$e(o)};return $e(I),I}
1
+ import{Command as e,Option as o}from"commander";import{readFileSync as s}from"fs";import{join as t,dirname as n}from"path";import{fileURLToPath as a}from"url";import{i18n as i}from"./i18n.js";import{wizard as r}from"./wizard.js";import{SUPPORTED_TOOLS as c}from"./tool-manager.js";import{DEFAULT_BASE_URL as l}from"./config.js";import{attachCommandHelp as p,helpConfiguration as m}from"./cli-help.js";import{langCommand as u,authCommand as d,doctorCommand as f,configCommand as g,statusCommand as x,refreshCommand as h}from"../commands/index.js";import{logsCommand as y}from"../commands/logs.js";import{completionCommand as $}from"../commands/completion.js";import{benchCommand as b}from"../commands/bench.js";import{updateCommand as k}from"../commands/update.js";import{upgradeCommand as _}from"../commands/upgrade.js";import{installCommand as w,listCommand as v}from"../commands/components.js";import{codexSessionsCommand as j}from"../commands/codex-sessions.js";import{sessionsExportCommand as O,sessionsListCommand as S,sessionsResumeCommand as A,sessionsShowCommand as E}from"../commands/sessions.js";import{setupCommand as G,DEDICATED_KEYS as z}from"../commands/setup.js";import{baseCommand as C}from"../commands/base.js";import{usageError as R}from"./errors.js";import{requireTerminal as B}from"./confirm.js";import{brand as I,brandEnv as L,CLI_NAME as N}from"./brand.js";import{asksBeforeWriting as P}from"./write-plan.js";const T=(I().gatewayAddresses[1]??I().gatewayAddresses[0]).url,U=(I().gatewayAddresses[2]??I().gatewayAddresses[0]).url;function H(e,o){return i.t(`help.${e}`,o)}function K(e,o){return{command:e,note:H(o)}}function M(e){const o=H(e);return o===`help.${e}`?"":o}function q(e,o=[]){return{when:M(`${e}.when`),prerequisites:M(`${e}.needs`).split("\n").filter(Boolean),alternatives:o.map(([e,o])=>K(e,o))}}function D(e){return e.helpCommand("help [command]",H("help_command"))}export function buildProgram(){const I=new e;I.name(`${N}`).summary(H("root.summary")).description(H("root.description")).configureHelp(m()).allowExcessArguments(!0).optionsGroup(H("group.global_options")).helpOption("-h, --help",H("global.help")).version(function(){try{const e=n(a(import.meta.url));return JSON.parse(s(t(e,"../../package.json"),"utf-8")).version}catch{return"1.0.0"}}(),"-v, --version",H("global.version")).option("--base <url>",H("global.base")).option("--non-interactive",H("global.non_interactive")).option("--json",H("global.json")).option("-y, --yes",H("global.yes")).option("--dry-run",H("global.dry_run")).option("--no-color",H("global.no_color")),I.configureOutput({writeErr:()=>{},outputError:()=>{}}),I.showSuggestionAfterError(),I.exitOverride(e=>{throw e}),I.commandsGroup(H("group.configure"));const M=I.command("setup").summary(H("setup.summary")).description(H("setup.description")).option("--key <key>",H("setup.opt.key"));for(const e of z){const s=new o(`--${e.option} <key>`,H(`setup.opt.${e.option}`));e.hidden&&s.hideHelp(),M.addOption(s)}M.option("--1m",H("setup.opt.one_m")).option("--no-1m",H("setup.opt.no_one_m")).option("--claude-official <on|off>",H("setup.opt.claude_official")).option("--desktop-registry <on|off>",H("setup.opt.desktop_registry")).option("--force",H("setup.opt.force")).option("--install",H("setup.opt.install")).option("--no-install",H("setup.opt.no_install")).option("--all",H("setup.opt.all")).action(async e=>{e.key||z.some(o=>e[o.option])||(e.key=L("SETUP_KEY")?.trim()||void 0,e.fromInstaller=Boolean(e.key));const o=Boolean(e.key||z.some(o=>e[o.option])),s=void 0!==e["1m"]||void 0!==e.claudeOfficial||void 0!==e.desktopRegistry,t=i.t("errors.key_placeholder");if(!o&&!s&&!P())throw R(i.t("setup.usage"),`${N} setup --key ${t}`,"missing_key");if(void 0!==e.claudeOfficial&&!["on","off"].includes(String(e.claudeOfficial).toLowerCase()))throw R(i.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)}),`${N} setup --claude-official on|off`,"invalid_value");if(void 0!==e.desktopRegistry&&!["on","off"].includes(String(e.desktopRegistry).toLowerCase()))throw R(i.t("setup.desktop_registry_invalid",{value:String(e.desktopRegistry)}),`${N} setup --desktop-registry on|off`,"invalid_value");await G({key:e.key,...Object.fromEntries(z.map(o=>[o.option,e[o.option]])),all:e.all,oneMillion:e["1m"],claudeOfficial:e.claudeOfficial,desktopRegistry:e.desktopRegistry,force:e.force,install:e.install,fromInstaller:e.fromInstaller})}),p(M,{...q("setup",[[`${N} init`,"setup.alt.init"],[`${N} config <tool>`,"setup.alt.config"],[`${N} auth <key>`,"setup.alt.auth"]]),sections:[{title:H("setup.autodetect_title"),rows:[["Claude",H("setup.autodetect.claude")],["GPT",H("setup.autodetect.gpt")],["Grok",H("setup.autodetect.grok")],["Gemini",H("setup.autodetect.gemini")],[H("setup.autodetect.any_label"),H("setup.autodetect.any")]]}],examples:[K(`${N} setup --key sk-xxx`,"setup.ex.key"),K(`${N} setup --install --key sk-xxx`,"setup.ex.install"),K(`${N} setup --claudekey sk-a --codexkey sk-b --agykey sk-g`,"setup.ex.split"),K(`${N} setup --force --key sk-xxx`,"setup.ex.force"),K(`${N} setup --base ${T} --key sk-xxx`,"setup.ex.base")]});const F=I.command("init").summary(H("init.summary")).description(H("init.description")).action(async()=>{B(),await r.runFirstTimeSetup()});p(F,{...q("init",[[`${N} setup --key <key>`,"init.alt.setup"],[`${N}`,"init.alt.menu"]]),examples:[K(`${N} init`,"init.ex.run"),K(`${N} init --base ${T}`,"init.ex.base"),K(`${N}`,"init.ex.menu")]});const J=I.command("auth").summary(H("auth.summary")).description(H("auth.description")).argument("[token]",H("auth.arg.token")).action(async e=>{const o=[];e&&o.push(e),await d(o)});D(J);const Y=J.command("revoke").description(H("auth.revoke")).action(async()=>{await d(["revoke"])});p(Y,{examples:[K(`${N} auth revoke`,"auth.ex.revoke_ask"),K(`${N} auth revoke --yes`,"auth.ex.revoke")]});const Q=J.command("reload <tool>").description(H("auth.reload")).action(async e=>{await d(["reload",e])});p(Q,{examples:[K(`${N} auth reload claude-code`,"auth.ex.reload"),K(`${N} auth reload claude-code --json`,"auth.ex.reload_json")]}),p(J,{...q("auth",[[`${N} setup --key <key>`,"auth.alt.setup"]]),examples:[K(`${N} auth`,"auth.ex.prompt"),K(`${N} auth sk-xxx --non-interactive`,"auth.ex.save"),K(`${N} auth revoke --yes`,"auth.ex.revoke"),K(`${N} auth reload claude-code`,"auth.ex.reload")]});const V=I.command("config").summary(H("config.summary")).description(H("config.description")).argument("[args...]",H("config.arg.args")).option("-f, --force",H("config.opt.force")).allowUnknownOption(!0).action(async(e=[],o={})=>{await g(o.force?[...e,"--force"]:e)});p(V,{...q("config",[[`${N} setup --force --key <key>`,"config.alt.setup"],[`${N} status`,"config.alt.status"]]),sections:[{title:H("config.subcommands_title"),rows:[["<tool>",H("config.sub.tool")],["<tool> --force",H("config.sub.tool_force")],["<tool> --non-interactive",H("config.sub.tool_non_interactive")],["<tool> remove",H("config.sub.tool_remove")],["<tool> restore",H("config.sub.tool_restore")],["<tool> backups",H("config.sub.tool_backups")],["<tool> clear-model",H("config.sub.tool_clear_model")],["tool-model list",H("config.sub.tool_model_list")],["tool-model set <tool> [slot] <model>",H("config.sub.tool_model_set")],["tool-model clear <tool>",H("config.sub.tool_model_clear")],["profile list",H("config.sub.profile_list")],["profile create <name>",H("config.sub.profile_create")],["profile use <name>",H("config.sub.profile_use")],["profile delete <name>",H("config.sub.profile_delete")],["preset list",H("config.sub.preset_list")],["preset save <name>",H("config.sub.preset_save")],["preset use <name>",H("config.sub.preset_use")],["preset delete <name>",H("config.sub.preset_delete")],["backup list",H("config.sub.backup_list")],["backup create [label]",H("config.sub.backup_create")],["backup restore <name>",H("config.sub.backup_restore")]]},{title:H("config.tools_title"),rows:Object.values(c).filter(e=>!e.hidden).map(e=>[e.name,e.displayName])}],examples:[K(`${N} config codex`,"config.ex.menu"),K(`${N} config claude-code --force`,"config.ex.force"),K(`${N} config tool-model set codex gpt-6-astra`,"config.ex.tool_model"),K(`${N} config profile create work`,"config.ex.profile"),K(`${N} config codex remove`,"config.ex.remove")]});const W=I.command("base").summary(H("base.summary")).description(H("base.description")).argument("[target]",H("base.arg.target")).action(async e=>{await C(e)});p(W,{...q("base",[[`${N} doctor`,"base.alt.doctor"],[`${N} bench`,"base.alt.bench"]]),sections:[{title:H("base.targets_title"),rows:[[H("base.target.none_term"),H("base.target.none")],[H("base.target.index_term"),H("base.target.index")],[H("base.target.url_term"),H("base.target.url")],["auto",H("base.target.auto")],["default",H("base.target.default",{url:l})]]}],examples:[K(`${N} base`,"base.ex.list"),K(`${N} base auto`,"base.ex.auto"),K(`${N} base 2`,"base.ex.index"),K(`${N} base ${T}`,"base.ex.url"),K(`${N} base default`,"base.ex.default")]}),I.commandsGroup(H("group.diagnose"));const X=I.command("status").summary(H("status.summary")).description(H("status.description")).action(async()=>{await x()});p(X,{...q("status",[[`${N} doctor`,"status.alt.doctor"]]),examples:[K(`${N} status`,"status.ex.show"),K(`${N} status --json`,"status.ex.json")]});const Z=I.command("doctor").summary(H("doctor.summary")).description(H("doctor.description")).option("--deep",H("doctor.opt.deep")).option("--report",H("doctor.opt.report")).action(async e=>{await f({deep:e.deep,report:e.report})});p(Z,{...q("doctor",[[`${N} base auto`,"doctor.alt.base"],[`${N} logs tail`,"doctor.alt.logs"]]),examples:[K(`${N} doctor`,"doctor.ex.run"),K(`${N} doctor --deep`,"doctor.ex.deep"),K(`${N} doctor --report`,"doctor.ex.report")]});const ee=I.command("bench").summary(H("bench.summary")).description(H("bench.description")).option("--samples <n>",H("bench.opt.samples"),"5").option("--stream",H("bench.opt.stream")).option("--model <model>",H("bench.opt.model")).action(async e=>{const o=[];e.samples&&o.push("--samples",e.samples),e.stream&&o.push("--stream"),e.model&&o.push("--model",e.model),await b(o)});p(ee,{...q("bench",[[`${N} base`,"bench.alt.base"]]),examples:[K(`${N} bench`,"bench.ex.run"),K(`${N} bench --samples 3`,"bench.ex.samples"),K(`${N} bench --stream`,"bench.ex.stream"),K(`${N} bench --stream --model gpt-6-astra`,"bench.ex.stream_model"),K(`${N} bench --json`,"bench.ex.json")]});const oe=I.command("logs").summary(H("logs.summary")).description(H("logs.description")).argument("[action]",H("logs.arg.action")).argument("[file]",H("logs.arg.file")).action(async(e,o)=>{const s=[];e&&s.push(e),o&&s.push(o),await y(s)});p(oe,{...q("logs",[[`${N} doctor`,"logs.alt.doctor"]]),sections:[{title:H("logs.actions_title"),rows:[["list",H("logs.action.list")],["tail [file]",H("logs.action.tail")],["path",H("logs.action.path")]]}],examples:[K(`${N} logs`,"logs.ex.list"),K(`${N} logs tail`,"logs.ex.tail"),K(`${N} logs path`,"logs.ex.path")]}),I.commandsGroup(H("group.maintain"));const se=I.command("list").summary(H("list.summary")).description(H("list.description")).option("--refresh",H("list.opt.refresh")).action(async(e={})=>{await v({refresh:e.refresh})});p(se,{...q("list",[[`${N} doctor`,"list.alt.doctor"]]),examples:[K(`${N} list`,"list.ex.all"),K(`${N} list --refresh`,"list.ex.refresh"),K(`${N} list --json`,"list.ex.json")]});const te=I.command("install").summary(H("install.summary")).description(H("install.description")).argument("<components...>",H("install.arg.components")).option("--force",H("install.opt.force")).action(async(e,o={})=>{await w(e,{force:o.force})});p(te,{...q("install",[[`${N} upgrade`,"install.alt.upgrade"],[`${N} setup --key ${i.t("errors.key_placeholder")}`,"install.alt.setup"]]),examples:[K(`${N} install node uv`,"install.ex.runtimes"),K(`${N} install claude-code codex`,"install.ex.clis"),K(`${N} install chatgpt`,"install.ex.app"),K(`${N} install uv --force`,"install.ex.force"),K(`${N} install node uv --yes --json`,"install.ex.json")]});const ne=I.command("upgrade").summary(H("upgrade.summary")).description(H("upgrade.description")).argument("[tools...]",H("upgrade.arg.tools")).option("--force",H("upgrade.opt.force")).action(async(e=[],o={})=>{await _(e,{force:o.force})});p(ne,{...q("upgrade",[[`${N} update`,"upgrade.alt.update"]]),examples:[K(`${N} upgrade`,"upgrade.ex.all"),K(`${N} upgrade codex agy`,"upgrade.ex.many"),K(`${N} upgrade claude-desktop`,"upgrade.ex.desktop"),K(`${N} upgrade chatgpt --force`,"upgrade.ex.force"),K(`${N} upgrade node`,"upgrade.ex.runtime")]});const ae=I.command("refresh").summary(H("refresh.summary")).description(H("refresh.description")).action(async()=>{await h()});p(ae,{...q("refresh",[[`${N} setup --key ${i.t("errors.key_placeholder")}`,"refresh.alt.setup"]]),examples:[K(`${N} refresh`,"refresh.ex.run"),K(`${N} refresh --base ${U}`,"refresh.ex.base")]});const ie=I.command("update").summary(H("update.summary")).description(H("update.description")).action(async()=>{await k()});p(ie,{...q("update",[[`${N} upgrade`,"update.alt.upgrade"]]),examples:[K(`${N} update`,"update.ex.check"),K(`${N} update --json`,"update.ex.json")]});const re=I.command("codex").summary(H("codex.summary")).description(H("codex.description"));D(re);const ce=re.command("sessions").summary(H("codex_sessions.summary")).description(H("codex_sessions.description")).option("--to <provider>",H("codex_sessions.opt.to")).option("--undo <dir>",H("codex_sessions.opt.undo")).action(async e=>{await j(e)});p(re,{...q("codex"),examples:[K(`${N} codex sessions`,"codex_sessions.ex.move"),K(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]}),p(ce,{...q("codex_sessions",[[`${N} codex sessions --undo <dir>`,"codex_sessions.alt.undo"]]),examples:[K(`${N} codex sessions`,"codex_sessions.ex.move"),K(`${N} codex sessions --to custom`,"codex_sessions.ex.to"),K(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]});const le=I.command("sessions").summary(H("sessions.summary")).description(H("sessions.description"));D(le);const pe=le.command("list",{isDefault:!0}).description(H("sessions.list")).option("--tool <tool>",H("sessions.opt.tool")).option("--dir <path>",H("sessions.opt.dir")).option("--here",H("sessions.opt.here")).option("-n, --limit <count>",H("sessions.opt.limit")).option("--all",H("sessions.opt.all")).action(async e=>{await S(e)}),me=le.command("show <id>").description(H("sessions.show")).option("-m, --messages <count>",H("sessions.opt.messages")).action(async(e,o)=>{await E(e,o)}),ue=le.command("resume <id>").description(H("sessions.resume")).option("--run",H("sessions.opt.run")).action(async(e,o)=>{await A(e,o)}),de=le.command("export <ids...>").description(H("sessions.export")).option("-o, --output <dir>",H("sessions.opt.output")).option("--tools",H("sessions.opt.tools")).action(async(e,o)=>{await O(e,o)});p(pe,{examples:[K(`${N} sessions list`,"sessions.ex.list"),K(`${N} sessions list --tool codex`,"sessions.ex.codex"),K(`${N} sessions list --here --all`,"sessions.ex.here"),K(`${N} sessions list --json`,"sessions.ex.json")]}),p(me,{examples:[K(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),K(`${N} sessions show 01a0f5fe -m 20`,"sessions.ex.show_more")]}),p(ue,{examples:[K(`${N} sessions resume 01a0f5fe`,"sessions.ex.resume_print"),K(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume")]}),p(de,{examples:[K(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export"),K(`${N} sessions export 01a0f5fe -o ./sessions --tools`,"sessions.ex.export_tools")]}),p(le,{...q("sessions",[[`${N} codex sessions`,"sessions.alt.codex_sessions"]]),examples:[K(`${N} sessions`,"sessions.ex.list"),K(`${N} sessions --tool codex --here`,"sessions.ex.here"),K(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),K(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume"),K(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export")]});const fe=I.command("lang").summary(H("lang.summary")).description(H("lang.description"));D(fe);const ge=fe.command("show").description(H("lang.show")).action(async()=>{await u(["show"])}),xe=fe.command("set <locale>").description(H("lang.set")).action(async e=>{await u(["set",e])}),he=[K(`${N} lang show`,"lang.ex.show"),K(`${N} lang set en_US`,"lang.ex.set_en"),K(`${N} lang set zh_CN`,"lang.ex.set_zh")];p(fe,{...q("lang",[[`${N} enter lang`,"lang.alt.enter"]]),examples:he}),p(ge,{examples:[he[0],K(`${N} lang show --json`,"lang.ex.show_json")]}),p(xe,{examples:he.slice(1)});const ye=I.command("completion").summary(H("completion.summary")).description(H("completion.description")).argument("<shell>",H("completion.arg.shell")).action(async e=>{await $([e])});p(ye,{...q("completion"),examples:[K(`${N} completion bash > ~/.${N}-completion.bash`,"completion.ex.bash"),K(`${N} completion zsh > ~/.${N}-completion.zsh`,"completion.ex.zsh"),K(`${N} completion fish > ~/.config/fish/completions/${N}.fish`,"completion.ex.fish")]});const $e=I.command("enter").summary(H("enter.summary")).description(H("enter.description")).argument("[option]",H("enter.arg.option")).action(async e=>{if(e&&!["lang","language","apikey","api-key","models"].includes(e)||B(),e)switch(e){case"lang":case"language":await r.configLanguage();break;case"apikey":case"api-key":await r.configApiKey();break;case"models":await r.configModels();break;default:await g([e])}else await r.run()});p($e,{...q("enter",[[`${N}`,"enter.alt.menu"],[`${N} config <tool>`,"enter.alt.config"]]),sections:[{title:H("enter.options_title"),rows:[[H("enter.option.none_term"),H("enter.option.none")],["lang",H("enter.option.lang")],["apikey",H("enter.option.apikey")],["models",H("enter.option.models")],["<tool>",H("enter.option.tool")]]}],examples:[K(`${N} enter`,"enter.ex.menu"),K(`${N} enter models`,"enter.ex.models"),K(`${N} enter codex`,"enter.ex.tool")]}),D(I),I.action(async()=>{B(),await r.run()}),p(I,{examples:[K(`${N}`,"root.ex.menu"),K(`${N} setup --key sk-xxx`,"root.ex.setup"),K(`${N} doctor`,"root.ex.doctor"),K(`${N} base auto`,"root.ex.base"),K(`${N} config codex`,"root.ex.config")]});const be=e=>{for(const o of e.commands)o.helpOption("-h, --help",H("global.help")),be(o)};return be(I),I}
@@ -39,6 +39,11 @@ export declare function telemetryPending(): boolean;
39
39
  export declare function maskHome(text: string): string;
40
40
  /** API keys anywhere in a text (error messages, logs) become `sk-…abcd`; the home directory becomes `~`. */
41
41
  export declare function maskSecrets(text: string): string;
42
+ /**
43
+ * Every string in an event's `detail`, however deep, goes through maskSecrets: callers add detail fields one by
44
+ * one and each had to remember it (0.0.168 put doctor's failed checks there with a raw proxy URL, 710b234).
45
+ */
46
+ export declare function maskDetail(detail: Record<string, unknown>): Record<string, unknown>;
42
47
  /** What a command that ends with a failing exit code told the user; goes with its `command fail` event. */
43
48
  export declare function noteFailureReason(reason: string): void;
44
49
  export declare function lastFailureReason(): string | undefined;
@@ -1 +1 @@
1
- import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as o}from"os";import{format as n,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as u}from"./client-config.js";import{configManager as m}from"./config.js";import{gatewayAddresses as p}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as d,REPORT_PATH as f,TELEMETRY_PATH as g}from"./gateway-protocol.js";const h=e();let y="wizard",w=[];const x=new Set;let T=null,k=H;export function telemetryEnabled(){if(process.env.VITEST&&!_)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let S,_=!1;export function setTelemetrySenderForTests(e){k=e??H,_=null!==e,w=[],z=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${o()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[d]:u()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const o=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([m.getBaseUrl(),...p().map(e=>e.url)].map(e=>new URL(e).host)).has(o.host)){const o=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))o.has(e)||o.set(e,t);return e(t,{...r,headers:o})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return x.size>0}function $(){return{install_id:u(),cli_version:l(),brand:a().id,os:process.platform,os_release:o(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const o=new Set([t,t.replace(/\\/g,"/")]);let n=e;for(const e of o)n=n.split(e).join("~");return n}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}let b=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(S=t)}export function lastFailureReason(){return S}export function watchConsoleErrors(){if(b)return;b=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(n(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}let z=[],E=0;export function track(e,t,r={}){if("start"===t)z.push(e),"command"===e&&(E=Date.now());else{const t=z.lastIndexOf(e);t>=0&&z.splice(t,1)}if(!telemetryEnabled())return;const o=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:h,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...o?{error:o}:{},...r.detail?{detail:r.detail}:{}}),"start"===t?v():T||(T=setTimeout(v,500),T.unref())}export async function trackStep(e,t,r){const o=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-o}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-o,error:t}),t}}function v(){if(T&&(clearTimeout(T),T=null),0===w.length)return;const e=w.splice(0,50),t=k(g,{...$(),events:e},3e3).then(()=>{},()=>{}).finally(()=>x.delete(t));x.add(t),w.length>0&&v()}export async function flushTelemetry(e=1500){v(),0!==x.size&&await Promise.race([Promise.allSettled([...x]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export function commandInProgress(){return z.includes("command")}export async function reportSignal(e,t,r=1500){if(commandInProgress()){const r=z.filter(e=>"command"!==e).pop();track("command","cancel",{duration_ms:Date.now()-E,detail:{signal:e,exit_code:t,...r?{during:r}:{}}})}await flushTelemetry(r)}export async function uploadReport(e){try{const t=await k(f,{...$(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function H(e,t,r){const o=m.getApiKey()?.trim(),n=await fetch(new URL(e,m.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.json().catch(()=>null)}
1
+ import{randomUUID as e}from"crypto";import{arch as t,homedir as r,release as n}from"os";import{format as o,stripVTControlCharacters as s}from"util";import{brand as a,brandEnv as i,CLI_NAME as c}from"./brand.js";import{clientVersion as l,installId as m}from"./client-config.js";import{configManager as u}from"./config.js";import{gatewayAddresses as p}from"./gateway-addresses.js";import{INSTALL_ID_HEADER as f,REPORT_PATH as d,TELEMETRY_PATH as g}from"./gateway-protocol.js";const h=e();let y="wizard",w=[];const x=new Set;let k=null,S=A;export function telemetryEnabled(){if(process.env.VITEST&&!_)return!1;const e=i("TELEMETRY")?.trim().toLowerCase();return!("0"===e||"false"===e||"off"===e)}let T,_=!1;export function setTelemetrySenderForTests(e){S=e??A,_=null!==e,w=[],j=[]}export function clientHeaders(){const e=`${c}/${l()} (${process.platform} ${n()}; ${t()}) node/${process.versions.node}`;return telemetryEnabled()?{"User-Agent":e,[f]:m()}:{"User-Agent":e}}export function installClientHeaders(){const e=globalThis.fetch;if(!e||e.gatewayHeaders)return;const t=(t,r)=>{try{const n=new URL("string"==typeof t||t instanceof URL?t.toString():t.url);if(new Set([u.getBaseUrl(),...p().map(e=>e.url)].map(e=>new URL(e).host)).has(n.host)){const n=new Headers(r?.headers??(t instanceof Request?t.headers:void 0));for(const[e,t]of Object.entries(clientHeaders()))n.has(e)||n.set(e,t);return e(t,{...r,headers:n})}}catch{}return e(t,r)};t.gatewayHeaders=!0,globalThis.fetch=t}export function telemetryPending(){return x.size>0}function b(){return{install_id:m(),cli_version:l(),brand:a().id,os:process.platform,os_release:n(),arch:t(),node_version:process.versions.node}}export function maskHome(e){const t=r();if(!t||t.length<2)return e;const n=new Set([t,t.replace(/\\/g,"/")]);let o=e;for(const e of n)o=o.split(e).join("~");return o}export function maskSecrets(e){return maskHome(e).replace(/(sk-[A-Za-z0-9_-]{2})[A-Za-z0-9_-]{8,}([A-Za-z0-9_-]{4})\b/g,"$1…$2").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…").replace(/(\b[a-z][a-z0-9+.-]*:\/\/)\S*@/gi,"$1…@").replace(/[^\s/@:]+:[^\s/]*@(?=[a-z0-9.-]+)/gi,"…@").replace(/\b((?:api[_-]?key|token|password|passwd|secret|auth)\s*[=:]\s*)("?)[^\s"&;,]{6,}\2/gi,"$1$2…$2")}export function maskDetail(e){const t=(e,r)=>"string"==typeof e?maskSecrets(e):r>=8||null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t(e,r+1)):Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n,r+1)]));return t(e,0)}let $=!1;export function noteFailureReason(e){const t=s(e).split("\n").map(e=>e.trim()).filter(Boolean).pop();t&&(T=t)}export function lastFailureReason(){return T}export function watchConsoleErrors(){if($)return;$=!0;const e=console.error;console.error=(...t)=>{noteFailureReason(o(...t)),e.apply(console,t)}}export function setTelemetryCommand(e){y=e}let j=[],E=0;export function track(e,t,r={}){if("start"===t)j.push(e),"command"===e&&(E=Date.now());else{const t=j.lastIndexOf(e);t>=0&&j.splice(t,1)}if(!telemetryEnabled())return;const n=void 0===r.error?void 0:maskSecrets(r.error instanceof Error?r.error.message:String(r.error)).slice(0,2e3);w.push({ts:Date.now(),session:h,command:y,step:e,status:t,...void 0!==r.duration_ms?{duration_ms:Math.round(r.duration_ms)}:{},...n?{error:n}:{},...r.detail?{detail:maskDetail(r.detail)}:{}}),"start"===t?z():k||(k=setTimeout(z,500),k.unref())}export async function trackStep(e,t,r){const n=Date.now();track(e,"start",r?{detail:r}:{});try{const r=await t();return track(e,"ok",{duration_ms:Date.now()-n}),r}catch(t){throw track(e,"fail",{duration_ms:Date.now()-n,error:t}),t}}function z(){if(k&&(clearTimeout(k),k=null),0===w.length)return;const e=w.splice(0,50),t=S(g,{...b(),events:e},3e3).then(()=>{},()=>{}).finally(()=>x.delete(t));x.add(t),w.length>0&&z()}export async function flushTelemetry(e=1500){z(),0!==x.size&&await Promise.race([Promise.allSettled([...x]),new Promise(t=>setTimeout(t,e).unref())])}export async function reportCrash(e,t=1500){const r=(e instanceof Error?(e.stack??"").split("\n").slice(e.message.split("\n").length):[]).map(e=>e.trim()).find(e=>/^at .+(\(.+:\d+:\d+\)|:\d+:\d+)$/.test(e));track("command","fail",{error:e,detail:{exit_code:1,type:"crash",...r?{at:maskSecrets(r).slice(0,200)}:{}}}),await flushTelemetry(t)}export function commandInProgress(){return j.includes("command")}export async function reportSignal(e,t,r=1500){if(commandInProgress()){const r=j.filter(e=>"command"!==e).pop();track("command","cancel",{duration_ms:Date.now()-E,detail:{signal:e,exit_code:t,...r?{during:r}:{}}})}await flushTelemetry(r)}export async function uploadReport(e){try{const t=await S(d,{...b(),report:e},2e4),r=t?.data?.code;return"string"==typeof r&&r?r:null}catch{return null}}async function A(e,t,r){const n=u.getApiKey()?.trim(),o=await fetch(new URL(e,u.getBaseUrl()).toString(),{method:"POST",headers:{"Content-Type":"application/json",...clientHeaders(),...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t),signal:AbortSignal.timeout(r)});if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.json().catch(()=>null)}
@@ -366,6 +366,18 @@
366
366
  "path_reload_windows": "Open a new terminal to use {{commands}}",
367
367
  "list_separator": ", ",
368
368
  "ask_detected_tool": "Found {{tool}}. Configure it?",
369
+ "ask_key": "Paste your API key (starts with sk-):",
370
+ "pick_tools": "This key works with the tools below. Space toggles, Enter confirms:",
371
+ "pick_installed": "installed {{version}}",
372
+ "pick_installed_plain": "installed",
373
+ "pick_will_install": "will be installed",
374
+ "pick_none": "No tool selected; nothing was changed.",
375
+ "pick_mode": "What should be done?",
376
+ "pick_mode_install": "Install and configure: install the missing ones first",
377
+ "pick_mode_configure": "Only configure the installed ones",
378
+ "pick_mode_upgrade": "Only install or update, leave the config as is",
379
+ "pick_configure_skip": "{{tools}} not installed yet; not configured this time",
380
+ "pick_upgrade_skip": "{{cli}} can't install or update {{tool}}; skipped",
369
381
  "detected_tool_hint": "Found {{tool}}. To configure it, run `{{cli}} config {{name}} --yes`",
370
382
  "gui_preconfigured": "{{tool}} is not installed yet; its config is written already, so it works once you install and open it (download: {{install}})",
371
383
  "validate_failed": "Couldn't validate the API key for {{label}}: {{reason}}",
@@ -366,6 +366,18 @@
366
366
  "path_reload_windows": "新开一个终端后即可使用 {{commands}}",
367
367
  "list_separator": "、",
368
368
  "ask_detected_tool": "检测到 {{tool}},要配置它吗?",
369
+ "ask_key": "粘贴令牌(sk- 开头):",
370
+ "pick_tools": "这个令牌能用下面这些工具,空格勾选或取消,回车确认:",
371
+ "pick_installed": "已安装 {{version}}",
372
+ "pick_installed_plain": "已安装",
373
+ "pick_will_install": "将安装",
374
+ "pick_none": "没有选择工具,什么都没有改。",
375
+ "pick_mode": "要做什么?",
376
+ "pick_mode_install": "安装并配置:没装的先装上",
377
+ "pick_mode_configure": "只配置已安装的",
378
+ "pick_mode_upgrade": "只安装或更新,不改配置",
379
+ "pick_configure_skip": "{{tools}} 还没有安装,这次不配置",
380
+ "pick_upgrade_skip": "{{cli}} 不能安装或更新 {{tool}},已跳过",
369
381
  "detected_tool_hint": "检测到 {{tool}},配置它运行 `{{cli}} config {{name}} --yes`",
370
382
  "gui_preconfigured": "{{tool}} 还没有安装,已提前写好配置,安装后打开即可使用(下载:{{install}})",
371
383
  "validate_failed": "无法验证 {{label}} 的令牌:{{reason}}",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibeapi/api-helper",
3
- "version": "0.0.182",
3
+ "version": "0.0.184",
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",