Skip to content

Commit 1b4d80e

Browse files
iamziyuzhaoclaude
andcommitted
dsh: keyless servers, timed-out commands and every unfinished run end, as dsh 0.2.2 reports them
Checked against dsh's source at the tag dsh-v0.2.2-rc.1 and against the installed dsh: - A backend that needs no key: a pi-ai route that names no key variable gets no key under the route name `hermit`, so dsh refused every request (PI_AI_ERROR "No API key"). The session's route now names HERMIT_DSH_NO_KEY, which holds the placeholder key `local`, as Pi's models.json and Claude Code's environment send it. - A command stopped by its timeout (`[timed out after Nms]`) or from outside (`[stopped: ...]`) has an unknown exit code; one that trapped the signal and exited 0 read as a clean exit before. - A run that ends otherwise than completed (max-tokens, blocked, interrupted, ...) is an error in the trajectory and the notices, not only an error or an abort. dsh exits 1 for them and writes nothing on stderr. - STREAM_CLOSED (a stream the provider closed, which dsh does not retry) is an outage, as Codex's "stream disconnected" is. - DSH_TELEMETRY_DISABLED=1 in the session: dsh exports telemetry only after feedback, which a headless run never gives, and with it makes no anonymous id either. - The system-prompt reason, exactly: dsh's persona text takes only {{provider}} and {{model}}, and any other {{...}} fails the model's step. Tests: bash.jsonl re-recorded with two timeouts (8 bash endings), a new max_tokens.jsonl, a placeholder-key test with the fake and one with the installed dsh (it reaches the server with "Bearer local"; another provider's key in the environment is not sent), STREAM_CLOSED in the outage test, and a --dump-config check that every row the session patches exists in the installed dsh (dsh ignores an unknown row id without saying so). Each new test failed with its fix undone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c567239 commit 1b4d80e

6 files changed

Lines changed: 141 additions & 31 deletions

File tree

