subagent-claude-code.spec.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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 | undefined
  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: Object.hasOwn(options, '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: undefined })
  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 thrownAbort = new AbortController()
  1228. queryMock.mockImplementationOnce(() => {
  1229. thrownAbort.abort(new Error('startup cancelled before resource publication'))
  1230. throw new Error('query failed before resource publication')
  1231. })
  1232. await expect(startClaudeCodeRun(
  1233. request(undefined, thrownAbort.signal),
  1234. unused.spec,
  1235. )).rejects.toThrow('aborted before SDK startup')
  1236. const noChildClose = vi.fn()
  1237. queryMock.mockImplementationOnce(
  1238. () => queryFrom([], undefined, noChildClose),
  1239. )
  1240. await expect(startClaudeCodeRun(request(), {
  1241. ...unused.spec,
  1242. })).rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1243. expect(noChildClose).toHaveBeenCalledOnce()
  1244. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  1245. queryMock.mockImplementationOnce(
  1246. () => queryFrom([], undefined, closeFailure),
  1247. )
  1248. const noChild = startClaudeCodeRun(request(), {
  1249. ...unused.spec,
  1250. })
  1251. await expect(noChild)
  1252. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1253. await expect(noChild).rejects.toThrow(
  1254. `${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1255. )
  1256. await expect(noChild).rejects.toBeInstanceOf(AggregateError)
  1257. const startupAbort = new AbortController()
  1258. const abortedChild = fakeChild()
  1259. const abortedClose = vi.fn()
  1260. queryMock.mockImplementationOnce(({ options }) => {
  1261. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1262. startupAbort.abort(new Error('startup cancelled'))
  1263. return queryFrom([], undefined, abortedClose)
  1264. })
  1265. const abortedDuringStartup = startClaudeCodeRun(
  1266. request(undefined, startupAbort.signal),
  1267. {
  1268. ...unused.spec,
  1269. spawn: () => abortedChild.handle,
  1270. },
  1271. )
  1272. await expect(abortedDuringStartup)
  1273. .rejects.toThrow('aborted before SDK startup')
  1274. expect(abortedClose).toHaveBeenCalledOnce()
  1275. expect(abortedChild.terminate).toHaveBeenCalledOnce()
  1276. const cleanupAbort = new AbortController()
  1277. const cleanupFailedChild = fakeChild({
  1278. waitForExitError: new Error('SECRET_TOKEN cleanup wait failure'),
  1279. })
  1280. queryMock.mockImplementationOnce(({ options }) => {
  1281. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1282. cleanupAbort.abort(new Error('startup cancelled'))
  1283. return queryFrom([])
  1284. })
  1285. const cancelledCleanupFailure = startClaudeCodeRun(
  1286. request(undefined, cleanupAbort.signal),
  1287. {
  1288. ...unused.spec,
  1289. spawn: () => cleanupFailedChild.handle,
  1290. },
  1291. )
  1292. await expect(cancelledCleanupFailure)
  1293. .rejects.toBeInstanceOf(AggregateError)
  1294. await expect(cancelledCleanupFailure)
  1295. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1296. await expect(cancelledCleanupFailure).rejects.toThrow(
  1297. `${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown', { exitCode: 0, signal: null })}`,
  1298. )
  1299. await expect(cancelledCleanupFailure)
  1300. .rejects.not.toThrow('SECRET_TOKEN')
  1301. queryMock.mockImplementationOnce(() => {
  1302. throw new Error('query failed before resource creation')
  1303. })
  1304. const queryFailureOnError = vi.fn<
  1305. NonNullable<ClaudeCodeRunSpec['onError']>
  1306. >()
  1307. const queryFailure = startClaudeCodeRun(request(), {
  1308. ...unused.spec,
  1309. onError: queryFailureOnError,
  1310. })
  1311. await expect(queryFailure)
  1312. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1313. await expect(queryFailure).rejects.not.toThrow(
  1314. 'query failed before resource creation',
  1315. )
  1316. expect(queryFailureOnError).toHaveBeenCalledWith(
  1317. expect.any(Error),
  1318. 'error',
  1319. )
  1320. expect(errorCause(queryFailureOnError.mock.calls[0]?.[0])?.message)
  1321. .toBe('query failed before resource creation')
  1322. const spawned = fakeChild()
  1323. const spawnSpecs: SubprocessSpawnSpec[] = []
  1324. let factoryController: AbortController | undefined
  1325. queryMock.mockImplementationOnce(({ options }) => {
  1326. factoryController = options.abortController
  1327. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1328. spawned.settle({ exitCode: 17, signal: null })
  1329. throw new Error('query construction failed')
  1330. })
  1331. const factoryFailure = startClaudeCodeRun(request(), {
  1332. ...unused.spec,
  1333. spawn: (spawnSpec) => {
  1334. spawnSpecs.push(spawnSpec)
  1335. return spawned.handle
  1336. },
  1337. })
  1338. await expect(factoryFailure).rejects.toThrow(expectedFailureDiagnostic(
  1339. 'query-start',
  1340. 'unknown',
  1341. { exitCode: 17, signal: null },
  1342. ))
  1343. await expect(factoryFailure).rejects.not.toThrow('query construction failed')
  1344. expect(spawnSpecs).toHaveLength(1)
  1345. expect(factoryController?.signal.aborted).toBe(true)
  1346. expect(spawned.terminate).toHaveBeenCalledOnce()
  1347. const cleanupRaceAbort = new AbortController()
  1348. const cleanupRaceChild = fakeChild({ exitOnTerminate: false })
  1349. queryMock.mockImplementationOnce(({ options }) => {
  1350. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1351. throw new Error('query failed before cleanup wait')
  1352. })
  1353. const cleanupRace = startClaudeCodeRun(
  1354. request(undefined, cleanupRaceAbort.signal),
  1355. {
  1356. ...unused.spec,
  1357. spawn: () => cleanupRaceChild.handle,
  1358. },
  1359. )
  1360. await nextTask()
  1361. cleanupRaceAbort.abort(new Error('cancelled during cleanup'))
  1362. cleanupRaceChild.settle()
  1363. await expect(cleanupRace).rejects.toThrow('aborted before SDK startup')
  1364. const spawnError = Object.assign(
  1365. new Error('spawn /sdk/claude EACCES'),
  1366. { code: 'EACCES', path: '/sdk/claude' },
  1367. )
  1368. const failedSpawn = fakeChild({
  1369. pid: undefined,
  1370. doneError: spawnError,
  1371. })
  1372. const failed = fakeRun([], undefined, failedSpawn)
  1373. const failedStartup = startClaudeCodeRun(request(), failed.spec)
  1374. await expect(failedStartup)
  1375. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1376. await expect(failedStartup).rejects.not.toThrow('spawn /sdk/claude EACCES')
  1377. await expect(failedStartup).rejects.toMatchObject({ cause: spawnError })
  1378. expect(failed.close).toHaveBeenCalledOnce()
  1379. expect(failedSpawn.terminate).toHaveBeenCalledOnce()
  1380. expect(failedSpawn.waitForExit).toHaveBeenCalledOnce()
  1381. const failedSpawnAbort = new AbortController()
  1382. const cancelledFailedSpawn = fakeChild({
  1383. pid: undefined,
  1384. doneError: spawnError,
  1385. })
  1386. const cancelledFailedClose = vi.fn()
  1387. queryMock.mockImplementationOnce(({ options }) => {
  1388. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1389. failedSpawnAbort.abort(new Error('startup cancelled'))
  1390. return queryFrom([], undefined, cancelledFailedClose)
  1391. })
  1392. await expect(startClaudeCodeRun(
  1393. request(undefined, failedSpawnAbort.signal),
  1394. { ...unused.spec, spawn: () => cancelledFailedSpawn.handle },
  1395. )).rejects.toThrow('aborted before SDK startup')
  1396. expect(cancelledFailedClose).toHaveBeenCalledOnce()
  1397. const cancelledFailedSpawnCloseError = new Error('cancelled query close failed')
  1398. const cancelledFailedSpawnClose = vi.fn(() => {
  1399. throw cancelledFailedSpawnCloseError
  1400. })
  1401. const cancelledFailedSpawnWithCloseFailure = fakeChild({
  1402. pid: undefined,
  1403. doneError: spawnError,
  1404. })
  1405. const failedSpawnAbortWithCloseFailure = new AbortController()
  1406. queryMock.mockImplementationOnce(({ options }) => {
  1407. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1408. failedSpawnAbortWithCloseFailure.abort(new Error('startup cancelled'))
  1409. return queryFrom([], undefined, cancelledFailedSpawnClose)
  1410. })
  1411. const cancelledWithCloseFailure = startClaudeCodeRun(
  1412. request(undefined, failedSpawnAbortWithCloseFailure.signal),
  1413. { ...unused.spec, spawn: () => cancelledFailedSpawnWithCloseFailure.handle },
  1414. )
  1415. await expect(cancelledWithCloseFailure).rejects.toMatchObject({
  1416. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1417. errors: [
  1418. expect.objectContaining({
  1419. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}`,
  1420. cause: spawnError,
  1421. }),
  1422. expect.objectContaining({
  1423. message: `subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1424. cause: cancelledFailedSpawnCloseError,
  1425. }),
  1426. ],
  1427. })
  1428. await expect(cancelledWithCloseFailure)
  1429. .rejects.not.toThrow('spawn /sdk/claude EACCES')
  1430. expect(cancelledFailedSpawnClose).toHaveBeenCalledOnce()
  1431. const failedSpawnCloseError = new Error('query close failed')
  1432. const failedSpawnClose = vi.fn(() => { throw failedSpawnCloseError })
  1433. const failedSpawnWithCloseFailure = fakeChild({
  1434. pid: undefined,
  1435. doneError: spawnError,
  1436. })
  1437. queryMock.mockImplementationOnce(({ options }) => {
  1438. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1439. return queryFrom([], undefined, failedSpawnClose)
  1440. })
  1441. const failedWithCloseFailure = startClaudeCodeRun(request(), {
  1442. ...unused.spec,
  1443. spawn: () => failedSpawnWithCloseFailure.handle,
  1444. })
  1445. await expect(failedWithCloseFailure)
  1446. .rejects.toThrow(expectedFailureDiagnostic('query-start', 'unknown'))
  1447. await expect(failedWithCloseFailure)
  1448. .rejects.not.toThrow('spawn /sdk/claude EACCES')
  1449. await expect(failedWithCloseFailure).rejects.toMatchObject({
  1450. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown')}`,
  1451. errors: [
  1452. expect.objectContaining({ cause: spawnError }),
  1453. expect.objectContaining({ cause: failedSpawnCloseError }),
  1454. ],
  1455. })
  1456. const cleanupError = new Error('live child cleanup failed')
  1457. const constructionError = new Error(
  1458. 'query construction failed with a live child',
  1459. )
  1460. const liveChildCleanupFailure = fakeChild({ waitForExitError: cleanupError })
  1461. queryMock.mockImplementationOnce(({ options }) => {
  1462. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1463. throw constructionError
  1464. })
  1465. const liveCleanupFailure = startClaudeCodeRun(request(), {
  1466. ...unused.spec,
  1467. spawn: () => liveChildCleanupFailure.handle,
  1468. })
  1469. await expect(liveCleanupFailure).rejects.toMatchObject({
  1470. message: `subagent-claude-code: ${expectedFailureDiagnostic('query-start', 'unknown')}; subagent-claude-code: ${expectedFailureDiagnostic('teardown', 'unknown', { exitCode: 0, signal: null })}`,
  1471. errors: [
  1472. expect.objectContaining({ cause: constructionError }),
  1473. expect.objectContaining({ cause: cleanupError }),
  1474. ],
  1475. })
  1476. await expect(liveCleanupFailure)
  1477. .rejects.not.toThrow('query construction failed with a live child')
  1478. await expect(liveCleanupFailure)
  1479. .rejects.not.toThrow('live child cleanup failed')
  1480. })
  1481. it('waits one event-loop turn for a queued provider startup rejection', async () => {
  1482. const spawnError = Object.assign(
  1483. new Error('spawn /sdk/claude ENOENT'),
  1484. { code: 'ENOENT', path: '/sdk/claude' },
  1485. )
  1486. const child = fakeChild({ pid: undefined })
  1487. const close = vi.fn()
  1488. queryMock.mockImplementationOnce(({ options }) => {
  1489. options.spawnClaudeCodeProcess!(sdkSpawnOptions())
  1490. queueMicrotask(() => { child.fail(spawnError) })
  1491. return queryFrom([], undefined, close)
  1492. })
  1493. const startup = startClaudeCodeRun(request(), {
  1494. cwd: '/workspace',
  1495. permissionMode: DEFAULT_CLAUDE_CODE_PERMISSION_MODE,
  1496. env: {},
  1497. disposeGraceMs: 5,
  1498. spawn: () => child.handle,
  1499. })
  1500. await expect(startup).rejects.toMatchObject({ cause: spawnError })
  1501. expect(close).toHaveBeenCalledOnce()
  1502. expect(child.terminate).toHaveBeenCalledOnce()
  1503. expect(child.waitForExit).toHaveBeenCalledOnce()
  1504. })
  1505. })
  1506. describe('query and process disposal', () => {
  1507. it('closes the query, terminates the tree, and waits for direct-child outcome', async () => {
  1508. const child = fakeChild()
  1509. const close = vi.fn()
  1510. await disposeClaudeCodeChild({ close }, child.handle)
  1511. expect(close).toHaveBeenCalledOnce()
  1512. expect(child.terminate).toHaveBeenCalledOnce()
  1513. expect(child.waitForExit).toHaveBeenCalledOnce()
  1514. expect(child.waitForExit).toHaveBeenCalledWith()
  1515. await expect(child.handle.done).resolves.toEqual({
  1516. exitCode: 0,
  1517. signal: null,
  1518. })
  1519. })
  1520. it('reports a published teardown failure to the Host diagnostic sink', async () => {
  1521. const fixture = fakeRun([success('exact answer')])
  1522. const onError = vi.fn<NonNullable<ClaudeCodeRunSpec['onError']>>()
  1523. const run = await startClaudeCodeRun(request(), {
  1524. ...fixture.spec,
  1525. onError,
  1526. })
  1527. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  1528. fixture.close.mockImplementationOnce(() => {
  1529. throw new Error('SECRET_TOKEN close failure')
  1530. })
  1531. await expect(run.dispose()).rejects.toThrow(
  1532. expectedFailureDiagnostic('teardown', 'unknown', {
  1533. exitCode: 0,
  1534. signal: null,
  1535. }),
  1536. )
  1537. expect(onError).toHaveBeenCalledWith(expect.any(Error), 'error')
  1538. expect(errorCause(onError.mock.calls[0]?.[0])?.message)
  1539. .toBe('SECRET_TOKEN close failure')
  1540. })
  1541. it('does not finish disposal before the managed tree exits', async () => {
  1542. const child = fakeChild({ exitOnTerminate: false })
  1543. let disposed = false
  1544. const disposal = disposeClaudeCodeChild(
  1545. { close: vi.fn() },
  1546. child.handle,
  1547. ).then(() => {
  1548. disposed = true
  1549. })
  1550. await nextTask()
  1551. expect(disposed).toBe(false)
  1552. child.settle()
  1553. await disposal
  1554. expect(disposed).toBe(true)
  1555. })
  1556. it('reports close and tree-wait failures without skipping cleanup', async () => {
  1557. const waitFailure = fakeChild({
  1558. waitForExitError: new Error('wait boom'),
  1559. })
  1560. const closeFailure = vi.fn(() => { throw new Error('close boom') })
  1561. const waitAndClose = disposeClaudeCodeChild(
  1562. { close: closeFailure },
  1563. waitFailure.handle,
  1564. )
  1565. await expect(waitAndClose).rejects.toThrow(expectedFailureDiagnostic(
  1566. 'teardown',
  1567. 'unknown',
  1568. { exitCode: 0, signal: null },
  1569. ))
  1570. const waitAndCloseError = await waitAndClose.then(
  1571. () => undefined,
  1572. (error: unknown) => error,
  1573. )
  1574. const waitAndCloseCause = errorCause(waitAndCloseError)
  1575. expect(waitAndCloseCause).toBeInstanceOf(AggregateError)
  1576. expect((waitAndCloseCause as AggregateError).errors).toEqual([
  1577. expect.objectContaining({ message: 'close boom' }),
  1578. expect.objectContaining({ message: 'wait boom' }),
  1579. ])
  1580. expect(waitFailure.terminate).toHaveBeenCalledOnce()
  1581. })
  1582. it('reports a tree-wait failure without waiting for a pending direct outcome', async () => {
  1583. const waitFailure = new Error('managed range observation failed')
  1584. const child = fakeChild({
  1585. exitOnTerminate: false,
  1586. waitForExitError: waitFailure,
  1587. })
  1588. const result = await Promise.race([
  1589. disposeClaudeCodeChild({ close: vi.fn() }, child.handle).then(
  1590. () => undefined,
  1591. (error: unknown) => error,
  1592. ),
  1593. new Promise<'timeout'>(resolve => setTimeout(() => { resolve('timeout') }, 100)),
  1594. ])
  1595. expect(result).not.toBe('timeout')
  1596. expect(errorCause(result)).toBe(waitFailure)
  1597. expect(child.terminate).toHaveBeenCalledOnce()
  1598. })
  1599. })