You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/agents/api-reference/calling-agents.mdx
+133-1Lines changed: 133 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -178,7 +178,139 @@ export class MyAgent extends Agent<Env> {
178
178
```
179
179
</TypeScriptExample>
180
180
181
-
Replace `userId` with `teamName`, `channel`, `companyName` as fits your Agents goals - and/or configure authentication to ensure Agents are only created for known, authenticated users.
181
+
Replace `userId` with `teamName`, `channel`, `companyName` as fits your Agents goals - and configure authentication to ensure Agents are only created for known, authenticated users.
182
+
183
+
### Custom routing with basePath
184
+
185
+
For advanced use cases, you can bypass the default `/agents/:agent/:name` URL pattern and define custom routing. This is useful when the instance name should be determined server-side (for example, from authentication or session data) or when you need clean URLs without the `/agents/` prefix.
186
+
187
+
**Client-side with basePath:**
188
+
189
+
<TypeScriptExample>
190
+
191
+
```ts
192
+
import { useAgent } from"agents/react";
193
+
194
+
// Connect to /user instead of /agents/user-agent/...
195
+
const agent =useAgent({
196
+
agent: "UserAgent", // Required but ignored when basePath is set
197
+
basePath: "user"// Connects to /user
198
+
});
199
+
```
200
+
201
+
</TypeScriptExample>
202
+
203
+
**Server-side routing:**
204
+
205
+
When using `basePath`, your Worker must handle the custom path and forward requests to the appropriate agent instance:
returnagent.fetch(request); // Forward request directly to agent
221
+
}
222
+
223
+
// Default routing for standard /agents/... paths
224
+
return (
225
+
routeAgentRequest(request, env) ||
226
+
newResponse("Not found", { status: 404 })
227
+
);
228
+
}
229
+
};
230
+
```
231
+
232
+
</TypeScriptExample>
233
+
234
+
**Server-sent identity:**
235
+
236
+
When using `basePath`, clients do not know which instance they connected to until the server sends the identity. Agents automatically send their identity on connection:
237
+
238
+
<TypeScriptExample>
239
+
240
+
```ts
241
+
const agent =useAgent({
242
+
agent: "UserAgent",
243
+
basePath: "user",
244
+
onIdentity: (name, agentType) => {
245
+
console.log(`Connected to ${agentType} instance: ${name}`);
246
+
// for example, "Connected to user-agent instance: user-123"
247
+
}
248
+
});
249
+
250
+
// Reactive state - re-renders when identity is received
251
+
return (
252
+
<div>
253
+
{agent.identified ? `Connected to: ${agent.name}` : "Connecting..."}
254
+
</div>
255
+
);
256
+
```
257
+
258
+
</TypeScriptExample>
259
+
260
+
**Handling identity changes:**
261
+
262
+
If the identity changes on reconnect (for example, session expired and user logs in as someone else), handle it with `onIdentityChange`:
An Agent can schedule tasks to be run in the future by calling `this.schedule(when, callback, data)`, where `when` can be a delay, a `Date`, or a cron string; `callback` the function name to call, and `data` is an object of data to pass to the function.
10
+
An Agent can schedule tasks to be run in the future by calling `this.schedule(when, callback, data)`, where `when` can be a delay, a `Date`, or a cron string; `callback` the function name to call, and `data` is an object of data to pass to the function. For fixed-interval recurring tasks, use `this.scheduleEvery(intervalSeconds, callback, data)`.
11
11
12
12
Scheduled tasks can do anything a request or message from a user can: make requests, query databases, send emails, read+write state: scheduled tasks can invoke any regular method on your Agent.
// schedule a task to run every 30 seconds (interval)
73
+
let task =awaitthis.scheduleEvery(30, "pollData", { source: "api" });
74
+
72
75
// cancel a scheduled task
73
76
this.cancelSchedule(task.id);
74
77
```
75
78
76
79
</TypeScriptExample>
77
80
78
-
Calling `await this.schedule` returns a `Schedule`, which includes the task's randomly generated `id`. You can use this `id` to retrieve or cancel the task in the future. It also provides a `type` property that indicates the type of schedule, for example, one of `"scheduled" | "delayed" | "cron"`.
81
+
Calling `await this.schedule`or `await this.scheduleEvery`returns a `Schedule`, which includes the task's randomly generated `id`. You can use this `id` to retrieve or cancel the task in the future. It also provides a `type` property that indicates the type of schedule, for example, one of `"scheduled" | "delayed" | "cron" | "interval"`.
79
82
80
83
:::note[Maximum scheduled tasks]
81
84
@@ -89,6 +92,58 @@ You can safely call `this.destroy()` from within a scheduled task callback. The
89
92
90
93
:::
91
94
95
+
### Interval scheduling with scheduleEvery()
96
+
97
+
For tasks that need to run at fixed intervals, use `this.scheduleEvery()`. Unlike cron expressions (which have minute-level precision), intervals support sub-minute timing and arbitrary durations:
| Arbitrary intervals | No (must fit cron pattern) | Yes |
120
+
| Fixed schedule | Yes (for example, every day at 8am) | No (relative to start) |
121
+
| Overlap prevention | No | Yes (built-in) |
122
+
123
+
**Overlap prevention**: If a callback takes longer than the interval, the next execution is skipped to prevent resource exhaustion. A warning is logged when this occurs.
124
+
125
+
**Error resilience**: If a callback throws an error, the interval continues running. Only that specific execution fails.
126
+
127
+
<TypeScriptExample>
128
+
129
+
```ts
130
+
exportclassPollingAgentextendsAgent {
131
+
async onRequest() {
132
+
// Start polling every 30 seconds
133
+
awaitthis.scheduleEvery(30, "poll", {});
134
+
returnnewResponse("Polling started");
135
+
}
136
+
137
+
async poll() {
138
+
// If this takes longer than 30 seconds, the next execution is skipped
139
+
const data =awaitfetch("https://api.example.com/data");
140
+
awaitthis.processData(awaitdata.json());
141
+
}
142
+
}
143
+
```
144
+
145
+
</TypeScriptExample>
146
+
92
147
### Managing scheduled tasks
93
148
94
149
You can get, cancel and filter across scheduled tasks within an Agent using the scheduling API:
@@ -109,13 +164,19 @@ let tasks = this.getSchedules();
109
164
awaitthis.cancelSchedule(task.id);
110
165
111
166
// Filter for specific tasks
112
-
//e.g. all tasks starting in the next hour
167
+
//for example, all tasks starting in the next hour
113
168
let tasks =this.getSchedules({
114
169
timeRange: {
115
170
start: newDate(Date.now()),
116
171
end: newDate(Date.now() +60*60*1000),
117
172
}
118
173
});
174
+
175
+
// Get only interval schedules
176
+
let intervalTasks =this.getSchedules({ type: "interval" });
177
+
178
+
// Get only cron schedules
179
+
let cronTasks =this.getSchedules({ type: "cron" });
0 commit comments