@hifullmoon/aicommit 2.6.9 → 2.6.11

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.
@@ -1,155 +1,6 @@
1
1
  {
2
- "schemaVersion": 1,
3
- "defaultProvider": "minimax",
4
- "providers": {
5
- "minimax": {
6
- "providerType": "minimax",
7
- "apiUrl": "https://api.minimaxi.com/v1/chat/completions",
8
- "apiKeyEnv": "MINIMAX_API_KEY",
9
- "defaultModel": "default",
10
- "models": {
11
- "default": {
12
- "modelId": "MiniMax-M3",
13
- "reasoning": {
14
- "mode": "on",
15
- "effort": "medium"
16
- }
17
- }
18
- }
19
- },
20
- "deepseek": {
21
- "providerType": "deepseek",
22
- "apiUrl": "https://api.deepseek.com/v1/chat/completions",
23
- "apiKeyEnv": "DEEPSEEK_API_KEY",
24
- "defaultModel": "chat",
25
- "models": {
26
- "chat": {
27
- "modelId": "deepseek-v4-flash",
28
- "reasoning": {
29
- "mode": "on",
30
- "effort": "high"
31
- }
32
- }
33
- }
34
- },
35
- "openrouter": {
36
- "providerType": "openrouter",
37
- "apiUrl": "https://openrouter.ai/api/v1/chat/completions",
38
- "apiKeyEnv": "OPENROUTER_API_KEY",
39
- "defaultModel": "fast",
40
- "models": {
41
- "fast": {
42
- "modelId": "openai/gpt-4o-mini"
43
- },
44
- "quality": {
45
- "modelId": "openai/gpt-4o"
46
- }
47
- }
48
- },
49
- "kimi-code": {
50
- "providerType": "custom",
51
- "apiUrl": "https://api.kimi.com/coding/v1/chat/completions",
52
- "apiKeyEnv": "KIMI_API_KEY",
53
- "defaultModel": "default",
54
- "models": {
55
- "default": {
56
- "modelId": "kimi-for-coding"
57
- }
58
- }
59
- },
60
- "ollama": {
61
- "providerType": "ollama",
62
- "apiUrl": "http://127.0.0.1:11434/api/chat",
63
- "defaultModel": "qwen",
64
- "models": {
65
- "qwen": {
66
- "modelId": "qwen3:8b"
67
- },
68
- "deepseek": {
69
- "modelId": "deepseek-r1:14b"
70
- }
71
- }
72
- }
73
- },
74
- "language": "en",
75
- "commitPolicy": {
76
- "version": 1,
77
- "types": ["feat", "fix", "chore", "docs", "refactor", "test", "style", "perf", "ci", "build"],
78
- "scope": {
79
- "mode": "optional",
80
- "values": []
81
- },
82
- "subject": {
83
- "maxLength": 72
84
- },
85
- "body": {
86
- "mode": "optional",
87
- "maxLines": 8
88
- },
89
- "breakingChange": "allow",
90
- "language": "inherit"
91
- },
92
- "allowProjectPrompt": false,
93
- "prompt": "",
94
- "repositoryContext": {
95
- "enabled": true,
96
- "maxChars": 4000,
97
- "recentCommits": {
98
- "enabled": true,
99
- "count": 12,
100
- "maxChars": 1000
101
- },
102
- "packageBoundaries": {
103
- "enabled": true,
104
- "maxEntries": 40,
105
- "maxChars": 800
106
- },
107
- "conventions": {
108
- "enabled": true,
109
- "trustedFiles": [],
110
- "maxFiles": 4,
111
- "maxChars": 1400
112
- },
113
- "commitlint": {
114
- "enabled": true,
115
- "maxChars": 800
116
- }
117
- },
118
- "maxTokens": 1024,
119
- "timeoutMs": 120000,
120
- "retry": {
121
- "maxAttempts": 3,
122
- "baseDelayMs": 500,
123
- "maxDelayMs": 5000
124
- },
125
- "credentialHelper": {
126
- "enabled": false,
127
- "username": "aicommit"
128
- },
129
- "maxDiffChars": 30000,
130
- "maxFileDiffChars": 3000,
131
- "splitMaxDiffChars": 16000,
132
- "splitMaxPlanFiles": 100,
133
- "diffContextLines": 1,
134
- "regenerateWithDiff": false,
135
- "reasoning": {
136
- "mode": "on",
137
- "effort": "medium",
138
- "maxTokens": 4096,
139
- "maxDisplayChars": 12000
140
- },
141
- "stripFiles": ["*.min.js", "*.map", "*.snap"],
142
- "largeChange": {
143
- "strategy": "auto",
144
- "chunkInputTokens": 12000,
145
- "maxTotalTokens": 200000,
146
- "concurrency": 2,
147
- "timeoutMs": 180000,
148
- "cache": {
149
- "enabled": true,
150
- "ttlMs": 86400000,
151
- "maxBytes": 33554432,
152
- "allowUnprotected": false
153
- }
154
- }
2
+ "provider": "minimax",
3
+ "model": "MiniMax-M3.1-Flash",
4
+ "apiKeyEnv": "MINIMAX_API_KEY",
5
+ "language": "zh"
155
6
  }
package/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@ This file lists notable user-facing changes. Internal refactors, test-only chang
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [2.6.11] - 2026-11-19
8
+
9
+ ### Added
10
+
11
+ - Accept a compact provider, model, credential, and language configuration alongside existing provider catalogs. Setup uses the built-in thinking defaults for new profiles and preserves explicit settings on existing profiles.
12
+
13
+ ### Fixed
14
+
15
+ - Large-change split planning respects the configured reasoning budget and sends the selected thinking effort to MiniMax M3.1. An exhausted output budget is reported separately from malformed JSON.
16
+ - Reviewing or editing messages no longer consumes the next generation round's deadline. Token and request limits still apply across rounds.
17
+ - Regeneration uses bounded evidence from the original change snapshot and, in split mode, from the selected group. Truncated responses require recovery or manual editing, and edited messages must pass policy validation before use.
18
+
19
+ ## [2.6.10] - 2026-10-21
20
+
21
+ ### Fixed
22
+
23
+ - MiniMax M3.1 models retain their required thinking mode during follow-up requests, preventing split planning from failing with HTTP 400 when thinking is disabled.
24
+
7
25
  ## [2.6.9] - 2026-10-08
8
26
 
9
27
  ### Fixed
@@ -296,7 +314,9 @@ This file lists notable user-facing changes. Internal refactors, test-only chang
296
314
  - Added file-level split planning and execution with Git-state concurrency checks.
297
315
  - Added provider presets and user/project configuration boundaries.
298
316
 
299
- [Unreleased]: https://github.com/hi-fullmoon/AICommit/compare/v2.6.9...HEAD
317
+ [Unreleased]: https://github.com/hi-fullmoon/AICommit/compare/v2.6.11...HEAD
318
+ [2.6.11]: https://github.com/hi-fullmoon/AICommit/tree/v2.6.11
319
+ [2.6.10]: https://github.com/hi-fullmoon/AICommit/tree/v2.6.10
300
320
  [2.6.9]: https://github.com/hi-fullmoon/AICommit/tree/v2.6.9
301
321
  [2.6.8]: https://github.com/hi-fullmoon/AICommit/tree/v2.6.8
302
322
  [2.6.7]: https://github.com/hi-fullmoon/AICommit/tree/v2.6.7
package/README.md CHANGED
@@ -75,7 +75,12 @@ aicommit setup
75
75
 
76
76
  It walks you through choosing built-in provider defaults (OpenAI, DeepSeek, OpenRouter, MiniMax, Kimi Code, and Ollama) or entering a custom OpenAI-compatible endpoint, then entering your API key and one or more models, choosing a default model and commit language, and optionally testing the connection. Configuration is written atomically to the user config (`~/.aicommit/config.json`); a malformed or old-format existing file is backed up before replacement. The legacy `~/.aicommit.config.json` path remains readable and `aicommit setup` migrates its settings to the canonical path when saving.
77
77
 
