@trans-ai/trans-code 0.2.3 → 0.3.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/src/agent/loop.ts CHANGED
@@ -17,10 +17,12 @@ import {
17
17
  type ToolKind,
18
18
  type ToolSession,
19
19
  } from './tools/index.js';
20
+ import { askRole, getRouting } from '../provider/provider.js';
20
21
 
21
22
  export type AgentEvent =
22
23
  | { type: 'text'; text: string }
23
24
  | { type: 'thought'; text: string }
25
+ | { type: 'max_turns_reached'; maxTurns: number }
24
26
  | {
25
27
  type: 'tool_call';
26
28
  toolCallId: string;
@@ -55,6 +57,7 @@ export type StopReason =
55
57
  | 'end_turn'
56
58
  | 'cancelled'
57
59
  | 'max_turn_requests'
60
+ | 'stalled'
58
61
  | 'refusal';
59
62
 
60
63
  export interface AgentLoopOptions {
@@ -69,6 +72,8 @@ export interface AgentLoopOptions {
69
72
  requestPermission?: RequestPermission;
70
73
  /** Session state shared across tool calls (shell cwd, read files). Created when absent. */
71
74
  toolSession?: ToolSession;
75
+ /** Vision proxy override (tests). Default: routing.vision → askRole('vision'). */
76
+ describeImages?: (images: Array<{ data: string; mediaType: string }>) => Promise<string>;
72
77
  }
73
78
 
74
79
  export interface AgentLoopResult {
@@ -204,6 +209,7 @@ async function runMockTurn(
204
209
  cwd: toolSession.cwd,
205
210
  signal: options.signal,
206
211
  session: toolSession,
212
+ requestPermission: options.requestPermission,
207
213
  })
208
214
  : { ok: false, output: 'Permission denied.' };
209
215
 
@@ -255,7 +261,10 @@ export async function runAgentLoop(
255
261
  }
256
262
 
257
263
  const tools = options.tools ?? AGENT_TOOLS;
258
- const maxTurns = options.maxTurns ?? 50;
264
+ // Claude Code style: generous default cap (their subagents use 200),
265
+ // overridable via TRANSCODE_MAX_TURNS. Hitting it is loud, never silent.
266
+ const envTurns = Number(process.env.TRANSCODE_MAX_TURNS);
267
+ const maxTurns = options.maxTurns ?? (Number.isFinite(envTurns) && envTurns > 0 ? envTurns : 200);
259
268
  const toolSession = options.toolSession ?? createToolSession(options.cwd);
260
269
  if (!options.model) throw new Error('No model configured for the agent loop');
261
270
 
@@ -264,8 +273,27 @@ export async function runAgentLoop(
264
273
  ? options.model.bindTools(bindableTools(tools))
265
274
  : options.model;
266
275
 
267
- let repeatedKey: string | undefined;
268
- let repeatCount = 0;
276
+ // Windowed repetition tracking: the same call (name + args) occurring
277
+ // >= 3 times within the last 6 calls is refused, which catches both
278
+ // straight repeats (A,A,A) and alternating loops (A,B,A,B,A).
279
+ const recentKeys: string[] = [];
280
+
281
+ // Exploration stall detection: too many calls with zero mutations means
282
+ // the model is drilling instead of delivering (observed with DeepSeek:
283
+ // 272 read-only calls to "update a README"). Nudge it once mid-run.
284
+ const EXPLORE_STALL_THRESHOLD = 30;
285
+ // Hard rail: when the stall nudge is ignored, stop burning turns.
286
+ const STALL_GRACE_CALLS = 15;
287
+ // Wrap-up detection: the deliverable was already written, but the model
288
+ // keeps exploring instead of summarizing and ending its turn.
289
+ const WRAP_UP_GAP = 20;
290
+ let totalToolCalls = 0;
291
+ let callsSinceAction = 0;
292
+ let hasActed = false;
293
+ let hasDelivered = false; // a real file write happened (write_file/edit_file)
294
+ let stallNudged = false;
295
+ let callsAtStallNudge = 0;
296
+ let wrapUpNudged = false;
269
297
 
270
298
  for (let turn = 0; turn < maxTurns; turn++) {
271
299
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
@@ -319,21 +347,18 @@ export async function runAgentLoop(
319
347
  input,
320
348
  });
321
349
 
322
- let result: { ok: boolean; output: string; diff?: string };
350
+ let result: { ok: boolean; output: string; diff?: string; images?: Array<{ data: string; mediaType: string }> };
323
351
  let skippedPermission = false;
324
352
 
325
- // Circuit breaker: the third consecutive identical call is refused
326
- // instead of executed, with guidance to change approach.
353
+ // Circuit breaker (windowed): see recentKeys declaration.
327
354
  const key = `${call.name}:${stableKey(input)}`;
328
- if (key === repeatedKey) repeatCount++;
329
- else {
330
- repeatedKey = key;
331
- repeatCount = 1;
332
- }
355
+ const occurrences = recentKeys.filter((recent) => recent === key).length + 1;
356
+ recentKeys.push(key);
357
+ if (recentKeys.length > 6) recentKeys.shift();
333
358
 
334
359
  if (!tool) {
335
360
  result = { ok: false, output: `Unknown tool: ${call.name}` };
336
- } else if (repeatCount >= 3) {
361
+ } else if (occurrences >= 3) {
337
362
  result = { ok: false, output: `Error: ${REPEAT_GUIDANCE}` };
338
363
  } else {
339
364
  const readOnly = tool.isReadOnly?.(input) === true;
@@ -355,9 +380,22 @@ export async function runAgentLoop(
355
380
  cwd: toolSession.cwd,
356
381
  signal: options.signal,
357
382
  session: toolSession,
383
+ requestPermission: options.requestPermission,
358
384
  })
359
385
  : { ok: false, output: 'Permission denied by the client.' };
386
+
387
+ if (allowed && tool.isMutating && tool.isReadOnly?.(input) !== true) {
388
+ hasActed = true;
389
+ callsSinceAction = 0;
390
+ // "Delivered" means a file write; mutating bash is not a deliverable
391
+ // and must not trigger the wrap-up message.
392
+ if (tool.name === 'write_file' || tool.name === 'edit_file') {
393
+ hasDelivered = true;
394
+ }
395
+ }
360
396
  }
397
+ totalToolCalls++;
398
+ callsSinceAction++;
361
399
 
362
400
  await options.onEvent({
363
401
  type: 'tool_result',
@@ -369,15 +407,101 @@ export async function runAgentLoop(
369
407
  skippedPermission,
370
408
  });
371
409
 
410
+ // Image auto-proxy: when a vision role is routed (or a test describer
411
+ // is injected), images are converted to a text description so the
412
+ // primary model does not need multimodal support.
413
+ let toolContent:
414
+ | string
415
+ | Array<{ type: string; text?: string; image_url?: { url: string } }> = result.output;
416
+ if (result.images?.length) {
417
+ const describer =
418
+ options.describeImages ??
419
+ (getRouting().vision
420
+ ? (images: Array<{ data: string; mediaType: string }>) =>
421
+ askRole(
422
+ 'vision',
423
+ '简要描述图片的关键信息;如果是报错/截图,逐字给出其中文本。',
424
+ images,
425
+ )
426
+ : undefined);
427
+ if (describer) {
428
+ try {
429
+ const description = await describer(result.images);
430
+ toolContent = `${result.output}\n\n[vision] ${description}`;
431
+ } catch {
432
+ toolContent = [
433
+ { type: 'text', text: `${result.output}\n[vision 转述失败,原图已直接传入]` },
434
+ ...result.images.map((image) => ({
435
+ type: 'image_url',
436
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
437
+ })),
438
+ ];
439
+ }
440
+ } else {
441
+ toolContent = [
442
+ { type: 'text', text: result.output },
443
+ ...result.images.map((image) => ({
444
+ type: 'image_url',
445
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
446
+ })),
447
+ ];
448
+ }
449
+ }
450
+
372
451
  messages.push(
373
452
  new ToolMessage({
374
- content: result.output,
453
+ content: toolContent,
375
454
  tool_call_id: toolCallId,
376
455
  name: call.name,
377
456
  }),
378
457
  );
379
458
  }
459
+
460
+ if (!hasActed && !stallNudged && totalToolCalls >= EXPLORE_STALL_THRESHOLD) {
461
+ stallNudged = true;
462
+ callsAtStallNudge = totalToolCalls;
463
+ const nudge =
464
+ `You have made ${totalToolCalls} tool calls without producing any edits or output. ` +
465
+ 'Stop exploring: synthesize what you already have and complete the task now ' +
466
+ '(edit or write the deliverable, or answer directly). If you need file contents, ' +
467
+ 'read_file returns up to 2000 lines in one call — do not paginate with grep/sed windows.';
468
+ messages.push(new AIMessage({ content: nudge }));
469
+ await options.onEvent({ type: 'text', text: `\n⚠ ${nudge}\n` });
470
+ } else if (
471
+ !hasActed &&
472
+ stallNudged &&
473
+ totalToolCalls - callsAtStallNudge >= STALL_GRACE_CALLS
474
+ ) {
475
+ // Hard rail: the nudge was ignored. Fail fast and loudly instead of
476
+ // burning the remaining turns.
477
+ const notice =
478
+ `The agent made ${totalToolCalls} tool calls without starting the deliverable and ` +
479
+ 'ignored the earlier reminder. Stopping to avoid wasting turns. Re-prompt with a more ' +
480
+ 'specific instruction (name the exact file and what to change) or switch to a stronger model.';
481
+ messages.push(new AIMessage({ content: notice }));
482
+ await options.onEvent({ type: 'text', text: `\n⚠ ${notice}\n` });
483
+ return { stopReason: 'stalled', messages };
484
+ } else if (
485
+ hasDelivered &&
486
+ !wrapUpNudged &&
487
+ callsSinceAction >= WRAP_UP_GAP
488
+ ) {
489
+ wrapUpNudged = true;
490
+ const nudge =
491
+ `The deliverable has already been written, but you have made ${callsSinceAction} ` +
492
+ 'more tool calls since. Run any final verification now if truly needed, then ' +
493
+ 'reply with a summary of what changed and stop — further exploration is not needed.';
494
+ messages.push(new AIMessage({ content: nudge }));
495
+ await options.onEvent({ type: 'text', text: `\n⚠ ${nudge}\n` });
496
+ }
380
497
  }
381
498
 
499
+ // Record the cap in the conversation (like Claude Code's max_turns_reached
500
+ // attachment) and surface it as an event so no surface stays silent.
501
+ const notice = new AIMessage({
502
+ content: `Reached maximum number of turns (${maxTurns}). The task is incomplete — ask the user to say "continue" or raise TRANSCODE_MAX_TURNS.`,
503
+ });
504
+ messages.push(notice);
505
+ await options.onEvent({ type: 'max_turns_reached', maxTurns });
382
506
  return { stopReason: 'max_turn_requests', messages };
383
507
  }
