smoke-python-runtime.py 102 KB

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