agents 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +303 -314
  2. package/dist/ai-types.js +1 -1
  3. package/dist/{client-0lfEZpSQ.js → client-6CeOh-EV.js} +7 -3
  4. package/dist/client-6CeOh-EV.js.map +1 -0
  5. package/dist/{client-Cxno-5sH.d.ts → client-DGpERepg.d.ts} +8 -14
  6. package/dist/client.d.ts +80 -24
  7. package/dist/client.js +184 -2
  8. package/dist/client.js.map +1 -0
  9. package/dist/{do-oauth-client-provider-BH9zFtSy.d.ts → do-oauth-client-provider-BqnOQzjy.d.ts} +1 -1
  10. package/dist/{do-oauth-client-provider-BfPFgQU0.js → do-oauth-client-provider-DDg8QrEA.js} +1 -1
  11. package/dist/{do-oauth-client-provider-BfPFgQU0.js.map → do-oauth-client-provider-DDg8QrEA.js.map} +1 -1
  12. package/dist/email-8ljcpvwV.d.ts +157 -0
  13. package/dist/email-XHsSYsTO.js +223 -0
  14. package/dist/email-XHsSYsTO.js.map +1 -0
  15. package/dist/email.d.ts +30 -0
  16. package/dist/email.js +3 -0
  17. package/dist/{index-B7Ny-XfU.d.ts → index-N6791tVt.d.ts} +18 -3
  18. package/dist/index.d.ts +543 -87
  19. package/dist/index.js +6 -6
  20. package/dist/{internal_context-neg89p5n.d.ts → internal_context-CEu5ji80.d.ts} +8 -3
  21. package/dist/{internal_context-oN047Id3.js → internal_context-D9eKFth1.js} +1 -1
  22. package/dist/internal_context-D9eKFth1.js.map +1 -0
  23. package/dist/internal_context.d.ts +1 -1
  24. package/dist/internal_context.js +1 -1
  25. package/dist/mcp/client.d.ts +1 -1
  26. package/dist/mcp/client.js +2 -2
  27. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  28. package/dist/mcp/do-oauth-client-provider.js +1 -1
  29. package/dist/mcp/index.d.ts +7 -3
  30. package/dist/mcp/index.js +51 -36
  31. package/dist/mcp/index.js.map +1 -1
  32. package/dist/mcp/x402.d.ts +0 -1
  33. package/dist/mcp/x402.js.map +1 -1
  34. package/dist/{mcp-AK39tq6H.d.ts → mcp-BwPscEiF.d.ts} +1 -1
  35. package/dist/observability/index.d.ts +1 -1
  36. package/dist/observability/index.js +5 -5
  37. package/dist/react.d.ts +70 -26
  38. package/dist/react.js +83 -21
  39. package/dist/react.js.map +1 -1
  40. package/dist/schedule.d.ts +23 -2
  41. package/dist/schedule.js +23 -1
  42. package/dist/schedule.js.map +1 -1
  43. package/dist/serializable.d.ts +77 -4
  44. package/dist/src-BFP4sOQ4.js +2146 -0
  45. package/dist/src-BFP4sOQ4.js.map +1 -0
  46. package/dist/types-BITaDFf-.js +16 -0
  47. package/dist/{types-4b5tlB0u.js.map → types-BITaDFf-.js.map} +1 -1
  48. package/dist/{types-C5vR2Gzv.d.ts → types-DSSHBW6w.d.ts} +2 -1
  49. package/dist/types.d.ts +1 -1
  50. package/dist/types.js +1 -1
  51. package/dist/utils-B49TmLCI.js +16 -0
  52. package/dist/utils-B49TmLCI.js.map +1 -0
  53. package/dist/utils.d.ts +10 -0
  54. package/dist/utils.js +3 -0
  55. package/dist/workflow-types-Z_Oem1FJ.d.ts +260 -0
  56. package/dist/workflow-types.d.ts +48 -0
  57. package/dist/workflow-types.js +16 -0
  58. package/dist/workflow-types.js.map +1 -0
  59. package/dist/workflows.d.ts +163 -0
  60. package/dist/workflows.js +240 -0
  61. package/dist/workflows.js.map +1 -0
  62. package/package.json +22 -12
  63. package/dist/client-0lfEZpSQ.js.map +0 -1
  64. package/dist/client-CEO0P7vN.js +0 -117
  65. package/dist/client-CEO0P7vN.js.map +0 -1
  66. package/dist/internal_context-oN047Id3.js.map +0 -1
  67. package/dist/src-C_iKczoR.js +0 -1191
  68. package/dist/src-C_iKczoR.js.map +0 -1
  69. package/dist/types-4b5tlB0u.js +0 -15
