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.

✨ feat(project): run conversations and tasks inside their project (#21370)

LiJiancab0c6f5904f
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index a4494787bb1..45a3343cbe2 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -306,6 +306,7 @@ export class ServerToolTransport implements ToolTransport {
memoryToolPermission: context.state.world?.agent?.chatConfig?.memory?.toolPermission,
messageId: context.state.origin?.sourceMessageId,
operationId,
+ projectId: context.state.origin?.projectId,
projectSkills: resolveRunProjectSkills(context.state.plan),
rootOperationId: operationId,
scope: context.state.origin?.scope,
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
index 269b5d06c57..7c045d93c20 100644
--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
@@ -183,6 +183,8 @@ export const ExecAgentFieldsSchema = z.object({
* identity survives the gateway step_start snapshot / refetch.
*/
orchestrationRole: z.enum(['supervisor', 'member']).optional(),
+ /** Bind a NEW topic to this project (ignored with topicId; resolved from the topic). */
+ projectId: z.string().optional(),
/** Bind a NEW topic to this project working directory (ignored with topicId). */
projectWorkingDirectoryId: z.string().optional(),
scope: z.string().nullish(),
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
index f8956a5b722..7c4f05a1420 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
@@ -266,6 +266,7 @@ export async function createOperation(
parentOperationId,
progressAnchor: appContext?.subAgentProgress,
},
+ projectId: appContext?.projectId,
scope: appContext?.scope ?? undefined,
sessionId: appContext?.sessionId,
signal: appContext?.agentSignal,
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index cc2345b320f..80acfe91cfc 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -484,6 +484,8 @@ export interface OperationCreationParams {
* callSubAgent child (which shares `isSubAgent: true`).
*/
orchestrationRole?: 'supervisor' | 'member';
+ /** Project the run belongs to, stored on `state.origin.projectId`. */
+ projectId?: string;
scope?: string | null;
/** Conversation/session locator used to rebuild an authenticated Review route. */
sessionId?: string;
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index 55ccdf88216..abec7f2dfe3 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -22,6 +22,7 @@ const {
mockMessageCreate,
mockMessageQuery,
mockResolveTask,
+ mockToolState,
mockToolsEnv,
} = vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
@@ -34,6 +35,7 @@ const {
mockMessageCreate: vi.fn(),
mockMessageQuery: vi.fn(),
mockResolveTask: vi.fn(),
+ mockToolState: { enabledToolIds: [] as string[] },
mockToolsEnv: {
MULTIMODAL_UNDERSTANDING_MODEL: undefined as string | undefined,
MULTIMODAL_UNDERSTANDING_PROVIDER: undefined as string | undefined,
@@ -162,6 +164,32 @@ vi.mock('@/database/models/task', () => ({
}),
}));
+// The run's project: coordinated by `agent-coordinator`, one member, no knowledge.
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn().mockImplementation(function () {
+ const project = {
+ coordinatorAgentId: 'agent-coordinator',
+ id: 'project-1',
+ identifier: 'APO',
+ name: 'Apollo',
+ status: 'active',
+ };
+ return {
+ findById: vi.fn().mockResolvedValue(project),
+ getEnabledKnowledgeBaseIds: vi.fn().mockResolvedValue([]),
+ listAgents: vi.fn().mockResolvedValue([
+ {
+ agent: { id: 'agent-coordinator', title: 'Coordinator' },
+ binding: { enabled: true, role: 'coordinator' },
+ },
+ ]),
+ listKnowledgeBases: vi.fn().mockResolvedValue([]),
+ listTasks: vi.fn().mockResolvedValue([]),
+ resolveCoordinatorAgents: vi.fn(async (items: unknown[]) => items),
+ };
+ }),
+}));
+
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(function () {
return {
@@ -198,7 +226,7 @@ vi.mock('@/server/services/file', () => ({
vi.mock('@/server/modules/Mecha', () => ({
createServerAgentToolsEngine: vi.fn().mockReturnValue({
generateToolsDetailed: vi.fn().mockImplementation(function () {
- return { enabledToolIds: [], tools: [] };
+ return { enabledToolIds: [...mockToolState.enabledToolIds], tools: [] };
}),
getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
}),
@@ -254,6 +282,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
mockMessageQuery.mockResolvedValue([]);
mockIsAgentSignalEnabledForUser.mockResolvedValue(true);
mockResolveTask.mockResolvedValue(null);
+ mockToolState.enabledToolIds = [];
mockGetInfoForAIGeneration.mockResolvedValue({
responseLanguage: 'en-US',
userName: 'Test User',
@@ -842,6 +871,44 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
);
});
+ describe('project context', () => {
+ const runCoordinator = async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-coordinator',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ });
+ await service.execAgent({
+ agentId: 'agent-coordinator',
+ appContext: { projectId: 'project-1' },
+ prompt: 'Split the launch into tasks',
+ });
+ return mockCreateOperation.mock.calls[0][0].initialContext.initialContext.projectContext
+ .contextPrompt as string;
+ };
+
+ it('gives the coordinator its delegation rules when the task tool is in its tool set', async () => {
+ mockToolState.enabledToolIds = ['lobe-task'];
+
+ const prompt = await runCoordinator();
+
+ expect(prompt).toContain('Apollo');
+ expect(prompt).toContain('<coordination_rules>');
+ });
+
+ it('leaves the delegation rules out when the final tool set has no task tool', async () => {
+ // e.g. an exclusive continuation: the rules would name createTask / runTask,
+ // which the model cannot call.
+ const prompt = await runCoordinator();
+
+ expect(prompt).toContain('Apollo');
+ expect(prompt).not.toContain('<coordination_rules>');
+ });
+ });
+
it('should inject lobe-agent when history has audio and model lacks native audio support', async () => {
mockGetAgentConfig.mockResolvedValue({
chatConfig: {},
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 00e8fa11ad9..3dc0800bf09 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -449,9 +449,16 @@ export const execAgentTurn = async (
const runContext: ExecRunContext = {
agentConfig,
+ // Facts the turn resolved (builder target, project) ride on the context so
+ // every later stage β€” and the frozen operation origin β€” reads one value.
appContext:
- turn.editingAgentId && turn.editingAgentId !== appContext?.editingAgentId
- ? { ...appContext, editingAgentId: turn.editingAgentId }
+ (turn.editingAgentId && turn.editingAgentId !== appContext?.editingAgentId) ||
+ turn.projectId !== appContext?.projectId
+ ? {
+ ...appContext,
+ editingAgentId: turn.editingAgentId ?? appContext?.editingAgentId,
+ projectId: turn.projectId,
+ }
: appContext,
assistantMessageId: turn.assistantMessageId,
canUseDevice,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index ef5ccf65849..a5706fab1b8 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -21,6 +21,7 @@ import { resolveSandboxSessionConfig } from '@/server/services/sandbox/session';
import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';
import type { ExecRunContext } from '../../types';
import { heteroOperationCapabilities } from '../heteroOperationCapabilities';
+import { buildHeteroProjectContext } from '../projectContext';
import { buildViewedTaskContextPrompt, joinSystemContext } from '../viewedTaskContext';
import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';
@@ -196,7 +197,10 @@ export const prepareHeteroRun = async (
// user attached to this message ride along β€” the same selection context the
// desktop's in-process run hands its CLI.
const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;
- const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);
+ const [viewedTaskContext, projectContext] = await Promise.all([
+ buildViewedTaskContextPrompt(deps, appContext, operationTaskId),
+ buildHeteroProjectContext(deps, appContext?.projectId, agentConfig.id),
+ ]);
const contextSelections = userMessageMetadata?.contextSelections;
const pageSelections = userMessageMetadata?.pageSelections;
const selectionContext = contextSelections?.length
@@ -205,7 +209,7 @@ export const prepareHeteroRun = async (
? formatPageSelections(pageSelections)
: undefined;
const agentSystemContext = withConversationGoalPrompt(
- joinSystemContext(providerContext, viewedTaskContext, selectionContext),
+ joinSystemContext(providerContext, projectContext, viewedTaskContext, selectionContext),
prompt,
);
const systemContext = buildCloudHeteroContext({
diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts
new file mode 100644
index 00000000000..65204f29a63
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts
@@ -0,0 +1,75 @@
+import type { InternalExecAgentParams } from '../types';
+
+export interface NewTopicMetadataInput {
+ appContext?: InternalExecAgentParams['appContext'];
+ botContext?: InternalExecAgentParams['botContext'];
+ cronJobId?: string;
+ editingAgentId?: string;
+ /** Working directory the topic is born in; overrides the client-supplied one. */
+ projectDirectory?: { path: string };
+ taskId?: string;
+ topicBoundDeviceId?: string;
+}
+
+/**
+ * Metadata a NEW topic is written with: cronJobId, taskId, botContext, bound
+ * device, and any client-supplied initial metadata (e.g. repos selected before
+ * the first message). Returns undefined when there is nothing to record.
+ *
+ * Deliberately untyped: `taskId` is a durable key the topic schema type does
+ * not declare, so the caller merges the result into `ChatTopicMetadata`.
+ */
+export const buildNewTopicMetadata = ({
+ appContext,
+ botContext,
+ cronJobId,
+ editingAgentId,
+ projectDirectory,
+ taskId,
+ topicBoundDeviceId,
+}: NewTopicMetadataInput) => {
+ const initialTopicMeta = projectDirectory
+ ? {
+ ...appContext?.initialTopicMetadata,
+ workingDirectory: projectDirectory.path,
+ workingDirectoryConfig: { path: projectDirectory.path },
+ }
+ : appContext?.initialTopicMetadata;
+ // Builder conversations are owned by a builtin builder agent and get no
+ // `groupId` / `sessionId` (those columns mark the target's own chat), so
+ // without this the row keeps no trace of what it was configuring. The
+ // association exists only at run time: a topic written without it can
+ // never be attributed afterwards, which is why it is stamped even though
+ // nothing filters on it yet.
+ const { editingGroupId } = appContext ?? {};
+ if (
+ !cronJobId &&
+ !taskId &&
+ !botContext &&
+ !topicBoundDeviceId &&
+ !initialTopicMeta &&
+ !editingGroupId &&
+ !editingAgentId
+ )
+ return;
+
+ return {
+ bot: botContext,
+ boundDeviceId: topicBoundDeviceId,
+ cronJobId: cronJobId || undefined,
+ ...(editingAgentId && { editingAgentId }),
+ ...(editingGroupId && { editingGroupId }),
+ taskId,
+ ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),
+ ...(initialTopicMeta?.sandboxInstanceId && {
+ sandboxInstanceId: initialTopicMeta.sandboxInstanceId,
+ }),
+ ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),
+ ...(initialTopicMeta?.workingDirectory && {
+ workingDirectory: initialTopicMeta.workingDirectory,
+ }),
+ ...(initialTopicMeta?.workingDirectoryConfig && {
+ workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,
+ }),
+ };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index edfe74c8a22..5149030a0ed 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -1,17 +1,17 @@
import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';
import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';
import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import type { LobeAgentAgencyConfig, WorkspaceInitResult } from '@lobechat/types';
-import { buildGoalOverviewContext, getWorkingDirEffectivePath } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
import debug from 'debug';
import type { AgentModel } from '@/database/models/agent';
import { DeviceModel } from '@/database/models/device';
import { ExpertiseModel } from '@/database/models/expertise';
-import { GoalGraphModel } from '@/database/models/goalGraph';
import type { MessageModel } from '@/database/models/message';
import type { TopicModel } from '@/database/models/topic';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
@@ -33,8 +33,10 @@ import type {
} from '../types';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';
import { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';
+import { buildRunProjectContextPrompt } from './projectContext';
import type { ToolDiscoveryResult } from './toolDiscovery';
import type { RunAttachments } from './turnSetup';
+import { buildViewedGoalOverview } from './viewedGoalContext';
import { buildViewedTaskContextPrompt } from './viewedTaskContext';
const log = debug('lobe-server:ai-agent-service');
@@ -690,39 +692,27 @@ export const prepareOperation = async (
}
}
- // Tasks side conversation: the viewed task (or just the assignee defaults).
- const taskManagerPrompt = await buildViewedTaskContextPrompt(deps, appContext, input.taskId);
- if (taskManagerPrompt) {
+ // Page-scoped context (the viewed task or goal) and the project the run is in.
+ // Delegation rules name the task tool, so they follow its presence in the final set.
+ const [taskManagerPrompt, goalOverview, projectPrompt] = await Promise.all([
+ buildViewedTaskContextPrompt(deps, appContext, input.taskId),
+ buildViewedGoalOverview(deps, appContext),
+ buildRunProjectContextPrompt(deps, appContext?.projectId, resolvedAgentId, {
+ coordinationRules: !!toolsResult.enabledToolIds?.includes(TaskIdentifier),
+ }),
+ ]);
+ if (taskManagerPrompt || goalOverview || projectPrompt) {
initialContext = {
...initialContext,
initialContext: {
...initialContext.initialContext,
- taskManager: { contextPrompt: taskManagerPrompt },
+ ...(goalOverview && { goalOverview }),
+ ...(projectPrompt && { projectContext: { contextPrompt: projectPrompt } }),
+ ...(taskManagerPrompt && { taskManager: { contextPrompt: taskManagerPrompt } }),
},
};
}
- // Goal-page side conversation: mirror the client executor's injection so
- // server-run agents also answer progress questions from the live graph.
- if (appContext?.viewedGoal?.goalId) {
- try {
- const snapshot = await new GoalGraphModel(deps.db, deps.userId, deps.workspaceId).getGraph(
- appContext.viewedGoal.goalId,
- );
- if (snapshot) {
- initialContext = {
- ...initialContext,
- initialContext: {
- ...initialContext.initialContext,
- goalOverview: buildGoalOverviewContext(snapshot),
- },
- };
- }
- } catch (error) {
- log('execAgent: failed to build goal overview context: %O', error);
- }
- }
-
// Persist the @-mentioned agents into the runtime initialContext so the
// context engine injects the delegation context on every step (survives the
// queue-mode dispatch). The shared context rules fold them into the
diff --git a/apps/server/src/services/aiAgent/pipeline/projectContext.test.ts b/apps/server/src/services/aiAgent/pipeline/projectContext.test.ts
new file mode 100644
index 00000000000..76098b15a36
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/projectContext.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { buildHeteroProjectContext, buildRunProjectContextPrompt } from './projectContext';
+
+const mocks = vi.hoisted(() => ({
+ findById: vi.fn(),
+ listAgents: vi.fn(),
+ listKnowledgeBases: vi.fn(),
+ listTasks: vi.fn(),
+ resolveCoordinatorAgents: vi.fn(async (items: unknown[]) => items),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn().mockImplementation(function () {
+ return mocks;
+ }),
+}));
+
+const deps = { db: {} as never, userId: 'user-1' };
+
+describe('buildRunProjectContextPrompt', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findById.mockResolvedValue({
+ coordinatorAgentId: 'agt-coord',
+ description: 'Autumn launch',
+ identifier: 'APO',
+ name: 'Apollo Renamed',
+ status: 'active',
+ });
+ mocks.listAgents.mockResolvedValue([
+ { agent: { id: 'agt-coord', title: 'Coordinator' }, binding: { enabled: true } },
+ { agent: { id: 'agt-writer', title: 'Writer' }, binding: { enabled: true, role: 'copy' } },
+ { agent: { id: 'agt-off', title: 'Paused' }, binding: { enabled: false, role: 'qa' } },
+ ]);
+ mocks.listKnowledgeBases.mockResolvedValue([
+ { binding: { enabled: true }, knowledgeBase: { id: 'kb-1', name: 'Style guide' } },
+ { binding: { enabled: false }, knowledgeBase: { id: 'kb-2', name: 'Old notes' } },
+ ]);
+ mocks.listTasks.mockResolvedValue([
+ { identifier: 'APO-1', name: 'Done', status: 'completed' },
+ { assigneeAgentId: 'agt-writer', identifier: 'APO-2', name: 'Draft', status: 'running' },
+ { identifier: 'APO-3', name: 'Dropped', status: 'canceled' },
+ ]);
+ });
+
+ it('reads the live project so renames and membership changes reach the next turn', async () => {
+ const prompt = await buildRunProjectContextPrompt(deps, 'proj-1', 'agt-coord');
+
+ expect(prompt).toContain('Apollo Renamed');
+ expect(prompt).toContain('Writer (agt-writer): copy');
+ expect(prompt).not.toContain('agt-off');
+ expect(prompt).toContain('Style guide (kb-1)');
+ expect(prompt).not.toContain('Old notes');
+ expect(prompt).toContain('<open_tasks total="1">');
+ expect(prompt).toContain('APO-2');
+ expect(prompt).not.toContain('APO-1');
+ expect(prompt).toContain('<coordination_rules>');
+ });
+
+ it('treats LobeAI as the coordinator of a project whose main agent was cleared', async () => {
+ mocks.findById.mockResolvedValue({
+ coordinatorAgentId: null,
+ identifier: 'APO',
+ name: 'Apollo',
+ status: 'active',
+ });
+ mocks.resolveCoordinatorAgents.mockImplementationOnce(async (items: any[]) =>
+ items.map((item) => ({ ...item, coordinatorAgentId: 'agt-inbox' })),
+ );
+
+ const prompt = await buildRunProjectContextPrompt(deps, 'proj-1', 'agt-inbox');
+
+ expect(prompt).toContain('<coordination_rules>');
+ });
+
+ it('adds nothing outside a project or when the project is gone', async () => {
+ await expect(buildRunProjectContextPrompt(deps, undefined, 'agt-coord')).resolves.toBe(
+ undefined,
+ );
+ mocks.findById.mockResolvedValue(null);
+ await expect(buildRunProjectContextPrompt(deps, 'proj-1', 'agt-coord')).resolves.toBe(
+ undefined,
+ );
+ });
+
+ it('degrades to no project block when a read fails', async () => {
+ mocks.listTasks.mockRejectedValue(new Error('connection reset'));
+
+ await expect(buildRunProjectContextPrompt(deps, 'proj-1', 'agt-coord')).resolves.toBe(
+ undefined,
+ );
+ });
+
+ it('gives a CLI agent the wrapped context without tool-specific delegation rules', async () => {
+ const context = await buildHeteroProjectContext(deps, 'proj-1', 'agt-coord');
+
+ expect(context?.startsWith('<project_context>\n')).toBe(true);
+ expect(context?.endsWith('\n</project_context>')).toBe(true);
+ expect(context).toContain('Writer (agt-writer): copy');
+ expect(context).not.toContain('<coordination_rules>');
+ await expect(buildHeteroProjectContext(deps, undefined, 'agt-coord')).resolves.toBe(undefined);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/projectContext.ts b/apps/server/src/services/aiAgent/pipeline/projectContext.ts
new file mode 100644
index 00000000000..502e59e811d
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/projectContext.ts
@@ -0,0 +1,94 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { buildProjectContextPrompt } from '@lobechat/prompts';
+import debug from 'debug';
+
+import { ProjectModel } from '@/database/models/project';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/** Open work is anything a member may still act on. */
+const CLOSED_TASK_STATUSES = new Set(['canceled', 'completed']);
+/** Enough for the coordinator to plan from without crowding the turn. */
+const MAX_LISTED_TASKS = 20;
+
+export interface ProjectContextDeps {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * The project context injected into every turn of a run inside a project.
+ * Read live each turn β€” the coordinator's own systemRole only carries its
+ * identity, so renames and membership changes reach it immediately. A failed
+ * read leaves the turn without the block rather than failing it.
+ */
+export const buildRunProjectContextPrompt = async (
+ deps: ProjectContextDeps,
+ projectId: string | undefined,
+ agentId: string,
+ options: { coordinationRules?: boolean } = {},
+): Promise<string | undefined> => {
+ if (!projectId) return;
+
+ try {
+ const projectModel = new ProjectModel(deps.db, deps.userId, deps.workspaceId);
+ const [project, members, knowledgeBases, tasks] = await Promise.all([
+ projectModel.findById(projectId),
+ projectModel.listAgents(projectId),
+ projectModel.listKnowledgeBases(projectId),
+ projectModel.listTasks(projectId),
+ ]);
+ if (!project) return;
+ const [resolvedProject] = await projectModel.resolveCoordinatorAgents([project]);
+
+ const openTasks = (tasks ?? []).filter((task) => !CLOSED_TASK_STATUSES.has(task.status));
+ return buildProjectContextPrompt({
+ coordinationRules: options.coordinationRules,
+ currentAgentId: agentId,
+ knowledgeBases: (knowledgeBases ?? [])
+ .filter(({ binding }) => binding.enabled)
+ .map(({ knowledgeBase }) => ({
+ description: knowledgeBase.description,
+ id: knowledgeBase.id,
+ name: knowledgeBase.name,
+ })),
+ members: (members ?? [])
+ .filter(({ binding }) => binding.enabled)
+ .map(({ agent, binding }) => ({
+ agentId: agent.id,
+ responsibility: binding.responsibility,
+ role: binding.role,
+ title: agent.title,
+ })),
+ openTasks: openTasks.slice(0, MAX_LISTED_TASKS).map((task) => ({
+ assigneeAgentId: task.assigneeAgentId,
+ identifier: task.identifier,
+ name: task.name,
+ priority: task.priority,
+ status: task.status,
+ })),
+ project: resolvedProject,
+ totalOpenTasks: openTasks.length,
+ });
+ } catch (error) {
+ log('execAgent: failed to build project context for %s: %O', projectId, error);
+ return;
+ }
+};
+
+/**
+ * The same project context for a heterogeneous (CLI) agent's system context,
+ * which has no context engine to wrap it and no LobeHub task tools to follow
+ * delegation rules with.
+ */
+export const buildHeteroProjectContext = async (
+ deps: ProjectContextDeps,
+ projectId: string | undefined,
+ agentId: string,
+): Promise<string | undefined> => {
+ const prompt = await buildRunProjectContextPrompt(deps, projectId, agentId, {
+ coordinationRules: false,
+ });
+ return prompt && `<project_context>\n${prompt}\n</project_context>`;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index fffee15424a..8ad5129bfb9 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -289,6 +289,7 @@ export const startOperation = async (
// inactivity-watchdog abandon path can distinguish an isolated group
// member ('member') from a genuine callSubAgent child.
orchestrationRole: appContext?.orchestrationRole,
+ projectId: appContext?.projectId,
scope: appContext?.scope,
sessionId: appContext?.sessionId,
sourceMessageId: userMessageId ?? parentMessageId ?? undefined,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
index 29587c3b050..3ada594be33 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -9,6 +9,7 @@
import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -49,6 +50,29 @@ vi.mock('@/database/models/chatGroup', () => ({
getGroupAgentsWithMeta = vi.fn(async () => chatGroupState.roster);
},
}));
+const { projectState } = vi.hoisted(() => ({
+ projectState: {
+ coordinatorAgentId: 'coordinator-1' as string | null,
+ inboxAgentId: 'lobe-ai',
+ knowledgeBaseIds: [] as string[],
+ },
+}));
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: class {
+ findById = vi.fn(async (id: string) => ({
+ coordinatorAgentId: projectState.coordinatorAgentId,
+ id,
+ }));
+ getEnabledKnowledgeBaseIds = vi.fn(async () => projectState.knowledgeBaseIds);
+ // A cleared main agent reads back as LobeAI.
+ resolveCoordinatorAgents = vi.fn(async (items: Array<{ coordinatorAgentId: string | null }>) =>
+ items.map((item) => ({
+ ...item,
+ coordinatorAgentId: item.coordinatorAgentId ?? projectState.inboxAgentId,
+ })),
+ );
+ },
+}));
const { connectorToolState } = vi.hoisted(() => ({
connectorToolState: { tools: [] as Array<{ permission: string; toolName: string }> },
}));
@@ -182,6 +206,9 @@ const lastEngineOptions = () =>
beforeEach(() => {
deviceGatewayState.isConfigured = false;
chatGroupState.roster = [];
+ projectState.coordinatorAgentId = 'coordinator-1';
+ projectState.inboxAgentId = 'lobe-ai';
+ projectState.knowledgeBaseIds = [];
vi.mocked(getScopedOnlineDevices).mockReset().mockResolvedValue([]);
vi.mocked(collectBorrowedConnectors).mockReset().mockReturnValue([]);
vi.mocked(buildConnectorOwnershipPrompt).mockReset().mockReturnValue('');
@@ -312,11 +339,42 @@ describe('discoverTools β€” turn-scoped builtins', () => {
expect(result.agentPlugins).toContain(LobeAgentManifest.identifier);
});
+ it('gives a project coordinator the task tool and the project knowledge', async () => {
+ projectState.coordinatorAgentId = 'agent-1';
+ projectState.knowledgeBaseIds = ['kb-project'];
+
+ const result = await run({ appContext: { projectId: 'project-1' } }).promise;
+
+ expect(result.agentPlugins).toContain(TaskIdentifier);
+ expect(lastEngineOptions().hasEnabledKnowledgeBases).toBe(true);
+ });
+
+ it('gives LobeAI the task tool in a project whose main agent was cleared', async () => {
+ // The run agent is LobeAI: a cleared main agent resolves to it.
+ projectState.coordinatorAgentId = null;
+ projectState.inboxAgentId = 'agent-1';
+
+ const result = await run({ appContext: { projectId: 'project-1' } }).promise;
+
+ expect(result.agentPlugins).toContain(TaskIdentifier);
+ });
+
+ it('lets a project member search project knowledge without delegating work', async () => {
+ projectState.knowledgeBaseIds = ['kb-project'];
+
+ const result = await run({ appContext: { projectId: 'project-1' } }).promise;
+
+ expect(result.agentPlugins).not.toContain(TaskIdentifier);
+ expect(lastEngineOptions().hasEnabledKnowledgeBases).toBe(true);
+ });
+
it('adds nothing turn-scoped for a plain text turn', async () => {
const result = await run().promise;
expect(result.agentPlugins).not.toContain(MessageToolIdentifier);
expect(result.agentPlugins).not.toContain(LobeAgentManifest.identifier);
+ expect(result.agentPlugins).not.toContain(TaskIdentifier);
+ expect(lastEngineOptions().hasEnabledKnowledgeBases).toBe(false);
expect(result.operationAgentGroup).toBeUndefined();
});
});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index 238b7cd9256..e9ce20e4e71 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -210,6 +210,7 @@ export const discoverTools = async (
candidateIds: [...agentPlugins],
exclusivePluginIds,
isGoalTurn,
+ projectId: appContext?.projectId,
requestedDeviceId,
resolvedAgentId,
shareGate,
@@ -319,10 +320,15 @@ export const discoverTools = async (
await throwIfExecutionAborted('tool discovery');
- // 5e. Create tools using Server AgentToolsEngine
+ // 5e. Create tools using Server AgentToolsEngine. Project knowledge counts:
+ // every agent in a project searches it, even with none of its own.
+ const projectScope = await toolReads.projectScope;
hasEnabledKnowledgeBases =
- agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
- false;
+ projectScope.hasKnowledgeBases ||
+ (agentConfig.knowledgeBases?.some(
+ (kb: { enabled?: boolean | null }) => kb.enabled === true,
+ ) ??
+ false);
hasAgentDocuments = await toolReads.agentDocuments;
const hasOversizedFiles = await toolReads.oversizedFiles;
@@ -346,14 +352,17 @@ export const discoverTools = async (
builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
builtinModels.find((item) => item.id === model)?.abilities;
agentPlugins = [
- ...agentPlugins,
- ...(await resolveTurnScopedPluginIds({
- attachedFileTypes: await toolReads.attachedFileTypes,
- externalFileTypes: rawExternalFileTypes,
- isBotConversation,
- loadHistoryMessages,
- modelMediaCapabilities,
- })),
+ ...new Set([
+ ...agentPlugins,
+ ...(await resolveTurnScopedPluginIds({
+ attachedFileTypes: await toolReads.attachedFileTypes,
+ externalFileTypes: rawExternalFileTypes,
+ isBotConversation,
+ isProjectCoordinator: projectScope.isCoordinator,
+ loadHistoryMessages,
+ modelMediaCapabilities,
+ })),
+ ]),
];
if (exclusivePluginIds) {
agentPlugins = agentPlugins.filter((id) => exclusivePluginIds.includes(id));
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/projectScope.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/projectScope.ts
new file mode 100644
index 00000000000..0fb6b3bffb2
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/projectScope.ts
@@ -0,0 +1,52 @@
+import debug from 'debug';
+
+import { ProjectModel } from '@/database/models/project';
+
+import { traceDiscoveryStage } from '../discoveryTracing';
+import type { ToolDiscoveryDeps } from './types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+export interface ProjectToolScope {
+ /** The project links at least one enabled knowledge base the caller can read. */
+ hasKnowledgeBases: boolean;
+ /** The run's agent coordinates the project, so it plans work as tasks. */
+ isCoordinator: boolean;
+}
+
+const NO_PROJECT: ProjectToolScope = { hasKnowledgeBases: false, isCoordinator: false };
+
+/**
+ * What the project a run belongs to adds to its tool surface. Knowledge linked
+ * to the project is searchable by every agent working there, so the knowledge
+ * tool must appear even when the agent has none of its own; the coordinator
+ * also gets the task tool it delegates through. A failed read degrades to the
+ * agent's own surface rather than failing the run.
+ */
+export const readProjectToolScope = async (
+ deps: ToolDiscoveryDeps,
+ ctx: { projectId?: string; resolvedAgentId: string },
+): Promise<ProjectToolScope> => {
+ const { projectId } = ctx;
+ if (!projectId) return NO_PROJECT;
+
+ try {
+ return await traceDiscoveryStage('project_scope', async () => {
+ const projectModel = new ProjectModel(deps.db, deps.userId, deps.workspaceId);
+ const [project, knowledgeBaseIds] = await Promise.all([
+ projectModel.findById(projectId),
+ projectModel.getEnabledKnowledgeBaseIds(projectId),
+ ]);
+ if (!project) return NO_PROJECT;
+ // A cleared main agent falls back to LobeAI, the same as every project read.
+ const [{ coordinatorAgentId }] = await projectModel.resolveCoordinatorAgents([project]);
+ return {
+ hasKnowledgeBases: knowledgeBaseIds.length > 0,
+ isCoordinator: coordinatorAgentId === ctx.resolvedAgentId,
+ };
+ });
+ } catch (error) {
+ log('execAgent: failed to read project tool scope for %s: %O', projectId, error);
+ return NO_PROJECT;
+ }
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
index 00fa511ed37..845962a0017 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -17,6 +17,7 @@ import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDe
import type { ExecRunContext } from '../../types';
import { markDegradedStage, traceDiscoveryStage } from '../discoveryTracing';
+import { readProjectToolScope } from './projectScope';
import type { ToolDiscoveryDeps } from './types';
const log = debug('lobe-server:ai-agent-service');
@@ -46,6 +47,8 @@ export interface ToolReadsContext {
candidateIds: string[];
exclusivePluginIds?: string[];
isGoalTurn: boolean;
+ /** Project the run belongs to (`appContext.projectId`). */
+ projectId?: string;
requestedDeviceId?: string;
resolvedAgentId: string;
shareGate: ExecRunContext['shareGate'];
@@ -458,6 +461,7 @@ export const startToolReads = (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =
devicePool: started(readDevicePool(deps, ctx)),
installedPlugins,
lobehubSkillManifests: started(readLobehubSkillManifests(deps, ctx)),
+ projectScope: started(readProjectToolScope(deps, ctx)), // degrades to no project
};
};
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
index 79bd2e4d140..f8e22b4189b 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
@@ -1,5 +1,6 @@
import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import type { AgentGroupConfig } from '@lobechat/context-engine';
import debug from 'debug';
import type { ModelAbilities } from 'model-bank';
@@ -22,17 +23,20 @@ const log = debug('lobe-server:ai-agent-service');
/**
* Turn-scoped builtin tools to append to the candidate plugin ids: the IM
- * message tool for bot conversations, and multimodal understanding when this
- * turn or its history carries media the model cannot read itself.
+ * message tool for bot conversations, the task tool for a project coordinator
+ * (it delegates by creating and assigning tasks), and multimodal understanding
+ * when this turn or its history carries media the model cannot read itself.
*/
export const resolveTurnScopedPluginIds = async (params: {
attachedFileTypes: string[];
externalFileTypes?: string[];
isBotConversation: boolean;
+ isProjectCoordinator?: boolean;
loadHistoryMessages: ToolDiscoveryInput['loadHistoryMessages'];
modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;
}): Promise<string[]> => {
- const { isBotConversation, loadHistoryMessages, modelMediaCapabilities } = params;
+ const { isBotConversation, isProjectCoordinator, loadHistoryMessages, modelMediaCapabilities } =
+ params;
const externalFileTypes = params.externalFileTypes ?? [];
const inputFileTypes = [...externalFileTypes, ...params.attachedFileTypes];
const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);
@@ -63,6 +67,7 @@ export const resolveTurnScopedPluginIds = async (params: {
return [
...(isBotConversation ? [MessageToolIdentifier] : []),
+ ...(isProjectCoordinator ? [TaskIdentifier] : []),
...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),
];
};
diff --git a/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts b/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts
new file mode 100644
index 00000000000..7827d35c140
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveTurnProjectId } from './topicProject';
+
+const mocks = vi.hoisted(() => ({
+ findById: vi.fn(),
+ resolveTask: vi.fn(),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn().mockImplementation(function () {
+ return { findById: mocks.findById };
+ }),
+}));
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn().mockImplementation(function () {
+ return { resolve: mocks.resolveTask };
+ }),
+}));
+
+const deps = { db: {} as never, userId: 'user-1' };
+
+describe('resolveTurnProjectId', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findById.mockImplementation(async (id: string) => ({ id }));
+ mocks.resolveTask.mockResolvedValue(null);
+ });
+
+ it('starts a new topic in the project the home page opened', async () => {
+ await expect(
+ resolveTurnProjectId(deps, { agentId: 'agt-1', requestedProjectId: 'proj-1' }),
+ ).resolves.toBe('proj-1');
+ expect(mocks.findById).toHaveBeenCalledWith('proj-1');
+ });
+
+ it('rejects a new topic in a project the caller cannot see', async () => {
+ mocks.findById.mockResolvedValue(null);
+
+ await expect(
+ resolveTurnProjectId(deps, { agentId: 'agt-1', requestedProjectId: 'proj-hidden' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('never re-homes an existing topic from the request', async () => {
+ await expect(
+ resolveTurnProjectId(deps, {
+ requestedProjectId: 'proj-1',
+ topicProjectId: null,
+ }),
+ ).resolves.toBeUndefined();
+ expect(mocks.findById).not.toHaveBeenCalled();
+ });
+
+ it('prefers the directory and topic bindings over every other source', async () => {
+ await expect(
+ resolveTurnProjectId(deps, {
+ directoryProjectId: 'proj-dir',
+ requestedProjectId: 'proj-1',
+ }),
+ ).resolves.toBe('proj-dir');
+ await expect(
+ resolveTurnProjectId(deps, { agentId: 'agt-1', topicProjectId: 'proj-topic' }),
+ ).resolves.toBe('proj-topic');
+ expect(mocks.findById).not.toHaveBeenCalled();
+ });
+
+ it("runs a task's turns inside the task's project", async () => {
+ mocks.resolveTask.mockResolvedValue({ id: 'task-1', projectId: 'proj-task' });
+
+ await expect(
+ resolveTurnProjectId(deps, { agentId: 'agt-1', taskId: 'task-1', topicProjectId: null }),
+ ).resolves.toBe('proj-task');
+ });
+
+ it('never infers a project from the agent alone, since main agents are shared', async () => {
+ await expect(resolveTurnProjectId(deps, {})).resolves.toBeUndefined();
+ await expect(resolveTurnProjectId(deps, { topicProjectId: null })).resolves.toBeUndefined();
+ expect(mocks.findById).not.toHaveBeenCalled();
+ });
+
+ it('keeps share visitors out of the creator projects', async () => {
+ await expect(
+ resolveTurnProjectId(deps, {
+ requestedProjectId: 'proj-1',
+ shareGate: {} as never,
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/topicProject.ts b/apps/server/src/services/aiAgent/pipeline/topicProject.ts
new file mode 100644
index 00000000000..cbf9ccb8573
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/topicProject.ts
@@ -0,0 +1,54 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { TRPCError } from '@trpc/server';
+
+import { ProjectModel } from '@/database/models/project';
+import { TaskModel } from '@/database/models/task';
+
+import type { AgentShareGate } from '../shareGate';
+
+export interface TurnProjectDeps {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface TurnProjectInput {
+ /** Project of the working directory a new topic is born in. */
+ directoryProjectId?: string;
+ /** `appContext.projectId`; only honoured when the turn creates its topic. */
+ requestedProjectId?: string;
+ shareGate?: AgentShareGate;
+ taskId?: string;
+ /** `undefined` while the topic does not exist yet; `null` for an unbound topic. */
+ topicProjectId?: string | null;
+}
+
+/**
+ * The project a turn runs in, in order of authority: the directory or topic
+ * binding, the project the request opened (new topics only β€” an existing topic
+ * is never re-homed by a request), and the task the run executes. The agent
+ * alone never implies a project: a main agent (LobeAI by default) is reusable
+ * and may coordinate several projects. Share visitors never run inside the
+ * creator's projects.
+ */
+export const resolveTurnProjectId = async (
+ deps: TurnProjectDeps,
+ input: TurnProjectInput,
+): Promise<string | undefined> => {
+ if (input.directoryProjectId) return input.directoryProjectId;
+ if (input.topicProjectId) return input.topicProjectId;
+ if (input.shareGate) return;
+
+ if (input.topicProjectId === undefined && input.requestedProjectId) {
+ const project = await new ProjectModel(deps.db, deps.userId, deps.workspaceId).findById(
+ input.requestedProjectId,
+ );
+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+ return project.id;
+ }
+
+ if (!input.taskId) return;
+ // `resolve`, like the operation's own task lookup, so both read the task the same way.
+ const task = await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(input.taskId);
+ return task?.projectId ?? undefined;
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 7560318deeb..bef358409f0 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -43,8 +43,10 @@ import { ingestAttachment } from '../ingestAttachment';
import type { AgentShareGate } from '../shareGate';
import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';
import type { InternalExecAgentParams } from '../types';
+import { buildNewTopicMetadata } from './newTopicMetadata';
import { createUserTurnAnchor } from './resolveUserMessageParentId';
import { createStageTracer, openStageMark } from './sendTracing';
+import { resolveTurnProjectId } from './topicProject';
import { buildUserTurnMetadata } from './userTurnMetadata';
const log = debug('lobe-server:ai-agent-service');
@@ -396,6 +398,8 @@ export interface TurnSetupResult {
pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
/** Which layer supplied each pin, for the dispatched configuration receipt. */
pinnedHeterogeneousTopicSources?: HeterogeneousRuntimePinSources;
+ /** Project the turn runs in β€” see `resolveTurnProjectId`. */
+ projectId?: string;
provider: string;
/**
* The request's device, or β€” when it named none β€” the device a reused topic
@@ -469,6 +473,7 @@ export const setupTurn = async (
let topicId = appContext?.topicId;
let editingAgentId = appContext?.editingAgentId;
+ let turnProjectId: string | undefined;
const isFixedExecutionTargetSelection =
!!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
@@ -586,50 +591,21 @@ export const setupTurn = async (
await routeToProjectDirectory(projectDirectory);
}
- // Prepare metadata with cronJobId, taskId, botContext, bound device, and any
- // client-supplied initial metadata (e.g. repos selected before first message).
- const initialTopicMeta = projectDirectory
- ? {
- ...appContext?.initialTopicMetadata,
- workingDirectory: projectDirectory.path,
- workingDirectoryConfig: { path: projectDirectory.path },
- }
- : appContext?.initialTopicMetadata;
- // Builder conversations are owned by a builtin builder agent and get no
- // `groupId` / `sessionId` (those columns mark the target's own chat), so
- // without this the row keeps no trace of what it was configuring. The
- // association exists only at run time: a topic written without it can
- // never be attributed afterwards, which is why it is stamped even though
- // nothing filters on it yet.
- const { editingGroupId } = appContext ?? {};
- const metadata =
- cronJobId ||
- operationTaskId ||
- botContext ||
- topicBoundDeviceId ||
- initialTopicMeta ||
- editingGroupId ||
- editingAgentId
- ? {
- bot: botContext,
- boundDeviceId: topicBoundDeviceId,
- cronJobId: cronJobId || undefined,
- ...(editingAgentId && { editingAgentId }),
- ...(editingGroupId && { editingGroupId }),
- taskId: operationTaskId,
- ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),
- ...(initialTopicMeta?.sandboxInstanceId && {
- sandboxInstanceId: initialTopicMeta.sandboxInstanceId,
- }),
- ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),
- ...(initialTopicMeta?.workingDirectory && {
- workingDirectory: initialTopicMeta.workingDirectory,
- }),
- ...(initialTopicMeta?.workingDirectoryConfig && {
- workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,
- }),
- }
- : undefined;
+ const metadata = buildNewTopicMetadata({
+ appContext,
+ botContext,
+ cronJobId,
+ editingAgentId,
+ projectDirectory,
+ taskId: operationTaskId,
+ topicBoundDeviceId,
+ });
+ turnProjectId = await resolveTurnProjectId(deps, {
+ directoryProjectId: projectDirectory?.projectId,
+ requestedProjectId: appContext?.projectId,
+ shareGate,
+ taskId: operationTaskId,
+ });
const fallbackTitleSource = markdownToTxt(prompt);
const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
@@ -648,10 +624,8 @@ export const setupTurn = async (
// must carry the groupId through too (group topic sidebar + ownership fix).
groupId: appContext?.groupId,
metadata: metadataWithSnapshot,
- ...(projectDirectory && {
- projectId: projectDirectory.projectId,
- projectWorkingDirectoryId: projectDirectory.id,
- }),
+ projectId: turnProjectId,
+ projectWorkingDirectoryId: projectDirectory?.id,
// Snapshot the effective model as the topic's pinned model (config).
model: snapshot.model,
provider: snapshot.provider,
@@ -704,6 +678,11 @@ export const setupTurn = async (
// (config source of truth), NOT in metadata.
const existingTopic = await deps.topicModel.findById(topicId);
topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
+ turnProjectId = await resolveTurnProjectId(deps, {
+ shareGate,
+ taskId: operationTaskId,
+ topicProjectId: existingTopic?.projectId ?? null,
+ });
// A project conversation without a directory follows the plain
// topic-pinned device path below, like any other conversation.
if (existingTopic?.projectWorkingDirectoryId) {
@@ -1106,6 +1085,7 @@ export const setupTurn = async (
model,
pinnedHeterogeneousTopicModel,
pinnedHeterogeneousTopicSources,
+ projectId: turnProjectId,
provider,
requestedDeviceId: resolvedRequestedDeviceId,
requestTriggerMetadata,
diff --git a/apps/server/src/services/aiAgent/pipeline/viewedGoalContext.ts b/apps/server/src/services/aiAgent/pipeline/viewedGoalContext.ts
new file mode 100644
index 00000000000..4e130d5f015
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/viewedGoalContext.ts
@@ -0,0 +1,32 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { buildGoalOverviewContext } from '@lobechat/types';
+import debug from 'debug';
+
+import { GoalGraphModel } from '@/database/models/goalGraph';
+
+import type { InternalExecAgentParams } from '../types';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * Goal-page side conversation: mirror the client executor's injection so
+ * server-run agents also answer progress questions from the live graph. A
+ * failed read leaves the turn without the overview.
+ */
+export const buildViewedGoalOverview = async (
+ deps: { db: LobeChatDatabase; userId: string; workspaceId?: string },
+ appContext: InternalExecAgentParams['appContext'],
+) => {
+ const goalId = appContext?.viewedGoal?.goalId;
+ if (!goalId) return;
+
+ try {
+ const snapshot = await new GoalGraphModel(deps.db, deps.userId, deps.workspaceId).getGraph(
+ goalId,
+ );
+ return snapshot ? buildGoalOverviewContext(snapshot) : undefined;
+ } catch (error) {
+ log('execAgent: failed to build goal overview context: %O', error);
+ return;
+ }
+};
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 9ad9c5f1af6..4d79c64934d 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -133,7 +133,7 @@ export class TaskService {
}
if (createData.projectId) {
- const project = await this.projectModel.findManageableById(createData.projectId);
+ const project = await this.projectModel.findById(createData.projectId);
if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
index ec146f039df..d7749118363 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
@@ -6,6 +6,7 @@ import { knowledgeBaseRuntime } from '../knowledgeBase';
const mocks = vi.hoisted(() => ({
getAgentAssignedKnowledge: vi.fn(),
+ getEnabledKnowledgeBaseIds: vi.fn(),
getEnabledKnowledgeBaseIdsForTask: vi.fn(),
semanticSearchForChat: vi.fn(),
}));
@@ -18,7 +19,10 @@ vi.mock('@/database/models/agent', () => ({
vi.mock('@/database/models/project', () => ({
ProjectModel: vi.fn().mockImplementation(function () {
- return { getEnabledKnowledgeBaseIdsForTask: mocks.getEnabledKnowledgeBaseIdsForTask };
+ return {
+ getEnabledKnowledgeBaseIds: mocks.getEnabledKnowledgeBaseIds,
+ getEnabledKnowledgeBaseIdsForTask: mocks.getEnabledKnowledgeBaseIdsForTask,
+ };
}),
}));
@@ -46,6 +50,7 @@ const createRuntime = (context: Partial<ToolExecutionContext> = {}) =>
describe('knowledgeBaseRuntime searchKnowledgeBase scope', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.getEnabledKnowledgeBaseIds.mockResolvedValue([]);
mocks.getEnabledKnowledgeBaseIdsForTask.mockResolvedValue([]);
});
@@ -83,4 +88,30 @@ describe('knowledgeBaseRuntime searchKnowledgeBase scope', () => {
);
expect(result.content).toContain('No relevant files found');
});
+
+ it('searches the project knowledge for an agent talking inside a project', async () => {
+ // A project coordinator has no knowledge of its own and no task: before the
+ // project scope reached the runtime, its search always came back empty.
+ mocks.getAgentAssignedKnowledge.mockResolvedValue({
+ files: [],
+ knowledgeBases: [{ enabled: true, id: 'kb_agent' }],
+ });
+ mocks.getEnabledKnowledgeBaseIds.mockResolvedValue(['kb_project', 'kb_agent']);
+ mocks.semanticSearchForChat.mockResolvedValue({
+ chunks: [],
+ documents: [],
+ fileResults: [],
+ totalResults: 0,
+ });
+
+ await createRuntime({ projectId: 'proj_apollo', taskId: 'task_1' }).searchKnowledgeBase({
+ query: 'launch checklist',
+ });
+
+ expect(mocks.getEnabledKnowledgeBaseIds).toHaveBeenCalledWith('proj_apollo');
+ expect(mocks.getEnabledKnowledgeBaseIdsForTask).not.toHaveBeenCalled();
+ expect(mocks.semanticSearchForChat).toHaveBeenCalledWith(
+ expect.objectContaining({ knowledgeIds: ['kb_agent', 'kb_project'] }),
+ );
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts
new file mode 100644
index 00000000000..cfd4b8674f0
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.project.test.ts
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createTaskRuntime } from '../task';
+
+const projectMocks = vi.hoisted(() => ({
+ findById: vi.fn(),
+ listAgents: vi.fn(),
+ resolveCoordinatorAgents: vi.fn(),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn().mockImplementation(function () {
+ return projectMocks;
+ }),
+}));
+
+vi.mock('@/business/server/task/notifyTaskAssigned', () => ({ notifyTaskAssigned: vi.fn() }));
+
+// Server-only env, read for absolute task links.
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.lobehub.com' } }));
+
+// The real router imports the runtime registry back; the runtime only needs a caller.
+vi.mock('@/server/routers/lambda/task', () => ({ taskRouter: { createCaller: vi.fn() } }));
+
+// TaskService pulls ModelRuntime at module load; each test passes its own stub.
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const member = (id: string, title: string, role: string | null, enabled = true) => ({
+ agent: { id, title },
+ binding: { enabled, role },
+});
+
+const createdTask = {
+ assigneeUserId: null,
+ id: 'task-1',
+ identifier: 'APO-1',
+ name: 'Draft launch post',
+ priority: 0,
+ status: 'backlog',
+};
+
+const setup = (overrides: { parent?: { id: string; identifier: string; projectId: string } }) => {
+ const taskService = {
+ createTask: vi.fn().mockResolvedValue(createdTask),
+ updateTaskWithAssigneeLock: vi.fn().mockResolvedValue({}),
+ };
+ const taskModel = {
+ resolve: vi.fn(async (identifier: string) =>
+ overrides.parent?.identifier === identifier ? overrides.parent : null,
+ ),
+ };
+ const runtime = createTaskRuntime({
+ agentId: 'agt-coordinator',
+ agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
+ db: {} as any,
+ projectId: 'proj-apollo',
+ taskCaller: { update: vi.fn().mockResolvedValue({ data: { id: 'task-1' } }) } as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+ return { runtime, taskModel, taskService };
+};
+
+describe('task runtime inside a project', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ projectMocks.findById.mockImplementation(async (id: string) => ({
+ coordinatorAgentId: null,
+ id,
+ }));
+ // A cleared main agent reads back as LobeAI.
+ projectMocks.resolveCoordinatorAgents.mockImplementation(async (items: any[]) =>
+ items.map((item) => ({
+ ...item,
+ coordinatorAgentId: item.coordinatorAgentId ?? 'agt-lobe-ai',
+ })),
+ );
+ projectMocks.listAgents.mockResolvedValue([
+ member('agt-coordinator', 'Apollo Coordinator', 'coordinator'),
+ member('agt-writer', 'Writer', 'copywriter'),
+ member('agt-retired', 'Retired', 'reviewer', false),
+ ]);
+ });
+
+ it('files the tasks it creates under the run project', async () => {
+ const { runtime, taskService } = setup({});
+
+ const result = await runtime.createTask({
+ assigneeAgentId: 'agt-writer',
+ instruction: 'Write the launch post',
+ name: 'Draft launch post',
+ });
+
+ expect(result.success).toBe(true);
+ expect(projectMocks.listAgents).toHaveBeenCalledWith('proj-apollo');
+ expect(taskService.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ assigneeAgentId: 'agt-writer', projectId: 'proj-apollo' }),
+ );
+ });
+
+ it('refuses to hand project work to an agent outside the project and lists who can take it', async () => {
+ const { runtime, taskService } = setup({});
+
+ const result = await runtime.createTask({
+ assigneeAgentId: 'agt-outsider',
+ instruction: 'Write the launch post',
+ name: 'Draft launch post',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('agt-outsider is not a member of this project');
+ expect(result.content).toContain('Writer (agt-writer) β€” copywriter');
+ // A disabled member is not offered either.
+ expect(result.content).not.toContain('agt-retired');
+ expect(taskService.createTask).not.toHaveBeenCalled();
+ });
+
+ it('lets the main agent take project work without a member row', async () => {
+ const { runtime, taskService } = setup({});
+
+ const result = await runtime.createTask({
+ assigneeAgentId: 'agt-lobe-ai',
+ instruction: 'Plan the launch',
+ name: 'Launch plan',
+ });
+
+ expect(result.success).toBe(true);
+ expect(taskService.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ assigneeAgentId: 'agt-lobe-ai', projectId: 'proj-apollo' }),
+ );
+ });
+
+ it("lets a subtask inherit its parent's project instead of the run project", async () => {
+ projectMocks.listAgents.mockResolvedValue([member('agt-writer', 'Writer', null)]);
+ const { runtime, taskService } = setup({
+ parent: { id: 'task-parent', identifier: 'ZEUS-4', projectId: 'proj-zeus' },
+ });
+
+ await runtime.createTask({
+ assigneeAgentId: 'agt-writer',
+ instruction: 'Split out',
+ name: 'Sub',
+ parentIdentifier: 'ZEUS-4',
+ });
+
+ expect(projectMocks.listAgents).toHaveBeenCalledWith('proj-zeus');
+ expect(taskService.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ parentTaskId: 'task-parent', projectId: undefined }),
+ );
+ });
+
+ it("checks a reassignment against the edited task's own project", async () => {
+ const { runtime, taskModel } = setup({});
+ taskModel.resolve.mockResolvedValue({
+ id: 'task-9',
+ identifier: 'ZEUS-9',
+ projectId: 'proj-zeus',
+ });
+
+ const result = await runtime.editTask({
+ assigneeAgentId: 'agt-outsider',
+ identifier: 'ZEUS-9',
+ });
+
+ expect(result.success).toBe(false);
+ expect(projectMocks.listAgents).toHaveBeenCalledWith('proj-zeus');
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
index bfd1878a466..8c4bc78713a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -14,7 +14,7 @@ import { type ServerRuntimeRegistration } from './types';
export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
factory: (context) => {
- const { userId, serverDB, agentId, agentVisibility, taskId, workspaceId } = context;
+ const { userId, serverDB, agentId, agentVisibility, projectId, taskId, workspaceId } = context;
if (!userId || !serverDB) {
throw new Error('userId and serverDB are required for Knowledge Base execution');
}
@@ -40,9 +40,16 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
const knowledge = await agentModel.getAgentAssignedKnowledge(agentId);
return knowledge.knowledgeBases.filter((k) => k.enabled && k.id).map((k) => k.id as string);
};
+ // Every agent working inside a project β€” its coordinator, or a member
+ // running one of its tasks β€” searches the project's knowledge too.
+ const projectKnowledgeBaseIds = () => {
+ if (projectId) return projectModel.getEnabledKnowledgeBaseIds(projectId);
+ if (taskId) return projectModel.getEnabledKnowledgeBaseIdsForTask(taskId);
+ return Promise.resolve([]);
+ };
const [agentIds, projectIds] = await Promise.all([
agentKnowledgeBaseIds(),
- taskId ? projectModel.getEnabledKnowledgeBaseIdsForTask(taskId) : Promise.resolve([]),
+ projectKnowledgeBaseIds(),
]);
return [...new Set([...agentIds, ...projectIds])];
};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 7536f53d9c8..0031886e042 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -24,7 +24,6 @@ import {
import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';
import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';
-import { notifyTaskAssigned } from '@/business/server/task/notifyTaskAssigned';
import { AgentModel } from '@/database/models/agent';
import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
import { TaskModel } from '@/database/models/task';
@@ -35,9 +34,9 @@ import { appEnv } from '@/envs/app';
import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
-import { after } from '@/server/utils/scheduleAfterResponse';
import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';
+import { createTaskAssigneeHelpers } from './taskAssignees';
import { type ServerRuntimeRegistration } from './types';
export interface TaskRuntimeDeps {
@@ -52,6 +51,8 @@ export interface TaskRuntimeDeps {
// 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
@@ -86,7 +87,6 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
} = 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 agentModel = () => deps.agentModel;
const taskModel = () => deps.taskModel;
const taskService = () => deps.taskService;
const taskCaller = () => deps.taskCaller;
@@ -99,63 +99,8 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const taskLinkBaseUrl = async (): Promise<string> =>
(await deps.resolveLinkBaseUrl?.()) ?? appEnv.APP_URL.replace(/\/$/, '');
- const resolveAssigneeAgent = async (assigneeAgentId?: string | null) => {
- if (!assigneeAgentId) return { success: true } as const;
-
- const exists = await agentModel().existsById(assigneeAgentId);
- if (exists) return { success: true } as const;
-
- return {
- content: `Assignee agent not found: ${assigneeAgentId}`,
- success: false,
- } as const;
- };
-
- // Human-readable label for a member assignee in tool output: "Alice (usr_1)".
- // Falls back to the bare id when no db is wired (unit tests) or lookup fails.
- const resolveMemberLabel = async (assigneeUserId: string): Promise<string> => {
- if (!deps.db) return assigneeUserId;
- try {
- const [user] = await UserModel.getDisplayInfoByIds(deps.db, [assigneeUserId]);
- const name = user?.fullName?.trim() || user?.username?.trim();
- return name ? `${name} (${assigneeUserId})` : assigneeUserId;
- } catch {
- return assigneeUserId;
- }
- };
-
- // Assignment ping (Linear-style), mirroring `task.create` in the router: the
- // runtime calls TaskService directly (to persist `context.origin`), so the
- // router's notify hook never fires for tool-created tasks. Delivered after
- // the response as best-effort work β€” the `@/business` slot defaults to a
- // no-op, and a rejecting implementation must not become an unhandled
- // rejection. Silent for self-assignment; the assignee lock already
- // guarantees the member can open the task (private tasks cannot be assigned
- // to anyone but their creator).
- const notifyMemberAssigned = (task: {
- assigneeUserId: string | null;
- id: string;
- identifier: string;
- name: string | null;
- }) => {
- const { assigneeUserId } = task;
- if (!assigneeUserId || !deps.userId || assigneeUserId === deps.userId) return;
- const params = {
- actorUserId: deps.userId,
- assigneeUserId,
- taskId: task.id,
- taskIdentifier: task.identifier,
- taskName: task.name,
- workspaceId: deps.workspaceId,
- };
- after(async () => {
- try {
- await notifyTaskAssigned(params);
- } catch (error) {
- console.error('[task-runtime] Failed to send assignment notification', error);
- }
- });
- };
+ const { notifyMemberAssigned, resolveAssigneeAgent, resolveMemberLabel } =
+ createTaskAssigneeHelpers(deps);
type CreateTaskArgs = {
instruction: string;
@@ -193,15 +138,18 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
// 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);
+ const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, projectId);
if (!assigneeResult.success) return { content: assigneeResult.content, success: false };
// Capture where this task was spawned from so the lifecycle can later
@@ -234,6 +182,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
name: args.name,
parentTaskId,
priority: args.priority,
+ projectId: parentTaskId ? undefined : projectId,
sortOrder: args.sortOrder,
});
} catch (error) {
@@ -417,7 +366,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
changes.push(`name β†’ "${args.name}"`);
}
if (args.assigneeAgentId !== undefined) {
- const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId);
+ const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId, task.projectId);
if (!assigneeResult.success) return assigneeResult;
updateData.assigneeAgentId = args.assigneeAgentId;
@@ -990,6 +939,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
agentId,
assistantMessageId,
operationId,
+ projectId: context.projectId,
rootOperationId: context.rootOperationId ?? operationId,
resolveLinkBaseUrl,
scope,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/taskAssignees.ts b/apps/server/src/services/toolExecution/serverRuntimes/taskAssignees.ts
new file mode 100644
index 00000000000..9d4e6d0fa24
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/taskAssignees.ts
@@ -0,0 +1,108 @@
+import { notifyTaskAssigned } from '@/business/server/task/notifyTaskAssigned';
+import { ProjectModel } from '@/database/models/project';
+import { UserModel } from '@/database/models/user';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import type { TaskRuntimeDeps } from './task';
+
+type AssigneeCheck = { content: string; success: false } | { success: true };
+
+/**
+ * Assignee resolution and notification for the task runtime. Reads `deps`
+ * lazily: the runtime factory swaps its models and workspace in after the
+ * first call resolves the owning scope.
+ */
+export const createTaskAssigneeHelpers = (deps: TaskRuntimeDeps) => {
+ // Project work goes to the project's own agents: the coordinator delegates
+ // by assignment, so an agent nobody invited must not receive it.
+ const checkProjectMember = async (
+ assigneeAgentId: string,
+ projectId: string,
+ ): Promise<AssigneeCheck> => {
+ if (!deps.db || !deps.userId) return { success: true };
+ const projectModel = new ProjectModel(deps.db, deps.userId, deps.workspaceId);
+ const [project, members] = await Promise.all([
+ projectModel.findById(projectId),
+ projectModel.listAgents(projectId),
+ ]);
+ // An unreadable project fails on write with its own error.
+ if (!project || !members) return { success: true };
+ // The main agent always takes project work, even when it is a shared agent
+ // (or LobeAI after the main agent was cleared) without a member row.
+ const [{ coordinatorAgentId }] = await projectModel.resolveCoordinatorAgents([project]);
+ if (assigneeAgentId === coordinatorAgentId) return { success: true };
+ const enabled = members.filter(({ binding }) => binding.enabled);
+ if (enabled.some(({ agent }) => agent.id === assigneeAgentId)) return { success: true };
+
+ const roster = enabled
+ .map(
+ ({ agent, binding }) =>
+ `${agent.title || '(untitled agent)'} (${agent.id})${binding.role ? ` β€” ${binding.role}` : ''}`,
+ )
+ .join('; ');
+ return {
+ content: `Agent ${assigneeAgentId} is not a member of this project, so it cannot take project work. Assign one of the project members instead: ${roster || '(none)'}. If this agent should help, ask the user to invite it to the project first.`,
+ success: false,
+ };
+ };
+
+ const resolveAssigneeAgent = async (
+ assigneeAgentId?: string | null,
+ projectId?: string | null,
+ ): Promise<AssigneeCheck> => {
+ if (!assigneeAgentId) return { success: true };
+
+ const exists = await deps.agentModel.existsById(assigneeAgentId);
+ if (!exists) return { content: `Assignee agent not found: ${assigneeAgentId}`, success: false };
+
+ return projectId ? checkProjectMember(assigneeAgentId, projectId) : { success: true };
+ };
+
+ // Human-readable label for a member assignee in tool output: "Alice (usr_1)".
+ // Falls back to the bare id when no db is wired (unit tests) or lookup fails.
+ const resolveMemberLabel = async (assigneeUserId: string): Promise<string> => {
+ if (!deps.db) return assigneeUserId;
+ try {
+ const [user] = await UserModel.getDisplayInfoByIds(deps.db, [assigneeUserId]);
+ const name = user?.fullName?.trim() || user?.username?.trim();
+ return name ? `${name} (${assigneeUserId})` : assigneeUserId;
+ } catch {
+ return assigneeUserId;
+ }
+ };
+
+ // Assignment ping (Linear-style), mirroring `task.create` in the router: the
+ // runtime calls TaskService directly (to persist `context.origin`), so the
+ // router's notify hook never fires for tool-created tasks. Delivered after
+ // the response as best-effort work β€” the `@/business` slot defaults to a
+ // no-op, and a rejecting implementation must not become an unhandled
+ // rejection. Silent for self-assignment; the assignee lock already
+ // guarantees the member can open the task (private tasks cannot be assigned
+ // to anyone but their creator).
+ const notifyMemberAssigned = (task: {
+ assigneeUserId: string | null;
+ id: string;
+ identifier: string;
+ name: string | null;
+ }) => {
+ const { assigneeUserId } = task;
+ if (!assigneeUserId || !deps.userId || assigneeUserId === deps.userId) return;
+ const params = {
+ actorUserId: deps.userId,
+ assigneeUserId,
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ taskName: task.name,
+ workspaceId: deps.workspaceId,
+ };
+ after(async () => {
+ try {
+ await notifyTaskAssigned(params);
+ } catch (error) {
+ console.error('[task-runtime] Failed to send assignment notification', error);
+ }
+ });
+ };
+
+ return { notifyMemberAssigned, resolveAssigneeAgent, resolveMemberLabel };
+};
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index aa7d3c637b7..0211329aad1 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -304,6 +304,8 @@ export interface ToolExecutionContext {
onWorkRegistration?: (intent: WorkRegistrationIntent) => void;
/** Agent runtime operation ID for structured tool outcome identity. */
operationId?: string;
+ /** Project the run belongs to; scopes project knowledge and created tasks. */
+ projectId?: string;
/**
* Filesystem skills (name + absolute SKILL.md path) discovered on the
* execution device. Used by the Skills runtime to load them on demand via the
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 5c0459b5c72..a8ba3db0c6d 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -92,6 +92,8 @@ export interface AgentRunOrigin {
groupId?: string;
// --- Run tree ---
lineage?: AgentRunLineage;
+ /** Project the conversation (or the run's task) belongs to. */
+ projectId?: string;
scope?: string;
sessionId?: string;
/** Run-scoped Agent Signal marker for background self-iteration / memory runs. */
diff --git a/packages/builtin-agents/src/agents/project-coordinator/index.test.ts b/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
index 51fc4d494db..d9c89078f5e 100644
--- a/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
+++ b/packages/builtin-agents/src/agents/project-coordinator/index.test.ts
@@ -15,17 +15,22 @@ describe('createProjectCoordinatorAgentConfig', () => {
avatar: 'avatar.png',
description: 'Coordinates the LobeHub project',
systemRole: [
- 'You are the coordinator for the project "LobeHub" (LOBE).',
- 'Project description: Ship the next release',
+ 'You are the coordinator agent of a project.',
+ 'The current project, its member agents, linked knowledge bases and open tasks are provided with each message; rely on them over anything you remember.',
'Help the user resume work, turn intent into concrete tasks and goals, use project resources, and coordinate project agents.',
].join('\n'),
title: 'LobeHub Coordinator',
});
});
- it('omits the project description line when no description is provided', () => {
- const config = createProjectCoordinatorAgentConfig({ identifier: 'LOBE', name: 'LobeHub' });
+ it('keeps project facts out of the systemRole so a rename never leaves it stale', () => {
+ const config = createProjectCoordinatorAgentConfig({
+ description: 'Ship the next release',
+ identifier: 'LOBE',
+ name: 'LobeHub',
+ });
- expect(config.systemRole).not.toContain('Project description:');
+ expect(config.systemRole).not.toContain('LobeHub');
+ expect(config.systemRole).not.toContain('Ship the next release');
});
});
diff --git a/packages/builtin-agents/src/agents/project-coordinator/index.ts b/packages/builtin-agents/src/agents/project-coordinator/index.ts
index 6f98563bf83..1991c29e45f 100644
--- a/packages/builtin-agents/src/agents/project-coordinator/index.ts
+++ b/packages/builtin-agents/src/agents/project-coordinator/index.ts
@@ -9,21 +9,22 @@ export interface ProjectCoordinatorContext {
* Project coordinators are provisioned once per project, so they cannot use a
* shared reserved builtin slug. Keep their default configuration here with the
* other product-owned agents, then materialize it into each project's agent row.
+ *
+ * The systemRole only states the role. Everything about the project itself β€”
+ * name, members, linked knowledge, open tasks β€” is injected live on every turn
+ * (`<project_context>`), because a snapshot written here goes stale the moment
+ * the project is renamed or its members change.
*/
export const createProjectCoordinatorAgentConfig = ({
avatar,
- description,
- identifier,
name,
}: ProjectCoordinatorContext) => ({
avatar,
description: `Coordinates the ${name} project`,
systemRole: [
- `You are the coordinator for the project "${name}" (${identifier}).`,
- description ? `Project description: ${description}` : undefined,
+ 'You are the coordinator agent of a project.',
+ 'The current project, its member agents, linked knowledge bases and open tasks are provided with each message; rely on them over anything you remember.',
'Help the user resume work, turn intent into concrete tasks and goals, use project resources, and coordinate project agents.',
- ]
- .filter(Boolean)
- .join('\n'),
+ ].join('\n'),
title: `${name} Coordinator`,
});
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 31ec7b5856e..cbb3e84f4fb 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -58,6 +58,7 @@ import {
PageEditorContextInjector,
PageSelectionsInjector,
PlanInjector,
+ ProjectContextInjector,
ProjectInstructionsInjector,
RuntimeAdditionalContextProvider,
selectActivatedSkills,
@@ -474,6 +475,11 @@ export class MessagesEngine {
}
: undefined),
}),
+ // Project context (members, linked knowledge, open tasks) for a run inside a project
+ new ProjectContextInjector({
+ contextPrompt: initialContext?.projectContext?.contextPrompt,
+ enabled: !!initialContext?.projectContext?.contextPrompt,
+ }),
// Task Manager page context (inject current tasks list/detail to last user message)
new TaskManagerContextInjector({
contextPrompt: initialContext?.taskManager?.contextPrompt,
diff --git a/packages/context-engine/src/providers/ProjectContextInjector.ts b/packages/context-engine/src/providers/ProjectContextInjector.ts
new file mode 100644
index 00000000000..086aa7dcee9
--- /dev/null
+++ b/packages/context-engine/src/providers/ProjectContextInjector.ts
@@ -0,0 +1,65 @@
+import debug from 'debug';
+
+import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ projectContextInjected?: boolean;
+ }
+}
+
+const log = debug('context-engine:provider:ProjectContextInjector');
+
+export interface ProjectContextInjectorConfig {
+ contextPrompt?: string;
+ enabled?: boolean;
+}
+
+/**
+ * Appends the live context of the project a run belongs to (members, linked
+ * knowledge, open tasks) to the last user message.
+ */
+export class ProjectContextInjector extends BaseLastUserContentProvider {
+ readonly name = 'ProjectContextInjector';
+
+ constructor(
+ private config: ProjectContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ log('doProcess: enabled=%s hasPrompt=%s', this.config.enabled, !!this.config.contextPrompt);
+
+ const clonedContext = this.cloneContext(context);
+
+ if (!this.config.enabled || !this.config.contextPrompt) {
+ log('No project context, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);
+
+ log('Last user message index:', lastUserIndex);
+
+ if (lastUserIndex === -1) {
+ log('No user messages found, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock(this.config.contextPrompt, 'project_context')
+ : this.wrapWithSystemContext(this.config.contextPrompt, 'project_context');
+
+ this.appendToLastUserMessage(clonedContext, contentToAppend);
+
+ clonedContext.metadata.projectContextInjected = true;
+
+ log('Project context appended to last user message');
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/__tests__/ProjectContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/ProjectContextInjector.test.ts
new file mode 100644
index 00000000000..620b8f5119f
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/ProjectContextInjector.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { ProjectContextInjector } from '../ProjectContextInjector';
+
+const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [], model: 'test-model', provider: 'test-provider' },
+ isAborted: false,
+ messages,
+ metadata: { maxTokens: 4000, model: 'test-model' },
+});
+
+describe('ProjectContextInjector', () => {
+ it('appends the project context to the last user message', async () => {
+ const injector = new ProjectContextInjector({
+ contextPrompt: '<project identifier="APO" status="active">Apollo</project>',
+ enabled: true,
+ });
+
+ const result = await injector.process(
+ createContext([
+ { content: 'first', role: 'user' },
+ { content: 'reply', role: 'assistant' },
+ { content: 'split the launch into tasks', role: 'user' },
+ ]),
+ );
+
+ expect(result.messages[0].content).toBe('first');
+ expect(result.messages[2].content).toContain('split the launch into tasks');
+ expect(result.messages[2].content).toContain('<project_context>');
+ expect(result.messages[2].content).toContain('Apollo');
+ expect(result.metadata.projectContextInjected).toBe(true);
+ });
+
+ it('leaves the conversation untouched outside a project', async () => {
+ const injector = new ProjectContextInjector({ enabled: false });
+
+ const result = await injector.process(createContext([{ content: 'hello', role: 'user' }]));
+
+ expect(result.messages[0].content).toBe('hello');
+ expect(result.metadata.projectContextInjected).toBeUndefined();
+ });
+});
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index d2877e2c6c3..9ccbabeaf5d 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -35,6 +35,7 @@ export { OnboardingSyntheticStateInjector } from './OnboardingSyntheticStateInje
export { PageEditorContextInjector } from './PageEditorContextInjector';
export { PageSelectionsInjector } from './PageSelectionsInjector';
export { PlanInjector } from './PlanInjector';
+export { ProjectContextInjector } from './ProjectContextInjector';
export { ProjectInstructionsInjector } from './ProjectInstructionsInjector';
export { RuntimeAdditionalContextProvider } from './RuntimeAdditionalContextProvider';
export {
@@ -125,6 +126,7 @@ export type {
export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';
export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';
export type { Plan, PlanInjectorConfig } from './PlanInjector';
+export type { ProjectContextInjectorConfig } from './ProjectContextInjector';
export type {
ProjectInstructionFile,
ProjectInstructionsInjectorConfig,
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index 55440322d61..8c8bf470a33 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -550,6 +550,27 @@ describe('ProjectModel', () => {
}
});
+ it('lets every member who can see a project file work in it', async () => {
+ const workspaceId = 'project-task-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Task Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const creator = new ProjectModel(serverDB, userId, workspaceId);
+ const project = await createProject(creator, { name: 'Shared work' });
+ const privateProject = await createProject(creator, { name: 'Solo', visibility: 'private' });
+ const memberTasks = new TaskModel(serverDB, otherUserId, workspaceId);
+
+ expect(await memberTasks.create({ instruction: 'Pitch in', projectId: project.id })).toEqual(
+ expect.objectContaining({ identifier: `${project.identifier}-1` }),
+ );
+ await expect(
+ memberTasks.create({ instruction: 'Sneak in', projectId: privateProject.id }),
+ ).rejects.toThrow('Project not found');
+ });
+
it('returns null or false for binding operations on inaccessible projects and resources', async () => {
const foreignProject = await createProject(otherModel, { name: 'Foreign' });
const [foreignKnowledgeBase] = await serverDB
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index 73d91a8f0d0..e5a01928a89 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -80,13 +80,13 @@ export class TaskModel {
}
// A prefix is derived from placement, never accepted as a creation field.
+ // Anyone who can see a project may file work in it; project settings stay
+ // with its creator.
let identifierPrefix = DEFAULT_TASK_IDENTIFIER_PREFIX;
if (createData.projectId) {
- const project = await new ProjectModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findManageableById(createData.projectId);
+ const project = await new ProjectModel(this.db, this.userId, this.workspaceId).findById(
+ createData.projectId,
+ );
if (!project) throw new Error('Project not found');
identifierPrefix = project.identifier;
}
diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.ts
index 85b40760924..bb63adebc20 100644
--- a/packages/prompts/src/prompts/index.ts
+++ b/packages/prompts/src/prompts/index.ts
@@ -17,6 +17,7 @@ export * from './knowledgeBaseQA';
export * from './messagesToText';
export * from './planTodo';
export * from './plugin';
+export * from './project';
export * from './remoteDevice';
export * from './search';
export * from './skills';
diff --git a/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap
new file mode 100644
index 00000000000..ed5d6674104
--- /dev/null
+++ b/packages/prompts/src/prompts/project/__snapshots__/index.test.ts.snap
@@ -0,0 +1,26 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`buildProjectContextPrompt > gives the coordinator the roster, knowledge, open work and its delegation rules 1`] = `
+"<project identifier="APO" status="active">Apollo</project>
+<description>Ship the autumn launch</description>
+<members>
+ - Coordinator (agt_coord): coordinator β€” Leads the launch [you]
+ - Writer (agt_writer): copywriter β€” Drafts copy
+ - (untitled agent) (agt_blank)
+</members>
+<knowledge_bases hint="Searchable with the knowledge base tools by every agent in this project">
+ - Style guide (kb_style): Brand voice and tone
+ - Research (kb_research)
+</knowledge_bases>
+<open_tasks total="5">
+ APO-2 ● running [high] Draft post β€” Writer (agt_writer)
+ APO-3 β—‹ backlog [-] (unnamed) β€” unassigned
+ … and 3 more
+</open_tasks>
+<coordination_rules>
+- You coordinate this project. Answer conversational questions yourself; do not turn every message into a task.
+- When the user asks for work that should be planned, split or handed off, create tasks with \`createTask\` / \`createTasks\`. Tasks you create belong to this project automatically.
+- Delegate by setting \`assigneeAgentId\` to the member whose role and responsibility fit. Only the members listed above can be assigned; leave it empty to keep the task yourself. Run a task with \`runTask\` when the user wants it started now.
+- Search the project knowledge before answering questions about the project's own material.
+</coordination_rules>"
+`;
diff --git a/packages/prompts/src/prompts/project/index.test.ts b/packages/prompts/src/prompts/project/index.test.ts
new file mode 100644
index 00000000000..6ed480ced2a
--- /dev/null
+++ b/packages/prompts/src/prompts/project/index.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildProjectContextPrompt } from './index';
+
+const input = {
+ knowledgeBases: [
+ { description: 'Brand voice and tone', id: 'kb_style', name: 'Style guide' },
+ { id: 'kb_research', name: 'Research' },
+ ],
+ members: [
+ {
+ agentId: 'agt_coord',
+ responsibility: 'Leads the launch',
+ role: 'coordinator',
+ title: 'Coordinator',
+ },
+ { agentId: 'agt_writer', responsibility: 'Drafts copy', role: 'copywriter', title: 'Writer' },
+ { agentId: 'agt_blank', title: null },
+ ],
+ openTasks: [
+ {
+ assigneeAgentId: 'agt_writer',
+ identifier: 'APO-2',
+ name: 'Draft post',
+ priority: 2,
+ status: 'running',
+ },
+ { identifier: 'APO-3', name: null, priority: 0, status: 'backlog' },
+ ],
+ project: {
+ coordinatorAgentId: 'agt_coord',
+ description: ' Ship the autumn launch ',
+ identifier: 'APO',
+ name: 'Apollo',
+ status: 'active',
+ },
+ totalOpenTasks: 5,
+};
+
+describe('buildProjectContextPrompt', () => {
+ it('gives the coordinator the roster, knowledge, open work and its delegation rules', () => {
+ expect(buildProjectContextPrompt({ ...input, currentAgentId: 'agt_coord' })).toMatchSnapshot();
+ });
+
+ it('marks a member agent and leaves the coordination rules out', () => {
+ const prompt = buildProjectContextPrompt({ ...input, currentAgentId: 'agt_writer' });
+
+ expect(prompt).toContain('Writer (agt_writer): copywriter β€” Drafts copy [you]');
+ expect(prompt).toContain('Coordinator (agt_coord): coordinator β€” Leads the launch');
+ expect(prompt).not.toContain('<coordination_rules>');
+ });
+
+ it('omits empty knowledge and says there is no open work', () => {
+ const prompt = buildProjectContextPrompt({
+ ...input,
+ currentAgentId: 'agt_coord',
+ knowledgeBases: [],
+ openTasks: [],
+ project: { ...input.project, description: null },
+ totalOpenTasks: 0,
+ });
+
+ expect(prompt).not.toContain('<knowledge_bases');
+ expect(prompt).not.toContain('<description>');
+ expect(prompt).toContain('<open_tasks total="0">\n (none)\n</open_tasks>');
+ });
+});
diff --git a/packages/prompts/src/prompts/project/index.ts b/packages/prompts/src/prompts/project/index.ts
new file mode 100644
index 00000000000..e428eab1ae5
--- /dev/null
+++ b/packages/prompts/src/prompts/project/index.ts
@@ -0,0 +1,127 @@
+import type { TaskSummary } from '../task';
+import { priorityLabel, statusIcon } from '../task';
+
+export interface ProjectContextMember {
+ agentId: string;
+ responsibility?: string | null;
+ role?: string | null;
+ title?: string | null;
+}
+
+export interface ProjectContextKnowledgeBase {
+ description?: string | null;
+ id: string;
+ name: string;
+}
+
+export interface ProjectContextTask extends TaskSummary {
+ assigneeAgentId?: string | null;
+}
+
+export interface ProjectContextPromptInput {
+ /**
+ * Whether the coordinator gets the delegation rules. They name LobeHub task
+ * tools, so a runtime without them (a CLI agent) leaves them out.
+ */
+ coordinationRules?: boolean;
+ /** The agent this run executes as. */
+ currentAgentId: string;
+ knowledgeBases: ProjectContextKnowledgeBase[];
+ /** Enabled members, coordinator included. */
+ members: ProjectContextMember[];
+ /** Open tasks (not completed or canceled), most relevant first. */
+ openTasks: ProjectContextTask[];
+ project: {
+ coordinatorAgentId: string;
+ description?: string | null;
+ identifier: string;
+ name: string;
+ status: string;
+ };
+ /** Count of every open task, which may exceed `openTasks`. */
+ totalOpenTasks: number;
+}
+
+const memberLabel = (member?: ProjectContextMember) =>
+ member ? `${member.title || '(untitled agent)'} (${member.agentId})` : undefined;
+
+const COORDINATOR_RULES = [
+ '<coordination_rules>',
+ '- You coordinate this project. Answer conversational questions yourself; do not turn every message into a task.',
+ '- When the user asks for work that should be planned, split or handed off, create tasks with `createTask` / `createTasks`. Tasks you create belong to this project automatically.',
+ '- Delegate by setting `assigneeAgentId` to the member whose role and responsibility fit. Only the members listed above can be assigned; leave it empty to keep the task yourself. Run a task with `runTask` when the user wants it started now.',
+ "- Search the project knowledge before answering questions about the project's own material.",
+ '</coordination_rules>',
+];
+
+/**
+ * Live context for a run inside a project: who works here, what knowledge is
+ * linked, and what is still open. Rebuilt every turn so renames and membership
+ * changes never go stale; the coordinator also gets its delegation rules. The
+ * context engine wraps it in `<project_context>`.
+ */
+export const buildProjectContextPrompt = (input: ProjectContextPromptInput): string => {
+ const {
+ coordinationRules = true,
+ currentAgentId,
+ knowledgeBases,
+ members,
+ openTasks,
+ project,
+ totalOpenTasks,
+ } = input;
+ const isCoordinator = project.coordinatorAgentId === currentAgentId;
+ const membersById = new Map(members.map((member) => [member.agentId, member]));
+
+ const lines: string[] = [
+ `<project identifier="${project.identifier}" status="${project.status}">${project.name}</project>`,
+ ];
+ if (project.description?.trim()) {
+ lines.push(`<description>${project.description.trim()}</description>`);
+ }
+
+ lines.push('<members>');
+ for (const member of members) {
+ const details = [
+ member.agentId === project.coordinatorAgentId ? 'coordinator' : member.role,
+ member.responsibility,
+ ].filter(Boolean);
+ const you = member.agentId === currentAgentId ? ' [you]' : '';
+ lines.push(
+ ` - ${memberLabel(member)}${details.length > 0 ? `: ${details.join(' β€” ')}` : ''}${you}`,
+ );
+ }
+ lines.push('</members>');
+
+ if (knowledgeBases.length > 0) {
+ lines.push(
+ '<knowledge_bases hint="Searchable with the knowledge base tools by every agent in this project">',
+ );
+ for (const knowledgeBase of knowledgeBases) {
+ const description = knowledgeBase.description?.trim();
+ lines.push(
+ ` - ${knowledgeBase.name} (${knowledgeBase.id})${description ? `: ${description}` : ''}`,
+ );
+ }
+ lines.push('</knowledge_bases>');
+ }
+
+ lines.push(`<open_tasks total="${totalOpenTasks}">`);
+ if (openTasks.length === 0) lines.push(' (none)');
+ for (const task of openTasks) {
+ const assignee = task.assigneeAgentId
+ ? (memberLabel(membersById.get(task.assigneeAgentId)) ?? task.assigneeAgentId)
+ : 'unassigned';
+ lines.push(
+ ` ${task.identifier} ${statusIcon(task.status)} ${task.status} [${priorityLabel(task.priority)}] ${task.name || '(unnamed)'} β€” ${assignee}`,
+ );
+ }
+ if (totalOpenTasks > openTasks.length) {
+ lines.push(` … and ${totalOpenTasks - openTasks.length} more`);
+ }
+ lines.push('</open_tasks>');
+
+ if (isCoordinator && coordinationRules) lines.push(...COORDINATOR_RULES);
+
+ return lines.join('\n');
+};
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 5b26b574f75..4d1bb2c92a4 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -173,6 +173,14 @@ export interface ExecAgentAppContext {
* `metadata.orchestrationRole` so the role snapshot persists for rendering.
*/
orchestrationRole?: 'supervisor' | 'member';
+ /**
+ * Project the run belongs to. On a NEW topic it is written onto the row, so
+ * a conversation started from the project home is born inside the project
+ * even without a working directory. For an existing topic the server
+ * resolves it from the topic (or the run's task) and fills it in here, so
+ * every downstream stage reads one value.
+ */
+ projectId?: string;
/**
* Project working directory a NEW topic is born in β€” the blank conversation a
* project group's "+" opened. The topic is bound to it and the run routes to
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index 8ed8ca38430..ad6c2910d2e 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -254,6 +254,11 @@ export interface RuntimeInitialContext {
* Contains markdown content and metadata captured at operation start
*/
pageEditor?: InitialPageEditorContext;
+ /**
+ * Live project context (members, knowledge, open tasks) for a run inside a
+ * project, rebuilt each turn so renames and membership changes never go stale.
+ */
+ projectContext?: InitialProjectContext;
/**
* Skills explicitly selected by the user for the current request
* This is ephemeral runtime context and is not persisted to chat history
@@ -272,6 +277,11 @@ export interface RuntimeInitialContext {
taskManager?: InitialTaskManagerContext;
}
+export interface InitialProjectContext {
+ /** Prebuilt prompt describing the project the run belongs to. */
+ contextPrompt: string;
+}
+
export interface InitialTaskManagerContext {
/** Prebuilt prompt describing the tasks shown on the page. */
contextPrompt: string;