@@ -1,8 +1,9 @@
1
1
  import { afterEach, describe, expect, test } from 'bun:test';
2
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { INIT_PROMPT, buildSystemPrompt, loadProjectContext } from './system-prompt.js';
6
+ import { setRouting } from '../provider/provider.js';
6
7
 
7
8
  describe('buildSystemPrompt', () => {
8
9
  test('steers file inspection away from whole-file cat/sed dumps', () => {
@@ -14,6 +15,28 @@ describe('buildSystemPrompt', () => {
14
15
  expect(prompt).toContain('offset');
15
16
  expect(prompt.toLowerCase()).toContain('do not cat');
16
17
  });
18
+
19
+ test('warns that grep -c counts definition lines too', () => {
20
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
21
+ expect(prompt).toContain('grep -c');
22
+ });
23
+
24
+ test('advertises configured role routing for ask_model delegation', async () => {
25
+ const configDir = await fs.mkdtemp(path.join(tmpdir(), 'transcode-prompt-route-'));
26
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
27
+ try {
28
+ setRouting('analysis', 'glmc');
29
+ setRouting('design', 'opus');
30
+ const prompt = buildSystemPrompt({ cwd: '/tmp', projectFiles: [] });
31
+ expect(prompt).toContain('ask_model');
32
+ expect(prompt).toContain('dispatch_agent');
33
+ expect(prompt).toContain('analysis→glmc');
34
+ expect(prompt).toContain('design→opus');
35
+ } finally {
36
+ delete process.env.TRANSCODE_CONFIG_PATH;
37
+ await fs.rm(configDir, { recursive: true, force: true });
38
+ }
39
+ });
17
40
  });
18
41
 
19
42
  const cleanups: Array<() => void> = [];
@@ -1,5 +1,6 @@
1
1
  import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { getRouting } from '../provider/provider.js';
3
4
 
4
5
  const CONTEXT_FILES = ['TRANS.md', 'AGENTS.md', 'CLAUDE.md', 'TRANSCODE.md', '.transcode/AGENTS.md'];
5
6
  const MAX_CONTEXT_CHARS = 40_000;
@@ -32,6 +33,21 @@ async function readOptional(file: string): Promise<string | null> {
32
33
  }
33
34
  }
34
35
 
36
+ /** Advertises configured role routing so the model knows it can delegate. */
37
+ function roleRoutingLines(): string[] {
38
+ const entries = Object.entries(getRouting()).filter(([role]) => role !== 'default');
39
+ if (entries.length === 0) return [];
40
+ const roles = entries.map(([role, profile]) => `${role}→${profile}`).join(', ');
41
+ return [
42
+ `- Sub-task delegation. Configured roles: ${roles}. Three tiers — ` +
43
+ 'do it yourself for simple lookups; ask_model({role, prompt}) for one-shot expert ' +
44
+ 'questions (analysis, design trade-offs, reviews, image description); ' +
45
+ 'dispatch_agent({role, task, tools}) for multi-step research that needs file access — ' +
46
+ 'the sub-agent runs its own tool loop and returns a final report (it cannot see this ' +
47
+ 'conversation, so the task must be fully self-contained; dispatch asks the user first).',
48
+ ];
49
+ }
50
+
35
51
  async function gitBranch(cwd: string): Promise<string | undefined> {
36
52
  try {
37
53
  const { execFile } = await import('node:child_process');
@@ -91,6 +107,15 @@ export function buildSystemPrompt(
91
107
  '- Prefer read_file, glob and grep for exploration; use bash for builds, tests and git.',
92
108
  '- View file contents with read_file (NOT cat/head/tail/sed); check unknown file sizes with ' +
93
109
  'wc -l first and read large files in offset/limit chunks. Do not cat entire files into the conversation.',
110
+ '- read_file returns up to 2000 lines in ONE call. Never paginate a file through repeated ' +
111
+ 'grep/sed window commands — that wastes dozens of turns; read the file once instead.',
112
+ '- For synthesis tasks (update docs/README): explore briefly (aim for ~15 tool calls), ' +
113
+ 'then state a short plan and write the result. Exploration is not the deliverable.',
114
+ '- Multi-step tasks (3+ steps): create the list with todo_write first, keep exactly one ' +
115
+ 'step in_progress, and mark steps completed as you finish them.',
116
+ ...roleRoutingLines(),
117
+ '- Reporting counts (tests, checks, matches): grep -c counts matching LINES, including ' +
118
+ 'definitions like `def check(` — read the actual item list instead of trusting a raw count.',
94
119
  '- The bash working directory persists across calls; you do not need to cd again each time.',
95
120
  '- Never repeat an identical tool call; refine it or switch tools.',
96
121
  '- Use edit_file for targeted changes and write_file for new files.',
@@ -0,0 +1,54 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { createAskModelTool } from './ask-model.js';
6
+ import { createToolSession } from './session.js';
7
+
8
+ const calls: Array<{ role: string; prompt: string; images?: string[] }> = [];
9
+ const stubAsk = async (role: string, prompt: string, images?: string[]) => {
10
+ calls.push({ role, prompt, images });
11
+ return `answer from ${role}`;
12
+ };
13
+ const tool = createAskModelTool(stubAsk);
14
+
15
+ let dir: string;
16
+ beforeEach(() => {
17
+ dir = mkdtempSync(path.join(tmpdir(), 'transcode-askmodel-'));
18
+ calls.length = 0;
19
+ });
20
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
21
+
22
+ describe('ask_model', () => {
23
+ test('delegates a sub-task to the routed role and returns its answer', async () => {
24
+ const session = createToolSession(dir);
25
+ const output = await tool.execute(
26
+ { role: 'analysis', prompt: '分析这个架构的扩展性' },
27
+ { cwd: dir, session },
28
+ );
29
+ expect(output).toBe('answer from analysis');
30
+ expect(calls[0]?.role).toBe('analysis');
31
+ expect(calls[0]?.prompt).toContain('扩展性');
32
+ });
33
+
34
+ test('passes image paths through for vision roles', async () => {
35
+ const session = createToolSession(dir);
36
+ writeFileSync(path.join(dir, 'shot.png'), Buffer.from([1, 2, 3]));
37
+ await tool.execute(
38
+ { role: 'vision', prompt: '截图里什么报错', images: ['shot.png'] },
39
+ { cwd: dir, session },
40
+ );
41
+ expect(calls[0]?.images?.length).toBe(1);
42
+ expect(calls[0]?.images?.[0]).toContain('shot.png');
43
+ });
44
+
45
+ test('surfaces routing errors with the configured roles listed', async () => {
46
+ const failing = createAskModelTool(async (role) => {
47
+ throw new Error(`Unknown role "${role}". Configured roles: analysis, design`);
48
+ });
49
+ const session = createToolSession(dir);
50
+ await expect(
51
+ failing.execute({ role: 'x', prompt: 'hi' }, { cwd: dir, session }),
52
+ ).rejects.toThrow(/Unknown role "x".*analysis, design/);
53
+ });
54
+ });
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import type { AgentTool } from './types.js';
3
+
4
+ export type AskRoleFn = (
5
+ role: string,
6
+ prompt: string,
7
+ images?: string[],
8
+ ctx?: { cwd: string },
9
+ ) => Promise<string>;
10
+
11
+ /** Factory so tests can inject a stub; production wires the provider. */
12
+ export function createAskModelTool(askRole: AskRoleFn): AgentTool {
13
+ return {
14
+ name: 'ask_model',
15
+ description:
16
+ 'Delegate a sub-task to a specialized model configured under a role ' +
17
+ '(analysis, design, review, vision, …). The sub-model answers in one shot; ' +
18
+ 'its answer comes back as text here. Use it for deep analysis, design ' +
19
+ 'trade-offs, reviews or describing images instead of doing everything ' +
20
+ 'yourself. images (optional) lists workspace file paths for vision roles.',
21
+ kind: 'think',
22
+ isMutating: false,
23
+ schema: z.object({
24
+ role: z.string().describe('Role name configured via /route'),
25
+ prompt: z.string().describe('The sub-task, fully self-contained'),
26
+ images: z
27
+ .array(z.string())
28
+ .nullable()
29
+ .optional()
30
+ .describe('Workspace image paths for vision roles'),
31
+ }),
32
+ title: (input) => `ask ${String(input.role ?? '')}: ${String(input.prompt ?? '').slice(0, 60)}`,
33
+ async execute(input, ctx) {
34
+ const role = String(input.role ?? '').trim();
35
+ const prompt = String(input.prompt ?? '').trim();
36
+ if (!role || !prompt) throw new Error('Both role and prompt are required.');
37
+ const images = Array.isArray(input.images)
38
+ ? (input.images as string[]).map((file) => String(file))
39
+ : undefined;
40
+ const answer = await askRole(role, prompt, images, { cwd: ctx.cwd });
41
+ return answer.length > 20_000 ? `${answer.slice(0, 20_000)}\n… (truncated)` : answer;
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,115 @@
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('an empty sub-agent report is an error', async () => {
105
+ const tool = createDispatchAgentTool({
106
+ runLoop: async () => ({ stopReason: 'end_turn', messages: [new HumanMessage('t')] }),
107
+ tools: pool,
108
+ model: noopModel,
109
+ });
110
+ const session = createToolSession('/tmp');
111
+ await expect(
112
+ tool.execute({ role: 'research', task: 'x' }, { cwd: '/tmp', session }),
113
+ ).rejects.toThrow(/报告|report/i);
114
+ });
115
+ });
@@ -0,0 +1,141 @@
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: () => {},
115
+ requestPermission: ctx.requestPermission,
116
+ });
117
+
118
+ const lastAi = [...result.messages].reverse().find((message) => message.getType() === 'ai');
119
+ const content = lastAi?.content;
120
+ const report =
121
+ typeof content === 'string'
122
+ ? content
123
+ : Array.isArray(content)
124
+ ? content
125
+ .map((block) =>
126
+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
127
+ ? (block as { text: string }).text
128
+ : '',
129
+ )
130
+ .join('')
131
+ : '';
132
+
133
+ if (!report.trim()) {
134
+ throw new Error(`子代理未产出报告(stopReason: ${result.stopReason})。`);
135
+ }
136
+ return report.length > MAX_REPORT_CHARS
137
+ ? `${report.slice(0, MAX_REPORT_CHARS)}\n… (truncated)`
138
+ : report;
139
+ },
140
+ };
141
+ }