@trans-ai/trans-code 0.2.4 → 0.4.0

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.
Files changed (39) hide show
  1. package/README.md +68 -17
  2. package/package.json +1 -1
  3. package/src/acp/session.ts +4 -1
  4. package/src/agent/loop.test.ts +337 -1
  5. package/src/agent/loop.ts +166 -2
  6. package/src/agent/system-prompt.test.ts +24 -1
  7. package/src/agent/system-prompt.ts +21 -0
  8. package/src/agent/tools/ask-model.test.ts +54 -0
  9. package/src/agent/tools/ask-model.ts +44 -0
  10. package/src/agent/tools/bash.test.ts +42 -1
  11. package/src/agent/tools/bash.ts +202 -15
  12. package/src/agent/tools/dispatch.test.ts +157 -0
  13. package/src/agent/tools/dispatch.ts +151 -0
  14. package/src/agent/tools/files.test.ts +96 -0
  15. package/src/agent/tools/files.ts +111 -29
  16. package/src/agent/tools/fs-utils.ts +40 -0
  17. package/src/agent/tools/index.ts +29 -2
  18. package/src/agent/tools/powershell.test.ts +61 -0
  19. package/src/agent/tools/read-only.ts +16 -0
  20. package/src/agent/tools/search.test.ts +55 -1
  21. package/src/agent/tools/search.ts +56 -8
  22. package/src/agent/tools/session.ts +21 -0
  23. package/src/agent/tools/shell-paths.test.ts +65 -0
  24. package/src/agent/tools/shell-paths.ts +19 -0
  25. package/src/agent/tools/todo.test.ts +54 -0
  26. package/src/agent/tools/todo.ts +47 -0
  27. package/src/agent/tools/types.ts +15 -1
  28. package/src/cli.ts +2 -0
  29. package/src/commands.ts +55 -2
  30. package/src/config.ts +21 -3
  31. package/src/main.tsx +4 -4
  32. package/src/provider/model-list.test.ts +65 -0
  33. package/src/provider/provider.test.ts +117 -0
  34. package/src/provider/provider.ts +312 -34
  35. package/src/provider/routing.test.ts +109 -0
  36. package/src/screens/REPL.tsx +432 -35
  37. package/src/sessions/store.test.ts +91 -0
  38. package/src/sessions/store.ts +149 -0
  39. package/src/version.ts +1 -1
@@ -3,7 +3,15 @@ import { ChatAnthropic } from '@langchain/anthropic';
3
3
  import { BaseChatModel } from '@langchain/core/language_models/chat_models';
4
4
  import { loadConfig, saveConfig } from '../config.js';
5
5
 
6
- export type ModelId = 'opus' | 'gpt' | 'deepseek' | 'glm' | 'minimax' | 'kimi';
6
+ export type ModelId =
7
+ | 'opus'
8
+ | 'gpt'
9
+ | 'deepseek'
10
+ | 'glm'
11
+ | 'glmc'
12
+ | 'minimax'
13
+ | 'kimi'
14
+ | 'custom';
7
15
 
8
16
  export type ProviderKind = 'openai' | 'anthropic';
9
17
 
@@ -42,6 +50,16 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
42
50
  baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
43
51
  envKey: 'GLM_API_KEY',
44
52
  },
53
+ glmc: {
54
+ name: 'GLM Coding Plan',
55
+ provider: 'openai',
56
+ // The GLM Coding Plan subscription only bills against the dedicated
57
+ // coding endpoint; the standard /api/paas/v4 endpoint answers 429
58
+ // "余额不足或无可用资源包" because the plan is not applied there.
59
+ model: 'glm-4.6',
60
+ baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
61
+ envKey: 'GLM_API_KEY',
62
+ },
45
63
  minimax: {
46
64
  name: 'MiniMax',
47
65
  provider: 'openai',
@@ -56,8 +74,42 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
56
74
  baseUrl: 'https://api.moonshot.cn/v1',
57
75
  envKey: 'KIMI_API_KEY',
58
76
  },
