Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { computerUseTool } from '@tanstack/ai-anthropic/tools'
5
6const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
7
8/**
9 * Drives the Anthropic chat adapter with `computerUseTool()`. A custom
10 * `fetch` captures the headers of the outgoing request and answers with a
11 * short Claude SSE stream, so the companion spec can read the
12 * `anthropic-beta` header without an API key.
13 */
14function endTurnStream(): ReadableStream<Uint8Array> {
15 const encoder = new TextEncoder()
16 const events = [
17 {
18 type: 'message_start',
19 message: {
20 id: 'msg_computer_use_wire',
21 type: 'message',
22 role: 'assistant',
23 content: [],
24 model: 'claude-haiku-4-5',
25 stop_reason: null,
26 stop_sequence: null,
27 usage: { input_tokens: 5, output_tokens: 0 },
28 },
29 },
30 {
31 type: 'message_delta',
32 delta: { stop_reason: 'end_turn', stop_sequence: null },
33 usage: { output_tokens: 1 },
34 },
35 { type: 'message_stop' },
36 ]
37 return new ReadableStream<Uint8Array>({
38 start(controller) {
39 for (const event of events) {
40 controller.enqueue(
41 encoder.encode(
42 `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
43 ),
44 )
45 }
46 controller.close()
47 },
48 })
49}
50
51export const Route = createFileRoute('/api/anthropic-computer-use-wire')({
52 server: {
53 handlers: {
54 POST: async () => {
55 let anthropicBeta: string | null = null
56 const capturingFetch: typeof fetch = async (input, init) => {
57 const req =
58 input instanceof Request ? input : new Request(input, init)
59 anthropicBeta = req.headers.get('anthropic-beta')
60 return new Response(endTurnStream(), {
61 status: 200,
62 headers: { 'Content-Type': 'text/event-stream' },
63 })
64 }
65
66 const adapter = createAnthropicChat('claude-haiku-4-5', DUMMY_KEY, {
67 fetch: capturingFetch,
68 })
69
70 try {
71 for await (const _ of chat({
72 threadId: 'anthropic-computer-use-wire',
73 ...createChatOptions({ adapter }),
74 messages: [{ role: 'user', content: 'Open the browser.' }],
75 tools: [
76 computerUseTool({
77 type: 'computer_20250124',
78 name: 'computer',
79 display_width_px: 1024,
80 display_height_px: 768,
81 }),
82 ],
83 })) {
84 // Drain the stream.
85 }
86 } catch (error) {
87 return Response.json({
88 ok: false,
89 error: error instanceof Error ? error.message : String(error),
90 })
91 }
92
93 return Response.json({ ok: true, anthropicBeta })
94 },
95 },
96 },
97})