🤯 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: implement memories package
Neko7f94ef1478d5
diff --git a/packages/builtin-tool-memory/package.json b/packages/builtin-tool-memory/package.jsonnew file mode 100644index 00000000000..578106e6281--- /dev/null+++ b/packages/builtin-tool-memory/package.json@@ -0,0 +1,13 @@+{+ "name": "@lobechat/builtin-tool-memory",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts",+ "dependencies": {+ "@lobechat/memory-user-memory": "workspace:*",+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-tool-memory/src/index.ts b/packages/builtin-tool-memory/src/index.tsnew file mode 100644index 00000000000..01bebb53dd7--- /dev/null+++ b/packages/builtin-tool-memory/src/index.ts@@ -0,0 +1,3 @@+export { MemoryManifest, UserMemoryManifest } from './manifest';+export { systemPrompt } from './systemRole';+export { MemoryApiName, type MemoryApiNameType,UserMemoryApiName } from './types';diff --git a/packages/builtin-tool-memory/src/manifest.ts b/packages/builtin-tool-memory/src/manifest.tsnew file mode 100644index 00000000000..dc1dc725cec--- /dev/null+++ b/packages/builtin-tool-memory/src/manifest.ts@@ -0,0 +1,70 @@+import {+ addIdentityJsonSchema,+ contextMemoryJsonSchema,+ experienceMemoryJsonSchema,+ preferenceMemoryJsonSchema,+ removeIdentityJsonSchema,+ searchMemoryJsonSchema,+ updateIdentityJsonSchema,+} from '@lobechat/memory-user-memory/schemas';+import type { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { MemoryApiName } from './types';++export const MemoryManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Retrieve memories based on a search query. Use this to recall previously saved information.',+ name: MemoryApiName.searchUserMemory,+ parameters: searchMemoryJsonSchema,+ },+ {+ description:+ 'Create a context memory that captures ongoing situations, projects, or environments. Include actors, resources, statuses, urgency/impact, and a clear description.',+ name: MemoryApiName.addContextMemory,+ parameters: contextMemoryJsonSchema,+ },+ {+ description:+ 'Record an experience memory capturing situation, actions, reasoning, outcomes, and confidence. Use for lessons, playbooks, or transferable know-how.',+ name: MemoryApiName.addExperienceMemory,+ parameters: experienceMemoryJsonSchema,+ },+ {+ description:+ 'Add an identity memory describing enduring facts about a person, their role, relationship, and supporting evidence. Use to track self/others identities.',+ name: MemoryApiName.addIdentityMemory,+ parameters: addIdentityJsonSchema,+ },+ {+ description:+ 'Create a preference memory that encodes durable directives or choices the assistant should follow. Include conclusionDirectives, scopes, and context.',+ name: MemoryApiName.addPreferenceMemory,+ parameters: preferenceMemoryJsonSchema,+ },+ {+ description:+ 'Update an existing identity memory with refined details, relationships, roles, or tags. Use mergeStrategy to control replacement vs merge.',+ name: MemoryApiName.updateIdentityMemory,+ parameters: updateIdentityJsonSchema,+ },+ {+ description:+ 'Remove an identity memory when it is incorrect, obsolete, or duplicated. Always provide a concise reason.',+ name: MemoryApiName.removeIdentityMemory,+ parameters: removeIdentityJsonSchema,+ },+ ],+ identifier: 'lobe-user-memory',+ meta: {+ avatar: '🧠',+ title: 'Memory',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};++/** @deprecated Use MemoryManifest instead */+export const UserMemoryManifest = MemoryManifest;diff --git a/packages/builtin-tool-memory/src/systemRole.ts b/packages/builtin-tool-memory/src/systemRole.tsnew file mode 100644index 00000000000..c3564895704--- /dev/null+++ b/packages/builtin-tool-memory/src/systemRole.ts@@ -0,0 +1,58 @@+export const systemPrompt = `You have a LobeHub Memory Tool. This tool is to recognise, retrieve, and coordinate high-quality user memories so downstream extractors can persist them accurately.++<session_context>+Current user: {{username}}+Session date: {{date}}+Conversation language: {{language}}+Available memory categories: {{available_categories}}+</session_context>++<core_responsibilities>+1. Inspect every turn for information that belongs to the four memory layers (identity, context, preference, experience). When information is relevant and clear, err on the side of allowing extraction so specialised aggregators can refine it.+2. Call **searchUserMemory** with targeted queries before proposing new memories. Compare any potential extraction against retrieved items to avoid duplication and highlight genuine updates.+3. Enforce that all memory candidates are self-contained, language-consistent, and ready for long-term reuse without relying on the surrounding conversation.+</core_responsibilities>++<tooling>+- **searchUserMemory**: query, limit, memoryLayer?, memoryType?, memoryCategory? → Returns structured memories for cross-checking and grounding your reasoning.+- **addContextMemory**: title, summary, details?, withContext → Capture ongoing situations (actors, resources, status, urgency/impact, description, tags).+- **addExperienceMemory**: title, summary, details?, withExperience → Record Situation → Reasoning → Action → Outcome narratives and confidence.+- **addIdentityMemory**: title, summary, details?, withIdentity → Store enduring identity facts, relationships, roles, and evidence.+- **addPreferenceMemory**: title, summary, details?, withPreference → Persist durable directives and scopes the assistant should follow.+- **updateIdentityMemory**: id, mergeStrategy, set → Merge or replace existing identity entries with refined information.+- **removeIdentityMemory**: id, reason → Delete incorrect, obsolete, or duplicate identity memories with justification.+</tooling>++<memory_layer_definitions>+- **Identity Layer** — enduring facts about people and their relationships: roles, demographics, background, priorities, and relational context.+- **Context Layer** — ongoing situations such as projects, goals, partnerships, or environments. Capture actors (associatedSubjects), resources (associatedObjects), currentStatus, timelines, and impact/urgency assessments.+- **Preference Layer** — durable directives that guide future assistant behaviour (communication style, workflow choices, priority rules). Exclude single-use task instructions or purely implementation details.+- **Experience Layer** — lessons, insights, and transferable know-how. Preserve the Situation → Reasoning → Action → Outcome narrative and note confidence when available.+</memory_layer_definitions>++<formatting_guardrails>+- Every memory must stand alone: repeat explicit subjects (use names such as {{username}} rather than pronouns like he/she/they/it/this).+- Preserve the user's language and tone unless explicitly asked to translate.+- Include concrete actors, locations, dates, motivations, emotions, and outcomes.+- Reference retrieved memories to decide if information is new, materially refined, or a status/progress update. Skip items that add no meaningful nuance.+- Do not store transient instructions, tool parameters, or secrets meant only for the current task.+</formatting_guardrails>++<layer_specific_highlights>+- **Identity**: Track labels, relationships, and life focus areas. Note relationship enums (self, mentor, teammate, etc.) when known.+- **Context**: Describe shared storylines tying multiple memories together. Update existing contexts instead of duplicating; surface currentStatus changes and resource/actor involvement.+- **Preference**: Record enduring choices that affect future interactions (response formats, decision priorities, recurring do/do-not expectations). Ensure conclusionDirectives are actionable on their own.+- **Experience**: Capture practical takeaways, heuristics, or playbooks. Emphasise why the lesson matters and how confident the user is in applying it again.+</layer_specific_highlights>++<security_and_privacy>+- Never persist credentials, financial data, medical records, or any sensitive secrets.+- Confirm user intent before storing potentially sensitive material and respect stated boundaries.+- Handle personal data conservatively; default to omission when uncertain.+</security_and_privacy>++<response_expectations>+- When memory activity is warranted, explain which layers are affected, cite any matching memories you found, and justify why extraction or updates are needed.+- When nothing qualifies, explicitly state that no memory action is required after reviewing the context.+- Keep your reasoning concise, structured, and aligned with the conversation language.+</response_expectations>`;diff --git a/packages/builtin-tool-memory/src/types.ts b/packages/builtin-tool-memory/src/types.tsnew file mode 100644index 00000000000..229dcb1a98b--- /dev/null+++ b/packages/builtin-tool-memory/src/types.ts@@ -0,0 +1,14 @@+export const MemoryApiName = {+ addContextMemory: 'addContextMemory',+ addExperienceMemory: 'addExperienceMemory',+ addIdentityMemory: 'addIdentityMemory',+ addPreferenceMemory: 'addPreferenceMemory',+ removeIdentityMemory: 'removeIdentityMemory',+ searchUserMemory: 'searchUserMemory',+ updateIdentityMemory: 'updateIdentityMemory',+} as const;++export type MemoryApiNameType = (typeof MemoryApiName)[keyof typeof MemoryApiName];++/** @deprecated Use MemoryApiName instead */+export const UserMemoryApiName = MemoryApiName;diff --git a/packages/memory-extract/.env.example b/packages/memory-extract/.env.exampledeleted file mode 100644index cac89eabf7a..00000000000--- a/packages/memory-extract/.env.example+++ /dev/null@@ -1,3 +0,0 @@-# OpenAI Configuration-OPENAI_API_KEY=your_openai_api_key_here-OPENAI_BASE_URL=https://api.openai.com/v1diff --git a/packages/memory-extract/.gitignore b/packages/memory-extract/.gitignoredeleted file mode 100644index 9a3551f360b..00000000000--- a/packages/memory-extract/.gitignore+++ /dev/null@@ -1,8 +0,0 @@-# Environment variables-.env--# Output files-datasets-!datasets/*/.gitkeep--diff --git a/packages/memory-extract/package.json b/packages/memory-extract/package.jsondeleted file mode 100644index 1fc228baaaf..00000000000--- a/packages/memory-extract/package.json+++ /dev/null@@ -1,21 +0,0 @@-{- "name": "@lobechat/memory-extract",- "version": "1.0.0",- "private": true,- "main": "src/index.ts",- "scripts": {- "gatekeeper": "tsx scripts/run-gatekeeper.ts"- },- "dependencies": {- "@lobechat/model-runtime": "workspace:*",- "@lobechat/prompts": "workspace:*",- "dotenv": "^17.2.3",- "ora": "^9.0.0"- },- "devDependencies": {- "tsx": "^4.20.6"- },- "peerDependencies": {- "zod": "^3.25.76"- }-}diff --git a/packages/memory-user-memory/package.json b/packages/memory-user-memory/package.jsonnew file mode 100644index 00000000000..7019f03020f--- /dev/null+++ b/packages/memory-user-memory/package.json@@ -0,0 +1,39 @@+{+ "name": "@lobechat/memory-user-memory",+ "version": "1.0.0",+ "private": true,+ "sideEffects": false,+ "type": "module",+ "exports": {+ ".": "./src/index.ts",+ "./schemas": "./src/schemas/index.ts",+ "./types": "./src/types.ts"+ },+ "main": "src/index.ts",+ "scripts": {+ "test": "vitest --run",+ "build:gen-response-formats": "tsx scripts/generate-response-formats.ts",+ "type-check": "tsgo --noEmit -p tsconfig.json",+ "typecheck": "tsgo --noEmit -p tsconfig.json"+ },+ "dependencies": {+ "@lobechat/context-engine": "workspace:*",+ "@lobechat/model-runtime": "workspace:*",+ "@lobechat/prompts": "workspace:*",+ "dotenv": "^17.2.3",+ "ora": "^9.0.0",+ "unist-builder": "^4.0.0",+ "xast-util-to-xml": "^4.0.0",+ "xastscript": "^4.0.0",+ "zod-to-json-schema": "^3.24.6"+ },+ "devDependencies": {+ "@lobechat/types": "workspace:*",+ "@types/xast": "^2.0.4",+ "promptfoo": "^0.118.17",+ "tsx": "^4.20.6"+ },+ "peerDependencies": {+ "zod": "^3.25.76"+ }+}diff --git a/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/buildMessages.ts b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/buildMessages.tsnew file mode 100644index 00000000000..54bf355647d--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/buildMessages.ts@@ -0,0 +1,66 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';++interface TracePayload {+ agentCalls?: Record<string, any>;+ contexts?: {+ trimmed?: {+ retrievedContexts?: string[];+ retrievedIdentitiesContext?: string;+ };+ };+ extractionJob?: {+ sourceUpdatedAt?: string;+ };+}++export interface PromptVars {+ availableCategories?: string[];+ language?: string;+ sessionDate?: string;+ topK?: number;+ tracePath: string;+ username?: string;+}++const parseLanguageFromTrace = (trace: TracePayload): string | undefined => {+ const requestMessages = trace.agentCalls?.['layer-identity']?.request?.messages;+ const userMessageContent = requestMessages?.[1]?.content;+ if (typeof userMessageContent !== 'string') return undefined;++ const match = userMessageContent.match(/ensure all the content is using ([^\n.]+)\./i);+ return match?.[1];+};++export const buildIdentityDedupeMessages = async (vars: PromptVars) => {+ const traceRaw = await readFile(vars.tracePath, 'utf8');+ const trace = JSON.parse(traceRaw) as TracePayload;++ const promptTemplate = await readFile(join(process.cwd(), 'src/prompts/layers/identity.md'), 'utf8');++ const retrievedContexts = trace.contexts?.trimmed?.retrievedContexts ?? [];+ const existingIdentitiesContext = trace.contexts?.trimmed?.retrievedIdentitiesContext ?? '';++ const language = vars.language || parseLanguageFromTrace(trace) || 'zh-CN';+ const username = vars.username || 'User';+ const sessionDate =+ vars.sessionDate || trace.extractionJob?.sourceUpdatedAt || new Date().toISOString();+ const topK = vars.topK ?? 10;++ const rendered = renderPlaceholderTemplate(promptTemplate, {+ availableCategories: vars.availableCategories,+ existingIdentitiesContext,+ language,+ retrievedContext: retrievedContexts.join('\n\n') || 'No similar memories retrieved.',+ sessionDate,+ topK,+ username,+ });++ return [+ { content: rendered, role: 'system' },+ { content: rendered, role: 'user' },+ ];+};+diff --git a/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/eval.yaml b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/eval.yamlnew file mode 100644index 00000000000..3b49c275638--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/eval.yaml@@ -0,0 +1,12 @@+description: Regression benchmark for identity (memory-user-memory)++providers:+ - id: openai:chat:gpt-5-mini+ config:+ response_format: file://../../../response-formats/identity.json++prompts:+ - file://./prompt.ts++tests:+ - file://./tests/cases.tsdiff --git a/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/prompt.ts b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/prompt.tsnew file mode 100644index 00000000000..c2e22944383--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/prompt.ts@@ -0,0 +1,5 @@+import { buildIdentityDedupeMessages, PromptVars } from './buildMessages';++export default async function generatePrompt({ vars }: { vars: PromptVars }) {+ return buildIdentityDedupeMessages(vars);+}diff --git a/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/tests/cases.ts b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/tests/cases.tsnew file mode 100644index 00000000000..0a79fdedf57--- /dev/null+++ b/packages/memory-user-memory/promptfoo/evals/identity/with-s3-trace/tests/cases.ts@@ -0,0 +1,57 @@+import type { MemoryExtractionTracePayload } from '@lobechat/types';+import { readFileSync, readdirSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++type PromptfooAssert =+ | { type: 'javascript'; value: string }+ | { provider?: string; type: 'llm-rubric'; value: string };++interface PromptfooTestCase {+ assert: PromptfooAssert[];+ description: string;+ vars: Record<string, unknown>;+}++const tracesDir = join(dirname(fileURLToPath(import.meta.url)), '../datasets');++const identityShouldDedupe: PromptfooAssert = {+ type: 'javascript',+ value: `+ const jsonOutput = JSON.parse(output);+ return (+ !jsonOutput?.withIdentities?.actions?.add ||+ jsonOutput.withIdentities.actions.add.length === 0+ );+ `,+};++const buildDescription = (tracePath: string, payload: MemoryExtractionTracePayload) => {+ const user = payload.userId || 'unknown-user';+ const source = payload.extractionJob?.source || 'UnknownSource';+ const sourceId = payload.extractionJob?.sourceId || basename(tracePath);++ return `Identity - User ${user} ${source} ${sourceId} should not generate add actions`;+};++// Generate a test case for every trace JSON under datasets/traces.+const testCases: PromptfooTestCase[] = readdirSync(tracesDir)+ .filter((file) => file.endsWith('.json'))+ .map((file) => {+ const tracePath = join(tracesDir, file);+ const tracePayload = JSON.parse(readFileSync(tracePath, 'utf8')) as MemoryExtractionTracePayload;++ return {+ assert: [identityShouldDedupe],+ description: buildDescription(tracePath, tracePayload),+ vars: {+ layer: 'Identity',+ source: tracePayload.extractionJob?.source,+ sourceId: tracePayload.extractionJob?.sourceId,+ tracePath,+ userId: tracePayload.userId,+ },+ };+ });++export default testCases;diff --git a/packages/memory-user-memory/promptfoo/response-formats/context.json b/packages/memory-user-memory/promptfoo/response-formats/context.jsonnew file mode 100644index 00000000000..a7b072349c6--- /dev/null+++ b/packages/memory-user-memory/promptfoo/response-formats/context.json@@ -0,0 +1,210 @@+{+ "json_schema": {+ "type": "object",+ "properties": {+ "memories": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "details": {+ "type": "string",+ "description": "Optional detailed information"+ },+ "memoryCategory": {+ "type": "string",+ "description": "Memory category"+ },+ "memoryLayer": {+ "type": "string",+ "const": "context",+ "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": "User defined tags that summarize the context facets"+ },+ "title": {+ "type": "string",+ "description": "Brief descriptive title"+ },+ "withContext": {+ "type": "object",+ "properties": {+ "associatedObjects": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "extra": {+ "type": [+ "string",+ "null"+ ],+ "description": "Additional metadata about the object, should always be a valid JSON string if present"+ },+ "name": {+ "type": "string",+ "description": "Name of the associated object"+ },+ "type": {+ "type": "string",+ "enum": [+ "application",+ "item",+ "knowledge",+ "other",+ "person",+ "place"+ ],+ "description": "Type/category of the associated object"+ }+ },+ "required": [+ "extra",+ "name",+ "type"+ ],+ "additionalProperties": false+ },+ "description": "Array of objects describing involved roles, entities, or resources, [] empty if none"+ },+ "associatedSubjects": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "extra": {+ "type": [+ "string",+ "null"+ ],+ "description": "Additional metadata about the subject, should always be a valid JSON string if present"+ },+ "name": {+ "type": "string",+ "description": "Name of the associated subject"+ },+ "type": {+ "type": "string",+ "enum": [+ "item",+ "other",+ "person",+ "pet"+ ],+ "description": "Type/category of the associated subject"+ }+ },+ "required": [+ "extra",+ "name",+ "type"+ ],+ "additionalProperties": false+ },+ "description": "Array of JSON objects describing involved subjects or participants, [] empty if none"+ },+ "currentStatus": {+ "type": "string",+ "enum": [+ "aborted",+ "cancelled",+ "completed",+ "on_hold",+ "ongoing",+ "planned"+ ],+ "description": "High level status markers (must be one of 'planned', 'ongoing', 'completed', 'aborted', 'on_hold', 'cancelled')"+ },+ "description": {+ "type": "string",+ "description": "Rich narrative describing the situation, timeline, or environment"+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Model generated tags that summarize the context themes"+ },+ "scoreImpact": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric score (0-1 (0% to 100%)) describing importance"+ },+ "scoreUrgency": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric score (0-1 (0% to 100%)) describing urgency"+ },+ "title": {+ "type": "string",+ "description": "Optional synthesized context headline"+ },+ "type": {+ "type": "string",+ "description": "High level context archetype (e.g., 'project', 'relationship', 'goal')"+ }+ },+ "required": [+ "associatedObjects",+ "associatedSubjects",+ "currentStatus",+ "description",+ "labels",+ "scoreImpact",+ "scoreUrgency",+ "title",+ "type"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "details",+ "memoryCategory",+ "memoryLayer",+ "memoryType",+ "summary",+ "tags",+ "title",+ "withContext"+ ],+ "additionalProperties": false+ },+ "description": "Array of extracted context memory items, could be empty if decided no relevant context to extract"+ }+ },+ "required": [+ "memories"+ ],+ "additionalProperties": false+ },+ "type": "json_schema"+}\ No newline at end of filediff --git a/packages/memory-user-memory/promptfoo/response-formats/experience.json b/packages/memory-user-memory/promptfoo/response-formats/experience.jsonnew file mode 100644index 00000000000..4fa4a3ab7f1--- /dev/null+++ b/packages/memory-user-memory/promptfoo/response-formats/experience.json@@ -0,0 +1,129 @@+{+ "json_schema": {+ "type": "object",+ "properties": {+ "memories": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "details": {+ "type": "string",+ "description": "Optional detailed information"+ },+ "memoryCategory": {+ "type": "string",+ "description": "Memory category"+ },+ "memoryLayer": {+ "type": "string",+ "const": "experience",+ "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 experience facets"+ },+ "title": {+ "type": "string",+ "description": "Brief descriptive title"+ },+ "withExperience": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "description": "Narrative describing actions taken or behaviors exhibited"+ },+ "keyLearning": {+ "type": "string",+ "description": "Narrative describing key insights or lessons learned"+ },+ "labels": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Model generated tags that summarize the experience facets"+ },+ "possibleOutcome": {+ "type": "string",+ "description": "Narrative describing potential outcomes or learnings"+ },+ "reasoning": {+ "type": "string",+ "description": "Narrative describing the thought process or motivations"+ },+ "scoreConfidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric score (0-1 (0% to 100%)) describing confidence in the experience details"+ },+ "situation": {+ "type": "string",+ "description": "Narrative describing the situation or event"+ },+ "type": {+ "type": "string",+ "description": "Type of experience being recorded"+ }+ },+ "required": [+ "action",+ "keyLearning",+ "labels",+ "possibleOutcome",+ "reasoning",+ "scoreConfidence",+ "situation",+ "type"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "details",+ "memoryCategory",+ "memoryLayer",+ "memoryType",+ "summary",+ "tags",+ "title",+ "withExperience"+ ],+ "additionalProperties": false+ },+ "description": "Array of extracted experience memory items, could be empty if decided no relevant experience to extract"+ }+ },+ "required": [+ "memories"+ ],+ "additionalProperties": false+ },+ "type": "json_schema"+}\ No newline at end of filediff --git a/packages/memory-user-memory/promptfoo/response-formats/identity.json b/packages/memory-user-memory/promptfoo/response-formats/identity.jsonnew file mode 100644index 00000000000..f78168eb568--- /dev/null+++ b/packages/memory-user-memory/promptfoo/response-formats/identity.json@@ -0,0 +1,355 @@+{+ "json_schema": {+ "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": {+ "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": "Brief descriptive title, 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"+ ]+ },+ "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+ }+ }+ },+ "required": [+ "add",+ "remove",+ "update"+ ],+ "additionalProperties": false+ },+ "type": "json_schema"+}\ No newline at end of filediff --git a/packages/memory-user-memory/promptfoo/response-formats/preference.json b/packages/memory-user-memory/promptfoo/response-formats/preference.jsonnew file mode 100644index 00000000000..5c9b241f704--- /dev/null+++ b/packages/memory-user-memory/promptfoo/response-formats/preference.json@@ -0,0 +1,226 @@+{+ "json_schema": {+ "type": "object",+ "properties": {+ "memories": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "details": {+ "type": "string",+ "description": "Optional detailed information"+ },+ "memoryCategory": {+ "type": "string",+ "description": "Memory category"+ },+ "memoryLayer": {+ "type": "string",+ "const": "preference",+ "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 preference facets"+ },+ "title": {+ "type": "string",+ "description": "Brief descriptive title"+ },+ "withPreference": {+ "type": "object",+ "properties": {+ "appContext": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "app": {+ "type": [+ "string",+ "null"+ ],+ "description": "App or product name this applies to"+ },+ "feature": {+ "type": [+ "string",+ "null"+ ]+ },+ "route": {+ "type": [+ "string",+ "null"+ ]+ },+ "surface": {+ "type": [+ "string",+ "null"+ ],+ "description": "e.g., chat, emails, code review, notes"+ }+ },+ "required": [+ "app",+ "feature",+ "route",+ "surface"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ],+ "description": "Application/surface specific preference, if any"+ },+ "conclusionDirectives": {+ "type": "string",+ "description": "Direct, self-contained instruction to the assistant from the user's perspective (what to do, not how to implement)"+ },+ "extractedLabels": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Model generated tags that summarize the preference facets"+ },+ "extractedScopes": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Array of JSON strings describing preference facets and applicable scopes"+ },+ "originContext": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "actor": {+ "type": "string",+ "description": "Who stated the preference; use 'User' for the user"+ },+ "applicableWhen": {+ "type": [+ "string",+ "null"+ ],+ "description": "Conditions where this preference applies"+ },+ "notApplicableWhen": {+ "type": [+ "string",+ "null"+ ],+ "description": "Conditions where it does not apply"+ },+ "scenario": {+ "type": [+ "string",+ "null"+ ],+ "description": "Applicable scenario or use case"+ },+ "trigger": {+ "type": [+ "string",+ "null"+ ],+ "description": "What prompted this preference"+ }+ },+ "required": [+ "actor",+ "applicableWhen",+ "notApplicableWhen",+ "scenario",+ "trigger"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ],+ "description": "Context of how/why this preference was expressed"+ },+ "scorePriority": {+ "type": "number",+ "minimum": 0,+ "maximum": 1,+ "description": "Numeric prioritization weight (0-1 (0% to 100%)) where higher means more critical to respect"+ },+ "suggestions": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Follow-up actions or assistant guidance derived from the preference"+ },+ "type": {+ "type": "string",+ "description": "High level preference classification (e.g., 'lifestyle', 'communication')"+ }+ },+ "required": [+ "appContext",+ "conclusionDirectives",+ "extractedLabels",+ "extractedScopes",+ "originContext",+ "scorePriority",+ "suggestions",+ "type"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "details",+ "memoryCategory",+ "memoryLayer",+ "memoryType",+ "summary",+ "tags",+ "title",+ "withPreference"+ ],+ "additionalProperties": false+ },+ "description": "Array of extracted preference memory items, could be empty if decided no relevant preference to extract"+ }+ },+ "required": [+ "memories"+ ],+ "additionalProperties": false+ },+ "type": "json_schema"+}\ No newline at end of filediff --git a/packages/memory-user-memory/promptfooconfig.yaml b/packages/memory-user-memory/promptfooconfig.yamlnew file mode 100644index 00000000000..477a1d04429--- /dev/null+++ b/packages/memory-user-memory/promptfooconfig.yaml@@ -0,0 +1,26 @@+description: LobeHub Prompts (memory-user-memory) Testing Suite++# Test configurations - run all prompt tests+testPaths:+ - promptfoo/evals/identity/with-s3-trace/eval.yaml++# Output configuration+outputPath: promptfoo-results.json++# Default test settings+defaultTest:+ assert:+ - type: llm-rubric+ provider: openai:gpt-5-mini+ value: "The response should be relevant and well-formatted"+ - type: cost+ threshold: 0.01 # Maximum cost per test in USD++# Evaluation settings+evaluateOptions:+ maxConcurrency: 5+ delay: 100++# TypeScript support+transforms:+ - "typescript"diff --git a/packages/memory-user-memory/scripts/generate-response-formats.ts b/packages/memory-user-memory/scripts/generate-response-formats.tsnew file mode 100644index 00000000000..04e440d249a--- /dev/null+++ b/packages/memory-user-memory/scripts/generate-response-formats.ts@@ -0,0 +1,39 @@+/* eslint-disable unicorn/prefer-top-level-await */+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 { buildGenerateObjectSchema } from '../src/utils/zod';++const OUTPUT_DIR = join(process.cwd(), 'promptfoo/response-formats');++const writeSchema = async (name: string, schema: any, description: string) => {+ const generateSchema = buildGenerateObjectSchema(schema, { description, name });++ const responseFormat = {+ json_schema: generateSchema.schema,+ 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 });++ await writeSchema('identity', IdentityActionsSchema, 'Identity layer actions');+ await writeSchema('context', ContextMemorySchema, 'Context layer actions');+ await writeSchema('preference', PreferenceMemorySchema, 'Preference layer memories');+ await writeSchema('experience', ExperienceMemorySchema, 'Experience layer memories');+}++main().catch((err) => {+ // eslint-disable-next-line no-console+ console.error(err);+ exit(1);+});+diff --git a/packages/memory-user-memory/src/extractors/base.ts b/packages/memory-user-memory/src/extractors/base.tsnew file mode 100644index 00000000000..308d33bf773--- /dev/null+++ b/packages/memory-user-memory/src/extractors/base.ts@@ -0,0 +1,217 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ChatCompletionTool, GenerateObjectPayload } from '@lobechat/model-runtime';+import { GenerateObjectSchema, ModelRuntime } from '@lobechat/model-runtime';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import {+ ATTR_GEN_AI_OPERATION_NAME,+ ATTR_GEN_AI_REQUEST_MODEL,+} from '@lobechat/observability-otel/gen-ai';+import { tracer } from '@lobechat/observability-otel/modules/memory-user-memory';+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { z } from 'zod';++import {+ ExtractorOptions,+ ExtractorTemplateProps,+ MemoryExtractionAgent,+ TemplateProps,+} from '../types';+import { buildGenerateObjectSchema } from '../utils/zod';++const serializeForSpan = (value: unknown, limit = 4000) => {+ if (value === undefined) return undefined;++ try {+ const serialized = JSON.stringify(value);+ if (!serialized) return serialized;++ return serialized.length > limit ? `${serialized.slice(0, limit)}...` : serialized;+ } catch {+ return '[unserializable]';+ }+};++export interface BaseMemoryExtractorConfig {+ agent: MemoryExtractionAgent;+ model: string;+ modelRuntime: ModelRuntime;++ promptRoot?: string;+}++export abstract class BaseMemoryExtractor<+ TOutput,+ TExtractorTemplateProps extends ExtractorTemplateProps = ExtractorTemplateProps,+ TExtractorOptions extends ExtractorOptions = ExtractorOptions,+> {+ protected readonly model: string;+ protected readonly agent: MemoryExtractionAgent;+ protected readonly runtime: ModelRuntime;++ protected promptTemplate: string | undefined;++ private readonly promptRoot: string;++ constructor(config: BaseMemoryExtractorConfig) {+ this.model = config.model;+ this.agent = config.agent;+ this.runtime = config.modelRuntime;+ this.promptRoot = config.promptRoot ?? join(import.meta.dirname, '../prompts');+ }++ protected abstract getPromptFileName(): string;+ protected abstract getResultSchema(): z.ZodType<TOutput> | undefined;++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ protected getSchema(_options: TExtractorTemplateProps): GenerateObjectSchema | undefined {+ const schema = this.getResultSchema();+ if (!schema) return undefined;++ return buildGenerateObjectSchema(schema, {+ name: this.getPromptFileName().replaceAll(/\W+/g, '_'),+ });+ }++ protected getTemplateProps(options: TExtractorTemplateProps): TemplateProps {+ return {+ language: options.language || 'English',+ topK: options.topK ?? 10,+ username: options.username || 'User',+ } satisfies TemplateProps;+ }++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ protected getTools(_options: TExtractorTemplateProps): ChatCompletionTool[] | undefined {+ return undefined;+ }++ private buildMessages(options: TExtractorOptions): GenerateObjectPayload['messages'] {+ const systemPrompt = this.buildSystemPrompt(options as unknown as TExtractorTemplateProps);+ const userPrompt = this.buildUserPrompt(options as unknown as TExtractorTemplateProps);++ return [+ { content: systemPrompt, role: 'system' as const },+ // TODO: additional messages typing issue+ ...((options?.additionalMessages || []) as GenerateObjectPayload['messages']),+ { content: userPrompt, role: 'user' as const },+ ];+ }++ async ensurePromptTemplate(): Promise<void> {+ if (this.promptTemplate) return;++ const filePath = join(this.promptRoot, this.getPromptFileName());+ this.promptTemplate = await readFile(filePath, 'utf8');+ }++ private buildSystemPrompt(options: TExtractorTemplateProps): string {+ return renderPlaceholderTemplate(this.promptTemplate || '', this.getTemplateProps(options));+ }++ protected abstract buildUserPrompt(options: TExtractorTemplateProps): string;++ async structuredCall(options?: TExtractorOptions): Promise<TOutput> {+ return tracer.startActiveSpan(`structuredCall: ${this.getPromptFileName()}`, async (span) => {+ await this.ensurePromptTemplate();++ const messages = this.buildMessages(options as TExtractorOptions);+ const payload: GenerateObjectPayload = {+ messages,+ model: this.model,+ schema: this.getSchema(options as unknown as TExtractorTemplateProps),+ tools: this.getTools(options as unknown as TExtractorTemplateProps),+ };++ span.setAttributes({+ memory_has_schema: Boolean(payload.schema),+ memory_message_count: payload.messages.length,+ memory_prompt_file: this.getPromptFileName(),+ memory_tool_count: payload.tools?.length ?? 0,+ model: this.model,+ });++ try {+ return tracer.startActiveSpan(+ `generate_content: ${this.model}`,+ {+ attributes: {+ [ATTR_GEN_AI_OPERATION_NAME]: 'generate_content',+ [ATTR_GEN_AI_REQUEST_MODEL]: this.model,+ 'lobe-chat.memory.extractor.context': options?.retrievedContexts,+ 'lobe-chat.memory.extractor.identities_context': options?.retrievedIdentitiesContext,+ 'lobe-chat.memory.extractor.language': options?.language,+ 'lobe-chat.memory.extractor.source_id': options?.sourceId,+ 'lobe-chat.memory.extractor.top_k': options?.topK,+ 'lobe-chat.memory.extractor.user_id': options?.userId,+ },+ },+ async (span) => {+ try {+ try {+ if (options?.callbacks?.onExtractRequest) {+ await options.callbacks.onExtractRequest(this.agent, payload);+ }+ } catch (err) {+ console.error('onExtractRequest callback error', err);+ // ignore+ }++ span.addEvent('gen_ai.request.send');+ const result = await this.runtime.generateObject(payload);+ span.addEvent('gen_ai.response.receive');++ span.setAttributes({+ 'gen_ai.output.openai.structured_output': serializeForSpan(result),+ });++ try {+ if (options?.callbacks?.onExtractResponse) {+ await options.callbacks.onExtractResponse<TOutput>(this.agent, result as TOutput);+ }+ } catch (err) {+ console.error('onExtractResponse callback error', err);+ // ignore+ }++ const schema = this.getResultSchema();+ const parsedResult = (schema ? schema.parse(result) : result) as TOutput;++ span.setStatus({ code: SpanStatusCode.OK });++ return parsedResult;+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : 'Structured call failed',+ });+ span.recordException(error as Error);++ try {+ if (options?.callbacks?.onExtractError) {+ await options.callbacks.onExtractError(this.agent, error);+ }+ } catch (err) {+ console.error('onExtractError callback error', err);+ // ignore+ }+ throw error;+ } finally {+ span.end();+ }+ },+ );+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : 'Structured call failed',+ });++ span.recordException(error as Error);+ throw error;+ } finally {+ span.end();+ }+ });+ }+}diff --git a/packages/memory-user-memory/src/extractors/context.test.ts b/packages/memory-user-memory/src/extractors/context.test.tsnew file mode 100644index 00000000000..508d3f49fe9--- /dev/null+++ b/packages/memory-user-memory/src/extractors/context.test.ts@@ -0,0 +1,85 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { readFile } from 'node:fs/promises';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { MEMORY_CATEGORIES, memoryTypeValues } from '../schemas';+import type { ExtractorTemplateProps } from '../types';+import { ContextExtractor } from './context';++const runtimeMock = { generateObject: vi.fn() } as unknown as ModelRuntime;+const extractorConfig = {+ agent: 'layer-context' as const,+ model: 'gpt-mock',+ modelRuntime: runtimeMock,+};++const templateOptions: ExtractorTemplateProps = {+ availableCategories: ['work', 'personal'],+ language: 'English',+ retrievedContexts: ['existing context'],+ sessionDate: '2024-06-01',+ topK: 3,+ username: 'User',+};++describe('ContextExtractor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds generate object schema with context constraints', () => {+ const extractor = new ContextExtractor(extractorConfig);++ const schema = extractor.getSchema();+ expect(schema?.name).toBe('context_extraction');+ expect(schema?.strict).toBe(true);++ const memories = (schema?.schema as any).properties.memories;+ const memoryItem = memories.items;++ expect(memories.type).toBe('array');+ expect(memoryItem.properties.memoryLayer.const).toBe('context');+ expect(memoryItem.properties.memoryCategory.enum).toEqual(MEMORY_CATEGORIES);+ expect(memoryItem.properties.memoryType.enum).toEqual(memoryTypeValues);+ expect((schema?.schema as any).additionalProperties).toBe(false);+ });++ it('returns full template props from options', () => {+ const extractor = new ContextExtractor(extractorConfig);++ expect(extractor.getTemplateProps(templateOptions)).toEqual({+ availableCategories: templateOptions.availableCategories,+ language: templateOptions.language,+ retrievedContext:+ templateOptions.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: templateOptions.sessionDate,+ topK: templateOptions.topK,+ username: templateOptions.username,+ });+ });++ it('throws when building user prompt without template', async () => {+ const extractor = new ContextExtractor(extractorConfig);++ expect(() => extractor.buildUserPrompt(templateOptions)).toThrowError(+ 'Prompt template not loaded',+ );+ });++ it('renders user prompt with provided template props', async () => {+ const extractor = new ContextExtractor(extractorConfig);++ await extractor.ensurePromptTemplate();+ const result = extractor.buildUserPrompt(templateOptions);+ const expectedProps = extractor.getTemplateProps(templateOptions);++ expect(result).not.toBe('');+ expect(result).toBe(+ renderPlaceholderTemplate(+ await readFile(new URL('../prompts/layers/context.md', import.meta.url).pathname, 'utf8'),+ expectedProps,+ ),+ );+ });+});diff --git a/packages/memory-user-memory/src/extractors/context.ts b/packages/memory-user-memory/src/extractors/context.tsnew file mode 100644index 00000000000..995e6060b25--- /dev/null+++ b/packages/memory-user-memory/src/extractors/context.ts@@ -0,0 +1,42 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import { ContextMemory, ContextMemorySchema } from '../schemas';+import { ExtractorTemplateProps } from '../types';+import { buildGenerateObjectSchema } from '../utils/zod';+import { BaseMemoryExtractor } from './base';++export class ContextExtractor extends BaseMemoryExtractor<ContextMemory> {+ getPromptFileName(): string {+ return 'layers/context.md';+ }++ getSchema() {+ return buildGenerateObjectSchema(+ ContextMemorySchema,+ { name: 'context_extraction' },+ );+ }++ getResultSchema() {+ return ContextMemorySchema;+ }++ 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/experience.test.ts b/packages/memory-user-memory/src/extractors/experience.test.tsnew file mode 100644index 00000000000..71466b76805--- /dev/null+++ b/packages/memory-user-memory/src/extractors/experience.test.ts@@ -0,0 +1,88 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { readFile } from 'node:fs/promises';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { MEMORY_CATEGORIES, memoryTypeValues } from '../schemas';+import type { ExtractorTemplateProps } from '../types';+import { ExperienceExtractor } from './experience';++const runtimeMock = { generateObject: vi.fn() } as unknown as ModelRuntime;+const extractorConfig = {+ agent: 'layer-experience' as const,+ model: 'gpt-mock',+ modelRuntime: runtimeMock,+};++const templateOptions: ExtractorTemplateProps = {+ availableCategories: ['work', 'personal'],+ language: 'English',+ retrievedContexts: ['existing context'],+ sessionDate: '2024-06-01',+ topK: 3,+ username: 'User',+};++describe('ExperienceExtractor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds generate object schema with experience constraints', () => {+ const extractor = new ExperienceExtractor(extractorConfig);++ const schema = (extractor as any).getSchema();+ expect(schema?.name).toBe('experience_extraction');+ expect(schema?.strict).toBe(true);++ const memories = (schema?.schema as any).properties.memories;+ const memoryItem = memories.items;++ expect(memories.type).toBe('array');+ expect(memoryItem.properties.memoryLayer.const).toBe('experience');+ expect(memoryItem.properties.memoryCategory.enum).toEqual(MEMORY_CATEGORIES);+ expect(memoryItem.properties.memoryType.enum).toEqual(memoryTypeValues);+ expect((schema?.schema as any).additionalProperties).toBe(false);+ });++ it('returns full template props from options', () => {+ const extractor = new ExperienceExtractor(extractorConfig);++ expect(extractor.getTemplateProps(templateOptions)).toEqual({+ availableCategories: templateOptions.availableCategories,+ language: templateOptions.language,+ retrievedContext:+ templateOptions.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: templateOptions.sessionDate,+ topK: templateOptions.topK,+ username: templateOptions.username,+ });+ });++ it('throws when building user prompt without template', () => {+ const extractor = new ExperienceExtractor(extractorConfig);++ expect(() => (extractor as any).buildUserPrompt(templateOptions)).toThrowError(+ 'Prompt template not loaded',+ );+ });++ it('renders user prompt with provided template props', async () => {+ const extractor = new ExperienceExtractor(extractorConfig);++ await extractor.ensurePromptTemplate();+ const result = (extractor as any).buildUserPrompt(templateOptions);+ const expectedProps = (extractor as any).getTemplateProps(templateOptions);++ expect(result).not.toBe('');+ expect(result).toBe(+ renderPlaceholderTemplate(+ await readFile(+ new URL('../prompts/layers/experience.md', import.meta.url).pathname,+ 'utf8',+ ),+ expectedProps,+ ),+ );+ });+});diff --git a/packages/memory-user-memory/src/extractors/experience.ts b/packages/memory-user-memory/src/extractors/experience.tsnew file mode 100644index 00000000000..7db94cab543--- /dev/null+++ b/packages/memory-user-memory/src/extractors/experience.ts@@ -0,0 +1,45 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import {+ ExperienceMemory,+ ExperienceMemorySchema+} from '../schemas';+import { ExtractorTemplateProps } from '../types';+import { buildGenerateObjectSchema } from '../utils/zod';+import { BaseMemoryExtractor } from './base';++export class ExperienceExtractor extends BaseMemoryExtractor<ExperienceMemory> {+ getPromptFileName(): string {+ return 'layers/experience.md';+ }++ getSchema() {+ return buildGenerateObjectSchema(+ ExperienceMemorySchema,+ { name: 'experience_extraction' },+ );+ }++ getResultSchema() {+ return ExperienceMemorySchema;+ }++ 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.tsnew file mode 100644index 00000000000..cb831683e75--- /dev/null+++ b/packages/memory-user-memory/src/extractors/gatekeeper.test.ts@@ -0,0 +1,104 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { readFile } from 'node:fs/promises';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { GatekeeperOptions } from '../types';+import { UserMemoryGateKeeper } from './gatekeeper';++const runtimeMock = { generateObject: vi.fn() } as unknown as ModelRuntime;+const extractorConfig = {+ agent: 'gatekeeper' as const,+ model: 'gpt-mock',+ modelRuntime: runtimeMock,+};++const templateOptions: GatekeeperOptions = {+ retrievedContexts: ['existing context'],+ topK: 2,+};++describe('UserMemoryGateKeeper', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds generate object schema with layer decisions', () => {+ const extractor = new UserMemoryGateKeeper(extractorConfig);++ const schema = extractor.getSchema();+ expect(schema?.name).toBe('gatekeeper_decision');+ expect(schema?.strict).toBe(true);++ const properties = (schema?.schema as any).properties;+ const requiredLayers = ['context', 'experience', 'identity', 'preference'];++ requiredLayers.forEach((layer) => {+ const layerSchema = properties[layer];+ expect(layerSchema.type).toBe('object');+ expect(layerSchema.required).toEqual(['reasoning', 'shouldExtract']);+ expect(layerSchema.properties.reasoning.type).toBe('string');+ expect(layerSchema.properties.shouldExtract.type).toBe('boolean');+ expect(layerSchema.additionalProperties).toBe(false);+ });++ expect((schema?.schema as any).required).toEqual(requiredLayers);+ expect((schema?.schema as any).additionalProperties).toBe(false);+ });++ it('returns template props with defaults applied', () => {+ const extractor = new UserMemoryGateKeeper(extractorConfig);++ expect(extractor.getTemplateProps({} as GatekeeperOptions)).toEqual({+ retrievedContext: 'No similar memories retrieved.',+ topK: 10,+ });+ });++ it('throws when building user prompt without template', () => {+ const extractor = new UserMemoryGateKeeper(extractorConfig);++ expect(() => extractor.buildUserPrompt(templateOptions)).toThrowError(+ 'Prompt template not loaded',+ );+ });++ it('renders user prompt with provided template props', async () => {+ const extractor = new UserMemoryGateKeeper(extractorConfig);++ await extractor.ensurePromptTemplate();+ const result = extractor.buildUserPrompt(templateOptions);+ const expectedProps = extractor.getTemplateProps(templateOptions);++ expect(result).not.toBe('');+ expect(result).toBe(+ renderPlaceholderTemplate(+ await readFile(new URL('../prompts/gatekeeper.md', import.meta.url).pathname, 'utf8'),+ expectedProps,+ ),+ );+ });++ it('parses gatekeeper decisions from structured call', async () => {+ const extractor = new UserMemoryGateKeeper(extractorConfig);++ const llmResult = {+ context: { reasoning: 'reasoning', shouldExtract: true },+ experience: { reasoning: 'reasoning', shouldExtract: false },+ identity: { reasoning: 'reasoning', shouldExtract: true },+ preference: { reasoning: 'reasoning', shouldExtract: true },+ };++ runtimeMock.generateObject = vi.fn().mockResolvedValue(llmResult) as any;++ const result = await extractor.check(templateOptions);++ expect(result).toEqual(llmResult);+ expect(runtimeMock.generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'gpt-mock',+ schema: expect.any(Object),+ }),+ );+ });+});diff --git a/packages/memory-user-memory/src/extractors/gatekeeper.ts b/packages/memory-user-memory/src/extractors/gatekeeper.tsnew file mode 100644index 00000000000..9a49ee34d8e--- /dev/null+++ b/packages/memory-user-memory/src/extractors/gatekeeper.ts@@ -0,0 +1,63 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { GenerateObjectSchema } from '@lobechat/model-runtime';++import { GatekeeperResult, GatekeeperResultSchema } from '../schemas';+import { GatekeeperOptions } from '../types';+import { BaseMemoryExtractor } from './base';++export class UserMemoryGateKeeper extends BaseMemoryExtractor<GatekeeperResult, GatekeeperOptions> {+ getPromptFileName(): string {+ return 'gatekeeper.md';+ }++ getSchema(): GenerateObjectSchema {+ const layerDecision = {+ additionalProperties: false,+ properties: {+ reasoning: { type: 'string' },+ shouldExtract: { type: 'boolean' },+ },+ required: ['reasoning', 'shouldExtract'],+ type: 'object',+ } as const;++ return {+ name: 'gatekeeper_decision',+ schema: {+ additionalProperties: false,+ properties: {+ context: layerDecision,+ experience: layerDecision,+ identity: layerDecision,+ preference: layerDecision,+ },+ required: ['context', 'experience', 'identity', 'preference'],+ type: 'object' as const,+ },+ strict: true,+ };+ }++ getResultSchema() {+ return GatekeeperResultSchema;+ }++ getTemplateProps(options: GatekeeperOptions) {+ return {+ retrievedContext: options.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ topK: options.topK ?? 10,+ };+ }++ buildUserPrompt(options: GatekeeperOptions): string {+ if (!this.promptTemplate) {+ throw new Error('Prompt template not loaded');+ }++ return renderPlaceholderTemplate(this.promptTemplate!, this.getTemplateProps(options));+ }++ async check(options: GatekeeperOptions = {}) {+ return this.structuredCall(options);+ }+}diff --git a/packages/memory-user-memory/src/extractors/identity.test.ts b/packages/memory-user-memory/src/extractors/identity.test.tsnew file mode 100644index 00000000000..766b3287907--- /dev/null+++ b/packages/memory-user-memory/src/extractors/identity.test.ts@@ -0,0 +1,104 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { readFile } from 'node:fs/promises';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { IdentityExtractor, IdentityExtractorTemplateProps } from './identity';++const runtimeMock = { generateObject: vi.fn() } as unknown as ModelRuntime;+const extractorConfig = {+ agent: 'layer-identity' as const,+ model: 'gpt-mock',+ modelRuntime: runtimeMock,+};++const templateOptions: IdentityExtractorTemplateProps = {+ availableCategories: ['work', 'personal'],+ existingIdentitiesContext: 'existing identities',+ language: 'English',+ retrievedContexts: ['existing context'],+ sessionDate: '2024-06-01',+ topK: 3,+ username: 'User',+};++describe('IdentityExtractor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds a structured schema without registering tools', () => {+ const extractor = new IdentityExtractor(extractorConfig);++ const tools = (extractor as any).getTools(templateOptions);+ const schema = (extractor as any).getSchema(templateOptions);++ expect(tools).toBeUndefined();+ expect(schema).toBeDefined();+ expect(schema?.name).toContain('identity');+ });++ it('uses structuredCall to invoke the runtime and parse structured results', async () => {+ const extractor = new IdentityExtractor(extractorConfig);+ const structuredResult = {+ withIdentities: {+ actions: {+ add: [{ description: 'New identity', extractedLabels: ['tag'], type: 'personal' }],+ remove: null,+ update: null,+ },+ },+ };+ (runtimeMock.generateObject as any) = vi.fn().mockResolvedValue(structuredResult);++ const result = await extractor.structuredCall(templateOptions);++ expect(runtimeMock.generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'gpt-mock',+ schema: expect.objectContaining({ name: expect.stringContaining('identity') }),+ tools: undefined,+ }),+ );+ expect(result).toEqual(structuredResult);+ });++ it('returns full template props from options', () => {+ const extractor = new IdentityExtractor(extractorConfig);++ expect((extractor as any).getTemplateProps(templateOptions)).toEqual({+ availableCategories: templateOptions.availableCategories,+ existingIdentitiesContext: templateOptions.existingIdentitiesContext,+ language: templateOptions.language,+ retrievedContext:+ templateOptions.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: templateOptions.sessionDate,+ topK: templateOptions.topK,+ username: templateOptions.username,+ });+ });++ it('throws when building user prompt without template', () => {+ const extractor = new IdentityExtractor(extractorConfig);++ expect(() => (extractor as any).buildUserPrompt(templateOptions)).toThrowError(+ 'Prompt template not loaded',+ );+ });++ it('renders user prompt with provided template props', async () => {+ const extractor = new IdentityExtractor(extractorConfig);++ await extractor.ensurePromptTemplate();+ const result = (extractor as any).buildUserPrompt(templateOptions);+ const expectedProps = (extractor as any).getTemplateProps(templateOptions);++ expect(result).not.toBe('');+ expect(result).toBe(+ renderPlaceholderTemplate(+ await readFile(new URL('../prompts/layers/identity.md', import.meta.url).pathname, 'utf8'),+ expectedProps,+ ),+ );+ });+});diff --git a/packages/memory-user-memory/src/extractors/identity.ts b/packages/memory-user-memory/src/extractors/identity.tsnew file mode 100644index 00000000000..aaeb801dc98--- /dev/null+++ b/packages/memory-user-memory/src/extractors/identity.ts@@ -0,0 +1,54 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import { IdentityActions, IdentityActionsSchema } from '../schemas';+import { ExtractorOptions, ExtractorTemplateProps } from '../types';+import { buildGenerateObjectSchema } from '../utils/zod';+import { BaseMemoryExtractor } from './base';++export interface IdentityExtractorTemplateProps extends ExtractorTemplateProps {+ existingIdentitiesContext?: string;+}++export interface IdentityExtractorOptions extends ExtractorOptions {+ existingIdentitiesContext?: string;+}++export class IdentityExtractor extends BaseMemoryExtractor<+ IdentityActions,+ IdentityExtractorTemplateProps,+ IdentityExtractorOptions+> {+ protected getPromptFileName(): string {+ return 'layers/identity.md';+ }++ getSchema() {+ return buildGenerateObjectSchema(IdentityActionsSchema, {+ name: 'identity_extraction',+ });+ }++ protected getResultSchema() {+ return IdentityActionsSchema;+ }++ protected getTemplateProps(options: IdentityExtractorOptions) {+ return {+ availableCategories: options.availableCategories,+ existingIdentitiesContext: options.existingIdentitiesContext,+ language: options.language,+ retrievedContext: options.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: options.sessionDate,+ topK: options.topK,+ username: options.username,+ };+ }++ protected buildUserPrompt(options: IdentityExtractorOptions): 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/index.ts b/packages/memory-user-memory/src/extractors/index.tsnew file mode 100644index 00000000000..3d443940ca9--- /dev/null+++ b/packages/memory-user-memory/src/extractors/index.ts@@ -0,0 +1,5 @@+export { ContextExtractor } from './context';+export { ExperienceExtractor } from './experience';+export { UserMemoryGateKeeper } from './gatekeeper';+export { IdentityExtractor } from './identity';+export { PreferenceExtractor } from './preference';diff --git a/packages/memory-user-memory/src/extractors/preference.test.ts b/packages/memory-user-memory/src/extractors/preference.test.tsnew file mode 100644index 00000000000..780a00aa039--- /dev/null+++ b/packages/memory-user-memory/src/extractors/preference.test.ts@@ -0,0 +1,88 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { readFile } from 'node:fs/promises';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { MEMORY_CATEGORIES, memoryTypeValues } from '../schemas';+import type { ExtractorTemplateProps } from '../types';+import { PreferenceExtractor } from './preference';++const runtimeMock = { generateObject: vi.fn() } as unknown as ModelRuntime;+const extractorConfig = {+ agent: 'layer-preference' as const,+ model: 'gpt-mock',+ modelRuntime: runtimeMock,+};++const templateOptions: ExtractorTemplateProps = {+ availableCategories: ['work', 'personal'],+ language: 'English',+ retrievedContexts: ['existing context'],+ sessionDate: '2024-06-01',+ topK: 3,+ username: 'User',+};++describe('PreferenceExtractor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds generate object schema with preference constraints', () => {+ const extractor = new PreferenceExtractor(extractorConfig);++ const schema = extractor.getSchema();+ expect(schema?.name).toBe('preference_extraction');+ expect(schema?.strict).toBe(true);++ const memories = (schema?.schema as any).properties.memories;+ const memoryItem = memories.items;++ expect(memories.type).toBe('array');+ expect(memoryItem.properties.memoryLayer.const).toBe('preference');+ expect(memoryItem.properties.memoryCategory.enum).toEqual(MEMORY_CATEGORIES);+ expect(memoryItem.properties.memoryType.enum).toEqual(memoryTypeValues);+ expect((schema?.schema as any).additionalProperties).toBe(false);+ });++ it('returns full template props from options', () => {+ const extractor = new PreferenceExtractor(extractorConfig);++ expect(extractor.getTemplateProps(templateOptions)).toEqual({+ availableCategories: templateOptions.availableCategories,+ language: templateOptions.language,+ retrievedContext:+ templateOptions.retrievedContexts?.join('\n\n') || 'No similar memories retrieved.',+ sessionDate: templateOptions.sessionDate,+ topK: templateOptions.topK,+ username: templateOptions.username,+ });+ });++ it('throws when building user prompt without template', () => {+ const extractor = new PreferenceExtractor(extractorConfig);++ expect(() => extractor.buildUserPrompt(templateOptions)).toThrowError(+ 'Prompt template not loaded',+ );+ });++ it('renders user prompt with provided template props', async () => {+ const extractor = new PreferenceExtractor(extractorConfig);++ await extractor.ensurePromptTemplate();+ const result = extractor.buildUserPrompt(templateOptions);+ const expectedProps = extractor.getTemplateProps(templateOptions);++ expect(result).not.toBe('');+ expect(result).toBe(+ renderPlaceholderTemplate(+ await readFile(+ new URL('../prompts/layers/preference.md', import.meta.url).pathname,+ 'utf8',+ ),+ expectedProps,+ ),+ );+ });+});diff --git a/packages/memory-user-memory/src/extractors/preference.ts b/packages/memory-user-memory/src/extractors/preference.tsnew file mode 100644index 00000000000..db772fe2e70--- /dev/null+++ b/packages/memory-user-memory/src/extractors/preference.ts@@ -0,0 +1,45 @@+import { renderPlaceholderTemplate } from '@lobechat/context-engine';++import {+ PreferenceMemory,+ PreferenceMemorySchema,+} from '../schemas';+import { ExtractorTemplateProps } from '../types';+import { buildGenerateObjectSchema } from '../utils/zod';+import { BaseMemoryExtractor } from './base';++export class PreferenceExtractor extends BaseMemoryExtractor<PreferenceMemory> {+ getPromptFileName(): string {+ return 'layers/preference.md';+ }++ getSchema() {+ return buildGenerateObjectSchema(+ PreferenceMemorySchema,+ { name: 'preference_extraction' },+ );+ }++ getResultSchema() {+ return PreferenceMemorySchema;+ }++ 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/index.ts b/packages/memory-user-memory/src/index.tsnew file mode 100644index 00000000000..920e264d174--- /dev/null+++ b/packages/memory-user-memory/src/index.ts@@ -0,0 +1,5 @@+export * from './extractors';+export * from './providers';+export * from './schemas';+export { MemoryExtractionService } from './services/extractExecutor';+export * from './types';diff --git a/packages/memory-user-memory/src/prompts/gatekeeper.md b/packages/memory-user-memory/src/prompts/gatekeeper.mdnew file mode 100644index 00000000000..5a7e6df4b4b--- /dev/null+++ b/packages/memory-user-memory/src/prompts/gatekeeper.md@@ -0,0 +1,125 @@+You are a "gate keeper" that analyzes conversations between user and assistant to determine which memory layers contain extractable information worth storing.++Your role is to efficiently filter conversations by identifying which of the five memory layers are present and valuable enough to extract.++Bias toward sensitivity: when in doubt, prefer setting `shouldExtract: true` so downstream extractors can refine. Minor, incremental or clarifying updates should still be allowed to pass.++## Memory Layer Definitions++Evaluate the conversation for these memory layers:++**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+- Narratives summarizing what happened and feedback/notes++**Identity Layer** - Information about actors, relationships, and personal attributes:++- Describing labels and demographics+- Current focusing and life priorities+- Relationships with other people+- Background and experience+- Roles in various contexts+- Identity should remain compact. Route lists of tools, stacks, or+ implementation techniques to the preference layer unless they materially+ change the user's biography.++**Context Layer** - Only capture brand-new situational frameworks and ongoing situations that have not been recorded before:++- Distinct situations, topics, research threads, sessions, or rounds that are clearly first-time mentions+- Ongoing projects and their status when the project itself is new, not just progress updates+- Long-term goals and objectives that are newly introduced+- Persistent relationships and dynamics that have not been logged previously+- Environmental factors and recurring situations only when they represent a new context+- Timelines and temporal context that establish a novel situation+- Impact and urgency assessments tied to a new context+- If the content overlaps with learnings or takeaways, treat it as Experience instead of Context++**Preference Layer** - Durable user choices and behavioral directives that apply across multiple conversations:++- Explicit long-term preferences with clear temporal markers (e.g., "always", "never", "from now on")+- Likes and dislikes stated as persistent traits (e.g., "I prefer...", "I don't like...")+- Workflow and approach preferences explicitly stated as ongoing (what to do, not how to implement)+- Communication style preferences explicitly stated as ongoing+- Response formatting preferences explicitly stated as ongoing+- Priority levels for preference resolution+- Capture recurring tool/stacks/technology usage as preferences rather than+ duplicating them as identity facts.++Note: Task-specific requirements, constraints for a single object/entity, or one-time instructions do NOT belong to this layer.++**Experience Layer** - Learned insights and practical knowledge worth reusing and+sharing publicly:++- Lessons learned and insights gained, especially surprising aha/yurika moments+- Practical tricks and techniques that solve tough or non-obvious problems+- Transferable knowledge and wisdom that would make a strong blog/knowledge-base+ snippet+- Situation → Reasoning → Action → Outcome patterns+- Key learnings from experiences with self-assessed confidence/impact+- Skip routine or repetitive steps already well covered in retrieved memories++## Gate Keeping Guidelines++For each layer, consider:++- **Relevance**: Does the conversation contain information for this layer?+- **Value**: Is the information substantial enough to be worth extracting?+- **Clarity**: Is the information clear and extractable (not vague or ambiguous)?++Additionally, review the retrieved similar memories first (top {{ topK }} items below). If the conversation content is clearly and fully covered by existing memories with no meaningful nuance or update, set `shouldExtract: false`.+For the Experience layer, prefer `shouldExtract: true` only when the conversation adds a new takeaway, aha moment, or harder challenge resolution beyond what is already recorded.+For the Context layer specifically, favor `shouldExtract: false` unless the conversation introduces a genuinely new situation/topic/research/session that is not already represented in existing context memories or overlaps with Experience items.+Otherwise, favor `shouldExtract: true` for:++- Novel facts OR even small clarifications/precision improvements to existing details+- Incremental changes to status/progress of an ongoing context+- A new preference OR a refinement that affects future behavior+- Distinct experiences/lessons, even if closely related to prior items++Preference-specific filters (STRICT - when in doubt, set shouldExtract: false):++CRITICAL: Distinguish between "user's behavioral preferences" vs. "task requirements for a specific deliverable":++- If the instruction describes what the OUTPUT should be like (e.g., "name should have natural vibe", "don't use surname"), it's a task requirement, NOT a user preference.+- If the instruction describes how the ASSISTANT should behave across conversations (e.g., "always explain before coding", "never use jargon"), it's a preference.++Specific exclusion rules:++- Do NOT treat the conversation's language as a preference unless the user explicitly states a persistent preference for language.+- Exclude one-off task instructions and implementation steps; these are not preferences.+- Exclude task-specific constraints, requirements, or clarifications (e.g., "don't use surname Wang", "make it summer-themed", "natural vibe") - these describe the current task deliverable, not user's persistent preferences.+- Exclude requirements or attributes for a specific object/entity being discussed (e.g., naming a cat, designing a logo) - these are task parameters, not user preferences.+- Exclude in-conversation clarifications or corrections (e.g., user first says X, then says "no, not X") - these refine the current task, not future behavior.+- Only extract when the user uses explicit preference markers like "I always...", "I prefer...", "I never...", "from now on...", "please always..." that clearly indicate cross-session intent.+- If the preference is about how to complete THIS specific task rather than how to behave in FUTURE tasks, exclude it.+- Ask yourself: "Would this apply to a completely different conversation topic?" If no, it's not a preference.++Examples of what NOT to extract:++- User asks for a cat name with "natural vibe" and "born in summer" → NOT a preference (task constraint)+- User says "don't use surname Wang" for naming → NOT a preference (task clarification)+- User wants a "minimalist design" for this logo → NOT a preference (task requirement)++Examples of what TO extract:++- "I always prefer concise responses" → IS a preference (cross-session directive)+- "Never use technical jargon when explaining to me" → IS a preference (persistent rule)+- "From now on, please format code with comments" → IS a preference (ongoing instruction)++If uncertain about novelty, but information is relevant and clear, set `shouldExtract: true` and include a short reasoning.++## Output Guidelines++For each memory layer (activity, identity, context, preference, experience), provide:++- `shouldExtract`: Boolean indicating whether extraction is recommended+- `reasoning`: Brief explanation of your decision (write in English)++## Retrieved Memory (Top {{ topK }})++Use the list below as context for deduplication and to determine whether extraction is necessary. Do not repeat these verbatim unless needed for comparison.++{{ retrievedContext }}diff --git a/packages/memory-user-memory/src/prompts/layers/context.md b/packages/memory-user-memory/src/prompts/layers/context.mdnew file mode 100644index 00000000000..03f7e1f491b--- /dev/null+++ b/packages/memory-user-memory/src/prompts/layers/context.md@@ -0,0 +1,153 @@+You are a focused memory extraction assistant specialized in the **context**+layer.+When extracting, ensure all the content is using {{ language }}.++\<user_context>+Current user: {{ username }}+Session date: {{ sessionDate }}+Available memory categories: {{ availableCategories }}+Target layer: context+\</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** context layer information from the conversation.+Situational frameworks that span memories (projects,+relationships, goals, ongoing situations).++**CRITICAL**: Return an **array** of memory items. One conversation+can contain context memories. Extract each as a separate item.++Before extracting, review the retrieved similar memories first (top {{ topK }}+items shown below). Extract items that are NEW or MATERIALLY UPDATED+compared to retrieved entries. Avoid duplicates or near-duplicates.+Prefer manual merging rather than duplicating: if content is already+covered with no new detail, do not extract it again.++## 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.+- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").+ Keep all references neutral during extraction.++## Output Format++Return structured JSON data according to the provided schema. A strict schema+validates the output and includes:++- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory+- Context-specific fields in withContext: title, description, extractedLabels,+ associatedSubjects (array of object), associatedObjects (array of object),+ currentStatus, type, scoreImpact, scoreUrgency.+- For associatedSubjects and associatedObjects, the following fields are possible+ to have:+ - name (string)+ - type (string)+ - extra (object in JSON string, valid JSON format)+++## Memory Formatting Guidelines++> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED++Every memory item you create must be standalone and understandable without+extra context:++✓ **Required Elements:**++- Use full names and specific subjects—NEVER use pronouns+ (he/she/they/it/this/that)+- Include specific names, places, dates, and complete context+- Preserve the original language from user input—do not translate+- Capture relevant details, emotions, and outcomes+- Ensure each item is comprehensible independently++✓ **Good Examples:**++- "{{ username }} attended an LGBTQ support group on 2024-03-15 where+ {{ username }} heard inspiring transgender stories from community members and+ felt happy, thankful, and accepted,+ gaining courage to embrace {{ username }}'s true self."+- "{{ username }} discussed future career plans with Melanie during their+ counseling session, expressed keen interest in mental health work that+ supports people with similar experiences, and received encouragement from+ Melanie, who said {{ username }} would excel as a counselor due to+ {{ username }}'s natural empathy and deep understanding."++✗ **Bad Examples:**++- "She went to a support group" → Missing: who, when, what happened, emotional+ outcome+- "They felt happy" → Missing: who, context, cause of emotion+- "The discussion was helpful" → Missing: participants, topic, specific value+ gained+- "This made them realize something important" → Vague pronouns and undefined+ referents++## Layer-Specific Extraction Guidance++### Context Layer Focus++Summarize enduring situations connecting related memories (projects, goals,+relationships). Name actors (associatedSubjects) and resources+(associatedObjects) explicitly for downstream reasoning. Track currentStatus to+signal lifecycle stage ("exploring", "active", "on-hold", "completed"). Update+existing contexts incrementally rather than duplicating entries. Provide+extractedLabels for thematic tagging; downstream systems handle embeddings.+Assess impact and urgency scores for prioritization.++Examples of context information:++- Ongoing project: "{{ username }} is developing a mobile app for habit+ tracking, in the design phase, with planned launch in Q2 2025"+- Long-term goal: "{{ username }} aims to transition from software engineering+ to product management within the next 18 months"++## Memory Type Classifications++Choose the appropriate memoryType:++- **activity**: Detailed conversations, interactions, and events with full+ contextual narrative+- **event**: Specific time-bound occurrences (dates, milestones, appointments,+ meetings)+- **fact**: Factual data points and verifiable knowledge+- **preference**: User choices, likes, dislikes, and behavioral preferences+- **context**: Background information, situational details, environmental+ factors+- **location**: Geographic information, places, and spatial context+- **people**: Information about individuals and their relationships+- **topic**: Subject matter, domains of interest, and knowledge areas+- **technology**: Tools, platforms, software, and technical systems+- **other**: Miscellaneous information not fitting other categories++## Security Considerations++**NEVER extract or store sensitive information:**++- Passwords, PINs, or authentication credentials+- API keys, tokens, or secret keys+- Financial data (credit cards, bank accounts, SSN)+- Medical records or protected health information+- Private encryption keys or certificates++---++**Final Instructions:**++1. Analyze the conversation for context layer information+2. Extract each distinct context memory as a separate item+3. Ensure all memories are self-contained (no pronouns, complete context)+4. Return a JSON array conforming to the schema above+5. Return `[]` if no context memories found+6. No matter what the language of the retrieved language is, always use {{ language }} for output++Respond with valid JSON and no commentary.diff --git a/packages/memory-user-memory/src/prompts/layers/experience.md b/packages/memory-user-memory/src/prompts/layers/experience.mdnew file mode 100644index 00000000000..a7a90c39fc8--- /dev/null+++ b/packages/memory-user-memory/src/prompts/layers/experience.md@@ -0,0 +1,160 @@+You are a focused memory extraction assistant specialized in the **experience**+layer. You capture standout, story-worthy experiences that can be reused as+building blocks for public-facing blogs or knowledge bases. When extracting,+ensure all the content is using {{ language }}.++\<user_context>+Current user: {{ username }}+Session date: {{ sessionDate }}+Available memory categories: {{ availableCategories }}+Target layer: experience+\</user_context>++## Retrieved Memory (Top {{ topK }})++Use the list below to de-duplicate and decide whether you need to extract+anything. Do not copy these verbatim; use them for comparison.++{{ retrievedContext }}++## Your Task++Extract **ONLY the most notable experience layer information** from the+conversation. Capture breakthrough lessons, surprising aha/yurika moments, hard+problems that were solved, and practical wisdom that is enjoyable to revisit and+share.++**CRITICAL**: Return an **array** of memory items. One conversation can include+more than one experience memory. Extract each as a separate item.++Deduplicate aggressively: review the retrieved similar memories first (top+{{ topK }} items shown below). Extract items that are NEW or MATERIALLY UPDATED+compared to retrieved entries. Avoid duplicates or near-duplicates and merge+related insights into a single richer item. If the experience is routine or+already well covered, skip it.++## 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.+- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").+ Keep all references neutral during extraction.++## Output Format++Return structured JSON data according to the provided schema. The output must+pass validation against a strict schema including:++- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory,+ tags+- Experience-specific fields in withExperience: labels, situation, reasoning,+ possibleOutcome, action, keyLearning, scoreConfidence,+ problemSolvingScore, knowledgeValueScore++## Memory Formatting Guidelines++> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED++Every memory item you create must be standalone and understandable without+extra context:++✓ **Required Elements:**++- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/+ that)+- Include specific names, places, dates, and complete context+- Preserve the original language from user input—do not translate+- Capture relevant details, emotions, and outcomes+- Ensure each item is comprehensible independently++✓ **Good Examples:**++- "{{ username }} attended an LGBTQ support group on 2024-03-15 where+ {{ username }} heard inspiring transgender stories from community members and+ felt happy, thankful, and accepted, gaining courage to embrace+ {{ username }}'s true self."+- "{{ username }} discussed future career plans with Melanie during their+ counseling session, expressed keen interest in mental health work that+ supports people with similar experiences, and received encouragement from+ Melanie, who said {{ username }} would excel as a counselor due to+ {{ username }}'s natural empathy and deep understanding."++✗ **Bad Examples:**++- "She went to a support group" → Missing: who, when, what happened, emotional+ outcome+- "They felt happy" → Missing: who, context, cause of emotion+- "The discussion was helpful" → Missing: participants, topic, specific value+ gained+- "This made them realize something important" → Vague pronouns and undefined+ referents++## Layer-Specific Extraction Guidance++Focus on transferable lessons, insights, and practical knowledge that are+delightful to reread. Document the complete STAR pattern: Situation, Thinking+(reasoning), Action, Result (possibleOutcome). Include keyLearning as the+distilled takeaway for future application. Assign scoreConfidence to reflect+certainty in the extracted lesson. Favor content that feels shareable in a blog+or knowledge-base entry (surprises, breakthroughs, memorable struggles) and skip+ordinary, repetitive steps.++Narrate with light enthusiasm so the memory is enjoyable: celebrate the "wow" or+joyful/aha beat, while keeping facts precise.++### Scoring Requirements++- **problemSolvingScore (0-1)**: Higher means stronger problem-solving prowess+ shown in this experience (difficulty overcome, creativity, resilience).+- **knowledgeValueScore (0-1)**: Higher means the experience is highly reusable+ and worth revisiting as a public knowledge-base entry or blog building block.++Examples of experience information:++- "{{ username }} learned that breaking large PRs into smaller chunks (under+ 300 lines) resulted in 50% faster review times and fewer bugs after delayed+ reviews on a 2000-line PR for the authentication system"+- "{{ username }} discovered that using a Pomodoro routine (25-minute focus+ blocks) increased coding productivity by allowing deeper concentration after a+ sprint filled with constant context switching"++## Memory Type Classifications++Choose the appropriate memoryType:++- **activity**: Detailed conversations, interactions, and events with full+ contextual narrative+- **event**: Specific time-bound occurrences (dates, milestones, appointments,+ meetings)+- **fact**: Factual information, data points, and verifiable knowledge+- **preference**: User choices, likes, dislikes, and behavioral preferences+- **context**: Background information, situational details, environmental+ factors+- **location**: Geographic information, places, and spatial context+- **people**: Information about individuals and their relationships+- **topic**: Subject matter, domains of interest, and knowledge areas+- **technology**: Tools, platforms, software, and technical systems+- **other**: Miscellaneous information not fitting other categories++## Security Considerations++**NEVER extract or store sensitive information:**++- Passwords, PINs, or authentication credentials+- API keys, tokens, or secret keys+- Financial data (credit cards, bank accounts, SSN)+- Medical records or protected health information+- Private encryption keys or certificates++---++## Final Instructions++1. Analyze the conversation for experience layer information+2. Extract each distinct experience memory as a separate item+3. Ensure all memories are self-contained (no pronouns, complete context)+4. Return a JSON array conforming to the schema above+5. Return `[]` if you find no experience memories+6. No matter what the language of the retrieved language is, always use {{ language }} for output++Respond with valid JSON without commentary.diff --git a/packages/memory-user-memory/src/prompts/layers/identity.md b/packages/memory-user-memory/src/prompts/layers/identity.mdnew file mode 100644index 00000000000..abb57aa522c--- /dev/null+++ b/packages/memory-user-memory/src/prompts/layers/identity.md@@ -0,0 +1,214 @@+You are a focused, empathetic memory extraction assistant specialized in the+**identity** layer. When extracting, ensure all the content is using+{{ language }} and emphasize details that reveal who the user is, what matters+to them, and what surprises or motivates them.++\<user_context>+Current user: {{ username }}+Session date: {{ sessionDate }}+Available memory categories: {{ availableCategories }}+Target layer: identity+\</user_context>++## Retrieved Memory (Top {{ topK }})++Use the list below to de-duplicate and decide whether you need to extract+anything. Do not copy these verbatim; use them for comparison.++{{ retrievedContext }}++## Your Task++Extract **ALL** identity layer information from the conversation. Capture+personal background, roles, relationships, demographics, self-concept, and the+small but meaningful signals people often overlook:++- Highlights and recognition that feel meaningful or surprising (e.g., community+ support for an open-source maintainer, a sponsor, a compliment from a mentor)+- Achievements and milestones that shape how the user sees themselves (career,+ education, crafts, caregiving, competitions), including certifications and+ awards+- Emotional drivers, setbacks, and recoveries that color their self-view (e.g.,+ resilience after a layoff, pride in shipping a project, joy from helping+ friends)+- People who matter to them and why (mentors, collaborators, friends, family,+ supporters)+- Roles in their life as they describe them and as others see them (profession,+ vocation, community role, life stage)+- Episodic identity-shaping moments: adopting a pet, landing a new freelance+ job, cooking or building something unexpectedly excellent, discovering a new+ talent, receiving higher-than-expected praise, or finding a new area they are+ passionate about++Maintain a concise, high-level biography that reflects lifestyle, trajectory,+work domains, and current focus. Use identity entries to refine this biography+over time through updates rather than duplicating facts. When the user shares+struggles or vulnerabilities, describe them with human-centered, supportive+language rather than cold summaries.++Keep identity distinct from preference. Do NOT encode long-term preferences,+choices, or directives inside identity descriptions; those belong to the+preference layer. Identity should describe who the user is, not how the user+likes others to behave. Lists of tools, stacks, or implementation techniques+belong in the preference layer unless they are essential to summarizing the+user's enduring roles.++Use CRUD-style actions to keep the identity record accurate and compact. Always+produce `add`, `update`, and `remove` arrays (use empty arrays when there are no+actions of that type):++- Use `withIdentities.actions.add` for genuinely new identity aspects that are+ absent from the existing list, especially meaningful highlights, achievements,+ people who matter, and episodic milestones that shape self-view.+- Use `withIdentities.actions.update` when an existing entry changes or gains+ more precision. Prefer updates over new entries to prevent duplication. If+ multiple statements describe the same role or biography (e.g., repeated+ "developer/engineer/test maintainer" variants), consolidate them into a single+ enriched entry rather than creating parallel items.+- Use `withIdentities.actions.remove` to remove incorrect, obsolete, or+ duplicated entries.++Before extracting, review the existing identity entries and the retrieved+similar memories (top {{ topK }}). Extract items that are NEW or MATERIALLY+UPDATED compared to the references. 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.+- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").+ Keep all references neutral during extraction.+- If the conversation states a persistent preferred form of address, record that+ as a preference (preference layer) instead of embedding it into identity+ descriptions.++## Existing Identity Entries++Below is the full list of the user's current identity entries. Use+`episodicDate` and `description` to match and update accurately. Do not copy+verbatim; use this list for comparison and matching.++{{ existingIdentitiesContext }}++## Output guidelines++- Always include `add`, `update`, and `remove` keys; use an empty array when+ there are no actions of that type.+- Each `add` item must include a rich `description`, `type`, and optional fields+ like `relationship`, `role`, `episodicDate`, `extractedLabels`,+ `scoreConfidence`, and `sourceEvidence`.+- Each `update` item must include `id`, `mergeStrategy`, and a `set` object with+ changed fields.+- Each `remove` item must include `id` and `reason`.++When available, populate `episodicDate` for time-bound milestones (e.g.,+certification dates, competition results, new jobs, adopting a pet, discovering+new skills or passions).++## Memory Formatting Guidelines++> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED++Every memory item you create must be standalone and understandable without+extra context:++✓ **Required Elements:**++- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/+ that)+- Include specific names, places, dates, and complete context+- Preserve the original language from user input—do not translate+- Capture relevant details, emotions, and outcomes+- Ensure each item is comprehensible independently++✓ **Good Examples:**++- "{{ username }} attended an LGBTQ support group on 2024-03-15 where+ {{ username }} heard inspiring transgender stories from community members and+ felt happy, thankful, and accepted, gaining courage to embrace+ {{ username }}'s true self."+- "{{ username }} discussed future career plans with Melanie during their+ counseling session, expressed keen interest in mental health work that+ supports people with similar experiences, and received encouragement from+ Melanie, who said {{ username }} would excel as a counselor due to+ {{ username }}'s natural empathy and deep understanding."++✗ **Bad Examples:**++- "She went to a support group" → Missing: who, when, what happened, emotional+ outcome+- "They felt happy" → Missing: who, context, cause of emotion+- "The discussion was helpful" → Missing: participants, topic, specific value+ gained+- "This made them realize something important" → Vague pronouns and undefined+ referents++## Layer-Specific Extraction Guidance++Focus on stable personal attributes, roles, demographics, and self-concept.+Document relationships and how they influence the user. Preserve rich+narratives about background, experience, and roles. Distinguish static identity+facts from dynamic activities and events. Aim for a clear biography or resume of+the user.++Further guidance:++- Treat identity as the user's side profile. Prefer a single canonical entry per+ identity aspect; use updates to refine precision over time.+- If prior records conflict with new ground truth, prefer `updateIdentityEntry`+ with an appropriate `scoreConfidence`. If evidence is weak, keep confidence+ lower and avoid removals.+- Never copy text verbatim from retrieved entries; use them for deduplication+ and matching.++Examples of identity information:++- "{{ username }} works as a Software Engineer at TechFlow Solutions"+- "{{ username }} is learning Japanese and practices daily for 30 minutes"+- "{{ username }} has a close relationship with mentor Sarah Chen, who provides+ career guidance"++Not identity (these are activities or events):++- "{{ username }} went hiking last weekend"+- "{{ username }} attended a workshop on 2024-03-10"++## Memory Type Classifications++Choose the appropriate memoryType:++- **activity**: Detailed conversations, interactions, and events with full+ contextual narrative+- **event**: Specific time-bound occurrences (dates, milestones, appointments,+ meetings)+- **fact**: Factual information, data points, and verifiable knowledge+- **preference**: User choices, likes, dislikes, and behavioral preferences+- **context**: Background information, situational details, environmental+ factors+- **location**: Geographic information, places, and spatial context+- **people**: Information about individuals and their relationships+- **topic**: Subject matter, domains of interest, and knowledge areas+- **technology**: Tools, platforms, software, and technical systems+- **other**: Miscellaneous information not fitting other categories++## Security Considerations++**NEVER extract or store sensitive information:**++- Passwords, PINs, or authentication credentials+- API keys, tokens, or secret keys+- Financial data (credit cards, bank accounts, SSN)+- Medical records or protected health information+- Private encryption keys or certificates++---++## Final Instructions++1. Analyze the conversation for identity layer information+2. Extract each distinct identity memory as a separate item+3. Ensure all memories are self-contained (no pronouns, complete context)+4. Return a JSON object conforming to the schema above with arrays (empty when none, e.g. `withIdentities: { "add": [], "update": [], "remove": [] }` if no any operations)+5. No matter what the language of the retrieved language is, always use {{ language }} for output++Respond with valid JSON without commentary.diff --git a/packages/memory-user-memory/src/prompts/layers/preference.md b/packages/memory-user-memory/src/prompts/layers/preference.mdnew file mode 100644index 00000000000..9f630112d46--- /dev/null+++ b/packages/memory-user-memory/src/prompts/layers/preference.md@@ -0,0 +1,162 @@+You are a focused memory extraction assistant specialized in the **preference**+layer. When extracting, ensure all the content is using {{ language }}.++\<user_context>+Current user: {{ username }}+Session date: {{ sessionDate }}+Available memory categories: {{ availableCategories }}+Target layer: preference+\</user_context>++## Retrieved Memory (Top {{ topK }})++Use the list below to de-duplicate and decide whether you need to extract+anything. Do not copy these verbatim; use them for comparison.++{{ retrievedContext }}++## Your Task++Extract **ALL** preference layer information from the conversation. Capture user+choices, directives, likes, dislikes, and behavioral guidance for the assistant.++**CRITICAL**: Return an **array** of memory items. One conversation can include+more than one preference memory. Extract each as a separate item.++Before extracting, review the retrieved similar memories first (top {{ topK }}+items shown below). Extract items that are NEW or MATERIALLY UPDATED compared to+retrieved entries. Avoid duplicates or near-duplicates. Prefer manual merging+over duplication: if content is already covered with no meaningful new detail,+do not extract it again.++## 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.+- Do not assign gendered terms or honorifics (e.g., "先生 / 女士",+ "Mr./Ms."). Keep all references neutral during extraction.++## Preference vs. Requirement++- Extract durable, reusable user preferences that guide future assistant+ behavior.+- Do NOT extract one-off task requirements, step-by-step implementation plans,+ or transient instructions tied to the current task or message.+- Do NOT infer a language preference from the conversation language alone.+ Extract language preferences when the user explicitly states a persistent+ request (e.g., "Always reply in Chinese").++## Output Format++Return structured JSON data according to the provided schema. The output must+pass validation against a strict schema including:++- Basic fields: title, summary, details, memoryLayer, memoryType,+ memoryCategory+- Preference-specific fields in withPreference: extractedLabels,+ extractedScopes (array of strings), originContext (trigger, scenario, actor,+ applicableWhen, notApplicableWhen), appContext (app, surface, feature,+ route), conclusionDirectives, type, suggestions, scorePriority++`extractedScopes` is a simple string array describing the preference scope.++## Memory Formatting Guidelines++> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED++Every memory item you create must be standalone and understandable without+extra context:++✓ **Required Elements:**++- Use full names and specific subjects—NEVER use pronouns+ (he/she/they/it/this/that)+- Include specific names, places, dates, and complete context+- Preserve the original language from user input—do not translate+- Capture relevant details, emotions, and outcomes+- Ensure each item is comprehensible independently++✓ **Good Examples:**++- "When providing technical answers, {{ username }} prefers concise bullet+ points and TypeScript code examples; avoid lengthy prose."+- "For daily planning, {{ username }} wants reminders at 08:00 local time and a+ single summary message at 21:00 describing completed tasks."++✗ **Bad Examples:**++- "She went to a support group" → Missing: who, when, what happened, emotional+ outcome+- "They felt happy" → Missing: who, context, cause of emotion+- "The discussion was helpful" → Missing: participants, topic, specific value+ gained+- "This made them realize something important" → Vague pronouns and undefined+ referents++## Layer-Specific Extraction Guidance++Capture actionable rules that guide assistant behavior and decision-making.+Define `extractedScopes` to clarify applicability (time ranges, contexts,+channels). Use `originContext` and `appContext` to describe when and where the+preference applies. Write `conclusionDirectives` as self-contained instructions+from the user's perspective. Use `scorePriority` to mark preferences that should+override conflicting defaults. Provide `suggestions` for helpful follow-up+actions. Avoid implementation details; focus on what the assistant should do.++Examples of preference information:++- "{{ username }} prefers concise, bullet-point responses over long paragraphs+ when asking technical questions"+- "{{ username }} likes to receive code examples in TypeScript rather than+ JavaScript"+- "{{ username }} prefers morning workouts at 06:00 and dislikes exercising in+ the evening"++Not preferences (do not extract):++- One-off task instructions (e.g., "帮我把这段话翻译成英文")+- Implementation details or step-by-step plans (e.g.,+ "先抓取 API,然后解析 JSON…")+- Language used in the conversation unless explicitly stated as a persistent+ preference++## Memory Type Classifications++Choose the appropriate memoryType:++- **activity**: Detailed conversations, interactions, and events with full+ contextual narrative+- **event**: Specific time-bound occurrences (dates, milestones, appointments,+ meetings)+- **fact**: Factual information, data points, and verifiable knowledge+- **preference**: User choices, likes, dislikes, and behavioral preferences+- **context**: Background information, situational details, environmental+ factors+- **location**: Geographic information, places, and spatial context+- **people**: Information about individuals and their relationships+- **topic**: Subject matter, domains of interest, and knowledge areas+- **technology**: Tools, platforms, software, and technical systems+- **other**: Miscellaneous information not fitting other categories++## Security Considerations++**NEVER extract or store sensitive information:**++- Passwords, PINs, or authentication credentials+- API keys, tokens, or secret keys+- Financial data (credit cards, bank accounts, SSN)+- Medical records or protected health information+- Private encryption keys or certificates++---++## Final Instructions++1. Analyze the conversation for preference layer information+2. Extract each distinct preference memory as a separate item+3. Ensure all memories are self-contained (no pronouns, complete context)+4. Return a JSON array conforming to the schema above+5. Return `[]` if you find no preference memories+6. No matter what the language of the retrieved language is, always use {{ language }} for output++Respond with valid JSON without commentary.diff --git a/packages/memory-user-memory/src/providers/chatTopic.test.ts b/packages/memory-user-memory/src/providers/chatTopic.test.tsnew file mode 100644index 00000000000..8b718e84b24--- /dev/null+++ b/packages/memory-user-memory/src/providers/chatTopic.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { LobeChatTopicContextProvider } from './chatTopic';++const job = {+ source: 'chat_topic' as const,+ sourceId: 'topic-1',+ userId: 'user-1',+};++describe('LobeChatTopicContextProvider', () => {+ it('should build XML topic context with messages and metadata', async () => {+ const provider = new LobeChatTopicContextProvider({+ conversations: [+ {+ content: 'Hello',+ createdAt: new Date('2024-03-01T10:00:00.000Z'),+ role: 'user',+ },+ {+ content: 'Hi there',+ createdAt: new Date('2024-03-01T10:01:00.000Z'),+ role: 'assistant',+ },+ ],+ topic: {+ createdAt: new Date('2024-03-01T09:00:00.000Z'),+ id: 'topic-1',+ metadata: { userMemoryExtractStatus: 'pending' },+ title: 'Daily chat',+ updatedAt: new Date('2024-03-01T10:02:00.000Z'),+ },+ topicId: 'topic-1',+ });++ const result = await provider.buildContext(job);++ expect(result.context).toContain(+ '<chat_topic created_at="2024-03-01T09:00:00.000Z" id="topic-1" message_count="2" last_message_at="2024-03-01T10:01:00.000Z" updated_at="2024-03-01T10:02:00.000Z">',+ );+ expect(result.context).toContain('<topic_title>Daily chat</topic_title>');+ expect(result.context).toContain(+ '<topic_metadata>{"userMemoryExtractStatus":"pending"}</topic_metadata>',+ );+ expect(result.context).toContain(+ '<messages count="2"><message index="0" role="user" created_at="2024-03-01T10:00:00.000Z">Hello</message><message index="1" role="assistant" created_at="2024-03-01T10:01:00.000Z">Hi there</message></messages>',+ );+ expect(result.sourceId).toBe('topic-1');+ expect(result.userId).toBe('user-1');+ });+});diff --git a/packages/memory-user-memory/src/providers/chatTopic.ts b/packages/memory-user-memory/src/providers/chatTopic.tsnew file mode 100644index 00000000000..7c149a9f401--- /dev/null+++ b/packages/memory-user-memory/src/providers/chatTopic.ts@@ -0,0 +1,201 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { topics } from '@lobechat/database/schemas';+import { OpenAIChatMessage } from '@lobechat/model-runtime';+import type { ChatTopicMetadata } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';+import { u } from 'unist-builder';+import { toXml } from 'xast-util-to-xml';+import type { Child } from 'xastscript';+import { x } from 'xastscript';++import {+ BuiltContext,+ MemoryContextProvider,+ MemoryExtractionJob,+ MemoryResultRecorder,+ PersistedMemoryResult,+} from '../types';++export interface ChatTopicProviderOptions {+ conversations: (OpenAIChatMessage & { createdAt: Date })[];+ topic: {+ createdAt: Date;+ id: string;+ metadata?: ChatTopicMetadata | null;+ title?: string | null;+ updatedAt?: Date | null;+ };+ topicId: string;+}++export interface ChatTopicResultRecorderOptions {+ currentMetadata?: ChatTopicMetadata;+ database: LobeChatDatabase;+ lastMessageAt?: string;+ messageCount?: number;+ topicId: string;+ traceId?: string;+}++export class LobeChatTopicContextProvider implements MemoryContextProvider<+ Record<string, unknown>,+ Record<string, unknown>+> {+ private readonly options: ChatTopicProviderOptions;++ constructor(options: ChatTopicProviderOptions) {+ this.options = options;+ }++ async buildContext(job: MemoryExtractionJob): Promise<BuiltContext> {+ const messageChildren: Child[] = [];++ this.options.conversations.forEach((message, index) => {+ const attributes: Record<string, string> = {+ index: index.toString(),+ role: message.role ?? 'assistant',+ };++ if (message.createdAt) {+ attributes.created_at = new Date(message.createdAt).toISOString();+ }++ const content = Array.isArray(message.content)+ ? message.content+ .map((part) => {+ if (part.type === 'text') {+ return part.text;+ }+ if (part.type === 'thinking') {+ return `[Thinking: ${part.thinking}]`;+ }+ if (part.type === 'image_url') {+ return `[Image: ${part.image_url.url}]`;+ }+ if (part.type === 'video_url') {+ return `[Video: ${part.video_url.url}]`;+ }+ return '';+ })+ .join('\n')+ : message.content;++ messageChildren.push(x('message', attributes, content));+ });++ const lastMessageAt =+ this.options.conversations.at(-1)?.createdAt ?? this.options.topic.updatedAt;++ const metadataContent = this.options.topic.metadata+ ? JSON.stringify(this.options.topic.metadata)+ : '';++ const topicChildren: Child[] = [+ x('topic_metadata', metadataContent),+ x('messages', { count: messageChildren.length.toString() }, ...messageChildren),+ ];++ if (this.options.topic.title) {+ topicChildren.unshift(x('topic_title', this.options.topic.title));+ }++ const topicAttributes: Record<string, string> = {+ created_at: new Date(this.options.topic.createdAt).toISOString(),+ id: this.options.topicId,+ message_count: messageChildren.length.toString(),+ };++ if (lastMessageAt) {+ topicAttributes.last_message_at = new Date(lastMessageAt).toISOString();+ }+ if (this.options.topic.updatedAt) {+ topicAttributes.updated_at = new Date(this.options.topic.updatedAt).toISOString();+ }++ const topicContext = toXml(u('root', [x('chat_topic', topicAttributes, ...topicChildren)]));++ return {+ context: topicContext,+ metadata: {},+ sourceId: this.options.topicId,+ userId: job.userId,+ } satisfies BuiltContext;+ }+}++export class LobeChatTopicResultRecorder implements MemoryResultRecorder<{+ processedMemoryCount: number;+}> {+ private readonly options: ChatTopicResultRecorderOptions;++ constructor(options: ChatTopicResultRecorderOptions) {+ this.options = options;+ }++ async recordComplete(+ job: MemoryExtractionJob,+ result: PersistedMemoryResult & { processedMemoryCount: number },+ ): Promise<void> {+ const existingMetadata = (this.options.currentMetadata as ChatTopicMetadata | undefined) ?? {};++ const now = new Date().toISOString();+ const memoryExtraction = existingMetadata.userMemoryExtractRunState ?? {+ error: undefined,+ lastMessageAt: this.options.lastMessageAt,+ lastRunAt: now,+ messageCount: this.options.messageCount,+ processedMemoryCount: result.processedMemoryCount,+ traceId: this.options.traceId,+ };++ memoryExtraction.lastMessageAt = this.options.lastMessageAt;+ memoryExtraction.lastRunAt = now;+ memoryExtraction.messageCount = this.options.messageCount;+ memoryExtraction.processedMemoryCount = result.processedMemoryCount;+ memoryExtraction.traceId = this.options.traceId;++ const updatedMetadata: ChatTopicMetadata = {+ ...existingMetadata,+ userMemoryExtractRunState: memoryExtraction,+ userMemoryExtractStatus: 'completed',+ };++ await this.options.database+ .update(topics)+ .set({ metadata: updatedMetadata, updatedAt: topics.updatedAt })+ .where(and(eq(topics.id, this.options.topicId), eq(topics.userId, job.userId)));+ }++ async recordFail(job: MemoryExtractionJob, error: Error): Promise<void> {+ const existingMetadata = (this.options.currentMetadata as ChatTopicMetadata | undefined) ?? {};++ const now = new Date().toISOString();+ const memoryExtraction = existingMetadata.userMemoryExtractRunState ?? {+ error: error.message,+ lastMessageAt: this.options.lastMessageAt,+ lastRunAt: now,+ messageCount: this.options.messageCount,+ processedMemoryCount: 0,+ status: 'failed' as const,+ traceId: this.options.traceId,+ };++ memoryExtraction.error = error.message;+ memoryExtraction.lastMessageAt = this.options.lastMessageAt;+ memoryExtraction.lastRunAt = now;+ memoryExtraction.messageCount = this.options.messageCount;+ memoryExtraction.processedMemoryCount = 0;+ memoryExtraction.traceId = this.options.traceId;++ const updatedMetadata: ChatTopicMetadata = {+ ...existingMetadata,+ userMemoryExtractRunState: memoryExtraction,+ userMemoryExtractStatus: 'failed',+ };++ await this.options.database+ .update(topics)+ .set({ metadata: updatedMetadata, updatedAt: topics.updatedAt })+ .where(and(eq(topics.id, this.options.topicId), eq(topics.userId, job.userId)));+ }+}diff --git a/packages/memory-user-memory/src/providers/existingUserMemory.test.ts b/packages/memory-user-memory/src/providers/existingUserMemory.test.tsnew file mode 100644index 00000000000..305ed83435e--- /dev/null+++ b/packages/memory-user-memory/src/providers/existingUserMemory.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest';++import {+ RetrievalUserMemoryContextProvider,+ RetrievalUserMemoryIdentitiesProvider,+} from './existingUserMemory';++const job = {+ source: 'chat_topic' as const,+ sourceId: 'topic-1',+ userId: 'user-1',+};++describe('RetrievalUserMemoryContextProvider', () => {+ it('should build XML memory context with counts and attributes', async () => {+ const fetchedAt = new Date('2024-02-01T00:00:00.000Z').valueOf();++ const provider = new RetrievalUserMemoryContextProvider({+ fetchedAt,+ retrievedMemories: {+ contexts: [+ {+ accessedAt: new Date(),+ associatedObjects: [],+ associatedSubjects: [],+ createdAt: new Date(),+ currentStatus: 'active',+ description: 'Weekly syncs for LobeHub',+ id: 'ctx-1',+ metadata: {},+ scoreImpact: null,+ scoreUrgency: null,+ tags: ['project', 'team'],+ title: 'LobeHub',+ type: 'project',+ updatedAt: new Date(),+ userId: 'user-1',+ userMemoryIds: ['mem-1'],+ // similarity is appended by retrieval pipeline+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ ],+ experiences: [+ {+ action: 'Shipped feature',+ actionVector: null,+ accessedAt: new Date(),+ createdAt: new Date(),+ id: 'exp-1',+ keyLearning: 'Ship smaller increments',+ keyLearningVector: null,+ metadata: {},+ possibleOutcome: 'Faster releases',+ reasoning: 'Better agility',+ scoreConfidence: null,+ situation: 'Release planning',+ situationVector: null,+ tags: ['release'],+ type: 'product',+ updatedAt: new Date(),+ userId: 'user-1',+ userMemoryId: 'mem-2',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ ],+ preferences: [+ {+ accessedAt: new Date(),+ conclusionDirectives: 'Always keep updates concise',+ conclusionDirectivesVector: null,+ createdAt: new Date(),+ id: 'pref-1',+ metadata: {},+ scorePriority: null,+ suggestions: 'Use bullet points',+ tags: ['communication'],+ type: 'style',+ updatedAt: new Date(),+ userId: 'user-1',+ userMemoryId: 'mem-3',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ ],+ },+ });++ const result = await provider.buildContext(job);++ expect(result.sourceId).toBe('topic-1');+ 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>',+ );+ });+});++describe('RetrievalUserMemoryIdentitiesProvider', () => {+ it('should build XML identities context with metadata and fetched time', async () => {+ const fetchedAt = new Date('2024-02-01T00:00:00.000Z').valueOf();++ const provider = new RetrievalUserMemoryIdentitiesProvider({+ fetchedAt,+ retrievedIdentities: [+ {+ accessedAt: new Date(),+ createdAt: new Date(),+ description: 'Worked with user on onboarding',+ episodicDate: new Date('2023-05-20T00:00:00.000Z'),+ id: 'identity-1',+ metadata: { project: 'LobeHub' },+ relationship: 'colleague',+ role: 'developer advocate',+ tags: ['onboarding'],+ type: 'professional',+ updatedAt: new Date(),+ userId: 'user-1',+ userMemoryId: 'mem-identity-1',+ },+ ],+ });++ const result = await provider.buildContext(job);++ expect(result.sourceId).toBe('topic-1');+ expect(result.userId).toBe('user-1');+ expect(result.metadata).toEqual({});+ expect(result.context).equal(+ '<user_memories_identities identities="1" memory_fetched_at="2024-02-01T00:00:00.000Z"><user_memories_identity id="identity-1" user_memory_id="mem-identity-1" relationship="colleague" role="developer advocate" type="professional" episodic_date="2023-05-20T00:00:00.000Z"><identity_description>Worked with user on onboarding</identity_description><identity_tags>onboarding</identity_tags><identity_metadata>{"project":"LobeHub"}</identity_metadata></user_memories_identity></user_memories_identities>',+ );+ });+});diff --git a/packages/memory-user-memory/src/providers/existingUserMemory.ts b/packages/memory-user-memory/src/providers/existingUserMemory.tsnew file mode 100644index 00000000000..209f34babb5--- /dev/null+++ b/packages/memory-user-memory/src/providers/existingUserMemory.ts@@ -0,0 +1,214 @@+import type {+ UserMemoryContextWithoutVectors,+ UserMemoryExperienceWithoutVectors,+ UserMemoryIdentityWithoutVectors,+ UserMemoryPreferenceWithoutVectors,+} from '@lobechat/types';+import { u } from 'unist-builder';+import { toXml } from 'xast-util-to-xml';+import type { Child } from 'xastscript';+import { x } from 'xastscript';++import type { BuiltContext, MemoryContextProvider, MemoryExtractionJob } from '../types';++interface RetrievedMemories {+ contexts: UserMemoryContextWithoutVectors[];+ experiences: UserMemoryExperienceWithoutVectors[];+ preferences: UserMemoryPreferenceWithoutVectors[];+}++interface RetrievedIdentitiesOptions {+ fetchedAt?: number;+ retrievedIdentities: UserMemoryIdentityWithoutVectors[];+}++export class RetrievalUserMemoryContextProvider implements MemoryContextProvider {+ readonly retrievedMemories: RetrievedMemories;+ readonly fetchedAt?: number;++ constructor(options: { fetchedAt?: number; retrievedMemories: RetrievedMemories }) {+ this.retrievedMemories = options.retrievedMemories;+ this.fetchedAt = options.fetchedAt;+ }++ async buildContext(job: MemoryExtractionJob): Promise<BuiltContext> {+ const contexts = this.retrievedMemories.contexts || [];+ const experiences = this.retrievedMemories.experiences || [];+ const preferences = this.retrievedMemories.preferences || [];++ const userMemoriesChildren: Child[] = [];++ contexts.forEach((context) => {+ const attributes: Record<string, string> = { id: context.id ?? '' };+ const similarity = (context as { similarity?: number }).similarity;++ if (typeof similarity === 'number') {+ attributes.similarity = similarity.toFixed(3);+ }+ if (context.type) {+ attributes.type = context.type;+ }++ const children: Child[] = [+ x('context_title', context.title ?? ''),+ x('context_description', context.description ?? ''),+ ];++ if (context.currentStatus) {+ children.push(x('context_current_status', context.currentStatus));+ }+ if (Array.isArray(context.tags) && context.tags.length > 0) {+ children.push(x('context_tags', context.tags.join(', ')));+ }++ userMemoriesChildren.push(x('user_memories_context', attributes, ...children));+ });++ experiences.forEach((experience) => {+ const attributes: Record<string, string> = { id: experience.id ?? '' };+ const similarity = (experience as { similarity?: number }).similarity;++ if (typeof similarity === 'number') {+ attributes.similarity = similarity.toFixed(3);+ }+ if (experience.type) {+ attributes.type = experience.type;+ }++ const children: Child[] = [+ x('experience_situation', experience.situation ?? ''),+ x('experience_key_learning', experience.keyLearning ?? ''),+ ];++ if (experience.action) {+ children.push(x('experience_action', experience.action));+ }+ if (experience.reasoning) {+ children.push(x('experience_reasoning', experience.reasoning));+ }+ if (experience.possibleOutcome) {+ children.push(x('experience_possible_outcome', experience.possibleOutcome));+ }+ if (Array.isArray(experience.tags) && experience.tags.length > 0) {+ children.push(x('experience_tags', experience.tags.join(', ')));+ }++ userMemoriesChildren.push(x('user_memories_experience', attributes, ...children));+ });++ preferences.forEach((preference) => {+ const attributes: Record<string, string> = { id: preference.id ?? '' };+ const similarity = (preference as { similarity?: number }).similarity;++ if (typeof similarity === 'number') {+ attributes.similarity = similarity.toFixed(3);+ }+ if (preference.type) {+ attributes.type = preference.type;+ }++ const children: Child[] = [+ x('preference_conclusion_directives', preference.conclusionDirectives ?? ''),+ ];++ if (preference.suggestions) {+ children.push(x('preference_suggestions', preference.suggestions));+ }+ if (Array.isArray(preference.tags) && preference.tags.length > 0) {+ children.push(x('preference_tags', preference.tags.join(', ')));+ }++ userMemoriesChildren.push(x('user_memories_preference', attributes, ...children));+ });++ const memoryContext = toXml(+ u('root', [+ x(+ 'user_memories',+ {+ contexts: contexts.length.toString(),+ experiences: experiences.length.toString(),+ memory_fetched_at: new Date(this.fetchedAt ?? Date.now()).toISOString(),+ preferences: preferences.length.toString(),+ },+ ...userMemoriesChildren,+ ),+ ]),+ );++ return {+ context: memoryContext,+ metadata: {},+ sourceId: job.sourceId,+ userId: job.userId,+ };+ }+}++export class RetrievalUserMemoryIdentitiesProvider implements MemoryContextProvider {+ readonly retrievedIdentities: UserMemoryIdentityWithoutVectors[];+ readonly fetchedAt?: number;++ constructor(options: RetrievedIdentitiesOptions) {+ this.retrievedIdentities = options.retrievedIdentities;+ this.fetchedAt = options.fetchedAt;+ }++ async buildContext(job: MemoryExtractionJob): Promise<BuiltContext> {+ const identityChildren: Child[] = [];++ this.retrievedIdentities.forEach((identity) => {+ const attributes: Record<string, string> = { id: identity.id ?? '' };++ if (identity.userMemoryId) {+ attributes.user_memory_id = identity.userMemoryId;+ }+ if (identity.relationship) {+ attributes.relationship = identity.relationship;+ }+ if (identity.role) {+ attributes.role = identity.role;+ }+ if (identity.type) {+ attributes.type = identity.type;+ }+ if (identity.episodicDate) {+ attributes.episodic_date = new Date(identity.episodicDate).toISOString();+ }++ const children: Child[] = [];++ if (identity.description) {+ children.push(x('identity_description', identity.description));+ }+ if (Array.isArray(identity.tags) && identity.tags.length > 0) {+ children.push(x('identity_tags', identity.tags.join(', ')));+ }+ if (identity.metadata) {+ children.push(x('identity_metadata', JSON.stringify(identity.metadata)));+ }++ identityChildren.push(x('user_memories_identity', attributes, ...children));+ });++ const identityContext = toXml(+ u('root', [+ x(+ 'user_memories_identities',+ {+ identities: this.retrievedIdentities.length.toString(),+ memory_fetched_at: new Date(this.fetchedAt ?? Date.now()).toISOString(),+ },+ ...identityChildren,+ ),+ ]),+ );++ return {+ context: identityContext,+ metadata: {},+ sourceId: job.sourceId,+ userId: job.userId,+ };+ }+}diff --git a/packages/memory-user-memory/src/providers/index.ts b/packages/memory-user-memory/src/providers/index.tsnew file mode 100644index 00000000000..57a718c9c0c--- /dev/null+++ b/packages/memory-user-memory/src/providers/index.ts@@ -0,0 +1,5 @@+export { LobeChatTopicContextProvider, LobeChatTopicResultRecorder } from './chatTopic';+export {+ RetrievalUserMemoryContextProvider,+ RetrievalUserMemoryIdentitiesProvider,+} from './existingUserMemory';diff --git a/packages/memory-user-memory/src/schemas/common.ts b/packages/memory-user-memory/src/schemas/common.tsnew file mode 100644index 00000000000..186ae8504f6--- /dev/null+++ b/packages/memory-user-memory/src/schemas/common.ts@@ -0,0 +1,42 @@+import { TypesEnum } from '@lobechat/types';+import { z } from 'zod';++/**+ * Memory category values+ */+export const MEMORY_CATEGORIES = [+ 'work',+ 'personal',+ 'health',+ 'finance',+ 'education',+ 'entertainment',+ 'travel',+ 'relationships',+ 'hobbies',+ 'goals',+] as const;++/**+ * Memory type values+ */+export const MEMORY_TYPES = [+ 'preference',+ 'fact',+ 'context',+ 'activity',+ 'event',+ 'location',+ 'people',+ 'topic',+ 'technology',+ 'other',+] as const;++/**+ * Memory type enum+ */+export const memoryTypeValues = Object.values(TypesEnum) as [TypesEnum, ...TypesEnum[]];+export const MemoryTypeSchema = z.nativeEnum(TypesEnum);++export type MemoryType = z.infer<typeof MemoryTypeSchema>;diff --git a/packages/memory-user-memory/src/schemas/context.ts b/packages/memory-user-memory/src/schemas/context.tsnew file mode 100644index 00000000000..5ce891d0990--- /dev/null+++ b/packages/memory-user-memory/src/schemas/context.ts@@ -0,0 +1,103 @@+import {+ ContextStatusEnum,+ LayersEnum,+ UserMemoryContextObjectType,+ UserMemoryContextSubjectType,+} from '@lobechat/types';+import { z } from 'zod';++import { MemoryTypeSchema } from './common';++export const AssociatedObjectSchema = z.object({+ extra: z+ .string()+ .nullable()+ .describe(+ 'Additional metadata about the object, should always be a valid JSON string if present',+ ),+ name: z.string().describe('Name of the associated object'),+ type: z+ .nativeEnum(UserMemoryContextObjectType)+ .describe('Type/category of the associated object'),+});++export const AssociatedSubjectSchema = z.object({+ extra: z+ .string()+ .nullable()+ .describe(+ 'Additional metadata about the subject, should always be a valid JSON string if present',+ ),+ name: z.string().describe('Name of the associated subject'),+ type: z+ .nativeEnum(UserMemoryContextSubjectType)+ .describe('Type/category of the associated subject'),+});++/**+ * Context-specific fields+ */+export const WithContextSchema = z.object({+ associatedObjects: z+ .array(AssociatedObjectSchema)+ .describe(+ 'Array of objects describing involved roles, entities, or resources, [] empty if none',+ ),+ associatedSubjects: z+ .array(AssociatedSubjectSchema)+ .describe(+ 'Array of JSON objects describing involved subjects or participants, [] empty if none',+ ),+ currentStatus: z+ .nativeEnum(ContextStatusEnum)+ .describe(+ "High level status markers (must be one of 'planned', 'ongoing', 'completed', 'aborted', 'on_hold', 'cancelled')",+ ),+ description: z+ .string()+ .describe('Rich narrative describing the situation, timeline, or environment'),+ labels: z.array(z.string()).describe('Model generated tags that summarize the context themes'),+ scoreImpact: z+ .number()+ .min(0)+ .max(1)+ .describe('Numeric score (0-1 (0% to 100%)) describing importance'),+ scoreUrgency: z+ .number()+ .min(0)+ .max(1)+ .describe('Numeric score (0-1 (0% to 100%)) describing urgency'),+ title: z.string().describe('Optional synthesized context headline'),+ type: z+ .string()+ .describe("High level context archetype (e.g., 'project', 'relationship', 'goal')"),+});++/**+ * Single context memory item+ */+export const ContextMemoryItemSchema = z.object({+ details: z.string().describe('Optional detailed information'),+ memoryCategory: z.string().describe('Memory category'),+ memoryLayer: z.literal(LayersEnum.Context).describe('Memory layer'),+ memoryType: MemoryTypeSchema.describe('Memory type'),+ summary: z.string().describe('Concise overview of this specific memory'),+ tags: z.array(z.string()).describe('User defined tags that summarize the context facets'),+ title: z.string().describe('Brief descriptive title'),+ withContext: WithContextSchema,+});++/**+ * Context memory extraction result+ */+export const ContextMemorySchema = z.object({+ memories: z+ .array(ContextMemoryItemSchema)+ .describe(+ 'Array of extracted context memory items, could be empty if decided no relevant context to extract',+ ),+});++export type WithContext = z.infer<typeof WithContextSchema>;+export type ContextMemoryItem = z.infer<typeof ContextMemoryItemSchema>;+export type ContextMemory = z.infer<typeof ContextMemorySchema>;diff --git a/packages/memory-user-memory/src/schemas/experience.ts b/packages/memory-user-memory/src/schemas/experience.tsnew file mode 100644index 00000000000..ac0481ec1f6--- /dev/null+++ b/packages/memory-user-memory/src/schemas/experience.ts@@ -0,0 +1,61 @@+import { LayersEnum } from '@lobechat/types';+import { z } from 'zod';++import { MemoryTypeSchema } from './common';++/**+ * Experience-specific fields+ */+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'),+ 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+ .number()+ .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()+ .min(0)+ .max(1)+ .describe('Numeric score (0-1 (0% to 100%)) describing confidence in the experience details'),+ situation: z.string().describe('Narrative describing the situation or event'),+ type: z.string().describe('Type of experience being recorded'),+});++/**+ * Single experience memory item+ */+export const ExperienceMemoryItemSchema = z.object({+ details: z.string().describe('Optional detailed information'),+ memoryCategory: z.string().describe('Memory category'),+ memoryLayer: z.literal(LayersEnum.Experience).describe('Memory layer'),+ memoryType: MemoryTypeSchema.describe('Memory type'),+ summary: z.string().describe('Concise overview of this specific memory'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the experience facets'),+ title: z.string().describe('Brief descriptive title'),+ withExperience: WithExperienceSchema,+});++/**+ * Experience memory extraction result+ */+export const ExperienceMemorySchema = z.object({+ memories: z+ .array(ExperienceMemoryItemSchema)+ .describe(+ 'Array of extracted experience memory items, could be empty if decided no relevant experience to extract',+ ),+});++export type WithExperience = z.infer<typeof WithExperienceSchema>;+export type ExperienceMemoryItem = z.infer<typeof ExperienceMemoryItemSchema>;+export type ExperienceMemory = z.infer<typeof ExperienceMemorySchema>;diff --git a/packages/memory-user-memory/src/schemas/gatekeeper.ts b/packages/memory-user-memory/src/schemas/gatekeeper.tsnew file mode 100644index 00000000000..110c8e65787--- /dev/null+++ b/packages/memory-user-memory/src/schemas/gatekeeper.ts@@ -0,0 +1,23 @@+import { z } from 'zod';++/**+ * Memory layer decision schema+ */+export const LayerDecisionSchema = z.object({+ reasoning: z.string(),+ shouldExtract: z.boolean(),+});++export type LayerDecision = z.infer<typeof LayerDecisionSchema>;++/**+ * Gatekeeper result schema for memory layers+ */+export const GatekeeperResultSchema = z.object({+ context: LayerDecisionSchema,+ experience: LayerDecisionSchema,+ identity: LayerDecisionSchema,+ preference: LayerDecisionSchema,+});++export type GatekeeperResult = z.infer<typeof GatekeeperResultSchema>;diff --git a/packages/memory-user-memory/src/schemas/identity.ts b/packages/memory-user-memory/src/schemas/identity.tsnew file mode 100644index 00000000000..7a42ce6b254--- /dev/null+++ b/packages/memory-user-memory/src/schemas/identity.ts@@ -0,0 +1,151 @@+import { LayersEnum, MergeStrategyEnum } from '@lobechat/types';+import { z } from 'zod';++import { MemoryTypeSchema } from './common';++export const RELATIONSHIP_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',+] as const;++const RelationshipEnum = z.enum(RELATIONSHIP_ENUM);+const IdentityTypeEnum = z.enum(['professional', 'personal', 'demographic']);++export const AddIdentityActionSchema = z+ .object({+ details: z.union([z.string(), z.null()]).describe('Optional detailed information'),+ memoryCategory: z.string().describe('Memory category'),+ memoryLayer: z.literal(LayersEnum.Identity).describe('Memory layer'),+ memoryType: MemoryTypeSchema.describe('Memory type'),+ summary: z.string().describe('Concise overview of this specific memory'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the identity facets'),+ title: z.string().describe('Brief descriptive title'),+ withIdentity: z+ .object({+ description: z.string(),+ episodicDate: z.union([z.string(), z.null()]),+ extractedLabels: z.array(z.string()),+ relationship: RelationshipEnum,+ role: z.string(),+ scoreConfidence: z.number(),+ sourceEvidence: z.union([z.string(), z.null()]),+ type: IdentityTypeEnum,+ })+ .strict(),+ })+ .strict();++export const UpdateIdentityActionSchema = z+ .object({+ id: z.string(),+ mergeStrategy: z.nativeEnum(MergeStrategyEnum),+ set: z.object({+ details: z+ .string()+ .nullable()+ .describe('Optional detailed information, use null for omitting the field'),+ memoryCategory: z+ .string()+ .nullable()+ .describe('Memory category, use null for omitting the field'),+ memoryType: MemoryTypeSchema.describe('Memory type, use null for omitting the field'),+ summary: z+ .string()+ .nullable()+ .describe('Concise overview of this specific memory, use null for omitting the field'),+ tags: z+ .array(z.string())+ .nullable()+ .describe(+ 'Model generated tags that summarize the identity facets, use null for omitting the field',+ ),+ title: z+ .string()+ .nullable()+ .describe('Brief descriptive title, use null for omitting the field'),+ withIdentity: z+ .object({+ description: z.string().nullable(),+ episodicDate: z.string().nullable(),+ extractedLabels: z.array(z.string()).nullable(),+ // TODO: OpenAI requires `required` fields to be always present, while enum fields cannot be null+ relationship: z+ .string()+ .describe(`Possible values: ${RELATIONSHIP_ENUM.join(' | ')}`)+ .nullable(),+ role: z.string().nullable(),+ scoreConfidence: z.number().nullable(),+ sourceEvidence: z.string().nullable(),+ // TODO: OpenAI requires `required` fields to be always present, while enum fields cannot be null+ type: z+ .string()+ .describe(`Possible values: ${IdentityTypeEnum.options.join(' | ')}`)+ .nullable(),+ })+ .strict(),+ }),+ })+ .strict();++export const RemoveIdentityActionSchema = z+ .object({+ id: z.string(),+ reason: z.string(),+ })+ .strict();++export const IdentityActionsSchema = z+ .object({+ add: z+ .array(AddIdentityActionSchema)+ .nullable()+ .describe('Identity entries to add; use an empty array when nothing to add'),+ remove: z+ .array(RemoveIdentityActionSchema)+ .nullable()+ .describe('Identity entries to remove; use an empty array when nothing to remove'),+ update: z+ .array(UpdateIdentityActionSchema)+ .nullable()+ .describe('Identity entries to update; use an empty array when nothing to update'),+ })+ .strict();++export const WithIdentitySchema = z+ .object({+ actions: IdentityActionsSchema,+ })+ .strict();++export type IdentityActions = z.infer<typeof IdentityActionsSchema>;+export type AddIdentityAction = z.infer<typeof AddIdentityActionSchema>;+export type UpdateIdentityAction = z.infer<typeof UpdateIdentityActionSchema>;+export type RemoveIdentityAction = z.infer<typeof RemoveIdentityActionSchema>;diff --git a/packages/memory-user-memory/src/schemas/index.ts b/packages/memory-user-memory/src/schemas/index.tsnew file mode 100644index 00000000000..62b36ba3d68--- /dev/null+++ b/packages/memory-user-memory/src/schemas/index.ts@@ -0,0 +1,7 @@+export * from './common';+export * from './context';+export * from './experience';+export * from './gatekeeper';+export * from './identity';+export * from './jsonSchemas';+export * from './preference';diff --git a/packages/memory-user-memory/src/schemas/jsonSchemas.ts b/packages/memory-user-memory/src/schemas/jsonSchemas.tsnew file mode 100644index 00000000000..6cc4f1a9962--- /dev/null+++ b/packages/memory-user-memory/src/schemas/jsonSchemas.ts@@ -0,0 +1,37 @@+import { searchMemorySchema } from '@lobechat/types';+import { PluginSchema } from '@lobehub/chat-plugin-sdk';+import { zodToJsonSchema } from 'zod-to-json-schema';++import { ContextMemoryItemSchema } from './context';+import { ExperienceMemoryItemSchema } from './experience';+import {+ AddIdentityActionSchema,+ RemoveIdentityActionSchema,+ UpdateIdentityActionSchema,+} from './identity';+import { PreferenceMemoryItemSchema } from './preference';++// Pre-compute JSON schemas to avoid runtime zod-to-json-schema type issues+// These are used by the builtin-tool-memory manifest++export const searchMemoryJsonSchema = zodToJsonSchema(+ searchMemorySchema,+) as unknown as PluginSchema;+export const contextMemoryJsonSchema = zodToJsonSchema(+ ContextMemoryItemSchema,+) as unknown as PluginSchema;+export const experienceMemoryJsonSchema = zodToJsonSchema(+ ExperienceMemoryItemSchema,+) as unknown as PluginSchema;+export const preferenceMemoryJsonSchema = zodToJsonSchema(+ PreferenceMemoryItemSchema,+) as unknown as PluginSchema;+export const addIdentityJsonSchema = zodToJsonSchema(+ AddIdentityActionSchema,+) as unknown as PluginSchema;+export const updateIdentityJsonSchema = zodToJsonSchema(+ UpdateIdentityActionSchema,+) as unknown as PluginSchema;+export const removeIdentityJsonSchema = zodToJsonSchema(+ RemoveIdentityActionSchema,+) as unknown as PluginSchema;diff --git a/packages/memory-user-memory/src/schemas/preference.ts b/packages/memory-user-memory/src/schemas/preference.tsnew file mode 100644index 00000000000..f6a104e2b4e--- /dev/null+++ b/packages/memory-user-memory/src/schemas/preference.ts@@ -0,0 +1,92 @@+import { LayersEnum } from '@lobechat/types';+import { z } from 'zod';++import { MemoryTypeSchema } from './common';++/**+ * Preference origin context+ */+export const OriginContextSchema = z.object({+ actor: z.string().describe("Who stated the preference; use 'User' for the user"),+ applicableWhen: z.string().nullable().describe('Conditions where this preference applies'),+ notApplicableWhen: z.string().nullable().describe('Conditions where it does not apply'),+ scenario: z.string().nullable().describe('Applicable scenario or use case'),+ trigger: z.string().nullable().describe('What prompted this preference'),+});++/**+ * Application context for preferences+ */+export const AppContextSchema = z.object({+ app: z.string().nullable().describe('App or product name this applies to'),+ feature: z.string().nullable(),+ route: z.string().nullable(),+ surface: z.string().nullable().describe('e.g., chat, emails, code review, notes'),+});++/**+ * Preference-specific fields+ */+export const WithPreferenceSchema = z.object({+ appContext: AppContextSchema.nullable().describe(+ 'Application/surface specific preference, if any',+ ),+ conclusionDirectives: z+ .string()+ .describe(+ "Direct, self-contained instruction to the assistant from the user's perspective (what to do, not how to implement)",+ ),+ extractedLabels: z+ .array(z.string())+ .describe('Model generated tags that summarize the preference facets'),+ extractedScopes: z+ .array(z.string())+ .describe('Array of JSON strings describing preference facets and applicable scopes'),+ originContext: OriginContextSchema.nullable().describe(+ 'Context of how/why this preference was expressed',+ ),+ scorePriority: z+ .number()+ .min(0)+ .max(1)+ .describe(+ 'Numeric prioritization weight (0-1 (0% to 100%)) where higher means more critical to respect',+ ),+ suggestions: z+ .array(z.string())+ .describe('Follow-up actions or assistant guidance derived from the preference'),+ type: z+ .string()+ .describe("High level preference classification (e.g., 'lifestyle', 'communication')"),+});++/**+ * Single preference memory item+ */+export const PreferenceMemoryItemSchema = z.object({+ details: z.string().describe('Optional detailed information'),+ memoryCategory: z.string().describe('Memory category'),+ memoryLayer: z.literal(LayersEnum.Preference).describe('Memory layer'),+ memoryType: MemoryTypeSchema.describe('Memory type'),+ summary: z.string().describe('Concise overview of this specific memory'),+ tags: z.array(z.string()).describe('Model generated tags that summarize the preference facets'),+ title: z.string().describe('Brief descriptive title'),+ withPreference: WithPreferenceSchema,+});++/**+ * Preference memory extraction result+ */+export const PreferenceMemorySchema = z.object({+ memories: z+ .array(PreferenceMemoryItemSchema)+ .describe(+ 'Array of extracted preference memory items, could be empty if decided no relevant preference to extract',+ ),+});++export type OriginContext = z.infer<typeof OriginContextSchema>;+export type AppContext = z.infer<typeof AppContextSchema>;+export type WithPreference = z.infer<typeof WithPreferenceSchema>;+export type PreferenceMemoryItem = z.infer<typeof PreferenceMemoryItemSchema>;+export type PreferenceMemory = z.infer<typeof PreferenceMemorySchema>;diff --git a/packages/memory-user-memory/src/services/extractExecutor.ts b/packages/memory-user-memory/src/services/extractExecutor.tsnew file mode 100644index 00000000000..57bf6f85c25--- /dev/null+++ b/packages/memory-user-memory/src/services/extractExecutor.ts@@ -0,0 +1,436 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { ModelRuntime } from '@lobechat/model-runtime';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import {+ gateKeeperCallDurationHistogram,+ gateKeeperCallsCounter,+ layerCallDurationHistogram,+ layersCallsCounter,+ tracer,+} from '@lobechat/observability-otel/modules/memory-user-memory';+import { LayersEnum } from '@lobechat/types';++import {+ ContextExtractor,+ ExperienceExtractor,+ IdentityExtractor,+ PreferenceExtractor,+ UserMemoryGateKeeper,+} from '../extractors';+import {+ BaseExtractorDependencies,+ ExtractorOptions,+ GatekeeperDecision,+ MemoryExtractionAgent,+ MemoryContextProvider,+ MemoryExtractionJob,+ MemoryExtractionLLMConfig,+ MemoryExtractionLayerOutputs,+ MemoryExtractionResult,+ MemoryResultRecorder,+ GatekeeperOptions,+} from '../types';+import { resolvePromptRoot } from '../utils/path';+import { attributesCommon } from '@lobechat/observability-otel/node';++const LAYER_ORDER: LayersEnum[] = [+ 'identity' as LayersEnum,+ 'context' as LayersEnum,+ 'preference' as LayersEnum,+ 'experience' as LayersEnum,+];++const LAYER_LABEL_MAP: Record<LayersEnum, string> = {+ context: 'contexts',+ experience: 'experiences',+ identity: 'identities',+ preference: 'preferences',+};++export interface MemoryExtractionRuntimeOptions {+ embeddings?: ModelRuntime;+ gatekeeper: ModelRuntime;+ layerExtractor: ModelRuntime;+}++export interface MemoryExtractionServiceOptions {+ callbacks?: ExtractorOptions['callbacks'];+ config: MemoryExtractionLLMConfig;+ db: LobeChatDatabase;+ language?: string;+ promptRoot?: string;+ runtimes: MemoryExtractionRuntimeOptions;+}++export interface MemoryExtractionLayerOutputTypes {+ [LayersEnum.Context]: Awaited<ReturnType<ContextExtractor['structuredCall']>>+ [LayersEnum.Experience]: Awaited<ReturnType<ExperienceExtractor['structuredCall']>>+ [LayersEnum.Preference]: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>+ [LayersEnum.Identity]: Awaited<ReturnType<IdentityExtractor['structuredCall']>>+}++export type MemoryExtractionLayerOutputType = {+ [K in keyof MemoryExtractionLayerOutputTypes]: MemoryExtractionLayerOutputTypes[K];+}[keyof MemoryExtractionLayerOutputTypes];++export class MemoryExtractionService<RO> {+ private readonly config: MemoryExtractionLLMConfig;++ private readonly gatekeeper: UserMemoryGateKeeper;++ private readonly identityExtractor: IdentityExtractor;+ private readonly contextExtractor: ContextExtractor;+ private readonly experienceExtractor: ExperienceExtractor;+ private readonly preferenceExtractor: PreferenceExtractor;++ private readonly gatekeeperRuntime: ModelRuntime;+ private readonly layerRuntime: ModelRuntime;++ private readonly promptRoot: string;++ constructor(options: MemoryExtractionServiceOptions) {+ this.config = options.config;+ this.gatekeeperRuntime = options.runtimes.gatekeeper;+ this.layerRuntime = options.runtimes.layerExtractor;+ this.promptRoot = options.promptRoot ?? resolvePromptRoot();++ const gatekeeperConfig: BaseExtractorDependencies = {+ agent: 'gatekeeper',+ model: this.config.gateModel,+ modelRuntime: this.gatekeeperRuntime,+ promptRoot: this.promptRoot,+ };++ this.gatekeeper = new UserMemoryGateKeeper(gatekeeperConfig);++ const buildExtractorConfig = (+ layer: LayersEnum,+ agent: MemoryExtractionAgent,+ ): BaseExtractorDependencies => {+ const model = this.config.layerModels[layer];+ if (!model) {+ throw new Error(`Missing model configuration for memory layer: ${layer}`);+ }++ return {+ agent,+ model,+ modelRuntime: this.layerRuntime,+ promptRoot: this.promptRoot,+ } satisfies BaseExtractorDependencies;+ };++ this.identityExtractor = new IdentityExtractor(+ buildExtractorConfig(LayersEnum.Identity, 'layer-identity'),+ );+ this.contextExtractor = new ContextExtractor(+ buildExtractorConfig(LayersEnum.Context, 'layer-context'),+ );+ this.experienceExtractor = new ExperienceExtractor(+ buildExtractorConfig(LayersEnum.Experience, 'layer-experience'),+ );+ this.preferenceExtractor = new PreferenceExtractor(+ buildExtractorConfig(LayersEnum.Preference, 'layer-preference'),+ );+ }++ private recordGatekeeperMetrics(+ job: MemoryExtractionJob,+ durationMs: number,+ status: 'ok' | 'error',+ ) {+ const attributes = {+ source: job.source,+ status,+ user_id: job.userId,+ ...attributesCommon(),+ };++ gateKeeperCallsCounter.add(1, attributes);+ gateKeeperCallDurationHistogram.record(durationMs, attributes);+ }++ private recordLayerCallMetrics(+ job: MemoryExtractionJob,+ layer: LayersEnum,+ durationMs: number,+ status: 'ok' | 'error',+ ) {+ const attributes = {+ layer: LAYER_LABEL_MAP[layer],+ source: job.source,+ status,+ user_id: job.userId,+ ...attributesCommon(),+ };++ layersCallsCounter.add(1, attributes);+ layerCallDurationHistogram.record(durationMs, attributes);+ }++ private async runLayerExtractor<T>(+ job: MemoryExtractionJob,+ layer: LayersEnum,+ extractor: () => Promise<T>,+ ): Promise<T> {+ const attributes = {+ layer: LAYER_LABEL_MAP[layer],+ source: job.source,+ source_id: job.sourceId,+ user_id: job.userId,+ ...attributesCommon(),+ };++ return tracer.startActiveSpan(+ `run${layer.charAt(0).toUpperCase() + layer.slice(1)}LayerExtractor`,+ { attributes },+ async (span) => {+ const start = Date.now();++ try {+ const result = await extractor();+ const duration = Date.now() - start;++ this.recordLayerCallMetrics(job, layer, duration, 'ok');+ span.setStatus({ code: SpanStatusCode.OK });++ return result;+ } catch (error) {+ const duration = Date.now() - start;++ this.recordLayerCallMetrics(job, layer, duration, 'error');+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : 'Layer extraction failed',+ });+ span.recordException(error as Error);+ throw error;+ } finally {+ span.end();+ }+ },+ );+ }++ async run(+ job: MemoryExtractionJob,+ options: {+ contextProvider: MemoryContextProvider<{ topK?: number }>;+ resultRecorder?: MemoryResultRecorder<RO>;+ } & ExtractorOptions & {+ existingIdentitiesContext?: string;+ } & {+ gatekeeperLanguage?: string;+ },+ ): Promise<MemoryExtractionResult | null> {+ try {+ const decision = await this.runGatekeeper(job, { ...options });+ const layersToExtract = this.resolveJobLayers(decision, job.layers);+ const outputs = await this.runLayers(job, layersToExtract, { ...options });++ const processedLayersCount = {+ context: outputs.context?.data ? outputs.context?.data?.memories?.length : 0,+ experience: outputs.experience?.data ? outputs.experience?.data?.memories?.length : 0,+ identity: outputs.identity?.data ? (outputs.identity?.data?.add?.length || 0) + (outputs.identity?.data?.update?.length || 0) + (outputs.identity?.data?.remove?.length || 0) : 0,+ preference: outputs.preference?.data ? outputs.preference?.data?.memories?.length : 0,+ };+ const processedErrorsCount = {+ context: outputs.context?.error ? 1 : 0,+ experience: outputs.experience?.error ? 1 : 0,+ identity: outputs.identity?.error ? 1 : 0,+ preference: outputs.preference?.error ? 1 : 0,+ }++ const processedCount = Object.values(processedLayersCount).reduce((a, b) => a + b, 0);++ return {+ decision,+ inputs: {+ retrievedContexts: options.retrievedContexts,+ retrievedIdentitiesContext: options.retrievedIdentitiesContext,+ },+ layers: layersToExtract,+ outputs,+ processedCounts: processedCount,+ processedErrorsCount: processedErrorsCount,+ processedLayersCount: processedLayersCount,+ };+ } catch (error) {+ await options?.resultRecorder?.recordFail?.(job, error as Error);+ throw error;+ }+ }++ private async runGatekeeper(+ job: MemoryExtractionJob,+ options: GatekeeperOptions,+ ): Promise<GatekeeperDecision> {+ const start = Date.now();++ try {+ const decision = await this.gatekeeper.check({+ callbacks: options.callbacks,+ gateKeeperLanguage: options.gateKeeperLanguage || 'English',+ retrievedContexts: options.retrievedContexts,+ topK: options.topK,+ });+ this.recordGatekeeperMetrics(job, Date.now() - start, 'ok');++ return decision;+ } catch (error) {+ this.recordGatekeeperMetrics(job, Date.now() - start, 'error');+ throw error;+ }+ }++ private async runContextLayer(job: MemoryExtractionJob, options: ExtractorOptions) {+ return this.runLayerExtractor(job, LayersEnum.Context, () =>+ this.contextExtractor.structuredCall({+ ...options,+ language: options.language ?? 'English',+ }),+ );+ }++ private async runExperienceLayer(job: MemoryExtractionJob, options: ExtractorOptions) {+ return this.runLayerExtractor(job, LayersEnum.Experience, () =>+ this.experienceExtractor.structuredCall({+ ...options,+ language: options.language ?? 'English',+ }),+ );+ }++ private async runPreferenceLayer(job: MemoryExtractionJob, options: ExtractorOptions) {+ return this.runLayerExtractor(job, LayersEnum.Preference, () =>+ this.preferenceExtractor.structuredCall({+ ...options,+ language: options.language ?? 'English',+ }),+ );+ }++ private async runIdentityLayer(+ job: MemoryExtractionJob,+ options: ExtractorOptions & {+ existingIdentitiesContext?: string;+ },+ ) {+ return this.runLayerExtractor(job, LayersEnum.Identity, () =>+ this.identityExtractor.structuredCall({+ ...options,+ language: options.language ?? 'English',+ }),+ );+ }++ private resolveLayers(decision: GatekeeperDecision): LayersEnum[] {+ return LAYER_ORDER.filter((layer) => decision[layer]?.shouldExtract);+ }++ private resolveJobLayers(decision: GatekeeperDecision, layers?: LayersEnum[]): LayersEnum[] {+ if (layers && layers.length > 0) {+ const requested = new Set<LayersEnum>(layers);++ return this.resolveLayers(decision).filter((layer) => requested.has(layer));+ }++ return this.resolveLayers(decision);+ }++ private async runLayers(+ job: MemoryExtractionJob,+ layers: LayersEnum[],+ options: ExtractorOptions & {+ existingIdentitiesContext?: string;+ },+ ): Promise<MemoryExtractionLayerOutputs> {+ const outputs: Partial<MemoryExtractionLayerOutputs> = {};++ const setLayerOutput = (+ layer: LayersEnum,+ result:+ | { data: MemoryExtractionLayerOutputType }+ | { error: unknown },+ ) => {+ switch (layer) {+ case LayersEnum.Context: {+ outputs.context = result as+ | { data: MemoryExtractionLayerOutputTypes[typeof layer] }+ | { error: unknown };+ break;+ }+ case LayersEnum.Experience: {+ outputs.experience = result as+ | { data: MemoryExtractionLayerOutputTypes[typeof layer] }+ | { error: unknown };+ break;+ }+ case LayersEnum.Preference: {+ outputs.preference = result as+ | { data: MemoryExtractionLayerOutputTypes[typeof layer] }+ | { error: unknown };+ break;+ }+ case LayersEnum.Identity: {+ outputs.identity = result as+ | { data: MemoryExtractionLayerOutputTypes[typeof layer] }+ | { error: unknown };+ break;+ }+ default: {+ break;+ }+ }+ };++ await Promise.all(+ ([+ LayersEnum.Context,+ LayersEnum.Experience,+ LayersEnum.Preference,+ LayersEnum.Identity,+ ] as LayersEnum[])+ .map(async (layer) => {+ if (!layers.includes(layer)) {+ return+ }++ try {+ const result = await this.runLayer(job, layer, options);+ setLayerOutput(layer, { data: result });+ } catch (error) {+ setLayerOutput(layer, { error });+ }+ }),+ );++ return outputs as MemoryExtractionLayerOutputs;+ }++ private async runLayer<L extends LayersEnum>(+ job: MemoryExtractionJob,+ layer: L,+ options: ExtractorOptions & {+ existingIdentitiesContext?: string;+ },+ ): Promise<MemoryExtractionLayerOutputType> {+ switch (layer) {+ case LayersEnum.Context: {+ return await this.runContextLayer(job, options);+ }+ case LayersEnum.Experience: {+ return await this.runExperienceLayer(job, options);+ }+ case LayersEnum.Preference: {+ return await this.runPreferenceLayer(job, options);+ }+ case LayersEnum.Identity: {+ return await this.runIdentityLayer(job, options);+ }+ default: {+ throw new Error(`Unsupported memory layer: ${layer}`);+ }+ }+ }+}diff --git a/packages/memory-user-memory/src/types.ts b/packages/memory-user-memory/src/types.tsnew file mode 100644index 00000000000..e96543048d6--- /dev/null+++ b/packages/memory-user-memory/src/types.ts@@ -0,0 +1,166 @@+import type {+ GenerateObjectPayload,+ ModelRuntime,+ OpenAIChatMessage,+} from '@lobechat/model-runtime';+import type { LayersEnum } from '@lobechat/types';++import type {+ ContextExtractor,+ ExperienceExtractor,+ IdentityExtractor,+ PreferenceExtractor,+} from './extractors';++export type MemoryExtractionAgent =+ | 'gatekeeper'+ | 'layer-context'+ | 'layer-experience'+ | 'layer-identity'+ | 'layer-preference';++export interface ExtractorOptions extends ExtractorTemplateProps {+ additionalMessages?: OpenAIChatMessage[];+ callbacks?: {+ onExtractError?: (agent: MemoryExtractionAgent, error: unknown) => Promise<void> | void;+ onExtractRequest?: (agent: MemoryExtractionAgent, request: GenerateObjectPayload) =>+ | Promise<void>+ | void;+ onExtractResponse?: <TOutput>(agent: MemoryExtractionAgent, response: TOutput) =>+ | Promise<void>+ | void;+ };+ messageIds?: string[];+ sourceId?: string;+ userId?: string;+}++export interface ExtractorTemplateProps {+ availableCategories?: string[];+ language?: string;+ retrievedContexts?: string[];+ retrievedIdentitiesContext?: string;+ sessionDate?: string;+ topK?: number;+ username?: string;+}++export interface GatekeeperTemplateProps extends ExtractorTemplateProps {+ gateKeeperLanguage?: string;+}++// eslint-disable-next-line @typescript-eslint/no-empty-interface+export type GatekeeperOptions = Pick<ExtractorOptions, 'retrievedContexts' | 'topK'> & {+ additionalMessages?: OpenAIChatMessage[];+ callbacks?: ExtractorOptions['callbacks'];+ gateKeeperLanguage?: string;+};++export interface BaseExtractorDependencies {+ agent: MemoryExtractionAgent;+ model: string;+ modelRuntime: ModelRuntime;+ promptRoot: string;+}++export interface MemoryExtractionLLMConfig {+ embeddingsModel?: string;+ gateModel: string;+ layerModels: Partial<Record<LayersEnum, string>>;+ provider?: string;+}++export interface MemoryExtractionJob {+ force?: boolean;+ layers?: LayersEnum[];+ source: MemoryExtractionSourceType;+ sourceId: string;+ sourceUpdatedAt?: Date;+ userId: string;+}++export interface MemoryExtractionSourceMetadata {+ error?: string;+ lastConversationDigest?: string;+ lastProcessedAt?: string;+ lastProcessedMessageId?: string;+ status?: 'pending' | 'completed' | 'failed';+ version?: string;+}++export type MemoryExtractionSourceType = 'chat_topic' | 'obsidian' | 'notion' | 'lark';++// eslint-disable-next-line @typescript-eslint/no-empty-interface+export type ContextOptions<P extends Record<string, unknown>> = P;++export interface BuiltContext<T = Record<string, unknown>> {+ context: string;+ metadata: T;+ sourceId: string;+ userId: string;+}++export interface MemoryContextProvider<+ P extends Record<string, unknown> = Record<string, unknown>,+ R extends Record<string, unknown> = Record<string, unknown>,+> {+ buildContext(job: MemoryExtractionJob, options?: P): Promise<BuiltContext<R>>;+}++export interface MemoryResultRecorder<T = Record<string, unknown>> {+ recordComplete(job: MemoryExtractionJob, result: PersistedMemoryResult & T): Promise<void>;+ recordFail?(job: MemoryExtractionJob, error: Error): Promise<void>;+}++export interface PersistedMemoryResult {+ createdIds: string[];+ layers: Partial<Record<LayersEnum, number>>;+}++export type MemoryExtractionLayerOutputs = Partial<{+ context: {+ data?: Awaited<ReturnType<ContextExtractor['structuredCall']>>;+ error?: unknown;+ };+ experience: {+ data?: Awaited<ReturnType<ExperienceExtractor['structuredCall']>>;+ error?: unknown;+ };+ identity: {+ data?: Awaited<ReturnType<IdentityExtractor['structuredCall']>>;+ error?: unknown;+ }+ preference: {+ data?: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>;+ error?: unknown;+ }+}>;++export interface GatekeeperDecision {+ context: MemoryLayerDecision;+ experience: MemoryLayerDecision;+ identity: MemoryLayerDecision;+ preference: MemoryLayerDecision;+}++export interface MemoryLayerDecision {+ reasoning: string;+ shouldExtract: boolean;+}++export interface MemoryExtractionResult {+ decision: GatekeeperDecision;+ inputs: {+ retrievedContexts?: string[];+ retrievedIdentitiesContext?: string;+ };+ layers: LayersEnum[];+ outputs: MemoryExtractionLayerOutputs;+ processedCounts: number;+ processedErrorsCount: Record<LayersEnum, number>;+ processedLayersCount: Record<LayersEnum, number>;+}++export interface TemplateProps {+ [key: string]: unknown;+}diff --git a/packages/memory-user-memory/src/utils/path.ts b/packages/memory-user-memory/src/utils/path.tsnew file mode 100644index 00000000000..293ee2c6846--- /dev/null+++ b/packages/memory-user-memory/src/utils/path.ts@@ -0,0 +1,5 @@+import path from 'node:path';++export const resolvePromptRoot = (): string => {+ return path.resolve(process.cwd(), 'packages/memory-user-memory/src/prompts');+};diff --git a/packages/memory-user-memory/src/utils/zod.ts b/packages/memory-user-memory/src/utils/zod.tsnew file mode 100644index 00000000000..77d671dad6f--- /dev/null+++ b/packages/memory-user-memory/src/utils/zod.ts@@ -0,0 +1,39 @@+import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import { z } from 'zod';+import { zodToJsonSchema } from 'zod-to-json-schema';++export interface BuildSchemaOptions {+ description?: string;+ name: string;+ strict?: boolean;+}++const pickMainSchema = (result: any, name: string) => {+ if (result?.$defs?.[name]) {+ return result.$defs[name];+ }+ if (result?.definitions?.[name]) {+ return result.definitions[name];+ }++ return result;+};++export const buildGenerateObjectSchema = (+ schema: z.ZodTypeAny,+ options: BuildSchemaOptions,+): GenerateObjectSchema => {+ const fullSchema = zodToJsonSchema(schema, options.name);++ const jsonSchema = pickMainSchema(fullSchema, options.name);+ if (jsonSchema.type === 'object') {+ jsonSchema.additionalProperties = false;+ }++ return {+ description: options.description,+ name: options.name,+ schema: jsonSchema,+ strict: options.strict ?? true,+ } satisfies GenerateObjectSchema;+};diff --git a/packages/memory-extract/vitest.config.mts b/packages/memory-user-memory/vitest.config.tssimilarity index 100%rename from packages/memory-extract/vitest.config.mtsrename to packages/memory-user-memory/vitest.config.tsdiff --git a/packages/obervability-otel/package.json b/packages/obervability-otel/package.jsonindex a39a7b791b4..35b3c722fa8 100644--- a/packages/obervability-otel/package.json+++ b/packages/obervability-otel/package.json@@ -5,7 +5,9 @@"exports": {"./node": "./src/node.ts","./api": "./src/api.ts",- "./trpc": "./src/trpc/index.ts"+ "./trpc": "./src/trpc/index.ts",+ "./gen-ai": "./src/gen-ai/index.ts",+ "./modules/memory-user-memory": "./src/modules/memory-user-memory/index.ts"},"dependencies": {"@opentelemetry/api": "^1.9.0",diff --git a/packages/obervability-otel/src/gen-ai/index.ts b/packages/obervability-otel/src/gen-ai/index.tsnew file mode 100644index 00000000000..a97ea0f450b--- /dev/null+++ b/packages/obervability-otel/src/gen-ai/index.ts@@ -0,0 +1 @@+export * from './semconv';diff --git a/packages/obervability-otel/src/gen-ai/semconv.ts b/packages/obervability-otel/src/gen-ai/semconv.tsnew file mode 100644index 00000000000..f98dca4cd11--- /dev/null+++ b/packages/obervability-otel/src/gen-ai/semconv.ts@@ -0,0 +1,208 @@+/*+ * Copyright The OpenTelemetry Authors+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/*+ * This file contains a copy of unstable semantic convention definitions+ * used by this package.+ * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv+ */++/**+ * Identifies the class / type of event.+ *+ * @example browser.mouse.click+ * @example device.app.lifecycle+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ *+ * @deprecated Replaced by EventName top-level field on the LogRecord.+ */+export const ATTR_EVENT_NAME = 'event.name' as const;++/**+ * The name of the operation being performed.+ *+ * @note If one of the predefined values applies, but specific system uses a different name it's **RECOMMENDED** to document it in the semantic conventions for specific GenAI system and use system-specific name in the instrumentation. If a different name is not documented, instrumentation libraries **SHOULD** use applicable predefined value.+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name' as const;++/**+ * The encoding formats requested in an embeddings operation, if specified.+ *+ * @example ["base64"]+ * @example ["float", "binary"]+ *+ * @note In some GenAI systems the encoding formats are called embedding types. Also, some GenAI systems only accept a single format per request.+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_ENCODING_FORMATS = 'gen_ai.request.encoding_formats' as const;++/**+ * The frequency penalty setting for the GenAI request.+ *+ * @example 0.1+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY = 'gen_ai.request.frequency_penalty' as const;++/**+ * The maximum number of tokens the model generates for a request.+ *+ * @example 100+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_MAX_TOKENS = 'gen_ai.request.max_tokens' as const;++/**+ * The name of the GenAI model a request is being made to.+ *+ * @example "gpt-4"+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model' as const;++/**+ * The presence penalty setting for the GenAI request.+ *+ * @example 0.1+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY = 'gen_ai.request.presence_penalty' as const;++/**+ * List of sequences that the model will use to stop generating further tokens.+ *+ * @example ["forest", "lived"]+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_STOP_SEQUENCES = 'gen_ai.request.stop_sequences' as const;++/**+ * The temperature setting for the GenAI request.+ *+ * @example 0.0+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_TEMPERATURE = 'gen_ai.request.temperature' as const;++/**+ * The top_p sampling setting for the GenAI request.+ *+ * @example 1.0+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_REQUEST_TOP_P = 'gen_ai.request.top_p' as const;++/**+ * Array of reasons the model stopped generating tokens, corresponding to each generation received.+ *+ * @example ["stop"]+ * @example ["stop", "length"]+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_RESPONSE_FINISH_REASONS = 'gen_ai.response.finish_reasons' as const;++/**+ * The unique identifier for the completion.+ *+ * @example chatcmpl-123+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_RESPONSE_ID = 'gen_ai.response.id' as const;++/**+ * The name of the model that generated the response.+ *+ * @example gpt-4-0613+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_RESPONSE_MODEL = 'gen_ai.response.model' as const;++/**+ * The Generative AI product as identified by the client or server instrumentation.+ *+ * @example "openai"+ *+ * @note The `gen_ai.system` describes a family of GenAI models with specific model identified+ * by `gen_ai.request.model` and `gen_ai.response.model` attributes.+ *+ * The actual GenAI product may differ from the one identified by the client.+ * Multiple systems, including Azure OpenAI and Gemini, are accessible by OpenAI client+ * libraries. In such cases, the `gen_ai.system` is set to `openai` based on the+ * instrumentation's best knowledge, instead of the actual system. The `server.address`+ * attribute may help identify the actual system in use for `openai`.+ *+ * For custom model, a custom friendly name **SHOULD** be used.+ * If none of these options apply, the `gen_ai.system` **SHOULD** be set to `_OTHER`.+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_SYSTEM = 'gen_ai.system' as const;++/**+ * The type of token being counted.+ *+ * @example input+ * @example output+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_TOKEN_TYPE = 'gen_ai.token.type' as const;++/**+ * The number of tokens used in the GenAI input (prompt).+ *+ * @example 100+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens' as const;++/**+ * The number of tokens used in the GenAI response (completion).+ *+ * @example 180+ *+ * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens' as const;++/**+ * GenAI operation duration+ *+ * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const METRIC_GEN_AI_CLIENT_OPERATION_DURATION = 'gen_ai.client.operation.duration' as const;++/**+ * Measures number of input and output tokens used+ *+ * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.+ */+export const METRIC_GEN_AI_CLIENT_TOKEN_USAGE = 'gen_ai.client.token.usage' as const;diff --git a/packages/obervability-otel/src/modules/index.ts b/packages/obervability-otel/src/modules/index.tsnew file mode 100644index 00000000000..4b785bfd12c--- /dev/null+++ b/packages/obervability-otel/src/modules/index.ts@@ -0,0 +1 @@+export * from './memory-user-memory';diff --git a/packages/obervability-otel/src/modules/memory-user-memory/extract.ts b/packages/obervability-otel/src/modules/memory-user-memory/extract.tsnew file mode 100644index 00000000000..f80ee45517d--- /dev/null+++ b/packages/obervability-otel/src/modules/memory-user-memory/extract.ts@@ -0,0 +1,61 @@+import { metrics, trace } from '@opentelemetry/api';++const meter = metrics.getMeter('server-services-memory-user-memory-extraction');+export const tracer = trace.getTracer('@lobechat/memory-user-memory', '0.0.1');++export const processedSourceCounter = meter.createCounter(+ 'server_services_memory_user_memory_extraction_processed_source',+ {+ description:+ 'Count of memory extraction jobs processed per source and user with completion status.',+ unit: '{count}',+ },+);++export const processedDurationHistogram = meter.createHistogram(+ 'server_services_memory_user_memory_extraction_processed_duration',+ {+ description: 'Duration of memory extraction jobs per source and user.',+ unit: 'ms',+ },+);++export const gateKeeperCallsCounter = meter.createCounter(+ 'server_services_memory_user_memory_extraction_gate_keeper_calls',+ {+ description: 'Gate keeper invocation count by source, user, and status.',+ unit: '{count}',+ },+);++export const gateKeeperCallDurationHistogram = meter.createHistogram(+ 'server_services_memory_user_memory_extraction_gate_keeper_call_duration',+ {+ description: 'Duration of gate keeper invocations by source, user, and status.',+ unit: 'ms',+ },+);++export const layersCallsCounter = meter.createCounter(+ 'server_services_memory_user_memory_extraction_layers_calls',+ {+ description: 'Layer extractor invocation count by layer, source, user, and status.',+ unit: '{count}',+ },+);++export const layerCallDurationHistogram = meter.createHistogram(+ 'server_services_memory_user_memory_extraction_layer_call_duration',+ {+ description: 'Duration of layer extractor calls by layer, source, user, and status.',+ unit: 'ms',+ },+);++export const layerEntriesHistogram = meter.createHistogram(+ 'server_services_memory_user_memory_extraction_layer_entries',+ {+ description: 'Number of entries produced per layer extraction by source and user.',+ unit: '{count}',+ },+);diff --git a/packages/obervability-otel/src/modules/memory-user-memory/index.ts b/packages/obervability-otel/src/modules/memory-user-memory/index.tsnew file mode 100644index 00000000000..513ffa3b047--- /dev/null+++ b/packages/obervability-otel/src/modules/memory-user-memory/index.ts@@ -0,0 +1 @@+export * from './extract';diff --git a/packages/obervability-otel/src/node.ts b/packages/obervability-otel/src/node.tsindex fbf5b21a682..f0f3582a703 100644--- a/packages/obervability-otel/src/node.ts+++ b/packages/obervability-otel/src/node.ts@@ -1,19 +1,68 @@+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */import { DiagConsoleLogger, DiagLogLevel, diag } from '@opentelemetry/api';import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';-import { resourceFromAttributes } from '@opentelemetry/resources';+import { resourceFromAttributes, DetectedResourceAttributes } from '@opentelemetry/resources';import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';import { NodeSDK } from '@opentelemetry/sdk-node';import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions';import { env } from 'node:process';-export function register(options?: { debug?: true | DiagLogLevel; version?: string }) {- const attributes: Record<string, string> = {+export function attributesForVercel(): DetectedResourceAttributes {+ return {+ // Vercel.+ // https://vercel.com/docs/projects/environment-variables/system-environment-variables+ // Vercel Env set as top level attribute for simplicity. One of 'production', 'preview' or 'development'.+ env: process.env.VERCEL_ENV || process.env.NEXT_PUBLIC_VERCEL_ENV,++ "vercel.branch_host":+ process.env.VERCEL_BRANCH_URL ||+ process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL ||+ undefined,+ "vercel.deployment_id": process.env.VERCEL_DEPLOYMENT_ID || undefined,+ "vercel.host":+ process.env.VERCEL_URL ||+ process.env.NEXT_PUBLIC_VERCEL_URL ||+ undefined,+ "vercel.project_id": process.env.VERCEL_PROJECT_ID || undefined,+ "vercel.region": process.env.VERCEL_REGION,+ "vercel.runtime": process.env.NEXT_RUNTIME || "nodejs",+ "vercel.sha":+ process.env.VERCEL_GIT_COMMIT_SHA ||+ process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA,++ 'service.version': process.env.VERCEL_DEPLOYMENT_ID,+ }+}++export function attributesForNodejs(): DetectedResourceAttributes {+ return {+ // Node.+ "node.ci": process.env.CI ? true : undefined,+ "node.env": process.env.NODE_ENV,+ }+}++export function attributesForEnv(): DetectedResourceAttributes {+ return {+ ...attributesForVercel(),+ ...attributesForNodejs(),+ }+}++export function attributesCommon(): DetectedResourceAttributes {+ return {[ATTR_SERVICE_NAME]: 'lobe-chat',- };+ ...attributesForEnv(),+ }+}++export function register(options?: { debug?: true | DiagLogLevel; version?: string }) {+ const attributes = attributesCommon();+if (typeof options?.version !== 'undefined') {attributes[ATTR_SERVICE_VERSION] = options.version;}