test_client.py 42 KB

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