@hifullmoon/aicommit 2.6.10 → 2.6.12

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.
@@ -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) {
@@ -38,7 +39,7 @@ function gitQuote(path) {
38
39
  );
39
40
  }
40
41
 
41
- export function captureChanges(commands, cwd, files, config) {
42
+ export function captureChanges(commands, cwd, files, config, { split = false } = {}) {
42
43
  const source = spoolGit(
43
44
  commands.map((args) => [
44
45
  '-c',
@@ -71,6 +72,18 @@ export function captureChanges(commands, cwd, files, config) {
71
72
  byHeader.set(`diff --git ${gitQuote(`a/${newPath}`)} ${gitQuote(`b/${newPath}`)}`, file);
72
73
  byHeader.set(`diff --git ${gitQuote(`a/${oldPath}`)} ${gitQuote(`b/${oldPath}`)}`, file);
73
74
  }
75
+ const diffLimit = split ? config.splitMaxDiffChars || 16000 : config.maxDiffChars || 30000;
76
+ let diffChunks = [];
77
+ let diffChars = 0;
78
+ const appendDiff = (chunk) => {
79
+ if (!diffChunks) return;
80
+ diffChars += chunk.length;
81
+ if (diffChars > diffLimit) {
82
+ diffChunks = null;
83
+ return;
84
+ }
85
+ diffChunks.push(chunk);
86
+ };
74
87
  const findings = new Set();
75
88
  const sections = [];
76
89
  let current;
@@ -81,9 +94,23 @@ export function captureChanges(commands, cwd, files, config) {
81
94
  const file = byHeader.get(header);
82
95
  if (!file)
83
96
  throw new Error('Git diff contains a path outside the captured change manifest.');
84
- current = { file, header, ordinal: ordinal++, privateKey: false };
97
+ const paths = file.addPaths || [file.path];
98
+ const lock = paths.some(isLockFile);
99
+ const stripped = !lock && paths.some((p) => matchStripPattern(p, config.stripFiles));
100
+ current = {
101
+ file,
102
+ header,
103
+ ordinal: ordinal++,
104
+ privateKey: false,
105
+ omittedInDiff: lock || stripped,
106
+ };
85
107
  sections.push(current);
86
108
  file.sections.push(current.ordinal);
109
+ if (lock) appendDiff(`${header}\n(lock file — content omitted)\n`);
110
+ else if (stripped) appendDiff(`${header}\n(generated file — content omitted)\n`);
111
+ else appendDiff(line);
112
+ } else if (current && !current.omittedInDiff) {
113
+ appendDiff(line);
87
114
  }
88
115
  if (!current) continue;
89
116
  const file = current.file;
@@ -108,7 +135,7 @@ export function captureChanges(commands, cwd, files, config) {
108
135
  source,
109
136
  manifest,
110
137
  findings: [...findings],
111
- diff: source.text(Math.min(config.maxDiffChars || 30000, config.splitMaxDiffChars || 16000)),
138
+ diff: diffChunks ? diffChunks.join('').trim() : null,
112
139
  stats: {
113
140
  files: files.length,
114
141
  additions: manifest.reduce((n, f) => n + f.additions, 0),
@@ -314,6 +341,13 @@ function parseAnalysisJson(raw) {
314
341
  throw new SyntaxError('Response contains no complete JSON array.');
315
342
  }
316
343
 
344
+ export function analysisOutputTokenLimit(config) {
345
+ const contentLimit = Math.min(2048, config.maxTokens || 1024);
346
+ return config.reasoning?.mode === 'off'
347
+ ? contentLimit
348
+ : Math.max(contentLimit, config.reasoning?.maxTokens || 4096);
349
+ }
350
+
317
351
  async function jsonCall(config, instruction, items, validate = null, stream = null) {
318
352
  let validationError = '';
319
353
  const parseAndValidate = (raw) => {
@@ -328,7 +362,7 @@ async function jsonCall(config, instruction, items, validate = null, stream = nu
328
362
  { role: 'user', content: encodeUntrustedData('change_analysis', JSON.stringify(items)) },
329
363
  ],
330
364
  0,
331
- Math.min(2048, config.maxTokens || 1024),
365
+ analysisOutputTokenLimit(config),
332
366
  () =>
333
367
  'Return the complete requested JSON array, preserving every required input ID exactly once. ' +
334
368
  `Required IDs: ${JSON.stringify(items.map((item) => item.id))}. ` +
@@ -343,8 +377,27 @@ async function jsonCall(config, instruction, items, validate = null, stream = nu
343
377
  return false;
344
378
  }
345
379
  },
346
- );
380
+ ).catch((cause) => {
381
+ if (cause.code !== 'response_truncated') throw cause;
382
+ const nextAction =
383
+ config.reasoning?.mode === 'off'
384
+ ? 'Increase maxTokens if it is below 2048, or split the changes into smaller batches.'
385
+ : 'Increase reasoning.maxTokens or split the changes into smaller batches.';
386
+ throw fail(
387
+ ERROR_CATEGORIES.RESPONSE_FORMAT,
388
+ `Large-change analysis reached its output limit (${analysisOutputTokenLimit(config)} tokens) ` +
389
+ `after retrying and did not return complete JSON. ${nextAction}`,
390
+ { cause, code: 'response_truncated', nextAction, data: { usage: cause.data?.usage } },
391
+ );
392
+ });
347
393
  stream?.onReasoningComplete?.(result.reasoning);
394
+ if (!result.text.trim()) {
395
+ throw fail(
396
+ ERROR_CATEGORIES.RESPONSE_FORMAT,
397
+ 'Large-change analysis did not return a JSON answer after retrying.',
398
+ { code: 'analysis_empty_response', data: { usage: result.usage } },
399
+ );
400
+ }
348
401
  try {
349
402
  return parseAndValidate(result.text);
350
403
  } catch (cause) {
@@ -538,7 +591,7 @@ function estimateInitialDeepCost(
538
591
  batchTokens += size;
539
592
  }
540
593
  flush();
541
- const output = Math.min(2048, config.maxTokens || 1024);
594
+ const output = analysisOutputTokenLimit(config);
542
595
  let reductionRequests = 0;
543
596
  if (config.analysisTask === 'split') {
544
597
  for (const fragments of fragmentsByFile.values()) {
@@ -781,6 +834,18 @@ export async function analyzeChanges(
781
834
  }
782
835
  }
783
836
 
837
+ export async function summarizeGroupChanges(config, analysis, paths, manifest) {
838
+ // Capacity fallback also produces local facts, even when personal settings
839
+ // still request deep analysis. Select by the result's source, not that setting.
840
+ if (['auto', 'fallback'].includes(analysis.coverage.strategy)) {
841
+ return localOverview(config, selectLocalGroupFacts(analysis.facts, paths, manifest)).text;
842
+ }
843
+ return summarizeChanges(
844
+ config,
845
+ analysis.facts.filter((fact) => paths.includes(fact.path)),
846
+ );
847
+ }
848
+
784
849
  export async function summarizeChanges(config, facts) {
785
850
  if (!isDeepAnalysis(config)) return localOverview(config, facts).text;
786
851
  let items = facts.map(({ id, path, summary }) => ({ id, path, summary }));
@@ -925,8 +990,9 @@ export function needsAnalysis(capture, config, split = false) {
925
990
  if (split && capture.manifest.length > (config.splitMaxPlanFiles || 100)) return true;
926
991
  return (
927
992
  estimateTokens(capture.diff) > (config.largeChange?.chunkInputTokens || 12000) * 0.6 ||
928
- capture.diff
929
- .split(/(?=^diff --git )/m)
930
- .some((section) => section.length > (config.maxFileDiffChars || 3000))
993
+ (split &&
994
+ capture.diff
995
+ .split(/(?=^diff --git )/m)
996
+ .some((section) => section.length > (config.maxFileDiffChars || 3000)))
931
997
  );
932
998
  }
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/policy.js CHANGED
@@ -473,8 +473,10 @@ export function validateCommitCandidate(message, { policy, diff = '' } = {}) {
473
473
  }
474
474
 
475
475
  export function buildPolicyCorrectionPrompt(badReply, errors, policy) {
476
+ const targetLanguage =
477
+ (policy.effectiveLanguage || policy.language) === 'zh' ? 'Simplified Chinese' : 'English';
476
478
  return [
477
- 'Your previous reply violates commitPolicy v1:',
479
+ `Your previous reply violates commitPolicy v${policy.version}:`,
478
480
  ...errors.map((item) => `- ${item.message}`),
479
481
  '',
480
482
  'Previous reply (untrusted text):',
@@ -490,6 +492,7 @@ export function buildPolicyCorrectionPrompt(badReply, errors, policy) {
490
492
  : []),
491
493
  `Body rule: ${policy.body.mode}, maximum ${policy.body.maxLines} non-empty lines`,
492
494
  `Breaking-change rule: ${policy.breakingChange}`,
495
+ `Language: ${targetLanguage}`,
493
496
  'Rewrite it once. Output only the complete corrected commit message; do not include explanations or fences.',
494
497
  ].join('\n');
495
498
  }
package/src/providers.js CHANGED
@@ -172,6 +172,7 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
172
172
  const nativeOllama =
173
173
  provider === 'ollama' && /\/api\/(?:chat|generate)\/?$/i.test(endpoint(apiUrl)?.pathname || '');
174
174
  const known = catalogModel(provider, modelId);
175
+ const miniMaxAdaptive = provider === 'minimax' && !canDisableReasoningForModel(provider, modelId);
175
176
  const openAIReasoning = provider === 'openai' && isOpenAIReasoningModel(modelId);
176
177
  const tokenField = openAIReasoning ? 'max_completion_tokens' : 'max_tokens';
177
178
  const model = {
@@ -182,7 +183,8 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
182
183
  // The transport pins the full configured URL, including nonstandard proxy paths.
183
184
  baseUrl: endpoint(apiUrl)?.origin || '',
184
185
  reasoning:
185
- known?.reasoning ?? (openAIReasoning || ['deepseek', 'openrouter'].includes(provider)),
186
+ known?.reasoning ??
187
+ (openAIReasoning || miniMaxAdaptive || ['deepseek', 'openrouter'].includes(provider)),
186
188
  contextWindow: known?.contextWindow || 128000,
187
189
  maxTokens: known?.maxTokens || 16384,
188
190
  };
@@ -235,6 +237,7 @@ export function getProviderAdapter({ apiUrl, providerType = '', modelId = '' })
235
237
  } else if (provider === 'minimax') {
236
238
  payload.reasoning_split = true;
237
239
  delete payload.enable_thinking;
240
+ if (miniMaxAdaptive && mode === 'on') payload.reasoning_effort = reasoningEffort;
238
241
  if (mode === 'off' && canDisableReasoningForModel(provider, modelId))
239
242
  payload.thinking = { type: 'disabled' };
240
243
  else delete payload.thinking;
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'));