sdk.snapshot.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /**
  2. * Keyless snapshot coverage for the TypeScript SDK path: each scenario spawns
  3. * the REAL `dsh-jsonrpc-agent` runtime (per `DSH_EXAMPLE_MODE`) through the
  4. * REAL `@deepseek-ai/dsh-sdk-client`, drives one turn over stdio JSON-RPC,
  5. * and pins three surfaces — the SDK `TurnResult`, the complete notification
  6. * stream, and the persisted session logs. Replay serves recorded model
  7. * responses via `llm-replay` (`cordis.snapshot.yml`); `DSH_SNAPSHOT=record`
  8. * re-records against the live API; `DSH_SNAPSHOT=refresh` replays committed
  9. * fixtures and rewrites expected outputs.
  10. */
  11. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  12. import { tmpdir } from 'node:os'
  13. import { delimiter, join } from 'node:path'
  14. import { fileURLToPath } from 'node:url'
  15. import { describe, expect, it } from 'vitest'
  16. import {
  17. normalizeSessionLog,
  18. normalizeStdout,
  19. refreshFixtureReplacements,
  20. scrubRequestHeaders,
  21. stabilizeRefreshLog,
  22. type HarvestedLog,
  23. type NormalizeContext,
  24. } from '@deepseek-ai/dsh-acp-snapshot'
  25. import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke'
  26. import { DeepSeekHarness, type HarnessNotification, type TurnResult } from '@deepseek-ai/dsh-sdk-client'
  27. const testsDir = dirOf(import.meta.url)
  28. const snapshotsDir = join(testsDir, 'snapshots')
  29. const liveConfig = join(testsDir, '..', 'cordis.yml')
  30. const replayConfig = join(testsDir, '..', 'cordis.snapshot.yml')
  31. const runtimeBin = fileURLToPath(new URL('../../../packages/examples/jsonrpc-demo/src/bin.ts', import.meta.url))
  32. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  33. const mode = process.env.DSH_SNAPSHOT ?? 'replay'
  34. const recording = mode === 'record'
  35. const refreshing = mode === 'refresh'
  36. function dirOf(url: string): string {
  37. return fileURLToPath(new URL('.', url))
  38. }
  39. interface SdkScenario {
  40. /** Scenario name; the snapshots/<name> fixture directory. */
  41. name: string
  42. /** The user prompt for the single SDK turn. */
  43. prompt: string
  44. /** Fixed SDK session id, so fixtures and replay binding stay stable. */
  45. sessionId: string
  46. /** How many child sessions the turn persists (subagent scenarios). */
  47. children: number
  48. }
  49. const SCENARIOS: SdkScenario[] = [
  50. {
  51. name: 'text-turn',
  52. prompt: 'Reply with exactly: SDK snapshot OK',
  53. sessionId: 'sdk-snapshot-text',
  54. children: 0,
  55. },
  56. {
  57. name: 'bash-tool',
  58. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  59. sessionId: 'sdk-snapshot-bash',
  60. children: 0,
  61. },
  62. {
  63. name: 'subagent-spawn',
  64. prompt: "Use the subagent tool exactly once with description 'echo probe' and prompt: Reply with exactly: child answer 42. Then reply with the subagent's final answer verbatim.",
  65. sessionId: 'sdk-snapshot-subagent',
  66. children: 1,
  67. },
  68. ]
  69. interface PersistedLog {
  70. readonly path: string
  71. readonly content: string
  72. readonly header: Record<string, unknown>
  73. }
  74. async function jsonlFiles(dir: string): Promise<string[]> {
  75. const entries = await readdir(dir, { recursive: true })
  76. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  77. }
  78. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  79. const files = await jsonlFiles(sessionsRoot)
  80. return Promise.all(files.map(async (path) => {
  81. const content = await readFile(path, 'utf8')
  82. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  83. return { path, content, header }
  84. }))
  85. }
  86. function contextOf(logs: readonly { content: string; header: Record<string, unknown> }[], cwd: string): NormalizeContext {
  87. return {
  88. sessionIds: logs.flatMap(log => typeof log.header.id === 'string' ? [log.header.id] : []),
  89. cwd,
  90. }
  91. }
  92. function contextOfContents(contents: readonly string[]): NormalizeContext {
  93. const headers = contents.map(content => JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>)
  94. return {
  95. sessionIds: headers.flatMap(header => typeof header.id === 'string' ? [header.id] : []),
  96. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  97. }
  98. }
  99. /**
  100. * Normalize the SDK-visible notification stream: embedded `session.event`
  101. * envelopes get the session-log treatment (times zeroed, headers tokenized),
  102. * then every record is scrubbed like a wire frame.
  103. */
  104. function normalizeNotifications(notifications: readonly HarnessNotification[], ctx: NormalizeContext): string {
  105. const events = notifications
  106. .filter(n => n.method === 'session.event')
  107. .map(n => n.params.event as Record<string, unknown>)
  108. const normalizedEvents = events.length === 0
  109. ? []
  110. : scrubRequestHeaders(normalizeSessionLog(
  111. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  112. ctx,
  113. )).trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  114. let eventIndex = 0
  115. const records = notifications.map((notification) => {
  116. if (notification.method !== 'session.event') return { method: notification.method, params: notification.params }
  117. const event = normalizedEvents[eventIndex++]
  118. return { method: notification.method, params: { ...notification.params, event } }
  119. })
  120. return normalizeStdout(`${records.map(record => JSON.stringify(record)).join('\n')}\n`, ctx)
  121. }
  122. /** Normalize the turn-result projection (status, reason kind, final text). */
  123. function normalizeResult(result: TurnResult, ctx: NormalizeContext): string {
  124. return normalizeStdout(`${JSON.stringify({
  125. status: result.status,
  126. reason: result.reason,
  127. finalResponse: result.finalResponse,
  128. })}\n`, ctx)
  129. }
  130. /** One SDK turn against a fresh runtime subprocess in an isolated cwd. */
  131. async function runScenario(scenario: SdkScenario): Promise<{
  132. result: TurnResult
  133. notifications: HarnessNotification[]
  134. logs: PersistedLog[]
  135. cwd: string
  136. }> {
  137. const cwd = await mkdtemp(join(tmpdir(), `sdk-snapshot-${scenario.name}-`))
  138. const sessionsRoot = join(cwd, '.sessions')
  139. const scenarioDir = join(snapshotsDir, scenario.name)
  140. const launch = resolveExampleLaunch({
  141. srcBin: runtimeBin,
  142. configArgs: [],
  143. tsconfigPath: repoTsconfig,
  144. })
  145. const childFixtures = Array.from(
  146. { length: scenario.children },
  147. (_, index) => join(scenarioDir, `session.${index + 1}.jsonl`),
  148. )
  149. const env: Record<string, string> = {
  150. ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  151. ...Object.fromEntries(Object.entries(launch.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  152. DSH_CORDIS_CONFIG: recording ? liveConfig : replayConfig,
  153. DSH_SESSION_ROOT: sessionsRoot,
  154. DSH_CWD: cwd,
  155. DSH_SNAPSHOT: mode,
  156. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  157. ...recording ? {} : {
  158. DSH_SNAPSHOT_FILE: join(scenarioDir, 'session.jsonl'),
  159. ...childFixtures.length > 0 ? { DSH_SNAPSHOT_CHILD_FILES: childFixtures.join(delimiter) } : {},
  160. },
  161. }
  162. const harness = new DeepSeekHarness({
  163. launch: {
  164. command: launch.command,
  165. args: launch.args,
  166. cwd,
  167. env,
  168. requestTimeoutMs: 110_000,
  169. },
  170. cwd,
  171. provider: 'deepseek',
  172. model: 'deepseek-v4-flash',
  173. })
  174. try {
  175. const notifications: HarnessNotification[] = []
  176. const result = await harness.run(scenario.prompt, {
  177. sessionId: scenario.sessionId,
  178. onNotification: (notification) => { notifications.push(notification) },
  179. })
  180. await harness.close()
  181. const logs = await persistedLogs(sessionsRoot)
  182. return { result, notifications, logs, cwd }
  183. } finally {
  184. await harness.close()
  185. await rm(cwd, { recursive: true, force: true })
  186. }
  187. }
  188. /** Order logs parent-first, children by creation time (fixture layout order). */
  189. function orderLogs(logs: PersistedLog[], scenario: SdkScenario): PersistedLog[] {
  190. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  191. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  192. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  193. expect(parents).toHaveLength(1)
  194. expect(children).toHaveLength(scenario.children)
  195. return [...parents, ...children]
  196. }
  197. function fixtureFiles(scenario: SdkScenario): string[] {
  198. const dir = join(snapshotsDir, scenario.name)
  199. return [
  200. join(dir, 'session.jsonl'),
  201. ...Array.from({ length: scenario.children }, (_, index) => join(dir, `session.${index + 1}.jsonl`)),
  202. ]
  203. }
  204. describe('TypeScript SDK snapshots over the jsonrpc runtime', () => {
  205. for (const scenario of SCENARIOS) {
  206. it(`replays ${scenario.name} through the SDK`, async () => {
  207. const scenarioDir = join(snapshotsDir, scenario.name)
  208. const notificationsExpectedPath = join(scenarioDir, 'notifications.expected.jsonl')
  209. const resultExpectedPath = join(scenarioDir, 'result.expected.json')
  210. const { result, notifications, logs, cwd } = await runScenario(scenario)
  211. const ordered = orderLogs(logs, scenario)
  212. const actualContext = contextOf(ordered, cwd)
  213. if (recording) {
  214. // Fixtures carry tokenized request headers; llm-replay reads only
  215. // assistant output and tool traffic, so scrubbing keeps prompts and
  216. // schemas out of the corpus without affecting replay.
  217. await mkdir(scenarioDir, { recursive: true })
  218. await Promise.all(ordered.map(async (log, index) => {
  219. const file = fixtureFiles(scenario)[index]
  220. if (file === undefined) throw new Error(`no fixture path for persisted log ${index}`)
  221. await writeFile(file, scrubRequestHeaders(log.content))
  222. }))
  223. }
  224. const files = fixtureFiles(scenario)
  225. let expectedContents = await Promise.all(files.map(file => readFile(file, 'utf8')))
  226. if (refreshing) {
  227. const harvested = ordered.map((log): HarvestedLog => ({
  228. id: String(log.header.id),
  229. createdAt: Number(log.header.createdAt),
  230. ...typeof log.header.parentSession === 'string' ? { parentSession: log.header.parentSession } : {},
  231. content: log.content,
  232. }))
  233. const replacements = refreshFixtureReplacements(harvested, expectedContents)
  234. expectedContents = await Promise.all(ordered.map(async (log, index) => {
  235. const existing = expectedContents[index]
  236. const file = files[index]
  237. if (existing === undefined || file === undefined) throw new Error(`no fixture for persisted log ${index}`)
  238. const stable = stabilizeRefreshLog(log.content, existing, replacements, actualContext)
  239. await writeFile(file, stable)
  240. return stable
  241. }))
  242. }
  243. // Persisted transcripts match the committed fixtures.
  244. const expectedContext = contextOfContents(expectedContents)
  245. for (const [index, log] of ordered.entries()) {
  246. const expected = expectedContents[index]
  247. if (expected === undefined) throw new Error(`no fixture for persisted log ${index}`)
  248. expect(scrubRequestHeaders(normalizeSessionLog(log.content, actualContext)))
  249. .toBe(scrubRequestHeaders(normalizeSessionLog(expected, expectedContext)))
  250. }
  251. // The SDK-visible wire stream and turn result match their expected outputs.
  252. const normalizedNotifications = normalizeNotifications(notifications, actualContext)
  253. const normalizedResult = normalizeResult(result, actualContext)
  254. if (recording || refreshing) {
  255. await writeFile(notificationsExpectedPath, normalizedNotifications)
  256. await writeFile(resultExpectedPath, normalizedResult)
  257. }
  258. expect(normalizedNotifications).toBe(await readFile(notificationsExpectedPath, 'utf8'))
  259. expect(normalizedResult).toBe(await readFile(resultExpectedPath, 'utf8'))
  260. // Wire-shape invariants that must hold in every mode.
  261. expect(result.status).toBe('ok')
  262. expect(notifications.at(-1)?.method).toBe('session.finished')
  263. if (scenario.children > 0) {
  264. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  265. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  266. }
  267. })
  268. }
  269. })