@trans-ai/trans-code 0.3.0 → 0.4.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/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 +2 -0
- package/src/commands.ts +18 -0
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.ts +34 -0
- package/src/screens/REPL.tsx +256 -27
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- 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
|
|
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;
|
package/src/agent/tools/bash.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { promises as fs } from 'node:fs';
|
|
3
|
-
import { readFileSync, unlinkSync } from 'node:fs';
|
|
4
|
-
import { tmpdir } from 'node:os';
|
|
3
|
+
import { existsSync, readFileSync, unlinkSync } from 'node:fs';
|
|
4
|
+
import { homedir, tmpdir } from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import type { AgentTool } from './types.js';
|
|
8
8
|
import type { ToolSession } from './session.js';
|
|
9
9
|
import { isReadOnlyCommand } from './read-only.js';
|
|
10
|
+
import { fromPosixPath, toPosixPath } from './shell-paths.js';
|
|
10
11
|
|
|
11
12
|
const MAX_BASH_OUTPUT = 30_000;
|
|
12
13
|
const TRUNCATE_HEAD = 15_000;
|
|
@@ -21,18 +22,63 @@ function shellQuote(value: string): string {
|
|
|
21
22
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
/** Git Bash probe locations for Windows (Claude Code's list). */
|
|
26
|
+
const GIT_BASH_CANDIDATES = [
|
|
27
|
+
'C:\\Program Files\\Git\\bin\\bash.exe',
|
|
28
|
+
'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
|
|
29
|
+
`${process.env.LOCALAPPDATA ?? ''}\\Programs\\Git\\bin\\bash.exe`,
|
|
30
|
+
].filter((candidate) => candidate.length > 0);
|
|
31
|
+
|
|
32
|
+
/** PowerShell probe locations (pwsh 7 preferred over Windows PowerShell 5). */
|
|
33
|
+
const POWERSHELL_CANDIDATES = [
|
|
34
|
+
'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
|
|
35
|
+
`${process.env.ProgramFiles ?? 'C:\\Program Files'}\\PowerShell\\7\\pwsh.exe`,
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/** Pure, testable shell resolution: override → SHELL → Git Bash → PowerShell → /bin/bash. */
|
|
39
|
+
export function detectShellWith(
|
|
40
|
+
platform: NodeJS.Platform,
|
|
41
|
+
exists: (file: string) => boolean,
|
|
42
|
+
env: { TRANSCODE_SHELL?: string; SHELL?: string },
|
|
43
|
+
): string {
|
|
44
|
+
const override = env.TRANSCODE_SHELL?.trim();
|
|
45
|
+
if (override) return override;
|
|
46
|
+
|
|
47
|
+
const envShell = env.SHELL?.trim() ?? '';
|
|
48
|
+
if (envShell.includes('bash') || envShell.includes('zsh')) return envShell;
|
|
49
|
+
|
|
50
|
+
if (platform === 'win32') {
|
|
51
|
+
const gitBash = GIT_BASH_CANDIDATES.find((candidate) => exists(candidate));
|
|
52
|
+
if (gitBash) return gitBash;
|
|
53
|
+
const pwsh = POWERSHELL_CANDIDATES.find((candidate) => exists(candidate));
|
|
54
|
+
if (pwsh) return pwsh;
|
|
55
|
+
// powershell.exe ships with every Windows and resolves via PATH.
|
|
56
|
+
return 'powershell.exe';
|
|
57
|
+
}
|
|
27
58
|
return '/bin/bash';
|
|
28
59
|
}
|
|
29
60
|
|
|
61
|
+
function detectShell(): string {
|
|
62
|
+
return detectShellWith(process.platform, existsSync, process.env);
|
|
63
|
+
}
|
|
64
|
+
|
|
30
65
|
function isZsh(shell: string): boolean {
|
|
31
66
|
return shell.includes('zsh');
|
|
32
67
|
}
|
|
33
68
|
|
|
69
|
+
export function isPowerShell(shell: string): boolean {
|
|
70
|
+
return /(?:^|[\\/])(?:pwsh|powershell)(?:\.exe)?$/i.test(shell.trim());
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** PowerShell single-quoting: only ' needs doubling. */
|
|
74
|
+
export function psQuote(value: string): string {
|
|
75
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
76
|
+
}
|
|
77
|
+
|
|
34
78
|
function rcFileFor(shell: string): string {
|
|
35
|
-
|
|
79
|
+
// $HOME first (POSIX convention, also overridable in tests), os.homedir()
|
|
80
|
+
// as the Windows fallback (USERPROFILE), tmpdir as the last resort.
|
|
81
|
+
const home = process.env.HOME?.trim() || homedir() || tmpdir();
|
|
36
82
|
return isZsh(shell) ? path.join(home, '.zshrc') : path.join(home, '.bashrc');
|
|
37
83
|
}
|
|
38
84
|
|
|
@@ -69,8 +115,8 @@ function snapshotScript(shell: string, snapshotPath: string, rcFile: string, rcE
|
|
|
69
115
|
? ''
|
|
70
116
|
: 'echo "shopt -s expand_aliases" >> "$SNAPSHOT_FILE"';
|
|
71
117
|
|
|
72
|
-
return `SNAPSHOT_FILE=${shellQuote(snapshotPath)}
|
|
73
|
-
${rcExists ? `source ${shellQuote(rcFile)} < /dev/null` : '# No user config file to source'}
|
|
118
|
+
return `SNAPSHOT_FILE=${shellQuote(toPosixPath(snapshotPath))}
|
|
119
|
+
${rcExists ? `source ${shellQuote(toPosixPath(rcFile))} < /dev/null` : '# No user config file to source'}
|
|
74
120
|
|
|
75
121
|
echo "# Snapshot file" >| "$SNAPSHOT_FILE"
|
|
76
122
|
|
|
@@ -117,6 +163,7 @@ async function createSnapshot(shell: string): Promise<string | undefined> {
|
|
|
117
163
|
['-l', '-c', snapshotScript(shell, snapshotPath, rcFile, rcExists)],
|
|
118
164
|
{
|
|
119
165
|
stdio: 'ignore',
|
|
166
|
+
windowsHide: true,
|
|
120
167
|
env: { ...process.env, SHELL: shell, GIT_EDITOR: 'true', TRANSCODE: '1' },
|
|
121
168
|
},
|
|
122
169
|
);
|
|
@@ -180,17 +227,27 @@ async function resolveSpawnCwd(session: ToolSession): Promise<string> {
|
|
|
180
227
|
/**
|
|
181
228
|
* Wraps the user command so the snapshot is sourced, extended globs are
|
|
182
229
|
* disabled (security), and the physical cwd is captured even when the
|
|
183
|
-
* command fails.
|
|
230
|
+
* command fails. PowerShell runs an analogous wrapper: Invoke-Expression
|
|
231
|
+
* instead of eval, Out-File instead of pwd -P >|, no snapshot (NoProfile).
|
|
184
232
|
*/
|
|
185
|
-
function buildWrappedCommand(
|
|
233
|
+
export function buildWrappedCommand(
|
|
186
234
|
command: string,
|
|
187
235
|
shell: string,
|
|
188
236
|
snapshotPath: string | undefined,
|
|
189
237
|
cwdFilePath: string,
|
|
190
238
|
): string {
|
|
239
|
+
if (isPowerShell(shell)) {
|
|
240
|
+
return [
|
|
241
|
+
`Invoke-Expression ${psQuote(command)}`,
|
|
242
|
+
'$__transcode_rc = if ($?) { 0 } else { 1 }',
|
|
243
|
+
`try { (Get-Location).ProviderPath | Out-File -FilePath ${psQuote(cwdFilePath)} -Encoding ascii } catch {}`,
|
|
244
|
+
'exit $__transcode_rc',
|
|
245
|
+
].join('\n');
|
|
246
|
+
}
|
|
247
|
+
|
|
191
248
|
const parts: string[] = [];
|
|
192
249
|
if (snapshotPath) {
|
|
193
|
-
parts.push(`source ${shellQuote(snapshotPath)} 2>/dev/null || true`);
|
|
250
|
+
parts.push(`source ${shellQuote(toPosixPath(snapshotPath))} 2>/dev/null || true`);
|
|
194
251
|
}
|
|
195
252
|
parts.push(
|
|
196
253
|
isZsh(shell)
|
|
@@ -199,13 +256,39 @@ function buildWrappedCommand(
|
|
|
199
256
|
);
|
|
200
257
|
parts.push(`eval ${shellQuote(command)}`);
|
|
201
258
|
parts.push('__transcode_rc=$?');
|
|
202
|
-
parts.push(`pwd -P >| ${shellQuote(cwdFilePath)}`);
|
|
259
|
+
parts.push(`pwd -P >| ${shellQuote(toPosixPath(cwdFilePath))}`);
|
|
203
260
|
parts.push('exit $__transcode_rc');
|
|
204
261
|
return parts.join('\n');
|
|
205
262
|
}
|
|
206
263
|
|
|
264
|
+
/** Windows kills the tree via taskkill; POSIX uses the process-group kill. */
|
|
265
|
+
export function killTreeCommand(
|
|
266
|
+
pid: number,
|
|
267
|
+
platform: NodeJS.Platform,
|
|
268
|
+
): { file: string; args: string[] } | null {
|
|
269
|
+
if (platform !== 'win32') return null;
|
|
270
|
+
return { file: 'taskkill', args: ['/pid', String(pid), '/T', '/F'] };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Spawn argv for the configured shell (testable). */
|
|
274
|
+
export function shellSpawnArgs(
|
|
275
|
+
shell: string,
|
|
276
|
+
snapshotPath: string | undefined,
|
|
277
|
+
wrapped: string,
|
|
278
|
+
): string[] {
|
|
279
|
+
if (isPowerShell(shell)) {
|
|
280
|
+
return ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', wrapped];
|
|
281
|
+
}
|
|
282
|
+
return snapshotPath ? ['-c', wrapped] : ['-l', '-c', wrapped];
|
|
283
|
+
}
|
|
284
|
+
|
|
207
285
|
function killProcessGroup(pid: number | undefined, signal: NodeJS.Signals): void {
|
|
208
286
|
if (pid === undefined) return;
|
|
287
|
+
const tree = killTreeCommand(pid, process.platform);
|
|
288
|
+
if (tree) {
|
|
289
|
+
spawn(tree.file, tree.args, { stdio: 'ignore', windowsHide: true });
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
209
292
|
try {
|
|
210
293
|
process.kill(-pid, signal);
|
|
211
294
|
} catch {
|
|
@@ -213,6 +296,62 @@ function killProcessGroup(pid: number | undefined, signal: NodeJS.Signals): void
|
|
|
213
296
|
}
|
|
214
297
|
}
|
|
215
298
|
|
|
299
|
+
function processAlive(pid: number): boolean {
|
|
300
|
+
if (pid <= 0) return false;
|
|
301
|
+
try {
|
|
302
|
+
process.kill(pid, 0);
|
|
303
|
+
return true;
|
|
304
|
+
} catch {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export const bashOutputTool: AgentTool = {
|
|
310
|
+
name: 'bash_output',
|
|
311
|
+
description:
|
|
312
|
+
'Read output of background bash tasks (started with bash run_in_background). ' +
|
|
313
|
+
'Without task_id, lists all background tasks with running/exited status. ' +
|
|
314
|
+
'With wait=true, blocks up to 5s for the task to finish first.',
|
|
315
|
+
kind: 'read',
|
|
316
|
+
isMutating: false,
|
|
317
|
+
schema: z.object({
|
|
318
|
+
task_id: z.string().nullable().optional().describe('Background task id (bg-N)'),
|
|
319
|
+
wait: z.boolean().nullable().optional().describe('Wait up to 5s for the task to exit'),
|
|
320
|
+
}),
|
|
321
|
+
title: (input) => `bg output: ${String(input.task_id ?? 'list')}`,
|
|
322
|
+
async execute(input, ctx) {
|
|
323
|
+
const tasks = ctx.session.bgTasks;
|
|
324
|
+
|
|
325
|
+
if (!input.task_id) {
|
|
326
|
+
if (tasks.size === 0) return 'No background tasks.';
|
|
327
|
+
return [...tasks.values()]
|
|
328
|
+
.map(
|
|
329
|
+
(task) =>
|
|
330
|
+
`${task.id} ${processAlive(task.pid) ? 'running' : 'exited'} — ${task.command.slice(0, 80)}`,
|
|
331
|
+
)
|
|
332
|
+
.join('\n');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const id = String(input.task_id);
|
|
336
|
+
const task = tasks.get(id);
|
|
337
|
+
if (!task) {
|
|
338
|
+
throw new Error(`Unknown task_id ${id}. Known: ${[...tasks.keys()].join(', ') || '(none)'}`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (input.wait === true) {
|
|
342
|
+
const deadline = Date.now() + 5_000;
|
|
343
|
+
while (processAlive(task.pid) && Date.now() < deadline) {
|
|
344
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const log = await fs.readFile(task.logPath, 'utf8').catch(() => '');
|
|
349
|
+
const lines = log.split('\n');
|
|
350
|
+
const tail = lines.slice(-200).join('\n');
|
|
351
|
+
return `${processAlive(task.pid) ? 'running' : 'exited'} ${task.id} (pid ${task.pid})\n${tail || '(no output yet)'}`;
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
|
|
216
355
|
export const bashTool: AgentTool = {
|
|
217
356
|
name: 'bash',
|
|
218
357
|
description:
|
|
@@ -236,6 +375,11 @@ export const bashTool: AgentTool = {
|
|
|
236
375
|
command: z.string().describe('Shell command to run'),
|
|
237
376
|
timeout_ms: z.number().int().min(1000).max(600_000).nullable().optional().describe('Timeout in ms'),
|
|
238
377
|
description: z.string().nullable().optional().describe('Short description of what the command does'),
|
|
378
|
+
run_in_background: z
|
|
379
|
+
.boolean()
|
|
380
|
+
.nullable()
|
|
381
|
+
.optional()
|
|
382
|
+
.describe('Run detached; returns a task id immediately. Read output later via bash_output'),
|
|
239
383
|
}),
|
|
240
384
|
title: (input) => {
|
|
241
385
|
const command = String(input.command ?? '');
|
|
@@ -248,7 +392,9 @@ export const bashTool: AgentTool = {
|
|
|
248
392
|
|
|
249
393
|
const session = ctx.session;
|
|
250
394
|
const shell = detectShell();
|
|
251
|
-
const snapshotPath =
|
|
395
|
+
const snapshotPath = isPowerShell(shell)
|
|
396
|
+
? undefined
|
|
397
|
+
: await getSnapshot(session, shell);
|
|
252
398
|
const cwd = await resolveSpawnCwd(session);
|
|
253
399
|
const cwdFilePath = path.join(
|
|
254
400
|
tmpdir(),
|
|
@@ -256,12 +402,53 @@ export const bashTool: AgentTool = {
|
|
|
256
402
|
);
|
|
257
403
|
const wrapped = buildWrappedCommand(command, shell, snapshotPath, cwdFilePath);
|
|
258
404
|
|
|
405
|
+
// Background mode: spawn detached with output to a log file, return now.
|
|
406
|
+
if (input.run_in_background === true) {
|
|
407
|
+
const id = `bg-${session.bgTasks.size + 1}`;
|
|
408
|
+
const logPath = path.join(
|
|
409
|
+
tmpdir(),
|
|
410
|
+
`transcode-bg-${process.pid}-${session.bgTasks.size + 1}.log`,
|
|
411
|
+
);
|
|
412
|
+
const log = await fs.open(logPath, 'w');
|
|
413
|
+
const child = spawn(shell, shellSpawnArgs(shell, snapshotPath, wrapped), {
|
|
414
|
+
cwd,
|
|
415
|
+
env: { ...process.env, SHELL: shell, GIT_EDITOR: 'true', TRANSCODE: '1' },
|
|
416
|
+
stdio: ['ignore', log.fd, log.fd],
|
|
417
|
+
detached: true,
|
|
418
|
+
windowsHide: true,
|
|
419
|
+
});
|
|
420
|
+
session.bgTasks.set(id, {
|
|
421
|
+
id,
|
|
422
|
+
pid: child.pid ?? -1,
|
|
423
|
+
logPath,
|
|
424
|
+
command,
|
|
425
|
+
startedAt: Date.now(),
|
|
426
|
+
});
|
|
427
|
+
child.on('close', (code) => {
|
|
428
|
+
void fs.appendFile(logPath, `\n[exit] code=${code ?? 'null'}\n`).catch(() => {});
|
|
429
|
+
try {
|
|
430
|
+
const newCwd = fromPosixPath(readFileSync(cwdFilePath, 'utf8').trim());
|
|
431
|
+
if (newCwd) session.cwd = newCwd;
|
|
432
|
+
unlinkSync(cwdFilePath);
|
|
433
|
+
} catch {
|
|
434
|
+
// best effort
|
|
435
|
+
}
|
|
436
|
+
void log.close().catch(() => {});
|
|
437
|
+
});
|
|
438
|
+
child.unref();
|
|
439
|
+
return (
|
|
440
|
+
`Background task ${id} started (pid ${child.pid}). ` +
|
|
441
|
+
`Read its output with bash_output using task_id "${id}" (wait: true to block briefly).`
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
|
|
259
445
|
return await new Promise<string>((resolve) => {
|
|
260
|
-
const child = spawn(shell,
|
|
446
|
+
const child = spawn(shell, shellSpawnArgs(shell, snapshotPath, wrapped), {
|
|
261
447
|
cwd,
|
|
262
448
|
env: { ...process.env, SHELL: shell, GIT_EDITOR: 'true', TRANSCODE: '1' },
|
|
263
449
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
264
450
|
detached: true,
|
|
451
|
+
windowsHide: true,
|
|
265
452
|
});
|
|
266
453
|
|
|
267
454
|
let stdout = '';
|
|
@@ -299,7 +486,7 @@ export const bashTool: AgentTool = {
|
|
|
299
486
|
|
|
300
487
|
// Sync read so callers awaiting execute() see the updated cwd immediately.
|
|
301
488
|
try {
|
|
302
|
-
const newCwd = readFileSync(cwdFilePath, 'utf8').trim();
|
|
489
|
+
const newCwd = fromPosixPath(readFileSync(cwdFilePath, 'utf8').trim());
|
|
303
490
|
if (newCwd) session.cwd = newCwd;
|
|
304
491
|
} catch {
|
|
305
492
|
// Command exited before pwd ran (e.g. `exit`); keep the previous cwd.
|