@trans-ai/trans-code 0.3.0 → 0.5.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 +13 -3
- package/docs/superpowers/plans/2026-11-21-auto-update.md +138 -0
- package/docs/superpowers/specs/2026-11-21-auto-update-design.md +61 -0
- package/package.json +1 -1
- package/src/agent/loop.test.ts +92 -1
- package/src/agent/loop.ts +74 -0
- package/src/agent/tools/bash.test.ts +42 -1
- package/src/agent/tools/bash.ts +202 -15
- package/src/agent/tools/dispatch.test.ts +42 -0
- package/src/agent/tools/dispatch.ts +11 -1
- package/src/agent/tools/index.ts +2 -0
- package/src/agent/tools/powershell.test.ts +61 -0
- package/src/agent/tools/read-only.ts +16 -0
- package/src/agent/tools/session.ts +12 -0
- package/src/agent/tools/shell-paths.test.ts +65 -0
- package/src/agent/tools/shell-paths.ts +19 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/cli.ts +9 -3
- package/src/commands.ts +18 -0
- package/src/config.test.ts +49 -0
- package/src/config.ts +42 -0
- package/src/main.tsx +2 -1
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.test.ts +6 -0
- package/src/provider/provider.ts +35 -1
- package/src/screens/REPL.tsx +336 -42
- package/src/screens/slash-completion.test.ts +62 -0
- package/src/screens/slash-completion.ts +41 -0
- package/src/screens/submit.test.ts +23 -0
- package/src/screens/submit.ts +17 -0
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- package/src/upgrade.test.ts +242 -0
- package/src/upgrade.ts +206 -9
- package/src/version.ts +1 -1
package/README.md
CHANGED
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
- Bun >= 1.3
|
|
13
13
|
- 至少一个模型提供商的 API Key
|
|
14
14
|
|
|
15
|
+
**平台**:macOS / Linux 原生支持。Windows 需安装 [Git Bash](https://git-scm.com/)(bash 工具自动探测 `C:\Program Files\Git\bin\bash.exe` 等常见位置;也可用 `TRANSCODE_SHELL` 显式指定),超时终止走 `taskkill /T /F` 杀进程树,路径在 Windows/Git-Bash 两种形态间自动转换。纯 PowerShell 环境(无 Git Bash)暂不支持。
|
|
16
|
+
|
|
15
17
|
```bash
|
|
16
18
|
bun install
|
|
17
19
|
```
|
|
@@ -41,7 +43,10 @@ export OPENAI_API_KEY=...
|
|
|
41
43
|
export TRANSCODE_MODEL=openai:gpt-4o
|
|
42
44
|
```
|
|
43
45
|
|
|
44
|
-
**2. REPL 交互配置**(`/models`):三级流程——选厂商 →
|
|
46
|
+
**2. REPL 交互配置**(`/models`):三级流程——选厂商 → 选模型 → 输入 key(已存的可回车沿用)。
|
|
47
|
+
- 模型列表**从网关实时拉取**(`GET /v1/models`,标"网关实时列表"),选的就是实际可用的;网关不提供列表时回退内置精选列表 + "自定义模型名…"自由输入
|
|
48
|
+
- key 确认后**自动测试连通性**,显示端点**实际调度的模型**(如智谱 Coding 端点会把 `glm-4.6` 映射为套餐当前的 `glm-5.3-flash`,测试会如实亮出);失败显示 API 原始报错并可重输
|
|
49
|
+
- `custom` 支持任意 OpenAI 兼容网关:base URL → key → **从网关实时模型列表中选**(OneAPI/NewAPI/自建中转即插即见),无需盲填模型名
|
|
45
50
|
|
|
46
51
|
**3. 档案 + 角色路由**(`~/.transcode.json`,任务级模型分派):
|
|
47
52
|
|
|
@@ -198,7 +203,8 @@ ACP 默认权限模式是 `ask`:写文件、改文件、执行命令前会向
|
|
|
198
203
|
| `edit_file` | 精确替换,支持单次多处编辑(`edits[]` 原子应用);弯/直引号自动归一化 | 是 |
|
|
199
204
|
| `glob` | 按 glob 查文件(git 仓库内遵循 `.gitignore`) | 否 |
|
|
200
205
|
| `grep` | 正则搜索:上下文行(`context`)、跨行匹配(`multiline`)、`.gitignore` 感知 | 否 |
|
|
201
|
-
| `bash` | 用户 shell 执行;**cd 跨调用持久**、登录环境快照、进程组 kill
|
|
206
|
+
| `bash` | 用户 shell 执行;**cd 跨调用持久**、登录环境快照、进程组 kill、头尾截断;`run_in_background` 后台运行 | 是(只读命令免确认) |
|
|
207
|
+
| `bash_output` | 读取后台任务输出(`task_id` 可选,`wait: true` 等待最多 5s;无 id 时列出全部任务) | 否 |
|
|
202
208
|
| `todo_write` | 任务清单(`[x]/[~]/[ ]`),多步任务防漂移 | 否 |
|
|
203
209
|
| `ask_model` | 单次问答式分派:把子问题发给某角色的模型,答案回入对话 | 否 |
|
|
204
210
|
| `dispatch_agent` | 派发子 Agent:独立模型 + 工具白名单 + 自己的回合循环,只回传最终报告 | 是 |
|
|
@@ -215,7 +221,11 @@ ACP 默认权限模式是 `ask`:写文件、改文件、执行命令前会向
|
|
|
215
221
|
- **`dispatch_agent`**:多步研究型子任务 —— 子 Agent 用角色档案的模型 + 工具白名单(默认只读三件套)跑自己的循环。上下文契约是**任务进、报告出**:子 Agent 看不到主对话,任务描述必须自包含;只有最终报告回入主对话。派发本身需用户 y/n 授权,子 Agent 禁止递归派发,回合上限 25
|
|
216
222
|
- **图片自动代理**:配置了 `routing.vision` 时,工具产生的图片自动经视觉模型转文字描述,主模型无需多模态能力
|
|
217
223
|
|
|
218
|
-
主对话有防护栏:探索停滞(30 次零写入)自动催促、无视则强制终止(`stalled
|
|
224
|
+
主对话有防护栏:探索停滞(30 次零写入)自动催促、无视则强制终止(`stalled`);交付后长尾钻探会被收尾提醒;上下文接近上限自动摘要压缩(`TRANSCODE_COMPACT_CHARS`,默认 20 万字符,0 关闭)。
|
|
225
|
+
|
|
226
|
+
## 方案先行
|
|
227
|
+
|
|
228
|
+
`/plan <任务描述>` 进入只读探索模式:变更类工具全部被拒并引导模型产出**编号实施方案**(以 `PLAN READY` 结束),你确认方案后再让它执行 —— 探索和动手分离,防止一上来就改错。
|
|
219
229
|
|
|
220
230
|
## 上下文
|
|
221
231
|
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# transcode 自动更新 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:** REPL 启动时后台静默检查并安装 npm 更新(默认启用,24h 节流),`~/.transcode.json` 可关闭或钉住版本,`transcode upgrade [version]` 支持指定版本。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 决策逻辑全部放两个纯函数(`normalizeAutoUpdate` 在 config.ts、`planAutoUpdate` 在 upgrade.ts),后台执行器 `startAutoUpdate` 是薄壳(读配置 → 纯函数决策 → npm 子进程),notice 经模块级 Promise 传入 REPL 展示横幅。现有 `runUpgrade` 拆出可复用的 `isDevInstall(entry, root)` 守卫。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript + Bun(测试 `bun test`)、ink/React(REPL)、node:child_process(npm 子进程)。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-21-auto-update-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 用户可见文案用中文,横幅格式固定:`⟳ 已自动更新 ${from} → ${to},重启 transcode 生效`
|
|
16
|
+
- 注册表固定官方源 `https://registry.npmjs.org`(复用 upgrade.ts 的 `OFFICIAL` 常量,防镜像假升级)
|
|
17
|
+
- 不新增依赖;`tsc --noEmit` 必须保持零错误;现有 194 个测试保持全绿
|
|
18
|
+
- 环境变量:`TRANSCODE_SKIP_UPDATE=1` 强制关闭自动更新;`TRANSCODE_UPDATE_INTERVAL_HOURS` 覆盖节流时长(默认 24)
|
|
19
|
+
- `lastCheck` 仅在真正查询过 registry 后写回(失败不写,下次启动重试)
|
|
20
|
+
- 测试一律用 `TRANSCODE_CONFIG_PATH` 指向 mkdtemp 临时目录,绝不触碰真实 `~/.transcode.json`
|
|
21
|
+
|
|
22
|
+
## Review Focus
|
|
23
|
+
|
|
24
|
+
1. registry 不可达/超时 → 静默跳过且不写 `lastCheck` — Task 2 测 `unknown-latest`;Task 3 测 `disabled` 快速返回 null(网络路径靠 catch 兜底,Task 6 手动断网验证)
|
|
25
|
+
2. `autoUpdate` 为非法值(数字、字符串 `"yes"`、数组)→ 按默认启用处理,不抛错 — Task 1
|
|
26
|
+
3. 节流边界:距上次检查恰好 ≥ interval 才放行 — Task 2
|
|
27
|
+
4. 钉住版本 == 当前版本 → 不安装(含 `latest` == 当前)— Task 2
|
|
28
|
+
5. 仓库开发安装(bun link / checkout,entry 不在 npm root 下)→ 后台路径静默退出 — Task 3 对 `isDevInstall(entry, root)` 用 tmp 目录测两侧
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
### Task 1: `normalizeAutoUpdate` 配置规范化
|
|
33
|
+
|
|
34
|
+
**Files:**
|
|
35
|
+
- Modify: `src/config.ts`
|
|
36
|
+
- Test: `src/config.test.ts`(新建)
|
|
37
|
+
|
|
38
|
+
**Interfaces:**
|
|
39
|
+
- Produces:
|
|
40
|
+
```ts
|
|
41
|
+
export interface AutoUpdateConfig {
|
|
42
|
+
enabled?: boolean;
|
|
43
|
+
target?: string; // 'latest'(缺省)或具体版本号
|
|
44
|
+
lastCheck?: number; // epoch ms
|
|
45
|
+
}
|
|
46
|
+
// TranscodeConfig 增加: autoUpdate?: boolean | AutoUpdateConfig
|
|
47
|
+
export interface NormalizedAutoUpdate { enabled: boolean; target: string; lastCheck: number }
|
|
48
|
+
export function normalizeAutoUpdate(raw: unknown): NormalizedAutoUpdate
|
|
49
|
+
```
|
|
50
|
+
规则:`false` → `{enabled:false, target:'latest', lastCheck:0}`;`undefined` → 默认启用;对象取字段(`enabled` 缺省 true,`target` 缺省 `'latest'`,`lastCheck` 缺省 0);其余任何类型(数字/字符串/数组/null)→ 默认启用形。
|
|
51
|
+
|
|
52
|
+
- [ ] **Step 1: 写失败测试** — `src/config.test.ts`,`bun:test` 风格(参考 `src/screens/submit.test.ts`),describe `normalizeAutoUpdate`:false→关闭;undefined→enabled true;空对象→`{true,'latest',0}`;`{enabled:false,target:'0.3.0'}`→保留 target;`{enabled:true,target:'0.3.0',lastCheck:123}`→原样;非法值(`"yes"`、`5`、`null`、`[]`)→默认启用形
|
|
53
|
+
- [ ] **Step 2: 跑测确认失败** — `bun test src/config.test.ts` → Cannot find module 或 fail
|
|
54
|
+
- [ ] **Step 3: 实现** — config.ts 加类型 + `normalizeAutoUpdate`(纯函数,不碰 fs)
|
|
55
|
+
- [ ] **Step 4: 跑测通过** — `bun test src/config.test.ts` 全绿
|
|
56
|
+
- [ ] **Step 5: Commit** — `feat: normalizeAutoUpdate config parsing`
|
|
57
|
+
|
|
58
|
+
### Task 2: `planAutoUpdate` 决策纯函数
|
|
59
|
+
|
|
60
|
+
**Files:**
|
|
61
|
+
- Modify: `src/upgrade.ts`
|
|
62
|
+
- Test: `src/upgrade.test.ts`(新建)
|
|
63
|
+
|
|
64
|
+
**Interfaces:**
|
|
65
|
+
- Consumes: Task 1 的 `NormalizedAutoUpdate`(仅形状)
|
|
66
|
+
- Produces:
|
|
67
|
+
```ts
|
|
68
|
+
export type AutoUpdatePlan =
|
|
69
|
+
| { action: 'skip'; reason: 'env-skip' | 'disabled' | 'throttled' | 'up-to-date' | 'unknown-latest' }
|
|
70
|
+
| { action: 'install'; spec: string; from: string; to: string };
|
|
71
|
+
export function planAutoUpdate(input: {
|
|
72
|
+
current: string; latest: string | null; target: string;
|
|
73
|
+
enabled: boolean; lastCheck: number; now: number;
|
|
74
|
+
intervalHours?: number; envSkip?: boolean;
|
|
75
|
+
}): AutoUpdatePlan
|
|
76
|
+
```
|
|
77
|
+
顺序:envSkip→`env-skip`;!enabled→`disabled`;`now - lastCheck < (intervalHours ?? 24) * 3600_000`→`throttled`;target==='latest':latest null→`unknown-latest`,===current→`up-to-date`,否则 install `@trans-ai/trans-code@latest`;具体 target:===current→`up-to-date`,否则 install `@trans-ai/trans-code@${target}`(允许降级)。`spec` 含包名全名。
|
|
78
|
+
|
|
79
|
+
- [ ] **Step 1: 写失败测试** — describe `planAutoUpdate`:env-skip 优先于一切;disabled;throttled(差 1ms 也拦);边界 `now-lastCheck === interval` 放行;latest 模式 unknown-latest / up-to-date / install;pin 模式相同版本跳过、不同版本(含降级 0.4.0→0.3.0)install 且 spec 正确
|
|
80
|
+
- [ ] **Step 2: 跑测确认失败**
|
|
81
|
+
- [ ] **Step 3: 实现** — upgrade.ts 顶部导出纯函数
|
|
82
|
+
- [ ] **Step 4: 跑测通过**
|
|
83
|
+
- [ ] **Step 5: Commit** — `feat: planAutoUpdate decision function`
|
|
84
|
+
|
|
85
|
+
### Task 3: `isDevInstall` 守卫 + `startAutoUpdate` 后台执行
|
|
86
|
+
|
|
87
|
+
**Files:**
|
|
88
|
+
- Modify: `src/upgrade.ts`(从 `runUpgrade` 中抽出守卫)
|
|
89
|
+
- Test: `src/upgrade.test.ts`(追加)
|
|
90
|
+
|
|
91
|
+
**Interfaces:**
|
|
92
|
+
- Consumes: Task 1 `normalizeAutoUpdate`、Task 2 `planAutoUpdate`
|
|
93
|
+
- Produces:
|
|
94
|
+
```ts
|
|
95
|
+
export function isDevInstall(entryPath: string, npmRoot: string): boolean // 双参纯化,realpath 归一后前缀比较
|
|
96
|
+
export function autoUpdateNotice(): Promise<string | null> // 未启动时 resolve null
|
|
97
|
+
export function startAutoUpdate(): void // 仅 REPL 路径调用;fire-and-forget
|
|
98
|
+
```
|
|
99
|
+
`startAutoUpdate` 内部:临时 `TRANSCODE_CONFIG_PATH` 读配置 → normalize → envSkip → dev-install(`isDevInstall(realpathSync(fileURLToPath(import.meta.url)), await npmRoot())`)→ `target !== 'latest'` 时 `latest = target`,否则 `latestVersion()` → `planAutoUpdate` → skip 则 notice=null;install 则 `npm i -g ${spec} --registry=OFFICIAL`,成功后 notice=`⟳ 已自动更新 ${current} → ${installed ?? to},重启 transcode 生效` 并写回 lastCheck=now(skip 的 throttled/disabled 不写);任何异常 catch → notice=null。`autoUpdateNotice()` 返回模块级已 settle/settling 的 promise(`startAutoUpdate` 未调用时为 `Promise.resolve(null)`)。
|
|
100
|
+
- [ ] **Step 1: 写失败测试** — `isDevInstall`:mkdtemp 建 `root/pkg/entry.js`(同侧 false)与 root 外文件(true);`autoUpdateNotice`:未调用时 resolve null;`startAutoUpdate`(`TRANSCODE_CONFIG_PATH` 指临时配置写 `"autoUpdate": false`)→ notice 快速 resolve null 且不产生 npm 子进程(用 disabled 短路保证)
|
|
101
|
+
- [ ] **Step 2: 跑测确认失败**
|
|
102
|
+
- [ ] **Step 3: 实现** — 抽 `isDevInstall` 并让 `runUpgrade` 复用;实现 `startAutoUpdate`/`autoUpdateNotice`
|
|
103
|
+
- [ ] **Step 4: 跑测通过 + 全套回归** — `bun test`(194+新增)全绿
|
|
104
|
+
- [ ] **Step 5: Commit** — `feat: background auto-update with silent install`
|
|
105
|
+
|
|
106
|
+
### Task 4: `runUpgrade(target?)` 与 cli 子命令
|
|
107
|
+
|
|
108
|
+
**Files:**
|
|
109
|
+
- Modify: `src/upgrade.ts:61`(`runUpgrade` 签名加 `target?: string`)、`src/cli.ts:50-54`、`src/cli.ts` USAGE
|
|
110
|
+
|
|
111
|
+
**Interfaces:**
|
|
112
|
+
- Consumes: Task 3 `isDevInstall`
|
|
113
|
+
- Produces: `runUpgrade(target?: string): Promise<void>` — 有 target 时跳过 latest 比对直接装 `PKG@target`(仍走 dev-install 守卫与官方源),输出 `Upgrading ${VERSION} → ${target}…`
|
|
114
|
+
- [ ] **Step 1: 实现** — cli.ts:`const target = rest[0]; await runUpgrade(target)`;USAGE 第 8 行改为 `transcode upgrade [version] Upgrade to the latest or a specific version`
|
|
115
|
+
- [ ] **Step 2: 验证** — `bun run typecheck` 零错误;`bun test` 全绿
|
|
116
|
+
- [ ] **Step 3: 手动冒烟** — `bun bin/transcode.ts --help` 输出含 `upgrade [version]`
|
|
117
|
+
- [ ] **Step 4: Commit** — `feat: upgrade to a specific version`
|
|
118
|
+
|
|
119
|
+
### Task 5: REPL 接入与更新横幅
|
|
120
|
+
|
|
121
|
+
**Files:**
|
|
122
|
+
- Modify: `src/cli.ts`(REPL 分支先 `startAutoUpdate()`)、`src/main.tsx:53`、`src/screens/REPL.tsx:51`(props)+ 新增 useEffect
|
|
123
|
+
|
|
124
|
+
**Interfaces:**
|
|
125
|
+
- Consumes: Task 3 `autoUpdateNotice`
|
|
126
|
+
- Produces: `REPLProps` 增加 `updateNotice?: Promise<string | null>`;App 传 `autoUpdateNotice()`
|
|
127
|
+
- [ ] **Step 1: 实现** — cli.ts REPL 分支(`await import('./main.js')` 前)调 `startAutoUpdate()`(acp/upgrade 分支不调);main.tsx 传入;REPL 挂载时 `void updateNotice?.then(msg => { if (msg) { addHistory({input:'', output: msg}); dragFlush(); } })`,deps `[updateNotice]`
|
|
128
|
+
- [ ] **Step 2: 验证** — `bun run typecheck`;`bun test` 全绿
|
|
129
|
+
- [ ] **Step 3: Commit** — `feat: wire auto-update banner into the REPL`
|
|
130
|
+
|
|
131
|
+
### Task 6: E2E 验证与全局重装
|
|
132
|
+
|
|
133
|
+
**Files:** 无新改动(验证任务)
|
|
134
|
+
|
|
135
|
+
- [ ] **Step 1: 节流验证** — 临时配置 `lastCheck` = 当前时间 → `timeout 15 bun bin/transcode.ts` 启动退出,确认无 npm 安装输出、`lastCheck` 未变
|
|
136
|
+
- [ ] **Step 2: 钉版本验证** — 临时配置 `{"target":"0.3.0","lastCheck":0}`,`TRANSCODE_CONFIG_PATH=… timeout 60 bun bin/transcode.ts`,确认横幅与全局降至 0.3.0(`transcode --version`);随后 `npm i -g .` 恢复开发版本
|
|
137
|
+
- [ ] **Step 3: 断网/强制关验证** — `TRANSCODE_SKIP_UPDATE=1` 启动无更新动作;配置 enabled:false 同样静默
|
|
138
|
+
- [ ] **Step 4: 全局重装收尾** — `npm i -g .`;`bun test` + `bun run typecheck` 最后确认
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# transcode 自动更新 — 设计
|
|
2
|
+
|
|
3
|
+
日期:2026-11-21 · 状态:待确认
|
|
4
|
+
|
|
5
|
+
## 意图
|
|
6
|
+
|
|
7
|
+
用户启动 transcode 时自动保持 npm 全局安装为最新(或配置指定的版本),无需手动 `transcode upgrade`。默认启用,可在 `~/.transcode.json` 关闭或钉住版本。
|
|
8
|
+
|
|
9
|
+
## 现有基础
|
|
10
|
+
|
|
11
|
+
`src/upgrade.ts` 已有手动 `transcode upgrade`:查 npm 官方源(防镜像假升级)、版本比对、`npm i -g` 安装、仓库开发安装识别。本设计将其拆出可复用的检查/安装原语。
|
|
12
|
+
|
|
13
|
+
## 行为设计(已确认:静默安装)
|
|
14
|
+
|
|
15
|
+
**触发**:仅 REPL 启动路径(`cli.ts` 进 REPL 前);`acp` / `--version` / `help` / `upgrade` 子命令不触发。
|
|
16
|
+
|
|
17
|
+
**流程**:后台异步执行,绝不阻塞 REPL 启动——
|
|
18
|
+
1. 读取配置,未启用 → 退出(静默)
|
|
19
|
+
2. 节流:距上次检查 <24h → 退出(`TRANSCODE_UPDATE_INTERVAL_HOURS` 可调,`TRANSCODE_SKIP_UPDATE=1` 强制关闭)
|
|
20
|
+
3. 仓库开发安装(realpath 不在 npm root 下)→ 静默退出
|
|
21
|
+
4. 查目标版本:`target` 缺省 = `latest`;指定版本(如 `0.3.0`)= 钉住该版本(含降级)
|
|
22
|
+
5. 目标 ≠ 当前版本 → 静默 `npm i -g @trans-ai/trans-code@<target>`(官方源)
|
|
23
|
+
6. 完成/失败均不中断会话;成功后 REPL 内横幅一条:`⟳ 已自动更新 0.4.0 → 0.4.1,重启 transcode 生效`;失败静默(`TRANSCODE_DEBUG_UPGRADE=1` 可见原因)
|
|
24
|
+
7. 写回 `lastCheck` 时间戳
|
|
25
|
+
|
|
26
|
+
当前会话继续运行旧代码(新版本下次启动生效),避免运行中换文件。
|
|
27
|
+
|
|
28
|
+
## 配置(`~/.transcode.json`)
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"autoUpdate": {
|
|
33
|
+
"enabled": true, // 缺省 true;"autoUpdate": false 为关闭简写
|
|
34
|
+
"target": "latest", // 或 "0.3.0" 钉住指定版本(含降级)
|
|
35
|
+
"lastCheck": 0 // 内部节流缓存,epoch ms
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 手动命令
|
|
41
|
+
|
|
42
|
+
`transcode upgrade [version]` — 带版本号参数时安装指定版本(一次性,不写 target),其余行为不变。
|
|
43
|
+
|
|
44
|
+
## 模块划分
|
|
45
|
+
|
|
46
|
+
- `config.ts`:`TranscodeConfig.autoUpdate?: boolean | { enabled?; target?; lastCheck? }` + `normalizeAutoUpdate()` 纯函数(false/对象/缺省 → 规范形)
|
|
47
|
+
- `upgrade.ts`:`planAutoUpdate()` 纯函数(输入 current/latest/config/now → 输出 skip 原因或 install spec);`startAutoUpdate()` 后台执行并返回 notice Promise;`runUpgrade(target?)` 接受版本参数
|
|
48
|
+
- `cli.ts`:REPL 分支先 `startAutoUpdate()`,notice 以 Promise 传入 REPL,完成时 `addHistory` 横幅
|
|
49
|
+
- `main.tsx` / `REPL.tsx`:接受可选 notice prop,resolve 后展示
|
|
50
|
+
|
|
51
|
+
## 非目标
|
|
52
|
+
|
|
53
|
+
- 不做定时器/会话中周期检查(仅启动时)
|
|
54
|
+
- 不做更新日志/变更说明展示
|
|
55
|
+
- 不覆盖 `TRANSCODE_SKIP_UPDATE=1`
|
|
56
|
+
|
|
57
|
+
## 测试(TDD)
|
|
58
|
+
|
|
59
|
+
- `normalizeAutoUpdate`:false / 对象 / 缺省 / 非法值 → 规范形(enabled 默认 true)
|
|
60
|
+
- `planAutoUpdate`:未启用、节流中、已是目标版本、钉版本降级、升级、查不到版本 → 各自 action
|
|
61
|
+
- 现有 186+ 测试保持全绿
|
package/package.json
CHANGED
package/src/agent/loop.test.ts
CHANGED
|
@@ -50,7 +50,11 @@ function scriptedModel(steps: ScriptStep[]): BaseChatModel {
|
|
|
50
50
|
})();
|
|
51
51
|
},
|
|
52
52
|
};
|
|
53
|
-
|
|
53
|
+
const model = {
|
|
54
|
+
bindTools: () => runnable,
|
|
55
|
+
invoke: async () => ({ content: '摘要:任务是更新 README,已完成探索,接下来写入。' }),
|
|
56
|
+
};
|
|
57
|
+
return model as unknown as BaseChatModel;
|
|
54
58
|
}
|
|
55
59
|
|
|
56
60
|
const fakeTool: AgentTool = {
|
|
@@ -203,6 +207,93 @@ describe('runAgentLoop', () => {
|
|
|
203
207
|
expect(content[1]?.type).toBe('image_url');
|
|
204
208
|
});
|
|
205
209
|
|
|
210
|
+
test('auto-compacts the conversation when the char budget is exceeded', async () => {
|
|
211
|
+
process.env.TRANSCODE_COMPACT_CHARS = '1200';
|
|
212
|
+
const events: AgentEvent[] = [];
|
|
213
|
+
const chatty: AgentTool = {
|
|
214
|
+
...fakeTool,
|
|
215
|
+
isMutating: false,
|
|
216
|
+
async execute() {
|
|
217
|
+
return `large chunk ${'x'.repeat(400)} done`;
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const result = await runAgentLoop({
|
|
222
|
+
model: scriptedModel(
|
|
223
|
+
Array.from({ length: 10 }, (_, i) => ({ tool: 'fake' as const, args: JSON.stringify({ n: i }) })),
|
|
224
|
+
),
|
|
225
|
+
cwd: '/tmp',
|
|
226
|
+
messages: [],
|
|
227
|
+
systemPrompt: 'test',
|
|
228
|
+
tools: [chatty],
|
|
229
|
+
onEvent: (event) => events.push(event),
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
const text = events
|
|
234
|
+
.filter((event) => event.type === 'text')
|
|
235
|
+
.map((event) => (event as { text: string }).text)
|
|
236
|
+
.join('');
|
|
237
|
+
expect(text).toContain('自动压缩');
|
|
238
|
+
expect(
|
|
239
|
+
result.messages.some((message) =>
|
|
240
|
+
message.content.toString().includes('[conversation summary]'),
|
|
241
|
+
),
|
|
242
|
+
).toBe(true);
|
|
243
|
+
// The compacted history must not start with an orphaned tool message.
|
|
244
|
+
expect(result.messages[1]?.getType()).not.toBe('tool');
|
|
245
|
+
} finally {
|
|
246
|
+
delete process.env.TRANSCODE_COMPACT_CHARS;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test('plan mode denies mutations and allows read-only exploration', async () => {
|
|
251
|
+
let writes = 0;
|
|
252
|
+
let reads = 0;
|
|
253
|
+
const tools: AgentTool[] = [
|
|
254
|
+
{
|
|
255
|
+
...fakeTool,
|
|
256
|
+
name: 'write_file',
|
|
257
|
+
isMutating: true,
|
|
258
|
+
async execute() {
|
|
259
|
+
writes++;
|
|
260
|
+
return 'written';
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
...fakeTool,
|
|
265
|
+
name: 'read_file',
|
|
266
|
+
isMutating: false,
|
|
267
|
+
async execute() {
|
|
268
|
+
reads++;
|
|
269
|
+
return 'content';
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
];
|
|
273
|
+
|
|
274
|
+
const events: AgentEvent[] = [];
|
|
275
|
+
const result = await runAgentLoop({
|
|
276
|
+
model: scriptedModel([
|
|
277
|
+
{ tool: 'read_file', args: '{"path":"a"}' },
|
|
278
|
+
{ tool: 'write_file', args: '{"path":"a"}' },
|
|
279
|
+
]),
|
|
280
|
+
cwd: '/tmp',
|
|
281
|
+
messages: [],
|
|
282
|
+
systemPrompt: 'test',
|
|
283
|
+
tools,
|
|
284
|
+
planMode: true,
|
|
285
|
+
onEvent: (event) => events.push(event),
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
expect(result.stopReason).toBe('end_turn');
|
|
289
|
+
expect(reads).toBe(1);
|
|
290
|
+
expect(writes).toBe(0);
|
|
291
|
+
const denied = events.find(
|
|
292
|
+
(event) => event.type === 'tool_result' && event.output.includes('Plan mode'),
|
|
293
|
+
);
|
|
294
|
+
expect(denied).toBeDefined();
|
|
295
|
+
});
|
|
296
|
+
|
|
206
297
|
test('mutating tools without isReadOnly still request permission', async () => {
|
|
207
298
|
let permissionAsked = 0;
|
|
208
299
|
await runAgentLoop({
|
package/src/agent/loop.ts
CHANGED
|
@@ -72,6 +72,8 @@ export interface AgentLoopOptions {
|
|
|
72
72
|
requestPermission?: RequestPermission;
|
|
73
73
|
/** Session state shared across tool calls (shell cwd, read files). Created when absent. */
|
|
74
74
|
toolSession?: ToolSession;
|
|
75
|
+
/** Plan mode: read-only exploration; mutating tools are denied with guidance. */
|
|
76
|
+
planMode?: boolean;
|
|
75
77
|
/** Vision proxy override (tests). Default: routing.vision → askRole('vision'). */
|
|
76
78
|
describeImages?: (images: Array<{ data: string; mediaType: string }>) => Promise<string>;
|
|
77
79
|
}
|
|
@@ -245,6 +247,56 @@ async function runMockTurn(
|
|
|
245
247
|
return 'end_turn';
|
|
246
248
|
}
|
|
247
249
|
|
|
250
|
+
const COMPACT_DEFAULT_CHARS = 200_000;
|
|
251
|
+
|
|
252
|
+
function estimateMessagesChars(messages: BaseMessage[]): number {
|
|
253
|
+
return messages.reduce(
|
|
254
|
+
(sum, message) => sum + JSON.stringify(message.content ?? '').length + 200,
|
|
255
|
+
0,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Auto-compaction (Claude Code's autoCompact, ported): when the estimated
|
|
261
|
+
* conversation size exceeds the char budget, summarize the history with the
|
|
262
|
+
* same model and keep the summary plus a short recent tail. Tool messages
|
|
263
|
+
* at the tail head are dropped so providers never see orphaned tool calls.
|
|
264
|
+
*/
|
|
265
|
+
async function compactMessages(
|
|
266
|
+
model: BaseChatModel,
|
|
267
|
+
messages: BaseMessage[],
|
|
268
|
+
systemPrompt: string,
|
|
269
|
+
): Promise<BaseMessage[]> {
|
|
270
|
+
const nonSystem = messages.filter((message) => message.getType() !== 'system');
|
|
271
|
+
const transcript = nonSystem
|
|
272
|
+
.map((message) => `${message.getType()}: ${textFromContent(message.content)}`)
|
|
273
|
+
.join('\n')
|
|
274
|
+
.slice(0, 150_000);
|
|
275
|
+
const response = await model.invoke(
|
|
276
|
+
'Summarize this agent conversation so work can continue after compaction. ' +
|
|
277
|
+
'Include: the user task, key decisions, files read/modified, current state, next steps. ' +
|
|
278
|
+
'Be concise and factual.\n\n' +
|
|
279
|
+
transcript,
|
|
280
|
+
);
|
|
281
|
+
const summary = textFromContent((response as { content: unknown }).content);
|
|
282
|
+
|
|
283
|
+
const system = messages.find((message) => message.getType() === 'system') ??
|
|
284
|
+
new SystemMessage(systemPrompt);
|
|
285
|
+
const tail = nonSystem.slice(-4);
|
|
286
|
+
while (tail.length > 0 && tail[0]!.getType() === 'tool') tail.shift();
|
|
287
|
+
|
|
288
|
+
return [
|
|
289
|
+
system,
|
|
290
|
+
new (await import('@langchain/core/messages')).HumanMessage(
|
|
291
|
+
`[conversation summary]\n${summary}`,
|
|
292
|
+
),
|
|
293
|
+
new (await import('@langchain/core/messages')).AIMessage(
|
|
294
|
+
'Continuing with the summarized context.',
|
|
295
|
+
),
|
|
296
|
+
...tail,
|
|
297
|
+
];
|
|
298
|
+
}
|
|
299
|
+
|
|
248
300
|
export async function runAgentLoop(
|
|
249
301
|
options: AgentLoopOptions,
|
|
250
302
|
): Promise<AgentLoopResult> {
|
|
@@ -298,6 +350,19 @@ export async function runAgentLoop(
|
|
|
298
350
|
for (let turn = 0; turn < maxTurns; turn++) {
|
|
299
351
|
if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
|
|
300
352
|
|
|
353
|
+
// Auto-compaction before the request when over budget.
|
|
354
|
+
const compactChars = Number(process.env.TRANSCODE_COMPACT_CHARS ?? COMPACT_DEFAULT_CHARS);
|
|
355
|
+
if (compactChars > 0 && estimateMessagesChars(messages) > compactChars) {
|
|
356
|
+
await options.onEvent({ type: 'text', text: '\n⚠ 上下文接近上限,自动压缩历史…\n' });
|
|
357
|
+
try {
|
|
358
|
+
const compacted = await compactMessages(options.model, messages, options.systemPrompt);
|
|
359
|
+
messages.length = 0;
|
|
360
|
+
messages.push(...compacted);
|
|
361
|
+
} catch {
|
|
362
|
+
// Compaction failed (e.g. provider error) — continue un-compacted.
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
301
366
|
const partials = new Map<number, PartialToolCall>();
|
|
302
367
|
let text = '';
|
|
303
368
|
let finalChunk: AIMessageChunk | undefined;
|
|
@@ -360,6 +425,14 @@ export async function runAgentLoop(
|
|
|
360
425
|
result = { ok: false, output: `Unknown tool: ${call.name}` };
|
|
361
426
|
} else if (occurrences >= 3) {
|
|
362
427
|
result = { ok: false, output: `Error: ${REPEAT_GUIDANCE}` };
|
|
428
|
+
} else if (options.planMode === true && tool.isMutating && tool.isReadOnly?.(input) !== true) {
|
|
429
|
+
result = {
|
|
430
|
+
ok: false,
|
|
431
|
+
output:
|
|
432
|
+
'Plan mode is read-only: mutations are disabled. Finish exploring and output the ' +
|
|
433
|
+
'numbered implementation plan (end with the line PLAN READY). The user will approve ' +
|
|
434
|
+
'it before any changes are made.',
|
|
435
|
+
};
|
|
363
436
|
} else {
|
|
364
437
|
const readOnly = tool.isReadOnly?.(input) === true;
|
|
365
438
|
const needsPermission = tool.isMutating && !readOnly;
|
|
@@ -381,6 +454,7 @@ export async function runAgentLoop(
|
|
|
381
454
|
signal: options.signal,
|
|
382
455
|
session: toolSession,
|
|
383
456
|
requestPermission: options.requestPermission,
|
|
457
|
+
emit: options.onEvent as (event: { type: 'tool_call' }) => void,
|
|
384
458
|
})
|
|
385
459
|
: { ok: false, output: 'Permission denied by the client.' };
|
|
386
460
|
|
|
@@ -2,10 +2,51 @@ import { afterEach, describe, expect, test } from 'bun:test';
|
|
|
2
2
|
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { bashTool } from './bash.js';
|
|
5
|
+
import { bashTool, bashOutputTool } from './bash.js';
|
|
6
6
|
import { createToolSession, type ToolSession } from './session.js';
|
|
7
7
|
import type { ToolContext } from './types.js';
|
|
8
8
|
|
|
9
|
+
describe('background bash', () => {
|
|
10
|
+
test('run_in_background returns immediately; bash_output waits and reads the log', async () => {
|
|
11
|
+
const session = createToolSession(workspace());
|
|
12
|
+
const start = await bashTool.execute(
|
|
13
|
+
{ command: 'printf bg-done-XYZ', run_in_background: true },
|
|
14
|
+
ctx(session),
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
expect(start).toMatch(/bg-\d+ started/);
|
|
18
|
+
const id = /bg-\d+/.exec(start)![0]!;
|
|
19
|
+
|
|
20
|
+
const output = await bashOutputTool.execute(
|
|
21
|
+
{ task_id: id, wait: true },
|
|
22
|
+
ctx(session),
|
|
23
|
+
);
|
|
24
|
+
expect(output).toContain('bg-done-XYZ');
|
|
25
|
+
expect(output).toMatch(/exited/);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('bash_output without a task_id lists the background tasks', async () => {
|
|
29
|
+
const session = createToolSession(workspace());
|
|
30
|
+
const start = await bashTool.execute(
|
|
31
|
+
{ command: 'sleep 2', run_in_background: true },
|
|
32
|
+
ctx(session),
|
|
33
|
+
);
|
|
34
|
+
const id = /bg-\d+/.exec(start)![0]!;
|
|
35
|
+
|
|
36
|
+
const listing = await bashOutputTool.execute({}, ctx(session));
|
|
37
|
+
expect(listing).toContain(id);
|
|
38
|
+
expect(listing).toContain('sleep 2');
|
|
39
|
+
expect(listing).toMatch(/running/);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('bash_output rejects unknown ids', async () => {
|
|
43
|
+
const session = createToolSession(workspace());
|
|
44
|
+
await expect(
|
|
45
|
+
bashOutputTool.execute({ task_id: 'bg-999' }, ctx(session)),
|
|
46
|
+
).rejects.toThrow(/bg-999/);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
9
50
|
describe('bash tool wiring', () => {
|
|
10
51
|
test('description uses claudecode-style hard wording against file dumps', () => {
|
|
11
52
|
const d = bashTool.description;
|