agents 0.0.0-6ee3a60 → 0.0.0-74a8c74

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.
@@ -1,10 +1,3 @@
1
- import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateMethod,
5
- __privateSet
6
- } from "./chunk-HMLY7DHA.js";
7
-
8
1
  // src/index.ts
9
2
  import {
10
3
  Server,
@@ -13,6 +6,7 @@ import {
13
6
  } from "partyserver";
14
7
  import { parseCronExpression } from "cron-schedule";
15
8
  import { nanoid } from "nanoid";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
16
10
  import { WorkflowEntrypoint as CFWorkflowEntrypoint } from "cloudflare:workers";
17
11
  function isRPCRequest(msg) {
18
12
  return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
@@ -38,115 +32,20 @@ function getNextCronTime(cron) {
38
32
  var STATE_ROW_ID = "cf_state_row_id";
39
33
  var STATE_WAS_CHANGED = "cf_state_was_changed";
40
34
  var DEFAULT_STATE = {};
41
- var _state, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
35
+ var unstable_context = new AsyncLocalStorage();
42
36
  var Agent = class extends Server {
43
- constructor(ctx, env) {
44
- super(ctx, env);
45
- __privateAdd(this, _Agent_instances);
46
- __privateAdd(this, _state, DEFAULT_STATE);
47
- /**
48
- * Initial state for the Agent
49
- * Override to provide default state values
50
- */
51
- this.initialState = DEFAULT_STATE;
52
- this.sql`
53
- CREATE TABLE IF NOT EXISTS cf_agents_state (
54
- id TEXT PRIMARY KEY NOT NULL,
55
- state TEXT
56
- )
57
- `;
58
- void this.ctx.blockConcurrencyWhile(async () => {
59
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
60
- this.sql`
61
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
62
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
63
- callback TEXT,
64
- payload TEXT,
65
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
66
- time INTEGER,
67
- delayInSeconds INTEGER,
68
- cron TEXT,
69
- created_at INTEGER DEFAULT (unixepoch())
70
- )
71
- `;
72
- await this.alarm();
73
- });
74
- });
75
- const _onMessage = this.onMessage.bind(this);
76
- this.onMessage = async (connection, message) => {
77
- if (typeof message !== "string") {
78
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
79
- }
80
- let parsed;
81
- try {
82
- parsed = JSON.parse(message);
83
- } catch (e) {
84
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
85
- }
86
- if (isStateUpdateMessage(parsed)) {
87
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
88
- return;
89
- }
90
- if (isRPCRequest(parsed)) {
91
- try {
92
- const { id, method, args } = parsed;
93
- const methodFn = this[method];
94
- if (typeof methodFn !== "function") {
95
- throw new Error(`Method ${method} does not exist`);
96
- }
97
- if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
98
- throw new Error(`Method ${method} is not callable`);
99
- }
100
- const metadata = callableMetadata.get(methodFn);
101
- if (metadata?.streaming) {
102
- const stream = new StreamingResponse(connection, id);
103
- await methodFn.apply(this, [stream, ...args]);
104
- return;
105
- }
106
- const result = await methodFn.apply(this, args);
107
- const response = {
108
- type: "rpc",
109
- id,
110
- success: true,
111
- result,
112
- done: true
113
- };
114
- connection.send(JSON.stringify(response));
115
- } catch (e) {
116
- const response = {
117
- type: "rpc",
118
- id: parsed.id,
119
- success: false,
120
- error: e instanceof Error ? e.message : "Unknown error occurred"
121
- };
122
- connection.send(JSON.stringify(response));
123
- console.error("RPC error:", e);
124
- }
125
- return;
126
- }
127
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
128
- };
129
- const _onConnect = this.onConnect.bind(this);
130
- this.onConnect = (connection, ctx2) => {
131
- setTimeout(() => {
132
- if (this.state) {
133
- connection.send(
134
- JSON.stringify({
135
- type: "cf_agent_state",
136
- state: this.state
137
- })
138
- );
139
- }
140
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
141
- }, 20);
142
- };
143
- }
37
+ #state = DEFAULT_STATE;
38
+ /**
39
+ * Initial state for the Agent
40
+ * Override to provide default state values
41
+ */
42
+ initialState = DEFAULT_STATE;
144
43
  /**
145
44
  * Current state of the Agent
146
45
  */
147
46
  get state() {
148
- if (__privateGet(this, _state) !== DEFAULT_STATE) {
149
- return __privateGet(this, _state);
47
+ if (this.#state !== DEFAULT_STATE) {
48
+ return this.#state;
150
49
  }
151
50
  const wasChanged = this.sql`
152
51
  SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
@@ -157,8 +56,8 @@ var Agent = class extends Server {
157
56
  if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
158
57
  result[0]?.state) {
159
58
  const state = result[0]?.state;
160
- __privateSet(this, _state, JSON.parse(state));
161
- return __privateGet(this, _state);
59
+ this.#state = JSON.parse(state);
60
+ return this.#state;
162
61
  }
163
62
  if (this.initialState === DEFAULT_STATE) {
164
63
  return void 0;
@@ -166,6 +65,14 @@ var Agent = class extends Server {
166
65
  this.setState(this.initialState);
167
66
  return this.initialState;
168
67
  }
68
+ /**
69
+ * Agent configuration options
70
+ */
71
+ static options = {
72
+ /** Whether the Agent should hibernate when inactive */
73
+ hibernate: true
74
+ // default to hibernate
75
+ };
169
76
  /**
170
77
  * Execute SQL queries against the Agent's database
171
78
  * @template T Type of the returned rows
@@ -186,12 +93,143 @@ var Agent = class extends Server {
186
93
  throw this.onError(e);
187
94
  }
188
95
  }
96
+ constructor(ctx, env) {
97
+ super(ctx, env);
98
+ this.sql`
99
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
100
+ id TEXT PRIMARY KEY NOT NULL,
101
+ state TEXT
102
+ )
103
+ `;
104
+ void this.ctx.blockConcurrencyWhile(async () => {
105
+ return this.#tryCatch(async () => {
106
+ this.sql`
107
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
108
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
109
+ callback TEXT,
110
+ payload TEXT,
111
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
112
+ time INTEGER,
113
+ delayInSeconds INTEGER,
114
+ cron TEXT,
115
+ created_at INTEGER DEFAULT (unixepoch())
116
+ )
117
+ `;
118
+ await this.alarm();
119
+ });
120
+ });
121
+ const _onMessage = this.onMessage.bind(this);
122
+ this.onMessage = async (connection, message) => {
123
+ return unstable_context.run(
124
+ { agent: this, connection, request: void 0 },
125
+ async () => {
126
+ if (typeof message !== "string") {
127
+ return this.#tryCatch(() => _onMessage(connection, message));
128
+ }
129
+ let parsed;
130
+ try {
131
+ parsed = JSON.parse(message);
132
+ } catch (e) {
133
+ return this.#tryCatch(() => _onMessage(connection, message));
134
+ }
135
+ if (isStateUpdateMessage(parsed)) {
136
+ this.#setStateInternal(parsed.state, connection);
137
+ return;
138
+ }
139
+ if (isRPCRequest(parsed)) {
140
+ try {
141
+ const { id, method, args } = parsed;
142
+ const methodFn = this[method];
143
+ if (typeof methodFn !== "function") {
144
+ throw new Error(`Method ${method} does not exist`);
145
+ }
146
+ if (!this.#isCallable(method)) {
147
+ throw new Error(`Method ${method} is not callable`);
148
+ }
149
+ const metadata = callableMetadata.get(methodFn);
150
+ if (metadata?.streaming) {
151
+ const stream = new StreamingResponse(connection, id);
152
+ await methodFn.apply(this, [stream, ...args]);
153
+ return;
154
+ }
155
+ const result = await methodFn.apply(this, args);
156
+ const response = {
157
+ type: "rpc",
158
+ id,
159
+ success: true,
160
+ result,
161
+ done: true
162
+ };
163
+ connection.send(JSON.stringify(response));
164
+ } catch (e) {
165
+ const response = {
166
+ type: "rpc",
167
+ id: parsed.id,
168
+ success: false,
169
+ error: e instanceof Error ? e.message : "Unknown error occurred"
170
+ };
171
+ connection.send(JSON.stringify(response));
172
+ console.error("RPC error:", e);
173
+ }
174
+ return;
175
+ }
176
+ return this.#tryCatch(() => _onMessage(connection, message));
177
+ }
178
+ );
179
+ };
180
+ const _onConnect = this.onConnect.bind(this);
181
+ this.onConnect = (connection, ctx2) => {
182
+ return unstable_context.run(
183
+ { agent: this, connection, request: ctx2.request },
184
+ async () => {
185
+ setTimeout(() => {
186
+ if (this.state) {
187
+ connection.send(
188
+ JSON.stringify({
189
+ type: "cf_agent_state",
190
+ state: this.state
191
+ })
192
+ );
193
+ }
194
+ return this.#tryCatch(() => _onConnect(connection, ctx2));
195
+ }, 20);
196
+ }
197
+ );
198
+ };
199
+ }
200
+ #setStateInternal(state, source = "server") {
201
+ this.#state = state;
202
+ this.sql`
203
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
204
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
205
+ `;
206
+ this.sql`
207
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
208
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
209
+ `;
210
+ this.broadcast(
211
+ JSON.stringify({
212
+ type: "cf_agent_state",
213
+ state
214
+ }),
215
+ source !== "server" ? [source.id] : []
216
+ );
217
+ return this.#tryCatch(() => {
218
+ const { connection, request } = unstable_context.getStore() || {};
219
+ return unstable_context.run(
220
+ { agent: this, connection, request },
221
+ async () => {
222
+ return this.onStateUpdate(state, source);
223
+ }
224
+ );
225
+ });
226
+ }
189
227
  /**
190
228
  * Update the Agent's state
191
229
  * @param state New state to set
192
230
  */
193
231
  setState(state) {
194
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
232
+ this.#setStateInternal(state, "server");
195
233
  }
196
234
  /**
197
235
  * Called when the Agent's state is updated
@@ -205,7 +243,19 @@ var Agent = class extends Server {
205
243
  * @param email Email message to process
206
244
  */
207
245
  onEmail(email) {
208
- throw new Error("Not implemented");
246
+ return unstable_context.run(
247
+ { agent: this, connection: void 0, request: void 0 },
248
+ async () => {
249
+ console.error("onEmail not implemented");
250
+ }
251
+ );
252
+ }
253
+ async #tryCatch(fn) {
254
+ try {
255
+ return await fn();
256
+ } catch (e) {
257
+ throw this.onError(e);
258
+ }
209
259
  }
210
260
  onError(connectionOrError, error) {
211
261
  let theError;
@@ -256,7 +306,7 @@ var Agent = class extends Server {
256
306
  payload
257
307
  )}, 'scheduled', ${timestamp})
258
308
  `;
259
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
309
+ await this.#scheduleNextAlarm();
260
310
  return {
261
311
  id,
262
312
  callback,
@@ -274,7 +324,7 @@ var Agent = class extends Server {
274
324
  payload
275
325
  )}, 'delayed', ${when}, ${timestamp})
