1
0

smoke-python-runtime.py 37 KB

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