@trans-ai/trans-code 0.3.0 → 0.5.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.
@@ -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
- function detectShell(): string {
25
- const shell = process.env.SHELL ?? '';
26
- if (shell.includes('bash') || shell.includes('zsh')) return shell;
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
- const home = process.env.HOME ?? tmpdir();
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 = await getSnapshot(session, shell);
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, snapshotPath ? ['-c', wrapped] : ['-l', '-c', wrapped], {
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.
@@ -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
@@ -5,7 +5,7 @@ const USAGE = `transcode v${VERSION}
5
5
  Usage:
6
6
  transcode Start the interactive REPL
7
7
  transcode acp Start the ACP stdio server (for transonce, multica and other ACP clients)
8
- transcode upgrade Upgrade the npm global install to the latest version
8
+ transcode upgrade [version] Upgrade the npm global install to the latest or a specific version
9
9
  transcode --version Print the version
10
10
  transcode --help Show this help
11
11
 
@@ -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:
@@ -46,8 +48,9 @@ export async function runCli(argv: string[]): Promise<void> {
46
48
  }
47
49
 
48
50
  if (command === 'upgrade' || command === 'update') {
51
+ const target = rest.find(arg => !arg.startsWith('-'));
49
52
  const { runUpgrade } = await import('./upgrade.js');
50
- await runUpgrade();
53
+ await runUpgrade(target);
51
54
  return;
52
55
  }
53
56
 
@@ -57,6 +60,9 @@ export async function runCli(argv: string[]): Promise<void> {
57
60
  return;
58
61
  }
59
62
 
60
- // Default: interactive Ink REPL.
63
+ // Default: interactive Ink REPL. The auto-update runs in the background;
64
+ // its notice reaches the REPL through autoUpdateNotice() once settled.
65
+ const { startAutoUpdate } = await import('./upgrade.js');
66
+ startAutoUpdate();
61
67
  await import('./main.js');
62
68
  }