agents 0.0.0-fd36bbc → 0.0.0-fd59ae2

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