@economic/agents 2.1.0 → 2.1.1
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/dist/index.mjs +5 -5
- package/dist/{telemetry-a-1XBTxr.mjs → telemetry-BKgBMVF0.mjs} +25 -25
- package/dist/v2.d.mts +11 -11
- package/dist/v2.mjs +58 -58
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as extractTokenFromConnectRequest, r as verifyJwt, t as createAgentTracer } from "./telemetry-
|
|
1
|
+
import { n as extractTokenFromConnectRequest, r as verifyJwt, t as createAgentTracer } from "./telemetry-BKgBMVF0.mjs";
|
|
2
2
|
import { Output, convertToModelMessages, generateText, jsonSchema, stepCountIs, streamText, tool } from "ai";
|
|
3
3
|
import { Agent as Agent$1, callable, getCurrentAgent, routeAgentRequest as routeAgentRequest$1 } from "agents";
|
|
4
4
|
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
@@ -359,7 +359,7 @@ var Agent = class extends Agent$1 {
|
|
|
359
359
|
isEnabled: true,
|
|
360
360
|
tracer: createAgentTracer(this.env.AGENTS_AUDIT_LOGS, this.env.AGENTS_ANALYTICS, {
|
|
361
361
|
agentName: this.constructor.name,
|
|
362
|
-
|
|
362
|
+
chatId: this.name,
|
|
363
363
|
userId: this.getUserId(),
|
|
364
364
|
...this.clientIp ? { clientIp: this.clientIp } : {},
|
|
365
365
|
...this.forwardedFor ? { forwardedFor: this.forwardedFor } : {}
|
|
@@ -367,7 +367,7 @@ var Agent = class extends Agent$1 {
|
|
|
367
367
|
metadata: {
|
|
368
368
|
agentName: this.constructor.name,
|
|
369
369
|
version: "v1",
|
|
370
|
-
|
|
370
|
+
chatId: this.name,
|
|
371
371
|
userId: this.getUserId(),
|
|
372
372
|
...this.clientIp ? { clientIp: this.clientIp } : {},
|
|
373
373
|
...this.forwardedFor ? { forwardedFor: this.forwardedFor } : {},
|
|
@@ -769,7 +769,7 @@ var ChatAgent = class extends AIChatAgent {
|
|
|
769
769
|
isEnabled: true,
|
|
770
770
|
tracer: createAgentTracer(this.env.AGENTS_AUDIT_LOGS, this.env.AGENTS_ANALYTICS, {
|
|
771
771
|
agentName: this.constructor.name,
|
|
772
|
-
|
|
772
|
+
chatId: this.name,
|
|
773
773
|
userId: this.getUserId(),
|
|
774
774
|
...this.clientIp ? { clientIp: this.clientIp } : {},
|
|
775
775
|
...this.forwardedFor ? { forwardedFor: this.forwardedFor } : {}
|
|
@@ -777,7 +777,7 @@ var ChatAgent = class extends AIChatAgent {
|
|
|
777
777
|
metadata: {
|
|
778
778
|
agentName: this.constructor.name,
|
|
779
779
|
version: "v1",
|
|
780
|
-
|
|
780
|
+
chatId: this.name,
|
|
781
781
|
userId: this.getUserId(),
|
|
782
782
|
...this.clientIp ? { clientIp: this.clientIp } : {},
|
|
783
783
|
...this.forwardedFor ? { forwardedFor: this.forwardedFor } : {},
|
|
@@ -125,12 +125,12 @@ function parseJson(value) {
|
|
|
125
125
|
function safePathSegment(value, fallback) {
|
|
126
126
|
return (value || fallback).replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
127
127
|
}
|
|
128
|
-
function createAuditLogKey(agentName,
|
|
128
|
+
function createAuditLogKey(agentName, chatId) {
|
|
129
129
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-");
|
|
130
130
|
const id = crypto.randomUUID().slice(0, 8);
|
|
131
131
|
return [
|
|
132
132
|
safePathSegment(agentName, "unknown-agent"),
|
|
133
|
-
safePathSegment(
|
|
133
|
+
safePathSegment(chatId, "unknown-chat"),
|
|
134
134
|
`${timestamp}-${id}.json`
|
|
135
135
|
].join("/");
|
|
136
136
|
}
|
|
@@ -186,15 +186,15 @@ function pushToolCall(map, key, toolCall) {
|
|
|
186
186
|
else map.set(key, [toolCall]);
|
|
187
187
|
}
|
|
188
188
|
/**
|
|
189
|
-
* Stores the last ai.streamText.doStream span per
|
|
190
|
-
* Its ai.prompt.messages contains the full
|
|
189
|
+
* Stores the last ai.streamText.doStream span per chat.
|
|
190
|
+
* Its ai.prompt.messages contains the full chat history including all
|
|
191
191
|
* intermediate tool_use + tool_result turns from the agentic loop.
|
|
192
192
|
*/
|
|
193
|
-
const
|
|
193
|
+
const lastDoStreamByChat = /* @__PURE__ */ new Map();
|
|
194
194
|
const toolCallsByParentSpan = /* @__PURE__ */ new Map();
|
|
195
|
-
const
|
|
195
|
+
const toolCallsByChat = /* @__PURE__ */ new Map();
|
|
196
196
|
const pendingToolCalls = [];
|
|
197
|
-
const
|
|
197
|
+
const currentSkillByChat = /* @__PURE__ */ new Map();
|
|
198
198
|
function rememberToolCall(span) {
|
|
199
199
|
const parentSpanId = span.parentSpanContext?.spanId;
|
|
200
200
|
const toolName = stringAttribute(span, "ai.toolCall.name");
|
|
@@ -208,34 +208,34 @@ function rememberToolCall(span) {
|
|
|
208
208
|
if (parentSpanId) pushToolCall(toolCallsByParentSpan, parentSpanId, toolCall);
|
|
209
209
|
pendingToolCalls.push(toolCall);
|
|
210
210
|
}
|
|
211
|
-
function
|
|
211
|
+
function attachToolCallsToChat(span, chatId) {
|
|
212
212
|
const spanId = span.spanContext().spanId;
|
|
213
213
|
const toolCalls = toolCallsByParentSpan.get(spanId) ?? pendingToolCalls.splice(0);
|
|
214
214
|
if (!toolCalls.length) return;
|
|
215
215
|
toolCallsByParentSpan.delete(spanId);
|
|
216
|
-
const currentSkill =
|
|
216
|
+
const currentSkill = currentSkillByChat.get(chatId);
|
|
217
217
|
const attributedToolCalls = toolCalls.map((toolCall) => {
|
|
218
218
|
const skillName = toolCall.skillName ?? currentSkill;
|
|
219
|
-
if (toolCall.skillName)
|
|
219
|
+
if (toolCall.skillName) currentSkillByChat.set(chatId, toolCall.skillName);
|
|
220
220
|
return {
|
|
221
221
|
...toolCall,
|
|
222
222
|
...skillName ? { skillName } : {}
|
|
223
223
|
};
|
|
224
224
|
});
|
|
225
|
-
|
|
225
|
+
toolCallsByChat.set(chatId, [...toolCallsByChat.get(chatId) ?? [], ...attributedToolCalls]);
|
|
226
226
|
}
|
|
227
227
|
function buildAuditLog(span, context) {
|
|
228
|
-
const lastDoStream =
|
|
229
|
-
|
|
228
|
+
const lastDoStream = lastDoStreamByChat.get(context.chatId);
|
|
229
|
+
lastDoStreamByChat.delete(context.chatId);
|
|
230
230
|
const promptMessages = parseJson(stringAttribute(lastDoStream ?? span, "ai.prompt.messages"));
|
|
231
231
|
const fallbackPrompt = parseJson(stringAttribute(span, "ai.prompt"));
|
|
232
232
|
const inputMessages = promptMessages ?? fallbackPrompt?.messages ?? [];
|
|
233
|
-
const spanToolCalls =
|
|
234
|
-
|
|
233
|
+
const spanToolCalls = toolCallsByChat.get(context.chatId) ?? [];
|
|
234
|
+
toolCallsByChat.delete(context.chatId);
|
|
235
235
|
return {
|
|
236
|
-
id: createAuditLogKey(context.agentName, context.
|
|
236
|
+
id: createAuditLogKey(context.agentName, context.chatId),
|
|
237
237
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
238
|
-
|
|
238
|
+
chatId: context.chatId,
|
|
239
239
|
agent: {
|
|
240
240
|
name: context.agentName,
|
|
241
241
|
llm: {
|
|
@@ -256,8 +256,8 @@ function buildAuditLog(span, context) {
|
|
|
256
256
|
tools: [...extractTools(inputMessages), ...spanToolCalls]
|
|
257
257
|
};
|
|
258
258
|
}
|
|
259
|
-
function rememberDoStream(span,
|
|
260
|
-
|
|
259
|
+
function rememberDoStream(span, chatId) {
|
|
260
|
+
lastDoStreamByChat.set(chatId, span);
|
|
261
261
|
}
|
|
262
262
|
async function handleAuditSpan(span, auditLogs, context) {
|
|
263
263
|
const auditLog = buildAuditLog(span, context);
|
|
@@ -284,7 +284,7 @@ function handleAnalyticsSpan(span, analytics) {
|
|
|
284
284
|
blobs: [
|
|
285
285
|
"llm_call",
|
|
286
286
|
stringAttribute(span, "ai.telemetry.metadata.agentName") ?? "",
|
|
287
|
-
stringAttribute(span, "ai.telemetry.metadata.
|
|
287
|
+
stringAttribute(span, "ai.telemetry.metadata.chatId") ?? "",
|
|
288
288
|
stringAttribute(span, "ai.model.id") ?? "",
|
|
289
289
|
stringAttribute(span, "ai.model.provider") ?? "",
|
|
290
290
|
stringAttribute(span, "ai.response.finishReason") ?? ""
|
|
@@ -305,15 +305,15 @@ function handleAnalyticsSpan(span, analytics) {
|
|
|
305
305
|
if (span.name === "ai.toolCall") {
|
|
306
306
|
const toolName = stringAttribute(span, "ai.toolCall.name");
|
|
307
307
|
const toolInput = parseJson(stringAttribute(span, "ai.toolCall.args"));
|
|
308
|
-
const
|
|
309
|
-
const skillName = extractSkillName(toolName, toolInput) ??
|
|
308
|
+
const chatId = stringAttribute(span, "ai.telemetry.metadata.chatId") ?? "";
|
|
309
|
+
const skillName = extractSkillName(toolName, toolInput) ?? currentSkillByChat.get(chatId) ?? "";
|
|
310
310
|
const success = span.status.code === 0;
|
|
311
311
|
writeAnalyticsDatapoint(analytics, {
|
|
312
312
|
indexes: [stringAttribute(span, "ai.telemetry.metadata.userId") ?? ""],
|
|
313
313
|
blobs: [
|
|
314
314
|
"tool_call",
|
|
315
315
|
stringAttribute(span, "ai.telemetry.metadata.agentName") ?? "",
|
|
316
|
-
|
|
316
|
+
chatId,
|
|
317
317
|
toolName ?? "",
|
|
318
318
|
skillName,
|
|
319
319
|
success ? "success" : "error"
|
|
@@ -346,8 +346,8 @@ var AgentSpanExporter = class {
|
|
|
346
346
|
(async () => {
|
|
347
347
|
try {
|
|
348
348
|
for (const span of spans) if (span.name === "ai.streamText.doStream") {
|
|
349
|
-
rememberDoStream(span, this.context.
|
|
350
|
-
|
|
349
|
+
rememberDoStream(span, this.context.chatId);
|
|
350
|
+
attachToolCallsToChat(span, this.context.chatId);
|
|
351
351
|
handleAnalyticsSpan(span, this.analytics);
|
|
352
352
|
} else if (span.name === "ai.streamText") await handleAuditSpan(span, this.auditLogs, this.context);
|
|
353
353
|
else if (span.name === "ai.toolCall") {
|
package/dist/v2.d.mts
CHANGED
|
@@ -132,21 +132,21 @@ declare abstract class ChatAgent<RequestContext extends Record<string, unknown>
|
|
|
132
132
|
*/
|
|
133
133
|
rateMessage(messageId: string, rating: number, comment?: string): Promise<void>;
|
|
134
134
|
/**
|
|
135
|
-
* Returns all message ratings for the current
|
|
136
|
-
* @returns All message ratings for the current
|
|
135
|
+
* Returns all message ratings for the current chat.
|
|
136
|
+
* @returns All message ratings for the current chat.
|
|
137
137
|
*/
|
|
138
138
|
getMessageRatings(): Promise<any>;
|
|
139
139
|
}
|
|
140
140
|
//#endregion
|
|
141
|
-
//#region src/server/v2/features/
|
|
142
|
-
type
|
|
141
|
+
//#region src/server/v2/features/chats.d.ts
|
|
142
|
+
type Chat = {
|
|
143
143
|
durable_object_name: string;
|
|
144
144
|
title?: string;
|
|
145
145
|
summary?: string;
|
|
146
146
|
created_at: number;
|
|
147
147
|
updated_at: number;
|
|
148
148
|
};
|
|
149
|
-
declare const
|
|
149
|
+
declare const DELETE_CHAT_CALLBACK: "deleteChatCallback";
|
|
150
150
|
//#endregion
|
|
151
151
|
//#region src/server/v2/agents/Assistant.d.ts
|
|
152
152
|
declare abstract class Assistant extends Agent$1<Cloudflare.Env, AgentConnectionState> {
|
|
@@ -156,12 +156,12 @@ declare abstract class Assistant extends Agent$1<Cloudflare.Env, AgentConnection
|
|
|
156
156
|
onStart(): void;
|
|
157
157
|
onClose(): Promise<void>;
|
|
158
158
|
onConnect(): Promise<void>;
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
private [
|
|
164
|
-
private
|
|
159
|
+
createChat(): Promise<string>;
|
|
160
|
+
deleteChat(id: string): Promise<void>;
|
|
161
|
+
getChats(): Promise<Chat[]>;
|
|
162
|
+
recordChatTurn(durableObjectName: string, messages: UIMessage[]): Promise<void>;
|
|
163
|
+
private [DELETE_CHAT_CALLBACK];
|
|
164
|
+
private scheduleChatForAutoDeletion;
|
|
165
165
|
}
|
|
166
166
|
//#endregion
|
|
167
167
|
export { Agent, type AgentConnectionState, type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, Assistant, ChatAgent, type Skill, type Tool, type ToolContext, type ToolSet, getCurrentToolContext, skill, tool };
|
package/dist/v2.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as extractTokenFromConnectRequest, r as verifyJwt, t as createAgentTracer } from "./telemetry-
|
|
1
|
+
import { n as extractTokenFromConnectRequest, r as verifyJwt, t as createAgentTracer } from "./telemetry-BKgBMVF0.mjs";
|
|
2
2
|
import { Output, convertToModelMessages, generateText, jsonSchema, pruneMessages, tool as tool$1 } from "ai";
|
|
3
3
|
import { Agent as Agent$1, callable, getCurrentAgent } from "agents";
|
|
4
4
|
import { Think } from "@cloudflare/think";
|
|
@@ -185,7 +185,7 @@ var Agent = class extends Think {
|
|
|
185
185
|
isEnabled: true,
|
|
186
186
|
tracer: createAgentTracer(this.env.AGENTS_AUDIT_LOGS, this.env.AGENTS_ANALYTICS, {
|
|
187
187
|
agentName: this.constructor.name,
|
|
188
|
-
|
|
188
|
+
chatId: this.name,
|
|
189
189
|
userId: this.getUserIdFromDurableObjectName(),
|
|
190
190
|
clientIp: this.clientIp,
|
|
191
191
|
forwardedFor: this.forwardedFor
|
|
@@ -193,7 +193,7 @@ var Agent = class extends Think {
|
|
|
193
193
|
metadata: {
|
|
194
194
|
agentName: this.constructor.name,
|
|
195
195
|
version: "v2",
|
|
196
|
-
|
|
196
|
+
chatId: this.name,
|
|
197
197
|
userId: this.getUserIdFromDurableObjectName()
|
|
198
198
|
}
|
|
199
199
|
}
|
|
@@ -277,14 +277,14 @@ var Agent = class extends Think {
|
|
|
277
277
|
_userContext;
|
|
278
278
|
};
|
|
279
279
|
//#endregion
|
|
280
|
-
//#region src/server/v2/features/
|
|
280
|
+
//#region src/server/v2/features/chats.ts
|
|
281
281
|
/**
|
|
282
|
-
* Ensures that the
|
|
282
|
+
* Ensures that the chats table exists.
|
|
283
283
|
* @param sql - The SQL function to use to execute the query.
|
|
284
284
|
*/
|
|
285
|
-
function
|
|
285
|
+
function ensureChatsTableExists(sql) {
|
|
286
286
|
try {
|
|
287
|
-
sql`CREATE TABLE IF NOT EXISTS
|
|
287
|
+
sql`CREATE TABLE IF NOT EXISTS chats (
|
|
288
288
|
durable_object_name TEXT NOT NULL,
|
|
289
289
|
title TEXT,
|
|
290
290
|
summary TEXT,
|
|
@@ -293,80 +293,80 @@ function ensureConversationsTableExists(sql) {
|
|
|
293
293
|
PRIMARY KEY (durable_object_name)
|
|
294
294
|
)`;
|
|
295
295
|
} catch (error) {
|
|
296
|
-
console.error("[Agent] Failed to create
|
|
296
|
+
console.error("[Agent] Failed to create chats table", error);
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
|
-
function
|
|
300
|
-
sql`INSERT INTO
|
|
299
|
+
function registerChat(sql, durableObjectName, dateTime) {
|
|
300
|
+
sql`INSERT INTO chats (durable_object_name, created_at, updated_at)
|
|
301
301
|
VALUES (${durableObjectName}, ${dateTime}, ${dateTime})`;
|
|
302
302
|
}
|
|
303
|
-
function
|
|
304
|
-
sql`DELETE FROM
|
|
303
|
+
function deleteChat(sql, durableObjectName) {
|
|
304
|
+
sql`DELETE FROM chats WHERE durable_object_name = ${durableObjectName}`;
|
|
305
305
|
}
|
|
306
|
-
function
|
|
307
|
-
return sql`SELECT * FROM
|
|
306
|
+
function getChat(sql, durableObjectName) {
|
|
307
|
+
return sql`SELECT * FROM chats WHERE durable_object_name = ${durableObjectName}`[0] ?? null;
|
|
308
308
|
}
|
|
309
|
-
async function
|
|
310
|
-
return sql`SELECT * FROM
|
|
309
|
+
async function getChats(sql) {
|
|
310
|
+
return sql`SELECT * FROM chats ORDER BY updated_at DESC`;
|
|
311
311
|
}
|
|
312
|
-
function
|
|
313
|
-
return schedules.filter((schedule) => schedule.callback ===
|
|
312
|
+
function getDeleteChatScheduleIds(schedules) {
|
|
313
|
+
return schedules.filter((schedule) => schedule.callback === DELETE_CHAT_CALLBACK).map((schedule) => schedule.id);
|
|
314
314
|
}
|
|
315
315
|
/**
|
|
316
316
|
* Number of recent messages passed to `generateSummary` for rolling
|
|
317
317
|
* summarization. Keeping this bounded prevents the prompt growing
|
|
318
|
-
* unboundedly regardless of
|
|
318
|
+
* unboundedly regardless of chat length.
|
|
319
319
|
*/
|
|
320
|
-
const
|
|
321
|
-
async function
|
|
322
|
-
const
|
|
323
|
-
if (!(!
|
|
320
|
+
const CHAT_RECENT_MESSAGES_COUNT = 20;
|
|
321
|
+
async function summariseChatWithAI(sql, durableObjectName, messages, model) {
|
|
322
|
+
const chat = getChat(sql, durableObjectName);
|
|
323
|
+
if (!(!chat || !chat.title || messages.length % CHAT_RECENT_MESSAGES_COUNT === 0)) return;
|
|
324
324
|
let systemPrompt = `
|
|
325
|
-
You are a helpful assistant that summarises
|
|
326
|
-
You will be given a list of messages and you need to generate a title and summary for the
|
|
327
|
-
The title should be a short title for the
|
|
328
|
-
The summary should be a short 1-2 sentence summary of the
|
|
329
|
-
The summary should reflect the direction of the
|
|
330
|
-
if (
|
|
325
|
+
You are a helpful assistant that summarises chats.
|
|
326
|
+
You will be given a list of messages and you need to generate a title and summary for the chat.
|
|
327
|
+
The title should be a short title for the chat, max 8-10 words.
|
|
328
|
+
The summary should be a short 1-2 sentence summary of the chat.
|
|
329
|
+
The summary should reflect the direction of the chat.`;
|
|
330
|
+
if (chat) systemPrompt += `${systemPrompt}\n\nThe previous summary: ${chat.summary}`;
|
|
331
331
|
try {
|
|
332
332
|
const { output: { title, summary } } = await generateText({
|
|
333
333
|
model,
|
|
334
334
|
system: systemPrompt,
|
|
335
|
-
messages: await convertToModelMessages(messages.slice(-
|
|
335
|
+
messages: await convertToModelMessages(messages.slice(-CHAT_RECENT_MESSAGES_COUNT)),
|
|
336
336
|
output: Output.object({ schema: jsonSchema({
|
|
337
337
|
type: "object",
|
|
338
338
|
properties: {
|
|
339
339
|
title: {
|
|
340
340
|
type: "string",
|
|
341
|
-
description: "Short title for the
|
|
341
|
+
description: "Short title for the chat, max 8-10 words"
|
|
342
342
|
},
|
|
343
343
|
summary: {
|
|
344
344
|
type: "string",
|
|
345
|
-
description: "A short 1-2 sentence summary of the
|
|
345
|
+
description: "A short 1-2 sentence summary of the chat. If the chat direction has changed from the previous summary, reflect the new direction."
|
|
346
346
|
}
|
|
347
347
|
},
|
|
348
348
|
required: ["title", "summary"]
|
|
349
349
|
}) })
|
|
350
350
|
});
|
|
351
351
|
if (!title || !summary) {
|
|
352
|
-
console.error("[Assistant] Failed to generate
|
|
352
|
+
console.error("[Assistant] Failed to generate chat title and summary", { durableObjectName });
|
|
353
353
|
return;
|
|
354
354
|
}
|
|
355
|
-
sql`UPDATE
|
|
355
|
+
sql`UPDATE chats
|
|
356
356
|
SET title = ${title},
|
|
357
357
|
summary = ${summary},
|
|
358
358
|
updated_at = ${Date.now()}
|
|
359
359
|
WHERE durable_object_name = ${durableObjectName}`;
|
|
360
|
-
console.info("[Assistant] Generated
|
|
360
|
+
console.info("[Assistant] Generated chat summary", { durableObjectName });
|
|
361
361
|
} catch (error) {
|
|
362
|
-
console.error("[Assistant] Failed to generate
|
|
362
|
+
console.error("[Assistant] Failed to generate chat title and summary", {
|
|
363
363
|
durableObjectName,
|
|
364
364
|
error
|
|
365
365
|
});
|
|
366
366
|
}
|
|
367
367
|
}
|
|
368
|
-
const
|
|
369
|
-
function
|
|
368
|
+
const DELETE_CHAT_CALLBACK = "deleteChatCallback";
|
|
369
|
+
function getChatRetentionMs(days) {
|
|
370
370
|
if (typeof days !== "number" || !Number.isFinite(days) || days <= 0) return null;
|
|
371
371
|
return Math.floor(days * 24 * 60 * 60 * 1e3);
|
|
372
372
|
}
|
|
@@ -383,7 +383,7 @@ var Assistant = class extends Agent$1 {
|
|
|
383
383
|
status: "connecting",
|
|
384
384
|
subAgentName: this.agent.name
|
|
385
385
|
});
|
|
386
|
-
|
|
386
|
+
ensureChatsTableExists(this.sql.bind(this));
|
|
387
387
|
}
|
|
388
388
|
async onClose() {
|
|
389
389
|
this.setState({
|
|
@@ -399,33 +399,33 @@ var Assistant = class extends Agent$1 {
|
|
|
399
399
|
subAgentName: this.agent.name
|
|
400
400
|
});
|
|
401
401
|
}
|
|
402
|
-
@callable() async
|
|
402
|
+
@callable() async createChat() {
|
|
403
403
|
const id = nanoid();
|
|
404
404
|
const now = Date.now();
|
|
405
405
|
await this.subAgent(this.agent, id);
|
|
406
|
-
|
|
406
|
+
registerChat(this.sql.bind(this), id, now);
|
|
407
407
|
return id;
|
|
408
408
|
}
|
|
409
|
-
@callable() async
|
|
409
|
+
@callable() async deleteChat(id) {
|
|
410
410
|
await this.deleteSubAgent(this.agent, id);
|
|
411
|
-
|
|
411
|
+
deleteChat(this.sql.bind(this), id);
|
|
412
412
|
}
|
|
413
|
-
@callable() async
|
|
414
|
-
return
|
|
413
|
+
@callable() async getChats() {
|
|
414
|
+
return getChats(this.sql.bind(this));
|
|
415
415
|
}
|
|
416
|
-
async
|
|
417
|
-
|
|
418
|
-
this.
|
|
416
|
+
async recordChatTurn(durableObjectName, messages) {
|
|
417
|
+
summariseChatWithAI(this.sql.bind(this), durableObjectName, messages, this.fastModel);
|
|
418
|
+
this.scheduleChatForAutoDeletion(durableObjectName);
|
|
419
419
|
}
|
|
420
|
-
async [
|
|
421
|
-
await this.
|
|
420
|
+
async [DELETE_CHAT_CALLBACK](durableObjectName) {
|
|
421
|
+
await this.deleteChat(durableObjectName);
|
|
422
422
|
}
|
|
423
|
-
async
|
|
424
|
-
const retentionMs =
|
|
423
|
+
async scheduleChatForAutoDeletion(durableObjectName) {
|
|
424
|
+
const retentionMs = getChatRetentionMs(90);
|
|
425
425
|
if (retentionMs === null) return;
|
|
426
|
-
const scheduleIds =
|
|
426
|
+
const scheduleIds = getDeleteChatScheduleIds(await this.listSchedules());
|
|
427
427
|
await Promise.all(scheduleIds.map((scheduleId) => this.cancelSchedule(scheduleId)));
|
|
428
|
-
await this.schedule(new Date(Date.now() + retentionMs),
|
|
428
|
+
await this.schedule(new Date(Date.now() + retentionMs), DELETE_CHAT_CALLBACK, durableObjectName, { idempotent: true });
|
|
429
429
|
}
|
|
430
430
|
};
|
|
431
431
|
//#endregion
|
|
@@ -507,7 +507,7 @@ var ChatAgent = class extends Agent {
|
|
|
507
507
|
}
|
|
508
508
|
async onChatResponse(_result) {
|
|
509
509
|
const parent = await this.getParentAgent();
|
|
510
|
-
if (parent?.
|
|
510
|
+
if (parent?.recordChatTurn) await parent.recordChatTurn(this.name, this.messages);
|
|
511
511
|
}
|
|
512
512
|
/**
|
|
513
513
|
* Rate a message by its id.
|
|
@@ -519,10 +519,10 @@ var ChatAgent = class extends Agent {
|
|
|
519
519
|
return rateMessage(this.sql.bind(this), messageId, this.name, rating, comment);
|
|
520
520
|
}
|
|
521
521
|
/**
|
|
522
|
-
* Returns all message ratings for the current
|
|
523
|
-
* @returns All message ratings for the current
|
|
522
|
+
* Returns all message ratings for the current chat.
|
|
523
|
+
* @returns All message ratings for the current chat.
|
|
524
524
|
*/
|
|
525
|
-
@callable({ description: "Returns all message ratings for the current
|
|
525
|
+
@callable({ description: "Returns all message ratings for the current chat" }) async getMessageRatings() {
|
|
526
526
|
return getMessageRatings(this.sql.bind(this), this.name);
|
|
527
527
|
}
|
|
528
528
|
};
|