structured.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId, type ContentBlock, type GenerateOptions } from '@deepseek-ai/dsh-llm'
  4. import { SessionId } from '@deepseek-ai/dsh-session'
  5. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  6. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  7. import InvariantService from '@deepseek-ai/dsh-invariants'
  8. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  9. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  10. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  11. import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  12. import type { Config as ToolConfig, ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
  13. import { defineContentToolFixture, RUN_CODE_NAME } from '@deepseek-ai/dsh-tools'
  14. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  15. import { startInProcessRun } from '../src/index.ts'
  16. import {
  17. STRUCTURED_OUTPUT_INSTRUCTION,
  18. STRUCTURED_OUTPUT_TOOL,
  19. } from '../src/structured.ts'
  20. const testToolSignal = new AbortController().signal
  21. type Script = ConstructorParameters<typeof MockAdapter>[0]
  22. async function mountInvariants(ctx: Context): Promise<void> {
  23. await ctx.plugin(InvariantService)
  24. await ctx.plugin(SessionInvariant)
  25. await ctx.plugin(AgentInvariant)
  26. await ctx.plugin(AgentLoopInvariant)
  27. }
  28. interface CodeRunRequestLike {
  29. bindings: { global: string; functions: Record<string, (args: unknown) => Promise<unknown>> }[]
  30. }
  31. interface SetupOptions {
  32. toolMode?: ToolConfig['mode']
  33. codeRun?: (request: CodeRunRequestLike) => Promise<{ logs: never[]; value?: unknown }>
  34. }
  35. const SCHEMA: ObjectJsonSchema = {
  36. type: 'object',
  37. properties: { answer: { type: 'number' }, note: { type: 'string' } },
  38. required: ['answer'],
  39. }
  40. /**
  41. * Real loop, scripted model, and inline fresh-conversation provider over the shared driver. Loading
  42. * spawn/fork here would create a dev-dependency cycle; their specs cover plugin integration while
  43. * this fixture isolates driver behavior and scripts the child's `structured_output` calls.
  44. */
  45. async function setup(script: Script, options: SetupOptions = {}) {
  46. const ctx = new Context()
  47. const adapter = new MockAdapter(script)
  48. await mountAgentLoopTestDependencies(ctx, {
  49. tools: { mode: options.toolMode ?? 'native' },
  50. })
  51. if (options.toolMode === 'code' || options.toolMode === 'both') {
  52. ctx.provide('codeRuntime', {
  53. language: 'typescript',
  54. isolation: 'test',
  55. run: options.codeRun ?? (() => Promise.resolve({ logs: [] })),
  56. } as never)
  57. }
  58. await mountInvariants(ctx)
  59. await ctx.plugin(AgentLoop, { agents: [] })
  60. await ctx.plugin(SubagentService)
  61. const disposeProvider = ctx.subagents.registerProvider({
  62. name: 'spawn',
  63. capabilities: { outputSchema: true, depthLimit: true, toolFilter: false, persona: false },
  64. inheritsParentContext: false,
  65. start: (request: SubagentStartRequest) => startInProcessRun(request, {}),
  66. })
  67. ctx.llm.registerAdapter(['mock'], adapter)
  68. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  69. return { ctx, parent, adapter, disposeProvider }
  70. }
  71. function structuredRequest(parent: SubagentStartRequest['parent'], extra?: Partial<SubagentStartRequest>): SubagentStartRequest {
  72. return {
  73. prompt: [{ type: 'text', text: 'produce the answer' }],
  74. parent,
  75. signal: new AbortController().signal,
  76. outputSchema: SCHEMA,
  77. ...extra,
  78. }
  79. }
  80. /** The tool names of one recorded model request. */
  81. function toolNames(request: GenerateOptions): string[] {
  82. return (request.tools ?? []).map(tool => tool.name)
  83. }
  84. describe('in-process structured output', () => {
  85. it('captures a valid structured_output call and surfaces result.structured', async () => {
  86. const { ctx, parent } = await setup([
  87. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42, note: 'done' }),
  88. ])
  89. let acknowledgement: unknown
  90. ctx.on('tools/result', (exec, toolResult) => {
  91. if (exec.name === STRUCTURED_OUTPUT_TOOL && !toolResult.isError) acknowledgement = toolResult.value
  92. })
  93. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  94. const result = await run.result
  95. expect(result.stopReason).toBe('completed')
  96. expect(result.structured).toEqual({ answer: 42, note: 'done' })
  97. expect(acknowledgement).toEqual({ recorded: true })
  98. await run.dispose()
  99. })
  100. it('stops the turn after a successful capture — no extra model step is spent', async () => {
  101. const { ctx, parent, adapter } = await setup([
  102. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
  103. textResponse('MUST NOT BE CONSUMED'),
  104. ])
  105. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  106. await run.result
  107. // The structured tool marks its successful result as turn-concluding.
  108. expect(adapter.requests.length).toBe(1)
  109. await run.dispose()
  110. })
  111. it('denies tool calls that FOLLOW the capture in the same response — terminal means terminal', async () => {
  112. // One model response carrying structured_output FIRST and a side-effecting
  113. // call after it: the continuation veto only fires at step end, so without
  114. // the pre-execute deny the trailing call would still run after the final
  115. // answer was accepted.
  116. const response = [
  117. ...toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 5 }).slice(0, -2),
  118. { type: 'block-start', index: 1, blockType: 'tool-call' },
  119. { type: 'block-end', index: 1, block: { type: 'tool-call', id: CallId('c2'), name: 'side_effect', arguments: '{}' } },
  120. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  121. { type: 'finish', reason: { kind: 'tool-calls' } },
  122. ] as Script[number]
  123. const { ctx, parent } = await setup([response])
  124. let sideEffectRan = false
  125. ctx.tools.register(defineContentToolFixture({
  126. name: 'side_effect',
  127. description: 'probe',
  128. parameters: {},
  129. execute(): Promise<ContentBlock[]> {
  130. sideEffectRan = true
  131. return Promise.resolve([{ type: 'text', text: 'ran' }])
  132. },
  133. }))
  134. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  135. const result = await run.result
  136. expect(result.stopReason).toBe('completed')
  137. expect(result.structured).toEqual({ answer: 5 })
  138. // The deny skipped dispatch entirely: the probe body never ran.
  139. expect(sideEffectRan).toBe(false)
  140. await run.dispose()
  141. })
  142. it('a later prepended pre-execute listener cannot resurrect dispatch after capture', async () => {
  143. const response = [
  144. ...toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 5 }).slice(0, -2),
  145. { type: 'block-start', index: 1, blockType: 'tool-call' },
  146. { type: 'block-end', index: 1, block: { type: 'tool-call', id: CallId('c2'), name: 'side_effect', arguments: '{}' } },
  147. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  148. { type: 'finish', reason: { kind: 'tool-calls' } },
  149. ] as Script[number]
  150. const { ctx, parent } = await setup([response])
  151. let sideEffectRan = false
  152. ctx.tools.register(defineContentToolFixture({
  153. name: 'side_effect',
  154. description: 'probe',
  155. parameters: {},
  156. execute(): Promise<ContentBlock[]> {
  157. sideEffectRan = true
  158. return Promise.resolve([{ type: 'text', text: 'ran' }])
  159. },
  160. }))
  161. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  162. // Registered after the child and prepended: this listener returns allow
  163. // after every downstream pre-execute decision. The service-owned guard
  164. // runs after the waterfall and can only deny, so the body still cannot run.
  165. ctx.on('tools/pre-execute', async (_exec, next) => {
  166. await next()
  167. return { kind: 'allow' as const }
  168. }, { prepend: true })
  169. const result = await run.result
  170. expect(result.structured).toEqual({ answer: 5 })
  171. expect(sideEffectRan).toBe(false)
  172. const child = ctx.agents.get(run.id)
  173. const sideEffectResult = child?.session.events.find(event =>
  174. event.type === 'tool/result' && event.data.callId === 'c2')
  175. expect(sideEffectResult?.type === 'tool/result' && sideEffectResult.data.isError).toBe(true)
  176. await run.dispose()
  177. })
  178. it('leaves tool calls that PRECEDE the capture in the same response untouched', async () => {
  179. const response = [
  180. { type: 'block-start', index: 0, blockType: 'tool-call' },
  181. { type: 'block-end', index: 0, block: { type: 'tool-call', id: CallId('c1'), name: 'side_effect', arguments: '{}' } },
  182. ...toolCallResponse('c2', STRUCTURED_OUTPUT_TOOL, { answer: 6 }).map(chunk =>
  183. 'index' in chunk ? { ...chunk, index: 1 } : chunk),
  184. ] as Script[number]
  185. const { ctx, parent } = await setup([response])
  186. let sideEffectRan = false
  187. ctx.tools.register(defineContentToolFixture({
  188. name: 'side_effect',
  189. description: 'probe',
  190. parameters: {},
  191. execute(): Promise<ContentBlock[]> {
  192. sideEffectRan = true
  193. return Promise.resolve([{ type: 'text', text: 'ran' }])
  194. },
  195. }))
  196. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  197. const result = await run.result
  198. // The call ran BEFORE captured was set: the deny gate only guards the
  199. // window after the terminal answer landed.
  200. expect(sideEffectRan).toBe(true)
  201. expect(result.structured).toEqual({ answer: 6 })
  202. await run.dispose()
  203. })
  204. it('an invalid call gets an INVALID_ARGS isError result and the model retries in-turn', async () => {
  205. const { ctx, parent } = await setup([
  206. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 'not-a-number' }),
  207. toolCallResponse('c2', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
  208. ])
  209. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  210. const result = await run.result
  211. expect(result.structured).toEqual({ answer: 7 })
  212. expect(result.stopReason).toBe('completed')
  213. // The child's log carries the isError tool/result for the invalid call.
  214. const child = ctx.agents.get(run.id)!
  215. const results = child.session.events.filter(e => e.type === 'tool/result')
  216. expect(results.length).toBe(2)
  217. expect((results[0]!.data as { isError?: boolean }).isError).toBe(true)
  218. await run.dispose()
  219. })
  220. it('a clean finish without a capture is an immediate error to the parent — deliberately NO re-prompt', async () => {
  221. const { ctx, parent, adapter } = await setup([
  222. textResponse('here is my answer in prose'),
  223. textResponse('MUST NOT BE CONSUMED'),
  224. ])
  225. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  226. const result = await run.result
  227. expect(result.stopReason).toBe('error')
  228. expect(result.structured).toBeUndefined()
  229. // Exactly one model request and one user message: no nudge turn exists.
  230. expect(adapter.requests.length).toBe(1)
  231. const child = ctx.agents.get(run.id)!
  232. expect(child.session.events.filter(e => e.type === 'user/message').length).toBe(1)
  233. await run.dispose()
  234. })
  235. it('an errored child keeps its honest error result (no capture expected)', async () => {
  236. // Script exhaustion on the first call → the child turn errors.
  237. const { ctx, parent, adapter } = await setup([])
  238. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  239. const result = await run.result
  240. expect(result.stopReason).toBe('error')
  241. expect(adapter.requests.length).toBe(1)
  242. await run.dispose()
  243. })
  244. it('a cancel landing after a clean capture-less turn settles aborted, not error', async () => {
  245. const { ctx, parent } = await setup([textResponse('prose, no capture')])
  246. const controller = new AbortController()
  247. const run = await ctx.subagents.start('spawn', structuredRequest(parent, { signal: controller.signal }))
  248. // Cancel synchronously inside the turn's end recording: the cancel
  249. // contract outranks the schema shortfall, so the result maps to aborted.
  250. ctx.on('session/event', (session, event) => {
  251. const child = ctx.agents.get(run.id)
  252. if (session === child?.session && event.type === 'turn/end') controller.abort('cancelled at turn end')
  253. })
  254. const result = await run.result
  255. expect(result.stopReason).toBe('aborted')
  256. await run.dispose()
  257. })
  258. it('rejects a schema outside the subset loud, before any child exists', async () => {
  259. const { ctx, parent } = await setup([])
  260. await expect(ctx.subagents.start('spawn', structuredRequest(parent, {
  261. outputSchema: { type: 'object', oneOf: [] } as unknown as ObjectJsonSchema,
  262. }))).rejects.toThrow(/unsupported JSON schema/)
  263. expect(ctx.agents.get(SessionId('parent'))).toBeDefined()
  264. })
  265. it('a schema carrying non-JSON values fails as JsonSchemaError at the validation boundary', async () => {
  266. const { ctx, parent } = await setup([])
  267. // Semantic assertion runs before provider startup.
  268. await expect(ctx.subagents.start('spawn', structuredRequest(parent, {
  269. outputSchema: { type: 'object', default: () => {} } as unknown as ObjectJsonSchema,
  270. }))).rejects.toThrow(/unsupported JSON schema.*annotation must be lossless JSON data/)
  271. })
  272. it('a post-execute BLOCK on the capture call denies the capture: log and result agree on failure', async () => {
  273. const { ctx, parent, adapter } = await setup([
  274. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
  275. textResponse('continues after the blocked capture'),
  276. ])
  277. // A PostToolUse-style hook turns the tool body's provisional success into
  278. // the authoritative final error observed by the commit notification.
  279. ctx.on('tools/post-execute', (exec, _result, next) => {
  280. if (exec.name === STRUCTURED_OUTPUT_TOOL) {
  281. return Promise.resolve({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'capture rejected by hook' }] })
  282. }
  283. return next()
  284. })
  285. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  286. const result = await run.result
  287. // No capture was committed: the run reports the schema shortfall...
  288. expect(result.structured).toBeUndefined()
  289. expect(result.stopReason).toBe('error')
  290. // ...the logged tool result is the blocked isError with the feedback...
  291. const child = ctx.agents.get(run.id)!
  292. const results = child.session.events.filter(e => e.type === 'tool/result')
  293. expect((results[0]!.data as { isError?: boolean }).isError).toBe(true)
  294. expect(JSON.stringify((results[0]!.data as { content: unknown }).content)).toContain('capture rejected by hook')
  295. // ...and the turn CONTINUED past the blocked call (no captured veto):
  296. // the model got to react to the failure with a second step.
  297. expect(adapter.requests.length).toBe(2)
  298. await run.dispose()
  299. })
  300. it('a post-execute accept-with-replacement still commits the capture', async () => {
  301. const { ctx, parent } = await setup([
  302. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 8 }),
  303. ])
  304. ctx.on('tools/post-execute', (exec, _result, next) => {
  305. if (exec.name === STRUCTURED_OUTPUT_TOOL) {
  306. return Promise.resolve({ kind: 'accept' as const, content: [{ type: 'text' as const, text: 'recorded (rewritten)' }] })
  307. }
  308. return next()
  309. })
  310. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  311. const result = await run.result
  312. expect(result.stopReason).toBe('completed')
  313. expect(result.structured).toEqual({ answer: 8 })
  314. await run.dispose()
  315. })
  316. it('commits only after a later prepended post-execute wrapper returns the authoritative result', async () => {
  317. const { ctx, parent } = await setup([
  318. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 8 }),
  319. textResponse('capture was rejected'),
  320. ])
  321. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  322. // Registered after attachment and prepended, so it wraps every listener
  323. // the child installed. It delegates first, then converts the apparent
  324. // capture success into the pipeline's authoritative failure.
  325. ctx.on('tools/post-execute', async (exec, _result, next) => {
  326. const downstream = await next()
  327. if (exec.name !== STRUCTURED_OUTPUT_TOOL) return downstream
  328. return { kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'rejected after downstream' }] }
  329. }, { prepend: true })
  330. const result = await run.result
  331. expect(result.structured).toBeUndefined()
  332. expect(result.stopReason).toBe('error')
  333. const child = ctx.agents.get(run.id)
  334. const captureResult = child?.session.events.find(event =>
  335. event.type === 'tool/result' && event.data.callId === 'c1')
  336. expect(captureResult?.type === 'tool/result' && captureResult.data.isError).toBe(true)
  337. await run.dispose()
  338. })
  339. it('appends the structured instruction to the child REQUEST\'s system text (base prompt preserved)', async () => {
  340. const { ctx, parent, adapter } = await setup([toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 })])
  341. // A context-wide section stands in for the deployment persona: the
  342. // instruction must APPEND to the other scoped and global sections, not
  343. // replace them (AgentOptions has no prompt field — the instruction is an
  344. // ordinary child-scoped prompt registration).
  345. ctx.systemPrompt.section({ name: 'test:persona', order: 10, text: 'You are a counter.' })
  346. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  347. await run.result
  348. const childRequest = adapter.requests.at(-1)!
  349. expect(childRequest.system).toContain('You are a counter.')
  350. expect(childRequest.system!.endsWith(STRUCTURED_OUTPUT_INSTRUCTION)).toBe(true)
  351. expect(childRequest.system!.indexOf(STRUCTURED_OUTPUT_INSTRUCTION)).toBeGreaterThan(0)
  352. await run.dispose()
  353. })
  354. it('keeps pure Code Mode at one wire tool and exposes structured capture through the SDK only', async () => {
  355. const { ctx, parent, adapter } = await setup([
  356. toolCallResponse('c1', RUN_CODE_NAME, { code: 'return await tools.structured_output({ answer: 12 })', description: 'Capture the structured answer' }),
  357. ], {
  358. toolMode: 'code',
  359. codeRun: async (request) => {
  360. const capture = request.bindings.at(0)?.functions[STRUCTURED_OUTPUT_TOOL]
  361. if (!capture) throw new Error('structured_output binding missing')
  362. await capture({ answer: 12 })
  363. return { logs: [], value: 'captured' }
  364. },
  365. })
  366. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  367. const result = await run.result
  368. expect(result.structured).toEqual({ answer: 12 })
  369. const request = adapter.requests[0]!
  370. expect(toolNames(request)).toEqual([RUN_CODE_NAME])
  371. expect(request.system).toContain('interface ToolArgsMap')
  372. expect(request.system).toContain('interface ToolOutputMap')
  373. expect(request.system).toContain('recorded: true;')
  374. expect(request.system).toContain('Promise<ToolOutputMap[K]>')
  375. expect(request.system).toContain(STRUCTURED_OUTPUT_INSTRUCTION)
  376. await run.dispose()
  377. })
  378. it('discards a nested capture when the enclosing run_code execution fails', async () => {
  379. const { ctx, parent, adapter } = await setup([
  380. toolCallResponse('c1', RUN_CODE_NAME, { code: 'await tools.structured_output({ answer: 12 }); throw new Error("boom")', description: 'Capture then fail the program' }),
  381. textResponse('outer code failed'),
  382. ], {
  383. toolMode: 'code',
  384. codeRun: async (request) => {
  385. const capture = request.bindings.at(0)?.functions[STRUCTURED_OUTPUT_TOOL]
  386. if (!capture) throw new Error('structured_output binding missing')
  387. await capture({ answer: 12 })
  388. return {
  389. logs: [],
  390. error: { kind: 'runtime', message: 'boom after capture' },
  391. } as never
  392. },
  393. })
  394. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  395. const result = await run.result
  396. expect(result.structured).toBeUndefined()
  397. expect(result.stopReason).toBe('error')
  398. expect(adapter.requests).toHaveLength(2)
  399. const child = ctx.agents.get(run.id)!
  400. const outer = child.session.events.find(event =>
  401. event.type === 'tool/result' && event.data.callId === CallId('c1'))
  402. expect(outer?.type === 'tool/result' && outer.data.isError).toBe(true)
  403. await run.dispose()
  404. })
  405. it('discards a nested capture when post-policy blocks the enclosing run_code result', async () => {
  406. const { ctx, parent, adapter } = await setup([
  407. toolCallResponse('c1', RUN_CODE_NAME, { code: 'return await tools.structured_output({ answer: 12 })', description: 'Capture the structured answer' }),
  408. textResponse('outer code was blocked'),
  409. ], {
  410. toolMode: 'code',
  411. codeRun: async (request) => {
  412. const capture = request.bindings.at(0)?.functions[STRUCTURED_OUTPUT_TOOL]
  413. if (!capture) throw new Error('structured_output binding missing')
  414. await capture({ answer: 12 })
  415. return { logs: [], value: 'captured' }
  416. },
  417. })
  418. ctx.on('tools/post-execute', (exec, _result, next) => exec.name === RUN_CODE_NAME
  419. ? Promise.resolve({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'outer blocked' }] })
  420. : next())
  421. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  422. const result = await run.result
  423. expect(result.structured).toBeUndefined()
  424. expect(result.stopReason).toBe('error')
  425. expect(adapter.requests).toHaveLength(2)
  426. await run.dispose()
  427. })
  428. it('the instruction rides ONLY structured requests: appended for the child, absent for a plain agent', async () => {
  429. const { ctx, parent, adapter } = await setup([
  430. textResponse('parent answer'),
  431. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
  432. ])
  433. parent.followup({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } })
  434. await parent.whenIdle()
  435. expect(adapter.requests[0]!.system ?? '').not.toContain(STRUCTURED_OUTPUT_INSTRUCTION)
  436. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  437. await run.result
  438. // The loop always assembles a base prompt (the harness identity section),
  439. // so the instruction APPENDS — never replaces.
  440. const childSystem = adapter.requests.at(-1)!.system!
  441. expect(childSystem.endsWith(STRUCTURED_OUTPUT_INSTRUCTION)).toBe(true)
  442. expect(childSystem.length).toBeGreaterThan(STRUCTURED_OUTPUT_INSTRUCTION.length)
  443. await run.dispose()
  444. })
  445. describe('scoped registration (each child owns its capture tool)', () => {
  446. it('a plain agent never sees the tool: nothing is registered globally at all', async () => {
  447. const { ctx, parent, adapter } = await setup([textResponse('parent answer')])
  448. parent.followup({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } })
  449. await parent.whenIdle()
  450. // Scoped registration: the global view has no capture tool, ever.
  451. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  452. expect(toolNames(adapter.requests[0]!)).not.toContain(STRUCTURED_OUTPUT_TOOL)
  453. })
  454. it('a structured child sees structured_output with ITS schema; a plain agent never sees the tool', async () => {
  455. const { ctx, parent, adapter } = await setup([
  456. // Parent turn (a plain agent): must NOT see the tool.
  457. textResponse('parent answer'),
  458. // Child turn: must see it, with the run's schema.
  459. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
  460. ])
  461. parent.followup({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } })
  462. await parent.whenIdle()
  463. expect(toolNames(adapter.requests[0]!)).not.toContain(STRUCTURED_OUTPUT_TOOL)
  464. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  465. await run.result
  466. const childRequest = adapter.requests[1]!
  467. expect(toolNames(childRequest)).toContain(STRUCTURED_OUTPUT_TOOL)
  468. const entry = childRequest.tools!.find(tool => tool.name === STRUCTURED_OUTPUT_TOOL)!
  469. expect(entry.parameters).toEqual(SCHEMA)
  470. await run.dispose()
  471. })
  472. it('two concurrent structured children each see their OWN schema', async () => {
  473. const otherSchema: ObjectJsonSchema = {
  474. type: 'object',
  475. properties: { verdict: { type: 'string', enum: ['real', 'bogus'] } },
  476. required: ['verdict'],
  477. }
  478. const { ctx, parent, adapter } = await setup([
  479. (options: GenerateOptions) => {
  480. // Answer with whatever schema this child was given — proves each
  481. // request carried the right one regardless of scheduling order.
  482. const entry = options.tools!.find(tool => tool.name === STRUCTURED_OUTPUT_TOOL)!
  483. const args = 'verdict' in (entry.parameters.properties as Record<string, unknown>)
  484. ? { verdict: 'real' }
  485. : { answer: 1 }
  486. return toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, args)
  487. },
  488. (options: GenerateOptions) => {
  489. const entry = options.tools!.find(tool => tool.name === STRUCTURED_OUTPUT_TOOL)!
  490. const args = 'verdict' in (entry.parameters.properties as Record<string, unknown>)
  491. ? { verdict: 'real' }
  492. : { answer: 1 }
  493. return toolCallResponse('c2', STRUCTURED_OUTPUT_TOOL, args)
  494. },
  495. ])
  496. const runA = await ctx.subagents.start('spawn', structuredRequest(parent))
  497. const runB = await ctx.subagents.start('spawn', structuredRequest(parent, { outputSchema: otherSchema }))
  498. const [a, b] = await Promise.all([runA.result, runB.result])
  499. expect(a.structured).toEqual({ answer: 1 })
  500. expect(b.structured).toEqual({ verdict: 'real' })
  501. const schemas = adapter.requests.map(request =>
  502. request.tools!.find(tool => tool.name === STRUCTURED_OUTPUT_TOOL)!.parameters)
  503. expect(schemas).toContainEqual(SCHEMA)
  504. expect(schemas).toContainEqual(otherSchema)
  505. await runA.dispose()
  506. await runB.dispose()
  507. })
  508. it('places the capture tool and instruction in their canonical orders', async () => {
  509. const { ctx, parent, adapter } = await setup([
  510. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
  511. ])
  512. // A global tool sorts lexicographically after structured_output, while a
  513. // global section above the 190 band follows the capture instruction.
  514. ctx.tools.register(defineContentToolFixture({
  515. name: 'zz_probe',
  516. description: 'probe',
  517. parameters: {},
  518. execute: () => Promise.resolve([{ type: 'text', text: 'x' }]),
  519. }))
  520. ctx.systemPrompt.section({ name: 'after-band', order: 200, text: 'AFTER-BAND' })
  521. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  522. await run.result
  523. const request = adapter.requests[0]!
  524. const names = toolNames(request)
  525. expect(names.indexOf(STRUCTURED_OUTPUT_TOOL)).toBeGreaterThanOrEqual(0)
  526. expect(names.indexOf(STRUCTURED_OUTPUT_TOOL)).toBeLessThan(names.indexOf('zz_probe'))
  527. const system = request.system ?? ''
  528. const instructionAt = system.indexOf(STRUCTURED_OUTPUT_INSTRUCTION)
  529. expect(instructionAt).toBeGreaterThanOrEqual(0)
  530. expect(system.indexOf('AFTER-BAND')).toBeGreaterThan(instructionAt)
  531. await run.dispose()
  532. })
  533. it('a non-structured agent request keeps tools ABSENT when it had none (no tools: [] materialized)', async () => {
  534. const { parent, adapter } = await setup([textResponse('plain')])
  535. parent.followup({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } })
  536. await parent.whenIdle()
  537. const request = adapter.requests[0]!
  538. expect(request.tools).toBeUndefined()
  539. await new Promise(resolve => setTimeout(resolve, 0))
  540. })
  541. it('registrations ride the child fiber: disposing the run removes them; a provider reload mid-run cannot', async () => {
  542. const { ctx, parent, disposeProvider } = await setup([
  543. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 4 }),
  544. ])
  545. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  546. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  547. // A backend hot-reload mid-run must not unregister the capture tool out
  548. // from under the live child: the registration rides the CHILD's fiber.
  549. disposeProvider()
  550. const result = await run.result
  551. expect(result.structured).toEqual({ answer: 4 })
  552. const child = ctx.agents.get(run.id)!
  553. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL, child)).toBeDefined()
  554. await run.dispose()
  555. // Child disposed ⇒ its scoped registrations are gone.
  556. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL, child)).toBeUndefined()
  557. })
  558. })
  559. it('a structured_output call from an agent WITHOUT a structured run is UNKNOWN_TOOL (the tool does not exist for it)', async () => {
  560. const { ctx, parent } = await setup([])
  561. const result = await ctx.tools.execute({
  562. signal: testToolSignal,
  563. callId: 'x' as never,
  564. name: STRUCTURED_OUTPUT_TOOL,
  565. arguments: { answer: 1 },
  566. agent: parent,
  567. })
  568. expect(result.isError).toBe(true)
  569. expect(result.error?.info?.code).toBe('UNKNOWN_TOOL')
  570. })
  571. it('a structured_output call with NO calling agent at all is UNKNOWN_TOOL', async () => {
  572. const { ctx } = await setup([])
  573. const result = await ctx.tools.execute({
  574. signal: testToolSignal,
  575. callId: 'x' as never,
  576. name: STRUCTURED_OUTPUT_TOOL,
  577. arguments: { answer: 1 },
  578. })
  579. expect(result.isError).toBe(true)
  580. expect(result.error?.info?.code).toBe('UNKNOWN_TOOL')
  581. })
  582. it('a failed execution stage is discarded and never promoted by a later call', async () => {
  583. const { ctx, parent } = await setup([
  584. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
  585. ])
  586. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  587. // A prepended post-execute listener blocks the first capture without
  588. // delegating. The final-result notification discards that execution's
  589. // stage when it observes the error.
  590. let blocks = 1
  591. ctx.on('tools/post-execute', (exec, _result, next) => {
  592. if (exec.name === STRUCTURED_OUTPUT_TOOL && blocks > 0) {
  593. blocks -= 1
  594. return Promise.resolve({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'rejected' }] })
  595. }
  596. return next()
  597. }, { prepend: true })
  598. const result = await run.result
  599. const child = ctx.agents.get(run.id)!
  600. // The blocked capture must NOT surface as structured success…
  601. expect(result.stopReason).toBe('error')
  602. expect(result.structured).toBeUndefined()
  603. // …and a LATER invalid call (its own body staged nothing) must not
  604. // resurrect c1's discarded value: drive the pipeline directly.
  605. const invalid = await ctx.tools.execute({
  606. signal: testToolSignal,
  607. callId: 'c2' as never,
  608. name: STRUCTURED_OUTPUT_TOOL,
  609. arguments: { answer: 'not-a-number' },
  610. agent: child,
  611. })
  612. expect(invalid.isError).toBe(true)
  613. // A fresh valid call still captures ITS OWN value.
  614. const valid = await ctx.tools.execute({
  615. signal: testToolSignal,
  616. callId: 'c3' as never,
  617. name: STRUCTURED_OUTPUT_TOOL,
  618. arguments: { answer: 9 },
  619. agent: child,
  620. })
  621. expect(valid.isError).toBeFalsy()
  622. await run.dispose()
  623. })
  624. it('reusing a failed execution\'s call id never promotes its discarded stage', async () => {
  625. const { ctx, parent } = await setup([
  626. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
  627. ])
  628. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  629. // Block the first capture after its body stages a value. Its final error
  630. // discards that execution's stage.
  631. let blocks = 1
  632. ctx.on('tools/post-execute', (exec, _result, next) => {
  633. if (exec.name === STRUCTURED_OUTPUT_TOOL && blocks > 0) {
  634. blocks -= 1
  635. return Promise.resolve({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'rejected' }] })
  636. }
  637. return next()
  638. }, { prepend: true })
  639. await run.result
  640. const child = ctx.agents.get(run.id)!
  641. // A SECOND capture call with the SAME call id whose body never stages
  642. // (invalid args throw before the stage): the discarded value must not ride
  643. // its acceptance.
  644. const reused = await ctx.tools.execute({
  645. signal: testToolSignal,
  646. callId: 'c1' as never,
  647. name: STRUCTURED_OUTPUT_TOOL,
  648. arguments: { answer: 'not-a-number' },
  649. agent: child,
  650. })
  651. expect(reused.isError).toBe(true)
  652. // Nothing was ever committed: a fresh valid call is still required.
  653. const valid = await ctx.tools.execute({
  654. signal: testToolSignal,
  655. callId: 'c1' as never,
  656. name: STRUCTURED_OUTPUT_TOOL,
  657. arguments: { answer: 5 },
  658. agent: child,
  659. })
  660. expect(valid.isError).toBeFalsy()
  661. await run.dispose()
  662. })
  663. it('a pre-execute deny with call-id reuse cannot promote another execution\'s stage', async () => {
  664. const { ctx, parent } = await setup([
  665. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
  666. ])
  667. const run = await ctx.subagents.start('spawn', structuredRequest(parent))
  668. // Discard the first capture's stage via a final post-execute block.
  669. let blocks = 1
  670. ctx.on('tools/post-execute', (exec, _result, next) => {
  671. if (exec.name === STRUCTURED_OUTPUT_TOOL && blocks > 0) {
  672. blocks -= 1
  673. return Promise.resolve({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'rejected' }] })
  674. }
  675. return next()
  676. }, { prepend: true })
  677. await run.result
  678. const child = ctx.agents.get(run.id)!
  679. // A prepended pre-execute deny skips the body, while the denied call still
  680. // reaches the final notification with the same adapter-minted call id.
  681. const offDeny = ctx.on('tools/pre-execute', (exec) => {
  682. if (exec.name === STRUCTURED_OUTPUT_TOOL) {
  683. return Promise.resolve({ kind: 'deny' as const, reason: 'outer veto' })
  684. }
  685. return undefined as never
  686. }, { prepend: true })
  687. const denied = await ctx.tools.execute({
  688. signal: testToolSignal,
  689. callId: 'c1' as never,
  690. name: STRUCTURED_OUTPUT_TOOL,
  691. arguments: { answer: 2 },
  692. agent: child,
  693. })
  694. expect(denied.isError).toBe(true)
  695. offDeny()
  696. // The discarded value was never promoted: a fresh valid call is required
  697. // (and succeeds, proving the runtime is not wedged).
  698. const valid = await ctx.tools.execute({
  699. signal: testToolSignal,
  700. callId: 'c1' as never,
  701. name: STRUCTURED_OUTPUT_TOOL,
  702. arguments: { answer: 5 },
  703. agent: child,
  704. })
  705. expect(valid.isError).toBeFalsy()
  706. await run.dispose()
  707. })
  708. })