agents 0.9.0 → 0.10.1

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 (54) hide show
  1. package/dist/chat/index.d.ts +151 -2
  2. package/dist/chat/index.js +210 -11
  3. package/dist/chat/index.js.map +1 -1
  4. package/dist/{client-BwgM3cRz.js → client-QBjFV5de.js} +161 -49
  5. package/dist/client-QBjFV5de.js.map +1 -0
  6. package/dist/client.d.ts +2 -2
  7. package/dist/{compaction-helpers-BFTBIzpK.js → compaction-helpers-BPE1_ziA.js} +1 -1
  8. package/dist/compaction-helpers-BPE1_ziA.js.map +1 -0
  9. package/dist/compaction-helpers-BdQbZiML.d.ts +441 -0
  10. package/dist/{do-oauth-client-provider-C2jurFjW.d.ts → do-oauth-client-provider-31gqR33H.d.ts} +1 -1
  11. package/dist/{email-DwPlM0bQ.d.ts → email-Cql45SKP.d.ts} +1 -1
  12. package/dist/email.d.ts +2 -2
  13. package/dist/experimental/memory/session/index.d.ts +82 -218
  14. package/dist/experimental/memory/session/index.js +493 -56
  15. package/dist/experimental/memory/session/index.js.map +1 -1
  16. package/dist/experimental/memory/utils/index.d.ts +3 -4
  17. package/dist/experimental/memory/utils/index.js +1 -1
  18. package/dist/experimental/memory/utils/index.js.map +1 -1
  19. package/dist/{index-BtHngIIG.d.ts → index-D2lfljd3.d.ts} +205 -75
  20. package/dist/{index-Ua2Nfvbm.d.ts → index-DDSX-g7W.d.ts} +11 -1
  21. package/dist/index.d.ts +30 -26
  22. package/dist/index.js +2 -3049
  23. package/dist/{internal_context-DT8RxmAN.d.ts → internal_context-DuQZFvWI.d.ts} +1 -1
  24. package/dist/internal_context.d.ts +1 -1
  25. package/dist/mcp/client.d.ts +2 -2
  26. package/dist/mcp/client.js +1 -1
  27. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  28. package/dist/mcp/index.d.ts +1 -1
  29. package/dist/mcp/index.js +3 -11
  30. package/dist/mcp/index.js.map +1 -1
  31. package/dist/observability/index.d.ts +1 -1
  32. package/dist/react.d.ts +3 -1
  33. package/dist/react.js +3 -0
  34. package/dist/react.js.map +1 -1
  35. package/dist/{retries-DXMQGhG3.d.ts → retries-B_CN5KM9.d.ts} +1 -1
  36. package/dist/retries.d.ts +1 -1
  37. package/dist/{serializable-8Jt1B04R.d.ts → serializable-DGdO8CDh.d.ts} +1 -1
  38. package/dist/serializable.d.ts +1 -1
  39. package/dist/src-B8NZxxsO.js +3217 -0
  40. package/dist/src-B8NZxxsO.js.map +1 -0
  41. package/dist/{types-C-m0II8i.d.ts → types-B9A8AU7B.d.ts} +1 -1
  42. package/dist/types.d.ts +1 -1
  43. package/dist/{workflow-types-CZNXKj_D.d.ts → workflow-types-XmOkuI7A.d.ts} +1 -1
  44. package/dist/workflow-types.d.ts +1 -1
  45. package/dist/workflows.d.ts +2 -2
  46. package/dist/workflows.js +1 -1
  47. package/package.json +12 -16
  48. package/dist/client-BwgM3cRz.js.map +0 -1
  49. package/dist/compaction-helpers-BFTBIzpK.js.map +0 -1
  50. package/dist/compaction-helpers-DkJreaDR.d.ts +0 -139
  51. package/dist/experimental/forever.d.ts +0 -64
  52. package/dist/experimental/forever.js +0 -338
  53. package/dist/experimental/forever.js.map +0 -1
  54. package/dist/index.js.map +0 -1
