@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.
Files changed (39) hide show
  1. package/README.md +68 -17
  2. package/package.json +1 -1
  3. package/src/acp/session.ts +4 -1
  4. package/src/agent/loop.test.ts +337 -1
  5. package/src/agent/loop.ts +166 -2
  6. package/src/agent/system-prompt.test.ts +24 -1
  7. package/src/agent/system-prompt.ts +21 -0
  8. package/src/agent/tools/ask-model.test.ts +54 -0
  9. package/src/agent/tools/ask-model.ts +44 -0
  10. package/src/agent/tools/bash.test.ts +42 -1
  11. package/src/agent/tools/bash.ts +202 -15
  12. package/src/agent/tools/dispatch.test.ts +157 -0
  13. package/src/agent/tools/dispatch.ts +151 -0
  14. package/src/agent/tools/files.test.ts +96 -0
  15. package/src/agent/tools/files.ts +111 -29
  16. package/src/agent/tools/fs-utils.ts +40 -0
  17. package/src/agent/tools/index.ts +29 -2
  18. package/src/agent/tools/powershell.test.ts +61 -0
  19. package/src/agent/tools/read-only.ts +16 -0
  20. package/src/agent/tools/search.test.ts +55 -1
  21. package/src/agent/tools/search.ts +56 -8
  22. package/src/agent/tools/session.ts +21 -0
  23. package/src/agent/tools/shell-paths.test.ts +65 -0
  24. package/src/agent/tools/shell-paths.ts +19 -0
  25. package/src/agent/tools/todo.test.ts +54 -0
  26. package/src/agent/tools/todo.ts +47 -0
  27. package/src/agent/tools/types.ts +15 -1
  28. package/src/cli.ts +2 -0
  29. package/src/commands.ts +55 -2
  30. package/src/config.ts +21 -3
  31. package/src/main.tsx +4 -4
  32. package/src/provider/model-list.test.ts +65 -0
  33. package/src/provider/provider.test.ts +117 -0
  34. package/src/provider/provider.ts +312 -34
  35. package/src/provider/routing.test.ts +109 -0
  36. package/src/screens/REPL.tsx +432 -35
  37. package/src/sessions/store.test.ts +91 -0
  38. package/src/sessions/store.ts +149 -0
  39. package/src/version.ts +1 -1
package/src/agent/loop.ts CHANGED
@@ -17,6 +17,7 @@ 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 }
@@ -56,6 +57,7 @@ export type StopReason =
56
57
  | 'end_turn'
57
58
  | 'cancelled'
58
59
  | 'max_turn_requests'
60
+ | 'stalled'
59
61
  | 'refusal';
60
62
 
