🤯 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
♻️ refactor: migrate memory-user-memory workflows to Hono (#13768)
Arvin Xu4feafb3fcb43
diff --git a/package.json b/package.jsonindex ceb1be43cfc..b4ce03d22af 100644--- a/package.json+++ b/package.json@@ -330,6 +330,7 @@"file-type": "^21.3.0","fuse.js": "^7.0.0","gray-matter": "^4.0.3",+ "hono": "^4.11.1","html-to-text": "^9.0.5","i18next": "^25.8.0","i18next-browser-languagedetector": "^8.2.0",diff --git a/src/app/(backend)/api/workflows/memory-user-memory/[[...route]]/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/[[...route]]/route.tsnew file mode 100644index 00000000000..fce1b3a02b4--- /dev/null+++ b/src/app/(backend)/api/workflows/memory-user-memory/[[...route]]/route.ts@@ -0,0 +1,3 @@+import app from '@/server/workflows-hono/memory-user-memory/app';++export const POST = (request: Request) => app.fetch(request);diff --git a/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.tsdeleted file mode 100644index 1bf2fac5f7a..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.ts+++ /dev/null@@ -1,117 +0,0 @@-import { MemorySourceType } from '@lobechat/types';-import { Client } from '@upstash/qstash';-import { serve } from '@upstash/workflow/nextjs';-import { chunk } from 'es-toolkit/compat';--import { appEnv } from '@/envs/app';-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';-import {- buildWorkflowPayloadInput,- MemoryExtractionExecutor,- type MemoryExtractionHourlyWorkflowPayload,- MemoryExtractionWorkflowService,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--const USER_PAGE_SIZE = 200;-const USER_BATCH_SIZE = 20;--const { webhook, upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();--const resolveBaseUrl = () => webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEnv.APP_URL;--export const { POST } = serve<MemoryExtractionHourlyWorkflowPayload>(- async (context) => {- const { cursor, dryRun } = context.requestPayload || {};-- const baseUrl = resolveBaseUrl();- if (!baseUrl) {- throw new Error('Missing baseUrl for hourly memory extraction workflow');- }-- const parsedCursor = cursor- ? { createdAt: new Date(cursor.createdAt), id: cursor.id }- : undefined;- if (parsedCursor && Number.isNaN(parsedCursor.createdAt.getTime())) {- throw new Error('Invalid cursor date for hourly memory extraction workflow');- }-- const executor = await MemoryExtractionExecutor.create();- const userBatch = await context.run(- `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`,- () => executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),- );-- const userIds = userBatch.ids;- if (userIds.length === 0) {- return { message: 'No eligible users for hourly memory extraction.', processedUsers: 0 };- }-- const nextCursor = userBatch.cursor- ? {- createdAt: userBatch.cursor.createdAt.toISOString(),- id: userBatch.cursor.id,- }- : undefined;-- if (!dryRun) {- const batches = chunk(userIds, USER_BATCH_SIZE);- await Promise.all(- batches.map((batchUserIds, index) =>- context.run(`memory:user-memory:hourly:trigger-users:${index}`, () =>- MemoryExtractionWorkflowService.triggerProcessUsers(- buildWorkflowPayloadInput(- normalizeMemoryExtractionPayload({- baseUrl,- mode: 'workflow',- sources: [MemorySourceType.ChatTopic],- userIds: batchUserIds,- }),- ),- { extraHeaders: upstashWorkflowExtraHeaders },- ),- ),- ),- );- }-- if (nextCursor) {- await context.run('memory:user-memory:hourly:schedule-next-page', () =>- MemoryExtractionWorkflowService.triggerHourly(- {- baseUrl,- cursor: nextCursor,- dryRun,- },- { extraHeaders: upstashWorkflowExtraHeaders },- ),- );- }-- return {- dryRun: !!dryRun,- hasNextPage: !!nextCursor,- processedUsers: userIds.length,- scheduledBatches: dryRun ? 0 : chunk(userIds, USER_BATCH_SIZE).length,- };- },- {- flowControl: {- key: 'memory-user-memory.call-cron-hourly-analysis',- parallelism: 1,- ratePerSecond: 1,- },- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)- // for passing additional headers, we have to provide a custom QStash client with the required headers here.- //- // Refer to the doc for more details:- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),- },-);diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/[...any]/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/[...any]/route.tsdeleted file mode 100644index b86572ac51c..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/[...any]/route.ts+++ /dev/null@@ -1,22 +0,0 @@-import { Client } from '@upstash/qstash';-import { serveMany } from '@upstash/workflow/dist/nextjs';--import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';--import { processTopicWorkflow } from '../process-topic/workflows/topic';--const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();--export const { POST } = serveMany(- {- 'process-topic': processTopicWorkflow,- },- {- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),- },-);diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.tsdeleted file mode 100644index f928cb0ed62..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts+++ /dev/null@@ -1,180 +0,0 @@-import { SpanStatusCode } from '@lobechat/observability-otel/api';-import {- buildUpstashWorkflowAttributes,- tracer as upstashWorkflowTracer,-} from '@lobechat/observability-otel/modules/upstash-workflow';-import { LayersEnum, MemorySourceType } from '@lobechat/types';-import { Client } from '@upstash/qstash';-import { WorkflowAbort } from '@upstash/workflow';-import { serve } from '@upstash/workflow/nextjs';--import { AsyncTaskModel } from '@/database/models/asyncTask';-import { getServerDB } from '@/database/server';-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';-import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';-import {- MemoryExtractionWorkflowService,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--import { processTopicWorkflow } from '../process-topic/workflows/topic';--const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();--const CEPA_LAYERS: LayersEnum[] = [- LayersEnum.Context,- LayersEnum.Experience,- LayersEnum.Preference,- LayersEnum.Activity,-];-const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];--export const { POST } = serve<MemoryExtractionPayloadInput>(- (context) =>- upstashWorkflowTracer.startActiveSpan(- 'workflow:memory-user-memory:process-topics',- async (span) => {- const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});-- span.setAttributes({- ...buildUpstashWorkflowAttributes(context),- 'workflow.memory_user_memory.force_all': payload.forceAll,- 'workflow.memory_user_memory.force_topics': payload.forceTopics,- 'workflow.memory_user_memory.layers': payload.layers.join(','),- 'workflow.memory_user_memory.source': payload.sources.join(','),- 'workflow.memory_user_memory.topic_count': payload.topicIds.length,- 'workflow.memory_user_memory.user_count': payload.userIds.length,- 'workflow.name': 'memory-user-memory:process-topics',- });-- try {- if (!payload.userIds.length) {- span.setStatus({ code: SpanStatusCode.OK });-- return {- message: 'No user id provided for topic batch.',- processedTopics: 0,- processedUsers: 0,- };- }- if (!payload.topicIds.length) {- span.setStatus({ code: SpanStatusCode.OK });-- return {- message: 'No topic ids provided for extraction.',- processedTopics: 0,- processedUsers: 0,- };- }- if (!payload.sources.includes(MemorySourceType.ChatTopic)) {- span.setStatus({ code: SpanStatusCode.OK });-- return {- message: 'Source not supported in topic batch.',- processedTopics: 0,- processedUsers: 0,- };- }-- const userId = payload.userIds[0];- if (payload.asyncTaskId && userId) {- // NOTICE: Cooperative cascading cancellation for the workflow tree.- // If cancelled, stop before fan-out into per-topic child workflows.- const cancelled = await context.run(- `memory:user-memory:extract:users:${userId}:cancel-check`,- () =>- getServerDB().then((db) =>- new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(- payload.asyncTaskId!,- ),- ),- );- if (cancelled) {- span.setStatus({ code: SpanStatusCode.OK });- return {- message: 'Memory extraction task cancellation requested, skip topic batch.',- processedTopics: 0,- processedUsers: 0,- };- }- }- // Delegate per-topic extraction to dedicated workflow for better isolation- await Promise.all(- payload.topicIds.map(async (topicId, index) => {- await context.invoke(- `memory:user-memory:extract:users:${userId}:topics:${topicId}:invoke:${index}`,- {- body: {- ...payload,- layers: payload.layers.length- ? payload.layers- : [...CEPA_LAYERS, ...IDENTITY_LAYERS],- topicIds: [topicId],- userId,- userIds: [userId],- },- // CEPA: run in parallel across the batch- //- // NOTICE: if modified the parallelism of CEPA_LAYERS- // or added new memory layer, make sure to update the number below.- //- // Currently, CEPA (context, experience, preference, activity) + identity = 5 layers.- // and since identity requires sequential processing, we set parallelism to 5.- flowControl: {- key: `memory-user-memory.pipelines.chat-topic.process-topic.user.${userId}.topic.${topicId}`,- parallelism: 5,- },- headers: upstashWorkflowExtraHeaders,- workflow: processTopicWorkflow,- },- );- }),- );-- // Trigger user persona update after topic processing using the workflow client.- await context.run(`memory:user-memory:users:${userId}`, async () => {- await MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {- extraHeaders: upstashWorkflowExtraHeaders,- });- });-- span.setStatus({ code: SpanStatusCode.OK });-- return {- processedTopics: payload.topicIds.length,- processedUsers: payload.userIds.length,- };- } catch (error) {- // NOTICE: Let WorkflowAbort bubble up (used internally by Upstash); record others- if (error instanceof WorkflowAbort) {- console.warn('workflow aborted:', error.message);- throw error;- }-- span.recordException(error as Error);- span.setStatus({- code: SpanStatusCode.ERROR,- message: error instanceof Error ? error.message : 'process-topics workflow failed',- });-- throw error;- } finally {- span.end();- }- },- ),- {- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)- // for passing additional headers, we have to provide a custom QStash client with the required headers here.- //- // Refer to the doc for more details:- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),- },-);diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.tsdeleted file mode 100644index 5185caca0a9..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts+++ /dev/null@@ -1,176 +0,0 @@-import { MemorySourceType } from '@lobechat/types';-import { Client } from '@upstash/qstash';-import { serve } from '@upstash/workflow/nextjs';--import { AsyncTaskModel } from '@/database/models/asyncTask';-import { type ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';-import { getServerDB } from '@/database/server';-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';-import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';-import {- buildWorkflowPayloadInput,- MemoryExtractionExecutor,- MemoryExtractionWorkflowService,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';-import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';--const TOPIC_PAGE_SIZE = 50;-const TOPIC_BATCH_SIZE = 4;--const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();--export const { POST } = serve<MemoryExtractionPayloadInput>(- async (context) => {- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});- if (!params.userIds.length) {- return { message: 'No user ids provided for topic processing.' };- }- if (!params.sources.includes(MemorySourceType.ChatTopic)) {- return { message: 'No supported sources requested, skip topic processing.' };- }-- const executor = await MemoryExtractionExecutor.create();-- const scheduleNextPage = async (userId: string, cursorCreatedAt: Date, cursorId: string) => {- await MemoryExtractionWorkflowService.triggerProcessUserTopics(- {- ...buildWorkflowPayloadInput({- ...params,- topicCursor: {- createdAt: cursorCreatedAt.toISOString(),- id: cursorId,- userId,- },- topicIds: [],- userId,- userIds: [userId],- }),- },- { extraHeaders: upstashWorkflowExtraHeaders },- );- };-- for (const userId of params.userIds) {- if (params.asyncTaskId) {- // NOTICE: Cooperative cascading cancellation for the workflow tree.- // A cancelled root task should stop at user-topic pagination and avoid enqueuing topic batches.- const cancelled = await context.run(- `memory:user-memory:extract:users:${userId}:cancel-check`,- () =>- getServerDB().then((db) =>- new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(- params.asyncTaskId!,- ),- ),- );- if (cancelled) {- continue;- }- }-- const topicCursor =- params.topicCursor && params.topicCursor.userId === userId- ? {- createdAt: new Date(params.topicCursor.createdAt),- id: params.topicCursor.id,- }- : undefined;-- const topicsFromPayload =- params.topicIds && params.topicIds.length > 0- ? await context.run(- `memory:user-memory:extract:users:${userId}:filter-topic-ids`,- async () => {- const filtered = await executor.filterTopicIdsForUser(userId, params.topicIds);- return filtered.length > 0 ? filtered : undefined;- },- )- : undefined;-- const topicBatch = await context.run<{- cursor?: ListTopicsForMemoryExtractorCursor;- ids: string[];- }>(- `memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`,- () =>- topicsFromPayload && topicsFromPayload.length > 0- ? Promise.resolve({ ids: topicsFromPayload })- : executor.getTopicsForUser(- {- cursor: topicCursor,- forceAll: params.forceAll,- forceTopics: params.forceTopics,- from: params.from,- to: params.to,- userId,- },- TOPIC_PAGE_SIZE,- ),- );-- const ids = topicBatch.ids;- if (!ids.length) {- continue;- }-- const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;-- // TODO: follow the new pattern of process-topic- // remove the batch sequential, replace it with context.invoke(...) pattern- await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {- // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path- // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow- // URLs would inherit that base and lose the desired /process-topics/workflows prefix.- await context.run(- `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,- () =>- MemoryExtractionWorkflowService.triggerProcessTopics(- userId,- {- ...buildWorkflowPayloadInput(params),- topicCursor: undefined,- topicIds,- userId,- userIds: [userId],- },- { extraHeaders: upstashWorkflowExtraHeaders },- ),- );- });-- if (!topicsFromPayload && cursor) {- await context.run(- `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`,- () => {- // NOTICE: Upstash Workflow only supports serializable data into plain JSON,- // this causes the Date object to be converted into string when passed as parameter from- // context to child workflow. So we need to convert it back to Date object here.- const createdAt = new Date(cursor.createdAt);- if (Number.isNaN(createdAt.getTime())) {- throw new Error('Invalid cursor date when scheduling next topic page');- }-- return scheduleNextPage(userId, createdAt, cursor.id);- },- );- }- }-- return { processedUsers: params.userIds.length };- },- {- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)- // for passing additional headers, we have to provide a custom QStash client with the required headers here.- //- // Refer to the doc for more details:- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),- },-);diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.tsdeleted file mode 100644index 3d7d74ea27f..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts+++ /dev/null@@ -1,115 +0,0 @@-import { Client } from '@upstash/qstash';-import { serve } from '@upstash/workflow/nextjs';-import { chunk } from 'es-toolkit/compat';--import { AsyncTaskModel } from '@/database/models/asyncTask';-import { getServerDB } from '@/database/server';-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';-import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';-import {- buildWorkflowPayloadInput,- MemoryExtractionExecutor,- MemoryExtractionWorkflowService,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--const USER_PAGE_SIZE = 50;-const USER_BATCH_SIZE = 10;--const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();--export const { POST } = serve<MemoryExtractionPayloadInput>(- async (context) => {- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});- if (params.sources.length === 0) {- return { message: 'No sources provided, skip memory extraction.' };- }- if (params.asyncTaskId && params.userIds[0]) {- // NOTICE: Cooperative cascading cancellation for the workflow tree.- // If root task has cancelRequestedAt, this stage stops scheduling child workflows.- const cancelled = await context.run('memory:user-memory:extract:cancel-check:root', () =>- getServerDB().then((db) =>- new AsyncTaskModel(db, params.userIds[0]!).isUserMemoryExtractionCancellationRequested(- params.asyncTaskId!,- ),- ),- );- if (cancelled) {- return { message: 'Memory extraction task cancellation requested, skip processing users.' };- }- }-- const executor = await MemoryExtractionExecutor.create();-- // NOTICE: Upstash Workflow only supports serializable data into plain JSON,- // this causes the Date object to be converted into string when passed as parameter from- // context to child workflow. So we need to convert it back to Date object here.- const userCursor = params.userCursor- ? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }- : undefined;-- const userBatch = await context.run('memory:user-memory:extract:get-users', () =>- params.userIds.length > 0- ? { ids: params.userIds }- : executor.getUsers(USER_PAGE_SIZE, userCursor),- );-- const ids = userBatch.ids;- if (ids.length === 0) {- return { message: 'No users to process for memory extraction.' };- }-- const cursor = 'cursor' in userBatch ? userBatch.cursor : undefined;-- const batches = chunk(ids, USER_BATCH_SIZE);- await Promise.all(- batches.map((userIds) =>- context.run(`memory:user-memory:extract:users:process-topic-batches`, () =>- MemoryExtractionWorkflowService.triggerProcessUserTopics(- {- ...buildWorkflowPayloadInput(params),- topicCursor: undefined,- userId: userIds[0],- userIds,- },- { extraHeaders: upstashWorkflowExtraHeaders },- ),- ),- ),- );-- if (params.userIds.length === 0 && cursor) {- await context.run('memory:user-memory:extract:users:schedule-next-user-batch', () =>- MemoryExtractionWorkflowService.triggerProcessUsers(- {- ...buildWorkflowPayloadInput({- ...params,- userCursor: { createdAt: cursor.createdAt.toISOString(), id: cursor.id },- }),- },- { extraHeaders: upstashWorkflowExtraHeaders },- ),- );- }-- return {- batches: batches.length,- nextCursor: cursor ? cursor.id : null,- processedUsers: ids.length,- };- },- {- // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,- // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)- // for passing additional headers, we have to provide a custom QStash client with the required headers here.- //- // Refer to the doc for more details:- // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),- },-);diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.tsindex 82e49c9abf7..6294d0bb8d9 100644--- a/src/server/services/memory/userMemory/extract.ts+++ b/src/server/services/memory/userMemory/extract.ts@@ -2357,7 +2357,7 @@ export class MemoryExtractionWorkflowService {flowControl: {key: `memory-user-memory.pipelines.chat-topic.process-topics.user.${userId}`,// NOTICE: if modified the parallelism of- // src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts+ // src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts// or added new memory layer, make sure to update the number below.//// Currently, CEPA (context, experience, preference, activity) + identity = 5 layers.diff --git a/src/server/workflows-hono/memory-user-memory/app.ts b/src/server/workflows-hono/memory-user-memory/app.tsnew file mode 100644index 00000000000..de95cd10ac4--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/app.ts@@ -0,0 +1,53 @@+import { serve, serveMany } from '@upstash/workflow/hono';+import { Hono } from 'hono';++import { createWorkflowQstashClient } from './qstashClient';+import { hourlyWorkflowHandler, hourlyWorkflowOptions } from './workflows/hourly';+import { personaUpdateHandler } from './workflows/personaUpdate';+import { processTopicWorkflow } from './workflows/processTopic';+import { processTopicsHandler } from './workflows/processTopics';+import { processUsersHandler } from './workflows/processUsers';+import { processUserTopicsHandler } from './workflows/processUserTopics';++const app = new Hono().basePath('/api/workflows/memory-user-memory');++app.post(+ '/call-cron-hourly-analysis',+ serve(hourlyWorkflowHandler, {+ ...hourlyWorkflowOptions,+ qstashClient: createWorkflowQstashClient(),+ }),+);++app.post(+ '/pipelines/persona/update-writing',+ serve(personaUpdateHandler, { qstashClient: createWorkflowQstashClient() }),+);++app.post(+ '/pipelines/chat-topic/process-users',+ serve(processUsersHandler, { qstashClient: createWorkflowQstashClient() }),+);++app.post(+ '/pipelines/chat-topic/process-user-topics',+ serve(processUserTopicsHandler, { qstashClient: createWorkflowQstashClient() }),+);++app.post(+ '/pipelines/chat-topic/process-topics',+ serve(processTopicsHandler, { qstashClient: createWorkflowQstashClient() }),+);++// NOTICE: Must use serveMany here. The `context.invoke(processTopicWorkflow)` call in+// process-topics rewrites the URL last segment to the workflowId ("process-topic"). serveMany+// multiplexes by that final segment to dispatch to the right workflow.+app.post(+ '/pipelines/chat-topic/process-topic',+ serveMany(+ { 'process-topic': processTopicWorkflow },+ { qstashClient: createWorkflowQstashClient() },+ ),+);++export default app;diff --git a/src/server/workflows-hono/memory-user-memory/qstashClient.ts b/src/server/workflows-hono/memory-user-memory/qstashClient.tsnew file mode 100644index 00000000000..210d6527f9c--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/qstashClient.ts@@ -0,0 +1,17 @@+import { Client } from '@upstash/qstash';++import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';++const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();++// NOTICE(@nekomeowww): Scenarios like Vercel Deployment Protection require custom headers on+// intermediate `context.run(...)` calls (which don't accept per-call headers). We inject them via+// a shared QStash client. See:+// https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering+export const createWorkflowQstashClient = () =>+ new Client({+ headers: { ...upstashWorkflowExtraHeaders },+ token: process.env.QSTASH_TOKEN!,+ });++export { upstashWorkflowExtraHeaders };diff --git a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts b/src/server/workflows-hono/memory-user-memory/workflows/hourly.tsnew file mode 100644index 00000000000..859d84461a8--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts@@ -0,0 +1,105 @@+import { MemorySourceType } from '@lobechat/types';+import { type WorkflowContext } from '@upstash/workflow';+import { chunk } from 'es-toolkit/compat';++import { appEnv } from '@/envs/app';+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import {+ buildWorkflowPayloadInput,+ MemoryExtractionExecutor,+ type MemoryExtractionHourlyWorkflowPayload,+ MemoryExtractionWorkflowService,+ normalizeMemoryExtractionPayload,+} from '@/server/services/memory/userMemory/extract';++const USER_PAGE_SIZE = 200;+const USER_BATCH_SIZE = 20;++const { webhook, upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();++const resolveBaseUrl = () => webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEnv.APP_URL;++export const hourlyWorkflowHandler = async (+ context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,+) => {+ const { cursor, dryRun } = context.requestPayload || {};++ const baseUrl = resolveBaseUrl();+ if (!baseUrl) {+ throw new Error('Missing baseUrl for hourly memory extraction workflow');+ }++ const parsedCursor = cursor+ ? { createdAt: new Date(cursor.createdAt), id: cursor.id }+ : undefined;+ if (parsedCursor && Number.isNaN(parsedCursor.createdAt.getTime())) {+ throw new Error('Invalid cursor date for hourly memory extraction workflow');+ }++ const executor = await MemoryExtractionExecutor.create();+ const userBatch = await context.run(+ `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`,+ () => executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),+ );++ const userIds = userBatch.ids;+ if (userIds.length === 0) {+ return { message: 'No eligible users for hourly memory extraction.', processedUsers: 0 };+ }++ const nextCursor = userBatch.cursor+ ? {+ createdAt: userBatch.cursor.createdAt.toISOString(),+ id: userBatch.cursor.id,+ }+ : undefined;++ if (!dryRun) {+ const batches = chunk(userIds, USER_BATCH_SIZE);+ await Promise.all(+ batches.map((batchUserIds, index) =>+ context.run(`memory:user-memory:hourly:trigger-users:${index}`, () =>+ MemoryExtractionWorkflowService.triggerProcessUsers(+ buildWorkflowPayloadInput(+ normalizeMemoryExtractionPayload({+ baseUrl,+ mode: 'workflow',+ sources: [MemorySourceType.ChatTopic],+ userIds: batchUserIds,+ }),+ ),+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ ),+ ),+ );+ }++ if (nextCursor) {+ await context.run('memory:user-memory:hourly:schedule-next-page', () =>+ MemoryExtractionWorkflowService.triggerHourly(+ {+ baseUrl,+ cursor: nextCursor,+ dryRun,+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ );+ }++ return {+ dryRun: !!dryRun,+ hasNextPage: !!nextCursor,+ processedUsers: userIds.length,+ scheduledBatches: dryRun ? 0 : chunk(userIds, USER_BATCH_SIZE).length,+ };+};++export const hourlyWorkflowOptions = {+ flowControl: {+ key: 'memory-user-memory.call-cron-hourly-analysis',+ parallelism: 1,+ ratePerSecond: 1,+ },+};diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/persona/update-writing/route.ts b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.tssimilarity index 80%rename from src/app/(backend)/api/workflows/memory-user-memory/pipelines/persona/update-writing/route.tsrename to src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.tsindex 334f81e43d3..c7839b0e3c2 100644--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/persona/update-writing/route.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts@@ -1,4 +1,4 @@-import { serve } from '@upstash/workflow/nextjs';+import { type WorkflowContext } from '@upstash/workflow';import { z } from 'zod';import { getServerDB } from '@/database/server';@@ -11,7 +11,7 @@ const workflowPayloadSchema = z.object({userIds: z.array(z.string()).optional(),});-export const { POST } = serve(async (context) => {+export const personaUpdateHandler = async (context: WorkflowContext) => {const payload = await context.run('memory:pipelines:persona:update-writing:parse-payload', () =>workflowPayloadSchema.parse(context.requestPayload || {}),);@@ -27,8 +27,8 @@ export const { POST } = serve(async (context) => {await Promise.all(userIds.map(async (userId) =>context.run(`memory:pipelines:persona:update-writing:users:${userId}`, async () => {- const context = await buildUserPersonaJobInput(db, userId);- const result = await service.composeWriting({ ...context, userId });+ const jobInput = await buildUserPersonaJobInput(db, userId);+ const result = await service.composeWriting({ ...jobInput, userId });return {diffId: result.diff?.id,documentId: result.document.id,@@ -43,4 +43,4 @@ export const { POST } = serve(async (context) => {message: 'User persona processed via workflow.',processedUsers: userIds.length,};-});+};diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.tssimilarity index 94%rename from src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.tsrename to src/server/workflows-hono/memory-user-memory/workflows/processTopic.tsindex 649ae7bd3d4..720fe977c22 100644--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts@@ -5,21 +5,19 @@ import {} from '@lobechat/observability-otel/modules/upstash-workflow';import { LayersEnum, MemorySourceType } from '@lobechat/types';import { errorMessageFrom } from '@lobechat/utils';-import { Client } from '@upstash/qstash';import { type WorkflowContext } from '@upstash/workflow';import { WorkflowAbort, WorkflowNonRetryableError } from '@upstash/workflow';-import { createWorkflow } from '@upstash/workflow/nextjs';+import { createWorkflow } from '@upstash/workflow/hono';import { AsyncTaskModel } from '@/database/models/asyncTask';import { getServerDB } from '@/database/server';-import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';import {MemoryExtractionExecutor,normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';-const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();+import { createWorkflowQstashClient } from '../qstashClient';const CEPA_LAYERS: LayersEnum[] = [LayersEnum.Context,@@ -204,12 +202,7 @@ export const processTopicWorkflow = createWorkflow<MemoryExtractionPayloadInput,return 'async-task-update-failed';}},- qstashClient: new Client({- headers: {- ...upstashWorkflowExtraHeaders,- },- token: process.env.QSTASH_TOKEN!,- }),+ qstashClient: createWorkflowQstashClient(),},);diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.tsnew file mode 100644index 00000000000..1d85e2a9f28--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts@@ -0,0 +1,163 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import {+ buildUpstashWorkflowAttributes,+ tracer as upstashWorkflowTracer,+} from '@lobechat/observability-otel/modules/upstash-workflow';+import { LayersEnum, MemorySourceType } from '@lobechat/types';+import { type WorkflowContext } from '@upstash/workflow';+import { WorkflowAbort } from '@upstash/workflow';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { getServerDB } from '@/database/server';+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';+import {+ MemoryExtractionWorkflowService,+ normalizeMemoryExtractionPayload,+} from '@/server/services/memory/userMemory/extract';++import { processTopicWorkflow } from './processTopic';++const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();++const CEPA_LAYERS: LayersEnum[] = [+ LayersEnum.Context,+ LayersEnum.Experience,+ LayersEnum.Preference,+ LayersEnum.Activity,+];+const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];++export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPayloadInput>) =>+ upstashWorkflowTracer.startActiveSpan(+ 'workflow:memory-user-memory:process-topics',+ async (span) => {+ const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});++ span.setAttributes({+ ...buildUpstashWorkflowAttributes(context),+ 'workflow.memory_user_memory.force_all': payload.forceAll,+ 'workflow.memory_user_memory.force_topics': payload.forceTopics,+ 'workflow.memory_user_memory.layers': payload.layers.join(','),+ 'workflow.memory_user_memory.source': payload.sources.join(','),+ 'workflow.memory_user_memory.topic_count': payload.topicIds.length,+ 'workflow.memory_user_memory.user_count': payload.userIds.length,+ 'workflow.name': 'memory-user-memory:process-topics',+ });++ try {+ if (!payload.userIds.length) {+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ message: 'No user id provided for topic batch.',+ processedTopics: 0,+ processedUsers: 0,+ };+ }+ if (!payload.topicIds.length) {+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ message: 'No topic ids provided for extraction.',+ processedTopics: 0,+ processedUsers: 0,+ };+ }+ if (!payload.sources.includes(MemorySourceType.ChatTopic)) {+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ message: 'Source not supported in topic batch.',+ processedTopics: 0,+ processedUsers: 0,+ };+ }++ const userId = payload.userIds[0];+ if (payload.asyncTaskId && userId) {+ // NOTICE: Cooperative cascading cancellation for the workflow tree.+ // If cancelled, stop before fan-out into per-topic child workflows.+ const cancelled = await context.run(+ `memory:user-memory:extract:users:${userId}:cancel-check`,+ () =>+ getServerDB().then((db) =>+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(+ payload.asyncTaskId!,+ ),+ ),+ );+ if (cancelled) {+ span.setStatus({ code: SpanStatusCode.OK });+ return {+ message: 'Memory extraction task cancellation requested, skip topic batch.',+ processedTopics: 0,+ processedUsers: 0,+ };+ }+ }+ // Delegate per-topic extraction to dedicated workflow for better isolation+ await Promise.all(+ payload.topicIds.map(async (topicId, index) => {+ await context.invoke(+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:invoke:${index}`,+ {+ body: {+ ...payload,+ layers: payload.layers.length+ ? payload.layers+ : [...CEPA_LAYERS, ...IDENTITY_LAYERS],+ topicIds: [topicId],+ userId,+ userIds: [userId],+ },+ // CEPA: run in parallel across the batch+ //+ // NOTICE: if modified the parallelism of CEPA_LAYERS+ // or added new memory layer, make sure to update the number below.+ //+ // Currently, CEPA (context, experience, preference, activity) + identity = 5 layers.+ // and since identity requires sequential processing, we set parallelism to 5.+ flowControl: {+ key: `memory-user-memory.pipelines.chat-topic.process-topic.user.${userId}.topic.${topicId}`,+ parallelism: 5,+ },+ headers: upstashWorkflowExtraHeaders,+ workflow: processTopicWorkflow,+ },+ );+ }),+ );++ // Trigger user persona update after topic processing using the workflow client.+ await context.run(`memory:user-memory:users:${userId}`, async () => {+ await MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {+ extraHeaders: upstashWorkflowExtraHeaders,+ });+ });++ span.setStatus({ code: SpanStatusCode.OK });++ return {+ processedTopics: payload.topicIds.length,+ processedUsers: payload.userIds.length,+ };+ } catch (error) {+ // NOTICE: Let WorkflowAbort bubble up (used internally by Upstash); record others+ if (error instanceof WorkflowAbort) {+ console.warn('workflow aborted:', error.message);+ throw error;+ }++ span.recordException(error as Error);+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : 'process-topics workflow failed',+ });++ throw error;+ } finally {+ span.end();+ }+ },+ );diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.tsnew file mode 100644index 00000000000..727db2f9448--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts@@ -0,0 +1,159 @@+import { MemorySourceType } from '@lobechat/types';+import { type WorkflowContext } from '@upstash/workflow';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { type ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';+import { getServerDB } from '@/database/server';+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';+import {+ buildWorkflowPayloadInput,+ MemoryExtractionExecutor,+ MemoryExtractionWorkflowService,+ normalizeMemoryExtractionPayload,+} from '@/server/services/memory/userMemory/extract';+import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';++const TOPIC_PAGE_SIZE = 50;+const TOPIC_BATCH_SIZE = 4;++const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();++export const processUserTopicsHandler = async (+ context: WorkflowContext<MemoryExtractionPayloadInput>,+) => {+ const params = normalizeMemoryExtractionPayload(context.requestPayload || {});+ if (!params.userIds.length) {+ return { message: 'No user ids provided for topic processing.' };+ }+ if (!params.sources.includes(MemorySourceType.ChatTopic)) {+ return { message: 'No supported sources requested, skip topic processing.' };+ }++ const executor = await MemoryExtractionExecutor.create();++ const scheduleNextPage = async (userId: string, cursorCreatedAt: Date, cursorId: string) => {+ await MemoryExtractionWorkflowService.triggerProcessUserTopics(+ {+ ...buildWorkflowPayloadInput({+ ...params,+ topicCursor: {+ createdAt: cursorCreatedAt.toISOString(),+ id: cursorId,+ userId,+ },+ topicIds: [],+ userId,+ userIds: [userId],+ }),+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ );+ };++ for (const userId of params.userIds) {+ if (params.asyncTaskId) {+ // NOTICE: Cooperative cascading cancellation for the workflow tree.+ // A cancelled root task should stop at user-topic pagination and avoid enqueuing topic batches.+ const cancelled = await context.run(+ `memory:user-memory:extract:users:${userId}:cancel-check`,+ () =>+ getServerDB().then((db) =>+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(+ params.asyncTaskId!,+ ),+ ),+ );+ if (cancelled) {+ continue;+ }+ }++ const topicCursor =+ params.topicCursor && params.topicCursor.userId === userId+ ? {+ createdAt: new Date(params.topicCursor.createdAt),+ id: params.topicCursor.id,+ }+ : undefined;++ const topicsFromPayload =+ params.topicIds && params.topicIds.length > 0+ ? await context.run(+ `memory:user-memory:extract:users:${userId}:filter-topic-ids`,+ async () => {+ const filtered = await executor.filterTopicIdsForUser(userId, params.topicIds);+ return filtered.length > 0 ? filtered : undefined;+ },+ )+ : undefined;++ const topicBatch = await context.run<{+ cursor?: ListTopicsForMemoryExtractorCursor;+ ids: string[];+ }>(`memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`, () =>+ topicsFromPayload && topicsFromPayload.length > 0+ ? Promise.resolve({ ids: topicsFromPayload })+ : executor.getTopicsForUser(+ {+ cursor: topicCursor,+ forceAll: params.forceAll,+ forceTopics: params.forceTopics,+ from: params.from,+ to: params.to,+ userId,+ },+ TOPIC_PAGE_SIZE,+ ),+ );++ const ids = topicBatch.ids;+ if (!ids.length) {+ continue;+ }++ const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;++ // TODO: follow the new pattern of process-topic+ // remove the batch sequential, replace it with context.invoke(...) pattern+ await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {+ // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path+ // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow+ // URLs would inherit that base and lose the desired /process-topics/workflows prefix.+ await context.run(+ `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,+ () =>+ MemoryExtractionWorkflowService.triggerProcessTopics(+ userId,+ {+ ...buildWorkflowPayloadInput(params),+ topicCursor: undefined,+ topicIds,+ userId,+ userIds: [userId],+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ );+ });++ if (!topicsFromPayload && cursor) {+ await context.run(+ `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`,+ () => {+ // NOTICE: Upstash Workflow only supports serializable data into plain JSON,+ // this causes the Date object to be converted into string when passed as parameter from+ // context to child workflow. So we need to convert it back to Date object here.+ const createdAt = new Date(cursor.createdAt);+ if (Number.isNaN(createdAt.getTime())) {+ throw new Error('Invalid cursor date when scheduling next topic page');+ }++ return scheduleNextPage(userId, createdAt, cursor.id);+ },+ );+ }+ }++ return { processedUsers: params.userIds.length };+};diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.tsnew file mode 100644index 00000000000..6e79cbc1590--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts@@ -0,0 +1,100 @@+import { type WorkflowContext } from '@upstash/workflow';+import { chunk } from 'es-toolkit/compat';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { getServerDB } from '@/database/server';+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';+import {+ buildWorkflowPayloadInput,+ MemoryExtractionExecutor,+ MemoryExtractionWorkflowService,+ normalizeMemoryExtractionPayload,+} from '@/server/services/memory/userMemory/extract';++const USER_PAGE_SIZE = 50;+const USER_BATCH_SIZE = 10;++const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();++export const processUsersHandler = async (+ context: WorkflowContext<MemoryExtractionPayloadInput>,+) => {+ const params = normalizeMemoryExtractionPayload(context.requestPayload || {});+ if (params.sources.length === 0) {+ return { message: 'No sources provided, skip memory extraction.' };+ }+ if (params.asyncTaskId && params.userIds[0]) {+ // NOTICE: Cooperative cascading cancellation for the workflow tree.+ // If root task has cancelRequestedAt, this stage stops scheduling child workflows.+ const cancelled = await context.run('memory:user-memory:extract:cancel-check:root', () =>+ getServerDB().then((db) =>+ new AsyncTaskModel(db, params.userIds[0]!).isUserMemoryExtractionCancellationRequested(+ params.asyncTaskId!,+ ),+ ),+ );+ if (cancelled) {+ return { message: 'Memory extraction task cancellation requested, skip processing users.' };+ }+ }++ const executor = await MemoryExtractionExecutor.create();++ // NOTICE: Upstash Workflow only supports serializable data into plain JSON,+ // this causes the Date object to be converted into string when passed as parameter from+ // context to child workflow. So we need to convert it back to Date object here.+ const userCursor = params.userCursor+ ? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }+ : undefined;++ const userBatch = await context.run('memory:user-memory:extract:get-users', () =>+ params.userIds.length > 0+ ? { ids: params.userIds }+ : executor.getUsers(USER_PAGE_SIZE, userCursor),+ );++ const ids = userBatch.ids;+ if (ids.length === 0) {+ return { message: 'No users to process for memory extraction.' };+ }++ const cursor = 'cursor' in userBatch ? userBatch.cursor : undefined;++ const batches = chunk(ids, USER_BATCH_SIZE);+ await Promise.all(+ batches.map((userIds) =>+ context.run(`memory:user-memory:extract:users:process-topic-batches`, () =>+ MemoryExtractionWorkflowService.triggerProcessUserTopics(+ {+ ...buildWorkflowPayloadInput(params),+ topicCursor: undefined,+ userId: userIds[0],+ userIds,+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ ),+ ),+ );++ if (params.userIds.length === 0 && cursor) {+ await context.run('memory:user-memory:extract:users:schedule-next-user-batch', () =>+ MemoryExtractionWorkflowService.triggerProcessUsers(+ {+ ...buildWorkflowPayloadInput({+ ...params,+ userCursor: { createdAt: cursor.createdAt.toISOString(), id: cursor.id },+ }),+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ );+ }++ return {+ batches: batches.length,+ nextCursor: cursor ? cursor.id : null,+ processedUsers: ids.length,+ };+};