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.

46.3 KB
Raw Blame
import type { ListWorkspaceMembersParams, ToolLabelResolution } from '@lobechat/builtin-tool-task';
import {
  describeTaskModelChange,
  MISSING_TASK_NAME_ERROR,
  normalizeListTasksParams,
  normalizeListWorkspaceMembersParams,
  normalizeSetTaskVerifyParams,
  resolveToolLabelIds,
  selectAssignableMembers,
  TaskIdentifier,
  toCreateTaskModelConfig,
  toTaskModelConfigPatch,
} from '@lobechat/builtin-tool-task';
import type { LobeChatDatabase } from '@lobechat/database';
import type { TaskAssignableMember, TaskCreatedItem } from '@lobechat/prompts';
import {
  formatDependencyAdded,
  formatDependencyRemoved,
  formatTaskCreated,
  formatTaskDeleted,
  formatTaskDetail,
  formatTaskEdited,
  formatTaskList,
  formatTasksCreated,
  formatWorkspaceMembers,
  priorityLabel,
} from '@lobechat/prompts';
import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';
import { invertTaskLabelChange } from '@lobechat/types';
import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';
import pMap from 'p-map';

import { AgentModel } from '@/database/models/agent';
import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
import { WorkspaceModel } from '@/database/models/workspace';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import { appEnv } from '@/envs/app';
import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { taskRouter } from '@/server/routers/lambda/task';
import { taskLabelRouter } from '@/server/routers/lambda/taskLabel';
import { TaskService } from '@/server/services/task';
import { resolveTaskOrThrow, resolveTasksOrThrow } from '@/server/services/task/utils';

import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';
import { createTaskAssigneeHelpers } from './taskAssignees';
import { taskResult, taskResultLabel } from './taskResults';
import { type ServerRuntimeRegistration } from './types';

export interface TaskRuntimeDeps {
  agentId?: string;
  agentModel: AgentModel;
  // Assistant message that carried the createTask tool call β€” the tool-call
  // anchor, NOT the source user message. Recorded as `context.origin.messageId`.
  assistantMessageId?: string;
  db?: LobeChatDatabase;
  // Pointers to the conversation that invoked the createTask tool. Recorded into
  // `tasks.context.origin` so the task's handoff result can later be delivered
  // back to this session. All optional β€” a task can be created
  // outside an agent turn (e.g. via the API).
  operationId?: string;
  // Project the run belongs to: tasks it creates land there by default.
  projectId?: string;
  // Resolves the base URL for task deep-links: app origin + optional `/{slug}`
  // workspace prefix. Provided by the factory (which owns db / userId / the
  // resolved workspaceId); when absent (unit tests) links fall back to the bare
  // app origin.
  resolveLinkBaseUrl?: () => Promise<string>;
  // Root runtime operation used to aggregate Works produced during one run.
  rootOperationId?: string;
  scope?: string | null;
  taskCaller: ReturnType<typeof taskRouter.createCaller>;
  taskId?: string;
  taskLabelCaller?: ReturnType<typeof taskLabelRouter.createCaller>;
  taskModel: TaskModel;
  taskService: TaskService;
  threadId?: string | null;
  toolCallId?: string;
  // Source tool result message id, when the runtime already has one.
  toolMessageId?: string;
  topicId?: string | null;
  userId?: string;
  workspaceId?: string;
}

