Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.middleware-test.ts

842 lines27.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createCapability,
6 EventType,
7 maxIterations,
8 toServerSentEventsResponse,
9 toolDefinition,
10} from '@tanstack/ai'
11import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
12import { memoryMiddleware } from '@tanstack/ai-memory'
13import type { MemoryAdapter } from '@tanstack/ai-memory'
14import { clientContextToolDefinition } from '@/lib/middleware-test-tools'
15import {
16 getMemoryCapture,
17 recordMemoryConfig,
18 recordMemorySave,
19 resetMemoryCapture,
20} from '@/lib/memory-capture'
21import { SpanStatusCode } from '@opentelemetry/api'
22import { z } from 'zod'
23import type {
24 AnyTextAdapter,
25 ChatMiddleware,
26 StreamChunk,
27 Tool,
28} from '@tanstack/ai'
29import type {
30 AttributeValue,
31 Attributes,
32 Context,
33 Histogram,
34 Meter,
35 MetricOptions,
36 Span,
37 SpanContext,
38 SpanStatus,
39 Tracer,
40} from '@opentelemetry/api'
41import { guitarRecommendationSchema } from '@/lib/schemas'
42import {
43 getPhaseCapture,
44 recordGenericBoundary,
45 recordGenericPolicy,
46 recordGenericResolution,
47 recordGenericToolExecution,
48 recordOnError,
49 recordOnFinish,
50 recordPhase,
51 recordYieldedChunk,
52 resetPhaseCapture,
53} from '@/lib/phase-capture'
54import {
55 boundaryForScenario,
56 deleteReviewTool,
57 inspectReviewTool,
58 isGenericScenario,
59 renderReviewTool,
60 reviewPlan,
61 toolResumeForScenario,
62} from '@/lib/generic-middleware-interrupts'
63import type { GenericScenario } from '@/lib/generic-middleware-interrupts'
64import { createTextAdapter } from '@/lib/providers'
65import {
66 getOtelCapture,
67 recordOtelEvent,
68 recordOtelException,
69 recordOtelHistogram,
70 recordOtelSpan,
71 resetOtelCapture,
72} from '@/lib/otel-capture'
73​
74// The otel capture endpoint is only useful during E2E runs. Gate both the
75// POST 'otel' mode and the GET capture fetch behind this flag so the route
76// cannot be used as an oracle in a production-like build.
77const OTEL_TEST_ENABLED =
78 process.env.E2E_TEST === '1' || process.env.NODE_ENV !== 'production'
79​
80const weatherTool = toolDefinition({
81 name: 'get_weather',
82 description: 'Get weather',
83 inputSchema: z.object({ city: z.string() }),
84}).server(async (args) =>
85 JSON.stringify({ city: args.city, temperature: 72, condition: 'sunny' }),
87​
88function createRunErrorAdapter(): AnyTextAdapter {
89 return {
90 kind: 'text',
91 name: 'run-error-test',
92 model: 'run-error-test',
93 '~types': {
94 providerOptions: {},
95 inputModalities: ['text'],
96 messageMetadataByModality: {},
97 toolCapabilities: [],
98 toolCallMetadata: undefined,
99 systemPromptMetadata: undefined,
100 },
101 async *chatStream(options): AsyncGenerator<StreamChunk> {
102 yield {
103 type: EventType.RUN_STARTED,
104 runId: options.runId ?? 'run-error-test',
105 threadId: options.threadId ?? 'run-error-test',
106 timestamp: Date.now(),
107 }
108 yield {
109 type: EventType.RUN_ERROR,
110 message: 'Provider failed',
111 code: 'provider_error',
112 timestamp: Date.now(),
113 }
114 },
115 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
116 }
118​
119const runErrorBoundaryMiddleware: ChatMiddleware<unknown, typeof reviewPlan> = {
120 name: 'run-error-boundary',
121 onInterruptBoundary(ctx) {
122 if (ctx.phase !== 'afterModel') return
123 return {
124 interrupts: [
125 reviewPlan.interrupt({
126 key: 'run-error-review',
127 reason: 'review_required',
128 message: 'Review the response',
129 payload: { title: 'Run error review', boundary: ctx.phase },
130 }),
131 ],
132 }
133 },
135​
136/** The adapter's accumulated `content`. The AG-UI 1.0 event type omits it. */
137function accumulated(chunk: StreamChunk): string {
138 const content: unknown = Reflect.get(chunk, 'content')
139 return typeof content === 'string' ? content : ''
141​
142const chunkTransformMiddleware: ChatMiddleware = {
143 name: 'chunk-transform',
144 onChunk(_ctx, chunk) {
145 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
146 return {
147 ...chunk,
148 delta: '[MW] ' + chunk.delta,
149 content: '[MW] ' + accumulated(chunk),
150 }
151 }
152 return chunk
153 },
155​
156const toolSkipMiddleware: ChatMiddleware = {
157 name: 'tool-skip',
158 onBeforeToolCall(_ctx, hookCtx) {
159 if (hookCtx.toolName === 'get_weather') {
160 return {
161 type: 'skip' as const,
162 result: JSON.stringify({ skipped: true, reason: 'middleware' }),
163 }
164 }
165 return undefined
166 },
168​
169const toolReplaceMiddleware: ChatMiddleware = {
170 name: 'tool-replace',
171 onAfterToolCall(_ctx, info) {
172 if (info.toolName !== 'get_weather') return
173 return {
174 type: 'replaceResult',
175 result: { replaced: true, reason: 'middleware' },
176 }
177 },
179​
180// Rewrites the args to a value the tool's inputSchema rejects. The final
181// input check runs after this hook, so the tool must not run.
182const toolBadArgsMiddleware: ChatMiddleware = {
183 name: 'tool-bad-args',
184 onBeforeToolCall(_ctx, hookCtx) {
185 if (hookCtx.toolName !== 'get_weather') return undefined
186 return { type: 'transformArgs' as const, args: { city: { name: 'NYC' } } }
187 },
189​
190// `tool-guard` mode: the first middleware rewrites the city, so
191// onBeforeToolCall is done. The guard still runs, sees the rewritten city,
192// and denies the call.
193const toolRewriteMiddleware: ChatMiddleware = {
194 name: 'tool-rewrite',
195 onBeforeToolCall(_ctx, hookCtx) {
196 if (hookCtx.toolName !== 'get_weather') return undefined
197 return { type: 'transformArgs' as const, args: { city: 'Blocked City' } }
198 },
200​
201const toolGuardMiddleware: ChatMiddleware = {
202 name: 'tool-guard',
203 onGuardToolCall(_ctx, hookCtx) {
204 const args = hookCtx.args
205 const city =
206 typeof args === 'object' && args !== null && 'city' in args
207 ? args.city
208 : undefined
209 if (hookCtx.toolName !== 'get_weather' || city !== 'Blocked City') return
210 return {
211 type: 'skip' as const,
212 result: JSON.stringify({ guarded: true, city }),
213 }
214 },
216​
217/**
218 * Capability provide/consume flow (`capability` mode).
219 *
220 * Exercises the server-side middleware capability primitive end-to-end:
221 *
222 * - `prefixCapability` is a typed handle created via `createCapability`. It is
223 * simultaneously a `[get, provide]` tuple and the identity referenced in the
224 * middleware `provides`/`requires` declarations.
225 * - `prefixProviderMiddleware` declares `provides: [prefixCapability]` and calls
226 * `providePrefix(ctx, ...)` in `setup` — the hook that runs first, before any
227 * `onConfig`/`onChunk`.
228 * - `prefixConsumerMiddleware` declares `requires: [prefixCapability]` and reads
229 * the value with `getPrefix(ctx)` inside `onChunk`, using it to prefix every
230 * text delta. The consumed value therefore shows up verbatim in the streamed
231 * assistant text, which the spec asserts against the deterministic fixture.
232 */
233const prefixCapability = createCapability<string>()('capability-prefix')
234const [getPrefix, providePrefix] = prefixCapability
235​
236const prefixProviderMiddleware: ChatMiddleware = {
237 name: 'prefix-provider',
238 provides: [prefixCapability],
239 setup(ctx) {
240 providePrefix(ctx, '[CAP]')
241 },
243​
244const prefixConsumerMiddleware: ChatMiddleware = {
245 name: 'prefix-consumer',
246 requires: [prefixCapability],
247 onChunk(ctx, chunk) {
248 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
249 const prefix = getPrefix(ctx)
250 return {
251 ...chunk,
252 delta: prefix + ' ' + chunk.delta,
253 content: prefix + ' ' + accumulated(chunk),
254 }
255 }
256 return chunk
257 },
259​
260/**
261 * Per-testId recorder used by `phase-recorder` mode.
262 *
263 * Captures every `ctx.phase` observed during `onChunk` and counts `onFinish`
264 * invocations. The capture is stored in a module-global keyed by `testId` so
265 * the page can fetch it via `GET /api/middleware-test?testId=...&kind=phase`
266 * after the run finishes.
267 *
268 * Why a factory: middleware closes over `captureId` so we don't have to thread
269 * a per-request shim through global state.
270 */
271function createPhaseRecorderMiddleware(captureId: string): ChatMiddleware {
272 return {
273 name: 'phase-recorder',
274 onChunk(ctx, chunk) {
275 recordPhase(captureId, ctx.phase)
276 return chunk
277 },
278 onFinish() {
279 recordOnFinish(captureId)
280 },
281 onError() {
282 recordOnError(captureId)
283 },
284 }
286​
287/**
288 * Wraps a chat stream so every chunk that leaves `chat()` (post-middleware)
289 * is recorded into the per-testId phase capture as a yielded chunk. Used by
290 * `phase-recorder` mode to let the spec assert what the consumer actually
291 * sees — distinct from what `onChunk` observes inside the middleware chain.
292 */
293async function* teeForPhaseCapture(
294 source: AsyncIterable<StreamChunk>,
295 captureId: string,
296): AsyncIterable<StreamChunk> {
297 let currentRunId: string | undefined
298 for await (const chunk of source) {
299 if (chunk.type === 'RUN_STARTED' && typeof chunk.runId === 'string') {
300 currentRunId = chunk.runId
301 }
302 const runId =
303 'runId' in chunk && typeof chunk.runId === 'string'
304 ? chunk.runId
305 : currentRunId
306 recordYieldedChunk(captureId, {
307 type: chunk.type,
308 ...(runId !== undefined ? { runId } : {}),
309 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome
310 ? { outcomeType: chunk.outcome.type }
311 : {}),
312 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt'
313 ? { interruptCount: chunk.outcome.interrupts.length }
314 : {}),
315 })
316 yield chunk
317 }
319​
320function lifecycleMiddlewareStack(
321 existing: Array<ChatMiddleware>,
322 extra: ChatMiddleware<unknown, typeof reviewPlan>,
323): Array<ChatMiddleware<unknown, typeof reviewPlan>> {
324 return [...existing, extra]
326​
327function createGenericLifecycleMiddleware(
328 captureId: string,
329 scenario: GenericScenario,
330): ChatMiddleware<unknown, typeof reviewPlan> {
331 const boundary = boundaryForScenario(scenario)
332 return {
333 name: 'generic-lifecycle',
334 onInterruptBoundary(ctx) {
335 if (ctx.phase !== boundary || ctx.parentRunId) return
336 recordGenericBoundary(captureId, { phase: ctx.phase, runId: ctx.runId })
337 return {
338 interrupts: [
339 reviewPlan.interrupt({
340 key: `${scenario}-review`,
341 reason: 'review_required',
342 message: `Review the plan at ${ctx.phase}`,
343 payload: { title: 'Middleware review plan', boundary: ctx.phase },
344 }),
345 ],
346 }
347 },
348 onInterruptResolution(_ctx, resolutions) {
349 for (const resolution of resolutions.for(reviewPlan)) {
350 recordGenericResolution(captureId, {
351 definitionId: resolution.request.definition.id,
352 status: resolution.status,
353 ...(resolution.status === 'resolved'
354 ? { response: resolution.response }
355 : {}),
356 })
357 }
358 const policy = toolResumeForScenario(scenario)
359 recordGenericPolicy(captureId, policy)
360 return { toolResume: policy }
361 },
362 }
364​
365function genericTools(captureId: string, scenario: GenericScenario) {
366 if (scenario === 'generic-after-tools') {
367 return [
368 inspectReviewTool.server(async ({ reviewId }) => {
369 recordGenericToolExecution(captureId, {
370 name: 'inspect_review',
371 side: 'server',
372 })
373 return { inspected: true, reviewId }
374 }),
375 ]
376 }
377 if (boundaryForScenario(scenario) !== 'beforeTools') return []
378 return [
379 deleteReviewTool.server(async ({ reviewId }) => {
380 recordGenericToolExecution(captureId, {
381 name: 'delete_review',
382 side: 'server',
383 })
384 return { deleted: true, reviewId }
385 }),
386 renderReviewTool.client(),
387 ]
389​
390/**
391 * Fake memory adapter for `memory` mode. `recall` unconditionally returns a
392 * known system-prompt block plus a memory tool (so the spec can assert both the
393 * prompt injection AND tool injection reach the model config), and `save`
394 * records that the deferred write ran. Deterministic — no real vendor, no
395 * cross-request state.
396 */
397const RECALL_MORE_TOOL: Tool = {
398 name: 'recall_more',
399 description: 'Look up additional long-term memory by query.',
400 inputSchema: { type: 'object', properties: {}, additionalProperties: false },
402​
403function createFakeMemoryAdapter(captureId: string): MemoryAdapter {
404 return {
405 id: 'fake-memory',
406 recall: async () => ({
407 systemPrompt: 'MEMORY: the user previously said they love TanStack.',
408 fragments: [{ text: 'the user loves TanStack', source: 'f1' }],
409 tools: [RECALL_MORE_TOOL],
410 toolGuidance: 'Use recall_more to look up additional memory when needed.',
411 }),
412 save: async () => {
413 recordMemorySave(captureId)
414 return [{ ok: true }]
415 },
416 }
418​
419/**
420 * Recorder placed AFTER `memoryMiddleware` so it observes the config the model
421 * actually sees — i.e. WITH the recalled system prompt + tools already merged
422 * in. Records that into the per-testId memory capture.
423 */
424function createMemoryConfigRecorder(captureId: string): ChatMiddleware {
425 return {
426 name: 'memory-config-recorder',
427 onConfig(ctx, config) {
428 if (ctx.phase !== 'init') return
429 recordMemoryConfig(captureId, {
430 systemPrompts: config.systemPrompts.map((p) =>
431 typeof p === 'string' ? p : p.content,
432 ),
433 toolNames: config.tools.map((t) => t.name),
434 })
435 return
436 },
437 }
439​
440// Minimal in-memory tracer/meter. Captures into a per-testId bucket so that
441// the Playwright spec can fetch the recorded state via GET after the stream
442// finishes. Not exported — only used to build otelMiddleware for the test.
443function createCaptureTracer(captureId: string): Tracer {
444 let spanSeq = 0
445 const tracer: Tracer = {
446 startSpan(name, options = {}, _ctx?: Context): Span {
447 const id = `span-${spanSeq++}`
448 const attrs: Record<string, AttributeValue> = {}
449 for (const [k, v] of Object.entries(options.attributes ?? {})) {
450 if (v !== undefined) attrs[k] = v
451 }
452 recordOtelSpan(captureId, {
453 id,
454 name,
455 kind: options.kind,
456 attributes: attrs,
457 status: SpanStatusCode.UNSET,
458 events: [],
459 exceptions: [],
460 ended: false,
461 })
462 const status: SpanStatus = { code: SpanStatusCode.UNSET }
463 let ended = false
464 const span: Span = {
465 spanContext(): SpanContext {
466 return { traceId: 'capture-trace', spanId: id, traceFlags: 1 }
467 },
468 setAttribute(key, value) {
469 attrs[key] = value
470 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
471 return span
472 },
473 setAttributes(next) {
474 for (const [k, v] of Object.entries(next)) {
475 attrs[k] = v as AttributeValue
476 }
477 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
478 return span
479 },
480 addEvent(eventName, eventAttrs) {
481 recordOtelEvent(captureId, id, {
482 name: eventName,
483 attributes: eventAttrs as Attributes | undefined,
484 })
485 return span
486 },
487 addLink() {
488 return span
489 },
490 addLinks() {
491 return span
492 },
493 setStatus(next) {
494 status.code = next.code
495 status.message = next.message
496 recordOtelSpan(captureId, {
497 id,
498 patch: { status: next.code, statusMessage: next.message },
499 })
500 return span
501 },
502 updateName(next) {
503 recordOtelSpan(captureId, { id, patch: { name: next } })
504 return span
505 },
506 end() {
507 ended = true
508 recordOtelSpan(captureId, { id, patch: { ended: true } })
509 },
510 isRecording() {
511 return !ended
512 },
513 recordException(exception, exceptionAttrs) {
514 recordOtelException(captureId, id, {
515 exception: String(
516 (exception as { message?: string } | undefined)?.message ??
517 exception,
518 ),
519 attributes: exceptionAttrs as Attributes | undefined,
520 })
521 },
522 }
523 return span
524 },
525 // Minimal implementation — our middleware never calls startActiveSpan.
526​
527 startActiveSpan(...args: Array<any>) {
528 const fn = args[args.length - 1] as (span: Span) => unknown
529 const name = args[0] as string
530 const span = tracer.startSpan(name, {})
531 try {
532 return fn(span)
533 } finally {
534 span.end()
535 }
536 },
537 }
538 return tracer
540​
541function createCaptureMeter(captureId: string): Meter {
542 const histogram = (name: string, options?: MetricOptions): Histogram => ({
543 record(value: number, attributes?: Attributes) {
544 recordOtelHistogram(captureId, {
545 name,
546 value,
547 attributes,
548 unit: options?.unit,
549 })
550 },
551 })
552 return {
553 createHistogram: histogram,
554 } as any as Meter
556​
557export const Route = createFileRoute('/api/middleware-test')({
558 server: {
559 handlers: {
560 POST: async ({ request }) => {
561 if (request.signal?.aborted) return new Response(null, { status: 499 })
562 const abortController = new AbortController()
563​
564 let params
565 try {
566 params = await chatParamsFromRequestBody(await request.json())
567 } catch (error) {
568 return new Response(
569 error instanceof Error ? error.message : 'Bad request',
570 { status: 400 },
571 )
572 }
573​
574 const fp = params.forwardedProps
575 const scenario =
576 typeof fp.scenario === 'string' ? fp.scenario : 'basic-text'
577 const middlewareMode =
578 typeof fp.middlewareMode === 'string' ? fp.middlewareMode : 'none'
579 const testId: string | undefined =
580 typeof fp.testId === 'string' ? fp.testId : undefined
581 const aimockPort: number | undefined =
582 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
583 // Provider/model overrides let the middleware E2E exercise both the
584 // native-combined-mode path (modern OpenAI / Claude 4.5+ — no
585 // `structuredOutput` phase, single combined call) and the legacy
586 // finalization path (Claude 3.7, etc. — `structuredOutput` phase
587 // fires). See #605.
588 const provider =
589 typeof fp.provider === 'string' ? fp.provider : 'openai'
590 const modelOverride =
591 typeof fp.model === 'string' ? fp.model : undefined
592​
593 try {
594 const adapterOptions =
595 scenario === 'run-error'
596 ? { adapter: createRunErrorAdapter() }
597 : createTextAdapter(
598 provider as Parameters<typeof createTextAdapter>[0],
599 modelOverride,
600 aimockPort,
601 testId,
602 )
603​
604 const middleware: Array<ChatMiddleware> = []
605 let genericLifecycleMiddleware:
606 | ChatMiddleware<unknown, typeof reviewPlan>
607 | undefined =
608 scenario === 'run-error' ? runErrorBoundaryMiddleware : undefined
609 const genericScenario = isGenericScenario(scenario)
610 ? scenario
611 : undefined
612​
613 if (middlewareMode === 'chunk-transform')
614 middleware.push(chunkTransformMiddleware)
615 if (middlewareMode === 'tool-skip')
616 middleware.push(toolSkipMiddleware)
617 if (middlewareMode === 'tool-replace')
618 middleware.push(toolReplaceMiddleware)
619 if (middlewareMode === 'tool-bad-args')
620 middleware.push(toolBadArgsMiddleware)
621 if (middlewareMode === 'tool-guard')
622 middleware.push(toolRewriteMiddleware, toolGuardMiddleware)
623 if (middlewareMode === 'capability') {
624 // Order matters: the provider's setup() must run before the
625 // consumer reads the capability. Array order is preserved.
626 middleware.push(prefixProviderMiddleware, prefixConsumerMiddleware)
627 }
628 if (middlewareMode === 'phase-recorder') {
629 if (!testId) {
630 return new Response(
631 JSON.stringify({
632 error: 'phase-recorder mode requires testId',
633 }),
634 {
635 status: 400,
636 headers: { 'Content-Type': 'application/json' },
637 },
638 )
639 }
640 resetPhaseCapture(testId)
641 middleware.push(createPhaseRecorderMiddleware(testId))
642 }
643 if (middlewareMode === 'generic-lifecycle') {
644 if (!testId || !genericScenario) {
645 return new Response(
646 JSON.stringify({
647 error:
648 'generic-lifecycle mode requires testId and a generic scenario',
649 }),
650 {
651 status: 400,
652 headers: { 'Content-Type': 'application/json' },
653 },
654 )
655 }
656 if (!params.parentRunId) resetPhaseCapture(testId)
657 genericLifecycleMiddleware = createGenericLifecycleMiddleware(
658 testId,
659 genericScenario,
660 )
661 }
662 if (middlewareMode === 'memory') {
663 if (!testId) {
664 return new Response(
665 JSON.stringify({ error: 'memory mode requires testId' }),
666 {
667 status: 400,
668 headers: { 'Content-Type': 'application/json' },
669 },
670 )
671 }
672 resetMemoryCapture(testId)
673 middleware.push(
674 memoryMiddleware({
675 adapter: createFakeMemoryAdapter(testId),
676 scope: { threadId: testId },
677 }),
678 createMemoryConfigRecorder(testId),
679 )
680 }
681 if (middlewareMode === 'otel') {
682 if (!OTEL_TEST_ENABLED) {
683 return new Response(null, { status: 404 })
684 }
685 if (!testId) {
686 return new Response(
687 JSON.stringify({ error: 'otel mode requires testId' }),
688 {
689 status: 400,
690 headers: { 'Content-Type': 'application/json' },
691 },
692 )
693 }
694 resetOtelCapture(testId)
695 middleware.push(
696 otelMiddleware({
697 tracer: createCaptureTracer(testId),
698 meter: createCaptureMeter(testId),
699 captureContent: true,
700 }),
701 )
702 }
703​
704 const tools =
705 genericScenario && testId
706 ? genericTools(testId, genericScenario)
707 : scenario === 'with-tool' || scenario === 'raw-tool-args'
708 ? [weatherTool]
709 : scenario === 'structured-client-tool-wait'
710 ? [clientContextToolDefinition]
711 : []
712​
713 // Structured scenarios bind the same guitar schema. The client-tool
714 // variant also passes an isomorphic tool definition so the first
715 // server invocation can stop at the browser-execution boundary.
716 const isStructured =
717 scenario === 'structured-output' ||
718 scenario === 'structured-output-stream' ||
719 scenario === 'structured-client-tool-wait'
720​
721 const rawStream = isStructured
722 ? chat({
723 ...adapterOptions,
724 messages: params.messages,
725 tools,
726 middleware,
727 threadId: params.threadId,
728 runId: params.runId,
729 outputSchema: guitarRecommendationSchema,
730 stream: true,
731 abortController,
732 })
733 : genericLifecycleMiddleware
734 ? chat({
735 ...adapterOptions,
736 messages: params.messages,
737 tools,
738 middleware: lifecycleMiddlewareStack(
739 middleware,
740 genericLifecycleMiddleware,
741 ),
742 threadId: params.threadId,
743 runId: params.runId,
744 parentRunId: params.parentRunId,
745 resume: params.resume,
746 interrupts: [reviewPlan] as const,
747 agentLoopStrategy: maxIterations(10),
748 abortController,
749 })
750 : chat({
751 ...adapterOptions,
752 messages: params.messages,
753 tools,
754 middleware,
755 threadId: params.threadId,
756 runId: params.runId,
757 parentRunId: params.parentRunId,
758 resume: params.resume,
759 interrupts: genericScenario ? [reviewPlan] : undefined,
760 agentLoopStrategy: maxIterations(10),
761 abortController,
762 })
763​
764 // Tee the post-middleware stream when `phase-recorder` is active
765 // so the spec can assert on what the consumer ultimately sees
766 // (e.g. exactly one RUN_STARTED/RUN_FINISHED pair).
767 const stream =
768 (middlewareMode === 'phase-recorder' ||
769 middlewareMode === 'generic-lifecycle') &&
770 testId
771 ? teeForPhaseCapture(rawStream, testId)
772 : rawStream
773​
774 return toServerSentEventsResponse(stream, { abortController })
775 } catch (error: any) {
776 console.error('[api.middleware-test] Error:', error.message)
777 if (error.name === 'AbortError' || abortController.signal.aborted) {
778 return new Response(null, { status: 499 })
779 }
780 return new Response(JSON.stringify({ error: error.message }), {
781 status: 500,
782 headers: { 'Content-Type': 'application/json' },
783 })
784 }
785 },
786 GET: async ({ request }) => {
787 const url = new URL(request.url)
788 const testId = url.searchParams.get('testId')
789 const kind = url.searchParams.get('kind')
790​
791 // Phase capture is independent of OTEL — keep it available without
792 // requiring the OTEL_TEST_ENABLED gate so that the structured-output
793 // middleware spec works under any harness build configuration.
794 if (kind === 'phase') {
795 if (!testId) {
796 return new Response(
797 JSON.stringify({ error: 'testId query param required' }),
798 {
799 status: 400,
800 headers: { 'Content-Type': 'application/json' },
801 },
802 )
803 }
804 return new Response(JSON.stringify(getPhaseCapture(testId)), {
805 headers: { 'Content-Type': 'application/json' },
806 })
807 }
808​
809 // Memory capture — like phase capture, available without the OTEL gate.
810 if (kind === 'memory') {
811 if (!testId) {
812 return new Response(
813 JSON.stringify({ error: 'testId query param required' }),
814 { status: 400, headers: { 'Content-Type': 'application/json' } },
815 )
816 }
817 return new Response(JSON.stringify(getMemoryCapture(testId)), {
818 headers: { 'Content-Type': 'application/json' },
819 })
820 }
821​
822 // OTEL capture remains gated — the GET cannot act as an oracle in a
823 // production-like build.
824 if (!OTEL_TEST_ENABLED) {
825 return new Response(null, { status: 404 })
826 }
827 if (!testId) {
828 return new Response(
829 JSON.stringify({ error: 'testId query param required' }),
830 {
831 status: 400,
832 headers: { 'Content-Type': 'application/json' },
833 },
834 )
835 }
836 return new Response(JSON.stringify(getOtelCapture(testId)), {
837 headers: { 'Content-Type': 'application/json' },
838 })
839 },
840 },
841 },
842})