🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(userMemories): added memory layer activity (#11747)
Neko2021b1c83b3e
diff --git a/packages/const/src/userMemory.ts b/packages/const/src/userMemory.tsindex 268ba422a65..3effae17ef2 100644--- a/packages/const/src/userMemory.ts+++ b/packages/const/src/userMemory.ts@@ -3,6 +3,7 @@ import { DEFAULT_EMBEDDING_PROVIDER } from '@lobechat/business-const';import { DEFAULT_EMBEDDING_MODEL } from './settings';export const DEFAULT_SEARCH_USER_MEMORY_TOP_K = {+ activities: 3,contexts: 0,experiences: 0,preferences: 3,diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.tsindex d2eb2afae1a..ec5c536bdef 100644--- a/packages/database/src/models/userMemory/model.ts+++ b/packages/database/src/models/userMemory/model.ts@@ -1,5 +1,6 @@import { AssociatedObjectSchema } from '@lobechat/memory-user-memory';import {+ ActivityTypeEnum,IdentityTypeEnum,LayersEnum,MemorySourceType,@@ -40,7 +41,10 @@ import {UserMemoryIdentity,UserMemoryItem,UserMemoryPreference,+ UserMemoryActivitiesWithoutVectors,+ UserMemoryActivity,userMemories,+ userMemoriesActivities,userMemoriesContexts,userMemoriesExperiences,userMemoriesIdentities,@@ -104,6 +108,16 @@ export interface CreateUserMemoryContextParams extends BaseCreateUserMemoryParam>;}+export interface CreateUserMemoryActivityParams extends BaseCreateUserMemoryParams {+ activity: Optional<+ Omit<+ UserMemoryActivity,+ 'id' | 'userId' | 'createdAt' | 'updatedAt' | 'accessedAt' | 'userMemoryId'+ >,+ 'capturedAt'+ >;+}+export interface CreateUserMemoryExperienceParams extends BaseCreateUserMemoryParams {experience: Optional<Omit<@@ -135,6 +149,7 @@ export interface CreateUserMemoryPreferenceParams extends BaseCreateUserMemoryPa}export type CreateUserMemoryParams =+ | CreateUserMemoryActivityParams| CreateUserMemoryContextParams| CreateUserMemoryExperienceParams| CreateUserMemoryIdentityParams@@ -143,7 +158,7 @@ export type CreateUserMemoryParams =export interface SearchUserMemoryParams {embedding?: number[];limit?: number;- limits?: Partial<Record<'contexts' | 'experiences' | 'preferences', number>>;+ limits?: Partial<Record<'activities' | 'contexts' | 'experiences' | 'preferences', number>>;memoryCategory?: string;memoryType?: string;query?: string;@@ -151,12 +166,13 @@ export interface SearchUserMemoryParams {export interface SearchUserMemoryWithEmbeddingParams {embedding?: number[];- limits?: Partial<Record<'contexts' | 'experiences' | 'preferences', number>>;+ limits?: Partial<Record<'activities' | 'contexts' | 'experiences' | 'preferences', number>>;memoryCategory?: string;memoryType?: string;}export interface UserMemorySearchAggregatedResult {+ activities: UserMemoryActivitiesWithoutVectors[];contexts: UserMemoryContextWithoutVectors[];experiences: UserMemoryExperienceWithoutVectors[];preferences: UserMemoryPreferenceWithoutVectors[];@@ -380,12 +396,67 @@ export class UserMemoryModel {const extra = JSON.parse(parsed.data.extra || '{}');parsed.data.extra = extra;associations.push(parsed.data);+ return;+ }++ if (+ item &&+ typeof item === 'object' &&+ 'name' in item &&+ typeof (item as any).name === 'string'+ ) {+ associations.push({ name: (item as any).name });}});return associations.length > 0 ? associations : [];}+ static parseAssociatedLocations(+ value?:+ | {+ address?: unknown;+ name?: unknown;+ tags?: unknown;+ type?: unknown;+ }[]+ | Record<string, unknown>,+ ) {+ if (!value) return [];++ const raw = Array.isArray(value) ? value : [value];+ const locations: {+ address?: string;+ name?: string;+ tags?: string[];+ type?: string;+ }[] = [];++ raw.forEach((item) => {+ if (!item || typeof item !== 'object') return;++ const address = typeof (item as any).address === 'string' ? (item as any).address : undefined;+ const name = typeof (item as any).name === 'string' ? (item as any).name : undefined;+ const type = typeof (item as any).type === 'string' ? (item as any).type : undefined;+ const tagsRaw = (item as any).tags;+ const tags =+ Array.isArray(tagsRaw) && tagsRaw.every((tag) => typeof tag === 'string')+ ? (tagsRaw as string[])+ : undefined;++ if (address || name || type || tags) {+ locations.push({+ address,+ name,+ tags,+ type,+ });+ }+ });++ return locations;+ }+static parseDateFromString(value?: string | Date | null): Date | null {if (!value) return null;if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;@@ -537,6 +608,46 @@ export class UserMemoryModel {});};+ createActivityMemory = async (+ params: CreateUserMemoryActivityParams,+ ): Promise<{ activity: UserMemoryActivity; memory: UserMemoryItem }> => {+ return this.db.transaction(async (tx) => {+ const baseValues = this.buildBaseMemoryInsertValues(params, {+ metadata: params.activity.metadata ?? null,+ status: params.activity.status ?? 'pending',+ tags: params.activity.tags ?? null,+ });++ const [memory] = await tx.insert(userMemories).values(baseValues).returning();+ if (!memory) throw new Error('Failed to create user memory activity');++ const activityValues = {+ associatedLocations: params.activity.associatedLocations ?? null,+ associatedObjects: params.activity.associatedObjects ?? [],+ associatedSubjects: params.activity.associatedSubjects ?? [],+ capturedAt: params.activity.capturedAt,+ endsAt: coerceDate(params.activity.endsAt),+ feedback: params.activity.feedback ?? null,+ feedbackVector: params.activity.feedbackVector ?? null,+ metadata: params.activity.metadata ?? null,+ narrative: params.activity.narrative ?? null,+ narrativeVector: params.activity.narrativeVector ?? null,+ notes: params.activity.notes ?? null,+ startsAt: coerceDate(params.activity.startsAt),+ status: params.activity.status ?? null,+ tags: params.activity.tags ?? [],+ timezone: params.activity.timezone ?? null,+ type: params.activity.type ?? ActivityTypeEnum.Other,+ userId: this.userId,+ userMemoryId: memory.id,+ } satisfies typeof userMemoriesActivities.$inferInsert;++ const [activity] = await tx.insert(userMemoriesActivities).values(activityValues).returning();++ return { activity, memory };+ });+ };+createPreferenceMemory = async (params: CreateUserMemoryPreferenceParams,): Promise<{ memory: UserMemoryItem; preference: UserMemoryPreference }> => {@@ -575,12 +686,13 @@ export class UserMemoryModel {const { embedding, limits } = params;const resolvedLimits = {+ activities: limits?.activities,contexts: limits?.contexts,experiences: limits?.experiences,preferences: limits?.preferences,};- const [experiences, contexts, preferences] = await Promise.all([+ const [experiences, contexts, preferences, activities] = await Promise.all([this.searchExperiences({embedding,limit: resolvedLimits.experiences,@@ -593,6 +705,10 @@ export class UserMemoryModel {embedding,limit: resolvedLimits.preferences,}),+ this.searchActivities({+ embedding,+ limit: resolvedLimits.activities,+ }),]);const accessedMemoryIds = new Set<string>();@@ -602,6 +718,9 @@ export class UserMemoryModel {preferences.forEach((preference) => {if (preference.userMemoryId) accessedMemoryIds.add(preference.userMemoryId);});+ activities.forEach((activity) => {+ if (activity.userMemoryId) accessedMemoryIds.add(activity.userMemoryId);+ });const contextLinkIds: string[] = [];contexts.forEach((context) => {const ids = Array.isArray(context.userMemoryIds) ? (context.userMemoryIds as string[]) : [];@@ -617,6 +736,7 @@ export class UserMemoryModel {}return {+ activities,contexts,experiences,preferences,@@ -1795,6 +1915,61 @@ export class UserMemoryModel {await this.db.delete(userMemories).where(eq(userMemories.userId, this.userId));};+ searchActivities = async (params: {+ embedding?: number[];+ limit?: number;+ type?: string;+ }): Promise<UserMemoryActivitiesWithoutVectors[]> => {+ const { embedding, limit = 5, type } = params;+ if (limit <= 0) {+ return [];+ }++ let query = this.db+ .select({+ accessedAt: userMemoriesActivities.accessedAt,+ associatedLocations: userMemoriesActivities.associatedLocations,+ associatedObjects: userMemoriesActivities.associatedObjects,+ associatedSubjects: userMemoriesActivities.associatedSubjects,+ capturedAt: userMemoriesActivities.capturedAt,+ createdAt: userMemoriesActivities.createdAt,+ endsAt: userMemoriesActivities.endsAt,+ feedback: userMemoriesActivities.feedback,+ id: userMemoriesActivities.id,+ metadata: userMemoriesActivities.metadata,+ narrative: userMemoriesActivities.narrative,+ notes: userMemoriesActivities.notes,+ startsAt: userMemoriesActivities.startsAt,+ status: userMemoriesActivities.status,+ tags: userMemoriesActivities.tags,+ timezone: userMemoriesActivities.timezone,+ type: userMemoriesActivities.type,+ updatedAt: userMemoriesActivities.updatedAt,+ userId: userMemoriesActivities.userId,+ userMemoryId: userMemoriesActivities.userMemoryId,+ ...(embedding && {+ similarity: sql<number>`1 - (${cosineDistance(userMemoriesActivities.narrativeVector, embedding)}) AS similarity`,+ }),+ })+ .from(userMemoriesActivities)+ .$dynamic();++ const conditions = [eq(userMemoriesActivities.userId, this.userId)];+ if (type) {+ conditions.push(eq(userMemoriesActivities.type, type));+ }++ query = query.where(and(...conditions));++ if (embedding) {+ query = query.orderBy(desc(sql`similarity`));+ } else {+ query = query.orderBy(desc(userMemoriesActivities.createdAt));+ }++ return query.limit(limit) as Promise<UserMemoryActivitiesWithoutVectors[]>;+ };+searchContexts = async (params: {embedding?: number[];limit?: number;diff --git a/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts b/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.tsindex e31200ab198..81eddb6ddc2 100644--- a/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts+++ b/packages/database/src/models/userMemory/sources/benchmarkLoCoMo.ts@@ -63,7 +63,7 @@ export class UserMemorySourceBenchmarkLoCoMoModel {return { id };}- async replaceParts(sourceId: string, parts: BenchmarkLoCoMoPart[]) {+ replaceParts(sourceId: string, parts: BenchmarkLoCoMoPart[]) {const store = this.getPartStore();store.delete(sourceId);if (!parts.length) return;diff --git a/packages/memory-user-memory/package.json b/packages/memory-user-memory/package.jsonindex cd6a800efd3..210ebc8f7df 100644--- a/packages/memory-user-memory/package.json+++ b/packages/memory-user-memory/package.json@@ -20,8 +20,8 @@"@lobechat/context-engine": "workspace:*","@lobechat/model-runtime": "workspace:*","@lobechat/prompts": "workspace:*",- "dotenv": "^17.2.3","dayjs": "^1.11.11",+ "dotenv": "^17.2.3","ora": "^9.0.0","unist-builder": "^4.0.0","xast-util-to-xml": "^4.0.0",@@ -30,6 +30,7 @@},"devDependencies": {"@lobechat/types": "workspace:*",+ "@types/json-schema": "^7.0.15","@types/xast": "^2.0.4","promptfoo": "^0.118.17","tsx": "^4.20.6"diff --git a/packages/memory-user-memory/promptfoo/evals/activity/basic/buildMessages.ts b/packages/memory-user-memory/promptfoo/evals/activity/basic/buildMessages.tsnew file mode 100644index 00000000000..55e5432c397--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/basic/buildMessages.ts@@ -0,0 +1,40 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import { activityPrompt } from '../../../../src/prompts';+import type { ExtractorTemplateProps } from '../../../../src/types';++export interface PromptVars extends ExtractorTemplateProps {+ conversation: string;+}++export const buildActivityMessages = (vars: PromptVars) => {+ const retrievedContext =+ Array.isArray(vars.retrievedContexts) && vars.retrievedContexts.length > 0+ ? vars.retrievedContexts.join('\n\n')+ : typeof vars.retrievedContexts === 'string'+ ? vars.retrievedContexts+ : 'No similar memories retrieved.';++ const rendered = renderPlaceholderTemplate(activityPrompt, {+ availableCategories: vars.availableCategories,+ language: vars.language || 'English',+ retrievedContext,+ sessionDate: vars.sessionDate || new Date().toISOString(),+ topK: vars.topK ?? 5,+ username: vars.username || 'User',+ });++ const messages = [+ { content: rendered, role: 'system' as const },+ { content: rendered, role: 'user' as const },+ ];++ if (vars.conversation) {+ messages.push({+ content: `Conversation:\n${vars.conversation}`,+ role: 'user' as const,+ });+ }++ return messages;+};diff --git a/packages/memory-user-memory/promptfoo/evals/activity/basic/eval.yaml b/packages/memory-user-memory/promptfoo/evals/activity/basic/eval.yamlnew file mode 100644index 00000000000..dcf0e7da8f0--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/basic/eval.yaml@@ -0,0 +1,13 @@+description: Regression benchmark for activity layer structured extraction++providers:+ - id: openai:chat:gpt-5-mini+ config:+ response_format: file://../../../response-formats/activity.json+ temperature: 0++prompts:+ - file://./prompt.ts++tests:+ - file://./tests/cases.tsdiff --git a/packages/memory-user-memory/promptfoo/evals/activity/basic/prompt.ts b/packages/memory-user-memory/promptfoo/evals/activity/basic/prompt.tsnew file mode 100644index 00000000000..0b343bed3e3--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/basic/prompt.ts@@ -0,0 +1,5 @@+import { buildActivityMessages, PromptVars } from './buildMessages';++export default function generatePrompt({ vars }: { vars: PromptVars }) {+ return buildActivityMessages(vars);+}diff --git a/packages/memory-user-memory/promptfoo/evals/activity/basic/tests/cases.ts b/packages/memory-user-memory/promptfoo/evals/activity/basic/tests/cases.tsnew file mode 100644index 00000000000..f859f1883e9--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/basic/tests/cases.ts@@ -0,0 +1,106 @@+type PromptfooAssert =+ | { type: 'javascript'; value: string }+ | { provider?: string; type: 'llm-rubric'; value: string };++interface PromptfooTestCase {+ assert: PromptfooAssert[];+ description?: string;+ vars: Record<string, unknown>;+}++const baseSchemaAssert: PromptfooAssert = {+ type: 'javascript',+ value: `+ let parsed;+ try {+ parsed = JSON.parse(output);+ } catch (error) {+ console.error('Failed to parse JSON output', error);+ return false;+ }++ if (!parsed || !Array.isArray(parsed.memories)) return false;++ return parsed.memories.every((memory) => {+ return (+ memory.memoryType === 'activity' &&+ memory.title &&+ memory.summary &&+ memory.withActivity?.type &&+ memory.withActivity?.narrative+ );+ });+ `,+};++const baseVars = {+ availableCategories: ['work', 'health', 'personal'],+ language: 'English',+ topK: 5,+ username: 'User',+};++const testCases: PromptfooTestCase[] = [+ {+ assert: [+ baseSchemaAssert,+ {+ type: 'javascript',+ value: `+ const data = JSON.parse(output);+ const first = data.memories?.[0];+ if (!first) return false;++ const activity = first.withActivity || {};+ return Boolean(activity.startsAt && activity.endsAt && activity.timezone && activity.associatedLocations?.[0]?.name);+ `,+ },+ {+ provider: 'openai:gpt-5-mini',+ type: 'llm-rubric',+ value:+ 'Should extract a meeting activity including timing (start/end/timezone), location name ACME HQ, status completed when implied, and feedback reflecting the positive tone.',+ },+ ],+ description: 'Meeting with explicit time and location',+ vars: {+ ...baseVars,+ conversation:+ 'User: I met with Alice at ACME HQ on 2024-05-03 from 14:00-15:00 America/New_York. We reviewed Q2 renewal scope and agreed to send revised pricing next week. I felt positive and collaborative about the call.',+ retrievedContexts: ['Previous similar memory: met with Alice about renewal last month.'],+ sessionDate: '2024-05-03',+ },+ },+ {+ assert: [+ baseSchemaAssert,+ {+ type: 'javascript',+ value: `+ const data = JSON.parse(output);+ const first = data.memories?.[0];+ if (!first) return false;++ const activity = first.withActivity || {};+ return Boolean(activity.narrative && activity.feedback);+ `,+ },+ {+ provider: 'openai:gpt-5-mini',+ type: 'llm-rubric',+ value:+ 'Should capture an exercise activity without inventing exact timestamps or timezones; keep the narrative and feedback about the yoga session at home and omit temporal fields that were not provided.',+ },+ ],+ description: 'Exercise without explicit time or timezone',+ vars: {+ ...baseVars,+ conversation:+ 'User: Over the weekend I did a 30-minute yoga session at home with my roommate. No specific time was set, it was just a casual stretch and it left me feeling calm.',+ retrievedContexts: [],+ sessionDate: '2025-05-05 10:02:00',+ },+ },+];++export default testCases;diff --git a/packages/memory-user-memory/promptfoo/evals/activity/locomo/buildMessages.ts b/packages/memory-user-memory/promptfoo/evals/activity/locomo/buildMessages.tsnew file mode 100644index 00000000000..57b9bd57eb0--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/locomo/buildMessages.ts@@ -0,0 +1,104 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import { MemorySourceType } from '@lobechat/types';+import { readFile } from 'node:fs/promises';+import { isAbsolute, join } from 'node:path';++import { BenchmarkLocomoContextProvider, BenchmarkLocomoPart } from '../../../../src/providers';+import type { IngestPayload } from '../../../../src/converters/locomo';+import { activityPrompt } from '../../../../src/prompts';+import type { ExtractorTemplateProps, MemoryExtractionJob } from '../../../../src/types';++export interface PromptVars extends ExtractorTemplateProps {+ payloadPath: string;+ sessionId?: string;+ userId?: string;+}++const resolvePath = (payloadPath: string) =>+ isAbsolute(payloadPath) ? payloadPath : join(process.cwd(), payloadPath);++const buildParts = (payload: IngestPayload, sessionId?: string): BenchmarkLocomoPart[] => {+ let partIndex = 0;+ const sessions = payload.sessions.filter(+ (session) => !sessionId || session.sessionId === sessionId,+ );++ return sessions.flatMap((session) =>+ session.turns.map((turn) => {+ const metadata = {+ diaId: turn.diaId,+ imageCaption: turn.imageCaption,+ imageUrls: turn.imageUrls,+ sessionId: session.sessionId,+ };++ return {+ content: turn.text,+ createdAt: turn.createdAt || session.timestamp,+ metadata,+ partIndex: partIndex++,+ sessionId: session.sessionId,+ speaker: turn.speaker,+ };+ }),+ );+};++const resolveSessionDate = (payload: IngestPayload, parts: BenchmarkLocomoPart[], sessionId?: string) => {+ const sessionDate =+ payload.sessions.find((session) => session.sessionId === sessionId)?.timestamp ||+ payload.sessions[0]?.timestamp;++ if (sessionDate) return sessionDate;++ const latestCreatedAt = parts+ .map((part) => (part.createdAt ? new Date(part.createdAt) : null))+ .filter(Boolean)+ .sort((a, b) => (a!.getTime() > b!.getTime() ? 1 : -1))+ .at(-1);++ return latestCreatedAt ? latestCreatedAt.toISOString() : new Date().toISOString();+};++export const buildLocomoActivityMessages = async (vars: PromptVars) => {+ const payloadPath = resolvePath(vars.payloadPath);+ const payloadRaw = await readFile(payloadPath, 'utf8');+ const payload = JSON.parse(payloadRaw) as IngestPayload;++ const parts = buildParts(payload, vars.sessionId);+ if (parts.length === 0) {+ throw new Error(`No matching parts found in ${payload.sampleId} for session ${vars.sessionId || 'all'}`);+ }+ const userId = vars.userId || `locomo-user-${payload.sampleId}`;+ const sourceId = payload.topicId || `sample_${payload.sampleId}`;+ const sessionDate = vars.sessionDate || resolveSessionDate(payload, parts, vars.sessionId);++ const provider = new BenchmarkLocomoContextProvider({+ parts,+ sampleId: payload.sampleId,+ sourceId,+ userId,+ });++ const extractionJob: MemoryExtractionJob = {+ source: MemorySourceType.BenchmarkLocomo,+ sourceId,+ userId,+ };++ const { context } = await provider.buildContext(extractionJob);++ const rendered = renderPlaceholderTemplate(activityPrompt, {+ availableCategories: vars.availableCategories,+ language: vars.language || 'English',+ retrievedContext: context || 'No similar memories retrieved.',+ sessionDate,+ topK: vars.topK ?? 5,+ username: vars.username || 'User',+ });++ return [+ { content: rendered, role: 'system' as const },+ { content: rendered, role: 'user' as const },+ ];+};diff --git a/packages/memory-user-memory/promptfoo/evals/activity/locomo/eval.yaml b/packages/memory-user-memory/promptfoo/evals/activity/locomo/eval.yamlnew file mode 100644index 00000000000..f0bdede6f78--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/locomo/eval.yaml@@ -0,0 +1,13 @@+description: LoCoMo regression for activity layer with relative time resolution++providers:+ - id: openai:chat:gpt-5-mini+ config:+ response_format: file://../../../response-formats/activity.json+ temperature: 0++prompts:+ - file://./prompt.ts++tests:+ - file://./tests/cases.tsdiff --git a/packages/memory-user-memory/promptfoo/evals/activity/locomo/prompt.ts b/packages/memory-user-memory/promptfoo/evals/activity/locomo/prompt.tsnew file mode 100644index 00000000000..721b46ddb7c--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/locomo/prompt.ts@@ -0,0 +1,5 @@+import { buildLocomoActivityMessages, PromptVars } from './buildMessages';++export default async function generatePrompt({ vars }: { vars: PromptVars }) {+ return buildLocomoActivityMessages(vars);+}diff --git a/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/benchmark-locomo-payload-conv-26.json b/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/benchmark-locomo-payload-conv-26.jsonnew file mode 100644index 00000000000..a8141f36493--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/benchmark-locomo-payload-conv-26.json@@ -0,0 +1,149 @@+{+ "force": true,+ "layers": [],+ "sampleId": "conv-26",+ "sessions": [+ {+ "sessionId": "session_1",+ "timestamp": "2023-05-08T13:56:00.000Z",+ "turns": [+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:1",+ "role": "user",+ "speaker": "Caroline",+ "text": "Hey Mel! Good to see you! How have you been?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:2",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Hey Caroline! Good to see you! I'm swamped with the kids & work. What's up with you? Anything new?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:3",+ "role": "user",+ "speaker": "Caroline",+ "text": "I went to a LGBTQ support group yesterday and it was so powerful."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:4",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Wow, that's cool, Caroline! What happened that was so awesome? Did you hear any inspiring stories?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:5",+ "imageCaption": "a photo of a dog walking past a wall with a painting of a woman",+ "imageUrls": [+ "https://i.redd.it/l7hozpetnhlb1.jpg"+ ],+ "role": "user",+ "speaker": "Caroline",+ "text": "The transgender stories were so inspiring! I was so happy and thankful for all the support.\n[Image: a photo of a dog walking past a wall with a painting of a woman]"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:6",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Wow, love that painting! So cool you found such a helpful group. What's it done for you?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:7",+ "role": "user",+ "speaker": "Caroline",+ "text": "The support group has made me feel accepted and given me courage to embrace myself."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:8",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "That's really cool. You've got guts. What now?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:9",+ "role": "user",+ "speaker": "Caroline",+ "text": "Gonna continue my edu and check out career options, which is pretty exciting!"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:10",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Wow, Caroline! What kinda jobs are you thinkin' of? Anything that stands out?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:11",+ "role": "user",+ "speaker": "Caroline",+ "text": "I'm keen on counseling or working in mental health - I'd love to support those with similar issues."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:12",+ "imageCaption": "a photo of a painting of a sunset over a lake",+ "imageUrls": [+ "http://candicealexander.com/cdn/shop/products/IMG_7269_a49d5af8-c76c-4ecd-ae20-48c08cb11dec.jpg"+ ],+ "role": "assistant",+ "speaker": "Melanie",+ "text": "You'd be a great counselor! Your empathy and understanding will really help the people you work with. By the way, take a look at this.\n[Image: a photo of a painting of a sunset over a lake]"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:13",+ "role": "user",+ "speaker": "Caroline",+ "text": "Thanks, Melanie! That's really sweet. Is this your own painting?"+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:14",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Yeah, I painted that lake sunrise last year! It's special to me."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:15",+ "role": "user",+ "speaker": "Caroline",+ "text": "Wow, Melanie! The colors really blend nicely. Painting looks like a great outlet for expressing yourself."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:16",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Thanks, Caroline! Painting's a fun way to express my feelings and get creative. It's a great way to relax after a long day."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:17",+ "role": "user",+ "speaker": "Caroline",+ "text": "Totally agree, Mel. Relaxing and expressing ourselves is key. Well, I'm off to go do some research."+ },+ {+ "createdAt": "2023-05-08T13:56:00.000Z",+ "diaId": "D1:18",+ "role": "assistant",+ "speaker": "Melanie",+ "text": "Yep, Caroline. Taking care of ourselves is vital. I'm off to go swimming with the kids. Talk to you soon!"+ }+ ]+ }+ ],+ "source": "benchmark_locomo",+ "topicId": "sample_conv-26"+}diff --git a/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/cases.ts b/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/cases.tsnew file mode 100644index 00000000000..b0fd34e9de7--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/activity/locomo/tests/cases.ts@@ -0,0 +1,72 @@+type PromptfooAssert =+ | { type: 'javascript'; value: string }+ | { provider?: string; type: 'llm-rubric'; value: string };++interface PromptfooTestCase {+ assert: PromptfooAssert[];+ description?: string;+ vars: Record<string, unknown>;+}++const baseSchemaAssert: PromptfooAssert = {+ type: 'javascript',+ value: `+ let parsed;+ try {+ parsed = JSON.parse(output);+ } catch (error) {+ console.error('Failed to parse JSON output', error);+ return false;+ }++ if (!parsed || !Array.isArray(parsed.memories)) return false;++ return parsed.memories.every((memory) => {+ return memory.memoryType === 'activity' && memory.withActivity?.type;+ });+ `,+};++const testCases: PromptfooTestCase[] = [+ {+ assert: [+ baseSchemaAssert,+ {+ type: 'javascript',+ value: `+ const data = JSON.parse(output);+ const target = data.memories?.find((memory) => {+ const text = [memory.title, memory.summary, memory.withActivity?.narrative]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();+ return text.includes('support group');+ });++ if (!target) return false;+ const startsAt = target.withActivity?.startsAt;+ if (!startsAt) return false;++ return String(startsAt).startsWith('2023-05-07');+ `,+ },+ {+ provider: 'openai:gpt-5-mini',+ type: 'llm-rubric',+ value:+ 'Should extract the LGBTQ support group activity from session_1 diaId D1:3, convert "yesterday" relative to the 2023-05-08 session anchor into 2023-05-07, and include a narrative about feeling supported/accepted.',+ },+ ],+ description: 'LoCoMo conv-26 session_1 resolves relative date',+ vars: {+ availableCategories: ['personal'],+ language: 'English',+ payloadPath: './promptfoo/evals/activity/locomo/tests/benchmark-locomo-payload-conv-26.json',+ sessionId: 'session_1',+ topK: 3,+ username: 'Caroline',+ },+ },+];++export default testCases;diff --git a/packages/memory-user-memory/promptfoo/response-formats/activity.json b/packages/memory-user-memory/promptfoo/response-formats/activity.jsonnew file mode 100644index 00000000000..67ff2738882--- /dev/null+++ b/packages/memory-user-memory/promptfoo/response-formats/activity.json@@ -0,0 +1,370 @@+{+ "json_schema": {+ "name": "activity_extraction",+ "schema": {+ "additionalProperties": false,+ "properties": {+ "memories": {+ "description": "Array of extracted activity memories. Use an empty array when no activity should be captured.",+ "items": {+ "additionalProperties": false,+ "description": "Self-contained activity memory describing what happened, when, where, with whom, and how it felt.",+ "examples": [+ {+ "details": "Talked through renewal scope, confirmed timeline flexibility, and captured follow-ups.",+ "memoryCategory": "work",+ "memoryType": "activity",+ "summary": "Client Q2 renewal meeting with Alice (ACME)",+ "tags": [+ "meeting",+ "client",+ "renewal"+ ],+ "title": "ACME Q2 renewal meeting",+ "withActivity": {+ "type": "meeting",+ "associatedLocations": [+ {+ "address": "123 Main St, New York, NY",+ "name": "ACME HQ"+ }+ ],+ "associatedSubjects": [+ {+ "name": "Alice Smith",+ "type": "person"+ }+ ],+ "endsAt": "2024-05-03T15:00:00-04:00",+ "feedback": "Positive momentum; Alice felt heard and open to renewal.",+ "narrative": "Alice and User reviewed Q2 renewal scope, aligned on reduced deliverables, and agreed to share revised pricing next week.",+ "notes": "Agenda: renewal scope, pricing, next steps.",+ "startsAt": "2024-05-03T14:00:00-04:00",+ "status": "completed",+ "timezone": "America/New_York"+ }+ },+ {+ "details": "Routine check-up; discussed migraines and sleep habits.",+ "memoryCategory": "health",+ "memoryType": "activity",+ "summary": "Doctor appointment with Dr. Kim about migraines",+ "tags": [+ "appointment",+ "health"+ ],+ "title": "Neurology follow-up",+ "withActivity": {+ "type": "appointment",+ "associatedLocations": [+ {+ "name": "City Neurology Clinic"+ }+ ],+ "associatedSubjects": [+ {+ "name": "Dr. Kim",+ "type": "person"+ }+ ],+ "feedback": "Felt reassured; plan seems manageable.",+ "narrative": "User saw Dr. Kim to review migraine frequency; decided to track sleep, hydration, and start a low-dose preventive.",+ "notes": "Discussed triggers, hydration, and medication side effects.",+ "status": "completed"+ }+ }+ ],+ "properties": {+ "details": {+ "description": "Optional detailed information or longer notes supporting the summary and narrative.",+ "type": "string"+ },+ "memoryCategory": {+ "description": "Memory category best matching the activity (e.g., work, health, travel, relationships).",+ "type": "string"+ },+ "memoryType": {+ "const": "activity",+ "description": "Memory type; always activity.",+ "type": "string"+ },+ "summary": {+ "description": "Concise overview of this activity.",+ "type": "string"+ },+ "tags": {+ "description": "Model-generated tags summarizing key facets of the activity.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "title": {+ "description": "Brief descriptive title for the activity, e.g., \"Dinner with friends at Marina\".",+ "type": "string"+ },+ "withActivity": {+ "additionalProperties": false,+ "description": "Structured activity fields. Temporal and association values are optional—include only when the user mentioned them.",+ "properties": {+ "type": {+ "description": "Activity type enum. Choose the closest match; fall back to \"other\" when unclear.",+ "enum": [+ "appointment",+ "call",+ "celebration",+ "class",+ "conference",+ "errand",+ "event",+ "exercise",+ "meal",+ "meeting",+ "other",+ "project-session",+ "social",+ "task",+ "trip",+ "workshop"+ ],+ "type": "string"+ },+ "associatedLocations": {+ "description": "Places linked to this activity. Capture any mentioned venue, address, or setting.",+ "items": {+ "additionalProperties": false,+ "properties": {+ "address": {+ "description": "Free-form address or directions if provided.",+ "type": [+ "string",+ "null"+ ]+ },+ "extra": {+ "description": "Optional key-value metadata related to the location.",+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "description": "Place name or venue label.",+ "type": "string"+ },+ "tags": {+ "description": "Place-related tags (e.g., indoor, outdoor, virtual).",+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "type": {+ "description": "Place type or category (office, clinic, restaurant, virtual).",+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "address",+ "tags",+ "extra"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "associatedObjects": {+ "description": "Non-living entities or items tied to the activity (e.g., transportation for trips, devices, tools).",+ "items": {+ "additionalProperties": false,+ "properties": {+ "extra": {+ "description": "Optional key-value metadata related to the object.",+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "description": "Name or label of the object (e.g., “MacBook”, “flight UA123”).",+ "type": "string"+ },+ "type": {+ "description": "Object category (e.g., transportation, device, document).",+ "enum": [+ "application",+ "item",+ "knowledge",+ "other",+ "person",+ "place"+ ],+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "extra"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "associatedSubjects": {+ "description": "Living beings involved (people, pets, groups). Use when the subject lacks a known identity ID.",+ "items": {+ "additionalProperties": false,+ "properties": {+ "extra": {+ "description": "Optional key-value metadata related to the subject.",+ "type": [+ "string",+ "null"+ ]+ },+ "name": {+ "description": "Name or short label of the subject.",+ "type": "string"+ },+ "type": {+ "description": "Subject category (e.g., person, pet, group).",+ "enum": [+ "person",+ "pet",+ "group",+ "other"+ ],+ "type": "string"+ }+ },+ "required": [+ "type",+ "name",+ "extra"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "endsAt": {+ "description": "ISO 8601 end time for the activity when specified. Omit if not explicitly provided.",+ "format": "date-time",+ "type": [+ "string",+ "null"+ ]+ },+ "feedback": {+ "description": "Subjective feelings or evaluation of how the activity went (mood, satisfaction, effort).",+ "type": [+ "string",+ "null"+ ]+ },+ "metadata": {+ "additionalProperties": false,+ "description": "Additional structured metadata to keep raw hints (JSON object). Use sparingly.",+ "type": [+ "object",+ "null"+ ]+ },+ "narrative": {+ "description": "Factual story of what happened (chronology, participants, outcomes). Required for recall.",+ "type": "string"+ },+ "notes": {+ "description": "Short annotations such as agenda, preparation, or quick bullets distinct from narrative.",+ "type": [+ "string",+ "null"+ ]+ },+ "startsAt": {+ "description": "ISO 8601 start time for the activity when specified. Omit if not explicitly provided.",+ "format": "date-time",+ "type": [+ "string",+ "null"+ ]+ },+ "status": {+ "description": "Lifecycle status when mentioned. Use planned/completed/cancelled/ongoing/on_hold/pending. Omit if unclear.",+ "enum": [+ "planned",+ "completed",+ "cancelled",+ "ongoing",+ "on_hold",+ "pending"+ ],+ "type": [+ "string",+ "null"+ ]+ },+ "tags": {+ "description": "Optional activity-specific tags or facets.",+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "timezone": {+ "description": "IANA timezone string for the start/end times when provided (e.g., \"America/New_York\").",+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "type",+ "narrative",+ "feedback",+ "notes",+ "associatedLocations",+ "associatedSubjects",+ "associatedObjects",+ "startsAt",+ "endsAt",+ "status",+ "tags",+ "timezone",+ "metadata"+ ],+ "type": "object"+ }+ },+ "required": [+ "title",+ "summary",+ "details",+ "memoryType",+ "memoryCategory",+ "tags",+ "withActivity"+ ],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": [+ "memories"+ ],+ "type": "object"+ },+ "strict": true+ },+ "type": "json_schema"+}diff --git a/packages/memory-user-memory/promptfoo/response-formats/experience.json b/packages/memory-user-memory/promptfoo/response-formats/experience.jsonindex 4fa4a3ab7f1..cbe54325753 100644--- a/packages/memory-user-memory/promptfoo/response-formats/experience.json+++ b/packages/memory-user-memory/promptfoo/response-formats/experience.json@@ -62,6 +62,12 @@"type": "string","description": "Narrative describing key insights or lessons learned"},+ "knowledgeValueScore": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric score (0-1) describing how reusable and shareable this experience is"+ },"labels": {"type": "array","items": {@@ -73,6 +79,12 @@"type": "string","description": "Narrative describing potential outcomes or learnings"},+ "problemSolvingScore": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric score (0-1) describing how effectively the problem was solved"+ },"reasoning": {"type": "string","description": "Narrative describing the thought process or motivations"@@ -95,8 +107,10 @@"required": ["action","keyLearning",+ "knowledgeValueScore","labels","possibleOutcome",+ "problemSolvingScore","reasoning","scoreConfidence","situation",diff --git a/packages/memory-user-memory/promptfoo/response-formats/identity.json b/packages/memory-user-memory/promptfoo/response-formats/identity.jsonindex f78168eb568..853648db7f8 100644--- a/packages/memory-user-memory/promptfoo/response-formats/identity.json+++ b/packages/memory-user-memory/promptfoo/response-formats/identity.json@@ -3,192 +3,10 @@"type": "object","properties": {"add": {- "type": "array",- "items": {- "type": "object",- "properties": {- "details": {- "type": [- "string",- "null"- ],- "description": "Optional detailed information"- },- "memoryCategory": {- "type": "string",- "description": "Memory category"- },- "memoryLayer": {- "type": "string",- "const": "identity",- "description": "Memory layer"- },- "memoryType": {- "type": "string",- "enum": [- "activity",- "context",- "event",- "fact",- "location",- "other",- "people",- "preference",- "technology",- "topic"- ],- "description": "Memory type"- },- "summary": {- "type": "string",- "description": "Concise overview of this specific memory"- },- "tags": {- "type": "array",- "items": {- "type": "string"- },- "description": "Model generated tags that summarize the identity facets"- },- "title": {- "type": "string",- "description": "Brief descriptive title"- },- "withIdentity": {- "type": "object",- "properties": {- "description": {- "type": "string"- },- "episodicDate": {- "type": [- "string",- "null"- ]- },- "extractedLabels": {- "type": "array",- "items": {- "type": "string"- }- },- "relationship": {- "type": "string",- "enum": [- "self",- "father",- "mother",- "son",- "daughter",- "brother",- "sister",- "sibling",- "husband",- "wife",- "spouse",- "partner",- "couple",- "friend",- "colleague",- "coworker",- "classmate",- "mentor",- "mentee",- "manager",- "teammate",- "grandfather",- "grandmother",- "grandson",- "granddaughter",- "uncle",- "aunt",- "nephew",- "niece",- "other"- ]- },- "role": {- "type": "string"- },- "scoreConfidence": {- "type": "number"- },- "sourceEvidence": {- "type": [- "string",- "null"- ]- },- "type": {- "type": "string",- "enum": [- "professional",- "personal",- "demographic"- ]- }- },- "required": [- "description",- "episodicDate",- "extractedLabels",- "relationship",- "role",- "scoreConfidence",- "sourceEvidence",- "type"- ],- "additionalProperties": false- }- },- "required": [- "details",- "memoryCategory",- "memoryLayer",- "memoryType",- "summary",- "tags",- "title",- "withIdentity"- ],- "additionalProperties": false- }- },- "remove": {- "type": "array",- "items": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "reason": {- "type": "string"- }- },- "required": [- "id",- "reason"- ],- "additionalProperties": false- }- },- "update": {- "type": "array",- "items": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "mergeStrategy": {- "type": "string",- "enum": [- "merge",- "replace"- ]- },- "set": {+ "anyOf": [+ {+ "type": "array",+ "items": {"type": "object","properties": {"details": {@@ -196,14 +14,16 @@"string","null"],- "description": "Optional detailed information, use null for omitting the field"+ "description": "Optional detailed information"},"memoryCategory": {- "type": [- "string",- "null"- ],- "description": "Memory category, use null for omitting the field"+ "type": "string",+ "description": "Memory category"+ },+ "memoryLayer": {+ "type": "string",+ "const": "identity",+ "description": "Memory layer"},"memoryType": {"type": "string",@@ -219,44 +39,28 @@"technology","topic"],- "description": "Memory type, use null for omitting the field"+ "description": "Memory type"},"summary": {- "type": [- "string",- "null"- ],- "description": "Concise overview of this specific memory, use null for omitting the field"+ "type": "string",+ "description": "Concise overview of this specific memory"},"tags": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ],- "description": "Model generated tags that summarize the identity facets, use null for omitting the field"+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Model generated tags that summarize the identity facets"},"title": {- "type": [- "string",- "null"- ],- "description": "Brief descriptive title, use null for omitting the field"+ "type": "string",+ "description": "Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., \"Trusted open-source maintainer\", \"Specializes in low-latency infra\", \"Former Aliyun engineer\", \"Cares for rescue cats\""},"withIdentity": {"type": "object","properties": {"description": {- "type": [- "string",- "null"- ]+ "type": "string"},"episodicDate": {"type": [@@ -265,36 +69,52 @@]},"extractedLabels": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "type": "array",+ "items": {+ "type": "string"+ }},"relationship": {- "type": [- "string",- "null"- ],- "description": "Possible values: self | father | mother | son | daughter | brother | sister | sibling | husband | wife | spouse | partner | couple | friend | colleague | coworker | classmate | mentor | mentee | manager | teammate | grandfather | grandmother | grandson | granddaughter | uncle | aunt | nephew | niece | other"+ "type": "string",+ "enum": [+ "self",+ "father",+ "mother",+ "son",+ "daughter",+ "brother",+ "sister",+ "sibling",+ "husband",+ "wife",+ "spouse",+ "partner",+ "couple",+ "friend",+ "colleague",+ "coworker",+ "classmate",+ "mentor",+ "mentee",+ "manager",+ "teammate",+ "grandfather",+ "grandmother",+ "grandson",+ "granddaughter",+ "uncle",+ "aunt",+ "nephew",+ "niece",+ "other"+ ]},"role": {- "type": [- "string",- "null"- ]+ "type": "string",+ "description": "Role explicitly mentioned for this identity entry (e.g., \"platform engineer\", \"caregiver\"); keep neutral and only use when evidence exists"},"scoreConfidence": {- "type": [- "number",- "null"- ]+ "type": "number"},"sourceEvidence": {"type": [@@ -303,11 +123,12 @@]},"type": {- "type": [- "string",- "null"- ],- "description": "Possible values: professional | personal | demographic"+ "type": "string",+ "enum": [+ "professional",+ "personal",+ "demographic"+ ]}},"required": [@@ -326,6 +147,7 @@"required": ["details","memoryCategory",+ "memoryLayer","memoryType","summary","tags",@@ -335,13 +157,217 @@"additionalProperties": false}},- "required": [- "id",- "mergeStrategy",- "set"- ],- "additionalProperties": false- }+ {+ "type": "null"+ }+ ],+ "description": "Identity entries to add; use an empty array when nothing to add"+ },+ "remove": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "reason": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "reason"+ ],+ "additionalProperties": false+ }+ },+ {+ "type": "null"+ }+ ],+ "description": "Identity entries to remove; use an empty array when nothing to remove"+ },+ "update": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "mergeStrategy": {+ "type": "string",+ "enum": [+ "merge",+ "replace"+ ]+ },+ "set": {+ "type": "object",+ "properties": {+ "details": {+ "type": [+ "string",+ "null"+ ],+ "description": "Optional detailed information, use null for omitting the field"+ },+ "memoryCategory": {+ "type": [+ "string",+ "null"+ ],+ "description": "Memory category, use null for omitting the field"+ },+ "memoryType": {+ "type": "string",+ "enum": [+ "activity",+ "context",+ "event",+ "fact",+ "location",+ "other",+ "people",+ "preference",+ "technology",+ "topic"+ ],+ "description": "Memory type, use null for omitting the field"+ },+ "summary": {+ "type": [+ "string",+ "null"+ ],+ "description": "Concise overview of this specific memory, use null for omitting the field"+ },+ "tags": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ],+ "description": "Model generated tags that summarize the identity facets, use null for omitting the field"+ },+ "title": {+ "type": [+ "string",+ "null"+ ],+ "description": "Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., \"Trusted open-source maintainer\", \"Specializes in low-latency infra\", \"Former Aliyun engineer\", \"Cares for rescue cats\"; use null for omitting the field"+ },+ "withIdentity": {+ "type": "object",+ "properties": {+ "description": {+ "type": [+ "string",+ "null"+ ]+ },+ "episodicDate": {+ "type": [+ "string",+ "null"+ ]+ },+ "extractedLabels": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "relationship": {+ "type": [+ "string",+ "null"+ ],+ "description": "Possible values: self | father | mother | son | daughter | brother | sister | sibling | husband | wife | spouse | partner | couple | friend | colleague | coworker | classmate | mentor | mentee | manager | teammate | grandfather | grandmother | grandson | granddaughter | uncle | aunt | nephew | niece | other"+ },+ "role": {+ "type": [+ "string",+ "null"+ ],+ "description": "Role explicitly mentioned for this identity entry (e.g., \"platform engineer\", \"caregiver\"); keep existing when not updated; use null for omitting the field"+ },+ "scoreConfidence": {+ "type": [+ "number",+ "null"+ ]+ },+ "sourceEvidence": {+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": [+ "string",+ "null"+ ],+ "description": "Possible values: professional | personal | demographic"+ }+ },+ "required": [+ "description",+ "episodicDate",+ "extractedLabels",+ "relationship",+ "role",+ "scoreConfidence",+ "sourceEvidence",+ "type"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "details",+ "memoryCategory",+ "memoryType",+ "summary",+ "tags",+ "title",+ "withIdentity"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "id",+ "mergeStrategy",+ "set"+ ],+ "additionalProperties": false+ }+ },+ {+ "type": "null"+ }+ ],+ "description": "Identity entries to update; use an empty array when nothing to update"}},"required": [diff --git a/packages/memory-user-memory/promptfooconfig.yaml b/packages/memory-user-memory/promptfooconfig.yamlindex 477a1d04429..a9161be8493 100644--- a/packages/memory-user-memory/promptfooconfig.yaml+++ b/packages/memory-user-memory/promptfooconfig.yaml@@ -3,6 +3,7 @@ description: LobeHub Prompts (memory-user-memory) Testing Suite# Test configurations - run all prompt teststestPaths:- promptfoo/evals/identity/with-s3-trace/eval.yaml+ - promptfoo/evals/activity/basic/eval.yaml# Output configurationoutputPath: promptfoo-results.jsondiff --git a/packages/memory-user-memory/scripts/generate-response-formats.ts b/packages/memory-user-memory/scripts/generate-response-formats.tsindex 04e440d249a..df0bcdf278a 100644--- a/packages/memory-user-memory/scripts/generate-response-formats.ts+++ b/packages/memory-user-memory/scripts/generate-response-formats.ts@@ -3,7 +3,15 @@ import { mkdir, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { exit } from 'node:process';-import { ContextMemorySchema, IdentityActionsSchema, PreferenceMemorySchema, ExperienceMemorySchema } from '../src/schemas';+import type { GenerateObjectSchema } from '@lobechat/model-runtime';++import {+ ActivityMemorySchema,+ ContextMemorySchema,+ IdentityActionsSchema,+ PreferenceMemorySchema,+ ExperienceMemorySchema,+} from '../src/schemas';import { buildGenerateObjectSchema } from '../src/utils/zod';const OUTPUT_DIR = join(process.cwd(), 'promptfoo/response-formats');@@ -22,6 +30,22 @@ const writeSchema = async (name: string, schema: any, description: string) => {console.log(`Wrote ${outPath}`);};+const writeGenerateObjectSchema = async (name: string, generateSchema: GenerateObjectSchema) => {+ const responseFormat: { json_schema: GenerateObjectSchema, type: 'json_schema' } = {+ json_schema: {+ name: generateSchema.name || name,+ schema: generateSchema.schema,+ strict: generateSchema.strict,+ },+ type: 'json_schema' as const,+ };++ const outPath = join(OUTPUT_DIR, `${name}.json`);+ await writeFile(outPath, JSON.stringify(responseFormat, null, 2), 'utf8');+ // eslint-disable-next-line no-console+ console.log(`Wrote ${outPath}`);+};+async function main() {await mkdir(OUTPUT_DIR, { recursive: true });@@ -29,6 +53,7 @@ async function main() {await writeSchema('context', ContextMemorySchema, 'Context layer actions');await writeSchema('preference', PreferenceMemorySchema, 'Preference layer memories');await writeSchema('experience', ExperienceMemorySchema, 'Experience layer memories');+ await writeGenerateObjectSchema('activity', ActivityMemorySchema);}main().catch((err) => {@@ -36,4 +61,3 @@ main().catch((err) => {console.error(err);exit(1);});-diff --git a/packages/memory-user-memory/src/extractors/activity.ts b/packages/memory-user-memory/src/extractors/activity.tsnew file mode 100644index 00000000000..22e76a105ab--- /dev/null+++ b/packages/memory-user-memory/src/extractors/activity.ts@@ -0,0 +1,44 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import { activityPrompt } from '../prompts';+import { ActivityMemory, ActivityMemorySchema } from '../schemas';+import { ExtractorTemplateProps } from '../types';+import { BaseMemoryExtractor } from './base';++export class ActivityExtractor extends BaseMemoryExtractor<ActivityMemory> {+ getPrompt(): string {+ return activityPrompt;+ }++ protected getPromptName(): string {+ return 'layer-activity';+ }++ getSchema() {+ return ActivityMemorySchema;+ }++ // Activity schema uses JSON Schema directly; no zod validation is applied here.+ protected getResultSchema() {+ return undefined;+ }++ getTemplateProps(options: ExtractorTemplateProps) {+ return {+ availableCategories: options.availableCategories,+ language: options.language,+ retrievedContext: options.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: options.sessionDate,+ topK: options.topK,+ username: options.username,+ };+ }++ buildUserPrompt(options: ExtractorTemplateProps): string {+ if (!this.promptTemplate) {+ throw new Error('Prompt template not loaded');+ }++ return renderPlaceholderTemplate(this.promptTemplate!, this.getTemplateProps(options));+ }+}diff --git a/packages/memory-user-memory/src/extractors/gatekeeper.test.ts b/packages/memory-user-memory/src/extractors/gatekeeper.test.tsindex ed6478c03a3..fd42d9f2046 100644--- a/packages/memory-user-memory/src/extractors/gatekeeper.test.ts+++ b/packages/memory-user-memory/src/extractors/gatekeeper.test.ts@@ -31,7 +31,7 @@ describe('UserMemoryGateKeeper', () => {expect(schema?.strict).toBe(true);const properties = (schema?.schema as any).properties;- const requiredLayers = ['context', 'experience', 'identity', 'preference'];+ const requiredLayers = ['activity', 'context', 'experience', 'identity', 'preference'];requiredLayers.forEach((layer) => {const layerSchema = properties[layer];@@ -78,6 +78,7 @@ describe('UserMemoryGateKeeper', () => {const extractor = new UserMemoryGateKeeper(extractorConfig);const llmResult = {+ activity: { reasoning: 'reasoning', shouldExtract: true },context: { reasoning: 'reasoning', shouldExtract: true },experience: { reasoning: 'reasoning', shouldExtract: false },identity: { reasoning: 'reasoning', shouldExtract: true },diff --git a/packages/memory-user-memory/src/extractors/gatekeeper.ts b/packages/memory-user-memory/src/extractors/gatekeeper.tsindex 4e97735d7ae..91447fe9a86 100644--- a/packages/memory-user-memory/src/extractors/gatekeeper.ts+++ b/packages/memory-user-memory/src/extractors/gatekeeper.ts@@ -27,12 +27,13 @@ export class UserMemoryGateKeeper extends BaseMemoryExtractor<GatekeeperResult,schema: {additionalProperties: false,properties: {+ activity: layerDecision,context: layerDecision,experience: layerDecision,identity: layerDecision,preference: layerDecision,},- required: ['context', 'experience', 'identity', 'preference'],+ required: ['activity', 'context', 'experience', 'identity', 'preference'],type: 'object' as const,},strict: true,diff --git a/packages/memory-user-memory/src/extractors/index.ts b/packages/memory-user-memory/src/extractors/index.tsindex 3d443940ca9..360d4770ab4 100644--- a/packages/memory-user-memory/src/extractors/index.ts+++ b/packages/memory-user-memory/src/extractors/index.ts@@ -1,3 +1,4 @@+export { ActivityExtractor } from './activity';export { ContextExtractor } from './context';export { ExperienceExtractor } from './experience';export { UserMemoryGateKeeper } from './gatekeeper';diff --git a/packages/memory-user-memory/src/prompts/gatekeeper.ts b/packages/memory-user-memory/src/prompts/gatekeeper.tsindex 233ec208d98..11576eb2789 100644--- a/packages/memory-user-memory/src/prompts/gatekeeper.ts+++ b/packages/memory-user-memory/src/prompts/gatekeeper.ts@@ -9,11 +9,11 @@ export const gatekeeperPrompt = ['','Evaluate the conversation for these memory layers:','',- '**Activity Layer** - Episodic events with clear timelines and participants:',+'**Activity Layer** - Episodic events with clear timelines and participants:','','- Meetings, calls, errands, and appointments with start/end times',- '- Locations (physical or virtual) and timezones',- '- Status (planned, completed) and follow-up actions',+ '- Locations (physical or virtual) and timezones when provided (omit if absent)',+ '- Status (planned, completed, cancelled, ongoing, on_hold, pending) and follow-up actions','- Narratives summarizing what happened and feedback/notes','','**Identity Layer** - Information about actors, relationships, and personal attributes:',diff --git a/packages/memory-user-memory/src/prompts/index.ts b/packages/memory-user-memory/src/prompts/index.tsindex a96b178381b..a77fa95024a 100644--- a/packages/memory-user-memory/src/prompts/index.ts+++ b/packages/memory-user-memory/src/prompts/index.ts@@ -1,2 +1,8 @@export { gatekeeperPrompt } from './gatekeeper';-export { contextPrompt, experiencePrompt, identityPrompt, preferencePrompt } from './layers';+export {+ activityPrompt,+ contextPrompt,+ experiencePrompt,+ identityPrompt,+ preferencePrompt,+} from './layers';diff --git a/packages/memory-user-memory/src/prompts/layers/activity.ts b/packages/memory-user-memory/src/prompts/layers/activity.tsnew file mode 100644index 00000000000..d5ec1531229--- /dev/null+++ b/packages/memory-user-memory/src/prompts/layers/activity.ts@@ -0,0 +1,90 @@+export const activityPrompt = [+ 'You are a focused memory extraction assistant specialized in the **activity** layer.',+ 'When extracting, ensure all the content is using {{ language }}.',+ '',+ '\\<user_context>',+ 'Current user: {{ username }}',+ 'Session date: {{ sessionDate }}',+ 'Available memory categories: {{ availableCategories }}',+ 'Target layer: activity',+ '\\</user_context>',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below to de-duplicate and decide whether you need to extract anything new.',+ 'Do not copy these verbatim; treat them as comparison references.',+ '',+ '{{ retrievedContext }}',+ '',+ '## Your Task',+ '',+ 'Extract **ALL** activity layer information from the conversation. Activities are time-bound events',+ 'with people, places, status, and a factual narrative of what happened. Capture how it felt via',+ 'feedback. Temporal (startsAt, endsAt, timezone) and association fields are OPTIONAL—only include',+ 'them when explicitly provided. If missing, **omit the fields entirely** (do not set null/empty) instead of guessing.',+ '',+ '**CRITICAL**: Return an **array** of activity memory items. Extract each distinct activity as a separate item.',+ 'Before extracting, review the retrieved similar memories (top {{ topK }} items shown above). Extract items',+ 'that are NEW or MATERIALLY UPDATED compared to retrieved entries. Avoid duplicates or near-duplicates.',+ '',+ '## Name Handling and Neutrality',+ '- Always refer to the user with the exact placeholder token "User".',+ "- Do not infer, invent, or translate the user's real name.",+ '- Avoid gendered terms or honorifics; keep references neutral.',+ '',+ '## Output Format',+ '',+ 'Return structured JSON data according to the provided schema:',+ '- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory, tags',+ '- Activity-specific fields in withActivity: type (enum), status (planned/completed/cancelled/ongoing/on_hold/pending),',+ ' optional timezone, startsAt, endsAt (ISO 8601), associatedSubjects (self-aware entities: people, pets, groups, orgs), associatedObjects',+ ' (non-living items like transportation, devices),',+ ' associatedLocations (places; capture any mentioned venue/address), notes (prep/agenda), narrative (factual story),',+ ' feedback (how it felt), metadata (JSON), tags (activity facets).',+ '- Do not fabricate dates, timezones, or locations. Only include them when explicitly mentioned or derivable.',+ '',+ '## Memory Formatting Guidelines',+ '',+ '> ALL MEMORY ITEMS MUST BE SELF-CONTAINED',+ '- Use concrete names/entities—avoid pronouns.',+ '- Preserve the original language from user input—do not translate.',+ '- Include relevant details, participants, places, timing if present, and outcomes.',+ '- Keep narratives factual; avoid speculative embellishment.',+ '',+ '✓ **Good Examples:**',+ '- "User met with Alice at ACME HQ on 2024-05-03 14:00-15:00 America/New_York to review the Q2 renewal,',+ ' aligned on reduced scope, and agreed to send revised pricing; User felt the call was positive and collaborative."',+ '- "User visited Dr. Kim for a migraine check-up, discussed triggers and sleep, and started a low-dose preventive;',+ ' User felt reassured."',+ '',+ '✗ **Bad Examples:**',+ '- "They had a meeting" → Missing who, when, where, and outcome.',+ '- "Felt good" → Missing context of the activity.',+ '- "Probably in New York" → Do not guess locations or timezones.',+ '',+ '## Layer-Specific Guidance',+ '- Focus on discrete events (meetings, calls, trips, workouts, meals, appointments).',+ '- Always capture mentioned locations in associatedLocations. If none are stated, omit the field.',+ '- If the activity is a trip, record transportation modes or specific rides/tickets in associatedObjects.',+ '- Route any self-aware entity without a known identity ID (people, pets, groups, institutions/orgs) to associatedSubjects.',+ '- type choices: meeting, appointment, exercise, meal, social, trip, task, workshop, conference, call, errand, celebration, class, project-session, other.',+ '- Status handling: use provided status markers (planned, completed, cancelled, ongoing, on_hold, pending). If no status is stated, omit.',+ '- Do not add the user as an associatedSubject; only include other mentioned living entities.',+ '- Feedback captures how the activity felt (effort, mood, satisfaction); narrative captures the factual sequence.',+ '- Location and temporal fields are optional—only include when stated.',+ '- Temporal anchoring: when the conversation uses relative time phrases (yesterday, tomorrow, last week), anchor calculations to the specific message timestamp (created_at) if present; otherwise fall back to sessionDate. Keep the anchor timezone/time-of-day when converting relative references and do not invent new times if none are given.',+ '',+ '## Few-shot Hints',+ '- Meeting with known person, time stated → include type=meeting, startsAt/endsAt/timezone, associatedSubjects for participants, location name if given.',+ '- Workout described without time/place → type=exercise, omit time/timezone/location, keep narrative/feedback.',+ '- Dinner with friends mentioned without exact time → type=meal or social, include attendees if named, omit time/place if absent.',+ '',+ '## Security Considerations',+ '**NEVER extract or store sensitive information:** passwords, API keys, financial account numbers, or private encryption keys.',+ '',+ '---',+ 'Final instructions:',+ '1. Extract each distinct activity memory as a separate item.',+ '2. Ensure memories are self-contained and in {{ language }}.',+ '3. Return JSON matching the schema. Use [] when nothing should be extracted.',+].join('\\n');diff --git a/packages/memory-user-memory/src/prompts/layers/index.ts b/packages/memory-user-memory/src/prompts/layers/index.tsindex c070161668a..2e00b1083d6 100644--- a/packages/memory-user-memory/src/prompts/layers/index.ts+++ b/packages/memory-user-memory/src/prompts/layers/index.ts@@ -1,3 +1,4 @@+export { activityPrompt } from './activity';export { contextPrompt } from './context';export { experiencePrompt } from './experience';export { identityPrompt } from './identity';diff --git a/packages/memory-user-memory/src/providers/existingUserMemory.test.ts b/packages/memory-user-memory/src/providers/existingUserMemory.test.tsindex 87b34181cb6..96661d5a0d0 100644--- a/packages/memory-user-memory/src/providers/existingUserMemory.test.ts+++ b/packages/memory-user-memory/src/providers/existingUserMemory.test.ts@@ -19,6 +19,30 @@ describe('RetrievalUserMemoryContextProvider', () => {const provider = new RetrievalUserMemoryContextProvider({fetchedAt,retrievedMemories: {+ activities: [+ {+ accessedAt: new Date(),+ type: 'meeting',+ associatedLocations: [{ name: 'Zoom' }],+ associatedSubjects: [{ name: 'Alice', type: 'person' }],+ capturedAt: new Date(),+ createdAt: new Date(),+ endsAt: new Date('2024-02-01T02:00:00.000Z'),+ feedback: 'Felt good',+ id: 'act-1',+ metadata: {},+ narrative: 'Weekly sync about roadmap',+ notes: 'Agenda: roadmap',+ startsAt: new Date('2024-02-01T01:00:00.000Z'),+ status: 'completed',+ tags: ['meeting'],+ timezone: 'UTC',+ updatedAt: new Date(),+ userId: 'user-1',+ userMemoryId: 'mem-act-1',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ ],contexts: [{accessedAt: new Date(),@@ -91,7 +115,7 @@ describe('RetrievalUserMemoryContextProvider', () => {expect(result.userId).toBe('user-1');expect(result.metadata).toEqual({});expect(result.context).equal(- '<user_memories contexts="1" experiences="1" memory_fetched_at="2024-02-01T00:00:00.000Z" preferences="1"><user_memories_context id="ctx-1" type="project"><context_title>LobeHub</context_title><context_description>Weekly syncs for LobeHub</context_description><context_current_status>active</context_current_status><context_tags>project, team</context_tags></user_memories_context><user_memories_experience id="exp-1" type="product"><experience_situation>Release planning</experience_situation><experience_key_learning>Ship smaller increments</experience_key_learning><experience_action>Shipped feature</experience_action><experience_reasoning>Better agility</experience_reasoning><experience_possible_outcome>Faster releases</experience_possible_outcome><experience_tags>release</experience_tags></user_memories_experience><user_memories_preference id="pref-1" type="style"><preference_conclusion_directives>Always keep updates concise</preference_conclusion_directives><preference_suggestions>Use bullet points</preference_suggestions><preference_tags>communication</preference_tags></user_memories_preference></user_memories>',+ '<user_memories activities="1" contexts="1" experiences="1" memory_fetched_at="2024-02-01T00:00:00.000Z" preferences="1"><user_memories_activity id="act-1" activity_type="meeting" status="completed" timezone="UTC" starts_at="2024-02-01T01:00:00.000Z" ends_at="2024-02-01T02:00:00.000Z"><activity_narrative>Weekly sync about roadmap</activity_narrative><activity_notes>Agenda: roadmap</activity_notes><activity_feedback>Felt good</activity_feedback><activity_associated_location>Zoom</activity_associated_location><activity_associated_subject>Alice | type: person</activity_associated_subject><activity_tags>meeting</activity_tags></user_memories_activity><user_memories_context id="ctx-1" type="project"><context_title>LobeHub</context_title><context_description>Weekly syncs for LobeHub</context_description><context_current_status>active</context_current_status><context_tags>project, team</context_tags></user_memories_context><user_memories_experience id="exp-1" type="product"><experience_situation>Release planning</experience_situation><experience_key_learning>Ship smaller increments</experience_key_learning><experience_action>Shipped feature</experience_action><experience_reasoning>Better agility</experience_reasoning><experience_possible_outcome>Faster releases</experience_possible_outcome><experience_tags>release</experience_tags></user_memories_experience><user_memories_preference id="pref-1" type="style"><preference_conclusion_directives>Always keep updates concise</preference_conclusion_directives><preference_suggestions>Use bullet points</preference_suggestions><preference_tags>communication</preference_tags></user_memories_preference></user_memories>',);});});diff --git a/packages/memory-user-memory/src/providers/existingUserMemory.ts b/packages/memory-user-memory/src/providers/existingUserMemory.tsindex c82d5f9fa28..75eb581011b 100644--- a/packages/memory-user-memory/src/providers/existingUserMemory.ts+++ b/packages/memory-user-memory/src/providers/existingUserMemory.ts@@ -1,5 +1,6 @@import type {IdentityMemoryDetail,+ UserMemoryActivityWithoutVectors,UserMemoryContextWithoutVectors,UserMemoryExperienceWithoutVectors,UserMemoryPreferenceWithoutVectors,@@ -12,6 +13,7 @@ import { x } from 'xastscript';import type { BuiltContext, MemoryContextProvider, MemoryExtractionJob } from '../types';interface RetrievedMemories {+ activities: UserMemoryActivityWithoutVectors[];contexts: UserMemoryContextWithoutVectors[];experiences: UserMemoryExperienceWithoutVectors[];preferences: UserMemoryPreferenceWithoutVectors[];@@ -31,13 +33,123 @@ export class RetrievalUserMemoryContextProvider implements MemoryContextProviderthis.fetchedAt = options.fetchedAt;}+ private formatTags(tags?: unknown) {+ return Array.isArray(tags) && tags.length ? `tags: ${tags.join(', ')}` : '';+ }++ private formatLocation(location: any) {+ if (!location || typeof location !== 'object') return '';+ const parts: string[] = [];++ if (typeof location.name === 'string' && location.name) parts.push(location.name);+ if (typeof location.type === 'string' && location.type) parts.push(`type: ${location.type}`);+ if (typeof location.address === 'string' && location.address) parts.push(location.address);++ const tags = this.formatTags(location.tags);+ if (tags) parts.push(tags);++ return parts.join(' | ');+ }++ private formatAssociation(value: any) {+ if (!value || typeof value !== 'object') return '';+ const parts: string[] = [];++ if (typeof value.name === 'string' && value.name) parts.push(value.name);+ if (typeof value.type === 'string' && value.type) parts.push(`type: ${value.type}`);++ if (value.extra && typeof value.extra === 'object') {+ try {+ parts.push(`extra: ${JSON.stringify(value.extra)}`);+ } catch {+ parts.push('extra: [unserializable]');+ }+ }++ return parts.join(' | ');+ }+async buildContext(job: MemoryExtractionJob): Promise<BuiltContext> {+ const activities = this.retrievedMemories.activities || [];const contexts = this.retrievedMemories.contexts || [];const experiences = this.retrievedMemories.experiences || [];const preferences = this.retrievedMemories.preferences || [];++const userMemoriesChildren: Child[] = [];+ activities.forEach((activity) => {+ const attributes: Record<string, string> = { id: activity.id ?? '' };+ const similarity = (activity as { similarity?: number }).similarity;++ if (typeof similarity === 'number') {+ attributes.similarity = similarity.toFixed(3);+ }+ if (activity.type) {+ attributes.activity_type = activity.type;+ }+ if (activity.status) {+ attributes.status = activity.status;+ }+ if (activity.timezone) {+ attributes.timezone = activity.timezone;+ }+ if (activity.startsAt) {+ attributes.starts_at = new Date(activity.startsAt).toISOString();+ }+ if (activity.endsAt) {+ attributes.ends_at = new Date(activity.endsAt).toISOString();+ }++ const children: Child[] = [];+ const legacyLocation = (activity as { location?: unknown }).location;+ const associatedLocations = Array.isArray(activity.associatedLocations)+ ? activity.associatedLocations+ : legacyLocation+ ? [legacyLocation]+ : [];+ const associatedObjects = Array.isArray(activity.associatedObjects)+ ? activity.associatedObjects+ : [];+ const associatedSubjects = Array.isArray(activity.associatedSubjects)+ ? activity.associatedSubjects+ : [];++ if (activity.narrative) {+ children.push(x('activity_narrative', activity.narrative));+ }+ if (activity.notes) {+ children.push(x('activity_notes', activity.notes));+ }+ if (activity.feedback) {+ children.push(x('activity_feedback', activity.feedback));+ }+ associatedLocations.forEach((location) => {+ const value = this.formatLocation(location);+ if (value) {+ children.push(x('activity_associated_location', value));+ }+ });+ associatedObjects.forEach((object) => {+ const value = this.formatAssociation(object);+ if (value) {+ children.push(x('activity_associated_object', value));+ }+ });+ associatedSubjects.forEach((subject) => {+ const value = this.formatAssociation(subject);+ if (value) {+ children.push(x('activity_associated_subject', value));+ }+ });+ if (Array.isArray(activity.tags) && activity.tags.length > 0) {+ children.push(x('activity_tags', activity.tags.join(', ')));+ }++ userMemoriesChildren.push(x('user_memories_activity', attributes, ...children));+ });+contexts.forEach((context) => {const attributes: Record<string, string> = { id: context.id ?? '' };const similarity = (context as { similarity?: number }).similarity;@@ -126,6 +238,7 @@ export class RetrievalUserMemoryContextProvider implements MemoryContextProviderx('user_memories',{+ activities: activities.length.toString(),contexts: contexts.length.toString(),experiences: experiences.length.toString(),memory_fetched_at: new Date(this.fetchedAt ?? Date.now()).toISOString(),diff --git a/packages/memory-user-memory/src/schemas/activity.ts b/packages/memory-user-memory/src/schemas/activity.tsnew file mode 100644index 00000000000..872c3af2166--- /dev/null+++ b/packages/memory-user-memory/src/schemas/activity.ts@@ -0,0 +1,315 @@+import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import { ActivityTypeEnum, LayersEnum, TypesEnum } from '@lobechat/types';+import { type JSONSchema7 } from 'json-schema';++export interface WithActivity {+ associatedLocations?: {+ address?: string;+ extra?: string | null;+ name?: string;+ tags?: string[];+ type?: string;+ }[];+ associatedObjects?: {+ extra?: string | null;+ name?: string;+ type?: string;+ }[];+ associatedSubjects?: {+ extra?: string | null;+ name?: string;+ type?: string;+ }[];+ endsAt?: string;+ feedback?: string;+ metadata?: Record<string, unknown>;+ narrative: string;+ notes?: string;+ startsAt?: string;+ status?: string;+ tags?: string[];+ timezone?: string;+ type: ActivityTypeEnum | string;+}++export interface ActivityMemoryItem {+ details: string;+ memoryCategory: string;+ memoryLayer: LayersEnum.Activity;+ memoryType: TypesEnum.Activity;+ summary: string;+ tags: string[];+ title: string;+ withActivity: WithActivity;+}++export interface ActivityMemory {+ memories: ActivityMemoryItem[];+}++export const ActivityMemorySchema: GenerateObjectSchema = {+ description:+ 'Extract episodic activities with clear timelines, participants, objects, subjects, locations, and feelings. Temporal and associated fields are optional—omit when missing rather than guessing.',+ name: 'activity_extraction',+ schema: {+ additionalProperties: false,+ properties: {+ memories: {+ description:+ 'Array of extracted activity memories. Use an empty array when no activity should be captured.',+ items: {+ additionalProperties: false,+ description:+ 'Self-contained activity memory describing what happened, when, where, with whom, and how it felt.',+ examples: [+ {+ details:+ 'Talked through renewal scope, confirmed timeline flexibility, and captured follow-ups.',+ memoryCategory: 'work',+ memoryType: 'activity',+ summary: 'Client Q2 renewal meeting with Alice (ACME)',+ tags: ['meeting', 'client', 'renewal'],+ title: 'ACME Q2 renewal meeting',+ withActivity: {+ associatedLocations: [+ {+ address: '123 Main St, New York, NY',+ name: 'ACME HQ',+ },+ ],+ associatedSubjects: [+ { name: 'Alice Smith', type: 'person' },+ ],+ endsAt: '2024-05-03T15:00:00-04:00',+ feedback: 'Positive momentum; Alice felt heard and open to renewal.',+ narrative:+ 'Alice and User reviewed Q2 renewal scope, aligned on reduced deliverables, and agreed to share revised pricing next week.',+ notes: 'Agenda: renewal scope, pricing, next steps.',+ startsAt: '2024-05-03T14:00:00-04:00',+ status: 'completed',+ timezone: 'America/New_York',+ type: 'meeting',+ },+ },+ {+ details: 'Routine check-up; discussed migraines and sleep habits.',+ memoryCategory: 'health',+ memoryType: 'activity',+ summary: 'Doctor appointment with Dr. Kim about migraines',+ tags: ['appointment', 'health'],+ title: 'Neurology follow-up',+ withActivity: {+ associatedLocations: [+ {+ name: 'City Neurology Clinic',+ },+ ],+ associatedSubjects: [+ { name: 'Dr. Kim', type: 'person' },+ ],+ feedback: 'Felt reassured; plan seems manageable.',+ narrative:+ 'User saw Dr. Kim to review migraine frequency; decided to track sleep, hydration, and start a low-dose preventive.',+ notes: 'Discussed triggers, hydration, and medication side effects.',+ status: 'completed',+ type: 'appointment',+ },+ },+ ],+ properties: {+ details: {+ description:+ 'Optional detailed information or longer notes supporting the summary and narrative.',+ type: 'string',+ },+ memoryCategory: {+ description:+ 'Memory category best matching the activity (e.g., work, health, travel, relationships).',+ type: 'string',+ },+ memoryType: {+ const: TypesEnum.Activity,+ description: 'Memory type; always activity.',+ type: 'string',+ },+ summary: {+ description: 'Concise overview of this activity.',+ type: 'string',+ },+ tags: {+ description: 'Model-generated tags summarizing key facets of the activity.',+ items: { type: 'string' },+ type: 'array',+ },+ title: {+ description:+ 'Brief descriptive title for the activity, e.g., "Dinner with friends at Marina".',+ type: 'string',+ },+ withActivity: {+ additionalProperties: false,+ description:+ 'Structured activity fields. Temporal and association values are optional—include only when the user mentioned them.',+ properties: {+ associatedLocations: {+ description:+ 'Places linked to this activity. Capture any mentioned venue, address, or setting.',+ items: {+ additionalProperties: false,+ properties: {+ address: {+ description: 'Free-form address or directions if provided.',+ type: ['string', 'null'],+ },+ extra: {+ description: 'Optional key-value metadata related to the location.',+ type: ['string', 'null'],+ },+ name: {+ description: 'Place name or venue label.',+ type: 'string',+ },+ tags: {+ description: 'Place-related tags (e.g., indoor, outdoor, virtual).',+ items: { type: 'string' },+ type: ['array', 'null'],+ },+ type: {+ description: 'Place type or category (office, clinic, restaurant, virtual).',+ type: 'string',+ },+ },+ required: ['type', 'name', 'address', 'tags', 'extra'],+ type: 'object',+ },+ type: 'array',+ },+ associatedObjects: {+ description:+ 'Non-living entities or items tied to the activity (e.g., transportation for trips, devices, tools).',+ items: {+ additionalProperties: false,+ properties: {+ extra: {+ description: 'Optional key-value metadata related to the object.',+ type: ['string', 'null'],+ },+ name: {+ description: 'Name or label of the object (e.g., “MacBook”, “flight UA123”).',+ type: 'string',+ },+ type: {+ description: 'Object category (e.g., transportation, device, document).',+ enum: ['application', 'item', 'knowledge', 'other', 'person', 'place'],+ type: 'string',+ },+ },+ required: ['type', 'name', 'extra'],+ type: 'object',+ },+ type: 'array',+ },+ associatedSubjects: {+ description:+ 'Living beings involved (people, pets, groups). Use when the subject lacks a known identity ID.',+ items: {+ additionalProperties: false,+ properties: {+ extra: {+ description: 'Optional key-value metadata related to the subject.',+ type: ['string', 'null'],+ },+ name: {+ description: 'Name or short label of the subject.',+ type: 'string',+ },+ type: {+ description: 'Subject category (e.g., person, pet, group).',+ enum: ['person', 'pet', 'group', 'other'],+ type: 'string',+ },+ },+ required: ['type', 'name', 'extra'],+ type: 'object',+ },+ type: 'array',+ },+ endsAt: {+ description:+ 'ISO 8601 end time for the activity when specified. Omit if not explicitly provided.',+ format: 'date-time',+ type: ['string', 'null'],+ },+ feedback: {+ description:+ 'Subjective feelings or evaluation of how the activity went (mood, satisfaction, effort).',+ type: ['string', 'null'],+ },+ metadata: {+ additionalProperties: false,+ description:+ 'Additional structured metadata to keep raw hints (JSON object). Use sparingly.',+ type: ['object', 'null'],+ },+ narrative: {+ description:+ 'Factual story of what happened (chronology, participants, outcomes). Required for recall.',+ type: 'string',+ },+ notes: {+ description:+ 'Short annotations such as agenda, preparation, or quick bullets distinct from narrative.',+ type: ['string', 'null'],+ },+ startsAt: {+ description:+ 'ISO 8601 start time for the activity when specified. Omit if not explicitly provided.',+ format: 'date-time',+ type: ['string', 'null'],+ },+ status: {+ description:+ 'Lifecycle status when mentioned. Use planned/completed/cancelled/ongoing/on_hold/pending. Omit if unclear.',+ enum: ['planned', 'completed', 'cancelled', 'ongoing', 'on_hold', 'pending'],+ type: ['string', 'null'],+ },+ tags: {+ description: 'Optional activity-specific tags or facets.',+ items: { type: 'string' },+ type: ['array', 'null'],+ },+ timezone: {+ description:+ 'IANA timezone string for the start/end times when provided (e.g., "America/New_York").',+ type: ['string', 'null'],+ },+ type: {+ description:+ 'Activity type enum. Choose the closest match; fall back to "other" when unclear.',+ enum: Object.values(ActivityTypeEnum),+ type: 'string',+ },+ },+ required: ['type', 'narrative', 'feedback', 'notes', 'associatedLocations', 'associatedSubjects', 'associatedObjects', 'startsAt', 'endsAt', 'status', 'tags', 'timezone', 'metadata'],+ type: 'object',+ },+ },+ required: [+ 'title',+ 'summary',+ 'details',+ 'memoryType',+ 'memoryCategory',+ 'tags',+ 'withActivity',+ ],+ type: 'object',+ },+ type: 'array',+ },+ } satisfies JSONSchema7['properties'],+ required: ['memories'],+ type: 'object',+ },+ strict: true,+};diff --git a/packages/memory-user-memory/src/schemas/experience.ts b/packages/memory-user-memory/src/schemas/experience.tsindex 4d14a9a45e3..206e4ab6aae 100644--- a/packages/memory-user-memory/src/schemas/experience.ts+++ b/packages/memory-user-memory/src/schemas/experience.ts@@ -8,6 +8,11 @@ import { MemoryTypeSchema } from './common';export const WithExperienceSchema = z.object({action: z.string().describe('Narrative describing actions taken or behaviors exhibited'),keyLearning: z.string().describe('Narrative describing key insights or lessons learned'),+ knowledgeValueScore: z+ .number()+ .min(0)+ .max(1)+ .describe('Numeric score (0-1) describing how reusable and shareable this experience is'),labels: z.array(z.string()).describe('Model generated tags that summarize the experience facets'),possibleOutcome: z.string().describe('Narrative describing potential outcomes or learnings'),problemSolvingScore: z@@ -15,11 +20,6 @@ export const WithExperienceSchema = z.object({.min(0).max(1).describe('Numeric score (0-1) describing how effectively the problem was solved'),- knowledgeValueScore: z- .number()- .min(0)- .max(1)- .describe('Numeric score (0-1) describing how reusable and shareable this experience is'),reasoning: z.string().describe('Narrative describing the thought process or motivations'),scoreConfidence: z.number()diff --git a/packages/memory-user-memory/src/schemas/gatekeeper.ts b/packages/memory-user-memory/src/schemas/gatekeeper.tsindex 110c8e65787..8d6e17b4815 100644--- a/packages/memory-user-memory/src/schemas/gatekeeper.ts+++ b/packages/memory-user-memory/src/schemas/gatekeeper.ts@@ -14,6 +14,7 @@ export type LayerDecision = z.infer<typeof LayerDecisionSchema>;* Gatekeeper result schema for memory layers*/export const GatekeeperResultSchema = z.object({+ activity: LayerDecisionSchema,context: LayerDecisionSchema,experience: LayerDecisionSchema,identity: LayerDecisionSchema,diff --git a/packages/memory-user-memory/src/schemas/index.ts b/packages/memory-user-memory/src/schemas/index.tsindex ecbba85fd84..3227c0fbc59 100644--- a/packages/memory-user-memory/src/schemas/index.ts+++ b/packages/memory-user-memory/src/schemas/index.ts@@ -1,4 +1,5 @@export * from './common';+export * from './activity';export * from './context';export * from './experience';export * from './gatekeeper';diff --git a/packages/memory-user-memory/src/services/extractExecutor.ts b/packages/memory-user-memory/src/services/extractExecutor.tsindex cd1cb7bf489..d79186d8907 100644--- a/packages/memory-user-memory/src/services/extractExecutor.ts+++ b/packages/memory-user-memory/src/services/extractExecutor.ts@@ -12,6 +12,7 @@ import { attributesCommon } from '@lobechat/observability-otel/node';import { LayersEnum } from '@lobechat/types';import {+ ActivityExtractor,ContextExtractor,ExperienceExtractor,IdentityExtractor,@@ -32,6 +33,7 @@ import {} from '../types';const LAYER_ORDER: LayersEnum[] = [+ 'activity' as LayersEnum,'identity' as LayersEnum,'context' as LayersEnum,'preference' as LayersEnum,@@ -39,6 +41,7 @@ const LAYER_ORDER: LayersEnum[] = [];const LAYER_LABEL_MAP: Record<LayersEnum, string> = {+ activity: 'activities',context: 'contexts',experience: 'experiences',identity: 'identities',@@ -61,6 +64,7 @@ export interface MemoryExtractionServiceOptions {export interface MemoryExtractionLayerOutputTypes {[LayersEnum.Context]: Awaited<ReturnType<ContextExtractor['structuredCall']>>;+ [LayersEnum.Activity]: Awaited<ReturnType<ActivityExtractor['structuredCall']>>;[LayersEnum.Experience]: Awaited<ReturnType<ExperienceExtractor['structuredCall']>>;[LayersEnum.Preference]: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>;[LayersEnum.Identity]: Awaited<ReturnType<IdentityExtractor['structuredCall']>>;@@ -79,6 +83,7 @@ export class MemoryExtractionService<RO> {private readonly contextExtractor: ContextExtractor;private readonly experienceExtractor: ExperienceExtractor;private readonly preferenceExtractor: PreferenceExtractor;+ private readonly activityExtractor: ActivityExtractor;private readonly gatekeeperRuntime: ModelRuntime;private readonly layerRuntime: ModelRuntime;@@ -115,6 +120,9 @@ export class MemoryExtractionService<RO> {this.identityExtractor = new IdentityExtractor(buildExtractorConfig(LayersEnum.Identity, 'layer-identity'),);+ this.activityExtractor = new ActivityExtractor(+ buildExtractorConfig(LayersEnum.Activity, 'layer-activity'),+ );this.contextExtractor = new ContextExtractor(buildExtractorConfig(LayersEnum.Context, 'layer-context'),);@@ -214,6 +222,7 @@ export class MemoryExtractionService<RO> {const outputs = await this.runLayers(job, layersToExtract, { ...options });const processedLayersCount = {+ activity: outputs.activity?.data ? outputs.activity?.data?.memories?.length : 0,context: outputs.context?.data ? outputs.context?.data?.memories?.length : 0,experience: outputs.experience?.data ? outputs.experience?.data?.memories?.length : 0,identity: outputs.identity?.data@@ -224,6 +233,7 @@ export class MemoryExtractionService<RO> {preference: outputs.preference?.data ? outputs.preference?.data?.memories?.length : 0,};const processedErrorsCount = {+ activity: outputs.activity?.error ? 1 : 0,context: outputs.context?.error ? 1 : 0,experience: outputs.experience?.error ? 1 : 0,identity: outputs.identity?.error ? 1 : 0,@@ -281,6 +291,15 @@ export class MemoryExtractionService<RO> {);}+ private async runActivityLayer(job: MemoryExtractionJob, options: ExtractorOptions) {+ return this.runLayerExtractor(job, LayersEnum.Activity, () =>+ this.activityExtractor.structuredCall({+ ...options,+ language: options.language ?? 'English',+ }),+ );+ }+private async runExperienceLayer(job: MemoryExtractionJob, options: ExtractorOptions) {return this.runLayerExtractor(job, LayersEnum.Experience, () =>this.experienceExtractor.structuredCall({@@ -347,6 +366,12 @@ export class MemoryExtractionService<RO> {| { error: unknown };break;}+ case LayersEnum.Activity: {+ outputs.activity = result as+ | { data: MemoryExtractionLayerOutputTypes[typeof layer] }+ | { error: unknown };+ break;+ }case LayersEnum.Experience: {outputs.experience = result as| { data: MemoryExtractionLayerOutputTypes[typeof layer] }@@ -374,6 +399,7 @@ export class MemoryExtractionService<RO> {await Promise.all(([+ LayersEnum.Activity,LayersEnum.Context,LayersEnum.Experience,LayersEnum.Preference,@@ -407,6 +433,9 @@ export class MemoryExtractionService<RO> {case LayersEnum.Context: {return await this.runContextLayer(job, options);}+ case LayersEnum.Activity: {+ return await this.runActivityLayer(job, options);+ }case LayersEnum.Experience: {return await this.runExperienceLayer(job, options);}diff --git a/packages/memory-user-memory/src/types.ts b/packages/memory-user-memory/src/types.tsindex 9ea974f9552..3d4f72c88fd 100644--- a/packages/memory-user-memory/src/types.ts+++ b/packages/memory-user-memory/src/types.ts@@ -6,6 +6,7 @@ import type {import type { LayersEnum, MemorySourceType } from '@lobechat/types';import type {+ ActivityExtractor,ContextExtractor,ExperienceExtractor,IdentityExtractor,@@ -14,6 +15,7 @@ import type {export type MemoryExtractionAgent =| 'gatekeeper'+ | 'layer-activity'| 'layer-context'| 'layer-experience'| 'layer-identity'@@ -124,6 +126,10 @@ export interface PersistedMemoryResult {}export type MemoryExtractionLayerOutputs = Partial<{+ activity: {+ data?: Awaited<ReturnType<ActivityExtractor['structuredCall']>>;+ error?: unknown;+ };context: {data?: Awaited<ReturnType<ContextExtractor['structuredCall']>>;error?: unknown;@@ -143,6 +149,7 @@ export type MemoryExtractionLayerOutputs = Partial<{}>;export interface GatekeeperDecision {+ activity: MemoryLayerDecision;context: MemoryLayerDecision;experience: MemoryLayerDecision;identity: MemoryLayerDecision;diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex af3fac5a8be..c67a04db0a9 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -10,7 +10,7 @@ import {UserSystemAgentConfig,} from './user/settings';-export type GlobalMemoryLayer = 'context' | 'experience' | 'identity' | 'preference';+export type GlobalMemoryLayer = 'activity' | 'context' | 'experience' | 'identity' | 'preference';export interface MemoryAgentPublicConfig {baseURL?: string;diff --git a/packages/types/src/userMemory/layers.ts b/packages/types/src/userMemory/layers.tsindex eb686d9a975..f843f02d6ce 100644--- a/packages/types/src/userMemory/layers.ts+++ b/packages/types/src/userMemory/layers.ts@@ -22,6 +22,26 @@ export enum UserMemoryContextSubjectType {}export const CONTEXT_SUBJECT_TYPES = Object.values(UserMemoryContextSubjectType);+export interface UserMemoryAssociatedLocation {+ address?: string | null;+ extra?: Record<string, unknown> | null;+ name?: string | null;+ tags?: string[] | null;+ type?: string | null;+}++export interface UserMemoryAssociatedObject {+ extra?: Record<string, unknown> | null;+ name?: string;+ type?: string | null;+}++export interface UserMemoryAssociatedSubject {+ extra?: Record<string, unknown> | null;+ name?: string;+ type?: string | null;+}+export interface UserMemoryContext extends UserMemoryTimestamps {associatedObjects:| {@@ -112,3 +132,35 @@ export type UserMemoryPreferenceWithoutVectors = Omit<>;export type UserMemoryPreferencesListItem = Omit<UserMemoryPreferenceWithoutVectors, 'suggestions'>;++export interface UserMemoryActivity extends UserMemoryTimestamps {+ associatedLocations: UserMemoryAssociatedLocation[] | null;+ associatedObjects: UserMemoryAssociatedObject[] | null;+ associatedSubjects: UserMemoryAssociatedSubject[] | null;+ endsAt: Date | null;+ feedback: string | null;+ feedbackVector: number[] | null;+ id: string;+ metadata: Record<string, unknown> | null;+ narrative: string | null;+ narrativeVector: number[] | null;+ notes: string | null;+ startsAt: Date | null;+ status: string | null;+ tags: string[] | null;+ timezone: string | null;+ type: string | null;+ userId: string | null;+ userMemoryId: string | null;+}++// eslint-disable-next-line @typescript-eslint/no-empty-interface+export type UserMemoryActivityWithoutVectors = Omit<+ UserMemoryActivity,+ 'narrativeVector' | 'feedbackVector'+>;++export type UserMemoryActivitiesListItem = Omit<+ UserMemoryActivityWithoutVectors,+ 'feedback' | 'narrative' | 'notes'+>;diff --git a/packages/types/src/userMemory/list.ts b/packages/types/src/userMemory/list.tsindex ae97238d1a2..4c919abd21f 100644--- a/packages/types/src/userMemory/list.ts+++ b/packages/types/src/userMemory/list.ts@@ -5,6 +5,8 @@ import {UserMemoryContextsListItem,UserMemoryExperiencesListItem,UserMemoryPreferencesListItem,+ UserMemoryActivitiesListItem,+ UserMemoryActivityWithoutVectors,} from './layers'import {UserMemoryIdentityWithoutVectors,@@ -87,14 +89,30 @@ export interface IdentityMemoryDetail {sourceType?: MemorySourceType;}+export interface ActivityMemorySimple {+ activity: UserMemoryActivitiesListItem;+ layer: LayersEnum.Activity;+ memory: UserMemoryListItem;+}++export interface ActivityMemoryDetail {+ activity: UserMemoryActivityWithoutVectors;+ layer: LayersEnum.Activity;+ memory: UserMemoryWithoutVectors;+ source?: MemorySource;+ sourceType?: MemorySourceType;+}+export type UserMemoryItemSimple =| ContextMemorySimple| ExperienceMemorySimple| IdentityMemorySimple- | PreferenceMemorySimple;+ | PreferenceMemorySimple+ | ActivityMemorySimple;export type UserMemoryDetail =| ContextMemoryDetail| ExperienceMemoryDetail| IdentityMemoryDetail- | PreferenceMemoryDetail;+ | PreferenceMemoryDetail+ | ActivityMemoryDetail;diff --git a/packages/types/src/userMemory/shared.ts b/packages/types/src/userMemory/shared.tsindex 5f8143591f9..057edd0f4c0 100644--- a/packages/types/src/userMemory/shared.ts+++ b/packages/types/src/userMemory/shared.ts@@ -46,6 +46,7 @@ export enum IdentityTypeEnum {export const IDENTITY_TYPES = Object.values(IdentityTypeEnum);export enum LayersEnum {+ Activity = 'activity',Context = 'context',Experience = 'experience',Identity = 'identity',@@ -80,7 +81,6 @@ export const CONTEXT_STATUS = Object.values(ContextStatusEnum);/*** Shared types for memory list queries*/-export interface BaseListParams {order?: 'asc' | 'desc';page?: number;@@ -106,3 +106,24 @@ export interface BaseListItem {type: string | null;updatedAt: Date;}++export enum ActivityTypeEnum {+ Appointment = 'appointment',+ Call = 'call',+ Celebration = 'celebration',+ Class = 'class',+ Conference = 'conference',+ Errand = 'errand',+ Event = 'event',+ Exercise = 'exercise',+ Meal = 'meal',+ Meeting = 'meeting',+ Other = 'other',+ ProjectSession = 'project-session',+ Social = 'social',+ Task = 'task',+ Trip = 'trip',+ Workshop = 'workshop',+}++export const ACTIVITY_TYPES = Object.values(ActivityTypeEnum);diff --git a/packages/types/src/userMemory/trace.ts b/packages/types/src/userMemory/trace.tsindex 42eefb2c75f..5b7d67bdcb6 100644--- a/packages/types/src/userMemory/trace.ts+++ b/packages/types/src/userMemory/trace.ts@@ -3,6 +3,7 @@ import type { MemorySourceType } from './list';export type MemoryExtractionAgent =| 'gatekeeper'+ | 'layer-activity'| 'layer-context'| 'layer-experience'| 'layer-identity'diff --git a/packages/types/src/util.ts b/packages/types/src/util.tsindex 87ec9c0c0c3..6181f57e7fc 100644--- a/packages/types/src/util.ts+++ b/packages/types/src/util.ts@@ -1,2 +1,10 @@export type Primitive = number | string | boolean | undefined | null | any[];-export type Optional<T, K extends keyof T> = { [P in K]?: T[P] } & { [P in Exclude<keyof T, K>]: T[P] extends Primitive ? T[P] : Optional<T[P], keyof T[P] & K> };+type OptionalKeys<T> = { [P in keyof T]-?: undefined extends T[P] ? P : never }[keyof T];+type OptionalField<T, P extends keyof T, K extends keyof T> = T[P] extends Primitive+ ? T[P]+ : Optional<T[P], keyof T[P] & K>;++export type Optional<T, K extends keyof T> = T extends null | undefined+ ? T+ : Partial<Pick<T, K | OptionalKeys<T>>> &+ { [P in Exclude<keyof T, K | OptionalKeys<T>>]: OptionalField<T, P, K> };diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.tsindex 696554ea9f4..5fff4b261ff 100644--- a/src/libs/next/proxy/define-config.ts+++ b/src/libs/next/proxy/define-config.ts@@ -162,6 +162,7 @@ export function defineConfig() {'/api/webhooks(.*)','/api/workflows(.*)','/api/agent(.*)',+ '/api/dev(.*)','/webapi(.*)','/trpc(.*)',// better authdiff --git a/src/server/globalConfig/parseMemoryExtractionConfig.ts b/src/server/globalConfig/parseMemoryExtractionConfig.tsindex 19ac0d9b5d6..33904beac83 100644--- a/src/server/globalConfig/parseMemoryExtractionConfig.ts+++ b/src/server/globalConfig/parseMemoryExtractionConfig.ts@@ -8,7 +8,13 @@ import {type MemoryLayerExtractorPublicConfig,} from '@/types/serverConfig';-const MEMORY_LAYERS: GlobalMemoryLayer[] = ['context', 'experience', 'identity', 'preference'];+const MEMORY_LAYERS: GlobalMemoryLayer[] = [+ 'activity',+ 'context',+ 'experience',+ 'identity',+ 'preference',+];const parseTokenLimitEnv = (value?: string) => {if (value === undefined) return undefined;diff --git a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.tsindex ca9d8abc906..06c704949c4 100644--- a/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts+++ b/src/server/services/memory/userMemory/__tests__/extract.runtime.test.ts@@ -26,6 +26,7 @@ const createExecutor = (privateOverrides?: Partial<MemoryExtractionPrivateConfigagentLayerExtractor: {contextLimit: 2048,layers: {+ activity: 'layer-act',context: 'layer-ctx',experience: 'layer-exp',identity: 'layer-id',@@ -38,6 +39,7 @@ const createExecutor = (privateOverrides?: Partial<MemoryExtractionPrivateConfigembedding: { model: 'embed-1', provider: 'provider-e' },featureFlags: { enableBenchmarkLoCoMo: false },observabilityS3: { enabled: false },+ webhookHeaders: {},};const serverConfig = {diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.tsindex ab6ef963c27..839d3e81143 100644--- a/src/server/services/memory/userMemory/extract.ts+++ b/src/server/services/memory/userMemory/extract.ts@@ -90,6 +90,7 @@ const LAYER_ALIAS = new Set<LayersEnum>([]);const LAYER_LABEL_MAP: Record<LayersEnum, string> = {+ [LayersEnum.Activity]: 'activities',[LayersEnum.Context]: 'contexts',[LayersEnum.Experience]: 'experiences',[LayersEnum.Identity]: 'identities',@@ -267,6 +268,7 @@ const resolveLayerModels = (layers: Partial<Record<GlobalMemoryLayer, string>> | undefined,fallback: Record<GlobalMemoryLayer, string>,): Record<LayersEnum, string> => ({+ activity: layers?.activity ?? fallback.activity,context: layers?.context ?? fallback.context,experience: layers?.experience ?? fallback.experience,identity: layers?.identity ?? fallback.identity,@@ -569,6 +571,79 @@ export class MemoryExtractionExecutor {});}+ async persistActivityMemories(+ job: MemoryExtractionJob,+ messageIds: string[],+ result: NonNullable<MemoryExtractionResult['outputs']['activity']>['data'],+ runtime: ModelRuntime,+ model: string,+ tokenLimit: number | undefined,+ db: Awaited<ReturnType<typeof getServerDB>>,+ ) {+ const insertedIds: string[] = [];+ const userMemoryModel = new UserMemoryModel(db, job.userId);++ for (const item of result?.memories ?? []) {+ const activityTags = item.withActivity?.tags ?? item.tags;+ const associatedObjects = UserMemoryModel.parseAssociatedObjects(+ item.withActivity?.associatedObjects,+ );+ const associatedSubjects = UserMemoryModel.parseAssociatedSubjects(+ item.withActivity?.associatedSubjects,+ );+ const associatedLocations = UserMemoryModel.parseAssociatedLocations(+ item.withActivity?.associatedLocations,+ );+ const [summaryVector, detailsVector, narrativeVector, feedbackVector] =+ await this.generateEmbeddings(+ runtime,+ model,+ [item.summary, item.details, item.withActivity?.narrative, item.withActivity?.feedback],+ tokenLimit,+ );+ const baseMetadata = this.buildBaseMetadata(+ job,+ messageIds,+ LayersEnum.Activity,+ activityTags,+ );++ const { memory } = await userMemoryModel.createActivityMemory({+ activity: {+ associatedLocations: associatedLocations.length > 0 ? associatedLocations : [],+ associatedObjects: associatedObjects.length > 0 ? associatedObjects : [],+ associatedSubjects: associatedSubjects.length > 0 ? associatedSubjects : [],+ capturedAt: job.sourceUpdatedAt,+ endsAt: UserMemoryModel.parseDateFromString(item.withActivity?.endsAt),+ feedback: item.withActivity?.feedback ?? null,+ feedbackVector: feedbackVector ?? null,+ metadata: baseMetadata,+ narrative: item.withActivity?.narrative ?? null,+ narrativeVector: narrativeVector ?? null,+ notes: item.withActivity?.notes ?? null,+ startsAt: UserMemoryModel.parseDateFromString(item.withActivity?.startsAt),+ status: item.withActivity?.status ?? 'pending',+ tags: activityTags ?? null,+ timezone: item.withActivity?.timezone ?? null,+ type: item.withActivity?.type ?? 'other',+ },+ capturedAt: job.sourceUpdatedAt,+ details: item.details ?? '',+ detailsEmbedding: detailsVector ?? undefined,+ memoryCategory: item.memoryCategory ?? null,+ memoryLayer: (item.memoryLayer as LayersEnum) ?? LayersEnum.Activity,+ memoryType: (item.memoryType as TypesEnum) ?? TypesEnum.Activity,+ summary: item.summary ?? '',+ summaryEmbedding: summaryVector ?? undefined,+ title: item.title ?? '',+ });++ insertedIds.push(memory.id);+ }++ return insertedIds;+ }+async persistContextMemories(job: MemoryExtractionJob,messageIds: string[],@@ -601,7 +676,7 @@ export class MemoryExtractionExecutor {associatedObjects: UserMemoryModel.parseAssociatedObjects(item.withContext?.associatedObjects,),- associatedSubjects: UserMemoryModel.parseAssociatedObjects(+ associatedSubjects: UserMemoryModel.parseAssociatedSubjects(item.withContext?.associatedSubjects,),capturedAt: job.sourceUpdatedAt,@@ -923,13 +998,14 @@ export class MemoryExtractionExecutor {if (vector) {const retrieved = await userMemoryModel.searchWithEmbedding({embedding: vector,- limits: { contexts: topK, experiences: topK, preferences: topK },+ limits: { activities: topK, contexts: topK, experiences: topK, preferences: topK },});return retrieved;}return {+ activities: [],contexts: [],experiences: [],preferences: [],@@ -1563,6 +1639,24 @@ export class MemoryExtractionExecutor {);};+ const activityOutput = extraction.outputs.activity;+ if (activityOutput?.error) {+ appendError(LayersEnum.Activity, 'extract', activityOutput.error);+ }+ if (activityOutput?.data) {+ await persistWithSpan(LayersEnum.Activity, () =>+ this.persistActivityMemories(+ job,+ messageIds,+ activityOutput.data,+ runtimes.embeddings,+ this.modelConfig.embeddingsModel,+ this.embeddingContextLimit,+ db,+ ),+ );+ }+const contextOutput = extraction.outputs.context;if (contextOutput?.error) {appendError(LayersEnum.Context, 'extract', contextOutput.error);@@ -1636,7 +1730,7 @@ export class MemoryExtractionExecutor {}if (errors.length) {- const detail = errors.map((error) => error.message).join('; ');+ const detail = errors.map((error) => `${error.message}${error.cause ? `: ${error.cause}` : ''}`).join('; ');throw new AggregateError(errors, `Memory extraction encountered layer errors: ${detail}`);}@@ -1825,14 +1919,21 @@ export class MemoryExtractionExecutor {userId: params.userId,});+ const latestCreatedAt = params.parts.reduce<Date | undefined>((latest, part) => {+ if (!part.createdAt) return latest;++ const date = new Date(part.createdAt);+ if (Number.isNaN(date.getTime())) return latest;++ return !latest || date > latest ? date : latest;+ }, undefined);+extractionJob = {force: params.forceAll ?? true,layers: params.layers,source: params.source,sourceId: params.sourceId,- sourceUpdatedAt: params.parts.at(-1)?.createdAt- ? new Date(params.parts.at(-1)!.createdAt as Date)- : new Date(),+ sourceUpdatedAt: latestCreatedAt ?? new Date(),userId: params.userId,};@@ -1898,7 +1999,7 @@ export class MemoryExtractionExecutor {language,retrievedContexts: [trimmedContext],retrievedIdentitiesContext: undefined,- sessionDate: new Date().toISOString(),+ sessionDate: (latestCreatedAt ?? new Date()).toISOString(),topK: 10,username:userState.fullName || `${userState.firstName} ${userState.lastName}`.trim() || 'User',