Skip to content

Commit fec8dcd

Browse files
committed
fix build
1 parent eab5c7c commit fec8dcd

File tree

1 file changed

+1
-85
lines changed

1 file changed

+1
-85
lines changed

src/content/docs/agents/concepts/agent-class.mdx

Lines changed: 1 addition & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ sidebar:
55
order: 10
66
---
77

8-
import { Render, TypeScriptExample } from "~/components";
8+
import { Render } from "~/components";
99

1010
The core of the `agents` library is the exported `Agent` class. Following the pattern from [Durable Objects](/durable-objects/api/), the main API for developers is to extend the `Agent` class so those classes inherit all the built-in features. While this effectively is a supercharged primitive that allows developers to only write the logic they need in their agents, it obscures the inner workings.
1111

@@ -25,14 +25,10 @@ This won't cover Durable Objects in detail, but it's good to know what primitive
2525

2626
### constructor
2727

28-
<TypeScriptExample>
29-
3028
```ts
3129
constructor(ctx: DurableObjectState, env: Env) {}
3230
```
3331

34-
</TypeScriptExample>
35-
3632
The Workers runtime always calls the constructor to handle things internally. This means 2 things:
3733

3834
1. While the constructor is called every time the DO is initialized, the signature is fixed. Developers **can't add or update parameters from the constructor**.
@@ -42,8 +38,6 @@ The Workers runtime always calls the constructor to handle things internally. Th
4238

