agents 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3,13 +3,15 @@ import {
3
3
  __DO_NOT_USE_WILL_BREAK__agentContext
4
4
  } from "./internal_context.js";
5
5
  import { EmailResolver, createHeaderBasedEmailResolver } from "./email.js";
6
+ import { RetryOptions } from "./retries.js";
6
7
  import {
7
8
  l as TransportType,
8
9
  r as MCPConnectionState
9
- } from "./client-storage-Cvy5r9FG.js";
10
+ } from "./client-storage-D633wI1S.js";
10
11
  import {
11
12
  AgentMcpOAuthProvider,
12
- AgentsOAuthProvider
13
+ AgentsOAuthProvider,
14
+ DurableObjectOAuthClientProvider
13
15
  } from "./mcp/do-oauth-client-provider.js";
14
16
  import { MCPClientManager } from "./mcp/client.js";
15
17
  import {
@@ -119,6 +121,7 @@ type QueueItem<T = string> = {
119
121
  payload: T;
120
122
  callback: keyof Agent<Cloudflare.Env>;
121
123
  created_at: number;
124
+ retry?: RetryOptions;
122
125
  };
123
126
  /**
124
127
  * Represents a scheduled task within an Agent
@@ -127,7 +130,8 @@ type QueueItem<T = string> = {
127
130
  type Schedule<T = string> = {
128
131
  /** Unique identifier for the schedule */ id: string /** Name of the method to be called */;
129
132
  callback: string /** Data to be passed to the callback */;
130
- payload: T;
133
+ payload: T /** Retry options for callback execution */;
134
+ retry?: RetryOptions;
131
135
  } & (
132
136
  | {
133
137
  /** Type of schedule for one-time execution at a specific time */ type: "scheduled" /** Timestamp when the task should execute */;
@@ -174,7 +178,7 @@ type MCPServer = {
174
178
  name: string;
175
179
  server_url: string;
176
180
  auth_url: string | null;
177
- state: MCPConnectionState;
181
+ state: MCPConnectionState /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */;
178
182
  error: string | null;
179
183
  instructions: string | null;
180
184
  capabilities: ServerCapabilities | null;
@@ -197,7 +201,8 @@ type AddMcpServerOptions = {
197
201
  transport?: {
198
202
  /** Custom headers for authentication (e.g., bearer tokens, CF Access) */ headers?: HeadersInit /** Transport type: "sse", "streamable-http", or "auto" (default) */;
199
203
  type?: TransportType;
200
- };
204
+ } /** Retry options for connection and reconnection attempts */;
205
+ retry?: RetryOptions;
201
206
  };
202
207
  /**
203
208
  * Default options for Agent configuration.
@@ -211,16 +216,26 @@ declare const DEFAULT_AGENT_STATIC_OPTIONS: {
211
216
  * and force-reset. Increase this if you have callbacks that legitimately
212
217
  * take longer than 30 seconds.
213
218
  */
214
- hungScheduleTimeoutSeconds: number;
219
+ hungScheduleTimeoutSeconds: number /** Default retry options for schedule(), queue(), and this.retry() */;
220
+ retry: {
221
+ maxAttempts: number;
222
+ baseDelayMs: number;
223
+ maxDelayMs: number;
224
+ };
215
225
  };
216
- type ResolvedAgentOptions = typeof DEFAULT_AGENT_STATIC_OPTIONS;
217
226
  /**
218
227
  * Configuration options for the Agent.
219
228
  * Override in subclasses via `static options`.
220
229
  * All fields are optional - defaults are applied at runtime.
221
230
  * Note: `hibernate` defaults to `true` if not specified.
222
231
  */
223
- type AgentStaticOptions = Partial<ResolvedAgentOptions>;
232
+ interface AgentStaticOptions {
233
+ hibernate?: boolean;
234
+ sendIdentityOnConnect?: boolean;
235
+ hungScheduleTimeoutSeconds?: number;
236
+ /** Default retry options for schedule(), queue(), and this.retry(). */
237
+ retry?: RetryOptions;
238
+ }
224
239
  declare function getCurrentAgent<
225
240
  T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
226
241
  >(): {
@@ -257,8 +272,8 @@ declare class Agent<
257
272
  private _destroyed;
258
273
  /**
259
274
  * Stores raw state accessors for wrapped connections.
260
- * Used by setConnectionReadonly/isConnectionReadonly to read/write the
261
- * _cf_readonly flag without going through the user-facing state/setState.
275
+ * Used by internal flag methods (readonly, no-protocol) to read/write
276
+ * _cf_-prefixed keys without going through the user-facing state/setState.
262
277
  */
263
278
  private _rawStateAccessors;
264
279
  /**
@@ -289,8 +304,11 @@ declare class Agent<
289
304
  */
290
305
  static options: AgentStaticOptions;
291
306
  /**
292
- * Resolved options (merges defaults with subclass overrides)
307
+ * Resolved options (merges defaults with subclass overrides).
308
+ * Cached after first access — static options never change during the
309
+ * lifetime of a Durable Object instance.
293
310
  */
311
+ private _cachedOptions?;
294
312
  private get _resolvedOptions();
295
313
  /**
296
314
  * The observability implementation to use for the Agent
@@ -312,6 +330,14 @@ declare class Agent<
312
330
  * Check for workflows referencing unknown bindings and warn with migration suggestion.
313
331
  */
314
332
  private _checkOrphanedWorkflows;
333
+ /**
334
+ * Broadcast a protocol message only to connections that have protocol
335
+ * messages enabled. Connections where shouldSendProtocolMessages returned
336
+ * false are excluded automatically.
337
+ * @param msg The JSON-encoded protocol message
338
+ * @param excludeIds Additional connection IDs to exclude (e.g. the source)
339
+ */
340
+ private _broadcastProtocol;
315
341
  private _setStateInternal;
316
342
  /**
317
343
  * Update the Agent's state
@@ -320,11 +346,16 @@ declare class Agent<
320
346
  */
321
347
  setState(state: State): void;
322
348
  /**
323
- * Wraps connection.state and connection.setState so that the internal
324
- * _cf_readonly flag is hidden from user code and cannot be accidentally
325
- * overwritten. Must be called before any user code sees the connection.
349
+ * Wraps connection.state and connection.setState so that internal
350
+ * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code
351
+ * and cannot be accidentally overwritten.
326
352
  *
327
353
  * Idempotent — safe to call multiple times on the same connection.
354
+ * After hibernation, the _rawStateAccessors WeakMap is empty but the
355
+ * connection's state getter still reads from the persisted WebSocket
356
+ * attachment. Calling this method re-captures the raw getter so that
357
+ * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled)
358
+ * work correctly post-hibernation.
328
359
  */
329
360
  private _ensureConnectionWrapped;
330
361
  /**
@@ -334,7 +365,10 @@ declare class Agent<
334
365
  */
335
366
  setConnectionReadonly(connection: Connection$1, readonly?: boolean): void;
336
367
  /**
337
- * Check if a connection is marked as readonly
368
+ * Check if a connection is marked as readonly.
369
+ *
370
+ * Safe to call after hibernation — re-wraps the connection if the
371
+ * in-memory accessor cache was cleared.
338
372
  * @param connection The connection to check
339
373
  * @returns True if the connection is readonly
340
374
  */
@@ -349,6 +383,42 @@ declare class Agent<
349
383
  _connection: Connection$1,
350
384
  _ctx: ConnectionContext$1
351
385
  ): boolean;
386
+ /**
387
+ * Override this method to control whether protocol messages are sent to a
388
+ * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state
389
+ * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS).
390
+ *
391
+ * When this returns `false` for a connection, that connection will not
392
+ * receive any protocol text frames — neither on connect nor via broadcasts.
393
+ * This is useful for binary-only clients (e.g. MQTT devices) that cannot
394
+ * handle JSON text frames.
395
+ *
396
+ * The connection can still send and receive regular messages, use RPC, and
397
+ * participate in all non-protocol communication.
398
+ *
399
+ * @param _connection The connection that is being established
400
+ * @param _ctx Connection context (includes the upgrade request)
401
+ * @returns True if protocol messages should be sent (default), false to suppress them
402
+ */
403
+ shouldSendProtocolMessages(
404
+ _connection: Connection$1,
405
+ _ctx: ConnectionContext$1
406
+ ): boolean;
407
+ /**
408
+ * Check if a connection has protocol messages enabled.
409
+ * Protocol messages include identity, state sync, and MCP server lists.
410
+ *
411
+ * Safe to call after hibernation — re-wraps the connection if the
412
+ * in-memory accessor cache was cleared.
413
+ * @param connection The connection to check
414
+ * @returns True if the connection receives protocol messages
415
+ */
416
+ isConnectionProtocolEnabled(connection: Connection$1): boolean;
417
+ /**
418
+ * Mark a connection as having protocol messages disabled.
419
+ * Called internally when shouldSendProtocolMessages returns false.
420
+ */
421
+ private _setConnectionNoProtocol;
352
422
  /**
353
423
  * Called before the Agent's state is persisted and broadcast.
354
424
  * Override to validate or reject an update by throwing an error.
@@ -426,54 +496,89 @@ declare class Agent<
426
496
  * Render content (not implemented in base class)
427
497
  */
428
498
  render(): void;
499
+ /**
500
+ * Retry an async operation with exponential backoff and jitter.
501
+ * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors.
502
+ *
503
+ * @param fn The async function to retry. Receives the current attempt number (1-indexed).
504
+ * @param options Retry configuration.
505
+ * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3.
506
+ * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100.
507
+ * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000.
508
+ * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors.
509
+ * @returns The result of fn on success.
510
+ * @throws The last error if all attempts fail or shouldRetry returns false.
511
+ */
512
+ retry<T>(
513
+ fn: (attempt: number) => Promise<T>,
514
+ options?: RetryOptions & {
515
+ /** Return false to stop retrying a specific error. Receives the error and the next attempt number. Default: retry all errors. */ shouldRetry?: (
516
+ err: unknown,
517
+ nextAttempt: number
518
+ ) => boolean;
519
+ }
520
+ ): Promise<T>;
429
521
  /**
430
522
  * Queue a task to be executed in the future
431
- * @param payload Payload to pass to the callback
432
523
  * @param callback Name of the method to call
524
+ * @param payload Payload to pass to the callback
525
+ * @param options Options for the queued task
526
+ * @param options.retry Retry options for the callback execution
433
527
  * @returns The ID of the queued task
434
528
  */
435
- queue<T = unknown>(callback: keyof this, payload: T): Promise<string>;
529
+ queue<T = unknown>(
530
+ callback: keyof this,
531
+ payload: T,
532
+ options?: {
533
+ retry?: RetryOptions;
534
+ }
535
+ ): Promise<string>;
436
536
  private _flushingQueue;
437
537
  private _flushQueue;
438
538
  /**
439
539
  * Dequeue a task by ID
440
540
  * @param id ID of the task to dequeue
441
541
  */
442
- dequeue(id: string): Promise<void>;
542
+ dequeue(id: string): void;
443
543
  /**
444
544
  * Dequeue all tasks
445
545
  */
446
- dequeueAll(): Promise<void>;
546
+ dequeueAll(): void;
447
547
  /**
448
548
  * Dequeue all tasks by callback
449
549
  * @param callback Name of the callback to dequeue
450
550
  */
451
- dequeueAllByCallback(callback: string): Promise<void>;
551
+ dequeueAllByCallback(callback: string): void;
452
552
  /**
453
553
  * Get a queued task by ID
454
554
  * @param id ID of the task to get
455
555
  * @returns The task or undefined if not found
456
556
  */
457
- getQueue(id: string): Promise<QueueItem<string> | undefined>;
557
+ getQueue(id: string): QueueItem<string> | undefined;
458
558
  /**
459
559
  * Get all queues by key and value
460
560
  * @param key Key to filter by
461
561
  * @param value Value to filter by
462
562
  * @returns Array of matching QueueItem objects
463
563
  */
464
- getQueues(key: string, value: string): Promise<QueueItem<string>[]>;
564
+ getQueues(key: string, value: string): QueueItem<string>[];
465
565
  /**
466
566
  * Schedule a task to be executed in the future
467
567
  * @template T Type of the payload data
468
568
  * @param when When to execute the task (Date, seconds delay, or cron expression)
469
569
  * @param callback Name of the method to call
470
570
  * @param payload Data to pass to the callback
571
+ * @param options Options for the scheduled task
572
+ * @param options.retry Retry options for the callback execution
471
573
  * @returns Schedule object representing the scheduled task
472
574
  */
473
575
  schedule<T = string>(
474
576
  when: Date | string | number,
475
577
  callback: keyof this,
476
- payload?: T
578
+ payload?: T,
579
+ options?: {
580
+ retry?: RetryOptions;
581
+ }
477
582
  ): Promise<Schedule<T>>;
478
583
  /**
479
584
  * Schedule a task to run repeatedly at a fixed interval
@@ -481,12 +586,17 @@ declare class Agent<
481
586
  * @param intervalSeconds Number of seconds between executions
482
587
  * @param callback Name of the method to call
483
588
  * @param payload Data to pass to the callback
589
+ * @param options Options for the scheduled task
590
+ * @param options.retry Retry options for the callback execution
484
591
  * @returns Schedule object representing the scheduled task
485
592
  */
486
593
  scheduleEvery<T = string>(
487
594
  intervalSeconds: number,
488
595
  callback: keyof this,
489
- payload?: T
596
+ payload?: T,
597
+ options?: {
598
+ retry?: RetryOptions;
599
+ }
490
600
  ): Promise<Schedule<T>>;
491
601
  /**
492
602
  * Get a scheduled task by ID
@@ -494,7 +604,7 @@ declare class Agent<
494
604
  * @param id ID of the scheduled task
495
605
  * @returns The Schedule object or undefined if not found
496
606
  */
497
- getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
607
+ getSchedule<T = string>(id: string): Schedule<T> | undefined;
498
608
  /**
499
609
  * Get scheduled tasks matching the given criteria
500
610
  * @template T Type of the payload data
@@ -1124,6 +1234,7 @@ export {
1124
1234
  type Connection,
1125
1235
  type ConnectionContext,
1126
1236
  DEFAULT_AGENT_STATIC_OPTIONS,
1237
+ DurableObjectOAuthClientProvider,
1127
1238
  EmailRoutingOptions,
1128
1239
  MCPServer,
1129
1240
  MCPServerMessage,
@@ -1131,6 +1242,7 @@ export {
1131
1242
  QueueItem,
1132
1243
  RPCRequest,
1133
1244
  RPCResponse,
1245
+ type RetryOptions,
1134
1246
  Schedule,
1135
1247
  SqlError,
1136
1248
  StateUpdateMessage,