subagent-claude-code.spec.ts 58 KB

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