agents 0.0.0-e03246e → 0.0.0-e173b41

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 (72) hide show
  1. package/README.md +257 -27
  2. package/dist/ai-chat-agent.d.ts +133 -12
  3. package/dist/ai-chat-agent.js +798 -160
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-BSiGZmYU.js +155 -0
  6. package/dist/ai-chat-v5-migration-BSiGZmYU.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +78 -72
  10. package/dist/ai-react.js +411 -192
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-81H_-Uxh.d.ts +103 -0
  13. package/dist/ai-types-CrMqkwc_.js +24 -0
  14. package/dist/ai-types-CrMqkwc_.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-B3SR12TQ.js +117 -0
  21. package/dist/client-B3SR12TQ.js.map +1 -0
  22. package/dist/client-BAQA84dr.d.ts +104 -0
  23. package/dist/client-BZq9qau2.js +1093 -0
  24. package/dist/client-BZq9qau2.js.map +1 -0
  25. package/dist/client-CsaP9Irq.d.ts +1528 -0
  26. package/dist/client.d.ts +12 -79
  27. package/dist/client.js +3 -130
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-C2CHH5x-.d.ts +55 -0
  32. package/dist/do-oauth-client-provider-CwqK5SXm.js +94 -0
  33. package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
  34. package/dist/index-BUle9RiP.d.ts +58 -0
  35. package/dist/index-Bx5KK3VJ.d.ts +587 -0
  36. package/dist/index.d.ts +63 -301
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -675
  39. package/dist/mcp/client.js +3 -267
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  41. package/dist/mcp/do-oauth-client-provider.js +3 -0
  42. package/dist/mcp/index.d.ts +191 -43
  43. package/dist/mcp/index.js +1438 -334
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +198 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BwPscEiF.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-CbwD4fBf.d.ts +113 -0
  52. package/dist/react.d.ts +10 -39
  53. package/dist/react.js +183 -98
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -23
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-faDkMCai.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-D_KKH_4c.js +1184 -0
  62. package/dist/src-D_KKH_4c.js.map +1 -0
  63. package/package.json +130 -51
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-HMLY7DHA.js +0 -16
  66. package/dist/chunk-HMLY7DHA.js.map +0 -1
  67. package/dist/chunk-YMUU7QHV.js +0 -595
  68. package/dist/chunk-YMUU7QHV.js.map +0 -1
  69. package/dist/client.js.map +0 -1
  70. package/dist/index.js.map +0 -1
  71. package/dist/mcp/client.js.map +0 -1
  72. package/src/index.ts +0 -919
