@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.
@@ -101,6 +101,48 @@ describe('dispatch_agent', () => {
101
101
  expect(runs[0]!.maxTurns).toBe(7);
102
102
  });
103
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
+
104
146
  test('an empty sub-agent report is an error', async () => {
105
147
  const tool = createDispatchAgentTool({
106
148
  runLoop: async () => ({ stopReason: 'end_turn', messages: [new HumanMessage('t')] }),
@@ -111,7 +111,17 @@ export function createDispatchAgentTool(deps: DispatchDeps = {}): AgentTool {
111
111
  tools: selected,
112
112
  maxTurns,
113
113
  toolSession: createToolSession(ctx.session.cwd),
114
- onEvent: () => {},
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
+ },
115
125
  requestPermission: ctx.requestPermission,
116
126
  });
117
127
 
@@ -9,6 +9,7 @@ import { createAskModelTool } from './ask-model.js';
9
9
  import { createDispatchAgentTool } from './dispatch.js';
10
10
  import { readImageBlocks } from './files.js';
11
11
  import { askRole as providerAskRole } from '../../provider/provider.js';
12
+ import { bashOutputTool } from './bash.js';
12
13
 
13
14
  const askModelTool = createAskModelTool(async (role, prompt, images, ctx) => {
14
15
  const blocks = images?.length && ctx ? await readImageBlocks(images, ctx) : undefined;
@@ -23,6 +24,7 @@ const dispatchPool = [
23
24
  globTool,
24
25
  grepTool,
25
26
  bashTool,
27
+ bashOutputTool,
26
28
  todoWriteTool,
27
29
  askModelTool,
28
30
  ];
@@ -0,0 +1,61 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ buildWrappedCommand,
4
+ detectShellWith,
5
+ isPowerShell,
6
+ psQuote,
7
+ shellSpawnArgs,
8
+ } from './bash.js';
9
+ import { isReadOnlyCommand } from './read-only.js';
10
+
11
+ describe('PowerShell support', () => {
12
+ test('isPowerShell detects pwsh and powershell paths', () => {
13
+ expect(isPowerShell('C:\\Program Files\\PowerShell\\7\\pwsh.exe')).toBe(true);
14
+ expect(isPowerShell('powershell.exe')).toBe(true);
15
+ expect(isPowerShell('/bin/bash')).toBe(false);
16
+ expect(isPowerShell('/usr/bin/zsh')).toBe(false);
17
+ });
18
+
19
+ test('psQuote escapes single quotes the PowerShell way', () => {
20
+ expect(psQuote("it's")).toBe("'it''s'");
21
+ expect(psQuote('plain')).toBe("'plain'");
22
+ });
23
+
24
+ test('detectShellWith prefers Git Bash but falls back to PowerShell on win32', () => {
25
+ expect(detectShellWith('win32', () => false, {})).toBe('powershell.exe');
26
+ const gitBash = 'C:\\Program Files\\Git\\bin\\bash.exe';
27
+ expect(detectShellWith('win32', (p) => p === gitBash, {})).toBe(gitBash);
28
+ });
29
+
30
+ test('spawn args use NoProfile -Command for PowerShell', () => {
31
+ expect(shellSpawnArgs('powershell.exe', undefined, 'echo hi')).toEqual([
32
+ '-NoLogo',
33
+ '-NoProfile',
34
+ '-NonInteractive',
35
+ '-Command',
36
+ 'echo hi',
37
+ ]);
38
+ expect(shellSpawnArgs('/bin/bash', undefined, 'echo hi')).toEqual(['-l', '-c', 'echo hi']);
39
+ });
40
+
41
+ test('the PowerShell wrapper captures cwd and exit code without POSIX syntax', () => {
42
+ const wrapped = buildWrappedCommand(
43
+ 'Get-Location',
44
+ 'powershell.exe',
45
+ undefined,
46
+ 'C:\\tmp\\cwd-file',
47
+ );
48
+ expect(wrapped).toContain("Get-Location");
49
+ expect(wrapped).toContain('Out-File');
50
+ expect(wrapped).not.toContain('eval ');
51
+ expect(wrapped).not.toContain('pwd -P');
52
+ });
53
+
54
+ test('read-only analysis fails closed for PowerShell cmdlets, open for a safe few', () => {
55
+ expect(isReadOnlyCommand('Get-ChildItem')).toBe(true);
56
+ expect(isReadOnlyCommand('Get-Content file.txt')).toBe(true);
57
+ expect(isReadOnlyCommand('Select-String -Pattern x file.txt')).toBe(true);
58
+ expect(isReadOnlyCommand('Remove-Item -Recurse stuff')).toBe(false);
59
+ expect(isReadOnlyCommand('npm install')).toBe(false);
60
+ });
61
+ });
@@ -203,10 +203,26 @@ function segmentIsReadOnly(tokens: string[]): boolean {
203
203
  return SAFE_COMMANDS.has(base);
204
204
  }
205
205
 
206
+ /** PowerShell cmdlets that only read. */
207
+ const POWERSHELL_SAFE = new Set([
208
+ 'get-childitem', 'get-content', 'get-item', 'get-itemproperty', 'get-location',
209
+ 'get-command', 'get-process', 'get-service', 'get-date', 'get-variable',
210
+ 'select-string', 'measure-object', 'where-object', 'sort-object', 'foreach-object',
211
+ 'compare-object', 'format-list', 'format-table', 'set-location', 'out-string',
212
+ ]);
213
+
206
214
  /** True when the command can run without a permission prompt. */
207
215
  export function isReadOnlyCommand(command: string): boolean {
208
216
  const { segments, unsafe } = parseSegments(command);
209
217
  if (unsafe) return false;
210
218
  if (segments.length === 0) return false;
219
+
220
+ // PowerShell cmdlets are Verb-Noun (dashed); only then consult the PS set.
221
+ const firstTokens = segments.map((segment) => segment.tokens[0]?.toLowerCase() ?? '');
222
+ const isCmdlet = (token: string) => /^[a-z]+-[a-z][a-z0-9]*$/.test(token);
223
+ if (firstTokens.some(isCmdlet)) {
224
+ return firstTokens.every((token) => isCmdlet(token) && POWERSHELL_SAFE.has(token));
225
+ }
226
+
211
227
  return segments.every((segment) => segmentIsReadOnly(segment.tokens));
212
228
  }
@@ -6,6 +6,15 @@ export interface TodoItem {
6
6
  status: 'pending' | 'in_progress' | 'completed';
7
7
  }
8
8
 
9
+ /** A background shell task started via bash run_in_background. */
10
+ export interface BackgroundTask {
11
+ id: string;
12
+ pid: number;
13
+ logPath: string;
14
+ command: string;
15
+ startedAt: number;
16
+ }
17
+
9
18
  /**
10
19
  * State that persists across tool calls within one conversation/session:
11
20
  * the shell's current working directory (so `cd` survives between bash
@@ -23,6 +32,8 @@ export interface ToolSession {
23
32
  readFileState: Set<string>;
24
33
  /** Current task list, owned by the todo_write tool. */
25
34
  todos: TodoItem[];
35
+ /** Background shell tasks (bash run_in_background), keyed by id. */
36
+ bgTasks: Map<string, BackgroundTask>;
26
37
  }
27
38
 
28
39
  export function createToolSession(rootCwd: string): ToolSession {
@@ -32,6 +43,7 @@ export function createToolSession(rootCwd: string): ToolSession {
32
43
  rootCwd: absolute,
33
44
  readFileState: new Set<string>(),
34
45
  todos: [],
46
+ bgTasks: new Map(),
35
47
  };
36
48
  }
37
49
 
@@ -0,0 +1,65 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { fromPosixPath, toPosixPath } from './shell-paths.js';
3
+ import { detectShellWith, killTreeCommand } from './bash.js';
4
+
5
+ describe('path conversion', () => {
6
+ test('windows → posix drive paths', () => {
7
+ expect(toPosixPath('C:\\Users\\lindaw\\AppData\\Local\\Temp')).toBe(
8
+ '/c/Users/lindaw/AppData/Local/Temp',
9
+ );
10
+ expect(toPosixPath('D:/data/x')).toBe('/d/data/x');
11
+ });
12
+
13
+ test('posix paths pass through untouched', () => {
14
+ expect(toPosixPath('/var/folders/abc')).toBe('/var/folders/abc');
15
+ expect(toPosixPath('/tmp')).toBe('/tmp');
16
+ });
17
+
18
+ test('posix → windows drive paths (normalized uppercase)', () => {
19
+ expect(fromPosixPath('/c/Users/lindaw')).toBe('C:\\Users\\lindaw');
20
+ expect(fromPosixPath('/d/data/x')).toBe('D:\\data\\x');
21
+ });
22
+
23
+ test('non-drive posix paths pass through', () => {
24
+ expect(fromPosixPath('/var/folders/abc')).toBe('/var/folders/abc');
25
+ expect(fromPosixPath('/usr/bin/env')).toBe('/usr/bin/env');
26
+ });
27
+
28
+ test('roundtrips', () => {
29
+ const win = 'C:\\repo\\trans-once';
30
+ expect(fromPosixPath(toPosixPath(win))).toBe(win);
31
+ });
32
+ });
33
+
34
+ describe('detectShellWith', () => {
35
+ test('TRANSCODE_SHELL override wins everywhere', () => {
36
+ expect(
37
+ detectShellWith('win32', () => false, { TRANSCODE_SHELL: 'C:\\sh\\pwsh.exe' }),
38
+ ).toBe('C:\\sh\\pwsh.exe');
39
+ });
40
+
41
+ test('SHELL env is used when it is bash/zsh', () => {
42
+ expect(detectShellWith('linux', () => false, { SHELL: '/usr/bin/zsh' })).toBe('/usr/bin/zsh');
43
+ });
44
+
45
+ test('win32 probes Git Bash, then PowerShell, before the POSIX fallback', () => {
46
+ expect(detectShellWith('win32', (p) => p === 'C:\\Program Files\\Git\\bin\\bash.exe', {})).toBe(
47
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
48
+ );
49
+ // No Git Bash and no pwsh on disk → Windows PowerShell via PATH.
50
+ expect(detectShellWith('win32', () => false, {})).toBe('powershell.exe');
51
+ });
52
+ });
53
+
54
+ describe('killTreeCommand', () => {
55
+ test('win32 uses taskkill /T /F', () => {
56
+ const command = killTreeCommand(4242, 'win32');
57
+ expect(command?.file).toBe('taskkill');
58
+ expect(command?.args).toEqual(['/pid', '4242', '/T', '/F']);
59
+ });
60
+
61
+ test('posix uses the process-group kill path (no command)', () => {
62
+ expect(killTreeCommand(4242, 'darwin')).toBeNull();
63
+ expect(killTreeCommand(4242, 'linux')).toBeNull();
64
+ });
65
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Windows ↔ Git-Bash (MSYS) path conversion. Git Bash accepts both forms
3
+ * for arguments, but `pwd -P` outputs POSIX paths while Node APIs need
4
+ * native Windows ones — every boundary converts explicitly.
5
+ */
6
+
7
+ /** C:\a\b or C:/a/b → /c/a/b ; already-POSIX paths pass through. */
8
+ export function toPosixPath(input: string): string {
9
+ const drive = /^([a-zA-Z]):[\\/](.*)$/.exec(input);
10
+ if (!drive) return input;
11
+ return `/${drive[1]!.toLowerCase()}/${drive[2]!.replace(/\\/g, '/')}`;
12
+ }
13
+
14
+ /** /c/a/b → C:\a\b (drive letter uppercased) ; non-drive paths pass through. */
15
+ export function fromPosixPath(input: string): string {
16
+ const drive = /^\/([a-zA-Z])\/(.*)$/.exec(input);
17
+ if (!drive) return input;
18
+ return `${drive[1]!.toUpperCase()}:\\${drive[2]!.replace(/\//g, '\\')}`;
19
+ }
@@ -26,6 +26,8 @@ export interface ToolContext {
26
26
  kind: ToolKind;
27
27
  input: Record<string, unknown>;
28
28
  }) => Promise<boolean>;
29
+ /** Event sink for nested agent progress (dispatch_agent forwards here). */
30
+ emit?: (event: { type: 'tool_call'; [key: string]: unknown }) => void;
29
31
  }
30
32
 
31
33
  /** Rich execute result: model-facing output plus optional extras. */
package/src/cli.ts CHANGED
@@ -15,6 +15,8 @@ Environment:
15
15
  TRANSCODE_PERMISSION_MODE ask | auto | readonly (default: ask in ACP mode;
16
16
  switch at runtime in the REPL with /mode)
17
17
  TRANSCODE_MAX_TURNS Agent tool-call turn cap (default: 200)
18
+ TRANSCODE_SHELL Override the shell used by the bash tool
19
+ (Windows: Git Bash is auto-detected)
18
20
  ANTHROPIC_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY / ... provider keys
19
21
 
20
22
  Examples:
package/src/commands.ts CHANGED
@@ -70,6 +70,24 @@ const commands: Command[] = [
70
70
  return { output: `Permission mode switched to ${target}` };
71
71
  },
72
72
  },
73
+ {
74
+ name: 'new',
75
+ description: 'Start a new conversation',
76
+ // Intercepted by the REPL (needs messagesRef/toolSession state).
77
+ execute: () => ({ output: 'Starting a new conversation…' }),
78
+ },
79
+ {
80
+ name: 'sessions',
81
+ description: 'List/search saved conversations (optionally by keyword)',
82
+ // Intercepted by the REPL.
83
+ execute: () => ({ output: 'Listing conversations…' }),
84
+ },
85
+ {
86
+ name: 'resume',
87
+ description: 'Resume a saved conversation (/resume <序号|id|标题片段>)',
88
+ // Intercepted by the REPL.
89
+ execute: () => ({ output: 'Resuming…' }),
90
+ },
73
91
  {
74
92
  name: 'route',
75
93
  description: 'Show or set role→model routing (analysis/design/vision/…)',
@@ -0,0 +1,65 @@
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 { clearRegisteredApiKeys, listEndpointModels, registerApiKey } from './provider.js';
6
+
7
+ let configDir: string;
8
+ let server: ReturnType<typeof Bun.serve> | undefined;
9
+
10
+ beforeEach(() => {
11
+ configDir = mkdtempSync(path.join(tmpdir(), 'transcode-modellist-test-'));
12
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
13
+ clearRegisteredApiKeys();
14
+ });
15
+ afterEach(async () => {
16
+ delete process.env.TRANSCODE_CONFIG_PATH;
17
+ rmSync(configDir, { recursive: true, force: true });
18
+ await server?.stop?.();
19
+ server = undefined;
20
+ });
21
+
22
+ function stubModelsEndpoint(ids: string[]): string {
23
+ server = Bun.serve({
24
+ port: 0,
25
+ fetch: () =>
26
+ new Response(JSON.stringify({ object: 'list', data: ids.map((id) => ({ id })) }), {
27
+ headers: { 'content-type': 'application/json' },
28
+ }),
29
+ });
30
+ return `http://localhost:${server.port}/v1`;
31
+ }
32
+
33
+ describe('listEndpointModels', () => {
34
+ test('fetches the live model list from the endpoint', async () => {
35
+ const baseUrl = stubModelsEndpoint(['glm-5.1', 'glm-4.6', 'glm-5.3-flash']);
36
+ const { saveConfig } = await import('../config.js');
37
+ saveConfig({
38
+ apiKeys: { custom: 'k' },
39
+ profiles: { myhub: { baseUrl, model: 'glm-4.6', keyId: 'custom' } },
40
+ });
41
+
42
+ const models = await listEndpointModels('myhub');
43
+ expect(models).toEqual(['glm-4.6', 'glm-5.1', 'glm-5.3-flash']); // sorted
44
+ });
45
+
46
+ test('override form queries an unsaved custom gateway with its key', async () => {
47
+ const baseUrl = stubModelsEndpoint(['m1', 'm2']);
48
+ const models = await listEndpointModels('', { baseUrl, apiKey: 'k' });
49
+ expect(models).toEqual(['m1', 'm2']);
50
+ });
51
+
52
+ test('returns an empty list on failure so callers can fall back', async () => {
53
+ registerApiKey('deepseek', 'k');
54
+ const models = await listEndpointModels('deepseek'); // real URL, no network in test env → fails fast? may hit network…
55
+ // Use an unreachable local port instead for determinism.
56
+ const { saveConfig } = await import('../config.js');
57
+ saveConfig({
58
+ apiKeys: { custom: 'k' },
59
+ profiles: { dead: { baseUrl: 'http://127.0.0.1:1/v1', model: 'x', keyId: 'custom' } },
60
+ });
61
+ const none = await listEndpointModels('dead');
62
+ expect(none).toEqual([]);
63
+ void models;
64
+ });
65
+ });
@@ -581,6 +581,40 @@ export function getRouting(): Record<string, string> {
581
581
  return { ...(loadConfig().routing ?? {}) };
582
582
  }
583
583
 
584
+ /**
585
+ * Live model list from an endpoint's OpenAI-compatible GET /models, so the
586
+ * /models picker shows what the gateway actually serves (Zhipu's coding
587
+ * endpoint, for one, maps old names to newer generations). Empty list on
588
+ * any failure — callers fall back to the curated list. The override form
589
+ * queries an in-progress custom gateway before it is saved.
590
+ */
591
+ export async function listEndpointModels(
592
+ specOrId: string,
593
+ override?: { baseUrl: string; apiKey?: string },
594
+ ): Promise<string[]> {
595
+ try {
596
+ const baseUrl = (override?.baseUrl ?? baseUrlFor(resolveModel(specOrId)))?.replace(/\/$/, '');
597
+ if (!baseUrl) return [];
598
+ const apiKey = override?.apiKey ?? lookupApiKey(resolveModel(specOrId).id);
599
+ const response = await Promise.race([
600
+ fetch(`${baseUrl}/models`, {
601
+ headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
602
+ }),
603
+ new Promise<Response>((_, reject) =>
604
+ setTimeout(() => reject(new Error('timeout')), 5_000),
605
+ ),
606
+ ]);
607
+ if (!response.ok) return [];
608
+ const body = (await response.json()) as { data?: Array<{ id?: string }> };
609
+ const ids = (body.data ?? [])
610
+ .map((entry) => entry?.id)
611
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
612
+ return [...new Set(ids)].sort();
613
+ } catch {
614
+ return [];
615
+ }
616
+ }
617
+
584
618
  /** Set (or clear with "-") a role's profile. */
585
619
  export function setRouting(role: string, profile: string): void {
586
620
  if (!role.trim()) throw new Error('Role name cannot be empty.');