sdk.snapshot.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 `RunResult`, 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 RunResult } 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. /** Stable policy-context clauses the real assembled request must include or omit. */
  58. policyContext?: { includes: readonly string[]; excludes: readonly string[] }
  59. }
  60. const SCENARIOS: SdkScenario[] = [
  61. {
  62. name: 'text-turn',
  63. prompt: 'Reply with exactly: SDK snapshot OK',
  64. sessionId: 'sdk-snapshot-text',
  65. children: 0,
  66. },
  67. {
  68. name: 'bash-tool',
  69. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  70. sessionId: 'sdk-snapshot-bash',
  71. children: 0,
  72. },
  73. {
  74. name: 'subagent-spawn',
  75. 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.",
  76. sessionId: 'sdk-snapshot-subagent',
  77. children: 1,
  78. },
  79. {
  80. name: 'persistent-tools',
  81. 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.',
  82. sessionId: 'persistent-tools-snapshot',
  83. children: 0,
  84. configs: { live: persistentToolsLiveConfig, replay: persistentToolsReplayConfig },
  85. expectedFiles: { 'note.txt': 'target:\n\tnew\n' },
  86. expectedTools: { bash: ['command'], str_replace_editor: ['command', 'path'] },
  87. policyContext: {
  88. includes: ['Current DSH file policy: danger-full-access.', 'file modifications by available operations'],
  89. excludes: ['write and edit tools', 'terminal sessions', 'one-shot bash commands'],
  90. },
  91. },
  92. ]
  93. interface PersistedLog {
  94. readonly path: string
  95. readonly content: string
  96. readonly header: Record<string, unknown>
  97. }
  98. interface MissingFile {
  99. readonly missing: true
  100. }
  101. async function jsonlFiles(dir: string): Promise<string[]> {
  102. const entries = await readdir(dir, { recursive: true })
  103. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  104. }
  105. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  106. const files = await jsonlFiles(sessionsRoot)
  107. return Promise.all(files.map(async (path) => {
  108. const content = await readFile(path, 'utf8')
  109. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  110. return { path, content, header }
  111. }))
  112. }
  113. interface LoggedRequestHeader {
  114. type?: string
  115. data?: { header?: { system?: unknown; tools?: Array<{ name: string; parameters: { required?: string[] } }> } }
  116. }
  117. function assembledToolRequirements(log: PersistedLog): Record<string, string[]> {
  118. const event = log.content.trimEnd().split('\n')
  119. .map(line => JSON.parse(line) as LoggedRequestHeader)
  120. .find(candidate => candidate.type === 'request/header')
  121. const tools = event?.data?.header?.tools
  122. if (tools === undefined) throw new Error('session log has no request/header tools')
  123. return Object.fromEntries(tools.map(tool => [tool.name, tool.parameters.required ?? []]))
  124. }
  125. function assembledSystem(log: PersistedLog): string {
  126. const event = log.content.trimEnd().split('\n')
  127. .map(line => JSON.parse(line) as LoggedRequestHeader)
  128. .find(candidate => candidate.type === 'request/header')
  129. const system = event?.data?.header?.system
  130. if (typeof system !== 'string') throw new Error('session log has no request/header system')
  131. return system
  132. }
  133. function assembledPolicyContext(log: PersistedLog): string {
  134. const contexts = log.content.trimEnd().split('\n').flatMap((line) => {
  135. const event = JSON.parse(line) as {
  136. type?: string
  137. data?: { source?: { kind?: string; plugin?: string }; content?: Array<{ type?: string; text?: unknown }> }
  138. }
  139. if (event.type !== 'user/message'
  140. || event.data?.source?.kind !== 'plugin'
  141. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  142. return event.data.content?.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []) ?? []
  143. })
  144. if (contexts.length !== 1) throw new Error(`session log has ${String(contexts.length)} runtime-context snapshots; expected one`)
  145. return contexts[0] as string
  146. }
  147. function contextOf(logs: readonly { content: string; header: Record<string, unknown> }[], cwd: string): NormalizeContext {
  148. return {
  149. sessionIds: logs.flatMap(log => typeof log.header.id === 'string' ? [log.header.id] : []),
  150. cwd,
  151. }
  152. }
  153. function contextOfContents(contents: readonly string[]): NormalizeContext {
  154. const headers = contents.map(content => JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>)
  155. return {
  156. sessionIds: headers.flatMap(header => typeof header.id === 'string' ? [header.id] : []),
  157. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  158. }
  159. }
  160. async function hydrateReplayFixtures(scenario: SdkScenario, cwd: string): Promise<string[]> {
  161. const root = join(cwd, '.replay-fixtures')
  162. await mkdir(root, { recursive: true })
  163. return Promise.all(fixtureFiles(scenario).map(async (source) => {
  164. const destination = join(root, basename(source))
  165. await writeFile(destination, (await readFile(source, 'utf8')).replaceAll('{{cwd}}', cwd))
  166. return destination
  167. }))
  168. }
  169. async function readExpectedFile(path: string): Promise<string | MissingFile> {
  170. try {
  171. return await readFile(path, 'utf8')
  172. } catch (error: unknown) {
  173. if (error instanceof Error && (error as NodeJS.ErrnoException).code === 'ENOENT') return { missing: true }
  174. throw error
  175. }
  176. }
  177. /**
  178. * Normalize the SDK-visible notification stream: embedded `session.event`
  179. * envelopes get the session-log treatment (times zeroed, headers tokenized),
  180. * then every record is scrubbed like a wire frame.
  181. */
  182. function normalizeNotifications(notifications: readonly HarnessNotification[], ctx: NormalizeContext): string {
  183. const events = notifications
  184. .filter(n => n.method === 'session.event')
  185. .map(n => n.params.event as Record<string, unknown>)
  186. const normalizedEvents = events.length === 0
  187. ? []
  188. : scrubRequestHeaders(normalizeSessionLog(
  189. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  190. ctx,
  191. )).trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  192. let eventIndex = 0
  193. const records = notifications.map((notification) => {
  194. if (notification.method !== 'session.event') return { method: notification.method, params: notification.params }
  195. const event = normalizedEvents[eventIndex++]
  196. return { method: notification.method, params: { ...notification.params, event } }
  197. })
  198. return normalizeStdout(`${records.map(record => JSON.stringify(record)).join('\n')}\n`, ctx)
  199. }
  200. /** Normalize the owned-run projection. */
  201. function normalizeResult(result: RunResult, ctx: NormalizeContext): string {
  202. return normalizeStdout(`${JSON.stringify({
  203. sessionId: result.sessionId,
  204. finalResponse: result.finalResponse,
  205. })}\n`, ctx)
  206. }
  207. /** One SDK turn against a fresh runtime subprocess in an isolated cwd. */
  208. async function runScenario(scenario: SdkScenario): Promise<{
  209. result: RunResult
  210. notifications: HarnessNotification[]
  211. logs: PersistedLog[]
  212. observedFiles: Record<string, string | MissingFile>
  213. cwd: string
  214. }> {
  215. const cwd = await mkdtemp(join(tmpdir(), `sdk-snapshot-${scenario.name}-`))
  216. const sessionsRoot = join(cwd, '.sessions')
  217. const replayFixtures = recording ? [] : await hydrateReplayFixtures(scenario, cwd)
  218. const launch = resolveExampleLaunch({
  219. srcBin: runtimeBin,
  220. configArgs: [],
  221. tsconfigPath: repoTsconfig,
  222. })
  223. const [parentFixture, ...childFixtures] = replayFixtures
  224. const env: Record<string, string> = {
  225. ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  226. ...Object.fromEntries(Object.entries(launch.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  227. DSH_CORDIS_CONFIG: recording
  228. ? scenario.configs?.live ?? liveConfig
  229. : scenario.configs?.replay ?? replayConfig,
  230. DSH_SESSION_ROOT: sessionsRoot,
  231. DSH_CWD: cwd,
  232. DSH_SNAPSHOT: mode,
  233. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  234. ...parentFixture === undefined ? {} : {
  235. DSH_SNAPSHOT_FILE: parentFixture,
  236. ...childFixtures.length > 0 ? { DSH_SNAPSHOT_CHILD_FILES: childFixtures.join(delimiter) } : {},
  237. },
  238. }
  239. const harness = new DeepSeekHarness({
  240. launch: {
  241. command: launch.command,
  242. args: launch.args,
  243. cwd,
  244. env,
  245. requestTimeoutMs: 110_000,
  246. },
  247. cwd,
  248. provider: 'deepseek-official',
  249. model: 'deepseek-v4-flash',
  250. })
  251. try {
  252. const notifications: HarnessNotification[] = []
  253. const result = await harness.run(scenario.prompt.replaceAll('{{cwd}}', cwd), {
  254. sessionId: scenario.sessionId,
  255. onNotification: (notification) => { notifications.push(notification) },
  256. })
  257. await harness.close()
  258. const logs = await persistedLogs(sessionsRoot)
  259. const observedFiles = Object.fromEntries(await Promise.all(
  260. Object.keys(scenario.expectedFiles ?? {}).map(async (path): Promise<[string, string | MissingFile]> => [
  261. path,
  262. await readExpectedFile(join(cwd, path)),
  263. ]),
  264. ))
  265. return { result, notifications, logs, observedFiles, cwd }
  266. } finally {
  267. await harness.close()
  268. await rm(cwd, { recursive: true, force: true })
  269. }
  270. }
  271. /** Order logs parent-first, children by creation time (fixture layout order). */
  272. function orderLogs(logs: PersistedLog[], scenario: SdkScenario): PersistedLog[] {
  273. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  274. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  275. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  276. expect(parents).toHaveLength(1)
  277. expect(children).toHaveLength(scenario.children)
  278. return [...parents, ...children]
  279. }
  280. function fixtureFiles(scenario: SdkScenario): string[] {
  281. const dir = join(snapshotsDir, scenario.name)
  282. return [
  283. join(dir, 'session.jsonl'),
  284. ...Array.from({ length: scenario.children }, (_, index) => join(dir, `session.${index + 1}.jsonl`)),
  285. ]
  286. }
  287. describe('TypeScript SDK snapshots over the jsonrpc runtime', () => {
  288. for (const scenario of SCENARIOS) {
  289. it(`replays ${scenario.name} through the SDK`, async () => {
  290. const scenarioDir = join(snapshotsDir, scenario.name)
  291. const notificationsExpectedPath = join(scenarioDir, 'notifications.expected.jsonl')
  292. const resultExpectedPath = join(scenarioDir, 'result.expected.json')
  293. const { result, notifications, logs, observedFiles, cwd } = await runScenario(scenario)
  294. const ordered = orderLogs(logs, scenario)
  295. const actualContext = contextOf(ordered, cwd)
  296. if (recording) {
  297. // Fixtures carry tokenized request headers; llm-replay reads only
  298. // assistant output and tool traffic, so scrubbing keeps prompts and
  299. // schemas out of the corpus without affecting replay.
  300. await mkdir(scenarioDir, { recursive: true })
  301. await Promise.all(ordered.map(async (log, index) => {
  302. const file = fixtureFiles(scenario)[index]
  303. if (file === undefined) throw new Error(`no fixture path for persisted log ${index}`)
  304. await writeFile(file, scrubRequestHeaders(tokenizeSessionFixtureCwd(log.content)))
  305. }))
  306. }
  307. const files = fixtureFiles(scenario)
  308. let expectedContents = await Promise.all(files.map(file => readFile(file, 'utf8')))
  309. if (refreshing) {
  310. const harvested = ordered.map((log): HarvestedLog => ({
  311. id: String(log.header.id),
  312. createdAt: Number(log.header.createdAt),
  313. ...typeof log.header.parentSession === 'string' ? { parentSession: log.header.parentSession } : {},
  314. content: log.content,
  315. }))
  316. const replacements = refreshFixtureReplacements(harvested, expectedContents)
  317. expectedContents = await Promise.all(ordered.map(async (log, index) => {
  318. const existing = expectedContents[index]
  319. const file = files[index]
  320. if (existing === undefined || file === undefined) throw new Error(`no fixture for persisted log ${index}`)
  321. const stable = scrubRequestHeaders(tokenizeSessionFixtureCwd(
  322. stabilizeRefreshLog(log.content, existing, replacements, actualContext),
  323. ))
  324. await writeFile(file, stable)
  325. return stable
  326. }))
  327. }
  328. for (const [index, expected] of expectedContents.entries()) {
  329. expect(scrubRequestHeaders(expected), `${scenario.name} session fixture ${index} carries request-header bulk`)
  330. .toBe(expected)
  331. }
  332. // Persisted transcripts match the committed fixtures.
  333. const expectedContext = contextOfContents(expectedContents)
  334. for (const [index, log] of ordered.entries()) {
  335. const expected = expectedContents[index]
  336. if (expected === undefined) throw new Error(`no fixture for persisted log ${index}`)
  337. expect(scrubRequestHeaders(normalizeSessionLog(log.content, actualContext)))
  338. .toBe(scrubRequestHeaders(normalizeSessionLog(expected, expectedContext)))
  339. }
  340. // The SDK-visible wire stream and turn result match their expected outputs.
  341. const normalizedNotifications = normalizeNotifications(notifications, actualContext)
  342. const normalizedResult = normalizeResult(result, actualContext)
  343. if (recording || refreshing) {
  344. await writeFile(notificationsExpectedPath, normalizedNotifications)
  345. await writeFile(resultExpectedPath, normalizedResult)
  346. }
  347. expect(normalizedNotifications).toBe(await readFile(notificationsExpectedPath, 'utf8'))
  348. expect(normalizedResult).toBe(await readFile(resultExpectedPath, 'utf8'))
  349. // Wire-shape invariants that must hold in every mode.
  350. expect(notifications.at(-1)).toMatchObject({
  351. method: 'session.status',
  352. params: { status: 'idle' },
  353. })
  354. expect(observedFiles).toEqual(scenario.expectedFiles ?? {})
  355. if (scenario.expectedTools !== undefined) {
  356. const parent = ordered[0]
  357. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  358. expect(assembledToolRequirements(parent)).toEqual(scenario.expectedTools)
  359. }
  360. if (scenario.policyContext !== undefined) {
  361. const parent = ordered[0]
  362. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  363. const context = assembledPolicyContext(parent)
  364. for (const clause of scenario.policyContext.includes) expect(context).toContain(clause)
  365. for (const clause of scenario.policyContext.excludes) expect(context).not.toContain(clause)
  366. const system = assembledSystem(parent)
  367. for (const clause of scenario.policyContext.includes) expect(system).not.toContain(clause)
  368. }
  369. if (scenario.children > 0) {
  370. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  371. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  372. }
  373. })
  374. }
  375. })