Skip to content

Commit d7dfca0

Browse files
committed
Fix Bash working directory persistence
- Preserve cd targets through permission checks and retain the final cwd after failures. - Keep quoted arguments separate and resolve shell temp paths through the host temp directory. - Test shared provider adapters and run cwd regressions across the OS CI matrix.
1 parent d075b2b commit d7dfca0

12 files changed

Lines changed: 504 additions & 26 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ jobs:
113113
- name: Build with esbuild (default, Node-only)
114114
run: npm run build
115115

116+
- name: Test Bash working directory persistence and provider adapters
117+
run: node --test test/bash-cwd-persistence.test.mjs
118+
116119
- name: Test source-map reads and cache stability
117120
run: node --test test/file-read-source-maps.test.mjs test/file-read-range-dedup.test.mjs test/core-tool-contracts.test.mjs test/tool-result-budget.test.mjs
118121

‎src/tools/BashTool/BashTool.tsx‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
isSameBashCwd,
5757
normalizeBashExecutionInput,
5858
normalizeBashExecutionInputInPlace,
59+
normalizeForHostFs,
5960
resolveEffectiveBashCwd,
6061
} from './bashWorkdir.js';
6162
import { maybeAppendCommandHelp } from './commandHelp.js';
@@ -305,10 +306,9 @@ const fullInputSchema = lazySchema(() => z.strictObject({
305306
// re-parse (strictObject) would throw `unrecognized_keys` and crash the Bash
306307
// permission dialog. Re-wrap the omitted shape as a plain (stripping) z.object so
307308
// internal/unknown keys are dropped from the PARSED RESULT instead of rejected.
308-
// call() still reads `_workdirFromCd` off the original input object (not a parse
309-
// result), and `_simulatedSedEdit` stays omitted here AND stripped in toolExecution
310-
// (defense-in-depth) — so neither internal cwd compatibility nor the sed-edit
311-
// guard breaks.
309+
// Permission checks preserve the validated cwd fields separately before
310+
// returning updatedInput; otherwise call() would lose the leading cd.
311+
// `_simulatedSedEdit` stays omitted here AND stripped in toolExecution.
312312
const inputSchema = lazySchema(() => {
313313
const omittedShape = (isBackgroundTasksDisabled ? fullInputSchema().omit({
314314
run_in_background: true,
@@ -1010,16 +1010,13 @@ export const BashTool = buildTool({
10101010
if (resetCwdIfOutsideProject(appState.toolPermissionContext)) {
10111011
stderrForShellReset = stdErrAppendShellResetMessage('');
10121012
}
1013-
// A model-written leading `cd X && …` was converted into a one-off
1014-
// workdir (bashWorkdir.ts), which intentionally skips the shell's own
1015-
// cwd capture. Mirror real shell semantics by persisting the cd target
1016-
// as the session cwd — but only inside approved working directories,
1017-
// the same boundary resetCwdIfOutsideProject enforces for a bare `cd`.
1018-
// Runs even when the command part failed: in a real shell, `cd X &&
1019-
// failing-cmd` still leaves you in X.
1020-
if (input._workdirFromCd && input.workdir && !result.preSpawnError && !shouldMaintainProjectWorkingDir() && !isSameBashCwd(executionDir, getCwd()) && pathInAllowedWorkingPath(executionDir, appState.toolPermissionContext)) {
1013+
// A normalized leading cd may be followed by another directory change.
1014+
// Prefer the shell's final cwd; retain the initial-cd fallback when an
1015+
// explicit exit/exec bypassed capture. Explicit workdirs stay one-off.
1016+
const finalCwd = result.finalCwd ? normalizeForHostFs(result.finalCwd) : executionDir;
1017+
if (input._workdirFromCd && input.workdir && !result.preSpawnError && !result.backgroundTaskId && !shouldMaintainProjectWorkingDir() && !isSameBashCwd(finalCwd, getCwd()) && pathInAllowedWorkingPath(finalCwd, appState.toolPermissionContext)) {
10211018
try {
1022-
setCwd(executionDir);
1019+
setCwd(finalCwd);
10231020
clearSystemPromptSectionCacheEntry('env_info_simple');
10241021
} catch {
10251022
// Target vanished mid-command — keep the current session cwd
@@ -1161,10 +1158,10 @@ export const BashTool = buildTool({
11611158
if (!stderrForShellReset) {
11621159
if (autoWorkdir) {
11631160
cwdNote = `Auto-located ${autoWorkdirLabel} in ${executionDir} and ran it by absolute path (${cwdBeforeExec} had none; session cwd unchanged).`;
1164-
} else if (!isSameBashCwd(executionDir, cwdAfter)) {
1165-
cwdNote = `Ran in ${executionDir} for this command only. The session cwd is still ${cwdAfter}; use an absolute path or this command's native location flag for follow-up commands there.`;
11661161
} else if (!isSameBashCwd(cwdAfter, cwdBeforeExec)) {
11671162
cwdNote = `Shell cwd is now ${cwdAfter}`;
1163+
} else if (!isSameBashCwd(executionDir, cwdAfter)) {
1164+
cwdNote = `Ran in ${executionDir} for this command only. The session cwd is still ${cwdAfter}; use an absolute path or this command's native location flag for follow-up commands there.`;
11681165
} else if (isMainThread && !isSameBashCwd(cwdAfter, getOriginalCwd())) {
11691166
cwdNote = `Shell cwd: ${cwdAfter}`;
11701167
}
@@ -1280,6 +1277,7 @@ async function* runShellCommand({
12801277
shouldUseSandbox: shouldUseSandbox(input),
12811278
shouldAutoBackground,
12821279
workdir,
1280+
captureFinalCwd: input._workdirFromCd === true && !preventCwdChanges,
12831281
agentModelEnv
12841282
});
12851283

‎src/tools/BashTool/bashWorkdir.test.ts‎

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66

77
import { mkdirSync, mkdtempSync, rmSync } from 'fs'
88
import { tmpdir } from 'os'
9-
import { join, posix as pathPosix, relative } from 'path'
9+
import { join, posix as pathPosix, relative, win32 as pathWin32 } from 'path'
1010
import { toJSONSchema, z } from 'zod/v4'
1111
import { getPlatform } from '../../utils/platform.js'
1212
import {
1313
extractLeadingCdCommand,
1414
isSameBashCwd,
1515
normalizeBashExecutionInput,
16+
normalizeForHostFs,
1617
resolveBashPathFrom,
1718
} from './bashWorkdir.js'
1819

@@ -215,6 +216,97 @@ async function main(): Promise<void> {
215216
)
216217
})
217218

219+
await test('maps only the Windows host /tmp alias to the OS temp directory', () => {
220+
for (const [target, suffix] of [
221+
['/tmp', ''],
222+
['/tmp/', ''],
223+
['/tmp/dummy-project', 'dummy-project'],
224+
['/tmp/project with spaces/nested', 'project with spaces/nested'],
225+
] as const) {
226+
assert(
227+
normalizeForHostFs(target, 'windows') === pathWin32.join(tmpdir(), suffix),
228+
`wrong host mapping for ${target}`,
229+
)
230+
}
231+
for (const target of ['/tmp-other/repo', '/temporary/repo', 'tmp/repo', '/var/tmp/repo']) {
232+
assert(normalizeForHostFs(target, 'windows') === target, `must preserve ${target}`)
233+
}
234+
})
235+
236+
await test('preserves native /tmp semantics on Linux, macOS, and WSL', () => {
237+
for (const platform of ['linux', 'macos', 'wsl'] as const) {
238+
assert(normalizeForHostFs('/tmp/project', platform) === '/tmp/project', platform)
239+
const result = normalizeBashExecutionInput(
240+
{ command: 'cd /tmp/project && pwd' },
241+
'/workspace',
242+
platform,
243+
)
244+
assert(result.workdir === '/tmp/project', `wrong ${platform} workdir`)
245+
assert(result.command === 'pwd' && result._workdirFromCd === true, platform)
246+
}
247+
})
248+
249+
await test('leaves remote /tmp paths and git -C commands untouched', () => {
250+
for (const command of [
251+
'git -C /tmp/dummy-project status',
252+
'docker exec -w /tmp app sh -c "cd /tmp/project && pwd"',
253+
'docker compose exec namenode hadoop fs -ls /tmp/',
254+
'hadoop fs -ls /tmp/',
255+
'hdfs dfs -cat /tmp/result',
256+
]) {
257+
const input = { command }
258+
assert(normalizeBashExecutionInput(input, 'Q:\\workspace', 'windows') === input, command)
259+
const result = normalizeBashExecutionInput(
260+
{ command: `cd /tmp && ${command}` },
261+
'Q:\\workspace',
262+
'windows',
263+
)
264+
assert(result.command === command, `remote arguments changed: ${command}`)
265+
}
266+
})
267+
268+
if (getPlatform() === 'windows') {
269+
await test('fixes /tmp cd chains without changing cwd flags or command contents', () => {
270+
const command = 'git add -A && git commit -m "Initial commit"'
271+
const result = normalizeBashExecutionInput(
272+
{ command: `cd /tmp/dummy-project && ${command}` },
273+
tmpdir(),
274+
)
275+
assert(result.workdir === join(tmpdir(), 'dummy-project'), `got ${result.workdir}`)
276+
assert(result.command === command, 'git command must stay unchanged')
277+
assert(result._workdirFromCd === true, 'cd persistence flag must survive')
278+
assert(normalizeBashExecutionInput(result, tmpdir()) === result, 'must be idempotent')
279+
280+
const chained = normalizeBashExecutionInput(
281+
{ command: 'cd /tmp && cd "project with spaces" && pwd' },
282+
tmpdir(),
283+
)
284+
assert(chained.workdir === join(tmpdir(), 'project with spaces'), 'chained cd target')
285+
assert(chained.command === 'pwd', 'chained cd remainder')
286+
287+
const explicit = normalizeBashExecutionInput({ command: 'pwd', workdir: '/tmp' }, tmpdir())
288+
assert(explicit.workdir === tmpdir(), 'explicit /tmp workdir')
289+
assert(explicit._workdirFromCd === undefined, 'explicit workdir must remain one-off')
290+
assert(isSameBashCwd('/tmp', tmpdir()), 'temp alias must match native cwd')
291+
})
292+
293+
await test('uses configured temp roots without assuming a drive or caching the path', () => {
294+
const previousTemp = process.env.TEMP
295+
try {
296+
for (const temp of ['Q:\\custom temp', 'Z:\\', '\\\\server\\share\\temp']) {
297+
process.env.TEMP = temp
298+
assert(
299+
resolveBashPathFrom('R:\\workspace', '/tmp/project', 'windows') === pathWin32.join(temp, 'project'),
300+
`must use current temp root ${temp}`,
301+
)
302+
}
303+
} finally {
304+
if (previousTemp === undefined) delete process.env.TEMP
305+
else process.env.TEMP = previousTemp
306+
}
307+
})
308+
}
309+
218310
await test('collapses a repeated cwd suffix from a leading cd', () => {
219311
const root = mkdtempSync(join(tmpdir(), 'tau-workdir-overlap-'))
220312
try {

‎src/tools/BashTool/bashWorkdir.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { statSync } from 'fs'
2-
import { homedir } from 'os'
2+
import { homedir, tmpdir } from 'os'
33
import path from 'path'
44
import pathWin32 from 'path/win32'
55
import { getCwd } from '../../utils/cwd.js'
@@ -159,6 +159,11 @@ export function normalizeForHostFs(
159159
platform: Platform = getPlatform(),
160160
): string {
161161
if (platform !== 'windows') return target
162+
// Match the /tmp alias used by file tools (expandPath) and bashProvider.
163+
// Resolve it before Win32 path handling interprets it as a drive-root path.
164+
if (/^\/tmp(?:\/|$)/.test(target)) {
165+
return pathWin32.join(tmpdir(), target.slice(5))
166+
}
162167
if (!/^(\/[a-zA-Z]\/|\/cygdrive\/|\/\/)/.test(target)) return target
163168
try {
164169
return posixPathToWindowsPath(target)

‎src/utils/Shell.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ export type ExecOptions = {
219219
* lets the model run a command elsewhere without persisting a `cd`.
220220
*/
221221
workdir?: string
222+
/** Return the final cwd as metadata; does not make a workdir override persistent. */
223+
captureFinalCwd?: boolean
222224
/**
223225
* Provider, model and effort of the agent whose own tool call runs this
224226
* command (see shell/agentModelEnv.ts), exported as TAU_PROVIDER,
@@ -251,6 +253,7 @@ export async function exec(
251253
shouldAutoBackground,
252254
onStdout,
253255
workdir,
256+
captureFinalCwd,
254257
agentModelEnv,
255258
} = options ?? {}
256259
const commandTimeout = timeout || DEFAULT_TIMEOUT
@@ -277,6 +280,7 @@ export async function exec(
277280
id,
278281
sandboxTmpDir: shouldUseSandbox ? sandboxTmpDir : undefined,
279282
useSandbox: shouldUseSandbox ?? false,
283+
captureFinalCwd,
280284
})
281285

282286
let commandString = builtCommand
@@ -484,19 +488,24 @@ export async function exec(
484488
if (shouldUseSandbox) {
485489
SandboxManager.cleanupAfterCommand()
486490
}
487-
// Only foreground tasks update the cwd
488-
if (result && !preventCwdChanges && !result.backgroundTaskId) {
491+
// Metadata may also be needed when completion wins a backgrounding race.
492+
// Only foreground tasks without a workdir override update session state.
493+
const updateCwd = !preventCwdChanges && !result.backgroundTaskId
494+
if (captureFinalCwd || updateCwd) {
489495
try {
490496
let newCwd = readFileSync(nativeCwdFilePath, {
491497
encoding: 'utf8',
492498
}).trim()
499+
// Preserve shell spelling for the caller's existing workdir resolver
500+
// (including shell aliases such as /tmp).
501+
if (captureFinalCwd && newCwd) result.finalCwd = newCwd
493502
if (getPlatform() === 'windows') {
494503
newCwd = posixPathToWindowsPath(newCwd)
495504
}
496505
// cwd is NFC-normalized (setCwdState); newCwd from `pwd -P` may be
497506
// NFD on macOS APFS. Normalize before comparing so Unicode paths
498507
// don't false-positive as "changed" on every command.
499-
if (newCwd.normalize('NFC') !== cwd) {
508+
if (updateCwd && newCwd.normalize('NFC') !== cwd) {
500509
setCwd(newCwd, cwd)
501510
invalidateSessionEnvCache()
502511
clearSystemPromptSectionCacheEntry('env_info_simple')

‎src/utils/ShellCommand.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ export type ExecResult = {
2727
outputTaskId?: string
2828
/** Error message when the command failed before spawning (e.g., deleted cwd). */
2929
preSpawnError?: string
30+
/** Internal: final directory in shell spelling, for a normalized leading cd. */
31+
finalCwd?: string
3032
}
3133

3234
export type ShellCommand = {

‎src/utils/bash/defensiveRewrites.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,24 @@ function main(): void {
382382

383383
console.log('\nrewriteAmbiguousInlineCodeQuoting:')
384384

385+
test('keeps separate, correctly quoted arguments separate on every platform', () => {
386+
for (const command of [
387+
'mkdir -p "workflow/child" "workflow/result folder"',
388+
'mkdir -p "/c/work/child" "/c/work/result folder"',
389+
'mkdir -p "C:/work/child" "C:/work/result folder"',
390+
'mkdir -p "/tmp/work/child" "/tmp/work/result folder"',
391+
'cp -r "source folder" "destination folder"',
392+
'grep -e "needle" "input file"',
393+
'runtime --eval "print(1)" "input file"',
394+
'runtime --eval="print(1)" "input file"',
395+
]) {
396+
assertEqual(rewriteAmbiguousInlineCodeQuoting(command), command, command)
397+
for (const platform of ['windows', 'linux', 'macos'] as const) {
398+
assertEqual(applyBashDefensiveRewrites(command, platform), command, `${platform}: ${command}`)
399+
}
400+
}
401+
})
402+
385403
test('preserves nested code quotes for generic --eval payloads', () => {
386404
assertEqual(
387405
rewriteAmbiguousInlineCodeQuoting(

‎src/utils/bash/defensiveRewrites.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,9 @@ export function rewriteAmbiguousInlineCodeQuoting(command: string): string {
637637
if (equals !== -1) {
638638
const rawEquals = word.raw.indexOf('=')
639639
if (rawEquals === -1) continue
640+
// A complete quoted argument has no broken inline quotes to repair.
641+
// Do not absorb a later argument (e.g. --eval="code" "input file").
642+
if (/^"(?:\\.|[^"\\])*"$/.test(word.raw.slice(rawEquals + 1))) continue
640643
const rawStart = word.start + rawEquals + 1
641644
const rawTail = text.slice(rawStart)
642645
const close = rawTail.startsWith('"')
@@ -660,6 +663,11 @@ export function rewriteAmbiguousInlineCodeQuoting(command: string): string {
660663

661664
const argument = words[index + 1]
662665
if (!argument) continue
666+
// Short flags also belong to ordinary commands such as mkdir -p.
667+
if (/^"(?:\\.|[^"\\])*"$/.test(argument.raw)) {
668+
index++
669+
continue
670+
}
663671
const rawTail = text.slice(argument.start)
664672
const close = rawTail.startsWith('"')
665673
? findLastUnescapedDoubleQuote(rawTail)

‎src/utils/permissions/permissions.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,20 @@ async function runPermissionRequestHooksForHeadlessAgent(
511511
return null
512512
}
513513

514+
function parseToolInputForPermissions(tool: Tool, input: Record<string, unknown>) {
515+
const parsedInput = tool.inputSchema.parse(input)
516+
// Bash validation has already moved a leading cd into internal cwd fields.
517+
// Re-parsing with the public schema must not drop the execution directory.
518+
// Model-supplied internals are stripped at toolExecution's input boundary.
519+
if (tool.name === BASH_TOOL_NAME && typeof input.workdir === 'string') {
520+
parsedInput.workdir = input.workdir
521+
if (typeof input._workdirFromCd === 'boolean') {
522+
parsedInput._workdirFromCd = input._workdirFromCd
523+
}
524+
}
525+
return parsedInput
526+
}
527+
514528
export const hasPermissionsToUseTool: CanUseToolFn = async (
515529
tool,
516530
input,
@@ -644,7 +658,7 @@ export const hasPermissionsToUseTool: CanUseToolFn = async (
644658
tool.name !== REPL_TOOL_NAME
645659
) {
646660
try {
647-
const parsedInput = tool.inputSchema.parse(input)
661+
const parsedInput = parseToolInputForPermissions(tool, input)
648662
const acceptEditsResult = await tool.checkPermissions(parsedInput, {
649663
...context,
650664
getAppState: () => {
@@ -1159,7 +1173,7 @@ export async function checkRuleBasedPermissions(
11591173
message: createPermissionRequestMessage(tool.name),
11601174
}
11611175
try {
1162-
const parsedInput = tool.inputSchema.parse(input)
1176+
const parsedInput = parseToolInputForPermissions(tool, input)
11631177
toolPermissionResult = await tool.checkPermissions(parsedInput, context)
11641178
} catch (e) {
11651179
if (e instanceof AbortError || e instanceof APIUserAbortError) {
@@ -1259,7 +1273,7 @@ async function hasPermissionsToUseToolInner(
12591273
message: createPermissionRequestMessage(tool.name),
12601274
}
12611275
try {
1262-
const parsedInput = tool.inputSchema.parse(input)
1276+
const parsedInput = parseToolInputForPermissions(tool, input)
12631277
toolPermissionResult = await tool.checkPermissions(parsedInput, context)
12641278
} catch (e) {
12651279
// Rethrow abort errors so they propagate properly

‎src/utils/shell/bashProvider.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ export async function createBashShellProvider(
7979
id: number | string
8080
sandboxTmpDir?: string
8181
useSandbox: boolean
82+
captureFinalCwd?: boolean
8283
},
8384
): Promise<{ commandString: string; cwdFilePath: string }> {
8485
let snapshotFilePath = await snapshotPromise
@@ -171,9 +172,17 @@ export async function createBashShellProvider(
171172
// When sourcing a file with aliases, they won't be expanded in the same command line
172173
// because the shell parses the entire line before execution. Using eval after
173174
// sourcing causes a second parsing pass where aliases are now available for expansion.
174-
commandParts.push(`eval ${quotedCommand}`)
175-
// Use `pwd -P` to get the physical path of the current working directory for consistency with `process.cwd()`
176-
commandParts.push(`pwd -P >| ${quote([shellCwdFilePath])}`)
175+
const captureCwd = `pwd -P >| ${quote([shellCwdFilePath])}`
176+
if (opts.captureFinalCwd) {
177+
// A normalized leading cd needs the *final* directory, including after
178+
// a failing command. Keep eval in an AND/OR list as before (errexit),
179+
// and preserve its status without installing or replacing shell traps.
180+
commandParts.push(`{ eval ${quotedCommand} && __tau_cwd_status=0 || __tau_cwd_status=$?; ${captureCwd}; exit "$__tau_cwd_status"; }`)
181+
} else {
182+
commandParts.push(`eval ${quotedCommand}`)
183+
// Physical cwd, consistent with process.cwd().
184+
commandParts.push(captureCwd)
185+
}
177186
let commandString = commandParts.join(' && ')
178187

179188
// Apply CLAUDE_CODE_SHELL_PREFIX if set

0 commit comments

Comments
 (0)