276
326
  `;
277
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
327
+ await this.#scheduleNextAlarm();
278
328
  return {
279
329
  id,
280
330
  callback,
@@ -293,7 +343,7 @@ var Agent = class extends Server {
293
343
  payload
294
344
  )}, 'cron', ${when}, ${timestamp})
295
345
  `;
296
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
346
+ await this.#scheduleNextAlarm();
297
347
  return {
298
348
  id,
299
349
  callback,
@@ -334,10 +384,6 @@ var Agent = class extends Server {
334
384
  query += " AND id = ?";
335
385
  params.push(criteria.id);
336
386
  }
337
- if (criteria.description) {
338
- query += " AND description = ?";
339
- params.push(criteria.description);
340
- }
341
387
  if (criteria.type) {
342
388
  query += " AND type = ?";
343
389
  params.push(criteria.type);
@@ -364,9 +410,22 @@ var Agent = class extends Server {
364
410
  */
365
411
  async cancelSchedule(id) {
366
412
  this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
367
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
413
+ await this.#scheduleNextAlarm();
368
414
  return true;
369
415
  }
416
+ async #scheduleNextAlarm() {
417
+ const result = this.sql`
418
+ SELECT time FROM cf_agents_schedules
419
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
420
+ ORDER BY time ASC
421
+ LIMIT 1
422
+ `;
423
+ if (!result) return;
424
+ if (result.length > 0 && "time" in result[0]) {
425
+ const nextTime = result[0].time * 1e3;
426
+ await this.ctx.storage.setAlarm(nextTime);
427
+ }
428
+ }
370
429
  /**
371
430
  * Method called when an alarm fires
372
431
  * Executes any scheduled tasks that are due
@@ -382,11 +441,16 @@ var Agent = class extends Server {
382
441
  console.error(`callback ${row.callback} not found`);
383
442
  continue;
384
443
  }
385
- try {
386
- await callback.bind(this)(JSON.parse(row.payload), row);
387
- } catch (e) {
388
- console.error(`error executing callback "${row.callback}"`, e);
389
- }
444
+ await unstable_context.run(
445
+ { agent: this, connection: void 0, request: void 0 },
446
+ async () => {
447
+ try {
448
+ await callback.bind(this)(JSON.parse(row.payload), row);
449
+ } catch (e) {
450
+ console.error(`error executing callback "${row.callback}"`, e);
451
+ }
452
+ }
453
+ );
390
454
  if (row.type === "cron") {
391
455
  const nextExecutionTime = getNextCronTime(row.cron);
392
456
  const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
@@ -399,7 +463,7 @@ var Agent = class extends Server {
399
463
  `;
400
464
  }
401
465
  }
402
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
466
+ await this.#scheduleNextAlarm();
403
467
  }
404
468
  /**
405
469
  * Destroy the Agent, removing all state and scheduled tasks
@@ -410,63 +474,14 @@ var Agent = class extends Server {
410
474
  await this.ctx.storage.deleteAlarm();
411
475
  await this.ctx.storage.deleteAll();
412
476
  }
413
- };
414
- _state = new WeakMap();
415
- _Agent_instances = new WeakSet();
416
- setStateInternal_fn = function(state, source = "server") {
417
- __privateSet(this, _state, state);
418
- this.sql`
419
- INSERT OR REPLACE INTO cf_agents_state (id, state)
420
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
421
- `;
422
- this.sql`
423
- INSERT OR REPLACE INTO cf_agents_state (id, state)
424
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
425
- `;
426
- this.broadcast(
427
- JSON.stringify({
428
- type: "cf_agent_state",
429
- state
430
- }),
431
- source !== "server" ? [source.id] : []
432
- );
433
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => this.onStateUpdate(state, source));
434
- };
435
- tryCatch_fn = async function(fn) {
436
- try {
437
- return await fn();
438
- } catch (e) {
439
- throw this.onError(e);
440
- }
441
- };
442
- scheduleNextAlarm_fn = async function() {
443
- const result = this.sql`
444
- SELECT time FROM cf_agents_schedules
445
- WHERE time > ${Math.floor(Date.now() / 1e3)}
446
- ORDER BY time ASC
447
- LIMIT 1
448
- `;
449
- if (!result) return;
450
- if (result.length > 0 && "time" in result[0]) {
451
- const nextTime = result[0].time * 1e3;
452
- await this.ctx.storage.setAlarm(nextTime);
477
+ /**
478
+ * Get all methods marked as callable on this Agent
479
+ * @returns A map of method names to their metadata
480
+ */
481
+ #isCallable(method) {
482
+ return callableMetadata.has(this[method]);
453
483
  }
454
484
  };
