Spaces:
Running
Running
File size: 11,343 Bytes
612f16b 7bf1507 612f16b cb5990d 5ad620b 612f16b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 cb5990d 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b cb5990d 5ad620b 7bf1507 5ad620b 7bf1507 5ad620b 7bf1507 cb5990d 5ad620b 7bf1507 612f16b 7bf1507 612f16b 7bf1507 399bebf 7bf1507 2d7325b 7bf1507 399bebf 7bf1507 399bebf 7bf1507 399bebf 7bf1507 106688c 7bf1507 106688c 7bf1507 106688c 7bf1507 106688c cb5990d 7bf1507 612f16b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
import { Elysia, error, t } from "elysia";
import { authPlugin } from "$api/authPlugin";
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { authCondition } from "$lib/server/auth";
import { validModelIdSchema } from "$lib/server/models";
import { convertLegacyConversation } from "$lib/utils/tree/convertLegacyConversation";
import type { Conversation } from "$lib/types/Conversation";
import type { MetacognitiveEvent } from "$lib/types/Message";
import { logger } from "$lib/server/logger";
import { getMetacognitiveConfig, selectRandomFrequency } from "$lib/server/metacognitiveConfig";
import { CONV_NUM_PER_PAGE } from "$lib/constants/pagination";
export const conversationGroup = new Elysia().use(authPlugin).group("/conversations", (app) => {
return (
app
.guard({
as: "scoped",
beforeHandle: async ({ locals }) => {
if (!locals.user?._id && !locals.sessionId) {
return error(401, "Must have a valid session or user");
}
},
})
.get(
"",
async ({ locals, query }) => {
const convs = await collections.conversations
.find(authCondition(locals))
.project<Pick<Conversation, "_id" | "title" | "updatedAt" | "model">>({
title: 1,
updatedAt: 1,
model: 1,
})
.sort({ updatedAt: -1 })
.skip((query.p ?? 0) * CONV_NUM_PER_PAGE)
.limit(CONV_NUM_PER_PAGE)
.toArray();
const nConversations = await collections.conversations.countDocuments(
authCondition(locals)
);
const res = convs.map((conv) => ({
_id: conv._id,
id: conv._id, // legacy param iOS
title: conv.title,
updatedAt: conv.updatedAt,
model: conv.model,
modelId: conv.model, // legacy param iOS
}));
return { conversations: res, nConversations };
},
{
query: t.Object({
p: t.Optional(t.Number()),
}),
}
)
.delete("", async ({ locals }) => {
const res = await collections.conversations.deleteMany({
...authCondition(locals),
});
return res.deletedCount;
})
// search endpoint removed
.group(
"/:id",
{
params: t.Object({
id: t.String(),
}),
},
(app) => {
return app
.derive(async ({ locals, params }) => {
let conversation;
let shared = false;
const metacognitiveConfig = getMetacognitiveConfig();
// if the conver
if (params.id.length === 7) {
// shared link of length 7
conversation = await collections.sharedConversations.findOne({
_id: params.id,
});
shared = true;
if (!conversation) {
throw new Error("Conversation not found");
}
} else {
// todo: add validation on params.id
try {
new ObjectId(params.id);
} catch {
throw new Error("Invalid conversation ID format");
}
conversation = await collections.conversations.findOne({
_id: new ObjectId(params.id),
...authCondition(locals),
});
if (!conversation) {
const conversationExists =
(await collections.conversations.countDocuments({
_id: new ObjectId(params.id),
})) !== 0;
if (conversationExists) {
throw new Error(
"You don't have access to this conversation. If someone gave you this link, ask them to use the 'share' feature instead."
);
}
throw new Error("Conversation not found.");
}
// Initialize metacognitiveState server-side so targetFrequency is consistent across refresh/devices.
if (metacognitiveConfig.enabled) {
const existingTarget = conversation.metacognitiveState?.targetFrequency;
if (!existingTarget) {
const metacognitiveState = {
targetFrequency: selectRandomFrequency(),
lastPromptedAtMessageId: null,
updatedAt: new Date(),
};
await collections.conversations.updateOne(
{ _id: new ObjectId(params.id), ...authCondition(locals) },
{ $set: { metacognitiveState } }
);
conversation.metacognitiveState = metacognitiveState;
}
}
}
const convertedConv = {
...conversation,
...convertLegacyConversation(conversation),
shared,
};
return { conversation: convertedConv };
})
.get("", async ({ conversation }) => {
return {
messages: conversation.messages,
title: conversation.title,
model: conversation.model,
preprompt: conversation.preprompt,
rootMessageId: conversation.rootMessageId,
id: conversation._id.toString(),
updatedAt: conversation.updatedAt,
modelId: conversation.model,
shared: conversation.shared,
metacognitiveState: (conversation as Conversation).metacognitiveState,
};
})
.post("", () => {
// todo: post new message
throw new Error("Not implemented");
})
.delete("", async ({ locals, params }) => {
const res = await collections.conversations.deleteOne({
_id: new ObjectId(params.id),
...authCondition(locals),
});
if (res.deletedCount === 0) {
throw new Error("Conversation not found");
}
return { success: true };
})
.get("/output/:sha256", () => {
// todo: get output
throw new Error("Not implemented");
})
.post("/share", () => {
// todo: share conversation
throw new Error("Not implemented");
})
.post("/stop-generating", () => {
// todo: stop generating
throw new Error("Not implemented");
})
.patch(
"",
async ({ locals, params, body }) => {
if (body.model) {
if (!validModelIdSchema.safeParse(body.model).success) {
throw new Error("Invalid model ID");
}
}
// Only include defined values in the update (sanitize title)
const updateValues = {
...(body.title !== undefined && {
title: body.title.replace(/<\/?think>/gi, "").trim(),
}),
...(body.model !== undefined && { model: body.model }),
};
const res = await collections.conversations.updateOne(
{
_id: new ObjectId(params.id),
...authCondition(locals),
},
{
$set: updateValues,
}
);
if (res.modifiedCount === 0) {
throw new Error("Conversation not found");
}
return { success: true };
},
{
body: t.Object({
title: t.Optional(
t.String({
minLength: 1,
maxLength: 100,
})
),
model: t.Optional(t.String()),
}),
}
)
.delete(
"/message/:messageId",
async ({ locals, params, conversation }) => {
if (!conversation.messages.map((m) => m.id).includes(params.messageId)) {
throw new Error("Message not found");
}
const filteredMessages = conversation.messages
.filter(
(message) =>
// not the message AND the message is not in ancestors
!(message.id === params.messageId) &&
message.ancestors &&
!message.ancestors.includes(params.messageId)
)
.map((message) => {
// remove the message from children if it's there
if (message.children && message.children.includes(params.messageId)) {
message.children = message.children.filter(
(child) => child !== params.messageId
);
}
return message;
});
const res = await collections.conversations.updateOne(
{ _id: new ObjectId(conversation._id), ...authCondition(locals) },
{ $set: { messages: filteredMessages } }
);
if (res.modifiedCount === 0) {
throw new Error("Deleting message failed");
}
return { success: true };
},
{
params: t.Object({
id: t.String(),
messageId: t.String(),
}),
}
)
.post(
"/message/:messageId/metacognitive-event",
async ({ locals, params, body, conversation }) => {
// Find the message in the conversation
const messageIndex = conversation.messages.findIndex(
(m) => m.id === params.messageId
);
if (messageIndex === -1) {
throw new Error("Message not found");
}
// Create the metacognitive event
const event: MetacognitiveEvent = {
type: body.type as "comprehension" | "perspective",
promptText: body.promptText,
triggerFrequency: body.triggerFrequency,
timestamp: new Date(),
suggestedPersonaId: body.suggestedPersonaId,
suggestedPersonaName: body.suggestedPersonaName,
accepted: body.accepted,
};
// Log the event for research tracking
logger.info(
{
conversationId: params.id,
messageId: params.messageId,
eventType: event.type,
triggerFrequency: event.triggerFrequency,
accepted: event.accepted,
suggestedPersonaId: event.suggestedPersonaId,
},
"Metacognitive prompt event"
);
// Update the message with the new event
const updatePath = `messages.${messageIndex}.metacognitiveEvents`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateDoc: Record<string, any> = {
$push: { [updatePath]: event },
};
// If this is a shown event, persist metacognitive state so
// targetFrequency stays consistent across refresh/devices and the counter can reset.
let nextTargetFrequency: number | undefined;
if (body.accepted === false) {
const metacognitiveConfig = getMetacognitiveConfig();
if (metacognitiveConfig.enabled) {
nextTargetFrequency = selectRandomFrequency();
updateDoc.$set = {
"metacognitiveState.lastPromptedAtMessageId": params.messageId,
"metacognitiveState.targetFrequency": nextTargetFrequency,
"metacognitiveState.updatedAt": new Date(),
};
}
}
const res = await collections.conversations.updateOne(
{
_id: new ObjectId(params.id),
...authCondition(locals),
},
updateDoc
);
if (res.modifiedCount === 0) {
throw new Error("Failed to log metacognitive event");
}
return {
success: true,
event,
nextTargetFrequency,
};
},
{
params: t.Object({
id: t.String(),
messageId: t.String(),
}),
body: t.Object({
type: t.Union([t.Literal("comprehension"), t.Literal("perspective")]),
promptText: t.String(),
triggerFrequency: t.Number(),
suggestedPersonaId: t.Optional(t.String()),
suggestedPersonaName: t.Optional(t.String()),
accepted: t.Boolean(),
}),
}
);
}
)
);
});
|