77
+ custom: {
78
+ name: 'Custom (OpenAI 兼容网关)',
79
+ provider: 'openai',
80
+ model: '',
81
+ baseUrl: '',
82
+ envKey: 'TRANSCODE_API_KEY',
83
+ },
84
+ };
85
+
86
+ /** Curated model lists behind each vendor in the /models flow. */
87
+ const VENDOR_MODELS: Partial<Record<ModelId, string[]>> = {
88
+ opus: ['claude-opus-4-20250514', 'claude-sonnet-4-20250514'],
89
+ gpt: ['gpt-4o', 'gpt-4o-mini'],
90
+ deepseek: ['deepseek-chat', 'deepseek-reasoner'],
91
+ glm: ['glm-4.6', 'glm-4.5', 'glm-4.5-air', 'glm-4-flash'],
92
+ glmc: ['glm-4.6', 'glm-4.5'],
93
+ minimax: ['MiniMax-Text-01'],
94
+ kimi: ['moonshot-v1-128k', 'moonshot-v1-8k'],
59
95
  };
60
96
 
97
+ /** Registry id → spec prefix understood by resolveModel. */
98
+ const SPEC_PREFIX: Record<string, string> = {
99
+ opus: 'anthropic',
100
+ gpt: 'openai',
101
+ };
102
+
103
+ export function vendorModels(id: ModelId): string[] {
104
+ if (id === 'custom') return [loadConfig().custom?.model ?? ''].filter(Boolean);
105
+ return VENDOR_MODELS[id] ?? [MODEL_REGISTRY[id]?.model ?? ''].filter(Boolean);
106
+ }
107
+
108
+ export function vendorModelSpec(id: ModelId, modelName: string): string {
109
+ const prefix = SPEC_PREFIX[id] ?? id;
110
+ return `${prefix}:${modelName}`;
111
+ }
112
+
61
113
  const PROVIDER_DEFAULTS: Record<
62
114
  string,
63
115
  { provider: ProviderKind; baseUrl?: string; envKey: string }
@@ -74,6 +126,11 @@ const PROVIDER_DEFAULTS: Record<
74
126
  baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
75
127
  envKey: 'GLM_API_KEY',
76
128
  },
129
+ glmc: {
130
+ provider: 'openai',
131
+ baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
132
+ envKey: 'GLM_API_KEY',
133
+ },
77
134
  minimax: {
78
135
  provider: 'openai',
79
136
  baseUrl: 'https://api.minimax.chat/v1',
@@ -89,6 +146,11 @@ const PROVIDER_DEFAULTS: Record<
89
146
  baseUrl: 'https://api.moonshot.cn/v1',
90
147
  envKey: 'KIMI_API_KEY',
91
148
  },
149
+ custom: {
150
+ provider: 'openai',
151
+ baseUrl: undefined,
152
+ envKey: 'TRANSCODE_API_KEY',
153
+ },
92
154
  };
93
155
 
