@trans-ai/trans-code 0.2.3 → 0.3.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.
- package/README.md +58 -17
- package/package.json +1 -1
- package/src/acp/session.ts +15 -1
- package/src/agent/loop.test.ts +401 -1
- package/src/agent/loop.ts +137 -13
- package/src/agent/system-prompt.test.ts +24 -1
- package/src/agent/system-prompt.ts +25 -0
- package/src/agent/tools/ask-model.test.ts +54 -0
- package/src/agent/tools/ask-model.ts +44 -0
- package/src/agent/tools/dispatch.test.ts +115 -0
- package/src/agent/tools/dispatch.ts +141 -0
- package/src/agent/tools/files.test.ts +96 -0
- package/src/agent/tools/files.ts +111 -29
- package/src/agent/tools/fs-utils.ts +40 -0
- package/src/agent/tools/index.ts +27 -2
- package/src/agent/tools/search.test.ts +55 -1
- package/src/agent/tools/search.ts +56 -8
- package/src/agent/tools/session.ts +9 -0
- package/src/agent/tools/todo.test.ts +54 -0
- package/src/agent/tools/todo.ts +47 -0
- package/src/agent/tools/types.ts +13 -1
- package/src/cli.ts +1 -0
- package/src/commands.ts +37 -2
- package/src/config.ts +21 -3
- package/src/main.tsx +6 -8
- package/src/provider/provider.test.ts +117 -0
- package/src/provider/provider.ts +278 -34
- package/src/provider/routing.test.ts +109 -0
- package/src/screens/REPL.tsx +204 -31
- package/src/screens/banner.test.ts +21 -0
- package/src/screens/banner.ts +9 -0
- package/src/version.ts +1 -1
package/src/provider/provider.ts
CHANGED
|
@@ -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 =
|
|
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'],
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** Registry id → spec prefix understood by resolveModel. */
|
|
98
|
+
const SPEC_PREFIX: Record<string, string> = {
|
|
99
|
+
opus: 'anthropic',
|
|
100
|
+
gpt: 'openai',
|
|
59
101
|
};
|
|
60
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
|
-
|
|
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 =
|
|
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());
|
|
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
|
+
}
|
|
317
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
|
-
|
|
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:
|
|
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
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
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:
|
|
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:
|
|
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:
|
|
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,125 @@ 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
|
+
/** Set (or clear with "-") a role's profile. */
|
|
585
|
+
export function setRouting(role: string, profile: string): void {
|
|
586
|
+
if (!role.trim()) throw new Error('Role name cannot be empty.');
|
|
587
|
+
const cfg = loadConfig();
|
|
588
|
+
cfg.routing = { ...(cfg.routing ?? {}) };
|
|
589
|
+
if (profile.trim() === '-') delete cfg.routing[role];
|
|
590
|
+
else cfg.routing[role] = profile.trim();
|
|
591
|
+
saveConfig(cfg);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** Resolve a role name to its routed model, if configured. */
|
|
595
|
+
export function resolveRole(role: string): ResolvedModel | undefined {
|
|
596
|
+
const profile = getRouting()[role];
|
|
597
|
+
if (!profile) return undefined;
|
|
598
|
+
return resolveModel(profile);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* One-shot delegation to a routed role (used by the ask_model tool): sends
|
|
603
|
+
* the prompt — optionally with base64 images for vision roles — to the
|
|
604
|
+
* role's model and returns its text answer.
|
|
605
|
+
*/
|
|
606
|
+
export async function askRole(
|
|
607
|
+
role: string,
|
|
608
|
+
prompt: string,
|
|
609
|
+
images?: Array<{ data: string; mediaType: string }>,
|
|
610
|
+
): Promise<string> {
|
|
611
|
+
const routing = getRouting();
|
|
612
|
+
const profile = routing[role];
|
|
613
|
+
if (!profile) {
|
|
614
|
+
const names = Object.keys(routing).join(', ');
|
|
615
|
+
throw new Error(`Unknown role "${role}". Configured roles: ${names || '(none — set one with /route)'}`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const provider = createModel(profile);
|
|
619
|
+
const content = images?.length
|
|
620
|
+
? ([
|
|
621
|
+
{ type: 'text', text: prompt },
|
|
622
|
+
...images.map((image) => ({
|
|
623
|
+
type: 'image_url' as const,
|
|
624
|
+
image_url: { url: `data:${image.mediaType};base64,${image.data}` },
|
|
625
|
+
})),
|
|
626
|
+
] as unknown as string)
|
|
627
|
+
: prompt;
|
|
628
|
+
|
|
629
|
+
const response = (await Promise.race([
|
|
630
|
+
provider.model.invoke(content),
|
|
631
|
+
new Promise<never>((_, reject) =>
|
|
632
|
+
setTimeout(() => reject(new Error('角色模型超时(180s)')), 180_000),
|
|
633
|
+
),
|
|
634
|
+
])) as { content: unknown };
|
|
635
|
+
|
|
636
|
+
if (typeof response.content === 'string') return response.content;
|
|
637
|
+
if (Array.isArray(response.content)) {
|
|
638
|
+
return response.content
|
|
639
|
+
.map((block) =>
|
|
640
|
+
block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
|
|
641
|
+
? (block as { text: string }).text
|
|
642
|
+
: '',
|
|
643
|
+
)
|
|
644
|
+
.join('');
|
|
645
|
+
}
|
|
646
|
+
return '';
|
|
647
|
+
}
|
|
648
|
+
|
|
405
649
|
/** Model chosen in the REPL on a previous run, if any. */
|
|
406
|
-
export function preferredModelId():
|
|
650
|
+
export function preferredModelId(): string | undefined {
|
|
407
651
|
const saved = loadConfig().model;
|
|
408
|
-
return saved
|
|
652
|
+
return saved?.trim() || undefined;
|
|
409
653
|
}
|
|
410
654
|
|
|
411
|
-
/** Persist the REPL's model choice
|
|
412
|
-
export function setPreferredModel(id:
|
|
655
|
+
/** Persist the REPL's model choice (registry id or provider:model spec). */
|
|
656
|
+
export function setPreferredModel(id: string): void {
|
|
413
657
|
const cfg = loadConfig();
|
|
414
658
|
cfg.model = id;
|
|
415
659
|
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
|
+
});
|