@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
package/README.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
多模型 AI 编码 Agent CLI。当前 MVP 的目标是:**作为本地 Agent 被 transonce、multica 等客户端通过 ACP 调用**。
|
|
4
4
|
|
|
5
|
-
- 终端侧:Ink REPL(命令:`help` / `models` / `mode` / `route` / `init` / `clear` / `exit`)
|
|
5
|
+
- 终端侧:Ink REPL(命令:`help` / `models` / `mode` / `route` / `init` / `memory` / `remember` / `forget` / `search` / `clear` / `exit`)
|
|
6
6
|
- Agent 侧:`transcode acp` 启动 ACP v1 stdio 服务,供 transonce、multica 等客户端调用
|
|
7
7
|
- 模型侧:档案(Profile)+ 角色(Role)路由——一个模型 ID 对应一个地址,不同任务可派发不同模型(含子 Agent)
|
|
8
|
-
- 工具侧:`read_file` / `write_file` / `edit_file` / `glob` / `grep` / `bash` / `todo_write` / `ask_model` / `dispatch_agent`
|
|
8
|
+
- 工具侧:`read_file` / `write_file` / `edit_file` / `glob` / `grep` / `bash` / `todo_write` / `memory_save` / `web_fetch` / `web_search` / `ask_model` / `dispatch_agent`
|
|
9
9
|
|
|
10
10
|
## 环境要求
|
|
11
11
|
|
|
@@ -231,6 +231,24 @@ ACP 默认权限模式是 `ask`:写文件、改文件、执行命令前会向
|
|
|
231
231
|
|
|
232
232
|
每次 turn 按优先级加载 workspace 下的 `TRANS.md`、`AGENTS.md`、`CLAUDE.md`、`TRANSCODE.md`、`.transcode/AGENTS.md`(存在时)注入系统提示。REPL 里 `/init` 可让 Agent 自行探索仓库并生成 `TRANS.md`(项目背景 / 命令 / 架构 / 约定)。
|
|
233
233
|
|
|
234
|
+
## 用户记忆
|
|
235
|
+
|
|
236
|
+
跨会话、跨项目记住你的偏好与对 Agent 的纠正,存放在 `~/.transcode/`:
|
|
237
|
+
|
|
238
|
+
- **全局指令** `~/.transcode/TRANS.md`——手写一次、所有项目生效("所有项目用 bun"、"commit 用中文")
|
|
239
|
+
- **自动记忆** `~/.transcode/memory/`——一条事实一个文件,`MEMORY.md` 是索引。Agent 有 `memory_save` / `memory_delete` 工具:你纠正它的行为或表达持久偏好时,它会自己记下来;也可以直接 `/remember <text>` 手动存、`/forget <name>` 删、`/memory` 查看
|
|
240
|
+
|
|
241
|
+
注入预算 12k 字符,超预算整条省略最低优先级(user > feedback > project > reference)并在提示中注明。记忆目录文件是事实源,`MEMORY.md` 删除后会自动重建。测试与隔离用环境变量 `TRANSCODE_USER_DIR` 覆盖根目录。
|
|
242
|
+
|
|
243
|
+
## 联网工具
|
|
244
|
+
|
|
245
|
+
- **`web_fetch`**:零配置开箱即用。抓 URL 返回可读文本(HTML 剥离为文本 + 标题,text/json 原样,二进制给类型/大小提示);支持 gbk/gb2312 页面解码,512KB / 20k 字符上限,15s 超时
|
|
246
|
+
- **`web_search`**:搜索商由你配置,transcode 只提供实现(厂商无关,GLM/DeepSeek 路由下同样可用)。支持 Tavily 与 Brave,配置两条路:
|
|
247
|
+
- **`/search` 交互**:选搜索商 → 输 key → 发真实测试查询验证 → 自动写入配置
|
|
248
|
+
- **手改 JSON**:`~/.transcode.json` 的 `webSearch: { provider: "tavily" | "brave", apiKey: "…" }`,改完下一轮生效
|
|
249
|
+
|
|
250
|
+
未配置时 `web_search` 对模型不可见(不浪费轮次);配置存在但无效会在启动时提示一行。请求使用诚实 UA(`Mozilla/5.0 (compatible; transcode/<version>)`),部分强防护站点可能 403。全局安装(bun 运行时)的联网请求自动识别 `HTTP(S)_PROXY`;自建 Node dist 路径暂不支持代理。
|
|
251
|
+
|
|
234
252
|
## ACP 协议
|
|
235
253
|
|
|
236
254
|
支持的方法、事件格式、权限流程和调试方式见 [docs/ACP.md](docs/ACP.md)。
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# 自动压缩 Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** 每轮提交前估算上下文,超阈值自动压缩(与 /compact、resume 同一 `runCompaction`),带配置与连败熔断。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 纯逻辑(估算 + 配置归一)落 compact.ts/config.ts 走 TDD;REPL 在 handleSubmit 进入 agent loop 前接检查点,复用宿主条目流式显示;基于已审查的 `feat/compact-speed` 分支续作。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript、bun:test。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-21-auto-compact-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 阈值默认 `thresholdChars = 200_000`,估算 `estimateTokens = Σ contentText(chars)/4`
|
|
16
|
+
- 配置 `autoCompact?: { enabled?: boolean; thresholdChars?: number }`,默认 **enabled = true**;坏类型/空值全量回落默认(仿 normalizeAutoCompact 与 normalizeAutoUpdate 同风格)
|
|
17
|
+
- 熔断:连续失败 **3** 次停止自动压缩,成功复位;失败提示仅每会话首次显示
|
|
18
|
+
- 压缩参数 keepTurns = `DEFAULT_KEEP_TURNS`;三入口共用 `runCompaction`
|
|
19
|
+
- 跳过:无进行中会话、`TRANSCODE_MOCK=1`、busy
|
|
20
|
+
|
|
21
|
+
## Review Focus
|
|
22
|
+
|
|
23
|
+
- 首轮(无 conversationRef)与未达阈值不触发(接线)
|
|
24
|
+
- 恰好等于阈值触发(估算 `>=` 边界,Task 1 测试)
|
|
25
|
+
- 连败 3 次停、成功复位(接线,ref 语义)
|
|
26
|
+
- 坏配置(字符串 thresholdChars、null、数组)回落默认不崩(Task 1 测试)
|
|
27
|
+
- 压缩后本轮 loop 使用已压缩 messagesRef 且提要注入生效(复用现有注入点,接线核对)
|
|
28
|
+
- autoCompact 与用户提问回显的条目顺序不串(接线)
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
### Task 1: 估算 + 配置归一(纯逻辑)
|
|
33
|
+
|
|
34
|
+
**Files:**
|
|
35
|
+
- Modify: `src/sessions/compact.ts`、`src/sessions/compact.test.ts`、`src/config.ts`、`src/config.test.ts`
|
|
36
|
+
|
|
37
|
+
**Interfaces:**
|
|
38
|
+
- Produces:
|
|
39
|
+
- `estimateTokens(messages: BaseMessage[]): number`(compact.ts;contentText 求和 / 4,向下取整)
|
|
40
|
+
- config.ts:`interface AutoCompactConfig { enabled?: boolean; thresholdChars?: number }`、`interface NormalizedAutoCompact { enabled: boolean; thresholdChars: number }`、`normalizeAutoCompact(raw: unknown): NormalizedAutoCompact`、`TranscodeConfig.autoCompact?: boolean | AutoCompactConfig`(boolean 直通,与 autoUpdate 同款 raw 形状)
|
|
41
|
+
|
|
42
|
+
- [ ] **Step 1: 失败测试**
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// compact.test.ts
|
|
46
|
+
describe('estimateTokens', () => {
|
|
47
|
+
test('sums content chars / 4, floors; non-string content via JSON; empty → 0', () => {
|
|
48
|
+
expect(estimateTokens([])).toBe(0);
|
|
49
|
+
expect(estimateTokens([new HumanMessage('a'.repeat(40))])).toBe(10);
|
|
50
|
+
expect(estimateTokens([new HumanMessage('x'.repeat(10)), new AIMessage('y'.repeat(30))])).toBe(10);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
// config.test.ts
|
|
54
|
+
describe('normalizeAutoCompact', () => {
|
|
55
|
+
test('undefined → enabled default 200_000; false → disabled; valid override kept', () => {
|
|
56
|
+
expect(normalizeAutoCompact(undefined)).toEqual({ enabled: true, thresholdChars: 200_000 });
|
|
57
|
+
expect(normalizeAutoCompact(false)).toEqual({ enabled: false, thresholdChars: 200_000 });
|
|
58
|
+
expect(normalizeAutoCompact({ thresholdChars: 50_000 })).toEqual({ enabled: true, thresholdChars: 50_000 });
|
|
59
|
+
});
|
|
60
|
+
test('garbage (string/null/array/negative) falls back to defaults', () => {
|
|
61
|
+
expect(normalizeAutoCompact('yes')).toEqual({ enabled: true, thresholdChars: 200_000 });
|
|
62
|
+
expect(normalizeAutoCompact([1])).toEqual({ enabled: true, thresholdChars: 200_000 });
|
|
63
|
+
expect(normalizeAutoCompact({ thresholdChars: -5 })).toEqual({ enabled: true, thresholdChars: 200_000 });
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- [ ] **Step 2: 确认失败**(导出不存在)
|
|
69
|
+
- [ ] **Step 3: 实现** — `estimateTokens` 用已有 `contentText`;`normalizeAutoCompact` 仿 `normalizeAutoUpdate` 分支
|
|
70
|
+
- [ ] **Step 4: 确认通过**
|
|
71
|
+
- [ ] **Step 5: Commit** — `feat: token estimation and autoCompact config normalization`
|
|
72
|
+
|
|
73
|
+
### Task 2: REPL 检查点接线
|
|
74
|
+
|
|
75
|
+
**Files:**
|
|
76
|
+
- Modify: `src/screens/REPL.tsx`(handleSubmit 进入 agent loop 前;import estimateTokens/normalizeAutoCompact/loadConfig 已有)
|
|
77
|
+
|
|
78
|
+
**Interfaces:**
|
|
79
|
+
- Consumes: Task 1 全部;`runCompaction`、`buildSessionRecord`、`transcriptEntries`、`DEFAULT_KEEP_TURNS`、`saveSession`
|
|
80
|
+
|
|
81
|
+
- [ ] **Step 1: 状态** — `const autoCompactFailuresRef = useRef(0);`、`const autoCompactWarnedRef = useRef(false);`
|
|
82
|
+
- [ ] **Step 2: 检查点**(handleSubmit 内、构建 provider/进入 try 之前):条件 `normalizeAutoCompact(loadConfig().autoCompact).enabled && conversationRef.current && process.env.TRANSCODE_MOCK !== '1' && autoCompactFailuresRef.current < 3 && estimateTokens(messagesRef.current) >= cfg.thresholdChars` 满足时:`setBusyBoth(true)` → 空宿主条目 → `runCompaction(buildSessionRecord({...}), DEFAULT_KEEP_TURNS)`;成功 → 回写 refs + `saveSession` + 失败计数清零 + `transcriptEntries` 渲染;失败/异常 → 计数 +1,首次时 `⚠ 自动压缩失败(原因),本轮继续;连续 3 次将暂停自动压缩`,达 3 次时提示「自动压缩已暂停」;finally `setBusyBoth(false)`
|
|
83
|
+
- [ ] **Step 3: 全量验证** — `bun test` + `npm run typecheck` + `npm run build:repl`
|
|
84
|
+
- [ ] **Step 4: Commit** — `feat: proactive auto-compact with threshold config and failure circuit breaker`
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# 压缩提速(流式 + compact 路由 + 硬上限)Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** 压缩调用改为流式并实时显示、可路由快速模型、输出字符硬上限,消除感知与实际慢。
|
|
6
|
+
|
|
7
|
+
**Architecture:** `CompactModel` 换成 stream 接口,`compressSession` 增 `onDelta` 回调与 `COMPACT_MAX_SUMMARY_CHARS` 截断;REPL 两入口接 `appendChatOutput` 流式显示,模型经 `getRouting()['compact'] ?? ctx.modelId` 选择。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript、LangChain(`model.stream()`)、bun:test。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-21-compact-speed-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- `COMPACT_MAX_SUMMARY_CHARS = 1200`,累积超限即停止消费流并 `slice` 到上限
|
|
16
|
+
- `CompactModel = { stream(input: string): AsyncIterable<{ content: unknown }> }`;chunk 文本取 `typeof content === 'string' ? content : ''`
|
|
17
|
+
- 模型选择:`createModel(getRouting().compact ?? ctx.modelId)`;未配置 routing 行为与现状一致
|
|
18
|
+
- 失败回退(流中抛错/空摘要)、滚动合并、≤keepTurns no-op 语义不变;`TRANSCODE_MOCK` 跳过压缩不变
|
|
19
|
+
|
|
20
|
+
## Review Focus
|
|
21
|
+
|
|
22
|
+
- 流中第 2 块抛错 → 原会话完整回退、无文件写入(Task 1 测试)
|
|
23
|
+
- 显示与保存一致:onDelta 逐块文本拼接 === 最终 summary(Task 1 测试)
|
|
24
|
+
- 超限:5000 字符流 → summary ≤ 1200 且提前停止消费(Task 1 测试 + 生成器消费计数)
|
|
25
|
+
- 未配 `routing.compact` → 用当前模型(接线:?? 右侧默认)
|
|
26
|
+
- 多块 content 非字符串(如数组块)不崩、按空串跳过(Task 1 测试)
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
### Task 1: 流式压缩核心
|
|
31
|
+
|
|
32
|
+
**Files:**
|
|
33
|
+
- Modify: `src/sessions/compact.ts`、`src/sessions/compact.test.ts`
|
|
34
|
+
|
|
35
|
+
**Interfaces:**
|
|
36
|
+
- Produces:
|
|
37
|
+
- `export const COMPACT_MAX_SUMMARY_CHARS = 1200`
|
|
38
|
+
- `export interface CompactModel { stream(input: string): AsyncIterable<{ content: unknown }> }`
|
|
39
|
+
- `compressSession(record, model, keepTurns = DEFAULT_KEEP_TURNS, onDelta?: (delta: string) => void)`(返回形不变)
|
|
40
|
+
|
|
41
|
+
- [ ] **Step 1: 失败测试** — mock 改 async generator(`streamModel(chunks: string[], opts?: {throwAt?: number; trackPulled?: number[]}): CompactModel & { prompts: string[] }`),新增/改写:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
test('streams chunks into the summary and forwards each delta', async () => {
|
|
45
|
+
const deltas: string[] = [];
|
|
46
|
+
const { record } = await compressSession(recordWith(3), streamModel(['前情', '提要']), 1, d => deltas.push(d));
|
|
47
|
+
expect(record.summary).toBe('前情提要');
|
|
48
|
+
expect(deltas).toEqual(['前情', '提要']);
|
|
49
|
+
});
|
|
50
|
+
test('caps summary at COMPACT_MAX_SUMMARY_CHARS and stops consuming early', async () => {
|
|
51
|
+
const pulled: number[] = [];
|
|
52
|
+
const model = streamModel(['x'.repeat(1000), 'y'.repeat(1000), 'z'.repeat(1000)], { trackPulled: pulled });
|
|
53
|
+
const { record } = await compressSession(recordWith(3), model, 1);
|
|
54
|
+
expect(record.summary!.length).toBeLessThanOrEqual(COMPACT_MAX_SUMMARY_CHARS);
|
|
55
|
+
expect(pulled.length).toBe(2); // 第三块未被消费
|
|
56
|
+
});
|
|
57
|
+
test('mid-stream error falls back with error set', async () => {
|
|
58
|
+
const { compressed, record, error } = await compressSession(recordWith(3), streamModel(['前情'], { throwAt: 2 }), 1);
|
|
59
|
+
expect(compressed).toBe(false); expect(error).toBeDefined(); expect(record).toBeDefined();
|
|
60
|
+
});
|
|
61
|
+
test('non-string chunk content is skipped', async () => {
|
|
62
|
+
const model = { stream: async function* () { yield { content: '前情' }; yield { content: [{ text: 'x' }] }; yield { content: '提要' }; } };
|
|
63
|
+
const { record } = await compressSession(recordWith(3), model as never, 1);
|
|
64
|
+
expect(record.summary).toBe('前情提要');
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
(既有 8 个压缩用例换用 `streamModel(['提要内容'])` 等形式,断言不变)
|
|
68
|
+
|
|
69
|
+
- [ ] **Step 2: 确认失败** — `bun test src/sessions/compact.test.ts` → FAIL(stream 不存在/断言不匹配)
|
|
70
|
+
- [ ] **Step 3: 实现** — `COMPACT_MAX_SUMMARY_CHARS`;`compressSession` 内:`let summary = ''` + `for await (const chunk of model.stream(prompt))` 逐块取串文本、`onDelta?.(text)`、超限 `break`;循环后 `summary = summary.slice(0, COMPACT_MAX_SUMMARY_CHARS).trim()`;空 → error;catch 覆盖流中抛错
|
|
71
|
+
- [ ] **Step 4: 确认通过** — 同命令 → PASS
|
|
72
|
+
- [ ] **Step 5: Commit** — `git add src/sessions/compact.ts src/sessions/compact.test.ts && git commit -m "feat: streaming compaction with per-chunk deltas and hard char cap"`
|
|
73
|
+
|
|
74
|
+
### Task 2: REPL 流式显示 + compact 路由
|
|
75
|
+
|
|
76
|
+
**Files:**
|
|
77
|
+
- Modify: `src/screens/REPL.tsx`(resumeWith、/compact 分支;import `getRouting`)
|
|
78
|
+
|
|
79
|
+
**Interfaces:**
|
|
80
|
+
- Consumes: Task 1 全部导出;`getRouting()`(provider.js 已导出)
|
|
81
|
+
|
|
82
|
+
- [ ] **Step 1: 共享 helper** — 抽 `runCompaction(record, keepTurns): Promise<{compressed, record, error?}>`:内部统一「正在提炼前情提要…」提示 + `createModel(getRouting().compact ?? ctx.modelId).model` + `onDelta: delta => appendChatOutput(delta)` + 完成后补 `\n\n`;resumeWith 与 /compact 两入口**都只调它**,行为完全一致
|
|
83
|
+
- [ ] **Step 2: 两入口接线** — resumeWith 与 /compact 分支替换各自的模型构造与调用为 `runCompaction`(mock 跳过逻辑保留在 helper 内)
|
|
84
|
+
- [ ] **Step 3: 全量验证** — `bun test` 全绿 + `npm run typecheck` + `npm run build:repl`
|
|
85
|
+
- [ ] **Step 4: Commit** — `git commit -m "feat: live-stream compaction summary and compact-role fast-model routing"`
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# 用户记忆系统(User Memory)Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** transcode 跨会话/跨项目记住用户偏好:`~/.transcode/TRANS.md` 全局指令 + `memory/` 自动记忆 + `memory_save`/`memory_delete` 工具 + `/memory` `/remember` `/forget` 命令。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 新增 `src/agent/memory.ts` 存储层(目录文件是事实源,MEMORY.md 是 save/delete 时再生的产物);两个工具经 `dispatchPool` 进 `AGENT_TOOLS`(REPL/ACP/子 agent 同享);`loadProjectContext` 顺带装载用户记忆、`buildSystemPrompt` 渲染 `## User memory` 段——REPL(`src/screens/REPL.tsx:409`)与 ACP(`src/acp/session.ts:125`)每次提交都重建 prompt,记忆变更下一轮自动生效,无需失效机制,两调用点零改动。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript + Bun test + zod(均已有,不引新依赖)。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-22-user-memory-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 不引新依赖:frontmatter 行级解析,只认 `name` / `description` / `type` 三键,不引 yaml
|
|
16
|
+
- 文件是事实源:`loadUserMemory` 扫描目录文件;MEMORY.md 只在 save/delete 时从文件状态重新生成,装载时不读它
|
|
17
|
+
- 所有写盘原子化:tmp + rename,仿 `src/sessions/store.ts:124`
|
|
18
|
+
- 测试隔离:`TRANSCODE_USER_DIR` 指向 `mkdtemp` 根,try/finally 清理(仿 `system-prompt.test.ts` 对 `TRANSCODE_CONFIG_PATH` 的用法)
|
|
19
|
+
- 两工具 `isMutating: true`,不新增权限模式(plan 模式与 readonly 沿用 `loop.ts` 现有 isMutating 门禁)
|
|
20
|
+
- 预算 `12_000` 字符,条目整条丢弃不腰斩,优先级 `user > feedback > project > reference`
|
|
21
|
+
- 每任务收尾:`bun test` 全绿 + `bun run typecheck` 通过
|
|
22
|
+
|
|
23
|
+
## Review Focus
|
|
24
|
+
|
|
25
|
+
1. **首跑/目录不存在** → `loadUserMemory` 返回空对象、`saveMemory` 自建目录、`/memory` 显示空态(Task 1、4 测试)
|
|
26
|
+
2. **MEMORY.md 缺失或手改过期** → 装载/保存都以目录文件为准,索引可再生日后自动愈合成正确状态(Task 1)
|
|
27
|
+
3. **坏 frontmatter**(无 `---`、缺 type、未知 type、空文件)→ 该条跳过,绝不崩(Task 1)
|
|
28
|
+
4. **预算边界** → 超预算整条丢最低优先级并在 `omitted` 注名;TRANS.md 单独超长按现有项目文件方式截断加注(Task 1、3)
|
|
29
|
+
5. **危险 name**(空、含 `/`、`..`)→ 拒绝并返回可读错误;两工具 `isMutating=true` 被 plan/readonly 门禁拒绝(Task 1、2)
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
### Task 1: 记忆存储层 `src/agent/memory.ts`
|
|
34
|
+
|
|
35
|
+
**Files:**
|
|
36
|
+
- Create: `src/agent/memory.ts`
|
|
37
|
+
- Test: `src/agent/memory.test.ts`
|
|
38
|
+
|
|
39
|
+
**Interfaces:**
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
export type MemoryType = 'user' | 'feedback' | 'project' | 'reference';
|
|
43
|
+
export interface MemoryEntry { name: string; type: MemoryType; description: string; content: string }
|
|
44
|
+
export interface UserMemory { globalInstructions: string | null; entries: MemoryEntry[]; omitted: string[] }
|
|
45
|
+
export const USER_MEMORY_BUDGET_CHARS = 12_000;
|
|
46
|
+
export function userMemoryRoot(): string; // process.env.TRANSCODE_USER_DIR ?? ~/.transcode
|
|
47
|
+
export function globalInstructionsPath(): string; // <root>/TRANS.md
|
|
48
|
+
export function memoryDir(): string; // <root>/memory
|
|
49
|
+
export function sanitizeMemoryName(name: string): string | null; // trim 后空/含 / \ .. → null
|
|
50
|
+
export function parseMemoryFile(raw: string): MemoryEntry | null; // 坏 frontmatter → null
|
|
51
|
+
export function renderMemoryFile(entry: MemoryEntry): string; // 写盘格式,预算成本即此长度
|
|
52
|
+
export function renderMemoryIndex(entries: MemoryEntry[]): string; // MEMORY.md 内容
|
|
53
|
+
export function loadUserMemory(): Promise<UserMemory>;
|
|
54
|
+
export function saveMemory(input: { name: string; type: MemoryType; content: string; description?: string }): Promise<MemoryEntry>;
|
|
55
|
+
export function deleteMemory(name: string): Promise<boolean>;
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
文件格式(写盘与解析共用):
|
|
59
|
+
|
|
60
|
+
```markdown
|
|
61
|
+
---
|
|
62
|
+
name: bun-not-node
|
|
63
|
+
type: feedback
|
|
64
|
+
description: 用户所有项目用 bun 而非 node
|
|
65
|
+
---
|
|
66
|
+
正文,一条事实。
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
索引行:`- [name](name.md) — description`。
|
|
70
|
+
|
|
71
|
+
- [ ] **Step 1: 写失败测试**(bun:test + mkdtemp 根 + `TRANSCODE_USER_DIR`,try/finally 清理),覆盖:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
test('save→load 往返:文件 + 索引 + frontmatter 三键')
|
|
75
|
+
test('索引是再生产物:手删 MEMORY.md 后 load 仍返回条目,save 后索引重建')
|
|
76
|
+
test('预算:大 reference + 小 user 超预算 → user 保留、reference 进 omitted')
|
|
77
|
+
test('TRANS.md 超预算 → 截断并附 "... (global instructions truncated)"')
|
|
78
|
+
test('坏 frontmatter(空文件/缺 type/未知 type)→ 跳过该条不崩')
|
|
79
|
+
test('危险 name(空、a/b、..)→ saveMemory 抛错,deleteMemory 返回 false')
|
|
80
|
+
test('description 缺省取 content 首个非空行截 60 字符')
|
|
81
|
+
test('deleteMemory:命中删文件并重写索引,未命中返回 false')
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
85
|
+
|
|
86
|
+
Run: `bun test src/agent/memory.test.ts`
|
|
87
|
+
Expected: FAIL(模块不存在)
|
|
88
|
+
|
|
89
|
+
- [ ] **Step 3: 实现 `src/agent/memory.ts`**
|
|
90
|
+
|
|
91
|
+
同步 fs(仿 store.ts,该层无流式需求)。预算算法(测试未完全决定的唯一一处):
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
remaining = USER_MEMORY_BUDGET_CHARS
|
|
95
|
+
globalInstructions 超过 remaining → clip + "\n... (global instructions truncated)"
|
|
96
|
+
entries 显示序 = readdir 字典序;成本 = renderMemoryFile(entry).length
|
|
97
|
+
while 总成本 > remaining 且可丢:
|
|
98
|
+
丢 (priority 最低,同优先级取字典序最后) 一条 → omitted.push(name)
|
|
99
|
+
priority: user=3, feedback=2, project=1, reference=0
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`saveMemory`:sanitize(无效抛 `Error('invalid memory name …')`)→ 原子写 `<dir>/<name>.md` → 重扫目录按字典序重写 MEMORY.md → 返回 entry。目录不存在则 `mkdirSync recursive`。
|
|
103
|
+
|
|
104
|
+
- [ ] **Step 4: 跑测试确认通过**
|
|
105
|
+
|
|
106
|
+
Run: `bun test src/agent/memory.test.ts`
|
|
107
|
+
Expected: PASS 全绿
|
|
108
|
+
|
|
109
|
+
- [ ] **Step 5: 提交**
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
git add src/agent/memory.ts src/agent/memory.test.ts
|
|
113
|
+
git commit -m "feat: user memory store with atomic writes and budget"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
### Task 2: Agent 工具 `memory_save` / `memory_delete`
|
|
119
|
+
|
|
120
|
+
**Files:**
|
|
121
|
+
- Create: `src/agent/tools/memory.ts`
|
|
122
|
+
- Modify: `src/agent/tools/index.ts:15-28`(dispatchPool 数组加入两工具)
|
|
123
|
+
- Test: `src/agent/tools/memory.test.ts`
|
|
124
|
+
|
|
125
|
+
**Interfaces:**
|
|
126
|
+
- Consumes: Task 1 全部导出;`AgentTool`(src/agent/tools/types.ts)
|
|
127
|
+
- Produces: `memorySaveTool: AgentTool`(name `memory_save`)、`memoryDeleteTool: AgentTool`(name `memory_delete`)——schema 见下,`kind: 'edit'` / `'delete'`,均 `isMutating: true`
|
|
128
|
+
|
|
129
|
+
`memory_save` schema:`{ name: z.string().min(1), type: z.enum(['user','feedback','project','reference']), content: z.string().min(1), description: z.string().optional() }`。description 写入**不该存清单**:代码结构、git 历史、临时任务状态、TRANS.md 已有内容(CC 同款,让模型自筛)。
|
|
130
|
+
|
|
131
|
+
- [ ] **Step 1: 写失败测试**,覆盖:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
test('memory_save 经 execute 落盘:文件 + 索引 + 返回含 name/type')
|
|
135
|
+
test('memory_delete 经 execute 删条目,未命中返回 "not found" 文案')
|
|
136
|
+
test('两工具 isMutating === true(被 plan/readonly 门禁拒绝的根据)')
|
|
137
|
+
test('危险 name 经工具返回 Error 文案而非抛异常')
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
141
|
+
|
|
142
|
+
Run: `bun test src/agent/tools/memory.test.ts`
|
|
143
|
+
Expected: FAIL(模块不存在)
|
|
144
|
+
|
|
145
|
+
- [ ] **Step 3: 实现 `src/agent/tools/memory.ts`(仿 `todo.ts` 的 AgentTool 结构)并在 `index.ts` 的 dispatchPool 末尾加入两工具**
|
|
146
|
+
|
|
147
|
+
无效 name/删除未命中:execute 返回可读错误字符串(catch `saveMemory` 的抛错),不向上抛。
|
|
148
|
+
|
|
149
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
150
|
+
|
|
151
|
+
Run: `bun test src/agent/tools/memory.test.ts && bun test && bun run typecheck`
|
|
152
|
+
Expected: PASS 全绿
|
|
153
|
+
|
|
154
|
+
- [ ] **Step 5: 提交**
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
git add src/agent/tools/memory.ts src/agent/tools/memory.test.ts src/agent/tools/index.ts
|
|
158
|
+
git commit -m "feat: memory_save and memory_delete agent tools"
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
### Task 3: system prompt 注入
|
|
164
|
+
|
|
165
|
+
**Files:**
|
|
166
|
+
- Modify: `src/agent/system-prompt.ts:26-30`(ProjectContext)、`:64-82`(loadProjectContext)、`:85-137`(buildSystemPrompt)
|
|
167
|
+
- Test: `src/agent/system-prompt.test.ts`(追加)
|
|
168
|
+
|
|
169
|
+
**Interfaces:**
|
|
170
|
+
- Consumes: Task 1 的 `UserMemory` / `loadUserMemory` / `renderMemoryIndex`
|
|
171
|
+
- Produces: `ProjectContext.userMemory?: UserMemory`(可选——现有测试传 `{ cwd, projectFiles: [] }` 不受影响,REPL/ACP 调用点零改动)
|
|
172
|
+
|
|
173
|
+
- [ ] **Step 1: 写失败测试**,覆盖:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
test('userMemory 有内容 → 渲染 ## User memory 段,位于 ## Project instructions 之前')
|
|
177
|
+
test('段内含 Global instructions 原文、索引行、各条 #### name 与正文、omitted 注名行')
|
|
178
|
+
test('userMemory 为空/缺省 → 不渲染该段;How to work 始终含 memory_save 引导行(纠正即记、引用前先验证)')
|
|
179
|
+
test('loadProjectContext 集成:TRANSCODE_USER_DIR 根下放 TRANS.md + memory 条目 → context.userMemory 装载')
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
183
|
+
|
|
184
|
+
Run: `bun test src/agent/system-prompt.test.ts`
|
|
185
|
+
Expected: FAIL(新段不存在)
|
|
186
|
+
|
|
187
|
+
- [ ] **Step 3: 实现**
|
|
188
|
+
|
|
189
|
+
`loadProjectContext` 末尾追加 `userMemory: await loadUserMemory()`;`buildSystemPrompt` 在 Project instructions 之前渲染(仅当 globalInstructions 或 entries 非空):`### Global instructions`(原文)+ `### Memory`(索引行 + 各条 `#### name` + 正文 + `(omitted: a, b)` 注名行);How to work 数组追加一行:'- When the user corrects your behavior or states a lasting preference, save it with memory_save; before relying on a possibly stale memory, verify it still holds.'
|
|
190
|
+
|
|
191
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
192
|
+
|
|
193
|
+
Run: `bun test src/agent/system-prompt.test.ts && bun test && bun run typecheck`
|
|
194
|
+
Expected: PASS 全绿
|
|
195
|
+
|
|
196
|
+
- [ ] **Step 5: 提交**
|
|
197
|
+
|
|
198
|
+
```bash
|
|
199
|
+
git add src/agent/system-prompt.ts src/agent/system-prompt.test.ts
|
|
200
|
+
git commit -m "feat: inject user memory into system prompt"
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
### Task 4: REPL 命令 + README
|
|
206
|
+
|
|
207
|
+
**Files:**
|
|
208
|
+
- Modify: `src/commands.ts`(commands 数组追加三条)
|
|
209
|
+
- Modify: `README.md`(命令列表 + 「用户记忆」小节)
|
|
210
|
+
- Test: `src/commands.test.ts`(追加)
|
|
211
|
+
|
|
212
|
+
**Interfaces:**
|
|
213
|
+
- Consumes: Task 1 的 `loadUserMemory` / `saveMemory` / `deleteMemory` / `sanitizeMemoryName`(无循环依赖:memory.ts 只依赖 node:fs/path/os)
|
|
214
|
+
- Produces: 命令 `/memory`、`/remember <text>`、`/forget <name>`(execute 支持 Promise,签名见 `src/commands.ts:20`)
|
|
215
|
+
|
|
216
|
+
- [ ] **Step 1: 写失败测试**(tmp 根 + env,ctx 传 stub),覆盖:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
test('/memory:有记忆 → 列索引行 + 根路径 + 提示;空态 → "No memories yet" 引导 /remember')
|
|
220
|
+
test('/remember 一段话 → 存为 type=user,content=原文,输出确认与 name;同名冲突加 -2 后缀')
|
|
221
|
+
test('/forget 命中 → "Forgot <name>.";未命中 → "No memory named"')
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
225
|
+
|
|
226
|
+
Run: `bun test src/commands.test.ts`
|
|
227
|
+
Expected: FAIL(命令不存在)
|
|
228
|
+
|
|
229
|
+
- [ ] **Step 3: 实现三条命令 + README**
|
|
230
|
+
|
|
231
|
+
`/remember` slug 算法(测试未完全决定处):取文本前 4 个词的 ascii 部分小写、非字母数字折叠为 `-`;结果为空(纯中文等)→ 取前 8 个字符;冲突 → `-2`、`-3` 递增。`/memory` 输出:Memory 根路径、TRANS.md 行数、索引行、`/remember`/`/forget` 用法提示。README 命令列表补三条 + 「用户记忆」小节(存储路径、自动记忆行为、命令用法)。
|
|
232
|
+
|
|
233
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
234
|
+
|
|
235
|
+
Run: `bun test src/commands.test.ts && bun test && bun run typecheck`
|
|
236
|
+
Expected: PASS 全绿
|
|
237
|
+
|
|
238
|
+
- [ ] **Step 5: 提交**
|
|
239
|
+
|
|
240
|
+
```bash
|
|
241
|
+
git add src/commands.ts src/commands.test.ts README.md
|
|
242
|
+
git commit -m "feat: /memory /remember /forget commands with docs"
|
|
243
|
+
```
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Web 工具(WebFetch + WebSearch)Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** agent 联网能力:`web_fetch`(零配置抓网页)+ `web_search`(Tavily/Brave 适配器,用户配 `~/.transcode.json`)+ `/search` 交互配置命令。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 抓取与搜索的**可测逻辑全部抽成纯函数/注入 fetch 的模块**(HTML 提取、charset 嗅探、两家 REST 适配器、配置归一化),工具壳只做组装;`web_search` 经 `AgentTool.isEnabled` 谓词在 `loop.ts:315` 每轮组装时按配置过滤;`/search` 复刻 `/models` 的 REPL 拦截 + phase 状态机模式,可测部分(provider 列表、测试查询、配置写入)留在模块层。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript + Bun test + zod(已有);原生 fetch,零新依赖。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-22-web-tools-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 零新依赖:HTML 提取、charset 嗅探、代理(不做)全部手写;不引 undici/turndown
|
|
16
|
+
- UA 固定:`Mozilla/5.0 (compatible; transcode/${VERSION})`(版本取 `src/version.ts`)
|
|
17
|
+
- 端点与鉴权按 spec:Tavily `POST https://api.tavily.com/search` body `{ api_key, query, max_results }`;Brave `GET https://api.search.brave.com/res/v1/web/search` 头 `X-Subscription-Token`、参数 `q`/`count`
|
|
18
|
+
- 上限:响应体 512KB、注入文本 20k 字符、超时 15s(`AbortSignal.timeout`)、`maxResults` 默认 5、上限 20
|
|
19
|
+
- 测试**不发真实网络**:fetch 以参数注入或测试内替换 `globalThis.fetch`(try/finally 恢复)
|
|
20
|
+
- 两工具 `kind: 'fetch'`、`isMutating: false`,经 `dispatchPool` 注册(ACP/子 agent 同享)
|
|
21
|
+
- 每任务收尾:`bun test` 全绿 + `bun run typecheck` 通过
|
|
22
|
+
|
|
23
|
+
## Review Focus
|
|
24
|
+
|
|
25
|
+
1. **GBK/GB2312 页面** → Content-Type/meta 嗅探 + `TextDecoder` 解码,中文不乱码(Task 1 测试)
|
|
26
|
+
2. **超大响应/超长文本** → 512KB 字节截断、20k 字符截断并注明(Task 1)
|
|
27
|
+
3. **403/404/超时/DNS 失败** → 可读错误返回模型,execute 永不向上抛(Task 1)
|
|
28
|
+
4. **webSearch 配置坏 vs 未配** → 坏:工具隐藏 + REPL 启动一行警告 + ACP stderr 一次;未配:全程静默(Task 2)
|
|
29
|
+
5. **/search 中途放弃(Esc)/空 key/测试查询失败** → 不写坏配置,可重输,phase 正确回落 idle(Task 3)
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
### Task 1: `web_fetch` 工具
|
|
34
|
+
|
|
35
|
+
**Files:**
|
|
36
|
+
- Create: `src/agent/tools/web-fetch.ts`
|
|
37
|
+
- Test: `src/agent/tools/web-fetch.test.ts`
|
|
38
|
+
|
|
39
|
+
**Interfaces:**
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// 纯函数,Task 内导出供测试与工具壳共用
|
|
43
|
+
export const FETCH_MAX_BYTES = 512 * 1024;
|
|
44
|
+
export const FETCH_MAX_CHARS = 20_000;
|
|
45
|
+
export function sniffCharset(contentType: string, body: Uint8Array): string;
|
|
46
|
+
// Content-Type charset 优先 → 前 2KB 扫 <meta charset> / <meta http-equiv> → 'utf-8'
|
|
47
|
+
export function decodeBody(body: Uint8Array, charset: string): string;
|
|
48
|
+
// TextDecoder(charset),非法 charset 回落 utf-8
|
|
49
|
+
export function htmlToText(html: string): { title: string | null; text: string };
|
|
50
|
+
// 剥 script/style/noscript/head 噪声(含 <title> 提取),标签→空白,空行折叠
|
|
51
|
+
export const webFetchTool: AgentTool; // name 'web_fetch', schema { url: z.string().url(), prompt: z.string().optional() }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
- [ ] **Step 1: 写失败测试**(fetch 以替换 `globalThis.fetch` 注入,try/finally 恢复),覆盖:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
test('htmlToText:剥 script/style、留正文、提取 <title>、折叠空行')
|
|
58
|
+
test('sniffCharset:Content-Type charset 优先;meta charset 兜底;默认 utf-8')
|
|
59
|
+
test('decodeBody:gbk 字节用 TextDecoder 正确解码中文')
|
|
60
|
+
test('web_fetch:HTML 响应 → 标题 + 文本 + prompt 原样前置')
|
|
61
|
+
test('web_fetch:text/plain 与 application/json 原样返回(截断)')
|
|
62
|
+
test('web_fetch:超 20k 字符截断并注明 "... (truncated)"')
|
|
63
|
+
test('web_fetch:403/404 → 返回含状态码的可读错误;fetch 抛超时 → 可读错误,不向上抛')
|
|
64
|
+
test('web_fetch:非文本类型(pdf/图片)→ 返回内容类型与大小提示,不尝试解析')
|
|
65
|
+
test('web_fetch:请求头带 transcode UA,16 位非 UTF-8 gbk 页面解码不乱码')
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
69
|
+
|
|
70
|
+
Run: `bun test src/agent/tools/web-fetch.test.ts`
|
|
71
|
+
Expected: FAIL(模块不存在)
|
|
72
|
+
|
|
73
|
+
- [ ] **Step 3: 实现 `web-fetch.ts` 并在 `index.ts` dispatchPool 注册**
|
|
74
|
+
|
|
75
|
+
要点:`arrayBuffer()` 收字节(不做流式),字节超 `FETCH_MAX_BYTES` 即截断;按 content-type 分派(html → `htmlToText`,text/json → 原样,其余 → 提示);所有 fetch/解码异常 catch 为错误字符串。UA 常量放模块顶部(版本取 `src/version.ts` 的 `VERSION`)。
|
|
76
|
+
|
|
77
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
78
|
+
|
|
79
|
+
Run: `bun test src/agent/tools/web-fetch.test.ts && bun test && bun run typecheck`
|
|
80
|
+
Expected: PASS 全绿
|
|
81
|
+
|
|
82
|
+
- [ ] **Step 5: 提交**
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
git add src/agent/tools/web-fetch.ts src/agent/tools/web-fetch.test.ts src/agent/tools/index.ts
|
|
86
|
+
git commit -m "feat: web_fetch tool with charset sniffing and zero-dep HTML extraction"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
### Task 2: `web_search` 适配器 + 工具 + 配置门禁
|
|
92
|
+
|
|
93
|
+
**Files:**
|
|
94
|
+
- Create: `src/provider/web-search.ts`
|
|
95
|
+
- Create: `src/agent/tools/web-search.ts`
|
|
96
|
+
- Modify: `src/agent/tools/types.ts`(AgentTool 加 `isEnabled?`)、`src/agent/loop.ts:315`(组装时过滤)、`src/screens/REPL.tsx`(启动警告)、`src/acp/server.ts`(stderr 提示一次)
|
|
97
|
+
- Test: `src/provider/web-search.test.ts`、`src/agent/tools/web-search.test.ts`
|
|
98
|
+
|
|
99
|
+
**Interfaces:**
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
// src/provider/web-search.ts
|
|
103
|
+
export interface SearchHit { title: string; url: string; snippet: string }
|
|
104
|
+
export interface WebSearchConfig { provider: 'tavily' | 'brave'; apiKey: string }
|
|
105
|
+
export function normalizeWebSearchConfig(raw: unknown): WebSearchConfig | null;
|
|
106
|
+
// 段缺失/null → null(静默);段存在但坏 → null + warning 非空
|
|
107
|
+
export function webSearchConfigWarning(raw: unknown): string | null;
|
|
108
|
+
export async function runWebSearch(
|
|
109
|
+
cfg: WebSearchConfig, query: string, maxResults = 5,
|
|
110
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
111
|
+
): Promise<SearchHit[]>; // 未知 provider / HTTP 非 2xx / API 错误 → throw Error(含 API 原始报错)
|
|
112
|
+
// src/agent/tools/web-search.ts
|
|
113
|
+
export const webSearchTool: AgentTool; // name 'web_search', schema { query: z.string().min(1), maxResults: z.number().int().min(1).max(20).optional() }
|
|
114
|
+
// src/agent/tools/types.ts
|
|
115
|
+
export interface AgentTool { /* 现有字段 */ isEnabled?: () => boolean }
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- [ ] **Step 1: 写失败测试**,覆盖:
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
test('normalizeWebSearchConfig:tavily/brave 合法通过;段缺失 → null 且无警告')
|
|
122
|
+
test('normalizeWebSearchConfig:provider 拼错/key 空 → null 且警告含 "/search" 提示')
|
|
123
|
+
test('runWebSearch(tavily):按 spec 端点/体调用,映射 title/url/snippet(注入 fetch 断言)')
|
|
124
|
+
test('runWebSearch(brave):X-Subscription-Token 头 + q/count 参数,结果映射')
|
|
125
|
+
test('runWebSearch:HTTP 401/400 → 抛含状态与 API 报错文案的 Error')
|
|
126
|
+
test('web_search 工具:isEnabled 按当前 loadConfig 返回;execute 输出 "title — url\nsnippet" 列表')
|
|
127
|
+
test('web_search 工具:未配置时 execute 返回 not configured 可读错误(兜底路径)')
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
131
|
+
|
|
132
|
+
Run: `bun test src/provider/web-search.test.ts src/agent/tools/web-search.test.ts`
|
|
133
|
+
Expected: FAIL(模块不存在)
|
|
134
|
+
|
|
135
|
+
- [ ] **Step 3: 实现**
|
|
136
|
+
|
|
137
|
+
`loop.ts:315` 过滤:`const tools = (options.tools ?? AGENT_TOOLS).filter(t => !t.isEnabled || t.isEnabled())`(dispatch 的显式 tools 同样过滤)。REPL 挂载时与 ACP `session/new` 各查一次 `webSearchConfigWarning(loadConfig().webSearch)` 并输出(REPL 走 `appendChatOutput`,ACP 走既有 stderr 日志行)。工具 execute 每次现读配置。
|
|
138
|
+
|
|
139
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
140
|
+
|
|
141
|
+
Run: `bun test src/provider/web-search.test.ts src/agent/tools/web-search.test.ts && bun test && bun run typecheck`
|
|
142
|
+
Expected: PASS 全绿
|
|
143
|
+
|
|
144
|
+
- [ ] **Step 5: 提交**
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
git add src/provider/web-search.ts src/provider/web-search.test.ts src/agent/tools/web-search.ts src/agent/tools/web-search.test.ts src/agent/tools/types.ts src/agent/loop.ts src/screens/REPL.tsx src/acp/server.ts
|
|
148
|
+
git commit -m "feat: web_search tool with tavily/brave adapters and config gating"
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
### Task 3: `/search` REPL 交互 + README
|
|
154
|
+
|
|
155
|
+
**Files:**
|
|
156
|
+
- Modify: `src/commands.ts`(注册 `/search` 桩,注释标明 REPL 拦截)、`src/screens/REPL.tsx`(拦截 + phase 状态机)
|
|
157
|
+
- Modify: `README.md`(工具侧行 + 「联网工具」小节)
|
|
158
|
+
- Test: `src/commands.test.ts`(追加)、`src/screens/submit.test.ts`(追加,若 phase 分派进了 submit 纯函数)
|
|
159
|
+
|
|
160
|
+
**Interfaces:**
|
|
161
|
+
- Consumes: Task 2 全部导出;`saveConfig`/`loadConfig`(src/config.ts);REPL 既有 phase 模式(`model_select` → `model_apikey` → `model_check` 的同构缩微版)
|
|
162
|
+
- Produces: phase `search_provider | search_apikey | search_check`(REPL 内部,不导出);命令 `/search`
|
|
163
|
+
|
|
164
|
+
- [ ] **Step 1: 写失败测试**,覆盖:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
test('/search 桩已注册,/help 可见(仿 init 注册测试)')
|
|
168
|
+
test('saveWebSearchConfig:写 loadConfig().webSearch 且不覆盖其它段(注入 configPath)')
|
|
169
|
+
test('测试查询成功路径:runWebSearch 注入 fetch → 首条 title 进输出、配置已写入')
|
|
170
|
+
test('测试查询失败路径:API 报错 → 配置未写、错误文案展示、回 search_apikey 可重输')
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
174
|
+
|
|
175
|
+
Run: `bun test src/commands.test.ts src/provider/web-search.test.ts`
|
|
176
|
+
Expected: FAIL(命令不存在;saveWebSearchConfig 未实现)
|
|
177
|
+
|
|
178
|
+
- [ ] **Step 3: 实现**
|
|
179
|
+
|
|
180
|
+
REPL 拦截 `search`(仿 `REPL.tsx:749` 的 models 拦截):`search_provider` 光标选 tavily/brave → `search_apikey` 输 key(已存回车沿用)→ `search_check` 用固定测试查询 `transcode connectivity check` 调 `runWebSearch(maxResults=1)`:成功 → `saveConfig` 写入 + 展示首条 title;失败 → 展示 API 原始报错回 `search_apikey`;Esc 任意阶段回 idle 且不写配置。提取 `saveWebSearchConfig(provider, apiKey)` 进 `src/provider/web-search.ts`(可测)。README:命令列表补 `/search`,工具侧行补 `web_fetch`/`web_search`,新增「联网工具」小节(两条配置路径、bun 路径认 HTTP(S)_PROXY、诚实 UA 说明)。
|
|
181
|
+
|
|
182
|
+
- [ ] **Step 4: 跑测试确认通过 + 全量回归**
|
|
183
|
+
|
|
184
|
+
Run: `bun test src/commands.test.ts src/provider/web-search.test.ts && bun test && bun run typecheck`
|
|
185
|
+
Expected: PASS 全绿
|
|
186
|
+
|
|
187
|
+
- [ ] **Step 5: 提交**
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
git add src/commands.ts src/commands.test.ts src/screens/REPL.tsx src/provider/web-search.ts src/provider/web-search.test.ts README.md
|
|
191
|
+
git commit -m "feat: /search interactive setup command with docs"
|
|
192
|
+
```
|