4339
By writing a Durable Object class which inherits from the built-in type `DurableObject`, public methods are exposed as RPC methods, which developers can call using a [DurableObjectStub from a Worker](/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/#invoking-methods-on-a-durable-object).
4440

45-
<TypeScriptExample>
46-
4741
```ts
4842
// This instance could've been active, hibernated,
4943
// not initialized or maybe had never even been created!
@@ -54,8 +48,6 @@ const stub = env.MY_DO.getByName("foo");
5448
await stub.bar();
5549
```
5650

57-
</TypeScriptExample>
58-
5951
### fetch()
6052

6153
Durable Objects can take a `Request` from a Worker and send a `Response` back. This can **only** be done through the [`fetch`](/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/#invoking-the-fetch-handler) method (which the developer must implement).
@@ -66,8 +58,6 @@ Durable Objects include first-class support for [WebSockets](/durable-objects/be
6658

6759
The base class provides `webSocketMessage(ws, message)`, `webSocketClose(ws, code, reason, wasClean)` and `webSocketError(ws , error)` ([API](/workers/runtime-apis/websockets)).
6860

69-
<TypeScriptExample>
70-
7161
```ts
7262
export class MyDurableObject extends DurableObject {
7363
async fetch(request) {
@@ -91,8 +81,6 @@ export class MyDurableObject extends DurableObject {
9181
}
9282
```
9383

94-
</TypeScriptExample>
95-
9684
### alarm()
9785

9886
HTTP and RPC requests are not the only entrypoints for a DO. Alarms allow developers to schedule tasks to run at a later time. Whenever the runtime knows an alarm is due, it will call the `alarm()` method, which is left to the developer to implement.
@@ -107,8 +95,6 @@ The base `DurableObject` class sets the [DurableObjectState](/durable-objects/ap
10795

10896
[DurableObjectStorage](/durable-objects/api/sqlite-storage-api/) is the main interface with the DO's persistence mechanisms, which include both a KV and SQLITE **synchronous** APIs.
10997

110-
<TypeScriptExample>
111-
11298
```ts
11399
const sql = this.ctx.storage.sql;
114100
const kv = this.ctx.storage.kv;
@@ -120,8 +106,6 @@ const rows = sql.exec("SELECT * FROM contacts WHERE country = ?", "US");
120106
const token = kv.get("someToken");
121107
```
122108

123-
</TypeScriptExample>
124-
125109
### this.ctx.env
126110

127111
Lastly, it's worth mentioning that the DO also has the Worker `Env` in `this.env`. Read more about [bindings](/workers/runtime-apis/bindings).
@@ -138,8 +122,6 @@ An important note is that `Server` **does NOT make use any of the DO storage** s
138122

139123
Compare this to the DO addressing [example above](#rpc).
140124

141-
<TypeScriptExample>
142-
143125
```ts
144126
// Note the await here!
145127
const stub = await getServerByName(env.MY_DO, "foo");
@@ -148,12 +130,8 @@ const stub = await getServerByName(env.MY_DO, "foo");
148130
await stub.bar();
149131
```
150132

151-
</TypeScriptExample>
152-
153133
Since we have a URL addressing scheme, we also get access to `routePartykitRequest()`.
154134

155-
<TypeScriptExample>
156-
157135
```ts
158136
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
159137
// Behind the scenes, PartyKit normalizes your DO binding names
@@ -166,16 +144,12 @@ async fetch(request: Request, env: Env, ctx: ExecutionContext) {
166144
}
167145
```
168146

169-
</TypeScriptExample>
170-
171147
You can have a look at [the implementation](https://github.com/cloudflare/partykit/blob/main/packages/partyserver/src/index.ts#L122) if you're interested.
172148

173149
### onStart
174150

175151
The extra plumbing that `Server` includes on addressing allows it to expose an `onStart` callback that is **executed every time the DO starts up** (the DO was evicted, hibernated or never created at all) and **before any `fetch` or RPC**.
176152

177-
<TypeScriptExample>
178-
179153
```ts
180154
class MyServer extends Server {
181155
onStart() {
@@ -187,14 +161,10 @@ class MyServer extends Server {
187161
}
188162
```
189163

190-
</TypeScriptExample>
191-
192164
### onRequest and onConnect
193165

194166
`Server` already implements `fetch` for the underlying Durable Object and exposes 2 different callbacks that developers can make use of, `onRequest` and `onConnect` for HTTP requests and incoming WS connections, respectively (**WebSocket connections are accepted by default**).
195167

196-
<TypeScriptExample>
197-
198168
```ts
199169
class MyServer extends Server {
200170
async onRequest(request: Request) {
@@ -213,8 +183,6 @@ class MyServer extends Server {
213183
}
214184
```
215185

216-
</TypeScriptExample>
217-
218186
### WebSockets
219187

220188
Just as `onConnect` is the callback for every new connection, `Server` also provides wrappers on top of the default callbacks from the `DurableObject` class: `onMessage`, `onClose` and `onError`.
@@ -237,8 +205,6 @@ One of the core features of `Agent` is **automatic state persistence**. Develope
237205

238206
There's also `this.onStateUpdate` that you can override to react to state changes.
239207

240-
<TypeScriptExample>
241-
242208
```ts
243209
class MyAgent extends Agent<Env, { count: number }> {
244210
initialState = { count: 0 };
@@ -253,16 +219,12 @@ class MyAgent extends Agent<Env, { count: number }> {
253219
}
254220
```
255221

256-
</TypeScriptExample>
257-
258222
State is stored in the `cf_agents_state` SQL table. State messages are sent with `type: "cf_agent_state"` (both from the client and the server). Since the `agents` provides [JS and React clients](/agents/api-reference/store-and-sync-state/#synchronizing-state), real-time state updates are available out of the box.
259223

260224
### this.sql
261225

262226
The Agent provides a convenient `sql` template tag for executing queries against the Durable Object's SQL storage. It constructs parameterized queries and executes them. This uses the **synchronous** SQL API from `this.ctx.storage.sql`.
263227

264-
<TypeScriptExample>
265-
266228
```ts
267229
class MyAgent extends Agent {
268230
onStart() {
@@ -285,14 +247,10 @@ class MyAgent extends Agent {
285247
}
286248
```
287249

288-
</TypeScriptExample>
289-
290250
### RPC and Callable Methods
291251

292252
`agents` take Durable Objects RPC one step forward by implementing RPC through WebSockets, so clients can also call methods on the Agent directly. To make a method callable, developers can use the `@callable` decorator. Methods can return a serializable value or a stream (when using `@callable({ stream: true })`).
293253

294-
<TypeScriptExample>
295-
296254
```ts
297255
class MyAgent extends Agent {
298256
@callable({ description: "Add two numbers" })
@@ -302,8 +260,6 @@ class MyAgent extends Agent {
302260
}
303261
```
304262

305-
</TypeScriptExample>
306-
307263
Clients can invoke this method by sending a WebSocket message:
308264

309265
```json
@@ -317,22 +273,16 @@ Clients can invoke this method by sending a WebSocket message:
317273

318274
For example, with the provided `React` client it's as easy as:
319275

320-
<TypeScriptExample>
321-
322276
```ts
323277
const { stub } = useAgent({ name: "my-agent" });
324278
const result = await stub.add(2, 3);
325279
console.log(result); // 5
326280
```
327281

328-
</TypeScriptExample>
329-
330282
### this.queue and friends
331283

332284
Agents include a built-in task queue for deferred execution. This is useful for offloading work or retrying operations. The available methods are `this.queue`, `this.dequeue`, `this.dequeueAll`, `this.dequeueAllByCallback`, `this.getQueue`, and `this.getQueues`.
333285

334-
<TypeScriptExample>
335-
336286
```ts
337287
class MyAgent extends Agent {
338288
async onConnect() {
@@ -346,16 +296,12 @@ class MyAgent extends Agent {
346296
}
347297
```
348298

349-
</TypeScriptExample>
350-
351299
Tasks are stored in the `cf_agents_queues` SQL table and are automatically flushed in sequence. If a task succeeds, it's automatically dequeued.
352300

353301
### this.schedule and friends
354302

355303
Agents support scheduled execution of methods by wrapping the Durable Object's `alarm()`. The available methods are `this.schedule`, `this.getSchedule`, `this.getSchedules`, `this.cancelSchedule`. Schedules can be one-time, delayed, or recurring (using cron expressions).
356304

357-
<TypeScriptExample>
358-
359305
```ts
360306
class MyAgent extends Agent {
361307
async onStart() {
@@ -385,16 +331,12 @@ class MyAgent extends Agent {
385331
}
386332
```
387333

388-
</TypeScriptExample>
389-
390334
Schedules are stored in the `cf_agents_schedules` SQL table. Cron schedules automatically reschedule themselves after execution, while one-time schedules are deleted.
391335

392336
### this.mcp and friends
393337

394338
`Agent` includes a multi-server MCP client. This enables your Agent to interact with external services that expose MCP interfaces. The MCP client is documented in detail at [MCP Client API](/agents/model-context-protocol/mcp-client-api/).
395339

396-
<TypeScriptExample>
397-
398340
```ts
399341
class MyAgent extends Agent {
400342
async onConnect() {
@@ -409,14 +351,10 @@ class MyAgent extends Agent {
409351
}
410352
```
411353

412-
</TypeScriptExample>
413-
414354
### Email Handling
415355

416356
Agents can receive and reply to emails using Cloudflare's [Email Routing](/email-routing/email-workers/).
417357

418-
<TypeScriptExample>
419-
420358
```ts
421359
class MyAgent extends Agent {
422360
async onEmail(email: AgentEmail) {
@@ -437,12 +375,8 @@ class MyAgent extends Agent {
437375
}
438376
```
439377

440-
</TypeScriptExample>
441-
442378
To route emails to your Agent, use `routeAgentEmail` in your Worker's email handler:
443379

444-
<TypeScriptExample>
445-
446380
```ts
447381
export default {
448382
async email(message, env, ctx) {
@@ -453,14 +387,10 @@ export default {
453387
};
454388
```
455389

456-
</TypeScriptExample>
457-
458390
### Context Management
459391

460392
`agents` wraps all your methods with an `AsyncLocalStorage` to maintain context throughout the request lifecycle. This allows you to access the current agent, connection, request, or email (depending of what event is being handled) from anywhere in your code:
461393

462-
<TypeScriptExample>
463-
464394
```ts
465395
import { getCurrentAgent } from "agents";
466396

@@ -477,14 +407,10 @@ function someUtilityFunction() {
477407
}
478408
```
479409

480-
</TypeScriptExample>
481-
482410
### this.onError
483411

484412
`Agent` extends `Server`'s `onError` so it can be used to handle errors that are not necessarily WebSocket errors. It is called with a `Connection` or `unknown` error.
485413

486-
<TypeScriptExample>
487-
488414
```ts
489415
class MyAgent extends Agent {
490416
onError(connectionOrError: Connection | unknown, error?: unknown) {
@@ -502,14 +428,10 @@ class MyAgent extends Agent {
502428
}
503429
```
504430

505-
</TypeScriptExample>
506-
507431
### this.destroy
508432

509433
`destroy()` drops all tables, deletes alarms, clears storage, and aborts the context. The `this.abort` method that is called by `this.destroy` comes from `DurableObject` and ensures that the Agent is fully evicted. In order to do so, it throws an uncatchable error that will show up in your logs (read more at [abort()](/durable-objects/api/state/#abort)).
510434

511-
<TypeScriptExample>
512-
513435
```ts
514436
class MyAgent extends Agent {
515437
async onStart() {
@@ -524,14 +446,10 @@ class MyAgent extends Agent {
524446
}
525447
```
526448

527-
</TypeScriptExample>
528-
529449
### Routing
530450

531451
The `Agent` class re-exports PartyKit's [addressing helpers](#addressing) as `getAgentByName` and `routeAgentRequest`.
532452

533-
<TypeScriptExample>
534-
535453
```ts
536454
// Same API as getServerByName
537455
const stub = await getAgentByName(env.MY_DO, "foo");
@@ -544,5 +462,3 @@ if (res) return res;
544462

545463
return Response("Not found", { status: 404 });
546464
```
547-
548-
</TypeScriptExample>

0 commit comments

Comments
 (0)