-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathmodelCommand.ts
More file actions
971 lines (916 loc) · 31.8 KB
/
Copy pathmodelCommand.ts
File metadata and controls
971 lines (916 loc) · 31.8 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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type {
SlashCommand,
CommandContext,
OpenDialogActionReturn,
MessageActionReturn,
SubmitPromptActionReturn,
} 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,
parseVisionModelSetting,
resolveModelId,
} from '@qwen-code/qwen-code-core';
import { SettingScope, type LoadedSettings } from '../../config/settings.js';
import {
isInlineModelOverrideAllowed,
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.';
/**
* Parse --project / --global scope flags from the argument string.
* Returns the resolved scope override and the remaining args with flags stripped.
*/
function parseScopeFlags(args: string): {
scopeOverride: SettingScope | undefined;
remaining: string;
hasProject: boolean;
hasGlobal: boolean;
} {
let scopeOverride: SettingScope | undefined;
let remaining = args;
const hasProject = /(?:^|\s)--project(?:\s|$)/.test(remaining);
const hasGlobal = /(?:^|\s)--global(?:\s|$)/.test(remaining);
if (hasProject) {
scopeOverride = SettingScope.Workspace;
remaining = remaining.replace(/(?:^|\s)--project(?:\s|$)/, ' ').trim();
} else if (hasGlobal) {
scopeOverride = SettingScope.User;
remaining = remaining.replace(/(?:^|\s)--global(?:\s|$)/, ' ').trim();
}
return { scopeOverride, remaining, hasProject, hasGlobal };
}
function resolveScope(
settings: LoadedSettings,
scopeOverride: SettingScope | undefined,
): SettingScope {
return scopeOverride ?? getPersistScopeForModelSelection(settings);
}
function persistScopeSpread(
scopeOverride: SettingScope | undefined,
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
): { persistScope: 'workspace' } | { persistScope: 'user' } | {} {
if (scopeOverride === SettingScope.Workspace)
return { persistScope: 'workspace' as const };
if (scopeOverride === SettingScope.User)
return { persistScope: 'user' as const };
return {};
}
function formatVisionModelSettingForDisplay(setting: string): string {
const parsed = parseVisionModelSetting(setting);
if (!parsed) return setting.replace(/\0/g, '\\0');
return parsed.baseUrl
? `${parsed.selector} (${parsed.baseUrl})`
: parsed.selector;
}
function persistSetting(
settings: LoadedSettings,
path: string,
value: unknown,
scopeOverride?: SettingScope,
): void {
settings.setValue(resolveScope(settings, scopeOverride), path, value);
}
async function switchMainModel(
config: Config,
settings: LoadedSettings,
currentAuthType: AuthType,
modelArg: string,
scopeOverride?: SettingScope,
): 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,
scopeOverride,
);
persistSetting(settings, 'model.name', parsed.modelId, scopeOverride);
// `/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', '', scopeOverride);
return parsed.modelId;
}
await config.switchModel(currentAuthType, modelArg, undefined);
persistSetting(settings, 'model.name', modelArg, scopeOverride);
persistSetting(settings, 'model.baseUrl', '', scopeOverride);
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,
);
}
function formatAmbiguousVisionModelMessage(
modelName: string,
matchingModels: AvailableModel[],
): string {
const endpoints = matchingModels
.map((model) => model.baseUrl ?? '(default endpoint)')
.join(', ');
const qualifiedSelectors = Array.from(
new Set(
matchingModels
.map((model) =>
model.authType ? `${model.authType}:${model.id}` : undefined,
)
.filter((selector): selector is string => selector !== undefined),
),
);
const scriptedHint =
qualifiedSelectors.length > 1
? `\n${t(
'For scripts, pass an auth-qualified selector such as {{selector}}.',
{
selector: qualifiedSelectors[0],
},
)}`
: '';
return (
t("Vision model '{{modelName}}' matches multiple configured endpoints.", {
modelName,
}) +
'\n' +
t('Matching endpoints: {{endpoints}}.', { endpoints }) +
'\n' +
t(
'Run /model --vision without an argument and choose the exact endpoint.',
) +
scriptedHint
);
}
// 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, --project to persist to project settings, --global to persist to user settings, [model-id] to switch immediately, or [model-id] [prompt] to run a one-off prompt on another model; the inline prompt is sent verbatim without @file expansion).',
);
},
argumentHint:
'[--fast|--voice|--vision|--compaction] [--project|--global] [<model-id>] | <model-id> <prompt>',
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)',
),
},
{
value: '--project',
description: t(
'Persist the model selection to the project settings (workspace scope)',
),
},
{
value: '--global',
description: t(
'Persist the model selection to the user settings (global scope)',
),
},
].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';
// Strip all known flags to isolate the model prefix for completion
const modelPrefix = trimmed
.replace(/(?:^|\s)--fast(?:\s|$)/, ' ')
.replace(/(?:^|\s)--voice(?:\s|$)/, ' ')
.replace(/(?:^|\s)--vision(?:\s|$)/, ' ')
.replace(/(?:^|\s)--compaction(?:\s|$)/, ' ')
.replace(/(?:^|\s)--project(?:\s|$)/, ' ')
.replace(/(?:^|\s)--global(?:\s|$)/, ' ')
.trim();
if (/(?:^|\s)--fast(?:\s|$)/.test(trimmed)) mode = 'fast';
else if (/(?:^|\s)--voice(?:\s|$)/.test(trimmed)) mode = 'voice';
else if (/(?:^|\s)--vision(?:\s|$)/.test(trimmed)) mode = 'vision';
else if (/(?:^|\s)--compaction(?:\s|$)/.test(trimmed)) mode = 'compaction';
return getAvailableModelIds(context, mode).filter((id) =>
id.startsWith(modelPrefix),
);
}
return null;
} else {
return null;
}
},
action: async (
context: CommandContext,
actionArgs: string,
): Promise<
OpenDialogActionReturn | MessageActionReturn | SubmitPromptActionReturn
> => {
const { services } = context;
const { config, settings } = services;
if (!config) {
return {
type: 'message',
messageType: 'error',
content: t('Configuration not available.'),
};
}
// Parse --project / --global scope flags first, then process the rest
const rawArgs = context.invocation?.args?.trim() || actionArgs.trim();
const {
scopeOverride,
remaining: args,
hasProject,
hasGlobal,
} = parseScopeFlags(rawArgs);
// Reject mutually exclusive scope flags
if (hasProject && hasGlobal) {
return {
type: 'message',
messageType: 'error',
content: t(
'Cannot use both --project and --global. Choose one scope flag.',
),
};
}
// Reject --project when workspace is untrusted — workspace settings are
// ignored on merge, so the save would silently not take effect.
if (
scopeOverride === SettingScope.Workspace &&
settings &&
!settings.isTrusted
) {
return {
type: 'message',
messageType: 'error',
content: t('Workspace is untrusted; run /trust first or use --global.'),
};
}
const scopeSuffix =
scopeOverride === SettingScope.Workspace
? t(' (this project)')
: scopeOverride === SettingScope.User
? t(' (global)')
: '';
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',
...persistScopeSpread(scopeOverride),
};
}
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, scopeOverride);
return {
type: 'message',
messageType: 'info',
content: t('Voice Model') + ': ' + modelName + scopeSuffix,
};
}
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',
...persistScopeSpread(scopeOverride),
};
}
// 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, scopeOverride);
// 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 + scopeSuffix,
};
}
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();
return {
type: 'message',
messageType: 'info',
content: t(
'Current vision model: {{visionModel}}\nUse "/model --vision <model-id>" to set the vision bridge model.',
{
visionModel: visionModel
? formatVisionModelSettingForDisplay(visionModel)
: t('not set'),
},
),
};
}
return {
type: 'dialog',
dialog: 'vision-model',
...persistScopeSpread(scopeOverride),
};
}
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 matchingModels = availableModels.filter(
(model) => model.id === selector.modelId,
);
if (matchingModels.length > 1) {
return {
type: 'message',
messageType: 'error',
content: formatAmbiguousVisionModelMessage(modelName, matchingModels),
};
}
const matched = matchingModels[0];
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 },
),
};
}
const qualifiedModelName = `${
selector.authType ?? matched.authType
}:${selector.modelId}`;
const visionModel = matched.baseUrl
? `${qualifiedModelName}\0${matched.baseUrl}`
: qualifiedModelName;
persistSetting(settings, 'visionModel', visionModel, scopeOverride);
// Sync runtime Config so the vision bridge picks it up without a restart.
config.setVisionModel(visionModel);
// 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 + scopeSuffix + 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.'),
};
}
// `/model <id>` switches the session model; `/model <id> <prompt>` runs the
// prompt on <id> for this turn only (inline one-shot override) without
// changing or persisting the session model.
const trimmedArgs = args.trim();
const firstSpace = trimmedArgs.search(/\s/);
const modelName =
firstSpace === -1 ? trimmedArgs : trimmedArgs.slice(0, firstSpace);
const inlinePrompt =
firstSpace === -1 ? '' : trimmedArgs.slice(firstSpace + 1).trim();
if (modelName) {
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,
),
};
}
if (inlinePrompt) {
// ACP hosts send the prompt on the session model via a separate
// pipeline that doesn't thread a per-turn override, so the inline form
// would silently run on the default model. Reject it there rather than
// mislead; the two-step `/model <id>` flow still works in ACP.
if (context.executionMode === 'acp') {
return {
type: 'message',
messageType: 'error',
content: t(
"Inline one-shot override isn't supported in this mode — run '/model {{model}}' first, then send your prompt.",
{ model: modelName },
),
};
}
// Scope flags are silently consumed by parseScopeFlags but the inline
// prompt path doesn't persist the model. Reject the combination to avoid
// surprising the user with a "(this project)" confirmation that never
// took effect.
if (scopeOverride) {
const scopeFlag = hasProject
? '--project'
: hasGlobal
? '--global'
: '';
return {
type: 'message',
messageType: 'error',
content: t(
"Cannot combine {{flag}} with an inline prompt. Run '/model {{flag}} {{model}}' first, then send your prompt.",
{ flag: scopeFlag },
),
};
}
// The per-turn override reuses the active provider's endpoint and
// credentials and only swaps the model id; it cannot rebuild
// baseUrl/envKey for a different provider. So the target must resolve to
// the SAME provider identity, not merely the same auth type — otherwise
// a same-id model owned by a different (e.g. OpenAI-compatible) provider
// would be sent to the active endpoint/account. Reject an explicit
// different auth type outright (the `(authType)` suffix), then require
// the provider identity (baseUrl + envKey) to match the active content
// generator via the shared check that consumers also enforce. Mismatches
// are pointed at the two-step `/model <id>` flow, which does switch
// providers.
const sameAuthType = targetAuthType === authType;
if (
!sameAuthType ||
!isInlineModelOverrideAllowed(config, parsed.modelId)
) {
return {
type: 'message',
messageType: 'error',
content: t(
"Inline one-shot override can't switch providers. '{{model}}' belongs to a different provider — run '/model {{model}}' first, then send your prompt.",
{ model: modelName },
),
};
}
return {
type: 'submit_prompt',
content: inlinePrompt,
modelOverride: parsed.modelId,
};
}
if (!settings) {
return {
type: 'message',
messageType: 'error',
content: t('Settings service not available.'),
};
}
const effectiveModelName = await switchMainModel(
config,
settings,
authType,
modelName,
scopeOverride,
);
return {
type: 'message',
messageType: 'info',
content: t('Model') + ': ' + effectiveModelName + scopeSuffix,
};
}
// 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: t(
'Current model: {{model}}\nUse "/model <model-id>" to switch models, "/model --fast <model-id>" to set the fast model, "/model --project <model-id>" to persist to project settings, or "/model --global <model-id>" to persist to user settings.',
{ model: currentModel },
),
};
}
return {
type: 'dialog',
dialog: 'model',
...persistScopeSpread(scopeOverride),
};
},
};