agents 0.10.2 → 0.11.0

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