smoke-python-runtime.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. #!/usr/bin/env python3
  2. """Keyless full-turn and snapshot smoke for the Python SDK runtime."""
  3. from __future__ import annotations
  4. import argparse
  5. import difflib
  6. import json
  7. import os
  8. import queue
  9. import subprocess
  10. import tempfile
  11. import threading
  12. import time
  13. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  14. from pathlib import Path
  15. from typing import TYPE_CHECKING, Callable
  16. if TYPE_CHECKING:
  17. from deepseek_harness import TurnResult
  18. EXPECTED_TEXT = "runtime smoke ok"
  19. CODE_PROMPT = "Use run_code to compute the packaged worker smoke value."
  20. CODE_WORKER_TEXT = "code worker smoke ok"
  21. WORKFLOW_PROMPT = "Use workflow to compute the packaged worker smoke value without agents."
  22. WORKFLOW_WORKER_TEXT = "workflow worker smoke ok"
  23. PERSISTENT_TOOLS_PROMPT = "Exercise the packaged persistent Bash and string-replacement editor."
  24. PERSISTENT_TOOLS_TEXT = "persistent tools smoke ok"
  25. PERSISTENT_EDITOR_PATH_PREFIX = "Editor path: "
  26. PERSISTENT_BASH_COMMAND = (
  27. "counter=$(( ${counter:-0} + 1 )); export counter; "
  28. "printf 'COUNT=%s CWD=%s\\n' \"$counter\" \"$PWD\"; "
  29. "if [ \"$counter\" -eq 1 ]; then cd /tmp; fi"
  30. )
  31. SNAPSHOT_PROMPT = "Run the advanced packaged-runtime snapshot scenario."
  32. SNAPSHOT_SESSION_ID = "advanced-executable"
  33. SNAPSHOT_DIRECT_CHILD_PROMPT = "Reply with exactly DIRECT_CHILD_OK and nothing else."
  34. SNAPSHOT_WORKFLOW_CHILD_PROMPT = "Reply with exactly WORKFLOW_CHILD_OK and nothing else."
  35. SNAPSHOT_FINAL_TEXT = "ADVANCED_EXECUTABLE_OK"
  36. SNAPSHOT_MOUNT_CODE = """\
  37. return (ctx) => {
  38. harness.registerTool(ctx, harness.defineTool({
  39. name: 'snapshot_double',
  40. description: 'Double a number for executable snapshot verification.',
  41. parameters: { value: { type: 'number', required: true } },
  42. output: {
  43. schema: { type: 'number' },
  44. render(_args, value) {
  45. return [{ type: 'text', text: String(value) }]
  46. }
  47. },
  48. async execute(args) {
  49. return args.value * 2
  50. }
  51. }))
  52. }
  53. """
  54. SNAPSHOT_WORKFLOW_SCRIPT = (
  55. "phase('Delegate')\n"
  56. f"const reply = await agent('{SNAPSHOT_WORKFLOW_CHILD_PROMPT}', {{ label: 'workflow-child' }})\n"
  57. "return { reply }"
  58. )
  59. SNAPSHOT_DIRECTORY = (
  60. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
  61. )
  62. SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
  63. CUSTOM_CORDIS = """\
  64. - id: jsonrpc
  65. name: '@deepseek-ai/dsh-jsonrpc'
  66. - id: agent-core
  67. name: '@deepseek-ai/dsh-agent-spine-demo'
  68. config:
  69. workspaceContext: false
  70. tools:
  71. mode: both
  72. - id: sessions
  73. name: '@deepseek-ai/dsh-session-persistence-jsonl'
  74. config:
  75. root: !!js process.env.DSH_SESSION_ROOT
  76. compression: 'none'
  77. - id: bash
  78. name: '@deepseek-ai/dsh-bash-local'
  79. config:
  80. cwd: !!js process.env.DSH_CWD
  81. - id: code-runtime
  82. name: '@deepseek-ai/dsh-code-runtime-worker'
  83. - id: subagents
  84. name: '@deepseek-ai/dsh-subagent'
  85. - id: subagent-spawn
  86. name: '@deepseek-ai/dsh-subagent-spawn'
  87. config:
  88. providerName: spawn
  89. - id: subagent-tool
  90. name: '@deepseek-ai/dsh-tool-subagent'
  91. config:
  92. provider: spawn
  93. - id: workflow-engine
  94. name: '@deepseek-ai/dsh-workflow-workerthread'
  95. config:
  96. provider: spawn
  97. - id: workflow-tool
  98. name: '@deepseek-ai/dsh-tool-workflow'
  99. - id: cordis-tool
  100. name: '@deepseek-ai/dsh-tool-cordis'
  101. """
  102. PERSISTENT_TOOLS_CORDIS = """\
  103. - id: jsonrpc
  104. name: '@deepseek-ai/dsh-jsonrpc'
  105. - id: llm
  106. name: '@deepseek-ai/dsh-llm-deepseek'
  107. config:
  108. apiKey: !!js process.env.DEEPSEEK_API_KEY
  109. baseURL: !!js process.env.DEEPSEEK_BASE_URL
  110. - id: sandbox
  111. name: '@deepseek-ai/dsh-sandbox-local'
  112. - id: sandbox-policy
  113. name: '@deepseek-ai/dsh-sandbox-policy'
  114. config:
  115. mode: danger-full-access
  116. workspaceRoot: !!js process.env.DSH_CWD
  117. - id: pty
  118. name: '@deepseek-ai/dsh-pty'
  119. - id: pty-local
  120. name: '@deepseek-ai/dsh-pty-local'
  121. - id: fs
  122. name: '@deepseek-ai/dsh-fs-local'
  123. config:
  124. cwd: !!js process.env.DSH_CWD
  125. - id: agent-core
  126. name: '@deepseek-ai/dsh-agent-spine-demo'
  127. config:
  128. includeHarnessIdentity: false
  129. persona: 'You are a helpful software engineer assistant.'
  130. workspaceContext: false
  131. skills:
  132. enabled: false
  133. toolBash: false
  134. toolTasks: false
  135. - id: sessions
  136. name: '@deepseek-ai/dsh-session-persistence-jsonl'
  137. config:
  138. root: !!js process.env.DSH_SESSION_ROOT
  139. compression: 'none'
  140. - id: persistent-bash
  141. name: '@deepseek-ai/dsh-tool-bash-persistent'
  142. - id: str-replace-editor
  143. name: '@deepseek-ai/dsh-tool-str-replace-editor'
  144. """
  145. class MockModelHandler(BaseHTTPRequestHandler):
  146. """Return deterministic text, worker, and orchestration completions."""
  147. requests: list[dict[str, object]] = []
  148. def do_POST(self) -> None:
  149. content_length = int(self.headers.get("content-length", "0"))
  150. body = json.loads(self.rfile.read(content_length))
  151. self.requests.append(body)
  152. self.send_response(200)
  153. self.send_header("content-type", "text/event-stream")
  154. self.end_headers()
  155. chunks = completion_chunks(body)
  156. for chunk in chunks:
  157. self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
  158. self.wfile.write(b"data: [DONE]\n\n")
  159. self.wfile.flush()
  160. def log_message(self, _format: str, *_args: object) -> None:
  161. return
  162. def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
  163. """Choose the next deterministic model response from request history."""
  164. messages = body.get("messages")
  165. if not isinstance(messages, list) or not messages:
  166. raise AssertionError(f"model request has no messages: {body}")
  167. latest = messages[-1]
  168. if not isinstance(latest, dict):
  169. raise AssertionError(f"model request has an invalid latest message: {body}")
  170. if latest.get("role") == "tool":
  171. call_id, tool_name = latest_tool_call(messages)
  172. tool_text = message_text(latest.get("content"))
  173. persistent = persistent_tool_followup(body, call_id, tool_name, tool_text)
  174. if persistent is not None:
  175. return persistent
  176. advanced = advanced_tool_followup(body, call_id, tool_name, tool_text)
  177. if advanced is not None:
  178. return advanced
  179. if "42" not in tool_text:
  180. raise AssertionError(f"{tool_name} worker returned no expected value: {latest}")
  181. if tool_name == "run_code":
  182. return text_chunks(CODE_WORKER_TEXT)
  183. if tool_name == "workflow":
  184. return text_chunks(WORKFLOW_WORKER_TEXT)
  185. raise AssertionError(f"unexpected tool follow-up: {tool_name}")
  186. prompt = message_text(latest.get("content"))
  187. if prompt.startswith(f"{PERSISTENT_TOOLS_PROMPT}\n{PERSISTENT_EDITOR_PATH_PREFIX}"):
  188. names = advertised_tool_names(body)
  189. if names != {"bash", "str_replace_editor"}:
  190. raise AssertionError(f"persistent tools smoke advertised unexpected tools: {names}")
  191. return tool_call_chunks(
  192. "persistent-bash-1",
  193. "bash",
  194. {"command": PERSISTENT_BASH_COMMAND},
  195. )
  196. if prompt == SNAPSHOT_DIRECT_CHILD_PROMPT:
  197. return text_chunks("DIRECT_CHILD_OK")
  198. if prompt == SNAPSHOT_WORKFLOW_CHILD_PROMPT:
  199. return text_chunks("WORKFLOW_CHILD_OK")
  200. if prompt == SNAPSHOT_PROMPT:
  201. assert_advertised_tool(body, "cordis_mount")
  202. return tool_call_chunks(
  203. "advanced-mount",
  204. "cordis_mount",
  205. {"code": SNAPSHOT_MOUNT_CODE},
  206. )
  207. if prompt == CODE_PROMPT:
  208. assert_advertised_tool(body, "run_code")
  209. return tool_call_chunks(
  210. "call-code-worker",
  211. "run_code",
  212. {"code": "return 6 * 7", "description": "Compute the smoke value"},
  213. )
  214. if prompt == WORKFLOW_PROMPT:
  215. assert_advertised_tool(body, "workflow")
  216. return tool_call_chunks(
  217. "call-workflow-worker",
  218. "workflow",
  219. {
  220. "script": "return 6 * 7",
  221. "meta": {
  222. "name": "pkg-worker-smoke",
  223. "description": "exercise the packaged workflow worker",
  224. },
  225. },
  226. )
  227. return text_chunks(EXPECTED_TEXT)
  228. def persistent_tool_followup(
  229. body: dict[str, object],
  230. call_id: str,
  231. tool_name: str,
  232. tool_text: str,
  233. ) -> list[dict[str, object]] | None:
  234. """Verify packaged PTY persistence, then invoke the packaged editor."""
  235. if not call_id.startswith("persistent-"):
  236. return None
  237. if call_id == "persistent-bash-1" and tool_name == "bash":
  238. if "COUNT=1" not in tool_text:
  239. raise AssertionError(f"first persistent bash call lost its output: {tool_text}")
  240. return tool_call_chunks(
  241. "persistent-bash-2",
  242. "bash",
  243. {"command": PERSISTENT_BASH_COMMAND},
  244. )
  245. if call_id == "persistent-bash-2" and tool_name == "bash":
  246. if "COUNT=2 CWD=/tmp" not in tool_text:
  247. raise AssertionError(f"persistent bash did not retain state: {tool_text}")
  248. messages = body.get("messages")
  249. if not isinstance(messages, list):
  250. raise AssertionError("persistent editor smoke request has no messages")
  251. editor_path = next(
  252. (
  253. text.split(PERSISTENT_EDITOR_PATH_PREFIX, 1)[1].strip()
  254. for message in messages
  255. if isinstance(message, dict) and message.get("role") == "user"
  256. for text in [message_text(message.get("content"))]
  257. if PERSISTENT_EDITOR_PATH_PREFIX in text
  258. ),
  259. None,
  260. )
  261. if editor_path is None:
  262. raise AssertionError("persistent editor smoke prompt has no editor path")
  263. return tool_call_chunks(
  264. "persistent-editor",
  265. "str_replace_editor",
  266. {
  267. "command": "create",
  268. "path": editor_path,
  269. "file_text": "created by packaged editor\n",
  270. },
  271. )
  272. if call_id == "persistent-editor" and tool_name == "str_replace_editor":
  273. if "New file created successfully" not in tool_text:
  274. raise AssertionError(f"packaged editor did not create its file: {tool_text}")
  275. return text_chunks(PERSISTENT_TOOLS_TEXT)
  276. raise AssertionError(f"unexpected persistent-tools follow-up: {call_id} {tool_name}: {tool_text}")
  277. def advanced_tool_followup(
  278. body: dict[str, object],
  279. call_id: str,
  280. tool_name: str,
  281. tool_text: str,
  282. ) -> list[dict[str, object]] | None:
  283. """Advance the executable snapshot's deterministic parent tool chain."""
  284. if not call_id.startswith("advanced-"):
  285. return None
  286. if call_id == "advanced-mount" and tool_name == "cordis_mount":
  287. if "Temporary Plugin dyn-1 is running" not in tool_text:
  288. raise AssertionError(f"cordis_mount returned no temporary Plugin id: {tool_text}")
  289. assert_advertised_tool(body, "run_code")
  290. assert_advertised_tool(body, "snapshot_double")
  291. return tool_call_chunks(
  292. "advanced-code",
  293. "run_code",
  294. {
  295. "code": "return await tools.snapshot_double({ value: 21 })",
  296. "description": "Run the temporary Plugin tool",
  297. },
  298. )
  299. if call_id == "advanced-code" and tool_name == "run_code":
  300. if "42" not in tool_text:
  301. raise AssertionError(f"run_code returned no dynamic-tool value: {tool_text}")
  302. assert_advertised_tool(body, "subagent")
  303. return tool_call_chunks(
  304. "advanced-direct-child",
  305. "subagent",
  306. {
  307. "description": "Check direct child",
  308. "prompt": SNAPSHOT_DIRECT_CHILD_PROMPT,
  309. },
  310. )
  311. if call_id == "advanced-direct-child" and tool_name == "subagent":
  312. if "DIRECT_CHILD_OK" not in tool_text:
  313. raise AssertionError(f"subagent returned no expected child value: {tool_text}")
  314. assert_advertised_tool(body, "workflow")
  315. return tool_call_chunks(
  316. "advanced-workflow",
  317. "workflow",
  318. {
  319. "script": SNAPSHOT_WORKFLOW_SCRIPT,
  320. "meta": {
  321. "name": "advanced-exe-snapshot",
  322. "description": "exercise one packaged workflow child",
  323. },
  324. },
  325. )
  326. if call_id == "advanced-workflow" and tool_name == "workflow":
  327. if "WORKFLOW_CHILD_OK" not in tool_text:
  328. raise AssertionError(f"workflow returned no expected child value: {tool_text}")
  329. assert_advertised_tool(body, "cordis_unmount")
  330. return tool_call_chunks(
  331. "advanced-unmount",
  332. "cordis_unmount",
  333. {"id": "dyn-1"},
  334. )
  335. if call_id == "advanced-unmount" and tool_name == "cordis_unmount":
  336. if "Temporary Plugin dyn-1 was unmounted and removed." not in tool_text:
  337. raise AssertionError(f"cordis_unmount returned no unmount result: {tool_text}")
  338. if "snapshot_double" in advertised_tool_names(body):
  339. raise AssertionError("snapshot_double remained advertised after cordis_unmount")
  340. return text_chunks(SNAPSHOT_FINAL_TEXT)
  341. raise AssertionError(f"unexpected advanced tool follow-up: {call_id} {tool_name}: {tool_text}")
  342. def text_chunks(text: str) -> list[dict[str, object]]:
  343. """Build a complete streaming text response."""
  344. return [
  345. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  346. {"choices": [{"delta": {"content": text}}]},
  347. {
  348. "choices": [{"delta": {"content": ""}, "finish_reason": "stop"}],
  349. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  350. },
  351. ]
  352. def tool_call_chunks(call_id: str, name: str, arguments: dict[str, object]) -> list[dict[str, object]]:
  353. """Build a complete streaming function-call response."""
  354. return [
  355. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  356. {
  357. "choices": [{
  358. "delta": {
  359. "tool_calls": [{
  360. "index": 0,
  361. "id": call_id,
  362. "type": "function",
  363. "function": {"name": name, "arguments": json.dumps(arguments)},
  364. }],
  365. },
  366. }],
  367. },
  368. {
  369. "choices": [{"delta": {"content": ""}, "finish_reason": "tool_calls"}],
  370. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  371. },
  372. ]
  373. def latest_tool_call(messages: list[object]) -> tuple[str, str]:
  374. """Find the assistant call id and name paired with the latest tool result."""
  375. for message in reversed(messages[:-1]):
  376. if not isinstance(message, dict):
  377. continue
  378. calls = message.get("tool_calls")
  379. if not isinstance(calls, list):
  380. continue
  381. for call in reversed(calls):
  382. if not isinstance(call, dict):
  383. continue
  384. function = call.get("function")
  385. call_id = call.get("id")
  386. if (
  387. isinstance(call_id, str)
  388. and isinstance(function, dict)
  389. and isinstance(function.get("name"), str)
  390. ):
  391. return call_id, function["name"]
  392. raise AssertionError(f"tool result has no preceding assistant tool call: {messages}")
  393. def message_text(content: object) -> str:
  394. """Read OpenAI text content in either string or block-list form."""
  395. if isinstance(content, str):
  396. return content
  397. if isinstance(content, list):
  398. return "".join(
  399. block.get("text", "")
  400. for block in content
  401. if isinstance(block, dict) and isinstance(block.get("text"), str)
  402. )
  403. return ""
  404. def advertised_tool_names(body: dict[str, object]) -> set[str]:
  405. """Return the model-facing tool names advertised on one request."""
  406. tools = body.get("tools")
  407. if not isinstance(tools, list):
  408. raise AssertionError(f"model request advertised no tools: {body}")
  409. names: set[str] = set()
  410. for tool in tools:
  411. if not isinstance(tool, dict):
  412. continue
  413. function = tool.get("function")
  414. if isinstance(function, dict) and isinstance(function.get("name"), str):
  415. names.add(function["name"])
  416. return names
  417. def assert_advertised_tool(body: dict[str, object], expected: str) -> None:
  418. """Require the packaged deployment to expose the requested tool."""
  419. names = advertised_tool_names(body)
  420. if expected not in names:
  421. raise AssertionError(f"model request did not advertise {expected}: {names}")
  422. class MockModel:
  423. def __enter__(self) -> "MockModel":
  424. MockModelHandler.requests.clear()
  425. self.server = ThreadingHTTPServer(("127.0.0.1", 0), MockModelHandler)
  426. self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
  427. self.thread.start()
  428. host, port = self.server.server_address
  429. self.url = f"http://{host}:{port}"
  430. return self
  431. def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
  432. self.server.shutdown()
  433. self.server.server_close()
  434. self.thread.join(timeout=5)
  435. def main() -> None:
  436. parser = argparse.ArgumentParser(description=__doc__)
  437. parser.add_argument(
  438. "--scenario",
  439. choices=("all", "sdk-default", "sdk-custom", "sdk-persistent", "sdk-snapshot", "direct"),
  440. default="all",
  441. )
  442. parser.add_argument("--exe", type=Path)
  443. parser.add_argument("--update-snapshots", action="store_true")
  444. args = parser.parse_args()
  445. if args.scenario in {"all", "sdk-custom", "sdk-persistent", "sdk-snapshot", "direct"} and args.exe is None:
  446. parser.error("--exe is required for custom, persistent, snapshot, and direct scenarios")
  447. if args.update_snapshots and args.scenario not in {"all", "sdk-snapshot"}:
  448. parser.error("--update-snapshots requires --scenario sdk-snapshot or all")
  449. if args.exe is not None and not args.exe.is_file():
  450. parser.error(f"runtime executable does not exist: {args.exe}")
  451. with MockModel() as model:
  452. if args.scenario in {"all", "sdk-default"}:
  453. smoke_sdk_default(model.url)
  454. if args.scenario in {"all", "sdk-custom"}:
  455. assert args.exe is not None
  456. smoke_sdk_custom(model.url, args.exe.resolve())
  457. if args.scenario in {"all", "sdk-persistent"}:
  458. assert args.exe is not None
  459. smoke_sdk_persistent_tools(model.url, args.exe.resolve())
  460. if args.scenario in {"all", "sdk-snapshot"}:
  461. assert args.exe is not None
  462. smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  463. if args.scenario in {"all", "direct"}:
  464. assert args.exe is not None
  465. smoke_direct(model.url, args.exe.resolve())
  466. if not MockModelHandler.requests:
  467. raise AssertionError("mock model endpoint received no requests")
  468. print(f"smoke-python-runtime: {args.scenario} passed")
  469. def smoke_sdk_default(base_url: str) -> None:
  470. from deepseek_harness import DeepSeekHarness
  471. with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary:
  472. root = Path(temporary).resolve()
  473. sessions = root / "sessions"
  474. with DeepSeekHarness(
  475. provider="deepseek",
  476. model="smoke-model",
  477. cwd=str(root),
  478. session_root=str(sessions),
  479. api_key="sk-keyless-smoke",
  480. base_url=base_url,
  481. request_timeout_seconds=60,
  482. ) as harness:
  483. result = harness.run("reply with the smoke text", session_id="default-smoke")
  484. assert result.status == "ok", result
  485. assert result.final_response == EXPECTED_TEXT, result.final_response
  486. assert_zstd_session_log(sessions)
  487. def smoke_sdk_custom(base_url: str, executable: Path) -> None:
  488. from deepseek_harness import DeepSeekHarness
  489. with tempfile.TemporaryDirectory(prefix="dsh-sdk-custom-") as temporary:
  490. root = Path(temporary).resolve()
  491. sessions = root / "sessions"
  492. cordis = root / "cordis.yml"
  493. cordis.write_text(CUSTOM_CORDIS)
  494. with DeepSeekHarness(
  495. provider="deepseek",
  496. model="smoke-model",
  497. cwd=str(root),
  498. session_root=str(sessions),
  499. cordis=str(cordis),
  500. runtime_bin=str(executable),
  501. api_key="sk-keyless-smoke",
  502. base_url=base_url,
  503. request_timeout_seconds=60,
  504. ) as harness:
  505. text_result = harness.run("reply with the smoke text", session_id="custom-smoke")
  506. code_result = harness.run(CODE_PROMPT, session_id="custom-smoke")
  507. workflow_result = harness.run(WORKFLOW_PROMPT, session_id="custom-smoke")
  508. assert text_result.status == "ok", text_result
  509. assert text_result.final_response == EXPECTED_TEXT, text_result.final_response
  510. assert code_result.status == "ok", code_result
  511. assert code_result.final_response == CODE_WORKER_TEXT, code_result.final_response
  512. assert workflow_result.status == "ok", workflow_result
  513. assert workflow_result.final_response == WORKFLOW_WORKER_TEXT, workflow_result.final_response
  514. assert_session_log(sessions, root, EXPECTED_TEXT, CODE_WORKER_TEXT, WORKFLOW_WORKER_TEXT)
  515. def smoke_sdk_persistent_tools(base_url: str, executable: Path) -> None:
  516. """Exercise native PTY state and the editor through the packaged executable."""
  517. from deepseek_harness import DeepSeekHarness
  518. with tempfile.TemporaryDirectory(prefix="dsh-sdk-persistent-tools-") as temporary:
  519. root = Path(temporary).resolve()
  520. editor_path = root / "created.txt"
  521. prompt = f"{PERSISTENT_TOOLS_PROMPT}\n{PERSISTENT_EDITOR_PATH_PREFIX}{editor_path}"
  522. sessions = root / "sessions"
  523. cordis = root / "cordis.yml"
  524. cordis.write_text(PERSISTENT_TOOLS_CORDIS)
  525. with DeepSeekHarness(
  526. provider="deepseek",
  527. model="smoke-model",
  528. cwd=str(root),
  529. session_root=str(sessions),
  530. cordis=str(cordis),
  531. runtime_bin=str(executable),
  532. api_key="sk-keyless-smoke",
  533. base_url=base_url,
  534. request_timeout_seconds=60,
  535. ) as harness:
  536. result = harness.run(prompt, session_id="persistent-tools-smoke")
  537. assert result.status == "ok", result
  538. event_text = json.dumps(result.events)
  539. if PERSISTENT_TOOLS_TEXT not in event_text:
  540. raise AssertionError(f"packaged tools run emitted no final response: {result.events}")
  541. if editor_path.read_text() != "created by packaged editor\n":
  542. raise AssertionError(f"packaged editor wrote unexpected content: {editor_path.read_text()!r}")
  543. assert_session_log(sessions, root, PERSISTENT_TOOLS_TEXT, "COUNT=1", "COUNT=2 CWD=/tmp")
  544. def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  545. """Drive and compare the advanced SDK/executable behavioral snapshot."""
  546. from deepseek_harness import DeepSeekHarness
  547. with tempfile.TemporaryDirectory(prefix="dsh-sdk-snapshot-") as temporary:
  548. root = Path(temporary).resolve()
  549. sessions = root / "sessions"
  550. cordis = root / "cordis.yml"
  551. cordis.write_text(CUSTOM_CORDIS)
  552. with DeepSeekHarness(
  553. provider="deepseek",
  554. model="smoke-model",
  555. cwd=str(root),
  556. session_root=str(sessions),
  557. cordis=str(cordis),
  558. runtime_bin=str(executable),
  559. api_key="sk-keyless-smoke",
  560. base_url=base_url,
  561. request_timeout_seconds=60,
  562. ) as harness:
  563. result = harness.run(SNAPSHOT_PROMPT, session_id=SNAPSHOT_SESSION_ID)
  564. assert result.status == "ok", result
  565. assert result.final_response == SNAPSHOT_FINAL_TEXT, result.final_response
  566. methods = [notification.method for notification in result.notifications]
  567. if methods.count("subagent.started") != 2 or methods.count("subagent.finished") != 2:
  568. raise AssertionError(f"advanced snapshot emitted unexpected subagent lifecycle: {methods}")
  569. if not any(event.get("type") == "tool/code-dispatch" for event in result.events):
  570. raise AssertionError("advanced snapshot emitted no tool/code-dispatch event")
  571. logs = read_session_logs(sessions)
  572. child_ids = snapshot_child_ids(result)
  573. expected_ids = {SNAPSHOT_SESSION_ID, *child_ids}
  574. if set(logs) != expected_ids:
  575. raise AssertionError(f"advanced snapshot expected parent plus two child logs: {sorted(logs)}")
  576. if "DIRECT_CHILD_OK" not in render_jsonl(logs[child_ids[0]]):
  577. raise AssertionError("first advanced child log has no direct-subagent result")
  578. if "WORKFLOW_CHILD_OK" not in render_jsonl(logs[child_ids[1]]):
  579. raise AssertionError("second advanced child log has no workflow-subagent result")
  580. files = build_snapshot_files(result, logs, child_ids, root)
  581. compare_snapshot_files(files, update_snapshots)
  582. def smoke_direct(base_url: str, executable: Path) -> None:
  583. with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary:
  584. root = Path(temporary).resolve()
  585. sessions = root / "sessions"
  586. cordis = root / "cordis.yml"
  587. cordis.write_text(CUSTOM_CORDIS)
  588. environment = {
  589. **os.environ,
  590. "DSH_CORDIS_CONFIG": str(cordis),
  591. "DSH_SESSION_ROOT": str(sessions),
  592. "DSH_CWD": str(root),
  593. "DEEPSEEK_API_KEY": "sk-keyless-smoke",
  594. "DEEPSEEK_BASE_URL": base_url,
  595. }
  596. peer = RuntimePeer([str(executable)], root, environment)
  597. try:
  598. peer.send({"jsonrpc": "2.0", "id": "initialize", "method": "initialize", "params": {"cwd": str(root), "provider": "deepseek", "model": "smoke-model"}})
  599. peer.read_until(lambda message: message.get("id") == "initialize")
  600. peer.send({
  601. "jsonrpc": "2.0",
  602. "id": "prompt",
  603. "method": "session/prompt",
  604. "params": {"sessionId": "direct-smoke", "contentBlocks": [{"type": "text", "text": "reply with the smoke text"}]},
  605. })
  606. messages = peer.read_until(lambda message: message.get("id") == "prompt")
  607. if not any(message.get("method") == "session.finished" and message.get("params", {}).get("status") == "ok" for message in messages):
  608. messages.extend(peer.read_until(lambda message: message.get("method") == "session.finished"))
  609. event_text = json.dumps(messages)
  610. if EXPECTED_TEXT not in event_text:
  611. raise AssertionError(f"direct runtime emitted no final response: {messages}")
  612. peer.send({"jsonrpc": "2.0", "id": "shutdown", "method": "shutdown"})
  613. peer.read_until(lambda message: message.get("id") == "shutdown")
  614. finally:
  615. peer.close()
  616. assert_session_log(sessions, root, EXPECTED_TEXT)
  617. class RuntimePeer:
  618. def __init__(self, argv: list[str], cwd: Path, environment: dict[str, str]) -> None:
  619. self.process = subprocess.Popen(
  620. argv,
  621. cwd=cwd,
  622. env=environment,
  623. stdin=subprocess.PIPE,
  624. stdout=subprocess.PIPE,
  625. stderr=subprocess.PIPE,
  626. text=True,
  627. encoding="utf-8",
  628. bufsize=1,
  629. )
  630. self.stdout: queue.Queue[str | None] = queue.Queue()
  631. self.stderr: list[str] = []
  632. threading.Thread(target=self._read_stdout, daemon=True).start()
  633. threading.Thread(target=self._read_stderr, daemon=True).start()
  634. def send(self, message: dict[str, object]) -> None:
  635. if self.process.stdin is None:
  636. raise RuntimeError("runtime stdin is unavailable")
  637. self.process.stdin.write(json.dumps(message) + "\n")
  638. self.process.stdin.flush()
  639. def read_until(self, predicate: Callable[[dict[str, object]], bool]) -> list[dict[str, object]]:
  640. deadline = time.monotonic() + 60
  641. messages: list[dict[str, object]] = []
  642. while time.monotonic() < deadline:
  643. try:
  644. line = self.stdout.get(timeout=min(0.25, deadline - time.monotonic()))
  645. except queue.Empty:
  646. continue
  647. if line is None:
  648. raise RuntimeError(f"runtime exited before expected message; stderr: {''.join(self.stderr)}")
  649. try:
  650. message = json.loads(line)
  651. except json.JSONDecodeError:
  652. continue
  653. messages.append(message)
  654. if predicate(message):
  655. return messages
  656. raise TimeoutError(f"runtime timed out; messages={messages}; stderr={''.join(self.stderr)}")
  657. def close(self) -> None:
  658. if self.process.stdin is not None and not self.process.stdin.closed:
  659. self.process.stdin.close()
  660. try:
  661. self.process.wait(timeout=10)
  662. except subprocess.TimeoutExpired:
  663. self.process.kill()
  664. self.process.wait()
  665. if self.process.returncode not in {0, -15}:
  666. raise RuntimeError(f"runtime exited {self.process.returncode}; stderr: {''.join(self.stderr)}")
  667. def _read_stdout(self) -> None:
  668. assert self.process.stdout is not None
  669. for line in self.process.stdout:
  670. self.stdout.put(line)
  671. self.stdout.put(None)
  672. def _read_stderr(self) -> None:
  673. assert self.process.stderr is not None
  674. self.stderr.extend(self.process.stderr)
  675. def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
  676. logs = list(sessions.rglob("*.jsonl"))
  677. if len(logs) != 1:
  678. raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}")
  679. lines = logs[0].read_text().splitlines()
  680. header = json.loads(lines[0])
  681. if header.get("cwd") != str(cwd):
  682. raise AssertionError(f"session header cwd is not absolute/canonical: {header}")
  683. rendered = "\n".join(lines)
  684. for expected in expected_texts:
  685. if expected not in rendered:
  686. raise AssertionError(f"session log has no {expected!r} response: {logs[0]}")
  687. def assert_zstd_session_log(sessions: Path) -> None:
  688. logs = list(sessions.rglob("*.jsonl.zstd"))
  689. if len(logs) != 1:
  690. raise AssertionError(f"expected one Zstandard JSONL session log under {sessions}, found {logs}")
  691. if not logs[0].read_bytes().startswith(bytes.fromhex("28b52ffd")):
  692. raise AssertionError(f"session log has no Zstandard magic: {logs[0]}")
  693. def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]:
  694. """Parse every persisted JSONL session into a map keyed by header id."""
  695. logs: dict[str, list[dict[str, object]]] = {}
  696. for path in sorted(sessions.rglob("*.jsonl")):
  697. records = [
  698. json.loads(line)
  699. for line in path.read_text(encoding="utf-8").splitlines()
  700. if line
  701. ]
  702. if not records or records[0].get("type") != "session":
  703. raise AssertionError(f"session log has no header: {path}")
  704. session_id = records[0].get("id")
  705. if not isinstance(session_id, str):
  706. raise AssertionError(f"session log header has no string id: {path}")
  707. if session_id in logs:
  708. raise AssertionError(f"duplicate persisted session id: {session_id}")
  709. logs[session_id] = records
  710. return logs
  711. def snapshot_child_ids(result: "TurnResult") -> list[str]:
  712. """Return the two child session ids in their SDK notification order."""
  713. child_ids: list[str] = []
  714. for notification in result.notifications:
  715. if notification.method != "subagent.started":
  716. continue
  717. payload = notification.payload
  718. if payload.get("parentSessionId") != SNAPSHOT_SESSION_ID:
  719. continue
  720. child_id = payload.get("childSessionId")
  721. if isinstance(child_id, str) and child_id not in child_ids:
  722. child_ids.append(child_id)
  723. if len(child_ids) != 2:
  724. raise AssertionError(f"advanced snapshot expected two child session ids: {child_ids}")
  725. return child_ids
  726. def build_snapshot_files(
  727. result: "TurnResult",
  728. logs: dict[str, list[dict[str, object]]],
  729. child_ids: list[str],
  730. cwd: Path,
  731. ) -> dict[str, str]:
  732. """Render the SDK result and three persisted logs into stable expected outputs."""
  733. replacements = [(str(cwd), "{{cwd}}"), (SNAPSHOT_SESSION_ID, "{{parent}}")]
  734. for index, child_id in enumerate(child_ids, start=1):
  735. replacements.append((child_id, f"{{{{child-{index}}}}}"))
  736. agent_id = snapshot_agent_id(result, child_id)
  737. replacements.append((agent_id, f"{{{{agent-{index}}}}}"))
  738. replacements.sort(key=lambda pair: len(pair[0]), reverse=True)
  739. result_value = {
  740. "session_id": result.session_id,
  741. "status": result.status,
  742. "final_response": result.final_response,
  743. "events": result.events,
  744. "notifications": [
  745. {"method": notification.method, "payload": notification.payload}
  746. for notification in result.notifications
  747. ],
  748. "session_root": result.session_root,
  749. }
  750. normalized_result = normalize_snapshot_value(result_value, replacements)
  751. files = {
  752. "result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
  753. "session.jsonl": render_jsonl(
  754. [normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]]
  755. ),
  756. }
  757. for index, child_id in enumerate(child_ids, start=1):
  758. files[f"session.{index}.jsonl"] = render_jsonl(
  759. [normalize_snapshot_value(record, replacements) for record in logs[child_id]]
  760. )
  761. if tuple(files) != SNAPSHOT_FILENAMES:
  762. raise AssertionError(f"advanced snapshot file set drifted: {tuple(files)}")
  763. return files
  764. def snapshot_agent_id(result: "TurnResult", child_id: str) -> str:
  765. """Find the successful subagent id paired with one child session."""
  766. for notification in result.notifications:
  767. if notification.method != "subagent.finished":
  768. continue
  769. payload = notification.payload
  770. if payload.get("childSessionId") != child_id:
  771. continue
  772. if payload.get("provider") != "spawn" or payload.get("status") != "ok":
  773. raise AssertionError(f"advanced child did not finish successfully: {payload}")
  774. agent_id = payload.get("agentId")
  775. if isinstance(agent_id, str):
  776. return agent_id
  777. raise AssertionError(f"advanced snapshot has no finished agent for child {child_id}")
  778. def normalize_snapshot_value(
  779. value: object,
  780. replacements: list[tuple[str, str]],
  781. ) -> object:
  782. """Scrub volatile values and bulky request headers without losing behavior."""
  783. if isinstance(value, str):
  784. normalized = value
  785. for actual, token in replacements:
  786. normalized = normalized.replace(actual, token)
  787. return normalized
  788. if isinstance(value, list):
  789. return [normalize_snapshot_value(item, replacements) for item in value]
  790. if not isinstance(value, dict):
  791. return value
  792. normalized = {
  793. key: normalize_snapshot_value(item, replacements)
  794. for key, item in value.items()
  795. }
  796. if normalized.get("type") == "session" and "createdAt" in normalized:
  797. normalized["createdAt"] = 0
  798. if "seq" in normalized and "time" in normalized:
  799. normalized["time"] = 0
  800. scrub_snapshot_header(normalized)
  801. return normalized
  802. def scrub_snapshot_header(value: dict[object, object]) -> None:
  803. """Tokenize full request-header bulk while retaining tool names."""
  804. data = value.get("data")
  805. if not isinstance(data, dict):
  806. return
  807. if value.get("type") == "request/header":
  808. header = data.get("header")
  809. if not isinstance(header, dict):
  810. return
  811. if "system" in header:
  812. header["system"] = "{{system}}"
  813. tools = header.get("tools")
  814. if isinstance(tools, list):
  815. header["tools"] = [
  816. tool.get("name") if isinstance(tool, dict) else "{{tools}}"
  817. for tool in tools
  818. ]
  819. def render_jsonl(records: list[object]) -> str:
  820. """Render parsed JSON values as compact, newline-terminated JSONL."""
  821. return "".join(
  822. json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
  823. for record in records
  824. )
  825. def compare_snapshot_files(files: dict[str, str], update: bool) -> None:
  826. """Write or exactly compare the advanced executable snapshot files."""
  827. if update:
  828. SNAPSHOT_DIRECTORY.mkdir(parents=True, exist_ok=True)
  829. for name, content in files.items():
  830. (SNAPSHOT_DIRECTORY / name).write_text(content, encoding="utf-8")
  831. print(f"smoke-python-runtime: updated snapshots in {SNAPSHOT_DIRECTORY}")
  832. existing = {
  833. path.name
  834. for path in SNAPSHOT_DIRECTORY.iterdir()
  835. if path.is_file()
  836. } if SNAPSHOT_DIRECTORY.is_dir() else set()
  837. expected = set(SNAPSHOT_FILENAMES)
  838. if existing != expected:
  839. raise AssertionError(
  840. "advanced snapshot files differ: "
  841. f"missing={sorted(expected - existing)}, unexpected={sorted(existing - expected)}"
  842. )
  843. for name, actual in files.items():
  844. expected_text = (SNAPSHOT_DIRECTORY / name).read_text(encoding="utf-8")
  845. if actual == expected_text:
  846. continue
  847. diff = "".join(difflib.unified_diff(
  848. expected_text.splitlines(keepends=True),
  849. actual.splitlines(keepends=True),
  850. fromfile=f"expected/{name}",
  851. tofile=f"actual/{name}",
  852. ))
  853. raise AssertionError(
  854. f"advanced executable snapshot mismatch in {name}; "
  855. "rerun with --update-snapshots after reviewing the behavior\n"
  856. f"{diff}"
  857. )
  858. if __name__ == "__main__":
  859. main()