subagent-claude-code.spec.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. import { PassThrough } from 'node:stream'
  2. import type {
  3. Options,
  4. Query,
  5. SDKMessage,
  6. SDKResultMessage,
  7. SpawnOptions,
  8. } from '@anthropic-ai/claude-agent-sdk'
  9. import { Context } from 'cordis'
  10. import Loader from '@cordisjs/plugin-loader'
  11. import {
  12. afterEach,
  13. beforeEach,
  14. describe,
  15. expect,
  16. it,
  17. type Mock,
  18. vi,
  19. } from 'vitest'
  20. import type { Agent } from '@deepseek-ai/dsh-agent'
  21. import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  22. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  23. import SubagentService from '@deepseek-ai/dsh-subagent'
  24. import type {
  25. SubprocessHandle,
  26. SubprocessOutcome,
  27. SubprocessSpawnSpec,
  28. } from '@deepseek-ai/dsh-subprocess'
  29. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  30. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  31. import * as claudeCode from '../src/index.ts'
  32. import * as invariant from '../src/invariant.ts'
  33. import {
  34. claudeSpawnSpec,
  35. ManagedClaudeCodeProcess,
  36. sdkEnvironmentOverlay,
  37. } from '../src/process.ts'
  38. import {
  39. claudeQueryOptions,
  40. consumeClaudeQuery,
  41. disposeClaudeCodeChild,
  42. startClaudeCodeRun,
  43. successfulResult,
  44. textTask,
  45. type ClaudeCodeRunSpec,
  46. } from '../src/run.ts'
  47. type QueryFactory = (params: {
  48. prompt: string
  49. options: Options
  50. }) => Query
  51. const queryMock = vi.hoisted(() => vi.fn<QueryFactory>())
  52. vi.mock('@anthropic-ai/claude-agent-sdk', async importOriginal => ({
  53. ...await importOriginal<typeof import('@anthropic-ai/claude-agent-sdk')>(),
  54. query: queryMock,
  55. }))
  56. const fakeParent = {
  57. id: 'parent',
  58. session: { header: { cwd: process.cwd() } },
  59. } as unknown as Agent
  60. function request(
  61. prompt: ContentBlock[] = [{ type: 'text', text: 'do the task' }],
  62. signal = new AbortController().signal,
  63. ) {
  64. return { prompt, parent: fakeParent, signal }
  65. }
  66. async function nextTask(): Promise<void> {
  67. await new Promise<void>((resolve) => { setImmediate(resolve) })
  68. }
  69. interface FakeChildOptions {
  70. readonly pid?: number
  71. readonly exitOnTerminate?: boolean
  72. readonly waitForExitError?: Error
  73. readonly doneError?: Error
  74. }
  75. interface FakeChild {
  76. readonly handle: SubprocessHandle
  77. readonly stdin: PassThrough
  78. readonly stdout: PassThrough
  79. readonly settle: (outcome?: SubprocessOutcome) => void
  80. readonly fail: (error: Error) => void
  81. readonly terminate: Mock<SubprocessHandle['terminate']>
  82. readonly waitForExit: Mock<SubprocessHandle['waitForExit']>
  83. }
  84. function fakeChild(options: FakeChildOptions = {}): FakeChild {
  85. const stdin = new PassThrough()
  86. const stdout = new PassThrough()
  87. let exited = false
  88. let resolveDone!: (outcome: SubprocessOutcome) => void
  89. let rejectDone!: (error: Error) => void
  90. const done = new Promise<SubprocessOutcome>((resolve, reject) => {
  91. resolveDone = resolve
  92. rejectDone = reject
  93. })
  94. // Individual tests deliberately exercise rejected and still-pending handles.
  95. void done.catch(() => {})
  96. const settle = (
  97. outcome: SubprocessOutcome = { exitCode: 0, signal: null },
  98. ): void => {
  99. if (exited) return
  100. exited = true
  101. resolveDone(outcome)
  102. }
  103. const fail = (error: Error): void => {
  104. if (exited) return
  105. exited = true
  106. rejectDone(error)
  107. }
  108. if (options.doneError !== undefined) fail(options.doneError)
  109. const terminate = vi.fn<SubprocessHandle['terminate']>(() => {
  110. if (options.exitOnTerminate !== false) settle()
  111. })
  112. const waitForExit = vi.fn<SubprocessHandle['waitForExit']>(async (signal?: AbortSignal): Promise<boolean> => {
  113. if (options.waitForExitError !== undefined) {
  114. throw options.waitForExitError
  115. }
  116. if (exited) return true
  117. if (signal === undefined) {
  118. await done.catch(() => {})
  119. return true
  120. }
  121. return await new Promise<boolean>((resolve) => {
  122. const onAbort = (): void => { resolve(false) }
  123. signal.addEventListener('abort', onAbort, { once: true })
  124. void done.then(
  125. () => {
  126. signal.removeEventListener('abort', onAbort)
  127. resolve(true)
  128. },
  129. () => {
  130. signal.removeEventListener('abort', onAbort)
  131. resolve(true)
  132. },
  133. )
  134. })
  135. })
  136. const handle: SubprocessHandle = {
  137. pid: options.pid ?? 1234,
  138. stdin,
  139. stdout,
  140. stderr: undefined,
  141. collected: {},
  142. done,
  143. terminate,
  144. waitForExit,
  145. }
  146. return {
  147. handle,
  148. stdin,
  149. stdout,
  150. settle,
  151. fail,
  152. terminate,
  153. waitForExit,
  154. }
  155. }
  156. function success(
  157. result = 'answer',
  158. isError = false,
  159. ): SDKResultMessage {
  160. return {
  161. type: 'result',
  162. subtype: 'success',
  163. is_error: isError,
  164. result,
  165. } as SDKResultMessage
  166. }
  167. type ErrorSubtype = Exclude<SDKResultMessage['subtype'], 'success'>
  168. function failure(
  169. subtype: ErrorSubtype,
  170. errors: string[] = ['fixture failure'],
  171. ): SDKResultMessage {
  172. return {
  173. type: 'result',
  174. subtype,
  175. is_error: true,
  176. errors,
  177. } as SDKResultMessage
  178. }
  179. function queryFrom(
  180. messages: readonly SDKMessage[],
  181. after?: Error,
  182. close = vi.fn(),
  183. ): Query {
  184. async function* stream(): AsyncGenerator<SDKMessage, void> {
  185. for (const message of messages) yield message
  186. if (after !== undefined) throw after
  187. }
  188. return Object.assign(stream(), { close }) as unknown as Query
  189. }
  190. function waitingQuery(signal: AbortSignal, close = vi.fn()): Query {
  191. async function* stream(): AsyncGenerator<SDKMessage, void> {
  192. await new Promise<never>((_resolve, reject) => {
  193. const fail = (): void => {
  194. reject(signal.reason instanceof Error
  195. ? signal.reason
  196. : new Error(String(signal.reason)))
  197. }
  198. if (signal.aborted) fail()
  199. else signal.addEventListener('abort', fail, { once: true })
  200. })
  201. }
  202. return Object.assign(stream(), { close }) as unknown as Query
  203. }
  204. function sdkSpawnOptions(
  205. overrides: Partial<SpawnOptions> = {},
  206. ): SpawnOptions {
  207. return {
  208. command: '/sdk/claude',
  209. args: ['--output-format', 'stream-json'],
  210. cwd: '/workspace',
  211. env: { PATH: '/bin', OMITTED: undefined },
  212. signal: new AbortController().signal,
  213. ...overrides,
  214. }
  215. }
  216. interface FakeRun {
  217. readonly child: FakeChild
  218. readonly close: ReturnType<typeof vi.fn>
  219. readonly spawnSpecs: SubprocessSpawnSpec[]
  220. readonly options: Options[]
  221. readonly spec: ClaudeCodeRunSpec
  222. }
  223. function fakeRun(
  224. messages: readonly SDKMessage[] = [success()],
  225. after?: Error,
  226. child = fakeChild(),
  227. ): FakeRun {
  228. const close = vi.fn()
  229. const query = queryFrom(messages, after, close)
  230. const spawnSpecs: SubprocessSpawnSpec[] = []
  231. const options: FakeRun['options'] = []
  232. const spec: ClaudeCodeRunSpec = {
  233. cwd: '/workspace',
  234. env: { ANTHROPIC_API_KEY: 'fake-key' },
  235. disposeGraceMs: 5,
  236. spawn: (spawnSpec) => {
  237. spawnSpecs.push(spawnSpec)
  238. return child.handle
  239. },
  240. }
  241. queryMock.mockImplementation((params) => {
  242. options.push(params.options)
  243. params.options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  244. return query
  245. })
  246. return { child, close, spawnSpecs, options, spec }
  247. }
  248. beforeEach(() => {
  249. queryMock.mockImplementation(({ options }) => {
  250. options.spawnClaudeCodeProcess!(sdkSpawnOptions({
  251. cwd: options.cwd!,
  252. env: options.env!,
  253. signal: options.abortController!.signal,
  254. }))
  255. return queryFrom([])
  256. })
  257. })
  258. afterEach(() => {
  259. queryMock.mockReset()
  260. vi.restoreAllMocks()
  261. vi.unstubAllEnvs()
  262. })
  263. describe('task admission and package contracts', () => {
  264. it('preserves text sequences and rejects empty, blank, and non-text tasks', () => {
  265. expect(textTask([
  266. { type: 'text', text: 'one' },
  267. { type: 'text', text: 'two' },
  268. ])).toBe('onetwo')
  269. expect(() => textTask([])).toThrow('only text blocks')
  270. expect(() => textTask([{ type: 'reasoning', text: 'hidden' }]))
  271. .toThrow('only text blocks')
  272. expect(() => textTask([{ type: 'text', text: ' \n ' }]))
  273. .toThrow('must not be empty')
  274. })
  275. it('registers one fixed descriptor, validates config, and unregisters on HMR', async () => {
  276. const ctx = new Context()
  277. await ctx.plugin(SubagentService)
  278. await ctx.plugin(LocalSubprocessService)
  279. const fiber = await ctx.plugin(claudeCode, {})
  280. expect(ctx.subagents.getProvider('claude-code')).toMatchObject({
  281. name: 'claude-code',
  282. capabilities: {
  283. outputSchema: false,
  284. depthLimit: false,
  285. toolFilter: false,
  286. persona: false,
  287. },
  288. inheritsParentContext: false,
  289. })
  290. expect(ctx.subagents.list()).toEqual(['claude-code'])
  291. await fiber.dispose()
  292. expect(ctx.subagents.list()).toEqual([])
  293. for (const disposeGraceMs of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
  294. await expect(ctx.plugin(claudeCode, { disposeGraceMs }))
  295. .rejects.toThrow('disposeGraceMs must be a positive finite number')
  296. }
  297. await expect(ctx.plugin(claudeCode, {
  298. disposeGraceMs: MAX_TIMER_DELAY_MS + 1,
  299. })).rejects.toThrow(
  300. `disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`,
  301. )
  302. await ctx.fiber.dispose()
  303. })
  304. it('starts through the registered provider with its resolved config and diagnostics', async () => {
  305. const ctx = new Context()
  306. await ctx.plugin(SubagentService)
  307. await ctx.plugin(LocalSubprocessService)
  308. const child = fakeChild()
  309. const spawn = vi.spyOn(ctx.subprocess, 'spawn')
  310. .mockImplementation(() => child.handle)
  311. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  312. await ctx.plugin(claudeCode, {
  313. env: {
  314. ANTHROPIC_API_KEY: 'provider-fake-key',
  315. CLAUDE_CONFIG_DIR: '/private/tmp/dsh-claude-code-unit-config',
  316. HOME: '/private/tmp/dsh-claude-code-unit-home',
  317. },
  318. disposeGraceMs: 29,
  319. })
  320. await expect(ctx.subagents.start('claude-code', {
  321. ...request(),
  322. parent: {
  323. id: 'parent-without-cwd',
  324. session: { header: {} },
  325. } as unknown as Agent,
  326. })).rejects.toThrow(
  327. 'subagent-claude-code: no working directory for the child — delegate from a parent session that has one',
  328. )
  329. expect(queryMock).not.toHaveBeenCalled()
  330. const run = await ctx.subagents.start('claude-code', request())
  331. child.settle({ exitCode: 9, signal: null })
  332. child.stdout.end()
  333. await expect(run.result).resolves.toEqual({
  334. output: [],
  335. stopReason: 'error',
  336. })
  337. expect(warn).toHaveBeenCalledWith(expect.stringContaining(
  338. 'subagent-claude-code: child run failed (error):',
  339. ))
  340. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  341. cwd: process.cwd(),
  342. graceMs: 29,
  343. }))
  344. expect(spawn.mock.calls[0]?.[0].env).toMatchObject({
  345. ANTHROPIC_API_KEY: 'provider-fake-key',
  346. })
  347. await run.dispose()
  348. await ctx.fiber.dispose()
  349. })
  350. it('keeps the Loader namespace shape and package-owned empty invariant', async () => {
  351. expect('default' in claudeCode).toBe(false)
  352. expect(claudeCode.name).toBe('subagent-claude-code')
  353. expect(claudeCode.inject).toEqual(['subagents', 'subprocess'])
  354. const loader = Object.create(Loader.prototype) as Loader
  355. expect(loader.unwrapExports(claudeCode)).toBe(claudeCode)
  356. const dispose = vi.fn()
  357. const register = vi.fn((
  358. _packageName: string,
  359. _installer: InvariantInstaller,
  360. ) => dispose)
  361. const ctx = { invariants: { register } } as unknown as Context
  362. await expect(invariant.apply(ctx)).resolves.toBe(dispose)
  363. expect(register).toHaveBeenCalledWith(
  364. '@deepseek-ai/dsh-subagent-claude-code',
  365. expect.any(Function),
  366. )
  367. const install = register.mock.calls[0]![1]
  368. await install(new Context(), (message) => { throw new Error(message) })
  369. expect(invariant.name).toBe('subagent-claude-code-invariant')
  370. expect(invariant.inject).toEqual(['invariants'])
  371. })
  372. })
  373. describe('official spawn projection', () => {
  374. it('forwards command, arguments, cwd, environment, and signal exactly', () => {
  375. vi.stubEnv('SDK_REMOVED_AMBIENT', 'ambient-value')
  376. const signal = new AbortController().signal
  377. const options = sdkSpawnOptions({
  378. command: '/official/claude',
  379. args: ['--one', 'two'],
  380. cwd: '/parent/workspace',
  381. env: { A: 'one', B: undefined, C: 'three' },
  382. signal,
  383. })
  384. expect(sdkEnvironmentOverlay(options.env)).toEqual(expect.objectContaining({
  385. A: 'one',
  386. B: undefined,
  387. C: 'three',
  388. SDK_REMOVED_AMBIENT: undefined,
  389. }))
  390. const spawnSpec = claudeSpawnSpec(options, 321)
  391. expect(spawnSpec).toMatchObject({
  392. argv: ['/official/claude', '--one', 'two'],
  393. cwd: '/parent/workspace',
  394. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' },
  395. graceMs: 321,
  396. signal,
  397. })
  398. expect(spawnSpec.env).toEqual(expect.objectContaining({
  399. A: 'one',
  400. B: undefined,
  401. C: 'three',
  402. SDK_REMOVED_AMBIENT: undefined,
  403. }))
  404. const missingCwd = sdkSpawnOptions()
  405. delete missingCwd.cwd
  406. expect(() => claudeSpawnSpec(
  407. missingCwd,
  408. 321,
  409. )).toThrow('SDK spawn request omitted its workspace')
  410. expect(() => claudeSpawnSpec(
  411. sdkSpawnOptions({ cwd: '' }),
  412. 321,
  413. )).toThrow('SDK spawn request omitted its workspace')
  414. })
  415. it('projects streams, exit facts, listeners, and idempotent tree termination', async () => {
  416. const child = fakeChild({ exitOnTerminate: false })
  417. const process = new ManagedClaudeCodeProcess(child.handle)
  418. expect(process.stdin).toBe(child.stdin)
  419. expect(process.stdout).toBe(child.stdout)
  420. expect(process.killed).toBe(false)
  421. expect(process.exitCode).toBeNull()
  422. expect(process.signalCode).toBeNull()
  423. const exit = vi.fn()
  424. const once = vi.fn()
  425. const removed = vi.fn()
  426. process.on('exit', exit)
  427. process.once('exit', once)
  428. process.on('exit', removed)
  429. process.off('exit', removed)
  430. expect(process.kill('SIGTERM')).toBe(true)
  431. expect(process.killed).toBe(true)
  432. expect(process.kill('SIGKILL')).toBe(false)
  433. expect(child.terminate).toHaveBeenCalledOnce()
  434. child.settle({ exitCode: null, signal: 'SIGTERM' })
  435. await nextTask()
  436. expect(exit).toHaveBeenCalledWith(null, 'SIGTERM')
  437. expect(once).toHaveBeenCalledOnce()
  438. expect(removed).not.toHaveBeenCalled()
  439. expect(process.signalCode).toBe('SIGTERM')
  440. expect(process.kill('SIGTERM')).toBe(false)
  441. })
  442. it('emits spawn errors', async () => {
  443. const child = fakeChild()
  444. const process = new ManagedClaudeCodeProcess(child.handle)
  445. const errorListener = vi.fn()
  446. const removed = vi.fn()
  447. process.once('error', errorListener)
  448. process.on('error', removed)
  449. process.off('error', removed)
  450. child.fail(new Error('spawn boom'))
  451. await nextTask()
  452. expect(errorListener).toHaveBeenCalledWith(expect.objectContaining({
  453. message: 'spawn boom',
  454. }))
  455. expect(removed).not.toHaveBeenCalled()
  456. })
  457. it('exposes a settled direct-child exit code', async () => {
  458. const child = fakeChild()
  459. const process = new ManagedClaudeCodeProcess(child.handle)
  460. child.settle({ exitCode: 7, signal: null })
  461. await nextTask()
  462. expect(process.exitCode).toBe(7)
  463. expect(process.signalCode).toBeNull()
  464. expect(process.kill('SIGTERM')).toBe(false)
  465. })
  466. })
  467. describe('query options and result mapping', () => {
  468. it('builds the fixed unattended options over the scrubbed environment', () => {
  469. vi.stubEnv('HOST_VISIBLE', 'visible')
  470. vi.stubEnv('HOST_SECRET_TOKEN', 'must-not-leak')
  471. vi.stubEnv('DSH_INTERNAL', 'must-not-leak')
  472. const child = fakeChild()
  473. const spawn = vi.fn(() => child.handle)
  474. const captured: SubprocessHandle[] = []
  475. const spec: ClaudeCodeRunSpec = {
  476. cwd: '/workspace',
  477. env: {
  478. HOST_VISIBLE: 'overridden',
  479. ANTHROPIC_API_KEY: 'explicit-fake-key',
  480. },
  481. disposeGraceMs: 17,
  482. spawn,
  483. }
  484. const controller = new AbortController()
  485. const options = claudeQueryOptions(spec, controller, (value) => {
  486. captured.push(value)
  487. })
  488. expect(options).toMatchObject({
  489. abortController: controller,
  490. cwd: '/workspace',
  491. persistSession: false,
  492. disallowedTools: ['AskUserQuestion'],
  493. })
  494. expect(options.env).toMatchObject({
  495. HOST_VISIBLE: 'overridden',
  496. ANTHROPIC_API_KEY: 'explicit-fake-key',
  497. })
  498. expect(options.env).not.toHaveProperty('HOST_SECRET_TOKEN')
  499. expect(options.env).not.toHaveProperty('DSH_INTERNAL')
  500. for (const omitted of [
  501. 'settingSources',
  502. 'canUseTool',
  503. 'onElicitation',
  504. 'onUserDialog',
  505. 'supportedDialogKinds',
  506. ]) {
  507. expect(options).not.toHaveProperty(omitted)
  508. }
  509. const spawned = options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  510. expect(spawned).toBeInstanceOf(ManagedClaudeCodeProcess)
  511. expect(captured).toEqual([child.handle])
  512. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  513. argv: ['/sdk/claude', '--output-format', 'stream-json'],
  514. cwd: '/workspace',
  515. graceMs: 17,
  516. }))
  517. })
  518. it('accepts only a non-error success with a non-blank final result', () => {
  519. expect(successfulResult(success('exact final'))).toBe('exact final')
  520. expect(() => successfulResult(success('answer', true)))
  521. .toThrow('marked as an error')
  522. expect(() => successfulResult(success(' \n ')))
  523. .toThrow('contained no answer')
  524. expect(() => successfulResult(failure(
  525. 'error_during_execution',
  526. ['first', 'second'],
  527. ))).toThrow('first; second')
  528. expect(() => successfulResult(failure(
  529. 'error_max_turns',
  530. [],
  531. ))).toThrow('error_max_turns')
  532. })
  533. it('consumes the complete stream and keeps the latest strict success', async () => {
  534. const query = queryFrom([
  535. { type: 'system', subtype: 'init' } as SDKMessage,
  536. success('first'),
  537. success('last'),
  538. ])
  539. await expect(consumeClaudeQuery(query)).resolves.toEqual({
  540. output: [{ type: 'text', text: 'last' }],
  541. stopReason: 'completed',
  542. })
  543. await expect(consumeClaudeQuery(
  544. queryFrom([{ type: 'system', subtype: 'init' } as SDKMessage]),
  545. )).rejects.toThrow('ended without a result')
  546. })
  547. })
  548. describe('run publication, cancellation, and settlement', () => {
  549. it('publishes only after Query and managed child exist, then disposes once', async () => {
  550. const fixture = fakeRun([success('exact answer')])
  551. const run = await startClaudeCodeRun(
  552. request([
  553. { type: 'text', text: 'first' },
  554. { type: 'text', text: 'second' },
  555. ]),
  556. fixture.spec,
  557. )
  558. expect(fixture.options).toHaveLength(1)
  559. expect(fixture.spawnSpecs).toHaveLength(1)
  560. await expect(run.result).resolves.toEqual({
  561. output: [{ type: 'text', text: 'exact answer' }],
  562. stopReason: 'completed',
  563. })
  564. const first = run.dispose()
  565. const second = run.dispose()
  566. expect(second).toBe(first)
  567. await first
  568. expect(fixture.close).toHaveBeenCalledOnce()
  569. expect(fixture.child.terminate).toHaveBeenCalledOnce()
  570. })
  571. it('flattens every SDK error result without inventing shared stop reasons', async () => {
  572. const subtypes: ErrorSubtype[] = [
  573. 'error_during_execution',
  574. 'error_max_turns',
  575. 'error_max_budget_usd',
  576. 'error_max_structured_output_retries',
  577. ]
  578. for (const subtype of subtypes) {
  579. const fixture = fakeRun([failure(subtype)])
  580. const onError = vi.fn()
  581. const run = await startClaudeCodeRun(
  582. request(),
  583. { ...fixture.spec, onError },
  584. )
  585. await expect(run.result).resolves.toEqual({
  586. output: [],
  587. stopReason: 'error',
  588. })
  589. expect(onError).toHaveBeenCalledWith(
  590. expect.any(Error),
  591. 'error',
  592. )
  593. await run.dispose()
  594. }
  595. })
  596. it('fails closed when iteration rejects after a result', async () => {
  597. const fixture = fakeRun(
  598. [success('partial final')],
  599. new Error('iterator boom'),
  600. )
  601. const run = await startClaudeCodeRun(request(), fixture.spec)
  602. await expect(run.result).resolves.toEqual({
  603. output: [],
  604. stopReason: 'error',
  605. })
  606. await run.dispose()
  607. })
  608. it('maps invalid success and missing result to error', async () => {
  609. for (const messages of [
  610. [success('answer', true)],
  611. [success('')],
  612. [{ type: 'system', subtype: 'init' } as SDKMessage],
  613. ]) {
  614. const fixture = fakeRun(messages)
  615. const run = await startClaudeCodeRun(request(), fixture.spec)
  616. await expect(run.result).resolves.toMatchObject({
  617. stopReason: 'error',
  618. })
  619. await run.dispose()
  620. }
  621. })
  622. it('gives local cancellation precedence and isolates overlapping controllers', async () => {
  623. const firstChild = fakeChild()
  624. const secondChild = fakeChild()
  625. const children = [firstChild, secondChild]
  626. const controllers: AbortController[] = []
  627. let index = 0
  628. const spec: ClaudeCodeRunSpec = {
  629. cwd: '/workspace',
  630. env: {},
  631. disposeGraceMs: 5,
  632. spawn: () => children[index++]!.handle,
  633. }
  634. queryMock.mockImplementation(({ prompt, options }) => {
  635. controllers.push(options.abortController!)
  636. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  637. return prompt === 'wait'
  638. ? waitingQuery(options.abortController!.signal)
  639. : queryFrom([success('second answer')])
  640. })
  641. const firstAbort = new AbortController()
  642. const first = await startClaudeCodeRun(
  643. request([{ type: 'text', text: 'wait' }], firstAbort.signal),
  644. spec,
  645. )
  646. const second = await startClaudeCodeRun(
  647. request([{ type: 'text', text: 'finish' }]),
  648. spec,
  649. )
  650. expect(controllers).toHaveLength(2)
  651. expect(controllers[0]).not.toBe(controllers[1])
  652. firstAbort.abort(new Error('parent cancelled'))
  653. await expect(first.result).resolves.toEqual({
  654. output: [],
  655. stopReason: 'aborted',
  656. })
  657. await expect(second.result).resolves.toEqual({
  658. output: [{ type: 'text', text: 'second answer' }],
  659. stopReason: 'completed',
  660. })
  661. expect(controllers[1]!.signal.aborted).toBe(false)
  662. await Promise.all([first.dispose(), second.dispose()])
  663. })
  664. it('keeps local cancellation authoritative when the SDK iterator ends normally', async () => {
  665. const parentAbort = new AbortController()
  666. const child = fakeChild()
  667. async function* stream(): AsyncGenerator<SDKMessage, void> {
  668. yield success('candidate answer')
  669. parentAbort.abort(new Error('parent cancelled at iterator completion'))
  670. }
  671. queryMock.mockImplementation(({ options }) => {
  672. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  673. return Object.assign(stream(), { close: vi.fn() }) as unknown as Query
  674. })
  675. const run = await startClaudeCodeRun(
  676. request(undefined, parentAbort.signal),
  677. {
  678. cwd: '/workspace',
  679. env: {},
  680. disposeGraceMs: 5,
  681. spawn: () => child.handle,
  682. },
  683. )
  684. await expect(run.result).resolves.toEqual({
  685. output: [],
  686. stopReason: 'aborted',
  687. })
  688. await run.dispose()
  689. })
  690. it('rejects pre-abort and every incomplete startup transaction', async () => {
  691. const preAborted = new AbortController()
  692. preAborted.abort()
  693. const unused = fakeRun()
  694. await expect(startClaudeCodeRun(
  695. request(undefined, preAborted.signal),
  696. unused.spec,
  697. )).rejects.toThrow('aborted before SDK startup')
  698. expect(unused.options).toEqual([])
  699. const noChildClose = vi.fn()
  700. queryMock.mockImplementationOnce(
  701. () => queryFrom([], undefined, noChildClose),
  702. )
  703. await expect(startClaudeCodeRun(request(), {
  704. ...unused.spec,
  705. })).rejects.toThrow('did not publish a controllable')
  706. expect(noChildClose).toHaveBeenCalledOnce()
  707. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  708. queryMock.mockImplementationOnce(
  709. () => queryFrom([], undefined, closeFailure),
  710. )
  711. const noChild = startClaudeCodeRun(request(), {
  712. ...unused.spec,
  713. })
  714. await expect(noChild).rejects.toBeInstanceOf(AggregateError)
  715. const startupAbort = new AbortController()
  716. const abortedChild = fakeChild()
  717. const abortedClose = vi.fn()
  718. queryMock.mockImplementationOnce(({ options }) => {
  719. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  720. startupAbort.abort(new Error('startup cancelled'))
  721. return queryFrom([], undefined, abortedClose)
  722. })
  723. const abortedDuringStartup = startClaudeCodeRun(
  724. request(undefined, startupAbort.signal),
  725. {
  726. ...unused.spec,
  727. spawn: () => abortedChild.handle,
  728. },
  729. )
  730. await expect(abortedDuringStartup)
  731. .rejects.toThrow('aborted before SDK startup')
  732. expect(abortedClose).toHaveBeenCalledOnce()
  733. expect(abortedChild.terminate).toHaveBeenCalledOnce()
  734. queryMock.mockImplementationOnce(() => {
  735. throw new Error('query failed before resource creation')
  736. })
  737. await expect(startClaudeCodeRun(request(), {
  738. ...unused.spec,
  739. })).rejects.toThrow('query failed before resource creation')
  740. const spawned = fakeChild()
  741. const spawnSpecs: SubprocessSpawnSpec[] = []
  742. let factoryController: AbortController | undefined
  743. queryMock.mockImplementationOnce(({ options }) => {
  744. factoryController = options.abortController
  745. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  746. throw new Error('query construction failed')
  747. })
  748. const factoryFailure = startClaudeCodeRun(request(), {
  749. ...unused.spec,
  750. spawn: (spawnSpec) => {
  751. spawnSpecs.push(spawnSpec)
  752. return spawned.handle
  753. },
  754. })
  755. await expect(factoryFailure).rejects.toThrow('query construction failed')
  756. expect(spawnSpecs).toHaveLength(1)
  757. expect(factoryController?.signal.aborted).toBe(true)
  758. expect(spawned.terminate).toHaveBeenCalledOnce()
  759. const failedSpawn = fakeChild({
  760. pid: -1,
  761. doneError: new Error('spawn failed'),
  762. })
  763. const failed = fakeRun([], undefined, failedSpawn)
  764. await expect(startClaudeCodeRun(request(), failed.spec))
  765. .rejects.toBeInstanceOf(AggregateError)
  766. expect(failed.close).toHaveBeenCalledOnce()
  767. })
  768. })
  769. describe('query and process disposal', () => {
  770. it('closes the query, terminates the tree, and waits for direct-child outcome', async () => {
  771. const child = fakeChild()
  772. const close = vi.fn()
  773. await disposeClaudeCodeChild({ close }, child.handle)
  774. expect(close).toHaveBeenCalledOnce()
  775. expect(child.terminate).toHaveBeenCalledOnce()
  776. expect(child.waitForExit).toHaveBeenCalledOnce()
  777. expect(child.waitForExit).toHaveBeenCalledWith()
  778. await expect(child.handle.done).resolves.toEqual({
  779. exitCode: 0,
  780. signal: null,
  781. })
  782. })
  783. it('does not finish disposal before the managed tree exits', async () => {
  784. const child = fakeChild({ exitOnTerminate: false })
  785. let disposed = false
  786. const disposal = disposeClaudeCodeChild(
  787. { close: vi.fn() },
  788. child.handle,
  789. ).then(() => {
  790. disposed = true
  791. })
  792. await nextTask()
  793. expect(disposed).toBe(false)
  794. child.settle()
  795. await disposal
  796. expect(disposed).toBe(true)
  797. })
  798. it('reports wait, close, and direct-child failures without skipping cleanup', async () => {
  799. const waitFailure = fakeChild({
  800. waitForExitError: new Error('wait boom'),
  801. })
  802. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  803. await expect(disposeClaudeCodeChild(
  804. { close: closeFailure },
  805. waitFailure.handle,
  806. )).rejects.toBeInstanceOf(AggregateError)
  807. expect(waitFailure.terminate).toHaveBeenCalledOnce()
  808. const doneFailure = fakeChild({
  809. pid: -1,
  810. doneError: new Error('spawn boom'),
  811. })
  812. await expect(disposeClaudeCodeChild(
  813. { close: vi.fn() },
  814. doneFailure.handle,
  815. )).rejects.toThrow('spawn boom')
  816. const both = fakeChild({
  817. pid: -1,
  818. doneError: new Error('spawn boom'),
  819. })
  820. await expect(disposeClaudeCodeChild(
  821. { close: () => { throw new Error('close boom') } },
  822. both.handle,
  823. )).rejects.toBeInstanceOf(AggregateError)
  824. })
  825. })