1
0

smoke-python-runtime.py 89 KB

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