export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
  const {
    agentId,
    assistantMessageId,
    operationId,
    rootOperationId,
    scope,
    taskId,
    toolCallId,
    topicId,
  } = deps;
  // Models are read through `deps` (not destructured) so callers can swap them
  // in lazily β€” e.g. after async workspace resolution in the runtime factory.
  const taskModel = () => deps.taskModel;
  const taskService = () => deps.taskService;
  const taskCaller = () => deps.taskCaller;

  /** Resolve agent-supplied label names against the registry; never creates labels. */
  const resolveLabels = async (
    names: string[] | undefined,
    allowGroups = false,
  ): Promise<ToolLabelResolution> => {
    if (!names?.some((name) => name.trim())) return { ids: [] };
    if (!deps.taskLabelCaller) {
      return { error: 'Task labels are unavailable in this context.', ids: [] };
    }
    return resolveToolLabelIds(await deps.taskLabelCaller.list(), names, { allowGroups });
  };

  // Base URL for task deep-links embedded in tool results. These results can be
  // pushed to IM / bot channels and mobile, so the link must be ABSOLUTE β€” and
  // workspace-scoped tasks live under `/{slug}/task/...`, so the slug has to be
  // in the path too or the link resolves to the wrong (personal) scope. The
  // factory supplies the workspace-aware resolver; fall back to the bare origin.
  const taskLinkBaseUrl = async (): Promise<string> =>
    (await deps.resolveLinkBaseUrl?.()) ?? appEnv.APP_URL.replace(/\/$/, '');

  const { notifyMemberAssigned, resolveAssigneeAgent, resolveMemberLabel } =
    createTaskAssigneeHelpers(deps);

  type CreateTaskArgs = {
    instruction: string;
    assigneeAgentId?: string;
    assigneeUserId?: string;
    // Bind a goal entity to the created task (see TaskService.createTask).
    goal?: {
      maxRounds?: number | null;
      maxTotalCost?: number | null;
      requirement?: string | null;
      title?: string;
    };
    labels?: string[];
    model?: string;
    name: string;
    parentIdentifier?: string;
    priority?: number;
    provider?: string;
    sortOrder?: number;
  };

  const createTaskImpl = async (
    rawArgs: CreateTaskArgs,
  ): Promise<{ content: string; identifier?: string; success: boolean; taskId?: string }> => {
    // Models fill optional ids with "" β€” treat blanks as omitted so they fall
    // back to the defaults instead of hitting the foreign keys as ''.
    const args: CreateTaskArgs = {
      ...rawArgs,
      assigneeAgentId: rawArgs.assigneeAgentId?.trim() || undefined,
      assigneeUserId: rawArgs.assigneeUserId?.trim() || undefined,
      parentIdentifier: rawArgs.parentIdentifier?.trim() || undefined,
    };
    // `name` is required by the manifest but nothing enforced it: nameless
    // tasks listed as "(unnamed)" and the receipt printed `"null"`.
    if (!args.name?.trim()) return { content: MISSING_TASK_NAME_ERROR, success: false };
    let modelConfig: ReturnType<typeof toCreateTaskModelConfig>;
    try {
      modelConfig = toCreateTaskModelConfig(args);
    } catch (error) {
      return { content: (error as Error).message, success: false };
    }
    let parentLabel: string | undefined;

    // Pre-resolve parent identifier so we can surface a tool-friendly error
    // and label, and pass the resolved id straight through to the service.
    let parentTaskId: string | undefined;
    let projectId = deps.projectId;
    if (args.parentIdentifier) {
      const parent = await taskModel().resolve(args.parentIdentifier);
      if (!parent)
        return { content: `Parent task not found: ${args.parentIdentifier}`, success: false };
      parentTaskId = parent.id;
      parentLabel = parent.identifier;
      // A subtask follows its parent's project, which the service enforces.
      projectId = parent.projectId ?? undefined;
    }

    const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, projectId);
    if (!assigneeResult.success) return { content: assigneeResult.content, success: false };
    // Resolved before the insert so a bad label name creates nothing.
    const labelResult = await resolveLabels(args.labels);
    if (labelResult.error) return { content: labelResult.error, success: false };

    // Capture where this task was spawned from so the lifecycle can later
    // bridge the handoff result back to the creator conversation.
    // Only persist the pocket when we actually have a creator agent + topic;
    // tasks created outside an agent turn (e.g. via API) have no origin.
    const originOperationId = rootOperationId ?? operationId;
    const origin =
      agentId && topicId
        ? {
            agentId,
            messageId: assistantMessageId,
            operationId: originOperationId,
            toolCallId,
            topicId,
          }
        : undefined;

    // Executing agent and human owner are independent, coexisting sides (the
    // member owns the outcome, the agent executes) β€” a member owner does not
    // suppress the usual current-agent default.
    let task: Awaited<ReturnType<TaskService['createTask']>>;
    try {
      task = await taskService().createTask({
        assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),
        assigneeUserId: args.assigneeUserId,
        config: modelConfig,
        context: origin ? { origin } : undefined,
        createdByAgentId: agentId,
        instruction: args.instruction,
        name: args.name,
        parentTaskId,
        priority: args.priority,
        projectId: parentTaskId ? undefined : projectId,
        sortOrder: args.sortOrder,
      });
    } catch (error) {
      // Drizzle's message is only `Failed query: insert … params: …`, where
      // null and '' both print as empty, so agents misread it (e.g. as a null
      // workspace or a duplicate identifier). Surface the PG cause (SQLSTATE +
      // constraint + detail) instead. Non-DB errors (TRPCError etc.) already
      // carry an actionable message and keep propagating as before.
      const pgError = unwrapPgError(error);
      if (!pgError) throw error;
      return { content: `Failed to create task: ${formatPgError(pgError)}`, success: false };
    }

    let labels: { name: string }[] | undefined;
    if (labelResult.ids.length > 0) {
      try {
        labels = await deps.taskLabelCaller!.addToTask({
          labelIds: labelResult.ids,
          taskId: task.id,
        });
      } catch (error) {
        // Roll the task back (as task.create does) so a failed call leaves
        // nothing behind and a retry cannot produce a duplicate.
        await taskModel()
          .delete(task.id)
          .catch(() => {});
        const message = error instanceof Error ? error.message : String(error);
        return {
          content: `Failed to create task: its labels could not be attached (${message}). Nothing was created.`,
          success: false,
        };
      }
    }

    // Only once the task is complete, so a rolled-back task never notifies.
    notifyMemberAssigned(task);

    return {
      content: formatTaskCreated({
        assigneeLabel: task.assigneeUserId
          ? await resolveMemberLabel(task.assigneeUserId)
          : undefined,
        // Absolute, workspace-scoped link: this content can be pushed to IM /
        // bot channels and mobile, where a relative path has no app origin to
        // resolve against and the `/{slug}` prefix would otherwise be lost.
        baseUrl: await taskLinkBaseUrl(),
        id: task.id,
        identifier: task.identifier,
        instruction: args.instruction,
        labels,
        name: task.name,
        parentLabel,
        parentTaskId,
        priority: task.priority,
        status: task.status,
      }),
      identifier: task.identifier,
      success: true,
      taskId: task.id,
    };
  };

  return {
    addTaskComment: async (args: { content: string; identifier?: string }) => {
      const id = args.identifier?.trim() || taskId;
      if (!id) {
        return {
          content: 'No task identifier provided and no current task context.',
          success: false,
        };
      }

      try {
        const task = await resolveTaskOrThrow(taskModel(), id);
        const result = await taskCaller().addComment({
          authorAgentId: agentId,
          content: args.content,
          id: task.id,
        });

        return {
          content: `Comment added to task ${taskResultLabel(task)}.`,
          success: true,
          state: {
            commentId: result.data.id,
            identifier: task.identifier,
            taskId: task.id,
            success: true,
          },
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to add task comment';
        return { content: `Failed to add task comment: ${message}`, success: false };
      }
    },

    createTask: async (args: CreateTaskArgs) => {
      const result = await createTaskImpl(args);
      const { identifier, taskId: createdTaskId, ...rest } = result;
      // Surface the created task identifier as plugin state (mirrors the client
      // executor's `{ identifier, success }`) so the inline render can link to
      // the task detail, AND so the dispatch-layer Work registration can read the
      // created task identity from `result.state`. Without this the tool message
      // persists no state and the card has nothing to open.
      return identifier
        ? { ...rest, state: { identifier, success: rest.success, taskId: createdTaskId } }
        : rest;
    },

    createTasks: async (args: { tasks: CreateTaskArgs[] }) => {
      const items = Array.isArray(args.tasks) ? args.tasks : [];
      if (items.length === 0) {
        return { content: 'No tasks provided.', success: false };
      }

      const results: TaskCreatedItem[] = [];

      for (const item of items) {
        try {
          const result = await createTaskImpl(item);
          results.push({
            error: result.success ? undefined : result.content,
            identifier: result.identifier,
            taskId: result.taskId,
            name: item.name,
            success: result.success,
          });
        } catch (error) {
          const message = error instanceof Error ? error.message : 'Unknown error';
          results.push({ error: message, name: item.name, success: false });
        }
      }

      const succeeded = results.filter((r) => r.success).length;
      const failed = results.length - succeeded;

      return {
        // Absolute, workspace-scoped links so the summary stays clickable when
        // pushed to IM / mobile.
        content: formatTasksCreated(results, await taskLinkBaseUrl()),
        // State parity with the client executor (`{ failed, results, succeeded }`)
        // so the dispatch-layer Work registration can read per-item identity +
        // success from `result.state.results` for partial-failure batches.
        state: { failed, results, succeeded },
        success: failed === 0,
      };
    },

    deleteTask: async (args: { identifier: string }) => {
      const task = await taskModel().resolve(args.identifier);
      if (!task) return { content: `Task not found: ${args.identifier}`, success: false };

      try {
        await taskService().deleteTask(task.id, { keepOperationId: operationId });
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to delete task';
        return { content: `Failed to delete task ${task.identifier}: ${message}`, success: false };
      }

      return {
        content: formatTaskDeleted(taskResultLabel(task), task.name),
        // Surface the deleted task's internal id so the dispatch-layer Work
        // deletion (`work: { action: 'delete' }`) can locate the Work by
        // `works.resourceId = taskId` after the task row is gone.
        state: { identifier: task.identifier, success: true, taskId: task.id },
        success: true,
      };
    },

    deleteTaskComment: async (args: { commentId: string }) => {
      try {
        await taskCaller().deleteComment({ commentId: args.commentId });
        return {
          content: `Comment ${args.commentId} deleted.`,
          success: true,
          state: { commentId: args.commentId, success: true },
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to delete task comment';
        return { content: `Failed to delete task comment: ${message}`, success: false };
      }
    },

    editTask: async (args: {
      addDependencies?: string[];
      addLabels?: string[];
      assigneeAgentId?: string | null;
      assigneeUserId?: string | null;
      description?: string;
      identifier: string;
      instruction?: string;
      model?: string | null;
      name?: string;
      parentIdentifier?: string | null;
      priority?: number;
      provider?: string | null;
      removeDependencies?: string[];
      removeLabels?: string[];
    }) => {
      const task = await taskModel().resolve(args.identifier);
      if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
      const addLabels = await resolveLabels(args.addLabels);
      if (addLabels.error) return { content: addLabels.error, success: false };
      const removeLabels = await resolveLabels(args.removeLabels);
      if (removeLabels.error) return { content: removeLabels.error, success: false };

      // Labels first, in one transaction (removals apply first, so "swap Bug
      // for Feature" ends with Feature): a label failure then writes nothing
      // else. If a later write of this edit fails, only this label change is
      // undone β€” not the whole set replaced β€” so a concurrent edit survives.
      const labelDelta = { add: addLabels.ids, remove: removeLabels.ids };
      let undoLabels = async () => {};
      if (labelDelta.add.length > 0 || labelDelta.remove.length > 0) {
        const labelCaller = deps.taskLabelCaller!;
        const { addLabels: _a, identifier: _i, removeLabels: _r, ...otherArgs } = args;
        const hasOtherEdits = Object.values(otherArgs).some((value) => value !== undefined);
        const readLabels = async () =>
          (await taskCaller().detail({ id: task.id })).data?.labels ?? [];
        const before = hasOtherEdits ? await readLabels() : undefined;
        const after = (await labelCaller.changeForTask({ ...labelDelta, taskId: task.id })).map(
          (label) => label.id,
        );
        if (before) {
          undoLabels = async () => {
            try {
              // Re-read so a teammate's change made since is not rolled over.
              const undo = invertTaskLabelChange(before, labelDelta, after, await readLabels());
              if (undo.add.length === 0 && undo.remove.length === 0) return;
              await labelCaller.changeForTask({ ...undo, taskId: task.id });
            } catch {
              /* best-effort: the edit already reports its own failure */
            }
          };
        }
      }

      // Every failure from here on β€” a validation exit or a rejected write β€”
      // undoes this edit's label change, so the edit never half-applies.
      try {
        const result = await (async () => {
          const updateData: {
            assigneeAgentId?: string | null;
            assigneeUserId?: string | null;
            description?: string;
            instruction?: string;
            name?: string;
            parentTaskId?: string | null;
            priority?: number;
          } = {};
          const changes: string[] = [];
          const ops: Promise<unknown>[] = [];

          if (args.name !== undefined) {
            updateData.name = args.name;
            changes.push(`name β†’ "${args.name}"`);
          }
          if (args.assigneeAgentId !== undefined) {
            const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, task.projectId);
            if (!assigneeResult.success) return assigneeResult;

            updateData.assigneeAgentId = args.assigneeAgentId;
            changes.push(
              args.assigneeAgentId
                ? `assignee agent β†’ ${args.assigneeAgentId}`
                : 'assignee cleared',
            );
          }
          // Independent of the agent side: the member is the human owner and the
          // two assignees coexist, so touching one never clears the other.
          if (args.assigneeUserId !== undefined) {
            updateData.assigneeUserId = args.assigneeUserId;
            changes.push(
              args.assigneeUserId
                ? `assignee member β†’ ${await resolveMemberLabel(args.assigneeUserId)}`
                : 'assignee member cleared',
            );
          }
          if (args.instruction !== undefined) {
            updateData.instruction = args.instruction;
            changes.push(`instruction updated`);
          }
          if (args.description !== undefined) {
            updateData.description = args.description;
            changes.push('description updated');
          }
          if (args.parentIdentifier !== undefined) {
            const parentIdentifier = args.parentIdentifier?.trim() || null;
            updateData.parentTaskId = parentIdentifier
              ? (await resolveTaskOrThrow(taskModel(), parentIdentifier)).id
              : null;
            changes.push(parentIdentifier ? `parent β†’ ${parentIdentifier}` : 'parent cleared');
          }
          if (args.priority !== undefined) {
            updateData.priority = args.priority;
            changes.push(`priority β†’ ${priorityLabel(args.priority)}`);
          }

          // Deep-merged into `config` so checkpoint / review / execution keys survive.
          const configPatch = toTaskModelConfigPatch(args);
          if (configPatch) changes.push(describeTaskModelChange(configPatch));

          if (Object.keys(updateData).length > 0 || configPatch) {
            // Attribution rides the caller's context, not this payload β€” see
            // `AuthContext.actingAgentId`.
            ops.push(
              taskCaller().update({
                id: task.id,
                ...updateData,
                ...(configPatch && { configPatch }),
              }),
            );
          }

          const applyDeps = async (
            ids: string[],
            apply: (depId: string) => Promise<unknown>,
            onChange: (depIdentifier: string) => void,
          ): Promise<string | undefined> => {
            const resolved = await resolveTasksOrThrow(taskModel(), ids, {
              duplicates: 'collapse',
            });
            await pMap(resolved.tasks, (dep) => apply(dep.id), { concurrency: 5 });
            resolved.tasks.forEach((dep) => onChange(taskResultLabel(dep)));
            return undefined;
          };

          const depResults: Promise<string | undefined>[] = [];
          if (args.addDependencies?.length) {
            depResults.push(
              applyDeps(
                args.addDependencies,
                (depId) => taskModel().addDependency(task.id, depId),
                (depIdentifier) =>
                  changes.push(formatDependencyAdded(task.identifier, depIdentifier)),
              ),
            );
          }
          if (args.removeDependencies?.length) {
            depResults.push(
              applyDeps(
                args.removeDependencies,
                (depId) => taskModel().removeDependency(task.id, depId),
                (depIdentifier) =>
                  changes.push(formatDependencyRemoved(task.identifier, depIdentifier)),
              ),
            );
          }

          if (removeLabels.ids.length > 0) {
            changes.push(`labels removed: ${args.removeLabels!.join(', ')}`);
          }
          if (addLabels.ids.length > 0) changes.push(`labels added: ${args.addLabels!.join(', ')}`);

          const hasLabelEdit = labelDelta.add.length > 0 || labelDelta.remove.length > 0;
          if (ops.length === 0 && depResults.length === 0 && !hasLabelEdit) {
            return { content: 'No fields provided; nothing to update.', success: false };
          }

          // Settle every started write before reporting: fail-fast would return
          // while a sibling write is still running and could commit afterwards.
          const [opResults, depSettled] = await Promise.all([
            Promise.allSettled(ops),
            Promise.allSettled(depResults),
          ]);
          const failedOp = [...opResults, ...depSettled].find(
            (result): result is PromiseRejectedResult => result.status === 'rejected',
          );
          if (failedOp) throw failedOp.reason;
          const depErrors = depSettled.map((result) =>
            result.status === 'fulfilled' ? result.value : undefined,
          );
          const firstDepError = depErrors.find((e) => e);
          if (firstDepError) return { content: firstDepError, success: false };

          return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
        })();
        if (!result.success) await undoLabels();
        return result;
      } catch (error) {
        await undoLabels();
        throw error;
      }
    },

    listTasks: async (args: {
      assigneeAgentId?: string;
      labels?: string[];
      limit?: number;
      offset?: number;
      parentIdentifier?: string;
      priorities?: number[];
      statuses?: TaskStatus[];
    }) => {
      const normalized = normalizeListTasksParams(args, {
        currentAgentId: agentId,
        defaultScope: scope === 'task' ? 'allAgents' : 'currentAgent',
      });

      try {
        const labelFilter = await resolveLabels(args.labels, true);
        if (labelFilter.error) return { content: labelFilter.error, success: false };
        if (labelFilter.ids.length > 0) {
          normalized.query.filter = { label: { operator: 'is', values: labelFilter.ids } };
        }
        const result = await taskCaller().list(normalized.query);

        return {
          content: formatTaskList(result.data, normalized.displayFilters),
          state: {
            results: result.data.map((task) => ({
              identifier: task.identifier,
              taskId: task.id,
              success: true,
            })),
          },
          success: true,
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to list tasks';

        return {
          content: `Failed to list tasks: ${message}`,
          success: false,
        };
      }
    },

    listWorkspaceMembers: async (args: ListWorkspaceMembersParams = {}) => {
      const db = deps.db;
      const userId = deps.userId;
      if (!db || !userId) {
        return { content: 'Member directory is unavailable in this context.', success: false };
      }

      try {
        const workspaceId = deps.workspaceId;
        const { limit, query } = normalizeListWorkspaceMembersParams(args);
        // Workspace mode: `query` and `limit` run in SQL, so a large workspace
        // costs one page plus a count. Personal mode: the caller is the only
        // human a task can be assigned to (TaskService.assertAssigneeUserAssignable
        // enforces the same rule), and the same query contract applies.
        const page = workspaceId
          ? await new WorkspaceMemberModel(db, userId).searchAssignableMembers(workspaceId, {
              limit,
              query,
            })
          : (() => {
              const self = selectAssignableMembers([{ id: userId, isSelf: true }], args);
              return {
                rows: self.members.map((m) => ({ nickname: null, role: null, userId: m.id })),
                total: self.total,
              };
            })();
        const memberRows = page.rows;
        const total = page.total;

        const memberIds = memberRows.map((m) => m.userId);
        // Linked IM identities (Discord/Slack/Telegram…) make handle-based
        // requests ("assign this to @Neko") resolvable by exact platform id
        // instead of name similarity. Scoped to this workspace: identities a
        // member linked elsewhere are not exposed to coworkers here.
        const [profiles, emails, imLinks] = await Promise.all([
          UserModel.getDisplayInfoByIds(db, memberIds),
          UserModel.getEmailsByIds(db, memberIds),
          MessengerAccountLinkModel.findByUserIds(db, memberIds, {
            workspaceId: workspaceId ?? null,
          }),
        ]);
        const profileMap = new Map(profiles.map((u) => [u.id, u]));
        const emailMap = new Map(emails.map((u) => [u.id, u.email]));
        const imMap = new Map<string, string[]>();
        for (const link of imLinks) {
          const alias = link.platformUsername
            ? `${link.platform}:@${link.platformUsername}(${link.platformUserId})`
            : `${link.platform}:${link.platformUserId}`;
          imMap.set(link.userId, [...(imMap.get(link.userId) ?? []), alias]);
        }

        const members: TaskAssignableMember[] = memberRows.map((m) => {
          const profile = profileMap.get(m.userId);
          return {
            email: emailMap.get(m.userId),
            id: m.userId,
            imAccounts: imMap.get(m.userId),
            isSelf: m.userId === userId,
            // The name they go by in this workspace, as everywhere else it lists them.
            name: m.nickname ?? profile?.fullName,
            role: m.role,
            username: profile?.username,
          };
        });

        return {
          content: formatWorkspaceMembers(members, { inWorkspace: !!workspaceId, query, total }),
          state: { count: members.length, query, success: true, total },
          success: true,
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to list members';
        return { content: `Failed to list workspace members: ${message}`, success: false };
      }
    },

    setTaskSchedule: async (args: {
      automationMode?: TaskAutomationMode | null;
      heartbeatInterval?: number;
      identifier: string;
      maxExecutions?: number | null;
      schedulePattern?: string | null;
      scheduleTimezone?: string | null;
    }) => {
      const task = await taskModel().resolve(args.identifier);
      if (!task) return { content: `Task not found: ${args.identifier}`, success: false };

      // Validate the schedule the task will end up with before writing anything,
      // so an unsupported pattern is refused instead of stored and misfired.
      const schedule = validateScheduleUpdate(
        { pattern: task.schedulePattern, timezone: task.scheduleTimezone },
        args,
      );
      if (schedule && !schedule.valid) {
        return {
          content: formatInvalidScheduleMessage(task.identifier, schedule.error),
          success: false,
        };
      }
      const schedulePreview = schedule?.valid ? schedule.preview : undefined;

      const changes: string[] = [];
      const ops: Promise<unknown>[] = [];

      // Mirrors client executor: schedule columns go through taskCaller.update;
      // maxExecutions lives in `tasks.config.schedule.maxExecutions` (JSONB) and
      // routes through updateConfig so server-side merge preserves siblings.
      const scheduleUpdate: {
        automationMode?: TaskAutomationMode | null;
        heartbeatInterval?: number;
        schedulePattern?: string | null;
        scheduleTimezone?: string | null;
      } = {};
      if (args.automationMode !== undefined) {
        scheduleUpdate.automationMode = args.automationMode;
        changes.push(
          args.automationMode ? `automation mode β†’ ${args.automationMode}` : 'automation disabled',
        );
      }
      if (args.heartbeatInterval !== undefined) {
        scheduleUpdate.heartbeatInterval = args.heartbeatInterval;
        changes.push(
          args.heartbeatInterval > 0
            ? `heartbeat interval β†’ ${args.heartbeatInterval}s`
            : 'heartbeat interval cleared',
        );
      }
      if (args.schedulePattern !== undefined) {
        scheduleUpdate.schedulePattern = args.schedulePattern;
        changes.push(
          args.schedulePattern
            ? `schedule pattern β†’ "${args.schedulePattern}"`
            : 'schedule pattern cleared',
        );
      }
      if (args.scheduleTimezone !== undefined) {
        scheduleUpdate.scheduleTimezone = args.scheduleTimezone;
        changes.push(
          args.scheduleTimezone
            ? `schedule timezone β†’ ${args.scheduleTimezone}`
            : 'schedule timezone cleared',
        );
      }
      if (Object.keys(scheduleUpdate).length > 0) {
        ops.push(taskCaller().update({ id: task.id, ...scheduleUpdate }));
      }

      if (args.maxExecutions !== undefined) {
        ops.push(
          taskCaller().updateConfig({
            config: { schedule: { maxExecutions: args.maxExecutions } },
            id: task.id,
          }),
        );
        changes.push(
          args.maxExecutions === null
            ? 'max executions cleared (unlimited)'
            : `max executions β†’ ${args.maxExecutions}`,
        );
      }

      if (ops.length === 0) {
        return { content: 'No schedule fields provided; nothing to update.', success: false };
      }

      await Promise.all(ops);

      if (schedulePreview) changes.push(schedulePreview);

      return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
    },

    setTaskVerify: async (args: {
      enabled?: boolean | null;
      identifier: string;
      maxIterations?: number | null;
      requirement?: string | null;
      verifierAgentId?: string | null;
      verifyCriteriaIds?: string[] | null;
      verifyRubricId?: string | null;
    }) => {
      args = normalizeSetTaskVerifyParams(args);
      const task = await taskModel().resolve(args.identifier);
      if (!task) return { content: `Task not found: ${args.identifier}`, success: false };

      // Mirrors the client executor: only forward keys the caller actually
      // provided. The TRPC contract (task.updateVerifyConfig) treats `null` as
      // "clear" and omission as "leave untouched", so an undefined field must
      // NOT reach the payload.
      const verify: {
        enabled?: boolean | null;
        maxIterations?: number | null;
        requirement?: string | null;
        verifierAgentId?: string | null;
        verifyCriteriaIds?: string[] | null;
        verifyRubricId?: string | null;
      } = {};
      const changes: string[] = [];

      if (args.enabled !== undefined) {
        verify.enabled = args.enabled;
        changes.push(
          args.enabled === null
            ? 'verify enabled cleared'
            : `verify ${args.enabled ? 'enabled' : 'disabled'}`,
        );
      }
      if (args.requirement !== undefined) {
        verify.requirement = args.requirement;
        changes.push(
          args.requirement ? 'acceptance requirement set' : 'acceptance requirement cleared',
        );
      }
      if (args.maxIterations !== undefined) {
        verify.maxIterations = args.maxIterations;
        changes.push(
          args.maxIterations === null
            ? 'max iterations cleared'
            : `max iterations β†’ ${args.maxIterations}`,
        );
      }
      if (args.verifierAgentId !== undefined) {
        verify.verifierAgentId = args.verifierAgentId;
        changes.push(
          args.verifierAgentId
            ? `verifier agent β†’ ${args.verifierAgentId}`
            : 'verifier agent cleared',
        );
      }
      if (args.verifyRubricId !== undefined) {
        verify.verifyRubricId = args.verifyRubricId;
        changes.push(
          args.verifyRubricId ? `verify rubric β†’ ${args.verifyRubricId}` : 'verify rubric cleared',
        );
      }
      if (args.verifyCriteriaIds !== undefined) {
        verify.verifyCriteriaIds = args.verifyCriteriaIds;
        changes.push(
          args.verifyCriteriaIds?.length
            ? `verify criteria β†’ ${args.verifyCriteriaIds.length} item(s)`
            : 'verify criteria cleared',
        );
      }

      if (Object.keys(verify).length === 0) {
        return { content: 'No verify fields provided; nothing to update.', success: false };
      }

      await taskCaller().updateVerifyConfig({ id: task.id, verify });

      return taskResult(task, formatTaskEdited(taskResultLabel(task), changes));
    },

    runTask: async (args: {
      continueTopicId?: string;
      identifier?: string;
      model?: string;
      prompt?: string;
      provider?: string;
    }) => {
      const id = args.identifier?.trim() || taskId;
      if (!id) {
        return {
          content: 'No task identifier provided and no current task context.',
          success: false,
        };
      }

      try {
        const task = await resolveTaskOrThrow(taskModel(), id);
        const result = await taskCaller().run({
          continueTopicId: args.continueTopicId,
          id: task.id,
          model: args.model,
          prompt: args.prompt,
          provider: args.provider,
        });

        const topicId = (result as { topicId?: string } | undefined)?.topicId;
        const operationId = (result as { operationId?: string } | undefined)?.operationId;
        const lines = [`Task ${taskResultLabel(task)} started.`];
        if (topicId) lines.push(`  Topic: ${topicId}`);
        if (operationId) lines.push(`  Operation: ${operationId}`);

        return taskResult(task, lines.join('\n'), { topicId, operationId });
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to run task';
        return { content: `Failed to run task ${id}: ${message}`, success: false };
      }
    },

    runTasks: async (args: { identifiers: string[]; model?: string; provider?: string }) => {
      const identifiers = Array.isArray(args.identifiers)
        ? args.identifiers.filter(
            (value): value is string => typeof value === 'string' && !!value.trim(),
          )
        : [];

      if (identifiers.length === 0) {
        return { content: 'No task identifiers provided.', success: false };
      }

      const resolved = await taskModel().resolveRefs(identifiers);
      if (resolved.ambiguous.length)
        throw new Error(`Ambiguous task references: ${resolved.ambiguous.join(', ')}`);
      const results: {
        taskId?: string;
        identifier?: string;
        refs: string[];
        success: boolean;
        error?: string;
      }[] = [];
      for (const task of resolved.tasks) {
        const refs = identifiers.filter((ref) => resolved.byRef.get(ref)?.id === task.id);
        try {
          await taskCaller().run({ id: task.id, model: args.model, provider: args.provider });
          results.push({ taskId: task.id, identifier: task.identifier, refs, success: true });
        } catch (error) {
          results.push({
            taskId: task.id,
            identifier: task.identifier,
            refs,
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error',
          });
        }
      }
      for (const ref of resolved.missing)
        results.push({ refs: [ref], success: false, error: `Task not found: ${ref}` });
      const succeeded = results.filter((result) => result.success).length;
      const failed = results.length - succeeded;
      return {
        content: [
          `Started ${succeeded}/${results.length} tasks (${failed} failed):`,
          ...results.map(
            (result) =>
              `${result.identifier ?? result.refs[0]}${result.taskId ? ` (id: ${result.taskId})` : ''} β€” ${result.success ? 'started' : `failed: ${result.error}`}`,
          ),
        ].join('\n'),
        state: { results, succeeded, failed },
        success: failed === 0,
      };
    },

    updateTaskComment: async (args: { commentId: string; content: string }) => {
      try {
        await taskCaller().updateComment({ commentId: args.commentId, content: args.content });
        return {
          content: `Comment ${args.commentId} updated.`,
          success: true,
          state: { commentId: args.commentId, success: true },
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to update task comment';
        return { content: `Failed to update task comment: ${message}`, success: false };
      }
    },

    updateTaskStatus: async (args: { error?: string; identifier?: string; status: TaskStatus }) => {
      const id = args.identifier || taskId;
      if (!id) {
        return {
          content: 'No task identifier provided and no current task context.',
          success: false,
        };
      }

      try {
        const target = await resolveTaskOrThrow(taskModel(), id);
        // Completing the task that owns the current operation is a delivery
        // request, not an external cancellation. TaskService.updateStatus
        // interrupts every still-running topic when a task leaves `running`;
        // calling it here would therefore make the agent cancel itself and
        // leave an `interrupted` operation / `canceled` topic. Persist the
        // intent instead and let onTopicComplete finalize it after the runtime
        // has reached `done`.
        if (args.status === 'completed' && operationId && taskId && target?.id === taskId) {
          await taskModel().updateContext(target.id, {
            completion: { requestedByOperationId: operationId },
          });
          return {
            content: `Task ${target.identifier} completion requested. It will be finalized when the current run finishes.`,
            success: true,
            state: { taskId: target.id, identifier: target.identifier, success: true },
          };
        }

        const result = await taskCaller().updateStatus({
          error: args.error,
          id: target.id,
          status: args.status,
        });

        return {
          content:
            args.status === 'failed' && args.error
              ? `Task ${taskResultLabel(result.data)} status updated to failed. Error: ${args.error}`
              : `Task ${taskResultLabel(result.data)} status updated to ${args.status}.`,
          success: true,
          state: {
            taskId: result.data.id,
            identifier: result.data.identifier,
            status: result.data.status,
            success: true,
          },
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Failed to update task status';

        return {
          content: `Failed to update task status: ${message}`,
          success: false,
        };
      }
    },

    viewTask: async (args: { identifier?: string }) => {
      const id = args.identifier || taskId;
      if (!id) {
        return {
          content: 'No task identifier provided and no current task context.',
          success: false,
        };
      }

      const task = await resolveTaskOrThrow(taskModel(), id);
      const detail = await taskService().getTaskDetail(task.id);
      if (!detail) return { content: `Task not found: ${id}`, success: false };

      return {
        content: formatTaskDetail(detail),
        state: { taskId: detail.id, identifier: detail.identifier, success: true },
        success: true,
      };
    },
  };
};

export const taskRuntime: ServerRuntimeRegistration = {
  factory: (context) => {
    if (!context.userId || !context.serverDB) {
      throw new Error('userId and serverDB are required for Task tool execution');
    }

    const db = context.serverDB;
    const userId = context.userId;
    const {
      agentId,
      assistantMessageId,
      operationId,
      taskId,
      threadId,
      toolCallId,
      topicId,
      scope,
    } = context;

    // Workspace slug for deep-links: resolved once (memoized) from the workspace
    // owning the created task (`workspaceId` is set by `ensureModels` below),
    // and only when the task is actually workspace-scoped.
    let workspaceId: string | undefined;
    let slugPromise: Promise<string | undefined> | undefined;
    const resolveLinkBaseUrl = async (): Promise<string> => {
      const origin = appEnv.APP_URL.replace(/\/$/, '');
      if (!workspaceId) return origin;
      slugPromise ??= new WorkspaceModel(db, userId)
        .findById(workspaceId)
        .then((workspace) => workspace?.slug ?? undefined)
        .catch(() => undefined);
      const slug = await slugPromise;
      return slug ? `${origin}/${slug}` : origin;
    };

    // Models are wired in lazily after the workspaceId is resolved from the
    // owning task row. `createTaskRuntime` reads them through this shared
    // `deps` object, so re-assigning the fields below propagates into every
    // method without re-creating the runtime.
    const deps = {
      agentId,
      assistantMessageId,
      operationId,
      projectId: context.projectId,
      rootOperationId: context.rootOperationId ?? operationId,
      resolveLinkBaseUrl,
      scope,
      taskId,
      threadId,
      toolCallId,
      toolMessageId: context.toolMessageId,
      topicId,
      db,
      userId,
      workspaceId,
      // Initial personal-mode models cover the no-task-context case. Replaced
      // before the first call when `taskId` is set.
      agentModel: new AgentModel(db, userId),
      taskModel: new TaskModel(db, userId),
      taskService: new TaskService(db, userId),
      // `actingAgentId` names the agent for durable attribution (task
      // reassignment activity). Server-side only by contract β€” it must never
      // reach the router through a client-supplied field.
      taskCaller: taskRouter.createCaller({ actingAgentId: agentId, userId }),
      taskLabelCaller: taskLabelRouter.createCaller({ userId }),
    } as TaskRuntimeDeps;

    let modelsPromise: Promise<void> | undefined;
    const ensureModels = () =>
      (modelsPromise ??= (async () => {
        // A present task remains the durable scope anchor even when the pipeline
        // supplied workspaceId; validate both liveness and scope before writes.
        const wsId = await resolveTaskWorkspaceId(db, taskId, context.workspaceId);
        workspaceId = wsId;
        deps.workspaceId = wsId;
        deps.agentModel = new AgentModel(db, userId, wsId);
        deps.taskModel = new TaskModel(db, userId, wsId);
        deps.taskService = new TaskService(db, userId, wsId);
        // MUST keep `actingAgentId`: this replaces the caller built above, and
        // every exported method awaits `ensureModels()` first β€” dropping it here
        // silently attributes every agent-driven task edit to the session user.
        deps.taskCaller = taskRouter.createCaller({
          actingAgentId: agentId,
          userId,
          workspaceId: wsId,
        });
        deps.taskLabelCaller = taskLabelRouter.createCaller({ userId, workspaceId: wsId });
      })());

    const baseRuntime = createTaskRuntime(deps);

    // Wrap every method so that workspaceId + models are resolved before the
    // delegate runs. Preserves the existing tool API shape.
    return Object.fromEntries(
      Object.entries(baseRuntime).map(([name, fn]) => [
        name,
        async (...args: unknown[]) => {
          await ensureModels();
          return (fn as (...a: unknown[]) => unknown)(...args);
        },
      ]),
    ) as typeof baseRuntime;
  },
  identifier: TaskIdentifier,
};