‎hermit/agent/base/cli.py‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@
101101
r"error sending request|too many requests|service unavailable|bad gateway|overloaded|"
102102
r"model is at capacity|"
103103
r"^(?:429|5\d\d): |" # Pi's report of a provider's status
104-
r"^dsh: (?:RATE_LIMIT|SERVER|TIMEOUT|TRANSPORT|EMPTY_RESPONSE): |" # dsh's, by its codes
104+
# dsh's, by its codes: those it retries itself, and a stream the provider closed
105+
r"^dsh: (?:RATE_LIMIT|SERVER|TIMEOUT|TRANSPORT|EMPTY_RESPONSE|STREAM_CLOSED): |"
105106
r"error response from daemon|cannot connect to the docker daemon|"
106107
+ re.escape(container.MISSING), re.I | re.M)
107108
CODEX_HOME_SETTINGS = ["features.shell_snapshot = false", # a snapshot would bring back the whole environment
@@ -1078,6 +1079,9 @@ def _pi_session(home: Path, handle) -> Path | None:
10781079
DSH_OFF = ("session-telemetry-otel", "session-title-llm", "plugin-package-inventory-deepseek", "tool-subagent",
10791080
"tool-subagent-fork", "tool-subagent-control", "tool-workflow")
10801081
DSH_PERMISSION_MODES = ("read-only", "workspace-write", "danger-full-access")
1082+
# The variable a route names for a server that needs no key: a route that names none gets no key from pi-ai under
1083+
# the name `hermit`, and dsh refuses the request (PI_AI_ERROR "No API key")
1084+
DSH_NO_KEY = "HERMIT_DSH_NO_KEY"
10811085

10821086

10831087
class Dsh(CliAgent):
@@ -1100,8 +1104,11 @@ class Dsh(CliAgent):
11001104
def home_env(self, home):
11011105
"""Every variable dsh reads goes here, so that it passes the sandbox's filter: its home, HOME, and the shared
11021106
agents' folder dsh reads skills and AGENTS.md from (~/.agents unless DSH_AGENTS_HOME says another), so none of
1103-
the user's own is read."""
1104-
return {"DSH_HOME": str(home), "HOME": str(home), "DSH_AGENTS_HOME": str(home / ".agents")}
1107+
the user's own is read; telemetry off (no anonymous id is made either); the placeholder key of a server that
1108+
needs none (DSH_NO_KEY)."""
1109+
from hermit.agent.model.backends import PLACEHOLDER_KEY
1110+
return {"DSH_HOME": str(home), "HOME": str(home), "DSH_AGENTS_HOME": str(home / ".agents"),
1111+
"DSH_TELEMETRY_DISABLED": "1", DSH_NO_KEY: PLACEHOLDER_KEY}
11051112

11061113
def prepare_home(self, home, roles, tools_url, tools_name):
11071114
"""The patch layer (DSH_PATCH): dsh's own rows, by their ids. A row's `config` replaces the row's, so the
@@ -1121,6 +1128,7 @@ def prepare_home(self, home, roles, tools_url, tools_name):
11211128
default, chosen = {"provider": DSH_ROUTE}, {}
11221129
if s.get("provider"):
11231130
provider = json.loads(json.dumps(s["provider"]))
1131+
provider.setdefault("apiKeyEnv", DSH_NO_KEY) # a server that needs no key: the placeholder
11241132
for model in provider.get("models") or []:
11251133
if effort: # a declared model reasons only at the levels it lists; off: it does not reason
11261134
model.setdefault("reasoningEfforts", False if effort == "off" else {effort: effort})
@@ -1149,8 +1157,9 @@ def web_search_args(cls, enabled: bool) -> list[str]:
11491157
return []
11501158

11511159
def system_settings(self, system, prompt):
1152-
"""dsh takes no system prompt for one run (its persona rows interpolate `{{name}}`, which instructions may
1153-
hold): the instructions go at the top of the prompt, as a marked block."""
1160+
"""dsh takes no system prompt for one run, and its persona text (the system-prompt row) takes only the
1161+
variables `{{provider}}` and `{{model}}`: any other `{{...}}`, which instructions may hold, fails the model's
1162+
step. The instructions go at the top of the prompt instead, as a marked block."""
11541163
return {}, f"# SYSTEM INSTRUCTIONS\n\n{system}\n\n# END\n\n{prompt}"
11551164

11561165
@staticmethod
@@ -1172,11 +1181,12 @@ def exit_code(self, code, raw):
11721181

11731182
@classmethod
11741183
def errors(cls, event):
1175-
"""A run that ended in an error, as dsh writes it on stderr (`dsh: <code>: <message>`: the code is how a
1176-
provider that could not serve is told, UNAVAILABLE), or in an abort; a failure outside a turn."""
1184+
"""A run that did not complete: an error, as dsh writes it on stderr (`dsh: <code>: <message>`: the code is
1185+
how a provider that could not serve is told, UNAVAILABLE), or any other end (aborted, max-tokens, blocked,
1186+
interrupted, ...); a failure outside a turn."""
11771187
kind = event.get("type")
11781188
reason = event.get("reason") if isinstance(event.get("reason"), dict) else {}
1179-
if kind == "final" and reason.get("kind") in ("error", "aborted"):
1189+
if kind == "final" and reason.get("kind") not in (None, "completed"):
11801190
error = reason.get("error") if isinstance(reason.get("error"), dict) else {}
11811191
if error.get("code"):
11821192
return [f"dsh: {error['code']}: {error.get('message') or ''}"]

‎hermit/agent/base/trajectory.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -214,21 +214,24 @@ def pi_steps(stream: list[dict]) -> list[Step]:
214214

215215
DSH_FILE_TOOLS = ("write", "edit")
216216
# How dsh's bash tool ends a command's result (its own parseExitStatus reads it so): a nonzero exit or a signal is
217-
# marked last, a clean exit is not; a command still running was moved to the background, unfinished
217+
# marked last, a clean exit is not; a command stopped by its timeout or from outside is marked before that (a command
218+
# that traps the signal may still exit 0), and one still running was moved to the background, unfinished
218219
DSH_EXIT = re.compile(r"\n\[exit code: (\d+)\]$")
219220
DSH_SIGNAL = re.compile(r"\n\[killed by signal: [^\]\n]+\]$")
221+
DSH_STOPPED = re.compile(r"\n\[(?:timed out after \d+ms|stopped: [^\]\n]*)\](?:\n\[[^\]\n]*\])*$")
220222
DSH_BACKGROUND = re.compile(r"\[still running after \d+ms; moved to background job [^\]\n]+\]$")
221223
DSH_NO_OUTPUT = "(no output)" # what the result holds before its marker when the command printed nothing
222224

223225

224226
def dsh_steps(stream: list[dict]) -> list[Step]:
225227
"""DeepSeek Harness's `--json` events: its thinking and text as each model step committed them, and each
226228
`tool_call` completed by its `tool_result`: bash as a command whose exit code and output are read from the
227-
result as dsh reads them (`[exit code: N]` after the output; no marker: 0; a signal, a command moved to the
228-
background or a call that failed to run: unknown; `(no output)`: empty), write and edit as file changes, an
229-
MCP tool (`mcp__<server>__<tool>`) as a tool call with its server and arguments and its result as `output`, any
230-
other tool as a tool call; a run that ended in an error or an abort (the `final` event's reason), or failed
231-
outside a turn (an `error` event), as an error. Status events and usage are left out."""
229+
result as dsh reads them (`[exit code: N]` after the output; no marker: 0; a signal, a timeout, a stop, a command
230+
moved to the background or a call that failed to run: unknown; `(no output)`: empty), write and edit as file
231+
changes, an MCP tool (`mcp__<server>__<tool>`) as a tool call with its server and arguments and its result as
232+
`output`, any other tool as a tool call; a run that did not complete (the `final` event's reason: an error, an
233+
abort, the token limit, ...), or failed outside a turn (an `error` event), as an error. Status events and usage
234+
are left out."""
232235
steps, pending = [], {}
233236
for event in stream:
234237
kind = event.get("type")
@@ -263,12 +266,12 @@ def dsh_steps(stream: list[dict]) -> list[Step]:
263266
output = result[:found.start()] if found else result
264267
step.output = "" if output == DSH_NO_OUTPUT else output
265268
unknown = event.get("status") != "completed" or DSH_SIGNAL.search(result) or \
266-
DSH_BACKGROUND.search(result)
269+
DSH_STOPPED.search(result) or DSH_BACKGROUND.search(result)
267270
step.exit_code = None if unknown else int(found.group(1)) if found else 0
268271
elif step.kind == "tool_call":
269272
step.output = result
270273
elif kind == "final" and isinstance(event.get("reason"), dict) and \
271-
event["reason"].get("kind") in ("error", "aborted"):
274+
event["reason"].get("kind") not in (None, "completed"):
272275
error = event["reason"].get("error") if isinstance(event["reason"].get("error"), dict) else {}
273276
steps.append(Step("error", str(error.get("message") or f"run {event['reason']['kind']}")))
274277
elif kind == "error":

‎tests/core/test_dsh_agent.py‎

Lines changed: 81 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
import json, os, sys
3535
args = sys.argv[1:]
3636
patches = {{args[i + 1]: open(args[i + 1]).read() for i, a in enumerate(args[:-1]) if a == "--patch"}}
37-
names = ("DSH_HOME", "HOME", "DSH_AGENTS_HOME", "FAKE_KEY")
37+
names = ("DSH_HOME", "HOME", "DSH_AGENTS_HOME", "DSH_TELEMETRY_DISABLED", "{base_cli.DSH_NO_KEY}", "FAKE_KEY")
3838
seen = {{"args": args, "env": {{k: os.environ.get(k) for k in names}}, "patches": patches, "stdin": sys.stdin.read()}}
3939
with open(os.environ["FAKE_DSH_SEEN"], "a") as f:
4040
f.write(json.dumps(seen) + "\\n")
@@ -95,7 +95,7 @@ def test_a_bound_model_is_a_dsh_route_with_its_key_variable_in_the_dialect_the_b
9595
system = bound(developer_role="system", context_window=32000)["provider"]
9696
assert system["compat"] == {"supportsDeveloperRole": False} and system["models"][0]["contextWindow"] == 32000
9797
free = bound(api_key_env="NO_SUCH_KEY_VAR", key_required=False)["provider"]
98-
assert "apiKeyEnv" not in free # a server that needs no key: dsh sends none
98+
assert "apiKeyEnv" not in free # a server that needs no key: the session names the placeholder
9999

100100

101101
def test_dsh_runs_headless_in_its_home_with_its_model_and_the_tools_as_its_own(fake):
@@ -110,6 +110,7 @@ def test_dsh_runs_headless_in_its_home_with_its_model_and_the_tools_as_its_own(f
110110
assert call["args"][4:9] == ["--json", "--permission-mode", "workspace-write", "--approval-policy", "never"]
111111
assert call["args"][-2:] == ["--", "-a prompt that starts with a dash"]
112112
assert call["env"] == {"DSH_HOME": str(home), "HOME": str(home), "DSH_AGENTS_HOME": str(home / ".agents"),
113+
"DSH_TELEMETRY_DISABLED": "1", base_cli.DSH_NO_KEY: "local",
113114
"FAKE_KEY": "sk-fake"} # none of the user's own skills or AGENTS.md
114115
layer = rows(call, home)
115116
assert "sk-fake" not in json.dumps(layer)
@@ -166,6 +167,8 @@ def test_a_failed_run_is_an_error_and_an_outage_is_retried(fake, monkeypatch):
166167
assert [s.kind for s in result.trajectory] == ["error"] and result.trajectory[0].text.startswith("503: ")
167168
refused = (STREAMS / "failure.jsonl").read_text().replace('"SERVER"', '"AUTH"').replace("dsh: SERVER:", "dsh: AUTH:")
168169
assert not base_cli.UNAVAILABLE.search(base_cli.notices("dsh", refused)) # a bad key is no outage
170+
closed = (STREAMS / "failure.jsonl").read_text().replace("SERVER", "STREAM_CLOSED") # dsh does not retry it
171+
assert base_cli.UNAVAILABLE.search(base_cli.notices("dsh", closed))
169172

170173

171174
def test_a_run_dsh_was_stopped_in_is_no_success_although_dsh_exits_0(fake, monkeypatch, tmp_path):
@@ -263,13 +266,38 @@ def test_a_dsh_stream_is_read_back_by_its_name_or_by_its_events(tmp_path):
263266

264267
def test_a_bash_result_is_read_as_dsh_marks_its_end():
265268
"""dsh marks a nonzero exit (`[exit code: N]`) or a signal after a command's output and nothing after a clean
266-
exit; `(no output)` stands for an empty output, also before a marker. A signal's exit code is unknown, as Codex
267-
reports it."""
269+
exit; `(no output)` stands for an empty output, also before a marker. A command stopped by its timeout has no
270+
exit code to trust, even one that trapped the signal and exited 0 (it read as a clean exit before), as a
271+
signal's has none: unknown, as Codex reports it."""
268272
stream = [json.loads(line) for line in (STREAMS / "bash.jsonl").read_text().splitlines()]
269273
commands = [(s.command, s.exit_code, s.output) for s in trajectory.dsh_steps(stream) if s.kind == "command"]
270274
assert commands == [("exit 3", 3, ""), ("printf ''", 0, ""), ("true", 0, ""), ("echo out; exit 4", 4, "out"),
271275
("kill -9 $$", None, "(no output)\n[killed by signal: SIGKILL]"),
272-
("printf 'no newline'; exit 5", 5, "no newline")]
276+
("printf 'no newline'; exit 5", 5, "no newline"),
277+
("trap 'exit 0' TERM; sleep 5 & wait", None, "(no output)\n[timed out after 1000ms]"),
278+
("sleep 5", None, "(no output)\n[timed out after 1000ms]\n[killed by signal: SIGTERM]")]
279+
280+
281+
def test_a_run_that_ends_at_the_token_limit_is_an_error_the_learner_can_read():
282+
"""dsh exits 1 for a run that ends `max-tokens` and writes nothing on stderr: the run is no success and no
283+
outage, and its end is a step of the trajectory and a notice (only errors and aborts were, before)."""
284+
raw = (STREAMS / "max_tokens.jsonl").read_text()
285+
assert not base_cli.served("dsh", raw) and base_cli.notices("dsh", raw) == "run max-tokens"
286+
assert not base_cli.UNAVAILABLE.search(base_cli.notices("dsh", raw))
287+
steps = trajectory.dsh_steps([json.loads(line) for line in raw.splitlines()])
288+
assert [(s.kind, s.text) for s in steps] == [("message", "partial answ"), ("error", "run max-tokens")]
289+
290+
291+
def test_a_server_that_needs_no_key_gets_the_placeholder_key(fake):
292+
"""A route that names no key variable gets no key from pi-ai under the name `hermit`, and dsh refuses every
293+
request (PI_AI_ERROR "No API key"): the session names a variable that holds the placeholder key instead."""
294+
work = fake / "work"
295+
work.mkdir()
296+
params = bound(api_key_env="NO_SUCH_KEY_VAR", key_required=False)
297+
make("dsh", {**params, "web_search": False, "home": str(fake / "home")}).run("go", workspace=work)
298+
[call] = seen(fake)
299+
route = row(rows(call, fake / "home"), "llm-pi-ai")["config"]["providers"][base_cli.DSH_PROVIDER]
300+
assert route["apiKeyEnv"] == base_cli.DSH_NO_KEY and call["env"][base_cli.DSH_NO_KEY] == "local"
273301

