@vibeapi/cli 0.0.50 → 0.0.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,7 +42,7 @@ vibecli setup --key sk-xxx
42
42
  vibecli setup --claudekey sk-a --codexkey sk-b --grokkey sk-c --desktopkey sk-d
43
43
  ```
44
44
 
45
- Codex 同时开启 1M 上下文时,末尾加最短参数 `--1m`;已经配置过的用户无需再次输入 Key。单独执行 `--1m` 只幂等更新上下文字段,不改写 Codex 凭据:
45
+ Codex 同时开启 1M 上下文时,末尾加最短参数 `--1m`;已经配置过的用户无需再次输入 Key。单独执行 `--1m` 只重新生成模型目录里的上下文设置,不改写 Codex 凭据:
46
46
 
47
47
  ```bash
48
48
  vibecli setup --codexkey sk-xxx --1m
@@ -79,7 +79,7 @@ vibecli config claude-code clear-model # 模型选择被钉住时,交还给
79
79
  - **多工具一键配置**:把当前 API Key / 模型注入 Claude Code、Claude Desktop(桌面端第三方推理模式,写应用本地配置库,无需管理员 / 描述文件)、Codex、OpenClaw、Hermes、AtomCode、Grok Build(OpenCode 暂时下架,`vibecli config opencode` 仍可用)。
80
80
  - **按工具选模型**:使用默认 / 实时从 API 拉取 / 内置预设 / 手动输入;每个工具可用不同模型。
81
81
  - Claude Code 用默认模型时不写 `ANTHROPIC_*_MODEL` 环境变量,顶层 `model` 由 `settings-template.json` 提供(当前为 `opus[1m]`);显式选择其它模型时会覆盖该模板值。Codex 默认 `gpt-6-astra`,Grok Build 默认 `grok-4.6`,其余工具默认 `gpt-5.5`。
82
- - Codex 默认启用 1M 上下文窗口(自动压缩阈值 900K);交互配置 Codex 时可取消。
82
+ - Codex(CLI 与桌面版)的模型菜单除自带的 GPT 模型外,还列出网关的 Claude 与国产模型(只列 Key 能用的);Claude Code 的 `/model` 菜单也会在内置档位后列出 Key 能用的国产模型;每个模型按自己的上下文窗口设置,窗口用到 80% 时自动压缩。默认启用 1M 上下文,交互配置 Codex 时可取消(取消后窗口不超过 272K)。需要 Codex 0.122 及以上;Codex、Claude Code 版本过旧时,配置完成会提示升级命令。
83
83
  - **不动你的其它配置**:只改本工具的 provider 字段,你的 hooks、MCP、插件、权限设置原样保留。
84
84
  - **配置改坏了一键重置**:`vibecli config <tool> --force`(或 `setup … --force`)先快照再整份重写为推荐配置,坏掉的 JSON/TOML 也能救回;不加 `--force` 时只幂等合并、不碰坏文件。
85
85
  - **改前自动备份 + 一键还原**:覆盖配置前先快照(每文件留 10 份),`vibecli config <tool> restore` 随时回退;还原本身也可再撤销。