94
156
  export interface TransProvider {
@@ -199,6 +261,21 @@ export function resolveModel(spec?: string): ResolvedModel {
199
261
 
200
262
  if (!raw) return resolveModel('opus');
201
263
 
264
+ // User profiles win over built-in registry ids (same name = override).
265
+ const profile = raw.includes(':') ? undefined : loadConfig().profiles?.[raw];
266
+ if (profile?.baseUrl && profile.model) {
267
+ return {
268
+ id: raw,
269
+ name: `${raw} · ${profile.model}`,
270
+ provider: 'openai',
271
+ model: profile.model,
272
+ baseUrl: profile.baseUrl,
273
+ envKey: profile.envKey ?? keyIdToEnvKey(profile.keyId) ?? 'TRANSCODE_API_KEY',
274
+ // Carried internally for key resolution; harmless extra field.
275
+ ...({ keyId: profile.keyId } as object),
276
+ } as ResolvedModel;
277
+ }
278
+
202
279
  if (raw.toLowerCase() === 'fable') {
203
280
  const fable = fableModelName();
204
281
  if (fable) {
@@ -215,6 +292,17 @@ export function resolveModel(spec?: string): ResolvedModel {
215
292
 
216
293
  if (isKnownModelId(raw)) {
217
294
  const cfg = MODEL_REGISTRY[raw];
295
+ if (raw === 'custom') {
296
+ const saved = loadConfig().custom;
297
+ return {
298
+ id: raw,
299
+ name: saved?.model ? `${cfg.name} · ${saved.model}` : cfg.name,
300
+ provider: cfg.provider,
301
+ model: saved?.model ?? '',
302
+ baseUrl: saved?.baseUrl ?? '',
303
+ envKey: cfg.envKey,
304
+ };
305
+ }
218
306
  return {
219
307
  id: raw,
220
308
  name: cfg.name,
@@ -231,13 +319,15 @@ export function resolveModel(spec?: string): ResolvedModel {
231
319
  const model = raw.slice(colon + 1);
232
320
  const defaults = PROVIDER_DEFAULTS[prefix];
233
321
  if (defaults && model) {
322
+ const custom = prefix === 'custom' ? loadConfig().custom : undefined;
234
323
  return {
235
324
  id: raw,
236
325
  name: `${prefix}/${model}`,
237
326
  provider: defaults.provider,
238
327
  model,
239
328
  baseUrl:
240
- defaults.provider === 'anthropic' ? anthropicGatewayUrl() : defaults.baseUrl,
329
+ custom?.baseUrl ??
330
+ (defaults.provider === 'anthropic' ? anthropicGatewayUrl() : defaults.baseUrl),
241
331
  envKey: defaults.envKey,
242
332
  };
243
333
  }
@@ -303,7 +393,7 @@ export function createModel(spec?: string): TransProvider {
303
393
  const resolved = resolveModel(spec);
304
394
  // Keys entered in the REPL (`models` flow) take precedence over the
305
395
  // environment, so switching models in the session actually works.
306
- const apiKey = registeredApiKey(resolved.id) ?? apiKeyFor(resolved.envKey);
396
+ const apiKey = lookupApiKey(resolved.id);
307
397
 
308
398
  if (!apiKey) {
309
399
  throw new Error(
@@ -312,53 +402,96 @@ export function createModel(spec?: string): TransProvider {
312
402
  );
313
403
  }
314
404
 
315
- let model: BaseChatModel;
316
405
  const baseUrl = baseUrlFor(resolved);
406
+ const model = buildChatModel(resolved, apiKey, baseUrl, maxTokens());
317
407
 
408
+ return {
409
+ modelId: resolved.id,
410
+ model,
411
+ config: {
412
+ name: resolved.name,
413
+ provider: resolved.provider,
414
+ model: resolved.model,
415
+ baseUrl,
416
+ envKey: resolved.envKey,
417
+ },
418
+ };
419
+ }
420
+
421
+ function buildChatModel(
422
+ resolved: ResolvedModel,
423
+ apiKey: string,
424
+ baseUrl: string | undefined,
425
+ tokens: number,
426
+ ): BaseChatModel {
318
427
  if (resolved.provider === 'anthropic') {
319
428
  // Only use bearer auth when there is no explicit ANTHROPIC_API_KEY, so a
320
429
  // real Anthropic endpoint never receives both x-api-key and Authorization.
321
430
  const authToken = process.env.ANTHROPIC_API_KEY?.trim() ? '' : anthropicAuthToken();
322
- model = new ChatAnthropic({
431
+ return new ChatAnthropic({
323
432
  modelName: resolved.model,
324
433
  anthropicApiKey: apiKey,
325
434
  ...(baseUrl ? { anthropicApiUrl: baseUrl } : {}),
326
435
  ...(authToken ? { clientOptions: { authToken } } : {}),
327
436
  temperature: 0,
328
- maxTokens: maxTokens(),
437
+ maxTokens: tokens,
329
438
  // @langchain/anthropic defaults top_k/top_p to -1 and forwards them on
330
439
  // every request. Strict Anthropic-compatible gateways reject that
331
440
  // ("top_p is in (0, 1.0]"), so drop both keys unless explicitly set.
332
441
  invocationKwargs: { top_k: undefined, top_p: undefined },
333
442
  maxRetries: 1,
334
443
  });
335
- } else {
336
- model = new ChatOpenAI({
337
- modelName: resolved.model,
338
- openAIApiKey: apiKey,
339
- temperature: 0,
340
- maxTokens: maxTokens(),
341
- maxRetries: 1,
342
- configuration: baseUrl ? { baseURL: baseUrl } : undefined,
343
- });
344
444
  }
445
+ if (!baseUrl && /custom/.test(resolved.id)) {
446
+ throw new Error('Custom gateway is not configured yet — set a base URL and model first.');
447
+ }
448
+ return new ChatOpenAI({
449
+ modelName: resolved.model,
450
+ openAIApiKey: apiKey,
451
+ temperature: 0,
452
+ maxTokens: tokens,
453
+ maxRetries: 1,
454
+ configuration: baseUrl ? { baseURL: baseUrl } : undefined,
455
+ });
456
+ }
345
457
 
346
- return {
347
- modelId: resolved.id,
348
- model,
349
- config: {
350
- name: resolved.name,
351
- provider: resolved.provider,
352
- model: resolved.model,
353
- baseUrl,
354
- envKey: resolved.envKey,
355
- },
356
- };
458
+ /**
459
+ * Connectivity check used by the /models flow: one minimal completion with a
460
+ * short timeout. Returns a readable message for the UI either way.
461
+ */
462
+ export async function verifyModel(
463
+ spec: string,
464
+ apiKeyOverride?: string,
465
+ ): Promise<{ ok: boolean; message: string }> {
466
+ const resolved = resolveModel(spec);
467
+ const apiKey = apiKeyOverride?.trim() || lookupApiKey(resolved.id);
468
+ if (!apiKey) {
469
+ return { ok: false, message: `缺少 API key(${resolved.envKey}),请先输入。` };
470
+ }
471
+
472
+ try {
473
+ const model = buildChatModel(resolved, apiKey, baseUrlFor(resolved), 16);
474
+ const response = (await Promise.race([
475
+ model.invoke('ping'),
476
+ new Promise<never>((_, reject) =>
477
+ setTimeout(() => reject(new Error('连接超时(10s)')), 10_000).unref?.(),
478
+ ),
479
+ ])) as { response_metadata?: { model_name?: string } };
480
+
481
+ const served = response?.response_metadata?.model_name;
482
+ return {
483
+ ok: true,
484
+ message: `连通正常${served ? `(实际模型 ${served})` : ''}`,
485
+ };
486
+ } catch (error) {
487
+ const raw = (error as Error).message ?? String(error);
488
+ return { ok: false, message: raw.length > 300 ? `${raw.slice(0, 300)}…` : raw };
489
+ }
357
490
  }
358
491
 
359
492
  /** @deprecated Use createModel instead. Kept for the existing REPL. */
360
- export function createProviderWithKey(id: ModelId, apiKey: string): TransProvider {
361
- const config = MODEL_REGISTRY[id];
493
+ export function createProviderWithKey(id: string, apiKey: string): TransProvider {
494
+ const config = MODEL_REGISTRY[id as ModelId];
362
495
  if (!config) throw new Error(`Unknown model: ${id}`);
363
496
 
364
497
  registerApiKey(id, apiKey);
@@ -379,7 +512,7 @@ export function createProviderWithKey(id: ModelId, apiKey: string): TransProvide
379
512
  }
380
513
 
381
514
  /** @deprecated Use createModel instead. Kept for the existing REPL. */
382
- export function createProvider(id: ModelId): TransProvider {
515
+ export function createProvider(id: string): TransProvider {
383
516
  return createModel(id);
384
517
  }
385
518
 
@@ -390,7 +523,7 @@ const keyStore = new Map<string, string>(
390
523
  );
391
524
 
392
525
  /** Register an API key for a registry model and persist it to disk. */
393
- export function registerApiKey(id: ModelId, apiKey: string): void {
526
+ export function registerApiKey(id: string, apiKey: string): void {
394
527
  keyStore.set(id, apiKey);
395
528
  const cfg = loadConfig();
396
529
  cfg.apiKeys = { ...(cfg.apiKeys ?? {}), [id]: apiKey };
@@ -402,14 +535,159 @@ export function registeredApiKey(id: string): string | undefined {
402
535
  return keyStore.get(id);
403
536
  }
404
537
 
538
+ /** Test helper: forget all REPL-registered keys. */
539
+ export function clearRegisteredApiKeys(): void {
540
+ keyStore.clear();
541
+ }
542
+
543
+ /**
544
+ * Resolves the API key for a spec or registry id: exact match first, then
545
+ * the vendor prefix ("deepseek:deepseek-reasoner" → "deepseek"), then any
546
+ * vendor sharing the same env credential family (glmc reuses the glm key),
547
+ * then the environment.
548
+ */
549
+ export function lookupApiKey(specOrId: string): string | undefined {
550
+ const trimmed = specOrId.trim();
551
+ const prefix = trimmed.split(':')[0]!;
552
+ const candidates = [trimmed, prefix];
553
+ const resolved = resolveModel(trimmed);
554
+ for (const [id, config] of Object.entries(MODEL_REGISTRY)) {
555
+ if (config.envKey === resolved.envKey) candidates.push(id);
556
+ }
557
+ for (const candidate of candidates) {
558
+ const key = keyStore.get(candidate) ?? loadConfig().apiKeys?.[candidate];
559
+ if (key) return key;
560
+ }
561
+ return apiKeyFor(resolved.envKey) || undefined;
562
+ }
563
+
564
+ /** Persist the custom gateway chosen in the /models flow. */
565
+ export function setCustomModel(custom: { baseUrl: string; model: string }): void {
566
+ const cfg = loadConfig();
567
+ cfg.custom = { baseUrl: custom.baseUrl, model: custom.model };
568
+ saveConfig(cfg);
569
+ }
570
+
571
+ /** Maps a key store id onto a sensible env var name (glm → GLM_API_KEY). */
572
+ function keyIdToEnvKey(keyId: string | undefined): string | undefined {
573
+ if (!keyId) return undefined;
574
+ const registry = MODEL_REGISTRY[keyId as ModelId];
575
+ if (registry) return registry.envKey;
576
+ return `${keyId.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_API_KEY`;
577
+ }
578
+
579
+ /** Role → profile routing table. */
580
+ export function getRouting(): Record<string, string> {
581
+ return { ...(loadConfig().routing ?? {}) };
582
+ }
583
+
584
+ /**
585
+ * Live model list from an endpoint's OpenAI-compatible GET /models, so the
586
+ * /models picker shows what the gateway actually serves (Zhipu's coding
587
+ * endpoint, for one, maps old names to newer generations). Empty list on
588
+ * any failure — callers fall back to the curated list. The override form
589
+ * queries an in-progress custom gateway before it is saved.
590
+ */
591
+ export async function listEndpointModels(
592
+ specOrId: string,
593
+ override?: { baseUrl: string; apiKey?: string },
594
+ ): Promise<string[]> {
595
+ try {
596
+ const baseUrl = (override?.baseUrl ?? baseUrlFor(resolveModel(specOrId)))?.replace(/\/$/, '');
597
+ if (!baseUrl) return [];
598
+ const apiKey = override?.apiKey ?? lookupApiKey(resolveModel(specOrId).id);
599
+ const response = await Promise.race([
600
+ fetch(`${baseUrl}/models`, {
601
+ headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
602
+ }),
603
+ new Promise<Response>((_, reject) =>
604
+ setTimeout(() => reject(new Error('timeout')), 5_000),
605
+ ),
606
+ ]);
607
+ if (!response.ok) return [];
608
+ const body = (await response.json()) as { data?: Array<{ id?: string }> };
609
+ const ids = (body.data ?? [])
610
+ .map((entry) => entry?.id)
611
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
612
+ return [...new Set(ids)].sort();
613
+ } catch {
614
+ return [];
615
+ }
616
+ }
617
+
618
+ /** Set (or clear with "-") a role's profile. */
619
+ export function setRouting(role: string, profile: string): void {
620
+ if (!role.trim()) throw new Error('Role name cannot be empty.');
621
+ const cfg = loadConfig();
622
+ cfg.routing = { ...(cfg.routing ?? {}) };
623
+ if (profile.trim() === '-') delete cfg.routing[role];
624
+ else cfg.routing[role] = profile.trim();
625
+ saveConfig(cfg);
626
+ }
627
+
628
+ /** Resolve a role name to its routed model, if configured. */
629
+ export function resolveRole(role: string): ResolvedModel | undefined {
630
+ const profile = getRouting()[role];
631
+ if (!profile) return undefined;
632
+ return resolveModel(profile);
633
+ }
634
+
635
+ /**
636
+ * One-shot delegation to a routed role (used by the ask_model tool): sends
637
+ * the prompt — optionally with base64 images for vision roles — to the
638
+ * role's model and returns its text answer.
639
+ */
640
+ export async function askRole(
641
+ role: string,
642
+ prompt: string,
643
+ images?: Array<{ data: string; mediaType: string }>,
644
+ ): Promise<string> {
645
+ const routing = getRouting();
646
+ const profile = routing[role];
647
+ if (!profile) {
648
+ const names = Object.keys(routing).join(', ');
649
+ throw new Error(`Unknown role "${role}". Configured roles: ${names || '(none — set one with /route)'}`);
650
+ }
651
+
652
+ const provider = createModel(profile);
653
+ const content = images?.length
654
+ ? ([
655
+ { type: 'text', text: prompt },
656
+ ...images.map((image) => ({
657
+ type: 'image_url' as const,
658
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
659
+ })),
660
+ ] as unknown as string)
661
+ : prompt;
662
+
663
+ const response = (await Promise.race([
664
+ provider.model.invoke(content),
665
+ new Promise<never>((_, reject) =>
666
+ setTimeout(() => reject(new Error('角色模型超时(180s)')), 180_000),
667
+ ),
668
+ ])) as { content: unknown };
669
+
670
+ if (typeof response.content === 'string') return response.content;
671
+ if (Array.isArray(response.content)) {
672
+ return response.content
673
+ .map((block) =>
674
+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
675
+ ? (block as { text: string }).text
676
+ : '',
677
+ )
678
+ .join('');
679
+ }
680
+ return '';
681
+ }
682
+
405
683
  /** Model chosen in the REPL on a previous run, if any. */
406
- export function preferredModelId(): ModelId | undefined {
684
+ export function preferredModelId(): string | undefined {
407
685
  const saved = loadConfig().model;
408
- return saved && isKnownModelId(saved) ? saved : undefined;
686
+ return saved?.trim() || undefined;
409
687
  }
410
688
 
411
- /** Persist the REPL's model choice for the next run. */
412
- export function setPreferredModel(id: ModelId): void {
689
+ /** Persist the REPL's model choice (registry id or provider:model spec). */
690
+ export function setPreferredModel(id: string): void {
413
691
  const cfg = loadConfig();
414
692
  cfg.model = id;
415
693
  saveConfig(cfg);
@@ -0,0 +1,109 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { loadConfig, saveConfig } from '../config.js';
6
+ import {
7
+ clearRegisteredApiKeys,
8
+ getRouting,
9
+ lookupApiKey,
10
+ resolveModel,
11
+ resolveRole,
12
+ setRouting,
13
+ } from './provider.js';
14
+
15
+ let configDir: string;
16
+ beforeEach(() => {
17
+ configDir = mkdtempSync(path.join(tmpdir(), 'transcode-routing-test-'));
18
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
19
+ clearRegisteredApiKeys();
20
+ });
21
+ afterEach(() => {
22
+ delete process.env.TRANSCODE_CONFIG_PATH;
23
+ rmSync(configDir, { recursive: true, force: true });
24
+ });
25
+
26
+ describe('profiles', () => {
27
+ test('a user profile maps a model id to an endpoint and model name', () => {
28
+ saveConfig({
29
+ ...loadConfig(),
30
+ profiles: {
31
+ 'glm-vision': {
32
+ baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
33
+ model: 'glm-4.6v',
34
+ keyId: 'glm',
35
+ },
36
+ },
37
+ });
38
+
39
+ const resolved = resolveModel('glm-vision');
40
+ expect(resolved.model).toBe('glm-4.6v');
41
+ expect(resolved.baseUrl).toBe('https://open.bigmodel.cn/api/paas/v4');
42
+ expect(resolved.envKey).toBe('GLM_API_KEY');
43
+ });
44
+
45
+ test('a user profile overrides a built-in registry id of the same name', () => {
46
+ saveConfig({
47
+ ...loadConfig(),
48
+ profiles: {
49
+ deepseek: {
50
+ baseUrl: 'https://relay.example.com/v1',
51
+ model: 'deepseek-reasoner',
52
+ keyId: 'deepseek',
53
+ },
54
+ },
55
+ });
56
+
57
+ const resolved = resolveModel('deepseek');
58
+ expect(resolved.model).toBe('deepseek-reasoner');
59
+ expect(resolved.baseUrl).toBe('https://relay.example.com/v1');
60
+ });
61
+
62
+ test('keyId references the shared key store', () => {
63
+ saveConfig({
64
+ ...loadConfig(),
65
+ apiKeys: { glm: 'glm-key' },
66
+ profiles: {
67
+ 'glm-vision': {
68
+ baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
69
+ model: 'glm-4.6v',
70
+ keyId: 'glm',
71
+ },
72
+ },
73
+ });
74
+
75
+ expect(lookupApiKey('glm-vision')).toBe('glm-key');
76
+ });
77
+
78
+ test('unknown names keep the legacy resolution behavior', () => {
79
+ const resolved = resolveModel('kimi');
80
+ expect(resolved.baseUrl).toBe('https://api.moonshot.cn/v1');
81
+ });
82
+ });
83
+
84
+ describe('role routing', () => {
85
+ test('roles are arbitrary names mapped to profiles', () => {
86
+ setRouting('analysis', 'glm-coding');
87
+ setRouting('design', 'opus');
88
+ expect(getRouting()).toEqual({ analysis: 'glm-coding', design: 'opus' });
89
+ });
90
+
91
+ test('resolveRole maps a role through to the profile model', () => {
92
+ setRouting('analysis', 'glmc');
93
+ const resolved = resolveRole('analysis');
94
+ expect(resolved?.model).toBe('glm-4.6');
95
+ expect(resolved?.baseUrl).toContain('/api/coding/');
96
+ });
97
+
98
+ test('removing a role with "-" clears it', () => {
99
+ setRouting('analysis', 'glmc');
100
+ setRouting('analysis', '-');
101
+ expect(getRouting().analysis).toBeUndefined();
102
+ expect(resolveRole('analysis')).toBeUndefined();
103
+ });
104
+
105
+ test('routing persists across config loads', () => {
106
+ setRouting('review', 'deepseek');
107
+ expect(loadConfig().routing?.review).toBe('deepseek');
108
+ });
109
+ });