subagent-claude-code.spec.ts 59 KB

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