78
- The model step configures reasoning independently for each profile. `auto` sends no explicit reasoning switch and leaves the behavior to the provider, `on` requests reasoning and then prompts for its effort, and `off` explicitly disables reasoning when the model supports that switch. Effort defaults to `medium`. For known OpenAI models, setup removes unsupported mode and effort choices, including `off` when reasoning cannot be disabled. When editing an existing model, the wizard preselects valid saved values, falling back to the global reasoning settings when applicable; an unsupported saved mode falls back to `auto`.
78
+ For everyday use, configure only the provider, credentials, model, and language. Reasoning defaults to on with medium effort; output budgets, batching, caching, and retries use built-in defaults. The wizard no longer asks per-model reasoning questions and preserves existing explicit settings.
79
+
80
+ Use [.aicommit.config.example.json](.aicommit.config.example.json) as the minimal configuration; advanced fields are optional.
81
+
82
+ <details>
83
+ <summary>Advanced configuration and multiple providers</summary>
79
84
 
80
85
  To configure by hand, start from [.aicommit.config.example.json](.aicommit.config.example.json). User config is loaded first, then allow-listed generation preferences from the project config at `./.aicommit.config.json` are deep-merged over it. Project config may set `language`, `commitPolicy`, `stripFiles`, `temperature`, and lower diff/token/timeout or repository-context ceilings. A project-owned `prompt` is ignored unless the user config explicitly sets `allowProjectPrompt: true`. Connection/provider fields (including `apiKeyEnv`), reasoning request controls, unknown keys, and attempts to raise a ceiling are ignored with a warning. This prevents a cloned repository from redirecting an authenticated request or silently increasing its cost/data scope.
81
86
 
@@ -190,7 +195,7 @@ aicommit -p deepseek -m reasoner
190
195
 
191
196
  `schemaVersion`, `defaultProvider`, `providers`, and every provider's `providerType`, `apiUrl`, `defaultModel`, and non-empty `models` map are required. Without `-p`, AICommit selects `defaultProvider`; without `-m`, it selects that provider's `defaultModel`. Model profiles inherit global generation settings and provider connection settings, then may override `temperature`, `maxTokens`, `timeoutMs`, `reasoning`, and `extraBody`. Provider and model names are stable local aliases; `modelId` is the identifier sent to the API.
192
197
 
193
- This is the only supported user-config shape. Earlier flat or provider-level `modelId` configurations are rejected; run `aicommit setup` or migrate them explicitly.
198
+ The requirements above apply to the expanded catalog. The compact format shown earlier uses `model` instead of `modelId`. Legacy flat or provider-level `modelId` configurations are still rejected; run `aicommit setup` or migrate them explicitly.
194
199
 
195
200
  | Key | Description |
196
201
  | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -221,10 +226,12 @@ This is the only supported user-config shape. Earlier flat or provider-level `mo
221
226
  | `largeChange` | Large-change strategy, budgets, and short-lived chunk recovery cache; personal config only, retaining protected summaries for 24 hours up to 32 MiB by default |
222
227
  | `diffContextLines` | Context lines around each diff hunk (`git diff --unified=<n>`); lower values mean fewer tokens (default: `1`) |
223
228
  | `stripFiles` | Extra files to stub out of the diff like lock files, matched by basename with `*`/`?` wildcards, e.g. `["*.min.js", "*.map", "*.snap"]` (default: `[]`; project-level entries are merged with user-level ones, not replaced) |
224
- | `regenerateWithDiff` | `true` re-sends the full diff on every regenerate for more varied rewrites; `false` (default) only asks the model to reword its previous message, which is far cheaper |
229
+ | `regenerateWithDiff` | `true` re-sends the full diff on every regenerate; `false` (default) uses the previous message and up to 6,000 characters of change evidence to correct omissions and wording |
225
230
  | `extraBody` | Model-profile JSON fields merged into the request body, except `model`/`messages` (default: `{}`) |
226
231
  | `reasoning` | Global or model-profile reasoning controls: `mode` / `effort` (default: `on` / `medium`), `maxTokens`, and `maxDisplayChars` |
227
232
 
233
+ </details>
234
+
228
235
  Works with OpenAI, DeepSeek, [OpenRouter](https://openrouter.ai), MiniMax, [Kimi Code](https://www.kimi.com/code/docs/), Ollama (native `/api/chat` or OpenAI-compatible `/v1/chat/completions`), LiteLLM, and other compatible endpoints. HTTPS is required for remote endpoints; plaintext HTTP is accepted only for localhost/loopback.
229
236
 
230
237
  See the bilingual [provider compatibility table](docs/provider-compatibility.md) for streaming, reasoning, token-budget, usage, and authentication boundaries.
@@ -513,6 +520,8 @@ The default `largeChange.strategy: "auto"` inventories every file locally, group
513
520
 
514
521
  A normal commit typically needs one model request, with no per-file AI calls or recursive model reduction. The inventory contains at most 16 representative groups under a UTF-8 byte budget, prioritizing coverage across code, configuration, tests, and other categories. It explicitly describes sampling limits. Both terminal and JSON output distinguish fully analyzed files, representative excerpts, and metadata-only files. Provider retries, response recovery, policy correction, and user-requested regeneration can still add requests.
515
522
 
523
+ `largeChange.timeoutMs` bounds each active generation round, including its analysis and automatic retries. Reviewing or editing a message does not consume that time; a user-requested retry or regeneration starts a fresh deadline. Total token and request limits remain cumulative across rounds.
524
+
516
525
  Split mode builds local candidates and sends them in bounded batches of at most `splitMaxPlanFiles`, then merges the batch plans hierarchically. When an `auto` inventory exceeds four times that candidate limit, adjacent candidates are first bundled locally by top-level module, file kind, and Git status; the model receives compact counts, examples, and selected excerpts while the complete file mapping stays local. Every file remains represented even when the complete candidate inventory cannot fit one request. Exhausted analysis budgets stop without committing; increase the budget or use smaller batches. If the hierarchy cannot converge while budget remains, an all-files commit message can be generated from local change summaries; non-interactive committing requires `--allow-single-fallback`. Plans omitting files or hunks are rejected instead of creating an automatic "update remaining files" commit. Small changes keep the existing request path.
517
526
 
518
527
  For exhaustive chunk-by-chunk model analysis, opt in through personal configuration:
package/README.zh-CN.md CHANGED
@@ -77,7 +77,12 @@ aicommit setup
77
77
 
78
78
  向导会引导你选择内置 Provider 默认值(OpenAI、DeepSeek、OpenRouter、MiniMax、Kimi Code 和 Ollama),或填写自定义 OpenAI 兼容端点;随后输入 API Key 和一个或多个模型、选择默认模型和提交信息语言,并可选测试连接。配置会原子写入用户配置文件 `~/.aicommit/config.json`;如果已有文件格式错误或属于旧格式,替换前会先备份。旧路径 `~/.aicommit.config.json` 仍可读取,运行 `aicommit setup` 并保存时会把其中设置迁移到规范路径。
79
79
 
80
- 模型步骤会为每个配置单独设置推理。`auto` 不发送显式推理开关,交给 Provider 使用默认行为;`on` 请求推理并继续选择强度;`off` 在模型支持该开关时显式关闭推理。强度默认为 `medium`。对于已知的 OpenAI 模型,setup 会过滤不支持的模式和强度选项;无法关闭推理时也不会列出 `off`。编辑已有模型时,向导会回填其中仍有效的保存值;模型级未配置时,则在适用情况下回填全局推理设置,不再受支持的旧模式会回退到 `auto`。
80
+ 日常只需配置 Provider、凭据、模型和语言。思考默认开启、强度为 `medium`,输出预算、分批、缓存与重试采用内置默认值;向导不再逐个询问思考参数,编辑已有模型时会保留显式设置。
81
+
82
+ 最小配置见 [.aicommit.config.example.json](.aicommit.config.example.json),无需复制全部高级参数。
83
+
84
+ <details>
85
+ <summary>高级配置与多 Provider 示例</summary>
81
86
 
82
87
  如需手动配置,请从 [.aicommit.config.example.json](.aicommit.config.example.json) 开始。AICommit 先加载用户配置,再将项目配置 `./.aicommit.config.json` 中白名单内的生成偏好深度合并到用户配置之上。项目配置可以设置 `language`、`commitPolicy`、`stripFiles`、`temperature`,也可以降低 diff、token、timeout 或仓库上下文上限。项目拥有的 `prompt` 默认会被忽略,除非用户配置明确设置 `allowProjectPrompt: true`。连接或 Provider 字段(包括 `apiKeyEnv`)、推理请求控制、未知字段,以及任何试图提高上限的配置,都会被忽略并给出警告。这样可以防止克隆的仓库重定向已鉴权请求,或在不知情的情况下扩大成本和数据范围。
83
88
 
@@ -192,7 +197,7 @@ aicommit -p deepseek -m reasoner
192
197
 
193
198
  `schemaVersion`、`defaultProvider`、`providers`,以及每个 Provider 的 `providerType`、`apiUrl`、`defaultModel` 和非空 `models` 都是必填项。未指定 `-p` 时选择 `defaultProvider`;未指定 `-m` 时选择该 Provider 的 `defaultModel`。模型配置会继承全局生成设置和 Provider 连接设置,并可覆盖 `temperature`、`maxTokens`、`timeoutMs`、`reasoning` 与 `extraBody`。Provider 名和模型名是稳定的本地别名,`modelId` 才是发送给 API 的模型标识。
194
199
 
195
- 这是唯一支持的用户配置格式。旧版扁平配置或 Provider 级 `modelId` 会被直接拒绝;请运行 `aicommit setup` 或显式迁移。
200
+ 上述必填项适用于完整的 Provider 配置。前面的精简格式使用 `model`,而不是 `modelId`。旧版扁平配置或 Provider 级 `modelId` 仍会被拒绝;请运行 `aicommit setup` 或手动迁移。
196
201
 
197
202
  | 配置项 | 说明 |
198
203
  | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
@@ -223,10 +228,12 @@ aicommit -p deepseek -m reasoner
223
228
  | `largeChange` | 大变更策略、预算和短期分块恢复缓存;缓存只接受个人配置,默认保留受保护摘要 24 小时、最多 32 MiB |
224
229
  | `diffContextLines` | 每个 diff hunk 周围的上下文行数(`git diff --unified=<n>`);越小越节省 token(默认:`1`) |
225
230
  | `stripFiles` | 额外替换为占位的文件,按 basename 使用 `*` / `?` 通配,如 `["*.min.js", "*.map", "*.snap"]`(默认:`[]`;项目项与用户项合并而非覆盖) |
226
- | `regenerateWithDiff` | `true` 表示每次重写都重发完整 diff,以获得更多变化;`false`(默认)只要求模型改写上一条消息,成本更低 |
231
+ | `regenerateWithDiff` | `true` 表示每次重写都重发完整 diff;`false`(默认)携带上一条消息和最多 6,000 个字符的变更证据,用于纠正遗漏并调整措辞 |
227
232
  | `extraBody` | 模型配置中合并到请求体的 JSON 字段,但不允许覆盖 `model` / `messages`(默认:`{}`) |
228
233
  | `reasoning` | 全局或模型级推理控制:`mode` / `effort`(默认:`on` / `medium`)、`maxTokens` 和 `maxDisplayChars` |
229
234
 
235
+ </details>
236
+
230
237
  AICommit 支持 OpenAI、DeepSeek、[OpenRouter](https://openrouter.ai)、MiniMax、[Kimi Code](https://www.kimi.com/code/docs/)、Ollama(原生 `/api/chat` 或 OpenAI 兼容 `/v1/chat/completions`)、LiteLLM,以及其他兼容端点。远程端点必须使用 HTTPS;明文 HTTP 只允许 localhost / loopback。
231
238
 
232
239
  流式输出、推理、token 预算、usage 和鉴权边界,请参阅双语 [Provider 兼容表](docs/provider-compatibility.md)。
@@ -515,6 +522,8 @@ exec zsh
515
522
 
516
523
  普通提交通常只需要一次模型请求,不会为每个文件调用 AI,也不会递归调用模型汇总。摘要最多包含 16 个代表组,并受 UTF-8 字节预算约束;优先覆盖代码、配置和测试等不同类别。摘要明确说明抽样范围,界面和 JSON 分别报告全文分析、代表片段和仅元数据的文件数,不把抽样视为完整理解。提供方重试、响应恢复、格式修正和用户重新生成仍可能增加请求。
517
524
 
525
+ `largeChange.timeoutMs` 限制每轮实际生成的时间,包括该轮分析和自动重试。阅读或编辑消息不消耗这段时间;用户主动重试或重新生成时会开始新的计时。总 token 限额和请求次数仍跨轮累计。
526
+
518
527
  批次提交先在本地建立候选组,再按每批最多 `splitMaxPlanFiles` 个候选发送,并分层合并各批计划。当 `auto` 清单规模超过该候选上限的四倍时,会先按顶层模块、文件类型和 Git 状态在本地归并相邻候选;模型只接收紧凑计数、少量路径示例和代表片段,完整文件映射始终留在本地。完整候选清单放不进一次请求时,仍会保留每个文件。分析预算耗尽时停止提交,保留变更并提示提高预算或减少单批文件。如果分层规划无法收敛且预算仍充足,可根据本地变更摘要生成覆盖全部文件的单次提交;非交互提交需要 `--allow-single-fallback`。遗漏文件或 hunk 的计划会被拒绝,不再自动生成“更新其余文件”。小变更保持原有请求路径。
519
528
 
520
529
  确实需要逐块 AI 分析时,在个人配置中设置:
@@ -33,7 +33,7 @@ The release workflow uses npm Trusted Publishing without a long-lived `NPM_TOKEN
33
33
  ```bash
34
34
  workdir=$(mktemp -d)
35
35
  cd "$workdir"
36
- npm install --package-lock-only @hifullmoon/aicommit@2.6.9
36
+ npm install --package-lock-only @hifullmoon/aicommit@2.6.11
37
37
  npm audit signatures
38
38
  ```
