structured.spec.ts 35 KB

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