Open History to see the last commit
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' }),
86)
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 }
117}
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 },
134}
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 : ''
140}
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 },
154}
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 },
167}
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 },
178}
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 },
188}
189
190/**
191 * Capability provide/consume flow (`capability` mode).
192 *
193 * Exercises the server-side middleware capability primitive end-to-end:
194 *
195 * - `prefixCapability` is a typed handle created via `createCapability`. It is
196 * simultaneously a `[get, provide]` tuple and the identity referenced in the
197 * middleware `provides`/`requires` declarations.
198 * - `prefixProviderMiddleware` declares `provides: [prefixCapability]` and calls
199 * `providePrefix(ctx, ...)` in `setup` — the hook that runs first, before any
200 * `onConfig`/`onChunk`.
201 * - `prefixConsumerMiddleware` declares `requires: [prefixCapability]` and reads
202 * the value with `getPrefix(ctx)` inside `onChunk`, using it to prefix every
203 * text delta. The consumed value therefore shows up verbatim in the streamed
204 * assistant text, which the spec asserts against the deterministic fixture.
205 */
206const prefixCapability = createCapability<string>()('capability-prefix')
207const [getPrefix, providePrefix] = prefixCapability
208
209const prefixProviderMiddleware: ChatMiddleware = {
210 name: 'prefix-provider',
211 provides: [prefixCapability],
212 setup(ctx) {
213 providePrefix(ctx, '[CAP]')
214 },
215}
216
217const prefixConsumerMiddleware: ChatMiddleware = {
218 name: 'prefix-consumer',
219 requires: [prefixCapability],
220 onChunk(ctx, chunk) {
221 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
222 const prefix = getPrefix(ctx)
223 return {
224 ...chunk,
225 delta: prefix + ' ' + chunk.delta,
226 content: prefix + ' ' + accumulated(chunk),
227 }
228 }
229 return chunk
230 },
231}
232
233/**
234 * Per-testId recorder used by `phase-recorder` mode.
235 *
236 * Captures every `ctx.phase` observed during `onChunk` and counts `onFinish`
237 * invocations. The capture is stored in a module-global keyed by `testId` so
238 * the page can fetch it via `GET /api/middleware-test?testId=...&kind=phase`
239 * after the run finishes.
240 *
241 * Why a factory: middleware closes over `captureId` so we don't have to thread
242 * a per-request shim through global state.
243 */
244function createPhaseRecorderMiddleware(captureId: string): ChatMiddleware {
245 return {
246 name: 'phase-recorder',
247 onChunk(ctx, chunk) {
248 recordPhase(captureId, ctx.phase)
249 return chunk
250 },
251 onFinish() {
252 recordOnFinish(captureId)
253 },
254 onError() {
255 recordOnError(captureId)
256 },
257 }
258}
259
260/**
261 * Wraps a chat stream so every chunk that leaves `chat()` (post-middleware)
262 * is recorded into the per-testId phase capture as a yielded chunk. Used by
263 * `phase-recorder` mode to let the spec assert what the consumer actually
264 * sees — distinct from what `onChunk` observes inside the middleware chain.
265 */
266async function* teeForPhaseCapture(
267 source: AsyncIterable<StreamChunk>,
268 captureId: string,
269): AsyncIterable<StreamChunk> {
270 let currentRunId: string | undefined
271 for await (const chunk of source) {
272 if (chunk.type === 'RUN_STARTED' && typeof chunk.runId === 'string') {
273 currentRunId = chunk.runId
274 }
275 const runId =
276 'runId' in chunk && typeof chunk.runId === 'string'
277 ? chunk.runId
278 : currentRunId
279 recordYieldedChunk(captureId, {
280 type: chunk.type,
281 ...(runId !== undefined ? { runId } : {}),
282 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome
283 ? { outcomeType: chunk.outcome.type }
284 : {}),
285 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt'
286 ? { interruptCount: chunk.outcome.interrupts.length }
287 : {}),
288 })
289 yield chunk
290 }
291}
292
293function lifecycleMiddlewareStack(
294 existing: Array<ChatMiddleware>,
295 extra: ChatMiddleware<unknown, typeof reviewPlan>,
296): Array<ChatMiddleware<unknown, typeof reviewPlan>> {
297 return [...existing, extra]
298}
299
300function createGenericLifecycleMiddleware(
301 captureId: string,
302 scenario: GenericScenario,
303): ChatMiddleware<unknown, typeof reviewPlan> {
304 const boundary = boundaryForScenario(scenario)
305 return {
306 name: 'generic-lifecycle',
307 onInterruptBoundary(ctx) {
308 if (ctx.phase !== boundary || ctx.parentRunId) return
309 recordGenericBoundary(captureId, { phase: ctx.phase, runId: ctx.runId })
310 return {
311 interrupts: [
312 reviewPlan.interrupt({
313 key: `${scenario}-review`,
314 reason: 'review_required',
315 message: `Review the plan at ${ctx.phase}`,
316 payload: { title: 'Middleware review plan', boundary: ctx.phase },
317 }),
318 ],
319 }
320 },
321 onInterruptResolution(_ctx, resolutions) {
322 for (const resolution of resolutions.for(reviewPlan)) {
323 recordGenericResolution(captureId, {
324 definitionId: resolution.request.definition.id,
325 status: resolution.status,
326 ...(resolution.status === 'resolved'
327 ? { response: resolution.response }
328 : {}),
329 })
330 }
331 const policy = toolResumeForScenario(scenario)
332 recordGenericPolicy(captureId, policy)
333 return { toolResume: policy }
334 },
335 }
336}
337
338function genericTools(captureId: string, scenario: GenericScenario) {
339 if (scenario === 'generic-after-tools') {
340 return [
341 inspectReviewTool.server(async ({ reviewId }) => {
342 recordGenericToolExecution(captureId, {
343 name: 'inspect_review',
344 side: 'server',
345 })
346 return { inspected: true, reviewId }
347 }),
348 ]
349 }
350 if (boundaryForScenario(scenario) !== 'beforeTools') return []
351 return [
352 deleteReviewTool.server(async ({ reviewId }) => {
353 recordGenericToolExecution(captureId, {
354 name: 'delete_review',
355 side: 'server',
356 })
357 return { deleted: true, reviewId }
358 }),
359 renderReviewTool.client(),
360 ]
361}
362
363/**
364 * Fake memory adapter for `memory` mode. `recall` unconditionally returns a
365 * known system-prompt block plus a memory tool (so the spec can assert both the
366 * prompt injection AND tool injection reach the model config), and `save`
367 * records that the deferred write ran. Deterministic — no real vendor, no
368 * cross-request state.
369 */
370const RECALL_MORE_TOOL: Tool = {
371 name: 'recall_more',
372 description: 'Look up additional long-term memory by query.',
373 inputSchema: { type: 'object', properties: {}, additionalProperties: false },
374}
375
376function createFakeMemoryAdapter(captureId: string): MemoryAdapter {
377 return {
378 id: 'fake-memory',
379 recall: async () => ({
380 systemPrompt: 'MEMORY: the user previously said they love TanStack.',
381 fragments: [{ text: 'the user loves TanStack', source: 'f1' }],
382 tools: [RECALL_MORE_TOOL],
383 toolGuidance: 'Use recall_more to look up additional memory when needed.',
384 }),
385 save: async () => {
386 recordMemorySave(captureId)
387 return [{ ok: true }]
388 },
389 }
390}
391
392/**
393 * Recorder placed AFTER `memoryMiddleware` so it observes the config the model
394 * actually sees — i.e. WITH the recalled system prompt + tools already merged
395 * in. Records that into the per-testId memory capture.
396 */
397function createMemoryConfigRecorder(captureId: string): ChatMiddleware {
398 return {
399 name: 'memory-config-recorder',
400 onConfig(ctx, config) {
401 if (ctx.phase !== 'init') return
402 recordMemoryConfig(captureId, {
403 systemPrompts: config.systemPrompts.map((p) =>
404 typeof p === 'string' ? p : p.content,
405 ),
406 toolNames: config.tools.map((t) => t.name),
407 })
408 return
409 },
410 }
411}
412
413// Minimal in-memory tracer/meter. Captures into a per-testId bucket so that
414// the Playwright spec can fetch the recorded state via GET after the stream
415// finishes. Not exported — only used to build otelMiddleware for the test.
416function createCaptureTracer(captureId: string): Tracer {
417 let spanSeq = 0
418 const tracer: Tracer = {
419 startSpan(name, options = {}, _ctx?: Context): Span {
420 const id = `span-${spanSeq++}`
421 const attrs: Record<string, AttributeValue> = {}
422 for (const [k, v] of Object.entries(options.attributes ?? {})) {
423 if (v !== undefined) attrs[k] = v
424 }
425 recordOtelSpan(captureId, {
426 id,
427 name,
428 kind: options.kind,
429 attributes: attrs,
430 status: SpanStatusCode.UNSET,
431 events: [],
432 exceptions: [],
433 ended: false,
434 })
435 const status: SpanStatus = { code: SpanStatusCode.UNSET }
436 let ended = false
437 const span: Span = {
438 spanContext(): SpanContext {
439 return { traceId: 'capture-trace', spanId: id, traceFlags: 1 }
440 },
441 setAttribute(key, value) {
442 attrs[key] = value
443 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
444 return span
445 },
446 setAttributes(next) {
447 for (const [k, v] of Object.entries(next)) {
448 attrs[k] = v as AttributeValue
449 }
450 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
451 return span
452 },
453 addEvent(eventName, eventAttrs) {
454 recordOtelEvent(captureId, id, {
455 name: eventName,
456 attributes: eventAttrs as Attributes | undefined,
457 })
458 return span
459 },
460 addLink() {
461 return span
462 },
463 addLinks() {
464 return span
465 },
466 setStatus(next) {
467 status.code = next.code
468 status.message = next.message
469 recordOtelSpan(captureId, {
470 id,
471 patch: { status: next.code, statusMessage: next.message },
472 })
473 return span
474 },
475 updateName(next) {
476 recordOtelSpan(captureId, { id, patch: { name: next } })
477 return span
478 },
479 end() {
480 ended = true
481 recordOtelSpan(captureId, { id, patch: { ended: true } })
482 },
483 isRecording() {
484 return !ended
485 },
486 recordException(exception, exceptionAttrs) {
487 recordOtelException(captureId, id, {
488 exception: String(
489 (exception as { message?: string } | undefined)?.message ??
490 exception,
491 ),
492 attributes: exceptionAttrs as Attributes | undefined,
493 })
494 },
495 }
496 return span
497 },
498 // Minimal implementation — our middleware never calls startActiveSpan.
499
500 startActiveSpan(...args: Array<any>) {
501 const fn = args[args.length - 1] as (span: Span) => unknown
502 const name = args[0] as string
503 const span = tracer.startSpan(name, {})
504 try {
505 return fn(span)
506 } finally {
507 span.end()
508 }
509 },
510 }
511 return tracer
512}
513
514function createCaptureMeter(captureId: string): Meter {
515 const histogram = (name: string, options?: MetricOptions): Histogram => ({
516 record(value: number, attributes?: Attributes) {
517 recordOtelHistogram(captureId, {
518 name,
519 value,
520 attributes,
521 unit: options?.unit,
522 })
523 },
524 })
525 return {
526 createHistogram: histogram,
527 } as any as Meter
528}
529
530export const Route = createFileRoute('/api/middleware-test')({
531 server: {
532 handlers: {
533 POST: async ({ request }) => {
534 if (request.signal?.aborted) return new Response(null, { status: 499 })
535 const abortController = new AbortController()
536
537 let params
538 try {
539 params = await chatParamsFromRequestBody(await request.json())
540 } catch (error) {
541 return new Response(
542 error instanceof Error ? error.message : 'Bad request',
543 { status: 400 },
544 )
545 }
546
547 const fp = params.forwardedProps
548 const scenario =
549 typeof fp.scenario === 'string' ? fp.scenario : 'basic-text'
550 const middlewareMode =
551 typeof fp.middlewareMode === 'string' ? fp.middlewareMode : 'none'
552 const testId: string | undefined =
553 typeof fp.testId === 'string' ? fp.testId : undefined
554 const aimockPort: number | undefined =
555 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
556 // Provider/model overrides let the middleware E2E exercise both the
557 // native-combined-mode path (modern OpenAI / Claude 4.5+ — no
558 // `structuredOutput` phase, single combined call) and the legacy
559 // finalization path (Claude 3.7, etc. — `structuredOutput` phase
560 // fires). See #605.
561 const provider =
562 typeof fp.provider === 'string' ? fp.provider : 'openai'
563 const modelOverride =
564 typeof fp.model === 'string' ? fp.model : undefined
565
566 try {
567 const adapterOptions =
568 scenario === 'run-error'
569 ? { adapter: createRunErrorAdapter() }
570 : createTextAdapter(
571 provider as Parameters<typeof createTextAdapter>[0],
572 modelOverride,
573 aimockPort,
574 testId,
575 )
576
577 const middleware: Array<ChatMiddleware> = []
578 let genericLifecycleMiddleware:
579 | ChatMiddleware<unknown, typeof reviewPlan>
580 | undefined =
581 scenario === 'run-error' ? runErrorBoundaryMiddleware : undefined
582 const genericScenario = isGenericScenario(scenario)
583 ? scenario
584 : undefined
585
586 if (middlewareMode === 'chunk-transform')
587 middleware.push(chunkTransformMiddleware)
588 if (middlewareMode === 'tool-skip')
589 middleware.push(toolSkipMiddleware)
590 if (middlewareMode === 'tool-replace')
591 middleware.push(toolReplaceMiddleware)
592 if (middlewareMode === 'tool-bad-args')
593 middleware.push(toolBadArgsMiddleware)
594 if (middlewareMode === 'capability') {
595 // Order matters: the provider's setup() must run before the
596 // consumer reads the capability. Array order is preserved.
597 middleware.push(prefixProviderMiddleware, prefixConsumerMiddleware)
598 }
599 if (middlewareMode === 'phase-recorder') {
600 if (!testId) {
601 return new Response(
602 JSON.stringify({
603 error: 'phase-recorder mode requires testId',
604 }),
605 {
606 status: 400,
607 headers: { 'Content-Type': 'application/json' },
608 },
609 )
610 }
611 resetPhaseCapture(testId)
612 middleware.push(createPhaseRecorderMiddleware(testId))
613 }
614 if (middlewareMode === 'generic-lifecycle') {
615 if (!testId || !genericScenario) {
616 return new Response(
617 JSON.stringify({
618 error:
619 'generic-lifecycle mode requires testId and a generic scenario',
620 }),
621 {
622 status: 400,
623 headers: { 'Content-Type': 'application/json' },
624 },
625 )
626 }
627 if (!params.parentRunId) resetPhaseCapture(testId)
628 genericLifecycleMiddleware = createGenericLifecycleMiddleware(
629 testId,
630 genericScenario,
631 )
632 }
633 if (middlewareMode === 'memory') {
634 if (!testId) {
635 return new Response(
636 JSON.stringify({ error: 'memory mode requires testId' }),
637 {
638 status: 400,
639 headers: { 'Content-Type': 'application/json' },
640 },
641 )
642 }
643 resetMemoryCapture(testId)
644 middleware.push(
645 memoryMiddleware({
646 adapter: createFakeMemoryAdapter(testId),
647 scope: { threadId: testId },
648 }),
649 createMemoryConfigRecorder(testId),
650 )
651 }
652 if (middlewareMode === 'otel') {
653 if (!OTEL_TEST_ENABLED) {
654 return new Response(null, { status: 404 })
655 }
656 if (!testId) {
657 return new Response(
658 JSON.stringify({ error: 'otel mode requires testId' }),
659 {
660 status: 400,
661 headers: { 'Content-Type': 'application/json' },
662 },
663 )
664 }
665 resetOtelCapture(testId)
666 middleware.push(
667 otelMiddleware({
668 tracer: createCaptureTracer(testId),
669 meter: createCaptureMeter(testId),
670 captureContent: true,
671 }),
672 )
673 }
674
675 const tools =
676 genericScenario && testId
677 ? genericTools(testId, genericScenario)
678 : scenario === 'with-tool' || scenario === 'raw-tool-args'
679 ? [weatherTool]
680 : scenario === 'structured-client-tool-wait'
681 ? [clientContextToolDefinition]
682 : []
683
684 // Structured scenarios bind the same guitar schema. The client-tool
685 // variant also passes an isomorphic tool definition so the first
686 // server invocation can stop at the browser-execution boundary.
687 const isStructured =
688 scenario === 'structured-output' ||
689 scenario === 'structured-output-stream' ||
690 scenario === 'structured-client-tool-wait'
691
692 const rawStream = isStructured
693 ? chat({
694 ...adapterOptions,
695 messages: params.messages,
696 tools,
697 middleware,
698 threadId: params.threadId,
699 runId: params.runId,
700 outputSchema: guitarRecommendationSchema,
701 stream: true,
702 abortController,
703 })
704 : genericLifecycleMiddleware
705 ? chat({
706 ...adapterOptions,
707 messages: params.messages,
708 tools,
709 middleware: lifecycleMiddlewareStack(
710 middleware,
711 genericLifecycleMiddleware,
712 ),
713 threadId: params.threadId,
714 runId: params.runId,
715 parentRunId: params.parentRunId,
716 resume: params.resume,
717 interrupts: [reviewPlan] as const,
718 agentLoopStrategy: maxIterations(10),
719 abortController,
720 })
721 : chat({
722 ...adapterOptions,
723 messages: params.messages,
724 tools,
725 middleware,
726 threadId: params.threadId,
727 runId: params.runId,
728 parentRunId: params.parentRunId,
729 resume: params.resume,
730 interrupts: genericScenario ? [reviewPlan] : undefined,
731 agentLoopStrategy: maxIterations(10),
732 abortController,
733 })
734
735 // Tee the post-middleware stream when `phase-recorder` is active
736 // so the spec can assert on what the consumer ultimately sees
737 // (e.g. exactly one RUN_STARTED/RUN_FINISHED pair).
738 const stream =
739 (middlewareMode === 'phase-recorder' ||
740 middlewareMode === 'generic-lifecycle') &&
741 testId
742 ? teeForPhaseCapture(rawStream, testId)
743 : rawStream
744
745 return toServerSentEventsResponse(stream, { abortController })
746 } catch (error: any) {
747 console.error('[api.middleware-test] Error:', error.message)
748 if (error.name === 'AbortError' || abortController.signal.aborted) {
749 return new Response(null, { status: 499 })
750 }
751 return new Response(JSON.stringify({ error: error.message }), {
752 status: 500,
753 headers: { 'Content-Type': 'application/json' },
754 })
755 }
756 },
757 GET: async ({ request }) => {
758 const url = new URL(request.url)
759 const testId = url.searchParams.get('testId')
760 const kind = url.searchParams.get('kind')
761
762 // Phase capture is independent of OTEL — keep it available without
763 // requiring the OTEL_TEST_ENABLED gate so that the structured-output
764 // middleware spec works under any harness build configuration.
765 if (kind === 'phase') {
766 if (!testId) {
767 return new Response(
768 JSON.stringify({ error: 'testId query param required' }),
769 {
770 status: 400,
771 headers: { 'Content-Type': 'application/json' },
772 },
773 )
774 }
775 return new Response(JSON.stringify(getPhaseCapture(testId)), {
776 headers: { 'Content-Type': 'application/json' },
777 })
778 }
779
780 // Memory capture — like phase capture, available without the OTEL gate.
781 if (kind === 'memory') {
782 if (!testId) {
783 return new Response(
784 JSON.stringify({ error: 'testId query param required' }),
785 { status: 400, headers: { 'Content-Type': 'application/json' } },
786 )
787 }
788 return new Response(JSON.stringify(getMemoryCapture(testId)), {
789 headers: { 'Content-Type': 'application/json' },
790 })
791 }
792
793 // OTEL capture remains gated — the GET cannot act as an oracle in a
794 // production-like build.
795 if (!OTEL_TEST_ENABLED) {
796 return new Response(null, { status: 404 })
797 }
798 if (!testId) {
799 return new Response(
800 JSON.stringify({ error: 'testId query param required' }),
801 {
802 status: 400,
803 headers: { 'Content-Type': 'application/json' },
804 },
805 )
806 }
807 return new Response(JSON.stringify(getOtelCapture(testId)), {
808 headers: { 'Content-Type': 'application/json' },
809 })
810 },
811 },
812 },
813})