agents 0.0.0-ad0054b → 0.0.0-b123357

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 +128 -22
  2. package/dist/ai-chat-agent.d.ts +35 -6
  3. package/dist/ai-chat-agent.js +149 -115
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +20 -5
  6. package/dist/ai-react.js +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/{chunk-Q5ZBHY4Z.js → chunk-HY7ZLHJB.js} +193 -51
  9. package/dist/chunk-HY7ZLHJB.js.map +1 -0
  10. package/dist/chunk-KUH345EY.js +116 -0
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/chunk-OJFA7RKX.js +1270 -0
  13. package/dist/chunk-OJFA7RKX.js.map +1 -0
  14. package/dist/chunk-PVQZBKN7.js +106 -0
  15. package/dist/chunk-PVQZBKN7.js.map +1 -0
  16. package/dist/client-DgyzBU_8.d.ts +4601 -0
  17. package/dist/client.d.ts +16 -2
  18. package/dist/client.js +6 -126
  19. package/dist/client.js.map +1 -1
  20. package/dist/index-BCJclX6q.d.ts +615 -0
  21. package/dist/index.d.ts +35 -308
  22. package/dist/index.js +10 -3
  23. package/dist/mcp/client.d.ts +9 -775
  24. package/dist/mcp/client.js +1 -2
  25. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  26. package/dist/mcp/do-oauth-client-provider.js +3 -103
  27. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  28. package/dist/mcp/index.d.ts +41 -14
  29. package/dist/mcp/index.js +278 -178
  30. package/dist/mcp/index.js.map +1 -1
  31. package/dist/observability/index.d.ts +14 -0
  32. package/dist/observability/index.js +10 -0
  33. package/dist/react.d.ts +87 -5
  34. package/dist/react.js +20 -8
  35. package/dist/react.js.map +1 -1
  36. package/dist/schedule.d.ts +10 -10
  37. package/dist/schedule.js +4 -6
  38. package/dist/schedule.js.map +1 -1
  39. package/dist/serializable.d.ts +32 -0
  40. package/dist/serializable.js +1 -0
  41. package/dist/serializable.js.map +1 -0
  42. package/package.json +76 -68
  43. package/src/index.ts +1093 -140
  44. package/dist/chunk-A65CRW2D.js +0 -609
  45. package/dist/chunk-A65CRW2D.js.map +0 -1
  46. package/dist/chunk-HMLY7DHA.js +0 -16
  47. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  48. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -1,609 +0,0 @@