274302

275303
def test_the_dsh_acting_agent_deploys_the_adapter_and_loads_its_patch_layer(fake):
@@ -322,9 +350,10 @@ def __init__(self, root):
322350

323351
# ---------- the installed dsh (integration) ----------
324352

325-
def serve_chat(script):
353+
def serve_chat(script, keys=None):
326354
"""A chat-completions model on the loopback: `script(request body) -> (tool call (name, arguments) | None)`;
327-
None answers `the answer`. Every response is streamed, with usage."""
355+
None answers `the answer`. Every response is streamed, with usage. `keys` collects each request's
356+
Authorization header."""
328357
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
329358

330359
def chunk(body):
@@ -336,6 +365,8 @@ def log_message(self, *args):
336365

337366
def do_POST(self):
338367
body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")
368+
if keys is not None:
369+
keys.append(self.headers.get("authorization"))
339370
call = script(body)
340371
delta = {"role": "assistant", "tool_calls": [{"index": 0, "id": "call_1", "type": "function",
341372
"function": {"name": call[0],
@@ -443,3 +474,46 @@ def script(body):
443474
[answer] = [m for m in requests[1]["messages"] if m.get("role") == "tool"]
444475
assert json.loads(answer["content"] if isinstance(answer["content"], str) else
445476
"".join(p.get("text", "") for p in answer["content"])) == {"count": 3}
477+
478+
479+
@pytest.mark.integration
480+
@pytest.mark.skipif(not shutil.which("dsh"), reason="needs the dsh CLI")
481+
def test_with_the_dsh_cli_a_server_that_needs_no_key_is_reached_with_the_placeholder(tmp_path, monkeypatch):
482+
"""A backend that needs no key (a local server): the installed dsh refused every request of a route that named
483+
no key variable (PI_AI_ERROR "No API key"); the session's placeholder reaches the server, and a key of another
484+
provider in the environment (OPENAI_API_KEY) is never sent."""
485+
keys = []
486+
server, url = serve_chat(lambda body: None, keys)
487+
monkeypatch.setenv("OPENAI_API_KEY", "sk-another-provider")
488+
params = bind_agent_params({"model": "local/m-1"}, "dsh", registry(
489+
{"local": {"base_url": url, "api_key_env": "NO_SUCH_KEY_VAR", "key_required": False, "apis": ["chat"]}}))
490+
work = tmp_path / "work"
491+
work.mkdir()
492+
try:
493+
result = make("dsh", {**params, "web_search": False, "home": str(tmp_path / "home"),
494+
"timeout_s": 300}).run("Answer.", workspace=work)
495+
finally:
496+
server.shutdown()
497+
assert result.exit_code == 0 and result.reply == "the answer" and keys == ["Bearer local"]
498+
499+
500+
@pytest.mark.integration
501+
@pytest.mark.skipif(not shutil.which("dsh"), reason="needs the dsh CLI")
502+
def test_the_installed_dsh_has_every_row_the_session_patches(tmp_path):
503+
"""A patch row whose id dsh does not have is ignored, and dsh says so only when asked (--dump-config, which
504+
starts nothing and reaches no network): every row the session's layer names (telemetry, title, sub-agents, the
505+
web tools, the route, the default model) is one of the installed dsh's, so none is silently left on."""
506+
home = tmp_path / "home"
507+
home.mkdir()
508+
agent = make("dsh", {**bound(), "effort": "high", "web_search": False})
509+
agent.prepare_home(home, (), "http://127.0.0.1:9/mcp", "hermit_tools")
510+
layer = json.loads((home / base_cli.DSH_PATCH).read_text())
511+
assert {r["id"] for r in layer if "id" in r} >= {*base_cli.DSH_OFF, "session-log-deepseek", "tool-web",
512+
"llm-pi-ai", "agent-default-model"}
513+
work = tmp_path / "work"
514+
work.mkdir()
515+
env = {**os.environ, **agent.home_env(home)}
516+
done = subprocess.run(["dsh", "--profile", "headless", "--patch", str(home / base_cli.DSH_PATCH),
517+
"--dump-config"], cwd=work, env=env, capture_output=True, text=True, timeout=120)
518+
assert done.returncode == 0, done.stderr
519+
assert "not found" not in done.stderr and "id: llm-pi-ai" in done.stdout

