subagent-claude-code.spec.ts 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. import { readFileSync } from 'node:fs'
  2. import { dirname, resolve } from 'node:path'
  3. import { PassThrough } from 'node:stream'
  4. import { fileURLToPath } from 'node:url'
  5. import type {
  6. Options,
  7. Query,
  8. SDKMessage,
  9. SDKPermissionDeniedMessage,
  10. SDKResultMessage,
  11. SpawnOptions,
  12. } from '@anthropic-ai/claude-agent-sdk'
  13. import { Context } from '@deepseek-ai/cordis'
  14. import Loader from '@deepseek-ai/cordis-plugin-loader'
  15. import * as yaml from 'js-yaml'
  16. import {
  17. afterEach,
  18. beforeEach,
  19. describe,
  20. expect,
  21. it,
  22. type Mock,
  23. vi,
  24. } from 'vitest'
  25. import type { Agent } from '@deepseek-ai/dsh-agent'
  26. import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  27. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  28. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  29. import type {
  30. SubprocessHandle,
  31. SubprocessOutcome,
  32. SubprocessSpawnSpec,
  33. } from '@deepseek-ai/dsh-subprocess'
  34. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  35. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  36. import * as claudeCode from '../src/index.ts'
  37. import * as invariant from '../src/invariant.ts'
  38. import {
  39. claudeSpawnSpec,
  40. ManagedClaudeCodeProcess,
  41. sdkEnvironmentOverlay,
  42. } from '../src/process.ts'
  43. import {
  44. CLAUDE_CODE_PERMISSION_MODES,
  45. DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  46. claudeQueryOptions,
  47. consumeClaudeQuery,
  48. disposeClaudeCodeChild,
  49. startClaudeCodeRun,
  50. successfulResult,
  51. textTask,
  52. type ClaudeCodeRunSpec,
  53. } from '../src/run.ts'
  54. type QueryFactory = (params: {
  55. prompt: string
  56. options: Options
  57. }) => Query
  58. const queryMock = vi.hoisted(() => vi.fn<QueryFactory>())
  59. const CLAUDE_AGENT_SDK_VERSION = '0.3.220'
  60. const CLAUDE_CODE_VERSION = '2.1.220'
  61. const CLAUDE_PLATFORM_PACKAGES = [
  62. '@anthropic-ai/claude-agent-sdk-darwin-arm64',
  63. '@anthropic-ai/claude-agent-sdk-darwin-x64',
  64. '@anthropic-ai/claude-agent-sdk-linux-arm64',
  65. '@anthropic-ai/claude-agent-sdk-linux-arm64-musl',
  66. '@anthropic-ai/claude-agent-sdk-linux-x64',
  67. '@anthropic-ai/claude-agent-sdk-linux-x64-musl',
  68. '@anthropic-ai/claude-agent-sdk-win32-arm64',
  69. '@anthropic-ai/claude-agent-sdk-win32-x64',
  70. ] as const
  71. vi.mock('@anthropic-ai/claude-agent-sdk', async importOriginal => ({
  72. ...await importOriginal<typeof import('@anthropic-ai/claude-agent-sdk')>(),
  73. query: queryMock,
  74. }))
  75. const fakeParent = {
  76. id: 'parent',
  77. session: { header: { cwd: process.cwd() } },
  78. } as unknown as Agent
  79. function request(
  80. prompt: ContentBlock[] = [{ type: 'text', text: 'do the task' }],
  81. signal = new AbortController().signal,
  82. ) {
  83. return { prompt, parent: fakeParent, signal }
  84. }
  85. async function nextTask(): Promise<void> {
  86. await new Promise<void>((resolve) => { setImmediate(resolve) })
  87. }
  88. function errorCause(value: unknown): Error | undefined {
  89. return value instanceof Error && value.cause instanceof Error
  90. ? value.cause
  91. : undefined
  92. }
  93. interface FakeChildOptions {
  94. readonly pid?: number
  95. readonly exitOnTerminate?: boolean
  96. readonly waitForExitError?: Error
  97. readonly doneError?: Error
  98. }
  99. interface FakeChild {
  100. readonly handle: SubprocessHandle
  101. readonly stdin: PassThrough
  102. readonly stdout: PassThrough
  103. readonly settle: (outcome?: SubprocessOutcome) => void
  104. readonly fail: (error: Error) => void
  105. readonly terminate: Mock<SubprocessHandle['terminate']>
  106. readonly waitForExit: Mock<SubprocessHandle['waitForExit']>
  107. }
  108. function fakeChild(options: FakeChildOptions = {}): FakeChild {
  109. const stdin = new PassThrough()
  110. const stdout = new PassThrough()
  111. let exited = false
  112. let resolveDone!: (outcome: SubprocessOutcome) => void
  113. let rejectDone!: (error: Error) => void
  114. const done = new Promise<SubprocessOutcome>((resolve, reject) => {
  115. resolveDone = resolve
  116. rejectDone = reject
  117. })
  118. // Individual tests deliberately exercise rejected and still-pending handles.
  119. void done.catch(() => {})
  120. const settle = (
  121. outcome: SubprocessOutcome = { exitCode: 0, signal: null },
  122. ): void => {
  123. if (exited) return
  124. exited = true
  125. resolveDone(outcome)
  126. }
  127. const fail = (error: Error): void => {
  128. if (exited) return
  129. exited = true
  130. rejectDone(error)
  131. }
  132. if (options.doneError !== undefined) fail(options.doneError)
  133. const terminate = vi.fn<SubprocessHandle['terminate']>(() => {
  134. if (options.exitOnTerminate !== false) settle()
  135. })
  136. const waitForExit = vi.fn<SubprocessHandle['waitForExit']>(async (signal?: AbortSignal): Promise<boolean> => {
  137. if (options.waitForExitError !== undefined) {
  138. throw options.waitForExitError
  139. }
  140. if (exited) return true
  141. if (signal === undefined) {
  142. await done.catch(() => {})
  143. return true
  144. }
  145. return await new Promise<boolean>((resolve) => {
  146. const onAbort = (): void => { resolve(false) }
  147. signal.addEventListener('abort', onAbort, { once: true })
  148. void done.then(
  149. () => {
  150. signal.removeEventListener('abort', onAbort)
  151. resolve(true)
  152. },
  153. () => {
  154. signal.removeEventListener('abort', onAbort)
  155. resolve(true)
  156. },
  157. )
  158. })
  159. })
  160. const handle: SubprocessHandle = {
  161. pid: options.pid ?? 1234,
  162. stdin,
  163. stdout,
  164. stderr: undefined,
  165. collected: {},
  166. done,
  167. terminate,
  168. waitForExit,
  169. }
  170. return {
  171. handle,
  172. stdin,
  173. stdout,
  174. settle,
  175. fail,
  176. terminate,
  177. waitForExit,
  178. }
  179. }
  180. function success(
  181. result = 'answer',
  182. isError = false,
  183. ): SDKResultMessage {
  184. return {
  185. type: 'result',
  186. subtype: 'success',
  187. is_error: isError,
  188. result,
  189. } as SDKResultMessage
  190. }
  191. type ErrorSubtype = Exclude<SDKResultMessage['subtype'], 'success'>
  192. function failure(
  193. subtype: ErrorSubtype,
  194. errors: string[] = ['fixture failure'],
  195. ): SDKResultMessage {
  196. return {
  197. type: 'result',
  198. subtype,
  199. is_error: true,
  200. errors,
  201. } as SDKResultMessage
  202. }
  203. function expectedFailureDiagnostic(
  204. stage: 'query-start' | 'query-run' | 'process' | 'teardown',
  205. category: string,
  206. outcome?: Partial<SubprocessOutcome>,
  207. ): string {
  208. const fields = [
  209. 'product: Claude Code',
  210. `stage: ${stage}`,
  211. `category: ${category}`,
  212. ]
  213. if (outcome?.exitCode !== null && outcome?.exitCode !== undefined) {
  214. fields.push(`exit code: ${outcome.exitCode}`)
  215. }
  216. if (outcome?.signal !== null && outcome?.signal !== undefined) {
  217. fields.push(`signal: ${outcome.signal}`)
  218. }
  219. return `Product subagent failure (${fields.join('; ')})`
  220. }
  221. function permissionDenied(): SDKPermissionDeniedMessage {
  222. return {
  223. type: 'system',
  224. subtype: 'permission_denied',
  225. tool_name: 'Bash',
  226. tool_use_id: 'tool-secret',
  227. decision_reason_type: 'mode',
  228. decision_reason: 'contains /private/secret.txt',
  229. message: 'command with SECRET_TOKEN was denied',
  230. uuid: '00000000-0000-4000-8000-000000000001',
  231. session_id: 'session-secret',
  232. }
  233. }
  234. function queryFrom(
  235. messages: readonly SDKMessage[],
  236. after?: Error,
  237. close = vi.fn(),
  238. ): Query {
  239. async function* stream(): AsyncGenerator<SDKMessage, void> {
  240. for (const message of messages) yield message
  241. if (after !== undefined) throw after
  242. }
  243. return Object.assign(stream(), { close }) as unknown as Query
  244. }
  245. function waitingQuery(signal: AbortSignal, close = vi.fn()): Query {
  246. async function* stream(): AsyncGenerator<SDKMessage, void> {
  247. await new Promise<never>((_resolve, reject) => {
  248. const fail = (): void => {
  249. reject(signal.reason instanceof Error
  250. ? signal.reason
  251. : new Error(String(signal.reason)))
  252. }
  253. if (signal.aborted) fail()
  254. else signal.addEventListener('abort', fail, { once: true })
  255. })
  256. }
  257. return Object.assign(stream(), { close }) as unknown as Query
  258. }
  259. function sdkSpawnOptions(
  260. overrides: Partial<SpawnOptions> = {},
  261. ): SpawnOptions {
  262. return {
  263. command: '/sdk/claude',
  264. args: ['--output-format', 'stream-json'],
  265. cwd: '/workspace',
  266. env: { PATH: '/bin', OMITTED: undefined },
  267. signal: new AbortController().signal,
  268. ...overrides,
  269. }
  270. }
  271. interface FakeRun {
  272. readonly child: FakeChild
  273. readonly close: ReturnType<typeof vi.fn>
  274. readonly spawnSpecs: SubprocessSpawnSpec[]
  275. readonly options: Options[]
  276. readonly spec: ClaudeCodeRunSpec
  277. }
  278. function fakeRun(
  279. messages: readonly SDKMessage[] = [success()],
  280. after?: Error,
  281. child = fakeChild(),
  282. ): FakeRun {
  283. const close = vi.fn()
  284. const query = queryFrom(messages, after, close)
  285. const spawnSpecs: SubprocessSpawnSpec[] = []
  286. const options: FakeRun['options'] = []
  287. const spec: ClaudeCodeRunSpec = {
  288. cwd: '/workspace',
  289. permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  290. env: { ANTHROPIC_API_KEY: 'fake-key' },
  291. disposeGraceMs: 5,
  292. spawn: (spawnSpec) => {
  293. spawnSpecs.push(spawnSpec)
  294. return child.handle
  295. },
  296. }
  297. queryMock.mockImplementation((params) => {
  298. options.push(params.options)
  299. params.options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  300. return query
  301. })
  302. return { child, close, spawnSpecs, options, spec }
  303. }
  304. beforeEach(() => {
  305. queryMock.mockImplementation(({ options }) => {
  306. options.spawnClaudeCodeProcess!(sdkSpawnOptions({
  307. cwd: options.cwd!,
  308. env: options.env!,
  309. signal: options.abortController!.signal,
  310. }))
  311. return queryFrom([])
  312. })
  313. })
  314. afterEach(() => {
  315. queryMock.mockReset()
  316. vi.restoreAllMocks()
  317. vi.unstubAllEnvs()
  318. })
  319. describe('task admission and package contracts', () => {
  320. it('ships one independently installable provider-only Bundle patch', () => {
  321. const root = fileURLToPath(new URL('..', import.meta.url))
  322. const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as {
  323. dependencies?: Record<string, string>
  324. files?: string[]
  325. dsh?: { bundle?: { patch?: string } }
  326. }
  327. expect(manifest.dsh?.bundle?.patch).toBe('./cordis.patch.yml')
  328. expect(manifest.files).toContain('cordis.patch.yml')
  329. expect(manifest.dependencies).toHaveProperty(
  330. '@anthropic-ai/claude-agent-sdk',
  331. CLAUDE_AGENT_SDK_VERSION,
  332. )
  333. expect(manifest.dependencies).toHaveProperty(
  334. '@modelcontextprotocol/sdk',
  335. '^1.29.0',
  336. )
  337. expect(manifest.dependencies).toHaveProperty('zod', '^4.4.3')
  338. expect(manifest.dependencies).not.toHaveProperty('@deepseek-ai/dsh-subagent-codex')
  339. const sdkRoot = dirname(fileURLToPath(
  340. import.meta.resolve('@anthropic-ai/claude-agent-sdk'),
  341. ))
  342. const sdkManifest = JSON.parse(readFileSync(
  343. resolve(sdkRoot, 'package.json'),
  344. 'utf8',
  345. )) as {
  346. version: string
  347. claudeCodeVersion: string
  348. optionalDependencies: Record<string, string>
  349. }
  350. expect(sdkManifest.version).toBe(CLAUDE_AGENT_SDK_VERSION)
  351. expect(sdkManifest.claudeCodeVersion).toBe(CLAUDE_CODE_VERSION)
  352. expect(sdkManifest.optionalDependencies).toEqual(Object.fromEntries(
  353. CLAUDE_PLATFORM_PACKAGES.map(packageName => [
  354. packageName,
  355. CLAUDE_AGENT_SDK_VERSION,
  356. ]),
  357. ))
  358. const lockfile = readFileSync(resolve(root, '../../../pnpm-lock.yaml'), 'utf8')
  359. for (const packageName of CLAUDE_PLATFORM_PACKAGES) {
  360. expect(lockfile).toContain(
  361. ` '${packageName}@${CLAUDE_AGENT_SDK_VERSION}':`,
  362. )
  363. expect(lockfile).toContain(
  364. ` '${packageName}': ${CLAUDE_AGENT_SDK_VERSION}`,
  365. )
  366. }
  367. const parsed = yaml.load(readFileSync(resolve(root, manifest.dsh!.bundle!.patch!), 'utf8'))
  368. const rows = Array.isArray(parsed)
  369. ? (parsed as Array<{ insert?: Array<{ id?: string; name?: string }> }>).flatMap(entry => entry.insert ?? [])
  370. : []
  371. expect(rows).toEqual([{
  372. id: 'subagent-claude-code',
  373. name: '@deepseek-ai/dsh-subagent-claude-code',
  374. }])
  375. expect(JSON.stringify(rows)).not.toContain('tool-subagent')
  376. })
  377. it('preserves text sequences and rejects empty, blank, and non-text tasks', () => {
  378. expect(textTask([
  379. { type: 'text', text: 'one' },
  380. { type: 'text', text: 'two' },
  381. ])).toBe('onetwo')
  382. expect(() => textTask([])).toThrow('only text blocks')
  383. expect(() => textTask([{ type: 'reasoning', text: 'hidden' }]))
  384. .toThrow('only text blocks')
  385. expect(() => textTask([{ type: 'text', text: ' \n ' }]))
  386. .toThrow('must not be empty')
  387. })
  388. it('registers the default descriptor, validates config, and unregisters on HMR', async () => {
  389. const ctx = new Context()
  390. await ctx.plugin(SubagentRuntime)
  391. await ctx.plugin(LocalSubprocessRuntime)
  392. const fiber = await ctx.plugin(claudeCode, {})
  393. expect(ctx.subagents.getProvider('claude-code')).toMatchObject({
  394. name: 'claude-code',
  395. capabilities: {
  396. outputSchema: false,
  397. depthLimit: false,
  398. toolFilter: false,
  399. persona: false,
  400. },
  401. inheritsParentContext: false,
  402. })
  403. expect(ctx.subagents.list()).toEqual(['claude-code'])
  404. await fiber.dispose()
  405. expect(ctx.subagents.list()).toEqual([])
  406. for (const disposeGraceMs of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
  407. await expect(ctx.plugin(claudeCode, { disposeGraceMs }))
  408. .rejects.toThrow('disposeGraceMs must be a positive finite number')
  409. }
  410. await expect(ctx.plugin(claudeCode, {
  411. disposeGraceMs: MAX_TIMER_DELAY_MS + 1,
  412. })).rejects.toThrow(
  413. `disposeGraceMs must be no greater than ${MAX_TIMER_DELAY_MS}`,
  414. )
  415. await ctx.fiber.dispose()
  416. })
  417. it('keeps named instances, runs, and HMR ownership isolated', async () => {
  418. const ctx = new Context()
  419. await ctx.plugin(SubagentRuntime)
  420. await ctx.plugin(LocalSubprocessRuntime)
  421. const safeChild = fakeChild()
  422. const bypassChild = fakeChild()
  423. const spawnSpecs: SubprocessSpawnSpec[] = []
  424. vi.spyOn(ctx.subprocess, 'spawn').mockImplementation((spec) => {
  425. spawnSpecs.push(spec)
  426. return spec.env?.DSH_CLAUDE_INSTANCE === 'safe'
  427. ? safeChild.handle
  428. : bypassChild.handle
  429. })
  430. const queryOptions: Options[] = []
  431. queryMock.mockImplementation(({ options }) => {
  432. queryOptions.push(options)
  433. options.spawnClaudeCodeProcess!(sdkSpawnOptions({
  434. cwd: options.cwd!,
  435. env: options.env!,
  436. signal: options.abortController!.signal,
  437. }))
  438. return options.permissionMode === 'dontAsk'
  439. ? waitingQuery(options.abortController!.signal)
  440. : queryFrom([success('bypass answer')])
  441. })
  442. const added: string[] = []
  443. const started: string[] = []
  444. const ended: string[] = []
  445. const removed: string[] = []
  446. ctx.on('subagent/provider-added', provider => void added.push(provider.name))
  447. ctx.on('subagent/start', info => void started.push(info.provider))
  448. ctx.on('subagent/end', info => void ended.push(info.provider))
  449. ctx.on('subagent/provider-removed', providerName => void removed.push(providerName))
  450. const safeFiber = await ctx.plugin(claudeCode, {
  451. providerName: 'claude-safe',
  452. env: { DSH_CLAUDE_INSTANCE: 'safe' },
  453. permissionMode: 'dontAsk',
  454. disposeGraceMs: 11,
  455. })
  456. const bypassFiber = await ctx.plugin(claudeCode, {
  457. providerName: 'claude-bypass',
  458. env: { DSH_CLAUDE_INSTANCE: 'bypass' },
  459. permissionMode: 'bypassPermissions',
  460. disposeGraceMs: 29,
  461. })
  462. expect(ctx.subagents.list()).toEqual(['claude-safe', 'claude-bypass'])
  463. expect(added).toEqual(['claude-safe', 'claude-bypass'])
  464. const safeController = new AbortController()
  465. const [safeRun, bypassRun] = await Promise.all([
  466. ctx.subagents.start('claude-safe', request(undefined, safeController.signal)),
  467. ctx.subagents.start('claude-bypass', request()),
  468. ])
  469. await safeFiber.dispose()
  470. expect(ctx.subagents.list()).toEqual(['claude-bypass'])
  471. expect(removed).toEqual(['claude-safe'])
  472. await expect(ctx.subagents.start('claude-safe', request()))
  473. .rejects.toMatchObject({ code: 'NO_PROVIDER' })
  474. await expect(bypassRun.result).resolves.toEqual({
  475. output: [{ type: 'text', text: 'bypass answer' }],
  476. stopReason: 'completed',
  477. })
  478. safeController.abort(new Error('stop only the safe instance'))
  479. await expect(safeRun.result).resolves.toEqual({
  480. output: [],
  481. stopReason: 'aborted',
  482. })
  483. expect(queryOptions.map(options => ({
  484. instance: options.env?.DSH_CLAUDE_INSTANCE,
  485. permissionMode: options.permissionMode,
  486. }))).toEqual([
  487. { instance: 'safe', permissionMode: 'dontAsk' },
  488. { instance: 'bypass', permissionMode: 'bypassPermissions' },
  489. ])
  490. expect(spawnSpecs.map(spec => ({
  491. instance: spec.env?.DSH_CLAUDE_INSTANCE,
  492. graceMs: spec.graceMs,
  493. }))).toEqual([
  494. { instance: 'safe', graceMs: 11 },
  495. { instance: 'bypass', graceMs: 29 },
  496. ])
  497. await Promise.all([safeRun.dispose(), bypassRun.dispose()])
  498. expect([...started].sort()).toEqual(['claude-bypass', 'claude-safe'])
  499. expect([...ended].sort()).toEqual(['claude-bypass', 'claude-safe'])
  500. expect(safeChild.terminate).toHaveBeenCalledOnce()
  501. expect(bypassChild.terminate).toHaveBeenCalledOnce()
  502. await bypassFiber.dispose()
  503. expect(removed).toEqual(['claude-safe', 'claude-bypass'])
  504. await ctx.fiber.dispose()
  505. })
  506. it('rejects duplicate provider names without replacing the first instance', async () => {
  507. const ctx = new Context()
  508. await ctx.plugin(SubagentRuntime)
  509. await ctx.plugin(LocalSubprocessRuntime)
  510. const firstFiber = await ctx.plugin(claudeCode, {
  511. providerName: 'claude-duplicate',
  512. })
  513. const first = ctx.subagents.getProvider('claude-duplicate')
  514. await expect(ctx.plugin(claudeCode, {
  515. providerName: 'claude-duplicate',
  516. permissionMode: 'bypassPermissions',
  517. })).rejects.toMatchObject({ code: 'DUPLICATE_PROVIDER' })
  518. expect(ctx.subagents.getProvider('claude-duplicate')).toBe(first)
  519. expect(ctx.subagents.list()).toEqual(['claude-duplicate'])
  520. await firstFiber.dispose()
  521. await ctx.fiber.dispose()
  522. })
  523. it('accepts only the five fixed non-interactive permission modes', () => {
  524. expect(claudeCode.Config({}).providerName).toBe('claude-code')
  525. expect(claudeCode.Config({ providerName: 'claude-safe' }).providerName)
  526. .toBe('claude-safe')
  527. expect(() => claudeCode.Config({ providerName: '' })).toThrow()
  528. expect(claudeCode.Config({}).permissionMode)
  529. .toBe(DEFAULT_CLAUDE_CODE_PERMISSION_MODE)
  530. for (const permissionMode of CLAUDE_CODE_PERMISSION_MODES) {
  531. expect(claudeCode.Config({ permissionMode }).permissionMode)
  532. .toBe(permissionMode)
  533. }
  534. for (const permissionMode of ['default', 'interactive', 'future-mode']) {
  535. expect(() => claudeCode.Config({ permissionMode } as never)).toThrow()
  536. }
  537. })
  538. it('resolves the safe permission default when apply is called directly', async () => {
  539. const ctx = new Context()
  540. await ctx.plugin(SubagentRuntime)
  541. await ctx.plugin(LocalSubprocessRuntime)
  542. claudeCode.apply(ctx, { env: {}, disposeGraceMs: 3_000 })
  543. expect(ctx.subagents.getProvider('claude-code')).toBeDefined()
  544. await ctx.fiber.dispose()
  545. })
  546. it('starts through the registered provider with its resolved config and diagnostics', async () => {
  547. const ctx = new Context()
  548. await ctx.plugin(SubagentRuntime)
  549. await ctx.plugin(LocalSubprocessRuntime)
  550. const child = fakeChild()
  551. const spawn = vi.spyOn(ctx.subprocess, 'spawn')
  552. .mockImplementation(() => child.handle)
  553. const resolveExecutable = vi.spyOn(ctx.subprocess, 'resolveExecutable')
  554. .mockResolvedValue('/host/bin/claude')
  555. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  556. await ctx.plugin(claudeCode, {
  557. providerName: 'claude-diagnostic',
  558. env: {
  559. ANTHROPIC_API_KEY: 'provider-fake-key',
  560. CLAUDE_CONFIG_DIR: '/private/tmp/dsh-claude-code-unit-config',
  561. HOME: '/private/tmp/dsh-claude-code-unit-home',
  562. },
  563. permissionMode: 'auto',
  564. disposeGraceMs: 29,
  565. })
  566. await expect(ctx.subagents.start('claude-diagnostic', {
  567. ...request(),
  568. parent: {
  569. id: 'parent-without-cwd',
  570. session: { header: {} },
  571. } as unknown as Agent,
  572. })).rejects.toThrow(
  573. 'subagent-claude-code: no working directory for the child — delegate from a parent session that has one',
  574. )
  575. expect(queryMock).not.toHaveBeenCalled()
  576. const invalidCwdParent = {
  577. id: 'parent-with-invalid-cwd',
  578. session: { header: { cwd: 'relative/SECRET_TOKEN' } },
  579. } as unknown as Agent
  580. const invalidCwd = ctx.subagents.start('claude-diagnostic', {
  581. ...request(),
  582. parent: invalidCwdParent,
  583. })
  584. await expect(invalidCwd)
  585. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  586. await expect(invalidCwd).rejects.not.toThrow('relative/SECRET_TOKEN')
  587. expect(warn).toHaveBeenCalledWith(
  588. 'subagent-claude-code "claude-diagnostic": child start failed: %o',
  589. expect.any(Error),
  590. )
  591. expect(errorCause(warn.mock.calls[0]?.[1] as unknown)?.message)
  592. .toContain('relative/SECRET_TOKEN')
  593. const invalidCwdAbort = new AbortController()
  594. invalidCwdAbort.abort(new Error('cancel invalid cwd startup'))
  595. await expect(ctx.subagents.start('claude-diagnostic', {
  596. ...request(undefined, invalidCwdAbort.signal),
  597. parent: invalidCwdParent,
  598. })).rejects.toThrow('aborted before SDK startup')
  599. expect(queryMock).not.toHaveBeenCalled()
  600. warn.mockClear()
  601. vi.stubEnv('PATH', '/host/bin')
  602. queryMock.mockImplementationOnce(() => {
  603. throw new Error(
  604. 'Native CLI binary for fixture-platform not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.',
  605. )
  606. })
  607. const missingPayload = ctx.subagents.start('claude-diagnostic', request())
  608. await expect(missingPayload)
  609. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  610. await expect(missingPayload).rejects.not.toThrow('Native CLI binary')
  611. expect(warn).toHaveBeenCalledWith(
  612. expect.stringContaining(
  613. 'subagent-claude-code "claude-diagnostic": child run failed (error):',
  614. ),
  615. expect.any(Error),
  616. )
  617. expect(errorCause(warn.mock.calls[0]?.[1] as unknown)?.message)
  618. .toContain('Native CLI binary for fixture-platform not found')
  619. expect(resolveExecutable).not.toHaveBeenCalled()
  620. const run = await ctx.subagents.start('claude-diagnostic', request())
  621. child.settle({ exitCode: 9, signal: null })
  622. child.stdout.end()
  623. await expect(run.result).resolves.toEqual({
  624. output: [],
  625. diagnostic: expectedFailureDiagnostic('query-run', 'missing-result'),
  626. stopReason: 'error',
  627. })
  628. expect(warn).toHaveBeenCalledWith(
  629. expect.stringContaining(
  630. 'subagent-claude-code "claude-diagnostic": child run failed (error):',
  631. ),
  632. expect.any(Error),
  633. )
  634. expect(resolveExecutable).not.toHaveBeenCalled()
  635. expect(queryMock.mock.calls[1]?.[0].options)
  636. .not.toHaveProperty('pathToClaudeCodeExecutable')
  637. expect(queryMock.mock.calls[1]?.[0].options.permissionMode).toBe('auto')
  638. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  639. cwd: process.cwd(),
  640. graceMs: 29,
  641. }))
  642. expect(spawn.mock.calls[0]?.[0].env).toMatchObject({
  643. ANTHROPIC_API_KEY: 'provider-fake-key',
  644. })
  645. await run.dispose()
  646. await ctx.fiber.dispose()
  647. })
  648. it('keeps the Loader namespace shape and package-owned empty invariant', async () => {
  649. expect('default' in claudeCode).toBe(false)
  650. expect(claudeCode.name).toBe('subagent-claude-code')
  651. expect(claudeCode.inject).toEqual(['subagents', 'subprocess'])
  652. const loader = Object.create(Loader.prototype) as Loader
  653. expect(loader.unwrapExports(claudeCode)).toBe(claudeCode)
  654. const dispose = vi.fn()
  655. const register = vi.fn((
  656. _packageName: string,
  657. _installer: InvariantInstaller,
  658. ) => dispose)
  659. const ctx = { invariants: { register } } as unknown as Context
  660. await expect(invariant.apply(ctx)).resolves.toBe(dispose)
  661. expect(register).toHaveBeenCalledWith(
  662. '@deepseek-ai/dsh-subagent-claude-code',
  663. expect.any(Function),
  664. )
  665. const install = register.mock.calls[0]![1]
  666. await install(new Context(), (message) => { throw new Error(message) })
  667. expect(invariant.name).toBe('subagent-claude-code-invariant')
  668. expect(invariant.inject).toEqual(['invariants'])
  669. })
  670. })
  671. describe('official spawn projection', () => {
  672. it('forwards command, arguments, cwd, environment, and signal exactly', () => {
  673. vi.stubEnv('SDK_REMOVED_AMBIENT', 'ambient-value')
  674. const signal = new AbortController().signal
  675. const options = sdkSpawnOptions({
  676. command: '/official/claude',
  677. args: ['--one', 'two'],
  678. cwd: '/parent/workspace',
  679. env: { A: 'one', B: undefined, C: 'three' },
  680. signal,
  681. })
  682. expect(sdkEnvironmentOverlay(options.env)).toEqual(expect.objectContaining({
  683. A: 'one',
  684. B: undefined,
  685. C: 'three',
  686. SDK_REMOVED_AMBIENT: undefined,
  687. }))
  688. const spawnSpec = claudeSpawnSpec(options, 321)
  689. expect(spawnSpec).toMatchObject({
  690. argv: ['/official/claude', '--one', 'two'],
  691. cwd: '/parent/workspace',
  692. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' },
  693. graceMs: 321,
  694. signal,
  695. })
  696. expect(spawnSpec.env).toEqual(expect.objectContaining({
  697. A: 'one',
  698. B: undefined,
  699. C: 'three',
  700. SDK_REMOVED_AMBIENT: undefined,
  701. }))
  702. const missingCwd = sdkSpawnOptions()
  703. delete missingCwd.cwd
  704. expect(() => claudeSpawnSpec(
  705. missingCwd,
  706. 321,
  707. )).toThrow('SDK spawn request omitted its workspace')
  708. expect(() => claudeSpawnSpec(
  709. sdkSpawnOptions({ cwd: '' }),
  710. 321,
  711. )).toThrow('SDK spawn request omitted its workspace')
  712. })
  713. it('forwards the SDK-selected Windows native executable without a batch shim', () => {
  714. const command = String.raw`C:\Program Files\Claude\claude.exe`
  715. const spec = claudeSpawnSpec(sdkSpawnOptions({
  716. command,
  717. args: ['--output-format', 'stream-json'],
  718. }), 7)
  719. expect(spec.argv).toEqual([
  720. command, '--output-format', 'stream-json',
  721. ])
  722. })
  723. it('projects streams, exit facts, listeners, and idempotent tree termination', async () => {
  724. const child = fakeChild({ exitOnTerminate: false })
  725. const process = new ManagedClaudeCodeProcess(child.handle)
  726. expect(process.stdin).toBe(child.stdin)
  727. expect(process.stdout).toBe(child.stdout)
  728. expect(process.killed).toBe(false)
  729. expect(process.exitCode).toBeNull()
  730. expect(process.signalCode).toBeNull()
  731. expect(process.outcome).toBeUndefined()
  732. const exit = vi.fn()
  733. const once = vi.fn()
  734. const removed = vi.fn()
  735. process.on('exit', exit)
  736. process.once('exit', once)
  737. process.on('exit', removed)
  738. process.off('exit', removed)
  739. expect(process.kill('SIGTERM')).toBe(true)
  740. expect(process.killed).toBe(true)
  741. expect(process.kill('SIGKILL')).toBe(false)
  742. expect(child.terminate).toHaveBeenCalledOnce()
  743. child.settle({ exitCode: null, signal: 'SIGTERM' })
  744. await nextTask()
  745. expect(exit).toHaveBeenCalledWith(null, 'SIGTERM')
  746. expect(once).toHaveBeenCalledOnce()
  747. expect(removed).not.toHaveBeenCalled()
  748. expect(process.signalCode).toBe('SIGTERM')
  749. expect(process.outcome).toEqual({ exitCode: null, signal: 'SIGTERM' })
  750. expect(process.kill('SIGTERM')).toBe(false)
  751. })
  752. it('emits spawn errors', async () => {
  753. const child = fakeChild({ pid: -1 })
  754. const process = new ManagedClaudeCodeProcess(child.handle)
  755. const errorListener = vi.fn()
  756. const removed = vi.fn()
  757. process.once('error', errorListener)
  758. process.on('error', removed)
  759. process.off('error', removed)
  760. child.fail(new Error('spawn boom'))
  761. await nextTask()
  762. expect(errorListener).toHaveBeenCalledWith(expect.objectContaining({
  763. message: 'spawn boom',
  764. }))
  765. expect(removed).not.toHaveBeenCalled()
  766. })
  767. it('exposes a settled direct-child exit code', async () => {
  768. const child = fakeChild()
  769. const process = new ManagedClaudeCodeProcess(child.handle)
  770. child.settle({ exitCode: 7, signal: null })
  771. await nextTask()
  772. expect(process.exitCode).toBe(7)
  773. expect(process.signalCode).toBeNull()
  774. expect(process.outcome).toEqual({ exitCode: 7, signal: null })
  775. expect(process.kill('SIGTERM')).toBe(false)
  776. })
  777. })
  778. describe('query options and result mapping', () => {
  779. it('builds the fixed unattended options over the scrubbed environment', async () => {
  780. vi.stubEnv('HOST_VISIBLE', 'visible')
  781. vi.stubEnv('HOST_SECRET_TOKEN', 'must-not-leak')
  782. vi.stubEnv('DSH_INTERNAL', 'must-not-leak')
  783. const child = fakeChild()
  784. const spawn = vi.fn(() => child.handle)
  785. const captured: SubprocessHandle[] = []
  786. const diagnostics: string[] = []
  787. const spec: ClaudeCodeRunSpec = {
  788. cwd: '/workspace',
  789. permissionMode: 'acceptEdits',
  790. env: {
  791. HOST_VISIBLE: 'overridden',
  792. ANTHROPIC_API_KEY: 'explicit-fake-key',
  793. },
  794. disposeGraceMs: 17,
  795. spawn,
  796. }
  797. const controller = new AbortController()
  798. const options = claudeQueryOptions(
  799. spec,
  800. controller,
  801. (value) => {
  802. captured.push(value)
  803. },
  804. value => diagnostics.push(value),
  805. )
  806. expect(options).toMatchObject({
  807. abortController: controller,
  808. cwd: '/workspace',
  809. persistSession: false,
  810. disallowedTools: ['AskUserQuestion'],
  811. permissionMode: 'acceptEdits',
  812. supportedDialogKinds: ['refusal_fallback_prompt'],
  813. })
  814. expect(options).not.toHaveProperty('pathToClaudeCodeExecutable')
  815. expect(options).not.toHaveProperty('allowDangerouslySkipPermissions')
  816. expect(options.env).toMatchObject({
  817. HOST_VISIBLE: 'overridden',
  818. ANTHROPIC_API_KEY: 'explicit-fake-key',
  819. })
  820. expect(options.env).not.toHaveProperty('HOST_SECRET_TOKEN')
  821. expect(options.env).not.toHaveProperty('DSH_INTERNAL')
  822. expect(options).not.toHaveProperty('settingSources')
  823. const callbackSignal = new AbortController().signal
  824. await expect(options.canUseTool!(
  825. 'Bash',
  826. { command: 'cat /private/secret.txt', token: 'SECRET_TOKEN' },
  827. {
  828. signal: callbackSignal,
  829. toolUseID: 'tool-1',
  830. requestId: 'request-1',
  831. blockedPath: '/private/secret.txt',
  832. decisionReason: 'SECRET_TOKEN in /private/secret.txt',
  833. },
  834. )).resolves.toEqual({
  835. behavior: 'deny',
  836. message: 'This unattended Claude Code subagent cannot request human approval.',
  837. })
  838. await expect(options.onElicitation!(
  839. {
  840. serverName: 'private-server',
  841. message: 'enter SECRET_TOKEN',
  842. requestedSchema: { secret: true },
  843. },
  844. { signal: callbackSignal },
  845. )).resolves.toEqual({ action: 'decline' })
  846. await expect(options.onUserDialog!(
  847. {
  848. dialogKind: 'refusal_fallback_prompt',
  849. payload: { path: '/private/secret.txt', token: 'SECRET_TOKEN' },
  850. },
  851. { signal: callbackSignal },
  852. )).resolves.toEqual({ behavior: 'cancelled' })
  853. expect(diagnostics).toEqual([
  854. 'Claude Code unattended decision (mode: acceptEdits; request: tool permission; decision: denied): the provider does not request human approval',
  855. 'Claude Code unattended decision (mode: acceptEdits; request: MCP elicitation; decision: declined): the provider does not collect interactive MCP input',
  856. 'Claude Code unattended decision (mode: acceptEdits; request: user dialog; decision: cancelled): the provider does not render blocking dialogs',
  857. ])
  858. expect(diagnostics.join('\n')).not.toContain('SECRET_TOKEN')
  859. expect(diagnostics.join('\n')).not.toContain('/private/secret.txt')
  860. const spawned = options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  861. expect(spawned).toBeInstanceOf(ManagedClaudeCodeProcess)
  862. expect(captured).toEqual([child.handle])
  863. expect(spawn).toHaveBeenCalledWith(expect.objectContaining({
  864. argv: ['/sdk/claude', '--output-format', 'stream-json'],
  865. cwd: '/workspace',
  866. graceMs: 17,
  867. }))
  868. })
  869. it.each(CLAUDE_CODE_PERMISSION_MODES)(
  870. 'maps the %s mode and only confirms the dangerous bypass',
  871. (permissionMode) => {
  872. const child = fakeChild()
  873. const options = claudeQueryOptions({
  874. cwd: '/workspace',
  875. permissionMode,
  876. env: {},
  877. disposeGraceMs: 17,
  878. spawn: () => child.handle,
  879. }, new AbortController(), () => {}, () => {})
  880. expect(options.permissionMode).toBe(permissionMode)
  881. expect(options.disallowedTools).toEqual(permissionMode === 'plan'
  882. ? ['AskUserQuestion', 'ExitPlanMode']
  883. : ['AskUserQuestion'])
  884. if (permissionMode === 'bypassPermissions') {
  885. expect(options.allowDangerouslySkipPermissions).toBe(true)
  886. expect(options).not.toHaveProperty('canUseTool')
  887. } else {
  888. expect(options).not.toHaveProperty('allowDangerouslySkipPermissions')
  889. expect(options.canUseTool).toBeTypeOf('function')
  890. }
  891. },
  892. )
  893. it('disallows ExitPlanMode before native plan-mode allow rules', () => {
  894. const child = fakeChild()
  895. const options = claudeQueryOptions({
  896. cwd: '/workspace',
  897. permissionMode: 'plan',
  898. env: {},
  899. disposeGraceMs: 17,
  900. spawn: () => child.handle,
  901. }, new AbortController(), () => {}, () => {})
  902. expect(options.disallowedTools).toEqual([
  903. 'AskUserQuestion',
  904. 'ExitPlanMode',
  905. ])
  906. })
  907. it('accepts only a non-error success with a non-blank final result', () => {
  908. expect(successfulResult(success('exact final'))).toBe('exact final')
  909. expect(() => successfulResult(success('answer', true)))
  910. .toThrow(expectedFailureDiagnostic('query-run', 'invalid-success'))
  911. expect(() => successfulResult(success(' \n ')))
  912. .toThrow(expectedFailureDiagnostic('query-run', 'invalid-success'))
  913. const sdkFailure = () => successfulResult(failure(
  914. 'error_during_execution',
  915. ['SECRET_TOKEN', '/private/secret.txt'],
  916. ))
  917. expect(sdkFailure).toThrow(expectedFailureDiagnostic(
  918. 'query-run',
  919. 'error_during_execution',
  920. ))
  921. expect(sdkFailure).not.toThrow('SECRET_TOKEN')
  922. expect(sdkFailure).not.toThrow('/private/secret.txt')
  923. expect(() => successfulResult(failure(
  924. 'error_max_turns',
  925. [],
  926. ))).toThrow(expectedFailureDiagnostic('query-run', 'error_max_turns'))
  927. const unknown = {
  928. type: 'result',
  929. subtype: 'future_failure',
  930. is_error: true,
  931. errors: ['SECRET_TOKEN'],
  932. } as unknown as SDKResultMessage
  933. expect(() => successfulResult(unknown))
  934. .toThrow(expectedFailureDiagnostic('query-run', 'unknown'))
  935. expect(() => successfulResult(unknown)).not.toThrow('future_failure')
  936. expect(() => successfulResult(unknown)).not.toThrow('SECRET_TOKEN')
  937. })
  938. it('consumes the complete stream and keeps the latest strict success', async () => {
  939. const query = queryFrom([
  940. { type: 'system', subtype: 'init' } as SDKMessage,
  941. success('first'),
  942. success('last'),
  943. ])
  944. await expect(consumeClaudeQuery(query)).resolves.toEqual({
  945. output: [{ type: 'text', text: 'last' }],
  946. stopReason: 'completed',
  947. })
  948. await expect(consumeClaudeQuery(
  949. queryFrom([{ type: 'system', subtype: 'init' } as SDKMessage]),
  950. )).rejects.toThrow(expectedFailureDiagnostic('query-run', 'missing-result'))
  951. const onPermissionDenied = vi.fn()
  952. await expect(consumeClaudeQuery(queryFrom([
  953. permissionDenied(),
  954. success('after denial'),
  955. ]), onPermissionDenied)).resolves.toEqual({
  956. output: [{ type: 'text', text: 'after denial' }],
  957. stopReason: 'completed',
  958. })
  959. expect(onPermissionDenied).toHaveBeenCalledOnce()
  960. })
  961. })
  962. describe('run publication, cancellation, and settlement', () => {
  963. it('publishes only after Query and managed child exist, then disposes once', async () => {
  964. const fixture = fakeRun([success('exact answer')])
  965. const run = await startClaudeCodeRun(
  966. request([
  967. { type: 'text', text: 'first' },
  968. { type: 'text', text: 'second' },
  969. ]),
  970. fixture.spec,
  971. )
  972. expect(fixture.options).toHaveLength(1)
  973. expect(fixture.spawnSpecs).toHaveLength(1)
  974. await expect(run.result).resolves.toEqual({
  975. output: [{ type: 'text', text: 'exact answer' }],
  976. stopReason: 'completed',
  977. })
  978. const first = run.dispose()
  979. const second = run.dispose()
  980. expect(second).toBe(first)
  981. await first
  982. expect(fixture.close).toHaveBeenCalledOnce()
  983. expect(fixture.child.terminate).toHaveBeenCalledOnce()
  984. })
  985. it('flattens every SDK error result without inventing shared stop reasons', async () => {
  986. const subtypes: ErrorSubtype[] = [
  987. 'error_during_execution',
  988. 'error_max_turns',
  989. 'error_max_budget_usd',
  990. 'error_max_structured_output_retries',
  991. ]
  992. for (const subtype of subtypes) {
  993. const fixture = fakeRun([failure(subtype)])
  994. const onError = vi.fn()
  995. const run = await startClaudeCodeRun(
  996. request(),
  997. { ...fixture.spec, onError },
  998. )
  999. await expect(run.result).resolves.toEqual({
  1000. output: [],
  1001. diagnostic: expectedFailureDiagnostic('query-run', subtype),
  1002. stopReason: 'error',
  1003. })
  1004. expect(onError).toHaveBeenCalledWith(
  1005. expect.any(Error),
  1006. 'error',
  1007. )
  1008. await run.dispose()
  1009. }
  1010. })
  1011. it('attaches a safe diagnostic when a permission denial precedes failure', async () => {
  1012. const fixture = fakeRun([
  1013. permissionDenied(),
  1014. failure('error_during_execution'),
  1015. ])
  1016. const run = await startClaudeCodeRun(request(), fixture.spec)
  1017. const result = await run.result
  1018. expect(result).toEqual({
  1019. output: [],
  1020. diagnostic: `${expectedFailureDiagnostic('query-run', 'error_during_execution')}\nClaude Code unattended decision (mode: dontAsk; request: tool permission; decision: denied): Claude Code denied the request before an interactive prompt`,
  1021. stopReason: 'error',
  1022. })
  1023. expect(result.diagnostic).not.toContain('SECRET_TOKEN')
  1024. expect(result.diagnostic).not.toContain('/private/secret.txt')
  1025. await run.dispose()
  1026. })
  1027. it('omits captured diagnostics on success and isolates concurrent runs', async () => {
  1028. const children = [fakeChild(), fakeChild()]
  1029. let childIndex = 0
  1030. const spec: ClaudeCodeRunSpec = {
  1031. cwd: '/workspace',
  1032. permissionMode: 'dontAsk',
  1033. env: {},
  1034. disposeGraceMs: 5,
  1035. spawn: () => children[childIndex++]!.handle,
  1036. }
  1037. queryMock.mockImplementation(({ prompt, options }) => {
  1038. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1039. return prompt === 'denied then completed'
  1040. ? queryFrom([permissionDenied(), success('completed answer')])
  1041. : queryFrom([failure('error_during_execution')])
  1042. })
  1043. const [completed, failed] = await Promise.all([
  1044. startClaudeCodeRun(
  1045. request([{ type: 'text', text: 'denied then completed' }]),
  1046. spec,
  1047. ),
  1048. startClaudeCodeRun(
  1049. request([{ type: 'text', text: 'unrelated failure' }]),
  1050. spec,
  1051. ),
  1052. ])
  1053. await expect(completed.result).resolves.toEqual({
  1054. output: [{ type: 'text', text: 'completed answer' }],
  1055. stopReason: 'completed',
  1056. })
  1057. await expect(failed.result).resolves.toEqual({
  1058. output: [],
  1059. diagnostic: expectedFailureDiagnostic(
  1060. 'query-run',
  1061. 'error_during_execution',
  1062. ),
  1063. stopReason: 'error',
  1064. })
  1065. await Promise.all([completed.dispose(), failed.dispose()])
  1066. })
  1067. it('fails closed when iteration rejects after a result', async () => {
  1068. const child = fakeChild()
  1069. const outcome = { exitCode: 31, signal: null } as const
  1070. async function* stream(): AsyncGenerator<SDKMessage, void> {
  1071. yield success('partial final')
  1072. child.settle(outcome)
  1073. await Promise.resolve()
  1074. throw new Error('iterator boom')
  1075. }
  1076. queryMock.mockImplementation(({ options }) => {
  1077. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1078. return Object.assign(stream(), { close: vi.fn() }) as unknown as Query
  1079. })
  1080. const run = await startClaudeCodeRun(request(), {
  1081. cwd: '/workspace',
  1082. permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  1083. env: {},
  1084. disposeGraceMs: 5,
  1085. spawn: () => child.handle,
  1086. })
  1087. await expect(run.result).resolves.toEqual({
  1088. output: [],
  1089. diagnostic: expectedFailureDiagnostic('query-run', 'unknown', outcome),
  1090. stopReason: 'error',
  1091. })
  1092. await run.dispose()
  1093. })
  1094. it('maps invalid success and missing result to fixed query-run facts', async () => {
  1095. for (const [messages, category] of [
  1096. [[success('answer', true)], 'invalid-success'],
  1097. [[success('')], 'invalid-success'],
  1098. [[{ type: 'system', subtype: 'init' } as SDKMessage], 'missing-result'],
  1099. ] as const) {
  1100. const fixture = fakeRun(messages)
  1101. const run = await startClaudeCodeRun(request(), fixture.spec)
  1102. await expect(run.result).resolves.toEqual({
  1103. output: [],
  1104. diagnostic: expectedFailureDiagnostic('query-run', category),
  1105. stopReason: 'error',
  1106. })
  1107. await run.dispose()
  1108. }
  1109. })
  1110. it('reports an early process exit with independent code and signal facts', async () => {
  1111. const outcomes: SubprocessOutcome[] = [
  1112. { exitCode: 23, signal: null },
  1113. { exitCode: null, signal: 'SIGABRT' },
  1114. { exitCode: null, signal: null },
  1115. ]
  1116. for (const outcome of outcomes) {
  1117. const child = fakeChild()
  1118. async function* stream(): AsyncGenerator<SDKMessage, void> {
  1119. child.settle(outcome)
  1120. await Promise.resolve()
  1121. throw new Error('SECRET_TOKEN from process transport')
  1122. }
  1123. queryMock.mockImplementation(({ options }) => {
  1124. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1125. return Object.assign(stream(), { close: vi.fn() }) as unknown as Query
  1126. })
  1127. const run = await startClaudeCodeRun(request(), {
  1128. cwd: '/workspace',
  1129. permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  1130. env: {},
  1131. disposeGraceMs: 5,
  1132. spawn: () => child.handle,
  1133. })
  1134. const result = await run.result
  1135. expect(result).toEqual({
  1136. output: [],
  1137. diagnostic: expectedFailureDiagnostic(
  1138. 'process',
  1139. 'process-exit',
  1140. outcome,
  1141. ),
  1142. stopReason: 'error',
  1143. })
  1144. expect(result.diagnostic).not.toContain('SECRET_TOKEN')
  1145. await run.dispose()
  1146. }
  1147. })
  1148. it('gives local cancellation precedence and isolates overlapping controllers', async () => {
  1149. const firstChild = fakeChild()
  1150. const secondChild = fakeChild()
  1151. const children = [firstChild, secondChild]
  1152. const controllers: AbortController[] = []
  1153. let index = 0
  1154. const spec: ClaudeCodeRunSpec = {
  1155. cwd: '/workspace',
  1156. permissionMode: 'dontAsk',
  1157. env: {},
  1158. disposeGraceMs: 5,
  1159. spawn: () => children[index++]!.handle,
  1160. }
  1161. queryMock.mockImplementation(({ prompt, options }) => {
  1162. controllers.push(options.abortController!)
  1163. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1164. return prompt === 'wait'
  1165. ? waitingQuery(options.abortController!.signal)
  1166. : queryFrom([success('second answer')])
  1167. })
  1168. const firstAbort = new AbortController()
  1169. const first = await startClaudeCodeRun(
  1170. request([{ type: 'text', text: 'wait' }], firstAbort.signal),
  1171. spec,
  1172. )
  1173. const second = await startClaudeCodeRun(
  1174. request([{ type: 'text', text: 'finish' }]),
  1175. spec,
  1176. )
  1177. expect(controllers).toHaveLength(2)
  1178. expect(controllers[0]).not.toBe(controllers[1])
  1179. firstAbort.abort(new Error('parent cancelled'))
  1180. await expect(first.result).resolves.toEqual({
  1181. output: [],
  1182. stopReason: 'aborted',
  1183. })
  1184. await expect(second.result).resolves.toEqual({
  1185. output: [{ type: 'text', text: 'second answer' }],
  1186. stopReason: 'completed',
  1187. })
  1188. expect(controllers[1]!.signal.aborted).toBe(false)
  1189. await Promise.all([first.dispose(), second.dispose()])
  1190. })
  1191. it('keeps local cancellation authoritative when the SDK iterator ends normally', async () => {
  1192. const parentAbort = new AbortController()
  1193. const child = fakeChild()
  1194. async function* stream(): AsyncGenerator<SDKMessage, void> {
  1195. yield success('candidate answer')
  1196. parentAbort.abort(new Error('parent cancelled at iterator completion'))
  1197. }
  1198. queryMock.mockImplementation(({ options }) => {
  1199. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1200. return Object.assign(stream(), { close: vi.fn() }) as unknown as Query
  1201. })
  1202. const run = await startClaudeCodeRun(
  1203. request(undefined, parentAbort.signal),
  1204. {
  1205. cwd: '/workspace',
  1206. permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  1207. env: {},
  1208. disposeGraceMs: 5,
  1209. spawn: () => child.handle,
  1210. },
  1211. )
  1212. await expect(run.result).resolves.toEqual({
  1213. output: [],
  1214. stopReason: 'aborted',
  1215. })
  1216. await run.dispose()
  1217. })
  1218. it('rejects pre-abort and every incomplete startup transaction', async () => {
  1219. const preAborted = new AbortController()
  1220. preAborted.abort()
  1221. const unused = fakeRun()
  1222. await expect(startClaudeCodeRun(
  1223. request(undefined, preAborted.signal),
  1224. unused.spec,
  1225. )).rejects.toThrow('aborted before SDK startup')
  1226. expect(unused.options).toEqual([])
  1227. const noChildClose = vi.fn()
  1228. queryMock.mockImplementationOnce(
  1229. () => queryFrom([], undefined, noChildClose),
  1230. )
  1231. await expect(startClaudeCodeRun(request(), {
  1232. ...unused.spec,
  1233. })).rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1234. expect(noChildClose).toHaveBeenCalledOnce()
  1235. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  1236. queryMock.mockImplementationOnce(
  1237. () => queryFrom([], undefined, closeFailure),
  1238. )
  1239. const noChild = startClaudeCodeRun(request(), {
  1240. ...unused.spec,
  1241. })
  1242. await expect(noChild)
  1243. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1244. await expect(noChild).rejects.toThrow(
  1245. `${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1246. )
  1247. await expect(noChild).rejects.toBeInstanceOf(AggregateError)
  1248. const startupAbort = new AbortController()
  1249. const abortedChild = fakeChild()
  1250. const abortedClose = vi.fn()
  1251. queryMock.mockImplementationOnce(({ options }) => {
  1252. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1253. startupAbort.abort(new Error('startup cancelled'))
  1254. return queryFrom([], undefined, abortedClose)
  1255. })
  1256. const abortedDuringStartup = startClaudeCodeRun(
  1257. request(undefined, startupAbort.signal),
  1258. {
  1259. ...unused.spec,
  1260. spawn: () => abortedChild.handle,
  1261. },
  1262. )
  1263. await expect(abortedDuringStartup)
  1264. .rejects.toThrow('aborted before SDK startup')
  1265. expect(abortedClose).toHaveBeenCalledOnce()
  1266. expect(abortedChild.terminate).toHaveBeenCalledOnce()
  1267. const cleanupAbort = new AbortController()
  1268. const cleanupFailedChild = fakeChild({
  1269. waitForExitError: new Error('SECRET_TOKEN cleanup wait failure'),
  1270. })
  1271. queryMock.mockImplementationOnce(({ options }) => {
  1272. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1273. cleanupAbort.abort(new Error('startup cancelled'))
  1274. return queryFrom([])
  1275. })
  1276. const cancelledCleanupFailure = startClaudeCodeRun(
  1277. request(undefined, cleanupAbort.signal),
  1278. {
  1279. ...unused.spec,
  1280. spawn: () => cleanupFailedChild.handle,
  1281. },
  1282. )
  1283. await expect(cancelledCleanupFailure)
  1284. .rejects.toBeInstanceOf(AggregateError)
  1285. await expect(cancelledCleanupFailure)
  1286. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1287. await expect(cancelledCleanupFailure).rejects.toThrow(
  1288. `${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown', { exitCode: 0, signal: null })}`,
  1289. )
  1290. await expect(cancelledCleanupFailure)
  1291. .rejects.not.toThrow('SECRET_TOKEN')
  1292. queryMock.mockImplementationOnce(() => {
  1293. throw new Error('query failed before resource creation')
  1294. })
  1295. const queryFailureOnError = vi.fn<
  1296. NonNullable<ClaudeCodeRunSpec['onError']>
  1297. >()
  1298. const queryFailure = startClaudeCodeRun(request(), {
  1299. ...unused.spec,
  1300. onError: queryFailureOnError,
  1301. })
  1302. await expect(queryFailure)
  1303. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1304. await expect(queryFailure).rejects.not.toThrow(
  1305. 'query failed before resource creation',
  1306. )
  1307. expect(queryFailureOnError).toHaveBeenCalledWith(
  1308. expect.any(Error),
  1309. 'error',
  1310. )
  1311. expect(errorCause(queryFailureOnError.mock.calls[0]?.[0])?.message)
  1312. .toBe('query failed before resource creation')
  1313. const spawned = fakeChild()
  1314. const spawnSpecs: SubprocessSpawnSpec[] = []
  1315. let factoryController: AbortController | undefined
  1316. queryMock.mockImplementationOnce(({ options }) => {
  1317. factoryController = options.abortController
  1318. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1319. spawned.settle({ exitCode: 17, signal: null })
  1320. throw new Error('query construction failed')
  1321. })
  1322. const factoryFailure = startClaudeCodeRun(request(), {
  1323. ...unused.spec,
  1324. spawn: (spawnSpec) => {
  1325. spawnSpecs.push(spawnSpec)
  1326. return spawned.handle
  1327. },
  1328. })
  1329. await expect(factoryFailure).rejects.toThrow(expectedFailureDiagnostic(
  1330. 'query-start',
  1331. 'unknown',
  1332. { exitCode: 17, signal: null },
  1333. ))
  1334. await expect(factoryFailure).rejects.not.toThrow('query construction failed')
  1335. expect(spawnSpecs).toHaveLength(1)
  1336. expect(factoryController?.signal.aborted).toBe(true)
  1337. expect(spawned.terminate).toHaveBeenCalledOnce()
  1338. const cleanupRaceAbort = new AbortController()
  1339. const cleanupRaceChild = fakeChild({ exitOnTerminate: false })
  1340. queryMock.mockImplementationOnce(({ options }) => {
  1341. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1342. throw new Error('query failed before cleanup wait')
  1343. })
  1344. const cleanupRace = startClaudeCodeRun(
  1345. request(undefined, cleanupRaceAbort.signal),
  1346. {
  1347. ...unused.spec,
  1348. spawn: () => cleanupRaceChild.handle,
  1349. },
  1350. )
  1351. await nextTask()
  1352. cleanupRaceAbort.abort(new Error('cancelled during cleanup'))
  1353. cleanupRaceChild.settle()
  1354. await expect(cleanupRace).rejects.toThrow('aborted before SDK startup')
  1355. const spawnError = Object.assign(
  1356. new Error('spawn /sdk/claude EACCES'),
  1357. { code: 'EACCES', path: '/sdk/claude' },
  1358. )
  1359. const failedSpawn = fakeChild({
  1360. pid: -1,
  1361. doneError: spawnError,
  1362. })
  1363. const failed = fakeRun([], undefined, failedSpawn)
  1364. const failedStartup = startClaudeCodeRun(request(), failed.spec)
  1365. await expect(failedStartup)
  1366. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1367. await expect(failedStartup).rejects.not.toThrow('spawn /sdk/claude EACCES')
  1368. await expect(failedStartup).rejects.toMatchObject({ cause: spawnError })
  1369. expect(failed.close).toHaveBeenCalledOnce()
  1370. expect(failedSpawn.terminate).not.toHaveBeenCalled()
  1371. expect(failedSpawn.waitForExit).not.toHaveBeenCalled()
  1372. const failedSpawnAbort = new AbortController()
  1373. const cancelledFailedSpawn = fakeChild({
  1374. pid: -1,
  1375. doneError: spawnError,
  1376. })
  1377. const cancelledFailedClose = vi.fn()
  1378. queryMock.mockImplementationOnce(({ options }) => {
  1379. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1380. failedSpawnAbort.abort(new Error('startup cancelled'))
  1381. return queryFrom([], undefined, cancelledFailedClose)
  1382. })
  1383. await expect(startClaudeCodeRun(
  1384. request(undefined, failedSpawnAbort.signal),
  1385. { ...unused.spec, spawn: () => cancelledFailedSpawn.handle },
  1386. )).rejects.toThrow('aborted before SDK startup')
  1387. expect(cancelledFailedClose).toHaveBeenCalledOnce()
  1388. const cancelledFailedSpawnCloseError = new Error('cancelled query close failed')
  1389. const cancelledFailedSpawnClose = vi.fn(() => {
  1390. throw cancelledFailedSpawnCloseError
  1391. })
  1392. const cancelledFailedSpawnWithCloseFailure = fakeChild({
  1393. pid: -1,
  1394. doneError: spawnError,
  1395. })
  1396. const failedSpawnAbortWithCloseFailure = new AbortController()
  1397. queryMock.mockImplementationOnce(({ options }) => {
  1398. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1399. failedSpawnAbortWithCloseFailure.abort(new Error('startup cancelled'))
  1400. return queryFrom([], undefined, cancelledFailedSpawnClose)
  1401. })
  1402. const cancelledWithCloseFailure = startClaudeCodeRun(
  1403. request(undefined, failedSpawnAbortWithCloseFailure.signal),
  1404. { ...unused.spec, spawn: () => cancelledFailedSpawnWithCloseFailure.handle },
  1405. )
  1406. await expect(cancelledWithCloseFailure).rejects.toMatchObject({
  1407. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1408. errors: [
  1409. expect.objectContaining({
  1410. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}`,
  1411. cause: spawnError,
  1412. }),
  1413. expect.objectContaining({
  1414. message: `subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1415. cause: cancelledFailedSpawnCloseError,
  1416. }),
  1417. ],
  1418. })
  1419. await expect(cancelledWithCloseFailure)
  1420. .rejects.not.toThrow('spawn /sdk/claude EACCES')
  1421. expect(cancelledFailedSpawnClose).toHaveBeenCalledOnce()
  1422. const failedSpawnCloseError = new Error('query close failed')
  1423. const failedSpawnClose = vi.fn(() => { throw failedSpawnCloseError })
  1424. const failedSpawnWithCloseFailure = fakeChild({
  1425. pid: -1,
  1426. doneError: spawnError,
  1427. })
  1428. queryMock.mockImplementationOnce(({ options }) => {
  1429. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1430. return queryFrom([], undefined, failedSpawnClose)
  1431. })
  1432. const failedWithCloseFailure = startClaudeCodeRun(request(), {
  1433. ...unused.spec,
  1434. spawn: () => failedSpawnWithCloseFailure.handle,
  1435. })
  1436. await expect(failedWithCloseFailure)
  1437. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1438. await expect(failedWithCloseFailure)
  1439. .rejects.not.toThrow('spawn /sdk/claude EACCES')
  1440. await expect(failedWithCloseFailure).rejects.toMatchObject({
  1441. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1442. errors: [
  1443. expect.objectContaining({ cause: spawnError }),
  1444. expect.objectContaining({ cause: failedSpawnCloseError }),
  1445. ],
  1446. })
  1447. const cleanupError = new Error('live child cleanup failed')
  1448. const constructionError = new Error(
  1449. 'query construction failed with a live child',
  1450. )
  1451. const liveChildCleanupFailure = fakeChild({ waitForExitError: cleanupError })
  1452. queryMock.mockImplementationOnce(({ options }) => {
  1453. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1454. throw constructionError
  1455. })
  1456. const liveCleanupFailure = startClaudeCodeRun(request(), {
  1457. ...unused.spec,
  1458. spawn: () => liveChildCleanupFailure.handle,
  1459. })
  1460. await expect(liveCleanupFailure).rejects.toMatchObject({
  1461. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown', { exitCode: 0, signal: null })}`,
  1462. errors: [
  1463. expect.objectContaining({ cause: constructionError }),
  1464. expect.objectContaining({ cause: cleanupError }),
  1465. ],
  1466. })
  1467. await expect(liveCleanupFailure)
  1468. .rejects.not.toThrow('query construction failed with a live child')
  1469. await expect(liveCleanupFailure)
  1470. .rejects.not.toThrow('live child cleanup failed')
  1471. })
  1472. })
  1473. describe('query and process disposal', () => {
  1474. it('closes the query, terminates the tree, and waits for direct-child outcome', async () => {
  1475. const child = fakeChild()
  1476. const close = vi.fn()
  1477. await disposeClaudeCodeChild({ close }, child.handle)
  1478. expect(close).toHaveBeenCalledOnce()
  1479. expect(child.terminate).toHaveBeenCalledOnce()
  1480. expect(child.waitForExit).toHaveBeenCalledOnce()
  1481. expect(child.waitForExit).toHaveBeenCalledWith()
  1482. await expect(child.handle.done).resolves.toEqual({
  1483. exitCode: 0,
  1484. signal: null,
  1485. })
  1486. })
  1487. it('reports a published teardown failure to the Host diagnostic sink', async () => {
  1488. const fixture = fakeRun([success('exact answer')])
  1489. const onError = vi.fn<NonNullable<ClaudeCodeRunSpec['onError']>>()
  1490. const run = await startClaudeCodeRun(request(), {
  1491. ...fixture.spec,
  1492. onError,
  1493. })
  1494. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  1495. fixture.close.mockImplementationOnce(() => {
  1496. throw new Error('SECRET_TOKEN close failure')
  1497. })
  1498. await expect(run.dispose()).rejects.toThrow(
  1499. expectedFailureDiagnostic('teardown', 'unknown', {
  1500. exitCode: 0,
  1501. signal: null,
  1502. }),
  1503. )
  1504. expect(onError).toHaveBeenCalledWith(expect.any(Error), 'error')
  1505. expect(errorCause(onError.mock.calls[0]?.[0])?.message)
  1506. .toBe('SECRET_TOKEN close failure')
  1507. })
  1508. it('does not finish disposal before the managed tree exits', async () => {
  1509. const child = fakeChild({ exitOnTerminate: false })
  1510. let disposed = false
  1511. const disposal = disposeClaudeCodeChild(
  1512. { close: vi.fn() },
  1513. child.handle,
  1514. ).then(() => {
  1515. disposed = true
  1516. })
  1517. await nextTask()
  1518. expect(disposed).toBe(false)
  1519. child.settle()
  1520. await disposal
  1521. expect(disposed).toBe(true)
  1522. })
  1523. it('reports close and tree-wait failures without skipping cleanup', async () => {
  1524. const waitFailure = fakeChild({
  1525. waitForExitError: new Error('wait boom'),
  1526. })
  1527. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  1528. const waitAndClose = disposeClaudeCodeChild(
  1529. { close: closeFailure },
  1530. waitFailure.handle,
  1531. )
  1532. await expect(waitAndClose).rejects.toThrow(expectedFailureDiagnostic(
  1533. 'teardown',
  1534. 'unknown',
  1535. { exitCode: 0, signal: null },
  1536. ))
  1537. const waitAndCloseError = await waitAndClose.then(
  1538. () => undefined,
  1539. (error: unknown) => error,
  1540. )
  1541. const waitAndCloseCause = errorCause(waitAndCloseError)
  1542. expect(waitAndCloseCause).toBeInstanceOf(AggregateError)
  1543. expect((waitAndCloseCause as AggregateError).errors).toEqual([
  1544. expect.objectContaining({ message: 'close boom' }),
  1545. expect.objectContaining({ message: 'wait boom' }),
  1546. ])
  1547. expect(waitFailure.terminate).toHaveBeenCalledOnce()
  1548. })
  1549. })