agents 0.3.9 → 0.4.0
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 +2 -2
- package/dist/{index-N6791tVt.d.ts → agent-DY6QmSI_.d.ts} +3 -25
- package/dist/ai-types.js +1 -1
- package/dist/client-connection-CGMuV62J.js +472 -0
- package/dist/client-connection-CGMuV62J.js.map +1 -0
- package/dist/client-storage-Cvy5r9FG.d.ts +355 -0
- package/dist/client.d.ts +11 -7
- package/dist/client.js +6 -2
- package/dist/client.js.map +1 -1
- package/dist/email.d.ts +146 -16
- package/dist/email.js +222 -2
- package/dist/email.js.map +1 -0
- package/dist/index.d.ts +139 -41
- package/dist/index.js +2317 -6
- package/dist/index.js.map +1 -0
- package/dist/internal_context.d.ts +28 -5
- package/dist/internal_context.js +7 -2
- package/dist/internal_context.js.map +1 -0
- package/dist/mcp/client.d.ts +516 -2
- package/dist/mcp/client.js +662 -3
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/do-oauth-client-provider.d.ts +61 -2
- package/dist/mcp/do-oauth-client-provider.js +154 -2
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +3 -5
- package/dist/mcp/index.js +8 -7
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +34 -14
- package/dist/mcp/x402.js +128 -66
- package/dist/mcp/x402.js.map +1 -1
- package/dist/{mcp-BwPscEiF.d.ts → mcp-Dw5vDrY8.d.ts} +1 -1
- package/dist/observability/index.d.ts +23 -2
- package/dist/observability/index.js +25 -6
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +16 -10
- package/dist/react.js +34 -16
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +14 -1
- package/dist/types.js +16 -2
- package/dist/types.js.map +1 -0
- package/dist/utils.js +15 -2
- package/dist/utils.js.map +1 -0
- package/dist/workflow-types.d.ts +235 -23
- package/dist/workflows.d.ts +22 -24
- package/dist/workflows.js +2 -5
- package/dist/workflows.js.map +1 -1
- package/package.json +26 -23
- package/dist/client-BA8NJB6l.js +0 -1124
- package/dist/client-BA8NJB6l.js.map +0 -1
- package/dist/client-Ba-xntmv.d.ts +0 -963
- package/dist/do-oauth-client-provider-BqnOQzjy.d.ts +0 -70
- package/dist/do-oauth-client-provider-DDg8QrEA.js +0 -155
- package/dist/do-oauth-client-provider-DDg8QrEA.js.map +0 -1
- package/dist/email-8ljcpvwV.d.ts +0 -157
- package/dist/email-XHsSYsTO.js +0 -223
- package/dist/email-XHsSYsTO.js.map +0 -1
- package/dist/internal_context-CEu5ji80.d.ts +0 -29
- package/dist/internal_context-D9eKFth1.js +0 -8
- package/dist/internal_context-D9eKFth1.js.map +0 -1
- package/dist/src-CqnVUbg1.js +0 -2146
- package/dist/src-CqnVUbg1.js.map +0 -1
- package/dist/types-BITaDFf-.js +0 -16
- package/dist/types-BITaDFf-.js.map +0 -1
- package/dist/types-DSSHBW6w.d.ts +0 -14
- package/dist/utils-B49TmLCI.js +0 -16
- package/dist/utils-B49TmLCI.js.map +0 -1
- package/dist/workflow-types-Z_Oem1FJ.d.ts +0 -260
package/dist/index.js
CHANGED
|
@@ -1,7 +1,2318 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import "./
|
|
3
|
-
import "./
|
|
4
|
-
import "./
|
|
5
|
-
import {
|
|
1
|
+
import { MessageType } from "./types.js";
|
|
2
|
+
import { camelCaseToKebabCase } from "./utils.js";
|
|
3
|
+
import { createHeaderBasedEmailResolver, signAgentHeaders } from "./email.js";
|
|
4
|
+
import { agentContext } from "./internal_context.js";
|
|
5
|
+
import { i as DisposableStore, n as MCPConnectionState } from "./client-connection-CGMuV62J.js";
|
|
6
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider.js";
|
|
7
|
+
import { MCPClientManager } from "./mcp/client.js";
|
|
8
|
+
import { genericObservability } from "./observability/index.js";
|
|
9
|
+
import { parseCronExpression } from "cron-schedule";
|
|
10
|
+
import { nanoid } from "nanoid";
|
|
11
|
+
import { EmailMessage } from "cloudflare:email";
|
|
12
|
+
import { Server, getServerByName, routePartykitRequest } from "partyserver";
|
|
6
13
|
|
|
7
|
-
|
|
14
|
+
//#region src/index.ts
|
|
15
|
+
/**
|
|
16
|
+
* Type guard for RPC request messages
|
|
17
|
+
*/
|
|
18
|
+
function isRPCRequest(msg) {
|
|
19
|
+
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);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Type guard for state update messages
|
|
23
|
+
*/
|
|
24
|
+
function isStateUpdateMessage(msg) {
|
|
25
|
+
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
|
|
26
|
+
}
|
|
27
|
+
const callableMetadata = /* @__PURE__ */ new WeakMap();
|
|
28
|
+
/**
|
|
29
|
+
* Error class for SQL execution failures, containing the query that failed
|
|
30
|
+
*/
|
|
31
|
+
var SqlError = class extends Error {
|
|
32
|
+
constructor(query, cause) {
|
|
33
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
34
|
+
super(`SQL query failed: ${message}`, { cause });
|
|
35
|
+
this.name = "SqlError";
|
|
36
|
+
this.query = query;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Decorator that marks a method as callable by clients
|
|
41
|
+
* @param metadata Optional metadata about the callable method
|
|
42
|
+
*/
|
|
43
|
+
function callable(metadata = {}) {
|
|
44
|
+
return function callableDecorator(target, _context) {
|
|
45
|
+
if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
|
|
46
|
+
return target;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
let didWarnAboutUnstableCallable = false;
|
|
50
|
+
/**
|
|
51
|
+
* Decorator that marks a method as callable by clients
|
|
52
|
+
* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
|
|
53
|
+
* @param metadata Optional metadata about the callable method
|
|
54
|
+
*/
|
|
55
|
+
const unstable_callable = (metadata = {}) => {
|
|
56
|
+
if (!didWarnAboutUnstableCallable) {
|
|
57
|
+
didWarnAboutUnstableCallable = true;
|
|
58
|
+
console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
|
|
59
|
+
}
|
|
60
|
+
return callable(metadata);
|
|
61
|
+
};
|
|
62
|
+
function getNextCronTime(cron) {
|
|
63
|
+
return parseCronExpression(cron).getNextDate();
|
|
64
|
+
}
|
|
65
|
+
const STATE_ROW_ID = "cf_state_row_id";
|
|
66
|
+
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
67
|
+
const DEFAULT_STATE = {};
|
|
68
|
+
/**
|
|
69
|
+
* Internal key used to store the readonly flag in connection state.
|
|
70
|
+
* Prefixed with _cf_ to avoid collision with user state keys.
|
|
71
|
+
*/
|
|
72
|
+
const CF_READONLY_KEY = "_cf_readonly";
|
|
73
|
+
/**
|
|
74
|
+
* Tracks which agent constructors have already emitted the onStateUpdate
|
|
75
|
+
* deprecation warning, so it fires at most once per class.
|
|
76
|
+
*/
|
|
77
|
+
const _onStateUpdateWarnedClasses = /* @__PURE__ */ new WeakSet();
|
|
78
|
+
/**
|
|
79
|
+
* Default options for Agent configuration.
|
|
80
|
+
* Child classes can override specific options without spreading.
|
|
81
|
+
*/
|
|
82
|
+
const DEFAULT_AGENT_STATIC_OPTIONS = {
|
|
83
|
+
hibernate: true,
|
|
84
|
+
sendIdentityOnConnect: true,
|
|
85
|
+
hungScheduleTimeoutSeconds: 30
|
|
86
|
+
};
|
|
87
|
+
function getCurrentAgent() {
|
|
88
|
+
const store = agentContext.getStore();
|
|
89
|
+
if (!store) return {
|
|
90
|
+
agent: void 0,
|
|
91
|
+
connection: void 0,
|
|
92
|
+
request: void 0,
|
|
93
|
+
email: void 0
|
|
94
|
+
};
|
|
95
|
+
return store;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
|
|
99
|
+
* @param agent The agent instance
|
|
100
|
+
* @param method The method to wrap
|
|
101
|
+
* @returns A wrapped method that runs within the agent context
|
|
102
|
+
*/
|
|
103
|
+
function withAgentContext(method) {
|
|
104
|
+
return function(...args) {
|
|
105
|
+
const { connection, request, email, agent } = getCurrentAgent();
|
|
106
|
+
if (agent === this) return method.apply(this, args);
|
|
107
|
+
return agentContext.run({
|
|
108
|
+
agent: this,
|
|
109
|
+
connection,
|
|
110
|
+
request,
|
|
111
|
+
email
|
|
112
|
+
}, () => {
|
|
113
|
+
return method.apply(this, args);
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Base class for creating Agent implementations
|
|
119
|
+
* @template Env Environment type containing bindings
|
|
120
|
+
* @template State State type to store within the Agent
|
|
121
|
+
*/
|
|
122
|
+
var Agent = class Agent extends Server {
|
|
123
|
+
/**
|
|
124
|
+
* Current state of the Agent
|
|
125
|
+
*/
|
|
126
|
+
get state() {
|
|
127
|
+
if (this._state !== DEFAULT_STATE) return this._state;
|
|
128
|
+
const wasChanged = this.sql`
|
|
129
|
+
SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
|
|
130
|
+
`;
|
|
131
|
+
const result = this.sql`
|
|
132
|
+
SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
|
|
133
|
+
`;
|
|
134
|
+
if (wasChanged[0]?.state === "true" || result[0]?.state) {
|
|
135
|
+
const state = result[0]?.state;
|
|
136
|
+
try {
|
|
137
|
+
this._state = JSON.parse(state);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
console.error("Failed to parse stored state, falling back to initialState:", e);
|
|
140
|
+
if (this.initialState !== DEFAULT_STATE) {
|
|
141
|
+
this._state = this.initialState;
|
|
142
|
+
this._setStateInternal(this.initialState);
|
|
143
|
+
} else {
|
|
144
|
+
this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_ROW_ID}`;
|
|
145
|
+
this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}`;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return this._state;
|
|
150
|
+
}
|
|
151
|
+
if (this.initialState === DEFAULT_STATE) return;
|
|
152
|
+
this._setStateInternal(this.initialState);
|
|
153
|
+
return this.initialState;
|
|
154
|
+
}
|
|
155
|
+
static {
|
|
156
|
+
this.options = { hibernate: true };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Resolved options (merges defaults with subclass overrides)
|
|
160
|
+
*/
|
|
161
|
+
get _resolvedOptions() {
|
|
162
|
+
const ctor = this.constructor;
|
|
163
|
+
return {
|
|
164
|
+
hibernate: ctor.options?.hibernate ?? DEFAULT_AGENT_STATIC_OPTIONS.hibernate,
|
|
165
|
+
sendIdentityOnConnect: ctor.options?.sendIdentityOnConnect ?? DEFAULT_AGENT_STATIC_OPTIONS.sendIdentityOnConnect,
|
|
166
|
+
hungScheduleTimeoutSeconds: ctor.options?.hungScheduleTimeoutSeconds ?? DEFAULT_AGENT_STATIC_OPTIONS.hungScheduleTimeoutSeconds
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Execute SQL queries against the Agent's database
|
|
171
|
+
* @template T Type of the returned rows
|
|
172
|
+
* @param strings SQL query template strings
|
|
173
|
+
* @param values Values to be inserted into the query
|
|
174
|
+
* @returns Array of query results
|
|
175
|
+
*/
|
|
176
|
+
sql(strings, ...values) {
|
|
177
|
+
let query = "";
|
|
178
|
+
try {
|
|
179
|
+
query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
|
|
180
|
+
return [...this.ctx.storage.sql.exec(query, ...values)];
|
|
181
|
+
} catch (e) {
|
|
182
|
+
throw this.onError(new SqlError(query, e));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
constructor(ctx, env) {
|
|
186
|
+
super(ctx, env);
|
|
187
|
+
this._state = DEFAULT_STATE;
|
|
188
|
+
this._disposables = new DisposableStore();
|
|
189
|
+
this._destroyed = false;
|
|
190
|
+
this._rawStateAccessors = /* @__PURE__ */ new WeakMap();
|
|
191
|
+
this._persistenceHookMode = "none";
|
|
192
|
+
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
193
|
+
this.initialState = DEFAULT_STATE;
|
|
194
|
+
this.observability = genericObservability;
|
|
195
|
+
this._flushingQueue = false;
|
|
196
|
+
this.alarm = async () => {
|
|
197
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
198
|
+
const result = this.sql`
|
|
199
|
+
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
200
|
+
`;
|
|
201
|
+
if (result && Array.isArray(result)) for (const row of result) {
|
|
202
|
+
const callback = this[row.callback];
|
|
203
|
+
if (!callback) {
|
|
204
|
+
console.error(`callback ${row.callback} not found`);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (row.type === "interval" && row.running === 1) {
|
|
208
|
+
const executionStartedAt = row.execution_started_at ?? 0;
|
|
209
|
+
const hungTimeoutSeconds = this._resolvedOptions.hungScheduleTimeoutSeconds;
|
|
210
|
+
const elapsedSeconds = now - executionStartedAt;
|
|
211
|
+
if (elapsedSeconds < hungTimeoutSeconds) {
|
|
212
|
+
console.warn(`Skipping interval schedule ${row.id}: previous execution still running`);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
console.warn(`Forcing reset of hung interval schedule ${row.id} (started ${elapsedSeconds}s ago)`);
|
|
216
|
+
}
|
|
217
|
+
if (row.type === "interval") this.sql`UPDATE cf_agents_schedules SET running = 1, execution_started_at = ${now} WHERE id = ${row.id}`;
|
|
218
|
+
await agentContext.run({
|
|
219
|
+
agent: this,
|
|
220
|
+
connection: void 0,
|
|
221
|
+
request: void 0,
|
|
222
|
+
email: void 0
|
|
223
|
+
}, async () => {
|
|
224
|
+
try {
|
|
225
|
+
this.observability?.emit({
|
|
226
|
+
displayMessage: `Schedule ${row.id} executed`,
|
|
227
|
+
id: nanoid(),
|
|
228
|
+
payload: {
|
|
229
|
+
callback: row.callback,
|
|
230
|
+
id: row.id
|
|
231
|
+
},
|
|
232
|
+
timestamp: Date.now(),
|
|
233
|
+
type: "schedule:execute"
|
|
234
|
+
}, this.ctx);
|
|
235
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
236
|
+
} catch (e) {
|
|
237
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
238
|
+
try {
|
|
239
|
+
await this.onError(e);
|
|
240
|
+
} catch {}
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
if (this._destroyed) return;
|
|
244
|
+
if (row.type === "cron") {
|
|
245
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
246
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
247
|
+
this.sql`
|
|
248
|
+
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
249
|
+
`;
|
|
250
|
+
} else if (row.type === "interval") {
|
|
251
|
+
const nextTimestamp = Math.floor(Date.now() / 1e3) + (row.intervalSeconds ?? 0);
|
|
252
|
+
this.sql`
|
|
253
|
+
UPDATE cf_agents_schedules SET running = 0, time = ${nextTimestamp} WHERE id = ${row.id}
|
|
254
|
+
`;
|
|
255
|
+
} else this.sql`
|
|
256
|
+
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
257
|
+
`;
|
|
258
|
+
}
|
|
259
|
+
if (this._destroyed) return;
|
|
260
|
+
await this._scheduleNextAlarm();
|
|
261
|
+
};
|
|
262
|
+
if (!wrappedClasses.has(this.constructor)) {
|
|
263
|
+
this._autoWrapCustomMethods();
|
|
264
|
+
wrappedClasses.add(this.constructor);
|
|
265
|
+
}
|
|
266
|
+
this.sql`
|
|
267
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
268
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
269
|
+
name TEXT NOT NULL,
|
|
270
|
+
server_url TEXT NOT NULL,
|
|
271
|
+
callback_url TEXT NOT NULL,
|
|
272
|
+
client_id TEXT,
|
|
273
|
+
auth_url TEXT,
|
|
274
|
+
server_options TEXT
|
|
275
|
+
)
|
|
276
|
+
`;
|
|
277
|
+
this.sql`
|
|
278
|
+
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
279
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
280
|
+
state TEXT
|
|
281
|
+
)
|
|
282
|
+
`;
|
|
283
|
+
this.sql`
|
|
284
|
+
CREATE TABLE IF NOT EXISTS cf_agents_queues (
|
|
285
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
286
|
+
payload TEXT,
|
|
287
|
+
callback TEXT,
|
|
288
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
289
|
+
)
|
|
290
|
+
`;
|
|
291
|
+
this.sql`
|
|
292
|
+
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
293
|
+
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
294
|
+
callback TEXT,
|
|
295
|
+
payload TEXT,
|
|
296
|
+
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron', 'interval')),
|
|
297
|
+
time INTEGER,
|
|
298
|
+
delayInSeconds INTEGER,
|
|
299
|
+
cron TEXT,
|
|
300
|
+
intervalSeconds INTEGER,
|
|
301
|
+
running INTEGER DEFAULT 0,
|
|
302
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
303
|
+
)
|
|
304
|
+
`;
|
|
305
|
+
const addColumnIfNotExists = (sql) => {
|
|
306
|
+
try {
|
|
307
|
+
this.ctx.storage.sql.exec(sql);
|
|
308
|
+
} catch (e) {
|
|
309
|
+
if (!(e instanceof Error ? e.message : String(e)).toLowerCase().includes("duplicate column")) throw e;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN intervalSeconds INTEGER");
|
|
313
|
+
addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN running INTEGER DEFAULT 0");
|
|
314
|
+
addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER");
|
|
315
|
+
this.sql`
|
|
316
|
+
CREATE TABLE IF NOT EXISTS cf_agents_workflows (
|
|
317
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
318
|
+
workflow_id TEXT NOT NULL UNIQUE,
|
|
319
|
+
workflow_name TEXT NOT NULL,
|
|
320
|
+
status TEXT NOT NULL CHECK(status IN (
|
|
321
|
+
'queued', 'running', 'paused', 'errored',
|
|
322
|
+
'terminated', 'complete', 'waiting',
|
|
323
|
+
'waitingForPause', 'unknown'
|
|
324
|
+
)),
|
|
325
|
+
metadata TEXT,
|
|
326
|
+
error_name TEXT,
|
|
327
|
+
error_message TEXT,
|
|
328
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
329
|
+
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
330
|
+
completed_at INTEGER
|
|
331
|
+
)
|
|
332
|
+
`;
|
|
333
|
+
this.sql`
|
|
334
|
+
CREATE INDEX IF NOT EXISTS idx_workflows_status ON cf_agents_workflows(status)
|
|
335
|
+
`;
|
|
336
|
+
this.sql`
|
|
337
|
+
CREATE INDEX IF NOT EXISTS idx_workflows_name ON cf_agents_workflows(workflow_name)
|
|
338
|
+
`;
|
|
339
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
|
|
340
|
+
this._disposables.add(this.mcp.onServerStateChanged(async () => {
|
|
341
|
+
this.broadcastMcpServers();
|
|
342
|
+
}));
|
|
343
|
+
this._disposables.add(this.mcp.onObservabilityEvent((event) => {
|
|
344
|
+
this.observability?.emit(event);
|
|
345
|
+
}));
|
|
346
|
+
{
|
|
347
|
+
const proto = Object.getPrototypeOf(this);
|
|
348
|
+
const hasOwnNew = Object.prototype.hasOwnProperty.call(proto, "onStateChanged");
|
|
349
|
+
const hasOwnOld = Object.prototype.hasOwnProperty.call(proto, "onStateUpdate");
|
|
350
|
+
if (hasOwnNew && hasOwnOld) throw new Error("[Agent] Cannot override both onStateChanged and onStateUpdate. Remove onStateUpdate — it has been renamed to onStateChanged.");
|
|
351
|
+
if (hasOwnOld) {
|
|
352
|
+
const ctor = this.constructor;
|
|
353
|
+
if (!_onStateUpdateWarnedClasses.has(ctor)) {
|
|
354
|
+
_onStateUpdateWarnedClasses.add(ctor);
|
|
355
|
+
console.warn(`[Agent] onStateUpdate is deprecated. Rename to onStateChanged — the behavior is identical.`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const base = Agent.prototype;
|
|
359
|
+
if (proto.onStateChanged !== base.onStateChanged) this._persistenceHookMode = "new";
|
|
360
|
+
else if (proto.onStateUpdate !== base.onStateUpdate) this._persistenceHookMode = "old";
|
|
361
|
+
}
|
|
362
|
+
const _onRequest = this.onRequest.bind(this);
|
|
363
|
+
this.onRequest = (request) => {
|
|
364
|
+
return agentContext.run({
|
|
365
|
+
agent: this,
|
|
366
|
+
connection: void 0,
|
|
367
|
+
request,
|
|
368
|
+
email: void 0
|
|
369
|
+
}, async () => {
|
|
370
|
+
await this.mcp.ensureJsonSchema();
|
|
371
|
+
const oauthResponse = await this.handleMcpOAuthCallback(request);
|
|
372
|
+
if (oauthResponse) return oauthResponse;
|
|
373
|
+
return this._tryCatch(() => _onRequest(request));
|
|
374
|
+
});
|
|
375
|
+
};
|
|
376
|
+
const _onMessage = this.onMessage.bind(this);
|
|
377
|
+
this.onMessage = async (connection, message) => {
|
|
378
|
+
this._ensureConnectionWrapped(connection);
|
|
379
|
+
return agentContext.run({
|
|
380
|
+
agent: this,
|
|
381
|
+
connection,
|
|
382
|
+
request: void 0,
|
|
383
|
+
email: void 0
|
|
384
|
+
}, async () => {
|
|
385
|
+
await this.mcp.ensureJsonSchema();
|
|
386
|
+
if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
|
|
387
|
+
let parsed;
|
|
388
|
+
try {
|
|
389
|
+
parsed = JSON.parse(message);
|
|
390
|
+
} catch (_e) {
|
|
391
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
392
|
+
}
|
|
393
|
+
if (isStateUpdateMessage(parsed)) {
|
|
394
|
+
if (this.isConnectionReadonly(connection)) {
|
|
395
|
+
connection.send(JSON.stringify({
|
|
396
|
+
type: MessageType.CF_AGENT_STATE_ERROR,
|
|
397
|
+
error: "Connection is readonly"
|
|
398
|
+
}));
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
this._setStateInternal(parsed.state, connection);
|
|
403
|
+
} catch (e) {
|
|
404
|
+
console.error("[Agent] State update rejected:", e);
|
|
405
|
+
connection.send(JSON.stringify({
|
|
406
|
+
type: MessageType.CF_AGENT_STATE_ERROR,
|
|
407
|
+
error: "State update rejected"
|
|
408
|
+
}));
|
|
409
|
+
}
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (isRPCRequest(parsed)) {
|
|
413
|
+
try {
|
|
414
|
+
const { id, method, args } = parsed;
|
|
415
|
+
const methodFn = this[method];
|
|
416
|
+
if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
|
|
417
|
+
if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
|
|
418
|
+
const metadata = callableMetadata.get(methodFn);
|
|
419
|
+
if (metadata?.streaming) {
|
|
420
|
+
const stream = new StreamingResponse(connection, id);
|
|
421
|
+
this.observability?.emit({
|
|
422
|
+
displayMessage: `RPC streaming call to ${method}`,
|
|
423
|
+
id: nanoid(),
|
|
424
|
+
payload: {
|
|
425
|
+
method,
|
|
426
|
+
streaming: true
|
|
427
|
+
},
|
|
428
|
+
timestamp: Date.now(),
|
|
429
|
+
type: "rpc"
|
|
430
|
+
}, this.ctx);
|
|
431
|
+
try {
|
|
432
|
+
await methodFn.apply(this, [stream, ...args]);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
console.error(`Error in streaming method "${method}":`, err);
|
|
435
|
+
if (!stream.isClosed) stream.error(err instanceof Error ? err.message : String(err));
|
|
436
|
+
}
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const result = await methodFn.apply(this, args);
|
|
440
|
+
this.observability?.emit({
|
|
441
|
+
displayMessage: `RPC call to ${method}`,
|
|
442
|
+
id: nanoid(),
|
|
443
|
+
payload: {
|
|
444
|
+
method,
|
|
445
|
+
streaming: metadata?.streaming
|
|
446
|
+
},
|
|
447
|
+
timestamp: Date.now(),
|
|
448
|
+
type: "rpc"
|
|
449
|
+
}, this.ctx);
|
|
450
|
+
const response = {
|
|
451
|
+
done: true,
|
|
452
|
+
id,
|
|
453
|
+
result,
|
|
454
|
+
success: true,
|
|
455
|
+
type: MessageType.RPC
|
|
456
|
+
};
|
|
457
|
+
connection.send(JSON.stringify(response));
|
|
458
|
+
} catch (e) {
|
|
459
|
+
const response = {
|
|
460
|
+
error: e instanceof Error ? e.message : "Unknown error occurred",
|
|
461
|
+
id: parsed.id,
|
|
462
|
+
success: false,
|
|
463
|
+
type: MessageType.RPC
|
|
464
|
+
};
|
|
465
|
+
connection.send(JSON.stringify(response));
|
|
466
|
+
console.error("RPC error:", e);
|
|
467
|
+
}
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
471
|
+
});
|
|
472
|
+
};
|
|
473
|
+
const _onConnect = this.onConnect.bind(this);
|
|
474
|
+
this.onConnect = (connection, ctx) => {
|
|
475
|
+
this._ensureConnectionWrapped(connection);
|
|
476
|
+
return agentContext.run({
|
|
477
|
+
agent: this,
|
|
478
|
+
connection,
|
|
479
|
+
request: ctx.request,
|
|
480
|
+
email: void 0
|
|
481
|
+
}, async () => {
|
|
482
|
+
if (this.shouldConnectionBeReadonly(connection, ctx)) this.setConnectionReadonly(connection, true);
|
|
483
|
+
if (this._resolvedOptions.sendIdentityOnConnect) connection.send(JSON.stringify({
|
|
484
|
+
name: this.name,
|
|
485
|
+
agent: camelCaseToKebabCase(this._ParentClass.name),
|
|
486
|
+
type: MessageType.CF_AGENT_IDENTITY
|
|
487
|
+
}));
|
|
488
|
+
if (this.state) connection.send(JSON.stringify({
|
|
489
|
+
state: this.state,
|
|
490
|
+
type: MessageType.CF_AGENT_STATE
|
|
491
|
+
}));
|
|
492
|
+
connection.send(JSON.stringify({
|
|
493
|
+
mcp: this.getMcpServers(),
|
|
494
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
495
|
+
}));
|
|
496
|
+
this.observability?.emit({
|
|
497
|
+
displayMessage: "Connection established",
|
|
498
|
+
id: nanoid(),
|
|
499
|
+
payload: { connectionId: connection.id },
|
|
500
|
+
timestamp: Date.now(),
|
|
501
|
+
type: "connect"
|
|
502
|
+
}, this.ctx);
|
|
503
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
504
|
+
});
|
|
505
|
+
};
|
|
506
|
+
const _onStart = this.onStart.bind(this);
|
|
507
|
+
this.onStart = async (props) => {
|
|
508
|
+
return agentContext.run({
|
|
509
|
+
agent: this,
|
|
510
|
+
connection: void 0,
|
|
511
|
+
request: void 0,
|
|
512
|
+
email: void 0
|
|
513
|
+
}, async () => {
|
|
514
|
+
await this._tryCatch(async () => {
|
|
515
|
+
await this.mcp.restoreConnectionsFromStorage(this.name);
|
|
516
|
+
this.broadcastMcpServers();
|
|
517
|
+
this._checkOrphanedWorkflows();
|
|
518
|
+
return _onStart(props);
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Check for workflows referencing unknown bindings and warn with migration suggestion.
|
|
525
|
+
*/
|
|
526
|
+
_checkOrphanedWorkflows() {
|
|
527
|
+
const orphaned = this.sql`
|
|
528
|
+
SELECT
|
|
529
|
+
workflow_name,
|
|
530
|
+
COUNT(*) as total,
|
|
531
|
+
SUM(CASE WHEN status NOT IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as active,
|
|
532
|
+
SUM(CASE WHEN status IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as completed
|
|
533
|
+
FROM cf_agents_workflows
|
|
534
|
+
GROUP BY workflow_name
|
|
535
|
+
`.filter((row) => !this._findWorkflowBindingByName(row.workflow_name));
|
|
536
|
+
if (orphaned.length > 0) {
|
|
537
|
+
const currentBindings = this._getWorkflowBindingNames();
|
|
538
|
+
for (const { workflow_name: oldName, total, active, completed } of orphaned) {
|
|
539
|
+
const suggestion = currentBindings.length === 1 ? `this.migrateWorkflowBinding('${oldName}', '${currentBindings[0]}')` : `this.migrateWorkflowBinding('${oldName}', '<NEW_BINDING_NAME>')`;
|
|
540
|
+
const breakdown = active > 0 && completed > 0 ? ` (${active} active, ${completed} completed)` : active > 0 ? ` (${active} active)` : ` (${completed} completed)`;
|
|
541
|
+
console.warn(`[Agent] Found ${total} workflow(s) referencing unknown binding '${oldName}'${breakdown}. If you renamed the binding, call: ${suggestion}`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
_setStateInternal(nextState, source = "server") {
|
|
546
|
+
this.validateStateChange(nextState, source);
|
|
547
|
+
this._state = nextState;
|
|
548
|
+
this.sql`
|
|
549
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
550
|
+
VALUES (${STATE_ROW_ID}, ${JSON.stringify(nextState)})
|
|
551
|
+
`;
|
|
552
|
+
this.sql`
|
|
553
|
+
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
554
|
+
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
555
|
+
`;
|
|
556
|
+
this.broadcast(JSON.stringify({
|
|
557
|
+
state: nextState,
|
|
558
|
+
type: MessageType.CF_AGENT_STATE
|
|
559
|
+
}), source !== "server" ? [source.id] : []);
|
|
560
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
561
|
+
this.ctx.waitUntil((async () => {
|
|
562
|
+
try {
|
|
563
|
+
await agentContext.run({
|
|
564
|
+
agent: this,
|
|
565
|
+
connection,
|
|
566
|
+
request,
|
|
567
|
+
email
|
|
568
|
+
}, async () => {
|
|
569
|
+
this.observability?.emit({
|
|
570
|
+
displayMessage: "State updated",
|
|
571
|
+
id: nanoid(),
|
|
572
|
+
payload: {},
|
|
573
|
+
timestamp: Date.now(),
|
|
574
|
+
type: "state:update"
|
|
575
|
+
}, this.ctx);
|
|
576
|
+
await this._callStatePersistenceHook(nextState, source);
|
|
577
|
+
});
|
|
578
|
+
} catch (e) {
|
|
579
|
+
try {
|
|
580
|
+
await this.onError(e);
|
|
581
|
+
} catch {}
|
|
582
|
+
}
|
|
583
|
+
})());
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Update the Agent's state
|
|
587
|
+
* @param state New state to set
|
|
588
|
+
* @throws Error if called from a readonly connection context
|
|
589
|
+
*/
|
|
590
|
+
setState(state) {
|
|
591
|
+
const store = agentContext.getStore();
|
|
592
|
+
if (store?.connection && this.isConnectionReadonly(store.connection)) throw new Error("Connection is readonly");
|
|
593
|
+
this._setStateInternal(state, "server");
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Wraps connection.state and connection.setState so that the internal
|
|
597
|
+
* _cf_readonly flag is hidden from user code and cannot be accidentally
|
|
598
|
+
* overwritten. Must be called before any user code sees the connection.
|
|
599
|
+
*
|
|
600
|
+
* Idempotent — safe to call multiple times on the same connection.
|
|
601
|
+
*/
|
|
602
|
+
_ensureConnectionWrapped(connection) {
|
|
603
|
+
if (this._rawStateAccessors.has(connection)) return;
|
|
604
|
+
const descriptor = Object.getOwnPropertyDescriptor(connection, "state");
|
|
605
|
+
let getRaw;
|
|
606
|
+
let setRaw;
|
|
607
|
+
if (descriptor?.get) {
|
|
608
|
+
getRaw = descriptor.get.bind(connection);
|
|
609
|
+
setRaw = connection.setState.bind(connection);
|
|
610
|
+
} else {
|
|
611
|
+
let rawState = connection.state ?? null;
|
|
612
|
+
getRaw = () => rawState;
|
|
613
|
+
setRaw = (state) => {
|
|
614
|
+
rawState = state;
|
|
615
|
+
return rawState;
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
this._rawStateAccessors.set(connection, {
|
|
619
|
+
getRaw,
|
|
620
|
+
setRaw
|
|
621
|
+
});
|
|
622
|
+
const CF_KEY = CF_READONLY_KEY;
|
|
623
|
+
Object.defineProperty(connection, "state", {
|
|
624
|
+
configurable: true,
|
|
625
|
+
enumerable: true,
|
|
626
|
+
get() {
|
|
627
|
+
const raw = getRaw();
|
|
628
|
+
if (raw != null && typeof raw === "object" && CF_KEY in raw) {
|
|
629
|
+
const { [CF_KEY]: _, ...userState } = raw;
|
|
630
|
+
return Object.keys(userState).length > 0 ? userState : null;
|
|
631
|
+
}
|
|
632
|
+
return raw;
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
Object.defineProperty(connection, "setState", {
|
|
636
|
+
configurable: true,
|
|
637
|
+
writable: true,
|
|
638
|
+
value(stateOrFn) {
|
|
639
|
+
const raw = getRaw();
|
|
640
|
+
const readonlyFlag = raw != null && typeof raw === "object" ? raw[CF_KEY] : void 0;
|
|
641
|
+
let newUserState;
|
|
642
|
+
if (typeof stateOrFn === "function") {
|
|
643
|
+
let userVisible = raw;
|
|
644
|
+
if (raw != null && typeof raw === "object" && CF_KEY in raw) {
|
|
645
|
+
const { [CF_KEY]: _, ...rest } = raw;
|
|
646
|
+
userVisible = Object.keys(rest).length > 0 ? rest : null;
|
|
647
|
+
}
|
|
648
|
+
newUserState = stateOrFn(userVisible);
|
|
649
|
+
} else newUserState = stateOrFn;
|
|
650
|
+
if (readonlyFlag !== void 0) {
|
|
651
|
+
if (newUserState != null && typeof newUserState === "object") return setRaw({
|
|
652
|
+
...newUserState,
|
|
653
|
+
[CF_KEY]: readonlyFlag
|
|
654
|
+
});
|
|
655
|
+
return setRaw({ [CF_KEY]: readonlyFlag });
|
|
656
|
+
}
|
|
657
|
+
return setRaw(newUserState);
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Mark a connection as readonly or readwrite
|
|
663
|
+
* @param connection The connection to mark
|
|
664
|
+
* @param readonly Whether the connection should be readonly (default: true)
|
|
665
|
+
*/
|
|
666
|
+
setConnectionReadonly(connection, readonly = true) {
|
|
667
|
+
this._ensureConnectionWrapped(connection);
|
|
668
|
+
const accessors = this._rawStateAccessors.get(connection);
|
|
669
|
+
const raw = accessors.getRaw() ?? {};
|
|
670
|
+
if (readonly) accessors.setRaw({
|
|
671
|
+
...raw,
|
|
672
|
+
[CF_READONLY_KEY]: true
|
|
673
|
+
});
|
|
674
|
+
else {
|
|
675
|
+
const { [CF_READONLY_KEY]: _, ...rest } = raw;
|
|
676
|
+
accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Check if a connection is marked as readonly
|
|
681
|
+
* @param connection The connection to check
|
|
682
|
+
* @returns True if the connection is readonly
|
|
683
|
+
*/
|
|
684
|
+
isConnectionReadonly(connection) {
|
|
685
|
+
const accessors = this._rawStateAccessors.get(connection);
|
|
686
|
+
if (accessors) return !!accessors.getRaw()?.[CF_READONLY_KEY];
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Override this method to determine if a connection should be readonly on connect
|
|
691
|
+
* @param _connection The connection that is being established
|
|
692
|
+
* @param _ctx Connection context
|
|
693
|
+
* @returns True if the connection should be readonly
|
|
694
|
+
*/
|
|
695
|
+
shouldConnectionBeReadonly(_connection, _ctx) {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Called before the Agent's state is persisted and broadcast.
|
|
700
|
+
* Override to validate or reject an update by throwing an error.
|
|
701
|
+
*
|
|
702
|
+
* IMPORTANT: This hook must be synchronous.
|
|
703
|
+
*/
|
|
704
|
+
validateStateChange(nextState, source) {}
|
|
705
|
+
/**
|
|
706
|
+
* Called after the Agent's state has been persisted and broadcast to all clients.
|
|
707
|
+
* This is a notification hook — errors here are routed to onError and do not
|
|
708
|
+
* affect state persistence or client broadcasts.
|
|
709
|
+
*
|
|
710
|
+
* @param state Updated state
|
|
711
|
+
* @param source Source of the state update ("server" or a client connection)
|
|
712
|
+
*/
|
|
713
|
+
onStateChanged(state, source) {}
|
|
714
|
+
/**
|
|
715
|
+
* @deprecated Renamed to `onStateChanged` — the behavior is identical.
|
|
716
|
+
* `onStateUpdate` will be removed in the next major version.
|
|
717
|
+
*
|
|
718
|
+
* Called after the Agent's state has been persisted and broadcast to all clients.
|
|
719
|
+
* This is a server-side notification hook. For the client-side state callback,
|
|
720
|
+
* see the `onStateUpdate` option in `useAgent` / `AgentClient`.
|
|
721
|
+
*
|
|
722
|
+
* @param state Updated state
|
|
723
|
+
* @param source Source of the state update ("server" or a client connection)
|
|
724
|
+
*/
|
|
725
|
+
onStateUpdate(state, source) {}
|
|
726
|
+
/**
|
|
727
|
+
* Dispatch to the appropriate persistence hook based on the mode
|
|
728
|
+
* cached in the constructor. No prototype walks at call time.
|
|
729
|
+
*/
|
|
730
|
+
async _callStatePersistenceHook(state, source) {
|
|
731
|
+
switch (this._persistenceHookMode) {
|
|
732
|
+
case "new":
|
|
733
|
+
await this.onStateChanged(state, source);
|
|
734
|
+
break;
|
|
735
|
+
case "old":
|
|
736
|
+
await this.onStateUpdate(state, source);
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Called when the Agent receives an email via routeAgentEmail()
|
|
742
|
+
* Override this method to handle incoming emails
|
|
743
|
+
* @param email Email message to process
|
|
744
|
+
*/
|
|
745
|
+
async _onEmail(email) {
|
|
746
|
+
return agentContext.run({
|
|
747
|
+
agent: this,
|
|
748
|
+
connection: void 0,
|
|
749
|
+
request: void 0,
|
|
750
|
+
email
|
|
751
|
+
}, async () => {
|
|
752
|
+
if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
|
|
753
|
+
else {
|
|
754
|
+
console.log("Received email from:", email.from, "to:", email.to);
|
|
755
|
+
console.log("Subject:", email.headers.get("subject"));
|
|
756
|
+
console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
|
|
757
|
+
}
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Reply to an email
|
|
762
|
+
* @param email The email to reply to
|
|
763
|
+
* @param options Options for the reply
|
|
764
|
+
* @param options.secret Secret for signing agent headers (enables secure reply routing).
|
|
765
|
+
* Required if the email was routed via createSecureReplyEmailResolver.
|
|
766
|
+
* Pass explicit `null` to opt-out of signing (not recommended for secure routing).
|
|
767
|
+
* @returns void
|
|
768
|
+
*/
|
|
769
|
+
async replyToEmail(email, options) {
|
|
770
|
+
return this._tryCatch(async () => {
|
|
771
|
+
if (email._secureRouted && options.secret === void 0) throw new Error("This email was routed via createSecureReplyEmailResolver. You must pass a secret to replyToEmail() to sign replies, or pass explicit null to opt-out (not recommended).");
|
|
772
|
+
const agentName = camelCaseToKebabCase(this._ParentClass.name);
|
|
773
|
+
const agentId = this.name;
|
|
774
|
+
const { createMimeMessage } = await import("mimetext");
|
|
775
|
+
const msg = createMimeMessage();
|
|
776
|
+
msg.setSender({
|
|
777
|
+
addr: email.to,
|
|
778
|
+
name: options.fromName
|
|
779
|
+
});
|
|
780
|
+
msg.setRecipient(email.from);
|
|
781
|
+
msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
|
|
782
|
+
msg.addMessage({
|
|
783
|
+
contentType: options.contentType || "text/plain",
|
|
784
|
+
data: options.body
|
|
785
|
+
});
|
|
786
|
+
const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
|
|
787
|
+
msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
|
|
788
|
+
msg.setHeader("Message-ID", messageId);
|
|
789
|
+
msg.setHeader("X-Agent-Name", agentName);
|
|
790
|
+
msg.setHeader("X-Agent-ID", agentId);
|
|
791
|
+
if (typeof options.secret === "string") {
|
|
792
|
+
const signedHeaders = await signAgentHeaders(options.secret, agentName, agentId);
|
|
793
|
+
msg.setHeader("X-Agent-Sig", signedHeaders["X-Agent-Sig"]);
|
|
794
|
+
msg.setHeader("X-Agent-Sig-Ts", signedHeaders["X-Agent-Sig-Ts"]);
|
|
795
|
+
}
|
|
796
|
+
if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
|
|
797
|
+
await email.reply({
|
|
798
|
+
from: email.to,
|
|
799
|
+
raw: msg.asRaw(),
|
|
800
|
+
to: email.from
|
|
801
|
+
});
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
async _tryCatch(fn) {
|
|
805
|
+
try {
|
|
806
|
+
return await fn();
|
|
807
|
+
} catch (e) {
|
|
808
|
+
throw this.onError(e);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Automatically wrap custom methods with agent context
|
|
813
|
+
* This ensures getCurrentAgent() works in all custom methods without decorators
|
|
814
|
+
*/
|
|
815
|
+
_autoWrapCustomMethods() {
|
|
816
|
+
const basePrototypes = [Agent.prototype, Server.prototype];
|
|
817
|
+
const baseMethods = /* @__PURE__ */ new Set();
|
|
818
|
+
for (const baseProto of basePrototypes) {
|
|
819
|
+
let proto = baseProto;
|
|
820
|
+
while (proto && proto !== Object.prototype) {
|
|
821
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
822
|
+
for (const methodName of methodNames) baseMethods.add(methodName);
|
|
823
|
+
proto = Object.getPrototypeOf(proto);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
let proto = Object.getPrototypeOf(this);
|
|
827
|
+
let depth = 0;
|
|
828
|
+
while (proto && proto !== Object.prototype && depth < 10) {
|
|
829
|
+
const methodNames = Object.getOwnPropertyNames(proto);
|
|
830
|
+
for (const methodName of methodNames) {
|
|
831
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
|
|
832
|
+
if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
|
|
833
|
+
const wrappedFunction = withAgentContext(this[methodName]);
|
|
834
|
+
if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
|
|
835
|
+
this.constructor.prototype[methodName] = wrappedFunction;
|
|
836
|
+
}
|
|
837
|
+
proto = Object.getPrototypeOf(proto);
|
|
838
|
+
depth++;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
onError(connectionOrError, error) {
|
|
842
|
+
let theError;
|
|
843
|
+
if (connectionOrError && error) {
|
|
844
|
+
theError = error;
|
|
845
|
+
console.error("Error on websocket connection:", connectionOrError.id, theError);
|
|
846
|
+
console.error("Override onError(connection, error) to handle websocket connection errors");
|
|
847
|
+
} else {
|
|
848
|
+
theError = connectionOrError;
|
|
849
|
+
console.error("Error on server:", theError);
|
|
850
|
+
console.error("Override onError(error) to handle server errors");
|
|
851
|
+
}
|
|
852
|
+
throw theError;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Render content (not implemented in base class)
|
|
856
|
+
*/
|
|
857
|
+
render() {
|
|
858
|
+
throw new Error("Not implemented");
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Queue a task to be executed in the future
|
|
862
|
+
* @param payload Payload to pass to the callback
|
|
863
|
+
* @param callback Name of the method to call
|
|
864
|
+
* @returns The ID of the queued task
|
|
865
|
+
*/
|
|
866
|
+
async queue(callback, payload) {
|
|
867
|
+
const id = nanoid(9);
|
|
868
|
+
if (typeof callback !== "string") throw new Error("Callback must be a string");
|
|
869
|
+
if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
|
|
870
|
+
this.sql`
|
|
871
|
+
INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
|
|
872
|
+
VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
|
|
873
|
+
`;
|
|
874
|
+
this._flushQueue().catch((e) => {
|
|
875
|
+
console.error("Error flushing queue:", e);
|
|
876
|
+
});
|
|
877
|
+
return id;
|
|
878
|
+
}
|
|
879
|
+
async _flushQueue() {
|
|
880
|
+
if (this._flushingQueue) return;
|
|
881
|
+
this._flushingQueue = true;
|
|
882
|
+
while (true) {
|
|
883
|
+
const result = this.sql`
|
|
884
|
+
SELECT * FROM cf_agents_queues
|
|
885
|
+
ORDER BY created_at ASC
|
|
886
|
+
`;
|
|
887
|
+
if (!result || result.length === 0) break;
|
|
888
|
+
for (const row of result || []) {
|
|
889
|
+
const callback = this[row.callback];
|
|
890
|
+
if (!callback) {
|
|
891
|
+
console.error(`callback ${row.callback} not found`);
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
const { connection, request, email } = agentContext.getStore() || {};
|
|
895
|
+
await agentContext.run({
|
|
896
|
+
agent: this,
|
|
897
|
+
connection,
|
|
898
|
+
request,
|
|
899
|
+
email
|
|
900
|
+
}, async () => {
|
|
901
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
902
|
+
await this.dequeue(row.id);
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
this._flushingQueue = false;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Dequeue a task by ID
|
|
910
|
+
* @param id ID of the task to dequeue
|
|
911
|
+
*/
|
|
912
|
+
async dequeue(id) {
|
|
913
|
+
this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Dequeue all tasks
|
|
917
|
+
*/
|
|
918
|
+
async dequeueAll() {
|
|
919
|
+
this.sql`DELETE FROM cf_agents_queues`;
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Dequeue all tasks by callback
|
|
923
|
+
* @param callback Name of the callback to dequeue
|
|
924
|
+
*/
|
|
925
|
+
async dequeueAllByCallback(callback) {
|
|
926
|
+
this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Get a queued task by ID
|
|
930
|
+
* @param id ID of the task to get
|
|
931
|
+
* @returns The task or undefined if not found
|
|
932
|
+
*/
|
|
933
|
+
async getQueue(id) {
|
|
934
|
+
const result = this.sql`
|
|
935
|
+
SELECT * FROM cf_agents_queues WHERE id = ${id}
|
|
936
|
+
`;
|
|
937
|
+
return result ? {
|
|
938
|
+
...result[0],
|
|
939
|
+
payload: JSON.parse(result[0].payload)
|
|
940
|
+
} : void 0;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Get all queues by key and value
|
|
944
|
+
* @param key Key to filter by
|
|
945
|
+
* @param value Value to filter by
|
|
946
|
+
* @returns Array of matching QueueItem objects
|
|
947
|
+
*/
|
|
948
|
+
async getQueues(key, value) {
|
|
949
|
+
return this.sql`
|
|
950
|
+
SELECT * FROM cf_agents_queues
|
|
951
|
+
`.filter((row) => JSON.parse(row.payload)[key] === value);
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Schedule a task to be executed in the future
|
|
955
|
+
* @template T Type of the payload data
|
|
956
|
+
* @param when When to execute the task (Date, seconds delay, or cron expression)
|
|
957
|
+
* @param callback Name of the method to call
|
|
958
|
+
* @param payload Data to pass to the callback
|
|
959
|
+
* @returns Schedule object representing the scheduled task
|
|
960
|
+
*/
|
|
961
|
+
async schedule(when, callback, payload) {
|
|
962
|
+
const id = nanoid(9);
|
|
963
|
+
const emitScheduleCreate = (schedule) => this.observability?.emit({
|
|
964
|
+
displayMessage: `Schedule ${schedule.id} created`,
|
|
965
|
+
id: nanoid(),
|
|
966
|
+
payload: {
|
|
967
|
+
callback,
|
|
968
|
+
id
|
|
969
|
+
},
|
|
970
|
+
timestamp: Date.now(),
|
|
971
|
+
type: "schedule:create"
|
|
972
|
+
}, this.ctx);
|
|
973
|
+
if (typeof callback !== "string") throw new Error("Callback must be a string");
|
|
974
|
+
if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
|
|
975
|
+
if (when instanceof Date) {
|
|
976
|
+
const timestamp = Math.floor(when.getTime() / 1e3);
|
|
977
|
+
this.sql`
|
|
978
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
|
|
979
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
|
|
980
|
+
`;
|
|
981
|
+
await this._scheduleNextAlarm();
|
|
982
|
+
const schedule = {
|
|
983
|
+
callback,
|
|
984
|
+
id,
|
|
985
|
+
payload,
|
|
986
|
+
time: timestamp,
|
|
987
|
+
type: "scheduled"
|
|
988
|
+
};
|
|
989
|
+
emitScheduleCreate(schedule);
|
|
990
|
+
return schedule;
|
|
991
|
+
}
|
|
992
|
+
if (typeof when === "number") {
|
|
993
|
+
const time = new Date(Date.now() + when * 1e3);
|
|
994
|
+
const timestamp = Math.floor(time.getTime() / 1e3);
|
|
995
|
+
this.sql`
|
|
996
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
|
|
997
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
|
|
998
|
+
`;
|
|
999
|
+
await this._scheduleNextAlarm();
|
|
1000
|
+
const schedule = {
|
|
1001
|
+
callback,
|
|
1002
|
+
delayInSeconds: when,
|
|
1003
|
+
id,
|
|
1004
|
+
payload,
|
|
1005
|
+
time: timestamp,
|
|
1006
|
+
type: "delayed"
|
|
1007
|
+
};
|
|
1008
|
+
emitScheduleCreate(schedule);
|
|
1009
|
+
return schedule;
|
|
1010
|
+
}
|
|
1011
|
+
if (typeof when === "string") {
|
|
1012
|
+
const nextExecutionTime = getNextCronTime(when);
|
|
1013
|
+
const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
1014
|
+
this.sql`
|
|
1015
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
|
|
1016
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
|
|
1017
|
+
`;
|
|
1018
|
+
await this._scheduleNextAlarm();
|
|
1019
|
+
const schedule = {
|
|
1020
|
+
callback,
|
|
1021
|
+
cron: when,
|
|
1022
|
+
id,
|
|
1023
|
+
payload,
|
|
1024
|
+
time: timestamp,
|
|
1025
|
+
type: "cron"
|
|
1026
|
+
};
|
|
1027
|
+
emitScheduleCreate(schedule);
|
|
1028
|
+
return schedule;
|
|
1029
|
+
}
|
|
1030
|
+
throw new Error(`Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`);
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Schedule a task to run repeatedly at a fixed interval
|
|
1034
|
+
* @template T Type of the payload data
|
|
1035
|
+
* @param intervalSeconds Number of seconds between executions
|
|
1036
|
+
* @param callback Name of the method to call
|
|
1037
|
+
* @param payload Data to pass to the callback
|
|
1038
|
+
* @returns Schedule object representing the scheduled task
|
|
1039
|
+
*/
|
|
1040
|
+
async scheduleEvery(intervalSeconds, callback, payload) {
|
|
1041
|
+
const MAX_INTERVAL_SECONDS = 720 * 60 * 60;
|
|
1042
|
+
if (typeof intervalSeconds !== "number" || intervalSeconds <= 0) throw new Error("intervalSeconds must be a positive number");
|
|
1043
|
+
if (intervalSeconds > MAX_INTERVAL_SECONDS) throw new Error(`intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`);
|
|
1044
|
+
if (typeof callback !== "string") throw new Error("Callback must be a string");
|
|
1045
|
+
if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
|
|
1046
|
+
const id = nanoid(9);
|
|
1047
|
+
const time = new Date(Date.now() + intervalSeconds * 1e3);
|
|
1048
|
+
const timestamp = Math.floor(time.getTime() / 1e3);
|
|
1049
|
+
this.sql`
|
|
1050
|
+
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, intervalSeconds, time, running)
|
|
1051
|
+
VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'interval', ${intervalSeconds}, ${timestamp}, 0)
|
|
1052
|
+
`;
|
|
1053
|
+
await this._scheduleNextAlarm();
|
|
1054
|
+
const schedule = {
|
|
1055
|
+
callback,
|
|
1056
|
+
id,
|
|
1057
|
+
intervalSeconds,
|
|
1058
|
+
payload,
|
|
1059
|
+
time: timestamp,
|
|
1060
|
+
type: "interval"
|
|
1061
|
+
};
|
|
1062
|
+
this.observability?.emit({
|
|
1063
|
+
displayMessage: `Schedule ${schedule.id} created`,
|
|
1064
|
+
id: nanoid(),
|
|
1065
|
+
payload: {
|
|
1066
|
+
callback,
|
|
1067
|
+
id
|
|
1068
|
+
},
|
|
1069
|
+
timestamp: Date.now(),
|
|
1070
|
+
type: "schedule:create"
|
|
1071
|
+
}, this.ctx);
|
|
1072
|
+
return schedule;
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Get a scheduled task by ID
|
|
1076
|
+
* @template T Type of the payload data
|
|
1077
|
+
* @param id ID of the scheduled task
|
|
1078
|
+
* @returns The Schedule object or undefined if not found
|
|
1079
|
+
*/
|
|
1080
|
+
async getSchedule(id) {
|
|
1081
|
+
const result = this.sql`
|
|
1082
|
+
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
1083
|
+
`;
|
|
1084
|
+
if (!result || result.length === 0) return;
|
|
1085
|
+
return {
|
|
1086
|
+
...result[0],
|
|
1087
|
+
payload: JSON.parse(result[0].payload)
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* Get scheduled tasks matching the given criteria
|
|
1092
|
+
* @template T Type of the payload data
|
|
1093
|
+
* @param criteria Criteria to filter schedules
|
|
1094
|
+
* @returns Array of matching Schedule objects
|
|
1095
|
+
*/
|
|
1096
|
+
getSchedules(criteria = {}) {
|
|
1097
|
+
let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
|
|
1098
|
+
const params = [];
|
|
1099
|
+
if (criteria.id) {
|
|
1100
|
+
query += " AND id = ?";
|
|
1101
|
+
params.push(criteria.id);
|
|
1102
|
+
}
|
|
1103
|
+
if (criteria.type) {
|
|
1104
|
+
query += " AND type = ?";
|
|
1105
|
+
params.push(criteria.type);
|
|
1106
|
+
}
|
|
1107
|
+
if (criteria.timeRange) {
|
|
1108
|
+
query += " AND time >= ? AND time <= ?";
|
|
1109
|
+
const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
|
|
1110
|
+
const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
|
|
1111
|
+
params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
|
|
1112
|
+
}
|
|
1113
|
+
return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
|
|
1114
|
+
...row,
|
|
1115
|
+
payload: JSON.parse(row.payload)
|
|
1116
|
+
}));
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Cancel a scheduled task
|
|
1120
|
+
* @param id ID of the task to cancel
|
|
1121
|
+
* @returns true if the task was cancelled, false if the task was not found
|
|
1122
|
+
*/
|
|
1123
|
+
async cancelSchedule(id) {
|
|
1124
|
+
const schedule = await this.getSchedule(id);
|
|
1125
|
+
if (!schedule) return false;
|
|
1126
|
+
this.observability?.emit({
|
|
1127
|
+
displayMessage: `Schedule ${id} cancelled`,
|
|
1128
|
+
id: nanoid(),
|
|
1129
|
+
payload: {
|
|
1130
|
+
callback: schedule.callback,
|
|
1131
|
+
id: schedule.id
|
|
1132
|
+
},
|
|
1133
|
+
timestamp: Date.now(),
|
|
1134
|
+
type: "schedule:cancel"
|
|
1135
|
+
}, this.ctx);
|
|
1136
|
+
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
1137
|
+
await this._scheduleNextAlarm();
|
|
1138
|
+
return true;
|
|
1139
|
+
}
|
|
1140
|
+
async _scheduleNextAlarm() {
|
|
1141
|
+
const result = this.sql`
|
|
1142
|
+
SELECT time FROM cf_agents_schedules
|
|
1143
|
+
WHERE time >= ${Math.floor(Date.now() / 1e3)}
|
|
1144
|
+
ORDER BY time ASC
|
|
1145
|
+
LIMIT 1
|
|
1146
|
+
`;
|
|
1147
|
+
if (!result) return;
|
|
1148
|
+
if (result.length > 0 && "time" in result[0]) {
|
|
1149
|
+
const nextTime = result[0].time * 1e3;
|
|
1150
|
+
await this.ctx.storage.setAlarm(nextTime);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Destroy the Agent, removing all state and scheduled tasks
|
|
1155
|
+
*/
|
|
1156
|
+
async destroy() {
|
|
1157
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
1158
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
1159
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
1160
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
1161
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_workflows`;
|
|
1162
|
+
await this.ctx.storage.deleteAlarm();
|
|
1163
|
+
await this.ctx.storage.deleteAll();
|
|
1164
|
+
this._disposables.dispose();
|
|
1165
|
+
await this.mcp.dispose();
|
|
1166
|
+
this._destroyed = true;
|
|
1167
|
+
setTimeout(() => {
|
|
1168
|
+
this.ctx.abort("destroyed");
|
|
1169
|
+
}, 0);
|
|
1170
|
+
this.observability?.emit({
|
|
1171
|
+
displayMessage: "Agent destroyed",
|
|
1172
|
+
id: nanoid(),
|
|
1173
|
+
payload: {},
|
|
1174
|
+
timestamp: Date.now(),
|
|
1175
|
+
type: "destroy"
|
|
1176
|
+
}, this.ctx);
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Check if a method is callable
|
|
1180
|
+
* @param method The method name to check
|
|
1181
|
+
* @returns True if the method is marked as callable
|
|
1182
|
+
*/
|
|
1183
|
+
_isCallable(method) {
|
|
1184
|
+
return callableMetadata.has(this[method]);
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Get all methods marked as callable on this Agent
|
|
1188
|
+
* @returns A map of method names to their metadata
|
|
1189
|
+
*/
|
|
1190
|
+
getCallableMethods() {
|
|
1191
|
+
const result = /* @__PURE__ */ new Map();
|
|
1192
|
+
let prototype = Object.getPrototypeOf(this);
|
|
1193
|
+
while (prototype && prototype !== Object.prototype) {
|
|
1194
|
+
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
1195
|
+
if (name === "constructor") continue;
|
|
1196
|
+
if (result.has(name)) continue;
|
|
1197
|
+
try {
|
|
1198
|
+
const fn = prototype[name];
|
|
1199
|
+
if (typeof fn === "function") {
|
|
1200
|
+
const meta = callableMetadata.get(fn);
|
|
1201
|
+
if (meta) result.set(name, meta);
|
|
1202
|
+
}
|
|
1203
|
+
} catch (e) {
|
|
1204
|
+
if (!(e instanceof TypeError)) throw e;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
1208
|
+
}
|
|
1209
|
+
return result;
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Start a workflow and track it in this Agent's database.
|
|
1213
|
+
* Automatically injects agent identity into the workflow params.
|
|
1214
|
+
*
|
|
1215
|
+
* @template P - Type of params to pass to the workflow
|
|
1216
|
+
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
|
|
1217
|
+
* @param params - Params to pass to the workflow
|
|
1218
|
+
* @param options - Optional workflow options
|
|
1219
|
+
* @returns The workflow instance ID
|
|
1220
|
+
*
|
|
1221
|
+
* @example
|
|
1222
|
+
* ```typescript
|
|
1223
|
+
* const workflowId = await this.runWorkflow(
|
|
1224
|
+
* 'MY_WORKFLOW',
|
|
1225
|
+
* { taskId: '123', data: 'process this' }
|
|
1226
|
+
* );
|
|
1227
|
+
* ```
|
|
1228
|
+
*/
|
|
1229
|
+
async runWorkflow(workflowName, params, options) {
|
|
1230
|
+
const workflow = this._findWorkflowBindingByName(workflowName);
|
|
1231
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
|
|
1232
|
+
const agentBindingName = options?.agentBinding ?? this._findAgentBindingName();
|
|
1233
|
+
if (!agentBindingName) throw new Error("Could not detect Agent binding name from class name. Pass it explicitly via options.agentBinding");
|
|
1234
|
+
const workflowId = options?.id ?? nanoid();
|
|
1235
|
+
const augmentedParams = {
|
|
1236
|
+
...params,
|
|
1237
|
+
__agentName: this.name,
|
|
1238
|
+
__agentBinding: agentBindingName,
|
|
1239
|
+
__workflowName: workflowName
|
|
1240
|
+
};
|
|
1241
|
+
const instance = await workflow.create({
|
|
1242
|
+
id: workflowId,
|
|
1243
|
+
params: augmentedParams
|
|
1244
|
+
});
|
|
1245
|
+
const id = nanoid();
|
|
1246
|
+
const metadataJson = options?.metadata ? JSON.stringify(options.metadata) : null;
|
|
1247
|
+
try {
|
|
1248
|
+
this.sql`
|
|
1249
|
+
INSERT INTO cf_agents_workflows (id, workflow_id, workflow_name, status, metadata)
|
|
1250
|
+
VALUES (${id}, ${instance.id}, ${workflowName}, 'queued', ${metadataJson})
|
|
1251
|
+
`;
|
|
1252
|
+
} catch (e) {
|
|
1253
|
+
if (e instanceof Error && e.message.includes("UNIQUE constraint failed")) throw new Error(`Workflow with ID "${workflowId}" is already being tracked`);
|
|
1254
|
+
throw e;
|
|
1255
|
+
}
|
|
1256
|
+
this.observability?.emit({
|
|
1257
|
+
displayMessage: `Workflow ${instance.id} started`,
|
|
1258
|
+
id: nanoid(),
|
|
1259
|
+
payload: {
|
|
1260
|
+
workflowId: instance.id,
|
|
1261
|
+
workflowName
|
|
1262
|
+
},
|
|
1263
|
+
timestamp: Date.now(),
|
|
1264
|
+
type: "workflow:start"
|
|
1265
|
+
}, this.ctx);
|
|
1266
|
+
return instance.id;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Send an event to a running workflow.
|
|
1270
|
+
* The workflow can wait for this event using step.waitForEvent().
|
|
1271
|
+
*
|
|
1272
|
+
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
|
|
1273
|
+
* @param workflowId - ID of the workflow instance
|
|
1274
|
+
* @param event - Event to send
|
|
1275
|
+
*
|
|
1276
|
+
* @example
|
|
1277
|
+
* ```typescript
|
|
1278
|
+
* await this.sendWorkflowEvent(
|
|
1279
|
+
* 'MY_WORKFLOW',
|
|
1280
|
+
* workflowId,
|
|
1281
|
+
* { type: 'approval', payload: { approved: true } }
|
|
1282
|
+
* );
|
|
1283
|
+
* ```
|
|
1284
|
+
*/
|
|
1285
|
+
async sendWorkflowEvent(workflowName, workflowId, event) {
|
|
1286
|
+
const workflow = this._findWorkflowBindingByName(workflowName);
|
|
1287
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
|
|
1288
|
+
await (await workflow.get(workflowId)).sendEvent(event);
|
|
1289
|
+
this.observability?.emit({
|
|
1290
|
+
displayMessage: `Event sent to workflow ${workflowId}`,
|
|
1291
|
+
id: nanoid(),
|
|
1292
|
+
payload: {
|
|
1293
|
+
workflowId,
|
|
1294
|
+
eventType: event.type
|
|
1295
|
+
},
|
|
1296
|
+
timestamp: Date.now(),
|
|
1297
|
+
type: "workflow:event"
|
|
1298
|
+
}, this.ctx);
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* Approve a waiting workflow.
|
|
1302
|
+
* Sends an approval event to the workflow that can be received by waitForApproval().
|
|
1303
|
+
*
|
|
1304
|
+
* @param workflowId - ID of the workflow to approve
|
|
1305
|
+
* @param data - Optional approval data (reason, metadata)
|
|
1306
|
+
*
|
|
1307
|
+
* @example
|
|
1308
|
+
* ```typescript
|
|
1309
|
+
* await this.approveWorkflow(workflowId, {
|
|
1310
|
+
* reason: 'Approved by admin',
|
|
1311
|
+
* metadata: { approvedBy: userId }
|
|
1312
|
+
* });
|
|
1313
|
+
* ```
|
|
1314
|
+
*/
|
|
1315
|
+
async approveWorkflow(workflowId, data) {
|
|
1316
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1317
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1318
|
+
await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
|
|
1319
|
+
type: "approval",
|
|
1320
|
+
payload: {
|
|
1321
|
+
approved: true,
|
|
1322
|
+
reason: data?.reason,
|
|
1323
|
+
metadata: data?.metadata
|
|
1324
|
+
}
|
|
1325
|
+
});
|
|
1326
|
+
this.observability?.emit({
|
|
1327
|
+
displayMessage: `Workflow ${workflowId} approved`,
|
|
1328
|
+
id: nanoid(),
|
|
1329
|
+
payload: {
|
|
1330
|
+
workflowId,
|
|
1331
|
+
reason: data?.reason
|
|
1332
|
+
},
|
|
1333
|
+
timestamp: Date.now(),
|
|
1334
|
+
type: "workflow:approved"
|
|
1335
|
+
}, this.ctx);
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Reject a waiting workflow.
|
|
1339
|
+
* Sends a rejection event to the workflow that will cause waitForApproval() to throw.
|
|
1340
|
+
*
|
|
1341
|
+
* @param workflowId - ID of the workflow to reject
|
|
1342
|
+
* @param data - Optional rejection data (reason)
|
|
1343
|
+
*
|
|
1344
|
+
* @example
|
|
1345
|
+
* ```typescript
|
|
1346
|
+
* await this.rejectWorkflow(workflowId, {
|
|
1347
|
+
* reason: 'Request denied by admin'
|
|
1348
|
+
* });
|
|
1349
|
+
* ```
|
|
1350
|
+
*/
|
|
1351
|
+
async rejectWorkflow(workflowId, data) {
|
|
1352
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1353
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1354
|
+
await this.sendWorkflowEvent(workflowInfo.workflowName, workflowId, {
|
|
1355
|
+
type: "approval",
|
|
1356
|
+
payload: {
|
|
1357
|
+
approved: false,
|
|
1358
|
+
reason: data?.reason
|
|
1359
|
+
}
|
|
1360
|
+
});
|
|
1361
|
+
this.observability?.emit({
|
|
1362
|
+
displayMessage: `Workflow ${workflowId} rejected`,
|
|
1363
|
+
id: nanoid(),
|
|
1364
|
+
payload: {
|
|
1365
|
+
workflowId,
|
|
1366
|
+
reason: data?.reason
|
|
1367
|
+
},
|
|
1368
|
+
timestamp: Date.now(),
|
|
1369
|
+
type: "workflow:rejected"
|
|
1370
|
+
}, this.ctx);
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Terminate a running workflow.
|
|
1374
|
+
* This immediately stops the workflow and sets its status to "terminated".
|
|
1375
|
+
*
|
|
1376
|
+
* @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)
|
|
1377
|
+
* @throws Error if workflow not found in tracking table
|
|
1378
|
+
* @throws Error if workflow binding not found in environment
|
|
1379
|
+
* @throws Error if workflow is already completed/errored/terminated (from Cloudflare)
|
|
1380
|
+
*
|
|
1381
|
+
* @note `terminate()` is not yet supported in local development (wrangler dev).
|
|
1382
|
+
* It will throw an error locally but works when deployed to Cloudflare.
|
|
1383
|
+
*
|
|
1384
|
+
* @example
|
|
1385
|
+
* ```typescript
|
|
1386
|
+
* await this.terminateWorkflow(workflowId);
|
|
1387
|
+
* ```
|
|
1388
|
+
*/
|
|
1389
|
+
async terminateWorkflow(workflowId) {
|
|
1390
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1391
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1392
|
+
const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
|
|
1393
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
|
|
1394
|
+
const instance = await workflow.get(workflowId);
|
|
1395
|
+
try {
|
|
1396
|
+
await instance.terminate();
|
|
1397
|
+
} catch (err) {
|
|
1398
|
+
if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("terminateWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
|
|
1399
|
+
throw err;
|
|
1400
|
+
}
|
|
1401
|
+
const status = await instance.status();
|
|
1402
|
+
this._updateWorkflowTracking(workflowId, status);
|
|
1403
|
+
this.observability?.emit({
|
|
1404
|
+
displayMessage: `Workflow ${workflowId} terminated`,
|
|
1405
|
+
id: nanoid(),
|
|
1406
|
+
payload: {
|
|
1407
|
+
workflowId,
|
|
1408
|
+
workflowName: workflowInfo.workflowName
|
|
1409
|
+
},
|
|
1410
|
+
timestamp: Date.now(),
|
|
1411
|
+
type: "workflow:terminated"
|
|
1412
|
+
}, this.ctx);
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Pause a running workflow.
|
|
1416
|
+
* The workflow can be resumed later with resumeWorkflow().
|
|
1417
|
+
*
|
|
1418
|
+
* @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)
|
|
1419
|
+
* @throws Error if workflow not found in tracking table
|
|
1420
|
+
* @throws Error if workflow binding not found in environment
|
|
1421
|
+
* @throws Error if workflow is not running (from Cloudflare)
|
|
1422
|
+
*
|
|
1423
|
+
* @note `pause()` is not yet supported in local development (wrangler dev).
|
|
1424
|
+
* It will throw an error locally but works when deployed to Cloudflare.
|
|
1425
|
+
*
|
|
1426
|
+
* @example
|
|
1427
|
+
* ```typescript
|
|
1428
|
+
* await this.pauseWorkflow(workflowId);
|
|
1429
|
+
* ```
|
|
1430
|
+
*/
|
|
1431
|
+
async pauseWorkflow(workflowId) {
|
|
1432
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1433
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1434
|
+
const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
|
|
1435
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
|
|
1436
|
+
const instance = await workflow.get(workflowId);
|
|
1437
|
+
try {
|
|
1438
|
+
await instance.pause();
|
|
1439
|
+
} catch (err) {
|
|
1440
|
+
if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("pauseWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
|
|
1441
|
+
throw err;
|
|
1442
|
+
}
|
|
1443
|
+
const status = await instance.status();
|
|
1444
|
+
this._updateWorkflowTracking(workflowId, status);
|
|
1445
|
+
this.observability?.emit({
|
|
1446
|
+
displayMessage: `Workflow ${workflowId} paused`,
|
|
1447
|
+
id: nanoid(),
|
|
1448
|
+
payload: {
|
|
1449
|
+
workflowId,
|
|
1450
|
+
workflowName: workflowInfo.workflowName
|
|
1451
|
+
},
|
|
1452
|
+
timestamp: Date.now(),
|
|
1453
|
+
type: "workflow:paused"
|
|
1454
|
+
}, this.ctx);
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Resume a paused workflow.
|
|
1458
|
+
*
|
|
1459
|
+
* @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)
|
|
1460
|
+
* @throws Error if workflow not found in tracking table
|
|
1461
|
+
* @throws Error if workflow binding not found in environment
|
|
1462
|
+
* @throws Error if workflow is not paused (from Cloudflare)
|
|
1463
|
+
*
|
|
1464
|
+
* @note `resume()` is not yet supported in local development (wrangler dev).
|
|
1465
|
+
* It will throw an error locally but works when deployed to Cloudflare.
|
|
1466
|
+
*
|
|
1467
|
+
* @example
|
|
1468
|
+
* ```typescript
|
|
1469
|
+
* await this.resumeWorkflow(workflowId);
|
|
1470
|
+
* ```
|
|
1471
|
+
*/
|
|
1472
|
+
async resumeWorkflow(workflowId) {
|
|
1473
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1474
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1475
|
+
const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
|
|
1476
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
|
|
1477
|
+
const instance = await workflow.get(workflowId);
|
|
1478
|
+
try {
|
|
1479
|
+
await instance.resume();
|
|
1480
|
+
} catch (err) {
|
|
1481
|
+
if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("resumeWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
|
|
1482
|
+
throw err;
|
|
1483
|
+
}
|
|
1484
|
+
const status = await instance.status();
|
|
1485
|
+
this._updateWorkflowTracking(workflowId, status);
|
|
1486
|
+
this.observability?.emit({
|
|
1487
|
+
displayMessage: `Workflow ${workflowId} resumed`,
|
|
1488
|
+
id: nanoid(),
|
|
1489
|
+
payload: {
|
|
1490
|
+
workflowId,
|
|
1491
|
+
workflowName: workflowInfo.workflowName
|
|
1492
|
+
},
|
|
1493
|
+
timestamp: Date.now(),
|
|
1494
|
+
type: "workflow:resumed"
|
|
1495
|
+
}, this.ctx);
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Restart a workflow instance.
|
|
1499
|
+
* This re-runs the workflow from the beginning with the same ID.
|
|
1500
|
+
*
|
|
1501
|
+
* @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)
|
|
1502
|
+
* @param options - Optional settings
|
|
1503
|
+
* @param options.resetTracking - If true (default), resets created_at and clears error fields.
|
|
1504
|
+
* If false, preserves original timestamps.
|
|
1505
|
+
* @throws Error if workflow not found in tracking table
|
|
1506
|
+
* @throws Error if workflow binding not found in environment
|
|
1507
|
+
*
|
|
1508
|
+
* @note `restart()` is not yet supported in local development (wrangler dev).
|
|
1509
|
+
* It will throw an error locally but works when deployed to Cloudflare.
|
|
1510
|
+
*
|
|
1511
|
+
* @example
|
|
1512
|
+
* ```typescript
|
|
1513
|
+
* // Reset tracking (default)
|
|
1514
|
+
* await this.restartWorkflow(workflowId);
|
|
1515
|
+
*
|
|
1516
|
+
* // Preserve original timestamps
|
|
1517
|
+
* await this.restartWorkflow(workflowId, { resetTracking: false });
|
|
1518
|
+
* ```
|
|
1519
|
+
*/
|
|
1520
|
+
async restartWorkflow(workflowId, options = {}) {
|
|
1521
|
+
const { resetTracking = true } = options;
|
|
1522
|
+
const workflowInfo = this.getWorkflow(workflowId);
|
|
1523
|
+
if (!workflowInfo) throw new Error(`Workflow ${workflowId} not found in tracking table`);
|
|
1524
|
+
const workflow = this._findWorkflowBindingByName(workflowInfo.workflowName);
|
|
1525
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowInfo.workflowName}' not found in environment`);
|
|
1526
|
+
const instance = await workflow.get(workflowId);
|
|
1527
|
+
try {
|
|
1528
|
+
await instance.restart();
|
|
1529
|
+
} catch (err) {
|
|
1530
|
+
if (err instanceof Error && err.message.includes("Not implemented")) throw new Error("restartWorkflow() is not supported in local development. Deploy to Cloudflare to use this feature. Follow https://github.com/cloudflare/agents/issues/823 for details and updates.");
|
|
1531
|
+
throw err;
|
|
1532
|
+
}
|
|
1533
|
+
if (resetTracking) {
|
|
1534
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1535
|
+
this.sql`
|
|
1536
|
+
UPDATE cf_agents_workflows
|
|
1537
|
+
SET status = 'queued',
|
|
1538
|
+
created_at = ${now},
|
|
1539
|
+
updated_at = ${now},
|
|
1540
|
+
completed_at = NULL,
|
|
1541
|
+
error_name = NULL,
|
|
1542
|
+
error_message = NULL
|
|
1543
|
+
WHERE workflow_id = ${workflowId}
|
|
1544
|
+
`;
|
|
1545
|
+
} else {
|
|
1546
|
+
const status = await instance.status();
|
|
1547
|
+
this._updateWorkflowTracking(workflowId, status);
|
|
1548
|
+
}
|
|
1549
|
+
this.observability?.emit({
|
|
1550
|
+
displayMessage: `Workflow ${workflowId} restarted`,
|
|
1551
|
+
id: nanoid(),
|
|
1552
|
+
payload: {
|
|
1553
|
+
workflowId,
|
|
1554
|
+
workflowName: workflowInfo.workflowName
|
|
1555
|
+
},
|
|
1556
|
+
timestamp: Date.now(),
|
|
1557
|
+
type: "workflow:restarted"
|
|
1558
|
+
}, this.ctx);
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* Find a workflow binding by its name.
|
|
1562
|
+
*/
|
|
1563
|
+
_findWorkflowBindingByName(workflowName) {
|
|
1564
|
+
const binding = this.env[workflowName];
|
|
1565
|
+
if (binding && typeof binding === "object" && "create" in binding && "get" in binding) return binding;
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Get all workflow binding names from the environment.
|
|
1569
|
+
*/
|
|
1570
|
+
_getWorkflowBindingNames() {
|
|
1571
|
+
const names = [];
|
|
1572
|
+
for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "create" in value && "get" in value) names.push(key);
|
|
1573
|
+
return names;
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* Get the status of a workflow and update the tracking record.
|
|
1577
|
+
*
|
|
1578
|
+
* @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
|
|
1579
|
+
* @param workflowId - ID of the workflow instance
|
|
1580
|
+
* @returns The workflow status
|
|
1581
|
+
*/
|
|
1582
|
+
async getWorkflowStatus(workflowName, workflowId) {
|
|
1583
|
+
const workflow = this._findWorkflowBindingByName(workflowName);
|
|
1584
|
+
if (!workflow) throw new Error(`Workflow binding '${workflowName}' not found in environment`);
|
|
1585
|
+
const status = await (await workflow.get(workflowId)).status();
|
|
1586
|
+
this._updateWorkflowTracking(workflowId, status);
|
|
1587
|
+
return status;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Get a tracked workflow by ID.
|
|
1591
|
+
*
|
|
1592
|
+
* @param workflowId - Workflow instance ID
|
|
1593
|
+
* @returns Workflow info or undefined if not found
|
|
1594
|
+
*/
|
|
1595
|
+
getWorkflow(workflowId) {
|
|
1596
|
+
const rows = this.sql`
|
|
1597
|
+
SELECT * FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
|
|
1598
|
+
`;
|
|
1599
|
+
if (!rows || rows.length === 0) return;
|
|
1600
|
+
return this._rowToWorkflowInfo(rows[0]);
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* Query tracked workflows with cursor-based pagination.
|
|
1604
|
+
*
|
|
1605
|
+
* @param criteria - Query criteria including optional cursor for pagination
|
|
1606
|
+
* @returns WorkflowPage with workflows, total count, and next cursor
|
|
1607
|
+
*
|
|
1608
|
+
* @example
|
|
1609
|
+
* ```typescript
|
|
1610
|
+
* // First page
|
|
1611
|
+
* const page1 = this.getWorkflows({ status: 'running', limit: 20 });
|
|
1612
|
+
*
|
|
1613
|
+
* // Next page
|
|
1614
|
+
* if (page1.nextCursor) {
|
|
1615
|
+
* const page2 = this.getWorkflows({
|
|
1616
|
+
* status: 'running',
|
|
1617
|
+
* limit: 20,
|
|
1618
|
+
* cursor: page1.nextCursor
|
|
1619
|
+
* });
|
|
1620
|
+
* }
|
|
1621
|
+
* ```
|
|
1622
|
+
*/
|
|
1623
|
+
getWorkflows(criteria = {}) {
|
|
1624
|
+
const limit = Math.min(criteria.limit ?? 50, 100);
|
|
1625
|
+
const isAsc = criteria.orderBy === "asc";
|
|
1626
|
+
const total = this._countWorkflows(criteria);
|
|
1627
|
+
let query = "SELECT * FROM cf_agents_workflows WHERE 1=1";
|
|
1628
|
+
const params = [];
|
|
1629
|
+
if (criteria.status) {
|
|
1630
|
+
const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
|
|
1631
|
+
const placeholders = statuses.map(() => "?").join(", ");
|
|
1632
|
+
query += ` AND status IN (${placeholders})`;
|
|
1633
|
+
params.push(...statuses);
|
|
1634
|
+
}
|
|
1635
|
+
if (criteria.workflowName) {
|
|
1636
|
+
query += " AND workflow_name = ?";
|
|
1637
|
+
params.push(criteria.workflowName);
|
|
1638
|
+
}
|
|
1639
|
+
if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
|
|
1640
|
+
query += ` AND json_extract(metadata, '$.' || ?) = ?`;
|
|
1641
|
+
params.push(key, value);
|
|
1642
|
+
}
|
|
1643
|
+
if (criteria.cursor) {
|
|
1644
|
+
const cursor = this._decodeCursor(criteria.cursor);
|
|
1645
|
+
if (isAsc) query += " AND (created_at > ? OR (created_at = ? AND workflow_id > ?))";
|
|
1646
|
+
else query += " AND (created_at < ? OR (created_at = ? AND workflow_id < ?))";
|
|
1647
|
+
params.push(cursor.createdAt, cursor.createdAt, cursor.workflowId);
|
|
1648
|
+
}
|
|
1649
|
+
query += ` ORDER BY created_at ${isAsc ? "ASC" : "DESC"}, workflow_id ${isAsc ? "ASC" : "DESC"}`;
|
|
1650
|
+
query += " LIMIT ?";
|
|
1651
|
+
params.push(limit + 1);
|
|
1652
|
+
const rows = this.ctx.storage.sql.exec(query, ...params).toArray();
|
|
1653
|
+
const hasMore = rows.length > limit;
|
|
1654
|
+
const workflows = (hasMore ? rows.slice(0, limit) : rows).map((row) => this._rowToWorkflowInfo(row));
|
|
1655
|
+
return {
|
|
1656
|
+
workflows,
|
|
1657
|
+
total,
|
|
1658
|
+
nextCursor: hasMore && workflows.length > 0 ? this._encodeCursor(workflows[workflows.length - 1]) : null
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Count workflows matching criteria (for pagination total).
|
|
1663
|
+
*/
|
|
1664
|
+
_countWorkflows(criteria) {
|
|
1665
|
+
let query = "SELECT COUNT(*) as count FROM cf_agents_workflows WHERE 1=1";
|
|
1666
|
+
const params = [];
|
|
1667
|
+
if (criteria.status) {
|
|
1668
|
+
const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
|
|
1669
|
+
const placeholders = statuses.map(() => "?").join(", ");
|
|
1670
|
+
query += ` AND status IN (${placeholders})`;
|
|
1671
|
+
params.push(...statuses);
|
|
1672
|
+
}
|
|
1673
|
+
if (criteria.workflowName) {
|
|
1674
|
+
query += " AND workflow_name = ?";
|
|
1675
|
+
params.push(criteria.workflowName);
|
|
1676
|
+
}
|
|
1677
|
+
if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
|
|
1678
|
+
query += ` AND json_extract(metadata, '$.' || ?) = ?`;
|
|
1679
|
+
params.push(key, value);
|
|
1680
|
+
}
|
|
1681
|
+
if (criteria.createdBefore) {
|
|
1682
|
+
query += " AND created_at < ?";
|
|
1683
|
+
params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
|
|
1684
|
+
}
|
|
1685
|
+
return this.ctx.storage.sql.exec(query, ...params).toArray()[0]?.count ?? 0;
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Encode a cursor from workflow info for pagination.
|
|
1689
|
+
* Stores createdAt as Unix timestamp in seconds (matching DB storage).
|
|
1690
|
+
*/
|
|
1691
|
+
_encodeCursor(workflow) {
|
|
1692
|
+
return btoa(JSON.stringify({
|
|
1693
|
+
c: Math.floor(workflow.createdAt.getTime() / 1e3),
|
|
1694
|
+
i: workflow.workflowId
|
|
1695
|
+
}));
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Decode a pagination cursor.
|
|
1699
|
+
* Returns createdAt as Unix timestamp in seconds (matching DB storage).
|
|
1700
|
+
*/
|
|
1701
|
+
_decodeCursor(cursor) {
|
|
1702
|
+
try {
|
|
1703
|
+
const data = JSON.parse(atob(cursor));
|
|
1704
|
+
if (typeof data.c !== "number" || typeof data.i !== "string") throw new Error("Invalid cursor structure");
|
|
1705
|
+
return {
|
|
1706
|
+
createdAt: data.c,
|
|
1707
|
+
workflowId: data.i
|
|
1708
|
+
};
|
|
1709
|
+
} catch {
|
|
1710
|
+
throw new Error("Invalid pagination cursor. The cursor may be malformed or corrupted.");
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Delete a workflow tracking record.
|
|
1715
|
+
*
|
|
1716
|
+
* @param workflowId - ID of the workflow to delete
|
|
1717
|
+
* @returns true if a record was deleted, false if not found
|
|
1718
|
+
*/
|
|
1719
|
+
deleteWorkflow(workflowId) {
|
|
1720
|
+
const existing = this.sql`
|
|
1721
|
+
SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_id = ${workflowId}
|
|
1722
|
+
`;
|
|
1723
|
+
if (!existing[0] || existing[0].count === 0) return false;
|
|
1724
|
+
this.sql`DELETE FROM cf_agents_workflows WHERE workflow_id = ${workflowId}`;
|
|
1725
|
+
return true;
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Delete workflow tracking records matching criteria.
|
|
1729
|
+
* Useful for cleaning up old completed/errored workflows.
|
|
1730
|
+
*
|
|
1731
|
+
* @param criteria - Criteria for which workflows to delete
|
|
1732
|
+
* @returns Number of records matching criteria (expected deleted count)
|
|
1733
|
+
*
|
|
1734
|
+
* @example
|
|
1735
|
+
* ```typescript
|
|
1736
|
+
* // Delete all completed workflows created more than 7 days ago
|
|
1737
|
+
* const deleted = this.deleteWorkflows({
|
|
1738
|
+
* status: 'complete',
|
|
1739
|
+
* createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
|
1740
|
+
* });
|
|
1741
|
+
*
|
|
1742
|
+
* // Delete all errored and terminated workflows
|
|
1743
|
+
* const deleted = this.deleteWorkflows({
|
|
1744
|
+
* status: ['errored', 'terminated']
|
|
1745
|
+
* });
|
|
1746
|
+
* ```
|
|
1747
|
+
*/
|
|
1748
|
+
deleteWorkflows(criteria = {}) {
|
|
1749
|
+
let query = "DELETE FROM cf_agents_workflows WHERE 1=1";
|
|
1750
|
+
const params = [];
|
|
1751
|
+
if (criteria.status) {
|
|
1752
|
+
const statuses = Array.isArray(criteria.status) ? criteria.status : [criteria.status];
|
|
1753
|
+
const placeholders = statuses.map(() => "?").join(", ");
|
|
1754
|
+
query += ` AND status IN (${placeholders})`;
|
|
1755
|
+
params.push(...statuses);
|
|
1756
|
+
}
|
|
1757
|
+
if (criteria.workflowName) {
|
|
1758
|
+
query += " AND workflow_name = ?";
|
|
1759
|
+
params.push(criteria.workflowName);
|
|
1760
|
+
}
|
|
1761
|
+
if (criteria.metadata) for (const [key, value] of Object.entries(criteria.metadata)) {
|
|
1762
|
+
query += ` AND json_extract(metadata, '$.' || ?) = ?`;
|
|
1763
|
+
params.push(key, value);
|
|
1764
|
+
}
|
|
1765
|
+
if (criteria.createdBefore) {
|
|
1766
|
+
query += " AND created_at < ?";
|
|
1767
|
+
params.push(Math.floor(criteria.createdBefore.getTime() / 1e3));
|
|
1768
|
+
}
|
|
1769
|
+
return this.ctx.storage.sql.exec(query, ...params).rowsWritten;
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Migrate workflow tracking records from an old binding name to a new one.
|
|
1773
|
+
* Use this after renaming a workflow binding in wrangler.toml.
|
|
1774
|
+
*
|
|
1775
|
+
* @param oldName - Previous workflow binding name
|
|
1776
|
+
* @param newName - New workflow binding name
|
|
1777
|
+
* @returns Number of records migrated
|
|
1778
|
+
*
|
|
1779
|
+
* @example
|
|
1780
|
+
* ```typescript
|
|
1781
|
+
* // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml
|
|
1782
|
+
* async onStart() {
|
|
1783
|
+
* const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');
|
|
1784
|
+
* }
|
|
1785
|
+
* ```
|
|
1786
|
+
*/
|
|
1787
|
+
migrateWorkflowBinding(oldName, newName) {
|
|
1788
|
+
if (!this._findWorkflowBindingByName(newName)) throw new Error(`Workflow binding '${newName}' not found in environment`);
|
|
1789
|
+
const count = this.sql`
|
|
1790
|
+
SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_name = ${oldName}
|
|
1791
|
+
`[0]?.count ?? 0;
|
|
1792
|
+
if (count > 0) {
|
|
1793
|
+
this.sql`UPDATE cf_agents_workflows SET workflow_name = ${newName} WHERE workflow_name = ${oldName}`;
|
|
1794
|
+
console.log(`[Agent] Migrated ${count} workflow(s) from '${oldName}' to '${newName}'`);
|
|
1795
|
+
}
|
|
1796
|
+
return count;
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Update workflow tracking record from InstanceStatus
|
|
1800
|
+
*/
|
|
1801
|
+
_updateWorkflowTracking(workflowId, status) {
|
|
1802
|
+
const statusName = status.status;
|
|
1803
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1804
|
+
const completedAt = [
|
|
1805
|
+
"complete",
|
|
1806
|
+
"errored",
|
|
1807
|
+
"terminated"
|
|
1808
|
+
].includes(statusName) ? now : null;
|
|
1809
|
+
const errorName = status.error?.name ?? null;
|
|
1810
|
+
const errorMessage = status.error?.message ?? null;
|
|
1811
|
+
this.sql`
|
|
1812
|
+
UPDATE cf_agents_workflows
|
|
1813
|
+
SET status = ${statusName},
|
|
1814
|
+
error_name = ${errorName},
|
|
1815
|
+
error_message = ${errorMessage},
|
|
1816
|
+
updated_at = ${now},
|
|
1817
|
+
completed_at = ${completedAt}
|
|
1818
|
+
WHERE workflow_id = ${workflowId}
|
|
1819
|
+
`;
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* Convert a database row to WorkflowInfo
|
|
1823
|
+
*/
|
|
1824
|
+
_rowToWorkflowInfo(row) {
|
|
1825
|
+
return {
|
|
1826
|
+
id: row.id,
|
|
1827
|
+
workflowId: row.workflow_id,
|
|
1828
|
+
workflowName: row.workflow_name,
|
|
1829
|
+
status: row.status,
|
|
1830
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : null,
|
|
1831
|
+
error: row.error_name ? {
|
|
1832
|
+
name: row.error_name,
|
|
1833
|
+
message: row.error_message ?? ""
|
|
1834
|
+
} : null,
|
|
1835
|
+
createdAt: /* @__PURE__ */ new Date(row.created_at * 1e3),
|
|
1836
|
+
updatedAt: /* @__PURE__ */ new Date(row.updated_at * 1e3),
|
|
1837
|
+
completedAt: row.completed_at ? /* @__PURE__ */ new Date(row.completed_at * 1e3) : null
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Find the binding name for this Agent's namespace by matching class name.
|
|
1842
|
+
* Returns undefined if no match found - use options.agentBinding as fallback.
|
|
1843
|
+
*/
|
|
1844
|
+
_findAgentBindingName() {
|
|
1845
|
+
const className = this._ParentClass.name;
|
|
1846
|
+
for (const [key, value] of Object.entries(this.env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
|
|
1847
|
+
if (key === className || camelCaseToKebabCase(key) === camelCaseToKebabCase(className)) return key;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
/**
|
|
1851
|
+
* Handle a callback from a workflow.
|
|
1852
|
+
* Called when the Agent receives a callback at /_workflow/callback.
|
|
1853
|
+
* Override this to handle all callback types in one place.
|
|
1854
|
+
*
|
|
1855
|
+
* @param callback - The callback payload
|
|
1856
|
+
*/
|
|
1857
|
+
async onWorkflowCallback(callback) {
|
|
1858
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1859
|
+
switch (callback.type) {
|
|
1860
|
+
case "progress":
|
|
1861
|
+
this.sql`
|
|
1862
|
+
UPDATE cf_agents_workflows
|
|
1863
|
+
SET status = 'running', updated_at = ${now}
|
|
1864
|
+
WHERE workflow_id = ${callback.workflowId} AND status IN ('queued', 'waiting')
|
|
1865
|
+
`;
|
|
1866
|
+
await this.onWorkflowProgress(callback.workflowName, callback.workflowId, callback.progress);
|
|
1867
|
+
break;
|
|
1868
|
+
case "complete":
|
|
1869
|
+
this.sql`
|
|
1870
|
+
UPDATE cf_agents_workflows
|
|
1871
|
+
SET status = 'complete', updated_at = ${now}, completed_at = ${now}
|
|
1872
|
+
WHERE workflow_id = ${callback.workflowId}
|
|
1873
|
+
AND status NOT IN ('terminated', 'paused')
|
|
1874
|
+
`;
|
|
1875
|
+
await this.onWorkflowComplete(callback.workflowName, callback.workflowId, callback.result);
|
|
1876
|
+
break;
|
|
1877
|
+
case "error":
|
|
1878
|
+
this.sql`
|
|
1879
|
+
UPDATE cf_agents_workflows
|
|
1880
|
+
SET status = 'errored', updated_at = ${now}, completed_at = ${now},
|
|
1881
|
+
error_name = 'WorkflowError', error_message = ${callback.error}
|
|
1882
|
+
WHERE workflow_id = ${callback.workflowId}
|
|
1883
|
+
AND status NOT IN ('terminated', 'paused')
|
|
1884
|
+
`;
|
|
1885
|
+
await this.onWorkflowError(callback.workflowName, callback.workflowId, callback.error);
|
|
1886
|
+
break;
|
|
1887
|
+
case "event":
|
|
1888
|
+
await this.onWorkflowEvent(callback.workflowName, callback.workflowId, callback.event);
|
|
1889
|
+
break;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Called when a workflow reports progress.
|
|
1894
|
+
* Override to handle progress updates.
|
|
1895
|
+
*
|
|
1896
|
+
* @param workflowName - Workflow binding name
|
|
1897
|
+
* @param workflowId - ID of the workflow
|
|
1898
|
+
* @param progress - Typed progress data (default: DefaultProgress)
|
|
1899
|
+
*/
|
|
1900
|
+
async onWorkflowProgress(_workflowName, _workflowId, _progress) {}
|
|
1901
|
+
/**
|
|
1902
|
+
* Called when a workflow completes successfully.
|
|
1903
|
+
* Override to handle completion.
|
|
1904
|
+
*
|
|
1905
|
+
* @param workflowName - Workflow binding name
|
|
1906
|
+
* @param workflowId - ID of the workflow
|
|
1907
|
+
* @param result - Optional result data
|
|
1908
|
+
*/
|
|
1909
|
+
async onWorkflowComplete(_workflowName, _workflowId, _result) {}
|
|
1910
|
+
/**
|
|
1911
|
+
* Called when a workflow encounters an error.
|
|
1912
|
+
* Override to handle errors.
|
|
1913
|
+
*
|
|
1914
|
+
* @param workflowName - Workflow binding name
|
|
1915
|
+
* @param workflowId - ID of the workflow
|
|
1916
|
+
* @param error - Error message
|
|
1917
|
+
*/
|
|
1918
|
+
async onWorkflowError(_workflowName, _workflowId, _error) {}
|
|
1919
|
+
/**
|
|
1920
|
+
* Called when a workflow sends a custom event.
|
|
1921
|
+
* Override to handle custom events.
|
|
1922
|
+
*
|
|
1923
|
+
* @param workflowName - Workflow binding name
|
|
1924
|
+
* @param workflowId - ID of the workflow
|
|
1925
|
+
* @param event - Custom event payload
|
|
1926
|
+
*/
|
|
1927
|
+
async onWorkflowEvent(_workflowName, _workflowId, _event) {}
|
|
1928
|
+
/**
|
|
1929
|
+
* Handle a workflow callback via RPC.
|
|
1930
|
+
* @internal - Called by AgentWorkflow, do not call directly
|
|
1931
|
+
*/
|
|
1932
|
+
async _workflow_handleCallback(callback) {
|
|
1933
|
+
await this.onWorkflowCallback(callback);
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* Broadcast a message to all connected clients via RPC.
|
|
1937
|
+
* @internal - Called by AgentWorkflow, do not call directly
|
|
1938
|
+
*/
|
|
1939
|
+
_workflow_broadcast(message) {
|
|
1940
|
+
this.broadcast(JSON.stringify(message));
|
|
1941
|
+
}
|
|
1942
|
+
/**
|
|
1943
|
+
* Update agent state via RPC.
|
|
1944
|
+
* @internal - Called by AgentWorkflow, do not call directly
|
|
1945
|
+
*/
|
|
1946
|
+
_workflow_updateState(action, state) {
|
|
1947
|
+
if (action === "set") this.setState(state);
|
|
1948
|
+
else if (action === "merge") {
|
|
1949
|
+
const currentState = this.state ?? {};
|
|
1950
|
+
this.setState({
|
|
1951
|
+
...currentState,
|
|
1952
|
+
...state
|
|
1953
|
+
});
|
|
1954
|
+
} else if (action === "reset") this.setState(this.initialState);
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* Connect to a new MCP Server
|
|
1958
|
+
*
|
|
1959
|
+
* @example
|
|
1960
|
+
* // Simple usage
|
|
1961
|
+
* await this.addMcpServer("github", "https://mcp.github.com");
|
|
1962
|
+
*
|
|
1963
|
+
* @example
|
|
1964
|
+
* // With options (preferred for custom headers, transport, etc.)
|
|
1965
|
+
* await this.addMcpServer("github", "https://mcp.github.com", {
|
|
1966
|
+
* transport: { headers: { "Authorization": "Bearer ..." } }
|
|
1967
|
+
* });
|
|
1968
|
+
*
|
|
1969
|
+
* @example
|
|
1970
|
+
* // Legacy 5-parameter signature (still supported)
|
|
1971
|
+
* await this.addMcpServer("github", url, callbackHost, agentsPrefix, options);
|
|
1972
|
+
*
|
|
1973
|
+
* @param serverName Name of the MCP server
|
|
1974
|
+
* @param url MCP Server URL
|
|
1975
|
+
* @param callbackHostOrOptions Options object, or callback host string (legacy)
|
|
1976
|
+
* @param agentsPrefix agents routing prefix if not using `agents` (legacy)
|
|
1977
|
+
* @param options MCP client and transport options (legacy)
|
|
1978
|
+
* @returns Server id and state - either "authenticating" with authUrl, or "ready"
|
|
1979
|
+
* @throws If connection or discovery fails
|
|
1980
|
+
*/
|
|
1981
|
+
async addMcpServer(serverName, url, callbackHostOrOptions, agentsPrefix, options) {
|
|
1982
|
+
let resolvedCallbackHost;
|
|
1983
|
+
let resolvedAgentsPrefix;
|
|
1984
|
+
let resolvedOptions;
|
|
1985
|
+
let resolvedCallbackPath;
|
|
1986
|
+
if (typeof callbackHostOrOptions === "object" && callbackHostOrOptions !== null) {
|
|
1987
|
+
resolvedCallbackHost = callbackHostOrOptions.callbackHost;
|
|
1988
|
+
resolvedCallbackPath = callbackHostOrOptions.callbackPath;
|
|
1989
|
+
resolvedAgentsPrefix = callbackHostOrOptions.agentsPrefix ?? "agents";
|
|
1990
|
+
resolvedOptions = {
|
|
1991
|
+
client: callbackHostOrOptions.client,
|
|
1992
|
+
transport: callbackHostOrOptions.transport
|
|
1993
|
+
};
|
|
1994
|
+
} else {
|
|
1995
|
+
resolvedCallbackHost = callbackHostOrOptions;
|
|
1996
|
+
resolvedAgentsPrefix = agentsPrefix ?? "agents";
|
|
1997
|
+
resolvedOptions = options;
|
|
1998
|
+
}
|
|
1999
|
+
if (!this._resolvedOptions.sendIdentityOnConnect && !resolvedCallbackPath) throw new Error("callbackPath is required in addMcpServer options when sendIdentityOnConnect is false — the default callback URL would expose the instance name. Provide a callbackPath and route the callback request to this agent via getAgentByName.");
|
|
2000
|
+
if (!resolvedCallbackHost) {
|
|
2001
|
+
const { request } = getCurrentAgent();
|
|
2002
|
+
if (!request) throw new Error("callbackHost is required when not called within a request context");
|
|
2003
|
+
const requestUrl = new URL(request.url);
|
|
2004
|
+
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
2005
|
+
}
|
|
2006
|
+
const normalizedHost = resolvedCallbackHost.replace(/\/$/, "");
|
|
2007
|
+
const callbackUrl = resolvedCallbackPath ? `${normalizedHost}/${resolvedCallbackPath.replace(/^\//, "")}` : `${normalizedHost}/${resolvedAgentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
2008
|
+
await this.mcp.ensureJsonSchema();
|
|
2009
|
+
const id = nanoid(8);
|
|
2010
|
+
const authProvider = this.createMcpOAuthProvider(callbackUrl);
|
|
2011
|
+
authProvider.serverId = id;
|
|
2012
|
+
const transportType = resolvedOptions?.transport?.type ?? "auto";
|
|
2013
|
+
let headerTransportOpts = {};
|
|
2014
|
+
if (resolvedOptions?.transport?.headers) headerTransportOpts = {
|
|
2015
|
+
eventSourceInit: { fetch: (url, init) => fetch(url, {
|
|
2016
|
+
...init,
|
|
2017
|
+
headers: resolvedOptions?.transport?.headers
|
|
2018
|
+
}) },
|
|
2019
|
+
requestInit: { headers: resolvedOptions?.transport?.headers }
|
|
2020
|
+
};
|
|
2021
|
+
await this.mcp.registerServer(id, {
|
|
2022
|
+
url,
|
|
2023
|
+
name: serverName,
|
|
2024
|
+
callbackUrl,
|
|
2025
|
+
client: resolvedOptions?.client,
|
|
2026
|
+
transport: {
|
|
2027
|
+
...headerTransportOpts,
|
|
2028
|
+
authProvider,
|
|
2029
|
+
type: transportType
|
|
2030
|
+
}
|
|
2031
|
+
});
|
|
2032
|
+
const result = await this.mcp.connectToServer(id);
|
|
2033
|
+
if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
|
|
2034
|
+
if (result.state === MCPConnectionState.AUTHENTICATING) return {
|
|
2035
|
+
id,
|
|
2036
|
+
state: result.state,
|
|
2037
|
+
authUrl: result.authUrl
|
|
2038
|
+
};
|
|
2039
|
+
const discoverResult = await this.mcp.discoverIfConnected(id);
|
|
2040
|
+
if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
|
|
2041
|
+
return {
|
|
2042
|
+
id,
|
|
2043
|
+
state: MCPConnectionState.READY
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
async removeMcpServer(id) {
|
|
2047
|
+
await this.mcp.removeServer(id);
|
|
2048
|
+
}
|
|
2049
|
+
getMcpServers() {
|
|
2050
|
+
const mcpState = {
|
|
2051
|
+
prompts: this.mcp.listPrompts(),
|
|
2052
|
+
resources: this.mcp.listResources(),
|
|
2053
|
+
servers: {},
|
|
2054
|
+
tools: this.mcp.listTools()
|
|
2055
|
+
};
|
|
2056
|
+
const servers = this.mcp.listServers();
|
|
2057
|
+
if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
|
|
2058
|
+
const serverConn = this.mcp.mcpConnections[server.id];
|
|
2059
|
+
let defaultState = "not-connected";
|
|
2060
|
+
if (!serverConn && server.auth_url) defaultState = "authenticating";
|
|
2061
|
+
mcpState.servers[server.id] = {
|
|
2062
|
+
auth_url: server.auth_url,
|
|
2063
|
+
capabilities: serverConn?.serverCapabilities ?? null,
|
|
2064
|
+
error: serverConn?.connectionError ?? null,
|
|
2065
|
+
instructions: serverConn?.instructions ?? null,
|
|
2066
|
+
name: server.name,
|
|
2067
|
+
server_url: server.server_url,
|
|
2068
|
+
state: serverConn?.connectionState ?? defaultState
|
|
2069
|
+
};
|
|
2070
|
+
}
|
|
2071
|
+
return mcpState;
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* Create the OAuth provider used when connecting to MCP servers that require authentication.
|
|
2075
|
+
*
|
|
2076
|
+
* Override this method in a subclass to supply a custom OAuth provider implementation,
|
|
2077
|
+
* for example to use pre-registered client credentials, mTLS-based authentication,
|
|
2078
|
+
* or any other OAuth flow beyond dynamic client registration.
|
|
2079
|
+
*
|
|
2080
|
+
* @example
|
|
2081
|
+
* // Custom OAuth provider
|
|
2082
|
+
* class MyAgent extends Agent {
|
|
2083
|
+
* createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
|
|
2084
|
+
* return new MyCustomOAuthProvider(
|
|
2085
|
+
* this.ctx.storage,
|
|
2086
|
+
* this.name,
|
|
2087
|
+
* callbackUrl
|
|
2088
|
+
* );
|
|
2089
|
+
* }
|
|
2090
|
+
* }
|
|
2091
|
+
*
|
|
2092
|
+
* @param callbackUrl The OAuth callback URL for the authorization flow
|
|
2093
|
+
* @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer}
|
|
2094
|
+
*/
|
|
2095
|
+
createMcpOAuthProvider(callbackUrl) {
|
|
2096
|
+
return new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
|
|
2097
|
+
}
|
|
2098
|
+
broadcastMcpServers() {
|
|
2099
|
+
this.broadcast(JSON.stringify({
|
|
2100
|
+
mcp: this.getMcpServers(),
|
|
2101
|
+
type: MessageType.CF_AGENT_MCP_SERVERS
|
|
2102
|
+
}));
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Handle MCP OAuth callback request if it's an OAuth callback.
|
|
2106
|
+
*
|
|
2107
|
+
* This method encapsulates the entire OAuth callback flow:
|
|
2108
|
+
* 1. Checks if the request is an MCP OAuth callback
|
|
2109
|
+
* 2. Processes the OAuth code exchange
|
|
2110
|
+
* 3. Establishes the connection if successful
|
|
2111
|
+
* 4. Broadcasts MCP server state updates
|
|
2112
|
+
* 5. Returns the appropriate HTTP response
|
|
2113
|
+
*
|
|
2114
|
+
* @param request The incoming HTTP request
|
|
2115
|
+
* @returns Response if this was an OAuth callback, null otherwise
|
|
2116
|
+
*/
|
|
2117
|
+
async handleMcpOAuthCallback(request) {
|
|
2118
|
+
if (!this.mcp.isCallbackRequest(request)) return null;
|
|
2119
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
2120
|
+
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
2121
|
+
console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
|
|
2122
|
+
});
|
|
2123
|
+
this.broadcastMcpServers();
|
|
2124
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
2125
|
+
}
|
|
2126
|
+
/**
|
|
2127
|
+
* Handle OAuth callback response using MCPClientManager configuration
|
|
2128
|
+
* @param result OAuth callback result
|
|
2129
|
+
* @param request The original request (needed for base URL)
|
|
2130
|
+
* @returns Response for the OAuth callback
|
|
2131
|
+
*/
|
|
2132
|
+
handleOAuthCallbackResponse(result, request) {
|
|
2133
|
+
const config = this.mcp.getOAuthCallbackConfig();
|
|
2134
|
+
if (config?.customHandler) return config.customHandler(result);
|
|
2135
|
+
const baseOrigin = new URL(request.url).origin;
|
|
2136
|
+
if (config?.successRedirect && result.authSuccess) try {
|
|
2137
|
+
return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
|
|
2138
|
+
} catch (e) {
|
|
2139
|
+
console.error("Invalid successRedirect URL:", config.successRedirect, e);
|
|
2140
|
+
return Response.redirect(baseOrigin);
|
|
2141
|
+
}
|
|
2142
|
+
if (config?.errorRedirect && !result.authSuccess) try {
|
|
2143
|
+
const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
|
|
2144
|
+
return Response.redirect(new URL(errorUrl, baseOrigin).href);
|
|
2145
|
+
} catch (e) {
|
|
2146
|
+
console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
|
|
2147
|
+
return Response.redirect(baseOrigin);
|
|
2148
|
+
}
|
|
2149
|
+
return Response.redirect(baseOrigin);
|
|
2150
|
+
}
|
|
2151
|
+
};
|
|
2152
|
+
const wrappedClasses = /* @__PURE__ */ new Set();
|
|
2153
|
+
/**
|
|
2154
|
+
* Route a request to the appropriate Agent
|
|
2155
|
+
* @param request Request to route
|
|
2156
|
+
* @param env Environment containing Agent bindings
|
|
2157
|
+
* @param options Routing options
|
|
2158
|
+
* @returns Response from the Agent or undefined if no route matched
|
|
2159
|
+
*/
|
|
2160
|
+
async function routeAgentRequest(request, env, options) {
|
|
2161
|
+
return routePartykitRequest(request, env, {
|
|
2162
|
+
prefix: "agents",
|
|
2163
|
+
...options
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
const agentMapCache = /* @__PURE__ */ new WeakMap();
|
|
2167
|
+
/**
|
|
2168
|
+
* Route an email to the appropriate Agent
|
|
2169
|
+
* @param email The email to route
|
|
2170
|
+
* @param env The environment containing the Agent bindings
|
|
2171
|
+
* @param options The options for routing the email
|
|
2172
|
+
* @returns A promise that resolves when the email has been routed
|
|
2173
|
+
*/
|
|
2174
|
+
async function routeAgentEmail(email, env, options) {
|
|
2175
|
+
const routingInfo = await options.resolver(email, env);
|
|
2176
|
+
if (!routingInfo) {
|
|
2177
|
+
if (options.onNoRoute) await options.onNoRoute(email);
|
|
2178
|
+
else console.warn("No routing information found for email, dropping message");
|
|
2179
|
+
return;
|
|
2180
|
+
}
|
|
2181
|
+
if (!agentMapCache.has(env)) {
|
|
2182
|
+
const map = {};
|
|
2183
|
+
for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
|
|
2184
|
+
map[key] = value;
|
|
2185
|
+
map[camelCaseToKebabCase(key)] = value;
|
|
2186
|
+
}
|
|
2187
|
+
agentMapCache.set(env, map);
|
|
2188
|
+
}
|
|
2189
|
+
const agentMap = agentMapCache.get(env);
|
|
2190
|
+
const namespace = agentMap[routingInfo.agentName];
|
|
2191
|
+
if (!namespace) {
|
|
2192
|
+
const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
|
|
2193
|
+
throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
|
|
2194
|
+
}
|
|
2195
|
+
const agent = await getAgentByName(namespace, routingInfo.agentId);
|
|
2196
|
+
const serialisableEmail = {
|
|
2197
|
+
getRaw: async () => {
|
|
2198
|
+
const reader = email.raw.getReader();
|
|
2199
|
+
const chunks = [];
|
|
2200
|
+
let done = false;
|
|
2201
|
+
while (!done) {
|
|
2202
|
+
const { value, done: readerDone } = await reader.read();
|
|
2203
|
+
done = readerDone;
|
|
2204
|
+
if (value) chunks.push(value);
|
|
2205
|
+
}
|
|
2206
|
+
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
2207
|
+
const combined = new Uint8Array(totalLength);
|
|
2208
|
+
let offset = 0;
|
|
2209
|
+
for (const chunk of chunks) {
|
|
2210
|
+
combined.set(chunk, offset);
|
|
2211
|
+
offset += chunk.length;
|
|
2212
|
+
}
|
|
2213
|
+
return combined;
|
|
2214
|
+
},
|
|
2215
|
+
headers: email.headers,
|
|
2216
|
+
rawSize: email.rawSize,
|
|
2217
|
+
setReject: (reason) => {
|
|
2218
|
+
email.setReject(reason);
|
|
2219
|
+
},
|
|
2220
|
+
forward: (rcptTo, headers) => {
|
|
2221
|
+
return email.forward(rcptTo, headers);
|
|
2222
|
+
},
|
|
2223
|
+
reply: (replyOptions) => {
|
|
2224
|
+
return email.reply(new EmailMessage(replyOptions.from, replyOptions.to, replyOptions.raw));
|
|
2225
|
+
},
|
|
2226
|
+
from: email.from,
|
|
2227
|
+
to: email.to,
|
|
2228
|
+
_secureRouted: routingInfo._secureRouted
|
|
2229
|
+
};
|
|
2230
|
+
await agent._onEmail(serialisableEmail);
|
|
2231
|
+
}
|
|
2232
|
+
/**
|
|
2233
|
+
* Get or create an Agent by name
|
|
2234
|
+
* @template Env Environment type containing bindings
|
|
2235
|
+
* @template T Type of the Agent class
|
|
2236
|
+
* @param namespace Agent namespace
|
|
2237
|
+
* @param name Name of the Agent instance
|
|
2238
|
+
* @param options Options for Agent creation
|
|
2239
|
+
* @returns Promise resolving to an Agent instance stub
|
|
2240
|
+
*/
|
|
2241
|
+
async function getAgentByName(namespace, name, options) {
|
|
2242
|
+
return getServerByName(namespace, name, options);
|
|
2243
|
+
}
|
|
2244
|
+
/**
|
|
2245
|
+
* A wrapper for streaming responses in callable methods
|
|
2246
|
+
*/
|
|
2247
|
+
var StreamingResponse = class {
|
|
2248
|
+
constructor(connection, id) {
|
|
2249
|
+
this._closed = false;
|
|
2250
|
+
this._connection = connection;
|
|
2251
|
+
this._id = id;
|
|
2252
|
+
}
|
|
2253
|
+
/**
|
|
2254
|
+
* Whether the stream has been closed (via end() or error())
|
|
2255
|
+
*/
|
|
2256
|
+
get isClosed() {
|
|
2257
|
+
return this._closed;
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* Send a chunk of data to the client
|
|
2261
|
+
* @param chunk The data to send
|
|
2262
|
+
* @returns false if stream is already closed (no-op), true if sent
|
|
2263
|
+
*/
|
|
2264
|
+
send(chunk) {
|
|
2265
|
+
if (this._closed) {
|
|
2266
|
+
console.warn("StreamingResponse.send() called after stream was closed - data not sent");
|
|
2267
|
+
return false;
|
|
2268
|
+
}
|
|
2269
|
+
const response = {
|
|
2270
|
+
done: false,
|
|
2271
|
+
id: this._id,
|
|
2272
|
+
result: chunk,
|
|
2273
|
+
success: true,
|
|
2274
|
+
type: MessageType.RPC
|
|
2275
|
+
};
|
|
2276
|
+
this._connection.send(JSON.stringify(response));
|
|
2277
|
+
return true;
|
|
2278
|
+
}
|
|
2279
|
+
/**
|
|
2280
|
+
* End the stream and send the final chunk (if any)
|
|
2281
|
+
* @param finalChunk Optional final chunk of data to send
|
|
2282
|
+
* @returns false if stream is already closed (no-op), true if sent
|
|
2283
|
+
*/
|
|
2284
|
+
end(finalChunk) {
|
|
2285
|
+
if (this._closed) return false;
|
|
2286
|
+
this._closed = true;
|
|
2287
|
+
const response = {
|
|
2288
|
+
done: true,
|
|
2289
|
+
id: this._id,
|
|
2290
|
+
result: finalChunk,
|
|
2291
|
+
success: true,
|
|
2292
|
+
type: MessageType.RPC
|
|
2293
|
+
};
|
|
2294
|
+
this._connection.send(JSON.stringify(response));
|
|
2295
|
+
return true;
|
|
2296
|
+
}
|
|
2297
|
+
/**
|
|
2298
|
+
* Send an error to the client and close the stream
|
|
2299
|
+
* @param message Error message to send
|
|
2300
|
+
* @returns false if stream is already closed (no-op), true if sent
|
|
2301
|
+
*/
|
|
2302
|
+
error(message) {
|
|
2303
|
+
if (this._closed) return false;
|
|
2304
|
+
this._closed = true;
|
|
2305
|
+
const response = {
|
|
2306
|
+
error: message,
|
|
2307
|
+
id: this._id,
|
|
2308
|
+
success: false,
|
|
2309
|
+
type: MessageType.RPC
|
|
2310
|
+
};
|
|
2311
|
+
this._connection.send(JSON.stringify(response));
|
|
2312
|
+
return true;
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
2315
|
+
|
|
2316
|
+
//#endregion
|
|
2317
|
+
export { Agent, DEFAULT_AGENT_STATIC_OPTIONS, SqlError, StreamingResponse, callable, createHeaderBasedEmailResolver, getAgentByName, getCurrentAgent, routeAgentEmail, routeAgentRequest, unstable_callable };
|
|
2318
|
+
//# sourceMappingURL=index.js.map
|