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