smoke-python-runtime.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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 importlib
  7. import importlib.metadata
  8. import json
  9. import os
  10. import queue
  11. import subprocess
  12. import sys
  13. import sysconfig
  14. import tempfile
  15. import threading
  16. import time
  17. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  18. from pathlib import Path
  19. from typing import TYPE_CHECKING, Callable
  20. if TYPE_CHECKING:
  21. from deepseek_harness import RunResult
  22. EXPECTED_TEXT = "runtime smoke ok"
  23. LIVE_API_SENTINEL = "PYTHON_SDK_LIVE_OK"
  24. CODE_PROMPT = "Use run_code to compute the packaged worker smoke value."
  25. CODE_WORKER_TEXT = "code worker smoke ok"
  26. WORKFLOW_PROMPT = "Use workflow to compute the packaged worker smoke value without agents."
  27. WORKFLOW_WORKER_TEXT = "workflow worker smoke ok"
  28. MINIMAL_PROMPT = "Exercise the packaged minimal agent's persistent shell and string-replacement editor."
  29. MINIMAL_TEXT = "minimal agent smoke ok"
  30. MINIMAL_EDITOR_PATH_PREFIX = "Editor path: "
  31. FS_SEARCH_PROMPT = "Exercise the packaged filesystem search tools."
  32. FS_SEARCH_TEXT = "filesystem search smoke ok"
  33. FS_SEARCH_MARKER = "PACKAGED_FS_SEARCH_OK"
  34. MCP_PROMPT = "Exercise the packaged MCP client with one external stdio server."
  35. MCP_TEXT = "MCP client smoke ok"
  36. PROFILE_PLUGIN_PROMPT = "Verify the Python-installed dsh profile plugin."
  37. PROFILE_PLUGIN_TEXT = "profile plugin smoke ok"
  38. PROFILE_PLUGIN_MARKER = "PYTHON_INSTALLED_DSH_PROFILE_PLUGIN"
  39. IS_WINDOWS = sys.platform == "win32"
  40. MINIMAL_SHELL_TOOL = "pwsh" if IS_WINDOWS else "bash"
  41. MINIMAL_SHELL_COMMAND = (
  42. "$global:dshSdkCounter = [int]$global:dshSdkCounter + 1; "
  43. 'Write-Output "COUNT=$global:dshSdkCounter CWD=$((Get-Location).Path)"; '
  44. "if ($global:dshSdkCounter -eq 1) { Set-Location $env:TEMP }"
  45. if IS_WINDOWS
  46. else (
  47. "counter=$(( ${counter:-0} + 1 )); export counter; "
  48. "printf 'COUNT=%s CWD=%s\\n' \"$counter\" \"$PWD\"; "
  49. "if [ \"$counter\" -eq 1 ]; then cd /tmp; fi"
  50. )
  51. )
  52. MINIMAL_SHELL_SECOND_CWD = str(Path(tempfile.gettempdir()).resolve()) if IS_WINDOWS else "/tmp"
  53. LEGACY_CUSTOM_DISABLED_ROWS = (
  54. "agent-instructions",
  55. "goal",
  56. "goal-round-driver",
  57. "command-goal",
  58. "plan-mode",
  59. "skill",
  60. "skill-filesystem",
  61. "tool-fs",
  62. "tool-fs-search",
  63. "tool-goal",
  64. "tool-ralph",
  65. "tool-skill",
  66. "tool-str-replace-editor",
  67. "tool-subagent-control",
  68. "tool-subagent-list-agents",
  69. "tool-subagent-fork",
  70. "tool-subagent-report",
  71. "tool-todo",
  72. "tool-web",
  73. )
  74. SNAPSHOT_PROMPT = "Run the advanced packaged-runtime snapshot scenario."
  75. SNAPSHOT_SESSION_ID = "advanced-executable"
  76. SNAPSHOT_DIRECT_CHILD_PROMPT = "Reply with exactly DIRECT_CHILD_OK and nothing else."
  77. SNAPSHOT_WORKFLOW_CHILD_PROMPT = "Reply with exactly WORKFLOW_CHILD_OK and nothing else."
  78. SNAPSHOT_FINAL_TEXT = "ADVANCED_EXECUTABLE_OK"
  79. RESTART_FIRST_PROMPT = "Complete the first isolated Python SDK process turn."
  80. RESTART_FIRST_TEXT = "PROCESS_ONE_OK"
  81. RESTART_SECOND_PROMPT = "Complete the second isolated Python SDK process turn."
  82. RESTART_SECOND_TEXT = "PROCESS_TWO_OK"
  83. RESTART_FIRST_SESSION_ID = "process-one"
  84. RESTART_SECOND_SESSION_ID = "process-two"
  85. SNAPSHOT_PLUGIN_CODE = """\
  86. return (ctx) => {
  87. harness.registerTool(ctx, harness.defineTool({
  88. name: 'snapshot_double',
  89. description: 'Double a number for executable snapshot verification.',
  90. parameters: { value: { type: 'number', required: true } },
  91. output: {
  92. schema: { type: 'number' },
  93. render(_args, value) {
  94. return [{ type: 'text', text: String(value) }]
  95. }
  96. },
  97. async execute(args) {
  98. return args.value * 2
  99. }
  100. }))
  101. }
  102. """
  103. SNAPSHOT_WORKFLOW_SCRIPT = (
  104. "phase('Delegate')\n"
  105. f"const reply = await agent('{SNAPSHOT_WORKFLOW_CHILD_PROMPT}', {{ label: 'workflow-child' }})\n"
  106. "return { reply }"
  107. )
  108. ADVANCED_SNAPSHOT_DIRECTORY = (
  109. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
  110. )
  111. ADVANCED_SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
  112. MINIMAL_SNAPSHOT_DIRECTORY = (
  113. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "minimal"
  114. )
  115. if IS_WINDOWS:
  116. MINIMAL_SNAPSHOT_DIRECTORY /= "win-x64"
  117. MINIMAL_SNAPSHOT_FILENAMES = ("model-visible.json",)
  118. RESTART_SNAPSHOT_DIRECTORY = (
  119. Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "restart"
  120. )
  121. RESTART_SNAPSHOT_FILENAMES = ("result.json", "requests.json", "session.1.jsonl", "session.2.jsonl")
  122. MCP_SERVER_SCRIPT = """\
  123. import json
  124. import os
  125. import sys
  126. import time
  127. log_path = os.environ.get("MCP_SMOKE_LOG")
  128. def send(message):
  129. sys.stdout.write(json.dumps(message, separators=(",", ":")) + "\\n")
  130. sys.stdout.flush()
  131. for line in sys.stdin:
  132. request = json.loads(line)
  133. if log_path is not None:
  134. with open(log_path, "a", encoding="utf-8") as log:
  135. log.write(str(request.get("method")) + "\\n")
  136. request_id = request.get("id")
  137. if request_id is None:
  138. continue
  139. method = request.get("method")
  140. if method == "initialize":
  141. send({
  142. "jsonrpc": "2.0",
  143. "id": request_id,
  144. "result": {
  145. "protocolVersion": request["params"]["protocolVersion"],
  146. "capabilities": {"tools": {"listChanged": False}},
  147. "serverInfo": {"name": "python-wheel-fixture", "version": "1.0.0"},
  148. },
  149. })
  150. elif method == "tools/list":
  151. # Keep discovery pending long enough that an SDK runtime answering
  152. # initialize before discovery completes makes its first model request
  153. # without this tool and fails deterministically.
  154. time.sleep(0.25)
  155. send({
  156. "jsonrpc": "2.0",
  157. "id": request_id,
  158. "result": {
  159. "tools": [{
  160. "name": "add",
  161. "description": "Add two numbers.",
  162. "inputSchema": {
  163. "type": "object",
  164. "properties": {"a": {"type": "number"}, "b": {"type": "number"}},
  165. "required": ["a", "b"],
  166. "additionalProperties": False,
  167. },
  168. }],
  169. },
  170. })
  171. elif method == "tools/call":
  172. params = request["params"]
  173. if params.get("name") != "add" or params.get("arguments") != {"a": 19, "b": 23}:
  174. send({
  175. "jsonrpc": "2.0",
  176. "id": request_id,
  177. "error": {"code": -32602, "message": "unexpected tool call"},
  178. })
  179. continue
  180. send({
  181. "jsonrpc": "2.0",
  182. "id": request_id,
  183. "result": {"content": [{"type": "text", "text": "42"}]},
  184. })
  185. else:
  186. send({
  187. "jsonrpc": "2.0",
  188. "id": request_id,
  189. "error": {"code": -32601, "message": f"unsupported method: {method}"},
  190. })
  191. """
  192. def write_profile_patch(
  193. root: Path,
  194. name: str,
  195. sessions: Path,
  196. patches: list[dict[str, object]],
  197. ) -> Path:
  198. """Write one JSON-form dsh profile patch with deterministic persistence."""
  199. path = root / name
  200. path.write_text(json.dumps([
  201. {
  202. "id": "session-persistence-jsonl",
  203. "config": {"root": str(sessions), "compression": "none"},
  204. },
  205. {"id": "session-telemetry-otel", "disabled": True},
  206. *patches,
  207. ], indent=2))
  208. return path
  209. def write_mcp_patch(root: Path, sessions: Path, server_script: Path) -> Path:
  210. """Write a profile patch that mounts the packaged MCP client."""
  211. return write_profile_patch(root, "mcp.patch.yml", sessions, [{
  212. "insert": [{
  213. "id": "mcp-fixture",
  214. "name": "@deepseek-ai/dsh-mcp-client",
  215. "config": {
  216. "serverName": "fixture",
  217. "transport": "stdio",
  218. "command": sys.executable,
  219. "args": [str(server_script)],
  220. "env": {"MCP_SMOKE_LOG": str(server_script.with_suffix(".log"))},
  221. "failOnStartupError": True,
  222. "reconnect": {"enabled": False},
  223. },
  224. }],
  225. }])
  226. class MockModelHandler(BaseHTTPRequestHandler):
  227. """Return deterministic text, worker, and orchestration completions."""
  228. requests: list[dict[str, object]] = []
  229. def do_POST(self) -> None:
  230. content_length = int(self.headers.get("content-length", "0"))
  231. body = json.loads(self.rfile.read(content_length))
  232. self.requests.append(body)
  233. self.send_response(200)
  234. self.send_header("content-type", "text/event-stream")
  235. self.end_headers()
  236. chunks = completion_chunks(body)
  237. for chunk in chunks:
  238. self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
  239. self.wfile.write(b"data: [DONE]\n\n")
  240. self.wfile.flush()
  241. def log_message(self, _format: str, *_args: object) -> None:
  242. return
  243. def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
  244. """Choose the next deterministic model response from request history."""
  245. messages = body.get("messages")
  246. if not isinstance(messages, list) or not messages:
  247. raise AssertionError(f"model request has no messages: {body}")
  248. latest = messages[-1]
  249. if not isinstance(latest, dict):
  250. raise AssertionError(f"model request has an invalid latest message: {body}")
  251. if latest.get("role") == "tool":
  252. call_id, tool_name = latest_tool_call(messages)
  253. tool_text = message_text(latest.get("content"))
  254. mcp = mcp_tool_followup(call_id, tool_name, tool_text)
  255. if mcp is not None:
  256. return mcp
  257. fs_search = fs_search_tool_followup(call_id, tool_name, tool_text)
  258. if fs_search is not None:
  259. return fs_search
  260. minimal = minimal_tool_followup(body, call_id, tool_name, tool_text)
  261. if minimal is not None:
  262. return minimal
  263. advanced = advanced_tool_followup(body, call_id, tool_name, tool_text)
  264. if advanced is not None:
  265. return advanced
  266. if "42" not in tool_text:
  267. raise AssertionError(f"{tool_name} worker returned no expected value: {latest}")
  268. if tool_name == "run_code":
  269. return text_chunks(CODE_WORKER_TEXT)
  270. if tool_name == "workflow":
  271. return text_chunks(WORKFLOW_WORKER_TEXT)
  272. raise AssertionError(f"unexpected tool follow-up: {tool_name}")
  273. user_prompts = [
  274. message_text(message.get("content"))
  275. for message in reversed(messages)
  276. if isinstance(message, dict) and message.get("role") == "user"
  277. ]
  278. minimal_prompt = next(
  279. (
  280. prompt
  281. for prompt in user_prompts
  282. if prompt.startswith(f"{MINIMAL_PROMPT}\n{MINIMAL_EDITOR_PATH_PREFIX}")
  283. ),
  284. None,
  285. )
  286. # The minimal composition's assembled system prompt, advertised tool schemas, and
  287. # model-visible messages are pinned by its snapshot, not asserted here.
  288. if minimal_prompt is not None:
  289. return tool_call_chunks(
  290. "minimal-bash-1",
  291. MINIMAL_SHELL_TOOL,
  292. {"command": MINIMAL_SHELL_COMMAND},
  293. )
  294. scenario_prompts = {
  295. SNAPSHOT_DIRECT_CHILD_PROMPT,
  296. SNAPSHOT_WORKFLOW_CHILD_PROMPT,
  297. SNAPSHOT_PROMPT,
  298. CODE_PROMPT,
  299. WORKFLOW_PROMPT,
  300. FS_SEARCH_PROMPT,
  301. MCP_PROMPT,
  302. RESTART_FIRST_PROMPT,
  303. RESTART_SECOND_PROMPT,
  304. PROFILE_PLUGIN_PROMPT,
  305. }
  306. prompt = next(
  307. (candidate for candidate in user_prompts if candidate in scenario_prompts),
  308. message_text(latest.get("content")),
  309. )
  310. if prompt == SNAPSHOT_DIRECT_CHILD_PROMPT:
  311. return text_chunks("DIRECT_CHILD_OK")
  312. if prompt == SNAPSHOT_WORKFLOW_CHILD_PROMPT:
  313. return text_chunks("WORKFLOW_CHILD_OK")
  314. if prompt == SNAPSHOT_PROMPT:
  315. assert_advertised_tool(body, "cordis_define")
  316. return tool_call_chunks(
  317. "advanced-define",
  318. "cordis_define",
  319. {
  320. "plugin": {"kind": "new", "idPrefix": "snap"},
  321. "name": "Snapshot Double",
  322. "purpose": "Expose a deterministic doubling tool for executable snapshot verification.",
  323. "code": {"host": SNAPSHOT_PLUGIN_CODE},
  324. },
  325. )
  326. if prompt == RESTART_FIRST_PROMPT:
  327. return text_chunks(RESTART_FIRST_TEXT)
  328. if prompt == RESTART_SECOND_PROMPT:
  329. if any(
  330. isinstance(message, dict)
  331. and RESTART_FIRST_TEXT in message_text(message.get("content"))
  332. for message in messages
  333. ):
  334. raise AssertionError("second isolated process inherited the first process history")
  335. return text_chunks(RESTART_SECOND_TEXT)
  336. if prompt == CODE_PROMPT:
  337. assert_advertised_tool(body, "run_code")
  338. return tool_call_chunks(
  339. "call-code-worker",
  340. "run_code",
  341. {"code": "return 6 * 7", "description": "Compute the smoke value"},
  342. )
  343. if prompt == WORKFLOW_PROMPT:
  344. assert_advertised_tool(body, "workflow")
  345. return tool_call_chunks(
  346. "call-workflow-worker",
  347. "workflow",
  348. {
  349. "script": "return 6 * 7",
  350. "meta": {
  351. "name": "pkg-worker-smoke",
  352. "description": "exercise the packaged workflow worker",
  353. },
  354. },
  355. )
  356. if prompt == FS_SEARCH_PROMPT:
  357. assert_advertised_tool(body, "grep")
  358. assert_advertised_tool(body, "glob")
  359. return tool_call_chunks(
  360. "fs-search-grep",
  361. "grep",
  362. {"pattern": FS_SEARCH_MARKER, "path": "."},
  363. )
  364. if prompt == MCP_PROMPT:
  365. assert_advertised_tool(body, "mcp__fixture__add")
  366. return tool_call_chunks(
  367. "mcp-add",
  368. "mcp__fixture__add",
  369. {"a": 19, "b": 23},
  370. )
  371. if prompt == PROFILE_PLUGIN_PROMPT:
  372. system_text = "\n".join(
  373. message_text(message.get("content"))
  374. for message in messages
  375. if isinstance(message, dict) and message.get("role") == "system"
  376. )
  377. if PROFILE_PLUGIN_MARKER not in system_text:
  378. raise AssertionError("external profile plugin contributed no model-visible marker")
  379. return text_chunks(PROFILE_PLUGIN_TEXT)
  380. return text_chunks(EXPECTED_TEXT)
  381. def mcp_tool_followup(
  382. call_id: str,
  383. tool_name: str,
  384. tool_text: str,
  385. ) -> list[dict[str, object]] | None:
  386. """Verify one tool call through the packaged MCP client."""
  387. if call_id != "mcp-add":
  388. return None
  389. if tool_name != "mcp__fixture__add" or "42" not in tool_text:
  390. raise AssertionError(f"packaged MCP call returned an unexpected result: {tool_name}: {tool_text}")
  391. return text_chunks(MCP_TEXT)
  392. def fs_search_tool_followup(
  393. call_id: str,
  394. tool_name: str,
  395. tool_text: str,
  396. ) -> list[dict[str, object]] | None:
  397. """Exercise both ripgrep-backed tools through the packaged executable."""
  398. if not call_id.startswith("fs-search-"):
  399. return None
  400. if call_id == "fs-search-grep" and tool_name == "grep":
  401. if "needle.txt" not in tool_text or FS_SEARCH_MARKER not in tool_text:
  402. raise AssertionError(f"packaged grep returned no marker: {tool_text}")
  403. return tool_call_chunks(
  404. "fs-search-glob",
  405. "glob",
  406. {"pattern": "**/*.txt"},
  407. )
  408. if call_id == "fs-search-glob" and tool_name == "glob":
  409. if "needle.txt" not in tool_text:
  410. raise AssertionError(f"packaged glob returned no fixture path: {tool_text}")
  411. return text_chunks(FS_SEARCH_TEXT)
  412. raise AssertionError(f"unexpected filesystem-search follow-up: {call_id} {tool_name}: {tool_text}")
  413. def minimal_tool_followup(
  414. body: dict[str, object],
  415. call_id: str,
  416. tool_name: str,
  417. tool_text: str,
  418. ) -> list[dict[str, object]] | None:
  419. """Verify the checked-in minimal composition's PTY and editor."""
  420. if not call_id.startswith("minimal-"):
  421. return None
  422. if call_id == "minimal-bash-1" and tool_name == MINIMAL_SHELL_TOOL:
  423. if "COUNT=1" not in tool_text:
  424. raise AssertionError(f"first persistent shell call lost its output: {tool_text}")
  425. return tool_call_chunks(
  426. "minimal-bash-2",
  427. MINIMAL_SHELL_TOOL,
  428. {"command": MINIMAL_SHELL_COMMAND},
  429. )
  430. if call_id == "minimal-bash-2" and tool_name == MINIMAL_SHELL_TOOL:
  431. expected = f"COUNT=2 CWD={MINIMAL_SHELL_SECOND_CWD}"
  432. if expected.lower() not in tool_text.lower():
  433. raise AssertionError(f"persistent shell did not retain state: {tool_text}")
  434. messages = body.get("messages")
  435. if not isinstance(messages, list):
  436. raise AssertionError("persistent editor smoke request has no messages")
  437. editor_path = next(
  438. (
  439. text.split(MINIMAL_EDITOR_PATH_PREFIX, 1)[1].strip()
  440. for message in messages
  441. if isinstance(message, dict) and message.get("role") == "user"
  442. for text in [message_text(message.get("content"))]
  443. if MINIMAL_EDITOR_PATH_PREFIX in text
  444. ),
  445. None,
  446. )
  447. if editor_path is None:
  448. raise AssertionError("persistent editor smoke prompt has no editor path")
  449. return tool_call_chunks(
  450. "minimal-editor",
  451. "str_replace_editor",
  452. {
  453. "command": "create",
  454. "path": editor_path,
  455. "file_text": "created by packaged editor\n",
  456. },
  457. )
  458. if call_id == "minimal-editor" and tool_name == "str_replace_editor":
  459. if "New file created successfully" not in tool_text:
  460. raise AssertionError(f"packaged editor did not create its file: {tool_text}")
  461. return text_chunks(MINIMAL_TEXT)
  462. raise AssertionError(f"unexpected minimal-agent follow-up: {call_id} {tool_name}: {tool_text}")
  463. def advanced_tool_followup(
  464. body: dict[str, object],
  465. call_id: str,
  466. tool_name: str,
  467. tool_text: str,
  468. ) -> list[dict[str, object]] | None:
  469. """Advance the executable snapshot's deterministic parent tool chain."""
  470. if not call_id.startswith("advanced-"):
  471. return None
  472. if call_id == "advanced-define" and tool_name == "cordis_define":
  473. if "Defined snap-1/pkg-1 (Snapshot Double)" not in tool_text:
  474. raise AssertionError(f"cordis_define returned no dynamic Package ids: {tool_text}")
  475. if "snapshot_double" in advertised_tool_names(body):
  476. raise AssertionError("snapshot_double was advertised before cordis_run")
  477. assert_advertised_tool(body, "cordis_run")
  478. return tool_call_chunks(
  479. "advanced-run",
  480. "cordis_run",
  481. {"pluginId": "snap-1", "packageId": "pkg-1", "mode": "run"},
  482. )
  483. if call_id == "advanced-run" and tool_name == "cordis_run":
  484. if "snap-1/pkg-1 is running (run-1)" not in tool_text:
  485. raise AssertionError(f"cordis_run returned no running Package ids: {tool_text}")
  486. assert_advertised_tool(body, "run_code")
  487. assert_advertised_tool(body, "snapshot_double")
  488. return tool_call_chunks(
  489. "advanced-code",
  490. "run_code",
  491. {
  492. "code": "return await tools.snapshot_double({ value: 21 })",
  493. "description": "Run the temporary Plugin tool",
  494. },
  495. )
  496. if call_id == "advanced-code" and tool_name == "run_code":
  497. if "42" not in tool_text:
  498. raise AssertionError(f"run_code returned no dynamic-tool value: {tool_text}")
  499. assert_advertised_tool(body, "subagent")
  500. return tool_call_chunks(
  501. "advanced-direct-child",
  502. "subagent",
  503. {
  504. "description": "Check direct child",
  505. "prompt": SNAPSHOT_DIRECT_CHILD_PROMPT,
  506. },
  507. )
  508. if call_id == "advanced-direct-child" and tool_name == "subagent":
  509. if "DIRECT_CHILD_OK" not in tool_text:
  510. raise AssertionError(f"subagent returned no expected child value: {tool_text}")
  511. assert_advertised_tool(body, "workflow")
  512. return tool_call_chunks(
  513. "advanced-workflow",
  514. "workflow",
  515. {
  516. "script": SNAPSHOT_WORKFLOW_SCRIPT,
  517. "meta": {
  518. "name": "advanced-exe-snapshot",
  519. "description": "exercise one packaged workflow child",
  520. },
  521. },
  522. )
  523. if call_id == "advanced-workflow" and tool_name == "workflow":
  524. if "WORKFLOW_CHILD_OK" not in tool_text:
  525. raise AssertionError(f"workflow returned no expected child value: {tool_text}")
  526. assert_advertised_tool(body, "cordis_undefine")
  527. return tool_call_chunks(
  528. "advanced-undefine",
  529. "cordis_undefine",
  530. {"pluginId": "snap-1"},
  531. )
  532. if call_id == "advanced-undefine" and tool_name == "cordis_undefine":
  533. if "Removed dynamic Plugin snap-1 and all of its Packages." not in tool_text:
  534. raise AssertionError(f"cordis_undefine returned no removal result: {tool_text}")
  535. if "snapshot_double" in advertised_tool_names(body):
  536. raise AssertionError("snapshot_double remained advertised after cordis_undefine")
  537. return text_chunks(SNAPSHOT_FINAL_TEXT)
  538. raise AssertionError(f"unexpected advanced tool follow-up: {call_id} {tool_name}: {tool_text}")
  539. def text_chunks(text: str) -> list[dict[str, object]]:
  540. """Build a complete streaming text response."""
  541. return [
  542. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  543. {"choices": [{"delta": {"content": text}}]},
  544. {
  545. "choices": [{"delta": {"content": ""}, "finish_reason": "stop"}],
  546. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  547. },
  548. ]
  549. def tool_call_chunks(call_id: str, name: str, arguments: dict[str, object]) -> list[dict[str, object]]:
  550. """Build a complete streaming function-call response."""
  551. return [
  552. {"choices": [{"delta": {"role": "assistant", "content": None, "reasoning_content": ""}}]},
  553. {
  554. "choices": [{
  555. "delta": {
  556. "tool_calls": [{
  557. "index": 0,
  558. "id": call_id,
  559. "type": "function",
  560. "function": {"name": name, "arguments": json.dumps(arguments)},
  561. }],
  562. },
  563. }],
  564. },
  565. {
  566. "choices": [{"delta": {"content": ""}, "finish_reason": "tool_calls"}],
  567. "usage": {"prompt_tokens": 3, "completion_tokens": 3},
  568. },
  569. ]
  570. def latest_tool_call(messages: list[object]) -> tuple[str, str]:
  571. """Find the assistant call id and name paired with the latest tool result."""
  572. for message in reversed(messages[:-1]):
  573. if not isinstance(message, dict):
  574. continue
  575. calls = message.get("tool_calls")
  576. if not isinstance(calls, list):
  577. continue
  578. for call in reversed(calls):
  579. if not isinstance(call, dict):
  580. continue
  581. function = call.get("function")
  582. call_id = call.get("id")
  583. if (
  584. isinstance(call_id, str)
  585. and isinstance(function, dict)
  586. and isinstance(function.get("name"), str)
  587. ):
  588. return call_id, function["name"]
  589. raise AssertionError(f"tool result has no preceding assistant tool call: {messages}")
  590. def message_text(content: object) -> str:
  591. """Read OpenAI text content in either string or block-list form."""
  592. if isinstance(content, str):
  593. return content
  594. if isinstance(content, list):
  595. return "".join(
  596. block.get("text", "")
  597. for block in content
  598. if isinstance(block, dict) and isinstance(block.get("text"), str)
  599. )
  600. return ""
  601. def advertised_tool_names(body: dict[str, object]) -> set[str]:
  602. """Return the model-facing tool names advertised on one request."""
  603. tools = body.get("tools")
  604. if not isinstance(tools, list):
  605. raise AssertionError(f"model request advertised no tools: {body}")
  606. names: set[str] = set()
  607. for tool in tools:
  608. if not isinstance(tool, dict):
  609. continue
  610. function = tool.get("function")
  611. if isinstance(function, dict) and isinstance(function.get("name"), str):
  612. names.add(function["name"])
  613. return names
  614. def assert_advertised_tool(body: dict[str, object], expected: str) -> None:
  615. """Require the packaged deployment to expose the requested tool."""
  616. names = advertised_tool_names(body)
  617. if expected not in names:
  618. raise AssertionError(f"model request did not advertise {expected}: {names}")
  619. class MockModel:
  620. def __enter__(self) -> "MockModel":
  621. MockModelHandler.requests.clear()
  622. self.server = ThreadingHTTPServer(("127.0.0.1", 0), MockModelHandler)
  623. self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
  624. self.thread.start()
  625. host, port = self.server.server_address
  626. self.url = f"http://{host}:{port}"
  627. return self
  628. def __exit__(self, _exc_type: object, _exc: object, _tb: object) -> None:
  629. self.server.shutdown()
  630. self.server.server_close()
  631. self.thread.join(timeout=5)
  632. def main() -> None:
  633. parser = argparse.ArgumentParser(description=__doc__)
  634. parser.add_argument(
  635. "--scenario",
  636. choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-mcp", "sdk-snapshot", "sdk-restart", "sdk-profile-plugin", "sdk-live", "direct"),
  637. default="all",
  638. )
  639. parser.add_argument("--exe", type=Path)
  640. parser.add_argument(
  641. "--installed-wheel",
  642. action="store_true",
  643. help="require a clean virtual environment containing matching installed SDK and runtime wheels",
  644. )
  645. parser.add_argument("--update-snapshots", action="store_true")
  646. args = parser.parse_args()
  647. if args.installed_wheel and args.exe is not None:
  648. parser.error("--installed-wheel resolves the wheel's own runtime and cannot be combined with --exe")
  649. if args.scenario == "sdk-live" and not args.installed_wheel:
  650. parser.error("--scenario sdk-live requires --installed-wheel")
  651. if args.scenario == "sdk-profile-plugin" and not args.installed_wheel:
  652. parser.error("--scenario sdk-profile-plugin requires --installed-wheel")
  653. if args.installed_wheel:
  654. args.exe = assert_installed_wheel_environment()
  655. if args.scenario in {"all", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-snapshot", "sdk-restart", "direct"} and args.exe is None:
  656. parser.error("--exe is required for custom, minimal, snapshot, and direct scenarios")
  657. if args.update_snapshots and args.scenario not in {"all", "sdk-minimal", "sdk-snapshot", "sdk-restart"}:
  658. parser.error("--update-snapshots requires --scenario sdk-minimal, sdk-snapshot, sdk-restart, or all")
  659. if args.exe is not None and not args.exe.is_file():
  660. parser.error(f"runtime executable does not exist: {args.exe}")
  661. if args.scenario == "sdk-live":
  662. smoke_sdk_live()
  663. print("smoke-python-runtime: sdk-live passed")
  664. return
  665. with MockModel() as model:
  666. if args.scenario in {"all", "sdk-default"}:
  667. smoke_sdk_default(model.url)
  668. if args.scenario in {"all", "sdk-custom"}:
  669. assert args.exe is not None
  670. smoke_sdk_custom(model.url, args.exe.resolve())
  671. if args.scenario in {"all", "sdk-minimal"}:
  672. assert args.exe is not None
  673. smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots)
  674. if args.scenario in {"all", "sdk-fs-search"}:
  675. assert args.exe is not None
  676. smoke_sdk_fs_search(model.url, args.exe.resolve())
  677. if args.scenario in {"all", "sdk-mcp"}:
  678. smoke_sdk_mcp(model.url, None if args.exe is None else args.exe.resolve())
  679. if args.scenario in {"all", "sdk-snapshot"}:
  680. assert args.exe is not None
  681. smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  682. if args.scenario in {"all", "sdk-restart"}:
  683. assert args.exe is not None
  684. smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
  685. if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}:
  686. smoke_sdk_profile_plugin(model.url)
  687. if args.scenario in {"all", "direct"}:
  688. assert args.exe is not None
  689. smoke_direct(model.url, args.exe.resolve())
  690. if not MockModelHandler.requests:
  691. raise AssertionError("mock model endpoint received no requests")
  692. print(f"smoke-python-runtime: {args.scenario} passed")
  693. def assert_installed_wheel_environment() -> Path:
  694. """Prove that this process imports matching non-editable wheel installations."""
  695. if sys.prefix == sys.base_prefix:
  696. raise AssertionError("installed-wheel smoke must run inside a virtual environment")
  697. if os.environ.get("PYTHONPATH"):
  698. raise AssertionError("installed-wheel smoke requires PYTHONPATH to be unset")
  699. if os.environ.get("DSH_RUNTIME_MODE"):
  700. raise AssertionError("installed-wheel smoke requires DSH_RUNTIME_MODE to be unset")
  701. repo_root = Path(__file__).resolve().parent.parent
  702. cwd = Path.cwd().resolve()
  703. if cwd.is_relative_to(repo_root):
  704. raise AssertionError(f"installed-wheel smoke must run outside the repository, got {cwd}")
  705. sdk_version = importlib.metadata.version("deepseek-harness-sdk")
  706. runtime_version = importlib.metadata.version("deepseek-harness-runtime-bin")
  707. if sdk_version != runtime_version:
  708. raise AssertionError(
  709. f"installed SDK/runtime versions differ: {sdk_version} != {runtime_version}"
  710. )
  711. expected_runtime_requirement = f"deepseek-harness-runtime-bin=={sdk_version}"
  712. requirements = importlib.metadata.requires("deepseek-harness-sdk") or []
  713. if expected_runtime_requirement not in requirements:
  714. raise AssertionError(
  715. f"installed SDK does not require {expected_runtime_requirement}: {requirements}"
  716. )
  717. prefix = Path(sys.prefix).resolve()
  718. imported: dict[str, Path] = {}
  719. for name in ("deepseek_harness", "deepseek_harness_runtime"):
  720. module = importlib.import_module(name)
  721. module_file = getattr(module, "__file__", None)
  722. if not isinstance(module_file, str):
  723. raise AssertionError(f"installed module {name} has no filesystem location")
  724. path = Path(module_file).resolve()
  725. if not path.is_relative_to(prefix):
  726. raise AssertionError(f"installed module {name} came from outside the virtual environment: {path}")
  727. if path.is_relative_to(repo_root):
  728. raise AssertionError(f"installed module {name} came from the repository checkout: {path}")
  729. imported[name] = path
  730. runtime_module = sys.modules["deepseek_harness_runtime"]
  731. executable = runtime_module.bundled_runtime_path().resolve()
  732. runtime_package = imported["deepseek_harness_runtime"].parent
  733. if not executable.is_relative_to(runtime_package):
  734. raise AssertionError(f"bundled runtime came from outside the installed runtime wheel: {executable}")
  735. runtime_files = importlib.metadata.files("deepseek-harness-runtime-bin") or []
  736. if not any(Path(file).name == executable.name for file in runtime_files):
  737. raise AssertionError(f"runtime executable is absent from installed distribution records: {executable}")
  738. return executable
  739. def smoke_sdk_live() -> None:
  740. """Run a real-model, tool-using two-turn task through installed wheels."""
  741. from deepseek_harness import DeepSeekHarness
  742. api_key = os.environ.get("DEEPSEEK_API_KEY")
  743. base_url = os.environ.get("DEEPSEEK_BASE_URL")
  744. if not api_key:
  745. raise AssertionError("sdk-live requires DEEPSEEK_API_KEY")
  746. if not base_url:
  747. raise AssertionError("sdk-live requires an explicit DEEPSEEK_BASE_URL")
  748. with tempfile.TemporaryDirectory(prefix="dsh-sdk-live-") as temporary:
  749. root = Path(temporary).resolve()
  750. dsh_home = root / "home"
  751. sessions = dsh_home / "sessions"
  752. marker = root / "live-api-marker.txt"
  753. session_id = "installed-wheel-live-api"
  754. shell_tool = "pwsh" if IS_WINDOWS else "bash"
  755. create_prompt = (
  756. f"Use the {shell_tool} tool to create the file at the absolute path below with exactly one line "
  757. f"containing {LIVE_API_SENTINEL}. Then reply with exactly {LIVE_API_SENTINEL}.\n{marker}"
  758. )
  759. verify_prompt = (
  760. "Use a tool to read the file created in the previous turn. "
  761. f"If its only line is {LIVE_API_SENTINEL}, reply with exactly {LIVE_API_SENTINEL}."
  762. )
  763. with DeepSeekHarness(
  764. provider="deepseek-official",
  765. model="deepseek-v4-flash",
  766. cwd=str(root),
  767. dsh_home=str(dsh_home),
  768. env={
  769. "DSH_PERMISSION_MODE": "danger-full-access",
  770. "DSH_TELEMETRY_DISABLED": "1",
  771. },
  772. api_key=api_key,
  773. base_url=base_url,
  774. request_timeout_seconds=180,
  775. ) as harness:
  776. created = harness.run(create_prompt, session_id=session_id)
  777. verified = harness.run(verify_prompt, session_id=session_id)
  778. for label, result in (("create", created), ("verify", verified)):
  779. if result.finish_reason != "completed":
  780. event_types = [event.get("type") for event in result.events]
  781. turn_end_data = next(
  782. (event.get("data") for event in reversed(result.events) if event.get("type") == "turn/end"),
  783. None,
  784. )
  785. turn_end = safe_turn_end(turn_end_data)
  786. raise AssertionError(
  787. f"{label} turn ended with {result.finish_reason!r}; "
  788. f"final={result.final_response!r}; turn_end={turn_end!r}; events={event_types}"
  789. )
  790. if not any(event.get("type") == "tool/call" for event in result.events):
  791. raise AssertionError(
  792. f"{label} turn made no model-requested tool call; "
  793. f"final={result.final_response!r}"
  794. )
  795. if result.final_response.strip() != LIVE_API_SENTINEL:
  796. raise AssertionError(f"{label} turn returned {result.final_response!r}")
  797. if not marker.is_file():
  798. raise AssertionError(f"real-model tool turn did not create {marker}")
  799. if marker.read_text(encoding="utf-8").splitlines() != [LIVE_API_SENTINEL]:
  800. raise AssertionError(f"real-model tool turn wrote unexpected text to {marker}")
  801. assert_zstd_session_log(sessions)
  802. def safe_turn_end(value: object) -> object:
  803. """Project a live-provider failure without retaining credential-bearing text."""
  804. if not isinstance(value, dict):
  805. return value
  806. reason = value.get("reason")
  807. if not isinstance(reason, dict):
  808. return {"turn": value.get("turn"), "reason": reason}
  809. error = reason.get("error")
  810. safe_error = None
  811. if isinstance(error, dict):
  812. safe_error = {
  813. key: error.get(key)
  814. for key in ("code", "status")
  815. if error.get(key) is not None
  816. }
  817. return {
  818. "turn": value.get("turn"),
  819. "reason": {
  820. "kind": reason.get("kind"),
  821. **({"error": safe_error} if safe_error is not None else {}),
  822. },
  823. }
  824. def smoke_sdk_default(base_url: str) -> None:
  825. from deepseek_harness import DeepSeekHarness
  826. with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary:
  827. root = Path(temporary).resolve()
  828. dsh_home = root / "home"
  829. sessions = dsh_home / "sessions"
  830. with DeepSeekHarness(
  831. provider="deepseek-official",
  832. model="smoke-model",
  833. cwd=str(root),
  834. dsh_home=str(dsh_home),
  835. env={
  836. "DSH_PERMISSION_MODE": "danger-full-access",
  837. "DSH_TELEMETRY_DISABLED": "1",
  838. },
  839. api_key="sk-keyless-smoke",
  840. base_url=base_url,
  841. request_timeout_seconds=60,
  842. ) as harness:
  843. result = harness.run("reply with the smoke text", session_id="default-smoke")
  844. assert result.final_response == EXPECTED_TEXT, (
  845. f"final={result.final_response!r} finish={result.finish_reason!r} "
  846. f"events={[event.get('type') for event in result.events]!r} "
  847. f"turn_end={safe_turn_end(next((event.get('data', event) for event in reversed(result.events) if event.get('type') == 'turn/end'), {}))!r}"
  848. )
  849. assert_zstd_session_log(sessions)
  850. def smoke_sdk_custom(base_url: str, executable: Path) -> None:
  851. from deepseek_harness import DeepSeekHarness
  852. with tempfile.TemporaryDirectory(prefix="dsh-sdk-custom-") as temporary:
  853. root = Path(temporary).resolve()
  854. dsh_home = root / "home"
  855. sessions = dsh_home / "sessions"
  856. patch = write_profile_patch(root, "custom.patch.yml", sessions, [
  857. {"id": "tools", "config": {"mode": "both"}},
  858. {
  859. "id": "system-prompt",
  860. "config": {
  861. "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.",
  862. },
  863. },
  864. {"id": "session-log-deepseek", "config": {"enabled": True}},
  865. *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS),
  866. {"id": "tool-bash", "disabled": True},
  867. {"id": "tool-pwsh", "disabled": True},
  868. {
  869. "id": "tool-subagent",
  870. "config": {
  871. "provider": "spawn",
  872. "toolName": "subagent",
  873. "backgroundMode": "one-shot",
  874. },
  875. },
  876. {"insert": [
  877. {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"},
  878. {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"},
  879. {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"},
  880. ]},
  881. ])
  882. with DeepSeekHarness(
  883. provider="deepseek-official",
  884. model="smoke-model",
  885. cwd=str(root),
  886. dsh_bin=str(executable),
  887. dsh_home=str(dsh_home),
  888. patches=(str(patch),),
  889. env={
  890. "DSH_PERMISSION_MODE": "danger-full-access",
  891. "DSH_TELEMETRY_DISABLED": "1",
  892. },
  893. api_key="sk-keyless-smoke",
  894. base_url=base_url,
  895. request_timeout_seconds=60,
  896. ) as harness:
  897. text_result = harness.run("reply with the smoke text", session_id="custom-smoke")
  898. code_result = harness.run(CODE_PROMPT, session_id="custom-smoke")
  899. workflow_result = harness.run(WORKFLOW_PROMPT, session_id="custom-smoke")
  900. assert text_result.final_response == EXPECTED_TEXT, text_result.final_response
  901. assert code_result.final_response == CODE_WORKER_TEXT, code_result.final_response
  902. assert workflow_result.final_response == WORKFLOW_WORKER_TEXT, workflow_result.final_response
  903. assert_session_log(sessions, root, EXPECTED_TEXT, CODE_WORKER_TEXT, WORKFLOW_WORKER_TEXT)
  904. def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) -> None:
  905. """Exercise the shipped standalone minimal profile through the packaged executable."""
  906. from deepseek_harness import DeepSeekHarness
  907. # One mock model serves every scenario of a run, so the snapshot takes this turn's slice.
  908. first_request = len(MockModelHandler.requests)
  909. with tempfile.TemporaryDirectory(prefix="dsh-sdk-minimal-") as temporary:
  910. root = Path(temporary).resolve()
  911. editor_path = root / "created.txt"
  912. prompt = f"{MINIMAL_PROMPT}\n{MINIMAL_EDITOR_PATH_PREFIX}{editor_path}"
  913. dsh_home = root / "home"
  914. sessions = dsh_home / "sessions"
  915. with DeepSeekHarness(
  916. provider="deepseek-official",
  917. model="smoke-model",
  918. cwd=str(root),
  919. dsh_bin=str(executable),
  920. dsh_home=str(dsh_home),
  921. profile="sdk-minimal",
  922. api_key="sk-keyless-smoke",
  923. base_url=base_url,
  924. request_timeout_seconds=60,
  925. ) as harness:
  926. result = harness.run(prompt, session_id="minimal-agent-smoke")
  927. event_text = json.dumps(result.events)
  928. if MINIMAL_TEXT not in event_text:
  929. raise AssertionError(f"minimal agent run emitted no final response: {result.events}")
  930. if editor_path.read_text() != "created by packaged editor\n":
  931. raise AssertionError(f"packaged editor wrote unexpected content: {editor_path.read_text()!r}")
  932. assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2")
  933. files = build_minimal_snapshot_files(MockModelHandler.requests[first_request:], root)
  934. compare_snapshot_files(
  935. files, update_snapshots, MINIMAL_SNAPSHOT_DIRECTORY, MINIMAL_SNAPSHOT_FILENAMES,
  936. )
  937. def smoke_sdk_fs_search(base_url: str, executable: Path) -> None:
  938. """Exercise real grep and glob spawns through the packaged executable."""
  939. from deepseek_harness import DeepSeekHarness
  940. with tempfile.TemporaryDirectory(prefix="dsh-sdk-fs-search-") as temporary:
  941. root = Path(temporary).resolve()
  942. (root / "needle.txt").write_text(f"{FS_SEARCH_MARKER}\n")
  943. dsh_home = root / "home"
  944. sessions = dsh_home / "sessions"
  945. patch = write_profile_patch(root, "fs-search.patch.yml", sessions, [
  946. {"id": "skill-filesystem", "disabled": True},
  947. {"id": "tool-fs-search", "config": {"sampleOverCapGlobResults": False}},
  948. ])
  949. with DeepSeekHarness(
  950. provider="deepseek-official",
  951. model="smoke-model",
  952. cwd=str(root),
  953. dsh_bin=str(executable),
  954. dsh_home=str(dsh_home),
  955. patches=(str(patch),),
  956. env={
  957. "DSH_PERMISSION_MODE": "danger-full-access",
  958. "DSH_TELEMETRY_DISABLED": "1",
  959. },
  960. api_key="sk-keyless-smoke",
  961. base_url=base_url,
  962. request_timeout_seconds=60,
  963. ) as harness:
  964. result = harness.run(FS_SEARCH_PROMPT, session_id="fs-search-smoke")
  965. assert result.final_response == FS_SEARCH_TEXT, result.final_response
  966. assert_session_log(sessions, root, FS_SEARCH_TEXT, FS_SEARCH_MARKER, "needle.txt")
  967. def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None:
  968. """Discover and call an external stdio MCP tool through the packaged client."""
  969. from deepseek_harness import DeepSeekHarness
  970. with tempfile.TemporaryDirectory(prefix="dsh-sdk-mcp-") as temporary:
  971. root = Path(temporary).resolve()
  972. dsh_home = root / "home"
  973. sessions = dsh_home / "sessions"
  974. server_script = root / "mcp_server.py"
  975. server_script.write_text(MCP_SERVER_SCRIPT)
  976. patch = write_mcp_patch(root, sessions, server_script)
  977. discovery_log = server_script.with_suffix(".log")
  978. with DeepSeekHarness(
  979. provider="deepseek-official",
  980. model="smoke-model",
  981. cwd=str(root),
  982. dsh_bin=None if executable is None else str(executable),
  983. dsh_home=str(dsh_home),
  984. patches=(str(patch),),
  985. env={
  986. "DSH_PERMISSION_MODE": "danger-full-access",
  987. "DSH_TELEMETRY_DISABLED": "1",
  988. },
  989. api_key="sk-keyless-smoke",
  990. base_url=base_url,
  991. request_timeout_seconds=60,
  992. ) as harness:
  993. result = harness.run(MCP_PROMPT, session_id="mcp-smoke")
  994. assert result.final_response == MCP_TEXT, result.final_response
  995. assert discovery_log.read_text().splitlines() == [
  996. "initialize",
  997. "notifications/initialized",
  998. "tools/list",
  999. "tools/call",
  1000. ]
  1001. assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42")
  1002. def smoke_sdk_profile_plugin(base_url: str) -> None:
  1003. """Install an external bundle through Python's dsh command and load it in the SDK."""
  1004. from deepseek_harness import DeepSeekHarness
  1005. with tempfile.TemporaryDirectory(prefix="dsh-sdk-profile-plugin-") as temporary:
  1006. root = Path(temporary).resolve()
  1007. dsh_home = root / "home"
  1008. plugin = root / "plugin"
  1009. plugin.mkdir()
  1010. (plugin / "package.json").write_text(json.dumps({
  1011. "name": "dsh-python-blackbox-plugin",
  1012. "version": "1.0.0",
  1013. "private": True,
  1014. "type": "module",
  1015. "exports": "./index.js",
  1016. "peerDependencies": {"@deepseek-ai/cordis": "*"},
  1017. "dsh": {"bundle": {"patch": "./cordis.patch.yml"}},
  1018. }, indent=2))
  1019. (plugin / "index.js").write_text(
  1020. "import { Context } from '@deepseek-ai/cordis'\n"
  1021. "export const name = 'python-sdk-blackbox-plugin'\n"
  1022. "export const inject = ['systemPrompt']\n"
  1023. "export function apply(ctx) {\n"
  1024. " if (!(ctx instanceof Context)) throw new Error('external plugin loaded a second Cordis instance')\n"
  1025. " ctx.effect(() => ctx.systemPrompt.section({\n"
  1026. " name: 'python-sdk:blackbox-plugin',\n"
  1027. " order: 10,\n"
  1028. f" text: '{PROFILE_PLUGIN_MARKER}',\n"
  1029. " }))\n"
  1030. "}\n"
  1031. )
  1032. (plugin / "cordis.patch.yml").write_text(json.dumps([{
  1033. "insert": [{"id": "python-sdk-blackbox-plugin", "name": "dsh-python-blackbox-plugin"}],
  1034. }], indent=2))
  1035. dsh = Path(sysconfig.get_path("scripts")) / ("dsh.exe" if IS_WINDOWS else "dsh")
  1036. environment = {**os.environ, "DSH_HOME": str(dsh_home)}
  1037. installed = subprocess.run(
  1038. [str(dsh), "plugin", "--profile", "sdk", "add", f"file:{plugin}"],
  1039. cwd=root,
  1040. env=environment,
  1041. text=True,
  1042. capture_output=True,
  1043. check=False,
  1044. )
  1045. if installed.returncode != 0:
  1046. raise AssertionError(
  1047. f"Python-installed dsh could not add the external profile plugin: "
  1048. f"stdout={installed.stdout!r} stderr={installed.stderr!r}"
  1049. )
  1050. manifest = json.loads((dsh_home / "profiles" / "sdk" / "package.json").read_text())
  1051. if "dsh-python-blackbox-plugin" not in manifest.get("dependencies", {}):
  1052. raise AssertionError(f"dsh plugin did not record the external dependency: {manifest}")
  1053. if "dsh-python-blackbox-plugin" not in manifest["dsh"]["profile"]["bundles"]:
  1054. raise AssertionError(f"dsh plugin did not activate the external bundle: {manifest}")
  1055. harness = DeepSeekHarness(
  1056. provider="deepseek-official",
  1057. model="smoke-model",
  1058. cwd=str(root),
  1059. dsh_home=str(dsh_home),
  1060. env={
  1061. "DSH_PERMISSION_MODE": "danger-full-access",
  1062. "DSH_TELEMETRY_DISABLED": "1",
  1063. },
  1064. api_key="sk-keyless-smoke",
  1065. base_url=base_url,
  1066. request_timeout_seconds=60,
  1067. )
  1068. try:
  1069. with harness:
  1070. result = harness.run(PROFILE_PLUGIN_PROMPT, session_id="profile-plugin-smoke")
  1071. except Exception as error:
  1072. raise AssertionError(
  1073. f"external profile plugin runtime failed: {harness.client._runtime_diagnostics()}"
  1074. ) from error
  1075. assert result.final_response == PROFILE_PLUGIN_TEXT, result.final_response
  1076. assert_zstd_session_log(dsh_home / "sessions")
  1077. def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  1078. """Drive and compare the advanced SDK/executable behavioral snapshot."""
  1079. from deepseek_harness import DeepSeekHarness
  1080. with tempfile.TemporaryDirectory(prefix="dsh-sdk-snapshot-") as temporary:
  1081. root = Path(temporary).resolve()
  1082. dsh_home = root / "home"
  1083. sessions = dsh_home / "sessions"
  1084. patch = write_profile_patch(root, "snapshot.patch.yml", sessions, [
  1085. {"id": "tools", "config": {"mode": "both"}},
  1086. {
  1087. "id": "system-prompt",
  1088. "config": {
  1089. "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.",
  1090. },
  1091. },
  1092. {"id": "session-log-deepseek", "config": {"enabled": True}},
  1093. *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS),
  1094. {"id": "tool-bash", "disabled": True},
  1095. {"id": "tool-pwsh", "disabled": True},
  1096. {
  1097. "id": "tool-subagent",
  1098. "config": {
  1099. "provider": "spawn",
  1100. "toolName": "subagent",
  1101. "backgroundMode": "one-shot",
  1102. },
  1103. },
  1104. {"insert": [
  1105. {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"},
  1106. {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"},
  1107. {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"},
  1108. ]},
  1109. ])
  1110. with DeepSeekHarness(
  1111. provider="deepseek-official",
  1112. model="smoke-model",
  1113. cwd=str(root),
  1114. dsh_bin=str(executable),
  1115. dsh_home=str(dsh_home),
  1116. patches=(str(patch),),
  1117. env={
  1118. "DSH_PERMISSION_MODE": "danger-full-access",
  1119. "DSH_TELEMETRY_DISABLED": "1",
  1120. },
  1121. api_key="sk-keyless-smoke",
  1122. base_url=base_url,
  1123. request_timeout_seconds=60,
  1124. ) as harness:
  1125. result = harness.run(SNAPSHOT_PROMPT, session_id=SNAPSHOT_SESSION_ID)
  1126. assert result.final_response == SNAPSHOT_FINAL_TEXT, result.final_response
  1127. methods = [notification.method for notification in result.notifications]
  1128. if methods.count("subagent.started") != 2 or methods.count("subagent.finished") != 2:
  1129. raise AssertionError(f"advanced snapshot emitted unexpected subagent lifecycle: {methods}")
  1130. if not any(event.get("type") == "tool/code-dispatch" for event in result.events):
  1131. raise AssertionError("advanced snapshot emitted no tool/code-dispatch event")
  1132. logs = read_session_logs(sessions)
  1133. child_ids = snapshot_child_ids(result)
  1134. expected_ids = {SNAPSHOT_SESSION_ID, *child_ids}
  1135. if set(logs) != expected_ids:
  1136. raise AssertionError(f"advanced snapshot expected parent plus two child logs: {sorted(logs)}")
  1137. if "DIRECT_CHILD_OK" not in render_jsonl(logs[child_ids[0]]):
  1138. raise AssertionError("first advanced child log has no direct-subagent result")
  1139. if "WORKFLOW_CHILD_OK" not in render_jsonl(logs[child_ids[1]]):
  1140. raise AssertionError("second advanced child log has no workflow-subagent result")
  1141. files = build_snapshot_files(result, logs, child_ids, root)
  1142. compare_snapshot_files(
  1143. files, update_snapshots, ADVANCED_SNAPSHOT_DIRECTORY, ADVANCED_SNAPSHOT_FILENAMES,
  1144. )
  1145. def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
  1146. """Snapshot two isolated sessions across complete SDK runtime restarts."""
  1147. from deepseek_harness import DeepSeekHarness
  1148. with tempfile.TemporaryDirectory(prefix="dsh-sdk-restart-") as temporary:
  1149. root = Path(temporary).resolve()
  1150. dsh_home = root / "home"
  1151. sessions = dsh_home / "sessions"
  1152. patch = write_profile_patch(root, "restart.patch.yml", sessions, [
  1153. {"id": "tools", "config": {"mode": "both"}},
  1154. {
  1155. "id": "system-prompt",
  1156. "config": {
  1157. "persona": "You are a coding agent powered by the {{model}} model. Your working directory is {{cwd}}.",
  1158. },
  1159. },
  1160. {"id": "session-log-deepseek", "config": {"enabled": True}},
  1161. *({"id": row_id, "disabled": True} for row_id in LEGACY_CUSTOM_DISABLED_ROWS),
  1162. {"id": "tool-bash", "disabled": True},
  1163. {"id": "tool-pwsh", "disabled": True},
  1164. {
  1165. "id": "tool-subagent",
  1166. "config": {
  1167. "provider": "spawn",
  1168. "toolName": "subagent",
  1169. "backgroundMode": "one-shot",
  1170. },
  1171. },
  1172. {"insert": [
  1173. {"id": "code-runtime", "name": "@deepseek-ai/dsh-code-runtime-worker-thread"},
  1174. {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"},
  1175. {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"},
  1176. ]},
  1177. ])
  1178. first_request = len(MockModelHandler.requests)
  1179. def run(prompt: str, session_id: str) -> "RunResult":
  1180. with DeepSeekHarness(
  1181. provider="deepseek-official",
  1182. model="smoke-model",
  1183. cwd=str(root),
  1184. dsh_bin=str(executable),
  1185. dsh_home=str(dsh_home),
  1186. patches=(str(patch),),
  1187. env={
  1188. "DSH_PERMISSION_MODE": "danger-full-access",
  1189. "DSH_TELEMETRY_DISABLED": "1",
  1190. },
  1191. api_key="sk-keyless-smoke",
  1192. base_url=base_url,
  1193. request_timeout_seconds=60,
  1194. ) as harness:
  1195. return harness.run(prompt, session_id=session_id)
  1196. first = run(RESTART_FIRST_PROMPT, RESTART_FIRST_SESSION_ID)
  1197. second = run(RESTART_SECOND_PROMPT, RESTART_SECOND_SESSION_ID)
  1198. requests = MockModelHandler.requests[first_request:]
  1199. if len(requests) != 2:
  1200. raise AssertionError(f"restart snapshot expected two model requests: {requests}")
  1201. if first.final_response != RESTART_FIRST_TEXT or second.final_response != RESTART_SECOND_TEXT:
  1202. raise AssertionError(
  1203. f"restart snapshot responses differ: {first.final_response!r}, {second.final_response!r}"
  1204. )
  1205. logs = read_session_logs(sessions)
  1206. expected_ids = {RESTART_FIRST_SESSION_ID, RESTART_SECOND_SESSION_ID}
  1207. if set(logs) != expected_ids:
  1208. raise AssertionError(f"restart snapshot expected two durable sessions: {sorted(logs)}")
  1209. for session_id, expected in (
  1210. (RESTART_FIRST_SESSION_ID, RESTART_FIRST_TEXT),
  1211. (RESTART_SECOND_SESSION_ID, RESTART_SECOND_TEXT),
  1212. ):
  1213. records = logs[session_id]
  1214. if sum(record.get("type") == "turn/end" for record in records) != 1:
  1215. raise AssertionError(f"restart snapshot {session_id} has an unexpected turn count")
  1216. if expected not in render_jsonl(records):
  1217. raise AssertionError(f"restart snapshot durable log has no {expected}")
  1218. files = build_restart_snapshot_files(first, second, requests, logs, root, sessions)
  1219. compare_snapshot_files(
  1220. files, update_snapshots, RESTART_SNAPSHOT_DIRECTORY, RESTART_SNAPSHOT_FILENAMES,
  1221. )
  1222. def smoke_direct(base_url: str, executable: Path) -> None:
  1223. with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary:
  1224. root = Path(temporary).resolve()
  1225. dsh_home = root / "home"
  1226. sessions = dsh_home / "sessions"
  1227. patch = write_profile_patch(root, "direct.patch.yml", sessions, [])
  1228. environment = {
  1229. **os.environ,
  1230. "DSH_HOME": str(dsh_home),
  1231. "DSH_PERMISSION_MODE": "danger-full-access",
  1232. "DSH_TELEMETRY_DISABLED": "1",
  1233. "DEEPSEEK_API_KEY": "sk-keyless-smoke",
  1234. "DEEPSEEK_BASE_URL": base_url,
  1235. }
  1236. peer = RuntimePeer(
  1237. [str(executable), "--profile", "sdk", "--patch", str(patch)],
  1238. root,
  1239. environment,
  1240. )
  1241. try:
  1242. peer.send({"jsonrpc": "2.0", "id": "initialize", "method": "initialize", "params": {"cwd": str(root), "provider": "deepseek-official", "model": "smoke-model"}})
  1243. peer.read_until(lambda message: message.get("id") == "initialize")
  1244. peer.send({
  1245. "jsonrpc": "2.0",
  1246. "id": "prompt",
  1247. "method": "session/prompt",
  1248. "params": {"sessionId": "direct-smoke", "contentBlocks": [{"type": "text", "text": "reply with the smoke text"}]},
  1249. })
  1250. messages = peer.read_until(lambda message: message.get("id") == "prompt")
  1251. if not any(is_idle_notification(message) for message in messages):
  1252. messages.extend(peer.read_until(is_idle_notification))
  1253. event_text = json.dumps(messages)
  1254. if EXPECTED_TEXT not in event_text:
  1255. raise AssertionError(f"direct runtime emitted no final response: {messages}")
  1256. peer.send({"jsonrpc": "2.0", "id": "shutdown", "method": "shutdown"})
  1257. peer.read_until(lambda message: message.get("id") == "shutdown")
  1258. finally:
  1259. peer.close()
  1260. assert_session_log(sessions, root, EXPECTED_TEXT)
  1261. def is_idle_notification(message: dict[str, object]) -> bool:
  1262. """Return whether a JSON-RPC notification marks a session idle."""
  1263. params = message.get("params")
  1264. return (
  1265. message.get("method") == "session.status"
  1266. and isinstance(params, dict)
  1267. and params.get("status") == "idle"
  1268. )
  1269. class RuntimePeer:
  1270. def __init__(self, argv: list[str], cwd: Path, environment: dict[str, str]) -> None:
  1271. self.process = subprocess.Popen(
  1272. argv,
  1273. cwd=cwd,
  1274. env=environment,
  1275. stdin=subprocess.PIPE,
  1276. stdout=subprocess.PIPE,
  1277. stderr=subprocess.PIPE,
  1278. text=True,
  1279. encoding="utf-8",
  1280. bufsize=1,
  1281. )
  1282. self.stdout: queue.Queue[str | None] = queue.Queue()
  1283. self.stderr: list[str] = []
  1284. threading.Thread(target=self._read_stdout, daemon=True).start()
  1285. threading.Thread(target=self._read_stderr, daemon=True).start()
  1286. def send(self, message: dict[str, object]) -> None:
  1287. if self.process.stdin is None:
  1288. raise RuntimeError("runtime stdin is unavailable")
  1289. self.process.stdin.write(json.dumps(message) + "\n")
  1290. self.process.stdin.flush()
  1291. def read_until(self, predicate: Callable[[dict[str, object]], bool]) -> list[dict[str, object]]:
  1292. deadline = time.monotonic() + 60
  1293. messages: list[dict[str, object]] = []
  1294. while time.monotonic() < deadline:
  1295. try:
  1296. line = self.stdout.get(timeout=min(0.25, deadline - time.monotonic()))
  1297. except queue.Empty:
  1298. continue
  1299. if line is None:
  1300. raise RuntimeError(f"runtime exited before expected message; stderr: {''.join(self.stderr)}")
  1301. try:
  1302. message = json.loads(line)
  1303. except json.JSONDecodeError:
  1304. continue
  1305. messages.append(message)
  1306. if predicate(message):
  1307. return messages
  1308. raise TimeoutError(f"runtime timed out; messages={messages}; stderr={''.join(self.stderr)}")
  1309. def close(self) -> None:
  1310. if self.process.stdin is not None and not self.process.stdin.closed:
  1311. self.process.stdin.close()
  1312. try:
  1313. self.process.wait(timeout=10)
  1314. except subprocess.TimeoutExpired:
  1315. self.process.kill()
  1316. self.process.wait()
  1317. if self.process.returncode not in {0, -15}:
  1318. raise RuntimeError(f"runtime exited {self.process.returncode}; stderr: {''.join(self.stderr)}")
  1319. def _read_stdout(self) -> None:
  1320. assert self.process.stdout is not None
  1321. for line in self.process.stdout:
  1322. self.stdout.put(line)
  1323. self.stdout.put(None)
  1324. def _read_stderr(self) -> None:
  1325. assert self.process.stderr is not None
  1326. self.stderr.extend(self.process.stderr)
  1327. def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
  1328. logs = list(sessions.rglob("*.jsonl"))
  1329. if len(logs) != 1:
  1330. raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}")
  1331. lines = logs[0].read_text().splitlines()
  1332. header = json.loads(lines[0])
  1333. if header.get("cwd") != str(cwd):
  1334. raise AssertionError(f"session header cwd is not absolute/canonical: {header}")
  1335. rendered = "\n".join(lines)
  1336. for expected in expected_texts:
  1337. if expected not in rendered:
  1338. raise AssertionError(f"session log has no {expected!r} response: {logs[0]}")
  1339. def assert_zstd_session_log(sessions: Path) -> None:
  1340. logs = list(sessions.rglob("*.jsonl.zstd"))
  1341. if len(logs) != 1:
  1342. raise AssertionError(f"expected one Zstandard JSONL session log under {sessions}, found {logs}")
  1343. if not logs[0].read_bytes().startswith(bytes.fromhex("28b52ffd")):
  1344. raise AssertionError(f"session log has no Zstandard magic: {logs[0]}")
  1345. def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]:
  1346. """Parse every persisted JSONL session into a map keyed by header id."""
  1347. logs: dict[str, list[dict[str, object]]] = {}
  1348. for path in sorted(sessions.rglob("*.jsonl")):
  1349. records = [
  1350. json.loads(line)
  1351. for line in path.read_text(encoding="utf-8").splitlines()
  1352. if line
  1353. ]
  1354. if not records or records[0].get("type") != "session":
  1355. raise AssertionError(f"session log has no header: {path}")
  1356. session_id = records[0].get("id")
  1357. if not isinstance(session_id, str):
  1358. raise AssertionError(f"session log header has no string id: {path}")
  1359. if session_id in logs:
  1360. raise AssertionError(f"duplicate persisted session id: {session_id}")
  1361. logs[session_id] = records
  1362. return logs
  1363. def snapshot_child_ids(result: "RunResult") -> list[str]:
  1364. """Return the two child session ids in their SDK notification order."""
  1365. child_ids: list[str] = []
  1366. for notification in result.notifications:
  1367. if notification.method != "subagent.started":
  1368. continue
  1369. payload = notification.payload
  1370. if payload.get("parentSessionId") != SNAPSHOT_SESSION_ID:
  1371. continue
  1372. child_id = payload.get("childSessionId")
  1373. if isinstance(child_id, str) and child_id not in child_ids:
  1374. child_ids.append(child_id)
  1375. if len(child_ids) != 2:
  1376. raise AssertionError(f"advanced snapshot expected two child session ids: {child_ids}")
  1377. return child_ids
  1378. def build_minimal_snapshot_files(
  1379. requests: list[dict[str, object]],
  1380. cwd: Path,
  1381. ) -> dict[str, str]:
  1382. """Render the minimal composition's model-visible surface as expected output.
  1383. Every assembled system prompt, advertised tool schema, and system or user message is
  1384. kept verbatim: they carry what the deployment actually shows the model, so a plugin
  1385. that contributes an unintended system section or user message cannot pass unnoticed.
  1386. Assistant and tool payloads keep only their call identity because their text differs
  1387. across the platforms this expected output must replay on. The shipped profile omits
  1388. dynamic runtime context, so every message it emits is compared.
  1389. """
  1390. snapshot = []
  1391. for body in requests:
  1392. messages = body.get("messages")
  1393. if not isinstance(messages, list):
  1394. raise AssertionError(f"minimal model request has no messages: {body}")
  1395. snapshot.append({
  1396. "tools": minimal_snapshot_text(body.get("tools"), cwd),
  1397. "messages": [
  1398. minimal_snapshot_message(message, cwd)
  1399. for message in messages
  1400. ],
  1401. })
  1402. return {"model-visible.json": json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"}
  1403. def minimal_snapshot_message(message: object, cwd: Path) -> dict[str, object]:
  1404. """Reduce one model-visible message to its stable, behavior-carrying parts."""
  1405. if not isinstance(message, dict):
  1406. raise AssertionError(f"minimal model request has an invalid message: {message}")
  1407. role = message.get("role")
  1408. if role in ("system", "user"):
  1409. return {"role": role, "text": minimal_snapshot_text(message_text(message.get("content")), cwd)}
  1410. if role == "assistant":
  1411. calls = message.get("tool_calls")
  1412. if not isinstance(calls, list):
  1413. raise AssertionError(f"minimal assistant message has no tool calls: {message}")
  1414. return {
  1415. "role": role,
  1416. "toolCalls": [
  1417. {"id": call.get("id"), "name": (call.get("function") or {}).get("name")}
  1418. for call in calls
  1419. if isinstance(call, dict)
  1420. ],
  1421. }
  1422. if role == "tool":
  1423. return {"role": role, "toolCallId": message.get("tool_call_id"), "text": "{{tool-result}}"}
  1424. raise AssertionError(f"minimal model request has an unexpected message role: {message}")
  1425. def minimal_snapshot_text(value: object, cwd: Path) -> object:
  1426. """Replace the scenario's temporary working directory everywhere it appears."""
  1427. if isinstance(value, str):
  1428. return value.replace(str(cwd), "{{cwd}}")
  1429. if isinstance(value, list):
  1430. return [minimal_snapshot_text(item, cwd) for item in value]
  1431. if isinstance(value, dict):
  1432. return {key: minimal_snapshot_text(item, cwd) for key, item in value.items()}
  1433. return value
  1434. def build_snapshot_files(
  1435. result: "RunResult",
  1436. logs: dict[str, list[dict[str, object]]],
  1437. child_ids: list[str],
  1438. cwd: Path,
  1439. ) -> dict[str, str]:
  1440. """Render the SDK result and three persisted logs into stable expected outputs."""
  1441. replacements = [(str(cwd), "{{cwd}}"), (SNAPSHOT_SESSION_ID, "{{parent}}")]
  1442. replacements.append((snapshot_workflow_run_id(result), "{{workflow-run}}"))
  1443. for index, child_id in enumerate(child_ids, start=1):
  1444. replacements.append((child_id, f"{{{{child-{index}}}}}"))
  1445. agent_id = snapshot_agent_id(result, child_id)
  1446. replacements.append((agent_id, f"{{{{agent-{index}}}}}"))
  1447. replacements.sort(key=lambda pair: len(pair[0]), reverse=True)
  1448. result_value = {
  1449. "session_id": result.session_id,
  1450. "final_response": result.final_response,
  1451. "events": result.events,
  1452. "notifications": [
  1453. {"method": notification.method, "payload": notification.payload}
  1454. for notification in result.notifications
  1455. ],
  1456. }
  1457. normalized_result = normalize_snapshot_value(result_value, replacements)
  1458. files = {
  1459. "result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
  1460. "session.jsonl": render_jsonl(
  1461. project_session_snapshot([
  1462. normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]
  1463. ])
  1464. ),
  1465. }
  1466. for index, child_id in enumerate(child_ids, start=1):
  1467. files[f"session.{index}.jsonl"] = render_jsonl(
  1468. project_session_snapshot([
  1469. normalize_snapshot_value(record, replacements) for record in logs[child_id]
  1470. ])
  1471. )
  1472. return files
  1473. def build_restart_snapshot_files(
  1474. first: "RunResult",
  1475. second: "RunResult",
  1476. requests: list[dict[str, object]],
  1477. logs: dict[str, list[dict[str, object]]],
  1478. cwd: Path,
  1479. sessions: Path,
  1480. ) -> dict[str, str]:
  1481. """Render two SDK processes, isolated model histories, and durable logs."""
  1482. replacements = [
  1483. (str(sessions), "{{sessions}}"),
  1484. (str(cwd), "{{cwd}}"),
  1485. (RESTART_FIRST_SESSION_ID, "{{session-1}}"),
  1486. (RESTART_SECOND_SESSION_ID, "{{session-2}}"),
  1487. ]
  1488. result_value = [
  1489. {
  1490. "session_id": result.session_id,
  1491. "final_response": result.final_response,
  1492. "finish_reason": result.finish_reason,
  1493. "eventTypes": [event.get("type") for event in result.events],
  1494. "notificationMethods": [notification.method for notification in result.notifications],
  1495. }
  1496. for result in (first, second)
  1497. ]
  1498. request_value = [
  1499. {
  1500. "model": request.get("model"),
  1501. "messages": restart_request_messages(request),
  1502. "toolNames": sorted(advertised_tool_names(request)),
  1503. }
  1504. for request in requests
  1505. ]
  1506. return {
  1507. "result.json": json.dumps(
  1508. normalize_snapshot_value(result_value, replacements), indent=2, ensure_ascii=False,
  1509. ) + "\n",
  1510. "requests.json": json.dumps(
  1511. normalize_snapshot_value(request_value, replacements), indent=2, ensure_ascii=False,
  1512. ) + "\n",
  1513. "session.1.jsonl": render_jsonl(project_session_snapshot([
  1514. normalize_snapshot_value(record, replacements) for record in logs[RESTART_FIRST_SESSION_ID]
  1515. ])),
  1516. "session.2.jsonl": render_jsonl(project_session_snapshot([
  1517. normalize_snapshot_value(record, replacements) for record in logs[RESTART_SECOND_SESSION_ID]
  1518. ])),
  1519. }
  1520. def restart_request_messages(request: dict[str, object]) -> list[object]:
  1521. """Project model history while tokenizing composition-owned system prose."""
  1522. messages = request.get("messages")
  1523. if not isinstance(messages, list):
  1524. raise AssertionError(f"restart snapshot request has no messages: {request}")
  1525. return [
  1526. {"role": "system", "content": "{{system}}"}
  1527. if isinstance(message, dict) and message.get("role") == "system"
  1528. else message
  1529. for message in messages
  1530. ]
  1531. def snapshot_workflow_run_id(result: "RunResult") -> str:
  1532. """Return the one workflow run id emitted by the advanced scenario."""
  1533. run_ids: set[str] = set()
  1534. for event in result.events:
  1535. event_type = event.get("type")
  1536. data = event.get("data")
  1537. if not isinstance(event_type, str) or not event_type.startswith("tool-workflow/"):
  1538. continue
  1539. if isinstance(data, dict) and isinstance(data.get("runId"), str):
  1540. run_ids.add(data["runId"])
  1541. if len(run_ids) != 1:
  1542. raise AssertionError(f"advanced snapshot expected one workflow run id: {sorted(run_ids)}")
  1543. return next(iter(run_ids))
  1544. def snapshot_agent_id(result: "RunResult", child_id: str) -> str:
  1545. """Find the successful subagent id paired with one child session."""
  1546. for notification in result.notifications:
  1547. if notification.method != "subagent.finished":
  1548. continue
  1549. payload = notification.payload
  1550. if payload.get("childSessionId") != child_id:
  1551. continue
  1552. if payload.get("provider") != "spawn" or payload.get("status") != "ok":
  1553. raise AssertionError(f"advanced child did not finish successfully: {payload}")
  1554. agent_id = payload.get("agentId")
  1555. if isinstance(agent_id, str):
  1556. return agent_id
  1557. raise AssertionError(f"advanced snapshot has no finished agent for child {child_id}")
  1558. def normalize_snapshot_value(
  1559. value: object,
  1560. replacements: list[tuple[str, str]],
  1561. ) -> object:
  1562. """Scrub volatile values and bulky request headers without losing behavior."""
  1563. if isinstance(value, str):
  1564. normalized = value
  1565. for actual, token in replacements:
  1566. normalized = normalized.replace(actual, token)
  1567. return normalized
  1568. if isinstance(value, list):
  1569. return [normalize_snapshot_value(item, replacements) for item in value]
  1570. if not isinstance(value, dict):
  1571. return value
  1572. normalized = {
  1573. key: normalize_snapshot_value(item, replacements)
  1574. for key, item in value.items()
  1575. }
  1576. if normalized.get("type") == "session" and "createdAt" in normalized:
  1577. normalized["createdAt"] = 0
  1578. if "seq" in normalized and "time" in normalized:
  1579. normalized["time"] = 0
  1580. if isinstance(normalized.get("id"), str) and normalized.get("role") in ("assistant", "user"):
  1581. normalized["id"] = "{{messageId}}"
  1582. scrub_snapshot_header(normalized)
  1583. return normalized
  1584. def scrub_snapshot_header(value: dict[object, object]) -> None:
  1585. """Tokenize full request-header bulk while retaining tool names."""
  1586. data = value.get("data")
  1587. if not isinstance(data, dict):
  1588. return
  1589. if value.get("type") == "request/header":
  1590. header = data.get("header")
  1591. if not isinstance(header, dict):
  1592. return
  1593. if "system" in header:
  1594. header["system"] = "{{system}}"
  1595. tools = header.get("tools")
  1596. if isinstance(tools, list):
  1597. header["tools"] = [
  1598. tool.get("name") if isinstance(tool, dict) else "{{tools}}"
  1599. for tool in tools
  1600. ]
  1601. def render_jsonl(records: list[object]) -> str:
  1602. """Render parsed JSON values as compact, newline-terminated JSONL."""
  1603. return "".join(
  1604. json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
  1605. for record in records
  1606. )
  1607. def project_session_snapshot(records: list[dict[str, object]]) -> list[dict[str, object]]:
  1608. """Omit storage sequence/time envelopes from snapshot body records."""
  1609. projected = [dict(record) for record in records]
  1610. for record in projected[1:]:
  1611. for key in ("seq", "time", "seq0", "time0"):
  1612. record.pop(key, None)
  1613. return projected
  1614. def compare_snapshot_files(
  1615. files: dict[str, str],
  1616. update: bool,
  1617. directory: Path,
  1618. filenames: tuple[str, ...],
  1619. ) -> None:
  1620. """Write or exactly compare one scenario's expected snapshot files."""
  1621. scenario = directory.name
  1622. if tuple(files) != filenames:
  1623. raise AssertionError(f"{scenario} snapshot builder produced {tuple(files)}, expected {filenames}")
  1624. if update:
  1625. directory.mkdir(parents=True, exist_ok=True)
  1626. for name, content in files.items():
  1627. (directory / name).write_text(content, encoding="utf-8", newline="\n")
  1628. print(f"smoke-python-runtime: updated snapshots in {directory}")
  1629. existing = {
  1630. path.name
  1631. for path in directory.iterdir()
  1632. if path.is_file()
  1633. } if directory.is_dir() else set()
  1634. expected = set(filenames)
  1635. if existing != expected:
  1636. raise AssertionError(
  1637. f"{scenario} snapshot files differ: "
  1638. f"missing={sorted(expected - existing)}, unexpected={sorted(existing - expected)}"
  1639. )
  1640. for name, actual in files.items():
  1641. expected_text = (directory / name).read_text(encoding="utf-8")
  1642. if actual == expected_text:
  1643. continue
  1644. diff = "".join(difflib.unified_diff(
  1645. expected_text.splitlines(keepends=True),
  1646. actual.splitlines(keepends=True),
  1647. fromfile=f"expected/{name}",
  1648. tofile=f"actual/{name}",
  1649. ))
  1650. raise AssertionError(
  1651. f"{scenario} executable snapshot mismatch in {name}; "
  1652. "rerun with --update-snapshots after reviewing the behavior\n"
  1653. f"{diff}"
  1654. )
  1655. if __name__ == "__main__":
  1656. main()