Files
upstream-tldraw/templates/agent/worker/do/AgentDurableObject.ts
upstream-mirror a774ac673a
Some checks failed
Deploy analytics worker / Deploy analytics worker to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
i18n upload strings / Upload latest strings (push) Failing after 1s
Deploy bemo / Deploy bemo to ${{ (github.ref == 'refs/heads/bemo-production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
Deploy grafana resources / ${{ github.event_name == 'push' && 'Deploy grafana resources' || 'Validate grafana resources (dry run)' }} (push) Failing after 0s
End to end tests (dotcom) / Check for relevant changes (push) Failing after 0s
End to end tests (examples) / Check for relevant changes (push) Failing after 0s
End to end tests (mermaid readability) / Check for relevant changes (push) Failing after 1s
End to end tests (perf) / Check for relevant changes (push) Failing after 0s
Publish editor extensions / Publish editor extensions (push) Failing after 1s
Publish SDK packages / Remove the publish-packages label (push) Has been skipped
Checks / Tests & checks (push) Has been cancelled
Checks / Build all projects (push) Has been cancelled
Deploy templates / Deploy templates (push) Has been cancelled
End to end tests (dotcom) / End to end tests (dotcom) (push) Has been cancelled
End to end tests (mermaid readability) / End to end tests (mermaid readability) (push) Has been cancelled
End to end tests (perf) / End to end tests (perf) (push) Has been cancelled
Deploy .com / Deploy dotcom to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Has been cancelled
End to end tests (examples) / End to end tests (examples) (push) Has been cancelled
Publish SDK packages / Publish SDK packages (push) Has been cancelled
Publish SDK packages / Tell user released version (push) Has been cancelled
Publish SDK packages / Publishes code templates to separate repositories (push) Has been cancelled
Publish SDK packages / Deploys the template demos with the new SDK version (push) Has been cancelled
snapshot of https://github.com/tldraw/tldraw.git (main, 2026-09-23; blobs > 131072B omitted)
2026-09-23 16:12:52 +05:00

81 lines
2.5 KiB
TypeScript

import { DurableObject } from 'cloudflare:workers'
import { AutoRouter, error } from 'itty-router'
import { AgentAction } from '../../shared/types/AgentAction'
import { AgentPrompt } from '../../shared/types/AgentPrompt'
import { Streaming } from '../../shared/types/Streaming'
import { Environment } from '../environment'
import { AgentService } from './AgentService'
export class AgentDurableObject extends DurableObject<Environment> {
service: AgentService
constructor(ctx: DurableObjectState, env: Environment) {
super(ctx, env)
this.service = new AgentService(this.env) // swap this with your own service
}
private readonly router = AutoRouter({
catch: (e) => {
console.error(e)
return error(e)
},
}).post('/stream', (request) => this.stream(request))
// `fetch` is the entry point for all requests to the Durable Object
override fetch(request: Request): Response | Promise<Response> {
return this.router.fetch(request)
}
/**
* Stream changes from the model.
*
* @param request - The request object containing the prompt.
* @returns A Promise that resolves to a Response object containing the streamed changes.
*/
private async stream(request: Request): Promise<Response> {
const encoder = new TextEncoder()
const { readable, writable } = new TransformStream()
const writer = writable.getWriter()
const response: { changes: Streaming<AgentAction>[] } = { changes: [] }
;(async () => {
try {
const prompt = (await request.json()) as AgentPrompt
for await (const change of this.service.stream(prompt)) {
response.changes.push(change)
const data = `data: ${JSON.stringify(change)}\n\n`
await writer.write(encoder.encode(data))
await writer.ready
}
await writer.close()
} catch (error: any) {
console.error('Stream error:', error)
// Send error through the stream
const errorData = `data: ${JSON.stringify({ error: error.message })}\n\n`
try {
await writer.write(encoder.encode(errorData))
await writer.close()
} catch (writeError) {
await writer.abort(writeError)
}
}
})()
return new Response(readable, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
'Transfer-Encoding': 'chunked',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
})
}
}