@@ -0,0 +1,2146 @@
1
+ import { t as MessageType } from "./types-BITaDFf-.js";
2
+ import { t as camelCaseToKebabCase } from "./utils-B49TmLCI.js";
3
+ import { s as signAgentHeaders } from "./email-XHsSYsTO.js";
4
+ import { t as agentContext } from "./internal_context-D9eKFth1.js";
5
+ import { i as DisposableStore, r as MCPConnectionState, t as MCPClientManager } from "./client-6CeOh-EV.js";
6
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-DDg8QrEA.js";
7
+ import { parseCronExpression } from "cron-schedule";
8
+ import { nanoid } from "nanoid";
9
+ import { EmailMessage } from "cloudflare:email";
10
+ import { Server, getServerByName, routePartykitRequest } from "partyserver";
11
+
12
+ //#region src/observability/index.ts
13
+ /**
14
+ * A generic observability implementation that logs events to the console.
15
+ */
16
+ const genericObservability = { emit(event) {
17
+ if (isLocalMode()) {
18
+ console.log(event.displayMessage);
19
+ return;
20
+ }
21
+ console.log(event);
22
+ } };
23
+ let localMode = false;
24
+ function isLocalMode() {
25
+ if (localMode) return true;
26
+ const { request } = getCurrentAgent();
27
+ if (!request) return false;
28
+ localMode = new URL(request.url).hostname === "localhost";
29
+ return localMode;
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/index.ts
34
+ /**
35
+ * Type guard for RPC request messages
36
+ */
37
+ function isRPCRequest(msg) {
38
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
39
+ }
40
+ /**
41
+ * Type guard for state update messages
42
+ */
43
+ function isStateUpdateMessage(msg) {
44
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
45
+ }
46
+ const callableMetadata = /* @__PURE__ */ new WeakMap();
47
+ /**
48
+ * Error class for SQL execution failures, containing the query that failed
49
+ */
50
+ var SqlError = class extends Error {
51
+ constructor(query, cause) {
52
+ const message = cause instanceof Error ? cause.message : String(cause);
53
+ super(`SQL query failed: ${message}`, { cause });
54
+ this.name = "SqlError";
55
+ this.query = query;
56
+ }
57
+ };
58
+ /**
59
+ * Decorator that marks a method as callable by clients
60
+ * @param metadata Optional metadata about the callable method
61
+ */
62
+ function callable(metadata = {}) {
63
+ return function callableDecorator(target, context) {
64
+ if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
65
+ return target;
66
+ };
67
+ }
68
+ let didWarnAboutUnstableCallable = false;
69
+ /**
70
+ * Decorator that marks a method as callable by clients
71
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
72
+ * @param metadata Optional metadata about the callable method
73
+ */
74
+ const unstable_callable = (metadata = {}) => {
75
+ if (!didWarnAboutUnstableCallable) {
76
+ didWarnAboutUnstableCallable = true;
77
+ console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
78
+ }
79
+ return callable(metadata);
80
+ };
81
+ function getNextCronTime(cron) {
82
+ return parseCronExpression(cron).getNextDate();
83
+ }
84
+ const STATE_ROW_ID = "cf_state_row_id";
85
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
86
+ const DEFAULT_STATE = {};
87
+ /**
88
+ * Default options for Agent configuration.
89
+ * Child classes can override specific options without spreading.
90
+ */
91
+ const DEFAULT_AGENT_STATIC_OPTIONS = {
92
+ hibernate: true,
93
+ sendIdentityOnConnect: true,
94
+ hungScheduleTimeoutSeconds: 30
95
+ };
96
+ function getCurrentAgent() {
97
+ const store = agentContext.getStore();
98
+ if (!store) return {
99
+ agent: void 0,
100
+ connection: void 0,
101
+ request: void 0,
102
+ email: void 0
103
+ };
104
+ return store;
105
+ }
106
+ /**
107
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
108
+ * @param agent The agent instance
109
+ * @param method The method to wrap
110
+ * @returns A wrapped method that runs within the agent context
111
+ */
112
+ function withAgentContext(method) {
113
+ return function(...args) {
114
+ const { connection, request, email, agent } = getCurrentAgent();
115
+ if (agent === this) return method.apply(this, args);
116
+ return agentContext.run({
117
+ agent: this,
118
+ connection,
119
+ request,
120
+ email
121
+ }, () => {
122
+ return method.apply(this, args);
123
+ });
124
+ };
125
+ }
126
+ /**
127
+ * Base class for creating Agent implementations
128
+ * @template Env Environment type containing bindings
129
+ * @template State State type to store within the Agent
130
+ */
131
+ var Agent = class Agent extends Server {
132
+ /**
133
+ * Current state of the Agent
134
+ */
135
+ get state() {
136
+ if (this._state !== DEFAULT_STATE) return this._state;
137
+ const wasChanged = this.sql`
138
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
139
+ `;
140
+ const result = this.sql`
141
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
142
+ `;
143
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
144
+ const state = result[0]?.state;
145
+ try {
146
+ this._state = JSON.parse(state);
147
+ } catch (e) {
148
+ console.error("Failed to parse stored state, falling back to initialState:", e);
149
+ if (this.initialState !== DEFAULT_STATE) {
150
+ this._state = this.initialState;
151
+ this.setState(this.initialState);
152
+ } else {
153
+ this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_ROW_ID}`;
154
+ this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}`;
155
+ return;
156
+ }
157
+ }
158
+ return this._state;
159
+ }
160
+ if (this.initialState === DEFAULT_STATE) return;
161
+ this.setState(this.initialState);
162
+ return this.initialState;
163
+ }
164
+ static {
165
+ this.options = { hibernate: true };
166
+ }
167
+ /**
168
+ * Resolved options (merges defaults with subclass overrides)
169
+ */
170
+ get _resolvedOptions() {
171
+ const ctor = this.constructor;
172
+ return {
173
+ hibernate: ctor.options?.hibernate ?? DEFAULT_AGENT_STATIC_OPTIONS.hibernate,
174
+ sendIdentityOnConnect: ctor.options?.sendIdentityOnConnect ?? DEFAULT_AGENT_STATIC_OPTIONS.sendIdentityOnConnect,
175
+ hungScheduleTimeoutSeconds: ctor.options?.hungScheduleTimeoutSeconds ?? DEFAULT_AGENT_STATIC_OPTIONS.hungScheduleTimeoutSeconds
176
+ };
177
+ }
178
+ /**
179
+ * Execute SQL queries against the Agent's database
180
+ * @template T Type of the returned rows
181
+ * @param strings SQL query template strings
182
+ * @param values Values to be inserted into the query
183
+ * @returns Array of query results
184
+ */
185
+ sql(strings, ...values) {
186
+ let query = "";
187
+ try {
188
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
189
+ return [...this.ctx.storage.sql.exec(query, ...values)];
190
+ } catch (e) {
191
+ throw this.onError(new SqlError(query, e));
192
+ }
193
+ }
194
+ constructor(ctx, env) {
195
+ super(ctx, env);
196
+ this._state = DEFAULT_STATE;
197
+ this._disposables = new DisposableStore();
198
+ this._destroyed = false;
199
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
200
+ this.initialState = DEFAULT_STATE;
201
+ this.observability = genericObservability;
202
+ this._flushingQueue = false;
203
+ this.alarm = async () => {
204
+ const now = Math.floor(Date.now() / 1e3);
205
+ const result = this.sql`
206
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
207
+ `;
208
+ if (result && Array.isArray(result)) for (const row of result) {
209
+ const callback = this[row.callback];
210
+ if (!callback) {
211
+ console.error(`callback ${row.callback} not found`);
212
+ continue;
213
+ }
214
+ if (row.type === "interval" && row.running === 1) {
215
+ const executionStartedAt = row.execution_started_at ?? 0;
216
+ const hungTimeoutSeconds = this._resolvedOptions.hungScheduleTimeoutSeconds;
217
+ const elapsedSeconds = now - executionStartedAt;
218
+ if (elapsedSeconds < hungTimeoutSeconds) {
219
+ console.warn(`Skipping interval schedule ${row.id}: previous execution still running`);
220
+ continue;
221
+ }
222
+ console.warn(`Forcing reset of hung interval schedule ${row.id} (started ${elapsedSeconds}s ago)`);
223
+ }
224
+ if (row.type === "interval") this.sql`UPDATE cf_agents_schedules SET running = 1, execution_started_at = ${now} WHERE id = ${row.id}`;
225
+ await agentContext.run({
226
+ agent: this,
227
+ connection: void 0,
228
+ request: void 0,
229
+ email: void 0
230
+ }, async () => {
231
+ try {
232
+ this.observability?.emit({
233
+ displayMessage: `Schedule ${row.id} executed`,
234
+ id: nanoid(),
235
+ payload: {
236
+ callback: row.callback,
237
+ id: row.id
238
+ },
239
+ timestamp: Date.now(),
240
+ type: "schedule:execute"
241
+ }, this.ctx);
242
+ await callback.bind(this)(JSON.parse(row.payload), row);
243
+ } catch (e) {
244
+ console.error(`error executing callback "${row.callback}"`, e);
245
+ try {
246
+ await this.onError(e);
247
+ } catch {}
248
+ }
249
+ });
250
+ if (this._destroyed) return;
251
+ if (row.type === "cron") {
252
+ const nextExecutionTime = getNextCronTime(row.cron);
253
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
254
+ this.sql`
255
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
256
+ `;
257
+ } else if (row.type === "interval") {
258
+ const nextTimestamp = Math.floor(Date.now() / 1e3) + (row.intervalSeconds ?? 0);
259
+ this.sql`
260
+ UPDATE cf_agents_schedules SET running = 0, time = ${nextTimestamp} WHERE id = ${row.id}
261
+ `;
262
+ } else this.sql`
263
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
264
+ `;
265
+ }
266
+ if (this._destroyed) return;
267
+ await this._scheduleNextAlarm();
268
+ };
269
+ if (!wrappedClasses.has(this.constructor)) {
270
+ this._autoWrapCustomMethods();
271
+ wrappedClasses.add(this.constructor);
272
+ }
273
+ this.sql`
274
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
275
+ id TEXT PRIMARY KEY NOT NULL,
276
+ name TEXT NOT NULL,
277
+ server_url TEXT NOT NULL,
278
+ callback_url TEXT NOT NULL,
279
+ client_id TEXT,
280
+ auth_url TEXT,
281
+ server_options TEXT
282
+ )
283
+ `;
284
+ this.sql`
285
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
286
+ id TEXT PRIMARY KEY NOT NULL,
287
+ state TEXT
288
+ )
289
+ `;
290
+ this.sql`
291
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
292
+ id TEXT PRIMARY KEY NOT NULL,
293
+ payload TEXT,
294
+ callback TEXT,
295
+ created_at INTEGER DEFAULT (unixepoch())
296
+ )
297
+ `;
298
+ this.sql`
299
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
300
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
301
+ callback TEXT,
302
+ payload TEXT,
303
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron', 'interval')),
304
+ time INTEGER,
305
+ delayInSeconds INTEGER,
306
+ cron TEXT,
307
+ intervalSeconds INTEGER,
308
+ running INTEGER DEFAULT 0,
309
+ created_at INTEGER DEFAULT (unixepoch())
310
+ )
311
+ `;
312
+ const addColumnIfNotExists = (sql) => {
313
+ try {
314
+ this.ctx.storage.sql.exec(sql);
315
+ } catch (e) {
316
+ if (!(e instanceof Error ? e.message : String(e)).toLowerCase().includes("duplicate column")) throw e;
317
+ }
318
+ };
319
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN intervalSeconds INTEGER");
320
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN running INTEGER DEFAULT 0");
321
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER");
322
+ this.sql`
323
+ CREATE TABLE IF NOT EXISTS cf_agents_workflows (
324
+ id TEXT PRIMARY KEY NOT NULL,
325
+ workflow_id TEXT NOT NULL UNIQUE,
326
+ workflow_name TEXT NOT NULL,
327
+ status TEXT NOT NULL CHECK(status IN (
328
+ 'queued', 'running', 'paused', 'errored',
329
+ 'terminated', 'complete', 'waiting',
330
+ 'waitingForPause', 'unknown'
331
+ )),
332
+ metadata TEXT,
333
+ error_name TEXT,
334
+ error_message TEXT,
335
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
336
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
337
+ completed_at INTEGER
338
+ )
339
+ `;
340
+ this.sql`
341
+ CREATE INDEX IF NOT EXISTS idx_workflows_status ON cf_agents_workflows(status)
342
+ `;
343
+ this.sql`
344
+ CREATE INDEX IF NOT EXISTS idx_workflows_name ON cf_agents_workflows(workflow_name)
345
+ `;
346
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
347
+ this._disposables.add(this.mcp.onServerStateChanged(async () => {
348
+ this.broadcastMcpServers();
349
+ }));
350
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
351
+ this.observability?.emit(event);
352
+ }));
353
+ const _onRequest = this.onRequest.bind(this);
354
+ this.onRequest = (request) => {
355
+ return agentContext.run({
356
+ agent: this,
357
+ connection: void 0,
358
+ request,
359
+ email: void 0
360
+ }, async () => {
361
+ await this.mcp.ensureJsonSchema();
362
+ const oauthResponse = await this.handleMcpOAuthCallback(request);
363
+ if (oauthResponse) return oauthResponse;
364
+ return this._tryCatch(() => _onRequest(request));
365
+ });
366
+ };
367
+ const _onMessage = this.onMessage.bind(this);
368
+ this.onMessage = async (connection, message) => {
369
+ return agentContext.run({
370
+ agent: this,
371
+ connection,
372
+ request: void 0,
373
+ email: void 0
374
+ }, async () => {
375
+ await this.mcp.ensureJsonSchema();
376
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
377
+ let parsed;
378
+ try {
379
+ parsed = JSON.parse(message);
380
+ } catch (_e) {
381
+ return this._tryCatch(() => _onMessage(connection, message));
382
+ }
383
+ if (isStateUpdateMessage(parsed)) {
384
+ this._setStateInternal(parsed.state, connection);
385
+ return;
386
+ }
387
+ if (isRPCRequest(parsed)) {
388
+ try {
389
+ const { id, method, args } = parsed;
390
+ const methodFn = this[method];
391
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
392
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
393
+ const metadata = callableMetadata.get(methodFn);
394
+ if (metadata?.streaming) {
395
+ const stream = new StreamingResponse(connection, id);
396
+ this.observability?.emit({
397
+ displayMessage: `RPC streaming call to ${method}`,
398
+ id: nanoid(),
399
+ payload: {
400
+ method,
401
+ streaming: true
402
+ },
403
+ timestamp: Date.now(),
404
+ type: "rpc"
405
+ }, this.ctx);
406
+ try {
407
+ await methodFn.apply(this, [stream, ...args]);
408
+ } catch (err) {
409
+ console.error(`Error in streaming method "${method}":`, err);
410
+ if (!stream.isClosed) stream.error(err instanceof Error ? err.message : String(err));
411
+ }
412
+ return;
413
+ }
414
+ const result = await methodFn.apply(this, args);
415
+ this.observability?.emit({
416
+ displayMessage: `RPC call to ${method}`,
417
+ id: nanoid(),
418
+ payload: {
419
+ method,
420
+ streaming: metadata?.streaming
421
+ },
422
+ timestamp: Date.now(),
423
+ type: "rpc"
424
+ }, this.ctx);
425
+ const response = {
426
+ done: true,
427
+ id,
428
+ result,
429
+ success: true,
430
+ type: MessageType.RPC
431
+ };
432
+ connection.send(JSON.stringify(response));
433
+ } catch (e) {
434
+ const response = {
435
+ error: e instanceof Error ? e.message : "Unknown error occurred",
436
+ id: parsed.id,
437
+ success: false,
438
+ type: MessageType.RPC
439
+ };
440
+ connection.send(JSON.stringify(response));
441
+ console.error("RPC error:", e);
442
+ }
443
+ return;
444
+ }
445
+ return this._tryCatch(() => _onMessage(connection, message));
446
+ });
447
+ };
448
+ const _onConnect = this.onConnect.bind(this);
449
+ this.onConnect = (connection, ctx) => {
450
+ return agentContext.run({
451
+ agent: this,
452
+ connection,
453
+ request: ctx.request,
454
+ email: void 0
455
+ }, async () => {
456
+ if (this._resolvedOptions.sendIdentityOnConnect) connection.send(JSON.stringify({
457
+ name: this.name,
458
+ agent: camelCaseToKebabCase(this._ParentClass.name),
459
+ type: MessageType.CF_AGENT_IDENTITY
460
+ }));
461
+ if (this.state) connection.send(JSON.stringify({
462
+ state: this.state,
463
+ type: MessageType.CF_AGENT_STATE
464
+ }));
465
+ connection.send(JSON.stringify({
466
+ mcp: this.getMcpServers(),
467
+ type: MessageType.CF_AGENT_MCP_SERVERS
468
+ }));
469
+ this.observability?.emit({
470
+ displayMessage: "Connection established",
471
+ id: nanoid(),
472
+ payload: { connectionId: connection.id },
473
+ timestamp: Date.now(),
474
+ type: "connect"
475
+ }, this.ctx);
476
+ return this._tryCatch(() => _onConnect(connection, ctx));
477
+ });
478
+ };
479
+ const _onStart = this.onStart.bind(this);
480
+ this.onStart = async (props) => {
481
+ return agentContext.run({
482
+ agent: this,
483
+ connection: void 0,
484
+ request: void 0,
485
+ email: void 0
486
+ }, async () => {
487
+ await this._tryCatch(async () => {
488
+ await this.mcp.restoreConnectionsFromStorage(this.name);
489
+ this.broadcastMcpServers();
490
+ this._checkOrphanedWorkflows();
491
+ return _onStart(props);
492
+ });
493
+ });
494
+ };
495
+ }
496
+ /**
497
+ * Check for workflows referencing unknown bindings and warn with migration suggestion.
498
+ */
499
+ _checkOrphanedWorkflows() {
500
+ const orphaned = this.sql`
501
+ SELECT
502
+ workflow_name,
503
+ COUNT(*) as total,
504
+ SUM(CASE WHEN status NOT IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as active,
505
+ SUM(CASE WHEN status IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as completed
506
+ FROM cf_agents_workflows
507
+ GROUP BY workflow_name
508
+ `.filter((row) => !this._findWorkflowBindingByName(row.workflow_name));
509
+ if (orphaned.length > 0) {
510
+ const currentBindings = this._getWorkflowBindingNames();
511
+ for (const { workflow_name: oldName, total, active, completed } of orphaned) {
512
+ const suggestion = currentBindings.length === 1 ? `this.migrateWorkflowBinding('${oldName}', '${currentBindings[0]}')` : `this.migrateWorkflowBinding('${oldName}', '<NEW_BINDING_NAME>')`;
513
+ const breakdown = active > 0 && completed > 0 ? ` (${active} active, ${completed} completed)` : active > 0 ? ` (${active} active)` : ` (${completed} completed)`;
514
+ console.warn(`[Agent] Found ${total} workflow(s) referencing unknown binding '${oldName}'${breakdown}. If you renamed the binding, call: ${suggestion}`);
515
+ }
516
+ }
517
+ }
518
+ _setStateInternal(nextState, source = "server") {
519
+ this.validateStateChange(nextState, source);
520
+ this._state = nextState;
521
+ this.sql`
522
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
523
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(nextState)})
524
+ `;
525
+ this.sql`
526
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
527
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
528
+ `;
529
+ this.broadcast(JSON.stringify({
530
+ state: nextState,
531
+ type: MessageType.CF_AGENT_STATE
532
+ }), source !== "server" ? [source.id] : []);
533
+ const { connection, request, email } = agentContext.getStore() || {};
534
+ this.ctx.waitUntil((async () => {
535
+ try {
536
+ await agentContext.run({
537
+ agent: this,
538
+ connection,
539
+ request,
540
+ email
541
+ }, async () => {
542
+ this.observability?.emit({
543
+ displayMessage: "State updated",
544
+ id: nanoid(),
545
+ payload: {},
546
+ timestamp: Date.now(),
547
+ type: "state:update"
548
+ }, this.ctx);
549
+ await this.onStateUpdate(nextState, source);
550
+ });
551
+ } catch (e) {
552
+ try {
553
+ await this.onError(e);
554
+ } catch {}
555
+ }
556
+ })());
557
+ }
558
+ /**
559
+ * Update the Agent's state
560
+ * @param state New state to set
561
+ */
562
+ setState(state) {
563
+ this._setStateInternal(state, "server");
564
+ }
565
+ /**
566
+ * Called before the Agent's state is persisted and broadcast.
567
+ * Override to validate or reject an update by throwing an error.
568
+ *
569
+ * IMPORTANT: This hook must be synchronous.
570
+ */
571
+ validateStateChange(nextState, source) {}
572
+ /**
573
+ * Called when the Agent's state is updated
574
+ * @param state Updated state
575
+ * @param source Source of the state update ("server" or a client connection)
576
+ */
577
+ onStateUpdate(state, source) {}
578
+ /**
579
+ * Called when the Agent receives an email via routeAgentEmail()
580
+ * Override this method to handle incoming emails
581
+ * @param email Email message to process
582
+ */
583
+ async _onEmail(email) {
584
+ return agentContext.run({
585
+ agent: this,
586
+ connection: void 0,
587
+ request: void 0,
588
+ email
589
+ }, async () => {
590
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
591
+ else {
592
+ console.log("Received email from:", email.from, "to:", email.to);
593
+ console.log("Subject:", email.headers.get("subject"));
594
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
595
+ }
596
+ });
597
+ }
598
+ /**
599
+ * Reply to an email
600
+ * @param email The email to reply to
601
+ * @param options Options for the reply
602
+ * @param options.secret Secret for signing agent headers (enables secure reply routing).
603
+ * Required if the email was routed via createSecureReplyEmailResolver.
604
+ * Pass explicit `null` to opt-out of signing (not recommended for secure routing).
605
+ * @returns void
606
+ */
607
+ async replyToEmail(email, options) {
608
+ return this._tryCatch(async () => {
609
+ if (email._secureRouted && options.secret === void 0) throw new Error("This email was routed via createSecureReplyEmailResolver. You must pass a secret to replyToEmail() to sign replies, or pass explicit null to opt-out (not recommended).");
610
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
611
+ const agentId = this.name;
612
+ const { createMimeMessage } = await import("mimetext");
613
+ const msg = createMimeMessage();
614
+ msg.setSender({
615
+ addr: email.to,
616
+ name: options.fromName
617
+ });
618
+ msg.setRecipient(email.from);
619
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
620
+ msg.addMessage({
621
+ contentType: options.contentType || "text/plain",
622
+ data: options.body
623
+ });
624
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
625
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
626
+ msg.setHeader("Message-ID", messageId);
627
+ msg.setHeader("X-Agent-Name", agentName);
628
+ msg.setHeader("X-Agent-ID", agentId);
629
+ if (typeof options.secret === "string") {
630
+ const signedHeaders = await signAgentHeaders(options.secret, agentName, agentId);
631
+ msg.setHeader("X-Agent-Sig", signedHeaders["X-Agent-Sig"]);
632
+ msg.setHeader("X-Agent-Sig-Ts", signedHeaders["X-Agent-Sig-Ts"]);
633
+ }
634
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
635
+ await email.reply({
636
+ from: email.to,
637
+ raw: msg.asRaw(),
638
+ to: email.from
639
+ });
640
+ });
641
+ }
642
+ async _tryCatch(fn) {
643
+ try {
644
+ return await fn();
645
+ } catch (e) {
646
+ throw this.onError(e);
647
+ }
648
+ }
649
+ /**
650
+ * Automatically wrap custom methods with agent context
651
+ * This ensures getCurrentAgent() works in all custom methods without decorators
652
+ */
653
+ _autoWrapCustomMethods() {
654
+ const basePrototypes = [Agent.prototype, Server.prototype];
655
+ const baseMethods = /* @__PURE__ */ new Set();
656
+ for (const baseProto of basePrototypes) {
657
+ let proto = baseProto;
658
+ while (proto && proto !== Object.prototype) {
659
+ const methodNames = Object.getOwnPropertyNames(proto);
660
+ for (const methodName of methodNames) baseMethods.add(methodName);
661
+ proto = Object.getPrototypeOf(proto);
662
+ }
663
+ }
664
+ let proto = Object.getPrototypeOf(this);
665
+ let depth = 0;
666
+ while (proto && proto !== Object.prototype && depth < 10) {
667
+ const methodNames = Object.getOwnPropertyNames(proto);
668
+ for (const methodName of methodNames) {
669
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
670
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
671
+ const wrappedFunction = withAgentContext(this[methodName]);
672
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
673
+ this.constructor.prototype[methodName] = wrappedFunction;
674
+ }
675
+ proto = Object.getPrototypeOf(proto);
676
+ depth++;
677
+ }
678
+ }
679
+ onError(connectionOrError, error) {
680
+ let theError;
681
+ if (connectionOrError && error) {
682
+ theError = error;
683
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
684
+ console.error("Override onError(connection, error) to handle websocket connection errors");
685
+ } else {
686
+ theError = connectionOrError;
687
+ console.error("Error on server:", theError);
688
+ console.error("Override onError(error) to handle server errors");
689
+ }
690
+ throw theError;
691
+ }
692
+ /**
693
+ * Render content (not implemented in base class)
694
+ */
695
+ render() {
696
+ throw new Error("Not implemented");
697
+ }
698
+ /**
699
+ * Queue a task to be executed in the future
700
+ * @param payload Payload to pass to the callback
701
+ * @param callback Name of the method to call
702
+ * @returns The ID of the queued task
703
+ */
704
+ async queue(callback, payload) {
705
+ const id = nanoid(9);
706
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
707
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
708
+ this.sql`
709
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
710
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
711
+ `;
712
+ this._flushQueue().catch((e) => {
713
+ console.error("Error flushing queue:", e);
714
+ });
715
+ return id;
716
+ }
717
+ async _flushQueue() {
718
+ if (this._flushingQueue) return;
719
+ this._flushingQueue = true;
720
+ while (true) {
721
+ const result = this.sql`
722
+ SELECT * FROM cf_agents_queues
723
+ ORDER BY created_at ASC
724
+ `;
725
+ if (!result || result.length === 0) break;
726
+ for (const row of result || []) {
727
+ const callback = this[row.callback];
728
+ if (!callback) {
729
+ console.error(`callback ${row.callback} not found`);
730
+ continue;
731
+ }
732
+ const { connection, request, email } = agentContext.getStore() || {};
733
+ await agentContext.run({
734
+ agent: this,
735
+ connection,
736
+ request,
737
+ email
738
+ }, async () => {
739
+ await callback.bind(this)(JSON.parse(row.payload), row);
740
+ await this.dequeue(row.id);
741
+ });
742
+ }
743
+ }
744
+ this._flushingQueue = false;
745
+ }
746
+ /**
747
+ * Dequeue a task by ID
748
+ * @param id ID of the task to dequeue
749
+ */
750
+ async dequeue(id) {
751
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
752
+ }
753
+ /**
754
+ * Dequeue all tasks
755
+ */
756
+ async dequeueAll() {
757
+ this.sql`DELETE FROM cf_agents_queues`;
758
+ }
759
+ /**
760
+ * Dequeue all tasks by callback
761
+ * @param callback Name of the callback to dequeue
762
+ */
763
+ async dequeueAllByCallback(callback) {
764
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
765
+ }
766
+ /**
767
+ * Get a queued task by ID
768
+ * @param id ID of the task to get
769
+ * @returns The task or undefined if not found
770
+ */
771
+ async getQueue(id) {
772
+ const result = this.sql`
773
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
774
+ `;
775
+ return result ? {
776
+ ...result[0],
777
+ payload: JSON.parse(result[0].payload)
778
+ } : void 0;
779
+ }
780
+ /**
781
+ * Get all queues by key and value
782
+ * @param key Key to filter by
783
+ * @param value Value to filter by
784
+ * @returns Array of matching QueueItem objects
785
+ */
786
+ async getQueues(key, value) {
787
+ return this.sql`
788
+ SELECT * FROM cf_agents_queues
789
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
790
+ }
791
+ /**
792
+ * Schedule a task to be executed in the future
793
+ * @template T Type of the payload data
794
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
795
+ * @param callback Name of the method to call
796
+ * @param payload Data to pass to the callback
797
+ * @returns Schedule object representing the scheduled task
798
+ */
799
+ async schedule(when, callback, payload) {
800
+ const id = nanoid(9);
801
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
802
+ displayMessage: `Schedule ${schedule.id} created`,
803
+ id: nanoid(),
804
+ payload: {
805
+ callback,
806
+ id
807
+ },
808
+ timestamp: Date.now(),
809
+ type: "schedule:create"
810
+ }, this.ctx);
811
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
812
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
813
+ if (when instanceof Date) {
814
+ const timestamp = Math.floor(when.getTime() / 1e3);
815
+ this.sql`
816
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
817
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
818
+ `;
819
+ await this._scheduleNextAlarm();
820
+ const schedule = {
821
+ callback,
822
+ id,
823
+ payload,
824
+ time: timestamp,
825
+ type: "scheduled"
826
+ };
827
+ emitScheduleCreate(schedule);
828
+ return schedule;
829
+ }
830
+ if (typeof when === "number") {
831
+ const time = new Date(Date.now() + when * 1e3);
832
+ const timestamp = Math.floor(time.getTime() / 1e3);
833
+ this.sql`
834
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
835
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
836
+ `;
837
+ await this._scheduleNextAlarm();
838
+ const schedule = {
839
+ callback,
840
+ delayInSeconds: when,
841
+ id,
842
+ payload,
843
+ time: timestamp,
844
+ type: "delayed"
845
+ };
846
+ emitScheduleCreate(schedule);
847
+ return schedule;
848
+ }
849
+ if (typeof when === "string") {
850
+ const nextExecutionTime = getNextCronTime(when);
851
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
852
+ this.sql`
853
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
854
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
855
+ `;
856
+ await this._scheduleNextAlarm();
857
+ const schedule = {
858
+ callback,
859
+ cron: when,
860
+ id,
861
+ payload,
862
+ time: timestamp,
863
+ type: "cron"
864
+ };
865
+ emitScheduleCreate(schedule);
866
+ return schedule;
867
+ }
868
+ throw new Error(`Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`);
869
+ }
870
+ /**
871
+ * Schedule a task to run repeatedly at a fixed interval
872
+ * @template T Type of the payload data
873
+ * @param intervalSeconds Number of seconds between executions
874
+ * @param callback Name of the method to call
875
+ * @param payload Data to pass to the callback
876
+ * @returns Schedule object representing the scheduled task
877
+ */
878
+ async scheduleEvery(intervalSeconds, callback, payload) {
879
+ const MAX_INTERVAL_SECONDS = 720 * 60 * 60;
880
+ if (typeof intervalSeconds !== "number" || intervalSeconds <= 0) throw new Error("intervalSeconds must be a positive number");
881
+ if (intervalSeconds > MAX_INTERVAL_SECONDS) throw new Error(`intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`);
882
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
883
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
884
+ const id = nanoid(9);
885
+ const time = new Date(Date.now() + intervalSeconds * 1e3);
886
+ const timestamp = Math.floor(time.getTime() / 1e3);
887
+ this.sql`
888
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, intervalSeconds, time, running)
889
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'interval', ${intervalSeconds}, ${timestamp}, 0)
890
+ `;
891
+ await this._scheduleNextAlarm();
892
+ const schedule = {
893
+ callback,
894
+ id,
895
+ intervalSeconds,
896
+ payload,
897
+ time: timestamp,
898
+ type: "interval"
899
+ };
900
+ this.observability?.emit({
901
+ displayMessage: `Schedule ${schedule.id} created`,
902
+ id: nanoid(),
903
+ payload: {
904
+ callback,
905
+ id
906
+ },
907
+ timestamp: Date.now(),
908
+ type: "schedule:create"
909
+ }, this.ctx);
910
+ return schedule;
911
+ }
912
+ /**
913
+ * Get a scheduled task by ID
914
+ * @template T Type of the payload data
915
+ * @param id ID of the scheduled task
916
+ * @returns The Schedule object or undefined if not found
917
+ */
918
+ async getSchedule(id) {
919
+ const result = this.sql`
920
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
921
+ `;
922
+ if (!result || result.length === 0) return;
923
+ return {
924
+ ...result[0],
925
+ payload: JSON.parse(result[0].payload)
926
+ };
927
+ }
928
+ /**
929
+ * Get scheduled tasks matching the given criteria
930
+ * @template T Type of the payload data
931
+ * @param criteria Criteria to filter schedules
932
+ * @returns Array of matching Schedule objects
933
+ */
934
+ getSchedules(criteria = {}) {
935
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
936
+ const params = [];
937
+ if (criteria.id) {
938
+ query += " AND id = ?";
939
+ params.push(criteria.id);
940
+ }
941
+ if (criteria.type) {
942
+ query += " AND type = ?";
943
+ params.push(criteria.type);
944
+ }
945
+ if (criteria.timeRange) {
946
+ query += " AND time >= ? AND time <= ?";
947
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
948
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
949
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
950
+ }
951
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
952
+ ...row,
953
+ payload: JSON.parse(row.payload)
954
+ }));
955
+ }
956
+ /**
957
+ * Cancel a scheduled task
958
+ * @param id ID of the task to cancel
959
+ * @returns true if the task was cancelled, false if the task was not found
960
+ */
961
+ async cancelSchedule(id) {
962
+ const schedule = await this.getSchedule(id);
963
+ if (!schedule) return false;
964
+ this.observability?.emit({
965
+ displayMessage: `Schedule ${id} cancelled`,
966
+ id: nanoid(),
967
+ payload: {
968
+ callback: schedule.callback,
969
+ id: schedule.id
970
+ },
971
+ timestamp: Date.now(),
972
+ type: "schedule:cancel"
973
+ }, this.ctx);
974
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
975
+ await this._scheduleNextAlarm();
976
+ return true;
977
+ }
978
+ async _scheduleNextAlarm() {
979
+ const result = this.sql`
980
+ SELECT time FROM cf_agents_schedules
981
+ WHERE time >= ${Math.floor(Date.now() / 1e3)}
982
+ ORDER BY time ASC
983
+ LIMIT 1
984
+ `;
985
+ if (!result) return;
986
+ if (result.length > 0 && "time" in result[0]) {
987
+ const nextTime = result[0].time * 1e3;
988
+ await this.ctx.storage.setAlarm(nextTime);
989
+ }
990
+ }
991
+ /**
992
+ * Destroy the Agent, removing all state and scheduled tasks
993
+ */
994
+ async destroy() {
995
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
996
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
997
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
998
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
999
+ this.sql`DROP TABLE IF EXISTS cf_agents_workflows`;
1000
+ await this.ctx.storage.deleteAlarm();
1001
+ await this.ctx.storage.deleteAll();
1002
+ this._disposables.dispose();
1003
+ await this.mcp.dispose();
1004
+ this._destroyed = true;
1005
+ setTimeout(() => {
1006
+ this.ctx.abort("destroyed");
1007
+ }, 0);
1008
+ this.observability?.emit({
1009
+ displayMessage: "Agent destroyed",
1010
+ id: nanoid(),
1011
+ payload: {},
1012
+ timestamp: Date.now(),
1013
+ type: "destroy"
1014
+ }, this.ctx);
1015
+ }
1016
+ /**
1017
+ * Check if a method is callable
1018
+ * @param method The method name to check
1019
+ * @returns True if the method is marked as callable
1020
+ */
1021
+ _isCallable(method) {
1022
+ return callableMetadata.has(this[method]);
1023
+ }
1024
+ /**
1025
+ * Get all methods marked as callable on this Agent
1026
+ * @returns A map of method names to their metadata
1027
+ */
1028
+ getCallableMethods() {
1029
+ const result = /* @__PURE__ */ new Map();
1030
+ let prototype = Object.getPrototypeOf(this);
1031
+ while (prototype && prototype !== Object.prototype) {
1032
+ for (const name of Object.getOwnPropertyNames(prototype)) {
1033
+ if (name === "constructor") continue;
1034
+ if (result.has(name)) continue;
1035
+ try {
1036
+ const fn = prototype[name];
1037
+ if (typeof fn === "function") {
1038
+ const meta = callableMetadata.get(fn);
1039
+ if (meta) result.set(name, meta);
1040
+ }
1041
+ } catch (e) {
1042
+ if (!(e instanceof TypeError)) throw e;
1043
+ }
1044
+ }
1045
+ prototype = Object.getPrototypeOf(prototype);
1046
+ }
1047
+ return result;
1048
+ }
1049
+ /**
1050
+ * Start a workflow and track it in this Agent's database.
1051
+ * Automatically injects agent identity into the workflow params.
1052
+ *
1053
+ * @template P - Type of params to pass to the workflow
1054
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
1055
+ * @param params - Params to pass to the workflow
1056
+ * @param options - Optional workflow options
1057
+ * @returns The workflow instance ID
1058
+ *
1059
+ * @example
1060
+ * ```typescript
1061
+ * const workflowId = await this.runWorkflow(
1062
+ * 'MY_WORKFLOW',
1063
+ * { taskId: '123', data: 'process this' }
1064
+ * );
1065
+ * ```
1066
+ */
1067
+ async runWorkflow(workflowName, params, options) {
1068
+ const workflow = this._findWorkflowBindingByName(workflowName);
1069
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
1070
+ const agentBindingName = options?.agentBinding ?? this._findAgentBindingName();
1071
+ if (!agentBindingName) throw new Error("Could not detect Agent binding name from class name. Pass it explicitly via options.agentBinding");
1072
+ const workflowId = options?.id ?? nanoid();
1073
+ const augmentedParams = {
1074
+ ...params,
1075
+ __agentName: this.name,
1076
+ __agentBinding: agentBindingName,
1077
+ __workflowName: workflowName
1078
+ };
1079
+ const instance = await workflow.create({
1080
+ id: workflowId,
1081
+ params: augmentedParams
1082
+ });
1083
+ const id = nanoid();
1084
+ const metadataJson = options?.metadata ? JSON.stringify(options.metadata) : null;
1085
+ try {
1086
+ this.sql`
1087
+ INSERT INTO cf_agents_workflows (id, workflow_id, workflow_name, status, metadata)
1088
+ VALUES (${id}, ${instance.id}, ${workflowName}, 'queued', ${metadataJson})
1089
+ `;
1090
+ } catch (e) {
1091
+ if (e instanceof Error && e.message.includes("UNIQUE constraint failed")) throw new Error(`Workflow with ID "${workflowId}" is already being tracked`);
1092
+ throw e;
1093
+ }
1094
+ this.observability?.emit({
1095
+ displayMessage: `Workflow ${instance.id} started`,
1096
+ id: nanoid(),
1097
+ payload: {
1098
+ workflowId: instance.id,
1099
+ workflowName
1100
+ },
1101
+ timestamp: Date.now(),
1102
+ type: "workflow:start"
1103
+ }, this.ctx);
1104
+ return instance.id;
1105
+ }
1106
+ /**
1107
+ * Send an event to a running workflow.
1108
+ * The workflow can wait for this event using step.waitForEvent().
1109
+ *
1110
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
1111
+ * @param workflowId - ID of the workflow instance
1112
+ * @param event - Event to send
1113
+ *
1114
+ * @example
1115
+ * ```typescript
1116
+ * await this.sendWorkflowEvent(
1117
+ * 'MY_WORKFLOW',
1118
+ * workflowId,
1119
+ * { type: 'approval', payload: { approved: true } }
1120
+ * );
1121
+ * ```
1122
+ */
1123
+ async sendWorkflowEvent(workflowName, workflowId, event) {
1124
+ const workflow = this._findWorkflowBindingByName(workflowName);
1125
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
1126
+ await (await workflow.get(workflowId)).sendEvent(event);
1127
+ this.observability?.emit({
1128
+ displayMessage: `Event sent to workflow ${workflowId}`,
1129
+ id: nanoid(),
1130
+ payload: {
1131
+ workflowId,
1132
+ eventType: event.type
1133
+ },
1134
+ timestamp: Date.now(),
1135
+ type: "workflow:event"
1136
+ }, this.ctx);
1137
+ }
1138
+ /**
1139
+ * Approve a waiting workflow.
1140
+ * Sends an approval event to the workflow that can be received by waitForApproval().
1141
+ *
1142
+ * @param workflowId - ID of the workflow to approve
1143
+ * @param data - Optional approval data (reason, metadata)
1144
+ *
1145
+ * @example
1146
+ * ```typescript
1147
+ * await this.approveWorkflow(workflowId, {
1148
+ * reason: 'Approved by admin',
1149
+ * metadata: { approvedBy: userId }
1150
+ * });
1151
+ * ```
1152
+ */
1153
+ async approveWorkflow(workflowId, data) {
1154
+ const workflowInfo = this.getWorkflow(workflowId);
1155
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1156
+ await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
1157
+ type: "approval",
1158
+ payload: {
1159
+ approved: true,
1160
+ reason: data?.reason,
1161
+ metadata: data?.metadata
1162
+ }
1163
+ });
1164
+ this.observability?.emit({
1165
+ displayMessage: `Workflow ${workflowId} approved`,
1166
+ id: nanoid(),
1167
+ payload: {
1168
+ workflowId,
1169
+ reason: data?.reason
1170
+ },
1171
+ timestamp: Date.now(),
1172
+ type: "workflow:approved"
1173
+ }, this.ctx);
1174
+ }
1175
+ /**
1176
+ * Reject a waiting workflow.
1177
+ * Sends a rejection event to the workflow that will cause waitForApproval() to throw.
1178
+ *
1179
+ * @param workflowId - ID of the workflow to reject
1180
+ * @param data - Optional rejection data (reason)
1181
+ *
1182
+ * @example
1183
+ * ```typescript
1184
+ * await this.rejectWorkflow(workflowId, {
1185
+ * reason: 'Request denied by admin'
1186
+ * });
1187
+ * ```
1188
+ */
1189
+ async rejectWorkflow(workflowId, data) {
1190
+ const workflowInfo = this.getWorkflow(workflowId);
1191
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1192
+ await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
1193
+ type: "approval",
1194
+ payload: {
1195
+ approved: false,
1196
+ reason: data?.reason
1197
+ }
1198
+ });
1199
+ this.observability?.emit({
1200
+ displayMessage: `Workflow ${workflowId} rejected`,
1201
+ id: nanoid(),
1202
+ payload: {
1203
+ workflowId,
1204
+ reason: data?.reason
1205
+ },
1206
+ timestamp: Date.now(),
1207
+ type: "workflow:rejected"
1208
+ }, this.ctx);
1209
+ }
1210
+ /**
1211
+ * Terminate a running workflow.
1212
+ * This immediately stops the workflow and sets its status to "terminated".
1213
+ *
1214
+ * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)
1215
+ * @throws Error if workflow not found in tracking table
1216
+ * @throws Error if workflow binding not found in environment
1217
+ * @throws Error if workflow is already completed/errored/terminated (from Cloudflare)
1218
+ *
1219
+ * @note `terminate()` is not yet supported in local development (wrangler dev).
1220
+ * It will throw an error locally but works when deployed to Cloudflare.
1221
+ *
1222
+ * @example
1223
+ * ```typescript
1224
+ * await this.terminateWorkflow(workflowId);
1225
+ * ```
1226
+ */
1227
+ async terminateWorkflow(workflowId) {
1228
+ const workflowInfo = this.getWorkflow(workflowId);
1229
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1230
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
1231
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
1232
+ const instance = await workflow.get(workflowId);
1233
+ try {
1234
+ await instance.terminate();
1235
+ } catch (err) {
1236
+ if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("terminateWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
1237
+ throw err;
1238
+ }
1239
+ const status = await instance.status();
1240
+ this._updateWorkflowTracking(workflowId, status);
1241
+ this.observability?.emit({
1242
+ displayMessage: `Workflow ${workflowId} terminated`,
1243
+ id: nanoid(),
1244
+ payload: {
1245
+ workflowId,
1246
+ workflowName: workflowInfo.workflowName
1247
+ },
1248
+ timestamp: Date.now(),
1249
+ type: "workflow:terminated"
1250
+ }, this.ctx);
1251
+ }
1252
+ /**
1253
+ * Pause a running workflow.
1254
+ * The workflow can be resumed later with resumeWorkflow().
1255
+ *
1256
+ * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)
1257
+ * @throws Error if workflow not found in tracking table
1258
+ * @throws Error if workflow binding not found in environment
1259
+ * @throws Error if workflow is not running (from Cloudflare)
1260
+ *
1261
+ * @note `pause()` is not yet supported in local development (wrangler dev).
1262
+ * It will throw an error locally but works when deployed to Cloudflare.
1263
+ *
1264
+ * @example
1265
+ * ```typescript
1266
+ * await this.pauseWorkflow(workflowId);
1267
+ * ```
1268
+ */
1269
+ async pauseWorkflow(workflowId) {
1270
+ const workflowInfo = this.getWorkflow(workflowId);
1271
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1272
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
1273
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
1274
+ const instance = await workflow.get(workflowId);
1275
+ try {
1276
+ await instance.pause();
1277
+ } catch (err) {
1278
+ if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("pauseWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
1279
+ throw err;
1280
+ }
1281
+ const status = await instance.status();
1282
+ this._updateWorkflowTracking(workflowId, status);
1283
+ this.observability?.emit({
1284
+ displayMessage: `Workflow ${workflowId} paused`,
1285
+ id: nanoid(),
1286
+ payload: {
1287
+ workflowId,
1288
+ workflowName: workflowInfo.workflowName
1289
+ },
1290
+ timestamp: Date.now(),
1291
+ type: "workflow:paused"
1292
+ }, this.ctx);
1293
+ }
1294
+ /**
1295
+ * Resume a paused workflow.
1296
+ *
1297
+ * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)
1298
+ * @throws Error if workflow not found in tracking table
1299
+ * @throws Error if workflow binding not found in environment
1300
+ * @throws Error if workflow is not paused (from Cloudflare)
1301
+ *
1302
+ * @note `resume()` is not yet supported in local development (wrangler dev).
1303
+ * It will throw an error locally but works when deployed to Cloudflare.
1304
+ *
1305
+ * @example
1306
+ * ```typescript
1307
+ * await this.resumeWorkflow(workflowId);
1308
+ * ```
1309
+ */
1310
+ async resumeWorkflow(workflowId) {
1311
+ const workflowInfo = this.getWorkflow(workflowId);
1312
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1313
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
1314
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
1315
+ const instance = await workflow.get(workflowId);
1316
+ try {
1317
+ await instance.resume();
1318
+ } catch (err) {
1319
+ if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("resumeWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
1320
+ throw err;
1321
+ }
1322
+ const status = await instance.status();
1323
+ this._updateWorkflowTracking(workflowId, status);
1324
+ this.observability?.emit({
1325
+ displayMessage: `Workflow ${workflowId} resumed`,
1326
+ id: nanoid(),
1327
+ payload: {
1328
+ workflowId,
1329
+ workflowName: workflowInfo.workflowName
1330
+ },
1331
+ timestamp: Date.now(),
1332
+ type: "workflow:resumed"
1333
+ }, this.ctx);
1334
+ }
1335
+ /**
1336
+ * Restart a workflow instance.
1337
+ * This re-runs the workflow from the beginning with the same ID.
1338
+ *
1339
+ * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)
1340
+ * @param options - Optional settings
1341
+ * @param options.resetTracking - If true (default), resets created_at and clears error fields.
1342
+ * If false, preserves original timestamps.
1343
+ * @throws Error if workflow not found in tracking table
1344
+ * @throws Error if workflow binding not found in environment
1345
+ *
1346
+ * @note `restart()` is not yet supported in local development (wrangler dev).
1347
+ * It will throw an error locally but works when deployed to Cloudflare.
1348
+ *
1349
+ * @example
1350
+ * ```typescript
1351
+ * // Reset tracking (default)
1352
+ * await this.restartWorkflow(workflowId);
1353
+ *
1354
+ * // Preserve original timestamps
1355
+ * await this.restartWorkflow(workflowId, { resetTracking: false });
1356
+ * ```
1357
+ */
1358
+ async restartWorkflow(workflowId, options = {}) {
1359
+ const { resetTracking = true } = options;
1360
+ const workflowInfo = this.getWorkflow(workflowId);
1361
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
1362
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
1363
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
1364
+ const instance = await workflow.get(workflowId);
1365
+ try {
1366
+ await instance.restart();
1367
+ } catch (err) {
1368
+ if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("restartWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
1369
+ throw err;
1370
+ }
1371
+ if (resetTracking) {
1372
+ const now = Math.floor(Date.now() / 1e3);
1373
+ this.sql`
1374
+ UPDATE cf_agents_workflows
1375
+ SET status = 'queued',
1376
+ created_at = ${now},
1377
+ updated_at = ${now},
1378
+ completed_at = NULL,
1379
+ error_name = NULL,
1380
+ error_message = NULL
1381
+ WHERE workflow_id = ${workflowId}
1382
+ `;
1383
+ } else {
1384
+ const status = await instance.status();
1385
+ this._updateWorkflowTracking(workflowId, status);
1386
+ }
1387
+ this.observability?.emit({
1388
+ displayMessage: `Workflow ${workflowId} restarted`,
1389
+ id: nanoid(),
1390
+ payload: {
1391
+ workflowId,
1392
+ workflowName: workflowInfo.workflowName
1393
+ },
1394
+ timestamp: Date.now(),
1395
+ type: "workflow:restarted"
1396
+ }, this.ctx);
1397
+ }
1398
+ /**
1399
+ * Find a workflow binding by its name.
1400
+ */
1401
+ _findWorkflowBindingByName(workflowName) {
1402
+ const binding = this.env[workflowName];
1403
+ if (binding && typeof binding === "object" && "create" in binding && "get" in binding) return binding;
1404
+ }
1405
+ /**
1406
+ * Get all workflow binding names from the environment.
1407
+ */
1408
+ _getWorkflowBindingNames() {
1409
+ const names = [];
1410
+ for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "create" in value && "get" in value) names.push(key);
1411
+ return names;
1412
+ }
1413
+ /**
1414
+ * Get the status of a workflow and update the tracking record.
1415
+ *
1416
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
1417
+ * @param workflowId - ID of the workflow instance
1418
+ * @returns The workflow status
1419
+ */
1420
+ async getWorkflowStatus(workflowName, workflowId) {
1421
+ const workflow = this._findWorkflowBindingByName(workflowName);
1422
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
1423
+ const status = await (await workflow.get(workflowId)).status();
1424
+ this._updateWorkflowTracking(workflowId, status);
1425
+ return status;
1426
+ }
1427
+ /**
1428
+ * Get a tracked workflow by ID.
1429
+ *
1430
+ * @param workflowId - Workflow instance ID
1431
+ * @returns Workflow info or undefined if not found
1432
+ */
1433
+ getWorkflow(workflowId) {
1434
+ const rows = this.sql`
1435
+ SELECT * FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
1436
+ `;
1437
+ if (!rows || rows.length === 0) return;
1438
+ return this._rowToWorkflowInfo(rows[0]);
1439
+ }
1440
+ /**
1441
+ * Query tracked workflows with cursor-based pagination.
1442
+ *
1443
+ * @param criteria - Query criteria including optional cursor for pagination
1444
+ * @returns WorkflowPage with workflows, total count, and next cursor
1445
+ *
1446
+ * @example
1447
+ * ```typescript
1448
+ * // First page
1449
+ * const page1 = this.getWorkflows({ status: 'running', limit: 20 });
1450
+ *
1451
+ * // Next page
1452
+ * if (page1.nextCursor) {
1453
+ * const page2 = this.getWorkflows({
1454
+ * status: 'running',
1455
+ * limit: 20,
1456
+ * cursor: page1.nextCursor
1457
+ * });
1458
+ * }
1459
+ * ```
1460
+ */
1461
+ getWorkflows(criteria = {}) {
1462
+ const limit = Math.min(criteria.limit ?? 50, 100);
1463
+ const isAsc = criteria.orderBy === "asc";
1464
+ const total = this._countWorkflows(criteria);
1465
+ let query = "SELECT * FROM cf_agents_workflows WHERE 1=1";
1466
+ const params = [];
1467
+ if (criteria.status) {
1468
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
1469
+ const placeholders = statuses.map(() => "?").join(", ");
1470
+ query += ` AND status IN (${placeholders})`;
1471
+ params.push(...statuses);
1472
+ }
1473
+ if (criteria.workflowName) {
1474
+ query += " AND workflow_name = ?";
1475
+ params.push(criteria.workflowName);
1476
+ }
1477
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
1478
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
1479
+ params.push(key, value);
1480
+ }
1481
+ if (criteria.cursor) {
1482
+ const cursor = this._decodeCursor(criteria.cursor);
1483
+ if (isAsc) query += " AND (created_at > ? OR (created_at = ? AND workflow_id > ?))";
1484
+ else query += " AND (created_at < ? OR (created_at = ? AND workflow_id < ?))";
1485
+ params.push(cursor.createdAt, cursor.createdAt, cursor.workflowId);
1486
+ }
1487
+ query += ` ORDER BY created_at ${isAsc ? "ASC" : "DESC"}, workflow_id ${isAsc ? "ASC" : "DESC"}`;
1488
+ query += " LIMIT ?";
1489
+ params.push(limit + 1);
1490
+ const rows = this.ctx.storage.sql.exec(query, ...params).toArray();
1491
+ const hasMore = rows.length > limit;
1492
+ const workflows = (hasMore ? rows.slice(0, limit) : rows).map((row) => this._rowToWorkflowInfo(row));
1493
+ return {
1494
+ workflows,
1495
+ total,
1496
+ nextCursor: hasMore && workflows.length > 0 ? this._encodeCursor(workflows[workflows.length - 1]) : null
1497
+ };
1498
+ }
1499
+ /**
1500
+ * Count workflows matching criteria (for pagination total).
1501
+ */
1502
+ _countWorkflows(criteria) {
1503
+ let query = "SELECT COUNT(*) as count FROM cf_agents_workflows WHERE 1=1";
1504
+ const params = [];
1505
+ if (criteria.status) {
1506
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
1507
+ const placeholders = statuses.map(() => "?").join(", ");
1508
+ query += ` AND status IN (${placeholders})`;
1509
+ params.push(...statuses);
1510
+ }
1511
+ if (criteria.workflowName) {
1512
+ query += " AND workflow_name = ?";
1513
+ params.push(criteria.workflowName);
1514
+ }
1515
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
1516
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
1517
+ params.push(key, value);
1518
+ }
1519
+ if (criteria.createdBefore) {
1520
+ query += " AND created_at < ?";
1521
+ params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
1522
+ }
1523
+ return this.ctx.storage.sql.exec(query, ...params).toArray()[0]?.count ?? 0;
1524
+ }
1525
+ /**
1526
+ * Encode a cursor from workflow info for pagination.
1527
+ * Stores createdAt as Unix timestamp in seconds (matching DB storage).
1528
+ */
1529
+ _encodeCursor(workflow) {
1530
+ return btoa(JSON.stringify({
1531
+ c: Math.floor(workflow.createdAt.getTime() / 1e3),
1532
+ i: workflow.workflowId
1533
+ }));
1534
+ }
1535
+ /**
1536
+ * Decode a pagination cursor.
1537
+ * Returns createdAt as Unix timestamp in seconds (matching DB storage).
1538
+ */
1539
+ _decodeCursor(cursor) {
1540
+ try {
1541
+ const data = JSON.parse(atob(cursor));
1542
+ if (typeof data.c !== "number" || typeof data.i !== "string") throw new Error("Invalid cursor structure");
1543
+ return {
1544
+ createdAt: data.c,
1545
+ workflowId: data.i
1546
+ };
1547
+ } catch {
1548
+ throw new Error("Invalid pagination cursor. The cursor may be malformed or corrupted.");
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Delete a workflow tracking record.
1553
+ *
1554
+ * @param workflowId - ID of the workflow to delete
1555
+ * @returns true if a record was deleted, false if not found
1556
+ */
1557
+ deleteWorkflow(workflowId) {
1558
+ const existing = this.sql`
1559
+ SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
1560
+ `;
1561
+ if (!existing[0] || existing[0].count === 0) return false;
1562
+ this.sql`DELETE FROM cf_agents_workflows WHERE workflow_id = ${workflowId}`;
1563
+ return true;
1564
+ }
1565
+ /**
1566
+ * Delete workflow tracking records matching criteria.
1567
+ * Useful for cleaning up old completed/errored workflows.
1568
+ *
1569
+ * @param criteria - Criteria for which workflows to delete
1570
+ * @returns Number of records matching criteria (expected deleted count)
1571
+ *
1572
+ * @example
1573
+ * ```typescript
1574
+ * // Delete all completed workflows created more than 7 days ago
1575
+ * const deleted = this.deleteWorkflows({
1576
+ * status: 'complete',
1577
+ * createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
1578
+ * });
1579
+ *
1580
+ * // Delete all errored and terminated workflows
1581
+ * const deleted = this.deleteWorkflows({
1582
+ * status: ['errored', 'terminated']
1583
+ * });
1584
+ * ```
1585
+ */
1586
+ deleteWorkflows(criteria = {}) {
1587
+ let query = "DELETE FROM cf_agents_workflows WHERE 1=1";
1588
+ const params = [];
1589
+ if (criteria.status) {
1590
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
1591
+ const placeholders = statuses.map(() => "?").join(", ");
1592
+ query += ` AND status IN (${placeholders})`;
1593
+ params.push(...statuses);
1594
+ }
1595
+ if (criteria.workflowName) {
1596
+ query += " AND workflow_name = ?";
1597
+ params.push(criteria.workflowName);
1598
+ }
1599
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
1600
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
1601
+ params.push(key, value);
1602
+ }
1603
+ if (criteria.createdBefore) {
1604
+ query += " AND created_at < ?";
1605
+ params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
1606
+ }
1607
+ return this.ctx.storage.sql.exec(query, ...params).rowsWritten;
1608
+ }
1609
+ /**
1610
+ * Migrate workflow tracking records from an old binding name to a new one.
1611
+ * Use this after renaming a workflow binding in wrangler.toml.
1612
+ *
1613
+ * @param oldName - Previous workflow binding name
1614
+ * @param newName - New workflow binding name
1615
+ * @returns Number of records migrated
1616
+ *
1617
+ * @example
1618
+ * ```typescript
1619
+ * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml
1620
+ * async onStart() {
1621
+ * const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');
1622
+ * }
1623
+ * ```
1624
+ */
1625
+ migrateWorkflowBinding(oldName, newName) {
1626
+ if (!this._findWorkflowBindingByName(newName)) throw new Error(`Workflow binding '${newName}' not found in environment`);
1627
+ const count = this.sql`
1628
+ SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_name = ${oldName}
1629
+ `[0]?.count ?? 0;
1630
+ if (count > 0) {
1631
+ this.sql`UPDATE cf_agents_workflows SET workflow_name = ${newName} WHERE workflow_name = ${oldName}`;
1632
+ console.log(`[Agent] Migrated ${count} workflow(s) from '${oldName}' to '${newName}'`);
1633
+ }
1634
+ return count;
1635
+ }
1636
+ /**
1637
+ * Update workflow tracking record from InstanceStatus
1638
+ */
1639
+ _updateWorkflowTracking(workflowId, status) {
1640
+ const statusName = status.status;
1641
+ const now = Math.floor(Date.now() / 1e3);
1642
+ const completedAt = [
1643
+ "complete",
1644
+ "errored",
1645
+ "terminated"
1646
+ ].includes(statusName) ? now : null;
1647
+ const errorName = status.error?.name ?? null;
1648
+ const errorMessage = status.error?.message ?? null;
1649
+ this.sql`
1650
+ UPDATE cf_agents_workflows
1651
+ SET status = ${statusName},
1652
+ error_name = ${errorName},
1653
+ error_message = ${errorMessage},
1654
+ updated_at = ${now},
1655
+ completed_at = ${completedAt}
1656
+ WHERE workflow_id = ${workflowId}
1657
+ `;
1658
+ }
1659
+ /**
1660
+ * Convert a database row to WorkflowInfo
1661
+ */
1662
+ _rowToWorkflowInfo(row) {
1663
+ return {
1664
+ id: row.id,
1665
+ workflowId: row.workflow_id,
1666
+ workflowName: row.workflow_name,
1667
+ status: row.status,
1668
+ metadata: row.metadata ? JSON.parse(row.metadata) : null,
1669
+ error: row.error_name ? {
1670
+ name: row.error_name,
1671
+ message: row.error_message ?? ""
1672
+ } : null,
1673
+ createdAt: /* @__PURE__ */ new Date(row.created_at * 1e3),
1674
+ updatedAt: /* @__PURE__ */ new Date(row.updated_at * 1e3),
1675
+ completedAt: row.completed_at ? /* @__PURE__ */ new Date(row.completed_at * 1e3) : null
1676
+ };
1677
+ }
1678
+ /**
1679
+ * Find the binding name for this Agent's namespace by matching class name.
1680
+ * Returns undefined if no match found - use options.agentBinding as fallback.
1681
+ */
1682
+ _findAgentBindingName() {
1683
+ const className = this._ParentClass.name;
1684
+ for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1685
+ if (key === className || camelCaseToKebabCase(key) === camelCaseToKebabCase(className)) return key;
1686
+ }
1687
+ }
1688
+ /**
1689
+ * Handle a callback from a workflow.
1690
+ * Called when the Agent receives a callback at /_workflow/callback.
1691
+ * Override this to handle all callback types in one place.
1692
+ *
1693
+ * @param callback - The callback payload
1694
+ */
1695
+ async onWorkflowCallback(callback) {
1696
+ const now = Math.floor(Date.now() / 1e3);
1697
+ switch (callback.type) {
1698
+ case "progress":
1699
+ this.sql`
1700
+ UPDATE cf_agents_workflows
1701
+ SET status = 'running', updated_at = ${now}
1702
+ WHERE workflow_id = ${callback.workflowId} AND status IN ('queued', 'waiting')
1703
+ `;
1704
+ await this.onWorkflowProgress(callback.workflowName, callback.workflowId, callback.progress);
1705
+ break;
1706
+ case "complete":
1707
+ this.sql`
1708
+ UPDATE cf_agents_workflows
1709
+ SET status = 'complete', updated_at = ${now}, completed_at = ${now}
1710
+ WHERE workflow_id = ${callback.workflowId}
1711
+ AND status NOT IN ('terminated', 'paused')
1712
+ `;
1713
+ await this.onWorkflowComplete(callback.workflowName, callback.workflowId, callback.result);
1714
+ break;
1715
+ case "error":
1716
+ this.sql`
1717
+ UPDATE cf_agents_workflows
1718
+ SET status = 'errored', updated_at = ${now}, completed_at = ${now},
1719
+ error_name = 'WorkflowError', error_message = ${callback.error}
1720
+ WHERE workflow_id = ${callback.workflowId}
1721
+ AND status NOT IN ('terminated', 'paused')
1722
+ `;
1723
+ await this.onWorkflowError(callback.workflowName, callback.workflowId, callback.error);
1724
+ break;
1725
+ case "event":
1726
+ await this.onWorkflowEvent(callback.workflowName, callback.workflowId, callback.event);
1727
+ break;
1728
+ }
1729
+ }
1730
+ /**
1731
+ * Called when a workflow reports progress.
1732
+ * Override to handle progress updates.
1733
+ *
1734
+ * @param workflowName - Workflow binding name
1735
+ * @param workflowId - ID of the workflow
1736
+ * @param progress - Typed progress data (default: DefaultProgress)
1737
+ */
1738
+ async onWorkflowProgress(_workflowName, _workflowId, _progress) {}
1739
+ /**
1740
+ * Called when a workflow completes successfully.
1741
+ * Override to handle completion.
1742
+ *
1743
+ * @param workflowName - Workflow binding name
1744
+ * @param workflowId - ID of the workflow
1745
+ * @param result - Optional result data
1746
+ */
1747
+ async onWorkflowComplete(_workflowName, _workflowId, _result) {}
1748
+ /**
1749
+ * Called when a workflow encounters an error.
1750
+ * Override to handle errors.
1751
+ *
1752
+ * @param workflowName - Workflow binding name
1753
+ * @param workflowId - ID of the workflow
1754
+ * @param error - Error message
1755
+ */
1756
+ async onWorkflowError(_workflowName, _workflowId, _error) {}
1757
+ /**
1758
+ * Called when a workflow sends a custom event.
1759
+ * Override to handle custom events.
1760
+ *
1761
+ * @param workflowName - Workflow binding name
1762
+ * @param workflowId - ID of the workflow
1763
+ * @param event - Custom event payload
1764
+ */
1765
+ async onWorkflowEvent(_workflowName, _workflowId, _event) {}
1766
+ /**
1767
+ * Handle a workflow callback via RPC.
1768
+ * @internal - Called by AgentWorkflow, do not call directly
1769
+ */
1770
+ async _workflow_handleCallback(callback) {
1771
+ await this.onWorkflowCallback(callback);
1772
+ }
1773
+ /**
1774
+ * Broadcast a message to all connected clients via RPC.
1775
+ * @internal - Called by AgentWorkflow, do not call directly
1776
+ */
1777
+ _workflow_broadcast(message) {
1778
+ this.broadcast(JSON.stringify(message));
1779
+ }
1780
+ /**
1781
+ * Update agent state via RPC.
1782
+ * @internal - Called by AgentWorkflow, do not call directly
1783
+ */
1784
+ _workflow_updateState(action, state) {
1785
+ if (action === "set") this.setState(state);
1786
+ else if (action === "merge") {
1787
+ const currentState = this.state ?? {};
1788
+ this.setState({
1789
+ ...currentState,
1790
+ ...state
1791
+ });
1792
+ } else if (action === "reset") this.setState(this.initialState);
1793
+ }
1794
+ /**
1795
+ * Connect to a new MCP Server
1796
+ *
1797
+ * @example
1798
+ * // Simple usage
1799
+ * await this.addMcpServer("github", "https://mcp.github.com");
1800
+ *
1801
+ * @example
1802
+ * // With options (preferred for custom headers, transport, etc.)
1803
+ * await this.addMcpServer("github", "https://mcp.github.com", {
1804
+ * transport: { headers: { "Authorization": "Bearer ..." } }
1805
+ * });
1806
+ *
1807
+ * @example
1808
+ * // Legacy 5-parameter signature (still supported)
1809
+ * await this.addMcpServer("github", url, callbackHost, agentsPrefix, options);
1810
+ *
1811
+ * @param serverName Name of the MCP server
1812
+ * @param url MCP Server URL
1813
+ * @param callbackHostOrOptions Options object, or callback host string (legacy)
1814
+ * @param agentsPrefix agents routing prefix if not using `agents` (legacy)
1815
+ * @param options MCP client and transport options (legacy)
1816
+ * @returns Server id and state - either "authenticating" with authUrl, or "ready"
1817
+ * @throws If connection or discovery fails
1818
+ */
1819
+ async addMcpServer(serverName, url, callbackHostOrOptions, agentsPrefix, options) {
1820
+ let resolvedCallbackHost;
1821
+ let resolvedAgentsPrefix;
1822
+ let resolvedOptions;
1823
+ if (typeof callbackHostOrOptions === "object" && callbackHostOrOptions !== null) {
1824
+ resolvedCallbackHost = callbackHostOrOptions.callbackHost;
1825
+ resolvedAgentsPrefix = callbackHostOrOptions.agentsPrefix ?? "agents";
1826
+ resolvedOptions = {
1827
+ client: callbackHostOrOptions.client,
1828
+ transport: callbackHostOrOptions.transport
1829
+ };
1830
+ } else {
1831
+ resolvedCallbackHost = callbackHostOrOptions;
1832
+ resolvedAgentsPrefix = agentsPrefix ?? "agents";
1833
+ resolvedOptions = options;
1834
+ }
1835
+ if (!resolvedCallbackHost) {
1836
+ const { request } = getCurrentAgent();
1837
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
1838
+ const requestUrl = new URL(request.url);
1839
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1840
+ }
1841
+ const callbackUrl = `${resolvedCallbackHost}/${resolvedAgentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1842
+ await this.mcp.ensureJsonSchema();
1843
+ const id = nanoid(8);
1844
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
1845
+ authProvider.serverId = id;
1846
+ const transportType = resolvedOptions?.transport?.type ?? "auto";
1847
+ let headerTransportOpts = {};
1848
+ if (resolvedOptions?.transport?.headers) headerTransportOpts = {
1849
+ eventSourceInit: { fetch: (url, init) => fetch(url, {
1850
+ ...init,
1851
+ headers: resolvedOptions?.transport?.headers
1852
+ }) },
1853
+ requestInit: { headers: resolvedOptions?.transport?.headers }
1854
+ };
1855
+ await this.mcp.registerServer(id, {
1856
+ url,
1857
+ name: serverName,
1858
+ callbackUrl,
1859
+ client: resolvedOptions?.client,
1860
+ transport: {
1861
+ ...headerTransportOpts,
1862
+ authProvider,
1863
+ type: transportType
1864
+ }
1865
+ });
1866
+ const result = await this.mcp.connectToServer(id);
1867
+ if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
1868
+ if (result.state === MCPConnectionState.AUTHENTICATING) return {
1869
+ id,
1870
+ state: result.state,
1871
+ authUrl: result.authUrl
1872
+ };
1873
+ const discoverResult = await this.mcp.discoverIfConnected(id);
1874
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
1875
+ return {
1876
+ id,
1877
+ state: MCPConnectionState.READY
1878
+ };
1879
+ }
1880
+ async removeMcpServer(id) {
1881
+ await this.mcp.removeServer(id);
1882
+ }
1883
+ getMcpServers() {
1884
+ const mcpState = {
1885
+ prompts: this.mcp.listPrompts(),
1886
+ resources: this.mcp.listResources(),
1887
+ servers: {},
1888
+ tools: this.mcp.listTools()
1889
+ };
1890
+ const servers = this.mcp.listServers();
1891
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
1892
+ const serverConn = this.mcp.mcpConnections[server.id];
1893
+ let defaultState = "not-connected";
1894
+ if (!serverConn && server.auth_url) defaultState = "authenticating";
1895
+ mcpState.servers[server.id] = {
1896
+ auth_url: server.auth_url,
1897
+ capabilities: serverConn?.serverCapabilities ?? null,
1898
+ instructions: serverConn?.instructions ?? null,
1899
+ name: server.name,
1900
+ server_url: server.server_url,
1901
+ state: serverConn?.connectionState ?? defaultState
1902
+ };
1903
+ }
1904
+ return mcpState;
1905
+ }
1906
+ broadcastMcpServers() {
1907
+ this.broadcast(JSON.stringify({
1908
+ mcp: this.getMcpServers(),
1909
+ type: MessageType.CF_AGENT_MCP_SERVERS
1910
+ }));
1911
+ }
1912
+ /**
1913
+ * Handle MCP OAuth callback request if it's an OAuth callback.
1914
+ *
1915
+ * This method encapsulates the entire OAuth callback flow:
1916
+ * 1. Checks if the request is an MCP OAuth callback
1917
+ * 2. Processes the OAuth code exchange
1918
+ * 3. Establishes the connection if successful
1919
+ * 4. Broadcasts MCP server state updates
1920
+ * 5. Returns the appropriate HTTP response
1921
+ *
1922
+ * @param request The incoming HTTP request
1923
+ * @returns Response if this was an OAuth callback, null otherwise
1924
+ */
1925
+ async handleMcpOAuthCallback(request) {
1926
+ if (!this.mcp.isCallbackRequest(request)) return null;
1927
+ const result = await this.mcp.handleCallbackRequest(request);
1928
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
1929
+ console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
1930
+ });
1931
+ this.broadcastMcpServers();
1932
+ return this.handleOAuthCallbackResponse(result, request);
1933
+ }
1934
+ /**
1935
+ * Handle OAuth callback response using MCPClientManager configuration
1936
+ * @param result OAuth callback result
1937
+ * @param request The original request (needed for base URL)
1938
+ * @returns Response for the OAuth callback
1939
+ */
1940
+ handleOAuthCallbackResponse(result, request) {
1941
+ const config = this.mcp.getOAuthCallbackConfig();
1942
+ if (config?.customHandler) return config.customHandler(result);
1943
+ const baseOrigin = new URL(request.url).origin;
1944
+ if (config?.successRedirect && result.authSuccess) try {
1945
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
1946
+ } catch (e) {
1947
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
1948
+ return Response.redirect(baseOrigin);
1949
+ }
1950
+ if (config?.errorRedirect && !result.authSuccess) try {
1951
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
1952
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
1953
+ } catch (e) {
1954
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
1955
+ return Response.redirect(baseOrigin);
1956
+ }
1957
+ return Response.redirect(baseOrigin);
1958
+ }
1959
+ };
1960
+ const wrappedClasses = /* @__PURE__ */ new Set();
1961
+ /**
1962
+ * Route a request to the appropriate Agent
1963
+ * @param request Request to route
1964
+ * @param env Environment containing Agent bindings
1965
+ * @param options Routing options
1966
+ * @returns Response from the Agent or undefined if no route matched
1967
+ */
1968
+ async function routeAgentRequest(request, env, options) {
1969
+ const corsHeaders = options?.cors === true ? {
1970
+ "Access-Control-Allow-Credentials": "true",
1971
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1972
+ "Access-Control-Allow-Origin": "*",
1973
+ "Access-Control-Max-Age": "86400"
1974
+ } : options?.cors;
1975
+ if (request.method === "OPTIONS") {
1976
+ if (corsHeaders) return new Response(null, { headers: corsHeaders });
1977
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
1978
+ }
1979
+ let response = await routePartykitRequest(request, env, {
1980
+ prefix: "agents",
1981
+ ...options
1982
+ });
1983
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1984
+ const newHeaders = new Headers(response.headers);
1985
+ for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
1986
+ response = new Response(response.body, {
1987
+ status: response.status,
1988
+ statusText: response.statusText,
1989
+ headers: newHeaders
1990
+ });
1991
+ }
1992
+ return response;
1993
+ }
1994
+ const agentMapCache = /* @__PURE__ */ new WeakMap();
1995
+ /**
1996
+ * Route an email to the appropriate Agent
1997
+ * @param email The email to route
1998
+ * @param env The environment containing the Agent bindings
1999
+ * @param options The options for routing the email
2000
+ * @returns A promise that resolves when the email has been routed
2001
+ */
2002
+ async function routeAgentEmail(email, env, options) {
2003
+ const routingInfo = await options.resolver(email, env);
2004
+ if (!routingInfo) {
2005
+ if (options.onNoRoute) await options.onNoRoute(email);
2006
+ else console.warn("No routing information found for email, dropping message");
2007
+ return;
2008
+ }
2009
+ if (!agentMapCache.has(env)) {
2010
+ const map = {};
2011
+ for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
2012
+ map[key] = value;
2013
+ map[camelCaseToKebabCase(key)] = value;
2014
+ }
2015
+ agentMapCache.set(env, map);
2016
+ }
2017
+ const agentMap = agentMapCache.get(env);
2018
+ const namespace = agentMap[routingInfo.agentName];
2019
+ if (!namespace) {
2020
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
2021
+ throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
2022
+ }
2023
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
2024
+ const serialisableEmail = {
2025
+ getRaw: async () => {
2026
+ const reader = email.raw.getReader();
2027
+ const chunks = [];
2028
+ let done = false;
2029
+ while (!done) {
2030
+ const { value, done: readerDone } = await reader.read();
2031
+ done = readerDone;
2032
+ if (value) chunks.push(value);
2033
+ }
2034
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
2035
+ const combined = new Uint8Array(totalLength);
2036
+ let offset = 0;
2037
+ for (const chunk of chunks) {
2038
+ combined.set(chunk, offset);
2039
+ offset += chunk.length;
2040
+ }
2041
+ return combined;
2042
+ },
2043
+ headers: email.headers,
2044
+ rawSize: email.rawSize,
2045
+ setReject: (reason) => {
2046
+ email.setReject(reason);
2047
+ },
2048
+ forward: (rcptTo, headers) => {
2049
+ return email.forward(rcptTo, headers);
2050
+ },
2051
+ reply: (replyOptions) => {
2052
+ return email.reply(new EmailMessage(replyOptions.from, replyOptions.to, replyOptions.raw));
2053
+ },
2054
+ from: email.from,
2055
+ to: email.to,
2056
+ _secureRouted: routingInfo._secureRouted
2057
+ };
2058
+ await agent._onEmail(serialisableEmail);
2059
+ }
2060
+ /**
2061
+ * Get or create an Agent by name
2062
+ * @template Env Environment type containing bindings
2063
+ * @template T Type of the Agent class
2064
+ * @param namespace Agent namespace
2065
+ * @param name Name of the Agent instance
2066
+ * @param options Options for Agent creation
2067
+ * @returns Promise resolving to an Agent instance stub
2068
+ */
2069
+ async function getAgentByName(namespace, name, options) {
2070
+ return getServerByName(namespace, name, options);
2071
+ }
2072
+ /**
2073
+ * A wrapper for streaming responses in callable methods
2074
+ */
2075
+ var StreamingResponse = class {
2076
+ constructor(connection, id) {
2077
+ this._closed = false;
2078
+ this._connection = connection;
2079
+ this._id = id;
2080
+ }
2081
+ /**
2082
+ * Whether the stream has been closed (via end() or error())
2083
+ */
2084
+ get isClosed() {
2085
+ return this._closed;
2086
+ }
2087
+ /**
2088
+ * Send a chunk of data to the client
2089
+ * @param chunk The data to send
2090
+ * @returns false if stream is already closed (no-op), true if sent
2091
+ */
2092
+ send(chunk) {
2093
+ if (this._closed) {
2094
+ console.warn("StreamingResponse.send() called after stream was closed - data not sent");
2095
+ return false;
2096
+ }
2097
+ const response = {
2098
+ done: false,
2099
+ id: this._id,
2100
+ result: chunk,
2101
+ success: true,
2102
+ type: MessageType.RPC
2103
+ };
2104
+ this._connection.send(JSON.stringify(response));
2105
+ return true;
2106
+ }
2107
+ /**
2108
+ * End the stream and send the final chunk (if any)
2109
+ * @param finalChunk Optional final chunk of data to send
2110
+ * @returns false if stream is already closed (no-op), true if sent
2111
+ */
2112
+ end(finalChunk) {
2113
+ if (this._closed) return false;
2114
+ this._closed = true;
2115
+ const response = {
2116
+ done: true,
2117
+ id: this._id,
2118
+ result: finalChunk,
2119
+ success: true,
2120
+ type: MessageType.RPC
2121
+ };
2122
+ this._connection.send(JSON.stringify(response));
2123
+ return true;
2124
+ }
2125
+ /**
2126
+ * Send an error to the client and close the stream
2127
+ * @param message Error message to send
2128
+ * @returns false if stream is already closed (no-op), true if sent
2129
+ */
2130
+ error(message) {
2131
+ if (this._closed) return false;
2132
+ this._closed = true;
2133
+ const response = {
2134
+ error: message,
2135
+ id: this._id,
2136
+ success: false,
2137
+ type: MessageType.RPC
2138
+ };
2139
+ this._connection.send(JSON.stringify(response));
2140
+ return true;
2141
+ }
2142
+ };
2143
+
2144
+ //#endregion
2145
+ export { callable as a, routeAgentEmail as c, genericObservability as d, StreamingResponse as i, routeAgentRequest as l, DEFAULT_AGENT_STATIC_OPTIONS as n, getAgentByName as o, SqlError as r, getCurrentAgent as s, Agent as t, unstable_callable as u };
2146
+ //# sourceMappingURL=src-BFP4sOQ4.js.map