‎tests/fixtures/dsh/README.md‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,17 @@ delta before each answer when it is asked for a reasoning effort.
1111
- `resume.jsonl`: the same session resumed (`--session-id`): one request.
1212
- `failure.jsonl`: every request answered 503; dsh retries five times, ends the run with the error `SERVER`, writes
1313
`dsh: SERVER: ...` on stderr (the last line, which the Base Agent keeps in the stream) and exits 1.
14-
- `bash.jsonl`: how dsh's bash tool marks a command's end, recorded by running dsh directly (`dsh --profile headless
15-
--json --permission-mode danger-full-access`, with a patch layer like the Base Agent's) against a scripted model
16-
that calls bash six times: `exit 3`, `printf ''`, `true`, `echo out; exit 4`, `kill -9 $$` and
17-
`printf 'no newline'; exit 5`, then answers `done`.
1814

19-
The streams are dsh's output unchanged; the run's directory was `/run`.
15+
Recorded by running dsh directly (`dsh --profile headless --json --permission-mode danger-full-access`, with a patch
16+
layer like the Base Agent's) against a scripted chat-completions model:
17+
18+
- `bash.jsonl`: how dsh's bash tool marks a command's end. The model calls bash eight times: `exit 3`, `printf ''`,
19+
`true`, `echo out; exit 4`, `kill -9 $$`, `printf 'no newline'; exit 5`, then with `timeoutMs: 1000`
20+
`trap 'exit 0' TERM; sleep 5 & wait` (stopped by its timeout, it exits 0) and `sleep 5` (killed), then answers
21+
`done`. The layer also sets the `tool-bash` row's `promoteOnTimeout: false`, so a timeout stops the command rather
22+
than moving it to a background job.
23+
- `max_tokens.jsonl`: the model's answer ends at its token limit (`finish_reason: length`): the run ends `max-tokens`
24+
and dsh exits 1, writing nothing on stderr.
25+
26+
The streams are dsh's output unchanged; the run's directory was `/run` (`/run/bash` and `/run/max_tokens` for the
27+
last two).

0 commit comments

Comments
 (0)