Skip to content

🀯 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.

πŸ› fix(builtin-tool-gtd): add server runtime for GTD tool (#13854)

Arvin Xu8475bc11fc61
diff --git a/packages/builtin-tool-gtd/package.json b/packages/builtin-tool-gtd/package.json
index 1057d4541a7..6df061ff42c 100644
--- a/packages/builtin-tool-gtd/package.json
+++ b/packages/builtin-tool-gtd/package.json
@@ -5,6 +5,7 @@
"exports": {
".": "./src/index.ts",
"./executor": "./src/executor/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts",
"./client": "./src/client/index.ts"
},
"main": "./src/index.ts",
diff --git a/packages/builtin-tool-gtd/src/ExecutionRuntime/index.ts b/packages/builtin-tool-gtd/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..a14b2551540
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/ExecutionRuntime/index.ts
@@ -0,0 +1,397 @@
+import { formatTodoStateSummary } from '@lobechat/prompts';
+import type { BuiltinToolResult } from '@lobechat/types';
+
+import type {
+ ClearTodosParams,
+ CreatePlanParams,
+ CreateTodosParams,
+ ExecTaskParams,
+ ExecTasksParams,
+ Plan,
+ TodoItem,
+ TodoState,
+ UpdatePlanParams,
+ UpdateTodosParams,
+} from '../types';
+
+export interface PlanDocument {
+ content: string | null;
+ createdAt: Date;
+ description: string | null;
+ id: string;
+ metadata: Record<string, any> | null;
+ title: string | null;
+ updatedAt: Date;
+}
+
+export interface GTDRuntimeService {
+ createPlan: (args: {
+ content: string;
+ description: string;
+ goal: string;
+ topicId: string;
+ }) => Promise<PlanDocument>;
+ findPlanById: (id: string) => Promise<PlanDocument | null>;
+ findPlanByTopic: (topicId: string) => Promise<PlanDocument | null>;
+ /**
+ * Update the user-facing plan fields (goal / description / context).
+ * `topicId` is forwarded so client implementations can refresh their SWR cache;
+ * server implementations can safely ignore it.
+ */
+ updatePlan: (
+ id: string,
+ args: { content?: string; description?: string; goal?: string },
+ topicId?: string,
+ ) => Promise<PlanDocument>;
+ /**
+ * Silently update the plan document's metadata (used for todos sync).
+ * Should NOT trigger UI refresh on the client.
+ */
+ updatePlanMetadata: (id: string, metadata: Record<string, any>) => Promise<void>;
+}
+
+export interface GTDRuntimeContext {
+ /**
+ * Existing todos supplied by the caller (client: from stepContext / pluginState).
+ * When undefined, the runtime resolves todos from the plan document's metadata.
+ */
+ currentTodos?: TodoItem[];
+ /** Tool call message ID β€” used as `parentMessageId` for execTask/execTasks. */
+ messageId?: string;
+ signal?: AbortSignal;
+ taskId?: string;
+ topicId?: string;
+}
+
+const toPlan = (doc: PlanDocument, completed = false): Plan => ({
+ completed,
+ context: doc.content ?? undefined,
+ createdAt: doc.createdAt.toISOString(),
+ description: doc.description ?? '',
+ goal: doc.title ?? '',
+ id: doc.id,
+ updatedAt: doc.updatedAt.toISOString(),
+});
+
+const readTodosFromPlan = (doc: PlanDocument | null): TodoItem[] => {
+ const todos = doc?.metadata?.todos;
+ if (!todos) return [];
+ if (Array.isArray(todos)) return todos as TodoItem[];
+ if (typeof todos === 'object' && Array.isArray((todos as TodoState).items)) {
+ return (todos as TodoState).items;
+ }
+ return [];
+};
+
+export class GTDExecutionRuntime {
+ private service: GTDRuntimeService;
+
+ constructor(service: GTDRuntimeService) {
+ this.service = service;
+ }
+
+ private async resolveExistingTodos(context: GTDRuntimeContext): Promise<TodoItem[]> {
+ if (context.currentTodos) return context.currentTodos;
+ if (!context.topicId) return [];
+ const plan = await this.service.findPlanByTopic(context.topicId);
+ return readTodosFromPlan(plan);
+ }
+
+ private async syncTodosToPlan(topicId: string, todos: TodoState): Promise<void> {
+ try {
+ const plan = await this.service.findPlanByTopic(topicId);
+ if (!plan) return;
+ await this.service.updatePlanMetadata(plan.id, { ...plan.metadata, todos });
+ } catch (error) {
+ console.warn('Failed to sync todos to plan:', error);
+ }
+ }
+
+ // ==================== Todo APIs ====================
+
+ createTodos = async (
+ params: CreateTodosParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ const itemsToAdd: TodoItem[] = params.items
+ ? params.items
+ : params.adds
+ ? params.adds.map((text) => ({ status: 'todo' as const, text }))
+ : [];
+
+ if (itemsToAdd.length === 0) {
+ return { content: 'No items provided to add.', success: false };
+ }
+
+ const existingTodos = await this.resolveExistingTodos(context);
+ const updatedTodos = [...existingTodos, ...itemsToAdd];
+ const now = new Date().toISOString();
+
+ const addedList = itemsToAdd.map((item) => `- ${item.text}`).join('\n');
+ const actionSummary = `βœ… Added ${itemsToAdd.length} item${itemsToAdd.length > 1 ? 's' : ''}:\n${addedList}`;
+
+ const todoState: TodoState = { items: updatedTodos, updatedAt: now };
+
+ if (context.topicId) await this.syncTodosToPlan(context.topicId, todoState);
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ createdItems: itemsToAdd.map((item) => item.text),
+ todos: todoState,
+ },
+ success: true,
+ };
+ };
+
+ updateTodos = async (
+ params: UpdateTodosParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ const { operations } = params;
+
+ if (!operations || operations.length === 0) {
+ return { content: 'No operations provided.', success: false };
+ }
+
+ const existingTodos = await this.resolveExistingTodos(context);
+ const updatedTodos = [...existingTodos];
+ const results: string[] = [];
+
+ for (const op of operations) {
+ switch (op.type) {
+ case 'add': {
+ if (op.text) {
+ updatedTodos.push({ status: 'todo', text: op.text });
+ results.push(`Added: "${op.text}"`);
+ }
+ break;
+ }
+ case 'update': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ const updatedItem = { ...updatedTodos[op.index] };
+ if (op.newText !== undefined) updatedItem.text = op.newText;
+ if (op.status !== undefined) updatedItem.status = op.status;
+ updatedTodos[op.index] = updatedItem;
+ results.push(`Updated item ${op.index + 1}`);
+ }
+ break;
+ }
+ case 'remove': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ const removed = updatedTodos.splice(op.index, 1)[0];
+ results.push(`Removed: "${removed.text}"`);
+ }
+ break;
+ }
+ case 'complete': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'completed' };
+ results.push(`Completed: "${updatedTodos[op.index].text}"`);
+ }
+ break;
+ }
+ case 'processing': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'processing' };
+ results.push(`In progress: "${updatedTodos[op.index].text}"`);
+ }
+ break;
+ }
+ }
+ }
+
+ const now = new Date().toISOString();
+ const actionSummary =
+ results.length > 0
+ ? `πŸ”„ Applied ${results.length} operation${results.length > 1 ? 's' : ''}:\n${results.map((r) => `- ${r}`).join('\n')}`
+ : 'No operations applied.';
+
+ const todoState: TodoState = { items: updatedTodos, updatedAt: now };
+
+ if (context.topicId) await this.syncTodosToPlan(context.topicId, todoState);
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: { todos: todoState },
+ success: true,
+ };
+ };
+
+ clearTodos = async (
+ params: ClearTodosParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ const { mode } = params;
+
+ const existingTodos = await this.resolveExistingTodos(context);
+
+ if (existingTodos.length === 0) {
+ const now = new Date().toISOString();
+ return {
+ content: 'Todo list is already empty.\n\n' + formatTodoStateSummary([], now),
+ state: {
+ clearedCount: 0,
+ mode,
+ todos: { items: [], updatedAt: now },
+ },
+ success: true,
+ };
+ }
+
+ let updatedTodos: TodoItem[];
+ let clearedCount: number;
+ let actionSummary: string;
+
+ if (mode === 'all') {
+ clearedCount = existingTodos.length;
+ updatedTodos = [];
+ actionSummary = `🧹 Cleared all ${clearedCount} item${clearedCount > 1 ? 's' : ''} from todo list.`;
+ } else {
+ updatedTodos = existingTodos.filter((todo) => todo.status !== 'completed');
+ clearedCount = existingTodos.length - updatedTodos.length;
+ actionSummary =
+ clearedCount === 0
+ ? 'No completed items to clear.'
+ : `🧹 Cleared ${clearedCount} completed item${clearedCount > 1 ? 's' : ''}.`;
+ }
+
+ const now = new Date().toISOString();
+ const todoState: TodoState = { items: updatedTodos, updatedAt: now };
+
+ if (context.topicId) await this.syncTodosToPlan(context.topicId, todoState);
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: { clearedCount, mode, todos: todoState },
+ success: true,
+ };
+ };
+
+ // ==================== Plan APIs ====================
+
+ createPlan = async (
+ params: CreatePlanParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (context.signal?.aborted) return { stop: true, success: false };
+
+ if (!context.topicId) {
+ return { content: 'Cannot create plan: no topic selected', success: false };
+ }
+
+ const { goal, description, context: planContext } = params;
+
+ const doc = await this.service.createPlan({
+ content: planContext ?? '',
+ description,
+ goal,
+ topicId: context.topicId,
+ });
+
+ const plan = toPlan(doc);
+ plan.context = planContext;
+
+ return {
+ content: `πŸ“‹ Created plan: "${plan.goal}"\n\nYou can view this plan in the Portal sidebar.`,
+ state: { plan },
+ success: true,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+
+ updatePlan = async (
+ params: UpdatePlanParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (context.signal?.aborted) return { stop: true, success: false };
+
+ if (!context.topicId) {
+ return { content: 'Cannot update plan: no topic selected', success: false };
+ }
+
+ const { planId, goal, description, context: planContext, completed } = params;
+
+ const existingDoc = await this.service.findPlanById(planId);
+ if (!existingDoc) {
+ return { content: `Plan not found: ${planId}`, success: false };
+ }
+
+ const updatedDoc = await this.service.updatePlan(
+ planId,
+ { content: planContext, description, goal },
+ context.topicId,
+ );
+
+ const plan = toPlan(updatedDoc, completed ?? false);
+ plan.context = planContext ?? existingDoc.content ?? undefined;
+
+ return {
+ content: `πŸ“ Updated plan: "${plan.goal}"`,
+ state: { plan },
+ success: true,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+
+ // ==================== Async Tasks API ====================
+
+ execTask = async (
+ params: ExecTaskParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ const { description, instruction, inheritMessages, timeout, runInClient } = params;
+
+ if (!description || !instruction) {
+ return { content: 'Task description and instruction are required.', success: false };
+ }
+
+ const task = { description, inheritMessages, instruction, runInClient, timeout };
+ const stateType = runInClient ? 'execClientTask' : 'execTask';
+
+ return {
+ content: `πŸš€ Triggered async task for ${runInClient ? 'client-side' : ''} execution:\n- ${description}`,
+ state: { parentMessageId: context.messageId ?? '', task, type: stateType },
+ stop: true,
+ success: true,
+ };
+ };
+
+ execTasks = async (
+ params: ExecTasksParams,
+ context: GTDRuntimeContext,
+ ): Promise<BuiltinToolResult> => {
+ const { tasks } = params;
+
+ if (!tasks || tasks.length === 0) {
+ return { content: 'No tasks provided to execute.', success: false };
+ }
+
+ const taskCount = tasks.length;
+ const taskList = tasks.map((t, i) => `${i + 1}. ${t.description}`).join('\n');
+ const hasClientTasks = tasks.some((t) => t.runInClient);
+ const stateType = hasClientTasks ? 'execClientTasks' : 'execTasks';
+ const executionMode = hasClientTasks ? 'client-side' : '';
+
+ return {
+ content: `πŸš€ Triggered ${taskCount} async task${taskCount > 1 ? 's' : ''} for ${executionMode} execution:\n${taskList}`,
+ state: { parentMessageId: context.messageId ?? '', tasks, type: stateType },
+ stop: true,
+ success: true,
+ };
+ };
+}
diff --git a/packages/builtin-tool-gtd/src/executor/index.ts b/packages/builtin-tool-gtd/src/executor/index.ts
index 38356d897a9..858511f78a8 100644
--- a/packages/builtin-tool-gtd/src/executor/index.ts
+++ b/packages/builtin-tool-gtd/src/executor/index.ts
@@ -1,10 +1,15 @@
-import { formatTodoStateSummary } from '@lobechat/prompts';
import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
import { notebookService } from '@/services/notebook';
import { useNotebookStore } from '@/store/notebook';
+import {
+ GTDExecutionRuntime,
+ type GTDRuntimeContext,
+ type GTDRuntimeService,
+ type PlanDocument,
+} from '../ExecutionRuntime';
import { GTDIdentifier } from '../manifest';
import type {
ClearTodosParams,
@@ -12,40 +17,77 @@ import type {
CreateTodosParams,
ExecTaskParams,
ExecTasksParams,
- Plan,
- TodoItem,
- TodoState,
UpdatePlanParams,
UpdateTodosParams,
} from '../types';
import { GTDApiName } from '../types';
import { getTodosFromContext } from './helper';
+const PLAN_DOC_TYPE = 'agent/plan';
+
/**
- * Sync todos to the Plan document's metadata
- * This allows the Plan to track todos persistently
+ * Normalize a document payload returned by notebookService / useNotebookStore
+ * into the `PlanDocument` shape expected by GTDExecutionRuntime.
*/
-const syncTodosToPlan = async (topicId: string, todos: TodoState): Promise<void> => {
- try {
- // List all documents for this topic with type 'agent/plan'
- const result = await notebookService.listDocuments({ topicId, type: 'agent/plan' });
+const normalizePlanDoc = (doc: {
+ content?: string | null;
+ createdAt: Date | string;
+ description?: string | null;
+ id: string;
+ metadata?: Record<string, any> | null;
+ title?: string | null;
+ updatedAt: Date | string;
+}): PlanDocument => ({
+ content: doc.content ?? null,
+ createdAt: typeof doc.createdAt === 'string' ? new Date(doc.createdAt) : doc.createdAt,
+ description: doc.description ?? null,
+ id: doc.id,
+ metadata: doc.metadata ?? null,
+ title: doc.title ?? null,
+ updatedAt: typeof doc.updatedAt === 'string' ? new Date(doc.updatedAt) : doc.updatedAt,
+});
- // If there's a plan document, update its metadata with the todos
- if (result.data.length > 0) {
- // Update the first (most recent) plan document
- const planDoc = result.data[0];
- await notebookService.updateDocument({
- id: planDoc.id,
- metadata: { todos },
- });
- }
- } catch (error) {
- // Silently fail - todo sync is a non-critical feature
- console.warn('Failed to sync todos to plan:', error);
- }
+/**
+ * Client-side implementation of the GTD runtime service.
+ * Routes user-facing plan CRUD through useNotebookStore (so SWR caches refresh),
+ * and keeps silent metadata writes (todos sync) on the raw notebookService.
+ */
+const clientGTDService: GTDRuntimeService = {
+ createPlan: async ({ topicId, goal, description, content }) => {
+ const doc = await useNotebookStore.getState().createDocument({
+ content,
+ description,
+ title: goal,
+ topicId,
+ type: PLAN_DOC_TYPE,
+ });
+ return normalizePlanDoc(doc);
+ },
+
+ findPlanById: async (id) => {
+ const doc = await notebookService.getDocument(id);
+ return doc ? normalizePlanDoc(doc) : null;
+ },
+
+ findPlanByTopic: async (topicId) => {
+ const result = await notebookService.listDocuments({ topicId, type: PLAN_DOC_TYPE });
+ const first = result.data[0];
+ return first ? normalizePlanDoc(first) : null;
+ },
+
+ updatePlan: async (id, { goal, description, content }, topicId) => {
+ const doc = await useNotebookStore
+ .getState()
+ .updateDocument({ content, description, id, title: goal }, topicId ?? '');
+ if (!doc) throw new Error(`Plan not found after update: ${id}`);
+ return normalizePlanDoc(doc);
+ },
+
+ updatePlanMetadata: async (id, metadata) => {
+ await notebookService.updateDocument({ id, metadata });
+ },
};
-// API enum for MVP (Todo + Plan)
const GTDApiNameEnum = {
clearTodos: GTDApiName.clearTodos,
createPlan: GTDApiName.createPlan,
@@ -56,455 +98,39 @@ const GTDApiNameEnum = {
updateTodos: GTDApiName.updateTodos,
} as const;
-/**
- * GTD Tool Executor
- */
+const toRuntimeContext = (ctx: BuiltinToolContext): GTDRuntimeContext => ({
+ currentTodos: getTodosFromContext(ctx),
+ messageId: ctx.messageId,
+ signal: ctx.signal,
+ topicId: ctx.topicId ?? undefined,
+});
+
class GTDExecutor extends BaseExecutor<typeof GTDApiNameEnum> {
readonly identifier = GTDIdentifier;
protected readonly apiEnum = GTDApiNameEnum;
- // ==================== Todo APIs ====================
-
- /**
- * Create new todo items
- * Handles both formats:
- * - AI input: { adds: string[] }
- * - User-edited: { items: TodoItem[] }
- */
- createTodos = async (
- params: CreateTodosParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- // Handle both formats: items (user-edited) takes priority over adds (AI input)
- const itemsToAdd: TodoItem[] = params.items
- ? params.items
- : params.adds
- ? params.adds.map((text) => ({ status: 'todo' as const, text }))
- : [];
-
- if (itemsToAdd.length === 0) {
- return {
- content: 'No items provided to add.',
- success: false,
- };
- }
-
- // Get current todos from step context (priority) or plugin state (fallback)
- const existingTodos = getTodosFromContext(ctx);
-
- // Add new items
- const now = new Date().toISOString();
- const updatedTodos = [...existingTodos, ...itemsToAdd];
-
- // Format response: action summary + todo state
- const addedList = itemsToAdd.map((item) => `- ${item.text}`).join('\n');
- const actionSummary = `βœ… Added ${itemsToAdd.length} item${itemsToAdd.length > 1 ? 's' : ''}:\n${addedList}`;
-
- const todoState = { items: updatedTodos, updatedAt: now };
-
- // Sync todos to Plan document if topic exists
- if (ctx.topicId) {
- await syncTodosToPlan(ctx.topicId, todoState);
- }
-
- return {
- content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
- state: {
- createdItems: itemsToAdd.map((item) => item.text),
- todos: todoState,
- },
- success: true,
- };
- };
-
- /**
- * Update todo items with batch operations
- */
- updateTodos = async (
- params: UpdateTodosParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { operations } = params;
-
- if (!operations || operations.length === 0) {
- return {
- content: 'No operations provided.',
- success: false,
- };
- }
-
- const existingTodos = getTodosFromContext(ctx);
- const updatedTodos = [...existingTodos];
- const results: string[] = [];
-
- for (const op of operations) {
- switch (op.type) {
- case 'add': {
- if (op.text) {
- updatedTodos.push({ status: 'todo', text: op.text });
- results.push(`Added: "${op.text}"`);
- }
- break;
- }
- case 'update': {
- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
- // Create a new object to avoid mutating frozen/immutable objects from store
- const updatedItem = { ...updatedTodos[op.index] };
- if (op.newText !== undefined) {
- updatedItem.text = op.newText;
- }
- // Handle status field
- if (op.status !== undefined) {
- updatedItem.status = op.status;
- }
- updatedTodos[op.index] = updatedItem;
- results.push(`Updated item ${op.index + 1}`);
- }
- break;
- }
- case 'remove': {
- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
- const removed = updatedTodos.splice(op.index, 1)[0];
- results.push(`Removed: "${removed.text}"`);
- }
- break;
- }
- case 'complete': {
- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
- // Create a new object to avoid mutating frozen/immutable objects from store
- updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'completed' };
- results.push(`Completed: "${updatedTodos[op.index].text}"`);
- }
- break;
- }
- case 'processing': {
- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
- // Create a new object to avoid mutating frozen/immutable objects from store
- updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'processing' };
- results.push(`In progress: "${updatedTodos[op.index].text}"`);
- }
- break;
- }
- }
- }
-
- const now = new Date().toISOString();
-
- // Format response: action summary + todo state
- const actionSummary =
- results.length > 0
- ? `πŸ”„ Applied ${results.length} operation${results.length > 1 ? 's' : ''}:\n${results.map((r) => `- ${r}`).join('\n')}`
- : 'No operations applied.';
-
- const todoState = { items: updatedTodos, updatedAt: now };
-
- // Sync todos to Plan document if topic exists
- if (ctx.topicId) {
- await syncTodosToPlan(ctx.topicId, todoState);
- }
-
- return {
- content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
- state: {
- todos: todoState,
- },
- success: true,
- };
- };
-
- /**
- * Clear todo items
- */
- clearTodos = async (
- params: ClearTodosParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { mode } = params;
-
- const existingTodos = getTodosFromContext(ctx);
-
- if (existingTodos.length === 0) {
- const now = new Date().toISOString();
- return {
- content: 'Todo list is already empty.\n\n' + formatTodoStateSummary([], now),
- state: {
- clearedCount: 0,
- mode,
- todos: { items: [], updatedAt: now },
- },
- success: true,
- };
- }
-
- let updatedTodos: TodoItem[];
- let clearedCount: number;
- let actionSummary: string;
-
- if (mode === 'all') {
- clearedCount = existingTodos.length;
- updatedTodos = [];
- actionSummary = `🧹 Cleared all ${clearedCount} item${clearedCount > 1 ? 's' : ''} from todo list.`;
- } else {
- // mode === 'completed'
- updatedTodos = existingTodos.filter((todo) => todo.status !== 'completed');
- clearedCount = existingTodos.length - updatedTodos.length;
-
- if (clearedCount === 0) {
- actionSummary = 'No completed items to clear.';
- } else {
- actionSummary = `🧹 Cleared ${clearedCount} completed item${clearedCount > 1 ? 's' : ''}.`;
- }
- }
-
- const now = new Date().toISOString();
- const todoState = { items: updatedTodos, updatedAt: now };
-
- // Sync todos to Plan document if topic exists
- if (ctx.topicId) {
- await syncTodosToPlan(ctx.topicId, todoState);
- }
-
- return {
- content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
- state: {
- clearedCount,
- mode,
- todos: todoState,
- },
- success: true,
- };
- };
-
- // ==================== Plan APIs ====================
-
- /**
- * Create a new plan document
- */
- createPlan = async (
- params: CreatePlanParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- if (ctx.signal?.aborted) {
- return { stop: true, success: false };
- }
-
- if (!ctx.topicId) {
- return {
- content: 'Cannot create plan: no topic selected',
- success: false,
- };
- }
-
- const { goal, description, context } = params;
-
- // Create document with type 'agent/plan'
- // Field mapping: goal -> title, description -> description, context -> content
- const document = await useNotebookStore.getState().createDocument({
- content: context || '',
- description,
- title: goal,
- topicId: ctx.topicId,
- type: 'agent/plan',
- });
-
- const plan: Plan = {
- completed: false,
- context,
- createdAt: document.createdAt.toISOString(),
- description: document.description || '',
- goal: document.title || '',
- id: document.id,
- updatedAt: document.updatedAt.toISOString(),
- };
-
- return {
- content: `πŸ“‹ Created plan: "${plan.goal}"\n\nYou can view this plan in the Portal sidebar.`,
- state: { plan },
- success: true,
- };
- } catch (e) {
- const err = e as Error;
- return {
- error: {
- body: e,
- message: err.message,
- type: 'PluginServerError',
- },
- success: false,
- };
- }
- };
-
- /**
- * Update an existing plan document
- */
- updatePlan = async (
- params: UpdatePlanParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- if (ctx.signal?.aborted) {
- return { stop: true, success: false };
- }
-
- const { planId, goal, description, context, completed } = params;
-
- if (!ctx.topicId) {
- return {
- content: 'Cannot update plan: no topic selected',
- success: false,
- };
- }
-
- // Get existing document
- const existingDoc = await notebookService.getDocument(planId);
- if (!existingDoc) {
- return {
- content: `Plan not found: ${planId}`,
- success: false,
- };
- }
-
- // Update document using store (triggers refresh)
- // Field mapping: goal -> title, description -> description, context -> content
- const document = await useNotebookStore.getState().updateDocument(
- {
- content: context,
- description,
- id: planId,
- title: goal,
- },
- ctx.topicId,
- );
-
- const plan: Plan = {
- completed: completed ?? false,
- context: context ?? existingDoc.content ?? undefined,
- createdAt: document?.createdAt.toISOString() || '',
- description: document?.description || existingDoc.description || '',
- goal: document?.title || existingDoc.title || '',
- id: planId,
- updatedAt: document?.updatedAt.toISOString() || '',
- };
-
- return {
- content: `πŸ“ Updated plan: "${plan.goal}"`,
- state: { plan },
- success: true,
- };
- } catch (e) {
- const err = e as Error;
- return {
- error: { body: e, message: err.message, type: 'PluginServerError' },
- success: false,
- };
- }
- };
-
- // ==================== Async Tasks API ====================
-
- /**
- * Execute a single async task
- *
- * This method triggers async task execution by returning a special state.
- * The AgentRuntime's executor will recognize this state and trigger the appropriate instruction.
- *
- * Flow:
- * 1. GTD tool returns stop: true with state.type = 'execTask' or 'execClientTask'
- * 2. AgentRuntime executor recognizes the state and triggers exec_task or exec_client_task instruction
- * 3. The executor creates task message and handles execution
- *
- * @param params.runInClient - If true, returns 'execClientTask' state for client-side execution
- */
- execTask = async (
- params: ExecTaskParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { description, instruction, inheritMessages, timeout, runInClient } = params;
-
- if (!description || !instruction) {
- return {
- content: 'Task description and instruction are required.',
- success: false,
- };
- }
-
- const task = {
- description,
- inheritMessages,
- instruction,
- runInClient,
- timeout,
- };
-
- // Determine state type based on runInClient
- // If runInClient is true, return 'execClientTask' to trigger client-side executor
- const stateType = runInClient ? 'execClientTask' : 'execTask';
+ private runtime = new GTDExecutionRuntime(clientGTDService);
- // Return stop: true with special state that AgentRuntime will recognize
- return {
- content: `πŸš€ Triggered async task for ${runInClient ? 'client-side' : ''} execution:\n- ${description}`,
- state: {
- parentMessageId: ctx.messageId,
- task,
- type: stateType,
- },
- stop: true,
- success: true,
- };
- };
+ createTodos = (params: CreateTodosParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.createTodos(params, toRuntimeContext(ctx));
- /**
- * Execute one or more async tasks
- *
- * This method triggers async task execution by returning a special state.
- * The AgentRuntime's executor will recognize this state and trigger the appropriate instruction.
- *
- * Flow:
- * 1. GTD tool returns stop: true with state.type = 'execTasks' or 'execClientTasks'
- * 2. AgentRuntime executor recognizes the state and triggers exec_tasks or exec_client_tasks instruction
- * 3. The executor creates task messages and handles execution
- *
- * Note: If any task has runInClient=true, all tasks will be routed to 'execClientTasks'.
- * This is because client-side execution is the "special" case requiring local tool access.
- */
- execTasks = async (
- params: ExecTasksParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { tasks } = params;
+ updateTodos = (params: UpdateTodosParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.updateTodos(params, toRuntimeContext(ctx));
- if (!tasks || tasks.length === 0) {
- return {
- content: 'No tasks provided to execute.',
- success: false,
- };
- }
+ clearTodos = (params: ClearTodosParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.clearTodos(params, toRuntimeContext(ctx));
- const taskCount = tasks.length;
- const taskList = tasks.map((t, i) => `${i + 1}. ${t.description}`).join('\n');
+ createPlan = (params: CreatePlanParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.createPlan(params, toRuntimeContext(ctx));
- // Check if any task requires client-side execution
- const hasClientTasks = tasks.some((t) => t.runInClient);
+ updatePlan = (params: UpdatePlanParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.updatePlan(params, toRuntimeContext(ctx));
- // Determine state type: if any task needs client-side, route all to client executor
- const stateType = hasClientTasks ? 'execClientTasks' : 'execTasks';
- const executionMode = hasClientTasks ? 'client-side' : '';
+ execTask = (params: ExecTaskParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.execTask(params, toRuntimeContext(ctx));
- // Return stop: true with special state that AgentRuntime will recognize
- return {
- content: `πŸš€ Triggered ${taskCount} async task${taskCount > 1 ? 's' : ''} for ${executionMode} execution:\n${taskList}`,
- state: {
- parentMessageId: ctx.messageId,
- tasks,
- type: stateType,
- },
- stop: true,
- success: true,
- };
- };
+ execTasks = (params: ExecTasksParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> =>
+ this.runtime.execTasks(params, toRuntimeContext(ctx));
}
-// Export the executor instance for registration
export const gtdExecutor = new GTDExecutor();
diff --git a/src/server/services/toolExecution/serverRuntimes/gtd.ts b/src/server/services/toolExecution/serverRuntimes/gtd.ts
new file mode 100644
index 00000000000..811c9e3fa1a
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/gtd.ts
@@ -0,0 +1,107 @@
+import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
+import {
+ GTDExecutionRuntime,
+ type GTDRuntimeService,
+ type PlanDocument,
+} from '@lobechat/builtin-tool-gtd/executionRuntime';
+import { type LobeChatDatabase } from '@lobechat/database';
+
+import { DocumentModel } from '@/database/models/document';
+import { TopicDocumentModel } from '@/database/models/topicDocument';
+
+import { type ServerRuntimeRegistration } from './types';
+
+const PLAN_FILE_TYPE = 'agent/plan';
+
+const createGTDRuntimeService = (serverDB: LobeChatDatabase, userId: string): GTDRuntimeService => {
+ const documentModel = new DocumentModel(serverDB, userId);
+ const topicDocumentModel = new TopicDocumentModel(serverDB, userId);
+
+ const toPlanDocument = (doc: {
+ content: string | null;
+ createdAt: Date;
+ description: string | null;
+ id: string;
+ metadata: Record<string, any> | null;
+ title: string | null;
+ updatedAt: Date;
+ }): PlanDocument => ({
+ content: doc.content,
+ createdAt: doc.createdAt,
+ description: doc.description,
+ id: doc.id,
+ metadata: doc.metadata,
+ title: doc.title,
+ updatedAt: doc.updatedAt,
+ });
+
+ const loadPlanOrThrow = async (id: string) => {
+ const doc = await documentModel.findById(id);
+ if (!doc) throw new Error(`Plan not found after update: ${id}`);
+ return toPlanDocument(doc);
+ };
+
+ return {
+ createPlan: async ({ topicId, goal, description, content }) => {
+ const doc = await documentModel.create({
+ content,
+ description,
+ fileType: PLAN_FILE_TYPE,
+ source: `gtd:${topicId}`,
+ sourceType: 'api',
+ title: goal,
+ totalCharCount: content.length,
+ totalLineCount: content.split('\n').length,
+ });
+
+ await topicDocumentModel.associate({ documentId: doc.id, topicId });
+
+ return toPlanDocument(doc);
+ },
+
+ findPlanById: async (id) => {
+ const doc = await documentModel.findById(id);
+ if (!doc || doc.fileType !== PLAN_FILE_TYPE) return null;
+ return toPlanDocument(doc);
+ },
+
+ findPlanByTopic: async (topicId) => {
+ const docs = await topicDocumentModel.findByTopicId(topicId, { type: PLAN_FILE_TYPE });
+ const first = docs[0];
+ return first ? toPlanDocument(first) : null;
+ },
+
+ updatePlan: async (id, { goal, description, content }) => {
+ const updateData: Record<string, any> = {};
+ if (goal !== undefined) updateData.title = goal;
+ if (description !== undefined) updateData.description = description;
+ if (content !== undefined) {
+ updateData.content = content;
+ updateData.totalCharCount = content.length;
+ updateData.totalLineCount = content.split('\n').length;
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ await documentModel.update(id, updateData);
+ }
+
+ return loadPlanOrThrow(id);
+ },
+
+ updatePlanMetadata: async (id, metadata) => {
+ await documentModel.update(id, { metadata });
+ },
+ };
+};
+
+export const gtdRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required for GTD tool execution');
+ }
+
+ const service = createGTDRuntimeService(context.serverDB, context.userId);
+ return new GTDExecutionRuntime(service);
+ },
+ identifier: GTDIdentifier,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index 76915bcb30d..9f37a99a91e 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -14,6 +14,7 @@ import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
import { cronRuntime } from './cron';
+import { gtdRuntime } from './gtd';
import { localSystemRuntime } from './localSystem';
import { memoryRuntime } from './memory';
import { messageRuntime } from './message';
@@ -62,6 +63,7 @@ registerRuntimes([
userInteractionRuntime,
credsRuntime,
cronRuntime,
+ gtdRuntime,
webOnboardingRuntime,
]);