@trans-ai/trans-code 0.9.0 → 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-22-user-memory.md +243 -0
- package/docs/superpowers/plans/2026-11-22-web-tools.md +192 -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.ts +2 -0
- package/src/provider/web-search.test.ts +195 -0
- package/src/provider/web-search.ts +143 -0
- package/src/screens/REPL.tsx +109 -3
- 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/version.ts +1 -1
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.ts
CHANGED
|
@@ -25,6 +25,8 @@ export interface TranscodeConfig {
|
|
|
25
25
|
autoUpdate?: boolean | AutoUpdateConfig;
|
|
26
26
|
/** Auto-compact on threshold: `false` disables, an object configures it. */
|
|
27
27
|
autoCompact?: boolean | AutoCompactConfig;
|
|
28
|
+
/** Web search vendor + key (user-configured; validated by normalizeWebSearchConfig). */
|
|
29
|
+
webSearch?: unknown;
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
/** Raw (on-disk) shape of the autoUpdate config block. */
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { loadConfig, saveConfig } from '../config.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Provider-agnostic web search: the user picks a search vendor and key in
|
|
5
|
+
* ~/.transcode.json (webSearch section); transcode only provides the
|
|
6
|
+
* adapters. Config is re-read on every use, so edits apply next turn.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface SearchHit {
|
|
10
|
+
title: string;
|
|
11
|
+
url: string;
|
|
12
|
+
snippet: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface WebSearchConfig {
|
|
16
|
+
provider: 'tavily' | 'brave';
|
|
17
|
+
apiKey: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const PROVIDERS: readonly WebSearchConfig['provider'][] = ['tavily', 'brave'];
|
|
21
|
+
|
|
22
|
+
/** null = not usable (absent OR malformed — distinguish with webSearchConfigWarning). */
|
|
23
|
+
export function normalizeWebSearchConfig(raw: unknown): WebSearchConfig | null {
|
|
24
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
25
|
+
const obj = raw as Record<string, unknown>;
|
|
26
|
+
const provider = typeof obj.provider === 'string' ? obj.provider.trim().toLowerCase() : '';
|
|
27
|
+
const apiKey = typeof obj.apiKey === 'string' ? obj.apiKey.trim() : '';
|
|
28
|
+
if (!(PROVIDERS as readonly string[]).includes(provider) || !apiKey) return null;
|
|
29
|
+
return { provider: provider as WebSearchConfig['provider'], apiKey };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Present-but-broken config gets one warning line; a simply-absent section stays silent. */
|
|
33
|
+
export function webSearchConfigWarning(raw: unknown): string | null {
|
|
34
|
+
if (raw === undefined || raw === null) return null;
|
|
35
|
+
if (normalizeWebSearchConfig(raw)) return null;
|
|
36
|
+
const provider = typeof (raw as Record<string, unknown>)?.provider === 'string'
|
|
37
|
+
? (raw as Record<string, unknown>).provider
|
|
38
|
+
: '(missing)';
|
|
39
|
+
return (
|
|
40
|
+
`⚠ webSearch 配置无效(provider:${String(provider)};需 provider=tavily|brave 且 apiKey 非空),` +
|
|
41
|
+
'web_search 已隐藏。运行 /search 重新配置,或手改 ~/.transcode.json'
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function safeText(res: Response): Promise<string> {
|
|
46
|
+
try {
|
|
47
|
+
return (await res.text()).slice(0, 500);
|
|
48
|
+
} catch {
|
|
49
|
+
return '';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Search requests get a 15s ceiling like web_fetch; an outer signal (Esc)
|
|
54
|
+
* can cut them short sooner via AbortSignal.any. */
|
|
55
|
+
const SEARCH_TIMEOUT_MS = 15_000;
|
|
56
|
+
|
|
57
|
+
function searchSignal(outer?: AbortSignal): AbortSignal {
|
|
58
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
59
|
+
return outer ? AbortSignal.any([timeout, outer]) : timeout;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function tavilySearch(
|
|
63
|
+
apiKey: string,
|
|
64
|
+
query: string,
|
|
65
|
+
maxResults: number,
|
|
66
|
+
fetchImpl: typeof fetch,
|
|
67
|
+
signal?: AbortSignal,
|
|
68
|
+
): Promise<SearchHit[]> {
|
|
69
|
+
const res = await fetchImpl('https://api.tavily.com/search', {
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers: { 'content-type': 'application/json' },
|
|
72
|
+
body: JSON.stringify({ api_key: apiKey, query, max_results: maxResults }),
|
|
73
|
+
signal: searchSignal(signal),
|
|
74
|
+
});
|
|
75
|
+
if (!res.ok) throw new Error(`tavily HTTP ${res.status}: ${await safeText(res)}`);
|
|
76
|
+
const data = (await res.json()) as {
|
|
77
|
+
results?: Array<{ title?: string; url?: string; content?: string }>;
|
|
78
|
+
};
|
|
79
|
+
return (data.results ?? []).map((hit) => ({
|
|
80
|
+
title: hit.title ?? '',
|
|
81
|
+
url: hit.url ?? '',
|
|
82
|
+
snippet: hit.content ?? '',
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function braveSearch(
|
|
87
|
+
apiKey: string,
|
|
88
|
+
query: string,
|
|
89
|
+
maxResults: number,
|
|
90
|
+
fetchImpl: typeof fetch,
|
|
91
|
+
signal?: AbortSignal,
|
|
92
|
+
): Promise<SearchHit[]> {
|
|
93
|
+
const qs = new URLSearchParams({ q: query, count: String(maxResults) }).toString();
|
|
94
|
+
const res = await fetchImpl(`https://api.search.brave.com/res/v1/web/search?${qs}`, {
|
|
95
|
+
headers: { accept: 'application/json', 'x-subscription-token': apiKey },
|
|
96
|
+
signal: searchSignal(signal),
|
|
97
|
+
});
|
|
98
|
+
if (!res.ok) throw new Error(`brave HTTP ${res.status}: ${await safeText(res)}`);
|
|
99
|
+
const data = (await res.json()) as {
|
|
100
|
+
web?: { results?: Array<{ title?: string; url?: string; description?: string }> };
|
|
101
|
+
};
|
|
102
|
+
return (data.web?.results ?? []).map((hit) => ({
|
|
103
|
+
title: hit.title ?? '',
|
|
104
|
+
url: hit.url ?? '',
|
|
105
|
+
snippet: hit.description ?? '',
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function runWebSearch(
|
|
110
|
+
cfg: WebSearchConfig,
|
|
111
|
+
query: string,
|
|
112
|
+
maxResults = 5,
|
|
113
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
114
|
+
signal?: AbortSignal,
|
|
115
|
+
): Promise<SearchHit[]> {
|
|
116
|
+
if (cfg.provider === 'tavily') {
|
|
117
|
+
return tavilySearch(cfg.apiKey, query, maxResults, fetchImpl, signal);
|
|
118
|
+
}
|
|
119
|
+
if (cfg.provider === 'brave') {
|
|
120
|
+
return braveSearch(cfg.apiKey, query, maxResults, fetchImpl, signal);
|
|
121
|
+
}
|
|
122
|
+
throw new Error(`unknown search provider: ${String(cfg.provider)}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Persist provider+key into the config's webSearch section, preserving other keys. */
|
|
126
|
+
export function saveWebSearchConfig(provider: WebSearchConfig['provider'], apiKey: string): void {
|
|
127
|
+
saveConfig({ ...loadConfig(), webSearch: { provider, apiKey } });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type WebSearchCheck = { ok: true; firstTitle: string } | { ok: false; error: string };
|
|
131
|
+
|
|
132
|
+
/** Live connectivity test for the /search flow: one real query, never throws. */
|
|
133
|
+
export async function checkWebSearch(
|
|
134
|
+
cfg: WebSearchConfig,
|
|
135
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
136
|
+
): Promise<WebSearchCheck> {
|
|
137
|
+
try {
|
|
138
|
+
const hits = await runWebSearch(cfg, 'transcode connectivity check', 1, fetchImpl);
|
|
139
|
+
return { ok: true, firstTitle: hits[0]?.title ?? '(empty result set — key works)' };
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
142
|
+
}
|
|
143
|
+
}
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Box, Text, useInput, useApp, useStdout } from 'ink';
|
|
2
2
|
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { findCommand, getCommands, type CommandContext } from '../commands.js';
|
|
4
|
+
import { executeCommand, findCommand, getCommands, type CommandContext } from '../commands.js';
|
|
5
5
|
import {
|
|
6
6
|
getAvailableModels,
|
|
7
7
|
createModel,
|
|
@@ -18,6 +18,13 @@ import {
|
|
|
18
18
|
type ModelId,
|
|
19
19
|
} from '../provider/provider.js';
|
|
20
20
|
import { loadConfig, normalizeAutoCompact } from '../config.js';
|
|
21
|
+
import {
|
|
22
|
+
checkWebSearch,
|
|
23
|
+
normalizeWebSearchConfig,
|
|
24
|
+
saveWebSearchConfig,
|
|
25
|
+
webSearchConfigWarning,
|
|
26
|
+
type WebSearchConfig,
|
|
27
|
+
} from '../provider/web-search.js';
|
|
21
28
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
22
29
|
import { createToolSession } from '../agent/tools/index.js';
|
|
23
30
|
import { getPermissionMode } from '../agent/permission.js';
|
|
@@ -40,6 +47,7 @@ import {
|
|
|
40
47
|
slashQuery,
|
|
41
48
|
} from './slash-completion.js';
|
|
42
49
|
import { resolveSubmitInput } from './submit.js';
|
|
50
|
+
import { submitSearchApiKey } from './search-setup.js';
|
|
43
51
|
import { historyRule } from './history-rule.js';
|
|
44
52
|
import { renderDiff } from './diff-render.js';
|
|
45
53
|
import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
@@ -61,7 +69,13 @@ type PromptPhase =
|
|
|
61
69
|
| 'model_apikey'
|
|
62
70
|
| 'model_check'
|
|
63
71
|
| 'permission'
|
|
64
|
-
| 'session_select'
|
|
72
|
+
| 'session_select'
|
|
73
|
+
| 'search_provider'
|
|
74
|
+
| 'search_apikey'
|
|
75
|
+
| 'search_check';
|
|
76
|
+
|
|
77
|
+
/** Providers offered by the /search setup flow (mirrors normalizeWebSearchConfig). */
|
|
78
|
+
const SEARCH_PROVIDERS: WebSearchConfig['provider'][] = ['tavily', 'brave'];
|
|
65
79
|
|
|
66
80
|
interface REPLProps {
|
|
67
81
|
ctx: CommandContext;
|
|
@@ -100,6 +114,12 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
100
114
|
setPendingModel(id);
|
|
101
115
|
};
|
|
102
116
|
const [modelCursor, setModelCursor] = useState(0);
|
|
117
|
+
// /search setup flow: cursor over SEARCH_PROVIDERS, ref carries the pick.
|
|
118
|
+
const [searchCursor, setSearchCursor] = useState(0);
|
|
119
|
+
const searchProviderRef = useRef<WebSearchConfig['provider']>('tavily');
|
|
120
|
+
// Generation guard: bumping invalidates an in-flight connectivity check,
|
|
121
|
+
// so a cancelled /search never writes config or yanks the phase back.
|
|
122
|
+
const searchRunIdRef = useRef(0);
|
|
103
123
|
// session_select picker: cursor over the project-scoped session snapshot.
|
|
104
124
|
const [sessionCursor, setSessionCursor] = useState(0);
|
|
105
125
|
// Model selection flow: vendor → model → key (reused if saved) → check.
|
|
@@ -231,6 +251,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
231
251
|
cancelled = true;
|
|
232
252
|
};
|
|
233
253
|
}, [updateNotice, addHistory, dragFlush]);
|
|
254
|
+
// Web search misconfiguration: one line on startup; a simply-absent
|
|
255
|
+
// section stays silent (never nags unconfigured users).
|
|
256
|
+
useEffect(() => {
|
|
257
|
+
const warning = webSearchConfigWarning(loadConfig().webSearch);
|
|
258
|
+
if (warning) {
|
|
259
|
+
addHistory({ input: '', output: warning });
|
|
260
|
+
dragFlush();
|
|
261
|
+
}
|
|
262
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
263
|
+
}, []);
|
|
234
264
|
const pendingPermissionRef = useRef<{
|
|
235
265
|
request: PermissionRequest;
|
|
236
266
|
resolve: (allow: boolean) => void;
|
|
@@ -625,6 +655,25 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
625
655
|
[applyModelSwitch, addHistory, commitInput, dragFlush],
|
|
626
656
|
);
|
|
627
657
|
|
|
658
|
+
// /search key step: orchestration lives in search-setup.ts (tested there).
|
|
659
|
+
const handleSearchApiKey = useCallback(
|
|
660
|
+
async (value: string) => {
|
|
661
|
+
const runId = ++searchRunIdRef.current;
|
|
662
|
+
const provider = searchProviderRef.current;
|
|
663
|
+
setPhase('search_check');
|
|
664
|
+
await submitSearchApiKey(value, provider, {
|
|
665
|
+
savedConfig: () => normalizeWebSearchConfig(loadConfig().webSearch),
|
|
666
|
+
check: (cfg) => checkWebSearch(cfg),
|
|
667
|
+
save: saveWebSearchConfig,
|
|
668
|
+
notify: (output) => addHistory({ input: '••••••••', output }),
|
|
669
|
+
onOutcome: (phase) => setPhase(phase),
|
|
670
|
+
isStale: () => searchRunIdRef.current !== runId,
|
|
671
|
+
});
|
|
672
|
+
dragFlush();
|
|
673
|
+
},
|
|
674
|
+
[addHistory, dragFlush],
|
|
675
|
+
);
|
|
676
|
+
|
|
628
677
|
const handleApiKey = useCallback(
|
|
629
678
|
async (value: string) => {
|
|
630
679
|
// Key-first vendor setup: the key unlocks the live model list before
|
|
@@ -715,6 +764,14 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
715
764
|
return;
|
|
716
765
|
}
|
|
717
766
|
|
|
767
|
+
if (phase === 'search_apikey') {
|
|
768
|
+
await handleSearchApiKey(trimmed);
|
|
769
|
+
commitInput('');
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
if (phase === 'search_check') return;
|
|
774
|
+
|
|
718
775
|
if (phase === 'custom_baseurl') {
|
|
719
776
|
if (!/^https?:\/\//.test(trimmed)) {
|
|
720
777
|
addHistory({ input: trimmed, output: '地址需以 http:// 或 https:// 开头。' });
|
|
@@ -754,6 +811,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
754
811
|
return;
|
|
755
812
|
}
|
|
756
813
|
|
|
814
|
+
if (cmdName === 'search') {
|
|
815
|
+
addHistory({ input: trimmed, output: 'Select a search provider (↑↓ to navigate, Enter to select):' });
|
|
816
|
+
setSearchCursor(0);
|
|
817
|
+
setPhase('search_provider');
|
|
818
|
+
commitInput('');
|
|
819
|
+
dragFlush();
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
|
|
757
823
|
if (cmdName === 'new') {
|
|
758
824
|
conversationRef.current = null;
|
|
759
825
|
conversationTitleRef.current = '';
|
|
@@ -911,7 +977,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
911
977
|
const cmd = findCommand(cmdName);
|
|
912
978
|
|
|
913
979
|
if (cmd) {
|
|
914
|
-
const result = await cmd
|
|
980
|
+
const result = await executeCommand(cmd, args, ctx);
|
|
915
981
|
|
|
916
982
|
if (result.exit) {
|
|
917
983
|
exit();
|
|
@@ -966,6 +1032,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
966
1032
|
return;
|
|
967
1033
|
}
|
|
968
1034
|
if (phase !== 'idle') {
|
|
1035
|
+
// Invalidate any in-flight /search connectivity check: its late
|
|
1036
|
+
// result must not write config or pull the user back into the flow.
|
|
1037
|
+
searchRunIdRef.current++;
|
|
969
1038
|
setPhase('idle');
|
|
970
1039
|
setVendor(null);
|
|
971
1040
|
commitInput('');
|
|
@@ -988,6 +1057,28 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
988
1057
|
return;
|
|
989
1058
|
}
|
|
990
1059
|
|
|
1060
|
+
if (phase === 'search_provider') {
|
|
1061
|
+
if (key.upArrow) {
|
|
1062
|
+
setSearchCursor((c) => (c - 1 + SEARCH_PROVIDERS.length) % SEARCH_PROVIDERS.length);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
if (key.downArrow) {
|
|
1066
|
+
setSearchCursor((c) => (c + 1) % SEARCH_PROVIDERS.length);
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
if (key.return) {
|
|
1070
|
+
const provider = SEARCH_PROVIDERS[searchCursor];
|
|
1071
|
+
searchProviderRef.current = provider;
|
|
1072
|
+
const saved = normalizeWebSearchConfig(loadConfig().webSearch);
|
|
1073
|
+
const hint = saved?.provider === provider ? '(Enter 沿用已存 key)' : '';
|
|
1074
|
+
addHistory({ input: '', output: `搜索商:${provider}。输入 API key ${hint}:` });
|
|
1075
|
+
setPhase('search_apikey');
|
|
1076
|
+
commitInput('');
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
991
1082
|
if (phase === 'model_select') {
|
|
992
1083
|
if (key.return) {
|
|
993
1084
|
const selected = models[modelCursor];
|
|
@@ -1216,6 +1307,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1216
1307
|
? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
|
|
1217
1308
|
: phase === 'vendor_apikey'
|
|
1218
1309
|
? 'apikey> '
|
|
1310
|
+
: phase === 'search_apikey'
|
|
1311
|
+
? 'search apikey> '
|
|
1219
1312
|
: phase === 'permission'
|
|
1220
1313
|
? 'allow?> '
|
|
1221
1314
|
: '> ';
|
|
@@ -1280,6 +1373,19 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1280
1373
|
</Box>
|
|
1281
1374
|
)}
|
|
1282
1375
|
|
|
1376
|
+
{phase === 'search_provider' && (
|
|
1377
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
1378
|
+
{SEARCH_PROVIDERS.map((p, i) => (
|
|
1379
|
+
<Box key={p}>
|
|
1380
|
+
<Text color={i === searchCursor ? 'cyan' : undefined}>
|
|
1381
|
+
{i === searchCursor ? '❯ ' : ' '}{p}
|
|
1382
|
+
</Text>
|
|
1383
|
+
</Box>
|
|
1384
|
+
))}
|
|
1385
|
+
<Text color="gray" dimColor>↑↓ 选择搜索商 · Enter 下一步 · Esc 取消</Text>
|
|
1386
|
+
</Box>
|
|
1387
|
+
)}
|
|
1388
|
+
|
|
1283
1389
|
{phase === 'session_select' && (
|
|
1284
1390
|
<Box flexDirection="column" marginLeft={2}>
|
|
1285
1391
|
<Text color="gray" dimColor>恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)</Text>
|