61
63
  export interface AgentLoopOptions {
@@ -70,6 +72,10 @@ export interface AgentLoopOptions {
70
72
  requestPermission?: RequestPermission;
71
73
  /** Session state shared across tool calls (shell cwd, read files). Created when absent. */
72
74
  toolSession?: ToolSession;
75
+ /** Plan mode: read-only exploration; mutating tools are denied with guidance. */
76
+ planMode?: boolean;
77
+ /** Vision proxy override (tests). Default: routing.vision → askRole('vision'). */
78
+ describeImages?: (images: Array<{ data: string; mediaType: string }>) => Promise<string>;
73
79
  }
74
80
 
75
81
  export interface AgentLoopResult {
@@ -205,6 +211,7 @@ async function runMockTurn(
205
211
  cwd: toolSession.cwd,
206
212
  signal: options.signal,
207
213
  session: toolSession,
214
+ requestPermission: options.requestPermission,
208
215
  })
209
216
  : { ok: false, output: 'Permission denied.' };
210
217
 
@@ -240,6 +247,56 @@ async function runMockTurn(
240
247
  return 'end_turn';
241
248
  }
242
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
+
243
300
  export async function runAgentLoop(
244
301
  options: AgentLoopOptions,
245
302
  ): Promise<AgentLoopResult> {
@@ -277,13 +334,35 @@ export async function runAgentLoop(
277
334
  // the model is drilling instead of delivering (observed with DeepSeek:
278
335
  // 272 read-only calls to "update a README"). Nudge it once mid-run.
279
336
  const EXPLORE_STALL_THRESHOLD = 30;
337
+ // Hard rail: when the stall nudge is ignored, stop burning turns.
338
+ const STALL_GRACE_CALLS = 15;
339
+ // Wrap-up detection: the deliverable was already written, but the model
340
+ // keeps exploring instead of summarizing and ending its turn.
341
+ const WRAP_UP_GAP = 20;
280
342
  let totalToolCalls = 0;
343
+ let callsSinceAction = 0;
281
344
  let hasActed = false;
345
+ let hasDelivered = false; // a real file write happened (write_file/edit_file)
282
346
  let stallNudged = false;
347
+ let callsAtStallNudge = 0;
348
+ let wrapUpNudged = false;
283
349
 
284
350
  for (let turn = 0; turn < maxTurns; turn++) {
285
351
  if (options.signal?.aborted) return { stopReason: 'cancelled', messages };
286
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
+
287
366
  const partials = new Map<number, PartialToolCall>();
288
367
  let text = '';
289
368
  let finalChunk: AIMessageChunk | undefined;
@@ -333,7 +412,7 @@ export async function runAgentLoop(
333
412
  input,
334
413
  });
335
414
 
336
- let result: { ok: boolean; output: string; diff?: string };
415
+ let result: { ok: boolean; output: string; diff?: string; images?: Array<{ data: string; mediaType: string }> };
337
416
  let skippedPermission = false;
338
417
 
339
418
  // Circuit breaker (windowed): see recentKeys declaration.
@@ -346,6 +425,14 @@ export async function runAgentLoop(
346
425
  result = { ok: false, output: `Unknown tool: ${call.name}` };
347
426
  } else if (occurrences >= 3) {
348
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
+ };
349
436
  } else {
350
437
  const readOnly = tool.isReadOnly?.(input) === true;
351
438
  const needsPermission = tool.isMutating && !readOnly;
@@ -366,14 +453,23 @@ export async function runAgentLoop(
366
453
  cwd: toolSession.cwd,
367
454
  signal: options.signal,
368
455
  session: toolSession,
456
+ requestPermission: options.requestPermission,
457
+ emit: options.onEvent as (event: { type: 'tool_call' }) => void,
369
458
  })
370
459
  : { ok: false, output: 'Permission denied by the client.' };
371
460
 
372
461
  if (allowed && tool.isMutating && tool.isReadOnly?.(input) !== true) {
373
462
  hasActed = true;
463
+ callsSinceAction = 0;
464
+ // "Delivered" means a file write; mutating bash is not a deliverable
465
+ // and must not trigger the wrap-up message.
466
+ if (tool.name === 'write_file' || tool.name === 'edit_file') {
467
+ hasDelivered = true;
468
+ }
374
469
  }
375
470
  }
376
471
  totalToolCalls++;
472
+ callsSinceAction++;
377
473
 
378
474
  await options.onEvent({
379
475
  type: 'tool_result',
@@ -385,9 +481,50 @@ export async function runAgentLoop(
385
481
  skippedPermission,
386
482
  });
387
483
 
484
+ // Image auto-proxy: when a vision role is routed (or a test describer
485
+ // is injected), images are converted to a text description so the
486
+ // primary model does not need multimodal support.
487
+ let toolContent:
488
+ | string
489
+ | Array<{ type: string; text?: string; image_url?: { url: string } }> = result.output;
490
+ if (result.images?.length) {
491
+ const describer =
492
+ options.describeImages ??
493
+ (getRouting().vision
494
+ ? (images: Array<{ data: string; mediaType: string }>) =>
495
+ askRole(
496
+ 'vision',
497
+ '简要描述图片的关键信息;如果是报错/截图,逐字给出其中文本。',
498
+ images,
499
+ )
500
+ : undefined);
501
+ if (describer) {
502
+ try {
503
+ const description = await describer(result.images);
504
+ toolContent = `${result.output}\n\n[vision] ${description}`;
505
+ } catch {
506
+ toolContent = [
507
+ { type: 'text', text: `${result.output}\n[vision 转述失败,原图已直接传入]` },
508
+ ...result.images.map((image) => ({
509
+ type: 'image_url',
510
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
511
+ })),
512
+ ];
513
+ }
514
+ } else {
515
+ toolContent = [
516
+ { type: 'text', text: result.output },
517
+ ...result.images.map((image) => ({
518
+ type: 'image_url',
519
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
520
+ })),
521
+ ];
522
+ }
523
+ }
524
+
388
525
  messages.push(
389
526
  new ToolMessage({
390
- content: result.output,
527
+ content: toolContent,
391
528
  tool_call_id: toolCallId,
392
529
  name: call.name,
393
530
  }),
@@ -396,6 +533,7 @@ export async function runAgentLoop(
396
533
 
397
534
  if (!hasActed && !stallNudged && totalToolCalls >= EXPLORE_STALL_THRESHOLD) {
398
535
  stallNudged = true;
536
+ callsAtStallNudge = totalToolCalls;
399
537
  const nudge =
400
538
  `You have made ${totalToolCalls} tool calls without producing any edits or output. ` +
401
539
  'Stop exploring: synthesize what you already have and complete the task now ' +
@@ -403,6 +541,32 @@ export async function runAgentLoop(
403
541
  'read_file returns up to 2000 lines in one call — do not paginate with grep/sed windows.';
404
542
  messages.push(new AIMessage({ content: nudge }));
405
543
  await options.onEvent({ type: 'text', text: `\n⚠ ${nudge}\n` });
544
+ } else if (
545
+ !hasActed &&
546
+ stallNudged &&
547
+ totalToolCalls - callsAtStallNudge >= STALL_GRACE_CALLS
548
+ ) {
549
+ // Hard rail: the nudge was ignored. Fail fast and loudly instead of
550
+ // burning the remaining turns.
551
+ const notice =
552
+ `The agent made ${totalToolCalls} tool calls without starting the deliverable and ` +
553
+ 'ignored the earlier reminder. Stopping to avoid wasting turns. Re-prompt with a more ' +
554
+ 'specific instruction (name the exact file and what to change) or switch to a stronger model.';
555
+ messages.push(new AIMessage({ content: notice }));
556
+ await options.onEvent({ type: 'text', text: `\n⚠ ${notice}\n` });
557
+ return { stopReason: 'stalled', messages };
558
+ } else if (
559
+ hasDelivered &&
560
+ !wrapUpNudged &&
561
+ callsSinceAction >= WRAP_UP_GAP
562
+ ) {
563
+ wrapUpNudged = true;
564
+ const nudge =
565
+ `The deliverable has already been written, but you have made ${callsSinceAction} ` +
566
+ 'more tool calls since. Run any final verification now if truly needed, then ' +
567
+ 'reply with a summary of what changed and stop — further exploration is not needed.';
568
+ messages.push(new AIMessage({ content: nudge }));
569
+ await options.onEvent({ type: 'text', text: `\n⚠ ${nudge}\n` });
406
570
  }
407
571
  }
408
572
 
@@ -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');
@@ -95,6 +111,11 @@ export function buildSystemPrompt(
95
111
  'grep/sed window commands — that wastes dozens of turns; read the file once instead.',
96
112
  '- For synthesis tasks (update docs/README): explore briefly (aim for ~15 tool calls), ' +
97
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.',
98
119
  '- The bash working directory persists across calls; you do not need to cd again each time.',
99
120
  '- Never repeat an identical tool call; refine it or switch tools.',
100
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
+ }
@@ -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;