test_client.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. from __future__ import annotations
  2. import json
  3. import inspect
  4. import sys
  5. import threading
  6. import time
  7. from pathlib import Path
  8. import pytest
  9. from deepseek_harness import DeepSeekHarness, HarnessClient, HarnessConfig, Notification, RunResult, SdkProtocolError
  10. from deepseek_harness.errors import JsonRpcError
  11. def test_high_level_sdk_runs_turn_and_collects_final_response(tmp_path: Path) -> None:
  12. script = tmp_path / "fake_runtime.py"
  13. env_dump = tmp_path / "env.json"
  14. init_dump = tmp_path / "init.json"
  15. script.write_text(
  16. """
  17. import json
  18. import os
  19. import sys
  20. env_dump = os.environ["ENV_DUMP"]
  21. json.dump({
  22. "DEEPSEEK_API_KEY": os.environ.get("DEEPSEEK_API_KEY"),
  23. "DEEPSEEK_BASE_URL": os.environ.get("DEEPSEEK_BASE_URL"),
  24. "DSH_CWD": os.environ.get("DSH_CWD"),
  25. "DSH_SESSION_ROOT": os.environ.get("DSH_SESSION_ROOT"),
  26. "DSH_CORDIS_CONFIG": os.environ.get("DSH_CORDIS_CONFIG"),
  27. }, open(env_dump, "w"))
  28. for line in sys.stdin:
  29. msg = json.loads(line)
  30. method = msg.get("method")
  31. if method == "initialize":
  32. json.dump(msg.get("params"), open(os.environ["INIT_DUMP"], "w"))
  33. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  34. elif method == "session/prompt":
  35. params = msg.get("params") or {}
  36. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  37. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "running"}}), flush=True)
  38. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  39. print(json.dumps({
  40. "jsonrpc": "2.0",
  41. "method": "session.event",
  42. "params": {
  43. "sessionId": params["sessionId"],
  44. "event": {
  45. "type": "assistant/message",
  46. "data": {
  47. "message": {
  48. "role": "assistant",
  49. "content": [{"type": "text", "text": "hello from runtime"}],
  50. },
  51. },
  52. },
  53. },
  54. }), flush=True)
  55. print(json.dumps({
  56. "jsonrpc": "2.0",
  57. "method": "session.event",
  58. "params": {
  59. "sessionId": params["sessionId"],
  60. "event": {
  61. "type": "turn/end",
  62. "data": {"turn": 1, "reason": {"kind": "completed"}},
  63. },
  64. },
  65. }), flush=True)
  66. print(json.dumps({
  67. "jsonrpc": "2.0",
  68. "method": "session.event",
  69. "params": {
  70. "sessionId": params["sessionId"],
  71. "event": {
  72. "type": "turn/end",
  73. "data": {"turn": 2, "reason": {"kind": "max-tokens"}},
  74. },
  75. },
  76. }), flush=True)
  77. print(json.dumps({
  78. "jsonrpc": "2.0",
  79. "method": "session.status",
  80. "params": {"sessionId": params["sessionId"], "status": "idle"},
  81. }), flush=True)
  82. elif method == "shutdown":
  83. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  84. break
  85. """.strip()
  86. )
  87. with DeepSeekHarness(
  88. model="deepseek-v4-flash",
  89. max_tokens=4096,
  90. cwd=str(tmp_path),
  91. _launch_args=(sys.executable, str(script)),
  92. env={
  93. "ENV_DUMP": str(env_dump),
  94. "INIT_DUMP": str(init_dump),
  95. "DEEPSEEK_API_KEY": "env-key",
  96. "DEEPSEEK_BASE_URL": "http://127.0.0.1:4321",
  97. },
  98. ) as harness:
  99. result = harness.run("say hello", session_id="main")
  100. assert result.final_response == "hello from runtime"
  101. assert result.finish_reason == "max-tokens"
  102. assert result.events[-1]["type"] == "turn/end"
  103. dumped_env = json.loads(env_dump.read_text())
  104. assert dumped_env["DEEPSEEK_API_KEY"] == "env-key"
  105. assert dumped_env["DEEPSEEK_BASE_URL"] == "http://127.0.0.1:4321"
  106. assert dumped_env["DSH_CWD"] is None
  107. assert dumped_env["DSH_SESSION_ROOT"] is None
  108. assert dumped_env["DSH_CORDIS_CONFIG"] is None
  109. assert json.loads(init_dump.read_text()) == {
  110. "cwd": str(tmp_path),
  111. "provider": "deepseek-official",
  112. "model": "deepseek-v4-flash",
  113. "maxTokens": 4096,
  114. }
  115. def test_session_run_invokes_notification_callback_before_returning(tmp_path: Path) -> None:
  116. script = tmp_path / "fake_runtime.py"
  117. script.write_text(
  118. """
  119. import json
  120. import sys
  121. for line in sys.stdin:
  122. msg = json.loads(line)
  123. method = msg.get("method")
  124. if method == "initialize":
  125. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  126. elif method == "session/prompt":
  127. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": "main", "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  128. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": "main", "status": "running"}}), flush=True)
  129. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  130. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.started", "params": {"parentSessionId": "main", "childSessionId": "child"}}), flush=True)
  131. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": "main", "status": "idle"}}), flush=True)
  132. elif method == "shutdown":
  133. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  134. break
  135. """.strip()
  136. )
  137. seen: list[str] = []
  138. with DeepSeekHarness(
  139. _launch_args=(sys.executable, str(script)),
  140. cwd=str(tmp_path),
  141. ) as harness:
  142. session = harness.start_session("main")
  143. result = session.run(
  144. "spawn a helper",
  145. on_notification=lambda notification: seen.append(notification.method),
  146. )
  147. assert seen == ["session.event", "session.status", "subagent.started", "session.status"]
  148. assert result.finish_reason is None
  149. def test_high_level_sdk_rejects_turn_end_without_reason_kind(tmp_path: Path) -> None:
  150. script = tmp_path / "fake_runtime.py"
  151. script.write_text(
  152. """
  153. import json
  154. import sys
  155. for line in sys.stdin:
  156. msg = json.loads(line)
  157. method = msg.get("method")
  158. if method == "initialize":
  159. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  160. elif method == "session/prompt":
  161. params = msg.get("params") or {}
  162. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  163. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  164. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "turn/end", "data": {"turn": 1, "reason": {}}}}}), flush=True)
  165. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "idle"}}), flush=True)
  166. elif method == "shutdown":
  167. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  168. break
  169. """.strip()
  170. )
  171. with DeepSeekHarness(
  172. _launch_args=(sys.executable, str(script)),
  173. cwd=str(tmp_path),
  174. ) as harness:
  175. with pytest.raises(
  176. SdkProtocolError,
  177. match=r"turn/end event requires a string data\.reason\.kind",
  178. ):
  179. harness.run("reject malformed turn ending", session_id="main")
  180. def test_relative_cwd_is_absolute_in_process_environment_and_wire(
  181. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  182. ) -> None:
  183. script = tmp_path / "capture_cwd.py"
  184. capture = tmp_path / "cwd.json"
  185. script.write_text(
  186. """
  187. import json
  188. import os
  189. import sys
  190. for line in sys.stdin:
  191. msg = json.loads(line)
  192. if msg.get("method") == "initialize":
  193. json.dump({"process": os.getcwd(), "environment": os.environ.get("DSH_CWD"), "wire": msg["params"]["cwd"]}, open(os.environ["CAPTURE"], "w"))
  194. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  195. elif msg.get("method") == "shutdown":
  196. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  197. break
  198. """.strip()
  199. )
  200. monkeypatch.chdir(tmp_path)
  201. with DeepSeekHarness(
  202. cwd=".",
  203. runtime_cwd=".",
  204. _launch_args=(sys.executable, str(script)),
  205. env={"CAPTURE": str(capture)},
  206. ):
  207. pass
  208. expected = str(tmp_path.resolve())
  209. assert json.loads(capture.read_text()) == {
  210. "process": expected,
  211. "environment": None,
  212. "wire": expected,
  213. }
  214. def test_session_run_includes_subagent_finished_for_parent_session(tmp_path: Path) -> None:
  215. script = tmp_path / "fake_runtime.py"
  216. script.write_text(
  217. """
  218. import json
  219. import sys
  220. for line in sys.stdin:
  221. msg = json.loads(line)
  222. method = msg.get("method")
  223. if method == "initialize":
  224. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  225. elif method == "session/prompt":
  226. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": "main", "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  227. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": "main", "status": "running"}}), flush=True)
  228. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  229. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.started", "params": {"parentSessionId": "main", "childSessionId": "child"}}), flush=True)
  230. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.finished", "params": {"parentSessionId": "main", "childSessionId": "child", "status": "ok", "stopReason": "completed"}}), flush=True)
  231. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": "main", "status": "idle"}}), flush=True)
  232. elif method == "shutdown":
  233. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  234. break
  235. """.strip()
  236. )
  237. with DeepSeekHarness(
  238. _launch_args=(sys.executable, str(script)),
  239. cwd=str(tmp_path),
  240. ) as harness:
  241. result = harness.run("spawn a helper", session_id="main")
  242. assert [notification.method for notification in result.notifications] == [
  243. "session.event",
  244. "session.status",
  245. "subagent.started",
  246. "subagent.finished",
  247. "session.status",
  248. ]
  249. def test_session_run_collects_nested_subagent_tree_without_polluting_root_events(
  250. tmp_path: Path,
  251. ) -> None:
  252. script = tmp_path / "fake_runtime.py"
  253. script.write_text(
  254. """
  255. import json
  256. import sys
  257. for line in sys.stdin:
  258. msg = json.loads(line)
  259. method = msg.get("method")
  260. if method == "initialize":
  261. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  262. elif method == "session/prompt":
  263. root = (msg.get("params") or {})["sessionId"]
  264. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": root, "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  265. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": root, "status": "running"}}), flush=True)
  266. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  267. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.started", "params": {"parentSessionId": root, "childSessionId": "child"}}), flush=True)
  268. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": "child", "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "child response"}]}}}}), flush=True)
  269. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.started", "params": {"parentSessionId": "child", "childSessionId": "grandchild"}}), flush=True)
  270. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": "grandchild", "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "grandchild response"}]}}}}), flush=True)
  271. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.finished", "params": {"parentSessionId": "child", "childSessionId": "grandchild", "status": "ok"}}), flush=True)
  272. print(json.dumps({"jsonrpc": "2.0", "method": "subagent.finished", "params": {"parentSessionId": root, "childSessionId": "child", "status": "ok"}}), flush=True)
  273. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": root, "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "root response"}]}}}}), flush=True)
  274. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": root, "status": "idle"}}), flush=True)
  275. elif method == "shutdown":
  276. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  277. break
  278. """.strip()
  279. )
  280. seen: list[str] = []
  281. with DeepSeekHarness(
  282. _launch_args=(sys.executable, str(script)),
  283. cwd=str(tmp_path),
  284. ) as harness:
  285. result = harness.run(
  286. "delegate recursively",
  287. session_id="main",
  288. on_notification=lambda notification: seen.append(notification.method),
  289. )
  290. assert harness.client._notifications.qsize() == 0
  291. assert result.final_response == "root response"
  292. assert [event["data"]["content"][0]["text"] for event in result.events if event["type"] == "assistant/message"] == ["root response"]
  293. assert [notification.method for notification in result.notifications] == [
  294. "session.event",
  295. "session.status",
  296. "subagent.started",
  297. "session.event",
  298. "subagent.started",
  299. "session.event",
  300. "subagent.finished",
  301. "subagent.finished",
  302. "session.event",
  303. "session.status",
  304. ]
  305. assert seen == [notification.method for notification in result.notifications]
  306. def test_session_run_ignores_notifications_for_other_sessions(tmp_path: Path) -> None:
  307. script = tmp_path / "fake_runtime.py"
  308. script.write_text(
  309. """
  310. import json
  311. import sys
  312. for line in sys.stdin:
  313. msg = json.loads(line)
  314. method = msg.get("method")
  315. if method == "initialize":
  316. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  317. elif method == "session/prompt":
  318. params = msg.get("params") or {}
  319. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": "other", "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "wrong session"}]}}}}), flush=True)
  320. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": "other", "status": "idle"}}), flush=True)
  321. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  322. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "running"}}), flush=True)
  323. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  324. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "right session"}]}}}}), flush=True)
  325. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "idle"}}), flush=True)
  326. elif method == "shutdown":
  327. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  328. break
  329. """.strip()
  330. )
  331. with DeepSeekHarness(
  332. _launch_args=(sys.executable, str(script)),
  333. cwd=str(tmp_path),
  334. ) as harness:
  335. result = harness.run("stay in your lane", session_id="main")
  336. assert result.final_response == "right session"
  337. assert [notification.payload.get("sessionId") for notification in result.notifications] == ["main"] * 4
  338. def test_high_level_session_run_does_not_accumulate_global_notifications(tmp_path: Path) -> None:
  339. script = tmp_path / "fake_runtime.py"
  340. script.write_text(
  341. """
  342. import json
  343. import sys
  344. for line in sys.stdin:
  345. msg = json.loads(line)
  346. method = msg.get("method")
  347. if method == "initialize":
  348. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  349. elif method == "session/prompt":
  350. params = msg.get("params") or {}
  351. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": "message-1"}]}}}}), flush=True)
  352. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "running"}}), flush=True)
  353. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  354. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": params["sessionId"], "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "ok"}]}}}}), flush=True)
  355. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": params["sessionId"], "status": "idle"}}), flush=True)
  356. elif method == "shutdown":
  357. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  358. break
  359. """.strip()
  360. )
  361. with DeepSeekHarness(_launch_args=(sys.executable, str(script)), cwd=str(tmp_path)) as harness:
  362. result = harness.run("one turn", session_id="main")
  363. assert harness.client._notifications.qsize() == 0
  364. def test_session_run_waits_for_late_idle_without_replaying_stale_notifications(tmp_path: Path) -> None:
  365. script = tmp_path / "fake_runtime.py"
  366. script.write_text(
  367. """
  368. import json
  369. import sys
  370. import time
  371. turn = 0
  372. for line in sys.stdin:
  373. msg = json.loads(line)
  374. method = msg.get("method")
  375. if method == "initialize":
  376. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-runtime"}}}), flush=True)
  377. elif method == "session/prompt":
  378. turn += 1
  379. params = msg.get("params") or {}
  380. session_id = params["sessionId"]
  381. message_id = f"message-{turn}"
  382. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": session_id, "event": {"type": "agent/inbox/spliced", "data": {"target": "next-turn", "start": 0, "inserted": [{"id": message_id}]}}}}), flush=True)
  383. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": session_id, "status": "running"}}), flush=True)
  384. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": message_id}}), flush=True)
  385. if turn == 1:
  386. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": session_id, "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "first"}]}}}}), flush=True)
  387. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": session_id, "status": "idle"}}), flush=True)
  388. else:
  389. time.sleep(0.05)
  390. print(json.dumps({"jsonrpc": "2.0", "method": "session.event", "params": {"sessionId": session_id, "event": {"type": "assistant/message", "data": {"content": [{"type": "text", "text": "second"}]}}}}), flush=True)
  391. print(json.dumps({"jsonrpc": "2.0", "method": "session.status", "params": {"sessionId": session_id, "status": "idle"}}), flush=True)
  392. elif method == "shutdown":
  393. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  394. break
  395. """.strip()
  396. )
  397. with DeepSeekHarness(_launch_args=(sys.executable, str(script)), cwd=str(tmp_path)) as harness:
  398. first = harness.run("first turn", session_id="main")
  399. second = harness.run("second turn", session_id="main")
  400. assert first.final_response == "first"
  401. assert second.final_response == "second"
  402. assert [notification.payload.get("sessionId") for notification in second.notifications] == ["main"] * 4
  403. def test_client_starts_subprocess_sends_requests_and_routes_notifications(tmp_path: Path) -> None:
  404. script = tmp_path / "fake_bridge.py"
  405. script.write_text(
  406. """
  407. import json
  408. import sys
  409. for line in sys.stdin:
  410. msg = json.loads(line)
  411. method = msg.get("method")
  412. if method == "initialize":
  413. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  414. elif method == "session/prompt":
  415. params = msg.get("params") or {}
  416. print(json.dumps({"jsonrpc": "2.0", "method": "llm/request", "params": {"requestId": "req-1", "sessionId": params["sessionId"], "model": "dsagent", "messages": []}}), flush=True)
  417. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  418. elif method == "shutdown":
  419. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  420. break
  421. """.strip()
  422. )
  423. with HarnessClient(
  424. HarnessConfig(_launch_args=(sys.executable, str(script)))
  425. ) as client:
  426. init = client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  427. assert init.serverInfo.name == "fake-dsh"
  428. client.session_prompt("main", [{"type": "text", "text": "fix it"}])
  429. notification = client.next_notification()
  430. assert notification.method == "llm/request"
  431. assert notification.payload["requestId"] == "req-1"
  432. assert notification.payload["sessionId"] == "main"
  433. def test_client_keeps_unmatched_notifications_available_globally_while_subscribed() -> None:
  434. client = HarnessClient()
  435. with client.subscribe_session_notifications("main"):
  436. client._handle_message({
  437. "jsonrpc": "2.0",
  438. "method": "session.event",
  439. "params": {"sessionId": "other", "event": {"type": "assistant/message"}},
  440. })
  441. assert client._notifications.qsize() == 1
  442. notification = client._notifications.get_nowait()
  443. assert not isinstance(notification, BaseException)
  444. assert notification.method == "session.event"
  445. assert notification.payload["sessionId"] == "other"
  446. def test_session_subscription_keeps_descendant_relationships_across_subscriptions() -> None:
  447. client = HarnessClient()
  448. with client.subscribe_session_notifications("main") as first:
  449. client._handle_message({
  450. "jsonrpc": "2.0",
  451. "method": "subagent.started",
  452. "params": {"parentSessionId": "main", "childSessionId": "child"},
  453. })
  454. assert first.next().payload["childSessionId"] == "child"
  455. with client.subscribe_session_notifications("main") as second:
  456. client._handle_message({
  457. "jsonrpc": "2.0",
  458. "method": "subagent.started",
  459. "params": {"parentSessionId": "child", "childSessionId": "grandchild"},
  460. })
  461. client._handle_message({
  462. "jsonrpc": "2.0",
  463. "method": "session.event",
  464. "params": {"sessionId": "grandchild", "event": {"type": "assistant/message"}},
  465. })
  466. assert second.next().payload["childSessionId"] == "grandchild"
  467. assert second.next().payload["sessionId"] == "grandchild"
  468. assert client._notifications.qsize() == 0
  469. def test_session_subscription_preserves_reused_child_ancestry_after_late_finish() -> None:
  470. client = HarnessClient()
  471. old_seen: list[Notification] = []
  472. new_seen: list[Notification] = []
  473. with (
  474. client.subscribe_session_notifications("old-parent") as old_subscription,
  475. client.subscribe_session_notifications("new-parent") as new_subscription,
  476. ):
  477. client._handle_message({
  478. "jsonrpc": "2.0",
  479. "method": "subagent.started",
  480. "params": {"parentSessionId": "old-parent", "childSessionId": "reused-child"},
  481. })
  482. old_subscription.drain(old_seen.append)
  483. new_subscription.drain(new_seen.append)
  484. assert [notification.method for notification in old_seen] == ["subagent.started"]
  485. assert new_seen == []
  486. client._handle_message({
  487. "jsonrpc": "2.0",
  488. "method": "subagent.started",
  489. "params": {"parentSessionId": "new-parent", "childSessionId": "reused-child"},
  490. })
  491. old_subscription.drain(old_seen.append)
  492. new_subscription.drain(new_seen.append)
  493. assert [notification.method for notification in new_seen] == ["subagent.started"]
  494. client._handle_message({
  495. "jsonrpc": "2.0",
  496. "method": "subagent.finished",
  497. "params": {"parentSessionId": "old-parent", "childSessionId": "reused-child"},
  498. })
  499. old_subscription.drain(old_seen.append)
  500. new_subscription.drain(new_seen.append)
  501. assert [notification.method for notification in old_seen] == [
  502. "subagent.started",
  503. "subagent.finished",
  504. ]
  505. assert [notification.method for notification in new_seen] == ["subagent.started"]
  506. client._handle_message({
  507. "jsonrpc": "2.0",
  508. "method": "session.event",
  509. "params": {"sessionId": "reused-child", "event": {"type": "assistant/message"}},
  510. })
  511. old_subscription.drain(old_seen.append)
  512. new_subscription.drain(new_seen.append)
  513. assert [notification.method for notification in old_seen] == [
  514. "subagent.started",
  515. "subagent.finished",
  516. ]
  517. assert [notification.method for notification in new_seen] == [
  518. "subagent.started",
  519. "session.event",
  520. ]
  521. assert client._notifications.qsize() == 0
  522. def test_client_contains_notification_filter_failure_to_its_subscription(tmp_path: Path) -> None:
  523. script = tmp_path / "fake_bridge.py"
  524. script.write_text(
  525. """
  526. import json
  527. import sys
  528. for line in sys.stdin:
  529. msg = json.loads(line)
  530. method = msg.get("method")
  531. if method == "initialize":
  532. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  533. elif method in {"emit-first", "emit-second"}:
  534. print(json.dumps({"jsonrpc": "2.0", "method": "tick", "params": {"source": method}}), flush=True)
  535. elif method == "session/prompt":
  536. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"messageId": "message-1"}}), flush=True)
  537. elif method == "shutdown":
  538. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  539. break
  540. """.strip()
  541. )
  542. def broken_filter(_notification: object) -> bool:
  543. raise RuntimeError("bad notification filter")
  544. with HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) as client:
  545. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  546. with (
  547. client.subscribe_notifications(broken_filter) as broken,
  548. client.subscribe_notifications(lambda notification: notification.method == "tick") as healthy,
  549. ):
  550. client.notify("emit-first")
  551. with pytest.raises(RuntimeError, match="bad notification filter"):
  552. broken.next()
  553. assert healthy.next().payload == {"source": "emit-first"}
  554. assert client._notifications.qsize() == 0
  555. client.session_prompt("main", [{"type": "text", "text": "reader still works"}])
  556. client.notify("emit-second")
  557. assert healthy.next().payload == {"source": "emit-second"}
  558. def test_client_rejects_unaccepted_session_prompt_response(tmp_path: Path) -> None:
  559. script = tmp_path / "fake_bridge.py"
  560. script.write_text(
  561. """
  562. import json
  563. import sys
  564. for line in sys.stdin:
  565. msg = json.loads(line)
  566. method = msg.get("method")
  567. if method == "initialize":
  568. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  569. elif method == "session/prompt":
  570. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"accepted": False}}), flush=True)
  571. elif method == "shutdown":
  572. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  573. break
  574. """.strip()
  575. )
  576. with HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script)))) as client:
  577. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  578. with pytest.raises(ValueError):
  579. client.session_prompt("main", [{"type": "text", "text": "fix it"}])
  580. def test_client_routes_bridge_requests_and_sends_responses(tmp_path: Path) -> None:
  581. script = tmp_path / "fake_bridge.py"
  582. script.write_text(
  583. """
  584. import json
  585. import sys
  586. for line in sys.stdin:
  587. msg = json.loads(line)
  588. method = msg.get("method")
  589. if method == "initialize":
  590. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  591. print(json.dumps({"jsonrpc": "2.0", "id": "bridge-req-1", "method": "llm.request", "params": {"requestId": "req-1", "sessionId": "main", "model": "dsagent", "messages": []}}), flush=True)
  592. elif "id" in msg and "method" not in msg:
  593. print(json.dumps({"jsonrpc": "2.0", "method": "response/seen", "params": {"result": msg.get("result")}}), flush=True)
  594. elif method == "shutdown":
  595. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  596. break
  597. """.strip()
  598. )
  599. with HarnessClient(
  600. HarnessConfig(_launch_args=(sys.executable, str(script)))
  601. ) as client:
  602. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  603. request = client.next_request()
  604. assert request.id == "bridge-req-1"
  605. assert request.method == "llm.request"
  606. assert request.payload["requestId"] == "req-1"
  607. client.respond(request.id, {"content_blocks": [{"type": "text", "text": "done"}]})
  608. notification = client.next_notification()
  609. assert notification.method == "response/seen"
  610. assert notification.payload["result"]["content_blocks"][0]["text"] == "done"
  611. def test_client_ignores_non_json_stdout_lines(tmp_path: Path) -> None:
  612. script = tmp_path / "fake_bridge.py"
  613. script.write_text(
  614. """
  615. import json
  616. import sys
  617. print("node warning: experimental loader", flush=True)
  618. for line in sys.stdin:
  619. msg = json.loads(line)
  620. if msg.get("method") == "initialize":
  621. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  622. elif msg.get("method") == "shutdown":
  623. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  624. break
  625. """.strip()
  626. )
  627. with HarnessClient(
  628. HarnessConfig(_launch_args=(sys.executable, str(script)))
  629. ) as client:
  630. init = client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  631. assert init.serverInfo.name == "fake-dsh"
  632. def test_client_request_times_out_when_bridge_does_not_respond(tmp_path: Path) -> None:
  633. script = tmp_path / "fake_bridge.py"
  634. script.write_text(
  635. """
  636. import sys
  637. import time
  638. print("bridge is still starting", file=sys.stderr, flush=True)
  639. time.sleep(60)
  640. """.strip()
  641. )
  642. with HarnessClient(
  643. HarnessConfig(
  644. _launch_args=(sys.executable, str(script)),
  645. request_timeout_seconds=0.1,
  646. )
  647. ) as client:
  648. start = time.monotonic()
  649. try:
  650. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  651. except TimeoutError as exc:
  652. assert time.monotonic() - start < 2
  653. assert "bridge is still starting" in str(exc)
  654. else:
  655. raise AssertionError("initialize should time out")
  656. def test_client_close_times_out_when_shutdown_does_not_respond(tmp_path: Path) -> None:
  657. script = tmp_path / "fake_bridge.py"
  658. script.write_text(
  659. """
  660. import json
  661. import signal
  662. import sys
  663. import time
  664. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  665. for line in sys.stdin:
  666. msg = json.loads(line)
  667. if msg.get("method") == "initialize":
  668. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  669. elif msg.get("method") == "shutdown":
  670. time.sleep(60)
  671. """.strip()
  672. )
  673. client = HarnessClient(
  674. HarnessConfig(
  675. _launch_args=(sys.executable, str(script)),
  676. shutdown_timeout_seconds=0.1,
  677. )
  678. )
  679. client.start()
  680. proc = client._proc
  681. assert proc is not None
  682. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  683. start = time.monotonic()
  684. client.close()
  685. assert time.monotonic() - start < 2
  686. assert proc.poll() is not None
  687. assert client._proc is None
  688. def test_initialize_failure_reaps_started_runtime(tmp_path: Path) -> None:
  689. script = tmp_path / "rejecting_runtime.py"
  690. script.write_text(
  691. """
  692. import json
  693. import sys
  694. for line in sys.stdin:
  695. msg = json.loads(line)
  696. if msg.get("method") == "initialize":
  697. print("initialize diagnostic", file=sys.stderr, flush=True)
  698. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32000, "message": "bad initialize"}}), flush=True)
  699. elif msg.get("method") == "shutdown":
  700. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  701. break
  702. """.strip()
  703. )
  704. client = HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script))))
  705. client.start()
  706. proc = client._proc
  707. assert proc is not None
  708. with pytest.raises(JsonRpcError, match="bad initialize") as excinfo:
  709. client.initialize(provider="deepseek-official", cwd=".", model="dsagent")
  710. assert excinfo.value.code == -32000
  711. assert "initialize diagnostic" in str(excinfo.value)
  712. assert proc.wait(timeout=1) is not None
  713. assert client._proc is None
  714. def test_public_signatures_omit_unsupported_wire_parameters() -> None:
  715. from deepseek_harness import DeepSeekHarnessConfig, Session
  716. assert "session_root" not in inspect.signature(HarnessClient.initialize).parameters
  717. assert "system_prompt" not in inspect.signature(HarnessClient.initialize).parameters
  718. assert "profile" not in inspect.signature(HarnessClient.session_prompt).parameters
  719. assert "profile" not in inspect.signature(DeepSeekHarness.run).parameters
  720. assert "profile" not in inspect.signature(Session.run).parameters
  721. assert "system_prompt" not in DeepSeekHarnessConfig.__dataclass_fields__
  722. assert "max_tokens" in DeepSeekHarnessConfig.__dataclass_fields__
  723. assert "max_tokens" in inspect.signature(HarnessClient.initialize).parameters
  724. assert "client_name" not in HarnessConfig.__dataclass_fields__
  725. assert "client_version" not in HarnessConfig.__dataclass_fields__
  726. assert {"dsh_bin", "profile", "patches", "dsh_home"} <= set(
  727. DeepSeekHarnessConfig.__dataclass_fields__
  728. )
  729. assert {"dsh_bin", "profile", "patches", "dsh_home"} <= set(
  730. HarnessConfig.__dataclass_fields__
  731. )
  732. for removed in ("cordis", "session_root", "runtime_bin", "bridge_bin", "launch_args_override"):
  733. assert removed not in DeepSeekHarnessConfig.__dataclass_fields__
  734. assert removed not in HarnessConfig.__dataclass_fields__
  735. assert "session_root" not in RunResult.__dataclass_fields__
  736. def test_client_close_is_idempotent_before_and_after_start(tmp_path: Path) -> None:
  737. HarnessClient().close()
  738. script = tmp_path / "fake_bridge.py"
  739. script.write_text(
  740. """
  741. import json
  742. import sys
  743. for line in sys.stdin:
  744. msg = json.loads(line)
  745. if msg.get("method") == "initialize":
  746. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  747. elif msg.get("method") == "shutdown":
  748. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  749. break
  750. """.strip()
  751. )
  752. client = HarnessClient(HarnessConfig(_launch_args=(sys.executable, str(script))))
  753. client.start()
  754. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  755. client.close()
  756. client.close()
  757. def test_runtime_closed_error_includes_stderr_tail(tmp_path: Path) -> None:
  758. script = tmp_path / "crashing_runtime.py"
  759. script.write_text(
  760. """
  761. import sys
  762. print("fatal bridge exploded", file=sys.stderr, flush=True)
  763. sys.exit(42)
  764. """.strip()
  765. )
  766. with HarnessClient(
  767. HarnessConfig(
  768. _launch_args=(sys.executable, str(script)),
  769. request_timeout_seconds=2,
  770. )
  771. ) as client:
  772. with pytest.raises(Exception, match="fatal bridge exploded"):
  773. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  774. def test_client_serializes_concurrent_writes(tmp_path: Path) -> None:
  775. script = tmp_path / "fake_bridge.py"
  776. output = tmp_path / "seen.jsonl"
  777. script.write_text(
  778. """
  779. import json
  780. import os
  781. import sys
  782. with open(os.environ["SEEN"], "w") as seen:
  783. for line in sys.stdin:
  784. seen.write(line)
  785. seen.flush()
  786. msg = json.loads(line)
  787. if "id" in msg and msg.get("method") == "initialize":
  788. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "fake-dsh"}}}), flush=True)
  789. elif "id" in msg and msg.get("method") == "shutdown":
  790. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  791. break
  792. """.strip()
  793. )
  794. with HarnessClient(
  795. HarnessConfig(
  796. _launch_args=(sys.executable, str(script)),
  797. env={"SEEN": str(output)},
  798. )
  799. ) as client:
  800. client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
  801. threads = [
  802. threading.Thread(target=client.notify, args=(f"notice-{index}", {"index": index}))
  803. for index in range(50)
  804. ]
  805. for thread in threads:
  806. thread.start()
  807. for thread in threads:
  808. thread.join()
  809. for line in output.read_text().splitlines():
  810. json.loads(line)
  811. def _install_fake_bundled_dsh(
  812. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  813. ) -> None:
  814. """Install a fake runtime package that records dsh argv and serves lifecycle calls."""
  815. runtime = tmp_path / "dsh.py"
  816. runtime.write_text(
  817. """
  818. import json
  819. import os
  820. import sys
  821. json.dump({
  822. "argv": sys.argv[1:],
  823. "DSH_HOME": os.environ.get("DSH_HOME"),
  824. "DSH_CORDIS_CONFIG": os.environ.get("DSH_CORDIS_CONFIG"),
  825. }, open(os.environ["ENV_DUMP"], "w"))
  826. for line in sys.stdin:
  827. msg = json.loads(line)
  828. if msg.get("method") == "initialize":
  829. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {"serverInfo": {"name": "bundled-runtime"}}}), flush=True)
  830. elif msg.get("method") == "shutdown":
  831. print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": {}}), flush=True)
  832. break
  833. """.strip()
  834. )
  835. module_dir = tmp_path / "deepseek_harness_runtime"
  836. module_dir.mkdir()
  837. (module_dir / "__init__.py").write_text(
  838. f"""
  839. def resolve_bundled_launch_args(mode=None):
  840. return ({sys.executable!r}, {str(runtime)!r})
  841. """.strip()
  842. )
  843. monkeypatch.syspath_prepend(str(tmp_path))
  844. monkeypatch.delitem(sys.modules, "deepseek_harness_runtime", raising=False)
  845. def test_client_default_launch_uses_bundled_dsh_sdk_profile_and_explicit_home(
  846. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  847. ) -> None:
  848. env_dump = tmp_path / "env.json"
  849. home = tmp_path / "home"
  850. patch = tmp_path / "sdk.patch.yml"
  851. patch.write_text("[]\n")
  852. _install_fake_bundled_dsh(tmp_path, monkeypatch)
  853. monkeypatch.chdir(tmp_path)
  854. monkeypatch.setenv("DSH_HOME", str(tmp_path / "ambient-home"))
  855. monkeypatch.delenv("DSH_CORDIS_CONFIG", raising=False)
  856. with HarnessClient(HarnessConfig(
  857. profile="sdk",
  858. patches=("sdk.patch.yml",),
  859. dsh_home=str(home),
  860. env={"ENV_DUMP": str(env_dump), "DSH_HOME": str(tmp_path / "env-home")},
  861. )) as client:
  862. init = client.initialize(provider="deepseek-official", cwd="/workspace", model="deepseek-v4-pro")
  863. assert init.serverInfo.name == "bundled-runtime"
  864. assert json.loads(env_dump.read_text()) == {
  865. "argv": ["--profile", "sdk", "--patch", str(patch)],
  866. "DSH_HOME": str(home),
  867. "DSH_CORDIS_CONFIG": None,
  868. }
  869. def test_client_accepts_explicit_environment_dsh_home(
  870. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  871. ) -> None:
  872. env_dump = tmp_path / "env.json"
  873. home = tmp_path / "environment-home"
  874. _install_fake_bundled_dsh(tmp_path, monkeypatch)
  875. with HarnessClient(
  876. HarnessConfig(profile="custom", env={"ENV_DUMP": str(env_dump), "DSH_HOME": str(home)})
  877. ) as client:
  878. client.initialize(provider="deepseek-official", cwd="/workspace", model="deepseek-v4-pro")
  879. assert json.loads(env_dump.read_text()) == {
  880. "argv": ["--profile", "custom"],
  881. "DSH_HOME": str(home),
  882. "DSH_CORDIS_CONFIG": None,
  883. }
  884. def test_client_rejects_an_implicit_default_dsh_home(
  885. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  886. ) -> None:
  887. _install_fake_bundled_dsh(tmp_path, monkeypatch)
  888. monkeypatch.delenv("DSH_HOME", raising=False)
  889. with pytest.raises(ValueError, match="explicit dsh_home or non-empty DSH_HOME"):
  890. HarnessClient(HarnessConfig(env={})).start()
  891. def test_client_reports_missing_bundled_runtime_dependency(monkeypatch: pytest.MonkeyPatch) -> None:
  892. monkeypatch.delitem(sys.modules, "deepseek_harness_runtime", raising=False)
  893. monkeypatch.setattr(sys, "path", [])
  894. with pytest.raises(FileNotFoundError, match="Install deepseek-harness-runtime-bin"):
  895. HarnessClient(HarnessConfig(dsh_home="/explicit/home")).start()