@@ -0,0 +1,1184 @@
1
+ import { t as MessageType } from "./ai-types-CrMqkwc_.js";
2
+ import { r as camelCaseToKebabCase } from "./client-B3SR12TQ.js";
3
+ import { i as DisposableStore, r as MCPConnectionState, t as MCPClientManager } from "./client-BZq9qau2.js";
4
+ import { t as DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-CwqK5SXm.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { parseCronExpression } from "cron-schedule";
7
+ import { nanoid } from "nanoid";
8
+ import { EmailMessage } from "cloudflare:email";
9
+ import { Server, getServerByName, routePartykitRequest } from "partyserver";
10
+
11
+ //#region src/observability/index.ts
12
+ /**
13
+ * A generic observability implementation that logs events to the console.
14
+ */
15
+ const genericObservability = { emit(event) {
16
+ if (isLocalMode()) {
17
+ console.log(event.displayMessage);
18
+ return;
19
+ }
20
+ console.log(event);
21
+ } };
22
+ let localMode = false;
23
+ function isLocalMode() {
24
+ if (localMode) return true;
25
+ const { request } = getCurrentAgent();
26
+ if (!request) return false;
27
+ localMode = new URL(request.url).hostname === "localhost";
28
+ return localMode;
29
+ }
30
+
31
+ //#endregion
32
+ //#region src/index.ts
33
+ /**
34
+ * Type guard for RPC request messages
35
+ */
36
+ function isRPCRequest(msg) {
37
+ 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);
38
+ }
39
+ /**
40
+ * Type guard for state update messages
41
+ */
42
+ function isStateUpdateMessage(msg) {
43
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
44
+ }
45
+ const callableMetadata = /* @__PURE__ */ new Map();
46
+ /**
47
+ * Decorator that marks a method as callable by clients
48
+ * @param metadata Optional metadata about the callable method
49
+ */
50
+ function callable(metadata = {}) {
51
+ return function callableDecorator(target, context) {
52
+ if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
53
+ return target;
54
+ };
55
+ }
56
+ let didWarnAboutUnstableCallable = false;
57
+ /**
58
+ * Decorator that marks a method as callable by clients
59
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
60
+ * @param metadata Optional metadata about the callable method
61
+ */
62
+ const unstable_callable = (metadata = {}) => {
63
+ if (!didWarnAboutUnstableCallable) {
64
+ didWarnAboutUnstableCallable = true;
65
+ console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
66
+ }
67
+ callable(metadata);
68
+ };
69
+ function getNextCronTime(cron) {
70
+ return parseCronExpression(cron).getNextDate();
71
+ }
72
+ const STATE_ROW_ID = "cf_state_row_id";
73
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
74
+ const DEFAULT_STATE = {};
75
+ const agentContext = new AsyncLocalStorage();
76
+ function getCurrentAgent() {
77
+ const store = agentContext.getStore();
78
+ if (!store) return {
79
+ agent: void 0,
80
+ connection: void 0,
81
+ request: void 0,
82
+ email: void 0
83
+ };
84
+ return store;
85
+ }
86
+ /**
87
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
88
+ * @param agent The agent instance
89
+ * @param method The method to wrap
90
+ * @returns A wrapped method that runs within the agent context
91
+ */
92
+ function withAgentContext(method) {
93
+ return function(...args) {
94
+ const { connection, request, email, agent } = getCurrentAgent();
95
+ if (agent === this) return method.apply(this, args);
96
+ return agentContext.run({
97
+ agent: this,
98
+ connection,
99
+ request,
100
+ email
101
+ }, () => {
102
+ return method.apply(this, args);
103
+ });
104
+ };
105
+ }
106
+ /**
107
+ * Base class for creating Agent implementations
108
+ * @template Env Environment type containing bindings
109
+ * @template State State type to store within the Agent
110
+ */
111
+ var Agent = class Agent extends Server {
112
+ /**
113
+ * Current state of the Agent
114
+ */
115
+ get state() {
116
+ if (this._state !== DEFAULT_STATE) return this._state;
117
+ const wasChanged = this.sql`
118
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
119
+ `;
120
+ const result = this.sql`
121
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
122
+ `;
123
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
124
+ const state = result[0]?.state;
125
+ this._state = JSON.parse(state);
126
+ return this._state;
127
+ }
128
+ if (this.initialState === DEFAULT_STATE) return;
129
+ this.setState(this.initialState);
130
+ return this.initialState;
131
+ }
132
+ static {
133
+ this.options = { hibernate: true };
134
+ }
135
+ /**
136
+ * Execute SQL queries against the Agent's database
137
+ * @template T Type of the returned rows
138
+ * @param strings SQL query template strings
139
+ * @param values Values to be inserted into the query
140
+ * @returns Array of query results
141
+ */
142
+ sql(strings, ...values) {
143
+ let query = "";
144
+ try {
145
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
146
+ return [...this.ctx.storage.sql.exec(query, ...values)];
147
+ } catch (e) {
148
+ console.error(`failed to execute sql query: ${query}`, e);
149
+ throw this.onError(e);
150
+ }
151
+ }
152
+ constructor(ctx, env) {
153
+ super(ctx, env);
154
+ this._state = DEFAULT_STATE;
155
+ this._disposables = new DisposableStore();
156
+ this._destroyed = false;
157
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
158
+ this.initialState = DEFAULT_STATE;
159
+ this.observability = genericObservability;
160
+ this._flushingQueue = false;
161
+ this.alarm = async () => {
162
+ const now = Math.floor(Date.now() / 1e3);
163
+ const result = this.sql`
164
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
165
+ `;
166
+ if (result && Array.isArray(result)) for (const row of result) {
167
+ const callback = this[row.callback];
168
+ if (!callback) {
169
+ console.error(`callback ${row.callback} not found`);
170
+ continue;
171
+ }
172
+ await agentContext.run({
173
+ agent: this,
174
+ connection: void 0,
175
+ request: void 0,
176
+ email: void 0
177
+ }, async () => {
178
+ try {
179
+ this.observability?.emit({
180
+ displayMessage: `Schedule ${row.id} executed`,
181
+ id: nanoid(),
182
+ payload: {
183
+ callback: row.callback,
184
+ id: row.id
185
+ },
186
+ timestamp: Date.now(),
187
+ type: "schedule:execute"
188
+ }, this.ctx);
189
+ await callback.bind(this)(JSON.parse(row.payload), row);
190
+ } catch (e) {
191
+ console.error(`error executing callback "${row.callback}"`, e);
192
+ }
193
+ });
194
+ if (row.type === "cron") {
195
+ if (this._destroyed) return;
196
+ const nextExecutionTime = getNextCronTime(row.cron);
197
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
198
+ this.sql`
199
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
200
+ `;
201
+ } else {
202
+ if (this._destroyed) return;
203
+ this.sql`
204
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
205
+ `;
206
+ }
207
+ }
208
+ if (this._destroyed) return;
209
+ await this._scheduleNextAlarm();
210
+ };
211
+ if (!wrappedClasses.has(this.constructor)) {
212
+ this._autoWrapCustomMethods();
213
+ wrappedClasses.add(this.constructor);
214
+ }
215
+ this.sql`
216
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
217
+ id TEXT PRIMARY KEY NOT NULL,
218
+ name TEXT NOT NULL,
219
+ server_url TEXT NOT NULL,
220
+ callback_url TEXT NOT NULL,
221
+ client_id TEXT,
222
+ auth_url TEXT,
223
+ server_options TEXT
224
+ )
225
+ `;
226
+ this.sql`
227
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
228
+ id TEXT PRIMARY KEY NOT NULL,
229
+ state TEXT
230
+ )
231
+ `;
232
+ this.sql`
233
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
234
+ id TEXT PRIMARY KEY NOT NULL,
235
+ payload TEXT,
236
+ callback TEXT,
237
+ created_at INTEGER DEFAULT (unixepoch())
238
+ )
239
+ `;
240
+ this.sql`
241
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
242
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
243
+ callback TEXT,
244
+ payload TEXT,
245
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
246
+ time INTEGER,
247
+ delayInSeconds INTEGER,
248
+ cron TEXT,
249
+ created_at INTEGER DEFAULT (unixepoch())
250
+ )
251
+ `;
252
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
253
+ this._disposables.add(this.mcp.onServerStateChanged(async () => {
254
+ this.broadcastMcpServers();
255
+ }));
256
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
257
+ this.observability?.emit(event);
258
+ }));
259
+ const _onRequest = this.onRequest.bind(this);
260
+ this.onRequest = (request) => {
261
+ return agentContext.run({
262
+ agent: this,
263
+ connection: void 0,
264
+ request,
265
+ email: void 0
266
+ }, async () => {
267
+ await this.mcp.ensureJsonSchema();
268
+ const oauthResponse = await this.handleMcpOAuthCallback(request);
269
+ if (oauthResponse) return oauthResponse;
270
+ return this._tryCatch(() => _onRequest(request));
271
+ });
272
+ };
273
+ const _onMessage = this.onMessage.bind(this);
274
+ this.onMessage = async (connection, message) => {
275
+ return agentContext.run({
276
+ agent: this,
277
+ connection,
278
+ request: void 0,
279
+ email: void 0
280
+ }, async () => {
281
+ await this.mcp.ensureJsonSchema();
282
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
283
+ let parsed;
284
+ try {
285
+ parsed = JSON.parse(message);
286
+ } catch (_e) {
287
+ return this._tryCatch(() => _onMessage(connection, message));
288
+ }
289
+ if (isStateUpdateMessage(parsed)) {
290
+ this._setStateInternal(parsed.state, connection);
291
+ return;
292
+ }
293
+ if (isRPCRequest(parsed)) {
294
+ try {
295
+ const { id, method, args } = parsed;
296
+ const methodFn = this[method];
297
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
298
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
299
+ const metadata = callableMetadata.get(methodFn);
300
+ if (metadata?.streaming) {
301
+ const stream = new StreamingResponse(connection, id);
302
+ await methodFn.apply(this, [stream, ...args]);
303
+ return;
304
+ }
305
+ const result = await methodFn.apply(this, args);
306
+ this.observability?.emit({
307
+ displayMessage: `RPC call to ${method}`,
308
+ id: nanoid(),
309
+ payload: {
310
+ method,
311
+ streaming: metadata?.streaming
312
+ },
313
+ timestamp: Date.now(),
314
+ type: "rpc"
315
+ }, this.ctx);
316
+ const response = {
317
+ done: true,
318
+ id,
319
+ result,
320
+ success: true,
321
+ type: MessageType.RPC
322
+ };
323
+ connection.send(JSON.stringify(response));
324
+ } catch (e) {
325
+ const response = {
326
+ error: e instanceof Error ? e.message : "Unknown error occurred",
327
+ id: parsed.id,
328
+ success: false,
329
+ type: MessageType.RPC
330
+ };
331
+ connection.send(JSON.stringify(response));
332
+ console.error("RPC error:", e);
333
+ }
334
+ return;
335
+ }
336
+ return this._tryCatch(() => _onMessage(connection, message));
337
+ });
338
+ };
339
+ const _onConnect = this.onConnect.bind(this);
340
+ this.onConnect = (connection, ctx$1) => {
341
+ return agentContext.run({
342
+ agent: this,
343
+ connection,
344
+ request: ctx$1.request,
345
+ email: void 0
346
+ }, async () => {
347
+ if (this.state) connection.send(JSON.stringify({
348
+ state: this.state,
349
+ type: MessageType.CF_AGENT_STATE
350
+ }));
351
+ connection.send(JSON.stringify({
352
+ mcp: this.getMcpServers(),
353
+ type: MessageType.CF_AGENT_MCP_SERVERS
354
+ }));
355
+ this.observability?.emit({
356
+ displayMessage: "Connection established",
357
+ id: nanoid(),
358
+ payload: { connectionId: connection.id },
359
+ timestamp: Date.now(),
360
+ type: "connect"
361
+ }, this.ctx);
362
+ return this._tryCatch(() => _onConnect(connection, ctx$1));
363
+ });
364
+ };
365
+ const _onStart = this.onStart.bind(this);
366
+ this.onStart = async (props) => {
367
+ return agentContext.run({
368
+ agent: this,
369
+ connection: void 0,
370
+ request: void 0,
371
+ email: void 0
372
+ }, async () => {
373
+ await this._tryCatch(async () => {
374
+ await this.mcp.restoreConnectionsFromStorage(this.name);
375
+ this.broadcastMcpServers();
376
+ return _onStart(props);
377
+ });
378
+ });
379
+ };
380
+ }
381
+ _setStateInternal(state, source = "server") {
382
+ this._state = state;
383
+ this.sql`
384
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
385
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
386
+ `;
387
+ this.sql`
388
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
389
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
390
+ `;
391
+ this.broadcast(JSON.stringify({
392
+ state,
393
+ type: MessageType.CF_AGENT_STATE
394
+ }), source !== "server" ? [source.id] : []);
395
+ return this._tryCatch(() => {
396
+ const { connection, request, email } = agentContext.getStore() || {};
397
+ return agentContext.run({
398
+ agent: this,
399
+ connection,
400
+ request,
401
+ email
402
+ }, async () => {
403
+ this.observability?.emit({
404
+ displayMessage: "State updated",
405
+ id: nanoid(),
406
+ payload: {},
407
+ timestamp: Date.now(),
408
+ type: "state:update"
409
+ }, this.ctx);
410
+ return this.onStateUpdate(state, source);
411
+ });
412
+ });
413
+ }
414
+ /**
415
+ * Update the Agent's state
416
+ * @param state New state to set
417
+ */
418
+ setState(state) {
419
+ this._setStateInternal(state, "server");
420
+ }
421
+ /**
422
+ * Called when the Agent's state is updated
423
+ * @param state Updated state
424
+ * @param source Source of the state update ("server" or a client connection)
425
+ */
426
+ onStateUpdate(state, source) {}
427
+ /**
428
+ * Called when the Agent receives an email via routeAgentEmail()
429
+ * Override this method to handle incoming emails
430
+ * @param email Email message to process
431
+ */
432
+ async _onEmail(email) {
433
+ return agentContext.run({
434
+ agent: this,
435
+ connection: void 0,
436
+ request: void 0,
437
+ email
438
+ }, async () => {
439
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
440
+ else {
441
+ console.log("Received email from:", email.from, "to:", email.to);
442
+ console.log("Subject:", email.headers.get("subject"));
443
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
444
+ }
445
+ });
446
+ }
447
+ /**
448
+ * Reply to an email
449
+ * @param email The email to reply to
450
+ * @param options Options for the reply
451
+ * @returns void
452
+ */
453
+ async replyToEmail(email, options) {
454
+ return this._tryCatch(async () => {
455
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
456
+ const agentId = this.name;
457
+ const { createMimeMessage } = await import("mimetext");
458
+ const msg = createMimeMessage();
459
+ msg.setSender({
460
+ addr: email.to,
461
+ name: options.fromName
462
+ });
463
+ msg.setRecipient(email.from);
464
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
465
+ msg.addMessage({
466
+ contentType: options.contentType || "text/plain",
467
+ data: options.body
468
+ });
469
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
470
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
471
+ msg.setHeader("Message-ID", messageId);
472
+ msg.setHeader("X-Agent-Name", agentName);
473
+ msg.setHeader("X-Agent-ID", agentId);
474
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
475
+ await email.reply({
476
+ from: email.to,
477
+ raw: msg.asRaw(),
478
+ to: email.from
479
+ });
480
+ });
481
+ }
482
+ async _tryCatch(fn) {
483
+ try {
484
+ return await fn();
485
+ } catch (e) {
486
+ throw this.onError(e);
487
+ }
488
+ }
489
+ /**
490
+ * Automatically wrap custom methods with agent context
491
+ * This ensures getCurrentAgent() works in all custom methods without decorators
492
+ */
493
+ _autoWrapCustomMethods() {
494
+ const basePrototypes = [Agent.prototype, Server.prototype];
495
+ const baseMethods = /* @__PURE__ */ new Set();
496
+ for (const baseProto of basePrototypes) {
497
+ let proto$1 = baseProto;
498
+ while (proto$1 && proto$1 !== Object.prototype) {
499
+ const methodNames = Object.getOwnPropertyNames(proto$1);
500
+ for (const methodName of methodNames) baseMethods.add(methodName);
501
+ proto$1 = Object.getPrototypeOf(proto$1);
502
+ }
503
+ }
504
+ let proto = Object.getPrototypeOf(this);
505
+ let depth = 0;
506
+ while (proto && proto !== Object.prototype && depth < 10) {
507
+ const methodNames = Object.getOwnPropertyNames(proto);
508
+ for (const methodName of methodNames) {
509
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
510
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
511
+ const wrappedFunction = withAgentContext(this[methodName]);
512
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
513
+ this.constructor.prototype[methodName] = wrappedFunction;
514
+ }
515
+ proto = Object.getPrototypeOf(proto);
516
+ depth++;
517
+ }
518
+ }
519
+ onError(connectionOrError, error) {
520
+ let theError;
521
+ if (connectionOrError && error) {
522
+ theError = error;
523
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
524
+ console.error("Override onError(connection, error) to handle websocket connection errors");
525
+ } else {
526
+ theError = connectionOrError;
527
+ console.error("Error on server:", theError);
528
+ console.error("Override onError(error) to handle server errors");
529
+ }
530
+ throw theError;
531
+ }
532
+ /**
533
+ * Render content (not implemented in base class)
534
+ */
535
+ render() {
536
+ throw new Error("Not implemented");
537
+ }
538
+ /**
539
+ * Queue a task to be executed in the future
540
+ * @param payload Payload to pass to the callback
541
+ * @param callback Name of the method to call
542
+ * @returns The ID of the queued task
543
+ */
544
+ async queue(callback, payload) {
545
+ const id = nanoid(9);
546
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
547
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
548
+ this.sql`
549
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
550
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
551
+ `;
552
+ this._flushQueue().catch((e) => {
553
+ console.error("Error flushing queue:", e);
554
+ });
555
+ return id;
556
+ }
557
+ async _flushQueue() {
558
+ if (this._flushingQueue) return;
559
+ this._flushingQueue = true;
560
+ while (true) {
561
+ const result = this.sql`
562
+ SELECT * FROM cf_agents_queues
563
+ ORDER BY created_at ASC
564
+ `;
565
+ if (!result || result.length === 0) break;
566
+ for (const row of result || []) {
567
+ const callback = this[row.callback];
568
+ if (!callback) {
569
+ console.error(`callback ${row.callback} not found`);
570
+ continue;
571
+ }
572
+ const { connection, request, email } = agentContext.getStore() || {};
573
+ await agentContext.run({
574
+ agent: this,
575
+ connection,
576
+ request,
577
+ email
578
+ }, async () => {
579
+ await callback.bind(this)(JSON.parse(row.payload), row);
580
+ await this.dequeue(row.id);
581
+ });
582
+ }
583
+ }
584
+ this._flushingQueue = false;
585
+ }
586
+ /**
587
+ * Dequeue a task by ID
588
+ * @param id ID of the task to dequeue
589
+ */
590
+ async dequeue(id) {
591
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
592
+ }
593
+ /**
594
+ * Dequeue all tasks
595
+ */
596
+ async dequeueAll() {
597
+ this.sql`DELETE FROM cf_agents_queues`;
598
+ }
599
+ /**
600
+ * Dequeue all tasks by callback
601
+ * @param callback Name of the callback to dequeue
602
+ */
603
+ async dequeueAllByCallback(callback) {
604
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
605
+ }
606
+ /**
607
+ * Get a queued task by ID
608
+ * @param id ID of the task to get
609
+ * @returns The task or undefined if not found
610
+ */
611
+ async getQueue(id) {
612
+ const result = this.sql`
613
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
614
+ `;
615
+ return result ? {
616
+ ...result[0],
617
+ payload: JSON.parse(result[0].payload)
618
+ } : void 0;
619
+ }
620
+ /**
621
+ * Get all queues by key and value
622
+ * @param key Key to filter by
623
+ * @param value Value to filter by
624
+ * @returns Array of matching QueueItem objects
625
+ */
626
+ async getQueues(key, value) {
627
+ return this.sql`
628
+ SELECT * FROM cf_agents_queues
629
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
630
+ }
631
+ /**
632
+ * Schedule a task to be executed in the future
633
+ * @template T Type of the payload data
634
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
635
+ * @param callback Name of the method to call
636
+ * @param payload Data to pass to the callback
637
+ * @returns Schedule object representing the scheduled task
638
+ */
639
+ async schedule(when, callback, payload) {
640
+ const id = nanoid(9);
641
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
642
+ displayMessage: `Schedule ${schedule.id} created`,
643
+ id: nanoid(),
644
+ payload: {
645
+ callback,
646
+ id
647
+ },
648
+ timestamp: Date.now(),
649
+ type: "schedule:create"
650
+ }, this.ctx);
651
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
652
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
653
+ if (when instanceof Date) {
654
+ const timestamp = Math.floor(when.getTime() / 1e3);
655
+ this.sql`
656
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
657
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
658
+ `;
659
+ await this._scheduleNextAlarm();
660
+ const schedule = {
661
+ callback,
662
+ id,
663
+ payload,
664
+ time: timestamp,
665
+ type: "scheduled"
666
+ };
667
+ emitScheduleCreate(schedule);
668
+ return schedule;
669
+ }
670
+ if (typeof when === "number") {
671
+ const time = new Date(Date.now() + when * 1e3);
672
+ const timestamp = Math.floor(time.getTime() / 1e3);
673
+ this.sql`
674
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
675
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
676
+ `;
677
+ await this._scheduleNextAlarm();
678
+ const schedule = {
679
+ callback,
680
+ delayInSeconds: when,
681
+ id,
682
+ payload,
683
+ time: timestamp,
684
+ type: "delayed"
685
+ };
686
+ emitScheduleCreate(schedule);
687
+ return schedule;
688
+ }
689
+ if (typeof when === "string") {
690
+ const nextExecutionTime = getNextCronTime(when);
691
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
692
+ this.sql`
693
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
694
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
695
+ `;
696
+ await this._scheduleNextAlarm();
697
+ const schedule = {
698
+ callback,
699
+ cron: when,
700
+ id,
701
+ payload,
702
+ time: timestamp,
703
+ type: "cron"
704
+ };
705
+ emitScheduleCreate(schedule);
706
+ return schedule;
707
+ }
708
+ throw new Error("Invalid schedule type");
709
+ }
710
+ /**
711
+ * Get a scheduled task by ID
712
+ * @template T Type of the payload data
713
+ * @param id ID of the scheduled task
714
+ * @returns The Schedule object or undefined if not found
715
+ */
716
+ async getSchedule(id) {
717
+ const result = this.sql`
718
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
719
+ `;
720
+ if (!result) {
721
+ console.error(`schedule ${id} not found`);
722
+ return;
723
+ }
724
+ return {
725
+ ...result[0],
726
+ payload: JSON.parse(result[0].payload)
727
+ };
728
+ }
729
+ /**
730
+ * Get scheduled tasks matching the given criteria
731
+ * @template T Type of the payload data
732
+ * @param criteria Criteria to filter schedules
733
+ * @returns Array of matching Schedule objects
734
+ */
735
+ getSchedules(criteria = {}) {
736
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
737
+ const params = [];
738
+ if (criteria.id) {
739
+ query += " AND id = ?";
740
+ params.push(criteria.id);
741
+ }
742
+ if (criteria.type) {
743
+ query += " AND type = ?";
744
+ params.push(criteria.type);
745
+ }
746
+ if (criteria.timeRange) {
747
+ query += " AND time >= ? AND time <= ?";
748
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
749
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
750
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
751
+ }
752
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
753
+ ...row,
754
+ payload: JSON.parse(row.payload)
755
+ }));
756
+ }
757
+ /**
758
+ * Cancel a scheduled task
759
+ * @param id ID of the task to cancel
760
+ * @returns true if the task was cancelled, false otherwise
761
+ */
762
+ async cancelSchedule(id) {
763
+ const schedule = await this.getSchedule(id);
764
+ if (schedule) this.observability?.emit({
765
+ displayMessage: `Schedule ${id} cancelled`,
766
+ id: nanoid(),
767
+ payload: {
768
+ callback: schedule.callback,
769
+ id: schedule.id
770
+ },
771
+ timestamp: Date.now(),
772
+ type: "schedule:cancel"
773
+ }, this.ctx);
774
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
775
+ await this._scheduleNextAlarm();
776
+ return true;
777
+ }
778
+ async _scheduleNextAlarm() {
779
+ const result = this.sql`
780
+ SELECT time FROM cf_agents_schedules
781
+ WHERE time >= ${Math.floor(Date.now() / 1e3)}
782
+ ORDER BY time ASC
783
+ LIMIT 1
784
+ `;
785
+ if (!result) return;
786
+ if (result.length > 0 && "time" in result[0]) {
787
+ const nextTime = result[0].time * 1e3;
788
+ await this.ctx.storage.setAlarm(nextTime);
789
+ }
790
+ }
791
+ /**
792
+ * Destroy the Agent, removing all state and scheduled tasks
793
+ */
794
+ async destroy() {
795
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
796
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
797
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
798
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
799
+ await this.ctx.storage.deleteAlarm();
800
+ await this.ctx.storage.deleteAll();
801
+ this._disposables.dispose();
802
+ await this.mcp.dispose();
803
+ this._destroyed = true;
804
+ setTimeout(() => {
805
+ this.ctx.abort("destroyed");
806
+ }, 0);
807
+ this.observability?.emit({
808
+ displayMessage: "Agent destroyed",
809
+ id: nanoid(),
810
+ payload: {},
811
+ timestamp: Date.now(),
812
+ type: "destroy"
813
+ }, this.ctx);
814
+ }
815
+ /**
816
+ * Get all methods marked as callable on this Agent
817
+ * @returns A map of method names to their metadata
818
+ */
819
+ _isCallable(method) {
820
+ return callableMetadata.has(this[method]);
821
+ }
822
+ /**
823
+ * Connect to a new MCP Server
824
+ *
825
+ * @param serverName Name of the MCP server
826
+ * @param url MCP Server SSE URL
827
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
828
+ * @param agentsPrefix agents routing prefix if not using `agents`
829
+ * @param options MCP client and transport options
830
+ * @returns Server id and state - either "authenticating" with authUrl, or "ready"
831
+ * @throws If connection or discovery fails
832
+ */
833
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
834
+ let resolvedCallbackHost = callbackHost;
835
+ if (!resolvedCallbackHost) {
836
+ const { request } = getCurrentAgent();
837
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
838
+ const requestUrl = new URL(request.url);
839
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
840
+ }
841
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
842
+ await this.mcp.ensureJsonSchema();
843
+ const id = nanoid(8);
844
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
845
+ authProvider.serverId = id;
846
+ const transportType = options?.transport?.type ?? "auto";
847
+ let headerTransportOpts = {};
848
+ if (options?.transport?.headers) headerTransportOpts = {
849
+ eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
850
+ ...init,
851
+ headers: options?.transport?.headers
852
+ }) },
853
+ requestInit: { headers: options?.transport?.headers }
854
+ };
855
+ await this.mcp.registerServer(id, {
856
+ url,
857
+ name: serverName,
858
+ callbackUrl,
859
+ client: options?.client,
860
+ transport: {
861
+ ...headerTransportOpts,
862
+ authProvider,
863
+ type: transportType
864
+ }
865
+ });
866
+ const result = await this.mcp.connectToServer(id);
867
+ if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
868
+ if (result.state === MCPConnectionState.AUTHENTICATING) return {
869
+ id,
870
+ state: result.state,
871
+ authUrl: result.authUrl
872
+ };
873
+ const discoverResult = await this.mcp.discoverIfConnected(id);
874
+ if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
875
+ return {
876
+ id,
877
+ state: MCPConnectionState.READY
878
+ };
879
+ }
880
+ async removeMcpServer(id) {
881
+ await this.mcp.removeServer(id);
882
+ }
883
+ getMcpServers() {
884
+ const mcpState = {
885
+ prompts: this.mcp.listPrompts(),
886
+ resources: this.mcp.listResources(),
887
+ servers: {},
888
+ tools: this.mcp.listTools()
889
+ };
890
+ const servers = this.mcp.listServers();
891
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
892
+ const serverConn = this.mcp.mcpConnections[server.id];
893
+ let defaultState = "not-connected";
894
+ if (!serverConn && server.auth_url) defaultState = "authenticating";
895
+ mcpState.servers[server.id] = {
896
+ auth_url: server.auth_url,
897
+ capabilities: serverConn?.serverCapabilities ?? null,
898
+ instructions: serverConn?.instructions ?? null,
899
+ name: server.name,
900
+ server_url: server.server_url,
901
+ state: serverConn?.connectionState ?? defaultState
902
+ };
903
+ }
904
+ return mcpState;
905
+ }
906
+ broadcastMcpServers() {
907
+ this.broadcast(JSON.stringify({
908
+ mcp: this.getMcpServers(),
909
+ type: MessageType.CF_AGENT_MCP_SERVERS
910
+ }));
911
+ }
912
+ /**
913
+ * Handle MCP OAuth callback request if it's an OAuth callback.
914
+ *
915
+ * This method encapsulates the entire OAuth callback flow:
916
+ * 1. Checks if the request is an MCP OAuth callback
917
+ * 2. Processes the OAuth code exchange
918
+ * 3. Establishes the connection if successful
919
+ * 4. Broadcasts MCP server state updates
920
+ * 5. Returns the appropriate HTTP response
921
+ *
922
+ * @param request The incoming HTTP request
923
+ * @returns Response if this was an OAuth callback, null otherwise
924
+ */
925
+ async handleMcpOAuthCallback(request) {
926
+ if (!this.mcp.isCallbackRequest(request)) return null;
927
+ const result = await this.mcp.handleCallbackRequest(request);
928
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
929
+ console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
930
+ });
931
+ this.broadcastMcpServers();
932
+ return this.handleOAuthCallbackResponse(result, request);
933
+ }
934
+ /**
935
+ * Handle OAuth callback response using MCPClientManager configuration
936
+ * @param result OAuth callback result
937
+ * @param request The original request (needed for base URL)
938
+ * @returns Response for the OAuth callback
939
+ */
940
+ handleOAuthCallbackResponse(result, request) {
941
+ const config = this.mcp.getOAuthCallbackConfig();
942
+ if (config?.customHandler) return config.customHandler(result);
943
+ const baseOrigin = new URL(request.url).origin;
944
+ if (config?.successRedirect && result.authSuccess) try {
945
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
946
+ } catch (e) {
947
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
948
+ return Response.redirect(baseOrigin);
949
+ }
950
+ if (config?.errorRedirect && !result.authSuccess) try {
951
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
952
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
953
+ } catch (e) {
954
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
955
+ return Response.redirect(baseOrigin);
956
+ }
957
+ return Response.redirect(baseOrigin);
958
+ }
959
+ };
960
+ const wrappedClasses = /* @__PURE__ */ new Set();
961
+ /**
962
+ * Route a request to the appropriate Agent
963
+ * @param request Request to route
964
+ * @param env Environment containing Agent bindings
965
+ * @param options Routing options
966
+ * @returns Response from the Agent or undefined if no route matched
967
+ */
968
+ async function routeAgentRequest(request, env, options) {
969
+ const corsHeaders = options?.cors === true ? {
970
+ "Access-Control-Allow-Credentials": "true",
971
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
972
+ "Access-Control-Allow-Origin": "*",
973
+ "Access-Control-Max-Age": "86400"
974
+ } : options?.cors;
975
+ if (request.method === "OPTIONS") {
976
+ if (corsHeaders) return new Response(null, { headers: corsHeaders });
977
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
978
+ }
979
+ let response = await routePartykitRequest(request, env, {
980
+ prefix: "agents",
981
+ ...options
982
+ });
983
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
984
+ const newHeaders = new Headers(response.headers);
985
+ for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
986
+ response = new Response(response.body, {
987
+ status: response.status,
988
+ statusText: response.statusText,
989
+ headers: newHeaders
990
+ });
991
+ }
992
+ return response;
993
+ }
994
+ /**
995
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
996
+ * @returns A function that resolves the agent to route the email to
997
+ */
998
+ function createHeaderBasedEmailResolver() {
999
+ return async (email, _env) => {
1000
+ const messageId = email.headers.get("message-id");
1001
+ if (messageId) {
1002
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
1003
+ if (messageIdMatch) {
1004
+ const [, agentId$1, domain] = messageIdMatch;
1005
+ return {
1006
+ agentName: domain.split(".")[0],
1007
+ agentId: agentId$1
1008
+ };
1009
+ }
1010
+ }
1011
+ const references = email.headers.get("references");
1012
+ if (references) {
1013
+ const referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);
1014
+ if (referencesMatch) {
1015
+ const [, base64Id, domain] = referencesMatch;
1016
+ const agentId$1 = Buffer.from(base64Id, "base64").toString("hex");
1017
+ return {
1018
+ agentName: domain.split(".")[0],
1019
+ agentId: agentId$1
1020
+ };
1021
+ }
1022
+ }
1023
+ const agentName = email.headers.get("x-agent-name");
1024
+ const agentId = email.headers.get("x-agent-id");
1025
+ if (agentName && agentId) return {
1026
+ agentName,
1027
+ agentId
1028
+ };
1029
+ return null;
1030
+ };
1031
+ }
1032
+ /**
1033
+ * Create a resolver that uses the email address to determine the agent to route the email to
1034
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
1035
+ * @returns A function that resolves the agent to route the email to
1036
+ */
1037
+ function createAddressBasedEmailResolver(defaultAgentName) {
1038
+ return async (email, _env) => {
1039
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
1040
+ if (!emailMatch) return null;
1041
+ const [, localPart, subAddress] = emailMatch;
1042
+ if (subAddress) return {
1043
+ agentName: localPart,
1044
+ agentId: subAddress
1045
+ };
1046
+ return {
1047
+ agentName: defaultAgentName,
1048
+ agentId: localPart
1049
+ };
1050
+ };
1051
+ }
1052
+ /**
1053
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
1054
+ * @param agentName The name of the agent to route the email to
1055
+ * @param agentId The id of the agent to route the email to
1056
+ * @returns A function that resolves the agent to route the email to
1057
+ */
1058
+ function createCatchAllEmailResolver(agentName, agentId) {
1059
+ return async () => ({
1060
+ agentName,
1061
+ agentId
1062
+ });
1063
+ }
1064
+ const agentMapCache = /* @__PURE__ */ new WeakMap();
1065
+ /**
1066
+ * Route an email to the appropriate Agent
1067
+ * @param email The email to route
1068
+ * @param env The environment containing the Agent bindings
1069
+ * @param options The options for routing the email
1070
+ * @returns A promise that resolves when the email has been routed
1071
+ */
1072
+ async function routeAgentEmail(email, env, options) {
1073
+ const routingInfo = await options.resolver(email, env);
1074
+ if (!routingInfo) {
1075
+ console.warn("No routing information found for email, dropping message");
1076
+ return;
1077
+ }
1078
+ if (!agentMapCache.has(env)) {
1079
+ const map = {};
1080
+ for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
1081
+ map[key] = value;
1082
+ map[camelCaseToKebabCase(key)] = value;
1083
+ }
1084
+ agentMapCache.set(env, map);
1085
+ }
1086
+ const agentMap = agentMapCache.get(env);
1087
+ const namespace = agentMap[routingInfo.agentName];
1088
+ if (!namespace) {
1089
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
1090
+ throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
1091
+ }
1092
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
1093
+ const serialisableEmail = {
1094
+ getRaw: async () => {
1095
+ const reader = email.raw.getReader();
1096
+ const chunks = [];
1097
+ let done = false;
1098
+ while (!done) {
1099
+ const { value, done: readerDone } = await reader.read();
1100
+ done = readerDone;
1101
+ if (value) chunks.push(value);
1102
+ }
1103
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
1104
+ const combined = new Uint8Array(totalLength);
1105
+ let offset = 0;
1106
+ for (const chunk of chunks) {
1107
+ combined.set(chunk, offset);
1108
+ offset += chunk.length;
1109
+ }
1110
+ return combined;
1111
+ },
1112
+ headers: email.headers,
1113
+ rawSize: email.rawSize,
1114
+ setReject: (reason) => {
1115
+ email.setReject(reason);
1116
+ },
1117
+ forward: (rcptTo, headers) => {
1118
+ return email.forward(rcptTo, headers);
1119
+ },
1120
+ reply: (options$1) => {
1121
+ return email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));
1122
+ },
1123
+ from: email.from,
1124
+ to: email.to
1125
+ };
1126
+ await agent._onEmail(serialisableEmail);
1127
+ }
1128
+ /**
1129
+ * Get or create an Agent by name
1130
+ * @template Env Environment type containing bindings
1131
+ * @template T Type of the Agent class
1132
+ * @param namespace Agent namespace
1133
+ * @param name Name of the Agent instance
1134
+ * @param options Options for Agent creation
1135
+ * @returns Promise resolving to an Agent instance stub
1136
+ */
1137
+ async function getAgentByName(namespace, name, options) {
1138
+ return getServerByName(namespace, name, options);
1139
+ }
1140
+ /**
1141
+ * A wrapper for streaming responses in callable methods
1142
+ */
1143
+ var StreamingResponse = class {
1144
+ constructor(connection, id) {
1145
+ this._closed = false;
1146
+ this._connection = connection;
1147
+ this._id = id;
1148
+ }
1149
+ /**
1150
+ * Send a chunk of data to the client
1151
+ * @param chunk The data to send
1152
+ */
1153
+ send(chunk) {
1154
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1155
+ const response = {
1156
+ done: false,
1157
+ id: this._id,
1158
+ result: chunk,
1159
+ success: true,
1160
+ type: MessageType.RPC
1161
+ };
1162
+ this._connection.send(JSON.stringify(response));
1163
+ }
1164
+ /**
1165
+ * End the stream and send the final chunk (if any)
1166
+ * @param finalChunk Optional final chunk of data to send
1167
+ */
1168
+ end(finalChunk) {
1169
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1170
+ this._closed = true;
1171
+ const response = {
1172
+ done: true,
1173
+ id: this._id,
1174
+ result: finalChunk,
1175
+ success: true,
1176
+ type: MessageType.RPC
1177
+ };
1178
+ this._connection.send(JSON.stringify(response));
1179
+ }
1180
+ };
1181
+
1182
+ //#endregion
1183
+ export { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };
1184
+ //# sourceMappingURL=src-D_KKH_4c.js.map