harness.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /**
  2. * Shared non-spec fixture that mounts the full in-memory agent/persistence stack and connects the
  3. * ACP bridge to a real SDK client over memory streams. Tests exercise the same protocol path as an
  4. * editor without a subprocess or stdio.
  5. */
  6. import { Context } from 'cordis'
  7. import { CallId, type GenerateOptions, type LlmModelInfo, type LlmProviderInfo, type StreamChunk } from '@deepseek-ai/dsh-llm'
  8. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  9. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  10. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. import CommandService from '@deepseek-ai/dsh-commands'
  12. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  15. import * as FsPolicy from '@deepseek-ai/dsh-fs-policy'
  16. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  17. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  18. import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
  19. import PlanModeService from '@deepseek-ai/dsh-plan-mode'
  20. import {
  21. ClientSideConnection,
  22. ndJsonStream,
  23. type Agent as AcpAgent,
  24. type Client,
  25. type CreateElicitationRequest,
  26. type CreateElicitationResponse,
  27. type RequestPermissionRequest,
  28. type RequestPermissionResponse,
  29. type SessionNotification,
  30. type Stream,
  31. } from '@agentclientprotocol/sdk'
  32. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  33. import SessionQueryService from '@deepseek-ai/dsh-session-query'
  34. import SessionReferenceService from '@deepseek-ai/dsh-session-reference'
  35. import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user'
  36. import * as AcpPlugin from '../src/index.ts'
  37. import { type AcpConfig } from '../src/index.ts'
  38. class TestSessionQueryService extends SessionQueryService {
  39. override searchSessions(
  40. ..._args: Parameters<SessionQueryService['searchSessions']>
  41. ): ReturnType<SessionQueryService['searchSessions']> {
  42. return Promise.resolve({ items: [] })
  43. }
  44. override searchEvents(
  45. ..._args: Parameters<SessionQueryService['searchEvents']>
  46. ): ReturnType<SessionQueryService['searchEvents']> {
  47. return Promise.resolve({ items: [] })
  48. }
  49. }
  50. /** A scripted mock adapter (mirrors the agent-loop test adapter). */
  51. class MockAdapter extends LlmAdapter {
  52. requests: GenerateOptions[] = []
  53. constructor(
  54. private script: (StreamChunk[] | 'hang')[],
  55. private readonly providers: readonly LlmProviderInfo[],
  56. private readonly models: readonly LlmModelInfo[],
  57. ) {
  58. super()
  59. }
  60. override providerInfo(provider: string): LlmProviderInfo {
  61. const info = this.providers.find(entry => entry.id === provider)
  62. if (info === undefined) throw new Error(`MockAdapter: unknown provider ${provider}`)
  63. return info
  64. }
  65. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  66. return Promise.resolve(this.models.filter(model => model.provider === provider))
  67. }
  68. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  69. this.requests.push(options)
  70. const entry = this.script.shift()
  71. if (!entry) throw new Error('MockAdapter: script exhausted')
  72. if (entry === 'hang') {
  73. yield { type: 'block-start', index: 0, blockType: 'text' }
  74. yield { type: 'text-delta', index: 0, text: 'partial' }
  75. await new Promise<void>((_resolve, reject) => {
  76. if (options.signal?.aborted) { reject(new Error('aborted')); return }
  77. options.signal?.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  78. })
  79. return
  80. }
  81. for (const chunk of entry) {
  82. if (options.signal?.aborted) throw new Error('aborted')
  83. yield chunk
  84. }
  85. }
  86. }
  87. /** Scripted text response ending in a clean `stop` finish. */
  88. export function textResponse(text: string): StreamChunk[] {
  89. return [
  90. { type: 'block-start', index: 0, blockType: 'text' },
  91. ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })),
  92. { type: 'block-end', index: 0, block: { type: 'text', text } },
  93. { type: 'usage', usage: { inputTokens: 5, outputTokens: text.length } },
  94. { type: 'finish', reason: { kind: 'stop' } },
  95. ]
  96. }
  97. /** Scripted response ending at the output-token ceiling (max-tokens finish). */
  98. export function maxTokensResponse(text: string): StreamChunk[] {
  99. return [
  100. { type: 'block-start', index: 0, blockType: 'text' },
  101. ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })),
  102. { type: 'block-end', index: 0, block: { type: 'text', text } },
  103. { type: 'finish', reason: { kind: 'max-tokens' } },
  104. ]
  105. }
  106. /** Scripted response that fails mid-turn with a finish-error chunk. */
  107. export function errorResponse(message: string): StreamChunk[] {
  108. return [
  109. { type: 'block-start', index: 0, blockType: 'text' },
  110. { type: 'text-delta', index: 0, text: 'partial' },
  111. { type: 'finish', reason: { kind: 'error', failure: { message, code: 'PROVIDER_ERROR' } } },
  112. ]
  113. }
  114. /** Scripted single tool call (no follow-up step scripted by default). */
  115. export function toolCallResponse(rawCallId: string, name: string, args: object): StreamChunk[] {
  116. const argumentsJson = JSON.stringify(args)
  117. const id = CallId(rawCallId)
  118. return [
  119. { type: 'block-start', index: 0, blockType: 'tool-call' },
  120. { type: 'tool-call-delta', index: 0, id, name, argumentsDelta: argumentsJson },
  121. { type: 'block-end', index: 0, block: { type: 'tool-call', id, name, arguments: argumentsJson } },
  122. { type: 'finish', reason: { kind: 'tool-calls' } },
  123. ]
  124. }
  125. /** A captured `session/update` notification (the update payload only). */
  126. export type CapturedUpdate = SessionNotification['update']
  127. export interface BridgeHarness {
  128. ctx: Context
  129. client: ClientSideConnection
  130. adapter: MockAdapter
  131. /** Every `session/update` the bridge pushed, in order (payload only). */
  132. updates: CapturedUpdate[]
  133. /** Same, but tagged with each update's `sessionId` (for multi-session demux assertions). */
  134. sessionUpdates: { sessionId: string; update: CapturedUpdate }[]
  135. /** Permission requests the bridge issued (none until the gate lands). */
  136. permissionRequests: RequestPermissionRequest[]
  137. /** Decide each permission request's outcome (default: cancelled). */
  138. onPermission: (req: RequestPermissionRequest) => RequestPermissionResponse
  139. /** Elicitation requests the bridge issued for ask_user_question. */
  140. elicitationRequests: CreateElicitationRequest[]
  141. /** Decide each elicitation response (default: cancel). */
  142. onElicitation: (req: CreateElicitationRequest) => CreateElicitationResponse | Promise<CreateElicitationResponse>
  143. /** If set, the client's sessionUpdate throws this (tests notify error path). */
  144. onSessionUpdateError: (() => void) | undefined
  145. /**
  146. * Sever the client→agent transport (close the writable the agent reads),
  147. * which ends the agent-side stream and resolves the bridge's `conn.closed` —
  148. * simulating an editor disconnecting. Returns once the close is requested.
  149. */
  150. closeClientTransport: () => Promise<void>
  151. /**
  152. * The child fiber the ACP bridge is mounted in. Disposing it tears down JUST
  153. * the bridge (its `ctx.on` listeners + effect) while the rest of the harness
  154. * stays up — an ACP-only HMR reload.
  155. */
  156. acpFiber: Awaited<ReturnType<Context['plugin']>>
  157. dispose: () => Promise<void>
  158. storageDir: string
  159. }
  160. /** Test-only overrides preserve explicit undefined to suppress harness defaults. */
  161. type AcpConfigOverrides = { [K in keyof AcpConfig]?: AcpConfig[K] | undefined }
  162. /**
  163. * Build the bridge + a connected client over an in-memory transport pair.
  164. *
  165. * Two identity `TransformStream`s cross-wired (agent writes → client reads,
  166. * client writes → agent reads) give a faithful bidirectional JSON-RPC channel.
  167. * The bridge's `apply` receives the agent-side `Stream` via `config.stream`;
  168. * the test holds the `ClientSideConnection`.
  169. *
  170. * Pass an explicit undefined route field to suppress its mock default.
  171. */
  172. export async function makeBridgeHarness(options: {
  173. script?: (StreamChunk[] | 'hang')[]
  174. config?: AcpConfigOverrides
  175. /** Provider-neutral directory exposed to ACP model-selection tests. */
  176. catalog?: { providers: LlmProviderInfo[]; models: LlmModelInfo[] }
  177. /** Deployment persona for the tree (the system-prompt plugin's config). */
  178. persona?: string
  179. storageDir: string
  180. /**
  181. * Plug the REAL `dsh-bash-local` executor + `dsh-tool-bash` tools (instead of
  182. * a test's own inline tool). Lets a test drive the actual `bash` tool — its
  183. * real `presentCall`/`presentResult` — through the bridge, so tool-call UI
  184. * tests verify the SHIPPING tool, not a stand-in (docs/testing.md "prefer the real
  185. * implementation over a mock in tests").
  186. */
  187. withBash?: boolean
  188. /** Plug the REAL `ask_user_question` tool and ACP user-interaction provider. */
  189. withAskUser?: boolean
  190. /**
  191. * Plug the REAL `dsh-tool-todo` tool so a test can drive `todo_write` through
  192. * the bridge and assert the resulting `plan` sessionUpdate — the shipping
  193. * tool + the bridge's own todo/write→plan mapping, not a stand-in.
  194. */
  195. withTodo?: boolean
  196. /** Mount exact session reads and cross-session snapshot preparation before ACP. */
  197. withSessionReferences?: boolean
  198. /** Plug the REAL `dsh-plan-mode` plugin so a test can drive the session-mode picker. */
  199. withModes?: boolean
  200. /**
  201. * Plug the REAL filesystem stack (`dsh-fs-local` + `dsh-fs-policy` +
  202. * `dsh-tool-fs`) so a test can drive `read`/`write`/`edit` through the bridge
  203. * and assert their tool-owned presentation (title/kind/`locations`) on the
  204. * wire — the shipping tools, not a stand-in. `fsCwd` sets the local backend's
  205. * base directory (default: `storageDir`).
  206. */
  207. withFs?: boolean
  208. fsCwd?: string
  209. } = { storageDir: '' }): Promise<BridgeHarness> {
  210. const catalog = options.catalog ?? {
  211. providers: [{ id: 'mock', name: 'Mock' }],
  212. models: [{ provider: 'mock', id: 'mock', name: 'Mock' }],
  213. }
  214. const adapter = new MockAdapter(options.script ?? [], catalog.providers, catalog.models)
  215. const ctx = new Context()
  216. await mountAgentLoopTestDependencies(ctx, {
  217. systemPrompt: { persona: options.persona ?? '' },
  218. })
  219. await ctx.plugin(CommandService)
  220. await ctx.plugin(AgentLoop, { agents: [] })
  221. await ctx.plugin(SessionPersistenceJsonl, { root: options.storageDir })
  222. await ctx.plugin(TestSessionQueryService)
  223. if (options.withSessionReferences) {
  224. await ctx.plugin(SessionReferenceService)
  225. }
  226. await ctx.plugin(UserInteractionService)
  227. if (options.withAskUser) {
  228. await ctx.plugin(ToolAskUser)
  229. }
  230. if (options.withBash) {
  231. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  232. await ctx.plugin(ToolBash)
  233. }
  234. if (options.withTodo) {
  235. await ctx.plugin(ToolTodo)
  236. }
  237. if (options.withModes) {
  238. await ctx.plugin(PlanModeService, { section: 'Test plan mode instructions.' })
  239. }
  240. if (options.withFs) {
  241. await ctx.plugin(LocalFileSystem, { cwd: options.fsCwd ?? options.storageDir })
  242. await ctx.plugin(FsPolicy)
  243. await ctx.plugin(ToolFs)
  244. }
  245. ctx.llm.registerAdapter(catalog.providers.map(provider => provider.id), adapter)
  246. // Two identity byte pipes cross-wired into the two ndJsonStreams: bytes the agent writes flow
  247. // to the client's reader and vice versa. (ndJsonStream takes (output, input): the agent
  248. // writes to a2c and reads from c2a; the client writes to c2a and reads from a2c.) Holding the c2a
  249. // writer lets tests EOF the agent reader and simulate editor disconnect.
  250. const a2c = new TransformStream<Uint8Array, Uint8Array>()
  251. const c2a = new TransformStream<Uint8Array, Uint8Array>()
  252. const c2aWriter = c2a.writable.getWriter()
  253. // A WritableStream the client writes into; each chunk is forwarded to the
  254. // held c2a writer. `closeClientTransport` closes that writer directly.
  255. const clientOutput = new WritableStream<Uint8Array>({
  256. write: chunk => c2aWriter.write(chunk),
  257. })
  258. const agentStream: Stream = ndJsonStream(a2c.writable, c2a.readable)
  259. const clientStream: Stream = ndJsonStream(clientOutput, a2c.readable)
  260. const updates: CapturedUpdate[] = []
  261. const sessionUpdates: { sessionId: string; update: CapturedUpdate }[] = []
  262. const permissionRequests: RequestPermissionRequest[] = []
  263. const elicitationRequests: CreateElicitationRequest[] = []
  264. const harness: BridgeHarness = {
  265. ctx,
  266. adapter,
  267. updates,
  268. sessionUpdates,
  269. permissionRequests,
  270. onPermission: () => ({ outcome: { outcome: 'cancelled' } }),
  271. elicitationRequests,
  272. onElicitation: () => ({ action: 'cancel' }),
  273. onSessionUpdateError: undefined,
  274. client: undefined as unknown as ClientSideConnection,
  275. acpFiber: undefined as unknown as BridgeHarness['acpFiber'],
  276. // Close the writable the CLIENT writes to (c2a) — its readable, which the agent's
  277. // ndJsonStream consumes, then EOFs cleanly, so the bridge's `conn.closed` resolves and it
  278. // sees the client disconnect.
  279. closeClientTransport: async () => { await c2aWriter.close() },
  280. dispose: async () => { await ctx.fiber.dispose() },
  281. storageDir: options.storageDir,
  282. }
  283. const makeClient = (_agent: AcpAgent): Client => ({
  284. sessionUpdate(params: SessionNotification): Promise<void> {
  285. updates.push(params.update)
  286. sessionUpdates.push({ sessionId: params.sessionId, update: params.update })
  287. // Let a test force the bridge's notify() error path.
  288. if (harness.onSessionUpdateError) return Promise.reject(new Error('client update rejected'))
  289. return Promise.resolve()
  290. },
  291. requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
  292. permissionRequests.push(params)
  293. return Promise.resolve(harness.onPermission(params))
  294. },
  295. unstable_createElicitation(params: CreateElicitationRequest): Promise<CreateElicitationResponse> {
  296. elicitationRequests.push(params)
  297. return Promise.resolve(harness.onElicitation(params))
  298. },
  299. })
  300. // Default route fields only when the caller omitted them; explicit undefined values must survive.
  301. const cfg = { stream: agentStream, ...options.config } as AcpConfig
  302. if (!(options.config && 'provider' in options.config)) cfg.provider = 'mock'
  303. if (!(options.config && 'model' in options.config)) cfg.model = 'mock'
  304. // Mount the bridge the way production does: as a cordis plugin (via `ctx.plugin` with the
  305. // real `inject`), not `AcpPlugin.apply(ctx, cfg)` on the ungated root. Later JSON-RPC callbacks run
  306. // outside apply's injection scope, matching production and exposing missing-inject failures.
  307. harness.acpFiber = await ctx.plugin({
  308. name: 'acp-test',
  309. // Use the bridge's real exported `inject` so this never drifts from the plugin's actual
  310. // dependency list (adding a service to the bridge must not require editing the harness — a
  311. // hardcoded list silently broke when `tools` was added). The returned fiber permits ACP-only
  312. // disposal while root services remain live for HMR assertions.
  313. inject: [...AcpPlugin.inject],
  314. apply: (inner: Context) => { AcpPlugin.apply(inner, cfg) },
  315. })
  316. harness.client = new ClientSideConnection(makeClient, clientStream)
  317. return harness
  318. }