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