smoke-python-runtime.py 39 KB

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