3434import json, os, sys
3535args = sys.argv[1:]
3636patches = {{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")
3838seen = {{"args": args, "env": {{k: os.environ.get(k) for k in names}}, "patches": patches, "stdin": sys.stdin.read()}}
3939with 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
101101def 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
171174def 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
264267def 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
275303def 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
0 commit comments