π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(goal): bind an existing goal to a topic (#20343)
Arvin Xu8951232a86be
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 4de44da9b01..81b989b9268 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -10,6 +10,8 @@ const { mockClient } = vi.hoisted(() => ({mockClient: {goal: {wake: { mutate: vi.fn() },+ bindTopic: { mutate: vi.fn() },+ bindOperationTopic: { mutate: vi.fn() },create: { mutate: vi.fn() },delete: { mutate: vi.fn() },submitPlan: { mutate: vi.fn() },@@ -518,6 +520,44 @@ describe('goal create command', () => {expect(output).not.toContain('/goal/undefined');});+ it.each(['--topic', '--conversation'])(+ 'creates the goal from the current topic run with %s',+ async (flag) => {+ vi.stubEnv('LOBEHUB_JWT', undefined);+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-1');+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc-1');+ vi.stubEnv('LOBEHUB_AGENT_ID', 'agent-1');+ mockClient.goal.create.mutate.mockResolvedValue({ data: { goal: { id: 'goal-1' } } });++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'create',+ 'Topic goal',+ flag,+ '--json',+ ]);++ expect(mockClient.goal.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ conversationOperationId: 'op-1',+ conversationTopicId: 'tpc-1',+ }),+ );+ },+ );++ it('refuses --topic outside an agent topic run', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', undefined);++ await expect(+ createProgram().parseAsync(['node', 'test', 'goal', 'create', 'Topic goal', '--topic']),+ ).rejects.toThrow('--topic must run inside an agent topic');+ expect(mockClient.goal.create.mutate).not.toHaveBeenCalled();+ });+it('sends task seeds and the per-Task attempt budget with the primary flags', async () => {mockClient.goal.create.mutate.mockResolvedValue({data: {@@ -581,6 +621,104 @@ describe('goal create command', () => {});});+describe('goal bind-topic command', () => {+ const operationJwt = `header.${Buffer.from(JSON.stringify({ purpose: 'hetero-operation' })).toString('base64url')}.signature`;+ const bound = (turnToken?: string) => ({+ data: { goal: { id: 'goal-1', subjectId: 'tpc-1', subjectType: 'topic' } },+ message: 'Goal bound to topic tpc-1',+ previousSubject: { id: null, type: 'standalone' },+ reassignedTaskIds: [],+ success: true,+ turnToken,+ });+ const output = () =>+ vi+ .mocked(console.log)+ .mock.calls.map(([value]) => String(value))+ .join('\n');++ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(log, 'info').mockImplementation(() => {});+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-1');+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc-1');+ vi.stubEnv('LOBEHUB_AGENT_ID', 'agent-1');+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ vi.mocked(console.log).mockRestore();+ });++ it('names the run, topic and agent on a desktop run signed in as the user', async () => {+ vi.stubEnv('LOBEHUB_JWT', undefined);+ mockClient.goal.bindTopic.mutate.mockResolvedValue(bound());++ await createProgram().parseAsync(['node', 'test', 'goal', 'bind-topic', 'goal-1']);++ expect(mockClient.goal.bindTopic.mutate).toHaveBeenCalledWith({+ agentId: 'agent-1',+ force: undefined,+ goalOnly: undefined,+ id: 'goal-1',+ operationId: 'op-1',+ topicId: 'tpc-1',+ });+ expect(mockClient.goal.bindOperationTopic.mutate).not.toHaveBeenCalled();+ expect(output()).not.toContain('planning turn');+ });++ it('sends only the operation on a device run, never a client-named topic', async () => {+ vi.stubEnv('LOBEHUB_JWT', operationJwt);+ mockClient.goal.bindOperationTopic.mutate.mockResolvedValue(bound('turn-1'));++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'bind-topic',+ 'goal-1',+ '--force',+ '--goal-only',+ ]);++ expect(mockClient.goal.bindOperationTopic.mutate).toHaveBeenCalledWith({+ force: true,+ goalOnly: true,+ id: 'goal-1',+ operationId: 'op-1',+ });+ expect(mockClient.goal.bindTopic.mutate).not.toHaveBeenCalled();+ expect(output()).toContain('lh goal plan goal-1 --token turn-1 --file <plan.json>');+ expect(output()).toContain('https://app.lobehub.com/goal/goal-1');+ });++ it('prints the turn token and subject in JSON output', async () => {+ vi.stubEnv('LOBEHUB_JWT', undefined);+ mockClient.goal.bindTopic.mutate.mockResolvedValue(bound('turn-1'));++ await createProgram().parseAsync(['node', 'test', 'goal', 'bind-topic', 'goal-1', '--json']);++ const json = JSON.parse(output());+ expect(json).toMatchObject({+ goal: { subjectId: 'tpc-1', subjectType: 'topic' },+ previousSubject: { type: 'standalone' },+ turnToken: 'turn-1',+ url: 'https://app.lobehub.com/goal/goal-1',+ });+ });++ it('refuses to run outside an agent topic', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', undefined);++ await expect(+ createProgram().parseAsync(['node', 'test', 'goal', 'bind-topic', 'goal-1']),+ ).rejects.toThrow(/LOBEHUB_OPERATION_ID/);+ expect(mockClient.goal.bindTopic.mutate).not.toHaveBeenCalled();+ expect(mockClient.goal.bindOperationTopic.mutate).not.toHaveBeenCalled();+ });+});+describe('goal supervision command', () => {it('exposes diagnostic identity and recovery metrics without advancing the Goal', async () => {vi.clearAllMocks();diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 35b9aa97e77..c34e60caa66 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -7,7 +7,7 @@ import type {GoalNodeKind,GoalTickResult,} from '@lobechat/types';-import type { Command } from 'commander';+import { type Command, Option } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';@@ -335,9 +335,11 @@ export function registerGoalCommand(program: Command) {'Reclaim a Task operation after this idle time (minimum: 60000)',).option(- '--conversation',- "Link the goal to the current conversation. Use it whenever you create a goal for the user from a chat, not only for /goal: without it the goal is standalone and never shows on this conversation's goal tray. This agent supervises the goal from this conversation; the output carries a turnToken, so submit the first plan with `lh goal plan <id> --token <turnToken> --file <plan.json>`",+ '--topic',+ "Link the goal to the current topic. Use it whenever you create a goal for the user from a chat, not only for /goal: without it the goal is standalone and never shows on this topic's goal tray. This agent supervises the goal from this topic; the output carries a turnToken, so submit the first plan with `lh goal plan <id> --token <turnToken> --file <plan.json>`",)+ // Former name of --topic, kept so existing prompts and scripts keep working.+ .addOption(new Option('--conversation').hideHelp()).option('--criterion <text...>', 'Acceptance criterion (repeatable)').option('--json [fields]', 'Output JSON').action(async (title: string, options) => {@@ -345,10 +347,9 @@ export function registerGoalCommand(program: Command) {throw new Error('--max-experiments requires --explore');}const operationId = process.env.LOBEHUB_OPERATION_ID;- if (options.conversation && !operationId) {- throw new Error(- '--conversation must run inside an agent conversation (LOBEHUB_OPERATION_ID)',- );+ const fromTopic = Boolean(options.topic || options.conversation);+ if (fromTopic && !operationId) {+ throw new Error('--topic must run inside an agent topic (LOBEHUB_OPERATION_ID)');}const client = await getTrpcClient();const buildUrl = await resolveAppUrlBuilder(client);@@ -400,12 +401,12 @@ export function registerGoalCommand(program: Command) {title,tasks: options.task,};- // A conversation goal takes its agent and conversation from the running+ // A topic goal takes its agent and topic from the running// operation on the server; the CLI only names the run. Device and gateway// runs hold an operation token, which only the operation endpoint accepts.// A local desktop run keeps its operation client-side, so it also names- // its conversation and agent for the server to check.- const result = options.conversation+ // its topic and agent for the server to check.+ const result = fromTopic? hasOperationToken()? await client.goal.createConversationGoal.mutate({...goalInput,@@ -712,6 +713,61 @@ export function registerGoalCommand(program: Command) {log.info(result.message);});+ goal+ .command('bind-topic <id>')+ .description(+ 'Attach an existing goal to the current topic run: this agent supervises it from this topic, as if it had been created here with create --topic',+ )+ .option('--force', 'Move a goal that is already bound to another topic or task')+ .option(+ '--goal-only',+ 'When the goal agent changes, leave existing tasks with their current agent',+ )+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ id: string,+ options: { force?: boolean; goalOnly?: boolean; json?: boolean | string },+ ) => {+ const operationId = process.env.LOBEHUB_OPERATION_ID;+ if (!operationId)+ throw new Error('bind-topic must run inside an agent topic (LOBEHUB_OPERATION_ID)');+ const client = await getTrpcClient();+ const buildUrl = await resolveAppUrlBuilder(client);+ const input = { force: options.force, goalOnly: options.goalOnly, id, operationId };+ // Same split as `create --topic`: the server takes the agent and+ // topic from the run; a local desktop run, whose operation lives+ // only on the client, also names them for the server to check.+ const result = hasOperationToken()+ ? await client.goal.bindOperationTopic.mutate(input)+ : await client.goal.bindTopic.mutate({+ ...input,+ agentId: process.env.LOBEHUB_AGENT_ID,+ topicId: process.env.LOBEHUB_TOPIC_ID,+ });+ const turnToken = result.turnToken;+ const url = buildUrl(`/goal/${encodeURIComponent(result.data!.goal.id)}`);+ if (options.json !== undefined)+ return outputJson(+ {+ ...result.data,+ previousSubject: result.previousSubject,+ reassignedTaskIds: result.reassignedTaskIds,+ turnToken,+ url,+ },+ options.json,+ );+ log.info(result.message);+ console.log(`${pc.bold('goal')}: ${url}`);+ if (turnToken) {+ console.log(+ `${pc.bold('planning turn')}: lh goal plan ${result.data!.goal.id} --token ${turnToken} --file <plan.json>`,+ );+ }+ },+ );+goal.command('restart <id>').description('Start every unfinished task over (cancel stale runs, reset to backlog)')diff --git a/apps/server/src/routers/lambda/__tests__/goal.bindTopic.test.ts b/apps/server/src/routers/lambda/__tests__/goal.bindTopic.test.tsnew file mode 100644index 00000000000..5e510a03528--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/goal.bindTopic.test.ts@@ -0,0 +1,121 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };+});++vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));++const mockBindTopic = vi.fn();+const mockFindById = vi.fn();++vi.mock('@/server/services/goal', () => ({+ GoalService: vi.fn(function () {+ return { bindTopic: mockBindTopic };+ }),+}));++vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(function () {+ return { findById: mockFindById };+ }),+}));++const mockScheduleGoalAdvance = vi.fn();+vi.mock('@/server/services/goal/scheduler', () => ({+ scheduleGoalAdvance: mockScheduleGoalAdvance,+}));++const { goalRouter } = await import('../goal');++describe('goalRouter.bindTopic', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: null };++ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'user-1' });+ mockBindTopic.mockResolvedValue({+ graph: { goal: { id: 'goal_1', subjectId: 'tpc_1', subjectType: 'topic' } },+ previousSubject: { id: 'tpc_0', type: 'topic' },+ reassignedTaskIds: ['task_1'],+ topicId: 'tpc_1',+ turnToken: 'turn_1',+ });+ });++ it('binds from the run, wakes the coordinator and returns the planning token', async () => {+ const result = await goalRouter+ .createCaller(ctx)+ .bindTopic({ force: true, id: 'goal_1', operationId: 'op_1' });++ expect(mockBindTopic).toHaveBeenCalledWith('goal_1', 'op_1', {+ force: true,+ goalOnly: undefined,+ localRun: undefined,+ });+ expect(mockScheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1', userId: 'user-1' }),+ );+ expect(result).toMatchObject({+ message: 'Goal bound to topic tpc_1 (moved from topic tpc_0); 1 task(s) reassigned',+ turnToken: 'turn_1',+ });+ });++ it('passes a local run only when it names both its topic and agent', async () => {+ const caller = goalRouter.createCaller(ctx);++ await caller.bindTopic({ agentId: 'agent_1', id: 'goal_1', operationId: 'op_1' });+ expect(mockBindTopic).toHaveBeenLastCalledWith(+ 'goal_1',+ 'op_1',+ expect.objectContaining({ localRun: undefined }),+ );++ await caller.bindTopic({+ agentId: 'agent_1',+ id: 'goal_1',+ operationId: 'op_1',+ topicId: 'tpc_1',+ });+ expect(mockBindTopic).toHaveBeenLastCalledWith(+ 'goal_1',+ 'op_1',+ expect.objectContaining({ localRun: { agentId: 'agent_1', topicId: 'tpc_1' } }),+ );+ });++ it("refuses a workspace member binding a colleague's goal", async () => {+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'colleague' });++ await expect(+ goalRouter+ .createCaller({ ...ctx, workspaceId: 'ws-1', workspaceRole: 'member' })+ .bindTopic({ id: 'goal_1', operationId: 'op_1' }),+ ).rejects.toThrow(/Only the creator or a workspace owner/);+ expect(mockBindTopic).not.toHaveBeenCalled();+ expect(mockScheduleGoalAdvance).not.toHaveBeenCalled();+ });++ it('reports a missing goal as not found', async () => {+ mockFindById.mockResolvedValue(undefined);++ await expect(+ goalRouter.createCaller(ctx).bindTopic({ id: 'goal_x', operationId: 'op_1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 2ad8cf76e53..13cd85d1184 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -147,6 +147,35 @@ const createGoalInput = conversationGoalInput.extend({createdByAgentId: z.string().optional(),});+const bindTopicInput = idInput.extend({+ /** Move a goal already bound to another topic or task. */+ force: z.boolean().optional(),+ /** Keep unfinished Tasks with their current agent when the goal agent changes. */+ goalOnly: z.boolean().optional(),+ /** The topic run doing the binding; its agent and topic are used. */+ operationId: z.string().min(1),+});++const bindTopicResponse = ({+ graph,+ previousSubject,+ reassignedTaskIds,+ topicId,+ turnToken,+}: Awaited<ReturnType<GoalService['bindTopic']>>) => ({+ data: graph,+ message:+ `Goal bound to topic ${topicId}` ++ (previousSubject.id && previousSubject.id !== topicId+ ? ` (moved from ${previousSubject.type} ${previousSubject.id})`+ : '') ++ (reassignedTaskIds.length ? `; ${reassignedTaskIds.length} task(s) reassigned` : ''),+ previousSubject,+ reassignedTaskIds,+ success: true,+ turnToken,+});+function mapGoalError(error: unknown, operation: string): never {if (error instanceof TRPCError) throw error;console.error(`[goal:${operation}]`, error);@@ -390,6 +419,99 @@ export const goalRouter = router({}}),+ /**+ * Attach an existing goal to the topic of a run authenticated by its+ * operation token (device and gateway runs), as if the goal had been created+ * there with `/goal`. Takes the same `goal:manage` capability as creating one.+ */+ bindOperationTopic: heteroAuthedProcedure+ .use(serverDatabase)+ .input(bindTopicInput)+ .mutation(async ({ ctx, input: { id, operationId, force, goalOnly } }) => {+ if (ctx.heteroAuthKind !== 'operation' || !ctx.heteroOperation) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'An operation-bound token is required',+ });+ }+ let principal;+ try {+ principal = await resolveActiveHeteroOperationPrincipal({+ capability: 'goal:manage',+ claims: ctx.heteroOperation,+ db: ctx.serverDB,+ operationId,+ });+ } catch (error) {+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;+ throw new TRPCError({+ cause: error,+ code:+ error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',+ message: error.message,+ });+ }+ try {+ const goal = await new GoalModel(+ ctx.serverDB,+ principal.userId,+ principal.workspaceId,+ ).findById(id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ // A token carries no workspace role, so only the goal's creator may+ // move it β the strict side of the rule `setAgent` applies.+ assertWorkspaceRowManageable(principal, goal.userId, 'goal');+ const result = await new GoalService(+ ctx.serverDB,+ principal.userId,+ principal.workspaceId,+ ).bindTopic(id, operationId, { force, goalOnly });+ await scheduleGoalAdvance({+ goalId: id,+ trigger: 'manual',+ userId: principal.userId,+ workspaceId: principal.workspaceId,+ });+ return bindTopicResponse(result);+ } catch (error) {+ mapGoalError(error, 'bindTopic');+ }+ }),++ /**+ * Attach an existing goal to the topic run with this id (a desktop+ * run signed in as the user). Agent and topic come from the operation;+ * a local run without a server row also names them, checked like `create`.+ */+ bindTopic: goalWriteProcedure+ .input(+ bindTopicInput.extend({+ agentId: z.string().min(1).optional(),+ topicId: z.string().min(1).optional(),+ }),+ )+ .mutation(async ({ ctx, input: { id, operationId, agentId, topicId, force, goalOnly } }) => {+ try {+ const goal = await ctx.goalModel.findById(id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');+ const result = await ctx.goalService.bindTopic(id, operationId, {+ force,+ goalOnly,+ localRun: agentId && topicId ? { agentId, topicId } : undefined,+ });+ await scheduleGoalAdvance({+ goalId: id,+ trigger: 'manual',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ return bindTopicResponse(result);+ } catch (error) {+ mapGoalError(error, 'bindTopic');+ }+ }),+create: goalWriteProcedure.input(createGoalInput.extend({diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.tsindex 096abd3ce2f..a91633d570c 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts@@ -6,7 +6,8 @@ import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';* What a heterogeneous run's operation token may do.** `goal:manage` lets the CLI create a goal the agent supervises from this- * conversation (`lh goal create --conversation`). The token is exposed to the+ * conversation (`lh goal create --conversation`), or bind an existing one to it+ * (`lh goal bind-topic`, which the `/goal` instructions route a named goal to). The token is exposed to the* always-installed CLI, so it is granted only when the user asked for a goal* with `/goal`: an ordinary coding run that meets instructions telling it to* run that command must not be able to launch persistent follow-on work.diff --git a/apps/server/src/services/goal/bindTopic.test.ts b/apps/server/src/services/goal/bindTopic.test.tsnew file mode 100644index 00000000000..6f7a4b911ed--- /dev/null+++ b/apps/server/src/services/goal/bindTopic.test.ts@@ -0,0 +1,468 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import {+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodes,+ goals,+ messages,+ tasks,+ taskTopics,+ topics,+ users,+} from '@/database/schemas';+import { goalRouter } from '@/server/routers/lambda/goal';+import { AiAgentService } from '@/server/services/aiAgent';++import { GoalService } from './index';+import { GoalManagerService } from './manager';+import * as scheduler from './scheduler';++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => db }));+vi.mock('@/libs/oidc-provider/access-control', () => ({ assertOIDCUserActive: async () => {} }));+vi.mock('@/database/models/rbac', () => ({+ RbacModel: class {+ hasAnyPermission = async () => true;+ },+}));++const db = await getTestDB();+const userId = 'goal-bind-test-user';+const agentId = 'goal-bind-topic-agent';+const otherAgentId = 'goal-bind-other-agent';+const boundTopicId = 'tpc_goal_bind_topic';+const runOpId = 'op_goal_bind_topic';+let seq = 0;++const service = () => new GoalService(db, userId);+const model = () => new GoalModel(db, userId);+const ops = () => new AgentOperationModel(db, userId);++beforeEach(async () => {+ await db.insert(users).values({ id: userId }).onConflictDoNothing();+ await db.insert(agents).values([+ { id: agentId, userId },+ { id: otherAgentId, userId },+ ]);+ await db.insert(topics).values({ agentId, id: boundTopicId, userId });+ await ops().recordStart({+ agentId,+ appContext: { sourceMessageId: 'msg_user_bind_request' },+ operationId: runOpId,+ topicId: boundTopicId,+ });+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ const operationId = `op-bind-manager-${++seq}`;+ const topicId = params.appContext!.topicId!;+ await ops().recordStart({+ agentId: params.agentId,+ appContext: { sourceMessageId: params.clientIds?.userMessageId },+ operationId,+ topicId,+ });+ return {+ agentId: params.agentId!,+ assistantMessageId: 'm',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId,+ status: 'running',+ success: true,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: 'u',+ };+ });+});++afterEach(async () => {+ vi.restoreAllMocks();+ for (const table of [+ goalEdges,+ goalEvents,+ goalNodes,+ goals,+ agentOperations,+ messages,+ taskTopics,+ topics,+ tasks,+ agents,+ users,+ ])+ await db.delete(table);+});++/** A goal created with plain `lh goal create`, two tasks in, one of them mid-run. */+async function standaloneGoalMidRun(goalAgentId = agentId) {+ const graph = await service().create({+ agentId: goalAgentId,+ maxRounds: 20,+ maxTotalCost: 15,+ tasks: ['Collect data', 'Write report'],+ title: 'Standalone goal',+ });+ const taskNode = graph.nodes.find((node) => node.kind === 'task')!;+ const task = await new TaskModel(db, userId).create({+ assigneeAgentId: goalAgentId,+ instruction: 'Collect data',+ status: 'running',+ });+ await db.update(goalNodes).set({ taskId: task.id }).where(eq(goalNodes.id, taskNode.id));+ await db.update(goals).set({ status: 'running' }).where(eq(goals.id, graph.goal.id));+ return { graph: await service().graph(graph.goal.id), id: graph.goal.id, taskId: task.id };+}++const graphShape = async (id: string) => {+ const graph = await service().graph(id);+ return {+ edges: graph.edges.map(({ id: edgeId, kind, sourceNodeId, targetNodeId }) => ({+ edgeId,+ kind,+ sourceNodeId,+ targetNodeId,+ })),+ nodes: graph.nodes.map(({ id: nodeId, status, taskId, title }) => ({+ nodeId,+ status,+ taskId,+ title,+ })),+ };+};++function operationCaller(operationId: string, capabilities: string[]) {+ return goalRouter.createCaller({+ oidcAuth: {+ aud: 'urn:lobehub:hetero-operation',+ capabilities,+ exp: Math.floor(Date.now() / 1000) + 3600,+ iat: Math.floor(Date.now() / 1000),+ iss: 'urn:lobehub:internal',+ jti: 'bind-test',+ operation_id: operationId,+ payload: {},+ purpose: 'hetero-operation',+ sub: userId,+ },+ });+}++describe('GoalService.bindTopic', () => {+ it('gives a standalone goal the subject and supervision a topic-created goal has, without touching its work', async () => {+ const { id, taskId } = await standaloneGoalMidRun();+ const before = await graphShape(id);++ const result = await service().bindTopic(id, runOpId);++ expect(result.turnToken).toBeUndefined();+ expect(result.previousSubject).toEqual({ id: null, type: 'standalone' });+ const goal = (await model().findById(id))!;+ expect(goal).toMatchObject({+ agentId,+ maxRounds: 20,+ maxTotalCost: 15,+ status: 'running',+ subjectId: boundTopicId,+ subjectType: 'topic',+ });+ // Same policy default as `createFromConversation`.+ expect(goal.config?.manager).toEqual({});+ // No turn in flight, nothing spent: the next turn is dispatched here.+ expect(goal.config?.managerState).toMatchObject({+ consumed: true,+ topicId: boundTopicId,+ turns: 0,+ });+ expect(await graphShape(id)).toEqual(before);+ expect((await new TaskModel(db, userId).findById(taskId))!).toMatchObject({+ assigneeAgentId: agentId,+ status: 'running',+ });+ // The topic finds the goal the way it finds one created there.+ expect(+ (await model().list({ topicId: boundTopicId })).goals.map((item) => item.goal.id),+ ).toEqual([id]);+ const [event] = await db+ .select()+ .from(goalEvents)+ .where(and(eq(goalEvents.goalId, id), eq(goalEvents.entityType, 'goal')));+ expect(event).toMatchObject({+ actorId: agentId,+ actorType: 'agent',+ eventType: 'updated',+ operationId: runOpId,+ });+ expect(event.reason).toContain(boundTopicId);+ });++ it('dispatches the next planning turn into the bound topic', async () => {+ const { id } = await standaloneGoalMidRun();+ await service().bindTopic(id, runOpId);++ // The work in flight settles; with the graph quiet the main Agent plans.+ await db.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.goalId, id));+ expect((await service().tick(id)).outcome).toBe('waiting_external');++ const call = vi.mocked(AiAgentService.prototype.execAgent).mock.calls.at(-1)![0];+ expect(call).toMatchObject({ agentId, appContext: { topicId: boundTopicId } });+ expect((await model().findById(id))!.config!.managerState).toMatchObject({+ topicId: boundTopicId,+ turns: 1,+ });+ });++ it('adopts the binding run as a planning turn when the goal has nothing in flight', async () => {+ const created = await service().create({ agentId, title: 'Unplanned goal' });++ const { turnToken } = await service().bindTopic(created.goal.id, runOpId);++ expect(turnToken).toBeTruthy();+ const goal = (await model().findById(created.goal.id))!;+ expect(goal.status).toBe('running');+ expect(goal.config?.managerState).toMatchObject({+ adopted: true,+ adoptedOperationId: runOpId,+ token: turnToken,+ topicId: boundTopicId,+ turns: 1,+ });+ expect(+ await new GoalManagerService(db, userId).submit(created.goal.id, turnToken!, runOpId, {+ action: 'tasks',+ reason: 'Start',+ tasks: [{ description: 'Do the work', title: 'Work' }],+ }),+ ).toEqual({ action: 'tasks', recorded: true });+ });++ it('refuses a goal bound to another topic unless forced, and records the move', async () => {+ const { id } = await standaloneGoalMidRun();+ await db.insert(topics).values({ agentId, id: 'tpc_previous_topic', userId });+ await db+ .update(goals)+ .set({+ config: {+ manager: {},+ managerState: {+ consumed: true,+ snapshot: 's',+ startedAt: new Date().toISOString(),+ token: 't',+ topicId: 'tpc_previous_topic',+ turns: 2,+ },+ },+ subjectId: 'tpc_previous_topic',+ subjectType: 'topic',+ })+ .where(eq(goals.id, id));++ await expect(service().bindTopic(id, runOpId)).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ expect((await model().findById(id))!.subjectId).toBe('tpc_previous_topic');++ const result = await service().bindTopic(id, runOpId, { force: true });++ expect(result.previousSubject).toEqual({ id: 'tpc_previous_topic', type: 'topic' });+ const goal = (await model().findById(id))!;+ expect(goal.subjectId).toBe(boundTopicId);+ expect(goal.config?.managerState).toMatchObject({+ previousTopicIds: ['tpc_previous_topic'],+ topicId: boundTopicId,+ turns: 2,+ });+ const [event] = await db+ .select()+ .from(goalEvents)+ .where(and(eq(goalEvents.goalId, id), eq(goalEvents.entityType, 'goal')));+ expect(event.reason).toContain('moved from topic tpc_previous_topic');+ });++ it('is a no-op re-bind to the topic it is already bound to', async () => {+ const { id } = await standaloneGoalMidRun();+ await service().bindTopic(id, runOpId);++ await expect(service().bindTopic(id, runOpId)).resolves.toMatchObject({+ previousSubject: { id: boundTopicId, type: 'topic' },+ });+ });++ it('refuses while a planning turn is in flight in another topic', async () => {+ const { id } = await standaloneGoalMidRun();+ await db+ .update(goals)+ .set({+ config: {+ manager: {},+ managerState: {+ snapshot: 's',+ startedAt: new Date().toISOString(),+ token: 't',+ topicId: 'tpc_management',+ turns: 1,+ },+ },+ })+ .where(eq(goals.id, id));++ await expect(service().bindTopic(id, runOpId)).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ expect((await model().findById(id))!.subjectType).toBe('standalone');+ });++ it.each(['achieved', 'failed', 'canceled'] as const)('refuses a %s goal', async (status) => {+ const { id } = await standaloneGoalMidRun();+ await db.update(goals).set({ status }).where(eq(goals.id, id));++ await expect(service().bindTopic(id, runOpId)).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ expect((await model().findById(id))!).toMatchObject({ status, subjectType: 'standalone' });+ });++ it('refuses a run whose topic belongs to another agent', async () => {+ const { id } = await standaloneGoalMidRun();+ await db.insert(topics).values({ agentId: otherAgentId, id: 'tpc_other_agent', userId });+ await ops().recordStart({+ agentId,+ operationId: 'op_mismatched_topic',+ topicId: 'tpc_other_agent',+ });++ await expect(service().bindTopic(id, 'op_mismatched_topic')).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it("refuses a local run naming another agent's or another user's topic", async () => {+ const { id } = await standaloneGoalMidRun();+ await db.insert(topics).values({ agentId: otherAgentId, id: 'tpc_other_agent', userId });+ await db.insert(users).values({ id: 'goal-bind-stranger' });+ await db.insert(agents).values({ id: 'stranger-agent', userId: 'goal-bind-stranger' });+ await db+ .insert(topics)+ .values({ agentId: 'stranger-agent', id: 'tpc_stranger', userId: 'goal-bind-stranger' });++ for (const localRun of [+ { agentId, topicId: 'tpc_other_agent' },+ { agentId: 'stranger-agent', topicId: 'tpc_stranger' },+ ])+ await expect(service().bindTopic(id, 'op_client_only', { localRun })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect((await model().findById(id))!.subjectType).toBe('standalone');+ });++ it('binds a local desktop run that has no server operation row', async () => {+ const { id } = await standaloneGoalMidRun();++ await service().bindTopic(id, 'op_client_only', {+ localRun: { agentId, topicId: boundTopicId },+ });++ expect((await model().findById(id))!).toMatchObject({+ subjectId: boundTopicId,+ subjectType: 'topic',+ });+ });++ it('refuses a run that has already ended', async () => {+ const { id } = await standaloneGoalMidRun();+ await ops().recordCompletion(runOpId, { status: 'done' });++ await expect(service().bindTopic(id, runOpId)).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ });++ it('hands supervision to the topic agent and moves unfinished tasks like setAgent', async () => {+ const { id, taskId } = await standaloneGoalMidRun(otherAgentId);++ const result = await service().bindTopic(id, runOpId);++ expect(result.reassignedTaskIds).toEqual([taskId]);+ expect((await model().findById(id))!.agentId).toBe(agentId);+ expect((await new TaskModel(db, userId).findById(taskId))!.assigneeAgentId).toBe(agentId);+ });++ it('leaves nothing half-bound when moving a task fails, so a retry still moves it', async () => {+ const { id, taskId } = await standaloneGoalMidRun(otherAgentId);+ const update = vi+ .spyOn(TaskModel.prototype, 'update')+ .mockRejectedValueOnce(new Error('connection lost'));++ await expect(service().bindTopic(id, runOpId)).rejects.toThrow('connection lost');+ const untouched = (await model().findById(id))!;+ expect(untouched.agentId).toBe(otherAgentId);+ expect(untouched.subjectId).toBeNull();++ update.mockRestore();+ const result = await service().bindTopic(id, runOpId);++ expect(result.reassignedTaskIds).toEqual([taskId]);+ expect((await model().findById(id))!.agentId).toBe(agentId);+ expect((await new TaskModel(db, userId).findById(taskId))!.assigneeAgentId).toBe(agentId);+ });++ it('keeps unfinished tasks with their agent when goalOnly is set', async () => {+ const { id, taskId } = await standaloneGoalMidRun(otherAgentId);++ const result = await service().bindTopic(id, runOpId, { goalOnly: true });++ expect(result.reassignedTaskIds).toEqual([]);+ expect((await model().findById(id))!.agentId).toBe(agentId);+ expect((await new TaskModel(db, userId).findById(taskId))!.assigneeAgentId).toBe(otherAgentId);+ });+});++describe('goal.bindOperationTopic', () => {+ it('binds only with the goal capability an operation token gets from /goal', async () => {+ const { id } = await standaloneGoalMidRun();++ await expect(+ operationCaller(runOpId, ['hetero:ingest']).bindOperationTopic({+ id,+ operationId: runOpId,+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect((await model().findById(id))!.subjectType).toBe('standalone');++ const result = await operationCaller(runOpId, [+ 'hetero:ingest',+ 'goal:manage',+ ]).bindOperationTopic({ id, operationId: runOpId });++ expect(result?.data.goal).toMatchObject({+ subjectId: boundTopicId,+ subjectType: 'topic',+ });+ expect(scheduler.scheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: id, userId }),+ );+ });++ it("cannot reach another user's goal", async () => {+ await db.insert(users).values({ id: 'goal-bind-stranger' });+ const foreign = await new GoalService(db, 'goal-bind-stranger').create({ title: 'Not yours' });++ await expect(+ operationCaller(runOpId, ['hetero:ingest', 'goal:manage']).bindOperationTopic({+ id: foreign.goal.id,+ operationId: runOpId,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex f77d5df1220..bddcdb2c24b 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -262,37 +262,11 @@ export class GoalService {*/localRun?: { agentId: string; topicId: string },): Promise<{ graph: GoalGraphSnapshot; turnToken: string }> => {- const operation = await new AgentOperationModel(- this.db,- this.userId,- this.workspaceId,- ).findOwnOperationById(operationId);- let agentId: string;- let topicId: string;- if (operation) {- if (operation.status !== 'running')- throw new TRPCError({- code: 'CONFLICT',- message: 'The conversation run has already ended',- });- if (!operation.agentId || !operation.topicId)- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Only a conversation run with an agent can create a goal it supervises',- });- agentId = operation.agentId;- topicId = operation.topicId;- } else {- const topic = localRun- ? await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(- localRun.topicId,- )- : undefined;- if (!localRun || !topic || topic.agentId !== localRun.agentId)- throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation run not found' });- agentId = localRun.agentId;- topicId = topic.id;- }+ const { agentId, topicId } = await this.resolveTopicRun(+ operationId,+ localRun,+ 'Only a run in a topic with an agent can create a goal it supervises',+ );const created = await this.create({...input,@@ -316,6 +290,107 @@ export class GoalService {}};+ /**+ * The agent and topic of the run with this id, taken from the server's+ * operation row; never from the caller while that row exists. A local desktop+ * run has no row, so its env-provided topic and agent are accepted only when+ * the topic is the caller's and belongs to that agent.+ */+ private resolveTopicRun = async (+ operationId: string,+ localRun: { agentId: string; topicId: string } | undefined,+ noAgentMessage: string,+ ): Promise<{ agentId: string; topicId: string }> => {+ const operation = await new AgentOperationModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findOwnOperationById(operationId);+ if (operation) {+ if (operation.status !== 'running')+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The conversation run has already ended',+ });+ if (!operation.agentId || !operation.topicId)+ throw new TRPCError({ code: 'BAD_REQUEST', message: noAgentMessage });+ return { agentId: operation.agentId, topicId: operation.topicId };+ }+ const topic = localRun+ ? await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(+ localRun.topicId,+ )+ : undefined;+ if (!localRun || !topic || topic.agentId !== localRun.agentId)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });+ return { agentId: localRun.agentId, topicId: topic.id };+ };++ /**+ * Attach an existing goal to the topic of the run with this id, so it+ * is supervised from there exactly as if it had been created there with+ * `/goal`: the topic's agent becomes the goal agent, the topic+ * becomes its `topic` subject and management topic. Graph, Tasks,+ * budgets and status are kept. A change of goal agent moves unfinished Tasks+ * the way `setAgent` does (unless `goalOnly`, or the goal has a dedicated+ * executor). Returns a `turnToken` when the binding run was adopted as a+ * planning turn.+ */+ bindTopic = async (+ goalId: string,+ operationId: string,+ options?: {+ force?: boolean;+ goalOnly?: boolean;+ /** A local desktop run's topic; see `resolveTopicRun`. */+ localRun?: { agentId: string; topicId: string };+ },+ ) => {+ const { agentId, topicId } = await this.resolveTopicRun(+ operationId,+ options?.localRun,+ 'Only a run in a topic with an agent can supervise a goal',+ );+ // A run row names its topic, but the topic must still be the caller's and+ // the run's agent's: the binding makes that agent plan into it.+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(+ topicId,+ );+ if (!topic || topic.agentId !== agentId)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ await assertAgentUsableBy(this.db, agentId, {+ userId: this.userId,+ workspaceId: this.workspaceId,+ });++ // One transaction: the agent change and the Task moves it implies commit+ // together. Committed apart, a failed move left the goal already on the new+ // agent, and the retry β seeing no agent change β never moved the Tasks.+ const { bound, reassignedTaskIds } = await this.db.transaction(async (tx) => {+ const bound = await new GoalManagerService(tx, this.userId, this.workspaceId).bindTopic(+ goalId,+ { agentId, operationId, topicId },+ { force: options?.force },+ );+ const reassignedTaskIds =+ bound.previousAgentId === agentId+ ? []+ : await new GoalService(tx, this.userId, this.workspaceId).followGoalAgent(+ bound.goal,+ agentId,+ options?.goalOnly,+ );+ return { bound, reassignedTaskIds };+ });+ return {+ graph: await this.requireGraph(goalId),+ previousSubject: bound.previousSubject,+ reassignedTaskIds,+ topicId,+ turnToken: bound.turnToken,+ };+ };+create = async (input: CreateGoalGraphInput): Promise<GoalGraphSnapshot> => {if (input.agentId ?? input.createdByAgentId) {await assertAgentUsableBy(this.db, (input.agentId ?? input.createdByAgentId)!, {@@ -1211,16 +1286,24 @@ export class GoalService {this.workspaceId,).moveConversationTo(goalId, agentId);- const reassignedTaskIds =- options?.goalOnly || goal.config?.taskAgentId- ? []- : await this.reassignUnfinishedTasks(goalId, agentId);+ const reassignedTaskIds = await this.followGoalAgent(goal, agentId, options?.goalOnly);return {goal: migrated ? ((await this.goalModel.findById(goalId)) ?? goal) : goal,reassignedTaskIds,};};+ /**+ * After the goal agent changed: when that agent also does the goal's Tasks,+ * unfinished ones follow it unless the caller keeps them (`goalOnly`). A goal+ * with a dedicated executor keeps its Tasks there.+ */+ private followGoalAgent = async (+ goal: Pick<GoalItem, 'config' | 'id'>,+ agentId: string,+ goalOnly?: boolean,+ ) => (goalOnly || goal.config?.taskAgentId ? [] : this.reassignUnfinishedTasks(goal.id, agentId));+/*** Route the goal's Tasks to a dedicated executor, or back to the goal agent* with `null`. The goal agent keeps supervising either way. Unfinished Tasksdiff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.mdindex f291698952b..ae4229e667b 100644--- a/apps/server/src/services/goal/manager.README.md+++ b/apps/server/src/services/goal/manager.README.md@@ -11,6 +11,22 @@ creates to a dedicated executor; without it the goal agent does its own Tasks.`lh goal set-agent` hands supervision to another agent; `lh goal set-task-agent`changes the executor. Neither replaces the other.+`lh goal bind-topic <goal-id> [--force] [--goal-only]`, run inside an agent+topic, attaches an existing goal to that topic and leaves it where+`lh goal create --topic` would have: the topic's agent is the goal+agent (unfinished Tasks follow as with `set-agent`), the topic is the+goal's `topic` subject, `config.manager` exists (an existing policy is kept), and+`managerState.topicId` is the topic, so later planning turns are+dispatched there. Graph, Tasks, budgets and status are untouched. The binding run+is adopted as a planning turn (and prints its `--token`) only when nothing is in+flight β no unsettled turn and no unfinished Task β because an adopted turn holds+task coordination until it settles. A goal bound to another topic or task+needs `--force`; the previous topic joins `previousTopicIds`, and the move is+recorded as a goal event. Finished goals and goals with a planning turn in flight+elsewhere are refused. Like `create --topic`, the topic comes from+the run's operation; an operation-token run (device or gateway) needs the+`goal:manage` capability that `/goal` grants.+The main Agent must have a working shell and an authenticated `lh` CLI in itsexecution environment (for example a configured device Kimi/Codex Agent). Itsnormal Agent configuration selects the runtime; dispatch uses the samediff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 1903be5b5f3..e92056c0f33 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -4,6 +4,7 @@ import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';import { buildGoalManagerPrompt } from '@lobechat/prompts';import type {GoalGraphSnapshot,+ GoalItem,GoalManagerState,GoalTickResult,TaskItem,@@ -25,6 +26,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';+import { TERMINAL_GOAL_STATUSES as finishedGoalStatuses } from './goalTraceRecorder';import { countDeviceOfflineRuns, DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';import { scheduleGoalAdvance } from './scheduler';import { recoveryEligibility } from './supervisor/policy';@@ -295,6 +297,160 @@ export class GoalManagerService {return next;});+ /**+ * Attach an existing goal to a topic so it ends up in the state+ * `/goal` in that topic would have left it: the topic's agent is+ * the goal agent, the topic is the goal's `topic` subject, the goal+ * has a main Agent policy, and its management topic+ * (`managerState.topicId`) is this topic, so later planning turns land+ * there.+ *+ * The graph, Tasks, budgets and status are left alone. The binding run is+ * adopted as a planning turn only when the goal is where a freshly created+ * topic goal would be β no turn in flight and no unfinished Task to+ * preempt β because an adopted turn holds task coordination until it settles.+ * Otherwise the next turn the coordinator starts is dispatched here.+ *+ * Refused while a planning turn is in flight elsewhere: `settleInFlight`+ * finds that turn's run through `state.topicId`, so moving it would strand+ * the turn and pause the goal.+ */+ bindTopic = async (+ goalId: string,+ run: { agentId: string; operationId: string; topicId: string },+ options?: { force?: boolean },+ ): Promise<{+ goal: GoalItem;+ previousAgentId: string | null;+ previousSubject: { id: string | null; type: GoalItem['subjectType'] };+ turnToken?: string;+ }> =>+ this.db.transaction(async (db) => {+ const model = new GoalModel(db, this.userId, this.workspaceId);+ const goal = await model.lockById(goalId);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ if (finishedGoalStatuses.has(goal.status))+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Goal is ${goal.status}; a finished goal cannot be bound to a topic`,+ });++ const previousSubject = { id: goal.subjectId, type: goal.subjectType };+ const alreadyBound = goal.subjectType === 'topic' && goal.subjectId === run.topicId;+ if (!alreadyBound && goal.subjectId && !options?.force)+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Goal is already bound to ${goal.subjectType} ${goal.subjectId}; pass force to move it to this topic`,+ });++ const state = goal.config?.managerState;+ if (+ state &&+ !state.consumed &&+ (state.topicId !== run.topicId || goal.agentId !== run.agentId)+ )+ throw new TRPCError({+ code: 'CONFLICT',+ message: `A planning turn of this goal is in flight in ${state.topicId}; wait for it to settle (or confirm its exit with lh goal resume ${goalId} --confirm-exit) before binding`,+ });++ // Same default as `createFromConversation`: a topic goal always+ // has a main Agent; an existing policy (turn cap, instruction) is kept.+ await db+ .update(goals)+ .set({+ agentId: run.agentId,+ config: sql`COALESCE(${goals.config}, '{}'::jsonb) || jsonb_build_object('manager', COALESCE(${goals.config}->'manager', '{}'::jsonb))`,+ subjectId: run.topicId,+ subjectType: 'topic',+ updatedAt: new Date(),+ })+ .where(eq(goals.id, goalId));++ let turnToken: string | undefined;+ // An in-flight turn reaching here is already this topic's.+ if (!state || state.consumed) {+ const graph = await this.graph(db).getGraph(goalId);+ if (!graph) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const previousTopicIds = [+ ...new Set([+ ...(state?.previousTopicIds ?? []),+ ...(state?.topicId && state.topicId !== run.topicId ? [state.topicId] : []),+ ]),+ ];+ const maxTurns = graph.goal.config?.manager?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS;+ const quiet =+ activeStatuses.has(goal.status) &&+ !state?.readyForAcceptance &&+ (state?.turns ?? 0) < maxTurns &&+ !graph.decisions.some((d) => d.status === 'pending') &&+ !graph.nodes.some((n) => n.kind === 'task' && !terminalNodes.has(n.status)) &&+ !(await this.budgetBlocked(graph, db));+ let next: GoalManagerState;+ if (quiet) {+ // What `adoptConversationTurn` records for a goal created here.+ next = {+ adopted: true,+ adoptedOperationId: run.operationId,+ operationId: run.operationId,+ ...(previousTopicIds.length > 0 && { previousTopicIds }),+ reviewSnapshot: (await this.reviews(graph, db)).hash,+ snapshot: managerSnapshot(graph),+ startedAt: new Date().toISOString(),+ token: randomUUID(),+ topicId: run.topicId,+ turns: (state?.turns ?? 0) + 1,+ };+ turnToken = next.token;+ } else {+ // No turn now: re-point the settled receipt (or record a settled+ // one with no turn spent) so the next turn the coordinator starts is+ // dispatched into this topic instead of a new topic.+ next = state+ ? {+ ...state,+ ...(previousTopicIds.length > 0 && { previousTopicIds }),+ topicId: run.topicId,+ }+ : {+ consumed: true,+ snapshot: managerSnapshot(graph),+ startedAt: new Date().toISOString(),+ token: managerTurnToken(goalId),+ topicId: run.topicId,+ turns: 0,+ };+ }+ await this.save(db, goalId, next);+ if (quiet && goal.status === 'planning') await model.updateStatus(goalId, 'running');+ }++ if (!alreadyBound || goal.agentId !== run.agentId) {+ const moved =+ previousSubject.id && !alreadyBound+ ? ` (moved from ${previousSubject.type} ${previousSubject.id})`+ : '';+ const agentChange =+ goal.agentId !== run.agentId+ ? `; goal agent ${goal.agentId ?? 'none'} β ${run.agentId}`+ : '';+ await new GoalGraphModel(db, this.userId, this.workspaceId, {+ id: run.agentId,+ type: 'agent',+ }).recordGoalUpdate(goalId, {+ operationId: run.operationId,+ reason: `bound to topic ${run.topicId}${moved}${agentChange}`,+ });+ }++ return {+ goal: (await model.findById(goalId))!,+ previousAgentId: goal.agentId,+ previousSubject,+ turnToken,+ };+ });+private save = async (db: LobeChatDatabase, id: string, state: GoalManagerState) => {// Caller holds the owned Goal row lock. Do not overwrite concurrent policy namespaces.await dbdiff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.tsindex e32fc01ae20..5c79bf72eb9 100644--- a/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts@@ -38,6 +38,14 @@ describe('withConversationGoalPrompt', () => {expect(conversationGoalPrompt).toContain('lh goal plan <goalId> --token <turnToken>');});+ it('binds a goal the user names instead of creating a duplicate', () => {+ // `goal:manage` reaches a device or gateway run only through `/goal`, so+ // these instructions are the only way such a run can bind an existing goal.+ expect(conversationGoalPrompt).toContain('lh goal bind-topic <goalId> --json');+ expect(conversationGoalPrompt).toContain('do not create a new goal');+ expect(conversationGoalPrompt).toContain('only allow creating or binding this goal');+ });+it('plans from the create output instead of reading the goal back', () => {// A device run holds an operation token, which the goal read endpoint// refuses; telling the agent to run `lh goal show` made its first commanddiff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.tsindex f3a4a52f83b..08730db4534 100644--- a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts@@ -7,7 +7,10 @@ import { isGoalPrompt } from './goalPrompt';* Those agents never receive the builtin goal tool: they run the `lh` CLI in* their own shell. So `/goal` is delivered as instructions rather than a tool β* create the goal bound to this conversation, then plan it in the same run,- * which the server adopts as the goal's first planning turn.+ * which the server adopts as the goal's first planning turn. A `/goal` that+ * names an existing goal binds it here (`lh goal bind-topic`) instead: the+ * `goal:manage` capability a device or gateway run needs for that is granted+ * only to `/goal` runs, so this is the bind's only entry for them.*/export const conversationGoalPrompt = `The user sent this request with LobeHub's /goal command (the prefix was removed before it reached you; it is not your own /goal command). They are asking you to turn the request into a long-running LobeHub Goal that you supervise from this conversation, not to do the work yourself in this run.@@ -15,12 +18,16 @@ export const conversationGoalPrompt = `The user sent this request with LobeHub's2. Create it bound to this conversation (the LOBEHUB_* environment already identifies you and this conversation):lh goal create "<title>" --conversation -r "<requirement>" -i "<the user's ask in their words>" --criterion "<criterion>" --criterion "<criterion>" --jsonThe output contains goal.id and turnToken. You are now the goal's supervising agent, and this run is its first planning turn.-3. Plan it now from the goal graph already printed by lh goal create (do not run lh goal show or other lh goal commands: this run's credentials only allow creating this goal and submitting its plan). Write a JSON plan file and submit it once:+3. Plan it now from the goal graph already printed by lh goal create (do not run lh goal show or other lh goal commands: this run's credentials only allow creating or binding this goal and submitting its plan). Write a JSON plan file and submit it once:lh goal plan <goalId> --token <turnToken> --file <path> --jsonPlan schema: {"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}]}Plan bounded, independent tasks; the goal's coordinator dispatches and runs them under the goal budget.4. Then end the run with one or two sentences in the user's language: the goal is running, and what the first tasks are.+If the request instead asks to attach an existing goal to this conversation (it names a goal id like goal_xxx, or a /goal/goal_xxx link, to continue, bind or supervise here), do not create a new goal. Bind that one:+ lh goal bind-topic <goalId> --json+Add --force only when the user explicitly asks to move a goal that is already bound to another conversation; otherwise report the refusal and stop. If the output contains a turnToken, this run is a planning turn: plan from the goal graph it printed and submit with lh goal plan as in step 3, then end as in step 4. Without a turnToken, tasks are already in flight: do not plan, and end with one or two sentences saying the goal is now supervised from this conversation.+Do not execute, preview or self-check the tasks, mark them complete, change budgets, or claim the goal is achieved. Later planning turns continue in this conversation once tasks deliver.`;/**diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex b45b3458ae8..84b39b33161 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -291,6 +291,27 @@ export class GoalGraphModel {});};+ /**+ * Record a change to the goal row itself that is not a status move, such as+ * binding it to a topic, so the goal's timeline says when and by whom+ * its carrier changed.+ */+ recordGoalUpdate = async (+ goalId: string,+ input: { operationId?: string; reason: string },+ ): Promise<void> => {+ await this.db.insert(goalEvents).values({+ actorId: this.actor?.id ?? this.userId,+ actorType: this.actor?.type ?? 'user',+ entityId: goalId,+ entityType: 'goal',+ eventType: 'updated',+ goalId,+ operationId: input.operationId,+ reason: input.reason,+ });+ };+attachWorkVersion = async (goalId: string,nodeId: string,