Skip to content

[Bug]: execute tool fails on any command whose last line is a heredoc terminator #3198

Closed

Description

@zhangqian7741

Describe the bug

Any command sent through the execute tool (ShellExecuteTool) fails if its last line is a heredoc terminator. The command is valid shell and works verbatim when run by hand. The error that comes back is a shell syntax error that mentions neither the heredoc nor its delimiter, so it reads as "heredocs are unavailable in the sandbox".

Something is appended to the command's final line before it reaches the shell. When that line is the closing delimiter, the delimiter stops matching, the heredoc consumes the rest of the input, and the shell reports an unterminated construct at the last line of the content.

This is the same family as the transport/escaping bugs already fixed or reported here — #2925 (Windows docker exec), #3084 (bash -lc escaping in edit()), #2618 (base64 payload in argv) — but it needs no large payload and no Windows: it reproduces with a three-line heredoc on Linux.

To Reproduce

  1. Call the execute tool with a command whose last line is the terminator:
cd /workspace/runs/1/work && python3 - <<'EOF'
import json
d = {'a': 1}
for k in d:
    if k in ('SRC-a','SRC-b','SRC-c'):
        print(k)
print("done")
EOF
  1. The call fails. The same command with one trailing newline, or with any command after the terminator (wc -c file), succeeds.

Where the appended text lands can be reproduced exactly outside the framework. Wrapping the command in ( … ) with the closing paren concatenated onto the end of the string reproduces the error string, wording and line number exactly, while two other plausible appendages do not:

import subprocess
lines = ["cd /tmp && python3 - <<'EOF'", "import json",
         "with open('/dev/null') as f:", "    pass", "d = {'a': 1}", "for k in d:",
         "    if k in ('SRC-a','SRC-b','SRC-c'):", "        print(k)",
         "with open('/dev/null') as f:", "    pass", 'print("done")', "EOF"]
cmd = "\n".join(lines)

for label, wrapped in [
    ("no wrapper",                 cmd),
    ("( … ) closing paren on its own line", "( " + cmd + "\n)"),
    ("( … ) closing paren appended to the last line", "( " + cmd + " )"),
    ("`< /dev/null` appended",      cmd + " < /dev/null"),
    ("`; echo EXIT:$?` appended",   cmd + " ; echo EXIT:$?"),
]:
    r = subprocess.run(["/bin/dash", "-c", wrapped], capture_output=True, text=True)
    print(label, "->", r.returncode, (r.stderr or r.stdout).strip().splitlines()[:1])
no wrapper                                      -> 0 ['done']
( … ) closing paren on its own line             -> 0 ['done']
( … ) closing paren appended to the last line   -> 2 ['/bin/dash: 12: Syntax error: end of file unexpected (expecting ")")']
`< /dev/null` appended                          -> 1 ['  File "<stdin>", line 11']
`; echo EXIT:$?` appended                       -> 1 ['  File "<stdin>", line 11']

Only the third matches what the tool returns, so the appended text is on the command's last line rather than on a new one.

Expected behavior

execute advertises "Execute a shell command". A command ending in a heredoc terminator is a shell command and should run. Either the command should not be modified, or whatever is appended should go on its own line.

Error messages

What the tool returned for the command above:

Exit code: 2

/bin/sh: 12: Syntax error: end of file unexpected (expecting ")")

Line 12 is the EOF line. Nothing in the message points at the heredoc, the delimiter, or the appended text.

Environment

  • AgentScope-Java Version: 2.0.2 (agentscope-harness, agentscope-core)
  • Java Version: 17
  • OS: Linux (sandbox container); /bin/sh is dash, judging by the sh: <line>: Syntax error format
  • Sandbox: Kubernetes (agentscope-extensions-sandbox-kubernetes, agent-sandbox)

Additional context

