@economic/agents 1.8.2 → 2.0.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.
@@ -0,0 +1,372 @@
1
+ import { createRemoteJWKSet, decodeJwt, errors, jwtVerify } from "jose";
2
+ import { BasicTracerProvider, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
3
+ //#region src/server/shared/features/auth/index.ts
4
+ const jwksByIssuer = /* @__PURE__ */ new Map();
5
+ function getJwksForIssuer(issuer) {
6
+ const normalized = issuer.replace(/\/$/, "");
7
+ let jwks = jwksByIssuer.get(normalized);
8
+ if (!jwks) {
9
+ jwks = createRemoteJWKSet(new URL(`${normalized}/.well-known/openid-configuration/jwks`));
10
+ jwksByIssuer.set(normalized, jwks);
11
+ }
12
+ return jwks;
13
+ }
14
+ function isIssuerAllowed(iss, allowed) {
15
+ return allowed.some((rule) => typeof rule === "string" ? rule === iss : rule.test(iss));
16
+ }
17
+ function extractTokenFromConnectRequest(request) {
18
+ const authorization = request.headers.get("Authorization");
19
+ if (authorization) {
20
+ const match = authorization.match(/^Bearer\s+(.+)$/i);
21
+ if (match?.[1]) return match[1].trim();
22
+ }
23
+ const wsProtocol = request.headers.get("Sec-WebSocket-Protocol");
24
+ if (wsProtocol) {
25
+ const parts = wsProtocol.split(",").map((p) => p.trim());
26
+ const idx = parts.indexOf("bearer");
27
+ if (idx !== -1 && parts[idx + 1]) return parts[idx + 1];
28
+ }
29
+ return null;
30
+ }
31
+ function hasRequiredScopes(tokenScope, required) {
32
+ if (required.length === 0) return true;
33
+ if (tokenScope === void 0) return false;
34
+ const tokens = Array.isArray(tokenScope) ? tokenScope : tokenScope.split(" ").map((s) => s.trim()).filter(Boolean);
35
+ const granted = new Set(tokens);
36
+ return required.every((scope) => granted.has(scope));
37
+ }
38
+ /**
39
+ * Verify a JWT from a request and extract claims.
40
+ *
41
+ * Extracts the token from `Authorization: Bearer` header first,
42
+ * then falls back to `Sec-WebSocket-Protocol: bearer, <token>` for WebSocket connections.
43
+ *
44
+ * Expected auth failures (missing/expired token, insufficient scope) return a failure result.
45
+ * Unexpected errors (network issues, malformed requests, untrusted issuers) throw and should
46
+ * be caught and logged by the caller.
47
+ *
48
+ * @param request - The incoming request (from ConnectionContext)
49
+ * @param config - JWT verification configuration
50
+ * @returns Result object with either verified claims or expected auth failure
51
+ * @throws Error for unexpected failures that should be logged
52
+ */
53
+ async function verifyJwt(request, config) {
54
+ const token = extractTokenFromConnectRequest(request);
55
+ if (!token) return {
56
+ success: false,
57
+ status: 401,
58
+ message: "Unauthorized: Missing authentication token"
59
+ };
60
+ let unverifiedPayload;
61
+ try {
62
+ unverifiedPayload = decodeJwt(token);
63
+ } catch {
64
+ throw new Error("Invalid token format");
65
+ }
66
+ const iss = typeof unverifiedPayload.iss === "string" ? unverifiedPayload.iss : void 0;
67
+ if (!iss) throw new Error("Missing issuer claim in token");
68
+ if (!isIssuerAllowed(iss, config.allowedIssuers)) throw new Error(`Untrusted issuer: ${iss}`);
69
+ const jwks = getJwksForIssuer(iss);
70
+ let payload;
71
+ try {
72
+ payload = (await jwtVerify(token, jwks, {
73
+ issuer: iss,
74
+ audience: config.audience
75
+ })).payload;
76
+ } catch (error) {
77
+ if (error instanceof errors.JWTExpired) return {
78
+ success: false,
79
+ status: 401,
80
+ message: "Unauthorized: Token expired"
81
+ };
82
+ if (error instanceof errors.JWTClaimValidationFailed) return {
83
+ success: false,
84
+ status: 401,
85
+ message: "Unauthorized: Token claim validation failed"
86
+ };
87
+ if (error instanceof errors.JWSSignatureVerificationFailed || error instanceof errors.JWKSNoMatchingKey) throw new Error("Invalid token signature");
88
+ throw error;
89
+ }
90
+ const requiredScopes = config.requiredScopes ?? [];
91
+ const scopeClaim = payload.scope;
92
+ if (!hasRequiredScopes(scopeClaim, requiredScopes)) return {
93
+ success: false,
94
+ status: 403,
95
+ message: "Forbidden: Insufficient scope"
96
+ };
97
+ return {
98
+ success: true,
99
+ claims: config.getClaims(payload)
100
+ };
101
+ }
102
+ //#endregion
103
+ //#region src/server/shared/features/telemetry/utils.ts
104
+ function durationMs(duration) {
105
+ return duration[0] * 1e3 + duration[1] / 1e6;
106
+ }
107
+ function stringAttribute(span, key) {
108
+ const value = span.attributes[key];
109
+ return typeof value === "string" ? value : void 0;
110
+ }
111
+ function numberAttribute(span, key) {
112
+ const value = span.attributes[key];
113
+ return typeof value === "number" ? value : void 0;
114
+ }
115
+ function parseJson(value) {
116
+ if (!value) return;
117
+ try {
118
+ return JSON.parse(value);
119
+ } catch {
120
+ return;
121
+ }
122
+ }
123
+ //#endregion
124
+ //#region src/server/shared/features/telemetry/audit-logs.ts
125
+ function safePathSegment(value, fallback) {
126
+ return (value || fallback).replace(/[^a-zA-Z0-9._-]/g, "_");
127
+ }
128
+ function createAuditLogKey(agentName, conversationId) {
129
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-");
130
+ const id = crypto.randomUUID().slice(0, 8);
131
+ return [
132
+ safePathSegment(agentName, "unknown-agent"),
133
+ safePathSegment(conversationId, "unknown-conversation"),
134
+ `${timestamp}-${id}.json`
135
+ ].join("/");
136
+ }
137
+ function textFromContent(content) {
138
+ if (typeof content === "string") return content;
139
+ if (Array.isArray(content)) return content.map((part) => {
140
+ if (!part || typeof part !== "object") return "";
141
+ const value = part.text;
142
+ return typeof value === "string" ? value : "";
143
+ }).filter(Boolean).join("\n");
144
+ return "";
145
+ }
146
+ function extractPrompt(messages) {
147
+ const firstUserMessage = messages.find((message) => message.role === "user");
148
+ return firstUserMessage ? textFromContent(firstUserMessage.content) : "";
149
+ }
150
+ function promptCharCount(messages) {
151
+ const firstUserMessage = messages.find((message) => message.role === "user");
152
+ return firstUserMessage ? textFromContent(firstUserMessage.content).length : 0;
153
+ }
154
+ function extractTools(messages) {
155
+ const tools = [];
156
+ for (const message of messages) {
157
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
158
+ for (const part of message.content) {
159
+ if (!part || typeof part !== "object") continue;
160
+ const record = part;
161
+ if (record.type !== "tool_use") continue;
162
+ tools.push({
163
+ name: typeof record.name === "string" ? record.name : void 0,
164
+ input: record.input,
165
+ status: "success"
166
+ });
167
+ }
168
+ }
169
+ return tools;
170
+ }
171
+ function extractSkillName(toolName, input) {
172
+ if (!input || typeof input !== "object") return;
173
+ const record = input;
174
+ if (toolName === "load_context") {
175
+ const key = record.key;
176
+ return typeof key === "string" ? key : void 0;
177
+ }
178
+ if (toolName === "activate_skill") {
179
+ const skill = record.skill ?? record.name ?? record.key;
180
+ return typeof skill === "string" ? skill : void 0;
181
+ }
182
+ }
183
+ function pushToolCall(map, key, toolCall) {
184
+ const existing = map.get(key);
185
+ if (existing) existing.push(toolCall);
186
+ else map.set(key, [toolCall]);
187
+ }
188
+ /**
189
+ * Stores the last ai.streamText.doStream span per conversation.
190
+ * Its ai.prompt.messages contains the full conversation history including all
191
+ * intermediate tool_use + tool_result turns from the agentic loop.
192
+ */
193
+ const lastDoStreamByConversation = /* @__PURE__ */ new Map();
194
+ const toolCallsByParentSpan = /* @__PURE__ */ new Map();
195
+ const toolCallsByConversation = /* @__PURE__ */ new Map();
196
+ const pendingToolCalls = [];
197
+ const currentSkillByConversation = /* @__PURE__ */ new Map();
198
+ function rememberToolCall(span) {
199
+ const parentSpanId = span.parentSpanContext?.spanId;
200
+ const toolName = stringAttribute(span, "ai.toolCall.name");
201
+ const input = parseJson(stringAttribute(span, "ai.toolCall.args"));
202
+ const toolCall = {
203
+ name: toolName,
204
+ input,
205
+ status: span.status.code === 0 ? "success" : "error",
206
+ skillName: extractSkillName(toolName, input)
207
+ };
208
+ if (parentSpanId) pushToolCall(toolCallsByParentSpan, parentSpanId, toolCall);
209
+ pendingToolCalls.push(toolCall);
210
+ }
211
+ function attachToolCallsToConversation(span, conversationId) {
212
+ const spanId = span.spanContext().spanId;
213
+ const toolCalls = toolCallsByParentSpan.get(spanId) ?? pendingToolCalls.splice(0);
214
+ if (!toolCalls.length) return;
215
+ toolCallsByParentSpan.delete(spanId);
216
+ const currentSkill = currentSkillByConversation.get(conversationId);
217
+ const attributedToolCalls = toolCalls.map((toolCall) => {
218
+ const skillName = toolCall.skillName ?? currentSkill;
219
+ if (toolCall.skillName) currentSkillByConversation.set(conversationId, toolCall.skillName);
220
+ return {
221
+ ...toolCall,
222
+ ...skillName ? { skillName } : {}
223
+ };
224
+ });
225
+ toolCallsByConversation.set(conversationId, [...toolCallsByConversation.get(conversationId) ?? [], ...attributedToolCalls]);
226
+ }
227
+ function buildAuditLog(span, context) {
228
+ const lastDoStream = lastDoStreamByConversation.get(context.conversationId);
229
+ lastDoStreamByConversation.delete(context.conversationId);
230
+ const promptMessages = parseJson(stringAttribute(lastDoStream ?? span, "ai.prompt.messages"));
231
+ const fallbackPrompt = parseJson(stringAttribute(span, "ai.prompt"));
232
+ const inputMessages = promptMessages ?? fallbackPrompt?.messages ?? [];
233
+ const spanToolCalls = toolCallsByConversation.get(context.conversationId) ?? [];
234
+ toolCallsByConversation.delete(context.conversationId);
235
+ return {
236
+ id: createAuditLogKey(context.agentName, context.conversationId),
237
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
238
+ conversationId: context.conversationId,
239
+ agent: {
240
+ name: context.agentName,
241
+ llm: {
242
+ model: stringAttribute(span, "ai.model.id"),
243
+ provider: stringAttribute(span, "ai.model.provider")
244
+ }
245
+ },
246
+ actor: {
247
+ userId: context.userId,
248
+ ip: {
249
+ client: context.clientIp ?? context.forwardedFor?.split(",").map((ip) => ip.trim()).filter(Boolean)[0],
250
+ forwardedFor: context.forwardedFor?.split(",").map((ip) => ip.trim()).filter(Boolean) ?? []
251
+ }
252
+ },
253
+ prompt: extractPrompt(inputMessages),
254
+ response: stringAttribute(span, "ai.response.text") ?? "",
255
+ status: span.status.code === 0 ? "success" : "error",
256
+ tools: [...extractTools(inputMessages), ...spanToolCalls]
257
+ };
258
+ }
259
+ function rememberDoStream(span, conversationId) {
260
+ lastDoStreamByConversation.set(conversationId, span);
261
+ }
262
+ async function handleAuditSpan(span, auditLogs, context) {
263
+ const auditLog = buildAuditLog(span, context);
264
+ if (!auditLogs) return;
265
+ await auditLogs.put(auditLog.id, JSON.stringify(auditLog, null, 2), { httpMetadata: { contentType: "application/json" } });
266
+ console.log("[AuditLog] Created", auditLog.id);
267
+ }
268
+ //#endregion
269
+ //#region src/server/shared/features/telemetry/analytics.ts
270
+ function writeAnalyticsDatapoint(analytics, dataPoint) {
271
+ if (!analytics) return;
272
+ try {
273
+ analytics.writeDataPoint(dataPoint);
274
+ } catch (error) {
275
+ console.error("[Agent] Failed to write analytics datapoint", error);
276
+ }
277
+ }
278
+ function handleAnalyticsSpan(span, analytics) {
279
+ if (span.name === "ai.streamText.doStream") {
280
+ const promptMessages = parseJson(stringAttribute(span, "ai.prompt.messages"));
281
+ const responseText = stringAttribute(span, "ai.response.text") ?? "";
282
+ writeAnalyticsDatapoint(analytics, {
283
+ indexes: [stringAttribute(span, "ai.telemetry.metadata.userId") ?? ""],
284
+ blobs: [
285
+ "llm_call",
286
+ stringAttribute(span, "ai.telemetry.metadata.agentName") ?? "",
287
+ stringAttribute(span, "ai.telemetry.metadata.conversationId") ?? "",
288
+ stringAttribute(span, "ai.model.id") ?? "",
289
+ stringAttribute(span, "ai.model.provider") ?? "",
290
+ stringAttribute(span, "ai.response.finishReason") ?? ""
291
+ ],
292
+ doubles: [
293
+ numberAttribute(span, "ai.usage.inputTokens") ?? 0,
294
+ numberAttribute(span, "ai.usage.outputTokens") ?? 0,
295
+ numberAttribute(span, "ai.usage.totalTokens") ?? 0,
296
+ numberAttribute(span, "ai.usage.inputTokenDetails.cacheReadTokens") ?? 0,
297
+ numberAttribute(span, "ai.usage.inputTokenDetails.cacheWriteTokens") ?? 0,
298
+ durationMs(span.duration),
299
+ promptCharCount(promptMessages ?? []),
300
+ responseText.length
301
+ ]
302
+ });
303
+ return;
304
+ }
305
+ if (span.name === "ai.toolCall") {
306
+ const toolName = stringAttribute(span, "ai.toolCall.name");
307
+ const toolInput = parseJson(stringAttribute(span, "ai.toolCall.args"));
308
+ const conversationId = stringAttribute(span, "ai.telemetry.metadata.conversationId") ?? "";
309
+ const skillName = extractSkillName(toolName, toolInput) ?? currentSkillByConversation.get(conversationId) ?? "";
310
+ const success = span.status.code === 0;
311
+ writeAnalyticsDatapoint(analytics, {
312
+ indexes: [stringAttribute(span, "ai.telemetry.metadata.userId") ?? ""],
313
+ blobs: [
314
+ "tool_call",
315
+ stringAttribute(span, "ai.telemetry.metadata.agentName") ?? "",
316
+ conversationId,
317
+ toolName ?? "",
318
+ skillName,
319
+ success ? "success" : "error"
320
+ ],
321
+ doubles: [
322
+ durationMs(span.duration),
323
+ success ? 1 : 0,
324
+ 0,
325
+ 0,
326
+ 0,
327
+ 0,
328
+ 0,
329
+ 0
330
+ ]
331
+ });
332
+ }
333
+ }
334
+ //#endregion
335
+ //#region src/server/shared/features/telemetry/index.ts
336
+ var AgentSpanExporter = class {
337
+ auditLogs;
338
+ analytics;
339
+ context;
340
+ constructor(auditLogs, analytics, context) {
341
+ this.auditLogs = auditLogs;
342
+ this.analytics = analytics;
343
+ this.context = context;
344
+ }
345
+ export(spans, resultCallback) {
346
+ (async () => {
347
+ try {
348
+ for (const span of spans) if (span.name === "ai.streamText.doStream") {
349
+ rememberDoStream(span, this.context.conversationId);
350
+ attachToolCallsToConversation(span, this.context.conversationId);
351
+ handleAnalyticsSpan(span, this.analytics);
352
+ } else if (span.name === "ai.streamText") await handleAuditSpan(span, this.auditLogs, this.context);
353
+ else if (span.name === "ai.toolCall") {
354
+ rememberToolCall(span);
355
+ handleAnalyticsSpan(span, this.analytics);
356
+ }
357
+ resultCallback({ code: 0 });
358
+ } catch (error) {
359
+ resultCallback({
360
+ code: 1,
361
+ error: error instanceof Error ? error : new Error(String(error))
362
+ });
363
+ }
364
+ })();
365
+ }
366
+ async shutdown() {}
367
+ };
368
+ function createAgentTracer(auditLogs, analytics, context) {
369
+ return new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(new AgentSpanExporter(auditLogs, analytics, context))] }).getTracer("@economic/agents");
370
+ }
371
+ //#endregion
372
+ export { extractTokenFromConnectRequest as n, verifyJwt as r, createAgentTracer as t };
package/dist/v2.d.mts ADDED
@@ -0,0 +1,164 @@
1
+ import { t as JwtAuthConfig } from "./index-DzOC3mNl.mjs";
2
+ import { JSONValue, LanguageModel, Tool as Tool$1, UIMessage } from "ai";
3
+ import { Agent as Agent$1, Connection, ConnectionContext, SubAgentClass } from "agents";
4
+ import { ChatResponseResult, Session, StepConfig, Think, ToolCallContext, ToolCallDecision, TurnConfig, TurnContext } from "@cloudflare/think";
5
+
6
+ //#region src/server/v2/types.d.ts
7
+ /**
8
+ * The context object available throughout an agent's lifetime — passed via
9
+ * `experimental_context` to tool `execute` functions. Contains the typed
10
+ * request body merged with platform capabilities like `logEvent`.ext = AgentToolContext<MyBody>;
11
+ * ```
12
+ */
13
+ type ToolContext<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext = Record<string, unknown> | undefined> = RequestContext & {
14
+ _userContext?: UserContext;
15
+ };
16
+ interface AgentEnv {
17
+ AGENT_DB: D1Database;
18
+ AGENTS_AUDIT_LOGS: R2Bucket;
19
+ AGENTS_ANALYTICS: AnalyticsEngineDataset;
20
+ SKILLS_BUCKET: R2Bucket;
21
+ }
22
+ //#endregion
23
+ //#region src/server/v2/util/tools.d.ts
24
+ type ToolSet = Record<string, Tool>;
25
+ type Tool<Context extends Record<string, unknown> = Record<string, unknown>, INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = Tool$1<INPUT, OUTPUT> & {
26
+ authorize?: (ctx: Context) => boolean;
27
+ };
28
+ declare function tool<Context extends Record<string, unknown> = Record<string, unknown>, INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any>(tool: Tool<Context, INPUT, OUTPUT>): Tool$1<INPUT, OUTPUT>;
29
+ //#endregion
30
+ //#region src/server/v2/util/skills.d.ts
31
+ interface Skill<Context extends Record<string, unknown> = Record<string, unknown>> {
32
+ name: string;
33
+ description: string;
34
+ instructions: string;
35
+ tools?: Record<string, Tool<Context>>;
36
+ authorize?: (ctx: Context) => boolean;
37
+ }
38
+ declare function skill<Context extends Record<string, unknown> = Record<string, unknown>>(definition: Skill<Context>): Skill<Context>;
39
+ //#endregion
40
+ //#region src/server/v2/agents/Agent.d.ts
41
+ declare function getCurrentToolContext(): any;
42
+ type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized";
43
+ type AgentConnectionType = "agent" | "chat" | "assistant";
44
+ type AgentConnectionState = {
45
+ status: AgentConnectionStatus;
46
+ type: AgentConnectionType;
47
+ };
48
+ declare abstract class Agent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Think<Cloudflare.Env & AgentEnv, AgentConnectionState> {
49
+ initialState: AgentConnectionState;
50
+ protected clientIp?: string;
51
+ protected forwardedFor?: string;
52
+ /**
53
+ * Returns the user ID from the durable object name.
54
+ */
55
+ protected getUserIdFromDurableObjectName(): string;
56
+ protected getParentAgent<T extends Agent$1>(): T | undefined;
57
+ abstract getModel(ctx?: ToolContext<RequestContext, UserContext>): LanguageModel;
58
+ abstract getSystemPrompt(ctx?: ToolContext<RequestContext, UserContext>): string;
59
+ configureSession(session: Session): Session;
60
+ onStart(): Promise<void>;
61
+ onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
62
+ /**
63
+ * Merges the client request `body` into `experimental_context` for tools
64
+ * returned from {@link getTools} only (Think-internal tools are unchanged).
65
+ *
66
+ * If you override `beforeTurn`, call `super.beforeTurn(ctx)` and merge
67
+ * `returned.tools` into your own `TurnConfig.tools` if you return tools.
68
+ */
69
+ beforeTurn(ctx: TurnContext): Promise<void | TurnConfig>;
70
+ /**
71
+ * Sets active tools based on skills that might be loaded in the current turn.
72
+ *
73
+ * @param ctx - The prepare step context.
74
+ * @returns The step config.
75
+ */
76
+ beforeStep(): Promise<StepConfig | void>;
77
+ beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void>;
78
+ private _buildToolContext;
79
+ getTools(): ToolSet;
80
+ /**
81
+ * Returns the remote skills to be loaded from SKILLS_BUCKET.
82
+ * @returns The remote skills to be loaded from SKILLS_BUCKET.
83
+ */
84
+ protected getRemoteSkills(): string[];
85
+ /**
86
+ * Returns the skills to load for the agent.
87
+ * @returns The skills to load for the agent.
88
+ */
89
+ protected getSkills(): Skill[];
90
+ private _getAuthorizedTools;
91
+ private _getAuthorizedSkills;
92
+ /** Store the pending user context request to defer awaiting it until after the connection is established */
93
+ private _requestContext?;
94
+ /**
95
+ * Override to enable JWT authentication on WebSocket connections.
96
+ * Return the auth config based on the incoming request, or undefined to skip auth.
97
+ * Do not add side effects to this method - return a single JwtAuthConfig from it.
98
+ *
99
+ * @param env - The worker environment variables
100
+ * @returns JWT auth config or undefined to skip authentication
101
+ */
102
+ static getJwtAuthConfig?(env: Cloudflare.Env): JwtAuthConfig<Record<string, unknown>> | undefined;
103
+ /** Store the pending user context request to defer awaiting it until after the connection is established */
104
+ private _pendingUserContextRequest?;
105
+ /**
106
+ * The user context for the session.
107
+ * Define getUserContext to set a user context.
108
+ */
109
+ private _userContext?;
110
+ /**
111
+ * Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
112
+ * This method should not have side effects - return a single object from it.
113
+ * @returns The user context from the request.
114
+ * @param jwtToken - A valid JWT token following authentication.
115
+ */
116
+ protected getUserContext?(jwtToken: string): Promise<UserContext>;
117
+ }
118
+ //#endregion
119
+ //#region src/server/v2/agents/ChatAgent.d.ts
120
+ declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Agent<RequestContext, UserContext> {
121
+ initialState: AgentConnectionState;
122
+ onStart(): Promise<void>;
123
+ configureSession(session: Session): Session;
124
+ onChatResponse(_result: ChatResponseResult): Promise<void>;
125
+ /**
126
+ * Rate a message by its id.
127
+ * @param messageId - The id of the message to rate.
128
+ * @param rating - The rating to give the message. 1 = thumbs up, -1 = thumbs down.
129
+ * @returns The message id and the rating.
130
+ */
131
+ rateMessage(messageId: string, rating: number, comment?: string): Promise<void>;
132
+ /**
133
+ * Returns all message ratings for the current conversation.
134
+ * @returns All message ratings for the current conversation.
135
+ */
136
+ getMessageRatings(): Promise<any>;
137
+ }
138
+ //#endregion
139
+ //#region src/server/v2/features/conversations.d.ts
140
+ type Conversation = {
141
+ durable_object_name: string;
142
+ title?: string;
143
+ summary?: string;
144
+ created_at: number;
145
+ updated_at: number;
146
+ };
147
+ declare const DELETE_CONVERSATION_CALLBACK: "deleteConversationCallback";
148
+ //#endregion
149
+ //#region src/server/v2/agents/Assistant.d.ts
150
+ declare abstract class Assistant extends Agent$1<Cloudflare.Env, AgentConnectionState> {
151
+ initialState: AgentConnectionState;
152
+ protected abstract agent: SubAgentClass<ChatAgent>;
153
+ protected abstract fastModel: LanguageModel;
154
+ onStart(): void;
155
+ onConnect(): Promise<void>;
156
+ createConversation(): Promise<string>;
157
+ deleteConversation(id: string): Promise<void>;
158
+ getConversations(): Promise<Conversation[]>;
159
+ recordConversationTurn(durableObjectName: string, messages: UIMessage[]): Promise<void>;
160
+ private [DELETE_CONVERSATION_CALLBACK];
161
+ private scheduleConversationForAutoDeletion;
162
+ }
163
+ //#endregion
164
+ export { Agent, type AgentEnv, Assistant, ChatAgent, type Skill, type Tool, type ToolContext, type ToolSet, getCurrentToolContext, skill, tool };