455
- /**
456
- * Get all methods marked as callable on this Agent
457
- * @returns A map of method names to their metadata
458
- */
459
- isCallable_fn = function(method) {
460
- return callableMetadata.has(this[method]);
461
- };
462
- /**
463
- * Agent configuration options
464
- */
465
- Agent.options = {
466
- /** Whether the Agent should hibernate when inactive */
467
- hibernate: true
468
- // default to hibernate
469
- };
470
485
  async function routeAgentRequest(request, env, options) {
471
486
  const corsHeaders = options?.cors === true ? {
472
487
  "Access-Control-Allow-Origin": "*",
@@ -507,62 +522,59 @@ async function routeAgentEmail(email, env, options) {
507
522
  function getAgentByName(namespace, name, options) {
508
523
  return getServerByName(namespace, name, options);
509
524
  }
510
- var _connection, _id, _closed;
511
525
  var StreamingResponse = class {
526
+ #connection;
527
+ #id;
528
+ #closed = false;
512
529
  constructor(connection, id) {
513
- __privateAdd(this, _connection);
514
- __privateAdd(this, _id);
515
- __privateAdd(this, _closed, false);
516
- __privateSet(this, _connection, connection);
517
- __privateSet(this, _id, id);
530
+ this.#connection = connection;
531
+ this.#id = id;
518
532
  }
519
533
  /**
520
534
  * Send a chunk of data to the client
521
535
  * @param chunk The data to send
522
536
  */
523
537
  send(chunk) {
524
- if (__privateGet(this, _closed)) {
538
+ if (this.#closed) {
525
539
  throw new Error("StreamingResponse is already closed");
526
540
  }
527
541
  const response = {
528
542
  type: "rpc",
529
- id: __privateGet(this, _id),
543
+ id: this.#id,
530
544
  success: true,
531
545
  result: chunk,
532
546
  done: false
533
547
  };
534
- __privateGet(this, _connection).send(JSON.stringify(response));
548
+ this.#connection.send(JSON.stringify(response));
535
549
  }
536
550
  /**
537
551
  * End the stream and send the final chunk (if any)
538
552
  * @param finalChunk Optional final chunk of data to send
539
553
  */
540
554
  end(finalChunk) {
541
- if (__privateGet(this, _closed)) {
555
+ if (this.#closed) {
542
556
  throw new Error("StreamingResponse is already closed");
543
557
  }
544
- __privateSet(this, _closed, true);
558
+ this.#closed = true;
545
559
  const response = {
546
560
  type: "rpc",
547
- id: __privateGet(this, _id),
561
+ id: this.#id,
548
562
  success: true,
549
563
  result: finalChunk,
550
564
  done: true
551
565
  };
552
- __privateGet(this, _connection).send(JSON.stringify(response));
566
+ this.#connection.send(JSON.stringify(response));
553
567
  }
554
568
  };
555
- _connection = new WeakMap();
556
- _id = new WeakMap();
557
- _closed = new WeakMap();
558
569
 
559
570
  export {
560
571
  unstable_callable,
561
572
  WorkflowEntrypoint,
573
+ unstable_context,
562
574
  Agent,
563
575
  routeAgentRequest,
564
576
  routeAgentEmail,
565
577
  getAgentByName,
566
578
  StreamingResponse
567
579
  };
568
- //# sourceMappingURL=chunk-X6BBKLSC.js.map
580
+ //# sourceMappingURL=chunk-SZEXGW6W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n Server,\n routePartykitRequest,\n type PartyServerOptions,\n getServerByName,\n type Connection,\n type ConnectionContext,\n type WSMessage,\n} from \"partyserver\";\n\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type { Connection, WSMessage, ConnectionContext } from \"partyserver\";\n\nimport { WorkflowEntrypoint as CFWorkflowEntrypoint } from \"cloudflare:workers\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: \"cf_agent_state\";\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: \"rpc\";\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"rpc\" &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"cf_agent_state\" &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: <explanation>\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function unstable_callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\n/**\n * A class for creating workflow entry points that can be used with Cloudflare Workers\n */\nexport class WorkflowEntrypoint extends CFWorkflowEntrypoint {}\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nexport const unstable_context = new AsyncLocalStorage<{\n agent: Agent<unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n}>();\n\n/**\n * Base class for creating Agent implementations\n * @template Env Environment type containing bindings\n * @template State State type to store within the Agent\n */\nexport class Agent<Env, State = unknown> extends Server<Env> {\n #state = DEFAULT_STATE as State;\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this.#state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this.#state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this.#state = JSON.parse(state);\n return this.#state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true, // default to hibernate\n };\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n void this.ctx.blockConcurrencyWhile(async () => {\n return this.#tryCatch(async () => {\n // Create alarms table if it doesn't exist\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n });\n });\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return unstable_context.run(\n { agent: this, connection, request: undefined },\n async () => {\n if (typeof message !== \"string\") {\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (e) {\n // silently fail and let the onMessage handler handle it\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this.#setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this.#isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n const response: RPCResponse = {\n type: \"rpc\",\n id,\n success: true,\n result,\n done: true,\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n type: \"rpc\",\n id: parsed.id,\n success: false,\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return unstable_context.run(\n { agent: this, connection, request: ctx.request },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: this.state,\n })\n );\n }\n return this.#tryCatch(() => _onConnect(connection, ctx));\n }, 20);\n }\n );\n };\n }\n\n #setStateInternal(state: State, source: Connection | \"server\" = \"server\") {\n this.#state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: state,\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this.#tryCatch(() => {\n const { connection, request } = unstable_context.getStore() || {};\n return unstable_context.run(\n { agent: this, connection, request },\n async () => {\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this.#setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email\n * @param email Email message to process\n */\n onEmail(email: ForwardableEmailMessage) {\n return unstable_context.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n console.error(\"onEmail not implemented\");\n }\n );\n }\n\n async #tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\",\n };\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n delayInSeconds: when,\n time: timestamp,\n type: \"delayed\",\n };\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n cron: when,\n time: timestamp,\n type: \"cron\",\n };\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T,\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this.#scheduleNextAlarm();\n return true;\n }\n\n async #scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules \n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC \n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires\n * Executes any scheduled tasks that are due\n */\n async alarm() {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await unstable_context.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n try {\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n\n // Schedule the next alarm\n await this.#scheduleNextAlarm();\n }\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n #isCallable(method: string): boolean {\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n}\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\n/**\n * Route a request to the appropriate Agent\n * @param request Request to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n * @returns Response from the Agent or undefined if no route matched\n */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Max-Age\": \"86400\",\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders,\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>),\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders,\n },\n });\n }\n return response;\n}\n\n/**\n * Route an email to the appropriate Agent\n * @param email Email message to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options?: AgentOptions<Env>\n): Promise<void> {}\n\n/**\n * Get or create an Agent by name\n * @template Env Environment type containing bindings\n * @template T Type of the Agent class\n * @param namespace Agent namespace\n * @param name Name of the Agent instance\n * @param options Options for Agent creation\n * @returns Promise resolving to an Agent instance stub\n */\nexport function getAgentByName<Env, T extends Agent<Env>>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n #connection: Connection;\n #id: string;\n #closed = false;\n\n constructor(connection: Connection, id: string) {\n this.#connection = connection;\n this.#id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: chunk,\n done: false,\n };\n this.#connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this.#closed = true;\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: finalChunk,\n done: true,\n };\n this.#connection.send(JSON.stringify(response));\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OAIK;AAEP,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAEvB,SAAS,yBAAyB;AAIlC,SAAS,sBAAsB,4BAA4B;AA8C3D,SAAS,aAAa,KAAiC;A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