Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.agentscope.core.tool.ToolParam;
import io.agentscope.harness.agent.filesystem.model.ExecuteResponse;
import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem;
import java.util.Locale;

/**
* Shell execution tool backed by a {@link AbstractSandboxFilesystem}.
Expand Down Expand Up @@ -68,7 +69,7 @@ public String execute(
return "Error: working_directory must be a relative path within the workspace"
+ " (absolute paths, '~', and '..' are not allowed).";
}
effectiveCommand = "cd '" + wd.replace("'", "'\\''") + "' && " + command;
effectiveCommand = prefixWorkingDirectory(command, wd, System.getProperty("os.name"));
}

int timeoutSeconds = timeout != null && timeout > 0 ? timeout : 30;
Expand All @@ -84,4 +85,15 @@ public String execute(
}
return sb.toString();
}

static String prefixWorkingDirectory(String command, String workingDirectory, String osName) {
if (isWindows(osName)) {
return "cd /d \"" + workingDirectory.replace("\"", "\\\"") + "\" && " + command;
}
return "cd '" + workingDirectory.replace("'", "'\\''") + "' && " + command;
}

private static boolean isWindows(String osName) {
return osName != null && osName.toLowerCase(Locale.ROOT).contains("win");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.agentscope.harness.agent.tool;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
Expand Down Expand Up @@ -65,12 +66,28 @@ void execute_explicitTimeout_isPassedThrough() {

@Test
void execute_withWorkingDirectory_prefixesCd() {
when(sandbox.execute(eq(RT), eq("cd 'sub' && ls"), eq(30)))
String expectedCommand =
ShellExecuteTool.prefixWorkingDirectory("ls", "sub", System.getProperty("os.name"));
when(sandbox.execute(eq(RT), eq(expectedCommand), eq(30)))
.thenReturn(new ExecuteResponse("out", 0, false));

String result = tool.execute(RT, "ls", "sub", null);

assertTrue(result.contains("Exit code: 0"));
verify(sandbox).execute(RT, "cd 'sub' && ls", 30);
verify(sandbox).execute(RT, expectedCommand, 30);
}

@Test
void prefixWorkingDirectory_onWindows_usesCmdCompatibleCd() {
assertEquals(
"cd /d \"sub dir\" && dir",
ShellExecuteTool.prefixWorkingDirectory("dir", "sub dir", "Windows 11"));
}

@Test
void prefixWorkingDirectory_onUnix_keepsSingleQuotedCd() {
assertEquals(
"cd 'it'\\''s' && ls",
ShellExecuteTool.prefixWorkingDirectory("ls", "it's", "Linux"));
}
}
Loading