1
- import {
2
- MCPClientManager
3
- } from "./chunk-Q5ZBHY4Z.js";
4
- import {
5
- __privateAdd,
6
- __privateGet,
7
- __privateMethod,
8
- __privateSet
9
- } from "./chunk-HMLY7DHA.js";
10
-
11
- // src/index.ts
12
- import {
13
- Server,
14
- routePartykitRequest,
15
- getServerByName
16
- } from "partyserver";
17
- import { parseCronExpression } from "cron-schedule";
18
- import { nanoid } from "nanoid";
19
- import { AsyncLocalStorage } from "node:async_hooks";
20
- function isRPCRequest(msg) {
21
- 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);
22
- }
23
- function isStateUpdateMessage(msg) {
24
- return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
25
- }
26
- var callableMetadata = /* @__PURE__ */ new Map();
27
- function unstable_callable(metadata = {}) {
28
- return function callableDecorator(target, context) {
29
- if (!callableMetadata.has(target)) {
30
- callableMetadata.set(target, metadata);
31
- }
32
- return target;
33
- };
34
- }
35
- function getNextCronTime(cron) {
36
- const interval = parseCronExpression(cron);
37
- return interval.getNextDate();
38
- }
39
- var STATE_ROW_ID = "cf_state_row_id";
40
- var STATE_WAS_CHANGED = "cf_state_was_changed";
41
- var DEFAULT_STATE = {};
42
- var agentContext = new AsyncLocalStorage();
43
- function getCurrentAgent() {
44
- const store = agentContext.getStore();
45
- if (!store) {
46
- return {
47
- agent: void 0,
48
- // yes I know this is icky
49
- connection: void 0,
50
- request: void 0
51
- };
52
- }
53
- return store;
54
- }
55
- var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
56
- var Agent = class extends Server {
57
- constructor(ctx, env) {
58
- super(ctx, env);
59
- __privateAdd(this, _Agent_instances);
60
- __privateAdd(this, _state, DEFAULT_STATE);
61
- __privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
62
- this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
63
- /**
64
- * Initial state for the Agent
65
- * Override to provide default state values
66
- */
67
- this.initialState = DEFAULT_STATE;
68
- this.sql`
69
- CREATE TABLE IF NOT EXISTS cf_agents_state (
70
- id TEXT PRIMARY KEY NOT NULL,
71
- state TEXT
72
- )
73
- `;
74
- void this.ctx.blockConcurrencyWhile(async () => {
75
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
76
- this.sql`
77
- CREATE TABLE IF NOT EXISTS cf_agents_schedules (
78
- id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
79
- callback TEXT,
80
- payload TEXT,
81
- type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
82
- time INTEGER,
83
- delayInSeconds INTEGER,
84
- cron TEXT,
85
- created_at INTEGER DEFAULT (unixepoch())
86
- )
87
- `;
88
- await this.alarm();
89
- });
90
- });
91
- const _onMessage = this.onMessage.bind(this);
92
- this.onMessage = async (connection, message) => {
93
- return agentContext.run(
94
- { agent: this, connection, request: void 0 },
95
- async () => {
96
- if (typeof message !== "string") {
97
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
98
- }
99
- let parsed;
100
- try {
101
- parsed = JSON.parse(message);
102
- } catch (e) {
103
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
104
- }
105
- if (isStateUpdateMessage(parsed)) {
106
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
107
- return;
108
- }
109
- if (isRPCRequest(parsed)) {
110
- try {
111
- const { id, method, args } = parsed;
112
- const methodFn = this[method];
113
- if (typeof methodFn !== "function") {
114
- throw new Error(`Method ${method} does not exist`);
115
- }
116
- if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
117
- throw new Error(`Method ${method} is not callable`);
118
- }
119
- const metadata = callableMetadata.get(methodFn);
120
- if (metadata?.streaming) {
121
- const stream = new StreamingResponse(connection, id);
122
- await methodFn.apply(this, [stream, ...args]);
123
- return;
124
- }
125
- const result = await methodFn.apply(this, args);
126
- const response = {
127
- type: "rpc",
128
- id,
129
- success: true,
130
- result,
131
- done: true
132
- };
133
- connection.send(JSON.stringify(response));
134
- } catch (e) {
135
- const response = {
136
- type: "rpc",
137
- id: parsed.id,
138
- success: false,
139
- error: e instanceof Error ? e.message : "Unknown error occurred"
140
- };
141
- connection.send(JSON.stringify(response));
142
- console.error("RPC error:", e);
143
- }
144
- return;
145
- }
146
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
147
- }
148
- );
149
- };
150
- const _onConnect = this.onConnect.bind(this);
151
- this.onConnect = (connection, ctx2) => {
152
- return agentContext.run(
153
- { agent: this, connection, request: ctx2.request },
154
- async () => {
155
- setTimeout(() => {
156
- if (this.state) {
157
- connection.send(
158
- JSON.stringify({
159
- type: "cf_agent_state",
160
- state: this.state
161
- })
162
- );
163
- }
164
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
165
- }, 20);
166
- }
167
- );
168
- };
169
- }
170
- /**
171
- * Current state of the Agent
172
- */
173
- get state() {
174
- if (__privateGet(this, _state) !== DEFAULT_STATE) {
175
- return __privateGet(this, _state);
176
- }
177
- const wasChanged = this.sql`
178
- SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
179
- `;
180
- const result = this.sql`
181
- SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
182
- `;
183
- if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
184
- result[0]?.state) {
185
- const state = result[0]?.state;
186
- __privateSet(this, _state, JSON.parse(state));
187
- return __privateGet(this, _state);
188
- }
189
- if (this.initialState === DEFAULT_STATE) {
190
- return void 0;
191
- }
192
- this.setState(this.initialState);
193
- return this.initialState;
194
- }
195
- /**
196
- * Execute SQL queries against the Agent's database
197
- * @template T Type of the returned rows
198
- * @param strings SQL query template strings
199
- * @param values Values to be inserted into the query
200
- * @returns Array of query results
201
- */
202
- sql(strings, ...values) {
203
- let query = "";
204
- try {
205
- query = strings.reduce(
206
- (acc, str, i) => acc + str + (i < values.length ? "?" : ""),
207
- ""
208
- );
209
- return [...this.ctx.storage.sql.exec(query, ...values)];
210
- } catch (e) {
211
- console.error(`failed to execute sql query: ${query}`, e);
212
- throw this.onError(e);
213
- }
214
- }
215
- /**
216
- * Update the Agent's state
217
- * @param state New state to set
218
- */
219
- setState(state) {
220
- __privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
221
- }
222
- /**
223
- * Called when the Agent's state is updated
224
- * @param state Updated state
225
- * @param source Source of the state update ("server" or a client connection)
226
- */
227
- onStateUpdate(state, source) {
228
- }
229
- /**
230
- * Called when the Agent receives an email
231
- * @param email Email message to process
232
- */
233
- onEmail(email) {
234
- return agentContext.run(
235
- { agent: this, connection: void 0, request: void 0 },
236
- async () => {
237
- console.error("onEmail not implemented");
238
- }
239
- );
240
- }
241
- onError(connectionOrError, error) {
242
- let theError;
243
- if (connectionOrError && error) {
244
- theError = error;
245
- console.error(
246
- "Error on websocket connection:",
247
- connectionOrError.id,
248
- theError
249
- );
250
- console.error(
251
- "Override onError(connection, error) to handle websocket connection errors"
252
- );
253
- } else {
254
- theError = connectionOrError;
255
- console.error("Error on server:", theError);
256
- console.error("Override onError(error) to handle server errors");
257
- }
258
- throw theError;
259
- }
260
- /**
261
- * Render content (not implemented in base class)
262
- */
263
- render() {
264
- throw new Error("Not implemented");
265
- }
266
- /**
267
- * Schedule a task to be executed in the future
268
- * @template T Type of the payload data
269
- * @param when When to execute the task (Date, seconds delay, or cron expression)
270
- * @param callback Name of the method to call
271
- * @param payload Data to pass to the callback
272
- * @returns Schedule object representing the scheduled task
273
- */
274
- async schedule(when, callback, payload) {
275
- const id = nanoid(9);
276
- if (typeof callback !== "string") {
277
- throw new Error("Callback must be a string");
278
- }
279
- if (typeof this[callback] !== "function") {
280
- throw new Error(`this.${callback} is not a function`);
281
- }
282
- if (when instanceof Date) {
283
- const timestamp = Math.floor(when.getTime() / 1e3);
284
- this.sql`
285
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
286
- VALUES (${id}, ${callback}, ${JSON.stringify(
287
- payload
288
- )}, 'scheduled', ${timestamp})
289
- `;
290
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
291
- return {
292
- id,
293
- callback,
294
- payload,
295
- time: timestamp,
296
- type: "scheduled"
297
- };
298
- }
299
- if (typeof when === "number") {
300
- const time = new Date(Date.now() + when * 1e3);
301
- const timestamp = Math.floor(time.getTime() / 1e3);
302
- this.sql`
303
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
304
- VALUES (${id}, ${callback}, ${JSON.stringify(
305
- payload
306
- )}, 'delayed', ${when}, ${timestamp})
307
- `;
308
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
309
- return {
310
- id,
311
- callback,
312
- payload,
313
- delayInSeconds: when,
314
- time: timestamp,
315
- type: "delayed"
316
- };
317
- }
318
- if (typeof when === "string") {
319
- const nextExecutionTime = getNextCronTime(when);
320
- const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
321
- this.sql`
322
- INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
323
- VALUES (${id}, ${callback}, ${JSON.stringify(
324
- payload
325
- )}, 'cron', ${when}, ${timestamp})
326
- `;
327
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
328
- return {
329
- id,
330
- callback,
331
- payload,
332
- cron: when,
333
- time: timestamp,
334
- type: "cron"
335
- };
336
- }
337
- throw new Error("Invalid schedule type");
338
- }
339
- /**
340
- * Get a scheduled task by ID
341
- * @template T Type of the payload data
342
- * @param id ID of the scheduled task
343
- * @returns The Schedule object or undefined if not found
344
- */
345
- async getSchedule(id) {
346
- const result = this.sql`
347
- SELECT * FROM cf_agents_schedules WHERE id = ${id}
348
- `;
349
- if (!result) {
350
- console.error(`schedule ${id} not found`);
351
- return void 0;
352
- }
353
- return { ...result[0], payload: JSON.parse(result[0].payload) };
354
- }
355
- /**
356
- * Get scheduled tasks matching the given criteria
357
- * @template T Type of the payload data
358
- * @param criteria Criteria to filter schedules
359
- * @returns Array of matching Schedule objects
360
- */
361
- getSchedules(criteria = {}) {
362
- let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
363
- const params = [];
364
- if (criteria.id) {
365
- query += " AND id = ?";
366
- params.push(criteria.id);
367
- }
368
- if (criteria.type) {
369
- query += " AND type = ?";
370
- params.push(criteria.type);
371
- }
372
- if (criteria.timeRange) {
373
- query += " AND time >= ? AND time <= ?";
374
- const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
375
- const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
376
- params.push(
377
- Math.floor(start.getTime() / 1e3),
378
- Math.floor(end.getTime() / 1e3)
379
- );
380
- }
381
- const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
382
- ...row,
383
- payload: JSON.parse(row.payload)
384
- }));
385
- return result;
386
- }
387
- /**
388
- * Cancel a scheduled task
389
- * @param id ID of the task to cancel
390
- * @returns true if the task was cancelled, false otherwise
391
- */
392
- async cancelSchedule(id) {
393
- this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
394
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
395
- return true;
396
- }
397
- /**
398
- * Method called when an alarm fires
399
- * Executes any scheduled tasks that are due
400
- */
401
- async alarm() {
402
- const now = Math.floor(Date.now() / 1e3);
403
- const result = this.sql`
404
- SELECT * FROM cf_agents_schedules WHERE time <= ${now}
405
- `;
406
- for (const row of result || []) {
407
- const callback = this[row.callback];
408
- if (!callback) {
409
- console.error(`callback ${row.callback} not found`);
410
- continue;
411
- }
412
- await agentContext.run(
413
- { agent: this, connection: void 0, request: void 0 },
414
- async () => {
415
- try {
416
- await callback.bind(this)(JSON.parse(row.payload), row);
417
- } catch (e) {
418
- console.error(`error executing callback "${row.callback}"`, e);
419
- }
420
- }
421
- );
422
- if (row.type === "cron") {
423
- const nextExecutionTime = getNextCronTime(row.cron);
424
- const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
425
- this.sql`
426
- UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
427
- `;
428
- } else {
429
- this.sql`
430
- DELETE FROM cf_agents_schedules WHERE id = ${row.id}
431
- `;
432
- }
433
- }
434
- await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
435
- }
436
- /**
437
- * Destroy the Agent, removing all state and scheduled tasks
438
- */
439
- async destroy() {
440
- this.sql`DROP TABLE IF EXISTS cf_agents_state`;
441
- this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
442
- await this.ctx.storage.deleteAlarm();
443
- await this.ctx.storage.deleteAll();
444
- }
445
- };
446
- _state = new WeakMap();
447
- _ParentClass = new WeakMap();
448
- _Agent_instances = new WeakSet();
449
- setStateInternal_fn = function(state, source = "server") {
450
- __privateSet(this, _state, state);
451
- this.sql`
452
- INSERT OR REPLACE INTO cf_agents_state (id, state)
453
- VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
454
- `;
455
- this.sql`
456
- INSERT OR REPLACE INTO cf_agents_state (id, state)
457
- VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
458
- `;
459
- this.broadcast(
460
- JSON.stringify({
461
- type: "cf_agent_state",
462
- state
463
- }),
464
- source !== "server" ? [source.id] : []
465
- );
466
- return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
467
- const { connection, request } = agentContext.getStore() || {};
468
- return agentContext.run(
469
- { agent: this, connection, request },
470
- async () => {
471
- return this.onStateUpdate(state, source);
472
- }
473
- );
474
- });
475
- };
476
- tryCatch_fn = async function(fn) {
477
- try {
478
- return await fn();
479
- } catch (e) {
480
- throw this.onError(e);
481
- }
482
- };
483
- scheduleNextAlarm_fn = async function() {
484
- const result = this.sql`
485
- SELECT time FROM cf_agents_schedules
486
- WHERE time > ${Math.floor(Date.now() / 1e3)}
487
- ORDER BY time ASC
488
- LIMIT 1
489
- `;
490
- if (!result) return;
491
- if (result.length > 0 && "time" in result[0]) {
492
- const nextTime = result[0].time * 1e3;
493
- await this.ctx.storage.setAlarm(nextTime);
494
- }
495
- };
496
- /**
497
- * Get all methods marked as callable on this Agent
498
- * @returns A map of method names to their metadata
499
- */
500
- isCallable_fn = function(method) {
501
- return callableMetadata.has(this[method]);
502
- };
503
- /**
504
- * Agent configuration options
505
- */
506
- Agent.options = {
507
- /** Whether the Agent should hibernate when inactive */
508
- hibernate: true
509
- // default to hibernate
510
- };
511
- async function routeAgentRequest(request, env, options) {
512
- const corsHeaders = options?.cors === true ? {
513
- "Access-Control-Allow-Origin": "*",
514
- "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
515
- "Access-Control-Allow-Credentials": "true",
516
- "Access-Control-Max-Age": "86400"
517
- } : options?.cors;
518
- if (request.method === "OPTIONS") {
519
- if (corsHeaders) {
520
- return new Response(null, {
521
- headers: corsHeaders
522
- });
523
- }
524
- console.warn(
525
- "Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
526
- );
527
- }
528
- let response = await routePartykitRequest(
529
- request,
530
- env,
531
- {
532
- prefix: "agents",
533
- ...options
534
- }
535
- );
536
- if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
537
- response = new Response(response.body, {
538
- headers: {
539
- ...response.headers,
540
- ...corsHeaders
541
- }
542
- });
543
- }
544
- return response;
545
- }
546
- async function routeAgentEmail(email, env, options) {
547
- }
548
- async function getAgentByName(namespace, name, options) {
549
- return getServerByName(namespace, name, options);
550
- }
551
- var _connection, _id, _closed;
552
- var StreamingResponse = class {
553
- constructor(connection, id) {
554
- __privateAdd(this, _connection);
555
- __privateAdd(this, _id);
556
- __privateAdd(this, _closed, false);
557
- __privateSet(this, _connection, connection);
558
- __privateSet(this, _id, id);
559
- }
560
- /**
561
- * Send a chunk of data to the client
562
- * @param chunk The data to send
563
- */
564
- send(chunk) {
565
- if (__privateGet(this, _closed)) {
566
- throw new Error("StreamingResponse is already closed");
567
- }
568
- const response = {
569
- type: "rpc",
570
- id: __privateGet(this, _id),
571
- success: true,
572
- result: chunk,
573
- done: false
574
- };
575
- __privateGet(this, _connection).send(JSON.stringify(response));
576
- }
577
- /**
578
- * End the stream and send the final chunk (if any)
579
- * @param finalChunk Optional final chunk of data to send
580
- */
581
- end(finalChunk) {
582
- if (__privateGet(this, _closed)) {
583
- throw new Error("StreamingResponse is already closed");
584
- }
585
- __privateSet(this, _closed, true);
586
- const response = {
587
- type: "rpc",
588
- id: __privateGet(this, _id),
589
- success: true,
590
- result: finalChunk,
591
- done: true
592
- };
593
- __privateGet(this, _connection).send(JSON.stringify(response));
594
- }
595
- };
596
- _connection = new WeakMap();
597
- _id = new WeakMap();
598
- _closed = new WeakMap();
599
-
600
- export {
601
- unstable_callable,
602
- getCurrentAgent,
603
- Agent,
604
- routeAgentRequest,
605
- routeAgentEmail,
606
- getAgentByName,
607
- StreamingResponse
608
- };
609
- //# sourceMappingURL=chunk-A65CRW2D.js.map