@@ -0,0 +1,3217 @@
1
+ import { MessageType } from "./types.js";
2
+ import { camelCaseToKebabCase } from "./utils.js";
3
+ import { signAgentHeaders } from "./email.js";
4
+ import { __DO_NOT_USE_WILL_BREAK__agentContext } from "./internal_context.js";
5
+ import { isErrorRetryable, tryN, validateRetryOptions } from "./retries.js";
6
+ import { o as RPC_DO_PREFIX, r as MCPConnectionState, s as DisposableStore, t as MCPClientManager } from "./client-QBjFV5de.js";
7
+ import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider.js";
8
+ import { genericObservability } from "./observability/index.js";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { parseCronExpression } from "cron-schedule";
11
+ import { nanoid } from "nanoid";
12
+ import { EmailMessage } from "cloudflare:email";
13
+ import { RpcTarget } from "cloudflare:workers";
14
+ import { Server, getServerByName, routePartykitRequest } from "partyserver";
15
+ //#region \0@oxc-project+runtime@0.122.0/helpers/checkPrivateRedeclaration.js
16
+ function _checkPrivateRedeclaration(e, t) {
17
+ if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
18
+ }
19
+ //#endregion
20
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldInitSpec.js
21
+ function _classPrivateFieldInitSpec(e, t, a) {
22
+ _checkPrivateRedeclaration(e, t), t.set(e, a);
23
+ }
24
+ //#endregion
25
+ //#region \0@oxc-project+runtime@0.122.0/helpers/assertClassBrand.js
26
+ function _assertClassBrand(e, t, n) {
27
+ if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
28
+ throw new TypeError("Private element is not present on this object");
29
+ }
30
+ //#endregion
31
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldSet2.js
32
+ function _classPrivateFieldSet2(s, a, r) {
33
+ return s.set(_assertClassBrand(s, a), r), r;
34
+ }
35
+ //#endregion
36
+ //#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldGet2.js
37
+ function _classPrivateFieldGet2(s, a) {
38
+ return s.get(_assertClassBrand(s, a));
39
+ }
40
+ //#endregion
41
+ //#region src/index.ts
42
+ let _Symbol$dispose;
43
+ /**
44
+ * Type guard for RPC request messages
45
+ */
46
+ function isRPCRequest(msg) {
47
+ 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);
48
+ }
49
+ /**
50
+ * Type guard for state update messages
51
+ */
52
+ function isStateUpdateMessage(msg) {
53
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
54
+ }
55
+ const callableMetadata = /* @__PURE__ */ new WeakMap();
56
+ /**
57
+ * Error class for SQL execution failures, containing the query that failed
58
+ */
59
+ var SqlError = class extends Error {
60
+ constructor(query, cause) {
61
+ const message = cause instanceof Error ? cause.message : String(cause);
62
+ super(`SQL query failed: ${message}`, { cause });
63
+ this.name = "SqlError";
64
+ this.query = query;
65
+ }
66
+ };
67
+ /**
68
+ * Decorator that marks a method as callable by clients
69
+ * @param metadata Optional metadata about the callable method
70
+ */
71
+ function callable(metadata = {}) {
72
+ return function callableDecorator(target, _context) {
73
+ if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
74
+ return target;
75
+ };
76
+ }
77
+ let didWarnAboutUnstableCallable = false;
78
+ /**
79
+ * Decorator that marks a method as callable by clients
80
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
81
+ * @param metadata Optional metadata about the callable method
82
+ */
83
+ const unstable_callable = (metadata = {}) => {
84
+ if (!didWarnAboutUnstableCallable) {
85
+ didWarnAboutUnstableCallable = true;
86
+ console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
87
+ }
88
+ return callable(metadata);
89
+ };
90
+ const _fiberALS = new AsyncLocalStorage();
91
+ function getNextCronTime(cron) {
92
+ return parseCronExpression(cron).getNextDate();
93
+ }
94
+ const DEFAULT_KEEP_ALIVE_INTERVAL_MS = 3e4;
95
+ /**
96
+ * Schema version for the Agent's internal SQLite tables.
97
+ * Bump this when adding new tables, columns, or migrations.
98
+ * The constructor stores this as a row in cf_agents_state and checks it
99
+ * on wake to skip DDL on established DOs.
100
+ */
101
+ const CURRENT_SCHEMA_VERSION = 3;
102
+ const SCHEMA_VERSION_ROW_ID = "cf_schema_version";
103
+ const STATE_ROW_ID = "cf_state_row_id";
104
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
105
+ const DEFAULT_STATE = {};
106
+ /**
107
+ * Internal key used to store the readonly flag in connection state.
108
+ * Prefixed with _cf_ to avoid collision with user state keys.
109
+ */
110
+ const CF_READONLY_KEY = "_cf_readonly";
111
+ /**
112
+ * Internal key used to store the no-protocol flag in connection state.
113
+ * When set, protocol messages (identity, state sync, MCP servers) are not
114
+ * sent to this connection — neither on connect nor via broadcasts.
115
+ */
116
+ const CF_NO_PROTOCOL_KEY = "_cf_no_protocol";
117
+ /**
118
+ * The set of all internal keys stored in connection state that must be
119
+ * hidden from user code and preserved across setState calls.
120
+ */
121
+ const CF_INTERNAL_KEYS = new Set([
122
+ CF_READONLY_KEY,
123
+ CF_NO_PROTOCOL_KEY,
124
+ "_cf_voiceInCall"
125
+ ]);
126
+ /** Check if a raw connection state object contains any internal keys. */
127
+ function rawHasInternalKeys(raw) {
128
+ for (const key of Object.keys(raw)) if (CF_INTERNAL_KEYS.has(key)) return true;
129
+ return false;
130
+ }
131
+ /** Return a copy of `raw` with all internal keys removed, or null if no user keys remain. */
132
+ function stripInternalKeys(raw) {
133
+ const result = {};
134
+ let hasUserKeys = false;
135
+ for (const key of Object.keys(raw)) if (!CF_INTERNAL_KEYS.has(key)) {
136
+ result[key] = raw[key];
137
+ hasUserKeys = true;
138
+ }
139
+ return hasUserKeys ? result : null;
140
+ }
141
+ /** Return a copy containing only the internal keys present in `raw`. */
142
+ function extractInternalFlags(raw) {
143
+ const result = {};
144
+ for (const key of Object.keys(raw)) if (CF_INTERNAL_KEYS.has(key)) result[key] = raw[key];
145
+ return result;
146
+ }
147
+ /** Max length for error strings broadcast to clients. */
148
+ const MAX_ERROR_STRING_LENGTH = 500;
149
+ /**
150
+ * Sanitize an error string before broadcasting to clients.
151
+ * MCP error strings may contain untrusted content from external OAuth
152
+ * providers — truncate and strip control characters to limit XSS risk.
153
+ */
154
+ const CONTROL_CHAR_RE = /* @__PURE__ */ new RegExp("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]", "g");
155
+ function sanitizeErrorString(error) {
156
+ if (error === null) return null;
157
+ let sanitized = error.replace(CONTROL_CHAR_RE, "");
158
+ if (sanitized.length > MAX_ERROR_STRING_LENGTH) sanitized = sanitized.substring(0, MAX_ERROR_STRING_LENGTH) + "...";
159
+ return sanitized;
160
+ }
161
+ /**
162
+ * Tracks which agent constructors have already emitted the onStateUpdate
163
+ * deprecation warning, so it fires at most once per class.
164
+ */
165
+ const _onStateUpdateWarnedClasses = /* @__PURE__ */ new WeakSet();
166
+ /**
167
+ * Tracks which agent constructors have already emitted the
168
+ * sendIdentityOnConnect deprecation warning, so it fires at most once per class.
169
+ */
170
+ const _sendIdentityWarnedClasses = /* @__PURE__ */ new WeakSet();
171
+ /**
172
+ * Default options for Agent configuration.
173
+ * Child classes can override specific options without spreading.
174
+ */
175
+ const DEFAULT_AGENT_STATIC_OPTIONS = {
176
+ hibernate: true,
177
+ sendIdentityOnConnect: true,
178
+ hungScheduleTimeoutSeconds: 30,
179
+ keepAliveIntervalMs: DEFAULT_KEEP_ALIVE_INTERVAL_MS,
180
+ retry: {
181
+ maxAttempts: 3,
182
+ baseDelayMs: 100,
183
+ maxDelayMs: 3e3
184
+ }
185
+ };
186
+ /**
187
+ * Parse the raw `retry_options` TEXT column from a SQLite row into a
188
+ * typed `RetryOptions` object, or `undefined` if not set.
189
+ */
190
+ function parseRetryOptions(row) {
191
+ const raw = row.retry_options;
192
+ if (typeof raw !== "string") return void 0;
193
+ return JSON.parse(raw);
194
+ }
195
+ /**
196
+ * Resolve per-task retry options against class-level defaults and call
197
+ * `tryN`. This is the shared retry-execution path used by both queue
198
+ * flush and schedule alarm handlers.
199
+ */
200
+ function resolveRetryConfig(taskRetry, defaults) {
201
+ return {
202
+ maxAttempts: taskRetry?.maxAttempts ?? defaults.maxAttempts,
203
+ baseDelayMs: taskRetry?.baseDelayMs ?? defaults.baseDelayMs,
204
+ maxDelayMs: taskRetry?.maxDelayMs ?? defaults.maxDelayMs
205
+ };
206
+ }
207
+ function getCurrentAgent() {
208
+ const store = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
209
+ if (!store) return {
210
+ agent: void 0,
211
+ connection: void 0,
212
+ request: void 0,
213
+ email: void 0
214
+ };
215
+ return store;
216
+ }
217
+ /**
218
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
219
+ * @param agent The agent instance
220
+ * @param method The method to wrap
221
+ * @returns A wrapped method that runs within the agent context
222
+ */
223
+ function withAgentContext(method) {
224
+ return function(...args) {
225
+ const { connection, request, email, agent } = getCurrentAgent();
226
+ if (agent === this) return method.apply(this, args);
227
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
228
+ agent: this,
229
+ connection,
230
+ request,
231
+ email
232
+ }, () => {
233
+ return method.apply(this, args);
234
+ });
235
+ };
236
+ }
237
+ /**
238
+ * Base class for creating Agent implementations
239
+ * @template Env Environment type containing bindings
240
+ * @template State State type to store within the Agent
241
+ */
242
+ var Agent = class Agent extends Server {
243
+ /**
244
+ * Stable key for Workers AI session affinity (prefix-cache optimization).
245
+ *
246
+ * Uses the Durable Object ID, which is globally unique across all agent
247
+ * classes and stable for the lifetime of the instance. Pass this value as
248
+ * the `sessionAffinity` option when creating a Workers AI model so that
249
+ * requests from the same agent instance are routed to the same backend
250
+ * replica, improving KV-prefix-cache hit rates across conversation turns.
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * const workersai = createWorkersAI({ binding: this.env.AI });
255
+ * const model = workersai("@cf/meta/llama-3.3-70b-instruct-fp8-fast", {
256
+ * sessionAffinity: this.sessionAffinity,
257
+ * });
258
+ * ```
259
+ */
260
+ get sessionAffinity() {
261
+ return this.ctx.id.toString();
262
+ }
263
+ /**
264
+ * Current state of the Agent
265
+ */
266
+ get state() {
267
+ if (this._state !== DEFAULT_STATE) return this._state;
268
+ const result = this.sql`
269
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
270
+ `;
271
+ if (result.length > 0) {
272
+ const state = result[0].state;
273
+ try {
274
+ this._state = JSON.parse(state);
275
+ } catch (e) {
276
+ console.error("Failed to parse stored state, falling back to initialState:", e);
277
+ if (this.initialState !== DEFAULT_STATE) {
278
+ this._state = this.initialState;
279
+ this._setStateInternal(this.initialState);
280
+ } else {
281
+ this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_ROW_ID}`;
282
+ return;
283
+ }
284
+ }
285
+ return this._state;
286
+ }
287
+ if (this.initialState === DEFAULT_STATE) return;
288
+ this._setStateInternal(this.initialState);
289
+ return this.initialState;
290
+ }
291
+ get _resolvedOptions() {
292
+ if (this._cachedOptions) return this._cachedOptions;
293
+ const ctor = this.constructor;
294
+ const userRetry = ctor.options?.retry;
295
+ this._cachedOptions = {
296
+ hibernate: ctor.options?.hibernate ?? DEFAULT_AGENT_STATIC_OPTIONS.hibernate,
297
+ sendIdentityOnConnect: ctor.options?.sendIdentityOnConnect ?? DEFAULT_AGENT_STATIC_OPTIONS.sendIdentityOnConnect,
298
+ hungScheduleTimeoutSeconds: ctor.options?.hungScheduleTimeoutSeconds ?? DEFAULT_AGENT_STATIC_OPTIONS.hungScheduleTimeoutSeconds,
299
+ keepAliveIntervalMs: ctor.options?.keepAliveIntervalMs ?? DEFAULT_AGENT_STATIC_OPTIONS.keepAliveIntervalMs,
300
+ retry: {
301
+ maxAttempts: userRetry?.maxAttempts ?? DEFAULT_AGENT_STATIC_OPTIONS.retry.maxAttempts,
302
+ baseDelayMs: userRetry?.baseDelayMs ?? DEFAULT_AGENT_STATIC_OPTIONS.retry.baseDelayMs,
303
+ maxDelayMs: userRetry?.maxDelayMs ?? DEFAULT_AGENT_STATIC_OPTIONS.retry.maxDelayMs
304
+ }
305
+ };
306
+ return this._cachedOptions;
307
+ }
308
+ /**
309
+ * Emit an observability event with auto-generated timestamp.
310
+ * @internal
311
+ */
312
+ _emit(type, payload = {}) {
313
+ this.observability?.emit({
314
+ type,
315
+ agent: this._ParentClass.name,
316
+ name: this.name,
317
+ payload,
318
+ timestamp: Date.now()
319
+ });
320
+ }
321
+ /**
322
+ * Execute SQL queries against the Agent's database
323
+ * @template T Type of the returned rows
324
+ * @param strings SQL query template strings
325
+ * @param values Values to be inserted into the query
326
+ * @returns Array of query results
327
+ */
328
+ sql(strings, ...values) {
329
+ let query = "";
330
+ try {
331
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
332
+ return [...this.ctx.storage.sql.exec(query, ...values)];
333
+ } catch (e) {
334
+ throw new SqlError(query, e);
335
+ }
336
+ }
337
+ /**
338
+ * Create all internal tables and run migrations if needed.
339
+ * Called by the constructor on every wake. Idempotent — skips DDL when
340
+ * the stored schema version matches CURRENT_SCHEMA_VERSION.
341
+ *
342
+ * Protected so that test agents can re-run the real migration path
343
+ * after manipulating DB state (since ctx.abort() is unavailable in
344
+ * local dev and the constructor only runs once per DO instance).
345
+ */
346
+ _ensureSchema() {
347
+ this.sql`
348
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
349
+ id TEXT PRIMARY KEY NOT NULL,
350
+ state TEXT
351
+ )
352
+ `;
353
+ const versionRow = this.sql`
354
+ SELECT state FROM cf_agents_state WHERE id = ${SCHEMA_VERSION_ROW_ID}
355
+ `;
356
+ const schemaVersion = versionRow.length > 0 ? Number(versionRow[0].state) : 0;
357
+ if (schemaVersion < CURRENT_SCHEMA_VERSION) {
358
+ this.sql`
359
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
360
+ id TEXT PRIMARY KEY NOT NULL,
361
+ name TEXT NOT NULL,
362
+ server_url TEXT NOT NULL,
363
+ callback_url TEXT NOT NULL,
364
+ client_id TEXT,
365
+ auth_url TEXT,
366
+ server_options TEXT
367
+ )
368
+ `;
369
+ this.sql`
370
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
371
+ id TEXT PRIMARY KEY NOT NULL,
372
+ payload TEXT,
373
+ callback TEXT,
374
+ created_at INTEGER DEFAULT (unixepoch())
375
+ )
376
+ `;
377
+ this.sql`
378
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
379
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
380
+ callback TEXT,
381
+ payload TEXT,
382
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron', 'interval')),
383
+ time INTEGER,
384
+ delayInSeconds INTEGER,
385
+ cron TEXT,
386
+ intervalSeconds INTEGER,
387
+ running INTEGER DEFAULT 0,
388
+ created_at INTEGER DEFAULT (unixepoch()),
389
+ execution_started_at INTEGER,
390
+ retry_options TEXT
391
+ )
392
+ `;
393
+ const addColumnIfNotExists = (sql) => {
394
+ try {
395
+ this.ctx.storage.sql.exec(sql);
396
+ } catch (e) {
397
+ if (!(e instanceof Error ? e.message : String(e)).toLowerCase().includes("duplicate column")) throw e;
398
+ }
399
+ };
400
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN intervalSeconds INTEGER");
401
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN running INTEGER DEFAULT 0");
402
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER");
403
+ addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN retry_options TEXT");
404
+ addColumnIfNotExists("ALTER TABLE cf_agents_queues ADD COLUMN retry_options TEXT");
405
+ {
406
+ const rows = this.ctx.storage.sql.exec("SELECT sql FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'").toArray();
407
+ if (rows.length > 0) {
408
+ if (!String(rows[0].sql).includes("'interval'")) {
409
+ this.ctx.storage.sql.exec("DROP TABLE IF EXISTS cf_agents_schedules_new");
410
+ this.ctx.storage.sql.exec(`
411
+ CREATE TABLE cf_agents_schedules_new (
412
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
413
+ callback TEXT,
414
+ payload TEXT,
415
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron', 'interval')),
416
+ time INTEGER,
417
+ delayInSeconds INTEGER,
418
+ cron TEXT,
419
+ intervalSeconds INTEGER,
420
+ running INTEGER DEFAULT 0,
421
+ created_at INTEGER DEFAULT (unixepoch()),
422
+ execution_started_at INTEGER,
423
+ retry_options TEXT
424
+ )
425
+ `);
426
+ this.ctx.storage.sql.exec(`
427
+ INSERT INTO cf_agents_schedules_new
428
+ (id, callback, payload, type, time, delayInSeconds, cron,
429
+ intervalSeconds, running, created_at, execution_started_at, retry_options)
430
+ SELECT id, callback, payload, type, time, delayInSeconds, cron,
431
+ intervalSeconds, running, created_at, execution_started_at, retry_options
432
+ FROM cf_agents_schedules
433
+ `);
434
+ this.ctx.storage.sql.exec("DROP TABLE cf_agents_schedules");
435
+ this.ctx.storage.sql.exec("ALTER TABLE cf_agents_schedules_new RENAME TO cf_agents_schedules");
436
+ }
437
+ }
438
+ }
439
+ this.sql`
440
+ CREATE TABLE IF NOT EXISTS cf_agents_workflows (
441
+ id TEXT PRIMARY KEY NOT NULL,
442
+ workflow_id TEXT NOT NULL UNIQUE,
443
+ workflow_name TEXT NOT NULL,
444
+ status TEXT NOT NULL CHECK(status IN (
445
+ 'queued', 'running', 'paused', 'errored',
446
+ 'terminated', 'complete', 'waiting',
447
+ 'waitingForPause', 'unknown'
448
+ )),
449
+ metadata TEXT,
450
+ error_name TEXT,
451
+ error_message TEXT,
452
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
453
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
454
+ completed_at INTEGER
455
+ )
456
+ `;
457
+ this.sql`
458
+ CREATE INDEX IF NOT EXISTS idx_workflows_status ON cf_agents_workflows(status)
459
+ `;
460
+ this.sql`
461
+ CREATE INDEX IF NOT EXISTS idx_workflows_name ON cf_agents_workflows(workflow_name)
462
+ `;
463
+ this.ctx.storage.sql.exec("DELETE FROM cf_agents_state WHERE id = ?", STATE_WAS_CHANGED);
464
+ if (schemaVersion < 2) this.ctx.storage.sql.exec("DELETE FROM cf_agents_schedules WHERE callback = '_cf_keepAliveHeartbeat'");
465
+ this.sql`
466
+ CREATE TABLE IF NOT EXISTS cf_agents_runs (
467
+ id TEXT PRIMARY KEY NOT NULL,
468
+ name TEXT NOT NULL,
469
+ snapshot TEXT,
470
+ created_at INTEGER NOT NULL
471
+ )
472
+ `;
473
+ this.sql`
474
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
475
+ VALUES (${SCHEMA_VERSION_ROW_ID}, ${String(CURRENT_SCHEMA_VERSION)})
476
+ `;
477
+ }
478
+ }
479
+ constructor(ctx, env) {
480
+ super(ctx, env);
481
+ this._state = DEFAULT_STATE;
482
+ this._disposables = new DisposableStore();
483
+ this._destroyed = false;
484
+ this._rawStateAccessors = /* @__PURE__ */ new WeakMap();
485
+ this._persistenceHookMode = "none";
486
+ this._isFacet = false;
487
+ this._insideOnStart = false;
488
+ this._warnedScheduleInOnStart = /* @__PURE__ */ new Set();
489
+ this._keepAliveRefs = 0;
490
+ this._runFiberActiveFibers = /* @__PURE__ */ new Set();
491
+ this._runFiberRecoveryInProgress = false;
492
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
493
+ this.initialState = DEFAULT_STATE;
494
+ this.observability = genericObservability;
495
+ this._flushingQueue = false;
496
+ if (!wrappedClasses.has(this.constructor)) {
497
+ this._autoWrapCustomMethods();
498
+ wrappedClasses.add(this.constructor);
499
+ }
500
+ this._ensureSchema();
501
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", {
502
+ storage: this.ctx.storage,
503
+ createAuthProvider: (callbackUrl) => this.createMcpOAuthProvider(callbackUrl)
504
+ });
505
+ this._disposables.add(this.mcp.onServerStateChanged(async () => {
506
+ this.broadcastMcpServers();
507
+ }));
508
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
509
+ this.observability?.emit({
510
+ ...event,
511
+ agent: this._ParentClass.name,
512
+ name: this.name
513
+ });
514
+ }));
515
+ {
516
+ const proto = Object.getPrototypeOf(this);
517
+ const hasOwnNew = Object.prototype.hasOwnProperty.call(proto, "onStateChanged");
518
+ const hasOwnOld = Object.prototype.hasOwnProperty.call(proto, "onStateUpdate");
519
+ if (hasOwnNew && hasOwnOld) throw new Error("[Agent] Cannot override both onStateChanged and onStateUpdate. Remove onStateUpdate — it has been renamed to onStateChanged.");
520
+ if (hasOwnOld) {
521
+ const ctor = this.constructor;
522
+ if (!_onStateUpdateWarnedClasses.has(ctor)) {
523
+ _onStateUpdateWarnedClasses.add(ctor);
524
+ console.warn(`[Agent] onStateUpdate is deprecated. Rename to onStateChanged — the behavior is identical.`);
525
+ }
526
+ }
527
+ const base = Agent.prototype;
528
+ if (proto.onStateChanged !== base.onStateChanged) this._persistenceHookMode = "new";
529
+ else if (proto.onStateUpdate !== base.onStateUpdate) this._persistenceHookMode = "old";
530
+ }
531
+ const _onRequest = this.onRequest.bind(this);
532
+ this.onRequest = (request) => {
533
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
534
+ agent: this,
535
+ connection: void 0,
536
+ request,
537
+ email: void 0
538
+ }, async () => {
539
+ const oauthResponse = await this.handleMcpOAuthCallback(request);
540
+ if (oauthResponse) return oauthResponse;
541
+ return this._tryCatch(() => _onRequest(request));
542
+ });
543
+ };
544
+ const _onMessage = this.onMessage.bind(this);
545
+ this.onMessage = async (connection, message) => {
546
+ this._ensureConnectionWrapped(connection);
547
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
548
+ agent: this,
549
+ connection,
550
+ request: void 0,
551
+ email: void 0
552
+ }, async () => {
553
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
554
+ let parsed;
555
+ try {
556
+ parsed = JSON.parse(message);
557
+ } catch (_e) {
558
+ return this._tryCatch(() => _onMessage(connection, message));
559
+ }
560
+ if (isStateUpdateMessage(parsed)) {
561
+ if (this.isConnectionReadonly(connection)) {
562
+ connection.send(JSON.stringify({
563
+ type: MessageType.CF_AGENT_STATE_ERROR,
564
+ error: "Connection is readonly"
565
+ }));
566
+ return;
567
+ }
568
+ try {
569
+ this._setStateInternal(parsed.state, connection);
570
+ } catch (e) {
571
+ console.error("[Agent] State update rejected:", e);
572
+ connection.send(JSON.stringify({
573
+ type: MessageType.CF_AGENT_STATE_ERROR,
574
+ error: "State update rejected"
575
+ }));
576
+ }
577
+ return;
578
+ }
579
+ if (isRPCRequest(parsed)) {
580
+ try {
581
+ const { id, method, args } = parsed;
582
+ const methodFn = this[method];
583
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
584
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
585
+ const metadata = callableMetadata.get(methodFn);
586
+ if (metadata?.streaming) {
587
+ const stream = new StreamingResponse(connection, id);
588
+ this._emit("rpc", {
589
+ method,
590
+ streaming: true
591
+ });
592
+ try {
593
+ await methodFn.apply(this, [stream, ...args]);
594
+ } catch (err) {
595
+ console.error(`Error in streaming method "${method}":`, err);
596
+ this._emit("rpc:error", {
597
+ method,
598
+ error: err instanceof Error ? err.message : String(err)
599
+ });
600
+ if (!stream.isClosed) stream.error(err instanceof Error ? err.message : String(err));
601
+ }
602
+ return;
603
+ }
604
+ const result = await methodFn.apply(this, args);
605
+ this._emit("rpc", {
606
+ method,
607
+ streaming: metadata?.streaming
608
+ });
609
+ const response = {
610
+ done: true,
611
+ id,
612
+ result,
613
+ success: true,
614
+ type: MessageType.RPC
615
+ };
616
+ connection.send(JSON.stringify(response));
617
+ } catch (e) {
618
+ const response = {
619
+ error: e instanceof Error ? e.message : "Unknown error occurred",
620
+ id: parsed.id,
621
+ success: false,
622
+ type: MessageType.RPC
623
+ };
624
+ connection.send(JSON.stringify(response));
625
+ console.error("RPC error:", e);
626
+ this._emit("rpc:error", {
627
+ method: parsed.method,
628
+ error: e instanceof Error ? e.message : String(e)
629
+ });
630
+ }
631
+ return;
632
+ }
633
+ return this._tryCatch(() => _onMessage(connection, message));
634
+ });
635
+ };
636
+ const _onConnect = this.onConnect.bind(this);
637
+ this.onConnect = (connection, ctx) => {
638
+ this._ensureConnectionWrapped(connection);
639
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
640
+ agent: this,
641
+ connection,
642
+ request: ctx.request,
643
+ email: void 0
644
+ }, async () => {
645
+ if (this.shouldConnectionBeReadonly(connection, ctx)) this.setConnectionReadonly(connection, true);
646
+ if (this.shouldSendProtocolMessages(connection, ctx)) {
647
+ if (this._resolvedOptions.sendIdentityOnConnect) {
648
+ const ctor = this.constructor;
649
+ if (ctor.options?.sendIdentityOnConnect === void 0 && !_sendIdentityWarnedClasses.has(ctor)) {
650
+ if (!new URL(ctx.request.url).pathname.includes(this.name)) {
651
+ _sendIdentityWarnedClasses.add(ctor);
652
+ console.warn(`[Agent] ${ctor.name}: sending instance name "${this.name}" to clients via sendIdentityOnConnect (the name is not visible in the URL with custom routing). If this name is sensitive, add \`static options = { sendIdentityOnConnect: false }\` to opt out. Set it to true to silence this message.`);
653
+ }
654
+ }
655
+ connection.send(JSON.stringify({
656
+ name: this.name,
657
+ agent: camelCaseToKebabCase(this._ParentClass.name),
658
+ type: MessageType.CF_AGENT_IDENTITY
659
+ }));
660
+ }
661
+ if (this.state) connection.send(JSON.stringify({
662
+ state: this.state,
663
+ type: MessageType.CF_AGENT_STATE
664
+ }));
665
+ connection.send(JSON.stringify({
666
+ mcp: this.getMcpServers(),
667
+ type: MessageType.CF_AGENT_MCP_SERVERS
668
+ }));
669
+ } else this._setConnectionNoProtocol(connection);
670
+ this._emit("connect", { connectionId: connection.id });
671
+ return this._tryCatch(() => _onConnect(connection, ctx));
672
+ });
673
+ };
674
+ const _onClose = this.onClose.bind(this);
675
+ this.onClose = (connection, code, reason, wasClean) => {
676
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
677
+ agent: this,
678
+ connection,
679
+ request: void 0,
680
+ email: void 0
681
+ }, () => {
682
+ this._emit("disconnect", {
683
+ connectionId: connection.id,
684
+ code,
685
+ reason
686
+ });
687
+ return _onClose(connection, code, reason, wasClean);
688
+ });
689
+ };
690
+ const _onStart = this.onStart.bind(this);
691
+ this.onStart = async (props) => {
692
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
693
+ agent: this,
694
+ connection: void 0,
695
+ request: void 0,
696
+ email: void 0
697
+ }, async () => {
698
+ if (await this.ctx.storage.get("cf_agents_is_facet")) this._isFacet = true;
699
+ await this._tryCatch(async () => {
700
+ await this.mcp.restoreConnectionsFromStorage(this.name);
701
+ await this._restoreRpcMcpServers();
702
+ this.broadcastMcpServers();
703
+ this._checkOrphanedWorkflows();
704
+ await this._checkRunFibers();
705
+ this._insideOnStart = true;
706
+ this._warnedScheduleInOnStart.clear();
707
+ try {
708
+ return await _onStart(props);
709
+ } finally {
710
+ this._insideOnStart = false;
711
+ }
712
+ });
713
+ });
714
+ };
715
+ }
716
+ /**
717
+ * Check for workflows referencing unknown bindings and warn with migration suggestion.
718
+ */
719
+ _checkOrphanedWorkflows() {
720
+ const orphaned = this.sql`
721
+ SELECT
722
+ workflow_name,
723
+ COUNT(*) as total,
724
+ SUM(CASE WHEN status NOT IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as active,
725
+ SUM(CASE WHEN status IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as completed
726
+ FROM cf_agents_workflows
727
+ GROUP BY workflow_name
728
+ `.filter((row) => !this._findWorkflowBindingByName(row.workflow_name));
729
+ if (orphaned.length > 0) {
730
+ const currentBindings = this._getWorkflowBindingNames();
731
+ for (const { workflow_name: oldName, total, active, completed } of orphaned) {
732
+ const suggestion = currentBindings.length === 1 ? `this.migrateWorkflowBinding('${oldName}', '${currentBindings[0]}')` : `this.migrateWorkflowBinding('${oldName}', '<NEW_BINDING_NAME>')`;
733
+ const breakdown = active > 0 && completed > 0 ? ` (${active} active, ${completed} completed)` : active > 0 ? ` (${active} active)` : ` (${completed} completed)`;
734
+ console.warn(`[Agent] Found ${total} workflow(s) referencing unknown binding '${oldName}'${breakdown}. If you renamed the binding, call: ${suggestion}`);
735
+ }
736
+ }
737
+ }
738
+ /**
739
+ * Broadcast a protocol message only to connections that have protocol
740
+ * messages enabled. Connections where shouldSendProtocolMessages returned
741
+ * false are excluded automatically.
742
+ * @param msg The JSON-encoded protocol message
743
+ * @param excludeIds Additional connection IDs to exclude (e.g. the source)
744
+ */
745
+ _broadcastProtocol(msg, excludeIds = []) {
746
+ const exclude = [...excludeIds];
747
+ for (const conn of this.getConnections()) if (!this.isConnectionProtocolEnabled(conn)) exclude.push(conn.id);
748
+ this.broadcast(msg, exclude);
749
+ }
750
+ _setStateInternal(nextState, source = "server") {
751
+ this.validateStateChange(nextState, source);
752
+ this._state = nextState;
753
+ this.sql`
754
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
755
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(nextState)})
756
+ `;
757
+ this._broadcastProtocol(JSON.stringify({
758
+ state: nextState,
759
+ type: MessageType.CF_AGENT_STATE
760
+ }), source !== "server" ? [source.id] : []);
761
+ const { connection, request, email } = __DO_NOT_USE_WILL_BREAK__agentContext.getStore() || {};
762
+ this.ctx.waitUntil((async () => {
763
+ try {
764
+ await __DO_NOT_USE_WILL_BREAK__agentContext.run({
765
+ agent: this,
766
+ connection,
767
+ request,
768
+ email
769
+ }, async () => {
770
+ this._emit("state:update");
771
+ await this._callStatePersistenceHook(nextState, source);
772
+ });
773
+ } catch (e) {
774
+ try {
775
+ await this.onError(e);
776
+ } catch {}
777
+ }
778
+ })());
779
+ }
780
+ /**
781
+ * Update the Agent's state
782
+ * @param state New state to set
783
+ * @throws Error if called from a readonly connection context
784
+ */
785
+ setState(state) {
786
+ const store = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
787
+ if (store?.connection && this.isConnectionReadonly(store.connection)) throw new Error("Connection is readonly");
788
+ this._setStateInternal(state, "server");
789
+ }
790
+ /**
791
+ * Wraps connection.state and connection.setState so that internal
792
+ * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code
793
+ * and cannot be accidentally overwritten.
794
+ *
795
+ * Idempotent — safe to call multiple times on the same connection.
796
+ * After hibernation, the _rawStateAccessors WeakMap is empty but the
797
+ * connection's state getter still reads from the persisted WebSocket
798
+ * attachment. Calling this method re-captures the raw getter so that
799
+ * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled)
800
+ * work correctly post-hibernation.
801
+ */
802
+ _ensureConnectionWrapped(connection) {
803
+ if (this._rawStateAccessors.has(connection)) return;
804
+ const descriptor = Object.getOwnPropertyDescriptor(connection, "state");
805
+ let getRaw;
806
+ let setRaw;
807
+ if (descriptor?.get) {
808
+ getRaw = descriptor.get.bind(connection);
809
+ setRaw = connection.setState.bind(connection);
810
+ } else {
811
+ let rawState = connection.state ?? null;
812
+ getRaw = () => rawState;
813
+ setRaw = (state) => {
814
+ rawState = state;
815
+ return rawState;
816
+ };
817
+ }
818
+ this._rawStateAccessors.set(connection, {
819
+ getRaw,
820
+ setRaw
821
+ });
822
+ Object.defineProperty(connection, "state", {
823
+ configurable: true,
824
+ enumerable: true,
825
+ get() {
826
+ const raw = getRaw();
827
+ if (raw != null && typeof raw === "object" && rawHasInternalKeys(raw)) return stripInternalKeys(raw);
828
+ return raw;
829
+ }
830
+ });
831
+ Object.defineProperty(connection, "setState", {
832
+ configurable: true,
833
+ writable: true,
834
+ value(stateOrFn) {
835
+ const raw = getRaw();
836
+ const flags = raw != null && typeof raw === "object" ? extractInternalFlags(raw) : {};
837
+ const hasFlags = Object.keys(flags).length > 0;
838
+ let newUserState;
839
+ if (typeof stateOrFn === "function") newUserState = stateOrFn(hasFlags ? stripInternalKeys(raw) : raw);
840
+ else newUserState = stateOrFn;
841
+ if (hasFlags) {
842
+ if (newUserState != null && typeof newUserState === "object") return setRaw({
843
+ ...newUserState,
844
+ ...flags
845
+ });
846
+ return setRaw(flags);
847
+ }
848
+ return setRaw(newUserState);
849
+ }
850
+ });
851
+ }
852
+ /**
853
+ * Mark a connection as readonly or readwrite
854
+ * @param connection The connection to mark
855
+ * @param readonly Whether the connection should be readonly (default: true)
856
+ */
857
+ setConnectionReadonly(connection, readonly = true) {
858
+ this._ensureConnectionWrapped(connection);
859
+ const accessors = this._rawStateAccessors.get(connection);
860
+ const raw = accessors.getRaw() ?? {};
861
+ if (readonly) accessors.setRaw({
862
+ ...raw,
863
+ [CF_READONLY_KEY]: true
864
+ });
865
+ else {
866
+ const { [CF_READONLY_KEY]: _, ...rest } = raw;
867
+ accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);
868
+ }
869
+ }
870
+ /**
871
+ * Check if a connection is marked as readonly.
872
+ *
873
+ * Safe to call after hibernation — re-wraps the connection if the
874
+ * in-memory accessor cache was cleared.
875
+ * @param connection The connection to check
876
+ * @returns True if the connection is readonly
877
+ */
878
+ isConnectionReadonly(connection) {
879
+ this._ensureConnectionWrapped(connection);
880
+ return !!this._rawStateAccessors.get(connection).getRaw()?.[CF_READONLY_KEY];
881
+ }
882
+ /**
883
+ * ⚠️ INTERNAL — DO NOT USE IN APPLICATION CODE. ⚠️
884
+ *
885
+ * Read an internal `_cf_`-prefixed flag from the raw connection state,
886
+ * bypassing the user-facing state wrapper that strips internal keys.
887
+ *
888
+ * This exists for framework mixins (e.g. voice) that need to persist
889
+ * flags in the connection attachment across hibernation. Application
890
+ * code should use `connection.state` and `connection.setState()` instead.
891
+ *
892
+ * @internal
893
+ */
894
+ _unsafe_getConnectionFlag(connection, key) {
895
+ this._ensureConnectionWrapped(connection);
896
+ return this._rawStateAccessors.get(connection).getRaw()?.[key];
897
+ }
898
+ /**
899
+ * ⚠️ INTERNAL — DO NOT USE IN APPLICATION CODE. ⚠️
900
+ *
901
+ * Write an internal `_cf_`-prefixed flag to the raw connection state,
902
+ * bypassing the user-facing state wrapper. The key must be registered
903
+ * in `CF_INTERNAL_KEYS` so it is preserved across user `setState` calls
904
+ * and hidden from `connection.state`.
905
+ *
906
+ * @internal
907
+ */
908
+ _unsafe_setConnectionFlag(connection, key, value) {
909
+ this._ensureConnectionWrapped(connection);
910
+ const accessors = this._rawStateAccessors.get(connection);
911
+ const raw = accessors.getRaw() ?? {};
912
+ if (value === void 0) {
913
+ const { [key]: _, ...rest } = raw;
914
+ accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);
915
+ } else accessors.setRaw({
916
+ ...raw,
917
+ [key]: value
918
+ });
919
+ }
920
+ /**
921
+ * Override this method to determine if a connection should be readonly on connect
922
+ * @param _connection The connection that is being established
923
+ * @param _ctx Connection context
924
+ * @returns True if the connection should be readonly
925
+ */
926
+ shouldConnectionBeReadonly(_connection, _ctx) {
927
+ return false;
928
+ }
929
+ /**
930
+ * Override this method to control whether protocol messages are sent to a
931
+ * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state
932
+ * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS).
933
+ *
934
+ * When this returns `false` for a connection, that connection will not
935
+ * receive any protocol text frames — neither on connect nor via broadcasts.
936
+ * This is useful for binary-only clients (e.g. MQTT devices) that cannot
937
+ * handle JSON text frames.
938
+ *
939
+ * The connection can still send and receive regular messages, use RPC, and
940
+ * participate in all non-protocol communication.
941
+ *
942
+ * @param _connection The connection that is being established
943
+ * @param _ctx Connection context (includes the upgrade request)
944
+ * @returns True if protocol messages should be sent (default), false to suppress them
945
+ */
946
+ shouldSendProtocolMessages(_connection, _ctx) {
947
+ return true;
948
+ }
949
+ /**
950
+ * Check if a connection has protocol messages enabled.
951
+ * Protocol messages include identity, state sync, and MCP server lists.
952
+ *
953
+ * Safe to call after hibernation — re-wraps the connection if the
954
+ * in-memory accessor cache was cleared.
955
+ * @param connection The connection to check
956
+ * @returns True if the connection receives protocol messages
957
+ */
958
+ isConnectionProtocolEnabled(connection) {
959
+ this._ensureConnectionWrapped(connection);
960
+ return !this._rawStateAccessors.get(connection).getRaw()?.[CF_NO_PROTOCOL_KEY];
961
+ }
962
+ /**
963
+ * Mark a connection as having protocol messages disabled.
964
+ * Called internally when shouldSendProtocolMessages returns false.
965
+ */
966
+ _setConnectionNoProtocol(connection) {
967
+ this._ensureConnectionWrapped(connection);
968
+ const accessors = this._rawStateAccessors.get(connection);
969
+ const raw = accessors.getRaw() ?? {};
970
+ accessors.setRaw({
971
+ ...raw,
972
+ [CF_NO_PROTOCOL_KEY]: true
973
+ });
974
+ }
975
+ /**
976
+ * Called before the Agent's state is persisted and broadcast.
977
+ * Override to validate or reject an update by throwing an error.
978
+ *
979
+ * IMPORTANT: This hook must be synchronous.
980
+ */
981
+ validateStateChange(nextState, source) {}
982
+ /**
983
+ * Called after the Agent's state has been persisted and broadcast to all clients.
984
+ * This is a notification hook — errors here are routed to onError and do not
985
+ * affect state persistence or client broadcasts.
986
+ *
987
+ * @param state Updated state
988
+ * @param source Source of the state update ("server" or a client connection)
989
+ */
990
+ onStateChanged(state, source) {}
991
+ /**
992
+ * @deprecated Renamed to `onStateChanged` — the behavior is identical.
993
+ * `onStateUpdate` will be removed in the next major version.
994
+ *
995
+ * Called after the Agent's state has been persisted and broadcast to all clients.
996
+ * This is a server-side notification hook. For the client-side state callback,
997
+ * see the `onStateUpdate` option in `useAgent` / `AgentClient`.
998
+ *
999
+ * @param state Updated state
1000
+ * @param source Source of the state update ("server" or a client connection)
1001
+ */
1002
+ onStateUpdate(state, source) {}
1003
+ /**
1004
+ * Dispatch to the appropriate persistence hook based on the mode
1005
+ * cached in the constructor. No prototype walks at call time.
1006
+ */
1007
+ async _callStatePersistenceHook(state, source) {
1008
+ switch (this._persistenceHookMode) {
1009
+ case "new":
1010
+ await this.onStateChanged(state, source);
1011
+ break;
1012
+ case "old":
1013
+ await this.onStateUpdate(state, source);
1014
+ break;
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Called when the Agent receives an email via routeAgentEmail()
1019
+ * Override this method to handle incoming emails
1020
+ * @param payload Internal wire format — plain data + RpcTarget bridge
1021
+ */
1022
+ async _onEmail(payload) {
1023
+ const email = {
1024
+ from: payload.from,
1025
+ to: payload.to,
1026
+ headers: payload.headers,
1027
+ rawSize: payload.rawSize,
1028
+ _secureRouted: payload._secureRouted,
1029
+ getRaw: () => payload._bridge.getRaw(),
1030
+ setReject: (reason) => payload._bridge.setReject(reason),
1031
+ forward: (rcptTo, headers) => payload._bridge.forward(rcptTo, headers),
1032
+ reply: (options) => payload._bridge.reply(options)
1033
+ };
1034
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1035
+ agent: this,
1036
+ connection: void 0,
1037
+ request: void 0,
1038
+ email
1039
+ }, async () => {
1040
+ this._emit("email:receive", {
1041
+ from: email.from,
1042
+ to: email.to,
1043
+ subject: email.headers.get("subject") ?? void 0
1044
+ });
1045
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
1046
+ else {
1047
+ console.log("Received email from:", email.from, "to:", email.to);
1048
+ console.log("Subject:", email.headers.get("subject"));
1049
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
1050
+ }
1051
+ });
1052
+ }
1053
+ /**
1054
+ * Reply to an email
1055
+ * @param email The email to reply to
1056
+ * @param options Options for the reply
1057
+ * @param options.secret Secret for signing agent headers (enables secure reply routing).
1058
+ * Required if the email was routed via createSecureReplyEmailResolver.
1059
+ * Pass explicit `null` to opt-out of signing (not recommended for secure routing).
1060
+ * @returns void
1061
+ */
1062
+ async replyToEmail(email, options) {
1063
+ return this._tryCatch(async () => {
1064
+ 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).");
1065
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
1066
+ const agentId = this.name;
1067
+ const { createMimeMessage } = await import("mimetext");
1068
+ const msg = createMimeMessage();
1069
+ msg.setSender({
1070
+ addr: email.to,
1071
+ name: options.fromName
1072
+ });
1073
+ msg.setRecipient(email.from);
1074
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
1075
+ msg.addMessage({
1076
+ contentType: options.contentType || "text/plain",
1077
+ data: options.body
1078
+ });
1079
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
1080
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
1081
+ msg.setHeader("Message-ID", messageId);
1082
+ msg.setHeader("X-Agent-Name", agentName);
1083
+ msg.setHeader("X-Agent-ID", agentId);
1084
+ if (typeof options.secret === "string") {
1085
+ const signedHeaders = await signAgentHeaders(options.secret, agentName, agentId);
1086
+ msg.setHeader("X-Agent-Sig", signedHeaders["X-Agent-Sig"]);
1087
+ msg.setHeader("X-Agent-Sig-Ts", signedHeaders["X-Agent-Sig-Ts"]);
1088
+ }
1089
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
1090
+ await email.reply({
1091
+ from: email.to,
1092
+ raw: msg.asRaw(),
1093
+ to: email.from
1094
+ });
1095
+ const rawSubject = email.headers.get("subject");
1096
+ this._emit("email:reply", {
1097
+ from: email.to,
1098
+ to: email.from,
1099
+ subject: options.subject ?? (rawSubject ? `Re: ${rawSubject}` : void 0)
1100
+ });
1101
+ });
1102
+ }
1103
+ async _tryCatch(fn) {
1104
+ try {
1105
+ return await fn();
1106
+ } catch (e) {
1107
+ throw this.onError(e);
1108
+ }
1109
+ }
1110
+ /**
1111
+ * Automatically wrap custom methods with agent context
1112
+ * This ensures getCurrentAgent() works in all custom methods without decorators
1113
+ */
1114
+ _autoWrapCustomMethods() {
1115
+ const basePrototypes = [Agent.prototype, Server.prototype];
1116
+ const baseMethods = /* @__PURE__ */ new Set();
1117
+ for (const baseProto of basePrototypes) {
1118
+ let proto = baseProto;
1119
+ while (proto && proto !== Object.prototype) {
1120
+ const methodNames = Object.getOwnPropertyNames(proto);
1121
+ for (const methodName of methodNames) baseMethods.add(methodName);
1122
+ proto = Object.getPrototypeOf(proto);
1123
+ }
1124
+ }
1125
+ let proto = Object.getPrototypeOf(this);
1126
+ let depth = 0;
1127
+ while (proto && proto !== Object.prototype && depth < 10) {
1128
+ const methodNames = Object.getOwnPropertyNames(proto);
1129
+ for (const methodName of methodNames) {
1130
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
1131
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
1132
+ const wrappedFunction = withAgentContext(this[methodName]);
1133
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
1134
+ this.constructor.prototype[methodName] = wrappedFunction;
1135
+ }
1136
+ proto = Object.getPrototypeOf(proto);
1137
+ depth++;
1138
+ }
1139
+ }
1140
+ onError(connectionOrError, error) {
1141
+ let theError;
1142
+ if (connectionOrError && error) {
1143
+ theError = error;
1144
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
1145
+ console.error("Override onError(connection, error) to handle websocket connection errors");
1146
+ } else {
1147
+ theError = connectionOrError;
1148
+ console.error("Error on server:", theError);
1149
+ console.error("Override onError(error) to handle server errors");
1150
+ }
1151
+ throw theError;
1152
+ }
1153
+ /**
1154
+ * Render content (not implemented in base class)
1155
+ */
1156
+ render() {
1157
+ throw new Error("Not implemented");
1158
+ }
1159
+ /**
1160
+ * Retry an async operation with exponential backoff and jitter.
1161
+ * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors.
1162
+ *
1163
+ * @param fn The async function to retry. Receives the current attempt number (1-indexed).
1164
+ * @param options Retry configuration.
1165
+ * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3.
1166
+ * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100.
1167
+ * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000.
1168
+ * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors.
1169
+ * @returns The result of fn on success.
1170
+ * @throws The last error if all attempts fail or shouldRetry returns false.
1171
+ */
1172
+ async retry(fn, options) {
1173
+ const defaults = this._resolvedOptions.retry;
1174
+ if (options) validateRetryOptions(options, defaults);
1175
+ return tryN(options?.maxAttempts ?? defaults.maxAttempts, fn, {
1176
+ baseDelayMs: options?.baseDelayMs ?? defaults.baseDelayMs,
1177
+ maxDelayMs: options?.maxDelayMs ?? defaults.maxDelayMs,
1178
+ shouldRetry: options?.shouldRetry
1179
+ });
1180
+ }
1181
+ /**
1182
+ * Queue a task to be executed in the future
1183
+ * @param callback Name of the method to call
1184
+ * @param payload Payload to pass to the callback
1185
+ * @param options Options for the queued task
1186
+ * @param options.retry Retry options for the callback execution
1187
+ * @returns The ID of the queued task
1188
+ */
1189
+ async queue(callback, payload, options) {
1190
+ const id = nanoid(9);
1191
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1192
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1193
+ if (options?.retry) validateRetryOptions(options.retry, this._resolvedOptions.retry);
1194
+ const retryJson = options?.retry ? JSON.stringify(options.retry) : null;
1195
+ this.sql`
1196
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback, retry_options)
1197
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback}, ${retryJson})
1198
+ `;
1199
+ this._emit("queue:create", {
1200
+ callback,
1201
+ id
1202
+ });
1203
+ this._flushQueue().catch((e) => {
1204
+ console.error("Error flushing queue:", e);
1205
+ });
1206
+ return id;
1207
+ }
1208
+ async _flushQueue() {
1209
+ if (this._flushingQueue) return;
1210
+ this._flushingQueue = true;
1211
+ try {
1212
+ while (true) {
1213
+ const result = this.sql`
1214
+ SELECT * FROM cf_agents_queues
1215
+ ORDER BY created_at ASC
1216
+ `;
1217
+ if (!result || result.length === 0) break;
1218
+ for (const row of result || []) {
1219
+ const callback = this[row.callback];
1220
+ if (!callback) {
1221
+ console.error(`callback ${row.callback} not found`);
1222
+ await this.dequeue(row.id);
1223
+ continue;
1224
+ }
1225
+ const { connection, request, email } = __DO_NOT_USE_WILL_BREAK__agentContext.getStore() || {};
1226
+ await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1227
+ agent: this,
1228
+ connection,
1229
+ request,
1230
+ email
1231
+ }, async () => {
1232
+ const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(parseRetryOptions(row), this._resolvedOptions.retry);
1233
+ const parsedPayload = JSON.parse(row.payload);
1234
+ try {
1235
+ await tryN(maxAttempts, async (attempt) => {
1236
+ if (attempt > 1) this._emit("queue:retry", {
1237
+ callback: row.callback,
1238
+ id: row.id,
1239
+ attempt,
1240
+ maxAttempts
1241
+ });
1242
+ await callback.bind(this)(parsedPayload, row);
1243
+ }, {
1244
+ baseDelayMs,
1245
+ maxDelayMs
1246
+ });
1247
+ } catch (e) {
1248
+ console.error(`queue callback "${row.callback}" failed after ${maxAttempts} attempts`, e);
1249
+ this._emit("queue:error", {
1250
+ callback: row.callback,
1251
+ id: row.id,
1252
+ error: e instanceof Error ? e.message : String(e),
1253
+ attempts: maxAttempts
1254
+ });
1255
+ try {
1256
+ await this.onError(e);
1257
+ } catch {}
1258
+ } finally {
1259
+ this.dequeue(row.id);
1260
+ }
1261
+ });
1262
+ }
1263
+ }
1264
+ } finally {
1265
+ this._flushingQueue = false;
1266
+ }
1267
+ }
1268
+ /**
1269
+ * Dequeue a task by ID
1270
+ * @param id ID of the task to dequeue
1271
+ */
1272
+ dequeue(id) {
1273
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1274
+ }
1275
+ /**
1276
+ * Dequeue all tasks
1277
+ */
1278
+ dequeueAll() {
1279
+ this.sql`DELETE FROM cf_agents_queues`;
1280
+ }
1281
+ /**
1282
+ * Dequeue all tasks by callback
1283
+ * @param callback Name of the callback to dequeue
1284
+ */
1285
+ dequeueAllByCallback(callback) {
1286
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1287
+ }
1288
+ /**
1289
+ * Get a queued task by ID
1290
+ * @param id ID of the task to get
1291
+ * @returns The task or undefined if not found
1292
+ */
1293
+ getQueue(id) {
1294
+ const result = this.sql`
1295
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1296
+ `;
1297
+ if (!result || result.length === 0) return void 0;
1298
+ const row = result[0];
1299
+ return {
1300
+ ...row,
1301
+ payload: JSON.parse(row.payload),
1302
+ retry: parseRetryOptions(row)
1303
+ };
1304
+ }
1305
+ /**
1306
+ * Get all queues by key and value
1307
+ * @param key Key to filter by
1308
+ * @param value Value to filter by
1309
+ * @returns Array of matching QueueItem objects
1310
+ */
1311
+ getQueues(key, value) {
1312
+ return this.sql`
1313
+ SELECT * FROM cf_agents_queues
1314
+ `.filter((row) => JSON.parse(row.payload)[key] === value).map((row) => ({
1315
+ ...row,
1316
+ payload: JSON.parse(row.payload),
1317
+ retry: parseRetryOptions(row)
1318
+ }));
1319
+ }
1320
+ /**
1321
+ * Schedule a task to be executed in the future
1322
+ *
1323
+ * Cron schedules are **idempotent by default** — calling `schedule("0 * * * *", "tick")`
1324
+ * multiple times with the same callback, cron expression, and payload returns
1325
+ * the existing schedule instead of creating a duplicate. Set `idempotent: false`
1326
+ * to override this.
1327
+ *
1328
+ * For delayed and scheduled (Date) types, set `idempotent: true` to opt in
1329
+ * to the same dedup behavior (matched on callback + payload). This is useful
1330
+ * when calling `schedule()` in `onStart()` to avoid accumulating duplicate
1331
+ * rows across Durable Object restarts.
1332
+ *
1333
+ * @template T Type of the payload data
1334
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
1335
+ * @param callback Name of the method to call
1336
+ * @param payload Data to pass to the callback
1337
+ * @param options Options for the scheduled task
1338
+ * @param options.retry Retry options for the callback execution
1339
+ * @param options.idempotent Dedup by callback+payload. Defaults to `true` for cron, `false` otherwise.
1340
+ * @returns Schedule object representing the scheduled task
1341
+ */
1342
+ async schedule(when, callback, payload, options) {
1343
+ if (this._isFacet) throw new Error("Scheduling is not supported in sub-agents. Schedule from the parent agent instead.");
1344
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1345
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1346
+ if (options?.retry) validateRetryOptions(options.retry, this._resolvedOptions.retry);
1347
+ const retryJson = options?.retry ? JSON.stringify(options.retry) : null;
1348
+ const payloadJson = JSON.stringify(payload);
1349
+ if (this._insideOnStart && options?.idempotent === void 0 && typeof when !== "string" && !this._warnedScheduleInOnStart.has(callback)) {
1350
+ this._warnedScheduleInOnStart.add(callback);
1351
+ console.warn(`schedule("${callback}") called inside onStart() without { idempotent: true }. This creates a new row on every Durable Object restart, which can cause duplicate executions. Pass { idempotent: true } to deduplicate, or use scheduleEvery() for recurring tasks.`);
1352
+ }
1353
+ if (when instanceof Date) {
1354
+ const timestamp = Math.floor(when.getTime() / 1e3);
1355
+ if (options?.idempotent) {
1356
+ const existing = this.sql`
1357
+ SELECT * FROM cf_agents_schedules
1358
+ WHERE type = 'scheduled'
1359
+ AND callback = ${callback}
1360
+ AND payload IS ${payloadJson}
1361
+ LIMIT 1
1362
+ `;
1363
+ if (existing.length > 0) {
1364
+ const row = existing[0];
1365
+ await this._scheduleNextAlarm();
1366
+ return {
1367
+ callback: row.callback,
1368
+ id: row.id,
1369
+ payload: JSON.parse(row.payload),
1370
+ retry: parseRetryOptions(row),
1371
+ time: row.time,
1372
+ type: "scheduled"
1373
+ };
1374
+ }
1375
+ }
1376
+ const id = nanoid(9);
1377
+ this.sql`
1378
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time, retry_options)
1379
+ VALUES (${id}, ${callback}, ${payloadJson}, 'scheduled', ${timestamp}, ${retryJson})
1380
+ `;
1381
+ await this._scheduleNextAlarm();
1382
+ const schedule = {
1383
+ callback,
1384
+ id,
1385
+ payload,
1386
+ retry: options?.retry,
1387
+ time: timestamp,
1388
+ type: "scheduled"
1389
+ };
1390
+ this._emit("schedule:create", {
1391
+ callback,
1392
+ id
1393
+ });
1394
+ return schedule;
1395
+ }
1396
+ if (typeof when === "number") {
1397
+ const time = new Date(Date.now() + when * 1e3);
1398
+ const timestamp = Math.floor(time.getTime() / 1e3);
1399
+ if (options?.idempotent) {
1400
+ const existing = this.sql`
1401
+ SELECT * FROM cf_agents_schedules
1402
+ WHERE type = 'delayed'
1403
+ AND callback = ${callback}
1404
+ AND payload IS ${payloadJson}
1405
+ LIMIT 1
1406
+ `;
1407
+ if (existing.length > 0) {
1408
+ const row = existing[0];
1409
+ await this._scheduleNextAlarm();
1410
+ return {
1411
+ callback: row.callback,
1412
+ delayInSeconds: row.delayInSeconds,
1413
+ id: row.id,
1414
+ payload: JSON.parse(row.payload),
1415
+ retry: parseRetryOptions(row),
1416
+ time: row.time,
1417
+ type: "delayed"
1418
+ };
1419
+ }
1420
+ }
1421
+ const id = nanoid(9);
1422
+ this.sql`
1423
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time, retry_options)
1424
+ VALUES (${id}, ${callback}, ${payloadJson}, 'delayed', ${when}, ${timestamp}, ${retryJson})
1425
+ `;
1426
+ await this._scheduleNextAlarm();
1427
+ const schedule = {
1428
+ callback,
1429
+ delayInSeconds: when,
1430
+ id,
1431
+ payload,
1432
+ retry: options?.retry,
1433
+ time: timestamp,
1434
+ type: "delayed"
1435
+ };
1436
+ this._emit("schedule:create", {
1437
+ callback,
1438
+ id
1439
+ });
1440
+ return schedule;
1441
+ }
1442
+ if (typeof when === "string") {
1443
+ const nextExecutionTime = getNextCronTime(when);
1444
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1445
+ if (options?.idempotent !== false) {
1446
+ const existing = this.sql`
1447
+ SELECT * FROM cf_agents_schedules
1448
+ WHERE type = 'cron'
1449
+ AND callback = ${callback}
1450
+ AND cron = ${when}
1451
+ AND payload IS ${payloadJson}
1452
+ LIMIT 1
1453
+ `;
1454
+ if (existing.length > 0) {
1455
+ const row = existing[0];
1456
+ await this._scheduleNextAlarm();
1457
+ return {
1458
+ callback: row.callback,
1459
+ cron: row.cron,
1460
+ id: row.id,
1461
+ payload: JSON.parse(row.payload),
1462
+ retry: parseRetryOptions(row),
1463
+ time: row.time,
1464
+ type: "cron"
1465
+ };
1466
+ }
1467
+ }
1468
+ const id = nanoid(9);
1469
+ this.sql`
1470
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time, retry_options)
1471
+ VALUES (${id}, ${callback}, ${payloadJson}, 'cron', ${when}, ${timestamp}, ${retryJson})
1472
+ `;
1473
+ await this._scheduleNextAlarm();
1474
+ const schedule = {
1475
+ callback,
1476
+ cron: when,
1477
+ id,
1478
+ payload,
1479
+ retry: options?.retry,
1480
+ time: timestamp,
1481
+ type: "cron"
1482
+ };
1483
+ this._emit("schedule:create", {
1484
+ callback,
1485
+ id
1486
+ });
1487
+ return schedule;
1488
+ }
1489
+ throw new Error(`Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`);
1490
+ }
1491
+ /**
1492
+ * Schedule a task to run repeatedly at a fixed interval.
1493
+ *
1494
+ * This method is **idempotent** — calling it multiple times with the same
1495
+ * `callback`, `intervalSeconds`, and `payload` returns the existing schedule
1496
+ * instead of creating a duplicate. A different interval or payload is
1497
+ * treated as a distinct schedule and creates a new row.
1498
+ *
1499
+ * This makes it safe to call in `onStart()`, which runs on every Durable
1500
+ * Object wake:
1501
+ *
1502
+ * ```ts
1503
+ * async onStart() {
1504
+ * // Only one schedule is created, no matter how many times the DO wakes
1505
+ * await this.scheduleEvery(30, "tick");
1506
+ * }
1507
+ * ```
1508
+ *
1509
+ * @template T Type of the payload data
1510
+ * @param intervalSeconds Number of seconds between executions
1511
+ * @param callback Name of the method to call
1512
+ * @param payload Data to pass to the callback
1513
+ * @param options Options for the scheduled task
1514
+ * @param options.retry Retry options for the callback execution
1515
+ * @returns Schedule object representing the scheduled task
1516
+ */
1517
+ async scheduleEvery(intervalSeconds, callback, payload, options) {
1518
+ if (this._isFacet) throw new Error("Scheduling is not supported in sub-agents. Schedule from the parent agent instead.");
1519
+ const MAX_INTERVAL_SECONDS = 720 * 60 * 60;
1520
+ if (typeof intervalSeconds !== "number" || intervalSeconds <= 0) throw new Error("intervalSeconds must be a positive number");
1521
+ if (intervalSeconds > MAX_INTERVAL_SECONDS) throw new Error(`intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`);
1522
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1523
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1524
+ if (options?.retry) validateRetryOptions(options.retry, this._resolvedOptions.retry);
1525
+ const idempotent = options?._idempotent !== false;
1526
+ const payloadJson = JSON.stringify(payload);
1527
+ if (idempotent) {
1528
+ const existing = this.sql`
1529
+ SELECT * FROM cf_agents_schedules
1530
+ WHERE type = 'interval'
1531
+ AND callback = ${callback}
1532
+ AND intervalSeconds = ${intervalSeconds}
1533
+ AND payload IS ${payloadJson}
1534
+ LIMIT 1
1535
+ `;
1536
+ if (existing.length > 0) {
1537
+ const row = existing[0];
1538
+ await this._scheduleNextAlarm();
1539
+ return {
1540
+ callback: row.callback,
1541
+ id: row.id,
1542
+ intervalSeconds: row.intervalSeconds,
1543
+ payload: JSON.parse(row.payload),
1544
+ retry: parseRetryOptions(row),
1545
+ time: row.time,
1546
+ type: "interval"
1547
+ };
1548
+ }
1549
+ }
1550
+ const id = nanoid(9);
1551
+ const time = new Date(Date.now() + intervalSeconds * 1e3);
1552
+ const timestamp = Math.floor(time.getTime() / 1e3);
1553
+ const retryJson = options?.retry ? JSON.stringify(options.retry) : null;
1554
+ this.sql`
1555
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, intervalSeconds, time, running, retry_options)
1556
+ VALUES (${id}, ${callback}, ${payloadJson}, 'interval', ${intervalSeconds}, ${timestamp}, 0, ${retryJson})
1557
+ `;
1558
+ await this._scheduleNextAlarm();
1559
+ const schedule = {
1560
+ callback,
1561
+ id,
1562
+ intervalSeconds,
1563
+ payload,
1564
+ retry: options?.retry,
1565
+ time: timestamp,
1566
+ type: "interval"
1567
+ };
1568
+ this._emit("schedule:create", {
1569
+ callback,
1570
+ id
1571
+ });
1572
+ return schedule;
1573
+ }
1574
+ /**
1575
+ * Get a scheduled task by ID
1576
+ * @template T Type of the payload data
1577
+ * @param id ID of the scheduled task
1578
+ * @returns The Schedule object or undefined if not found
1579
+ */
1580
+ getSchedule(id) {
1581
+ const result = this.sql`
1582
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
1583
+ `;
1584
+ if (!result || result.length === 0) return;
1585
+ const row = result[0];
1586
+ return {
1587
+ ...row,
1588
+ payload: JSON.parse(row.payload),
1589
+ retry: parseRetryOptions(row)
1590
+ };
1591
+ }
1592
+ /**
1593
+ * Get scheduled tasks matching the given criteria
1594
+ * @template T Type of the payload data
1595
+ * @param criteria Criteria to filter schedules
1596
+ * @returns Array of matching Schedule objects
1597
+ */
1598
+ getSchedules(criteria = {}) {
1599
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
1600
+ const params = [];
1601
+ if (criteria.id) {
1602
+ query += " AND id = ?";
1603
+ params.push(criteria.id);
1604
+ }
1605
+ if (criteria.type) {
1606
+ query += " AND type = ?";
1607
+ params.push(criteria.type);
1608
+ }
1609
+ if (criteria.timeRange) {
1610
+ query += " AND time >= ? AND time <= ?";
1611
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
1612
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
1613
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
1614
+ }
1615
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
1616
+ ...row,
1617
+ payload: JSON.parse(row.payload),
1618
+ retry: parseRetryOptions(row)
1619
+ }));
1620
+ }
1621
+ /**
1622
+ * Cancel a scheduled task
1623
+ * @param id ID of the task to cancel
1624
+ * @returns true if the task was cancelled, false if the task was not found
1625
+ */
1626
+ async cancelSchedule(id) {
1627
+ if (this._isFacet) throw new Error("Scheduling is not supported in sub-agents. Schedule from the parent agent instead.");
1628
+ const schedule = this.getSchedule(id);
1629
+ if (!schedule) return false;
1630
+ this._emit("schedule:cancel", {
1631
+ callback: schedule.callback,
1632
+ id: schedule.id
1633
+ });
1634
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
1635
+ await this._scheduleNextAlarm();
1636
+ return true;
1637
+ }
1638
+ /**
1639
+ * Keep the Durable Object alive via alarm heartbeats.
1640
+ * Returns a disposer function that stops the heartbeat when called.
1641
+ *
1642
+ * Use this when you have long-running work and need to prevent the
1643
+ * DO from going idle (eviction after ~70-140s of inactivity).
1644
+ * The heartbeat fires every `keepAliveIntervalMs` (default 30s) via the
1645
+ * alarm system, without creating schedule rows or emitting observability
1646
+ * events. Configure via `static options = { keepAliveIntervalMs: 5000 }`.
1647
+ *
1648
+ * @example
1649
+ * ```ts
1650
+ * const dispose = await this.keepAlive();
1651
+ * try {
1652
+ * // ... long-running work ...
1653
+ * } finally {
1654
+ * dispose();
1655
+ * }
1656
+ * ```
1657
+ */
1658
+ async keepAlive() {
1659
+ if (this._isFacet) throw new Error("keepAlive() is not supported in sub-agents. Use keepAlive() from the parent agent instead.");
1660
+ this._keepAliveRefs++;
1661
+ if (this._keepAliveRefs === 1) await this._scheduleNextAlarm();
1662
+ let disposed = false;
1663
+ return () => {
1664
+ if (disposed) return;
1665
+ disposed = true;
1666
+ this._keepAliveRefs = Math.max(0, this._keepAliveRefs - 1);
1667
+ };
1668
+ }
1669
+ /**
1670
+ * Run an async function while keeping the Durable Object alive.
1671
+ * The heartbeat is automatically stopped when the function completes
1672
+ * (whether it succeeds or throws).
1673
+ *
1674
+ * This is the recommended way to use keepAlive — it guarantees cleanup
1675
+ * so you cannot forget to dispose the heartbeat.
1676
+ *
1677
+ * @example
1678
+ * ```ts
1679
+ * const result = await this.keepAliveWhile(async () => {
1680
+ * const data = await longRunningComputation();
1681
+ * return data;
1682
+ * });
1683
+ * ```
1684
+ */
1685
+ async keepAliveWhile(fn) {
1686
+ const dispose = await this.keepAlive();
1687
+ try {
1688
+ return await fn();
1689
+ } finally {
1690
+ dispose();
1691
+ }
1692
+ }
1693
+ /**
1694
+ * Run a function as a durable fiber. The fiber is registered in SQLite
1695
+ * before execution, checkpointable during execution via `ctx.stash()`,
1696
+ * and recoverable after eviction via `onFiberRecovered`.
1697
+ *
1698
+ * - Row created in `cf_agents_runs` at start, deleted on completion
1699
+ * - `keepAlive()` held for the duration — prevents idle eviction
1700
+ * - Inline (await result) or fire-and-forget (`void this.runFiber(...)`)
1701
+ *
1702
+ * @param name Informational name for debugging and recovery filtering
1703
+ * @param fn Async function to execute. Receives a FiberContext with stash/snapshot.
1704
+ * @returns The return value of fn
1705
+ */
1706
+ async runFiber(name, fn) {
1707
+ const id = nanoid();
1708
+ this.sql`
1709
+ INSERT INTO cf_agents_runs (id, name, snapshot, created_at)
1710
+ VALUES (${id}, ${name}, NULL, ${Date.now()})
1711
+ `;
1712
+ this._runFiberActiveFibers.add(id);
1713
+ const dispose = await this.keepAlive();
1714
+ try {
1715
+ const stash = (data) => {
1716
+ this.sql`
1717
+ UPDATE cf_agents_runs SET snapshot = ${JSON.stringify(data)}
1718
+ WHERE id = ${id}
1719
+ `;
1720
+ };
1721
+ return await _fiberALS.run({
1722
+ id,
1723
+ stash
1724
+ }, () => fn({
1725
+ id,
1726
+ stash,
1727
+ snapshot: null
1728
+ }));
1729
+ } finally {
1730
+ this._runFiberActiveFibers.delete(id);
1731
+ this.sql`DELETE FROM cf_agents_runs WHERE id = ${id}`;
1732
+ dispose();
1733
+ }
1734
+ }
1735
+ /**
1736
+ * Checkpoint data for the currently executing fiber.
1737
+ * Uses AsyncLocalStorage to identify the correct fiber,
1738
+ * so it works correctly even with concurrent fibers.
1739
+ *
1740
+ * Throws if called outside a `runFiber` callback.
1741
+ */
1742
+ stash(data) {
1743
+ const ctx = _fiberALS.getStore();
1744
+ if (!ctx) throw new Error("stash() called outside a fiber");
1745
+ ctx.stash(data);
1746
+ }
1747
+ /**
1748
+ * Called when an interrupted fiber is detected after restart.
1749
+ * Override to implement recovery (re-invoke work, notify clients, etc.).
1750
+ *
1751
+ * Internal framework fibers are filtered by `_handleInternalFiberRecovery`
1752
+ * before this hook runs — users only see their own fibers.
1753
+ *
1754
+ * Default: logs a warning.
1755
+ */
1756
+ async onFiberRecovered(_ctx) {
1757
+ console.warn(`[Agent] Fiber "${_ctx.name}" (${_ctx.id}) was interrupted. Override onFiberRecovered to handle recovery.`);
1758
+ }
1759
+ /**
1760
+ * Override point for subclasses to handle internal (framework) fibers
1761
+ * before the user's recovery hook fires. Return `true` if handled.
1762
+ * @internal
1763
+ */
1764
+ async _handleInternalFiberRecovery(_ctx) {
1765
+ return false;
1766
+ }
1767
+ /** @internal Detect fibers left by a dead process (runFiber system). */
1768
+ async _checkRunFibers() {
1769
+ if (this._runFiberRecoveryInProgress) return;
1770
+ this._runFiberRecoveryInProgress = true;
1771
+ try {
1772
+ const rows = this.sql`SELECT id, name, snapshot FROM cf_agents_runs`;
1773
+ for (const row of rows) {
1774
+ if (this._runFiberActiveFibers.has(row.id)) continue;
1775
+ let snapshot = null;
1776
+ if (row.snapshot) try {
1777
+ snapshot = JSON.parse(row.snapshot);
1778
+ } catch {
1779
+ console.warn(`[Agent] Corrupted snapshot for fiber ${row.id}, treating as null`);
1780
+ }
1781
+ const ctx = {
1782
+ id: row.id,
1783
+ name: row.name,
1784
+ snapshot
1785
+ };
1786
+ try {
1787
+ if (!await this._handleInternalFiberRecovery(ctx)) await this.onFiberRecovered(ctx);
1788
+ } catch (e) {
1789
+ console.error(`[Agent] Fiber recovery failed for "${ctx.name}" (${ctx.id}):`, e);
1790
+ }
1791
+ this.sql`DELETE FROM cf_agents_runs WHERE id = ${row.id}`;
1792
+ }
1793
+ } finally {
1794
+ this._runFiberRecoveryInProgress = false;
1795
+ }
1796
+ }
1797
+ /** @internal */
1798
+ async _onAlarmHousekeeping() {
1799
+ await this._checkRunFibers();
1800
+ }
1801
+ async _scheduleNextAlarm() {
1802
+ const nowMs = Date.now();
1803
+ const hungCutoffSeconds = Math.floor(nowMs / 1e3) - this._resolvedOptions.hungScheduleTimeoutSeconds;
1804
+ const readySchedules = this.sql`
1805
+ SELECT time FROM cf_agents_schedules
1806
+ WHERE type != 'interval'
1807
+ OR running = 0
1808
+ OR coalesce(execution_started_at, 0) <= ${hungCutoffSeconds}
1809
+ ORDER BY time ASC
1810
+ LIMIT 1
1811
+ `;
1812
+ const recoveringIntervals = this.sql`
1813
+ SELECT execution_started_at FROM cf_agents_schedules
1814
+ WHERE type = 'interval'
1815
+ AND running = 1
1816
+ AND coalesce(execution_started_at, 0) > ${hungCutoffSeconds}
1817
+ ORDER BY execution_started_at ASC
1818
+ LIMIT 1
1819
+ `;
1820
+ let nextTimeMs = null;
1821
+ if (readySchedules.length > 0 && "time" in readySchedules[0]) nextTimeMs = Math.max(readySchedules[0].time * 1e3, nowMs + 1);
1822
+ if (recoveringIntervals.length > 0 && recoveringIntervals[0].execution_started_at !== null) {
1823
+ const recoveryTimeMs = (recoveringIntervals[0].execution_started_at + this._resolvedOptions.hungScheduleTimeoutSeconds) * 1e3;
1824
+ nextTimeMs = nextTimeMs === null ? recoveryTimeMs : Math.min(nextTimeMs, recoveryTimeMs);
1825
+ }
1826
+ if (this._keepAliveRefs > 0) {
1827
+ const keepAliveMs = nowMs + this._resolvedOptions.keepAliveIntervalMs;
1828
+ nextTimeMs = nextTimeMs === null ? keepAliveMs : Math.min(nextTimeMs, keepAliveMs);
1829
+ }
1830
+ if (nextTimeMs !== null) await this.ctx.storage.setAlarm(nextTimeMs);
1831
+ else await this.ctx.storage.deleteAlarm();
1832
+ }
1833
+ /**
1834
+ * Override PartyServer's onAlarm hook as a no-op.
1835
+ * Agent handles alarm logic directly in the alarm() method override,
1836
+ * but super.alarm() calls onAlarm() after #ensureInitialized(),
1837
+ * so we suppress the default "Implement onAlarm" warning.
1838
+ */
1839
+ onAlarm() {}
1840
+ /**
1841
+ * Method called when an alarm fires.
1842
+ * Executes any scheduled tasks that are due.
1843
+ *
1844
+ * Calls super.alarm() first to ensure PartyServer's #ensureInitialized()
1845
+ * runs, which hydrates this.name from storage and calls onStart() if needed.
1846
+ *
1847
+ * @remarks
1848
+ * To schedule a task, please use the `this.schedule` method instead.
1849
+ * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
1850
+ */
1851
+ async alarm() {
1852
+ await super.alarm();
1853
+ const now = Math.floor(Date.now() / 1e3);
1854
+ const result = this.sql`
1855
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
1856
+ `;
1857
+ if (result && Array.isArray(result)) {
1858
+ const DUPLICATE_SCHEDULE_THRESHOLD = 10;
1859
+ const oneShotCounts = /* @__PURE__ */ new Map();
1860
+ for (const row of result) if (row.type === "delayed" || row.type === "scheduled") oneShotCounts.set(row.callback, (oneShotCounts.get(row.callback) ?? 0) + 1);
1861
+ for (const [cb, count] of oneShotCounts) if (count >= DUPLICATE_SCHEDULE_THRESHOLD) try {
1862
+ console.warn(`Processing ${count} stale "${cb}" schedules in a single alarm cycle. This usually means schedule() is being called repeatedly without the idempotent option. Consider using scheduleEvery() for recurring tasks or passing { idempotent: true } to schedule().`);
1863
+ this._emit("schedule:duplicate_warning", {
1864
+ callback: cb,
1865
+ count,
1866
+ type: "one-shot"
1867
+ });
1868
+ } catch {}
1869
+ for (const row of result) {
1870
+ const callback = this[row.callback];
1871
+ if (!callback) {
1872
+ console.error(`callback ${row.callback} not found`);
1873
+ continue;
1874
+ }
1875
+ if (row.type === "interval" && row.running === 1) {
1876
+ const executionStartedAt = row.execution_started_at ?? 0;
1877
+ const hungTimeoutSeconds = this._resolvedOptions.hungScheduleTimeoutSeconds;
1878
+ const elapsedSeconds = now - executionStartedAt;
1879
+ if (elapsedSeconds < hungTimeoutSeconds) {
1880
+ console.warn(`Skipping interval schedule ${row.id}: previous execution still running`);
1881
+ continue;
1882
+ }
1883
+ console.warn(`Forcing reset of hung interval schedule ${row.id} (started ${elapsedSeconds}s ago)`);
1884
+ }
1885
+ if (row.type === "interval") this.sql`UPDATE cf_agents_schedules SET running = 1, execution_started_at = ${now} WHERE id = ${row.id}`;
1886
+ await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1887
+ agent: this,
1888
+ connection: void 0,
1889
+ request: void 0,
1890
+ email: void 0
1891
+ }, async () => {
1892
+ const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(parseRetryOptions(row), this._resolvedOptions.retry);
1893
+ let parsedPayload;
1894
+ try {
1895
+ parsedPayload = JSON.parse(row.payload);
1896
+ } catch (e) {
1897
+ console.error(`Failed to parse payload for schedule "${row.id}" (callback "${row.callback}")`, e);
1898
+ this._emit("schedule:error", {
1899
+ callback: row.callback,
1900
+ id: row.id,
1901
+ error: e instanceof Error ? e.message : String(e),
1902
+ attempts: 0
1903
+ });
1904
+ return;
1905
+ }
1906
+ try {
1907
+ this._emit("schedule:execute", {
1908
+ callback: row.callback,
1909
+ id: row.id
1910
+ });
1911
+ await tryN(maxAttempts, async (attempt) => {
1912
+ if (attempt > 1) this._emit("schedule:retry", {
1913
+ callback: row.callback,
1914
+ id: row.id,
1915
+ attempt,
1916
+ maxAttempts
1917
+ });
1918
+ await callback.bind(this)(parsedPayload, row);
1919
+ }, {
1920
+ baseDelayMs,
1921
+ maxDelayMs
1922
+ });
1923
+ } catch (e) {
1924
+ console.error(`error executing callback "${row.callback}" after ${maxAttempts} attempts`, e);
1925
+ this._emit("schedule:error", {
1926
+ callback: row.callback,
1927
+ id: row.id,
1928
+ error: e instanceof Error ? e.message : String(e),
1929
+ attempts: maxAttempts
1930
+ });
1931
+ try {
1932
+ await this.onError(e);
1933
+ } catch {}
1934
+ }
1935
+ });
1936
+ if (this._destroyed) return;
1937
+ if (row.type === "cron") {
1938
+ const nextExecutionTime = getNextCronTime(row.cron);
1939
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1940
+ this.sql`
1941
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1942
+ `;
1943
+ } else if (row.type === "interval") {
1944
+ const nextTimestamp = Math.floor(Date.now() / 1e3) + (row.intervalSeconds ?? 0);
1945
+ this.sql`
1946
+ UPDATE cf_agents_schedules SET running = 0, time = ${nextTimestamp} WHERE id = ${row.id}
1947
+ `;
1948
+ } else this.sql`
1949
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1950
+ `;
1951
+ }
1952
+ }
1953
+ if (this._destroyed) return;
1954
+ await this._onAlarmHousekeeping();
1955
+ await this._scheduleNextAlarm();
1956
+ }
1957
+ /**
1958
+ * Marks this agent as running inside a facet (sub-agent). Once set,
1959
+ * scheduling methods throw a clear error instead of crashing on
1960
+ * `setAlarm()` (which is not supported in facets).
1961
+ * @internal
1962
+ */
1963
+ async _cf_markAsFacet() {
1964
+ this._isFacet = true;
1965
+ await this.ctx.storage.put("cf_agents_is_facet", true);
1966
+ }
1967
+ /**
1968
+ * Get or create a named sub-agent — a child Durable Object (facet)
1969
+ * with its own isolated SQLite storage running on the same machine.
1970
+ *
1971
+ * The child class must extend `Agent` and be exported from the worker
1972
+ * entry point. The first call for a given name triggers the child's
1973
+ * `onStart()`. Subsequent calls return the existing instance.
1974
+ *
1975
+ * @experimental Requires the `"experimental"` compatibility flag.
1976
+ *
1977
+ * @param cls The Agent subclass (must be exported from the worker)
1978
+ * @param name Unique name for this child instance
1979
+ * @returns A typed RPC stub for calling methods on the child
1980
+ *
1981
+ * @example
1982
+ * ```typescript
1983
+ * const searcher = await this.subAgent(SearchAgent, "main-search");
1984
+ * const results = await searcher.search("cloudflare agents");
1985
+ * ```
1986
+ */
1987
+ async subAgent(cls, name) {
1988
+ const ctx = this.ctx;
1989
+ if (!ctx.facets || !ctx.exports) throw new Error("subAgent() requires the \"experimental\" compatibility flag. Add it to your wrangler.jsonc compatibility_flags.");
1990
+ if (!ctx.exports[cls.name]) throw new Error(`Sub-agent class "${cls.name}" not found in worker exports. Make sure the class is exported from your worker entry point and that the export name matches the class name.`);
1991
+ const facetKey = `${cls.name}\0${name}`;
1992
+ const stub = ctx.facets.get(facetKey, () => ({ class: ctx.exports[cls.name] }));
1993
+ const req = new Request("http://dummy-example.cloudflare.com/cdn-cgi/partyserver/set-name/");
1994
+ req.headers.set("x-partykit-room", name);
1995
+ await stub.fetch(req).then((res) => res.text());
1996
+ await stub._cf_markAsFacet();
1997
+ return stub;
1998
+ }
1999
+ /**
2000
+ * Forcefully abort a running sub-agent. The child stops executing
2001
+ * immediately and will be restarted on next {@link subAgent} call.
2002
+ * Pending RPC calls receive the reason as an error.
2003
+ * Transitively aborts the child's own children.
2004
+ *
2005
+ * @experimental Requires the `"experimental"` compatibility flag.
2006
+ *
2007
+ * @param cls The Agent subclass used when creating the child
2008
+ * @param name Name of the child to abort
2009
+ * @param reason Error thrown to pending/future RPC callers
2010
+ */
2011
+ abortSubAgent(cls, name, reason) {
2012
+ const ctx = this.ctx;
2013
+ if (!ctx.facets) throw new Error("abortSubAgent() requires the \"experimental\" compatibility flag.");
2014
+ const facetKey = `${cls.name}\0${name}`;
2015
+ ctx.facets.abort(facetKey, reason);
2016
+ }
2017
+ /**
2018
+ * Delete a sub-agent: abort it if running, then permanently wipe its
2019
+ * storage. Transitively deletes the child's own children.
2020
+ *
2021
+ * @experimental Requires the `"experimental"` compatibility flag.
2022
+ *
2023
+ * @param cls The Agent subclass used when creating the child
2024
+ * @param name Name of the child to delete
2025
+ */
2026
+ deleteSubAgent(cls, name) {
2027
+ const ctx = this.ctx;
2028
+ if (!ctx.facets) throw new Error("deleteSubAgent() requires the \"experimental\" compatibility flag.");
2029
+ const facetKey = `${cls.name}\0${name}`;
2030
+ ctx.facets.delete(facetKey);
2031
+ }
2032
+ /**
2033
+ * Destroy the Agent, removing all state and scheduled tasks
2034
+ */
2035
+ async destroy() {
2036
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
2037
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
2038
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
2039
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
2040
+ this.sql`DROP TABLE IF EXISTS cf_agents_workflows`;
2041
+ if (!this._isFacet) await this.ctx.storage.deleteAlarm();
2042
+ await this.ctx.storage.deleteAll();
2043
+ this._disposables.dispose();
2044
+ await this.mcp.dispose();
2045
+ this._destroyed = true;
2046
+ setTimeout(() => {
2047
+ this.ctx.abort("destroyed");
2048
+ }, 0);
2049
+ this._emit("destroy");
2050
+ }
2051
+ /**
2052
+ * Check if a method is callable
2053
+ * @param method The method name to check
2054
+ * @returns True if the method is marked as callable
2055
+ */
2056
+ _isCallable(method) {
2057
+ return callableMetadata.has(this[method]);
2058
+ }
2059
+ /**
2060
+ * Get all methods marked as callable on this Agent
2061
+ * @returns A map of method names to their metadata
2062
+ */
2063
+ getCallableMethods() {
2064
+ const result = /* @__PURE__ */ new Map();
2065
+ let prototype = Object.getPrototypeOf(this);
2066
+ while (prototype && prototype !== Object.prototype) {
2067
+ for (const name of Object.getOwnPropertyNames(prototype)) {
2068
+ if (name === "constructor") continue;
2069
+ if (result.has(name)) continue;
2070
+ try {
2071
+ const fn = prototype[name];
2072
+ if (typeof fn === "function") {
2073
+ const meta = callableMetadata.get(fn);
2074
+ if (meta) result.set(name, meta);
2075
+ }
2076
+ } catch (e) {
2077
+ if (!(e instanceof TypeError)) throw e;
2078
+ }
2079
+ }
2080
+ prototype = Object.getPrototypeOf(prototype);
2081
+ }
2082
+ return result;
2083
+ }
2084
+ /**
2085
+ * Start a workflow and track it in this Agent's database.
2086
+ * Automatically injects agent identity into the workflow params.
2087
+ *
2088
+ * @template P - Type of params to pass to the workflow
2089
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
2090
+ * @param params - Params to pass to the workflow
2091
+ * @param options - Optional workflow options
2092
+ * @returns The workflow instance ID
2093
+ *
2094
+ * @example
2095
+ * ```typescript
2096
+ * const workflowId = await this.runWorkflow(
2097
+ * 'MY_WORKFLOW',
2098
+ * { taskId: '123', data: 'process this' }
2099
+ * );
2100
+ * ```
2101
+ */
2102
+ async runWorkflow(workflowName, params, options) {
2103
+ const workflow = this._findWorkflowBindingByName(workflowName);
2104
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
2105
+ const agentBindingName = options?.agentBinding ?? this._findAgentBindingName();
2106
+ if (!agentBindingName) throw new Error("Could not detect Agent binding name from class name. Pass it explicitly via options.agentBinding");
2107
+ const workflowId = options?.id ?? nanoid();
2108
+ const augmentedParams = {
2109
+ ...params,
2110
+ __agentName: this.name,
2111
+ __agentBinding: agentBindingName,
2112
+ __workflowName: workflowName
2113
+ };
2114
+ const instance = await workflow.create({
2115
+ id: workflowId,
2116
+ params: augmentedParams
2117
+ });
2118
+ const id = nanoid();
2119
+ const metadataJson = options?.metadata ? JSON.stringify(options.metadata) : null;
2120
+ try {
2121
+ this.sql`
2122
+ INSERT INTO cf_agents_workflows (id, workflow_id, workflow_name, status, metadata)
2123
+ VALUES (${id}, ${instance.id}, ${workflowName}, 'queued', ${metadataJson})
2124
+ `;
2125
+ } catch (e) {
2126
+ if (e instanceof Error && e.message.includes("UNIQUE constraint failed")) throw new Error(`Workflow with ID "${workflowId}" is already being tracked`);
2127
+ throw e;
2128
+ }
2129
+ this._emit("workflow:start", {
2130
+ workflowId: instance.id,
2131
+ workflowName
2132
+ });
2133
+ return instance.id;
2134
+ }
2135
+ /**
2136
+ * Send an event to a running workflow.
2137
+ * The workflow can wait for this event using step.waitForEvent().
2138
+ *
2139
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
2140
+ * @param workflowId - ID of the workflow instance
2141
+ * @param event - Event to send
2142
+ *
2143
+ * @example
2144
+ * ```typescript
2145
+ * await this.sendWorkflowEvent(
2146
+ * 'MY_WORKFLOW',
2147
+ * workflowId,
2148
+ * { type: 'approval', payload: { approved: true } }
2149
+ * );
2150
+ * ```
2151
+ */
2152
+ async sendWorkflowEvent(workflowName, workflowId, event) {
2153
+ const workflow = this._findWorkflowBindingByName(workflowName);
2154
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
2155
+ const instance = await workflow.get(workflowId);
2156
+ await tryN(3, async () => instance.sendEvent(event), {
2157
+ shouldRetry: isErrorRetryable,
2158
+ baseDelayMs: 200,
2159
+ maxDelayMs: 3e3
2160
+ });
2161
+ this._emit("workflow:event", {
2162
+ workflowId,
2163
+ eventType: event.type
2164
+ });
2165
+ }
2166
+ /**
2167
+ * Approve a waiting workflow.
2168
+ * Sends an approval event to the workflow that can be received by waitForApproval().
2169
+ *
2170
+ * @param workflowId - ID of the workflow to approve
2171
+ * @param data - Optional approval data (reason, metadata)
2172
+ *
2173
+ * @example
2174
+ * ```typescript
2175
+ * await this.approveWorkflow(workflowId, {
2176
+ * reason: 'Approved by admin',
2177
+ * metadata: { approvedBy: userId }
2178
+ * });
2179
+ * ```
2180
+ */
2181
+ async approveWorkflow(workflowId, data) {
2182
+ const workflowInfo = this.getWorkflow(workflowId);
2183
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2184
+ await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
2185
+ type: "approval",
2186
+ payload: {
2187
+ approved: true,
2188
+ reason: data?.reason,
2189
+ metadata: data?.metadata
2190
+ }
2191
+ });
2192
+ this._emit("workflow:approved", {
2193
+ workflowId,
2194
+ reason: data?.reason
2195
+ });
2196
+ }
2197
+ /**
2198
+ * Reject a waiting workflow.
2199
+ * Sends a rejection event to the workflow that will cause waitForApproval() to throw.
2200
+ *
2201
+ * @param workflowId - ID of the workflow to reject
2202
+ * @param data - Optional rejection data (reason)
2203
+ *
2204
+ * @example
2205
+ * ```typescript
2206
+ * await this.rejectWorkflow(workflowId, {
2207
+ * reason: 'Request denied by admin'
2208
+ * });
2209
+ * ```
2210
+ */
2211
+ async rejectWorkflow(workflowId, data) {
2212
+ const workflowInfo = this.getWorkflow(workflowId);
2213
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2214
+ await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
2215
+ type: "approval",
2216
+ payload: {
2217
+ approved: false,
2218
+ reason: data?.reason
2219
+ }
2220
+ });
2221
+ this._emit("workflow:rejected", {
2222
+ workflowId,
2223
+ reason: data?.reason
2224
+ });
2225
+ }
2226
+ /**
2227
+ * Terminate a running workflow.
2228
+ * This immediately stops the workflow and sets its status to "terminated".
2229
+ *
2230
+ * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)
2231
+ * @throws Error if workflow not found in tracking table
2232
+ * @throws Error if workflow binding not found in environment
2233
+ * @throws Error if workflow is already completed/errored/terminated (from Cloudflare)
2234
+ *
2235
+ * @example
2236
+ * ```typescript
2237
+ * await this.terminateWorkflow(workflowId);
2238
+ * ```
2239
+ */
2240
+ async terminateWorkflow(workflowId) {
2241
+ const workflowInfo = this.getWorkflow(workflowId);
2242
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2243
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
2244
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
2245
+ const instance = await workflow.get(workflowId);
2246
+ await tryN(3, async () => instance.terminate(), {
2247
+ shouldRetry: isErrorRetryable,
2248
+ baseDelayMs: 200,
2249
+ maxDelayMs: 3e3
2250
+ });
2251
+ const status = await instance.status();
2252
+ this._updateWorkflowTracking(workflowId, status);
2253
+ this._emit("workflow:terminated", {
2254
+ workflowId,
2255
+ workflowName: workflowInfo.workflowName
2256
+ });
2257
+ }
2258
+ /**
2259
+ * Pause a running workflow.
2260
+ * The workflow can be resumed later with resumeWorkflow().
2261
+ *
2262
+ * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)
2263
+ * @throws Error if workflow not found in tracking table
2264
+ * @throws Error if workflow binding not found in environment
2265
+ * @throws Error if workflow is not running (from Cloudflare)
2266
+ *
2267
+ * @example
2268
+ * ```typescript
2269
+ * await this.pauseWorkflow(workflowId);
2270
+ * ```
2271
+ */
2272
+ async pauseWorkflow(workflowId) {
2273
+ const workflowInfo = this.getWorkflow(workflowId);
2274
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2275
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
2276
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
2277
+ const instance = await workflow.get(workflowId);
2278
+ await tryN(3, async () => instance.pause(), {
2279
+ shouldRetry: isErrorRetryable,
2280
+ baseDelayMs: 200,
2281
+ maxDelayMs: 3e3
2282
+ });
2283
+ const status = await instance.status();
2284
+ this._updateWorkflowTracking(workflowId, status);
2285
+ this._emit("workflow:paused", {
2286
+ workflowId,
2287
+ workflowName: workflowInfo.workflowName
2288
+ });
2289
+ }
2290
+ /**
2291
+ * Resume a paused workflow.
2292
+ *
2293
+ * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)
2294
+ * @throws Error if workflow not found in tracking table
2295
+ * @throws Error if workflow binding not found in environment
2296
+ * @throws Error if workflow is not paused (from Cloudflare)
2297
+ *
2298
+ * @example
2299
+ * ```typescript
2300
+ * await this.resumeWorkflow(workflowId);
2301
+ * ```
2302
+ */
2303
+ async resumeWorkflow(workflowId) {
2304
+ const workflowInfo = this.getWorkflow(workflowId);
2305
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2306
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
2307
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
2308
+ const instance = await workflow.get(workflowId);
2309
+ await tryN(3, async () => instance.resume(), {
2310
+ shouldRetry: isErrorRetryable,
2311
+ baseDelayMs: 200,
2312
+ maxDelayMs: 3e3
2313
+ });
2314
+ const status = await instance.status();
2315
+ this._updateWorkflowTracking(workflowId, status);
2316
+ this._emit("workflow:resumed", {
2317
+ workflowId,
2318
+ workflowName: workflowInfo.workflowName
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Restart a workflow instance.
2323
+ * This re-runs the workflow from the beginning with the same ID.
2324
+ *
2325
+ * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)
2326
+ * @param options - Optional settings
2327
+ * @param options.resetTracking - If true (default), resets created_at and clears error fields.
2328
+ * If false, preserves original timestamps.
2329
+ * @throws Error if workflow not found in tracking table
2330
+ * @throws Error if workflow binding not found in environment
2331
+ *
2332
+ * @example
2333
+ * ```typescript
2334
+ * // Reset tracking (default)
2335
+ * await this.restartWorkflow(workflowId);
2336
+ *
2337
+ * // Preserve original timestamps
2338
+ * await this.restartWorkflow(workflowId, { resetTracking: false });
2339
+ * ```
2340
+ */
2341
+ async restartWorkflow(workflowId, options = {}) {
2342
+ const { resetTracking = true } = options;
2343
+ const workflowInfo = this.getWorkflow(workflowId);
2344
+ if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
2345
+ const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
2346
+ if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
2347
+ const instance = await workflow.get(workflowId);
2348
+ await tryN(3, async () => instance.restart(), {
2349
+ shouldRetry: isErrorRetryable,
2350
+ baseDelayMs: 200,
2351
+ maxDelayMs: 3e3
2352
+ });
2353
+ if (resetTracking) {
2354
+ const now = Math.floor(Date.now() / 1e3);
2355
+ this.sql`
2356
+ UPDATE cf_agents_workflows
2357
+ SET status = 'queued',
2358
+ created_at = ${now},
2359
+ updated_at = ${now},
2360
+ completed_at = NULL,
2361
+ error_name = NULL,
2362
+ error_message = NULL
2363
+ WHERE workflow_id = ${workflowId}
2364
+ `;
2365
+ } else {
2366
+ const status = await instance.status();
2367
+ this._updateWorkflowTracking(workflowId, status);
2368
+ }
2369
+ this._emit("workflow:restarted", {
2370
+ workflowId,
2371
+ workflowName: workflowInfo.workflowName
2372
+ });
2373
+ }
2374
+ /**
2375
+ * Find a workflow binding by its name.
2376
+ */
2377
+ _findWorkflowBindingByName(workflowName) {
2378
+ const binding = this.env[workflowName];
2379
+ if (binding && typeof binding === "object" && "create" in binding && "get" in binding) return binding;
2380
+ }
2381
+ /**
2382
+ * Get all workflow binding names from the environment.
2383
+ */
2384
+ _getWorkflowBindingNames() {
2385
+ const names = [];
2386
+ for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "create" in value && "get" in value) names.push(key);
2387
+ return names;
2388
+ }
2389
+ /**
2390
+ * Get the status of a workflow and update the tracking record.
2391
+ *
2392
+ * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
2393
+ * @param workflowId - ID of the workflow instance
2394
+ * @returns The workflow status
2395
+ */
2396
+ async getWorkflowStatus(workflowName, workflowId) {
2397
+ const workflow = this._findWorkflowBindingByName(workflowName);
2398
+ if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
2399
+ const status = await (await workflow.get(workflowId)).status();
2400
+ this._updateWorkflowTracking(workflowId, status);
2401
+ return status;
2402
+ }
2403
+ /**
2404
+ * Get a tracked workflow by ID.
2405
+ *
2406
+ * @param workflowId - Workflow instance ID
2407
+ * @returns Workflow info or undefined if not found
2408
+ */
2409
+ getWorkflow(workflowId) {
2410
+ const rows = this.sql`
2411
+ SELECT * FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
2412
+ `;
2413
+ if (!rows || rows.length === 0) return;
2414
+ return this._rowToWorkflowInfo(rows[0]);
2415
+ }
2416
+ /**
2417
+ * Query tracked workflows with cursor-based pagination.
2418
+ *
2419
+ * @param criteria - Query criteria including optional cursor for pagination
2420
+ * @returns WorkflowPage with workflows, total count, and next cursor
2421
+ *
2422
+ * @example
2423
+ * ```typescript
2424
+ * // First page
2425
+ * const page1 = this.getWorkflows({ status: 'running', limit: 20 });
2426
+ *
2427
+ * // Next page
2428
+ * if (page1.nextCursor) {
2429
+ * const page2 = this.getWorkflows({
2430
+ * status: 'running',
2431
+ * limit: 20,
2432
+ * cursor: page1.nextCursor
2433
+ * });
2434
+ * }
2435
+ * ```
2436
+ */
2437
+ getWorkflows(criteria = {}) {
2438
+ const limit = Math.min(criteria.limit ?? 50, 100);
2439
+ const isAsc = criteria.orderBy === "asc";
2440
+ const total = this._countWorkflows(criteria);
2441
+ let query = "SELECT * FROM cf_agents_workflows WHERE 1=1";
2442
+ const params = [];
2443
+ if (criteria.status) {
2444
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
2445
+ const placeholders = statuses.map(() => "?").join(", ");
2446
+ query += ` AND status IN (${placeholders})`;
2447
+ params.push(...statuses);
2448
+ }
2449
+ if (criteria.workflowName) {
2450
+ query += " AND workflow_name = ?";
2451
+ params.push(criteria.workflowName);
2452
+ }
2453
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
2454
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
2455
+ params.push(key, value);
2456
+ }
2457
+ if (criteria.cursor) {
2458
+ const cursor = this._decodeCursor(criteria.cursor);
2459
+ if (isAsc) query += " AND (created_at > ? OR (created_at = ? AND workflow_id > ?))";
2460
+ else query += " AND (created_at < ? OR (created_at = ? AND workflow_id < ?))";
2461
+ params.push(cursor.createdAt, cursor.createdAt, cursor.workflowId);
2462
+ }
2463
+ query += ` ORDER BY created_at ${isAsc ? "ASC" : "DESC"}, workflow_id ${isAsc ? "ASC" : "DESC"}`;
2464
+ query += " LIMIT ?";
2465
+ params.push(limit + 1);
2466
+ const rows = this.ctx.storage.sql.exec(query, ...params).toArray();
2467
+ const hasMore = rows.length > limit;
2468
+ const workflows = (hasMore ? rows.slice(0, limit) : rows).map((row) => this._rowToWorkflowInfo(row));
2469
+ return {
2470
+ workflows,
2471
+ total,
2472
+ nextCursor: hasMore && workflows.length > 0 ? this._encodeCursor(workflows[workflows.length - 1]) : null
2473
+ };
2474
+ }
2475
+ /**
2476
+ * Count workflows matching criteria (for pagination total).
2477
+ */
2478
+ _countWorkflows(criteria) {
2479
+ let query = "SELECT COUNT(*) as count FROM cf_agents_workflows WHERE 1=1";
2480
+ const params = [];
2481
+ if (criteria.status) {
2482
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
2483
+ const placeholders = statuses.map(() => "?").join(", ");
2484
+ query += ` AND status IN (${placeholders})`;
2485
+ params.push(...statuses);
2486
+ }
2487
+ if (criteria.workflowName) {
2488
+ query += " AND workflow_name = ?";
2489
+ params.push(criteria.workflowName);
2490
+ }
2491
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
2492
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
2493
+ params.push(key, value);
2494
+ }
2495
+ if (criteria.createdBefore) {
2496
+ query += " AND created_at < ?";
2497
+ params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
2498
+ }
2499
+ return this.ctx.storage.sql.exec(query, ...params).toArray()[0]?.count ?? 0;
2500
+ }
2501
+ /**
2502
+ * Encode a cursor from workflow info for pagination.
2503
+ * Stores createdAt as Unix timestamp in seconds (matching DB storage).
2504
+ */
2505
+ _encodeCursor(workflow) {
2506
+ return btoa(JSON.stringify({
2507
+ c: Math.floor(workflow.createdAt.getTime() / 1e3),
2508
+ i: workflow.workflowId
2509
+ }));
2510
+ }
2511
+ /**
2512
+ * Decode a pagination cursor.
2513
+ * Returns createdAt as Unix timestamp in seconds (matching DB storage).
2514
+ */
2515
+ _decodeCursor(cursor) {
2516
+ try {
2517
+ const data = JSON.parse(atob(cursor));
2518
+ if (typeof data.c !== "number" || typeof data.i !== "string") throw new Error("Invalid cursor structure");
2519
+ return {
2520
+ createdAt: data.c,
2521
+ workflowId: data.i
2522
+ };
2523
+ } catch {
2524
+ throw new Error("Invalid pagination cursor. The cursor may be malformed or corrupted.");
2525
+ }
2526
+ }
2527
+ /**
2528
+ * Delete a workflow tracking record.
2529
+ *
2530
+ * @param workflowId - ID of the workflow to delete
2531
+ * @returns true if a record was deleted, false if not found
2532
+ */
2533
+ deleteWorkflow(workflowId) {
2534
+ const existing = this.sql`
2535
+ SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
2536
+ `;
2537
+ if (!existing[0] || existing[0].count === 0) return false;
2538
+ this.sql`DELETE FROM cf_agents_workflows WHERE workflow_id = ${workflowId}`;
2539
+ return true;
2540
+ }
2541
+ /**
2542
+ * Delete workflow tracking records matching criteria.
2543
+ * Useful for cleaning up old completed/errored workflows.
2544
+ *
2545
+ * @param criteria - Criteria for which workflows to delete
2546
+ * @returns Number of records matching criteria (expected deleted count)
2547
+ *
2548
+ * @example
2549
+ * ```typescript
2550
+ * // Delete all completed workflows created more than 7 days ago
2551
+ * const deleted = this.deleteWorkflows({
2552
+ * status: 'complete',
2553
+ * createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
2554
+ * });
2555
+ *
2556
+ * // Delete all errored and terminated workflows
2557
+ * const deleted = this.deleteWorkflows({
2558
+ * status: ['errored', 'terminated']
2559
+ * });
2560
+ * ```
2561
+ */
2562
+ deleteWorkflows(criteria = {}) {
2563
+ let query = "DELETE FROM cf_agents_workflows WHERE 1=1";
2564
+ const params = [];
2565
+ if (criteria.status) {
2566
+ const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
2567
+ const placeholders = statuses.map(() => "?").join(", ");
2568
+ query += ` AND status IN (${placeholders})`;
2569
+ params.push(...statuses);
2570
+ }
2571
+ if (criteria.workflowName) {
2572
+ query += " AND workflow_name = ?";
2573
+ params.push(criteria.workflowName);
2574
+ }
2575
+ if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
2576
+ query += ` AND json_extract(metadata, '$.' || ?) = ?`;
2577
+ params.push(key, value);
2578
+ }
2579
+ if (criteria.createdBefore) {
2580
+ query += " AND created_at < ?";
2581
+ params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
2582
+ }
2583
+ return this.ctx.storage.sql.exec(query, ...params).rowsWritten;
2584
+ }
2585
+ /**
2586
+ * Migrate workflow tracking records from an old binding name to a new one.
2587
+ * Use this after renaming a workflow binding in wrangler.toml.
2588
+ *
2589
+ * @param oldName - Previous workflow binding name
2590
+ * @param newName - New workflow binding name
2591
+ * @returns Number of records migrated
2592
+ *
2593
+ * @example
2594
+ * ```typescript
2595
+ * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml
2596
+ * async onStart() {
2597
+ * const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');
2598
+ * }
2599
+ * ```
2600
+ */
2601
+ migrateWorkflowBinding(oldName, newName) {
2602
+ if (!this._findWorkflowBindingByName(newName)) throw new Error(`Workflow binding '${newName}' not found in environment`);
2603
+ const count = this.sql`
2604
+ SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_name = ${oldName}
2605
+ `[0]?.count ?? 0;
2606
+ if (count > 0) {
2607
+ this.sql`UPDATE cf_agents_workflows SET workflow_name = ${newName} WHERE workflow_name = ${oldName}`;
2608
+ console.log(`[Agent] Migrated ${count} workflow(s) from '${oldName}' to '${newName}'`);
2609
+ }
2610
+ return count;
2611
+ }
2612
+ /**
2613
+ * Update workflow tracking record from InstanceStatus
2614
+ */
2615
+ _updateWorkflowTracking(workflowId, status) {
2616
+ const statusName = status.status;
2617
+ const now = Math.floor(Date.now() / 1e3);
2618
+ const completedAt = [
2619
+ "complete",
2620
+ "errored",
2621
+ "terminated"
2622
+ ].includes(statusName) ? now : null;
2623
+ const errorName = status.error?.name ?? null;
2624
+ const errorMessage = status.error?.message ?? null;
2625
+ this.sql`
2626
+ UPDATE cf_agents_workflows
2627
+ SET status = ${statusName},
2628
+ error_name = ${errorName},
2629
+ error_message = ${errorMessage},
2630
+ updated_at = ${now},
2631
+ completed_at = ${completedAt}
2632
+ WHERE workflow_id = ${workflowId}
2633
+ `;
2634
+ }
2635
+ /**
2636
+ * Convert a database row to WorkflowInfo
2637
+ */
2638
+ _rowToWorkflowInfo(row) {
2639
+ return {
2640
+ id: row.id,
2641
+ workflowId: row.workflow_id,
2642
+ workflowName: row.workflow_name,
2643
+ status: row.status,
2644
+ metadata: row.metadata ? JSON.parse(row.metadata) : null,
2645
+ error: row.error_name ? {
2646
+ name: row.error_name,
2647
+ message: row.error_message ?? ""
2648
+ } : null,
2649
+ createdAt: /* @__PURE__ */ new Date(row.created_at * 1e3),
2650
+ updatedAt: /* @__PURE__ */ new Date(row.updated_at * 1e3),
2651
+ completedAt: row.completed_at ? /* @__PURE__ */ new Date(row.completed_at * 1e3) : null
2652
+ };
2653
+ }
2654
+ /**
2655
+ * Find the binding name for this Agent's namespace by matching class name.
2656
+ * Returns undefined if no match found - use options.agentBinding as fallback.
2657
+ */
2658
+ _findAgentBindingName() {
2659
+ const className = this._ParentClass.name;
2660
+ for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
2661
+ if (key === className || camelCaseToKebabCase(key) === camelCaseToKebabCase(className)) return key;
2662
+ }
2663
+ }
2664
+ _findBindingNameForNamespace(namespace) {
2665
+ for (const [key, value] of Object.entries(this.env)) if (value === namespace) return key;
2666
+ }
2667
+ async _restoreRpcMcpServers() {
2668
+ const rpcServers = this.mcp.getRpcServersFromStorage();
2669
+ for (const server of rpcServers) {
2670
+ if (this.mcp.mcpConnections[server.id]) continue;
2671
+ const opts = server.server_options ? JSON.parse(server.server_options) : {};
2672
+ const namespace = this.env[opts.bindingName];
2673
+ if (!namespace) {
2674
+ console.warn(`[Agent] Cannot restore RPC MCP server "${server.name}": binding "${opts.bindingName}" not found in env`);
2675
+ continue;
2676
+ }
2677
+ const normalizedName = server.server_url.replace(RPC_DO_PREFIX, "");
2678
+ try {
2679
+ await this.mcp.connect(`${RPC_DO_PREFIX}${normalizedName}`, {
2680
+ reconnect: { id: server.id },
2681
+ transport: {
2682
+ type: "rpc",
2683
+ namespace,
2684
+ name: normalizedName,
2685
+ props: opts.props
2686
+ }
2687
+ });
2688
+ const conn = this.mcp.mcpConnections[server.id];
2689
+ if (conn && conn.connectionState === MCPConnectionState.CONNECTED) await this.mcp.discoverIfConnected(server.id);
2690
+ } catch (error) {
2691
+ console.error(`[Agent] Error restoring RPC MCP server "${server.name}":`, error);
2692
+ }
2693
+ }
2694
+ }
2695
+ /**
2696
+ * Handle a callback from a workflow.
2697
+ * Called when the Agent receives a callback at /_workflow/callback.
2698
+ * Override this to handle all callback types in one place.
2699
+ *
2700
+ * @param callback - The callback payload
2701
+ */
2702
+ async onWorkflowCallback(callback) {
2703
+ const now = Math.floor(Date.now() / 1e3);
2704
+ switch (callback.type) {
2705
+ case "progress":
2706
+ this.sql`
2707
+ UPDATE cf_agents_workflows
2708
+ SET status = 'running', updated_at = ${now}
2709
+ WHERE workflow_id = ${callback.workflowId} AND status IN ('queued', 'waiting')
2710
+ `;
2711
+ await this.onWorkflowProgress(callback.workflowName, callback.workflowId, callback.progress);
2712
+ break;
2713
+ case "complete":
2714
+ this.sql`
2715
+ UPDATE cf_agents_workflows
2716
+ SET status = 'complete', updated_at = ${now}, completed_at = ${now}
2717
+ WHERE workflow_id = ${callback.workflowId}
2718
+ AND status NOT IN ('terminated', 'paused')
2719
+ `;
2720
+ await this.onWorkflowComplete(callback.workflowName, callback.workflowId, callback.result);
2721
+ break;
2722
+ case "error":
2723
+ this.sql`
2724
+ UPDATE cf_agents_workflows
2725
+ SET status = 'errored', updated_at = ${now}, completed_at = ${now},
2726
+ error_name = 'WorkflowError', error_message = ${callback.error}
2727
+ WHERE workflow_id = ${callback.workflowId}
2728
+ AND status NOT IN ('terminated', 'paused')
2729
+ `;
2730
+ await this.onWorkflowError(callback.workflowName, callback.workflowId, callback.error);
2731
+ break;
2732
+ case "event":
2733
+ await this.onWorkflowEvent(callback.workflowName, callback.workflowId, callback.event);
2734
+ break;
2735
+ }
2736
+ }
2737
+ /**
2738
+ * Called when a workflow reports progress.
2739
+ * Override to handle progress updates.
2740
+ *
2741
+ * @param workflowName - Workflow binding name
2742
+ * @param workflowId - ID of the workflow
2743
+ * @param progress - Typed progress data (default: DefaultProgress)
2744
+ */
2745
+ async onWorkflowProgress(workflowName, workflowId, progress) {}
2746
+ /**
2747
+ * Called when a workflow completes successfully.
2748
+ * Override to handle completion.
2749
+ *
2750
+ * @param workflowName - Workflow binding name
2751
+ * @param workflowId - ID of the workflow
2752
+ * @param result - Optional result data
2753
+ */
2754
+ async onWorkflowComplete(workflowName, workflowId, result) {}
2755
+ /**
2756
+ * Called when a workflow encounters an error.
2757
+ * Override to handle errors.
2758
+ *
2759
+ * @param workflowName - Workflow binding name
2760
+ * @param workflowId - ID of the workflow
2761
+ * @param error - Error message
2762
+ */
2763
+ async onWorkflowError(workflowName, workflowId, error) {
2764
+ console.error(`Workflow error [${workflowName}/${workflowId}]: ${error}\nOverride onWorkflowError() in your Agent to handle workflow errors.`);
2765
+ }
2766
+ /**
2767
+ * Called when a workflow sends a custom event.
2768
+ * Override to handle custom events.
2769
+ *
2770
+ * @param workflowName - Workflow binding name
2771
+ * @param workflowId - ID of the workflow
2772
+ * @param event - Custom event payload
2773
+ */
2774
+ async onWorkflowEvent(workflowName, workflowId, event) {}
2775
+ /**
2776
+ * Handle a workflow callback via RPC.
2777
+ * @internal - Called by AgentWorkflow, do not call directly
2778
+ */
2779
+ async _workflow_handleCallback(callback) {
2780
+ await this.__unsafe_ensureInitialized();
2781
+ await this.onWorkflowCallback(callback);
2782
+ }
2783
+ /**
2784
+ * Broadcast a message to all connected clients via RPC.
2785
+ * @internal - Called by AgentWorkflow, do not call directly
2786
+ */
2787
+ async _workflow_broadcast(message) {
2788
+ await this.__unsafe_ensureInitialized();
2789
+ this.broadcast(JSON.stringify(message));
2790
+ }
2791
+ /**
2792
+ * Update agent state via RPC.
2793
+ * @internal - Called by AgentWorkflow, do not call directly
2794
+ */
2795
+ async _workflow_updateState(action, state) {
2796
+ await this.__unsafe_ensureInitialized();
2797
+ if (action === "set") this.setState(state);
2798
+ else if (action === "merge") {
2799
+ const currentState = this.state ?? {};
2800
+ this.setState({
2801
+ ...currentState,
2802
+ ...state
2803
+ });
2804
+ } else if (action === "reset") this.setState(this.initialState);
2805
+ }
2806
+ async addMcpServer(serverName, urlOrBinding, callbackHostOrOptions, agentsPrefix, options) {
2807
+ const isHttpTransport = typeof urlOrBinding === "string";
2808
+ const normalizedUrl = isHttpTransport ? new URL(urlOrBinding).href : void 0;
2809
+ const existingServer = this.mcp.listServers().find((s) => s.name === serverName && (!isHttpTransport || new URL(s.server_url).href === normalizedUrl));
2810
+ if (existingServer && this.mcp.mcpConnections[existingServer.id]) {
2811
+ const conn = this.mcp.mcpConnections[existingServer.id];
2812
+ if (conn.connectionState === MCPConnectionState.AUTHENTICATING && conn.options.transport.authProvider?.authUrl) return {
2813
+ id: existingServer.id,
2814
+ state: MCPConnectionState.AUTHENTICATING,
2815
+ authUrl: conn.options.transport.authProvider.authUrl
2816
+ };
2817
+ if (conn.connectionState === MCPConnectionState.FAILED) throw new Error(`MCP server "${serverName}" is in failed state: ${conn.connectionError}`);
2818
+ return {
2819
+ id: existingServer.id,
2820
+ state: MCPConnectionState.READY
2821
+ };
2822
+ }
2823
+ if (typeof urlOrBinding !== "string") {
2824
+ const rpcOpts = callbackHostOrOptions;
2825
+ const normalizedName = serverName.toLowerCase().replace(/\s+/g, "-");
2826
+ const reconnectId = existingServer?.id;
2827
+ const { id } = await this.mcp.connect(`${RPC_DO_PREFIX}${normalizedName}`, {
2828
+ reconnect: reconnectId ? { id: reconnectId } : void 0,
2829
+ transport: {
2830
+ type: "rpc",
2831
+ namespace: urlOrBinding,
2832
+ name: normalizedName,
2833
+ props: rpcOpts?.props
2834
+ }
2835
+ });
2836
+ const conn = this.mcp.mcpConnections[id];
2837
+ if (conn && conn.connectionState === MCPConnectionState.CONNECTED) {
2838
+ const discoverResult = await this.mcp.discoverIfConnected(id);
2839
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
2840
+ } else if (conn && conn.connectionState === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server "${serverName}" via RPC: ${conn.connectionError}`);
2841
+ const bindingName = this._findBindingNameForNamespace(urlOrBinding);
2842
+ if (bindingName) this.mcp.saveRpcServerToStorage(id, serverName, normalizedName, bindingName, rpcOpts?.props);
2843
+ return {
2844
+ id,
2845
+ state: MCPConnectionState.READY
2846
+ };
2847
+ }
2848
+ const httpOptions = callbackHostOrOptions;
2849
+ let resolvedCallbackHost;
2850
+ let resolvedAgentsPrefix;
2851
+ let resolvedOptions;
2852
+ let resolvedCallbackPath;
2853
+ if (typeof httpOptions === "object" && httpOptions !== null) {
2854
+ resolvedCallbackHost = httpOptions.callbackHost;
2855
+ resolvedCallbackPath = httpOptions.callbackPath;
2856
+ resolvedAgentsPrefix = httpOptions.agentsPrefix ?? "agents";
2857
+ resolvedOptions = {
2858
+ client: httpOptions.client,
2859
+ transport: httpOptions.transport,
2860
+ retry: httpOptions.retry
2861
+ };
2862
+ } else {
2863
+ resolvedCallbackHost = httpOptions;
2864
+ resolvedAgentsPrefix = agentsPrefix ?? "agents";
2865
+ resolvedOptions = options;
2866
+ }
2867
+ if (!this._resolvedOptions.sendIdentityOnConnect && resolvedCallbackHost && !resolvedCallbackPath) throw new Error("callbackPath is required in addMcpServer options when sendIdentityOnConnect is false — the default callback URL would expose the instance name. Provide a callbackPath and route the callback request to this agent via getAgentByName.");
2868
+ if (!resolvedCallbackHost) {
2869
+ const { request, connection } = getCurrentAgent();
2870
+ if (request) {
2871
+ const requestUrl = new URL(request.url);
2872
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
2873
+ } else if (connection?.uri) {
2874
+ const connectionUrl = new URL(connection.uri);
2875
+ resolvedCallbackHost = `${connectionUrl.protocol}//${connectionUrl.host}`;
2876
+ }
2877
+ }
2878
+ let callbackUrl;
2879
+ if (resolvedCallbackHost) {
2880
+ const normalizedHost = resolvedCallbackHost.replace(/\/$/, "");
2881
+ callbackUrl = resolvedCallbackPath ? `${normalizedHost}/${resolvedCallbackPath.replace(/^\//, "")}` : `${normalizedHost}/${resolvedAgentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
2882
+ }
2883
+ const id = nanoid(8);
2884
+ let authProvider;
2885
+ if (callbackUrl) {
2886
+ authProvider = this.createMcpOAuthProvider(callbackUrl);
2887
+ authProvider.serverId = id;
2888
+ }
2889
+ const transportType = resolvedOptions?.transport?.type ?? "auto";
2890
+ let headerTransportOpts = {};
2891
+ if (resolvedOptions?.transport?.headers) headerTransportOpts = {
2892
+ eventSourceInit: { fetch: (url, init) => fetch(url, {
2893
+ ...init,
2894
+ headers: resolvedOptions?.transport?.headers
2895
+ }) },
2896
+ requestInit: { headers: resolvedOptions?.transport?.headers }
2897
+ };
2898
+ await this.mcp.registerServer(id, {
2899
+ url: normalizedUrl,
2900
+ name: serverName,
2901
+ callbackUrl,
2902
+ client: resolvedOptions?.client,
2903
+ transport: {
2904
+ ...headerTransportOpts,
2905
+ authProvider,
2906
+ type: transportType
2907
+ },
2908
+ retry: resolvedOptions?.retry
2909
+ });
2910
+ const result = await this.mcp.connectToServer(id);
2911
+ if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${normalizedUrl}: ${result.error}`);
2912
+ if (result.state === MCPConnectionState.AUTHENTICATING) {
2913
+ if (!callbackUrl) throw new Error("This MCP server requires OAuth authentication. Provide callbackHost in addMcpServer options to enable the OAuth flow.");
2914
+ return {
2915
+ id,
2916
+ state: result.state,
2917
+ authUrl: result.authUrl
2918
+ };
2919
+ }
2920
+ const discoverResult = await this.mcp.discoverIfConnected(id);
2921
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
2922
+ return {
2923
+ id,
2924
+ state: MCPConnectionState.READY
2925
+ };
2926
+ }
2927
+ async removeMcpServer(id) {
2928
+ await this.mcp.removeServer(id);
2929
+ }
2930
+ getMcpServers() {
2931
+ const mcpState = {
2932
+ prompts: this.mcp.listPrompts(),
2933
+ resources: this.mcp.listResources(),
2934
+ servers: {},
2935
+ tools: this.mcp.listTools()
2936
+ };
2937
+ const servers = this.mcp.listServers();
2938
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
2939
+ const serverConn = this.mcp.mcpConnections[server.id];
2940
+ let defaultState = "not-connected";
2941
+ if (!serverConn && server.auth_url) defaultState = "authenticating";
2942
+ mcpState.servers[server.id] = {
2943
+ auth_url: server.auth_url,
2944
+ capabilities: serverConn?.serverCapabilities ?? null,
2945
+ error: sanitizeErrorString(serverConn?.connectionError ?? null),
2946
+ instructions: serverConn?.instructions ?? null,
2947
+ name: server.name,
2948
+ server_url: server.server_url,
2949
+ state: serverConn?.connectionState ?? defaultState
2950
+ };
2951
+ }
2952
+ return mcpState;
2953
+ }
2954
+ /**
2955
+ * Create the OAuth provider used when connecting to MCP servers that require authentication.
2956
+ *
2957
+ * Override this method in a subclass to supply a custom OAuth provider implementation,
2958
+ * for example to use pre-registered client credentials, mTLS-based authentication,
2959
+ * or any other OAuth flow beyond dynamic client registration.
2960
+ *
2961
+ * @example
2962
+ * // Custom OAuth provider
2963
+ * class MyAgent extends Agent {
2964
+ * createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
2965
+ * return new MyCustomOAuthProvider(
2966
+ * this.ctx.storage,
2967
+ * this.name,
2968
+ * callbackUrl
2969
+ * );
2970
+ * }
2971
+ * }
2972
+ *
2973
+ * @param callbackUrl The OAuth callback URL for the authorization flow
2974
+ * @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer}
2975
+ */
2976
+ createMcpOAuthProvider(callbackUrl) {
2977
+ return new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
2978
+ }
2979
+ broadcastMcpServers() {
2980
+ this._broadcastProtocol(JSON.stringify({
2981
+ mcp: this.getMcpServers(),
2982
+ type: MessageType.CF_AGENT_MCP_SERVERS
2983
+ }));
2984
+ }
2985
+ /**
2986
+ * Handle MCP OAuth callback request if it's an OAuth callback.
2987
+ *
2988
+ * This method encapsulates the entire OAuth callback flow:
2989
+ * 1. Checks if the request is an MCP OAuth callback
2990
+ * 2. Processes the OAuth code exchange
2991
+ * 3. Establishes the connection if successful
2992
+ * 4. Broadcasts MCP server state updates
2993
+ * 5. Returns the appropriate HTTP response
2994
+ *
2995
+ * @param request The incoming HTTP request
2996
+ * @returns Response if this was an OAuth callback, null otherwise
2997
+ */
2998
+ async handleMcpOAuthCallback(request) {
2999
+ if (!this.mcp.isCallbackRequest(request)) return null;
3000
+ const result = await this.mcp.handleCallbackRequest(request);
3001
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
3002
+ console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
3003
+ });
3004
+ this.broadcastMcpServers();
3005
+ return this.handleOAuthCallbackResponse(result, request);
3006
+ }
3007
+ /**
3008
+ * Handle OAuth callback response using MCPClientManager configuration
3009
+ * @param result OAuth callback result
3010
+ * @param request The original request (needed for base URL)
3011
+ * @returns Response for the OAuth callback
3012
+ */
3013
+ handleOAuthCallbackResponse(result, request) {
3014
+ const config = this.mcp.getOAuthCallbackConfig();
3015
+ if (config?.customHandler) return config.customHandler(result);
3016
+ const baseOrigin = new URL(request.url).origin;
3017
+ if (config?.successRedirect && result.authSuccess) try {
3018
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
3019
+ } catch (e) {
3020
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
3021
+ return Response.redirect(baseOrigin);
3022
+ }
3023
+ if (config?.errorRedirect && !result.authSuccess) try {
3024
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
3025
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
3026
+ } catch (e) {
3027
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
3028
+ return Response.redirect(baseOrigin);
3029
+ }
3030
+ return Response.redirect(baseOrigin);
3031
+ }
3032
+ };
3033
+ Agent.options = { hibernate: true };
3034
+ const wrappedClasses = /* @__PURE__ */ new Set();
3035
+ /**
3036
+ * Route a request to the appropriate Agent
3037
+ * @param request Request to route
3038
+ * @param env Environment containing Agent bindings
3039
+ * @param options Routing options
3040
+ * @returns Response from the Agent or undefined if no route matched
3041
+ */
3042
+ async function routeAgentRequest(request, env, options) {
3043
+ return routePartykitRequest(request, env, {
3044
+ prefix: "agents",
3045
+ ...options
3046
+ });
3047
+ }
3048
+ var _email = /* @__PURE__ */ new WeakMap();
3049
+ _Symbol$dispose = Symbol.dispose;
3050
+ var EmailBridge = class extends RpcTarget {
3051
+ constructor(email) {
3052
+ super();
3053
+ _classPrivateFieldInitSpec(this, _email, void 0);
3054
+ _classPrivateFieldSet2(_email, this, email);
3055
+ }
3056
+ async getRaw() {
3057
+ const reader = _classPrivateFieldGet2(_email, this).raw.getReader();
3058
+ const chunks = [];
3059
+ let done = false;
3060
+ while (!done) {
3061
+ const { value, done: readerDone } = await reader.read();
3062
+ done = readerDone;
3063
+ if (value) chunks.push(value);
3064
+ }
3065
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
3066
+ const combined = new Uint8Array(totalLength);
3067
+ let offset = 0;
3068
+ for (const chunk of chunks) {
3069
+ combined.set(chunk, offset);
3070
+ offset += chunk.length;
3071
+ }
3072
+ return combined;
3073
+ }
3074
+ setReject(reason) {
3075
+ _classPrivateFieldGet2(_email, this).setReject(reason);
3076
+ }
3077
+ forward(rcptTo, headers) {
3078
+ return _classPrivateFieldGet2(_email, this).forward(rcptTo, headers);
3079
+ }
3080
+ reply(options) {
3081
+ return _classPrivateFieldGet2(_email, this).reply(new EmailMessage(options.from, options.to, options.raw));
3082
+ }
3083
+ [_Symbol$dispose]() {}
3084
+ };
3085
+ const agentMapCache = /* @__PURE__ */ new WeakMap();
3086
+ /**
3087
+ * Route an email to the appropriate Agent
3088
+ * @param email The email to route
3089
+ * @param env The environment containing the Agent bindings
3090
+ * @param options The options for routing the email
3091
+ * @returns A promise that resolves when the email has been routed
3092
+ */
3093
+ async function routeAgentEmail(email, env, options) {
3094
+ const routingInfo = await options.resolver(email, env);
3095
+ if (!routingInfo) {
3096
+ if (options.onNoRoute) await options.onNoRoute(email);
3097
+ else console.warn("No routing information found for email, dropping message");
3098
+ return;
3099
+ }
3100
+ if (!agentMapCache.has(env)) {
3101
+ const map = {};
3102
+ const originalNames = [];
3103
+ for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
3104
+ map[key] = value;
3105
+ map[camelCaseToKebabCase(key)] = value;
3106
+ map[key.toLowerCase()] = value;
3107
+ originalNames.push(key);
3108
+ }
3109
+ agentMapCache.set(env, {
3110
+ map,
3111
+ originalNames
3112
+ });
3113
+ }
3114
+ const cached = agentMapCache.get(env);
3115
+ const namespace = cached.map[routingInfo.agentName];
3116
+ if (!namespace) {
3117
+ const availableAgents = cached.originalNames.join(", ");
3118
+ throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
3119
+ }
3120
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
3121
+ const bridge = new EmailBridge(email);
3122
+ await agent._onEmail({
3123
+ from: email.from,
3124
+ to: email.to,
3125
+ headers: email.headers,
3126
+ rawSize: email.rawSize,
3127
+ _secureRouted: routingInfo._secureRouted,
3128
+ _bridge: bridge
3129
+ });
3130
+ }
3131
+ /**
3132
+ * Get or create an Agent by name
3133
+ * @template Env Environment type containing bindings
3134
+ * @template T Type of the Agent class
3135
+ * @param namespace Agent namespace
3136
+ * @param name Name of the Agent instance
3137
+ * @param options Options for Agent creation
3138
+ * @returns Promise resolving to an Agent instance stub
3139
+ */
3140
+ async function getAgentByName(namespace, name, options) {
3141
+ return getServerByName(namespace, name, options);
3142
+ }
3143
+ /**
3144
+ * A wrapper for streaming responses in callable methods
3145
+ */
3146
+ var StreamingResponse = class {
3147
+ constructor(connection, id) {
3148
+ this._closed = false;
3149
+ this._connection = connection;
3150
+ this._id = id;
3151
+ }
3152
+ /**
3153
+ * Whether the stream has been closed (via end() or error())
3154
+ */
3155
+ get isClosed() {
3156
+ return this._closed;
3157
+ }
3158
+ /**
3159
+ * Send a chunk of data to the client
3160
+ * @param chunk The data to send
3161
+ * @returns false if stream is already closed (no-op), true if sent
3162
+ */
3163
+ send(chunk) {
3164
+ if (this._closed) {
3165
+ console.warn("StreamingResponse.send() called after stream was closed - data not sent");
3166
+ return false;
3167
+ }
3168
+ const response = {
3169
+ done: false,
3170
+ id: this._id,
3171
+ result: chunk,
3172
+ success: true,
3173
+ type: MessageType.RPC
3174
+ };
3175
+ this._connection.send(JSON.stringify(response));
3176
+ return true;
3177
+ }
3178
+ /**
3179
+ * End the stream and send the final chunk (if any)
3180
+ * @param finalChunk Optional final chunk of data to send
3181
+ * @returns false if stream is already closed (no-op), true if sent
3182
+ */
3183
+ end(finalChunk) {
3184
+ if (this._closed) return false;
3185
+ this._closed = true;
3186
+ const response = {
3187
+ done: true,
3188
+ id: this._id,
3189
+ result: finalChunk,
3190
+ success: true,
3191
+ type: MessageType.RPC
3192
+ };
3193
+ this._connection.send(JSON.stringify(response));
3194
+ return true;
3195
+ }
3196
+ /**
3197
+ * Send an error to the client and close the stream
3198
+ * @param message Error message to send
3199
+ * @returns false if stream is already closed (no-op), true if sent
3200
+ */
3201
+ error(message) {
3202
+ if (this._closed) return false;
3203
+ this._closed = true;
3204
+ const response = {
3205
+ error: message,
3206
+ id: this._id,
3207
+ success: false,
3208
+ type: MessageType.RPC
3209
+ };
3210
+ this._connection.send(JSON.stringify(response));
3211
+ return true;
3212
+ }
3213
+ };
3214
+ //#endregion
3215
+ export { callable as a, routeAgentEmail as c, 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 };
3216
+
3217
+ //# sourceMappingURL=src-B8NZxxsO.js.map