sdk.snapshot.ts 15 KB

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