sdk.snapshot.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 the SDK `RunResult`, the complete notification stream, and the
  6. * 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 { existsSync } from 'node:fs'
  12. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  13. import { tmpdir } from 'node:os'
  14. import { basename, delimiter, join } from 'node:path'
  15. import { fileURLToPath } from 'node:url'
  16. import { describe, expect, it } from 'vitest'
  17. import {
  18. normalizeSessionLog,
  19. normalizeSessionSnapshot,
  20. normalizeStdout,
  21. refreshFixtureReplacements,
  22. scrubRequestHeaders,
  23. scrubSessionSnapshot,
  24. stabilizeFixtureMessageIds,
  25. stabilizeRefreshLog,
  26. tokenizeSessionFixtureCwd,
  27. type HarvestedLog,
  28. type NormalizeContext,
  29. } from '@deepseek-ai/dsh-acp-snapshot'
  30. import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke'
  31. import { DeepSeekHarness, type HarnessNotification, type RunResult } from '@deepseek-ai/dsh-sdk-client'
  32. const testsDir = dirOf(import.meta.url)
  33. const snapshotsDir = join(testsDir, 'snapshots')
  34. const liveConfig = join(testsDir, '..', 'cordis.yml')
  35. const replayConfig = join(testsDir, '..', 'cordis.snapshot.yml')
  36. const minimalLiveConfig = join(testsDir, '..', 'minimal.cordis.yml')
  37. const minimalReplayConfig = join(testsDir, '..', 'minimal.snapshot.cordis.yml')
  38. const sessionUploadLiveConfig = join(testsDir, '..', 'session-upload.cordis.yml')
  39. const sessionUploadReplayConfig = join(testsDir, '..', 'session-upload.snapshot.cordis.yml')
  40. const runtimeBin = fileURLToPath(new URL('../../../packages/examples/jsonrpc-demo/src/bin.ts', import.meta.url))
  41. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  42. const MINIMAL_SYSTEM_PROMPT = 'You are the environment-selected minimal software engineer.'
  43. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  44. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  45. * You don't have access to the internet via this tool.
  46. * You do have access to a mirror of common linux and python packages via apt and pip.
  47. * State is persistent across command calls and discussions with the user.
  48. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  49. * Please avoid commands that may produce a very large amount of output.
  50. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  51. const mode = process.env.DSH_SNAPSHOT ?? 'replay'
  52. const recording = mode === 'record'
  53. const refreshing = mode === 'refresh'
  54. function dirOf(url: string): string {
  55. return fileURLToPath(new URL('.', url))
  56. }
  57. interface SdkScenario {
  58. /** Scenario name; the snapshots/<name> fixture directory. */
  59. name: string
  60. /** The user prompt for the single SDK turn. */
  61. prompt: string
  62. /** Fixed SDK session id, so fixtures and replay binding stay stable. */
  63. sessionId: string
  64. /** How many child sessions the turn persists (subagent scenarios). */
  65. children: number
  66. /** Optional scenario-specific live and replay compositions. */
  67. configs?: { live: string; replay: string }
  68. /** Environment overrides passed to the runtime subprocess. */
  69. environment?: Readonly<Record<string, string>>
  70. /** Cwd-relative files whose final contents are part of the scenario contract. */
  71. expectedFiles?: Readonly<Record<string, string>>
  72. /** Assembled model-facing tool names and required argument keys. */
  73. expectedTools?: Readonly<Record<string, readonly string[]>>
  74. /** Exact assembled system prompt for the root request. */
  75. expectedSystem?: string
  76. /** Exact model-facing descriptions for selected tools. */
  77. expectedToolDescriptions?: Readonly<Record<string, string>>
  78. /** Expected runtime-context state in the real assembled request. */
  79. runtimeContext?: false | { includes: readonly string[]; excludes: readonly string[] }
  80. }
  81. const SCENARIOS: SdkScenario[] = [
  82. {
  83. name: 'text-turn',
  84. prompt: 'Reply with exactly: SDK snapshot OK',
  85. sessionId: 'sdk-snapshot-text',
  86. children: 0,
  87. configs: { live: sessionUploadLiveConfig, replay: sessionUploadReplayConfig },
  88. },
  89. {
  90. name: 'bash-tool',
  91. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  92. sessionId: 'sdk-snapshot-bash',
  93. children: 0,
  94. },
  95. {
  96. name: 'subagent-spawn-in-process',
  97. 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.",
  98. sessionId: 'sdk-snapshot-subagent',
  99. children: 1,
  100. },
  101. {
  102. name: 'persistent-tools',
  103. 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.',
  104. sessionId: 'persistent-tools-snapshot',
  105. children: 0,
  106. configs: { live: minimalLiveConfig, replay: minimalReplayConfig },
  107. environment: { DSH_SYSTEM_PROMPT: MINIMAL_SYSTEM_PROMPT },
  108. expectedFiles: { 'note.txt': 'target:\n\tnew\n' },
  109. expectedTools: { bash: ['command'], str_replace_editor: ['command', 'path'] },
  110. expectedSystem: MINIMAL_SYSTEM_PROMPT,
  111. expectedToolDescriptions: { bash: MINIMAL_BASH_DESCRIPTION },
  112. runtimeContext: false,
  113. },
  114. ]
  115. interface PersistedLog {
  116. readonly path: string
  117. readonly content: string
  118. readonly header: Record<string, unknown>
  119. }
  120. interface MissingFile {
  121. readonly missing: true
  122. }
  123. async function jsonlFiles(dir: string): Promise<string[]> {
  124. const entries = await readdir(dir, { recursive: true })
  125. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  126. }
  127. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  128. const files = await jsonlFiles(sessionsRoot)
  129. return Promise.all(files.map(async (path) => {
  130. const content = await readFile(path, 'utf8')
  131. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  132. return { path, content, header }
  133. }))
  134. }
  135. interface LoggedRequestHeader {
  136. type?: string
  137. data?: { header?: { system?: unknown; tools?: LoggedTool[] } }
  138. }
  139. interface LoggedTool {
  140. readonly name: string
  141. readonly description?: unknown
  142. readonly parameters: { readonly required?: string[] }
  143. }
  144. function assembledTools(log: PersistedLog): LoggedTool[] {
  145. const event = log.content.trimEnd().split('\n')
  146. .map(line => JSON.parse(line) as LoggedRequestHeader)
  147. .find(candidate => candidate.type === 'request/header')
  148. const tools = event?.data?.header?.tools
  149. if (tools === undefined) throw new Error('session log has no request/header tools')
  150. return tools
  151. }
  152. function assembledToolRequirements(log: PersistedLog): Record<string, string[]> {
  153. return Object.fromEntries(assembledTools(log).map(tool => [tool.name, tool.parameters.required ?? []]))
  154. }
  155. function assembledToolDescriptions(log: PersistedLog): Record<string, string> {
  156. return Object.fromEntries(assembledTools(log).map((tool) => {
  157. if (typeof tool.description !== 'string') throw new Error(`tool ${tool.name} has no description`)
  158. return [tool.name, tool.description]
  159. }))
  160. }
  161. function assembledSystem(log: PersistedLog): string {
  162. const event = log.content.trimEnd().split('\n')
  163. .map(line => JSON.parse(line) as LoggedRequestHeader)
  164. .find(candidate => candidate.type === 'request/header')
  165. const system = event?.data?.header?.system
  166. if (typeof system !== 'string') throw new Error('session log has no request/header system')
  167. return system
  168. }
  169. function assembledRuntimeContexts(log: PersistedLog): string[] {
  170. return log.content.trimEnd().split('\n').flatMap((line) => {
  171. const event = JSON.parse(line) as {
  172. type?: string
  173. data?: { source?: { kind?: string; plugin?: string }; content?: Array<{ type?: string; text?: unknown }> }
  174. }
  175. if (event.type !== 'user/message'
  176. || event.data?.source?.kind !== 'plugin'
  177. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  178. return event.data.content?.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []) ?? []
  179. })
  180. }
  181. function contextOf(logs: readonly { content: string; header: Record<string, unknown> }[], cwd: string): NormalizeContext {
  182. return {
  183. sessionIds: logs.flatMap(log => typeof log.header.id === 'string' ? [log.header.id] : []),
  184. cwd,
  185. }
  186. }
  187. function contextOfContents(contents: readonly string[]): NormalizeContext {
  188. const headers = contents.map(content => JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>)
  189. return {
  190. sessionIds: headers.flatMap(header => typeof header.id === 'string' ? [header.id] : []),
  191. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  192. }
  193. }
  194. async function hydrateReplayFixtures(scenario: SdkScenario, cwd: string): Promise<string[]> {
  195. const root = join(cwd, '.replay-fixtures')
  196. await mkdir(root, { recursive: true })
  197. return Promise.all(fixtureFiles(scenario).map(async (source) => {
  198. const destination = join(root, basename(source))
  199. await writeFile(destination, (await readFile(source, 'utf8')).replaceAll('{{cwd}}', cwd))
  200. return destination
  201. }))
  202. }
  203. async function readExpectedFile(path: string): Promise<string | MissingFile> {
  204. try {
  205. return await readFile(path, 'utf8')
  206. } catch (error: unknown) {
  207. if (error instanceof Error && (error as NodeJS.ErrnoException).code === 'ENOENT') return { missing: true }
  208. throw error
  209. }
  210. }
  211. /**
  212. * Normalize the SDK-visible notification stream: embedded `session.event`
  213. * envelopes get the session-log treatment (times zeroed, headers tokenized),
  214. * then every record is scrubbed like a wire frame.
  215. */
  216. function normalizeNotifications(notifications: readonly HarnessNotification[], ctx: NormalizeContext): string {
  217. const events = notifications
  218. .filter(n => n.method === 'session.event')
  219. .map(n => n.params.event as Record<string, unknown>)
  220. const normalizedEvents = events.length === 0
  221. ? []
  222. : scrubRequestHeaders(normalizeSessionLog(
  223. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  224. ctx,
  225. )).trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  226. let eventIndex = 0
  227. const records = notifications.map((notification) => {
  228. if (notification.method !== 'session.event') return { method: notification.method, params: notification.params }
  229. const event = normalizedEvents[eventIndex++]
  230. return { method: notification.method, params: { ...notification.params, event } }
  231. })
  232. return normalizeStdout(`${records.map(record => JSON.stringify(record)).join('\n')}\n`, ctx)
  233. }
  234. /** Normalize the owned-run projection. */
  235. function normalizeResult(result: RunResult, ctx: NormalizeContext): string {
  236. return normalizeStdout(`${JSON.stringify({
  237. sessionId: result.sessionId,
  238. finalResponse: result.finalResponse,
  239. })}\n`, ctx)
  240. }
  241. /** One SDK turn against a fresh runtime subprocess in an isolated cwd. */
  242. async function runScenario(scenario: SdkScenario): Promise<{
  243. result: RunResult
  244. notifications: HarnessNotification[]
  245. logs: PersistedLog[]
  246. observedFiles: Record<string, string | MissingFile>
  247. cwd: string
  248. }> {
  249. const cwd = await mkdtemp(join(tmpdir(), `sdk-snapshot-${scenario.name}-`))
  250. const sessionsRoot = join(cwd, '.sessions')
  251. const replayFixtures = recording ? [] : await hydrateReplayFixtures(scenario, cwd)
  252. const launch = resolveExampleLaunch({
  253. srcBin: runtimeBin,
  254. configArgs: [],
  255. tsconfigPath: repoTsconfig,
  256. })
  257. const [parentFixture, ...childFixtures] = replayFixtures
  258. const env: Record<string, string> = {
  259. ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  260. ...Object.fromEntries(Object.entries(launch.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  261. DSH_CORDIS_CONFIG: recording
  262. ? scenario.configs?.live ?? liveConfig
  263. : scenario.configs?.replay ?? replayConfig,
  264. DSH_SESSION_ROOT: sessionsRoot,
  265. DSH_CWD: cwd,
  266. DSH_SNAPSHOT: mode,
  267. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  268. ...parentFixture === undefined ? {} : {
  269. DSH_SNAPSHOT_FILE: parentFixture,
  270. ...childFixtures.length > 0 ? { DSH_SNAPSHOT_CHILD_FILES: childFixtures.join(delimiter) } : {},
  271. },
  272. ...scenario.environment,
  273. }
  274. const harness = new DeepSeekHarness({
  275. launch: {
  276. command: launch.command,
  277. args: launch.args,
  278. cwd,
  279. env,
  280. requestTimeoutMs: 110_000,
  281. },
  282. cwd,
  283. provider: 'deepseek-official',
  284. model: 'deepseek-v4-flash',
  285. })
  286. try {
  287. const notifications: HarnessNotification[] = []
  288. const result = await harness.run(scenario.prompt.replaceAll('{{cwd}}', cwd), {
  289. sessionId: scenario.sessionId,
  290. onNotification: (notification) => { notifications.push(notification) },
  291. })
  292. await harness.close()
  293. const logs = await persistedLogs(sessionsRoot)
  294. const observedFiles = Object.fromEntries(await Promise.all(
  295. Object.keys(scenario.expectedFiles ?? {}).map(async (path): Promise<[string, string | MissingFile]> => [
  296. path,
  297. await readExpectedFile(join(cwd, path)),
  298. ]),
  299. ))
  300. return { result, notifications, logs, observedFiles, cwd }
  301. } finally {
  302. await harness.close()
  303. await rm(cwd, { recursive: true, force: true })
  304. }
  305. }
  306. /** Order logs parent-first, children by creation time (fixture layout order). */
  307. function orderLogs(logs: PersistedLog[], scenario: SdkScenario): PersistedLog[] {
  308. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  309. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  310. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  311. expect(parents).toHaveLength(1)
  312. expect(children).toHaveLength(scenario.children)
  313. return [...parents, ...children]
  314. }
  315. function fixtureFiles(scenario: SdkScenario): string[] {
  316. const dir = join(snapshotsDir, scenario.name)
  317. return [
  318. join(dir, 'session.jsonl'),
  319. ...Array.from({ length: scenario.children }, (_, index) => join(dir, `session.${index + 1}.jsonl`)),
  320. ]
  321. }
  322. describe('TypeScript SDK snapshots over the jsonrpc runtime', () => {
  323. for (const scenario of SCENARIOS) {
  324. it(`replays ${scenario.name} through the SDK`, async () => {
  325. const scenarioDir = join(snapshotsDir, scenario.name)
  326. const notificationsExpectedPath = join(scenarioDir, 'notifications.expected.jsonl')
  327. const resultExpectedPath = join(scenarioDir, 'result.expected.json')
  328. const { result, notifications, logs, observedFiles, cwd } = await runScenario(scenario)
  329. const ordered = orderLogs(logs, scenario)
  330. const actualContext = contextOf(ordered, cwd)
  331. const files = fixtureFiles(scenario)
  332. if (recording) {
  333. // Fixtures carry tokenized request headers; llm-replay reads only
  334. // assistant output and tool traffic, so scrubbing keeps prompts and
  335. // schemas out of the corpus without affecting replay.
  336. await mkdir(scenarioDir, { recursive: true })
  337. const existing = await Promise.all(files.map(async file => existsSync(file) ? readFile(file, 'utf8') : ''))
  338. const fixtures = stabilizeFixtureMessageIds(
  339. ordered.map(log => scrubSessionSnapshot(tokenizeSessionFixtureCwd(log.content))),
  340. existing,
  341. )
  342. await Promise.all(fixtures.map(async (fixture, index) => {
  343. const file = files[index]
  344. if (file === undefined) throw new Error(`no fixture path for persisted log ${index}`)
  345. await writeFile(file, fixture)
  346. }))
  347. }
  348. let expectedContents = await Promise.all(files.map(file => readFile(file, 'utf8')))
  349. if (refreshing) {
  350. const harvested = ordered.map((log): HarvestedLog => ({
  351. id: String(log.header.id),
  352. createdAt: Number(log.header.createdAt),
  353. ...typeof log.header.parentSession === 'string' ? { parentSession: log.header.parentSession } : {},
  354. content: log.content,
  355. }))
  356. const replacements = refreshFixtureReplacements(harvested, expectedContents)
  357. const refreshed = ordered.map((log, index) => {
  358. const existing = expectedContents[index]
  359. if (existing === undefined) throw new Error(`no fixture for persisted log ${index}`)
  360. return scrubSessionSnapshot(tokenizeSessionFixtureCwd(
  361. stabilizeRefreshLog(log.content, existing, replacements, actualContext),
  362. ))
  363. })
  364. expectedContents = stabilizeFixtureMessageIds(refreshed, expectedContents)
  365. await Promise.all(expectedContents.map(async (stable, index) => {
  366. const file = files[index]
  367. if (file === undefined) throw new Error(`no fixture for persisted log ${index}`)
  368. await writeFile(file, stable)
  369. }))
  370. }
  371. for (const [index, expected] of expectedContents.entries()) {
  372. expect(scrubRequestHeaders(expected), `${scenario.name} session fixture ${index} carries request-header bulk`)
  373. .toBe(expected)
  374. }
  375. // Persisted transcripts match the committed fixtures.
  376. const expectedContext = contextOfContents(expectedContents)
  377. for (const [index, log] of ordered.entries()) {
  378. const expected = expectedContents[index]
  379. if (expected === undefined) throw new Error(`no fixture for persisted log ${index}`)
  380. expect(normalizeSessionSnapshot(log.content, actualContext))
  381. .toBe(normalizeSessionSnapshot(expected, expectedContext))
  382. }
  383. // The SDK-visible wire stream and turn result match their expected outputs.
  384. const normalizedNotifications = normalizeNotifications(notifications, actualContext)
  385. const normalizedResult = normalizeResult(result, actualContext)
  386. if (recording || refreshing) {
  387. await writeFile(notificationsExpectedPath, normalizedNotifications)
  388. await writeFile(resultExpectedPath, normalizedResult)
  389. }
  390. expect(normalizedNotifications).toBe(await readFile(notificationsExpectedPath, 'utf8'))
  391. expect(normalizedResult).toBe(await readFile(resultExpectedPath, 'utf8'))
  392. // Wire-shape invariants that must hold in every mode.
  393. expect(notifications.at(-1)).toMatchObject({
  394. method: 'session.status',
  395. params: { status: 'idle' },
  396. })
  397. expect(observedFiles).toEqual(scenario.expectedFiles ?? {})
  398. if (scenario.expectedTools !== undefined) {
  399. const parent = ordered[0]
  400. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  401. expect(assembledToolRequirements(parent)).toEqual(scenario.expectedTools)
  402. }
  403. if (scenario.expectedSystem !== undefined) {
  404. const parent = ordered[0]
  405. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  406. expect(assembledSystem(parent)).toBe(scenario.expectedSystem)
  407. }
  408. if (scenario.expectedToolDescriptions !== undefined) {
  409. const parent = ordered[0]
  410. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  411. expect(assembledToolDescriptions(parent)).toMatchObject(scenario.expectedToolDescriptions)
  412. }
  413. if (scenario.runtimeContext !== undefined) {
  414. const parent = ordered[0]
  415. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  416. const contexts = assembledRuntimeContexts(parent)
  417. if (scenario.runtimeContext === false) {
  418. expect(contexts).toEqual([])
  419. } else {
  420. expect(contexts).toHaveLength(1)
  421. const context = contexts[0] as string
  422. for (const clause of scenario.runtimeContext.includes) expect(context).toContain(clause)
  423. for (const clause of scenario.runtimeContext.excludes) expect(context).not.toContain(clause)
  424. const system = assembledSystem(parent)
  425. for (const clause of scenario.runtimeContext.includes) expect(system).not.toContain(clause)
  426. }
  427. }
  428. if (scenario.children > 0) {
  429. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  430. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  431. }
  432. })
  433. }
  434. })