@trans-ai/trans-code 0.9.0 → 0.10.1

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.
@@ -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.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
+ }