@trans-ai/trans-code 0.2.4 → 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 +68 -17
- package/package.json +1 -1
- package/src/acp/session.ts +4 -1
- package/src/agent/loop.test.ts +337 -1
- package/src/agent/loop.ts +166 -2
- package/src/agent/system-prompt.test.ts +24 -1
- package/src/agent/system-prompt.ts +21 -0
- package/src/agent/tools/ask-model.test.ts +54 -0
- package/src/agent/tools/ask-model.ts +44 -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 +157 -0
- package/src/agent/tools/dispatch.ts +151 -0
- package/src/agent/tools/files.test.ts +96 -0
- package/src/agent/tools/files.ts +111 -29
- package/src/agent/tools/fs-utils.ts +40 -0
- package/src/agent/tools/index.ts +29 -2
- package/src/agent/tools/powershell.test.ts +61 -0
- package/src/agent/tools/read-only.ts +16 -0
- package/src/agent/tools/search.test.ts +55 -1
- package/src/agent/tools/search.ts +56 -8
- package/src/agent/tools/session.ts +21 -0
- package/src/agent/tools/shell-paths.test.ts +65 -0
- package/src/agent/tools/shell-paths.ts +19 -0
- package/src/agent/tools/todo.test.ts +54 -0
- package/src/agent/tools/todo.ts +47 -0
- package/src/agent/tools/types.ts +15 -1
- package/src/cli.ts +2 -0
- package/src/commands.ts +55 -2
- package/src/config.ts +21 -3
- package/src/main.tsx +4 -4
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.test.ts +117 -0
- package/src/provider/provider.ts +312 -34
- package/src/provider/routing.test.ts +109 -0
- package/src/screens/REPL.tsx +432 -35
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- package/src/version.ts +1 -1
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.
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { AIMessage, HumanMessage } from '@langchain/core/messages';
|
|
6
|
+
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
7
|
+
import type { AgentLoopOptions, AgentLoopResult } from '../loop.js';
|
|
8
|
+
import { createDispatchAgentTool } from './dispatch.js';
|
|
9
|
+
import { readFileTool } from './files.js';
|
|
10
|
+
import { globTool } from './search.js';
|
|
11
|
+
import { setRouting } from '../../provider/provider.js';
|
|
12
|
+
import { createToolSession } from './session.js';
|
|
13
|
+
|
|
14
|
+
const pool = [readFileTool, globTool];
|
|
15
|
+
const runs: AgentLoopOptions[] = [];
|
|
16
|
+
const runLoopStub = async (options: AgentLoopOptions): Promise<AgentLoopResult> => {
|
|
17
|
+
runs.push(options);
|
|
18
|
+
return {
|
|
19
|
+
stopReason: 'end_turn',
|
|
20
|
+
messages: [new HumanMessage('task'), new AIMessage('调查结论:风险 A 和 B')],
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
const noopModel = {} as BaseChatModel;
|
|
24
|
+
|
|
25
|
+
let configDir: string;
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
configDir = mkdtempSync(path.join(tmpdir(), 'transcode-dispatch-test-'));
|
|
28
|
+
process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
|
|
29
|
+
runs.length = 0;
|
|
30
|
+
setRouting('research', 'deepseek');
|
|
31
|
+
});
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
delete process.env.TRANSCODE_CONFIG_PATH;
|
|
34
|
+
delete process.env.TRANSCODE_SUBAGENT_MAX_TURNS;
|
|
35
|
+
rmSync(configDir, { recursive: true, force: true });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
function makeTool() {
|
|
39
|
+
return createDispatchAgentTool({ runLoop: runLoopStub, tools: pool, model: noopModel });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('dispatch_agent', () => {
|
|
43
|
+
test('runs a nested loop for the routed role and returns its final report', async () => {
|
|
44
|
+
const tool = makeTool();
|
|
45
|
+
const session = createToolSession('/tmp');
|
|
46
|
+
const report = await tool.execute(
|
|
47
|
+
{ role: 'research', task: '调查鉴权链路' },
|
|
48
|
+
{ cwd: '/tmp', session },
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
expect(report).toBe('调查结论:风险 A 和 B');
|
|
52
|
+
expect(runs.length).toBe(1);
|
|
53
|
+
const run = runs[0]!;
|
|
54
|
+
expect(run.maxTurns).toBe(25);
|
|
55
|
+
expect(String((run.messages[0] as HumanMessage).content)).toBe('调查鉴权链路');
|
|
56
|
+
expect(run.systemPrompt).toMatch(/sub-?agent|子代理/i);
|
|
57
|
+
expect(run.tools?.map((item) => item.name).sort()).toEqual(['glob', 'read_file']);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('is a mutating tool so dispatch requires user authorization', () => {
|
|
61
|
+
const tool = makeTool();
|
|
62
|
+
expect(tool.isMutating).toBe(true);
|
|
63
|
+
expect(tool.isReadOnly?.({ role: 'research', task: 'x' })).toBeFalsy();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test('unknown role lists the configured roles', async () => {
|
|
67
|
+
const tool = makeTool();
|
|
68
|
+
const session = createToolSession('/tmp');
|
|
69
|
+
await expect(
|
|
70
|
+
tool.execute({ role: 'nope', task: 'x' }, { cwd: '/tmp', session }),
|
|
71
|
+
).rejects.toThrow(/Unknown role "nope".*research/);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('unknown tool names in the whitelist are rejected', async () => {
|
|
75
|
+
const tool = makeTool();
|
|
76
|
+
const session = createToolSession('/tmp');
|
|
77
|
+
await expect(
|
|
78
|
+
tool.execute(
|
|
79
|
+
{ role: 'research', task: 'x', tools: ['read_file', 'nuclear_launch'] },
|
|
80
|
+
{ cwd: '/tmp', session },
|
|
81
|
+
),
|
|
82
|
+
).rejects.toThrow(/nuclear_launch/);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('dispatch_agent itself can never be whitelisted (no recursion)', async () => {
|
|
86
|
+
const tool = makeTool();
|
|
87
|
+
const session = createToolSession('/tmp');
|
|
88
|
+
await expect(
|
|
89
|
+
tool.execute(
|
|
90
|
+
{ role: 'research', task: 'x', tools: ['dispatch_agent'] },
|
|
91
|
+
{ cwd: '/tmp', session },
|
|
92
|
+
),
|
|
93
|
+
).rejects.toThrow(/dispatch_agent/);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('TRANSCODE_SUBAGENT_MAX_TURNS overrides the turn cap', async () => {
|
|
97
|
+
process.env.TRANSCODE_SUBAGENT_MAX_TURNS = '7';
|
|
98
|
+
const tool = makeTool();
|
|
99
|
+
const session = createToolSession('/tmp');
|
|
100
|
+
await tool.execute({ role: 'research', task: 'x' }, { cwd: '/tmp', session });
|
|
101
|
+
expect(runs[0]!.maxTurns).toBe(7);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('forwards sub-agent tool activity to the parent as prefixed events', async () => {
|
|
105
|
+
const emitted: Array<{ name: string; title: string }> = [];
|
|
106
|
+
const tool = createDispatchAgentTool({
|
|
107
|
+
runLoop: async (options) => {
|
|
108
|
+
void options.onEvent?.({
|
|
109
|
+
type: 'tool_call',
|
|
110
|
+
toolCallId: 'sub-1',
|
|
111
|
+
name: 'grep',
|
|
112
|
+
title: 'search: auth',
|
|
113
|
+
kind: 'search',
|
|
114
|
+
input: {},
|
|
115
|
+
});
|
|
116
|
+
void options.onEvent?.({
|
|
117
|
+
type: 'text',
|
|
118
|
+
text: 'should not be forwarded',
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
stopReason: 'end_turn',
|
|
122
|
+
messages: [new HumanMessage('t'), new AIMessage('报告')],
|
|
123
|
+
};
|
|
124
|
+
},
|
|
125
|
+
tools: pool,
|
|
126
|
+
model: noopModel,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const report = await tool.execute(
|
|
130
|
+
{ role: 'research', task: 'x' },
|
|
131
|
+
{
|
|
132
|
+
cwd: '/tmp',
|
|
133
|
+
session: createToolSession('/tmp'),
|
|
134
|
+
emit: (event) => {
|
|
135
|
+
if (event.type === 'tool_call') {
|
|
136
|
+
emitted.push({ name: event.name, title: event.title });
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
expect(report).toBe('报告');
|
|
143
|
+
expect(emitted).toEqual([{ name: 'grep', title: '[research] search: auth' }]);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('an empty sub-agent report is an error', async () => {
|
|
147
|
+
const tool = createDispatchAgentTool({
|
|
148
|
+
runLoop: async () => ({ stopReason: 'end_turn', messages: [new HumanMessage('t')] }),
|
|
149
|
+
tools: pool,
|
|
150
|
+
model: noopModel,
|
|
151
|
+
});
|
|
152
|
+
const session = createToolSession('/tmp');
|
|
153
|
+
await expect(
|
|
154
|
+
tool.execute({ role: 'research', task: 'x' }, { cwd: '/tmp', session }),
|
|
155
|
+
).rejects.toThrow(/报告|report/i);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { HumanMessage } from '@langchain/core/messages';
|
|
3
|
+
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
4
|
+
import type { AgentLoopOptions, AgentLoopResult } from '../loop.js';
|
|
5
|
+
import type { AgentTool } from './types.js';
|
|
6
|
+
import { createToolSession } from './session.js';
|
|
7
|
+
import { createModel, getRouting } from '../../provider/provider.js';
|
|
8
|
+
|
|
9
|
+
export interface DispatchDeps {
|
|
10
|
+
runLoop?: (options: AgentLoopOptions) => Promise<AgentLoopResult>;
|
|
11
|
+
/** Tool pool the whitelist selects from; MUST NOT include dispatch itself. */
|
|
12
|
+
tools?: AgentTool[];
|
|
13
|
+
/** Injected model factory (tests). Default: createModel(profile). */
|
|
14
|
+
model?: BaseChatModel | ((profile: string) => BaseChatModel);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const DEFAULT_WHITELIST = ['read_file', 'glob', 'grep'];
|
|
18
|
+
const MAX_REPORT_CHARS = 30_000;
|
|
19
|
+
|
|
20
|
+
const SUBAGENT_SYSTEM_PROMPT =
|
|
21
|
+
'You are a sub-agent. Complete the assigned task using the tools provided, then reply ' +
|
|
22
|
+
'with a final, self-contained report in the same language as the task. The report is the ' +
|
|
23
|
+
'only thing the dispatcher sees — include findings, evidence (file:line) and conclusions; ' +
|
|
24
|
+
'do not ask questions back.';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* dispatch_agent: the main model delegates an investigation-style sub-task to
|
|
28
|
+
* a routed role's model running its own agent loop with a tool whitelist.
|
|
29
|
+
* Context contract: task text in → final report out (the sub-agent sees
|
|
30
|
+
* nothing of the parent conversation). Dispatch itself is a mutating tool,
|
|
31
|
+
* so the user authorizes each dispatch (y/n) in ask mode.
|
|
32
|
+
*/
|
|
33
|
+
export function createDispatchAgentTool(deps: DispatchDeps = {}): AgentTool {
|
|
34
|
+
const runLoop = deps.runLoop;
|
|
35
|
+
const pool = deps.tools;
|
|
36
|
+
return {
|
|
37
|
+
name: 'dispatch_agent',
|
|
38
|
+
description:
|
|
39
|
+
'Dispatch a self-contained sub-task to a sub-agent running a routed role model ' +
|
|
40
|
+
'(configured via /route). The sub-agent explores with the whitelisted tools in its ' +
|
|
41
|
+
'own loop and returns one final report; it does NOT see this conversation, so the ' +
|
|
42
|
+
'task must carry all needed context (files, constraints, expected output). ' +
|
|
43
|
+
'tools defaults to the read-only set (read_file, glob, grep). Use for multi-step ' +
|
|
44
|
+
'research/investigation; use ask_model for single-shot expert questions.',
|
|
45
|
+
kind: 'execute',
|
|
46
|
+
isMutating: true,
|
|
47
|
+
schema: z.object({
|
|
48
|
+
role: z.string().describe('Role configured via /route (e.g. research, analysis)'),
|
|
49
|
+
task: z.string().describe('Fully self-contained sub-task description'),
|
|
50
|
+
tools: z
|
|
51
|
+
.array(z.string())
|
|
52
|
+
.nullable()
|
|
53
|
+
.optional()
|
|
54
|
+
.describe('Tool whitelist for the sub-agent (default: read_file, glob, grep)'),
|
|
55
|
+
}),
|
|
56
|
+
title: (input) =>
|
|
57
|
+
`dispatch ${String(input.role ?? '')}: ${String(input.task ?? '').slice(0, 60)}`,
|
|
58
|
+
async execute(input, ctx) {
|
|
59
|
+
const role = String(input.role ?? '').trim();
|
|
60
|
+
const task = String(input.task ?? '').trim();
|
|
61
|
+
if (!role || !task) throw new Error('Both role and task are required.');
|
|
62
|
+
|
|
63
|
+
const routing = getRouting();
|
|
64
|
+
const profile = routing[role];
|
|
65
|
+
if (!profile) {
|
|
66
|
+
const names = Object.keys(routing).join(', ');
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Unknown role "${role}". Configured roles: ${names || '(none — set one with /route)'}`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const poolTools = pool;
|
|
73
|
+
if (!poolTools) throw new Error('dispatch_agent is not wired with a tool pool.');
|
|
74
|
+
|
|
75
|
+
const explicit = Array.isArray(input.tools) && input.tools.length > 0
|
|
76
|
+
? (input.tools as string[]).map((name) => String(name))
|
|
77
|
+
: undefined;
|
|
78
|
+
let requested: string[];
|
|
79
|
+
if (explicit) {
|
|
80
|
+
const missing = explicit.filter((name) => !poolTools.some((item) => item.name === name));
|
|
81
|
+
if (missing.length > 0) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Unknown or forbidden tools: ${missing.join(', ')}. ` +
|
|
84
|
+
`Available: ${poolTools.map((item) => item.name).join(', ')}`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
requested = explicit;
|
|
88
|
+
} else {
|
|
89
|
+
// Default: the read-only set intersected with the wired pool.
|
|
90
|
+
requested = DEFAULT_WHITELIST.filter((name) =>
|
|
91
|
+
poolTools.some((item) => item.name === name),
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
const selected = poolTools.filter((item) => requested.includes(item.name));
|
|
95
|
+
|
|
96
|
+
const model =
|
|
97
|
+
typeof deps.model === 'function'
|
|
98
|
+
? deps.model(profile)
|
|
99
|
+
: deps.model
|
|
100
|
+
? deps.model
|
|
101
|
+
: createModel(profile).model;
|
|
102
|
+
|
|
103
|
+
const envTurns = Number(process.env.TRANSCODE_SUBAGENT_MAX_TURNS);
|
|
104
|
+
const maxTurns = Number.isFinite(envTurns) && envTurns > 0 ? envTurns : 25;
|
|
105
|
+
|
|
106
|
+
const result = await runLoop!({
|
|
107
|
+
model,
|
|
108
|
+
cwd: ctx.session.cwd,
|
|
109
|
+
messages: [new HumanMessage(task)],
|
|
110
|
+
systemPrompt: SUBAGENT_SYSTEM_PROMPT,
|
|
111
|
+
tools: selected,
|
|
112
|
+
maxTurns,
|
|
113
|
+
toolSession: createToolSession(ctx.session.cwd),
|
|
114
|
+
onEvent: (event) => {
|
|
115
|
+
// Forward sub-agent tool calls (prefixed) so the parent UI shows
|
|
116
|
+
// live progress; sub-agent text and results stay private.
|
|
117
|
+
if (ctx.emit && event.type === 'tool_call') {
|
|
118
|
+
ctx.emit({
|
|
119
|
+
...event,
|
|
120
|
+
toolCallId: `sub-${event.toolCallId}`,
|
|
121
|
+
title: `[${role}] ${event.title}`,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
requestPermission: ctx.requestPermission,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const lastAi = [...result.messages].reverse().find((message) => message.getType() === 'ai');
|
|
129
|
+
const content = lastAi?.content;
|
|
130
|
+
const report =
|
|
131
|
+
typeof content === 'string'
|
|
132
|
+
? content
|
|
133
|
+
: Array.isArray(content)
|
|
134
|
+
? content
|
|
135
|
+
.map((block) =>
|
|
136
|
+
block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
|
|
137
|
+
? (block as { text: string }).text
|
|
138
|
+
: '',
|
|
139
|
+
)
|
|
140
|
+
.join('')
|
|
141
|
+
: '';
|
|
142
|
+
|
|
143
|
+
if (!report.trim()) {
|
|
144
|
+
throw new Error(`子代理未产出报告(stopReason: ${result.stopReason})。`);
|
|
145
|
+
}
|
|
146
|
+
return report.length > MAX_REPORT_CHARS
|
|
147
|
+
? `${report.slice(0, MAX_REPORT_CHARS)}\n… (truncated)`
|
|
148
|
+
: report;
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|