sdk.snapshot.ts 12 KB

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