@trans-ai/trans-code 0.8.2 → 0.10.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 +20 -2
- package/docs/superpowers/plans/2026-11-21-auto-compact.md +84 -0
- package/docs/superpowers/plans/2026-11-21-compact-speed.md +85 -0
- package/docs/superpowers/plans/2026-11-22-user-memory.md +243 -0
- package/docs/superpowers/plans/2026-11-22-web-tools.md +192 -0
- package/docs/superpowers/specs/2026-11-21-auto-compact-design.md +25 -0
- package/docs/superpowers/specs/2026-11-21-compact-speed-design.md +21 -0
- package/docs/superpowers/specs/2026-11-22-user-memory-design.md +48 -0
- package/docs/superpowers/specs/2026-11-22-web-tools-design.md +48 -0
- package/package.json +1 -1
- package/src/acp/server.ts +6 -0
- package/src/agent/loop.ts +5 -1
- package/src/agent/memory.test.ts +169 -0
- package/src/agent/memory.ts +207 -0
- package/src/agent/system-prompt.test.ts +87 -1
- package/src/agent/system-prompt.ts +23 -1
- package/src/agent/tools/index.ts +7 -0
- package/src/agent/tools/memory.test.ts +88 -0
- package/src/agent/tools/memory.ts +61 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/agent/tools/web-fetch.test.ts +186 -0
- package/src/agent/tools/web-fetch.ts +137 -0
- package/src/agent/tools/web-search.test.ts +100 -0
- package/src/agent/tools/web-search.ts +41 -0
- package/src/commands.test.ts +104 -1
- package/src/commands.ts +101 -0
- package/src/config.test.ts +25 -0
- package/src/config.ts +52 -0
- package/src/provider/web-search.test.ts +195 -0
- package/src/provider/web-search.ts +143 -0
- package/src/screens/REPL.tsx +222 -24
- package/src/screens/search-setup.test.ts +89 -0
- package/src/screens/search-setup.ts +57 -0
- package/src/screens/submit.test.ts +8 -0
- package/src/screens/submit.ts +1 -1
- package/src/sessions/compact.test.ts +90 -25
- package/src/sessions/compact.ts +41 -9
- package/src/version.ts +1 -1
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AgentTool } from './types.js';
|
|
3
|
+
import { loadConfig } from '../../config.js';
|
|
4
|
+
import { normalizeWebSearchConfig, runWebSearch } from '../../provider/web-search.js';
|
|
5
|
+
|
|
6
|
+
export const webSearchTool: AgentTool = {
|
|
7
|
+
name: 'web_search',
|
|
8
|
+
description:
|
|
9
|
+
'Search the web via the user-configured provider (tavily|brave). Returns ' +
|
|
10
|
+
'title/url/snippet hits — pair with web_fetch to read a promising result.',
|
|
11
|
+
kind: 'fetch',
|
|
12
|
+
isMutating: false,
|
|
13
|
+
isEnabled: () => normalizeWebSearchConfig(loadConfig().webSearch) !== null,
|
|
14
|
+
schema: z.object({
|
|
15
|
+
query: z.string().min(1).describe('Search query'),
|
|
16
|
+
maxResults: z.number().int().min(1).max(20).optional().describe('Hits to return (default 5)'),
|
|
17
|
+
}),
|
|
18
|
+
title: (input) => `web_search ${input.query}`,
|
|
19
|
+
async execute(input, ctx) {
|
|
20
|
+
const cfg = normalizeWebSearchConfig(loadConfig().webSearch);
|
|
21
|
+
if (!cfg) {
|
|
22
|
+
return (
|
|
23
|
+
'Error: web_search not configured — set webSearch { provider, apiKey } in ' +
|
|
24
|
+
'~/.transcode.json or run /search.'
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const hits = await runWebSearch(
|
|
29
|
+
cfg,
|
|
30
|
+
String(input.query),
|
|
31
|
+
input.maxResults ? Number(input.maxResults) : undefined,
|
|
32
|
+
globalThis.fetch,
|
|
33
|
+
ctx?.signal,
|
|
34
|
+
);
|
|
35
|
+
if (hits.length === 0) return `No results for: ${input.query}`;
|
|
36
|
+
return hits.map((hit) => `${hit.title} — ${hit.url}\n${hit.snippet}`).join('\n\n');
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return `Error: web_search failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
};
|
package/src/commands.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
-
import { findCommand, getCommands } from './commands.js';
|
|
2
|
+
import { executeCommand, findCommand, getCommands, type Command } from './commands.js';
|
|
3
3
|
import { getPermissionMode, resetPermissionMode, setPermissionMode } from './agent/permission.js';
|
|
4
4
|
|
|
5
5
|
afterEach(() => {
|
|
@@ -54,3 +54,106 @@ describe('mode command', () => {
|
|
|
54
54
|
expect(getPermissionMode()).toBe('ask');
|
|
55
55
|
});
|
|
56
56
|
});
|
|
57
|
+
|
|
58
|
+
describe('memory commands', () => {
|
|
59
|
+
const ctx = { modelId: 'deepseek', setModelId: () => {}, clearHistory: () => {} };
|
|
60
|
+
|
|
61
|
+
async function withMemoryRoot(run: () => Promise<void>): Promise<void> {
|
|
62
|
+
const { mkdtempSync, promises: fs, rmSync } = await import('node:fs');
|
|
63
|
+
const { tmpdir } = await import('node:os');
|
|
64
|
+
const path = await import('node:path');
|
|
65
|
+
const root = mkdtempSync(path.join(tmpdir(), 'transcode-memory-cmd-'));
|
|
66
|
+
process.env.TRANSCODE_USER_DIR = root;
|
|
67
|
+
try {
|
|
68
|
+
await run();
|
|
69
|
+
} finally {
|
|
70
|
+
delete process.env.TRANSCODE_USER_DIR;
|
|
71
|
+
rmSync(root, { recursive: true, force: true });
|
|
72
|
+
void fs;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
test('/memory:有记忆 → 列索引行 + 根路径 + 提示;空态 → "No memories yet" 引导 /remember', async () => {
|
|
77
|
+
await withMemoryRoot(async () => {
|
|
78
|
+
const { saveMemory } = await import('./agent/memory.js');
|
|
79
|
+
await saveMemory({ name: 'pref-editor', type: 'user', content: 'Vim everywhere.', description: '编辑器偏好' });
|
|
80
|
+
|
|
81
|
+
const memory = findCommand('memory')!;
|
|
82
|
+
const result = await memory.execute([], ctx);
|
|
83
|
+
expect(result.output).toContain('pref-editor');
|
|
84
|
+
expect(result.output).toContain('编辑器偏好');
|
|
85
|
+
expect(result.output).toContain('/remember');
|
|
86
|
+
expect(result.output).toContain('/forget');
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
await withMemoryRoot(async () => {
|
|
90
|
+
const memory = findCommand('memory')!;
|
|
91
|
+
const empty = await memory.execute([], ctx);
|
|
92
|
+
expect(empty.output).toContain('No memories yet');
|
|
93
|
+
expect(empty.output).toContain('/remember');
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('/remember 一段话 → 存为 type=user,content=原文,输出确认与 name;同名冲突加 -2 后缀;纯中文取名前 8 字符', async () => {
|
|
98
|
+
await withMemoryRoot(async () => {
|
|
99
|
+
const { loadUserMemory, saveMemory } = await import('./agent/memory.js');
|
|
100
|
+
const remember = findCommand('remember')!;
|
|
101
|
+
|
|
102
|
+
const result = await remember.execute(['prefer', 'bun', 'over', 'node'], ctx);
|
|
103
|
+
expect(result.output).toContain('prefer-bun-over-node');
|
|
104
|
+
const saved = await loadUserMemory();
|
|
105
|
+
expect(saved.entries[0]).toMatchObject({
|
|
106
|
+
name: 'prefer-bun-over-node',
|
|
107
|
+
type: 'user',
|
|
108
|
+
content: 'prefer bun over node',
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
await saveMemory({ name: 'prefer-bun-over-node', type: 'user', content: '占位' });
|
|
112
|
+
const clash = await remember.execute(['prefer', 'bun', 'over', 'node', 'now'], ctx);
|
|
113
|
+
expect(clash.output).toContain('prefer-bun-over-node-2');
|
|
114
|
+
|
|
115
|
+
const cjk = await remember.execute(['中文偏好测试'], ctx);
|
|
116
|
+
expect(cjk.output).toContain('中文偏好测试');
|
|
117
|
+
const after = await loadUserMemory();
|
|
118
|
+
expect(after.entries.some((e) => e.name === '中文偏好测试' && e.content === '中文偏好测试')).toBe(true);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('/forget 命中 → "Forgot <name>.";未命中 → "No memory named"', async () => {
|
|
123
|
+
await withMemoryRoot(async () => {
|
|
124
|
+
const { saveMemory } = await import('./agent/memory.js');
|
|
125
|
+
await saveMemory({ name: 'drop-me', type: 'user', content: 'x', description: 'd' });
|
|
126
|
+
|
|
127
|
+
const forget = findCommand('forget')!;
|
|
128
|
+
const hit = await forget.execute(['drop-me'], ctx);
|
|
129
|
+
expect(hit.output).toContain('Forgot drop-me.');
|
|
130
|
+
|
|
131
|
+
const miss = await forget.execute(['no-such'], ctx);
|
|
132
|
+
expect(miss.output).toContain('No memory named');
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
describe('executeCommand error containment', () => {
|
|
138
|
+
test('命令 execute 抛异常 → 返回错误文案而非向上抛', async () => {
|
|
139
|
+
const boom: Command = {
|
|
140
|
+
name: 'boom',
|
|
141
|
+
description: 'throws',
|
|
142
|
+
execute: () => {
|
|
143
|
+
throw new Error('EACCES: permission denied');
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
const result = await executeCommand(boom, [], { modelId: 'deepseek', setModelId: () => {}, clearHistory: () => {} });
|
|
147
|
+
expect(result.output).toContain('Command failed');
|
|
148
|
+
expect(result.output).toContain('EACCES');
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe('search command registration', () => {
|
|
153
|
+
test('is registered so /help lists it', () => {
|
|
154
|
+
const search = findCommand('search');
|
|
155
|
+
expect(search).toBeDefined();
|
|
156
|
+
expect(search?.description.length).toBeGreaterThan(0);
|
|
157
|
+
expect(getCommands().map((c) => c.name)).toContain('search');
|
|
158
|
+
});
|
|
159
|
+
});
|
package/src/commands.ts
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
1
3
|
import type { ModelId } from './provider/provider.js';
|
|
2
4
|
import { getAvailableModels } from './provider/provider.js';
|
|
3
5
|
import { getPermissionMode, PERMISSION_MODES, setPermissionMode } from './agent/permission.js';
|
|
4
6
|
import { getRouting, resolveRole, setRouting } from './provider/provider.js';
|
|
7
|
+
import {
|
|
8
|
+
deleteMemory,
|
|
9
|
+
globalInstructionsPath,
|
|
10
|
+
loadUserMemory,
|
|
11
|
+
memoryDir,
|
|
12
|
+
renderMemoryIndex,
|
|
13
|
+
saveMemory,
|
|
14
|
+
userMemoryRoot,
|
|
15
|
+
} from './agent/memory.js';
|
|
5
16
|
|
|
6
17
|
export interface CommandContext {
|
|
7
18
|
/** Registry id (deepseek) or provider:model spec (deepseek:deepseek-reasoner). */
|
|
@@ -22,6 +33,28 @@ export interface Command {
|
|
|
22
33
|
execute: (args: string[], ctx: CommandContext) => CommandResult | Promise<CommandResult>;
|
|
23
34
|
}
|
|
24
35
|
|
|
36
|
+
/** /remember slug: ascii words (≤4) kebab-cased; pure non-ascii text falls back to its first 8 chars. */
|
|
37
|
+
function slugFromText(text: string): string {
|
|
38
|
+
const ascii = text
|
|
39
|
+
.split(/\s+/)
|
|
40
|
+
.slice(0, 4)
|
|
41
|
+
.join(' ')
|
|
42
|
+
.toLowerCase()
|
|
43
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
44
|
+
.replace(/^-+|-+$/g, '');
|
|
45
|
+
return ascii || text.replace(/\s+/g, '').slice(0, 8);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Appends -2, -3, … until the memory file name is free. */
|
|
49
|
+
function uniqueMemoryName(base: string): string {
|
|
50
|
+
let candidate = base;
|
|
51
|
+
let suffix = 2;
|
|
52
|
+
while (existsSync(path.join(memoryDir(), `${candidate}.md`))) {
|
|
53
|
+
candidate = `${base}-${suffix++}`;
|
|
54
|
+
}
|
|
55
|
+
return candidate;
|
|
56
|
+
}
|
|
57
|
+
|
|
25
58
|
const commands: Command[] = [
|
|
26
59
|
{
|
|
27
60
|
name: 'help',
|
|
@@ -49,6 +82,61 @@ const commands: Command[] = [
|
|
|
49
82
|
output: 'Analyzing the project and writing TRANS.md…',
|
|
50
83
|
}),
|
|
51
84
|
},
|
|
85
|
+
{
|
|
86
|
+
name: 'memory',
|
|
87
|
+
description: 'Show user memories (global instructions + memory index)',
|
|
88
|
+
execute: async () => {
|
|
89
|
+
const memory = await loadUserMemory();
|
|
90
|
+
const lines: string[] = [`Memory root: ${userMemoryRoot()}`];
|
|
91
|
+
lines.push(
|
|
92
|
+
memory.globalInstructions
|
|
93
|
+
? `Global instructions: ${globalInstructionsPath()} (${memory.globalInstructions.split('\n').length} lines)`
|
|
94
|
+
: `Global instructions: none yet — create ${globalInstructionsPath()}`,
|
|
95
|
+
);
|
|
96
|
+
if (memory.entries.length > 0) {
|
|
97
|
+
lines.push('Memories:', ...renderMemoryIndex(memory.entries).trim().split('\n'));
|
|
98
|
+
} else {
|
|
99
|
+
lines.push('No memories yet. Use /remember <text> to save one.');
|
|
100
|
+
}
|
|
101
|
+
if (memory.omitted.length > 0) {
|
|
102
|
+
lines.push(`(over budget, omitted: ${memory.omitted.join(', ')})`);
|
|
103
|
+
}
|
|
104
|
+
lines.push('Usage: /remember <text> — save a memory; /forget <name> — delete one.');
|
|
105
|
+
return { output: lines.join('\n') };
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: 'remember',
|
|
110
|
+
description: 'Save a user memory (/remember <text>)',
|
|
111
|
+
execute: async (args) => {
|
|
112
|
+
const text = args.join(' ').trim();
|
|
113
|
+
if (!text) return { output: 'Usage: /remember <text>' };
|
|
114
|
+
const name = uniqueMemoryName(slugFromText(text));
|
|
115
|
+
const entry = await saveMemory({ name, type: 'user', content: text });
|
|
116
|
+
return { output: `Saved memory "${entry.name}".` };
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
name: 'search',
|
|
121
|
+
description: 'Configure web search provider + key (tavily|brave)',
|
|
122
|
+
// Intercepted by the REPL before command dispatch (like /models): the
|
|
123
|
+
// setup runs an interactive provider → key → live-test flow.
|
|
124
|
+
execute: () => ({
|
|
125
|
+
output: 'Configuring web search…',
|
|
126
|
+
}),
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: 'forget',
|
|
130
|
+
description: 'Delete a user memory (/forget <name>)',
|
|
131
|
+
execute: async (args) => {
|
|
132
|
+
const name = args[0]?.trim();
|
|
133
|
+
if (!name) return { output: 'Usage: /forget <name>' };
|
|
134
|
+
const removed = await deleteMemory(name);
|
|
135
|
+
return removed
|
|
136
|
+
? { output: `Forgot ${name}.` }
|
|
137
|
+
: { output: `No memory named '${name}'.` };
|
|
138
|
+
},
|
|
139
|
+
},
|
|
52
140
|
{
|
|
53
141
|
name: 'mode',
|
|
54
142
|
description: 'Show or switch permission mode (ask | auto | readonly)',
|
|
@@ -142,6 +230,19 @@ const commands: Command[] = [
|
|
|
142
230
|
},
|
|
143
231
|
];
|
|
144
232
|
|
|
233
|
+
/** Dispatch wrapper: a throwing command becomes an error message, never an unhandled rejection. */
|
|
234
|
+
export async function executeCommand(
|
|
235
|
+
command: Command,
|
|
236
|
+
args: string[],
|
|
237
|
+
ctx: CommandContext,
|
|
238
|
+
): Promise<CommandResult> {
|
|
239
|
+
try {
|
|
240
|
+
return await command.execute(args, ctx);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
return { output: `Command failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
145
246
|
export function getCommands(): Command[] {
|
|
146
247
|
return commands;
|
|
147
248
|
}
|
package/src/config.test.ts
CHANGED
|
@@ -47,3 +47,28 @@ describe('normalizeAutoUpdate', () => {
|
|
|
47
47
|
}
|
|
48
48
|
});
|
|
49
49
|
});
|
|
50
|
+
|
|
51
|
+
import { normalizeAutoCompact } from './config.js';
|
|
52
|
+
|
|
53
|
+
describe('normalizeAutoCompact', () => {
|
|
54
|
+
test('undefined → enabled default 200_000; false → disabled; valid override kept', () => {
|
|
55
|
+
expect(normalizeAutoCompact(undefined)).toEqual({ enabled: true, thresholdChars: 200_000, keepTurns: 1 });
|
|
56
|
+
expect(normalizeAutoCompact(false)).toEqual({ enabled: false, thresholdChars: 200_000, keepTurns: 1 });
|
|
57
|
+
expect(normalizeAutoCompact({ thresholdChars: 50_000 })).toEqual({
|
|
58
|
+
enabled: true,
|
|
59
|
+
thresholdChars: 50_000,
|
|
60
|
+
keepTurns: 1,
|
|
61
|
+
});
|
|
62
|
+
expect(normalizeAutoCompact({ enabled: false, thresholdChars: 80_000, keepTurns: 5 })).toEqual({
|
|
63
|
+
enabled: false,
|
|
64
|
+
thresholdChars: 80_000,
|
|
65
|
+
keepTurns: 5,
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('garbage (string/null/array/negative) falls back to defaults', () => {
|
|
70
|
+
for (const raw of ['yes', 5, null, [1], { thresholdChars: -5 }, { thresholdChars: 'big' }, { keepTurns: 0 }, { keepTurns: 'ten' }]) {
|
|
71
|
+
expect(normalizeAutoCompact(raw)).toEqual({ enabled: true, thresholdChars: 200_000, keepTurns: 1 });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
});
|
package/src/config.ts
CHANGED
|
@@ -23,6 +23,10 @@ export interface TranscodeConfig {
|
|
|
23
23
|
routing?: Record<string, string>;
|
|
24
24
|
/** Auto-update on startup: `false` disables, an object configures it. */
|
|
25
25
|
autoUpdate?: boolean | AutoUpdateConfig;
|
|
26
|
+
/** Auto-compact on threshold: `false` disables, an object configures it. */
|
|
27
|
+
autoCompact?: boolean | AutoCompactConfig;
|
|
28
|
+
/** Web search vendor + key (user-configured; validated by normalizeWebSearchConfig). */
|
|
29
|
+
webSearch?: unknown;
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
/** Raw (on-disk) shape of the autoUpdate config block. */
|
|
@@ -65,6 +69,54 @@ export function normalizeAutoUpdate(raw: unknown): NormalizedAutoUpdate {
|
|
|
65
69
|
};
|
|
66
70
|
}
|
|
67
71
|
|
|
72
|
+
/** Raw (on-disk) shape of the autoCompact config block. */
|
|
73
|
+
export interface AutoCompactConfig {
|
|
74
|
+
enabled?: boolean;
|
|
75
|
+
/** Compact when the estimated context reaches this many chars. */
|
|
76
|
+
thresholdChars?: number;
|
|
77
|
+
/** Turns kept verbatim when auto-compacting (default 1). */
|
|
78
|
+
keepTurns?: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Normalized form used by the REPL checkpoint. */
|
|
82
|
+
export interface NormalizedAutoCompact {
|
|
83
|
+
enabled: boolean;
|
|
84
|
+
thresholdChars: number;
|
|
85
|
+
keepTurns: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const DEFAULT_AUTO_COMPACT: NormalizedAutoCompact = {
|
|
89
|
+
enabled: true,
|
|
90
|
+
thresholdChars: 200_000,
|
|
91
|
+
keepTurns: 1,
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Normalizes the raw autoCompact config value. Anything unrecognizable
|
|
96
|
+
* falls back to the enabled default rather than throwing — same contract
|
|
97
|
+
* as normalizeAutoUpdate.
|
|
98
|
+
*/
|
|
99
|
+
export function normalizeAutoCompact(raw: unknown): NormalizedAutoCompact {
|
|
100
|
+
if (raw === false) return { ...DEFAULT_AUTO_COMPACT, enabled: false };
|
|
101
|
+
if (raw === null || raw === undefined || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
102
|
+
return { ...DEFAULT_AUTO_COMPACT };
|
|
103
|
+
}
|
|
104
|
+
const obj = raw as AutoCompactConfig;
|
|
105
|
+
const threshold =
|
|
106
|
+
typeof obj.thresholdChars === 'number' && obj.thresholdChars > 0
|
|
107
|
+
? obj.thresholdChars
|
|
108
|
+
: DEFAULT_AUTO_COMPACT.thresholdChars;
|
|
109
|
+
const keepTurns =
|
|
110
|
+
typeof obj.keepTurns === 'number' && obj.keepTurns >= 1
|
|
111
|
+
? Math.floor(obj.keepTurns)
|
|
112
|
+
: DEFAULT_AUTO_COMPACT.keepTurns;
|
|
113
|
+
return {
|
|
114
|
+
enabled: typeof obj.enabled === 'boolean' ? obj.enabled : true,
|
|
115
|
+
thresholdChars: threshold,
|
|
116
|
+
keepTurns,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
68
120
|
// Overridable so tests never touch the user's real ~/.transcode.json.
|
|
69
121
|
const configPath = (): string =>
|
|
70
122
|
process.env.TRANSCODE_CONFIG_PATH ?? join(homedir(), '.transcode.json');
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { normalizeWebSearchConfig, runWebSearch, webSearchConfigWarning } from './web-search.js';
|
|
3
|
+
|
|
4
|
+
describe('normalizeWebSearchConfig', () => {
|
|
5
|
+
test('tavily/brave 合法通过;段缺失 → null 且无警告', () => {
|
|
6
|
+
expect(normalizeWebSearchConfig({ provider: 'tavily', apiKey: 'tvly-1' })).toEqual({
|
|
7
|
+
provider: 'tavily',
|
|
8
|
+
apiKey: 'tvly-1',
|
|
9
|
+
});
|
|
10
|
+
expect(normalizeWebSearchConfig({ provider: 'brave', apiKey: 'BSA2' })).toEqual({
|
|
11
|
+
provider: 'brave',
|
|
12
|
+
apiKey: 'BSA2',
|
|
13
|
+
});
|
|
14
|
+
expect(normalizeWebSearchConfig(undefined)).toBeNull();
|
|
15
|
+
expect(normalizeWebSearchConfig(null)).toBeNull();
|
|
16
|
+
expect(webSearchConfigWarning(undefined)).toBeNull();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('provider 拼错/key 空 → null 且警告含 "/search" 提示', () => {
|
|
20
|
+
expect(normalizeWebSearchConfig({ provider: 'google', apiKey: 'x' })).toBeNull();
|
|
21
|
+
expect(normalizeWebSearchConfig({ provider: 'tavily', apiKey: ' ' })).toBeNull();
|
|
22
|
+
expect(normalizeWebSearchConfig({ provider: 'tavily' })).toBeNull();
|
|
23
|
+
const warning = webSearchConfigWarning({ provider: 'google', apiKey: 'x' });
|
|
24
|
+
expect(warning).toContain('/search');
|
|
25
|
+
expect(warning).toContain('google');
|
|
26
|
+
expect(webSearchConfigWarning({ provider: 'tavily' })).toContain('/search');
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('runWebSearch adapters', () => {
|
|
31
|
+
test('tavily:按 spec 端点/体调用,映射 title/url/snippet', async () => {
|
|
32
|
+
let seenUrl = '';
|
|
33
|
+
let seenInit: RequestInit = {};
|
|
34
|
+
const hits = await runWebSearch(
|
|
35
|
+
{ provider: 'tavily', apiKey: 'tvly-9' },
|
|
36
|
+
'bun release notes',
|
|
37
|
+
5,
|
|
38
|
+
(async (input: any, init?: any) => {
|
|
39
|
+
seenUrl = String(input);
|
|
40
|
+
seenInit = init ?? {};
|
|
41
|
+
return new Response(
|
|
42
|
+
JSON.stringify({
|
|
43
|
+
results: [
|
|
44
|
+
{ title: 'Bun v1.3', url: 'https://bun.sh/blog/bun-v1.3', content: 'Bun 1.3 release' },
|
|
45
|
+
],
|
|
46
|
+
}),
|
|
47
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
48
|
+
);
|
|
49
|
+
}) as typeof fetch,
|
|
50
|
+
);
|
|
51
|
+
expect(seenUrl).toBe('https://api.tavily.com/search');
|
|
52
|
+
const body = JSON.parse(String(seenInit.body));
|
|
53
|
+
expect(body).toEqual({ api_key: 'tvly-9', query: 'bun release notes', max_results: 5 });
|
|
54
|
+
expect(hits).toEqual([
|
|
55
|
+
{ title: 'Bun v1.3', url: 'https://bun.sh/blog/bun-v1.3', snippet: 'Bun 1.3 release' },
|
|
56
|
+
]);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('brave:X-Subscription-Token 头 + q/count 参数,结果映射', async () => {
|
|
60
|
+
let seenUrl = '';
|
|
61
|
+
let seenHeaders: Headers | null = null;
|
|
62
|
+
const hits = await runWebSearch(
|
|
63
|
+
{ provider: 'brave', apiKey: 'BSA7' },
|
|
64
|
+
'ink react terminal',
|
|
65
|
+
3,
|
|
66
|
+
(async (input: any, init?: any) => {
|
|
67
|
+
seenUrl = String(input);
|
|
68
|
+
seenHeaders = new Headers(init?.headers);
|
|
69
|
+
return new Response(
|
|
70
|
+
JSON.stringify({
|
|
71
|
+
web: {
|
|
72
|
+
results: [
|
|
73
|
+
{ title: 'Ink', url: 'https://github.com/vadimdemedes/ink', description: 'React for CLIs' },
|
|
74
|
+
],
|
|
75
|
+
},
|
|
76
|
+
}),
|
|
77
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
78
|
+
);
|
|
79
|
+
}) as typeof fetch,
|
|
80
|
+
);
|
|
81
|
+
expect(seenUrl).toContain('https://api.search.brave.com/res/v1/web/search?');
|
|
82
|
+
expect(seenUrl).toContain('q=ink+react+terminal');
|
|
83
|
+
expect(seenUrl).toContain('count=3');
|
|
84
|
+
expect(seenHeaders!.get('x-subscription-token')).toBe('BSA7');
|
|
85
|
+
expect(hits).toEqual([
|
|
86
|
+
{ title: 'Ink', url: 'https://github.com/vadimdemedes/ink', snippet: 'React for CLIs' },
|
|
87
|
+
]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('HTTP 401/400 → 抛含状态与 API 报错文案的 Error;未知 provider 也抛', async () => {
|
|
91
|
+
const deny = (async () =>
|
|
92
|
+
new Response('{"detail":"Invalid API key"}', {
|
|
93
|
+
status: 401,
|
|
94
|
+
headers: { 'content-type': 'application/json' },
|
|
95
|
+
})) as typeof fetch;
|
|
96
|
+
await expect(
|
|
97
|
+
runWebSearch({ provider: 'tavily', apiKey: 'bad' }, 'q', 5, deny),
|
|
98
|
+
).rejects.toThrow(/401/);
|
|
99
|
+
await expect(
|
|
100
|
+
runWebSearch({ provider: 'tavily', apiKey: 'bad' }, 'q', 5, deny),
|
|
101
|
+
).rejects.toThrow(/Invalid API key/);
|
|
102
|
+
await expect(
|
|
103
|
+
runWebSearch({ provider: 'nope' as never, apiKey: 'x' }, 'q', 5, deny),
|
|
104
|
+
).rejects.toThrow(/nope/);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe('web search setup helpers', () => {
|
|
109
|
+
test('saveWebSearchConfig:写 webSearch 段且不覆盖其它段', async () => {
|
|
110
|
+
const { mkdtempSync, writeFileSync, rmSync } = await import('node:fs');
|
|
111
|
+
const { tmpdir } = await import('node:os');
|
|
112
|
+
const path = await import('node:path');
|
|
113
|
+
const { loadConfig } = await import('../config.js');
|
|
114
|
+
const { saveWebSearchConfig } = await import('./web-search.js');
|
|
115
|
+
const root = mkdtempSync(path.join(tmpdir(), 'transcode-ws-save-'));
|
|
116
|
+
const configPath = path.join(root, 'config.json');
|
|
117
|
+
writeFileSync(configPath, JSON.stringify({ apiKeys: { glm: 'g-1' }, model: 'glm' }));
|
|
118
|
+
process.env.TRANSCODE_CONFIG_PATH = configPath;
|
|
119
|
+
try {
|
|
120
|
+
saveWebSearchConfig('tavily', 'tvly-3');
|
|
121
|
+
const saved = JSON.parse((await import('node:fs')).readFileSync(configPath, 'utf8'));
|
|
122
|
+
expect(saved).toEqual({
|
|
123
|
+
apiKeys: { glm: 'g-1' },
|
|
124
|
+
model: 'glm',
|
|
125
|
+
webSearch: { provider: 'tavily', apiKey: 'tvly-3' },
|
|
126
|
+
});
|
|
127
|
+
expect(loadConfig().webSearch).toEqual({ provider: 'tavily', apiKey: 'tvly-3' });
|
|
128
|
+
} finally {
|
|
129
|
+
delete process.env.TRANSCODE_CONFIG_PATH;
|
|
130
|
+
rmSync(root, { recursive: true, force: true });
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('checkWebSearch 成功:固定测试查询,首条 title 返回', async () => {
|
|
135
|
+
const { checkWebSearch } = await import('./web-search.js');
|
|
136
|
+
let seenBody = '';
|
|
137
|
+
const result = await checkWebSearch(
|
|
138
|
+
{ provider: 'tavily', apiKey: 'tvly-8' },
|
|
139
|
+
(async (_input: any, init?: any) => {
|
|
140
|
+
seenBody = String(init?.body ?? '');
|
|
141
|
+
return new Response(
|
|
142
|
+
JSON.stringify({ results: [{ title: 'Alive', url: 'https://x/1', content: 's' }] }),
|
|
143
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
144
|
+
);
|
|
145
|
+
}) as typeof fetch,
|
|
146
|
+
);
|
|
147
|
+
expect(result).toEqual({ ok: true, firstTitle: 'Alive' });
|
|
148
|
+
expect(JSON.parse(seenBody).query).toBe('transcode connectivity check');
|
|
149
|
+
expect(JSON.parse(seenBody).max_results).toBe(1);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('checkWebSearch 失败:API 报错进 error,不抛异常', async () => {
|
|
153
|
+
const { checkWebSearch } = await import('./web-search.js');
|
|
154
|
+
const result = await checkWebSearch(
|
|
155
|
+
{ provider: 'brave', apiKey: 'bad' },
|
|
156
|
+
(async () =>
|
|
157
|
+
new Response('{"error":"Invalid key"}', {
|
|
158
|
+
status: 401,
|
|
159
|
+
headers: { 'content-type': 'application/json' },
|
|
160
|
+
})) as typeof fetch,
|
|
161
|
+
);
|
|
162
|
+
expect(result.ok).toBe(false);
|
|
163
|
+
if (!result.ok) {
|
|
164
|
+
expect(result.error).toContain('401');
|
|
165
|
+
expect(result.error).toContain('Invalid key');
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe('web search request signals', () => {
|
|
171
|
+
test('两适配器 fetch 带 AbortSignal,外部 signal abort 可传导(Esc 可取消)', async () => {
|
|
172
|
+
const { runWebSearch } = await import('./web-search.js');
|
|
173
|
+
for (const provider of ['tavily', 'brave'] as const) {
|
|
174
|
+
let captured: AbortSignal | undefined;
|
|
175
|
+
const fetchImpl = (async (_input: any, init?: any) => {
|
|
176
|
+
captured = init?.signal;
|
|
177
|
+
return new Response(
|
|
178
|
+
JSON.stringify(
|
|
179
|
+
provider === 'tavily'
|
|
180
|
+
? { results: [{ title: 'T', url: 'u', content: 'c' }] }
|
|
181
|
+
: { web: { results: [{ title: 'T', url: 'u', description: 'c' }] } },
|
|
182
|
+
),
|
|
183
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
184
|
+
);
|
|
185
|
+
}) as typeof fetch;
|
|
186
|
+
const outer = new AbortController();
|
|
187
|
+
const pending = runWebSearch({ provider, apiKey: 'k' }, 'q', 5, fetchImpl, outer.signal);
|
|
188
|
+
expect(captured).toBeInstanceOf(AbortSignal);
|
|
189
|
+
expect(captured!.aborted).toBe(false);
|
|
190
|
+
outer.abort();
|
|
191
|
+
expect(captured!.aborted).toBe(true);
|
|
192
|
+
await pending;
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
});
|