@@ -0,0 +1,10 @@
1
+ # Third-party notices
2
+
3
+ ## OpenAI Codex
4
+
5
+ `codex-base-instructions.md` is copied unmodified from `codex-rs/models-manager/prompt.md` in
6
+ [openai/codex](https://github.com/openai/codex) (commit `2351d9e1b608e6f9d9a3699b71d7eb39ee41cfa4`).
7
+
8
+ Copyright 2025 OpenAI. Licensed under the Apache License, Version 2.0
9
+ (<https://www.apache.org/licenses/LICENSE-2.0>). Distributed on an "AS IS" BASIS, WITHOUT
10
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -0,0 +1,277 @@
1
+ You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
2
+
3
+ Your capabilities:
4
+
5
+ - Receive user prompts and other context provided by the harness, such as files in the workspace.
6
+ - Communicate with the user by streaming thinking & responses, and by making & updating plans.
7
+ - Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
8
+
9
+ Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
10
+
11
+ # How you work
12
+
13
+ ## Personality
14
+
15
+ Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
16
+
17
+ # AGENTS.md spec
18
+
19
+ - Repos often contain AGENTS.md files. These files can appear anywhere within the repository.
20
+ - These files are a way for humans to give you (the agent) instructions or tips for working within the container.
21
+ - Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.
22
+ - Instructions in AGENTS.md files:
23
+ - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.
24
+ - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.
25
+ - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.
26
+ - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.
27
+ - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.
28
+ - The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.
29
+
30
+ ## Responsiveness
31
+
32
+ ### Preamble messages
33
+
34
+ Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
35
+
36
+ - **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
37
+ - **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
38
+ - **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
39
+ - **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
40
+ - **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
41
+
42
+ **Examples:**
43
+
44
+ - “I’ve explored the repo; now checking the API route definitions.”
45
+ - “Next, I’ll patch the config and update the related tests.”
46
+ - “I’m about to scaffold the CLI commands and helper functions.”
47
+ - “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
48
+ - “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
49
+ - “Finished poking at the DB gateway. I will now chase down error handling.”
50
+ - “Alright, build pipeline order is interesting. Checking how it reports failures.”
51
+ - “Spotted a clever caching util; now hunting where it gets used.”
52
+
53
+ ## Planning
54
+
55
+ You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go.
56
+
57
+ Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
58
+
59
+ Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
60
+
61
+ Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so.
62
+
63
+ Use a plan when:
64
+
65
+ - The task is non-trivial and will require multiple actions over a long time horizon.
66
+ - There are logical phases or dependencies where sequencing matters.
67
+ - The work has ambiguity that benefits from outlining high-level goals.
68
+ - You want intermediate checkpoints for feedback and validation.
69
+ - When the user asked you to do more than one thing in a single prompt
70
+ - The user has asked you to use the plan tool (aka "TODOs")
71
+ - You generate additional steps while working, and plan to do them before yielding to the user
72
+
73
+ ### Examples
74
+
75
+ **High-quality plans**
76
+
77
+ Example 1:
78
+
79
+ 1. Add CLI entry with file args
80
+ 2. Parse Markdown via CommonMark library
81
+ 3. Apply semantic HTML template
82
+ 4. Handle code blocks, images, links
83
+ 5. Add error handling for invalid files
84
+
85
+ Example 2:
86
+
87
+ 1. Define CSS variables for colors
88
+ 2. Add toggle with localStorage state
89
+ 3. Refactor components to use variables
90
+ 4. Verify all views for readability
91
+ 5. Add smooth theme-change transition
92
+
93
+ Example 3:
94
+
95
+ 1. Set up Node.js + WebSocket server
96
+ 2. Add join/leave broadcast events
97
+ 3. Implement messaging with timestamps
98
+ 4. Add usernames + mention highlighting
99
+ 5. Persist messages in lightweight DB
100
+ 6. Add typing indicators + unread count
101
+
102
+ **Low-quality plans**
103
+
104
+ Example 1:
105
+
106
+ 1. Create CLI tool
107
+ 2. Add Markdown parser
108
+ 3. Convert to HTML
109
+
110
+ Example 2:
111
+
112
+ 1. Add dark mode toggle
113
+ 2. Save preference
114
+ 3. Make styles look good
115
+
116
+ Example 3:
117
+
118
+ 1. Create single-file HTML game
119
+ 2. Run quick sanity check
120
+ 3. Summarize usage instructions
121
+
122
+ If you need to write a plan, only write high quality plans, not low quality ones.
123
+
124
+ ## Task execution
125
+
126
+ You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
127
+
128
+ You MUST adhere to the following criteria when solving queries:
129
+
130
+ - Working on the repo(s) in the current environment is allowed, even if they are proprietary.
131
+ - Analyzing code for vulnerabilities is allowed.
132
+ - Showing user code and tool call details is allowed.
133
+ - Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
134
+
135
+ If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
136
+
137
+ - Fix the problem at the root cause rather than applying surface-level patches, when possible.
138
+ - Avoid unneeded complexity in your solution.
139
+ - Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
140
+ - Update documentation as necessary.
141
+ - Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
142
+ - Use `git log` and `git blame` to search the history of the codebase if additional context is required.
143
+ - NEVER add copyright or license headers unless specifically requested.
144
+ - Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
145
+ - Do not `git commit` your changes or create new git branches unless explicitly requested.
146
+ - Do not add inline comments within code unless explicitly requested.
147
+ - Do not use one-letter variable names unless explicitly requested.
148
+ - NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
149
+
150
+ ## Validating your work
151
+
152
+ If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
153
+
154
+ When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.
155
+
156
+ Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
157
+
158
+ For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
159
+
160
+ Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
161
+
162
+ - When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
163
+ - When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
164
+ - When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
165
+
166
+ ## Ambition vs. precision
167
+
168
+ For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
169
+
170
+ If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
171
+
172
+ You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
173
+
174
+ ## Sharing progress updates
175
+
176
+ For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
177
+
178
+ Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
179
+
180
+ The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
181
+
182
+ ## Presenting your work and final message
183
+
184
+ Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
185
+
186
+ You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
187
+
188
+ The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
189
+
190
+ If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
191
+
192
+ Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
193
+
194
+ ### Final answer structure and style guidelines
195
+
196
+ You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
197
+
198
+ **Section Headers**
199
+
200
+ - Use only when they improve clarity — they are not mandatory for every answer.
201
+ - Choose descriptive names that fit the content
202
+ - Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
203
+ - Leave no blank line before the first bullet under a header.
204
+ - Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
205
+
206
+ **Bullets**
207
+
208
+ - Use `-` followed by a space for every bullet.
209
+ - Merge related points when possible; avoid a bullet for every trivial detail.
210
+ - Keep bullets to one line unless breaking for clarity is unavoidable.
211
+ - Group into short lists (4–6 bullets) ordered by importance.
212
+ - Use consistent keyword phrasing and formatting across sections.
213
+
214
+ **Monospace**
215
+
216
+ - Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
217
+ - Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
218
+ - Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
219
+
220
+ **File References**
221
+ When referencing files in your response, make sure to include the relevant start line and always follow the below rules:
222
+
223
+ - Use inline code to make file paths clickable.
224
+ - Each reference should have a stand alone path. Even if it's the same file.
225
+ - Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
226
+ - Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
227
+ - Do not use URIs like file://, vscode://, or https://.
228
+ - Do not provide range of lines
229
+ - Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
230
+
231
+ **Structure**
232
+
233
+ - Place related bullets together; don’t mix unrelated concepts in the same section.
234
+ - Order sections from general → specific → supporting info.
235
+ - For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
236
+ - Match structure to complexity:
237
+ - Multi-part or detailed results → use clear headers and grouped bullets.
238
+ - Simple results → minimal headers, possibly just a short list or paragraph.
239
+
240
+ **Tone**
241
+
242
+ - Keep the voice collaborative and natural, like a coding partner handing off work.
243
+ - Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
244
+ - Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
245
+ - Keep descriptions self-contained; don’t refer to “above” or “below”.
246
+ - Use parallel structure in lists for consistency.
247
+
248
+ **Don’t**
249
+
250
+ - Don’t use literal words “bold” or “monospace” in the content.
251
+ - Don’t nest bullets or create deep hierarchies.
252
+ - Don’t output ANSI escape codes directly — the CLI renderer applies them.
253
+ - Don’t cram unrelated keywords into a single bullet; split for clarity.
254
+ - Don’t let keyword lists run long — wrap or reformat for scanability.
255
+
256
+ Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
257
+
258
+ For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
259
+
260
+ # Tool Guidelines
261
+
262
+ ## Shell commands
263
+
264
+ When using the shell, you must adhere to the following guidelines:
265
+
266
+ - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
267
+ - Do not use python scripts to attempt to output larger chunks of a file.
268
+
269
+ ## `update_plan`
270
+
271
+ A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.
272
+
273
+ To create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).
274
+
275
+ When steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.
276
+
277
+ If all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.
@@ -1 +1 @@
1
- import e from"chalk";import{i18n as o}from"../lib/i18n.js";import{configManager as t}from"../lib/config.js";import{toolManager as s,SUPPORTED_TOOLS as a}from"../lib/tool-manager.js";import{validateApiKey as l,fetchModels as i}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as d,setCodexOneMillionContext as n}from"../lib/tools/codex.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as r}from"../lib/tools/claude-desktop.js";async function p(e){const o=await i(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!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")),probed:!0}}function c(e,o){return"claude"===o?e.hasClaude:"gpt"===o?e.hasGpt:e.hasGrok}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 u(o){console.log(e.green(o))}function f(o){console.log(e.yellow(o))}function m(o){console.error(e.red(o))}async function k(t,s){console.log(e.gray(o.t("setup.validating",{label:t})));const a=await l(s);return!!a.valid||(m(o.t("setup.invalid_key",{label:t,reason:a.message||a.error||"invalid"})),!1)}async function y(l,i,n,p,c){const k=a[l];try{"codex"===l&&void 0!==n&&t.setToolSetting("codex",d,n),"claude-desktop"===l&&void 0!==p&&t.setToolSetting("claude-desktop",r,!p),await s.applyPrivateConfig(l,i,t.getModelsForTool(l),{force:c})}catch(e){return m(o.t("setup.apply_failed",{tool:k.displayName,reason:e instanceof Error?e.message:String(e)})),!1}return c&&f(o.t("config.force_done",{tool:k.displayName})),u(o.t("setup.configured",{tool:k.displayName,command:k.command})),"codex"===l&&void 0!==n&&u(o.t(n?"setup.codex_1m_enabled":"setup.codex_1m_disabled")),s.applyNotes(l).forEach(e=>f(" "+e)),s.isToolInstalled(l)||console.log(e.gray(o.t("setup.install_hint",{tool:k.displayName,install:k.installCommand}))),!0}export async function setupCommand(e){const l=e.key?.trim(),i=e.claudekey?.trim(),r=e.codexkey?.trim(),g=e.grokkey?.trim(),_=e.desktopkey?.trim(),b=void 0!==e.oneMillion,h=void 0!==e.claudeOfficial;let x;if(h&&(x=parseOnOff(e.claudeOfficial),void 0===x))return m(o.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)})),void(process.exitCode=1);const C=Boolean(l||i||r||g||_);if(!C&&(b||h)){if(b)if(t.getApiKeyForTool("codex"))try{const s=!0===e.oneMillion;t.setToolSetting("codex",d,s),n(s),u(o.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){m(o.t("setup.apply_failed",{tool:a.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else m(o.t("setup.codex_1m_missing_key")),process.exitCode=1;if(h){const s=t.getApiKeyForTool("claude-desktop");s?await y("claude-desktop",s,void 0,x,e.force)||(process.exitCode=1):(m(o.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!C)return m(o.t("setup.usage")),void(process.exitCode=1);let v=0,w=0;const K=new Set,G=[];i&&G.push({tool:"claude-code",label:"--claudekey",apiKey:i,need:"claude"}),r&&G.push({tool:"codex",label:"--codexkey",apiKey:r,need:"gpt"}),g&&G.push({tool:"grok",label:"--grokkey",apiKey:g,need:"grok"}),_&&G.push({tool:"claude-desktop",label:"--desktopkey",apiKey:_,need:"claude"});for(const s of G){if(!await k(s.label,s.apiKey)){w+=1;continue}const l=await p(s.apiKey);!l.probed||c(l,s.need)?(l.probed||f(o.t("setup.probe_failed",{label:s.label})),t.setToolApiKey(s.tool,s.apiKey),await y(s.tool,s.apiKey,e.oneMillion,x,e.force)?(v+=1,K.add(s.tool)):w+=1):(m(o.t(`setup.key_no_${s.need}`,{label:s.label,tool:a[s.tool].displayName})),w+=1)}if(l){if(!await k("--key",l))return void(process.exitCode=1);t.setApiKey(l);const a=await p(l);if(a.probed||f(o.t("setup.probe_failed",{label:"--key"})),a.probed&&!a.hasClaude&&!a.hasGpt&&!a.hasGrok)return m(o.t("setup.key_no_family")),void(process.exitCode=1);const i=[{tool:"claude-code",capable:a.hasClaude,skipMsg:o.t("setup.skip_no_claude")},{tool:"codex",capable:a.hasGpt,skipMsg:o.t("setup.skip_no_gpt")},{tool:"grok",capable:a.hasGrok,skipMsg:o.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:a.hasClaude&&s.isToolInstalled("claude-desktop"),skipMsg:o.t("setup.skip_desktop_not_installed"),quiet:!a.hasClaude}];for(const o of i)K.has(o.tool)||(o.capable?await y(o.tool,l,e.oneMillion,x,e.force)?(v+=1,K.add(o.tool)):w+=1:o.quiet||f(o.skipMsg))}if(v>0){const e=[...K].map(e=>a[e]?.command).filter(Boolean).join(" / ");u("\n"+o.t("setup.done",{count:String(v),commands:e}))}(w>0||0===v)&&(process.exitCode=1)}
1
+ import e from"chalk";import{i18n as o}from"../lib/i18n.js";import{configManager as t}from"../lib/config.js";import{toolManager as a,SUPPORTED_TOOLS as s}from"../lib/tool-manager.js";import{validateApiKey as i,fetchModels as l}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as d,setCodexOneMillionContext as n}from"../lib/tools/codex.js";import{resolveModelCatalog as r}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as c}from"../lib/tools/claude-desktop.js";async function p(e){const o=await l(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!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")),probed:!0}}function u(e,o){return"claude"===o?e.hasClaude:"gpt"===o?e.hasGpt:e.hasGrok}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 f(o){console.log(e.green(o))}function m(o){console.log(e.yellow(o))}function k(o){console.error(e.red(o))}async function y(t,a){console.log(e.gray(o.t("setup.validating",{label:t})));const s=await i(a);return!!s.valid||(k(o.t("setup.invalid_key",{label:t,reason:s.message||s.error||"invalid"})),!1)}async function g(i,l,n,r,p){const u=s[i];try{"codex"===i&&void 0!==n&&t.setToolSetting("codex",d,n),"claude-desktop"===i&&void 0!==r&&t.setToolSetting("claude-desktop",c,!r),await a.applyPrivateConfig(i,l,t.getModelsForTool(i),{force:p})}catch(e){return k(o.t("setup.apply_failed",{tool:u.displayName,reason:e instanceof Error?e.message:String(e)})),!1}return p&&m(o.t("config.force_done",{tool:u.displayName})),f(o.t("setup.configured",{tool:u.displayName,command:u.command})),"codex"===i&&void 0!==n&&f(o.t(n?"setup.codex_1m_enabled":"setup.codex_1m_disabled")),a.applyNotes(i).forEach(e=>m(" "+e)),a.isToolInstalled(i)||console.log(e.gray(o.t("setup.install_hint",{tool:u.displayName,install:u.installCommand}))),!0}export async function setupCommand(e){const i=e.key?.trim(),l=e.claudekey?.trim(),c=e.codexkey?.trim(),_=e.grokkey?.trim(),b=e.desktopkey?.trim(),h=void 0!==e.oneMillion,x=void 0!==e.claudeOfficial;let v;if(x&&(v=parseOnOff(e.claudeOfficial),void 0===v))return k(o.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)})),void(process.exitCode=1);const C=Boolean(i||l||c||_||b);if(!C&&(h||x)){if(h){const a=t.getApiKeyForTool("codex");if(a)try{const s=!0===e.oneMillion;t.setToolSetting("codex",d,s);const i=await r(a);n(s,i??void 0),f(o.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){k(o.t("setup.apply_failed",{tool:s.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else k(o.t("setup.codex_1m_missing_key")),process.exitCode=1}if(x){const a=t.getApiKeyForTool("claude-desktop");a?await g("claude-desktop",a,void 0,v,e.force)||(process.exitCode=1):(k(o.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!C)return k(o.t("setup.usage")),void(process.exitCode=1);let w=0,K=0;const G=new Set,M=[];l&&M.push({tool:"claude-code",label:"--claudekey",apiKey:l,need:"claude"}),c&&M.push({tool:"codex",label:"--codexkey",apiKey:c,need:"gpt"}),_&&M.push({tool:"grok",label:"--grokkey",apiKey:_,need:"grok"}),b&&M.push({tool:"claude-desktop",label:"--desktopkey",apiKey:b,need:"claude"});for(const a of M){if(!await y(a.label,a.apiKey)){K+=1;continue}const i=await p(a.apiKey);!i.probed||u(i,a.need)?(i.probed||m(o.t("setup.probe_failed",{label:a.label})),t.setToolApiKey(a.tool,a.apiKey),await g(a.tool,a.apiKey,e.oneMillion,v,e.force)?(w+=1,G.add(a.tool)):K+=1):(k(o.t(`setup.key_no_${a.need}`,{label:a.label,tool:s[a.tool].displayName})),K+=1)}if(i){if(!await y("--key",i))return void(process.exitCode=1);t.setApiKey(i);const s=await p(i);if(s.probed||m(o.t("setup.probe_failed",{label:"--key"})),s.probed&&!s.hasClaude&&!s.hasGpt&&!s.hasGrok)return k(o.t("setup.key_no_family")),void(process.exitCode=1);const l=[{tool:"claude-code",capable:s.hasClaude,skipMsg:o.t("setup.skip_no_claude")},{tool:"codex",capable:s.hasGpt,skipMsg:o.t("setup.skip_no_gpt")},{tool:"grok",capable:s.hasGrok,skipMsg:o.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:s.hasClaude&&a.isToolInstalled("claude-desktop"),skipMsg:o.t("setup.skip_desktop_not_installed"),quiet:!s.hasClaude}];for(const o of l)G.has(o.tool)||(o.capable?await g(o.tool,i,e.oneMillion,v,e.force)?(w+=1,G.add(o.tool)):K+=1:o.quiet||m(o.skipMsg))}if(w>0){const e=[...G].map(e=>s[e]?.command).filter(Boolean).join(" / ");f("\n"+o.t("setup.done",{count:String(w),commands:e}))}(K>0||0===w)&&(process.exitCode=1)}
@@ -49,6 +49,23 @@ export declare function fetchGatewayStatus(options?: {
49
49
  timeoutMs?: number;
50
50
  fetchFn?: typeof fetch;
51
51
  }): Promise<FetchGatewayStatusResult>;
52
+ /** One model row of the gateway's client config (`/api/platform/vibecode/config` → `models.<tool>[]`). */
53
+ export interface GatewayClientModel {
54
+ id: string;
55
+ name?: string;
56
+ description?: string;
57
+ contextWindow?: number;
58
+ autoCompactTokens?: number;
59
+ }
60
+ /**
61
+ * 拉取网关下发给编码客户端的模型清单(公开接口,无需鉴权):每个工具的模型、名称、说明、
62
+ * 上下文窗口与压缩阈值,站长改了即时生效。老网关没有这个接口,任何失败都返回 null,
63
+ * 调用方回退到 models.json 里的内置清单。隐藏的模型直接丢弃。
64
+ */
65
+ export declare function fetchClientModelConfig(options?: {
66
+ timeoutMs?: number;
67
+ fetchFn?: typeof fetch;
68
+ }): Promise<Record<string, GatewayClientModel[]> | null>;
52
69
  /**
53
70
  * 验证 API Key 的有效性和网络连通性,遇到网络错误时按指数退避重试
54
71
  */
@@ -1 +1 @@
1
- import{logger as e}from"../utils/logger.js";import{configManager as r}from"./config.js";const t=e=>new Promise(r=>setTimeout(r,e));async function o(e,t,o){const a=`${r.getBaseUrl()}/v1/models`,s=new AbortController,n=setTimeout(()=>s.abort(),t);try{const r=await o(a,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},signal:s.signal});if(401===r.status)return{valid:!1,error:"invalid_api_key",message:"API Key is invalid or expired"};if(r.ok){try{const e=await r.json();if(e&&"list"===e.object)return{valid:!0}}catch{return{valid:!0}}return{valid:!0}}return{valid:!1,error:"unknown_error",message:`HTTP ${r.status}: ${r.statusText}`}}catch(e){return e instanceof Error&&"AbortError"===e.name?{valid:!1,error:"network_error",message:"Request timeout"}:{valid:!1,error:"network_error",message:e instanceof Error?e.message:"Network connection failed"}}finally{clearTimeout(n)}}export async function fetchModels(t,o={}){const{timeoutMs:a=3e4,fetchFn:s=fetch}=o,n=`${r.getBaseUrl()}/v1/models`,i=new AbortController,l=setTimeout(()=>i.abort(),a);try{const e=await s(n,{method:"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},signal:i.signal});if(!e.ok)return{ok:!1,models:[],error:`HTTP ${e.status}`};const r=await e.json();return{ok:!0,models:(Array.isArray(r?.data)?r.data:[]).map(e=>"string"==typeof e?e:e?.id).filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}}catch(r){return e.logError("fetchModels",r),{ok:!1,models:[],error:r instanceof Error?r.message:"network error"}}finally{clearTimeout(l)}}export async function fetchGatewayStatus(t={}){const{timeoutMs:o=15e3,fetchFn:a=fetch}=t,s=`${r.getBaseUrl()}/api/status`,n=new AbortController,i=setTimeout(()=>n.abort(),o);try{const e=await a(s,{method:"GET",signal:n.signal});if(!e.ok)return{ok:!1,claudeDesktopGroupModels:{},error:`HTTP ${e.status}`};const r=await e.json();let t=r?.data?.claude_desktop_group_models;if("string"==typeof t)try{t=JSON.parse(t)}catch{t=void 0}const o={};if(t&&"object"==typeof t&&!Array.isArray(t))for(const[e,r]of Object.entries(t))Array.isArray(r)&&(o[e]=r.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.name).map(e=>({name:e.name.trim(),..."string"==typeof e.labelOverride?{labelOverride:e.labelOverride}:{},..."boolean"==typeof e.supports1m?{supports1m:e.supports1m}:{}})).filter(e=>e.name.length>0));return{ok:!0,claudeDesktopGroupModels:o}}catch(r){return e.logError("fetchGatewayStatus",r),{ok:!1,claudeDesktopGroupModels:{},error:r instanceof Error?r.message:"network error"}}finally{clearTimeout(i)}}export async function validateApiKey(r,a={}){const{timeoutMs:s=3e4,retries:n=2,backoffMs:i=500,fetchFn:l=fetch,sleepFn:c=t}=a;let u={valid:!1,error:"network_error",message:"Network connection failed"};for(let t=0;t<=n;t++){const a=await o(r,s,l);if(a.valid||"invalid_api_key"===a.error)return a.valid||e.logError("validateApiKey",new Error(a.message||"invalid_api_key")),a;u=a,t<n&&await c(i*Math.pow(2,t))}return e.logError("validateApiKey",new Error(u.message||"network_error")),u}
1
+ import{logger as e}from"../utils/logger.js";import{configManager as t}from"./config.js";const r=e=>new Promise(t=>setTimeout(t,e));async function o(e,r,o){const n=`${t.getBaseUrl()}/v1/models`,a=new AbortController,i=setTimeout(()=>a.abort(),r);try{const t=await o(n,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},signal:a.signal});if(401===t.status)return{valid:!1,error:"invalid_api_key",message:"API Key is invalid or expired"};if(t.ok){try{const e=await t.json();if(e&&"list"===e.object)return{valid:!0}}catch{return{valid:!0}}return{valid:!0}}return{valid:!1,error:"unknown_error",message:`HTTP ${t.status}: ${t.statusText}`}}catch(e){return e instanceof Error&&"AbortError"===e.name?{valid:!1,error:"network_error",message:"Request timeout"}:{valid:!1,error:"network_error",message:e instanceof Error?e.message:"Network connection failed"}}finally{clearTimeout(i)}}export async function fetchModels(r,o={}){const{timeoutMs:n=3e4,fetchFn:a=fetch}=o,i=`${t.getBaseUrl()}/v1/models`,s=new AbortController,l=setTimeout(()=>s.abort(),n);try{const e=await a(i,{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},signal:s.signal});if(!e.ok)return{ok:!1,models:[],error:`HTTP ${e.status}`};const t=await e.json();return{ok:!0,models:(Array.isArray(t?.data)?t.data:[]).map(e=>"string"==typeof e?e:e?.id).filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}}catch(t){return e.logError("fetchModels",t),{ok:!1,models:[],error:t instanceof Error?t.message:"network error"}}finally{clearTimeout(l)}}export async function fetchGatewayStatus(r={}){const{timeoutMs:o=15e3,fetchFn:n=fetch}=r,a=`${t.getBaseUrl()}/api/status`,i=new AbortController,s=setTimeout(()=>i.abort(),o);try{const e=await n(a,{method:"GET",signal:i.signal});if(!e.ok)return{ok:!1,claudeDesktopGroupModels:{},error:`HTTP ${e.status}`};const t=await e.json();let r=t?.data?.claude_desktop_group_models;if("string"==typeof r)try{r=JSON.parse(r)}catch{r=void 0}const o={};if(r&&"object"==typeof r&&!Array.isArray(r))for(const[e,t]of Object.entries(r))Array.isArray(t)&&(o[e]=t.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.name).map(e=>({name:e.name.trim(),..."string"==typeof e.labelOverride?{labelOverride:e.labelOverride}:{},..."boolean"==typeof e.supports1m?{supports1m:e.supports1m}:{}})).filter(e=>e.name.length>0));return{ok:!0,claudeDesktopGroupModels:o}}catch(t){return e.logError("fetchGatewayStatus",t),{ok:!1,claudeDesktopGroupModels:{},error:t instanceof Error?t.message:"network error"}}finally{clearTimeout(s)}}function n(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}export async function fetchClientModelConfig(r={}){const{timeoutMs:o=1e4,fetchFn:a=fetch}=r,i=`${t.getBaseUrl()}/api/platform/vibecode/config`,s=new AbortController,l=setTimeout(()=>s.abort(),o);try{const e=await a(i,{method:"GET",signal:s.signal});if(!e.ok)return null;const t=await e.json(),r=t?.data?.models;if(!r||"object"!=typeof r||Array.isArray(r))return null;const o={};for(const[e,t]of Object.entries(r))Array.isArray(t)&&(o[e]=t.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id).filter(e=>!0!==e.hidden&&e.id.trim().length>0).map(e=>{const t={id:e.id.trim()};"string"==typeof e.name&&e.name.trim()&&(t.name=e.name.trim()),"string"==typeof e.description&&e.description.trim()&&(t.description=e.description.trim());const r=n(e.context_window);r&&(t.contextWindow=r);const o=n(e.auto_compact_tokens);return o&&(t.autoCompactTokens=o),t}));return o}catch(t){return e.logError("fetchClientModelConfig",t),null}finally{clearTimeout(l)}}export async function validateApiKey(t,n={}){const{timeoutMs:a=3e4,retries:i=2,backoffMs:s=500,fetchFn:l=fetch,sleepFn:c=r}=n;let f={valid:!1,error:"network_error",message:"Network connection failed"};for(let r=0;r<=i;r++){const n=await o(t,a,l);if(n.valid||"invalid_api_key"===n.error)return n.valid||e.logError("validateApiKey",new Error(n.message||"invalid_api_key")),n;f=n,r<i&&await c(s*Math.pow(2,r))}return e.logError("validateApiKey",new Error(f.message||"network_error")),f}
@@ -1,9 +1,18 @@
1
1
  import { DEFAULT_MODELS } from './config.js';
2
+ import { type GatewayModelSpec } from './model-registry.js';
2
3
  /**
3
4
  * settings.json 里所有"钉死模型"的 env 变量。写入、卸载与 clearPinnedModels
4
5
  * 共用这一份清单——新增模型槽时只改这里,避免某条路径漏清导致残留。
5
6
  */
6
7
  export declare const MODEL_ENV_VARS: readonly ["ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL", "ANTHROPIC_MODEL", "ANTHROPIC_REASONING_MODEL"];
8
+ /**
9
+ * Add the gateway's other models (domestic models, …) to Claude Code's `/model`
10
+ * menu: `modelPicker` rows after the built-in lineup, `modelSettings.<id>.autoCompactWindow`
11
+ * at 80% of each window, and `CLAUDE_CODE_MAX_CONTEXT_TOKENS` — Claude Code's only
12
+ * window setting for non-Claude ids, one value for all of them — at the smallest
13
+ * listed window. `models` undefined (offline) keeps what is there; empty removes ours.
14
+ */
15
+ export declare function applyGatewayModels(settings: ClaudeCodeSettingsConfig, models: GatewayModelSpec[] | undefined): ClaudeCodeSettingsConfig;
7
16
  export interface TierFallback {
8
17
  tier: string;
9
18
  envVar: string;
@@ -82,8 +91,9 @@ export declare class ClaudeCodeManager {
82
91
  /**
83
92
  * 加载私有 NewAPI 配置到 Claude Code
84
93
  * @param availableModels Key 在网关 `/v1/models` 能看到的模型;缺省(离线)时不做档位回退
94
+ * @param gatewayModels 加进 /model 菜单的其它网关模型(已按 Key 过滤);缺省(离线)时保持原样
85
95
  */
86
- loadPrivateConfig(apiKey: string, models: typeof DEFAULT_MODELS, availableModels?: string[]): void;
96
+ loadPrivateConfig(apiKey: string, models: typeof DEFAULT_MODELS, availableModels?: string[], gatewayModels?: GatewayModelSpec[]): void;
87
97
  /**
88
98
  * 确保 .claude.json 中有 hasCompletedOnboarding: true
89
99
  */
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as s,renameSync as o,unlinkSync as r}from"fs";import{join as i,dirname as a}from"path";import{homedir as l}from"os";import{logger as c}from"../utils/logger.js";import{configManager as g,DEFAULT_MODELS as C}from"./config.js";import{loadSettingsTemplate as O}from"./settings-template.js";import{cleanupAnthropicEnvVars as d}from"./env-cleanup.js";import{getClaudeCodeTierChains as h}from"./model-registry.js";import{baseModelId as _}from"./model-catalog.js";export const MODEL_ENV_VARS=["ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];const E={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"};export function resolveTierFallbacks(e){if(!e||0===e.length)return[];const t=new Set(e.map(_)),n=[];for(const[e,s]of Object.entries(h())){const o=E[e],[r,...i]=s;if(!o||!r||t.has(r))continue;const a=i.find(e=>t.has(e));a&&n.push({tier:e,envVar:o,from:r,to:a})}return n}export class ClaudeCodeManager{static instance;settingsPath;mcpConfigPath;lastTierFallbacks=[];constructor(){this.settingsPath=i(l(),".claude","settings.json"),this.mcpConfigPath=i(l(),".claude.json")}static getInstance(){return ClaudeCodeManager.instance||(ClaudeCodeManager.instance=new ClaudeCodeManager),ClaudeCodeManager.instance}ensureConfigDir(n){const s=a(n);e(s)||t(s,{recursive:!0})}atomicWrite(t,n){const i=`${t}.tmp`;try{s(i,n,"utf-8"),o(i,t)}catch(t){if(e(i))try{r(i)}catch{}throw t}}getSettings(){try{if(e(this.settingsPath)){const e=n(this.settingsPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code settings:",e),c.logError("ClaudeCodeManager.getSettings",e)}return{}}saveSettings(e){try{this.ensureConfigDir(this.settingsPath),this.atomicWrite(this.settingsPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code settings: ${e}`)}}getMCPConfig(){try{if(e(this.mcpConfigPath)){const e=n(this.mcpConfigPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code MCP config:",e),c.logError("ClaudeCodeManager.getMCPConfig",e)}return{}}saveMCPConfig(e){try{this.ensureConfigDir(this.mcpConfigPath),this.atomicWrite(this.mcpConfigPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code MCP config: ${e}`)}}loadPrivateConfig(e,t,n){this.ensureOnboardingCompleted(),d();const s=O(),o=s.env||{},{env:r,...i}=s,a=this.getSettings(),{ANTHROPIC_API_KEY:l,...c}=a.env||{},h={...c};for(const e of MODEL_ENV_VARS)delete h[e];const _={},E=e=>{const n=(t[e]||"").trim();return n&&n!==C[e]?n:null},f=E("haiku"),u=E("sonnet"),m=E("opus"),T=new Set([f&&"haiku",u&&"sonnet",m&&"opus"].filter(Boolean));this.lastTierFallbacks=resolveTierFallbacks(n).filter(e=>!T.has(e.tier));for(const e of this.lastTierFallbacks)_[e.envVar]=e.to;f&&(_.ANTHROPIC_DEFAULT_HAIKU_MODEL=f),u&&(_.ANTHROPIC_DEFAULT_SONNET_MODEL=u),m&&(_.ANTHROPIC_DEFAULT_OPUS_MODEL=m,_.ANTHROPIC_MODEL=m);const A={...a};for(const[e,t]of Object.entries(i))e in A||(A[e]=t);A.showThinkingSummaries=!0;const P={...A,env:{...h,...Object.fromEntries(Object.entries(o).filter(([e])=>!(e in h))),ANTHROPIC_AUTH_TOKEN:e,ANTHROPIC_BASE_URL:g.getBaseUrl(),..._}};m?P.model=m:Object.prototype.hasOwnProperty.call(i,"model")?P.model=i.model:delete P.model,this.saveSettings(P)}ensureOnboardingCompleted(){try{const e=this.getMCPConfig();e.hasCompletedOnboarding||this.saveMCPConfig({...e,hasCompletedOnboarding:!0})}catch(e){c.warn("Failed to ensure onboarding completed:",e),c.logError("ClaudeCodeManager.ensureOnboardingCompleted",e)}}unloadPrivateConfig(){const e=this.getSettings();if(!e.env){if(void 0!==e.model){const{model:t,...n}=e;this.saveSettings(n)}return}const{ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:n,API_TIMEOUT_MS:s,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:o,CLAUDE_CODE_AUTO_MODE_SERVER:r,...i}=e.env,a={...i};for(const e of MODEL_ENV_VARS)delete a[e];const l={...e,env:a};delete l.model,l.env&&0===Object.keys(l.env).length&&delete l.env,this.saveSettings(l)}clearPinnedModels(e){const t=this.getSettings(),n=t.env,s=n?.ANTHROPIC_AUTH_TOKEN?Object.fromEntries(resolveTierFallbacks(e).map(e=>[e.envVar,e.to])):{},o=[];for(const e of MODEL_ENV_VARS)n&&e in n&&n[e]!==s[e]&&o.push(e);void 0!==t.model&&o.push("model");const r=Object.entries(s).some(([e,t])=>n?.[e]!==t);if(0===o.length&&!r)return[];const i={...t};if(delete i.model,n){const e={...n};for(const t of MODEL_ENV_VARS)delete e[t];Object.assign(e,s),0===Object.keys(e).length?delete i.env:i.env=e}return this.saveSettings(i),o}getLastTierFallbacks(){return[...this.lastTierFallbacks]}detectCurrentConfig(){try{const e=this.getSettings();return e.env&&e.env.ANTHROPIC_AUTH_TOKEN?{apiKey:e.env.ANTHROPIC_AUTH_TOKEN}:{apiKey:null}}catch{return{apiKey:null}}}getExperimentalFeature(e){const t=this.getSettings();return t.env?.[e]}setExperimentalFeature(e,t){const n=this.getSettings(),s=n.env||{},o={...n,env:{...s,[e]:t}};this.saveSettings(o)}removeExperimentalFeature(e){const t=this.getSettings();if(!t.env)return;const{[e]:n,...s}=t.env,o={...t,env:s};this.saveSettings(o)}}export const claudeCodeManager=ClaudeCodeManager.getInstance();
1
+ import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as o,renameSync as s,unlinkSync as i}from"fs";import{join as r,dirname as a}from"path";import{homedir as l}from"os";import{logger as c}from"../utils/logger.js";import{configManager as d,DEFAULT_MODELS as g}from"./config.js";import{loadSettingsTemplate as m}from"./settings-template.js";import{cleanupAnthropicEnvVars as C}from"./env-cleanup.js";import{getClaudeCodeTierChains as f,getGatewayModelRules as O}from"./model-registry.js";import{autoCompactTokens as h,prettyModelName as u}from"./gateway-models.js";import{baseModelId as _}from"./model-catalog.js";export const MODEL_ENV_VARS=["ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];const p={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"},E="CLAUDE_CODE_MAX_CONTEXT_TOKENS";function T(e,t=[]){if(!e||"object"!=typeof e)return!1;const{options:n,replaceBuiltInOptions:o}=e;if(!Array.isArray(n)||o)return!1;const s=new Set([...O().models.map(e=>e.id),...t]);return n.every(e=>e&&"object"==typeof e&&s.has(e.model))}export function applyGatewayModels(e,t){if(void 0===t)return e;const n={...e};if(void 0!==n.modelPicker&&!T(n.modelPicker,t.map(e=>e.id)))return n;const o=T(n.modelPicker)?n.modelPicker.options.map(e=>e.model):[],s={...n.env||{}},i={...n.modelSettings||{}};for(const e of o){if(!i[e])continue;const{autoCompactWindow:t,...n}=i[e];Object.keys(n).length>0?i[e]=n:delete i[e]}const r=t.map(e=>e.contextWindow).filter(e=>"number"==typeof e&&e>0);if(0===t.length)delete n.modelPicker,delete s[E];else{n.modelPicker={options:t.map(e=>({model:e.id,label:e.name||u(e.id),...e.description?{description:e.description}:{}}))},r.length>0&&(s[E]=String(Math.min(...r)));for(const e of t){if(!e.contextWindow)continue;const t=h(e.contextWindow,e.autoCompactTokens);i[e.id]={...i[e.id],autoCompactWindow:Math.min(Math.max(t,1e5),1e6)}}}return Object.keys(i).length>0?n.modelSettings=i:delete n.modelSettings,Object.keys(s).length>0?n.env=s:delete n.env,n}export function resolveTierFallbacks(e){if(!e||0===e.length)return[];const t=new Set(e.map(_)),n=[];for(const[e,o]of Object.entries(f())){const s=p[e],[i,...r]=o;if(!s||!i||t.has(i))continue;const a=r.find(e=>t.has(e));a&&n.push({tier:e,envVar:s,from:i,to:a})}return n}export class ClaudeCodeManager{static instance;settingsPath;mcpConfigPath;lastTierFallbacks=[];constructor(){this.settingsPath=r(l(),".claude","settings.json"),this.mcpConfigPath=r(l(),".claude.json")}static getInstance(){return ClaudeCodeManager.instance||(ClaudeCodeManager.instance=new ClaudeCodeManager),ClaudeCodeManager.instance}ensureConfigDir(n){const o=a(n);e(o)||t(o,{recursive:!0})}atomicWrite(t,n){const r=`${t}.tmp`;try{o(r,n,"utf-8"),s(r,t)}catch(t){if(e(r))try{i(r)}catch{}throw t}}getSettings(){try{if(e(this.settingsPath)){const e=n(this.settingsPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code settings:",e),c.logError("ClaudeCodeManager.getSettings",e)}return{}}saveSettings(e){try{this.ensureConfigDir(this.settingsPath),this.atomicWrite(this.settingsPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code settings: ${e}`)}}getMCPConfig(){try{if(e(this.mcpConfigPath)){const e=n(this.mcpConfigPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code MCP config:",e),c.logError("ClaudeCodeManager.getMCPConfig",e)}return{}}saveMCPConfig(e){try{this.ensureConfigDir(this.mcpConfigPath),this.atomicWrite(this.mcpConfigPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code MCP config: ${e}`)}}loadPrivateConfig(e,t,n,o){this.ensureOnboardingCompleted(),C();const s=m(),i=s.env||{},{env:r,...a}=s,l=this.getSettings(),{ANTHROPIC_API_KEY:c,...f}=l.env||{},O={...f};for(const e of MODEL_ENV_VARS)delete O[e];const h={},u=e=>{const n=(t[e]||"").trim();return n&&n!==g[e]?n:null},_=u("haiku"),p=u("sonnet"),E=u("opus"),T=new Set([_&&"haiku",p&&"sonnet",E&&"opus"].filter(Boolean));this.lastTierFallbacks=resolveTierFallbacks(n).filter(e=>!T.has(e.tier));for(const e of this.lastTierFallbacks)h[e.envVar]=e.to;_&&(h.ANTHROPIC_DEFAULT_HAIKU_MODEL=_),p&&(h.ANTHROPIC_DEFAULT_SONNET_MODEL=p),E&&(h.ANTHROPIC_DEFAULT_OPUS_MODEL=E,h.ANTHROPIC_MODEL=E);const A={...l};for(const[e,t]of Object.entries(a))e in A||(A[e]=t);A.showThinkingSummaries=!0;const P={...A,env:{...O,...Object.fromEntries(Object.entries(i).filter(([e])=>!(e in O))),ANTHROPIC_AUTH_TOKEN:e,ANTHROPIC_BASE_URL:d.getBaseUrl(),...h}};E?P.model=E:Object.prototype.hasOwnProperty.call(a,"model")?P.model=a.model:delete P.model,this.saveSettings(applyGatewayModels(P,o))}ensureOnboardingCompleted(){try{const e=this.getMCPConfig();e.hasCompletedOnboarding||this.saveMCPConfig({...e,hasCompletedOnboarding:!0})}catch(e){c.warn("Failed to ensure onboarding completed:",e),c.logError("ClaudeCodeManager.ensureOnboardingCompleted",e)}}unloadPrivateConfig(){const e=this.getSettings();if(!e.env){if(void 0!==e.model){const{model:t,...n}=e;this.saveSettings(n)}return}const{ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:n,API_TIMEOUT_MS:o,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:s,CLAUDE_CODE_AUTO_MODE_SERVER:i,...r}=e.env,a={...r};for(const e of MODEL_ENV_VARS)delete a[e];const l={...applyGatewayModels({...e,env:a},[])};l.env=l.env||{},delete l.model,l.env&&0===Object.keys(l.env).length&&delete l.env,this.saveSettings(l)}clearPinnedModels(e){const t=this.getSettings(),n=t.env,o=n?.ANTHROPIC_AUTH_TOKEN?Object.fromEntries(resolveTierFallbacks(e).map(e=>[e.envVar,e.to])):{},s=[];for(const e of MODEL_ENV_VARS)n&&e in n&&n[e]!==o[e]&&s.push(e);void 0!==t.model&&s.push("model");const i=Object.entries(o).some(([e,t])=>n?.[e]!==t);if(0===s.length&&!i)return[];const r={...t};if(delete r.model,n){const e={...n};for(const t of MODEL_ENV_VARS)delete e[t];Object.assign(e,o),0===Object.keys(e).length?delete r.env:r.env=e}return this.saveSettings(r),s}getLastTierFallbacks(){return[...this.lastTierFallbacks]}detectCurrentConfig(){try{const e=this.getSettings();return e.env&&e.env.ANTHROPIC_AUTH_TOKEN?{apiKey:e.env.ANTHROPIC_AUTH_TOKEN}:{apiKey:null}}catch{return{apiKey:null}}}getExperimentalFeature(e){const t=this.getSettings();return t.env?.[e]}setExperimentalFeature(e,t){const n=this.getSettings(),o=n.env||{},s={...n,env:{...o,[e]:t}};this.saveSettings(s)}removeExperimentalFeature(e){const t=this.getSettings();if(!t.env)return;const{[e]:n,...o}=t.env,s={...t,env:o};this.saveSettings(s)}}export const claudeCodeManager=ClaudeCodeManager.getInstance();
@@ -0,0 +1,23 @@
1
+ import { type GatewayModelSpec } from './model-registry.js';
2
+ import type { GatewayClientModel } from './api-validator.js';
3
+ /**
4
+ * Gateway models (Claude, domestic, Grok) vibecli adds to the coding tools'
5
+ * model menus, and the shared context rules: each model compacts at
6
+ * `autoCompactRatio` (80%) of its window unless the gateway sets a point.
7
+ */
8
+ export type GatewayModelTool = 'codex' | 'claude-code';
9
+ /** Auto-compaction point for a window: the explicit value (capped at the window) or the ratio. */
10
+ export declare function autoCompactTokens(window: number, explicit?: number): number;
11
+ /**
12
+ * The models to add for `tool`. When the gateway publishes its client config
13
+ * (`/api/platform/vibecode/config`) its lists win — fields it leaves out keep the
14
+ * 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). Otherwise
16
+ * the built-in list from `models.json` → `gatewayModels`.
17
+ */
18
+ export declare function gatewayModelSpecs(tool: GatewayModelTool, clientModels?: Record<string, GatewayClientModel[]>): GatewayModelSpec[];
19
+ /**
20
+ * Menu label for a model id nobody named: `glm-5.3-flash` → `GLM 5.3 Flash`,
21
+ * `claude-opus-5-5` → `Claude Opus 5.5`, `qwen3.8-max` → `Qwen 3.8 Max`.
22
+ */
23
+ export declare function prettyModelName(id: string): string;
@@ -0,0 +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(t,o){const n=e().models.filter(e=>function(e,t){return"codex"===e||!t.id.startsWith("claude-")&&!1!==t.claudeCode}(t,e));if(!o)return n;const i=new Map(n.map(e=>[e.id,e])),s="codex"===t?[...o.codex??[],...(o.claude??[]).filter(e=>e.id.startsWith("claude-")&&i.has(e.id))]:(o.claude??[]).filter(e=>!e.id.startsWith("claude-")&&(i.get(e.id)?.claudeCode??!0));if(0===s.length)return n;const a=new Set,r=[];for(const e of s)a.has(e.id)||(a.add(e.id),r.push({...i.get(e.id),...e}));return r}const t={gpt:"GPT",glm:"GLM",deepseek:"DeepSeek",minimax:"MiniMax",qwen:"Qwen"};export function prettyModelName(e){const o=e.replace(/^([a-z]+)(\d)/i,"$1 $2").split(/[-_\s]+/).filter(Boolean),n=[];for(const e of o){const o=n[n.length-1];if(/^\d+$/.test(e)&&o&&/^\d+$/.test(o)&&e.length<=2&&!/^\d{8}$/.test(e)){n[n.length-1]=`${o}.${e}`;continue}const i=e.toLowerCase();n.push(t[i]??(/^[a-z]\d/i.test(e)?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))}return n.join(" ")}
@@ -1,4 +1,4 @@
1
- import { type GatewayGroupModel } from './api-validator.js';
1
+ import { type GatewayClientModel, type GatewayGroupModel } from './api-validator.js';
2
2
  /**
3
3
  * What a key can actually reach on the gateway, resolved once per apply so
4
4
  * adapters that advertise a model list (Claude Desktop) can offer every model
@@ -15,6 +15,11 @@ export interface ModelCatalog {
15
15
  oneMillionSource: 'gateway' | 'fallback';
16
16
  /** Console group names whose model table matched this key (empty when none did). */
17
17
  matchedGroups: string[];
18
+ /**
19
+ * Per-tool model lists the gateway publishes for coding clients (names, context
20
+ * windows, compaction points). Absent when the gateway has no such endpoint.
21
+ */
22
+ clientModels?: Record<string, GatewayClientModel[]>;
18
23
  }
19
24
  /** Strip a bracketed context-variant suffix: `claude-opus-4-8[1m]` → `claude-opus-4-8`. */
20
25
  export declare function baseModelId(id: string): string;
@@ -1 +1 @@
1
- import{logger as e}from"../utils/logger.js";import{fetchModels as o,fetchGatewayStatus as t}from"./api-validator.js";import{getClaudeDesktopRules as l}from"./model-registry.js";export function baseModelId(e){return e.replace(/\[[^\]]*\]$/,"").trim()}export function isClaudeModel(e){return/claude/i.test(baseModelId(e))}export function matchGroups(e,o){const t=new Set(e.map(baseModelId));if(0===t.size)return[];const l=[],r=[];for(const[e,n]of Object.entries(o)){const o=new Set(n.map(e=>baseModelId(e.name)).filter(isClaudeModel));[...t].every(e=>o.has(e))&&(o.size===t.size?l:r).push(e)}return l.length>0?l:r}export function resolveOneMillion(e,o){const t=l(),r=[...new Set(e.map(baseModelId))],n=new Set(e.filter(e=>/\[1m\]/i.test(e)).map(baseModelId)),s={};let a,i="fallback",d=[];if(o&&(d=matchGroups(r,o)),d.length>0){i="gateway",a=new Set(r);for(const e of d){const t=new Map(o[e].map(e=>[baseModelId(e.name),e]));for(const e of r){const o=t.get(e);o?.labelOverride&&!s[e]&&(s[e]=o.labelOverride),!0!==o?.supports1m&&a.delete(e)}}}else{const e=new Set(t.oneMillionFallback);a=new Set(r.filter(o=>e.has(o)))}for(const e of n)a.add(e);for(const e of t.oneMillionExclusions)if(r.some(o=>o.startsWith(e.whenPrefixPresent)))for(const o of e.models)a.delete(o);return{oneMillion:[...a],labels:s,oneMillionSource:i,matchedGroups:d}}export async function resolveModelCatalog(l){try{const[e,r]=await Promise.all([o(l),t()]);if(!e.ok||0===e.models.length)return null;const n=[...new Set(e.models.map(e=>e.trim()).filter(Boolean))],s=n.filter(isClaudeModel);return{models:n,...resolveOneMillion(s,r.ok?r.claudeDesktopGroupModels:null)}}catch(o){return e.logError("resolveModelCatalog",o),null}}
1
+ import{logger as e}from"../utils/logger.js";import{fetchClientModelConfig as o,fetchModels as t,fetchGatewayStatus as l}from"./api-validator.js";import{getClaudeDesktopRules as n}from"./model-registry.js";export function baseModelId(e){return e.replace(/\[[^\]]*\]$/,"").trim()}export function isClaudeModel(e){return/claude/i.test(baseModelId(e))}export function matchGroups(e,o){const t=new Set(e.map(baseModelId));if(0===t.size)return[];const l=[],n=[];for(const[e,r]of Object.entries(o)){const o=new Set(r.map(e=>baseModelId(e.name)).filter(isClaudeModel));[...t].every(e=>o.has(e))&&(o.size===t.size?l:n).push(e)}return l.length>0?l:n}export function resolveOneMillion(e,o){const t=n(),l=[...new Set(e.map(baseModelId))],r=new Set(e.filter(e=>/\[1m\]/i.test(e)).map(baseModelId)),s={};let i,a="fallback",d=[];if(o&&(d=matchGroups(l,o)),d.length>0){a="gateway",i=new Set(l);for(const e of d){const t=new Map(o[e].map(e=>[baseModelId(e.name),e]));for(const e of l){const o=t.get(e);o?.labelOverride&&!s[e]&&(s[e]=o.labelOverride),!0!==o?.supports1m&&i.delete(e)}}}else{const e=new Set(t.oneMillionFallback);i=new Set(l.filter(o=>e.has(o)))}for(const e of r)i.add(e);for(const e of t.oneMillionExclusions)if(l.some(o=>o.startsWith(e.whenPrefixPresent)))for(const o of e.models)i.delete(o);return{oneMillion:[...i],labels:s,oneMillionSource:a,matchedGroups:d}}export async function resolveModelCatalog(n){try{const[e,r,s]=await Promise.all([t(n),l(),o()]);if(!e.ok||0===e.models.length)return null;const i=[...new Set(e.models.map(e=>e.trim()).filter(Boolean))],a=i.filter(isClaudeModel);return{models:i,...resolveOneMillion(a,r.ok?r.claudeDesktopGroupModels:null),...s?{clientModels:s}:{}}}catch(o){return e.logError("resolveModelCatalog",o),null}}
@@ -34,6 +34,30 @@ export interface ClaudeCodeRules {
34
34
  */
35
35
  tierChains: Record<string, string[]>;
36
36
  }
37
+ /**
38
+ * One gateway model vibecli adds to the coding tools' model menus (Codex's
39
+ * catalog, Claude Code's `/model` picker), on top of what each tool ships with.
40
+ */
41
+ export interface GatewayModelSpec {
42
+ id: string;
43
+ name?: string;
44
+ description?: string;
45
+ contextWindow?: number;
46
+ /** Explicit auto-compaction point; defaults to `autoCompactRatio` of the window. */
47
+ autoCompactTokens?: number;
48
+ /** `false` keeps the model out of Claude Code's picker (its window differs from the rest). */
49
+ claudeCode?: boolean;
50
+ }
51
+ export interface GatewayModelRules {
52
+ /** Auto-compact at this fraction of the context window unless a model sets its own limit. */
53
+ autoCompactRatio: number;
54
+ models: GatewayModelSpec[];
55
+ }
56
+ /** Codex-only catalog defaults. */
57
+ export interface CodexRules {
58
+ /** Window every model is capped to when the user turns 1M context off. */
59
+ standardContextWindow: number;
60
+ }
37
61
  export interface ModelRegistryData {
38
62
  defaultModels: Models;
39
63
  /** Default model for non-Claude tools (Codex/OpenCode/OpenClaw/Hermes/AtomCode/Grok). */
@@ -43,6 +67,10 @@ export interface ModelRegistryData {
43
67
  presets: ModelPreset[];
44
68
  claudeCode?: Partial<ClaudeCodeRules>;
45
69
  claudeDesktop?: Partial<ClaudeDesktopRules>;
70
+ gatewayModels?: Partial<GatewayModelRules>;
71
+ codex?: Partial<CodexRules>;
72
+ /** Oldest tool release vibecli's written config works with (tool id → semver). */
73
+ toolMinVersions?: Record<string, string>;
46
74
  }
47
75
  export declare function getDefaultModels(): Models;
48
76
  /** The model non-Claude tools use unless the user configured something else. */
@@ -57,4 +85,7 @@ export declare function getPresets(): ModelPreset[];
57
85
  export declare function resolvePreset(preset: ModelPreset): Models;
58
86
  export declare function getClaudeCodeTierChains(): Record<string, string[]>;
59
87
  export declare function getClaudeDesktopRules(): ClaudeDesktopRules;
88
+ export declare function getGatewayModelRules(): GatewayModelRules;
89
+ export declare function getCodexRules(): CodexRules;
90
+ export declare function getToolMinVersion(toolName: string): string | null;
60
91
  export declare function reloadRegistry(): void;
@@ -1 +1 @@
1
- import{dirname as o,join as e}from"path";import{fileURLToPath as t}from"url";import{existsSync as n,readFileSync as l}from"fs";const r=o(t(import.meta.url));let s=null;function u(){return s||(s=function(){const o=[e(r,"..","..","models.json"),e(r,"..","models.json"),e(r,"models.json")];for(const e of o)if(n(e))return JSON.parse(l(e,"utf-8"));throw new Error(`models.json not found, searched: ${o.join(", ")}`)}()),s}export function getDefaultModels(){return{...u().defaultModels}}export function getDefaultToolModel(){return u().defaultToolModel?.trim()||"gpt-5.5"}export function getToolDefaultModel(o){const e=u().toolDefaults;return e&&Object.prototype.hasOwnProperty.call(e,o)?(e[o]??"").trim():getDefaultToolModel()}export function getPresets(){return[...u().presets]}export function resolvePreset(o){return o.models?{...o.models}:o.model?{haiku:o.model,sonnet:o.model,opus:o.model,reasoning:o.model}:getDefaultModels()}export function getClaudeCodeTierChains(){const o=u().claudeCode?.tierChains??{};return Object.fromEntries(Object.entries(o).map(([o,e])=>[o,[...e]]))}export function getClaudeDesktopRules(){const o=u().claudeDesktop??{};return{oneMillionFallback:[...o.oneMillionFallback??[]],oneMillionExclusions:(o.oneMillionExclusions??[]).map(o=>({...o,models:[...o.models]}))}}export function reloadRegistry(){s=null}
1
+ import{dirname as o,join as e}from"path";import{fileURLToPath as t}from"url";import{existsSync as n,readFileSync as l}from"fs";const r=o(t(import.meta.url));let s=null;function u(){return s||(s=function(){const o=[e(r,"..","..","models.json"),e(r,"..","models.json"),e(r,"models.json")];for(const e of o)if(n(e))return JSON.parse(l(e,"utf-8"));throw new Error(`models.json not found, searched: ${o.join(", ")}`)}()),s}export function getDefaultModels(){return{...u().defaultModels}}export function getDefaultToolModel(){return u().defaultToolModel?.trim()||"gpt-5.5"}export function getToolDefaultModel(o){const e=u().toolDefaults;return e&&Object.prototype.hasOwnProperty.call(e,o)?(e[o]??"").trim():getDefaultToolModel()}export function getPresets(){return[...u().presets]}export function resolvePreset(o){return o.models?{...o.models}:o.model?{haiku:o.model,sonnet:o.model,opus:o.model,reasoning:o.model}:getDefaultModels()}export function getClaudeCodeTierChains(){const o=u().claudeCode?.tierChains??{};return Object.fromEntries(Object.entries(o).map(([o,e])=>[o,[...e]]))}export function getClaudeDesktopRules(){const o=u().claudeDesktop??{};return{oneMillionFallback:[...o.oneMillionFallback??[]],oneMillionExclusions:(o.oneMillionExclusions??[]).map(o=>({...o,models:[...o.models]}))}}export function getGatewayModelRules(){const o=u().gatewayModels??{};return{autoCompactRatio:o.autoCompactRatio??.8,models:(o.models??[]).map(o=>({...o}))}}export function getCodexRules(){return{standardContextWindow:u().codex?.standardContextWindow??272e3}}export function getToolMinVersion(o){return u().toolMinVersions?.[o]?.trim()||null}export function reloadRegistry(){s=null}
@@ -52,6 +52,13 @@ export declare class ToolManager {
52
52
  }): Promise<void>;
53
53
  /** Post-apply follow-ups the adapter wants shown to the user (may be empty). */
54
54
  applyNotes(toolName: string): string[];
55
+ /** `<command> --version` of the installed tool, as `x.y.z`; null when absent or unparsable. */
56
+ installedVersion(toolName: string): string | null;
57
+ /** The installed and required versions when the tool is older than `models.json` → `toolMinVersions`. */
58
+ outdatedVersion(toolName: string): {
59
+ current: string;
60
+ min: string;
61
+ } | null;
55
62
  unloadPrivateConfig(toolName: string): void;
56
63
  /**
57
64
  * Clear the tool's pinned model, keeping its credentials. Also drops this
@@ -76,4 +83,6 @@ export declare class ToolManager {
76
83
  getSupportedTools(): ToolInfo[];
77
84
  isGitInstalled(): boolean;
78
85
  }
86
+ /** Compare dotted numeric versions (`2.1.9` < `2.1.10`); missing parts count as 0. */
87
+ export declare function compareVersions(a: string, b: string): number;
79
88
  export declare const toolManager: ToolManager;