39
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hifullmoon/aicommit",
3
- "version": "2.6.9",
3
+ "version": "2.6.11",
4
4
  "description": "AI Git commit message CLI for Conventional Commits with OpenAI, DeepSeek, OpenRouter and local Ollama models",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,7 +21,10 @@ export function estimateTokens(text) {
21
21
 
22
22
  export function createAnalysisBudget(settings = {}) {
23
23
  const limits = { ...DEFAULT_LARGE_CHANGE, ...settings };
24
- const started = Date.now();
24
+ let started = Date.now();
25
+ let elapsed = 0;
26
+ let roundElapsed = 0;
27
+ let signal = AbortSignal.timeout(limits.timeoutMs);
25
28
  let charged = 0;
26
29
  let requests = 0;
27
30
  let inputTokens = 0;
@@ -29,19 +32,37 @@ export function createAnalysisBudget(settings = {}) {
29
32
  let reserveFinal = 0;
30
33
  return {
31
34
  limits,
32
- signal: AbortSignal.timeout(limits.timeoutMs),
35
+ get signal() {
36
+ return signal;
37
+ },
38
+ startRound() {
39
+ this.endRound();
40
+ started = Date.now();
41
+ roundElapsed = 0;
42
+ signal = AbortSignal.timeout(limits.timeoutMs);
43
+ },
44
+ endRound() {
45
+ if (started !== null) {
46
+ roundElapsed = Date.now() - started;
47
+ elapsed += roundElapsed;
48
+ started = null;
49
+ }
50
+ },
33
51
  reserveFinal(tokens) {
34
52
  reserveFinal = tokens;
35
53
  },
36
54
  remainingMs() {
37
- return Math.max(0, limits.timeoutMs - (Date.now() - started));
55
+ return Math.max(
56
+ 0,
57
+ limits.timeoutMs - (started === null ? roundElapsed : Date.now() - started),
58
+ );
38
59
  },
39
60
  snapshot() {
40
61
  return {
41
62
  requests,
42
63
  budgetedTokens: charged,
43
64
  maxTotalTokens: limits.maxTotalTokens,
44
- elapsedMs: Date.now() - started,
65
+ elapsedMs: elapsed + (started === null ? 0 : Date.now() - started),
45
66
  usage: { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens },
46
67
  };
47
68
  },
package/src/api.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  validateCommitCandidate,
11
11
  } from './policy.js';
12
12
  import { encodeUntrustedData } from './trust.js';
13
+ import { estimateTokens } from './analysis-budget.js';
13
14
 
14
15
  export async function callAPI(
15
16
  apiUrl,
@@ -93,15 +94,27 @@ async function reasoningForFollowUp(config) {
93
94
  return adapter.reasoningForFollowUp(config.reasoning);
94
95
  }
95
96
 
96
- // Prompt for a regenerate request: the model already saw the diff on the
97
- // first call and produced a message for it, so the diff is NOT re-sent —
98
- // rewording its own previous reply is enough, and far cheaper than resending
99
- // what can be tens of thousands of tokens (same trade-off as correctivePrompt).
100
- function regeneratePrompt(previousMessage, policy) {
97
+ // Each generation is stateless. Keep bounded evidence from the same protected
98
+ // snapshot so a rewrite can correct an earlier misunderstanding.
99
+ function regenerationEvidence(diff, maxChars = 6000) {
100
+ const chars = Array.from(diff);
101
+ if (chars.length <= maxChars) return diff;
102
+ const marker = '\n... (middle omitted; these excerpts are incomplete evidence) ...\n';
103
+ const available = Math.max(0, maxChars - marker.length);
104
+ const tail = Math.floor(available / 3);
105
+ return (
106
+ chars.slice(0, available - tail).join('') + marker + (tail ? chars.slice(-tail).join('') : '')
107
+ );
108
+ }
109
+
110
+ function regeneratePrompt(previousMessage, policy, evidence) {
101
111
  return [
112
+ 'Reassess the change using these bounded excerpts from the original protected input. ' +
113
+ 'They may be incomplete. Correct omissions or mistakes in the previous message; do not infer unsupported behavior.',
114
+ encodeUntrustedData('change_evidence', evidence),
102
115
  'You previously generated this commit message for the change:',
103
116
  '',
104
- previousMessage.slice(0, 1000),
117
+ encodeUntrustedData('previous_message', previousMessage.slice(0, 1000)),
105
118
  '',
106
119
  'Generate a DIFFERENT commit message for the same change — different wording or emphasis. ' +
107
120
  `Keep commitPolicy v${policy.version}; allowed types: ${policy.types.join(', ')}. ` +
@@ -111,6 +124,19 @@ function regeneratePrompt(previousMessage, policy) {
111
124
  ].join('\n');
112
125
  }
113
126
 
127
+ export function assertCompleteResponse(response, usage = null, latencyMs = null) {
128
+ if (hitTokenLimit(response)) {
129
+ throw fail(
130
+ ERROR_CATEGORIES.RESPONSE_FORMAT,
131
+ 'Provider response was still truncated after recovery. Increase maxTokens or edit the partial message manually.',
132
+ {
133
+ code: 'response_truncated',
134
+ data: { partialMessage: response.content, usage, latencyMs },
135
+ },
136
+ );
137
+ }
138
+ }
139
+
114
140
  // Last-ditch extraction from raw reasoning text: prefer the first line that
115
141
  // carries a conventional-commit prefix, else fall back to the last non-empty
116
142
  // line.
@@ -188,6 +214,7 @@ export async function getResponseText(
188
214
  stream = null,
189
215
  responseValidator = null,
190
216
  ) {
217
+ const started = performance.now();
191
218
  let response = await requestGeneration(config, {
192
219
  messages,
193
220
  temperature,
@@ -258,7 +285,9 @@ export async function getResponseText(
258
285
  text = response.content;
259
286
  }
260
287
 
261
- return { text, data: response.raw, response, reasoning, usage: sumUsage(...usages) };
288
+ const usage = sumUsage(...usages);
289
+ assertCompleteResponse(response, usage, performance.now() - started);
290
+ return { text, data: response.raw, response, reasoning, usage };
262
291
  }
263
292
 
264
293
  export function buildCommitMessages(config, diff, regenerateCount = 0, previousMessage = '') {
@@ -270,16 +299,33 @@ export function buildCommitMessages(config, diff, regenerateCount = 0, previousM
270
299
  // constraint after the diff where it can't be drowned out by the prompt.
271
300
  const langReminder = `\n\n(Remember: the commit message must be in ${targetLang}.)`;
272
301
 
273
- // On regenerate, raise the temperature to get a different result — and skip
274
- // the diff entirely: re-sending it on every regenerate would be the biggest
275
- // token cost of the whole flow, while the previous message already captures
276
- // the change. The model rewords its own reply instead (same cheap pattern
277
- // as the corrective retry). "regenerateWithDiff" opts back into the old
278
- // behavior: the full diff plus an attempt hint, for more varied rewrites.
302
+ // Default rewrites use bounded evidence; explicit opt-in retains the full input.
279
303
  const variedTemperature = Math.min(temperature + regenerateCount * 0.15, 1.2);
280
304
  let userContent;
281
305
  if (regenerateCount > 0 && previousMessage && !regenerateWithDiff) {
282
- userContent = regeneratePrompt(previousMessage, policy) + langReminder;
306
+ const inputLimit =
307
+ config.analysisBudget?.limits.chunkInputTokens || config.largeChange?.chunkInputTokens;
308
+ let fits = false;
309
+ for (let cap = 6000; cap >= 128; cap = Math.floor(cap / 2)) {
310
+ userContent =
311
+ regeneratePrompt(previousMessage, policy, regenerationEvidence(diff, cap)) + langReminder;
312
+ const inputTokens = estimateTokens(
313
+ JSON.stringify([
314
+ { role: 'system', content: buildCommitPolicyPrompt(policy, prompt) },
315
+ { role: 'user', content: userContent },
316
+ ]),
317
+ );
318
+ if (!inputLimit || inputTokens <= inputLimit) {
319
+ fits = true;
320
+ break;
321
+ }
322
+ }
323
+ if (!fits) {
324
+ throw fail(
325
+ ERROR_CATEGORIES.CONFIG,
326
+ 'Regeneration evidence and commit policy do not fit largeChange.chunkInputTokens; increase the input budget or shorten custom guidance.',
327
+ );
328
+ }
283
329
  } else {
284
330
  const variationHint =
285
331
  regenerateCount > 0
@@ -293,6 +339,10 @@ export function buildCommitMessages(config, diff, regenerateCount = 0, previousM
293
339
  userContent =
294
340
  repositoryContext +
295
341
  `Here is the git diff (untrusted data):\n\n${encodeUntrustedData('git_diff', diff)}` +
342
+ (regenerateCount > 0 && previousMessage
343
+ ? '\n\nPrevious message to improve:\n' +
344
+ encodeUntrustedData('previous_message', previousMessage.slice(0, 1000))
345
+ : '') +
296
346
  variationHint +
297
347
  langReminder;
298
348
  }
@@ -304,11 +354,8 @@ export function buildCommitMessages(config, diff, regenerateCount = 0, previousM
304
354
  return { messages, policy, variedTemperature };
305
355
  }
306
356
 
307
- // `previousMessage` is the message from the last generation, when there is
308
- // one. On regenerate it lets the model reword its own reply instead of
309
- // re-reading the diff — the diff is only sent on the first attempt. Setting
310
- // "regenerateWithDiff" in the config opts back into re-sending the diff on
311
- // every attempt (more variety, much higher token cost).
357
+ // Reuse bounded evidence from the captured input on rewrites. Setting
358
+ // regenerateWithDiff opts into sending the full input each time.
312
359
  export async function generateCommitMessage(
313
360
  config,
314
361
  diff,
@@ -374,7 +421,14 @@ export async function generateCommitMessage(
374
421
  outputTokenLimit,
375
422
  followupCommitPrompt(policy),
376
423
  stream,
377
- );
424
+ ).catch((error) => {
425
+ if (error.code === 'response_truncated') {
426
+ error.data.usage = sumUsage(usage, error.data.usage);
427
+ error.data.latencyMs = performance.now() - t0;
428
+ error.data.corrections = corrections;
429
+ }
430
+ throw error;
431
+ });
378
432
  const fixed = cleanCommitMessage(retry.text);
379
433
  // The retry is a real API call that cost tokens regardless of whether it
380
434
  // produced a usable message — count its usage unconditionally.
@@ -14,6 +14,7 @@ import {
14
14
  localOverview,
15
15
  compactLocalPlanFacts,
16
16
  localPlanBatches,
17
+ selectLocalGroupFacts,
17
18
  } from './local-analysis.js';
18
19
 
19
20
  function gitQuote(path) {
@@ -314,6 +315,13 @@ function parseAnalysisJson(raw) {
314
315
  throw new SyntaxError('Response contains no complete JSON array.');
315
316
  }
316
317
 
318
+ export function analysisOutputTokenLimit(config) {
319
+ const contentLimit = Math.min(2048, config.maxTokens || 1024);
320
+ return config.reasoning?.mode === 'off'
321
+ ? contentLimit
322
+ : Math.max(contentLimit, config.reasoning?.maxTokens || 4096);
323
+ }
324
+
317
325
  async function jsonCall(config, instruction, items, validate = null, stream = null) {
318
326
  let validationError = '';
319
327
  const parseAndValidate = (raw) => {
@@ -328,7 +336,7 @@ async function jsonCall(config, instruction, items, validate = null, stream = nu
328
336
  { role: 'user', content: encodeUntrustedData('change_analysis', JSON.stringify(items)) },
329
337
  ],
330
338
  0,
331
- Math.min(2048, config.maxTokens || 1024),
339
+ analysisOutputTokenLimit(config),
332
340
  () =>
333
341
  'Return the complete requested JSON array, preserving every required input ID exactly once. ' +
334
342
  `Required IDs: ${JSON.stringify(items.map((item) => item.id))}. ` +
@@ -343,8 +351,27 @@ async function jsonCall(config, instruction, items, validate = null, stream = nu
343
351
  return false;
344
352
  }
345
353
  },
346
- );
354
+ ).catch((cause) => {
355
+ if (cause.code !== 'response_truncated') throw cause;
356
+ const nextAction =
357
+ config.reasoning?.mode === 'off'
358
+ ? 'Increase maxTokens if it is below 2048, or split the changes into smaller batches.'
359
+ : 'Increase reasoning.maxTokens or split the changes into smaller batches.';
360
+ throw fail(
361
+ ERROR_CATEGORIES.RESPONSE_FORMAT,
362
+ `Large-change analysis reached its output limit (${analysisOutputTokenLimit(config)} tokens) ` +
363
+ `after retrying and did not return complete JSON. ${nextAction}`,
364
+ { cause, code: 'response_truncated', nextAction, data: { usage: cause.data?.usage } },
365
+ );
366
+ });
347
367
  stream?.onReasoningComplete?.(result.reasoning);
368
+ if (!result.text.trim()) {
369
+ throw fail(
370
+ ERROR_CATEGORIES.RESPONSE_FORMAT,
371
+ 'Large-change analysis did not return a JSON answer after retrying.',
372
+ { code: 'analysis_empty_response', data: { usage: result.usage } },
373
+ );
374
+ }
348
375
  try {
349
376
  return parseAndValidate(result.text);
350
377
  } catch (cause) {
@@ -538,7 +565,7 @@ function estimateInitialDeepCost(
538
565
  batchTokens += size;
539
566
  }
540
567
  flush();
541
- const output = Math.min(2048, config.maxTokens || 1024);
568
+ const output = analysisOutputTokenLimit(config);
542
569
  let reductionRequests = 0;
543
570
  if (config.analysisTask === 'split') {
544
571
  for (const fragments of fragmentsByFile.values()) {
@@ -781,6 +808,18 @@ export async function analyzeChanges(
781
808
  }
782
809
  }
783
810
 
811
+ export async function summarizeGroupChanges(config, analysis, paths, manifest) {
812
+ // Capacity fallback also produces local facts, even when personal settings
813
+ // still request deep analysis. Select by the result's source, not that setting.
814
+ if (['auto', 'fallback'].includes(analysis.coverage.strategy)) {
815
+ return localOverview(config, selectLocalGroupFacts(analysis.facts, paths, manifest)).text;
816
+ }
817
+ return summarizeChanges(
818
+ config,
819
+ analysis.facts.filter((fact) => paths.includes(fact.path)),
820
+ );
821
+ }
822
+
784
823
  export async function summarizeChanges(config, facts) {
785
824
  if (!isDeepAnalysis(config)) return localOverview(config, facts).text;
786
825
  let items = facts.map(({ id, path, summary }) => ({ id, path, summary }));
package/src/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile, chmod } from 'node:fs/promises';
2
2
  import { DEFAULT_LARGE_CHANGE } from './analysis-budget.js';
3
+ import bundledPresets from '../presets/provider-presets.json' with { type: 'json' };
3
4
  import { execSync } from 'node:child_process';
4
5
 
5
6
  import chalk from 'chalk';
@@ -167,9 +168,8 @@ export const DEFAULT_CONFIG = {
167
168
  // with "*" wildcards (e.g. ["*.min.js", "*.map", "*.snap"]). Generated
168
169
  // artifacts carry no commit intent but can be enormous.
169
170
  stripFiles: [],
170
- // false (default): regenerate rewords the previous message without
171
- // re-sending the diff — far cheaper. true: re-send the full diff on every
172
- // regenerate, for more varied rewrites at a much higher token cost.
171
+ // false (default): regenerate uses bounded change evidence and the previous
172
+ // message. true: re-send the full diff on every regenerate.
173
173
  regenerateWithDiff: false,
174
174
  // Provider-specific request fields are opt-in. Keeping this empty by
175
175
  // default preserves compatibility with strict OpenAI-compatible servers.
@@ -274,6 +274,101 @@ function assertConfigId(value, path) {
274
274
  }
275
275
  }
276
276
 
277
+ export function normalizeUserConfig(value) {
278
+ if (!object(value)) return value;
279
+ const single = Object.hasOwn(value, 'provider');
280
+ const compact =
281
+ single ||
282
+ Object.values(value.providers || {}).some(
283
+ (entry) => object(entry) && Object.hasOwn(entry, 'model'),
284
+ );
285
+ if (!compact) return value;
286
+ if (value.schemaVersion !== undefined && value.schemaVersion !== CONFIG_SCHEMA_VERSION)
287
+ throw new Error(`Invalid config "schemaVersion": expected ${CONFIG_SCHEMA_VERSION}.`);
288
+ const expand = (entry, name) => {
289
+ const { provider = name, model, ...settings } = entry;
290
+ const preset = bundledPresets.providers.find((item) => item.id === provider);
291
+ const connection = {};
292
+ const modelSettings = { modelId: model };
293
+ for (const [key, val] of Object.entries(settings)) {
294
+ if (MODEL_CONFIG_KEYS.has(key) && key !== 'modelId') modelSettings[key] = val;
295
+ else connection[key] = val;
296
+ }
297
+ return {
298
+ ...(preset
299
+ ? { providerType: preset.adapter, apiUrl: preset.apiUrl }
300
+ : { providerType: provider }),
301
+ ...connection,
302
+ defaultModel: 'default',
303
+ models: { default: modelSettings },
304
+ };
305
+ };
306
+ if (single) {
307
+ assertKnownKeys(
308
+ value,
309
+ new Set([...Object.keys(DEFAULT_CONFIG), 'provider', 'model', 'schemaVersion']),
310
+ 'root',
311
+ );
312
+ const { provider, model, schemaVersion: _version, ...settings } = value;
313
+ assertConfigId(provider, 'provider');
314
+ const global = {};
315
+ const profile = { provider, model };
316
+ for (const [key, val] of Object.entries(settings)) {
317
+ if (TOP_LEVEL_CONNECTION_KEYS.has(key) || MODEL_CONFIG_KEYS.has(key)) profile[key] = val;
318
+ else global[key] = val;
319
+ }
320
+ return {
321
+ ...global,
322
+ schemaVersion: CONFIG_SCHEMA_VERSION,
323
+ defaultProvider: provider,
324
+ providers: { [provider]: expand(profile, provider) },
325
+ };
326
+ }
327
+ return {
328
+ ...value,
329
+ schemaVersion: CONFIG_SCHEMA_VERSION,
330
+ providers: Object.fromEntries(
331
+ Object.entries(value.providers).map(([name, entry]) => [
332
+ name,
333
+ object(entry) && Object.hasOwn(entry, 'model') ? expand(entry, name) : entry,
334
+ ]),
335
+ ),
336
+ };
337
+ }
338
+
339
+ export function compactUserConfig(value) {
340
+ const providers = {};
341
+ for (const [name, entry] of Object.entries(value.providers)) {
342
+ const models = Object.values(entry.models);
343
+ // Keep named-model catalogs intact so existing -m aliases remain valid.
344
+ if (models.length !== 1 || entry.defaultModel !== 'default' || models[0].label) return value;
345
+ const { models: _models, defaultModel: _default, providerType, apiUrl, ...connection } = entry;
346
+ const { modelId, ...settings } = models[0];
347
+ const preset = bundledPresets.providers.find(
348
+ (item) => item.id === name && item.adapter === providerType,
349
+ );
350
+ providers[name] = {
351
+ ...(!preset
352
+ ? { provider: providerType, apiUrl }
353
+ : apiUrl !== preset.apiUrl
354
+ ? { apiUrl }
355
+ : {}),
356
+ model: modelId,
357
+ ...connection,
358
+ ...settings,
359
+ };
360
+ if (!providers[name].apiKey) delete providers[name].apiKey;
361
+ if (!providers[name].apiKeyEnv) delete providers[name].apiKeyEnv;
362
+ }
363
+ const { schemaVersion: _version, providers: _providers, defaultProvider, ...global } = value;
364
+ if (Object.keys(providers).length === 1) {
365
+ const profile = providers[defaultProvider];
366
+ if (!profile.provider || profile.provider === defaultProvider)
367
+ return { provider: defaultProvider, ...profile, ...global };
368
+ }
369
+ return { defaultProvider, providers, ...global };
370
+ }
371
+
277
372
  function providerRuntimeConfig(provider) {
278
373
  const { defaultModel: _defaultModel, models: _models, ...runtime } = provider;
279
374
  return runtime;
@@ -286,6 +381,11 @@ function modelRuntimeConfig(model) {
286
381
 
287
382
  export function validateUserConfig(value) {
288
383
  if (!object(value)) throw new Error('Invalid user config: expected a JSON object.');
384
+ const normalized = normalizeUserConfig(value);
385
+ if (normalized !== value) {
386
+ validateUserConfig(normalized);
387
+ return value;
388
+ }
289
389
  if (value.schemaVersion !== CONFIG_SCHEMA_VERSION) {
290
390
  throw new Error(
291
391
  `Invalid config "schemaVersion": expected ${CONFIG_SCHEMA_VERSION}. ` +
@@ -638,6 +738,7 @@ export async function loadConfig(
638
738
  throw new Error(`Failed to parse user config ${userPath}: expected a JSON object.`);
639
739
  }
640
740
  validateUserConfig(parsed);
741
+ parsed = normalizeUserConfig(parsed);
641
742
  catalog = parsed;
642
743
  const globalConfig = { ...parsed };
643
744
  delete globalConfig.schemaVersion;
@@ -14,6 +14,7 @@ export async function runModelTask({
14
14
  failureMessage,
15
15
  successMessage,
16
16
  task,
17
+ analysisBudget = null,
17
18
  }) {
18
19
  const spinner = ora({ text: chalk.dim(spinnerText), color: 'cyan' }).start();
19
20
  let liveReasoning;
@@ -51,7 +52,13 @@ export async function runModelTask({
51
52
  process.on('SIGINT', cancelOnSigint);
52
53
 
53
54
  try {
54
- const result = await task(stream);
55
+ let result;
56
+ analysisBudget?.startRound();
57
+ try {
58
+ result = await task(stream);
59
+ } finally {
60
+ analysisBudget?.endRound();
61
+ }
55
62
  if (liveReasoning) await liveReasoning.stop();
56
63
  spinner.succeed(successMessage(result));
57
64
  return result;
@@ -295,6 +295,25 @@ export function analyzeLocally(config, capture, protect, previews) {
295
295
  };
296
296
  }
297
297
 
298
+ // An edited split plan can separate files that shared one local fact. Restrict
299
+ // paths and counts to the selected group while reusing its identical-edit evidence.
300
+ export function selectLocalGroupFacts(facts, paths, manifest) {
301
+ const selected = new Set(paths);
302
+ const filesByPath = new Map(manifest.map((file) => [file.path, file]));
303
+ return facts.flatMap((fact) => {
304
+ const files = fact.files.filter((path) => selected.has(path));
305
+ if (!files.length) return [];
306
+ return [
307
+ {
308
+ ...fact,
309
+ files,
310
+ additions: files.reduce((sum, path) => sum + filesByPath.get(path).additions, 0),
311
+ deletions: files.reduce((sum, path) => sum + filesByPath.get(path).deletions, 0),
312
+ },
313
+ ];
314
+ });
315
+ }
316
+
298
317
  function planningBucketKey(fact) {
299
318
  const topLevel = fact.module === '.' ? '.' : fact.module.split('/')[0];
300
319
  return JSON.stringify([
package/src/main.js CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  import { cleanupGitSpools } from './git-spool.js';
34
34
  import { createAnalysisCache } from './analysis-cache.js';
35
35
  import { generateCommitMessage } from './api.js';
36
+ import { normalizeCommitPolicy } from './policy.js';
36
37
  import {
37
38
  statusColor,
38
39
  statusIcon,
@@ -693,8 +694,7 @@ async function runMain() {
693
694
 
694
695
  while (true) {
695
696
  try {
696
- // Pass the previous message so a regenerate can ask for a rewording
697
- // instead of re-sending the full diff (see generateCommitMessage).
697
+ // Rewrites reuse evidence from the same captured, protected snapshot.
698
698
  ({
699
699
  message,
700
700
  elapsed,
@@ -708,6 +708,7 @@ async function runMain() {
708
708
  machineOutput,
709
709
  cancelMessage: 'Commit cancelled.',
710
710
  failureMessage: 'API call failed',
711
+ analysisBudget: generationConfig.analysisBudget,
711
712
  task: async (stream) => {
712
713
  if (large && !analysis) {
713
714
  analyzedFacts ||= await analyzeChanges(
@@ -766,11 +767,37 @@ async function runMain() {
766
767
  message: 'The API call failed. What would you like to do?',
767
768
  choices: [
768
769
  ...(message ? [{ name: 'Keep the previous message', value: 'keep' }] : []),
770
+ ...(err.code === 'response_truncated' && err.data?.partialMessage?.trim()
771
+ ? [{ name: 'Edit the partial message', value: 'edit' }]
772
+ : []),
769
773
  { name: 'Try again', value: 'retry' },
770
774
  { name: 'Cancel', value: 'cancel' },
771
775
  ],
772
776
  });
773
777
  if (choice === 'keep') break; // commit with the previous good message
778
+ if (choice === 'edit') {
779
+ const edited = await editMessage(err.data.partialMessage, {
780
+ policy: normalizeCommitPolicy(config.commitPolicy, config.language),
781
+ diff: modelDiff,
782
+ });
783
+ if (edited) {
784
+ message = edited;
785
+ wasEdited = true;
786
+ usage = generationConfig.analysisBudget?.snapshot().usage || err.data.usage;
787
+ elapsed = generationConfig.analysisBudget?.snapshot().elapsedMs ?? err.data.latencyMs;
788
+ automaticCorrectionCount += err.data.corrections || 0;
789
+ persistentAnalysisCache?.clear();
790
+ persistentAnalysisCache = null;
791
+ break;
792
+ }
793
+ return finishCancelled({
794
+ message,
795
+ latencyMs: elapsed,
796
+ usage,
797
+ edited: wasEdited,
798
+ rewrites: regenerateCount + automaticCorrectionCount,
799
+ });
800
+ }
774
801
  if (choice === 'retry') continue;
775
802
  return finishCancelled({
776
803
  message,
@@ -809,7 +836,10 @@ async function runMain() {
809
836
  }
810
837
 
811
838
  if (action === 'edit') {
812
- const edited = await editMessage(message);
839
+ const edited = await editMessage(message, {
840
+ policy: normalizeCommitPolicy(config.commitPolicy, config.language),
841
+ diff: modelDiff,
842
+ });
813
843
  if (edited) {
814
844
  message = edited;
815
845
  wasEdited = true;
package/src/providers.js CHANGED
@@ -133,6 +133,11 @@ export function reasoningEffortsForModel(providerType, modelId) {
133
133
  }
134
134
 
135
135
  export function canDisableReasoningForModel(providerType, modelId) {
136
+ if (
137
+ (providerType || '').toLowerCase() === 'minimax' &&
138
+ /^minimax-m3\.1(?:-|$)/i.test(modelId || '')
139
+ )
140
+ return false;
136
141
  const known = catalogModel((providerType || '').toLowerCase(), modelId);
137
142
  return !known || getSupportedThinkingLevels(known).includes('off');
138
143
  }
@@ -167,6 +172,7 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
167
172
  const nativeOllama =
168
173
  provider === 'ollama' && /\/api\/(?:chat|generate)\/?$/i.test(endpoint(apiUrl)?.pathname || '');
169
174
  const known = catalogModel(provider, modelId);
175
+ const miniMaxAdaptive = provider === 'minimax' && !canDisableReasoningForModel(provider, modelId);
170
176
  const openAIReasoning = provider === 'openai' && isOpenAIReasoningModel(modelId);
171
177
  const tokenField = openAIReasoning ? 'max_completion_tokens' : 'max_tokens';
172
178
  const model = {
@@ -177,7 +183,8 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
177
183
  // The transport pins the full configured URL, including nonstandard proxy paths.
178
184
  baseUrl: endpoint(apiUrl)?.origin || '',
179
185
  reasoning:
180
- known?.reasoning ?? (openAIReasoning || ['deepseek', 'openrouter'].includes(provider)),
186
+ known?.reasoning ??
187
+ (openAIReasoning || miniMaxAdaptive || ['deepseek', 'openrouter'].includes(provider)),
181
188
  contextWindow: known?.contextWindow || 128000,
182
189
  maxTokens: known?.maxTokens || 16384,
183
190
  };
@@ -230,7 +237,9 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
230
237
  } else if (provider === 'minimax') {
231
238
  payload.reasoning_split = true;
232
239
  delete payload.enable_thinking;
233
- if (mode === 'off') payload.thinking = { type: 'disabled' };
240
+ if (miniMaxAdaptive && mode === 'on') payload.reasoning_effort = reasoningEffort;
241
+ if (mode === 'off' && canDisableReasoningForModel(provider, modelId))
242
+ payload.thinking = { type: 'disabled' };
234
243
  else delete payload.thinking;
235
244
  } else if (nativeOllama) {
236
245
  payload.think = mode === 'on';
@@ -250,6 +259,7 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
250
259
  },
251
260
  reasoningForFollowUp(reasoning) {
252
261
  if (reasoning?.mode !== 'on') return reasoning;
262
+ if (!canDisableReasoningForModel(provider, modelId)) return reasoning;
253
263
  if (provider !== 'custom' && canDisableReasoningForModel(provider, modelId))
254
264
  return { ...reasoning, mode: 'off' };
255
265
  if (reasoning.disabledBody !== undefined) return { ...reasoning, mode: 'off' };
package/src/setup.js CHANGED
@@ -11,6 +11,8 @@ import confirm from '@inquirer/confirm';
11
11
  import { checkConnection } from './api.js';
12
12
  import {
13
13
  CONFIG_SCHEMA_VERSION,
14
+ normalizeUserConfig,
15
+ compactUserConfig,
14
16
  DEFAULT_CONFIG,
15
17
  isSecureApiUrl,
16
18
  validateUserConfig,
@@ -19,46 +21,6 @@ import { vimSelect } from './ui.js';
19
21
  import { fileExists, formatMs, indentError, maskApiKey } from './utils.js';
20
22
  import { loadProviderPresetManifest } from './provider-presets.js';
21
23
  import { resolveConfigLocations, userConfigLocations } from './config-paths.js';
22
- import {
23
- canDisableReasoningForModel,
24
- getProviderAdapter,
25
- reasoningEffortsForModel,
26
- } from './providers.js';
27
-
28
- const REASONING_MODES = new Set(['auto', 'on', 'off']);
29
- const REASONING_MODE_CHOICES = Object.freeze([
30
- {
31
- name: 'Provider default (auto)',
32
- value: 'auto',
33
- description: 'Do not send an explicit reasoning switch',
34
- },
35
- {
36
- name: 'Enabled (on)',
37
- value: 'on',
38
- description: 'Request reasoning and configure its effort',
39
- },
40
- {
41
- name: 'Disabled (off)',
42
- value: 'off',
43
- description: 'Explicitly disable reasoning when the model supports that switch',
44
- },
45
- ]);
46
-
47
- function suggestedReasoningMode({ currentModel, globalReasoning, apiUrl, providerType, modelId }) {
48
- const configured = currentModel.reasoning?.mode ?? globalReasoning?.mode;
49
- if (REASONING_MODES.has(configured)) return configured;
50
- return getProviderAdapter({ apiUrl, providerType, modelId }).capabilities.reasoning === 'native'
51
- ? 'on'
52
- : 'auto';
53
- }
54
-
55
- function effortDescription(effort) {
56
- if (effort === 'low') return 'Fastest and lowest-cost reasoning';
57
- if (effort === 'medium') return 'Balanced reasoning (default)';
58
- if (effort === 'high') return 'Deeper reasoning with more latency and tokens';
59
- if (effort === 'xhigh') return 'Very deep reasoning for models that support it';
60
- return 'Maximum reasoning for models that support it';
61
- }
62
24
 
63
25
  // Merge the wizard's answers into the one supported Provider/Model schema.
64
26
  // Existing providers and unrelated global settings are preserved; the
@@ -86,7 +48,7 @@ async function readExistingConfig(path) {
86
48
  }
87
49
 
88
50
  try {
89
- return validateUserConfig(parsed);
51
+ return normalizeUserConfig(validateUserConfig(parsed));
90
52
  } catch (err) {
91
53
  throw new Error(
92
54
  `Existing config ${path} is valid JSON but has an unsupported structure: ${err.message} ` +
@@ -231,7 +193,7 @@ export async function runSetup(dependencies = {}) {
231
193
  // ── 4. Model ────────────────────────────────────────────────────────
232
194
 
233
195
  const providerType = presetAdapter || existingProvider.providerType || 'custom';
234
- const models = { ...presetModels, ...existingProvider.models };
196
+ const models = { ...existingProvider.models };
235
197
  let suggestedModel = existingProvider.defaultModel || presetDefaultModel;
236
198
  while (true) {
237
199
  const modelNameInput = await inputPrompt({
@@ -245,49 +207,13 @@ export async function runSetup(dependencies = {}) {
245
207
  const currentModel = models[modelName] || {};
246
208
  const modelIdInput = await inputPrompt({
247
209
  message: `Model ID for ${modelName}`,
248
- default: currentModel.modelId || undefined,
210
+ default: currentModel.modelId || presetModels[modelName]?.modelId || undefined,
249
211
  validate: (v) => (v.trim() ? true : 'Model ID is required'),
250
212
  });
251
213
  const modelId = modelIdInput.trim();
252
- const reasoningModeChoices = canDisableReasoningForModel(providerType, modelId)
253
- ? REASONING_MODE_CHOICES
254
- : REASONING_MODE_CHOICES.filter((choice) => choice.value !== 'off');
255
- const suggestedMode = suggestedReasoningMode({
256
- currentModel,
257
- globalReasoning: existing.reasoning,
258
- apiUrl,
259
- providerType,
260
- modelId,
261
- });
262
- const reasoningMode = await selectPrompt({
263
- message: `Reasoning mode for ${modelName}`,
264
- default: reasoningModeChoices.some((choice) => choice.value === suggestedMode)
265
- ? suggestedMode
266
- : 'auto',
267
- choices: reasoningModeChoices,
268
- });
269
- const reasoning = { ...currentModel.reasoning, mode: reasoningMode };
270
- if (reasoningMode === 'on') {
271
- const efforts = reasoningEffortsForModel(providerType, modelId);
272
- const configuredEffort = currentModel.reasoning?.effort ?? existing.reasoning?.effort;
273
- const defaultEffort = efforts.includes(configuredEffort)
274
- ? configuredEffort
275
- : efforts.includes(DEFAULT_CONFIG.reasoning.effort)
276
- ? DEFAULT_CONFIG.reasoning.effort
277
- : efforts[0];
278
- reasoning.effort = await selectPrompt({
279
- message: `Reasoning effort for ${modelName}`,
280
- default: defaultEffort,
281
- choices: efforts.map((effort) => ({
282
- name: effort,
283
- value: effort,
284
- description: effortDescription(effort),
285
- })),
286
- });
287
- } else {
288
- delete reasoning.effort;
289
- }
290
- models[modelName] = { ...currentModel, modelId, reasoning };
214
+ // Inherit the runtime defaults without writing redundant tuning options.
215
+ // Preserve explicit settings when editing an existing model.
216
+ models[modelName] = { ...currentModel, modelId };
291
217
  const addAnother = await confirmPrompt({
292
218
  message: 'Add another model?',
293
219
  default: false,
@@ -385,7 +311,7 @@ export async function runSetup(dependencies = {}) {
385
311
  // Write through a same-directory temporary file so interruption cannot
386
312
  // leave a partially written config. Permissions are tightened before the
387
313
  // atomic replacement as well as after it (best effort on Windows).
388
- await writeConfigAtomic(targetPath, merged);
314
+ await writeConfigAtomic(targetPath, compactUserConfig(merged));
389
315
 
390
316
  console.log('');
391
317
  console.log(' ' + chalk.green.bold('✓ Config saved'));
package/src/split.js CHANGED
@@ -75,6 +75,7 @@ import {
75
75
  invalidPlanMessages,
76
76
  applyMessageCorrections,
77
77
  summarizeChanges,
78
+ summarizeGroupChanges,
78
79
  } from './change-analysis.js';
79
80
  import { updateGitHash, spoolGit } from './git-spool.js';
80
81
  import { createAnalysisCache } from './analysis-cache.js';
@@ -1825,6 +1826,7 @@ export async function splitFlow(
1825
1826
  machineOutput,
1826
1827
  cancelMessage: 'Split cancelled.',
1827
1828
  failureMessage: 'Split planning failed',
1829
+ analysisBudget: planningConfig.analysisBudget,
1828
1830
  task: async (stream) => {
1829
1831
  if (large) {
1830
1832
  let plan;
@@ -2114,25 +2116,6 @@ export async function splitFlow(
2114
2116
  });
2115
2117
 
2116
2118
  for (const idx of picked) {
2117
- const rawGroupDiff = analysis
2118
- ? await summarizeChanges(
2119
- planningConfig,
2120
- analysis.facts.filter((fact) => groups[idx].files.includes(fact.path)),
2121
- )
2122
- : getGroupDiff(
2123
- projectRoot,
2124
- head,
2125
- scope,
2126
- groups[idx],
2127
- allFiles,
2128
- config.diffContextLines,
2129
- planningConfig.stripFiles,
2130
- protectModelInput,
2131
- untrackedSnapshot.previews,
2132
- );
2133
- const groupDiff = protectModelInput
2134
- ? protectSensitiveDiff(rawGroupDiff).diff
2135
- : rawGroupDiff;
2136
2119
  if (
2137
2120
  getSplitStateFingerprint(projectRoot, head, undefined, scope) !== plannedStateFingerprint
2138
2121
  ) {
@@ -2159,14 +2142,46 @@ export async function splitFlow(
2159
2142
  machineOutput,
2160
2143
  cancelMessage: 'Split cancelled.',
2161
2144
  failureMessage: `Group ${idx + 1} regenerate failed`,
2162
- task: (stream) =>
2163
- generateCommitMessage(
2145
+ analysisBudget: planningConfig.analysisBudget,
2146
+ task: async (stream) => {
2147
+ const rawGroupDiff = analysis
2148
+ ? await summarizeGroupChanges(
2149
+ planningConfig,
2150
+ analysis,
2151
+ groups[idx].files,
2152
+ captured.manifest,
2153
+ )
2154
+ : getGroupDiff(
2155
+ projectRoot,
2156
+ head,
2157
+ scope,
2158
+ groups[idx],
2159
+ allFiles,
2160
+ config.diffContextLines,
2161
+ planningConfig.stripFiles,
2162
+ protectModelInput,
2163
+ untrackedSnapshot.previews,
2164
+ );
2165
+ const groupDiff = protectModelInput
2166
+ ? protectSensitiveDiff(rawGroupDiff).diff
2167
+ : rawGroupDiff;
2168
+ if (
2169
+ getSplitStateFingerprint(projectRoot, head, undefined, scope) !==
2170
+ plannedStateFingerprint
2171
+ ) {
2172
+ throw fail(
2173
+ ERROR_CATEGORIES.CONCURRENT_MODIFICATION,
2174
+ 'The working tree changed while preparing message regeneration; no request was sent.',
2175
+ );
2176
+ }
2177
+ return generateCommitMessage(
2164
2178
  analysis ? planningConfig : config,
2165
2179
  groupDiff,
2166
2180
  regenCounts[idx],
2167
2181
  groups[idx].message,
2168
2182
  stream,
2169
- ),
2183
+ );
2184
+ },
2170
2185
  successMessage(result) {
2171
2186
  let done = `Group ${idx + 1} regenerated in ${chalk.bold(formatMs(result.elapsed))}`;
2172
2187
  if (result.usage) done += chalk.dim(` · tokens: ${formatUsage(result.usage)}`);
@@ -2178,6 +2193,7 @@ export async function splitFlow(
2178
2193
  rewriteCount += 1 + (corrections || 0);
2179
2194
  } catch (err) {
2180
2195
  regenCounts[idx]--;
2196
+ if (err.category === ERROR_CATEGORIES.CONCURRENT_MODIFICATION) throw err;
2181
2197
  console.log(`\n ${indentError(err)}\n`);
2182
2198
  }
2183
2199
  }
package/src/ui.js CHANGED
@@ -10,6 +10,7 @@ import editor from '@inquirer/editor';
10
10
  import wrapAnsi from 'wrap-ansi';
11
11
 
12
12
  import { sanitizeTerminalText } from './utils.js';
13
+ import { validateCommitCandidate } from './policy.js';
13
14
 
14
15
  // Shared status → color/icon maps (A/M/D/R/C/T from git, '?' = untracked)
15
16
  export const statusColor = {
@@ -527,25 +528,40 @@ export async function confirmAction(message, reasoning) {
527
528
  return action;
528
529
  }
529
530
 
530
- export async function editMessage(message) {
531
+ export async function editMessage(message, { policy, diff = '' } = {}) {
531
532
  // `postfix` is the temp file's extension (not a help text) — ".md" gives
532
533
  // the editor markdown highlighting; guidance belongs in `message`.
533
- const edited = await editor({
534
- message: 'Edit your commit message (save and close to continue, leave empty to cancel)',
535
- default: message,
536
- postfix: '.md',
537
- waitForUseInput: false,
538
- });
539
-
540
- const cleaned = sanitizeTerminalText(edited).trim();
541
- if (!cleaned) return null;
534
+ let current = message;
535
+ while (true) {
536
+ const edited = await editor({
537
+ message: 'Edit your commit message (save and close to continue, leave empty to cancel)',
538
+ default: current,
539
+ postfix: '.md',
540
+ waitForUseInput: false,
541
+ });
542
+
543
+ const cleaned = sanitizeTerminalText(edited).trim();
544
+ if (!cleaned) return null;
545
+
546
+ const validation = validateCommitCandidate(cleaned, { policy, diff });
547
+ if (!validation.valid) {
548
+ for (const error of validation.errors) {
549
+ console.log(chalk.yellow(` commitPolicy: ${error.message}`));
550
+ }
551
+ current = cleaned;
552
+ continue;
553
+ }
554
+ for (const warning of validation.warnings) {
555
+ console.log(chalk.yellow(` Quality check: ${warning.message}`));
556
+ }
542
557
 
543
- displayMessage(cleaned);
544
- const reconfirm = await confirm({
545
- message: 'Commit with this edited message?',
546
- default: true,
547
- theme: { prefix: { idle: chalk.dim('?'), done: chalk.green('?') } },
548
- });
558
+ displayMessage(cleaned);
559
+ const reconfirm = await confirm({
560
+ message: 'Commit with this edited message?',
561
+ default: true,
562
+ theme: { prefix: { idle: chalk.dim('?'), done: chalk.green('?') } },
563
+ });
549
564
 
550
- return reconfirm ? cleaned : null;
565
+ return reconfirm ? cleaned : null;
566
+ }
551
567
  }