sdk.snapshot.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. normalizeStdout,
  20. refreshFixtureReplacements,
  21. scrubRequestHeaders,
  22. stabilizeFixtureMessageIds,
  23. stabilizeRefreshLog,
  24. tokenizeSessionFixtureCwd,
  25. type HarvestedLog,
  26. type NormalizeContext,
  27. } from '@deepseek-ai/dsh-acp-snapshot'
  28. import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke'
  29. import { DeepSeekHarness, type HarnessNotification, type RunResult } from '@deepseek-ai/dsh-sdk-client'
  30. const testsDir = dirOf(import.meta.url)
  31. const snapshotsDir = join(testsDir, 'snapshots')
  32. const liveConfig = join(testsDir, '..', 'cordis.yml')
  33. const replayConfig = join(testsDir, '..', 'cordis.snapshot.yml')
  34. const minimalLiveConfig = join(testsDir, '..', 'minimal.cordis.yml')
  35. const minimalReplayConfig = join(testsDir, '..', 'minimal.snapshot.cordis.yml')
  36. const runtimeBin = fileURLToPath(new URL('../../../packages/examples/jsonrpc-demo/src/bin.ts', import.meta.url))
  37. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  38. const MINIMAL_SYSTEM_PROMPT = 'You are the environment-selected minimal software engineer.'
  39. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  40. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  41. * You don't have access to the internet via this tool.
  42. * You do have access to a mirror of common linux and python packages via apt and pip.
  43. * State is persistent across command calls and discussions with the user.
  44. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  45. * Please avoid commands that may produce a very large amount of output.
  46. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  47. const mode = process.env.DSH_SNAPSHOT ?? 'replay'
  48. const recording = mode === 'record'
  49. const refreshing = mode === 'refresh'
  50. function dirOf(url: string): string {
  51. return fileURLToPath(new URL('.', url))
  52. }
  53. interface SdkScenario {
  54. /** Scenario name; the snapshots/<name> fixture directory. */
  55. name: string
  56. /** The user prompt for the single SDK turn. */
  57. prompt: string
  58. /** Fixed SDK session id, so fixtures and replay binding stay stable. */
  59. sessionId: string
  60. /** How many child sessions the turn persists (subagent scenarios). */
  61. children: number
  62. /** Optional scenario-specific live and replay compositions. */
  63. configs?: { live: string; replay: string }
  64. /** Environment overrides passed to the runtime subprocess. */
  65. environment?: Readonly<Record<string, string>>
  66. /** Cwd-relative files whose final contents are part of the scenario contract. */
  67. expectedFiles?: Readonly<Record<string, string>>
  68. /** Assembled model-facing tool names and required argument keys. */
  69. expectedTools?: Readonly<Record<string, readonly string[]>>
  70. /** Exact assembled system prompt for the root request. */
  71. expectedSystem?: string
  72. /** Exact model-facing descriptions for selected tools. */
  73. expectedToolDescriptions?: Readonly<Record<string, string>>
  74. /** Stable policy-context clauses the real assembled request must include or omit. */
  75. policyContext?: { includes: readonly string[]; excludes: readonly string[] }
  76. }
  77. const SCENARIOS: SdkScenario[] = [
  78. {
  79. name: 'text-turn',
  80. prompt: 'Reply with exactly: SDK snapshot OK',
  81. sessionId: 'sdk-snapshot-text',
  82. children: 0,
  83. },
  84. {
  85. name: 'bash-tool',
  86. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  87. sessionId: 'sdk-snapshot-bash',
  88. children: 0,
  89. },
  90. {
  91. name: 'subagent-spawn',
  92. 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.",
  93. sessionId: 'sdk-snapshot-subagent',
  94. children: 1,
  95. },
  96. {
  97. name: 'persistent-tools',
  98. 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.',
  99. sessionId: 'persistent-tools-snapshot',
  100. children: 0,
  101. configs: { live: minimalLiveConfig, replay: minimalReplayConfig },
  102. environment: { DSH_SYSTEM_PROMPT: MINIMAL_SYSTEM_PROMPT },
  103. expectedFiles: { 'note.txt': 'target:\n\tnew\n' },
  104. expectedTools: { bash: ['command'], str_replace_editor: ['command', 'path'] },
  105. expectedSystem: MINIMAL_SYSTEM_PROMPT,
  106. expectedToolDescriptions: { bash: MINIMAL_BASH_DESCRIPTION },
  107. policyContext: {
  108. includes: ['Current DSH file policy: danger-full-access.', 'file modifications by available operations'],
  109. excludes: ['write and edit tools', 'terminal sessions', 'one-shot bash commands'],
  110. },
  111. },
  112. ]
  113. interface PersistedLog {
  114. readonly path: string
  115. readonly content: string
  116. readonly header: Record<string, unknown>
  117. }
  118. interface MissingFile {
  119. readonly missing: true
  120. }
  121. async function jsonlFiles(dir: string): Promise<string[]> {
  122. const entries = await readdir(dir, { recursive: true })
  123. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  124. }
  125. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  126. const files = await jsonlFiles(sessionsRoot)
  127. return Promise.all(files.map(async (path) => {
  128. const content = await readFile(path, 'utf8')
  129. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  130. return { path, content, header }
  131. }))
  132. }
  133. interface LoggedRequestHeader {
  134. type?: string
  135. data?: { header?: { system?: unknown; tools?: LoggedTool[] } }
  136. }
  137. interface LoggedTool {
  138. readonly name: string
  139. readonly description?: unknown
  140. readonly parameters: { readonly required?: string[] }
  141. }
  142. function assembledTools(log: PersistedLog): LoggedTool[] {
  143. const event = log.content.trimEnd().split('\n')
  144. .map(line => JSON.parse(line) as LoggedRequestHeader)
  145. .find(candidate => candidate.type === 'request/header')
  146. const tools = event?.data?.header?.tools
  147. if (tools === undefined) throw new Error('session log has no request/header tools')
  148. return tools
  149. }
  150. function assembledToolRequirements(log: PersistedLog): Record<string, string[]> {
  151. return Object.fromEntries(assembledTools(log).map(tool => [tool.name, tool.parameters.required ?? []]))
  152. }
  153. function assembledToolDescriptions(log: PersistedLog): Record<string, string> {
  154. return Object.fromEntries(assembledTools(log).map((tool) => {
  155. if (typeof tool.description !== 'string') throw new Error(`tool ${tool.name} has no description`)
  156. return [tool.name, tool.description]
  157. }))
  158. }
  159. function assembledSystem(log: PersistedLog): string {
  160. const event = log.content.trimEnd().split('\n')
  161. .map(line => JSON.parse(line) as LoggedRequestHeader)
  162. .find(candidate => candidate.type === 'request/header')
  163. const system = event?.data?.header?.system
  164. if (typeof system !== 'string') throw new Error('session log has no request/header system')
  165. return system
  166. }
  167. function assembledPolicyContext(log: PersistedLog): string {
  168. const contexts = log.content.trimEnd().split('\n').flatMap((line) => {
  169. const event = JSON.parse(line) as {
  170. type?: string
  171. data?: { source?: { kind?: string; plugin?: string }; content?: Array<{ type?: string; text?: unknown }> }
  172. }
  173. if (event.type !== 'user/message'
  174. || event.data?.source?.kind !== 'plugin'
  175. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  176. return event.data.content?.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []) ?? []
  177. })
  178. if (contexts.length !== 1) throw new Error(`session log has ${String(contexts.length)} runtime-context snapshots; expected one`)
  179. return contexts[0] as string
  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 => scrubRequestHeaders(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 scrubRequestHeaders(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(scrubRequestHeaders(normalizeSessionLog(log.content, actualContext)))
  381. .toBe(scrubRequestHeaders(normalizeSessionLog(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.policyContext !== undefined) {
  414. const parent = ordered[0]
  415. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  416. const context = assembledPolicyContext(parent)
  417. for (const clause of scenario.policyContext.includes) expect(context).toContain(clause)
  418. for (const clause of scenario.policyContext.excludes) expect(context).not.toContain(clause)
  419. const system = assembledSystem(parent)
  420. for (const clause of scenario.policyContext.includes) expect(system).not.toContain(clause)
  421. }
  422. if (scenario.children > 0) {
  423. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  424. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  425. }
  426. })
  427. }
  428. })