-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathconfig.ts
More file actions
950 lines (880 loc) · 31.8 KB
/
Copy pathconfig.ts
File metadata and controls
950 lines (880 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
import {
effectiveModelAlias,
PRIMARY_SUBAGENT_MODEL_CHOICE,
SECONDARY_DERIVED_MODEL_ALIAS,
type ExperimentalFeatureState,
type ModelAlias,
type PermissionMode,
type Session,
type ThinkingEffort,
} from '@moonshot-ai/kimi-code-sdk';
import { EditorSelectorComponent } from '../components/dialogs/editor-selector';
import { EffortSelectorComponent } from '../components/dialogs/effort-selector';
import {
ExperimentsSelectorComponent,
type ExperimentalFeatureDraftChange,
} from '../components/dialogs/experiments-selector';
import {
defaultThinkingEffortFor,
modelDisplayName,
segmentsFor,
effortsOf,
} from '../components/dialogs/model-selector';
import { TabbedModelSelectorComponent } from '../components/dialogs/tabbed-model-selector';
import { PermissionSelectorComponent } from '../components/dialogs/permission-selector';
import { SettingsSelectorComponent, type SettingsSelection } from '../components/dialogs/settings-selector';
import { ThemeSelectorComponent } from '../components/dialogs/theme-selector';
import { UpdatePreferenceSelectorComponent } from '../components/dialogs/update-preference-selector';
import { DEFAULT_TUI_CONFIG, saveTuiConfig, type TuiConfig } from '../config';
import type { ThemeName } from '#/tui/theme';
import { currentTheme, isBuiltInTheme, lightColors, loadCustomThemeMerged } from '#/tui/theme';
import { NO_ACTIVE_SESSION_MESSAGE } from '../constant/kimi-tui';
import { formatErrorMessage } from '../utils/event-payload';
import { thinkingEffortToConfig } from '../utils/thinking-config';
import { showUsage } from './info';
import { setExperimentalFeatures } from './experimental-flags';
import type { SlashCommandHost } from './dispatch';
// ---------------------------------------------------------------------------
// Plan / Config commands
// ---------------------------------------------------------------------------
const MODEL_PICKER_REFRESH_TIMEOUT_MS = 2_000;
const MODEL_SWITCH_CACHE_WARNING =
'Note: Switching models invalidates the existing prompt cache. Use /new to avoid extra token costs.';
const EFFORT_SWITCH_CACHE_WARNING =
'Note: Switching effort invalidates the existing prompt cache. Use /new to avoid extra token costs.';
/** True once the conversation has at least one user message: a switch from
* then on resends the accumulated context, losing the cache. Shell-command
* echoes are also 'user' transcript entries but carry an empty `bullet`, so
* they're excluded. */
function hasConversationHistory(host: SlashCommandHost): boolean {
return host.state.transcriptEntries.some(
(entry) => entry.kind === 'user' && entry.bullet !== '',
);
}
export function currentTuiConfig(host: Pick<SlashCommandHost, 'state'>): TuiConfig {
return {
theme: host.state.appState.theme,
editorCommand: host.state.appState.editorCommand,
disablePasteBurst: host.state.appState.disablePasteBurst ?? DEFAULT_TUI_CONFIG.disablePasteBurst,
renderLatex: host.state.appState.renderLatex ?? DEFAULT_TUI_CONFIG.renderLatex ?? true,
cacheExpiryHint: host.state.appState.cacheExpiryHint ?? DEFAULT_TUI_CONFIG.cacheExpiryHint,
notifications: host.state.appState.notifications,
upgrade: host.state.appState.upgrade,
statusLine: host.state.appState.statusLine ?? DEFAULT_TUI_CONFIG.statusLine,
};
}
export function effectiveModelForHost(host: SlashCommandHost, model: ModelAlias): ModelAlias {
const providerType = host.state.appState.availableProviders[model.provider]?.type;
// Flat models (no named provider, e.g. inline base_url served by a v2
// backend) have no provider entry to look up; their own protocol declaration
// plays the provider-identity role, mirroring the resolver.
return effectiveModelAlias(model, providerType ?? model.protocol);
}
export async function handlePlanCommand(host: SlashCommandHost, args: string): Promise<void> {
const session = host.session;
if (session === undefined) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}
const subcmd = args.trim().toLowerCase();
if (subcmd === 'clear') {
await session.clearPlan();
host.showNotice('Plan cleared');
return;
}
let enabled: boolean;
if (subcmd.length === 0) enabled = !host.state.appState.planMode;
else if (subcmd === 'on') enabled = true;
else if (subcmd === 'off') enabled = false;
else {
host.showError(`Unknown plan subcommand: ${subcmd}`);
return;
}
// The session may already be in the requested mode (e.g. it was created
// with config.defaultPlanMode applied), and re-entering plan mode throws.
if (host.state.appState.planMode === enabled) {
host.showNotice(`Plan mode is already ${enabled ? 'on' : 'off'}`);
return;
}
await applyPlanMode(host, session, enabled);
}
async function applyPlanMode(host: SlashCommandHost, session: Session, enabled: boolean): Promise<void> {
try {
await session.setPlanMode(enabled);
host.setAppState({ planMode: enabled });
if (enabled) {
const plan = await session.getPlan().catch(() => null);
host.showNotice(
'Plan mode: ON',
plan?.path !== undefined ? `Plan will be created here: ${plan.path}` : undefined,
);
return;
}
host.showNotice('Plan mode: OFF');
} catch (error) {
const msg = formatErrorMessage(error);
host.showError(`Failed to set plan mode: ${msg}`);
}
}
export async function handleYoloCommand(host: SlashCommandHost, args: string): Promise<void> {
const session = host.session;
if (session === undefined && !host.engineV2) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}
// v2 session-less: the chosen mode is recorded in appState and passed to the
// lazy-created session; apply the runtime permission only when one exists.
const subcmd = args.trim().toLowerCase();
const currentMode = host.state.appState.permissionMode;
if (subcmd === 'on') {
if (currentMode === 'yolo') {
host.showNotice('YOLO mode is already on');
return;
}
await session?.setPermission('yolo');
host.setAppState({ permissionMode: 'yolo' });
host.showNotice('YOLO mode: ON', 'Tool actions auto-approved; the agent may still ask you questions.');
return;
}
if (subcmd === 'off') {
if (currentMode !== 'yolo') {
host.showNotice('YOLO mode is already off');
return;
}
await session?.setPermission('manual');
host.setAppState({ permissionMode: 'manual' });
host.showNotice('YOLO mode: OFF');
return;
}
// toggle
if (currentMode === 'yolo') {
await session?.setPermission('manual');
host.setAppState({ permissionMode: 'manual' });
host.showNotice('YOLO mode: OFF');
} else {
await session?.setPermission('yolo');
host.setAppState({ permissionMode: 'yolo' });
host.showNotice('YOLO mode: ON', 'Tool actions auto-approved; the agent may still ask you questions.');
}
}
export async function handleAutoCommand(host: SlashCommandHost, args: string): Promise<void> {
const session = host.session;
if (session === undefined && !host.engineV2) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}
// v2 session-less: the chosen mode is recorded in appState and passed to the
// lazy-created session; apply the runtime permission only when one exists.
const subcmd = args.trim().toLowerCase();
const currentMode = host.state.appState.permissionMode;
if (subcmd === 'on') {
if (currentMode === 'auto') {
host.showNotice('Auto mode is already on');
return;
}
await session?.setPermission('auto');
host.setAppState({ permissionMode: 'auto' });
host.showNotice('Auto mode: ON', 'All actions auto-approved; the agent will not ask you questions.');
return;
}
if (subcmd === 'off') {
if (currentMode !== 'auto') {
host.showNotice('Auto mode is already off');
return;
}
await session?.setPermission('manual');
host.setAppState({ permissionMode: 'manual' });
host.showNotice('Auto mode: OFF');
return;
}
// toggle
if (currentMode === 'auto') {
await session?.setPermission('manual');
host.setAppState({ permissionMode: 'manual' });
host.showNotice('Auto mode: OFF');
} else {
await session?.setPermission('auto');
host.setAppState({ permissionMode: 'auto' });
host.showNotice('Auto mode: ON', 'All actions auto-approved; the agent will not ask you questions.');
}
}
export async function handleCompactCommand(host: SlashCommandHost, args: string): Promise<void> {
const session = host.session;
if (session === undefined) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}
const customInstruction = args.trim() || undefined;
await session.compact({ instruction: customInstruction });
}
export async function handleEditorCommand(host: SlashCommandHost, args: string): Promise<void> {
const command = args.trim();
if (command.length === 0) {
showEditorPicker(host);
return;
}
await applyEditorChoice(host, command);
}
export async function handleThemeCommand(host: SlashCommandHost, args: string): Promise<void> {
const theme = args.trim();
if (theme.length === 0) {
showThemePicker(host);
return;
}
if (!isBuiltInTheme(theme)) {
const custom = await loadCustomThemeMerged(theme);
if (custom === null) {
host.showError(`Unknown theme: ${theme}`);
return;
}
}
await applyThemeChoice(host, theme);
}
export async function handleModelCommand(host: SlashCommandHost, args: string): Promise<void> {
const alias = args.trim();
await refreshModelsForPicker(host);
if (alias.length === 0) {
showModelPicker(host);
return;
}
if (host.state.appState.availableModels[alias] === undefined) {
host.showError(`Unknown model alias: ${alias}`);
return;
}
showModelPicker(host, alias);
}
export async function handleSecondaryModelCommand(host: SlashCommandHost, args: string): Promise<void> {
const alias = args.trim();
await refreshModelsForPicker(host);
const models = pickerModelsForHost(host);
// The pool reserves `primary` as the symbolic "caller's own model" choice —
// a user alias with that name can never be the subagent default.
delete models[PRIMARY_SUBAGENT_MODEL_CHOICE];
if (alias === PRIMARY_SUBAGENT_MODEL_CHOICE) {
host.showError(
`"${PRIMARY_SUBAGENT_MODEL_CHOICE}" is reserved by the subagent model pool (it always binds the caller's own model) — rename the [models] alias to use it here.`,
);
return;
}
if (Object.keys(models).length === 0) {
host.showNotice(
'No models configured',
'Run /login to sign in to Kimi, or /provider to add another provider from a model catalog.',
);
return;
}
if (alias.length > 0 && models[alias] === undefined) {
host.showError(`Unknown model alias: ${alias}`);
return;
}
const secondary = (await host.harness.getConfig()).secondaryModel;
// The v2 engine honors a lone legacy `model` key as the fallback pool
// default — reflect it as the picker's current value.
const current = secondary?.defaultModel ?? secondary?.model ?? '';
showSecondaryModelPicker(host, models, current, alias.length > 0 ? alias : undefined);
}
export async function handleEffortCommand(host: SlashCommandHost, args: string): Promise<void> {
const alias = host.state.appState.model;
const model = host.state.appState.availableModels[alias];
if (model === undefined) {
host.showError('No model selected. Run /model to select one first.');
return;
}
const effective = effectiveModelForHost(host, model);
const segments = segmentsFor(effective);
const arg = args.trim().toLowerCase();
if (arg.length === 0) {
showEffortPicker(host, effective, segments);
return;
}
const canonical = segments.find((segment) => segment.toLowerCase() === arg);
if (canonical === undefined) {
const declared = effortsOf(effective);
// 'on' is the generic enable signal: with a declared effort list the
// engine maps it to the declared default effort, so it stays a valid
// command even though it never appears in the segment list.
if (arg === 'on' && declared.length > 0) {
await performModelSwitch(host, alias, arg, true);
return;
}
const providerType = host.state.appState.availableProviders[effective.provider]?.type;
const protocol = effective.protocol ?? providerType;
// With a declared effort list the engine falls back to the model default
// for every protocol, so an unlisted value is rejected like any invalid
// input. Only Anthropic-compatible models WITHOUT a declared list keep
// the warn-and-send escape hatch — there the engine passes the value
// through for the backend to judge.
if (protocol !== 'anthropic' || declared.length > 0) {
host.showError(
`Unsupported thinking effort "${arg}" for ${alias}. Available: ${segments.join(', ')}`,
);
return;
}
host.showStatus(
`Thinking effort "${arg}" is not declared for ${alias}. Sending "${arg}" unchanged; the configured provider will validate it.`,
'warning',
);
}
await performModelSwitch(host, alias, canonical ?? arg, true);
}
function showEffortPicker(
host: SlashCommandHost,
model: ModelAlias,
segments: readonly string[],
): void {
const liveEffort = host.state.appState.thinkingEffort;
const currentValue = segments.includes(liveEffort) ? liveEffort : (segments[0] ?? 'off');
const alias = host.state.appState.model;
host.mountEditorReplacement(
new EffortSelectorComponent({
efforts: segments,
currentValue,
warning: hasConversationHistory(host) ? EFFORT_SWITCH_CACHE_WARNING : undefined,
onSelect: (effort) => {
host.restoreEditor();
void performModelSwitch(host, alias, effort, true);
},
onSessionOnlySelect: (effort) => {
host.restoreEditor();
void performModelSwitch(host, alias, effort, false);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
// ---------------------------------------------------------------------------
// Pickers & config apply
// ---------------------------------------------------------------------------
function showEditorPicker(host: SlashCommandHost): void {
const currentValue = host.state.appState.editorCommand ?? '';
host.mountEditorReplacement(
new EditorSelectorComponent({
currentValue,
onSelect: (value) => {
host.restoreEditor();
void applyEditorChoice(host, value);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
async function refreshModelsForPicker(host: SlashCommandHost): Promise<void> {
try {
const result = await withTimeout(
host.authFlow.refreshOAuthProviderModels(),
MODEL_PICKER_REFRESH_TIMEOUT_MS,
);
if (result === undefined) return;
for (const f of result.failed) {
host.showStatus(`Skipped refreshing ${f.provider}: ${f.reason}`, 'warning');
}
} catch (error) {
host.showStatus(`Skipped refreshing models: ${formatErrorMessage(error)}`, 'warning');
}
}
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<undefined>((resolve) => {
timeout = setTimeout(() => {
resolve(undefined);
}, timeoutMs);
}),
]);
} finally {
if (timeout !== undefined) clearTimeout(timeout);
}
}
async function applyEditorChoice(host: SlashCommandHost, value: string): Promise<void> {
const previous = host.state.appState.editorCommand ?? '';
if (value === previous && value.length > 0) {
host.showStatus(`Editor unchanged: ${value.length > 0 ? value : 'auto-detect'}`);
return;
}
const editorCommand = value.length > 0 ? value : null;
try {
await saveTuiConfig({
...currentTuiConfig(host),
editorCommand,
});
} catch (error) {
host.showStatus(
`Failed to save editor: ${formatErrorMessage(error)}`,
'error',
);
return;
}
host.setAppState({ editorCommand });
host.showStatus(
value.length > 0
? `Editor set to "${value}".`
: 'Editor set to auto-detect ($VISUAL / $EDITOR).',
);
}
/**
* The models a picker may offer: the user's configured aliases with
* host-effective provider resolution applied, minus the synthesized
* `__secondary__` derived entry — a runtime artifact of the v1 engine's
* `[secondary_model]` recipe that must never be selectable as a model.
*/
function pickerModelsForHost(host: SlashCommandHost): Record<string, ModelAlias> {
return Object.fromEntries(
Object.entries(host.state.appState.availableModels)
.filter(([alias]) => alias !== SECONDARY_DERIVED_MODEL_ALIAS)
.map(([alias, model]) => [alias, effectiveModelForHost(host, model)]),
);
}
export function showModelPicker(host: SlashCommandHost, selectedValue: string = host.state.appState.model): void {
const models = pickerModelsForHost(host);
const entries = Object.entries(models);
if (entries.length === 0) {
host.showNotice(
'No models configured',
'Run /login to sign in to Kimi, or /provider to add another provider from a model catalog.',
);
return;
}
host.mountEditorReplacement(
new TabbedModelSelectorComponent({
models,
currentValue: host.state.appState.model,
selectedValue,
currentThinkingEffort: host.state.appState.thinkingEffort,
warning: hasConversationHistory(host) ? MODEL_SWITCH_CACHE_WARNING : undefined,
onSelect: ({ alias, thinking }) => {
host.restoreEditor();
void performModelSwitch(host, alias, thinking, true);
},
onSessionOnlySelect: ({ alias, thinking }) => {
host.restoreEditor();
void performModelSwitch(host, alias, thinking, false);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
async function performModelSwitch(
host: SlashCommandHost,
alias: string,
effort: ThinkingEffort,
persist: boolean,
): Promise<void> {
let session = host.session;
if (session === undefined && host.engineV2) {
// A first prompt may still be inside lazy creation: wait it out so the
// switch lands on the new session instead of being overwritten by its
// assembly.
await host.waitForLazyCreation();
session = host.session;
}
if (host.state.appState.streamingPhase !== 'idle') {
host.showError('Cannot switch models while streaming — press Esc or Ctrl-C first.');
return;
}
const prevModel = host.state.appState.model;
const prevEffort = host.state.appState.thinkingEffort;
const modelChanged = alias !== prevModel;
const effortChanged = effort !== prevEffort;
const runtimeChanged = modelChanged || effortChanged;
let effectiveAlias = alias;
let effectiveEffort = effort;
try {
if (session === undefined && runtimeChanged) {
// Session-less (lazy creation): no engine is around to map the generic
// 'on' onto the model's declared default yet, so resolve it here — the
// carried state and the status line should show the effort the first
// session will actually use. The engine re-resolves the concrete value
// at creation, which is in-list and therefore unchanged.
const selectedModel = host.state.appState.availableModels[alias];
const sessionlessEffort =
effort === 'on' && selectedModel !== undefined
? defaultThinkingEffortFor(effectiveModelForHost(host, selectedModel))
: effort;
await host.authFlow.activateModelAfterLogin(alias, sessionlessEffort);
} else if (session !== undefined) {
if (alias !== prevModel) {
await session.setModel(alias);
}
if (effort !== prevEffort) {
await session.setThinking(effort);
}
const status = await session.getStatus();
effectiveAlias = status.model ?? alias;
effectiveEffort = status.thinkingEffort;
}
} catch (error) {
const msg = formatErrorMessage(error);
host.showError(`Failed to switch model: ${msg}`);
return;
}
if (session === undefined) {
effectiveAlias = host.state.appState.model;
effectiveEffort = host.state.appState.thinkingEffort;
}
const effectiveModelChanged = effectiveAlias !== prevModel;
const effectiveEffortChanged = effectiveEffort !== prevEffort;
const displayName = modelDisplayName(
effectiveAlias,
host.state.appState.availableModels[effectiveAlias],
);
host.setAppState({ model: effectiveAlias, thinkingEffort: effectiveEffort });
if (session === undefined && runtimeChanged) {
if (effectiveModelChanged) {
host.track('model_switch', { model: effectiveAlias });
}
if (effectiveEffortChanged) {
host.track('thinking_toggle', {
enabled: effectiveEffort !== 'off',
effort: effectiveEffort,
from: prevEffort,
});
}
}
let persisted = false;
if (persist) {
try {
persisted = await persistModelSelection(
host,
effectiveAlias,
effectiveEffort,
effectiveEffortChanged,
);
} catch (error) {
const msg = formatErrorMessage(error);
host.showError(`Switched to ${displayName}, but failed to save default: ${msg}`);
return;
}
}
let status: string;
if (effectiveModelChanged) {
status = persist
? `Switched to ${displayName} with thinking ${effectiveEffort}.`
: `Switched to ${displayName} with thinking ${effectiveEffort} for this session only.`;
} else if (effectiveEffortChanged) {
status = persist
? `Thinking set to ${effectiveEffort}.`
: `Thinking set to ${effectiveEffort} for this session only.`;
} else if (persist && persisted) {
status = `Saved ${displayName} with thinking ${effectiveEffort} as default.`;
} else {
status = `Already using ${displayName} with thinking ${effectiveEffort}.`;
}
host.showStatus(status, 'success');
}
async function persistModelSelection(
host: SlashCommandHost,
alias: string,
effort: ThinkingEffort,
effortChanged: boolean,
): Promise<boolean> {
const config = await host.harness.getConfig({ reload: true });
const model = host.state.appState.availableModels[alias];
const full = thinkingEffortToConfig(
effort,
model === undefined ? undefined : effectiveModelForHost(host, model).supportEfforts,
);
// Re-confirming the effort shown when the picker opened is not an explicit
// choice — persist the model but leave the stored effort preference alone.
const patch = effortChanged ? full : { enabled: full.enabled };
if (
config.defaultModel === alias &&
config.thinking?.enabled === patch.enabled &&
(!effortChanged || config.thinking?.effort === patch.effort)
) {
return false;
}
await host.harness.setConfig({
defaultModel: alias,
thinking: patch,
});
return true;
}
// ---------------------------------------------------------------------------
// Secondary model (`/secondary-model`) — persists `[secondary_model] default_model`
// ---------------------------------------------------------------------------
function showSecondaryModelPicker(
host: SlashCommandHost,
models: Record<string, ModelAlias>,
currentValue: string,
selectedValue?: string,
): void {
host.mountEditorReplacement(
new TabbedModelSelectorComponent({
models,
currentValue,
selectedValue,
currentThinkingEffort: 'off',
// Subagent pool bindings carry no explicit thinking level, so the picker
// hides the Thinking footer instead of offering a no-op choice.
thinkingControl: false,
title: ' Select a secondary model (subagents)',
onSelect: ({ alias }) => {
host.restoreEditor();
void performSecondaryModelSave(host, alias);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
/**
* Persists `[secondary_model] default_model`. When a
* `[secondary_model.models]` pool exists and does not list the alias yet, the
* alias is added with an empty description — the engine requires the default
* to be a pool key. Without a pool the default alone forms an implicit
* single-entry pool, so nothing else is written. No live-apply step: the
* engine resolves the pool per spawn, so the next subagent dispatch picks the
* new value up on its own.
*/
async function performSecondaryModelSave(host: SlashCommandHost, alias: string): Promise<void> {
const displayName = modelDisplayName(alias, host.state.appState.availableModels[alias]);
try {
const config = await host.harness.getConfig({ reload: true });
const existing = config.secondaryModel?.models;
const patch: { defaultModel: string; models?: Record<string, string> } = {
defaultModel: alias,
};
if (existing !== undefined) {
patch.models = { ...existing, [alias]: existing[alias] ?? '' };
}
await host.harness.setConfig({ secondaryModel: patch });
} catch (error) {
host.showError(`Failed to save secondary model: ${formatErrorMessage(error)}`);
return;
}
host.showStatus(
`Secondary model set to ${displayName}. Newly spawned subagents will use it by default.`,
'success',
);
}
function showThemePicker(host: SlashCommandHost): void {
host.mountEditorReplacement(
new ThemeSelectorComponent({
currentValue: host.state.appState.theme,
onSelect: (value) => {
host.restoreEditor();
void applyThemeChoice(host, value);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
async function applyThemeChoice(host: SlashCommandHost, theme: ThemeName): Promise<void> {
if (theme === host.state.appState.theme) {
if (theme === 'auto') host.refreshTerminalThemeTracking();
host.showStatus(`Theme unchanged: "${theme}".`);
return;
}
// Validate custom themes up front so a missing / malformed file reports an
// error instead of silently persisting a name that resolves to the dark
// fallback.
if (!isBuiltInTheme(theme)) {
const palette = await loadCustomThemeMerged(theme);
if (palette === null) {
host.showStatus(`Theme "${theme}" could not be loaded.`, 'error');
return;
}
}
try {
await saveTuiConfig({
...currentTuiConfig(host),
theme,
});
} catch (error) {
host.showStatus(
`Failed to save theme: ${formatErrorMessage(error)}`,
'error',
);
return;
}
const resolved = theme === 'auto'
? (currentTheme.palette === lightColors ? 'light' : 'dark')
: undefined;
await host.applyTheme(theme, resolved);
host.refreshTerminalThemeTracking();
host.track('theme_switch', { theme });
const detail = theme === 'auto' ? ` (tracking terminal; current: ${resolved})` : '';
host.showStatus(`Theme set to "${theme}"${detail}.`);
}
export function showPermissionPicker(host: SlashCommandHost): void {
host.mountEditorReplacement(
new PermissionSelectorComponent({
currentValue: host.state.appState.permissionMode,
onSelect: (value) => {
host.restoreEditor();
void applyPermissionChoice(host, value);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
export function showUpdatePreferencePicker(host: SlashCommandHost): void {
host.mountEditorReplacement(
new UpdatePreferenceSelectorComponent({
currentValue: host.state.appState.upgrade.autoInstall,
onSelect: (value) => {
host.restoreEditor();
void applyUpdatePreferenceChoice(host, value);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
export async function showExperimentsPanel(host: SlashCommandHost): Promise<void> {
let features: readonly ExperimentalFeatureState[];
try {
features = await host.harness.getExperimentalFeatures();
} catch (error) {
host.showError(`Failed to load experimental features: ${formatErrorMessage(error)}`);
return;
}
mountExperimentsPanel(host, features);
}
export async function applyExperimentalFeatureChanges(
host: SlashCommandHost,
changes: readonly ExperimentalFeatureDraftChange[],
): Promise<void> {
if (changes.length === 0) {
host.showStatus(
'No experimental feature changes to apply.',
'textMuted',
);
return;
}
const experimental: Record<string, boolean> = {};
for (const change of changes) {
experimental[change.id] = change.enabled;
}
try {
await host.harness.setConfig({ experimental });
const features = await host.harness.getExperimentalFeatures();
setExperimentalFeatures(features);
host.refreshSlashCommandAutocomplete();
host.restoreEditor();
if (host.session !== undefined) {
await host.session.reloadSession();
await host.reloadCurrentSessionView(
host.session,
'Experimental features updated. Session reloaded.',
);
} else {
host.showStatus('Experimental features updated.', 'success');
}
host.track('experimental_features_apply', { changed: changes.length });
} catch (error) {
host.showError(`Failed to update experimental features: ${formatErrorMessage(error)}`);
}
}
function mountExperimentsPanel(
host: SlashCommandHost,
features: readonly ExperimentalFeatureState[],
): void {
host.mountEditorReplacement(
new ExperimentsSelectorComponent({
features,
onApply: (changes) => {
void applyExperimentalFeatureChanges(host, changes);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
type UpdatePreferenceHost = {
readonly state: {
readonly appState: Pick<
SlashCommandHost['state']['appState'],
'theme' | 'editorCommand' | 'notifications' | 'upgrade'
>;
};
setAppState(patch: Pick<SlashCommandHost['state']['appState'], 'upgrade'>): void;
showStatus(msg: string, color?: string): void;
track: SlashCommandHost['track'];
};
export async function applyUpdatePreferenceChoice(
host: UpdatePreferenceHost,
autoInstall: boolean,
): Promise<void> {
if (autoInstall === host.state.appState.upgrade.autoInstall) {
host.showStatus(`Automatic updates already ${autoInstall ? 'enabled' : 'disabled'}.`);
return;
}
const upgrade = { autoInstall };
try {
await saveTuiConfig({
...currentTuiConfig(host as unknown as SlashCommandHost),
upgrade,
});
} catch (error) {
host.showStatus(
`Failed to save automatic update setting: ${formatErrorMessage(error)}`,
'error',
);
return;
}
host.setAppState({ upgrade });
host.track('upgrade_preference_changed', { auto_install: autoInstall });
host.showStatus(`Automatic updates ${autoInstall ? 'enabled' : 'disabled'}.`);
}
async function applyPermissionChoice(host: SlashCommandHost, mode: PermissionMode): Promise<void> {
if (mode === host.state.appState.permissionMode) {
host.showStatus(`Permission mode unchanged: ${mode}.`);
return;
}
try {
if (host.session !== undefined) {
await host.session.setPermission(mode);
} else if (!host.engineV2) {
host.showError(NO_ACTIVE_SESSION_MESSAGE);
return;
}
// v2 session-less: the chosen mode is recorded in appState and passed to
// the lazy-created session.
} catch (error) {
const msg = formatErrorMessage(error);
host.showError(`Failed to set permission mode: ${msg}`);
return;
}
host.setAppState({ permissionMode: mode });
host.showNotice(`Permission mode: ${mode}`);
}
export function showSettingsSelector(host: SlashCommandHost): void {
host.mountEditorReplacement(
new SettingsSelectorComponent({
onSelect: (value) => {
handleSettingsSelection(host, value);
},
onCancel: () => {
host.restoreEditor();
},
}),
);
}
function handleSettingsSelection(host: SlashCommandHost, value: SettingsSelection): void {
host.restoreEditor();
switch (value) {
case 'model': showModelPicker(host); return;
case 'permission': showPermissionPicker(host); return;
case 'theme': showThemePicker(host); return;
case 'editor': showEditorPicker(host); return;
case 'experiments': void showExperimentsPanel(host); return;
case 'upgrade': showUpdatePreferencePicker(host); return;
case 'usage': void showUsage(host); return;
}
}