-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathmodelCommand.ts
More file actions
718 lines (672 loc) · 22.7 KB
/
Copy pathmodelCommand.ts
File metadata and controls
718 lines (672 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type {
SlashCommand,
CommandContext,
OpenDialogActionReturn,
MessageActionReturn,
} from './types.js';
import { CommandKind } from './types.js';
import { t } from '../../i18n/index.js';
import { getPersistScopeForModelSelection } from '../../config/modelProvidersScope.js';
import {
AuthType,
type AvailableModel,
type Config,
isImageCapable,
resolveModelId,
} from '@qwen-code/qwen-code-core';
import type { LoadedSettings } from '../../config/settings.js';
import { parseAcpModelOption } from '../../utils/acpModelUtils.js';
import {
formatUnsupportedVoiceModelMessage,
isSelectableVoiceModel,
} from '../voice/voice-model.js';
const MAIN_MODEL_CONFIGURATION_HINT =
'Configure models in settings.modelProviders and ensure the required environment variables are set. In interactive mode, run /auth to configure or switch providers, or run /model without arguments to choose from configured models.';
const FAST_MODEL_CONFIGURATION_HINT =
'Configure models in settings.modelProviders and ensure the required environment variables are set. In interactive mode, run /auth to configure or switch providers, or run /model --fast without a model to choose from configured models.';
const COMPACTION_MODEL_CONFIGURATION_HINT =
'Configure models in settings.modelProviders and ensure the required environment variables are set. In interactive mode, run /auth to configure or switch providers, or run /model --compaction without a model to choose from configured models.';
const VISION_MODEL_CONFIGURATION_HINT =
'Configure an image-capable model in settings.modelProviders and ensure the required environment variables are set. Run /model --vision <model-id> to set it, or leave it unset to auto-pick a same-provider vision model.';
function persistSetting(
settings: LoadedSettings,
path: string,
value: unknown,
): void {
settings.setValue(getPersistScopeForModelSelection(settings), path, value);
}
async function switchMainModel(
config: Config,
settings: LoadedSettings,
currentAuthType: AuthType,
modelArg: string,
): Promise<string> {
const parsed = parseAcpModelOption(modelArg);
if (parsed.authType) {
await config.switchModel(
parsed.authType,
parsed.modelId,
parsed.authType !== currentAuthType &&
parsed.authType === AuthType.QWEN_OAUTH
? { requireCachedCredentials: true }
: undefined,
);
persistSetting(settings, 'security.auth.selectedType', parsed.authType);
persistSetting(settings, 'model.name', parsed.modelId);
// `/model <id>` selects by id only, so clear any baseUrl disambiguator left
// by a previous model-picker selection — otherwise next launch would
// resolve to a different provider than this switch just chose. Use an
// empty-string tombstone so the clear overrides a lower-scope value (an
// undefined write is dropped from JSON and would not override on merge).
persistSetting(settings, 'model.baseUrl', '');
return parsed.modelId;
}
await config.switchModel(currentAuthType, modelArg, undefined);
persistSetting(settings, 'model.name', modelArg);
persistSetting(settings, 'model.baseUrl', '');
return modelArg;
}
function formatUnavailableModelMessage(
kind: 'Model' | 'Fast model' | 'Vision model' | 'Compaction model',
modelName: string,
authType: AuthType,
availableModels: AvailableModel[],
): string {
const availableModelIds = Array.from(
new Set(availableModels.map((model) => model.id)),
);
const availableModelsLine =
availableModelIds.length === 0
? `No models are configured for auth type '${authType}'.`
: `Available models for '${authType}': ${availableModelIds.join(', ')}.`;
const hint =
kind === 'Fast model'
? FAST_MODEL_CONFIGURATION_HINT
: kind === 'Vision model'
? VISION_MODEL_CONFIGURATION_HINT
: kind === 'Compaction model'
? COMPACTION_MODEL_CONFIGURATION_HINT
: MAIN_MODEL_CONFIGURATION_HINT;
return (
`${kind} '${modelName}' is not available for auth type '${authType}'.\n` +
`${availableModelsLine}\n` +
hint
);
}
// Fast, vision, and compaction share the same "not configured for any auth type" message
// shape, differing only in the label and the configuration hint.
function formatUnavailableAuxModelMessage(
label: 'Fast model' | 'Vision model' | 'Compaction model',
modelName: string,
availableModels: AvailableModel[],
hint: string,
): string {
const availableModelIds = Array.from(
new Set(availableModels.map((model) => model.id)),
);
const availableModelsLine =
availableModelIds.length === 0
? 'No models are configured.'
: `Configured models: ${availableModelIds.join(', ')}.`;
return (
`${label} '${modelName}' is not configured for any auth type.\n` +
`${availableModelsLine}\n` +
hint
);
}
function formatUnavailableFastModelMessage(
modelName: string,
availableModels: AvailableModel[],
): string {
return formatUnavailableAuxModelMessage(
'Fast model',
modelName,
availableModels,
FAST_MODEL_CONFIGURATION_HINT,
);
}
function formatUnavailableVisionModelMessage(
modelName: string,
availableModels: AvailableModel[],
): string {
return formatUnavailableAuxModelMessage(
'Vision model',
modelName,
availableModels,
VISION_MODEL_CONFIGURATION_HINT,
);
}
function formatUnavailableCompactionModelMessage(
modelName: string,
availableModels: AvailableModel[],
): string {
return formatUnavailableAuxModelMessage(
'Compaction model',
modelName,
availableModels,
COMPACTION_MODEL_CONFIGURATION_HINT,
);
}
// Shown when a user pins a model that isn't known to accept images. The pin is
// still honored, but the bridge will send images to it, so flag it. Reuses the
// same translated key the model dialog emits (ModelDialog.tsx) so both paths
// stay i18n-consistent.
function formatNonVisionModelWarning(modelName: string): string {
return t(
"⚠ '{{model}}' is not a known image-capable model; the vision bridge may fail on images.",
{ model: modelName },
);
}
function formatUnavailableVoiceModelMessage(
modelName: string,
availableModels: AvailableModel[],
): string {
const availableModelIds = Array.from(
new Set(availableModels.map((model) => model.id)),
);
const availableModelsLine =
availableModelIds.length === 0
? t('No models are configured.')
: t('Configured models: {{models}}.', {
models: availableModelIds.join(', '),
});
return (
t("Voice model '{{modelName}}' is not configured.", { modelName }) +
'\n' +
`${availableModelsLine}\n` +
t(
'Configure a unique model id in settings.modelProviders or run /model --voice to select an available model.',
)
);
}
// Get an array of the available model IDs as strings, filtered by mode
function getAvailableModelIds(
context: CommandContext,
mode: 'main' | 'fast' | 'voice' | 'vision' | 'compaction' = 'main',
) {
const { services } = context;
const { config } = services;
if (!config) {
return [];
}
const availableModels = config.getAvailableModels().filter((m) => {
if (mode === 'fast' || mode === 'compaction') return !m.voiceOnly;
if (mode === 'voice') return !m.fastOnly;
// 'vision' and 'main' both exclude fast/voice-only models.
return !m.fastOnly && !m.voiceOnly;
});
return availableModels.map((model) => model.id);
}
export const modelCommand: SlashCommand = {
name: 'model',
completionPriority: 100,
get description() {
return t(
'Switch the model for this session (--fast for suggestion model, --voice for voice transcription model, --vision for the vision bridge model, --compaction for chat compression model, [model-id] to switch immediately).',
);
},
argumentHint: '[--fast|--voice|--vision|--compaction] [<model-id>]',
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
completion: async (context, partialArg) => {
if (partialArg) {
const flagCompletions = [
{
value: '--fast',
description: t(
'Set a lighter model for prompt suggestions and speculative execution',
),
},
{
value: '--voice',
description: t('Set the model for voice transcription'),
},
{
value: '--vision',
description: t(
'Set the image-capable model used to transcribe images for a text-only main model',
),
},
{
value: '--compaction',
description: t(
'Set the model used for chat compression (auto-compaction)',
),
},
].filter((item) => item.value.startsWith(partialArg));
if (flagCompletions.length > 0) {
return flagCompletions;
}
const trimmed = partialArg.trim();
if (trimmed) {
let mode: 'main' | 'fast' | 'voice' | 'vision' | 'compaction' = 'main';
let modelPrefix = trimmed;
if (trimmed.startsWith('--fast ')) {
mode = 'fast';
modelPrefix = trimmed.slice('--fast '.length);
} else if (trimmed.startsWith('--voice ')) {
mode = 'voice';
modelPrefix = trimmed.slice('--voice '.length);
} else if (trimmed.startsWith('--vision ')) {
mode = 'vision';
modelPrefix = trimmed.slice('--vision '.length);
} else if (trimmed.startsWith('--compaction ')) {
mode = 'compaction';
modelPrefix = trimmed.slice('--compaction '.length);
}
return getAvailableModelIds(context, mode).filter((id) =>
id.startsWith(modelPrefix),
);
}
return null;
} else {
return null;
}
},
action: async (
context: CommandContext,
actionArgs: string,
): Promise<OpenDialogActionReturn | MessageActionReturn> => {
const { services } = context;
const { config, settings } = services;
if (!config) {
return {
type: 'message',
messageType: 'error',
content: t('Configuration not available.'),
};
}
// Handle --fast flag: /model --fast <modelName>
const args = context.invocation?.args?.trim() || actionArgs.trim();
const isVoiceModelCommand =
args === '--voice' || args.startsWith('--voice ');
if (isVoiceModelCommand) {
const modelName = args.replace('--voice', '').trim();
if (!modelName) {
if (context.executionMode !== 'interactive') {
const voiceModel =
context.services.settings?.merged?.voiceModel?.trim() ||
t('not set');
return {
type: 'message',
messageType: 'info',
content: t(
'Current voice model: {{voiceModel}}\nUse "/model --voice <model-id>" to set voice model.',
{ voiceModel },
),
};
}
return {
type: 'dialog',
dialog: 'voice-model',
};
}
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const availableModels = config
.getAllConfiguredModels()
.filter((m) => !m.fastOnly);
const matches = availableModels.filter((model) => model.id === modelName);
if (matches.length === 0) {
return {
type: 'message',
messageType: 'error',
content: formatUnavailableVoiceModelMessage(
modelName,
availableModels,
),
};
}
if (matches.length > 1) {
return {
type: 'message',
messageType: 'error',
content: t(
"Voice model '{{modelName}}' is ambiguous. Configure a unique model id before using /model --voice.",
{ modelName },
),
};
}
if (!isSelectableVoiceModel(matches[0]!)) {
return {
type: 'message',
messageType: 'error',
content: formatUnsupportedVoiceModelMessage(modelName),
};
}
persistSetting(settings, 'voiceModel', modelName);
return {
type: 'message',
messageType: 'info',
content: t('Voice Model') + ': ' + modelName,
};
}
const isFastModelCommand = args === '--fast' || args.startsWith('--fast ');
if (isFastModelCommand) {
const modelName = args.replace('--fast', '').trim();
if (!modelName) {
// Open model dialog in fast-model mode (interactive) or return current fast model (non-interactive)
if (context.executionMode !== 'interactive') {
const fastModel =
context.services.settings?.merged?.fastModel ?? 'not set';
return {
type: 'message',
messageType: 'info',
content: `Current fast model: ${fastModel}\nUse "/model --fast <model-id>" to set fast model.`,
};
}
return {
type: 'dialog',
dialog: 'fast-model',
};
}
// Set fast model
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const contentGeneratorConfig = config.getContentGeneratorConfig();
const authType = contentGeneratorConfig?.authType;
if (!authType) {
return {
type: 'message',
messageType: 'error',
content: t('Authentication type not available.'),
};
}
const selector = (() => {
try {
return resolveModelId(modelName);
} catch {
return undefined;
}
})();
if (!selector) {
return {
type: 'message',
messageType: 'error',
content: formatUnavailableFastModelMessage(modelName, []),
};
}
const availableModels = (
selector.authType
? config.getAvailableModelsForAuthType(selector.authType)
: config.getAllConfiguredModels()
).filter((m) => !m.voiceOnly);
if (!availableModels.some((model) => model.id === selector.modelId)) {
return {
type: 'message',
messageType: 'error',
content: selector.authType
? formatUnavailableModelMessage(
'Fast model',
selector.modelId,
selector.authType,
availableModels,
)
: formatUnavailableFastModelMessage(modelName, availableModels),
};
}
persistSetting(settings, 'fastModel', modelName);
// Sync the runtime Config so forked agents pick up the change immediately
// without requiring a restart.
config.setFastModel(modelName);
return {
type: 'message',
messageType: 'info',
content: t('Fast Model') + ': ' + modelName,
};
}
const isVisionModelCommand =
args === '--vision' || args.startsWith('--vision ');
if (isVisionModelCommand) {
const modelName = args.replace('--vision', '').trim();
if (!modelName) {
// Open the model picker in vision mode (interactive) or print the
// current vision model (non-interactive).
if (context.executionMode !== 'interactive') {
const visionModel =
context.services.settings?.merged?.visionModel?.trim() ||
t('not set');
return {
type: 'message',
messageType: 'info',
content: t(
'Current vision model: {{visionModel}}\nUse "/model --vision <model-id>" to set the vision bridge model.',
{ visionModel },
),
};
}
return {
type: 'dialog',
dialog: 'vision-model',
};
}
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const selector = (() => {
try {
return resolveModelId(modelName);
} catch {
return undefined;
}
})();
if (!selector) {
return {
type: 'message',
messageType: 'error',
content: formatUnavailableVisionModelMessage(modelName, []),
};
}
const availableModels = (
selector.authType
? config.getAvailableModelsForAuthType(selector.authType)
: config.getAllConfiguredModels()
).filter((m) => !m.fastOnly && !m.voiceOnly);
const matched = availableModels.find(
(model) => model.id === selector.modelId,
);
if (!matched) {
return {
type: 'message',
messageType: 'error',
content: selector.authType
? formatUnavailableModelMessage(
'Vision model',
selector.modelId,
selector.authType,
availableModels,
)
: formatUnavailableVisionModelMessage(modelName, availableModels),
};
}
// Pinning the primary itself is a no-op at runtime (the bridge guard skips
// it and falls back to auto-select), so reject it at set time instead of
// persisting a dead pin and reporting success.
if (config.isCurrentPrimaryModel(matched)) {
return {
type: 'message',
messageType: 'error',
content: t(
"'{{model}}' is the current primary model and cannot be used as the vision bridge. Choose a different image-capable model.",
{ model: modelName },
),
};
}
persistSetting(settings, 'visionModel', modelName);
// Sync runtime Config so the vision bridge picks it up without a restart.
config.setVisionModel(modelName);
// The pin is honored even if the model isn't image-capable (the user may
// know better than our metadata), but warn — the bridge sends images to it.
const visionWarning = isImageCapable(matched)
? ''
: `\n${formatNonVisionModelWarning(modelName)}`;
return {
type: 'message',
messageType: 'info',
content: t('Vision Model') + ': ' + modelName + visionWarning,
};
}
const isCompactionModelCommand =
args === '--compaction' || args.startsWith('--compaction ');
if (isCompactionModelCommand) {
const modelName = args.replace('--compaction', '').trim();
if (!modelName) {
if (context.executionMode !== 'interactive') {
const compactionModel =
context.services.settings?.merged?.compactionModel?.trim() ||
t('not set (falls back to fast model, then main model)');
return {
type: 'message',
messageType: 'info',
content: t(
'Current compaction model: {{compactionModel}}\nUse "/model --compaction <model-id>" to set compaction model, or "/model --compaction " to clear the override.',
{ compactionModel },
),
};
}
return {
type: 'dialog',
dialog: 'compaction-model',
};
}
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const selector = (() => {
try {
return resolveModelId(modelName);
} catch {
return undefined;
}
})();
if (!selector) {
return {
type: 'message',
messageType: 'error',
content: formatUnavailableCompactionModelMessage(modelName, []),
};
}
const availableModels = (
selector.authType
? config.getAvailableModelsForAuthType(selector.authType)
: config.getAllConfiguredModels()
).filter((m) => !m.voiceOnly);
if (!availableModels.some((model) => model.id === selector.modelId)) {
return {
type: 'message',
messageType: 'error',
content: selector.authType
? formatUnavailableModelMessage(
'Compaction model',
selector.modelId,
selector.authType,
availableModels,
)
: formatUnavailableCompactionModelMessage(
modelName,
availableModels,
),
};
}
persistSetting(settings, 'compactionModel', modelName);
// Sync runtime Config so the compression service picks it up immediately.
config.setCompactionModel(modelName);
return {
type: 'message',
messageType: 'info',
content: t('Compaction Model') + ': ' + modelName,
};
}
const contentGeneratorConfig = config.getContentGeneratorConfig();
if (!contentGeneratorConfig) {
return {
type: 'message',
messageType: 'error',
content: t('Content generator configuration not available.'),
};
}
const authType = contentGeneratorConfig.authType;
if (!authType) {
return {
type: 'message',
messageType: 'error',
content: t('Authentication type not available.'),
};
}
const modelName = args.trim().split(/\s+/)[0] ?? '';
if (modelName) {
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const parsed = parseAcpModelOption(modelName);
const targetAuthType = parsed.authType ?? authType;
const availableModels = config
.getAvailableModelsForAuthType(targetAuthType)
.filter((m) => !m.fastOnly && !m.voiceOnly);
if (!availableModels.some((model) => model.id === parsed.modelId)) {
return {
type: 'message',
messageType: 'error',
content: formatUnavailableModelMessage(
'Model',
parsed.modelId,
targetAuthType,
availableModels,
),
};
}
const effectiveModelName = await switchMainModel(
config,
settings,
authType,
modelName,
);
return {
type: 'message',
messageType: 'info',
content: t('Model') + ': ' + effectiveModelName,
};
}
// Non-interactive/ACP: set model if an arg was provided, otherwise show current model
if (context.executionMode !== 'interactive') {
// /model with no args — show current model
const currentModel = config.getModel() ?? 'unknown';
return {
type: 'message',
messageType: 'info',
content: `Current model: ${currentModel}\nUse "/model <model-id>" to switch models or "/model --fast <model-id>" to set the fast model.`,
};
}
return {
type: 'dialog',
dialog: 'model',
};
},
};