Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 INTERRUPT_BINDING_METADATA_KEY,
4 INTERRUPT_BINDING_VERSION,
5 canonicalInterruptJson,
6 digestInterruptJson,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import type { StreamChunk } from '@tanstack/ai'
10
11const oursResponseSchema = {
12 type: 'object',
13 properties: { confirmed: { type: 'boolean' } },
14 required: ['confirmed'],
15}
16
17/**
18 * A provider-free harness route that ends a run with TWO interrupts:
19 *
20 * - `ours`, carrying a resume binding — resumable through the chat resume
21 * path.
22 * - `theirs`, carrying no binding at all — the shape another producer on the
23 * same AG-UI stream emits (a workflow engine's durable approval, another
24 * agent framework's pause).
25 *
26 * The client must surface `theirs` as `kind: 'unbound'` with no resolver
27 * instead of inventing a binding for it, and must still let `ours` be
28 * resolved and submitted.
29 */
30function foreignRun(
31 threadId: string,
32 runId: string,
33): AsyncIterable<StreamChunk> {
34 return (async function* () {
35 yield {
36 type: 'RUN_STARTED',
37 threadId,
38 runId,
39 timestamp: Date.now(),
40 } as StreamChunk
41 yield {
42 type: 'RUN_FINISHED',
43 threadId,
44 runId,
45 timestamp: Date.now(),
46 outcome: {
47 type: 'interrupt',
48 interrupts: [
49 {
50 id: 'ours',
51 reason: 'confirmation',
52 message: 'Confirm the shipment?',
53 responseSchema: oursResponseSchema,
54 metadata: {
55 [INTERRUPT_BINDING_METADATA_KEY]: {
56 v: INTERRUPT_BINDING_VERSION,
57 kind: 'generic',
58 interruptId: 'ours',
59 interruptedRunId: runId,
60 generation: 0,
61 responseSchemaHash: digestInterruptJson(
62 canonicalInterruptJson(oursResponseSchema),
63 ),
64 },
65 },
66 },
67 {
68 id: 'theirs',
69 reason: 'approval_requested',
70 message: 'Approve the deployment?',
71 metadata: { 'acme:workflowApproval': { stepId: 'deploy' } },
72 },
73 ],
74 },
75 } as StreamChunk
76 })()
77}
78
79/**
80 * The continuation run. Reaching this at all is the assertion: it only happens
81 * if the client submitted a resume batch, which it can only do if the unbound
82 * interrupt was excluded from the batch-completeness gate.
83 */
84function resumedRun(
85 threadId: string,
86 runId: string,
87 resumedIds: Array<string>,
88): AsyncIterable<StreamChunk> {
89 return (async function* () {
90 yield {
91 type: 'RUN_STARTED',
92 threadId,
93 runId,
94 timestamp: Date.now(),
95 } as StreamChunk
96 const text = `resumed:${resumedIds.join(',')}`
97 yield {
98 type: 'TEXT_MESSAGE_START',
99 messageId: 'resumed',
100 role: 'assistant',
101 timestamp: Date.now(),
102 } as StreamChunk
103 yield {
104 type: 'TEXT_MESSAGE_CONTENT',
105 messageId: 'resumed',
106 delta: text,
107 content: text,
108 timestamp: Date.now(),
109 } as StreamChunk
110 yield {
111 type: 'TEXT_MESSAGE_END',
112 messageId: 'resumed',
113 timestamp: Date.now(),
114 } as StreamChunk
115 yield {
116 type: 'RUN_FINISHED',
117 threadId,
118 runId,
119 timestamp: Date.now(),
120 outcome: { type: 'success' },
121 } as StreamChunk
122 })()
123}
124
125function stringField(body: unknown, key: string): string | undefined {
126 if (typeof body !== 'object' || body === null || !(key in body)) {
127 return undefined
128 }
129 const value: unknown = (body as Record<string, unknown>)[key]
130 return typeof value === 'string' ? value : undefined
131}
132
133function resumedInterruptIds(body: unknown): Array<string> {
134 if (typeof body !== 'object' || body === null || !('resume' in body)) {
135 return []
136 }
137 const resume: unknown = (body as Record<string, unknown>)['resume']
138 if (!Array.isArray(resume)) return []
139 return resume.flatMap((entry: unknown) => {
140 const id = stringField(entry, 'interruptId')
141 return id === undefined ? [] : [id]
142 })
143}
144
145export const Route = createFileRoute('/api/foreign-interrupt')({
146 server: {
147 handlers: {
148 POST: async ({ request }) => {
149 const body: unknown = await request.json()
150 const threadId = stringField(body, 'threadId') ?? 'thread-1'
151 // Bindings correlate on the request runId. A fresh server id would
152 // make `ours` generic but not resolvable.
153 const runId = stringField(body, 'runId') ?? `run-${threadId}`
154 const resumed = resumedInterruptIds(body)
155 if (resumed.length > 0) {
156 return toServerSentEventsResponse(
157 resumedRun(threadId, `${runId}-continuation`, resumed),
158 )
159 }
160 return toServerSentEventsResponse(foreignRun(threadId, runId))
161 },
162 },
163 },
164})