subagent-claude-code.spec.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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. const run = await ctx.subagents.start('claude-code', request())
  321. child.settle({ exitCode: 9, signal: null })
  322. child.stdout.end()
  323. await expect(run.result).resolves.toEqual({
  324. output: [],
  325. stopReason: 'error',
  326. })
  327. expect(warn).toHaveBeenCalledWith(expect.stringContaining(
  328. 'subagent-claude-code: child run failed (error):',
  329. ))
  330. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  331. cwd: process.cwd(),
  332. graceMs: 29,
  333. }))
  334. expect(spawn.mock.calls[0]?.[0].env).toMatchObject({
  335. ANTHROPIC_API_KEY: 'provider-fake-key',
  336. })
  337. await run.dispose()
  338. await ctx.fiber.dispose()
  339. })
  340. it('keeps the Loader namespace shape and package-owned empty invariant', async () => {
  341. expect('default' in claudeCode).toBe(false)
  342. expect(claudeCode.name).toBe('subagent-claude-code')
  343. expect(claudeCode.inject).toEqual(['subagents', 'subprocess'])
  344. const loader = Object.create(Loader.prototype) as Loader
  345. expect(loader.unwrapExports(claudeCode)).toBe(claudeCode)
  346. const dispose = vi.fn()
  347. const register = vi.fn((
  348. _packageName: string,
  349. _installer: InvariantInstaller,
  350. ) => dispose)
  351. const ctx = { invariants: { register } } as unknown as Context
  352. await expect(invariant.apply(ctx)).resolves.toBe(dispose)
  353. expect(register).toHaveBeenCalledWith(
  354. '@deepseek-ai/dsh-subagent-claude-code',
  355. expect.any(Function),
  356. )
  357. const install = register.mock.calls[0]![1]
  358. await install(new Context(), (message) => { throw new Error(message) })
  359. expect(invariant.name).toBe('subagent-claude-code-invariant')
  360. expect(invariant.inject).toEqual(['invariants'])
  361. })
  362. })
  363. describe('official spawn projection', () => {
  364. it('forwards command, arguments, cwd, environment, and signal exactly', () => {
  365. vi.stubEnv('SDK_REMOVED_AMBIENT', 'ambient-value')
  366. const signal = new AbortController().signal
  367. const options = sdkSpawnOptions({
  368. command: '/official/claude',
  369. args: ['--one', 'two'],
  370. cwd: '/parent/workspace',
  371. env: { A: 'one', B: undefined, C: 'three' },
  372. signal,
  373. })
  374. expect(sdkEnvironmentOverlay(options.env)).toEqual(expect.objectContaining({
  375. A: 'one',
  376. B: undefined,
  377. C: 'three',
  378. SDK_REMOVED_AMBIENT: undefined,
  379. }))
  380. const spawnSpec = claudeSpawnSpec(options, 321)
  381. expect(spawnSpec).toMatchObject({
  382. argv: ['/official/claude', '--one', 'two'],
  383. cwd: '/parent/workspace',
  384. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' },
  385. graceMs: 321,
  386. signal,
  387. })
  388. expect(spawnSpec.env).toEqual(expect.objectContaining({
  389. A: 'one',
  390. B: undefined,
  391. C: 'three',
  392. SDK_REMOVED_AMBIENT: undefined,
  393. }))
  394. const missingCwd = sdkSpawnOptions()
  395. delete missingCwd.cwd
  396. expect(() => claudeSpawnSpec(
  397. missingCwd,
  398. 321,
  399. )).toThrow('SDK spawn request omitted its workspace')
  400. expect(() => claudeSpawnSpec(
  401. sdkSpawnOptions({ cwd: '' }),
  402. 321,
  403. )).toThrow('SDK spawn request omitted its workspace')
  404. })
  405. it('projects streams, exit facts, listeners, and idempotent tree termination', async () => {
  406. const child = fakeChild({ exitOnTerminate: false })
  407. const process = new ManagedClaudeCodeProcess(child.handle)
  408. expect(process.stdin).toBe(child.stdin)
  409. expect(process.stdout).toBe(child.stdout)
  410. expect(process.killed).toBe(false)
  411. expect(process.exitCode).toBeNull()
  412. expect(process.signalCode).toBeNull()
  413. const exit = vi.fn()
  414. const once = vi.fn()
  415. const removed = vi.fn()
  416. process.on('exit', exit)
  417. process.once('exit', once)
  418. process.on('exit', removed)
  419. process.off('exit', removed)
  420. expect(process.kill('SIGTERM')).toBe(true)
  421. expect(process.killed).toBe(true)
  422. expect(process.kill('SIGKILL')).toBe(false)
  423. expect(child.terminate).toHaveBeenCalledOnce()
  424. child.settle({ exitCode: null, signal: 'SIGTERM' })
  425. await nextTask()
  426. expect(exit).toHaveBeenCalledWith(null, 'SIGTERM')
  427. expect(once).toHaveBeenCalledOnce()
  428. expect(removed).not.toHaveBeenCalled()
  429. expect(process.signalCode).toBe('SIGTERM')
  430. expect(process.kill('SIGTERM')).toBe(false)
  431. })
  432. it('emits spawn errors', async () => {
  433. const child = fakeChild()
  434. const process = new ManagedClaudeCodeProcess(child.handle)
  435. const errorListener = vi.fn()
  436. const removed = vi.fn()
  437. process.once('error', errorListener)
  438. process.on('error', removed)
  439. process.off('error', removed)
  440. child.fail(new Error('spawn boom'))
  441. await nextTask()
  442. expect(errorListener).toHaveBeenCalledWith(expect.objectContaining({
  443. message: 'spawn boom',
  444. }))
  445. expect(removed).not.toHaveBeenCalled()
  446. })
  447. it('exposes a settled direct-child exit code', async () => {
  448. const child = fakeChild()
  449. const process = new ManagedClaudeCodeProcess(child.handle)
  450. child.settle({ exitCode: 7, signal: null })
  451. await nextTask()
  452. expect(process.exitCode).toBe(7)
  453. expect(process.signalCode).toBeNull()
  454. expect(process.kill('SIGTERM')).toBe(false)
  455. })
  456. })
  457. describe('query options and result mapping', () => {
  458. it('builds the fixed unattended options over the scrubbed environment', () => {
  459. vi.stubEnv('HOST_VISIBLE', 'visible')
  460. vi.stubEnv('HOST_SECRET_TOKEN', 'must-not-leak')
  461. vi.stubEnv('DSH_INTERNAL', 'must-not-leak')
  462. const child = fakeChild()
  463. const spawn = vi.fn(() => child.handle)
  464. const captured: SubprocessHandle[] = []
  465. const spec: ClaudeCodeRunSpec = {
  466. cwd: '/workspace',
  467. env: {
  468. HOST_VISIBLE: 'overridden',
  469. ANTHROPIC_API_KEY: 'explicit-fake-key',
  470. },
  471. disposeGraceMs: 17,
  472. spawn,
  473. }
  474. const controller = new AbortController()
  475. const options = claudeQueryOptions(spec, controller, (value) => {
  476. captured.push(value)
  477. })
  478. expect(options).toMatchObject({
  479. abortController: controller,
  480. cwd: '/workspace',
  481. persistSession: false,
  482. disallowedTools: ['AskUserQuestion'],
  483. })
  484. expect(options.env).toMatchObject({
  485. HOST_VISIBLE: 'overridden',
  486. ANTHROPIC_API_KEY: 'explicit-fake-key',
  487. })
  488. expect(options.env).not.toHaveProperty('HOST_SECRET_TOKEN')
  489. expect(options.env).not.toHaveProperty('DSH_INTERNAL')
  490. for (const omitted of [
  491. 'settingSources',
  492. 'canUseTool',
  493. 'onElicitation',
  494. 'onUserDialog',
  495. 'supportedDialogKinds',
  496. ]) {
  497. expect(options).not.toHaveProperty(omitted)
  498. }
  499. const spawned = options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  500. expect(spawned).toBeInstanceOf(ManagedClaudeCodeProcess)
  501. expect(captured).toEqual([child.handle])
  502. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  503. argv: ['/sdk/claude', '--output-format', 'stream-json'],
  504. cwd: '/workspace',
  505. graceMs: 17,
  506. }))
  507. })
  508. it('accepts only a non-error success with a non-blank final result', () => {
  509. expect(successfulResult(success('exact final'))).toBe('exact final')
  510. expect(() => successfulResult(success('answer', true)))
  511. .toThrow('marked as an error')
  512. expect(() => successfulResult(success(' \n ')))
  513. .toThrow('contained no answer')
  514. expect(() => successfulResult(failure(
  515. 'error_during_execution',
  516. ['first', 'second'],
  517. ))).toThrow('first; second')
  518. expect(() => successfulResult(failure(
  519. 'error_max_turns',
  520. [],
  521. ))).toThrow('error_max_turns')
  522. })
  523. it('consumes the complete stream and keeps the latest strict success', async () => {
  524. const query = queryFrom([
  525. { type: 'system', subtype: 'init' } as SDKMessage,
  526. success('first'),
  527. success('last'),
  528. ])
  529. await expect(consumeClaudeQuery(query)).resolves.toEqual({
  530. output: [{ type: 'text', text: 'last' }],
  531. stopReason: 'completed',
  532. })
  533. await expect(consumeClaudeQuery(
  534. queryFrom([{ type: 'system', subtype: 'init' } as SDKMessage]),
  535. )).rejects.toThrow('ended without a result')
  536. })
  537. })
  538. describe('run publication, cancellation, and settlement', () => {
  539. it('publishes only after Query and managed child exist, then disposes once', async () => {
  540. const fixture = fakeRun([success('exact answer')])
  541. const run = await startClaudeCodeRun(
  542. request([
  543. { type: 'text', text: 'first' },
  544. { type: 'text', text: 'second' },
  545. ]),
  546. fixture.spec,
  547. )
  548. expect(fixture.options).toHaveLength(1)
  549. expect(fixture.spawnSpecs).toHaveLength(1)
  550. await expect(run.result).resolves.toEqual({
  551. output: [{ type: 'text', text: 'exact answer' }],
  552. stopReason: 'completed',
  553. })
  554. const first = run.dispose()
  555. const second = run.dispose()
  556. expect(second).toBe(first)
  557. await first
  558. expect(fixture.close).toHaveBeenCalledOnce()
  559. expect(fixture.child.terminate).toHaveBeenCalledOnce()
  560. })
  561. it('flattens every SDK error result without inventing shared stop reasons', async () => {
  562. const subtypes: ErrorSubtype[] = [
  563. 'error_during_execution',
  564. 'error_max_turns',
  565. 'error_max_budget_usd',
  566. 'error_max_structured_output_retries',
  567. ]
  568. for (const subtype of subtypes) {
  569. const fixture = fakeRun([failure(subtype)])
  570. const onError = vi.fn()
  571. const run = await startClaudeCodeRun(
  572. request(),
  573. { ...fixture.spec, onError },
  574. )
  575. await expect(run.result).resolves.toEqual({
  576. output: [],
  577. stopReason: 'error',
  578. })
  579. expect(onError).toHaveBeenCalledWith(
  580. expect.any(Error),
  581. 'error',
  582. )
  583. await run.dispose()
  584. }
  585. })
  586. it('fails closed when iteration rejects after a result', async () => {
  587. const fixture = fakeRun(
  588. [success('partial final')],
  589. new Error('iterator boom'),
  590. )
  591. const run = await startClaudeCodeRun(request(), fixture.spec)
  592. await expect(run.result).resolves.toEqual({
  593. output: [],
  594. stopReason: 'error',
  595. })
  596. await run.dispose()
  597. })
  598. it('maps invalid success and missing result to error', async () => {
  599. for (const messages of [
  600. [success('answer', true)],
  601. [success('')],
  602. [{ type: 'system', subtype: 'init' } as SDKMessage],
  603. ]) {
  604. const fixture = fakeRun(messages)
  605. const run = await startClaudeCodeRun(request(), fixture.spec)
  606. await expect(run.result).resolves.toMatchObject({
  607. stopReason: 'error',
  608. })
  609. await run.dispose()
  610. }
  611. })
  612. it('gives local cancellation precedence and isolates overlapping controllers', async () => {
  613. const firstChild = fakeChild()
  614. const secondChild = fakeChild()
  615. const children = [firstChild, secondChild]
  616. const controllers: AbortController[] = []
  617. let index = 0
  618. const spec: ClaudeCodeRunSpec = {
  619. cwd: '/workspace',
  620. env: {},
  621. disposeGraceMs: 5,
  622. spawn: () => children[index++]!.handle,
  623. }
  624. queryMock.mockImplementation(({ prompt, options }) => {
  625. controllers.push(options.abortController!)
  626. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  627. return prompt === 'wait'
  628. ? waitingQuery(options.abortController!.signal)
  629. : queryFrom([success('second answer')])
  630. })
  631. const firstAbort = new AbortController()
  632. const first = await startClaudeCodeRun(
  633. request([{ type: 'text', text: 'wait' }], firstAbort.signal),
  634. spec,
  635. )
  636. const second = await startClaudeCodeRun(
  637. request([{ type: 'text', text: 'finish' }]),
  638. spec,
  639. )
  640. expect(controllers).toHaveLength(2)
  641. expect(controllers[0]).not.toBe(controllers[1])
  642. firstAbort.abort(new Error('parent cancelled'))
  643. await expect(first.result).resolves.toEqual({
  644. output: [],
  645. stopReason: 'aborted',
  646. })
  647. await expect(second.result).resolves.toEqual({
  648. output: [{ type: 'text', text: 'second answer' }],
  649. stopReason: 'completed',
  650. })
  651. expect(controllers[1]!.signal.aborted).toBe(false)
  652. await Promise.all([first.dispose(), second.dispose()])
  653. })
  654. it('keeps local cancellation authoritative when the SDK iterator ends normally', async () => {
  655. const parentAbort = new AbortController()
  656. const child = fakeChild()
  657. async function* stream(): AsyncGenerator<SDKMessage, void> {
  658. yield success('candidate answer')
  659. parentAbort.abort(new Error('parent cancelled at iterator completion'))
  660. }
  661. queryMock.mockImplementation(({ options }) => {
  662. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  663. return Object.assign(stream(), { close: vi.fn() }) as unknown as Query
  664. })
  665. const run = await startClaudeCodeRun(
  666. request(undefined, parentAbort.signal),
  667. {
  668. cwd: '/workspace',
  669. env: {},
  670. disposeGraceMs: 5,
  671. spawn: () => child.handle,
  672. },
  673. )
  674. await expect(run.result).resolves.toEqual({
  675. output: [],
  676. stopReason: 'aborted',
  677. })
  678. await run.dispose()
  679. })
  680. it('rejects pre-abort and every incomplete startup transaction', async () => {
  681. const preAborted = new AbortController()
  682. preAborted.abort()
  683. const unused = fakeRun()
  684. await expect(startClaudeCodeRun(
  685. request(undefined, preAborted.signal),
  686. unused.spec,
  687. )).rejects.toThrow('aborted before SDK startup')
  688. expect(unused.options).toEqual([])
  689. const noChildClose = vi.fn()
  690. queryMock.mockImplementationOnce(
  691. () => queryFrom([], undefined, noChildClose),
  692. )
  693. await expect(startClaudeCodeRun(request(), {
  694. ...unused.spec,
  695. })).rejects.toThrow('did not publish a controllable')
  696. expect(noChildClose).toHaveBeenCalledOnce()
  697. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  698. queryMock.mockImplementationOnce(
  699. () => queryFrom([], undefined, closeFailure),
  700. )
  701. const noChild = startClaudeCodeRun(request(), {
  702. ...unused.spec,
  703. })
  704. await expect(noChild).rejects.toBeInstanceOf(AggregateError)
  705. const startupAbort = new AbortController()
  706. const abortedChild = fakeChild()
  707. const abortedClose = vi.fn()
  708. queryMock.mockImplementationOnce(({ options }) => {
  709. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  710. startupAbort.abort(new Error('startup cancelled'))
  711. return queryFrom([], undefined, abortedClose)
  712. })
  713. const abortedDuringStartup = startClaudeCodeRun(
  714. request(undefined, startupAbort.signal),
  715. {
  716. ...unused.spec,
  717. spawn: () => abortedChild.handle,
  718. },
  719. )
  720. await expect(abortedDuringStartup)
  721. .rejects.toThrow('aborted before SDK startup')
  722. expect(abortedClose).toHaveBeenCalledOnce()
  723. expect(abortedChild.terminate).toHaveBeenCalledOnce()
  724. queryMock.mockImplementationOnce(() => {
  725. throw new Error('query failed before resource creation')
  726. })
  727. await expect(startClaudeCodeRun(request(), {
  728. ...unused.spec,
  729. })).rejects.toThrow('query failed before resource creation')
  730. const spawned = fakeChild()
  731. const spawnSpecs: SubprocessSpawnSpec[] = []
  732. let factoryController: AbortController | undefined
  733. queryMock.mockImplementationOnce(({ options }) => {
  734. factoryController = options.abortController
  735. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  736. throw new Error('query construction failed')
  737. })
  738. const factoryFailure = startClaudeCodeRun(request(), {
  739. ...unused.spec,
  740. spawn: (spawnSpec) => {
  741. spawnSpecs.push(spawnSpec)
  742. return spawned.handle
  743. },
  744. })
  745. await expect(factoryFailure).rejects.toThrow('query construction failed')
  746. expect(spawnSpecs).toHaveLength(1)
  747. expect(factoryController?.signal.aborted).toBe(true)
  748. expect(spawned.terminate).toHaveBeenCalledOnce()
  749. const failedSpawn = fakeChild({
  750. pid: -1,
  751. doneError: new Error('spawn failed'),
  752. })
  753. const failed = fakeRun([], undefined, failedSpawn)
  754. await expect(startClaudeCodeRun(request(), failed.spec))
  755. .rejects.toBeInstanceOf(AggregateError)
  756. expect(failed.close).toHaveBeenCalledOnce()
  757. })
  758. })
  759. describe('query and process disposal', () => {
  760. it('closes the query, terminates the tree, and waits for direct-child outcome', async () => {
  761. const child = fakeChild()
  762. const close = vi.fn()
  763. await disposeClaudeCodeChild({ close }, child.handle)
  764. expect(close).toHaveBeenCalledOnce()
  765. expect(child.terminate).toHaveBeenCalledOnce()
  766. expect(child.waitForExit).toHaveBeenCalledOnce()
  767. expect(child.waitForExit).toHaveBeenCalledWith()
  768. await expect(child.handle.done).resolves.toEqual({
  769. exitCode: 0,
  770. signal: null,
  771. })
  772. })
  773. it('does not finish disposal before the managed tree exits', async () => {
  774. const child = fakeChild({ exitOnTerminate: false })
  775. let disposed = false
  776. const disposal = disposeClaudeCodeChild(
  777. { close: vi.fn() },
  778. child.handle,
  779. ).then(() => {
  780. disposed = true
  781. })
  782. await nextTask()
  783. expect(disposed).toBe(false)
  784. child.settle()
  785. await disposal
  786. expect(disposed).toBe(true)
  787. })
  788. it('reports wait, close, and direct-child failures without skipping cleanup', async () => {
  789. const waitFailure = fakeChild({
  790. waitForExitError: new Error('wait boom'),
  791. })
  792. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  793. await expect(disposeClaudeCodeChild(
  794. { close: closeFailure },
  795. waitFailure.handle,
  796. )).rejects.toBeInstanceOf(AggregateError)
  797. expect(waitFailure.terminate).toHaveBeenCalledOnce()
  798. const doneFailure = fakeChild({
  799. pid: -1,
  800. doneError: new Error('spawn boom'),
  801. })
  802. await expect(disposeClaudeCodeChild(
  803. { close: vi.fn() },
  804. doneFailure.handle,
  805. )).rejects.toThrow('spawn boom')
  806. const both = fakeChild({
  807. pid: -1,
  808. doneError: new Error('spawn boom'),
  809. })
  810. await expect(disposeClaudeCodeChild(
  811. { close: () => { throw new Error('close boom') } },
  812. both.handle,
  813. )).rejects.toBeInstanceOf(AggregateError)
  814. })
  815. })