@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,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,10 +1,11 @@
|
|
|
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,
|
|
8
|
+
getRouting,
|
|
8
9
|
setPreferredModel,
|
|
9
10
|
registerApiKey,
|
|
10
11
|
lookupApiKey,
|
|
@@ -16,7 +17,14 @@ import {
|
|
|
16
17
|
switchNote,
|
|
17
18
|
type ModelId,
|
|
18
19
|
} from '../provider/provider.js';
|
|
19
|
-
import { loadConfig } from '../config.js';
|
|
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';
|
|
20
28
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
21
29
|
import { createToolSession } from '../agent/tools/index.js';
|
|
22
30
|
import { getPermissionMode } from '../agent/permission.js';
|
|
@@ -30,7 +38,7 @@ import {
|
|
|
30
38
|
type SessionRecord,
|
|
31
39
|
} from '../sessions/store.js';
|
|
32
40
|
import { listProjectSessions, resolveResumeTarget, splitResumeArgs } from '../sessions/resume.js';
|
|
33
|
-
import { DEFAULT_KEEP_TURNS, compressSession, parseKeepCount, transcriptEntries, splitTurns } from '../sessions/compact.js';
|
|
41
|
+
import { DEFAULT_KEEP_TURNS, compressSession, parseKeepCount, shouldAutoCompact, transcriptEntries, splitTurns } from '../sessions/compact.js';
|
|
34
42
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
35
43
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
36
44
|
import {
|
|
@@ -39,6 +47,7 @@ import {
|
|
|
39
47
|
slashQuery,
|
|
40
48
|
} from './slash-completion.js';
|
|
41
49
|
import { resolveSubmitInput } from './submit.js';
|
|
50
|
+
import { submitSearchApiKey } from './search-setup.js';
|
|
42
51
|
import { historyRule } from './history-rule.js';
|
|
43
52
|
import { renderDiff } from './diff-render.js';
|
|
44
53
|
import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
@@ -60,7 +69,13 @@ type PromptPhase =
|
|
|
60
69
|
| 'model_apikey'
|
|
61
70
|
| 'model_check'
|
|
62
71
|
| 'permission'
|
|
63
|
-
| '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'];
|
|
64
79
|
|
|
65
80
|
interface REPLProps {
|
|
66
81
|
ctx: CommandContext;
|
|
@@ -99,6 +114,12 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
99
114
|
setPendingModel(id);
|
|
100
115
|
};
|
|
101
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);
|
|
102
123
|
// session_select picker: cursor over the project-scoped session snapshot.
|
|
103
124
|
const [sessionCursor, setSessionCursor] = useState(0);
|
|
104
125
|
// Model selection flow: vendor → model → key (reused if saved) → check.
|
|
@@ -141,6 +162,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
141
162
|
const conversationTitleRef = useRef('');
|
|
142
163
|
// Compaction digest of turns older than the kept window (from resume//compact).
|
|
143
164
|
const summaryRef = useRef<string | null>(null);
|
|
165
|
+
// Auto-compact breaker state: consecutive failures + warned-once flag.
|
|
166
|
+
const autoCompactFailuresRef = useRef(0);
|
|
167
|
+
const autoCompactWarnedRef = useRef(false);
|
|
144
168
|
const lastSessionsRef = useRef<string[]>([]);
|
|
145
169
|
// Snapshot for the /resume arrow-key picker (set together with the phase).
|
|
146
170
|
const sessionPickerRef = useRef<SessionRecord[]>([]);
|
|
@@ -227,6 +251,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
227
251
|
cancelled = true;
|
|
228
252
|
};
|
|
229
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
|
+
}, []);
|
|
230
264
|
const pendingPermissionRef = useRef<{
|
|
231
265
|
request: PermissionRequest;
|
|
232
266
|
resolve: (allow: boolean) => void;
|
|
@@ -240,20 +274,23 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
240
274
|
/** Shared resume flow: auto-compact over-long sessions, then load + render. */
|
|
241
275
|
const resumeWith = async (record: SessionRecord, inputLine: string, keepTurns = DEFAULT_KEEP_TURNS) => {
|
|
242
276
|
const { turns } = splitTurns(record.messages);
|
|
243
|
-
|
|
277
|
+
// Load first so the confirmation entry hosts the streamed digest.
|
|
278
|
+
applyResume(record, inputLine);
|
|
244
279
|
let oldTurns = 0;
|
|
245
|
-
if (turns.length > keepTurns) {
|
|
280
|
+
if (turns.length > keepTurns && process.env.TRANSCODE_MOCK !== '1') {
|
|
246
281
|
setBusyBoth(true);
|
|
247
282
|
try {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
283
|
+
const outcome = await runCompaction(record, keepTurns);
|
|
284
|
+
if (outcome.compressed) {
|
|
285
|
+
oldTurns = turns.length - keepTurns;
|
|
286
|
+
summaryRef.current = outcome.record.summary ?? null;
|
|
287
|
+
messagesRef.current = outcome.record.messages;
|
|
288
|
+
saveSession(outcome.record);
|
|
289
|
+
// Manual success heals the auto-compact breaker too.
|
|
290
|
+
autoCompactFailuresRef.current = 0;
|
|
291
|
+
autoCompactWarnedRef.current = false;
|
|
292
|
+
} else {
|
|
293
|
+
addHistory({ input: '', output: `⚠ 提炼失败(${outcome.error ?? '未知'}),已恢复完整对话。` });
|
|
257
294
|
}
|
|
258
295
|
} catch {
|
|
259
296
|
addHistory({ input: '', output: '⚠ 提炼失败,已恢复完整对话。' });
|
|
@@ -261,7 +298,6 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
261
298
|
setBusyBoth(false);
|
|
262
299
|
}
|
|
263
300
|
}
|
|
264
|
-
applyResume(finalRecord, inputLine);
|
|
265
301
|
// Restore in the original conversation form: each message becomes a
|
|
266
302
|
// history entry (rule-framed questions, full-length replies).
|
|
267
303
|
for (const entry of transcriptEntries(summaryRef.current, messagesRef.current, oldTurns || undefined)) {
|
|
@@ -280,6 +316,35 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
280
316
|
});
|
|
281
317
|
}, []);
|
|
282
318
|
|
|
319
|
+
/**
|
|
320
|
+
* One shared compaction run for /resume and /compact: fast-model routing
|
|
321
|
+
* (routing.compact → fallback current model) with the digest streamed
|
|
322
|
+
* live into the chat area.
|
|
323
|
+
*/
|
|
324
|
+
const runCompaction = async (
|
|
325
|
+
record: SessionRecord,
|
|
326
|
+
keepTurns: number,
|
|
327
|
+
): Promise<{ compressed: boolean; record: SessionRecord; error?: string }> => {
|
|
328
|
+
appendChatOutput('\n正在提炼前情提要…\n');
|
|
329
|
+
try {
|
|
330
|
+
const outcome = await compressSession(
|
|
331
|
+
record,
|
|
332
|
+
createModel(getRouting().compact ?? ctx.modelId).model,
|
|
333
|
+
keepTurns,
|
|
334
|
+
(delta) => appendChatOutput(delta),
|
|
335
|
+
);
|
|
336
|
+
appendChatOutput('\n\n');
|
|
337
|
+
return outcome;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
appendChatOutput('\n\n');
|
|
340
|
+
return {
|
|
341
|
+
compressed: false,
|
|
342
|
+
record,
|
|
343
|
+
error: error instanceof Error ? error.message : String(error),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
|
|
283
348
|
const askInTerminal = useCallback(
|
|
284
349
|
(request: PermissionRequest, signal: AbortSignal): Promise<boolean> => {
|
|
285
350
|
const mode = getPermissionMode();
|
|
@@ -301,11 +366,65 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
301
366
|
[],
|
|
302
367
|
);
|
|
303
368
|
|
|
369
|
+
// Auto-compact (Claude Code style proactive): threshold check before each
|
|
370
|
+
// turn, same runCompaction as /compact and resume. Circuit breaker stops
|
|
371
|
+
// after 3 consecutive failures; auto failures warn once per session.
|
|
372
|
+
const autoCompactIfNeeded = async (): Promise<void> => {
|
|
373
|
+
const cfg = normalizeAutoCompact(loadConfig().autoCompact);
|
|
374
|
+
if (!cfg.enabled || !conversationRef.current) return;
|
|
375
|
+
if (process.env.TRANSCODE_MOCK === '1') return;
|
|
376
|
+
if (autoCompactFailuresRef.current >= 3) return;
|
|
377
|
+
if (!shouldAutoCompact(messagesRef.current, cfg)) return;
|
|
378
|
+
try {
|
|
379
|
+
// Dedicated host entry before the question echo, so the digest neither
|
|
380
|
+
// mixes into the turn entry nor receives the turn's streamed reply.
|
|
381
|
+
addHistory({ input: '', output: '' });
|
|
382
|
+
const record = buildSessionRecord({
|
|
383
|
+
id: conversationRef.current.id,
|
|
384
|
+
title: conversationTitleRef.current,
|
|
385
|
+
createdAt: conversationRef.current.createdAt,
|
|
386
|
+
cwd: process.cwd(),
|
|
387
|
+
model: ctx.modelId,
|
|
388
|
+
messages: messagesRef.current,
|
|
389
|
+
summary: summaryRef.current,
|
|
390
|
+
});
|
|
391
|
+
const outcome = await runCompaction(record, cfg.keepTurns);
|
|
392
|
+
if (!outcome.compressed) {
|
|
393
|
+
// Without an error it is a no-op (≤ keepTurns turns — e.g. one giant
|
|
394
|
+
// turn over threshold): nothing compressible, skip without touching
|
|
395
|
+
// the breaker.
|
|
396
|
+
if (outcome.error) throw new Error(outcome.error);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
summaryRef.current = outcome.record.summary ?? null;
|
|
400
|
+
messagesRef.current = outcome.record.messages;
|
|
401
|
+
saveSession(outcome.record);
|
|
402
|
+
autoCompactFailuresRef.current = 0;
|
|
403
|
+
autoCompactWarnedRef.current = false;
|
|
404
|
+
for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
|
|
405
|
+
addHistory(entry);
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
autoCompactFailuresRef.current += 1;
|
|
409
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
410
|
+
if (autoCompactFailuresRef.current >= 3) {
|
|
411
|
+
addHistory({
|
|
412
|
+
input: '',
|
|
413
|
+
output: `⚠ 自动压缩已暂停(连续 3 次失败,最后原因:${reason})。可 /compact 手动压缩或检查 routing.compact 配置。`,
|
|
414
|
+
});
|
|
415
|
+
} else if (!autoCompactWarnedRef.current) {
|
|
416
|
+
autoCompactWarnedRef.current = true;
|
|
417
|
+
addHistory({ input: '', output: `⚠ 自动压缩失败(${reason}),本轮继续。` });
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
|
|
304
422
|
const runChat = useCallback(
|
|
305
423
|
async (text: string, display?: string, options?: { planMode?: boolean }) => {
|
|
306
424
|
setBusyBoth(true);
|
|
307
425
|
const controller = new AbortController();
|
|
308
426
|
abortRef.current = controller;
|
|
427
|
+
await autoCompactIfNeeded();
|
|
309
428
|
addHistory({ input: display ?? text, output: '' });
|
|
310
429
|
if (options?.planMode) {
|
|
311
430
|
appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
|
|
@@ -536,6 +655,25 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
536
655
|
[applyModelSwitch, addHistory, commitInput, dragFlush],
|
|
537
656
|
);
|
|
538
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
|
+
|
|
539
677
|
const handleApiKey = useCallback(
|
|
540
678
|
async (value: string) => {
|
|
541
679
|
// Key-first vendor setup: the key unlocks the live model list before
|
|
@@ -626,6 +764,14 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
626
764
|
return;
|
|
627
765
|
}
|
|
628
766
|
|
|
767
|
+
if (phase === 'search_apikey') {
|
|
768
|
+
await handleSearchApiKey(trimmed);
|
|
769
|
+
commitInput('');
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
if (phase === 'search_check') return;
|
|
774
|
+
|
|
629
775
|
if (phase === 'custom_baseurl') {
|
|
630
776
|
if (!/^https?:\/\//.test(trimmed)) {
|
|
631
777
|
addHistory({ input: trimmed, output: '地址需以 http:// 或 https:// 开头。' });
|
|
@@ -665,6 +811,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
665
811
|
return;
|
|
666
812
|
}
|
|
667
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
|
+
|
|
668
823
|
if (cmdName === 'new') {
|
|
669
824
|
conversationRef.current = null;
|
|
670
825
|
conversationTitleRef.current = '';
|
|
@@ -767,25 +922,28 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
767
922
|
messages: messagesRef.current,
|
|
768
923
|
summary: summaryRef.current,
|
|
769
924
|
});
|
|
925
|
+
// Host entry first so the streamed digest renders inside this
|
|
926
|
+
// command's own frame (same contract as the resume path).
|
|
927
|
+
addHistory({ input: trimmed, output: '' });
|
|
770
928
|
const outcome = process.env.TRANSCODE_MOCK === '1'
|
|
771
929
|
? { compressed: false as const, record, error: 'mock 模式无模型' }
|
|
772
|
-
: await
|
|
930
|
+
: await runCompaction(record, keepN);
|
|
773
931
|
if (outcome.compressed) {
|
|
774
932
|
summaryRef.current = outcome.record.summary ?? null;
|
|
775
933
|
messagesRef.current = outcome.record.messages;
|
|
776
934
|
saveSession(outcome.record);
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
});
|
|
935
|
+
// Manual success heals the auto-compact breaker too.
|
|
936
|
+
autoCompactFailuresRef.current = 0;
|
|
937
|
+
autoCompactWarnedRef.current = false;
|
|
938
|
+
appendChatOutput(`已压缩:旧 ${turns.length - keepN} 轮提炼为前情提要,保留最近 ${keepN} 轮。`);
|
|
781
939
|
for (const entry of transcriptEntries(summaryRef.current, messagesRef.current)) {
|
|
782
940
|
addHistory(entry);
|
|
783
941
|
}
|
|
784
942
|
} else {
|
|
785
|
-
|
|
943
|
+
appendChatOutput(`⚠ 压缩失败(${outcome.error ?? '未知'}),会话保持原样。`);
|
|
786
944
|
}
|
|
787
945
|
} catch {
|
|
788
|
-
|
|
946
|
+
appendChatOutput('⚠ 压缩失败,会话保持原样。');
|
|
789
947
|
} finally {
|
|
790
948
|
setBusyBoth(false);
|
|
791
949
|
}
|
|
@@ -819,7 +977,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
819
977
|
const cmd = findCommand(cmdName);
|
|
820
978
|
|
|
821
979
|
if (cmd) {
|
|
822
|
-
const result = await cmd
|
|
980
|
+
const result = await executeCommand(cmd, args, ctx);
|
|
823
981
|
|
|
824
982
|
if (result.exit) {
|
|
825
983
|
exit();
|
|
@@ -874,6 +1032,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
874
1032
|
return;
|
|
875
1033
|
}
|
|
876
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++;
|
|
877
1038
|
setPhase('idle');
|
|
878
1039
|
setVendor(null);
|
|
879
1040
|
commitInput('');
|
|
@@ -896,6 +1057,28 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
896
1057
|
return;
|
|
897
1058
|
}
|
|
898
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
|
+
|
|
899
1082
|
if (phase === 'model_select') {
|
|
900
1083
|
if (key.return) {
|
|
901
1084
|
const selected = models[modelCursor];
|
|
@@ -1124,6 +1307,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1124
1307
|
? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
|
|
1125
1308
|
: phase === 'vendor_apikey'
|
|
1126
1309
|
? 'apikey> '
|
|
1310
|
+
: phase === 'search_apikey'
|
|
1311
|
+
? 'search apikey> '
|
|
1127
1312
|
: phase === 'permission'
|
|
1128
1313
|
? 'allow?> '
|
|
1129
1314
|
: '> ';
|
|
@@ -1188,6 +1373,19 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1188
1373
|
</Box>
|
|
1189
1374
|
)}
|
|
1190
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
|
+
|
|
1191
1389
|
{phase === 'session_select' && (
|
|
1192
1390
|
<Box flexDirection="column" marginLeft={2}>
|
|
1193
1391
|
<Text color="gray" dimColor>恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)</Text>
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { submitSearchApiKey } from './search-setup.js';
|
|
3
|
+
import type { WebSearchCheck, WebSearchConfig } from '../provider/web-search.js';
|
|
4
|
+
|
|
5
|
+
interface Captured {
|
|
6
|
+
checked?: WebSearchConfig;
|
|
7
|
+
saved?: { provider: string; apiKey: string };
|
|
8
|
+
outcomes: string[];
|
|
9
|
+
notices: string[];
|
|
10
|
+
stale: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function makeDeps(overrides?: {
|
|
14
|
+
checkResult?: WebSearchCheck;
|
|
15
|
+
saveThrows?: boolean;
|
|
16
|
+
saved?: WebSearchConfig | null;
|
|
17
|
+
}) {
|
|
18
|
+
const cap: Captured = { outcomes: [], notices: [], stale: false };
|
|
19
|
+
return {
|
|
20
|
+
cap,
|
|
21
|
+
deps: {
|
|
22
|
+
savedConfig: () => overrides?.saved ?? null,
|
|
23
|
+
check: async (cfg: WebSearchConfig) => {
|
|
24
|
+
cap.checked = cfg;
|
|
25
|
+
return overrides?.checkResult ?? { ok: true, firstTitle: 'Alive' };
|
|
26
|
+
},
|
|
27
|
+
save: (provider: string, apiKey: string) => {
|
|
28
|
+
if (overrides?.saveThrows) throw new Error('EACCES: disk full');
|
|
29
|
+
cap.saved = { provider, apiKey };
|
|
30
|
+
},
|
|
31
|
+
notify: (output: string) => cap.notices.push(output),
|
|
32
|
+
onOutcome: (phase: 'idle' | 'search_apikey') => cap.outcomes.push(phase),
|
|
33
|
+
isStale: () => cap.stale,
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe('submitSearchApiKey', () => {
|
|
39
|
+
test('空输入 + 已存同商 key → 回车沿用 saved key 发起测试', async () => {
|
|
40
|
+
const { cap, deps } = makeDeps({ saved: { provider: 'tavily', apiKey: 'tvly-old' } });
|
|
41
|
+
await submitSearchApiKey('', 'tavily', deps);
|
|
42
|
+
expect(cap.checked).toEqual({ provider: 'tavily', apiKey: 'tvly-old' });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('空输入 + 无已存 → 错误提示,不发起测试,phase 不动', async () => {
|
|
46
|
+
const { cap, deps } = makeDeps();
|
|
47
|
+
await submitSearchApiKey(' ', 'brave', deps);
|
|
48
|
+
expect(cap.checked).toBeUndefined();
|
|
49
|
+
expect(cap.notices[0]).toContain('不能为空');
|
|
50
|
+
expect(cap.outcomes).toEqual([]);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('成功 → 写配置 + 成功提示 + 回 idle', async () => {
|
|
54
|
+
const { cap, deps } = makeDeps();
|
|
55
|
+
await submitSearchApiKey('tvly-new', 'tavily', deps);
|
|
56
|
+
expect(cap.saved).toEqual({ provider: 'tavily', apiKey: 'tvly-new' });
|
|
57
|
+
expect(cap.notices.join('\n')).toContain('已启用');
|
|
58
|
+
expect(cap.outcomes).toEqual(['idle']);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('测试失败 → 不写配置 + 错误提示 + 回 search_apikey 可重输', async () => {
|
|
62
|
+
const { cap, deps } = makeDeps({ checkResult: { ok: false, error: 'brave HTTP 401: bad key' } });
|
|
63
|
+
await submitSearchApiKey('k', 'brave', deps);
|
|
64
|
+
expect(cap.saved).toBeUndefined();
|
|
65
|
+
expect(cap.notices.join('\n')).toContain('401');
|
|
66
|
+
expect(cap.outcomes).toEqual(['search_apikey']);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('Esc 后代次失效(isStale)→ 不写配置、不动 phase、不发迟到的成功消息', async () => {
|
|
70
|
+
const { cap, deps } = makeDeps();
|
|
71
|
+
// Esc fires while the check is in flight: mark stale before completion.
|
|
72
|
+
deps.check = async (cfg: WebSearchConfig) => {
|
|
73
|
+
cap.checked = cfg;
|
|
74
|
+
cap.stale = true;
|
|
75
|
+
return { ok: true, firstTitle: 'late' };
|
|
76
|
+
};
|
|
77
|
+
await submitSearchApiKey('k', 'tavily', deps);
|
|
78
|
+
expect(cap.saved).toBeUndefined();
|
|
79
|
+
expect(cap.outcomes).toEqual([]);
|
|
80
|
+
expect(cap.notices.join('\n')).not.toContain('已启用');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('saveConfig 抛异常 → 错误提示 + 回 search_apikey,不向上抛', async () => {
|
|
84
|
+
const { cap, deps } = makeDeps({ saveThrows: true });
|
|
85
|
+
await submitSearchApiKey('k', 'tavily', deps);
|
|
86
|
+
expect(cap.notices.join('\n')).toContain('EACCES');
|
|
87
|
+
expect(cap.outcomes).toEqual(['search_apikey']);
|
|
88
|
+
});
|
|
89
|
+
});
|