structured.spec.ts 35 KB

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