Where the modification happens, as far as I could trace it: ShellExecuteTool.execute passes command through unchanged unless working_directory is set; SandboxBackedFilesystem.execute forwards it to Sandbox.exec; CommandExecutor POSTs {"command": …} to the sandbox's /execute endpoint. I found no ( … ) wrapping in agentscope-harness or in the Kubernetes client, so it looks server-side — but the tool is the surface where it is observable, and a one-line defence here would cover every sandbox backend:

// ShellExecuteTool.execute, before handing the command over
String effectiveCommand = command.endsWith("\n") ? command : command + "\n";

That is the same shape of defence as #3084 (base64 + stdin rather than relying on the shell's quoting). A server-side fix (append on a new line, or do not wrap) would be the real one; the trailing newline works for the behaviour observed above and would stop being needed once that lands.

Why this is worth more than the syntax error suggests. The failure teaches the wrong lesson. The error names nothing related to heredocs and the identical command works by hand, so an agent that hits it concludes heredocs are unavailable and switches to write_file a script, then execute the script — two tool calls for every one, for the rest of the run. In one 25-minute run of ours the agent did that three times after a single failure of this kind. It also removes cat >> file <<'EOF' as a way to build a file larger than one tool call can carry, which pushes the model toward writing many small files plus a merge script instead.

Activity

  1. oss-maintainer commented on Sep 18, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed (reproduced by code inspection on main @ dc15ff42c; also present in v2.0.2)

    Root cause — the wrapping IS in this repo (client side), and it is Kubernetes-specific.

    KubernetesSandbox.doExec concatenates the closing parenthesis directly onto the end of the command string:

    // agentscope-extensions/.../sandbox/kubernetes/KubernetesSandbox.java:91
    String wrapped = "cd " + shellQuote(k8sState.getWorkspaceRoot()) + " && (" + command + ")";

    When the command's last line is a heredoc terminator, the line the shell sees is EOF) instead of EOF, the delimiter never matches, the heredoc swallows the rest of the input, and dash fails at the last line with Syntax error: end of file unexpected (expecting ")") — the exact wording and line number reported here. Your ( … ) "closing paren appended to the last line" experiment matches the code path precisely.

    Blast radius: only the Kubernetes backend wraps. Other execution paths pass the command verbatim, which is why this is not observable with Docker/local/AgentRun:

    Path Code Wrapping
    Kubernetes sandbox KubernetesSandbox.java:91 cd <root> && (cmd) ← bug
    Docker sandbox DockerSandbox.java:156 (sh -c <command>) none
    Local filesystem LocalFilesystemWithShell.java:338 (sh -c <command>) none
    AgentRun sandbox AgentRunSandbox.java:119 (mcp.exec(command, …)) none

    The working_directory branch in ShellExecuteTool.java:64-98 only prefixes cd '<wd>' && , so it is not the cause (and it does not help either: the closing ) still lands on the terminator line).

    Suggested fix — put the subshell delimiters on their own lines, which fixes the defect at the place that creates it instead of masking it downstream:

    String wrapped = "cd " + shellQuote(k8sState.getWorkspaceRoot()) + " && (\n" + command + "\n)";

    The command.endsWith("\n") ? … : + "\n" guard in ShellExecuteTool.execute would hide the symptom for the Kubernetes path, but it changes the payload for every backend and leaves the wrapping bug in place, so it is better treated as optional hardening than as the fix.

    Note that KubernetesSandboxTest.java:78 currently pins the broken shape (assertEquals("cd '/workspace' && (echo hi)", …)); it needs updating together with the fix, plus a case whose command ends with a heredoc terminator asserting a newline before the closing ).

    Severity: medium (scoped to the Kubernetes sandbox), high impact on agent reliability — as you wrote, the error message teaches the agent to abandon heredocs for the rest of the run.

    An automated fix proposal will follow. Reply /approve to proceed with PR generation, /revise <text> to change the approach, or /reject to stop.


    Automated evaluation by github-manager-bot

  2. added
    bug
    area/extensions
    on Sep 18, 2026
  3. added a commit that references this issue on Sep 20, 2026
    c767160
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/extensionsbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions