🤯 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(agent-share): open Claude Code / Codex to allowlisted contacts (#23342)
YuTengjing3d68b210d29e
diff --git a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts b/apps/server/src/routers/lambda/__tests__/agentShare.test.tsindex 6cdf4b5d835..a66cebe3a94 100644--- a/apps/server/src/routers/lambda/__tests__/agentShare.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentShare.test.ts@@ -5,9 +5,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { createContextInner } from '@/libs/trpc/lambda/context';+/** Rows the router's Agent-owner lookup (`select … from agents`) returns. */+const mockAgentOwnerRows = vi.fn(async () => [{ userId: 'user-1' }]);vi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(function () {- return {};+ return {+ select: () => ({ from: () => ({ where: () => ({ limit: () => mockAgentOwnerRows() }) }) }),+ };}),}));@@ -106,6 +110,19 @@ vi.mock('@/business/server/agent-share/spendGate', () => ({getAgentShareMonthlySpend: (...args: unknown[]) => mockGetAgentShareMonthlySpend(...args),}));+const mockFilterAddressBookPeople = vi.fn();+const mockListAddressBookPeople = vi.fn();+const mockFindUser = vi.fn();+vi.mock('@/database/models/contact', () => ({+ ContactModel: vi.fn(function () {+ return {+ filterAddressBookPeople: mockFilterAddressBookPeople,+ findUser: mockFindUser,+ listAddressBookPeople: mockListAddressBookPeople,+ };+ }),+}));+const mockGetFeatureFlagsState = vi.fn();vi.mock('@/server/featureFlags', () => ({getServerFeatureFlagsStateFromRuntimeConfig: (...args: unknown[]) =>@@ -341,6 +358,89 @@ describe('agentShareRouter', () => {expect(mockUpdateConfig).not.toHaveBeenCalled();});+ describe('execution environment grant', () => {+ const bob = { avatar: null, fullName: 'Bob', id: 'user-bob', username: 'bob' };++ beforeEach(() => {+ mockAgentOwnerRows.mockResolvedValue([{ userId: 'user-1' }]);+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true, enableChannels: true });+ });++ it('grants only people in the address book', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ mockFilterAddressBookPeople.mockResolvedValue(['user-bob']);++ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { deviceAccess: 'allowlist', deviceAllowUserIds: ['user-bob', 'stranger'] },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();++ const config = { deviceAccess: 'allowlist' as const, deviceAllowUserIds: ['user-bob'] };+ await caller.updateShareConfig({ agentId: 'agent-1', config });+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', config);+ });++ // The runtime grants nothing while contacts are off, so a grant must not be+ // stored then either (it would also come alive when they turn on).+ it('refuses a grant while contacts are off for the Agent owner', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true, enableChannels: false });+ mockFilterAddressBookPeople.mockResolvedValue(['user-bob']);++ await expect(+ caller.updateShareConfig({+ agentId: 'agent-1',+ config: { deviceAccess: 'allowlist', deviceAllowUserIds: ['user-bob'] },+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ caller.updateShareConfig({ agentId: 'agent-1', config: { deviceAccess: 'allowlist' } }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockUpdateConfig).not.toHaveBeenCalled();++ await expect(caller.listDeviceGrantablePeople({ agentId: 'agent-1' })).resolves.toMatchObject(+ { enabled: false, people: [] },+ );+ expect(mockListAddressBookPeople).not.toHaveBeenCalled();+ });++ // A workspace manager other than the owner must see and save the same+ // people the run accepts: the runtime keys the book by the Agent owner.+ it('keys the address book by the Agent owner, not the calling manager', async () => {+ const { ContactModel } = await import('@/database/models/contact');+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ mockAgentOwnerRows.mockResolvedValue([{ userId: 'owner-9' }]);+ mockListAddressBookPeople.mockResolvedValue([]);++ await caller.listDeviceGrantablePeople({ agentId: 'agent-1' });++ expect(ContactModel).toHaveBeenCalledWith(expect.anything(), 'owner-9', undefined);+ expect(mockGetFeatureFlagsState).toHaveBeenCalledWith('owner-9');+ });++ it('lists the address book and the granted people who left it', async () => {+ const caller = agentShareRouter.createCaller(await createContextInner({ userId: 'user-1' }));+ const carol = { avatar: null, fullName: 'Carol', id: 'user-carol', username: 'carol' };+ mockGetByAgentId.mockResolvedValue({+ ...share,+ shareConfig: { ...share.shareConfig, deviceAllowUserIds: ['user-bob', 'user-carol'] },+ });+ mockListAddressBookPeople.mockResolvedValue([bob]);+ mockFindUser.mockResolvedValue(carol);+ mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true, enableChannels: true });++ await expect(caller.listDeviceGrantablePeople({ agentId: 'agent-1' })).resolves.toEqual({+ enabled: true,+ people: [bob],+ unlisted: [carol],+ });+ expect(mockFindUser).toHaveBeenCalledWith('user-carol');+ });+ });+it('caps maxTopicsPerVisitor at the visitor topic list limit', async () => {// The visitor topic list (`TopicModel.queryBySender`) is not paginated// and is bounded by `AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT` (200), so adiff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.tsnew file mode 100644index 00000000000..d214de9a71a--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.ts@@ -0,0 +1,144 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentRouter } from '../aiAgent';+import { resolveHeteroRunShareVisitor } from '../aiAgent/guards';+import { cleanupTestUser, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++const serviceCtor = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function (...args: unknown[]) {+ serviceCtor(...args);+ return { heteroFinish: vi.fn(), heteroIngest: vi.fn() };+ }),+}));+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));+vi.mock('@/server/services/aiChat', () => ({+ AiChatService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));++describe('hetero run share visitor', () => {+ let db: LobeChatDatabase;+ let userId: string;++ // Ids are suffixed per test: operation rows outlive `cleanupTestUser`.+ let seq = 0;+ let suffix = '';+ const ids = (name: string) => ({ op: `op-${name}-${suffix}`, topic: `topic-${name}-${suffix}` });+ const insertRun = async (+ name: string,+ senderId: string | null,+ metadata?: Record<string, unknown>,+ ) => {+ const { op, topic } = ids(name);+ await db.insert(topics).values({ id: topic, senderId, title: topic, userId });+ await db+ .insert(agentOperations)+ .values({ id: op, metadata, status: 'running', topicId: topic, userId });+ return { operationId: op, topicId: topic };+ };++ beforeEach(async () => {+ db = await getTestDB();+ testDB = db;+ userId = await createTestUser(db);+ serviceCtor.mockClear();+ suffix = String(++seq);+ });++ afterEach(async () => {+ await cleanupTestUser(db, userId);+ });++ const marker = { shareId: 'share-1', visitorUserId: 'visitor-1' };++ describe('resolveHeteroRunShareVisitor', () => {+ it('returns the marker when it names the topic sender', async () => {+ const run = await insertRun('ok', 'visitor-1', { agentShareVisitor: marker });++ await expect(resolveHeteroRunShareVisitor({ db, ...run })).resolves.toEqual(marker);+ });++ it.each([+ ['has no marker', 'visitor-1', {}],+ [+ 'names a different visitor than the topic sender',+ 'visitor-1',+ { agentShareVisitor: { ...marker, visitorUserId: 'someone-else' } },+ ],+ ['has no shareId', 'visitor-1', { agentShareVisitor: { visitorUserId: 'visitor-1' } }],+ ['belongs to a topic without a sender', null, { agentShareVisitor: marker }],+ ])('returns undefined when the operation %s', async (_, senderId, metadata) => {+ const run = await insertRun('x', senderId, metadata);++ await expect(resolveHeteroRunShareVisitor({ db, ...run })).resolves.toBeUndefined();+ });++ it('returns undefined when the topic or operation does not exist', async () => {+ const run = await insertRun('y', 'visitor-1', { agentShareVisitor: marker });++ await expect(+ resolveHeteroRunShareVisitor({ db, ...run, topicId: 'missing-topic' }),+ ).resolves.toBeUndefined();+ await expect(+ resolveHeteroRunShareVisitor({ db, ...run, operationId: 'missing-op' }),+ ).resolves.toBeUndefined();+ });+ });++ describe('heteroIngest / heteroFinish wiring', () => {+ const createCaller = () =>+ aiAgentRouter.createCaller({+ jwtPayload: { userId },+ oidcAuth: { sub: userId },+ userId,+ } as any);++ const serviceOptions = () => serviceCtor.mock.calls[0][2];+ const event = (operationId: string) => ({+ data: {},+ operationId,+ stepIndex: 0,+ timestamp: 1_700_000_000_000,+ type: 'stream_chunk' as const,+ });++ it('passes the resolved visitor into the service and starts no queued follow-up on finish', async () => {+ const run = await insertRun('share', 'visitor-1', { agentShareVisitor: marker });+ const params = { agentType: 'claude-code', ...run } as const;++ await createCaller().heteroIngest({ ...params, events: [event(run.operationId)] });+ expect(serviceOptions().shareVisitor).toEqual(marker);++ serviceCtor.mockClear();+ await createCaller().heteroFinish({ ...params, result: 'success' });+ expect(serviceOptions().shareVisitor).toEqual(marker);+ expect(serviceOptions().startQueuedFollowUp).toBeUndefined();+ });++ it('keeps the queued follow-up and no visitor for an ordinary run', async () => {+ const run = await insertRun('own', null);++ await createCaller().heteroFinish({ agentType: 'claude-code', ...run, result: 'success' });++ expect(serviceOptions().shareVisitor).toBeUndefined();+ expect(serviceOptions().startQueuedFollowUp).toEqual(expect.any(Function));+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.heteroIntervention.test.tsnew file mode 100644index 00000000000..cb83ddce9c2--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/shareChat.heteroIntervention.test.ts@@ -0,0 +1,122 @@+// @vitest-environment node+import type * as BusinessConst from '@lobechat/business-const';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createContextInner } from '@/libs/trpc/lambda/context';++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));+vi.mock('@lobechat/business-const', async () => {+ const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');+ return {+ ...actual,+ // Read dynamically by `packages/utils/src/apiKey.ts`; the Cloud override omits it.+ API_KEY_PREFIX: (actual as Record<string, unknown>).API_KEY_PREFIX,+ ENABLE_BUSINESS_FEATURES: true,+ };+});+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: vi+ .fn()+ .mockResolvedValue({ enableAgentShare: true }),+}));++const mocks = vi.hoisted(() => ({+ accessCheck: vi.fn(),+ findById: vi.fn(),+ submitAs: vi.fn(),+}));++vi.mock('@/database/models/agentShare', () => ({+ AgentShareModel: {+ findByShareIdWithAccessCheck: mocks.accessCheck,+ isRunStillAuthorized: vi.fn().mockResolvedValue(true),+ },+}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(function () {+ return { findById: mocks.findById, isRunningOperationAlive: vi.fn().mockResolvedValue(true) };+ }),+}));+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function () {+ return { getUserSettings: vi.fn().mockResolvedValue({}) };+ }),+}));+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn(function () {+ return {};+ }),+}));+vi.mock('../aiAgent/heteroInterventionSubmit', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ submitHeteroInterventionAs: mocks.submitAs,+}));++const { shareChatRouter } = await import('../shareChat');++const VISITOR = 'visitor-1';+const share = {+ agentId: 'agt_share',+ ownerId: 'owner-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visibility: 'link',+ workspaceId: 'ws-1',+};+const visitorTopic = {+ agentId: share.agentId,+ id: 'tpc_visitor',+ metadata: { runningOperation: { operationId: 'op-1' } },+ senderId: VISITOR,+};+const input = {+ operationId: 'op-1',+ resolutionRequestId: '2f4c5a7e-3b1d-4c8a-9e6f-0a1b2c3d4e5f',+ result: { answer: 'yes' },+ shareId: 'share-1',+ toolCallId: 'tool-1',+ topicId: 'tpc_visitor',+};++describe('shareChatRouter.submitHeteroIntervention', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.accessCheck.mockResolvedValue(share);+ mocks.findById.mockResolvedValue(visitorTopic);+ mocks.submitAs.mockResolvedValue({ status: 'resolving', success: true });+ });++ const call = async (override: Partial<typeof input> = {}) =>+ shareChatRouter+ .createCaller(await createContextInner({ userId: VISITOR }))+ .submitHeteroIntervention({ ...input, ...override });++ it("publishes the answer in the creator's scope without the share routing fields", async () => {+ await expect(call()).resolves.toEqual({ status: 'resolving', success: true });++ expect(mocks.submitAs).toHaveBeenCalledTimes(1);+ const [intervention, scope] = mocks.submitAs.mock.calls[0];+ expect(scope).toEqual({ userId: 'owner-1', workspaceId: 'ws-1' });+ expect(intervention).toMatchObject({+ operationId: 'op-1',+ result: { answer: 'yes' },+ toolCallId: 'tool-1',+ });+ expect(intervention).not.toHaveProperty('shareId');+ expect(intervention).not.toHaveProperty('topicId');+ });++ it('rejects an operation that is not the one running on the visitor topic', async () => {+ await expect(call({ operationId: 'op-someone-elses' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mocks.submitAs).not.toHaveBeenCalled();+ });++ it('rejects a topic that is not the visitor own topic', async () => {+ mocks.findById.mockResolvedValue({ ...visitorTopic, senderId: 'someone-else' });++ await expect(call()).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mocks.submitAs).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex f98701c432a..ad1a0d0e279 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -1,12 +1,14 @@import { builtinSkills } from '@lobechat/builtin-skills';import {AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,- AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT,+ AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT,AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT,} from '@lobechat/const';import { assembleSkillPool } from '@lobechat/mecha';import { getActivePluginIds, getDisabledPluginIds } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';+import pMap from 'p-map';import { z } from 'zod';import { getAgentShareMonthlySpend } from '@/business/server/agent-share/spendGate';@@ -16,14 +18,17 @@ import { AgentModel } from '@/database/models/agent';import { AgentShareModel } from '@/database/models/agentShare';import { AgentShareProfileModel } from '@/database/models/agentShareProfile';import { AgentSkillModel } from '@/database/models/agentSkill';+import { ContactModel } from '@/database/models/contact';import { FileModel } from '@/database/models/file';import { RbacModel } from '@/database/models/rbac';import { TopicModel } from '@/database/models/topic';+import { agents } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentService } from '@/server/services/agent';import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { isChannelEnabled } from '@/server/services/channel/featureGate';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';import { assertAgentShareCreationEnabled } from './_helpers/agentShareFeatureGate';@@ -66,15 +71,12 @@ export const agentShareConfigSchema = z).max(20).optional(),- deviceAccess: z.enum(['none', 'all', 'allowlist']).optional(),- /**- * Normalized to lower case before the duplicate check, because the- * runtime match against the visitor's account email is case-insensitive.- */- deviceAllowEmails: z- .array(z.string().trim().toLowerCase().pipe(z.email()))- .max(AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT)- .refine((emails) => new Set(emails).size === emails.length, 'Duplicate email')+ deviceAccess: z.enum(['none', 'allowlist']).optional(),+ /** Each id must also be in the scope's address book; `updateShareConfig` checks that. */+ deviceAllowUserIds: z+ .array(z.string().trim().min(1).max(64))+ .max(AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT)+ .refine((ids) => new Set(ids).size === ids.length, 'Duplicate user').optional(),featuredWorkIds: z.array(z.string().trim().min(1))@@ -195,6 +197,27 @@ const assertCanManageAgentShare = async (});};+/**+ * The address book a share's device grant draws from: the owner's personal+ * contacts for a personal Agent, the workspace's members and external+ * contacts for a workspace Agent. Keyed by the Agent's owner, exactly as the+ * runtime re-check (`resolveShareVisitorDeviceAccess`) is, so a workspace+ * manager other than the owner lists and saves the same people the run then+ * accepts. `enabled` mirrors the runtime's Channels gate on the same owner.+ */+const shareAddressBook = async (ctx: AgentSharePermissionContext, agentId: string) => {+ const [agent] = await ctx.serverDB+ .select({ userId: agents.userId })+ .from(agents)+ .where(eq(agents.id, agentId))+ .limit(1);+ const ownerId = agent?.userId ?? ctx.userId;+ return {+ book: new ContactModel(ctx.serverDB, ownerId, ctx.workspaceId),+ enabled: await isChannelEnabled(ownerId),+ };+};+/** `updateConfig` / `updateVisibility` / `updateSlug` all return `null` when the share (or its owning agent) does not resolve for this caller. */const requireShare = <T>(share: T | null): T => {if (!share) {@@ -442,6 +465,32 @@ export const agentShareRouter = router({}));}),+ /**+ * Who the execution-environment grant can name: the address book of the+ * share's scope (`ContactModel.listAddressBookPeople`). `unlisted` resolves+ * the profiles of already-granted people who have since left that book, so+ * the settings page can show them as no longer authorized instead of an id.+ * `enabled` is false while the address book itself is off for the caller+ * (Channels flag): nobody can be added then, and runtime grants nothing.+ */+ listDeviceGrantablePeople: agentShareProcedure+ .input(agentIdInput)+ .query(async ({ input, ctx }) => {+ await assertCanManageAgentShare(ctx, input.agentId);+ const share = requireShare(await ctx.agentShareModel.getByAgentId(input.agentId));++ const { book, enabled } = await shareAddressBook(ctx, input.agentId);+ const people = enabled ? await book.listAddressBookPeople() : [];+ const inBook = new Set(people.map((person) => person.id));+ const unlisted = await pMap(+ (share.shareConfig.deviceAllowUserIds ?? []).filter((id) => !inBook.has(id)),+ (id) => book.findUser(id),+ { concurrency: 5 },+ );++ return { enabled, people, unlisted: unlisted.filter((user) => !!user) };+ }),+updateShareConfig: agentShareProcedure.input(z@@ -453,6 +502,27 @@ export const agentShareRouter = router({).mutation(async ({ input, ctx }) => {await assertCanManageAgentShare(ctx, input.agentId);++ const { deviceAccess, deviceAllowUserIds } = input.config;+ if (deviceAccess === 'allowlist' || deviceAllowUserIds?.length) {+ const { book, enabled } = await shareAddressBook(ctx, input.agentId);+ // The runtime grants nothing while contacts are off, so refuse to store+ // a grant that would silently do nothing (or wake up when they turn on).+ if (!enabled)+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Device access needs contacts, which are not available',+ });+ const inBook = new Set(+ deviceAllowUserIds?.length ? await book.filterAddressBookPeople(deviceAllowUserIds) : [],+ );+ if (deviceAllowUserIds?.some((id) => !inBook.has(id)))+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Device access can only be granted to people in your contacts',+ });+ }+return requireShare(await ctx.agentShareModel.updateConfig(input.agentId, input.config));}),diff --git a/apps/server/src/routers/lambda/aiAgent/guards.ts b/apps/server/src/routers/lambda/aiAgent/guards.tsindex 5d86b6f2569..9b7af639b47 100644--- a/apps/server/src/routers/lambda/aiAgent/guards.ts+++ b/apps/server/src/routers/lambda/aiAgent/guards.ts@@ -9,6 +9,7 @@ import {assertCanUseTopicTargets,} from '@/server/routers/lambda/_helpers/conversationResourceGuard';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';+import type { OperationCompletionShareVisitor } from '@/server/services/agentRuntime/CompletionLifecycle/types';export const resolveHeteroTopicWorkspace = async (params: {db: LobeChatDatabase;@@ -53,6 +54,34 @@ export const resolveHeteroTopicWorkspace = async (params: {return topic.workspaceId;};+/**+ * The share visitor a hetero run on this topic belongs to, or `undefined` for+ * an ordinary run. Read from the marker the dispatch stamped on the operation+ * row, and trusted only when the topic really is that visitor's topic+ * (`topics.senderId`). A visitor topic whose operation has no matching marker+ * also resolves to `undefined`: its rows then stay hidden, which drops the+ * run's output rather than exposing it to the wrong scope.+ */+export const resolveHeteroRunShareVisitor = async (params: {+ db: LobeChatDatabase;+ operationId: string;+ topicId: string;+}): Promise<OperationCompletionShareVisitor | undefined> => {+ const { db, operationId, topicId } = params;+ const [row] = await db+ .select({ metadata: agentOperations.metadata, senderId: topics.senderId })+ .from(agentOperations)+ .innerJoin(topics, eq(topics.id, agentOperations.topicId))+ .where(and(eq(agentOperations.id, operationId), eq(agentOperations.topicId, topicId)))+ .limit(1);+ if (!row?.senderId) return undefined;++ const marker = row.metadata?.agentShareVisitor as+ Partial<OperationCompletionShareVisitor> | undefined;+ if (!marker?.shareId || marker.visitorUserId !== row.senderId) return undefined;+ return { shareId: marker.shareId, visitorUserId: marker.visitorUserId };+};+/*** Workspace `use` guard for operation-keyed endpoints: resolve the operation* row to its agent and run the same `use` guard. Operations without an agentdiff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex e84bef0f2a7..cdd154ec2f1 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -1,5 +1,3 @@-import { randomUUID } from 'node:crypto';-import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';import { LocalExecutionHeterogeneousAgentTypeSchema } from '@lobechat/types';import { TRPCError } from '@trpc/server';@@ -9,9 +7,7 @@ import { z } from 'zod';import {getHeteroInterventionReview,- onHeteroInterventionResolutionPublished,resolveHeteroIntervention,- rollbackHeteroInterventionResolution,} from '@/business/server/agent-run/heteroInterventionReview';import { agentOperations } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -38,7 +34,16 @@ import {resolveActiveHeteroOperationPrincipal,} from '@/server/services/heterogeneousAgent/operationPrincipal';-import { assertCanUseOperationAgent, resolveHeteroTopicWorkspace } from './guards';+import {+ assertCanUseOperationAgent,+ resolveHeteroRunShareVisitor,+ resolveHeteroTopicWorkspace,+} from './guards';+import {+ publishClaimedHeteroIntervention,+ submitHeteroInterventionAs,+ SubmitHeteroInterventionSchema,+} from './heteroInterventionSubmit';import { aiAgentBaseProcedure, aiAgentWriteProcedure, heteroAgentProcedure } from './procedures';const log = debug('lobe-server:ai-agent-router');@@ -234,26 +239,6 @@ const waitOrAbort = (ms: number, signal: AbortSignal | undefined) =>signal?.addEventListener('abort', done, { once: true });});-/**- * Schema for `aiAgent.submitHeteroIntervention` — the browser leg of remote- * Human-in-the-loop. The user's answer to an `agent_intervention_request` is- * published back onto the op's Redis stream as an `agent_intervention_response`,- * where both the renderer (card → resolved) and the exec long-poll converge on- * it by `toolCallId`. Mutually exclusive: `result` on submit, `cancelled` on- * skip/cancel.- */-const SubmitHeteroInterventionSchema = z.object({- cancelReason: z.enum(['timeout', 'user_cancelled', 'session_ended']).optional(),- cancelled: z.boolean().optional(),- operationId: z.string().min(1),- /** Optional only for backward compatibility with pre-contract Web clients. */- resolutionRequestId: z.string().uuid().optional(),- result: z.unknown().optional(),- /** Producer step index; harmless placeholder — correlation is by toolCallId. */- stepIndex: z.number().int().nonnegative().default(0),- toolCallId: z.string().min(1),-});-const HeteroInterventionReviewTokenSchema = z.object({/** 32 random bytes encoded as base64url without padding. */reviewToken: z.string().regex(/^[\w-]{43}$/),@@ -266,76 +251,6 @@ const ResolveHeteroInterventionReviewSchema = z.object({reviewToken: z.string().regex(/^[\w-]{43}$/),});-const publishClaimedHeteroIntervention = async (params: {- claim: Extract<- Awaited<ReturnType<typeof resolveHeteroIntervention>>,- { handled: true; state: 'claimed' }- >;- userId: string;- workspaceId?: string | null;-}) => {- const { claim, userId, workspaceId } = params;- const resolvedWorkspaceId = claim.workspaceId ?? workspaceId ?? undefined;- const streamEventManager = createStreamEventManager();-- try {- await streamEventManager.publishStreamEvent(claim.operationId, {- data: {- ...claim.response,- producerAck: false,- resolutionRequestId: claim.resolutionRequestId,- },- stepIndex: claim.stepIndex ?? 0,- type: 'agent_intervention_response',- });- } catch (error) {- await rollbackHeteroInterventionResolution({- claimId: claim.claimId,- operationId: claim.operationId,- resolutionRequestId: claim.resolutionRequestId,- toolCallId: claim.response.toolCallId,- userId,- workspaceId: resolvedWorkspaceId,- }).catch((rollbackError) => {- log(- 'conditional intervention rollback failed claim=%s op=%s: %O',- claim.claimId,- claim.operationId,- rollbackError,- );- });- throw error;- }-- // Notification surfaces may switch to `resolving` only after XADD has- // succeeded. This best-effort side effect must not roll back a response the- // producer can already consume from the stream.- await onHeteroInterventionResolutionPublished({- claimId: claim.claimId,- operationId: claim.operationId,- resolutionRequestId: claim.resolutionRequestId,- status: 'resolving',- toolCallId: claim.response.toolCallId,- userId,- workspaceId: resolvedWorkspaceId,- }).catch((notificationError) => {- log(- 'intervention published hook failed claim=%s op=%s: %O',- claim.claimId,- claim.operationId,- notificationError,- );- });-- return {- // XADD only acknowledges transport acceptance. The producer's echoed- // response is the authoritative terminal transition persisted by the- // intervention reducer; until then the durable row remains resolving.- status: 'resolving' as const,- success: true as const,- };-};-const authorizeOperationCallback = async (ctx: {heteroAuthKind: string;@@ -402,7 +317,13 @@ export const heteroRouter = router({topicId,userId: ctx.userId,});+ const shareVisitor = await resolveHeteroRunShareVisitor({+ db: ctx.serverDB,+ operationId,+ topicId,+ });const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {+ shareVisitor,workspaceId: wsId,});@@ -496,13 +417,23 @@ export const heteroRouter = router({topicId,userId: ctx.userId,});+ const shareVisitor = await resolveHeteroRunShareVisitor({+ db: ctx.serverDB,+ operationId,+ topicId,+ });const heteroService = new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {+ shareVisitor,// Follow-ups queued behind the run start as its next turn through the- // composer pipeline, under the run owner and its workspace.- startQueuedFollowUp: (params) =>- new AiAgentService(ctx.serverDB, ctx.userId, { workspaceId: wsId }).startQueuedFollowUp(- params,- ),+ // composer pipeline, under the run owner and its workspace. Not for a+ // share visitor run: that start carries no share gate, so it would run+ // the visitor's queued text as an ungated creator turn.+ startQueuedFollowUp: shareVisitor+ ? undefined+ : (params) =>+ new AiAgentService(ctx.serverDB, ctx.userId, {+ workspaceId: wsId,+ }).startQueuedFollowUp(params),workspaceId: wsId,});@@ -827,69 +758,20 @@ export const heteroRouter = router({submitHeteroIntervention: aiAgentWriteProcedure.input(SubmitHeteroInterventionSchema).mutation(async ({ input, ctx }) => {- const {- operationId,- toolCallId,- stepIndex,- result,- cancelled,- resolutionRequestId = randomUUID(),- } = input;-log('submitHeteroIntervention: op=%s toolCallId=%s cancelled=%s',- operationId,- toolCallId,- cancelled ?? false,+ input.operationId,+ input.toolCallId,+ input.cancelled ?? false,);await assertCanUseOperationAgent({db: ctx.serverDB,- operationId,+ operationId: input.operationId,userId: ctx.userId,workspaceId: ctx.workspaceId,});- // Cloud overrides this as an atomic first-winner claim shared by Web and- // Mobile. OSS returns `handled:false` and preserves the legacy stream- // publish below. A claimed response is authoritative: client-supplied- // operation/tool fields cannot override what Cloud resolved durably.- const businessResolution = await resolveHeteroIntervention({- action: cancelled ? 'skip' : 'submit',- cancelReason: cancelled ? 'user_cancelled' : undefined,- result: cancelled ? undefined : result,- resolutionRequestId,- target: { operationId, toolCallId },- userId: ctx.userId,- workspaceId: ctx.workspaceId ?? undefined,- });- if (businessResolution.handled) {- if (businessResolution.state === 'already_resolved') {- return { status: businessResolution.status, success: true as const };- }- return publishClaimedHeteroIntervention({- claim: businessResolution,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }-- const streamEventManager = createStreamEventManager();- await streamEventManager.publishStreamEvent(operationId, {- data: {- // Client-driven cancellation cannot impersonate producer timeout or- // session teardown; those terminal reasons originate from bridge ACKs.- cancelReason: cancelled ? 'user_cancelled' : undefined,- cancelled,- producerAck: false,- result: cancelled ? undefined : result,- resolutionRequestId,- toolCallId,- },- stepIndex,- type: 'agent_intervention_response',- });-- return { status: 'resolving' as const, success: true as const };+ return submitHeteroInterventionAs(input, ctx);}),});diff --git a/apps/server/src/routers/lambda/aiAgent/heteroInterventionSubmit.ts b/apps/server/src/routers/lambda/aiAgent/heteroInterventionSubmit.tsnew file mode 100644index 00000000000..5cbaa962e81--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/heteroInterventionSubmit.ts@@ -0,0 +1,168 @@+import { randomUUID } from 'node:crypto';++import debug from 'debug';+import { z } from 'zod';++import {+ onHeteroInterventionResolutionPublished,+ resolveHeteroIntervention,+ rollbackHeteroInterventionResolution,+} from '@/business/server/agent-run/heteroInterventionReview';+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';++const log = debug('lobe-server:ai-agent-hetero-intervention');++/**+ * Schema for `aiAgent.submitHeteroIntervention` — the browser leg of remote+ * Human-in-the-loop. The user's answer to an `agent_intervention_request` is+ * published back onto the op's Redis stream as an `agent_intervention_response`,+ * where both the renderer (card → resolved) and the exec long-poll converge on+ * it by `toolCallId`. Mutually exclusive: `result` on submit, `cancelled` on+ * skip/cancel.+ */+export const SubmitHeteroInterventionSchema = z.object({+ cancelReason: z.enum(['timeout', 'user_cancelled', 'session_ended']).optional(),+ cancelled: z.boolean().optional(),+ operationId: z.string().min(1),+ /** Optional only for backward compatibility with pre-contract Web clients. */+ resolutionRequestId: z.string().uuid().optional(),+ result: z.unknown().optional(),+ /** Producer step index; harmless placeholder — correlation is by toolCallId. */+ stepIndex: z.number().int().nonnegative().default(0),+ toolCallId: z.string().min(1),+});++export type SubmitHeteroInterventionInput = z.input<typeof SubmitHeteroInterventionSchema>;++export const publishClaimedHeteroIntervention = async (params: {+ claim: Extract<+ Awaited<ReturnType<typeof resolveHeteroIntervention>>,+ { handled: true; state: 'claimed' }+ >;+ userId: string;+ workspaceId?: string | null;+}) => {+ const { claim, userId, workspaceId } = params;+ const resolvedWorkspaceId = claim.workspaceId ?? workspaceId ?? undefined;+ const streamEventManager = createStreamEventManager();++ try {+ await streamEventManager.publishStreamEvent(claim.operationId, {+ data: {+ ...claim.response,+ producerAck: false,+ resolutionRequestId: claim.resolutionRequestId,+ },+ stepIndex: claim.stepIndex ?? 0,+ type: 'agent_intervention_response',+ });+ } catch (error) {+ await rollbackHeteroInterventionResolution({+ claimId: claim.claimId,+ operationId: claim.operationId,+ resolutionRequestId: claim.resolutionRequestId,+ toolCallId: claim.response.toolCallId,+ userId,+ workspaceId: resolvedWorkspaceId,+ }).catch((rollbackError) => {+ log(+ 'conditional intervention rollback failed claim=%s op=%s: %O',+ claim.claimId,+ claim.operationId,+ rollbackError,+ );+ });+ throw error;+ }++ // Notification surfaces may switch to `resolving` only after XADD has+ // succeeded. This best-effort side effect must not roll back a response the+ // producer can already consume from the stream.+ await onHeteroInterventionResolutionPublished({+ claimId: claim.claimId,+ operationId: claim.operationId,+ resolutionRequestId: claim.resolutionRequestId,+ status: 'resolving',+ toolCallId: claim.response.toolCallId,+ userId,+ workspaceId: resolvedWorkspaceId,+ }).catch((notificationError) => {+ log(+ 'intervention published hook failed claim=%s op=%s: %O',+ claim.claimId,+ claim.operationId,+ notificationError,+ );+ });++ return {+ // XADD only acknowledges transport acceptance. The producer's echoed+ // response is the authoritative terminal transition persisted by the+ // intervention reducer; until then the durable row remains resolving.+ status: 'resolving' as const,+ success: true as const,+ };+};++/**+ * Publish a browser answer to a remote hetero question once the caller has+ * been authorized for the operation. `userId` / `workspaceId` are the+ * operation owner's scope: the owner themselves, or the creator of a share+ * whose visitor is answering their own running operation.+ */+export const submitHeteroInterventionAs = async (+ input: z.output<typeof SubmitHeteroInterventionSchema>,+ owner: { userId: string; workspaceId?: string | null },+) => {+ const ctx = { userId: owner.userId, workspaceId: owner.workspaceId ?? undefined };+ const {+ operationId,+ toolCallId,+ stepIndex,+ result,+ cancelled,+ resolutionRequestId = randomUUID(),+ } = input;++ // Cloud overrides this as an atomic first-winner claim shared by Web and+ // Mobile. OSS returns `handled:false` and preserves the legacy stream+ // publish below. A claimed response is authoritative: client-supplied+ // operation/tool fields cannot override what Cloud resolved durably.+ const businessResolution = await resolveHeteroIntervention({+ action: cancelled ? 'skip' : 'submit',+ cancelReason: cancelled ? 'user_cancelled' : undefined,+ result: cancelled ? undefined : result,+ resolutionRequestId,+ target: { operationId, toolCallId },+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ if (businessResolution.handled) {+ if (businessResolution.state === 'already_resolved') {+ return { status: businessResolution.status, success: true as const };+ }+ return publishClaimedHeteroIntervention({+ claim: businessResolution,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }++ const streamEventManager = createStreamEventManager();+ await streamEventManager.publishStreamEvent(operationId, {+ data: {+ // Client-driven cancellation cannot impersonate producer timeout or+ // session teardown; those terminal reasons originate from bridge ACKs.+ cancelReason: cancelled ? 'user_cancelled' : undefined,+ cancelled,+ producerAck: false,+ result: cancelled ? undefined : result,+ resolutionRequestId,+ toolCallId,+ },+ stepIndex,+ type: 'agent_intervention_response',+ });++ return { status: 'resolving' as const, success: true as const };+};diff --git a/apps/server/src/routers/lambda/shareChat/index.procedures.test.ts b/apps/server/src/routers/lambda/shareChat/index.procedures.test.tsindex 4ae2976b85c..1fe781eb7c9 100644--- a/apps/server/src/routers/lambda/shareChat/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/shareChat/index.procedures.test.ts@@ -39,5 +39,6 @@ function expected(): Array<['resolveInterventionBySource', 'mutation', 11],['setQueuedMessages', 'mutation', 11],['stopPendingApproval', 'mutation', 11],+ ['submitHeteroIntervention', 'mutation', 11],];}diff --git a/apps/server/src/routers/lambda/shareChat/runControl.ts b/apps/server/src/routers/lambda/shareChat/runControl.tsindex ffaf625b343..bc045f68b5c 100644--- a/apps/server/src/routers/lambda/shareChat/runControl.ts+++ b/apps/server/src/routers/lambda/shareChat/runControl.ts@@ -15,6 +15,10 @@ import { mapAgentInterventionTRPCError } from '../_helpers/agentInterventionErroimport { toClientExecAgentResult } from '../_helpers/groupMemberContinuationResult';import { ResolveAgentInterventionBySourceSchema } from '../_schema/agentIntervention';import { dispatchClaimedAgentIntervention } from '../aiAgent';+import {+ submitHeteroInterventionAs,+ SubmitHeteroInterventionSchema,+} from '../aiAgent/heteroInterventionSubmit';import {findVisitorTopicOrThrow,resolveLinkShareOrThrow,@@ -335,4 +339,30 @@ export const runControlRouter = router({});}}),+ /**+ * The visitor counterpart of `aiAgent.submitHeteroIntervention`: answers a+ * question Claude Code / Codex asked during the visitor's own run. Authorized+ * like `interruptTask` (the operation must be the one running on the+ * visitor's topic), then published in the creator's scope, which owns the+ * operation row.+ */+ submitHeteroIntervention: shareChatProcedure+ .input(ShareTopicScopeSchema.merge(SubmitHeteroInterventionSchema))+ .mutation(async ({ input, ctx }) => {+ const { share } = await authorizeVisitorRunningOperation(ctx.serverDB, ctx.userId, input);++ log(+ 'submitHeteroIntervention: share=%s visitor=%s topic=%s operation=%s',+ input.shareId,+ ctx.userId,+ input.topicId,+ input.operationId,+ );++ const { shareId: _shareId, topicId: _topicId, ...intervention } = input;+ return submitHeteroInterventionAs(intervention, {+ userId: share.ownerId,+ workspaceId: share.workspaceId,+ });+ }),});diff --git a/apps/server/src/routers/lambda/shareChat/runScope.test.ts b/apps/server/src/routers/lambda/shareChat/runScope.test.tsindex f5f6f975b76..6209fa9dfe1 100644--- a/apps/server/src/routers/lambda/shareChat/runScope.test.ts+++ b/apps/server/src/routers/lambda/shareChat/runScope.test.ts@@ -21,7 +21,7 @@ const db = {} as any;const share = {agentId: 'agt_shared',ownerId: 'owner',- shareConfig: { deviceAccess: 'all', toolGrants: [] },+ shareConfig: { deviceAccess: 'allowlist', deviceAllowUserIds: ['visitor'], toolGrants: [] },shareId: 'share-1',workspaceId: null,} as any;@@ -36,7 +36,7 @@ describe('createShareRunScope', () => {const { dispatchContext, shareGate } = await createShareRunScope(db, share, 'visitor');- expect(resolveDeviceAccess).toHaveBeenCalledWith(db, share.shareConfig, 'visitor');+ expect(resolveDeviceAccess).toHaveBeenCalledWith(db, share, 'visitor');expect(shareGate).toEqual({agentId: 'agt_shared',canUseDevice: granted,diff --git a/apps/server/src/routers/lambda/shareChat/runScope.ts b/apps/server/src/routers/lambda/shareChat/runScope.tsindex 1a76ed28ebe..e41decdb722 100644--- a/apps/server/src/routers/lambda/shareChat/runScope.ts+++ b/apps/server/src/routers/lambda/shareChat/runScope.ts@@ -32,7 +32,7 @@ export const createShareRunScope = async (const shareGate: AgentShareGate = {agentId: share.agentId,- canUseDevice: await resolveShareVisitorDeviceAccess(db, share.shareConfig, visitorUserId),+ canUseDevice: await resolveShareVisitorDeviceAccess(db, share, visitorUserId),shareConfig: share.shareConfig,// See `AgentShareGate.shareId`'s JSDoc — the share instance this run is// authorized against, and the token every later revalidation compares.diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.tsindex 577bf1a1fe4..a76037000ee 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts@@ -401,3 +401,21 @@ describe('CompletionLifecycle.dispatchHooks — completion notification', () =>expect(hookDispatcher.unregister).toHaveBeenCalledWith('op-1');});});++describe('CompletionLifecycle.buildStateFromInput share visitor', () => {+ const build = (input: Record<string, unknown>) =>+ (new CompletionLifecycle({} as any, 'user-1') as any).buildStateFromInput({+ operationId: 'op-share',+ ...input,+ });++ it('marks the synthesized state as a share visitor run', () => {+ const shareVisitor = { shareId: 'share-1', visitorUserId: 'visitor-1' };++ expect(build({ shareVisitor }).principal).toEqual({ actor: { shareVisitor } });+ });++ it('adds no principal for an ordinary run', () => {+ expect(build({}).principal).toBeUndefined();+ });+});diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex 36da3cfaf18..5528dc6f587 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -305,6 +305,7 @@ export class CompletionLifecycle {],host: { hooks: input.serializedHooks },metadata: { assistantMessageId: input.assistantMessageId },+ ...(input.shareVisitor && { principal: { actor: { shareVisitor: input.shareVisitor } } }),origin: {agentId: input.agentId,lineage: { orchestrationRole: input.orchestrationRole },diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.tsindex 93dae3b0a6a..dcaa0e8bcf9 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts@@ -32,6 +32,17 @@ export type TopicRunSettledHandler = (params: {* The in-process runtime keeps calling `dispatchHooks` with its real, rich* `state` directly (full message array, interruption, …) — it needs no synthesis.*/+/**+ * The share visitor a run completed for, mirrored onto the synthetic state's+ * `principal.actor.shareVisitor` so completion treats it as a share run+ * (no creator recall, share-scoped Works). In-process runs carry the full+ * context on their own state instead.+ */+export interface OperationCompletionShareVisitor {+ shareId: string;+ visitorUserId: string;+}+export interface OperationCompletionInput {/** Owning agent id — trace snapshot key + the lifecycle event's `agentId`. */agentId?: string;@@ -60,6 +71,8 @@ export interface OperationCompletionInput {provider?: string | null;/** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */serializedHooks?: SerializedHook[];+ /** Set for a share visitor run settled outside its in-process state (hetero). */+ shareVisitor?: OperationCompletionShareVisitor;/** When the run started, so the terminal row keeps its processing time. */startedAt?: Date | string;stepCount?: number | null;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.tsindex 6fe9167e192..b249d8d922c 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.shareVisitorHetero.test.ts@@ -3,13 +3,30 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';-const { mockCreateOperation, mockGetAgentConfig, mockGetUserSettings, mockMessageCreate } =- vi.hoisted(() => ({- mockCreateOperation: vi.fn(),- mockGetAgentConfig: vi.fn(),- mockGetUserSettings: vi.fn(),- mockMessageCreate: vi.fn(),- }));+const {+ mockCreateOperation,+ mockGetAgentConfig,+ mockGetScopedOnlineDevices,+ mockGetUserSettings,+ mockMessageCreate,+ mockDispatchHeteroAgent,+ mockReserveShareVisitorTopic,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockDispatchHeteroAgent: vi.fn(),+ mockReserveShareVisitorTopic: vi.fn(),+ mockGetAgentConfig: vi.fn(),+ mockGetScopedOnlineDevices: vi.fn(),+ mockGetUserSettings: vi.fn(),+ mockMessageCreate: vi.fn(),+}));++// The share gate runs before dispatch; record what the dispatch is handed.+vi.mock('../pipeline/heteroDispatch', () => ({ dispatchHeteroAgent: mockDispatchHeteroAgent }));++vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({+ getScopedOnlineDevices: mockGetScopedOnlineDevices,+}));vi.mock('@/libs/trusted-client', () => ({generateTrustedClientToken: vi.fn().mockReturnValue(undefined),@@ -142,7 +159,7 @@ vi.mock('@/server/modules/ModelRuntime', () => ({// The share path's atomic cap reservations open real DB transactions — stub// them so the forced-headless test below can drive execAgent with a bare mock db.vi.mock('../shareVisitorAbuseGuards', () => ({- reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ reserveShareVisitorTopic: mockReserveShareVisitorTopic,reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),}));@@ -160,43 +177,120 @@ vi.mock('model-bank', async (importOriginal) => {};});+const shareGate = (canUseDevice: boolean) => ({+ agentId: 'agent-1',+ canUseDevice,+ shareConfig: {+ deviceAccess: canUseDevice ? ('allowlist' as const) : ('none' as const),+ deviceAllowUserIds: canUseDevice ? ['visitor-1'] : [],+ toolGrants: [],+ },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+});++const agentConfig = (agencyConfig: Record<string, unknown>) => ({+ agencyConfig,+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: '',+});++const run = (canUseDevice: boolean) =>+ new AiAgentService({} as any, 'creator-1').execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ shareGate: shareGate(canUseDevice),+ });+describe('AiAgentService.execAgent - share visitors and heterogeneous agents', () => {beforeEach(() => {vi.clearAllMocks();mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockReserveShareVisitorTopic.mockResolvedValue({ id: 'topic-1' });mockGetUserSettings.mockResolvedValue({});- mockGetAgentConfig.mockResolvedValue({- agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },- chatConfig: {},- id: 'agent-1',- model: 'gpt-4',- plugins: [],- provider: 'openai',- systemRole: '',+ mockGetScopedOnlineDevices.mockResolvedValue([]);+ mockGetAgentConfig.mockResolvedValue(+ agentConfig({+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ }),+ );+ });++ it('rejects a Claude Code Agent for a visitor without the device grant', async () => {+ mockGetScopedOnlineDevices.mockResolvedValue([{ deviceId: 'device-1', online: true }]);++ await expect(run(false)).rejects.toMatchObject({+ message: 'ShareHeterogeneousAgentUnsupported',});+ expect(mockMessageCreate).not.toHaveBeenCalled();+ expect(mockCreateOperation).not.toHaveBeenCalled();});- // The hetero dispatch path signs its gateway token for the run's user (the- // creator) and registers no visitor stream owner, so a share's device grant- // must not open it: the visitor would receive creator account access.- it('rejects a Claude Code Agent even when the share grants device access', async () => {- const service = new AiAgentService({} as any, 'creator-1');-- await expect(- service.execAgent({- agentId: 'agent-1',- prompt: 'Hello',- shareGate: {- agentId: 'agent-1',- canUseDevice: true,- shareConfig: { deviceAccess: 'all', toolGrants: [] },- shareId: 'share-1',- visitorUserId: 'visitor-1',- },- }),- ).rejects.toMatchObject({ message: 'ShareHeterogeneousAgentUnsupported' });+ it('rejects a heterogeneous type other than Claude Code / Codex even with the grant', async () => {+ mockGetAgentConfig.mockResolvedValue(+ agentConfig({ boundDeviceId: 'device-1', heterogeneousProvider: { type: 'openclaw' } }),+ );+ mockGetScopedOnlineDevices.mockResolvedValue([{ deviceId: 'device-1', online: true }]);++ await expect(run(true)).rejects.toMatchObject({+ message: 'ShareHeterogeneousAgentUnsupported',+ });+ expect(mockMessageCreate).not.toHaveBeenCalled();+ });+ // No cloud-sandbox fallback: a granted visitor runs on the creator's device+ // or not at all, and learns it is offline before any row is written.+ it('fails a granted visitor with a device-offline error when the device is offline', async () => {+ await expect(run(true)).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: 'ShareHeteroDeviceUnavailable',+ });+ expect(mockGetScopedOnlineDevices).toHaveBeenCalledWith({}, 'creator-1', undefined);expect(mockMessageCreate).not.toHaveBeenCalled();expect(mockCreateOperation).not.toHaveBeenCalled();});++ it('lets a granted visitor through when the bound device is online', async () => {+ mockGetScopedOnlineDevices.mockResolvedValue([{ deviceId: 'device-1', online: true }]);++ // The gate passes; whatever later stage this bare mock db stops at, it is+ // not one of the share gate errors.+ const error = await run(true).then(+ () => undefined,+ (e: unknown) => e as { message?: string },+ );+ expect(error?.message).not.toBe('ShareHeterogeneousAgentUnsupported');+ expect(error?.message).not.toBe('ShareHeteroDeviceUnavailable');+ });++ it('resolves an auto Agent to its only online device', async () => {+ mockGetAgentConfig.mockResolvedValue(+ agentConfig({ executionTarget: 'auto', heterogeneousProvider: { type: 'codex' } }),+ );+ mockGetScopedOnlineDevices.mockResolvedValue([{ deviceId: 'device-2', online: true }]);++ const error = await run(true).then(+ () => undefined,+ (e: unknown) => e as { message?: string },+ );+ expect(error?.message).not.toBe('ShareHeteroDeviceUnavailable');+ // The dispatch does not look at online devices, so it must be handed the+ // device the gate picked, or it reports the device as unavailable.+ expect(mockDispatchHeteroAgent).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.objectContaining({ requestedDeviceId: 'device-2' }),+ );+ // The automatic pick is not an explicit pin: a later turn may go to+ // whichever device is online then.+ const [, topicParams] = mockReserveShareVisitorTopic.mock.calls[0];+ expect(topicParams.metadata?.deviceBindingPinned).not.toBe(true);+ expect(topicParams.metadata?.boundDeviceId).toBeUndefined();+ });});diff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.tsindex 71eea7b1762..fab01b8e022 100644--- a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts+++ b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts@@ -51,11 +51,7 @@ const resolveShareGate = async (return {agentId: share.agentId,- canUseDevice: await resolveShareVisitorDeviceAccess(- deps.db,- share.shareConfig,- shareVisitor.visitorUserId,- ),+ canUseDevice: await resolveShareVisitorDeviceAccess(deps.db, share, shareVisitor.visitorUserId),shareConfig: share.shareConfig,shareId: share.shareId,visitorUserId: shareVisitor.visitorUserId,diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex 1cf92b29551..01f5ae5457c 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -569,6 +569,7 @@ export const execAgentTurn = async (bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),db: deps.db,getMarketService: (options) => deps.getMarketService(runFacts, options),+ includeShareVisitor: !!runContext.shareGate,messageModel: deps.messageModel,resolveDeviceWorkspaceId: deps.resolveDeviceWorkspaceId,topicModel: deps.topicModel,diff --git a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.tsindex 657e3e5afd4..128696a1de5 100644--- a/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts+++ b/apps/server/src/services/aiAgent/pipeline/finalizeHeteroDispatchError.ts@@ -20,6 +20,11 @@ const log = debug('lobe-server:ai-agent-service');/** The part of `HeteroDispatchDeps` that settling a dispatch failure needs. */export interface HeteroDispatchErrorDeps {db: LobeChatDatabase;+ /**+ * A share visitor run: its topic and messages are visitor rows, which the+ * models hide unless opted in, so settling the run must opt in too.+ */+ includeShareVisitor?: boolean;messageModel: MessageModel;topicModel: TopicModel;userId: string;@@ -112,7 +117,9 @@ export const finalizeHeteroDispatchError = async (// hooks, so asking afterwards can no longer tell "delivered" from "never// had one".const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');- await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(+ await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId, {+ includeShareVisitor: deps.includeShareVisitor,+ }).completeOperation({agentId,assistantMessageId,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.tsnew file mode 100644index 00000000000..ca58acfd319--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.shareVisitor.test.ts@@ -0,0 +1,231 @@+import { ChatErrorType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ExecRunContext } from '../../types';+import type { HeteroDispatchDeps, HeteroDispatchInput } from '.';+import { dispatchHeteroAgent } from '.';++const mocks = vi.hoisted(() => ({+ createOperationMetadata: vi.fn(),+ dispatchAgentRun: vi.fn(),+ finalizeHeteroDispatchError: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ recordStart: vi.fn(),+ resolveDeviceDispatchAuthorizationFailure: vi.fn(),+ resolveSandboxSessionConfig: vi.fn(),+ signHeteroOperationJWT: vi.fn(),+ signUserJWT: vi.fn(),+ spawnHeteroSandbox: vi.fn(),+}));++vi.mock('@/server/services/agentRuntime/CompletionLifecycle', () => ({+ CompletionLifecycle: vi.fn().mockImplementation(function () {+ return {+ completeOperation: vi.fn(),+ recordStart: mocks.recordStart,+ waitForVerifyPlan: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));+vi.mock('@/server/services/agentRuntime/hooks', () => ({+ hookDispatcher: {+ canDeliver: vi.fn().mockReturnValue(false),+ getSerializedHooks: vi.fn().mockReturnValue([]),+ register: vi.fn(),+ unregister: vi.fn(),+ },+}));+vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {+ return { getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined) };+ }),+}));+vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signHeteroOperationJWT: mocks.signHeteroOperationJWT,+ signUserJWT: mocks.signUserJWT,+}));+vi.mock('@/server/modules/AgentRuntime/factory', () => ({+ createAgentStateManager: () => ({ createOperationMetadata: mocks.createOperationMetadata }),+ createStreamEventManager: () => ({ publishAgentRuntimeInit: mocks.publishAgentRuntimeInit }),+}));+vi.mock('@/server/services/agentQuota', () => ({+ AgentQuotaService: vi.fn(function () {+ return {+ planDeviceRouting: vi.fn().mockResolvedValue(null),+ resolveDeviceRowId: async (id?: string) => (id ? `row-${id}` : undefined),+ };+ }),+}));+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ dispatchAgentRun: mocks.dispatchAgentRun,+ executeToolCall: vi.fn().mockResolvedValue({ success: true }),+ readDeviceSystemInfo: vi.fn(),+ },+}));+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: mocks.resolveDeviceDispatchAuthorizationFailure,+}));+vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findByDeviceId: vi.fn().mockResolvedValue(undefined),+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));+vi.mock('@/server/services/sandbox/session', () => ({+ resolveSandboxSessionConfig: mocks.resolveSandboxSessionConfig,+}));+vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({+ spawnHeteroSandbox: mocks.spawnHeteroSandbox,+}));+vi.mock('../finalizeHeteroDispatchError', () => ({+ finalizeHeteroDispatchError: mocks.finalizeHeteroDispatchError,+}));+vi.mock('./timeoutConfirmation', () => ({ scheduleTimedOutDispatchConfirmation: vi.fn() }));+vi.mock('../codexDeviceRuntime', () => ({+ selectCodexDeviceDispatch: vi.fn().mockResolvedValue({ kind: 'exec' }),+}));++const shareGate = {+ agentId: 'agent-1',+ canUseDevice: true,+ shareConfig: { showErrorDetails: false, showModelInfo: true },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+} as any;++const createDeps = (): HeteroDispatchDeps =>+ ({+ bindTopicWorkingDirectory: vi.fn().mockResolvedValue(undefined),+ db: {} as any,+ getMarketService: vi.fn().mockRejectedValue(new Error('market unavailable')),+ messageModel: { query: vi.fn().mockResolvedValue([]) } as any,+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),+ topicModel: {+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),+ findById: vi.fn().mockResolvedValue({ metadata: {} }),+ patchRunningOperation: vi.fn().mockResolvedValue(true),+ settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+ } as any,+ userId: 'creator-1',+ withholdGatewayToken: false,+ }) satisfies HeteroDispatchDeps;++const createCtx = (agencyConfig: Record<string, unknown>): ExecRunContext =>+ ({+ agentConfig: { agencyConfig, id: 'agent-1', userId: 'creator-1' },+ assistantMessageId: 'asst-1',+ canUseDevice: true,+ deviceAccessReason: 'owner',+ model: 'model',+ parentMessageId: 'parent-1',+ persistAgentId: 'agent-1',+ prompt: 'hello',+ provider: 'provider',+ resolvedAgentId: 'agent-1',+ runFacts: {} as any,+ shareGate,+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ }) as ExecRunContext;++const input: HeteroDispatchInput = {+ canManageAgent: false,+ heteroType: 'claude-code',+ isPublicWorkspaceAgent: false,+ runAttachments: { audioList: [], fileList: [], imageList: [], videoList: [] },+ selfMessageIds: new Set(),+};++const deviceConfig = {+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.recordStart.mockResolvedValue(true);+ mocks.signHeteroOperationJWT.mockResolvedValue('op-jwt');+ mocks.signUserJWT.mockResolvedValue('visitor-jwt');+ mocks.finalizeHeteroDispatchError.mockResolvedValue(true);+ mocks.resolveDeviceDispatchAuthorizationFailure.mockResolvedValue(undefined);+ mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);+ mocks.dispatchAgentRun.mockResolvedValue({ success: true });+ mocks.publishAgentRuntimeInit.mockResolvedValue('init');+ mocks.createOperationMetadata.mockResolvedValue(undefined);+});++describe('dispatchHeteroAgent — share visitor run', () => {+ it('signs the gateway token for the visitor and stamps the stream owner', async () => {+ const result = await dispatchHeteroAgent(createDeps(), createCtx(deviceConfig), input);++ expect(result).toMatchObject({ success: true, token: 'visitor-jwt' });+ expect(mocks.signUserJWT).toHaveBeenCalledWith('visitor-1');+ expect(mocks.signUserJWT).not.toHaveBeenCalledWith('creator-1');++ const redaction = { showErrorDetails: false, showModelInfo: true };+ expect(mocks.createOperationMetadata).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ streamOwnerUserId: 'visitor-1',+ userId: 'creator-1',+ visitorRedaction: redaction,+ }),+ );+ expect(mocks.publishAgentRuntimeInit).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ streamOwnerUserId: 'visitor-1', visitorRedaction: redaction }),+ );+ });++ it('records the visitor marker on the operation row', async () => {+ await dispatchHeteroAgent(createDeps(), createCtx(deviceConfig), input);++ expect(mocks.recordStart).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({+ agentShareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' },+ }),+ }),+ );+ });++ it('refuses to fall back to the cloud sandbox and never spawns one', async () => {+ const result = await dispatchHeteroAgent(+ createDeps(),+ createCtx({ executionTarget: 'sandbox', heterogeneousProvider: { type: 'claude-code' } }),+ input,+ );++ expect(mocks.spawnHeteroSandbox).not.toHaveBeenCalled();+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ errorType: ChatErrorType.ShareHeteroDeviceUnavailable }),+ );+ expect(result).toMatchObject({+ error: ChatErrorType.ShareHeteroDeviceUnavailable,+ success: false,+ });+ });++ // A later heteroIngest worker reads the stream owner and redaction back from+ // this metadata; without it the creator's unredacted stream would be served.+ it('does not dispatch when the stream owner metadata cannot be persisted', async () => {+ mocks.createOperationMetadata.mockRejectedValue(new Error('redis down'));++ const result = await dispatchHeteroAgent(createDeps(), createCtx(deviceConfig), input);++ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.publishAgentRuntimeInit).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ errorType: ChatErrorType.ServerAgentRuntimeError }),+ );+ expect(result).toMatchObject({ success: false });+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex bb12e6884bb..e9a8b4d42f3 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -3,7 +3,7 @@ import {isRemoteHeterogeneousType,} from '@lobechat/heterogeneous-agents';import type { ExecAgentResult } from '@lobechat/types';-import { resolveHeterogeneousRuntimeConfig } from '@lobechat/types';+import { ChatErrorType, resolveHeterogeneousRuntimeConfig } from '@lobechat/types';import { nanoid } from '@lobechat/utils';import debug from 'debug';@@ -73,6 +73,20 @@ const dispatchHeteroAgentImpl = async (} = input;const isRemoteHetero = isRemoteHeterogeneousType(heteroType);+ const { shareGate } = ctx;+ // A share visitor's run executes as the creator but streams only to the+ // visitor: the gateway registers the op under this id, the token it returns+ // is the visitor's, and `streamOwnerUserId` on the op metadata is what tells+ // the ingest/finish requests (other processes) to redact for a visitor.+ const shareStream = shareGate+ ? {+ streamOwnerUserId: shareGate.visitorUserId,+ visitorRedaction: {+ showErrorDetails: shareGate.shareConfig.showErrorDetails,+ showModelInfo: shareGate.shareConfig.showModelInfo,+ },+ }+ : undefined;// Same structured shape as the built-in path (`op_{ts}_{agentId}_{topicId}_{rand}`)// so hetero ops aren't visually distinct bare nanoids in the trace/op tables.const operationId =@@ -104,7 +118,9 @@ const dispatchHeteroAgentImpl = async (// also an authentication prerequisite: every callback// re-authorizes its operation token against this exact principal. Do not// mint a token or dispatch/spawn when persistence fails.- const completionLifecycle = new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId);+ const completionLifecycle = new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId, {+ includeShareVisitor: deps.includeShareVisitor,+ });const operationPersisted = await traceHeteroStage('record_start', () =>completionLifecycle.recordStart({requireReservation: !!input.reservedOperationId,@@ -114,6 +130,11 @@ const dispatchHeteroAgentImpl = async (maxSteps,metadata: {_hooks: serializedHooks,+ // Read back by heteroIngest / heteroFinish, which run in other+ // requests and must scope to (and settle) the visitor's rows.+ ...(shareGate && {+ agentShareVisitor: { shareId: shareGate.shareId, visitorUserId: shareGate.visitorUserId },+ }),assistantMessageId,heterogeneousRuntimeConfig: runtimeConfig,},@@ -234,7 +255,9 @@ const dispatchHeteroAgentImpl = async (// dispatch settles and unregisters it, so the caller learns whether this// failure was already announced to its own surfaces.const terminalReported = hookDispatcher.canDeliver(operationId, 'onComplete');- await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId).completeOperation(+ await new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId, {+ includeShareVisitor: deps.includeShareVisitor,+ }).completeOperation({agentId: persistAgentId,assistantMessageId,@@ -294,19 +317,22 @@ const dispatchHeteroAgentImpl = async (// callAgent has no metadata row, the callback 401s, and the parent// operation is never resumed (stays parked until the inactivity// watchdog abandons it).- const persistOperationMetadata = async () => {+ const persistOperationMetadata = async (): Promise<boolean> => {try {await traceHeteroStage('operation_metadata', () =>createAgentStateManager().createOperationMetadata(operationId, {...(topicStartOwnerOperationId && {mirrorToOperationId: topicStartOwnerOperationId,}),+ ...shareStream,userId: deps.userId,workspaceId: deps.workspaceId,}),);+ return true;} catch (err) {log('execAgent: failed to persist hetero operation metadata: %O', err);+ return false;}};@@ -332,7 +358,9 @@ const dispatchHeteroAgentImpl = async (canUseDevice,deviceAccessReason,heteroType,- persistOperationMetadata,+ persistOperationMetadata: async () => {+ await persistOperationMetadata();+ },prompt,remoteDeviceId,remoteDeviceUserId,@@ -374,14 +402,28 @@ const dispatchHeteroAgentImpl = async (// Best-effort: a stream-manager/Redis failure must never block dispatch —// the init only powers reconnect, not the run. `createStreamEventManager`// probes Redis synchronously, so guard construction too, not just publish.+ // A share run's stream owner and redaction live only in this metadata: a+ // later heteroIngest worker reads them back, and without them it would+ // publish the creator's unredacted stream. So a share run that cannot+ // persist them does not dispatch.+ const metadataPersisted = await persistOperationMetadata();+ if (shareGate && !metadataPersisted) {+ const message = 'Share run metadata could not be persisted';+ return failHeteroDispatch(+ deps,+ run,+ { detail: message, errorType: ChatErrorType.ServerAgentRuntimeError, message },+ { error: ChatErrorType.ServerAgentRuntimeError, message },+ );+ }try {- await persistOperationMetadata();await traceHeteroStage('stream_init', () =>createStreamEventManager().publishAgentRuntimeInit(operationId, {agentId: resolvedAgentId,assistantMessageId,heteroType,mirrorToOperationId: topicStartOwnerOperationId,+ ...shareStream,topicId,userId: deps.userId,}),@@ -391,6 +433,24 @@ const dispatchHeteroAgentImpl = async (}const heteroPlan = deviceHeteroPlan!;+ // `setupTurn` already refused a share run whose device is not online; this+ // keeps the sandbox (creator JWT + GitHub token in a box the visitor's+ // prompt controls) out of reach even if routing changed in between.+ if (shareGate && heteroPlan.kind !== 'device' && heteroPlan.kind !== 'device-wakeable') {+ return failHeteroDispatch(+ deps,+ run,+ {+ detail: ChatErrorType.ShareHeteroDeviceUnavailable,+ errorType: ChatErrorType.ShareHeteroDeviceUnavailable,+ message: ChatErrorType.ShareHeteroDeviceUnavailable,+ },+ {+ error: ChatErrorType.ShareHeteroDeviceUnavailable,+ message: ChatErrorType.ShareHeteroDeviceUnavailable,+ },+ );+ }const cliDispatchParams = {agentConfig,appContext,@@ -443,7 +503,9 @@ const dispatchHeteroAgentImpl = async (let gatewayToken: string | undefined;if (!deps.withholdGatewayToken) {try {- gatewayToken = await traceHeteroStage('sign_gateway_token', () => signUserJWT(deps.userId));+ gatewayToken = await traceHeteroStage('sign_gateway_token', () =>+ signUserJWT(shareGate?.visitorUserId ?? deps.userId),+ );} catch {// non-critical}diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.tsindex 61197e7d88c..7388f8c5089 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts@@ -282,13 +282,30 @@ describe('prepareHeteroRun — overlapping reads', () => {]);});- it('never resolves pasted images for a share visitor', async () => {- const { deps } = createDeps();+ it('never resolves pasted images or the GitHub credential for a share visitor', async () => {+ // A share run skips the GitHub read, so the barrier would never open.+ const { credsGet, deps, messageModel, topicModel } = createDeps();+ messageModel.query.mockResolvedValue([]);+ topicModel.findById.mockResolvedValue({ metadata: {} });+ mocks.getResumeSessionId.mockResolvedValue(undefined);+ mocks.signHeteroOperationJWT.mockResolvedValue('jwt');- const prepared = await prepareHeteroRun(deps, { ...ctx, shareGate: {} }, input, 'op-1');+ const prepared = await prepareHeteroRun(+ deps,+ { ...ctx, shareGate: { shareId: 'share-1', visitorUserId: 'visitor-1' } },+ input,+ 'op-1',+ );expect(mocks.resolveInlineImages).not.toHaveBeenCalled();expect(prepared.heteroParams.imageList).toBeUndefined();+ expect(deps.getMarketService).not.toHaveBeenCalled();+ expect(credsGet).not.toHaveBeenCalled();+ expect(mocks.signHeteroOperationJWT).toHaveBeenCalledWith(+ expect.objectContaining({+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],+ }),+ );});it('dispatches without pasted images when resolving them fails', async () => {diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex 04af97fca8d..c1c430560ee 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -88,8 +88,14 @@ export const prepareHeteroRun = async (selfMessageIds,} = input;- // Read resume session id for next-turn continuity.+ const { shareGate } = ctx;+ // Read resume session id for next-turn continuity. A share visitor's topic+ // is hidden from a default-scoped read, so the visitor scope is needed to+ // find the session the previous turn recorded.const heteroService = new HeterogeneousAgentService(deps.db, deps.userId, {+ shareVisitor: shareGate+ ? { shareId: shareGate.shareId, visitorUserId: shareGate.visitorUserId }+ : undefined,workspaceId: deps.workspaceId,});const isChannelOperation = ctx.trigger === 'channel' && input.reservedOperationId === operationId;@@ -110,6 +116,7 @@ export const prepareHeteroRun = async (capabilities: heteroOperationCapabilities(prompt, {channel: isChannelOperation,ownerBotTurn: isOwnerBotOperation,+ shareVisitor: !!shareGate,taskId: operationTaskId,// A scheduled run replays the user's own message off history, so it has// no fresh user row; server-started `chat` deliveries have none either.@@ -134,6 +141,9 @@ export const prepareHeteroRun = async (const githubCredKey =agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';const resolveGithubToken = async (): Promise<string | undefined> => {+ // The creator's (or workspace's) GitHub credential is never handed to a+ // run a share visitor drives.+ if (shareGate) return;try {const marketService = await deps.getMarketService();// Inside a workspace, the GitHub cred must come from the workspace's shared@@ -304,20 +314,22 @@ export const prepareHeteroRun = async (: pageSelections?.length? formatPageSelections(pageSelections): undefined;- const agentSystemContext = withConversationGoalPrompt(- joinSystemContext(- providerContext,- projectContext,- viewedTaskContext,- selectionContext,- isChannelOperation- ? CHANNEL_INSTRUCTIONS- : isOwnerBotOperation- ? BOT_CHANNEL_MESSAGING_INSTRUCTIONS- : undefined,- ),- prompt,+ const baseSystemContext = joinSystemContext(+ providerContext,+ projectContext,+ viewedTaskContext,+ selectionContext,+ isChannelOperation+ ? CHANNEL_INSTRUCTIONS+ : isOwnerBotOperation+ ? BOT_CHANNEL_MESSAGING_INSTRUCTIONS+ : undefined,);+ // A share visitor gets no goal capability (see `heteroOperationCapabilities`),+ // so a `/goal` prompt must not add goal instructions either.+ const agentSystemContext = shareGate+ ? baseSystemContext+ : withConversationGoalPrompt(baseSystemContext, prompt);const systemContext = buildCloudHeteroContext({agentSystemContext,conversationHistory: resumeSessionId ? undefined : conversationHistory,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.shareGate.test.tsnew file mode 100644index 00000000000..5766e9542c8--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.shareGate.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest';++import { resolveHeteroRouting } from './routing';++vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ findWakeableManagedDevices: vi.fn().mockResolvedValue([]),+}));++const deps = { db: {}, resolveDeviceWorkspaceId: vi.fn(), userId: 'creator' } as any;+const input = {+ canManageAgent: false,+ heteroType: 'claude-code',+ isPublicWorkspaceAgent: false,+} as any;+// No device is bound: the only place left for a Claude Code run is the sandbox.+const agentConfig = { agencyConfig: { executionTarget: 'sandbox' }, userId: 'creator' } as any;++describe('resolveHeteroRouting — share visitor', () => {+ it('routes a deviceless Claude Code agent to the cloud sandbox without a share gate', async () => {+ const routing = await resolveHeteroRouting(deps, { agentConfig, canUseDevice: true }, input);++ expect(routing.deviceHeteroPlan?.kind).toBe('sandbox');+ });++ it('never resolves to the cloud sandbox for a share visitor', async () => {+ const routing = await resolveHeteroRouting(+ deps,+ { agentConfig, canUseDevice: true, shareGate: { canUseDevice: true } as any },+ input,+ );++ expect(routing.deviceHeteroPlan?.kind).not.toBe('sandbox');+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.tsindex 7afd98d3520..9659f590158 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.ts@@ -15,7 +15,7 @@ import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';*/export const resolveHeteroRouting = async (deps: HeteroDispatchDeps,- ctx: Pick<ExecRunContext, 'agentConfig' | 'canUseDevice'>,+ ctx: Pick<ExecRunContext, 'agentConfig' | 'canUseDevice' | 'shareGate'>,input: Pick<HeteroDispatchInput,| 'canManageAgent'@@ -28,7 +28,7 @@ export const resolveHeteroRouting = async (| 'requestedDeviceId'>,) => {- const { agentConfig, canUseDevice } = ctx;+ const { agentConfig, canUseDevice, shareGate } = ctx;const {canManageAgent,effectiveRequestedDeviceId,@@ -89,7 +89,9 @@ export const resolveHeteroRouting = async (clientExecutionAvailable: false,isHetero: true,requestedDeviceId,- sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),+ // A share visitor's run never falls back to the cloud sandbox: it would+ // hold the creator's credentials in a box the visitor's prompt controls.+ sandboxExecutionAvailable: !shareGate && supportsCloudHeterogeneousSandbox(heteroType),trigger: requestTrigger,wakeableDeviceIds: wakeableCliDevices.map((device) => device.deviceId),};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.tsindex 6cf0d01039d..0b37100a462 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts@@ -27,6 +27,11 @@ export interface HeteroDispatchDeps {getMarketService: (options?: {sandboxStorage: NonNullable<SandboxSessionConfig['claim']>;}) => Promise<MarketService>;+ /**+ * A share visitor run: its topic and messages are visitor rows, which the+ * models hide unless opted in, so settling the run must opt in too.+ */+ includeShareVisitor?: boolean;messageModel: MessageModel;resolveDeviceWorkspaceId: (deviceId: string | undefined) => Promise<string | undefined>;topicModel: TopicModel;diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.tsindex 3cfa5fc4d9d..e0645f50a0c 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts@@ -70,3 +70,17 @@ describe('heteroOperationCapabilities', () => {expect(heteroOperationCapabilities('fix the build', {})).not.toContain('acceptance:evidence');});});++describe('heteroOperationCapabilities for a share visitor', () => {+ it.each([+ ['a /goal prompt', '/goal ship the report', { userTurn: true }],+ ['a task', 'do the step', { taskId: 'task_1', userTurn: true }],+ ['a channel', 'read the discussion', { channel: true, ownerBotTurn: true }],+ ])('grants only the run callbacks for %s', (_, prompt, options) => {+ expect(heteroOperationCapabilities(prompt, { ...options, shareVisitor: true })).toEqual([+ 'hetero:ingest',+ 'hetero:finish',+ 'hetero:intervention:read',+ ]);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.tsindex be8a2a299e6..78a757a55cd 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts@@ -40,21 +40,29 @@ export const heteroOperationCapabilities = (channel?: boolean;/** The run answers a bot message its owner sent (`botContext.isOwner`). */ownerBotTurn?: boolean;+ /**+ * A share visitor drives the run. It gets only the run's own callbacks:+ * a goal or acceptance round it created would belong to the creator.+ */+ shareVisitor?: boolean;taskId?: string;/** The run answers a message the user sent: a chat turn or one they scheduled. */userTurn?: boolean;} = {},-): HeteroOperationCapability[] => [- 'hetero:ingest',- ...(options.channel- ? (['channel:read', 'channel:message'] as const)- : options.ownerBotTurn- ? (['channel:message'] as const)- : []),- 'hetero:finish',- 'hetero:intervention:read',- ...(isGoalPrompt(prompt) || (options.userTurn && !options.channel && !options.taskId)- ? (['goal:manage'] as const)- : []),- ...(options.taskId ? (['acceptance:evidence'] as const) : []),-];+): HeteroOperationCapability[] =>+ options.shareVisitor+ ? ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read']+ : [+ 'hetero:ingest',+ ...(options.channel+ ? (['channel:read', 'channel:message'] as const)+ : options.ownerBotTurn+ ? (['channel:message'] as const)+ : []),+ 'hetero:finish',+ 'hetero:intervention:read',+ ...(isGoalPrompt(prompt) || (options.userTurn && !options.channel && !options.taskId)+ ? (['goal:manage'] as const)+ : []),+ ...(options.taskId ? (['acceptance:evidence'] as const) : []),+ ];diff --git a/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.ts b/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.tsnew file mode 100644index 00000000000..f334c175c75--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/shareHeteroGate.ts@@ -0,0 +1,92 @@+import { isHeterogeneousAgentModelId } from '@lobechat/const';+import type { LobeChatDatabase } from '@lobechat/database';+import type { LobeAgentAgencyConfig, RequestTrigger } from '@lobechat/types';+import { ChatErrorType } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { resolveExecutionPlan } from '@/helpers/executionTarget';+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';++import type { AgentShareGate } from '../shareGate';++/**+ * Heterogeneous runtimes a share visitor may run, on a device the share grants+ * them. Both run as a local CLI on that device; platform agents (OpenClaw /+ * Hermes) and the other CLIs have no visitor-scoped dispatch.+ */+const SHARE_VISITOR_HETERO_TYPES = new Set<string>(['claude-code', 'codex']);++export interface AssertShareHeteroAllowedParams {+ agencyConfig?: LobeAgentAgencyConfig;+ db: LobeChatDatabase;+ heterogeneousType?: string;+ model: string;+ /** The creator, whose devices the run uses. */+ ownerUserId: string;+ requestedDeviceId?: string;+ shareGate?: AgentShareGate;+ trigger?: string;+ workspaceId?: string;+}++/**+ * Share-visitor fail-closed gate for heterogeneous agents, checked BEFORE any+ * topic/message row is written (and so before the visitor's topic quota is+ * spent). A visitor may run Claude Code / Codex only when the share grants+ * them the Agent's device (`shareGate.canUseDevice`), and only there: the CLI+ * then has a shell on the creator's machine, which is exactly what that grant+ * hands over. Every other heterogeneous runtime, and every visitor without the+ * grant, is refused.+ *+ * The run goes to the Agent's device or nowhere — never the cloud sandbox,+ * which would hold creator credentials in a box the visitor's prompt+ * controls. An offline or unset device is a clear refusal the visitor can+ * retry, instead of a failed turn counted against the topic.+ *+ * Returns the device the share run goes to, so the dispatch routes there too:+ * an `auto` Agent's single online device is found only here, because the+ * dispatch does not look at online devices.+ */+export const assertShareHeteroAllowed = async ({+ agencyConfig,+ db,+ heterogeneousType,+ model,+ ownerUserId,+ requestedDeviceId,+ shareGate,+ trigger,+ workspaceId,+}: AssertShareHeteroAllowedParams): Promise<string | undefined> => {+ if (!shareGate) return;+ const type = heterogeneousType ?? (isHeterogeneousAgentModelId(model) ? model : undefined);+ if (!type) return;+ if (!shareGate.canUseDevice || !SHARE_VISITOR_HETERO_TYPES.has(type))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: ChatErrorType.ShareHeterogeneousAgentUnsupported,+ });++ // Online devices are passed in so an `auto` Agent with one online device+ // resolves to it.+ const onlineDeviceIds = (await getScopedOnlineDevices(db, ownerUserId, workspaceId))+ .filter((device) => device.online)+ .map((device) => device.deviceId);+ const plan = resolveExecutionPlan({+ agencyConfig,+ canUseDevice: true,+ clientExecutionAvailable: false,+ isHetero: true,+ onlineDeviceIds,+ requestedDeviceId,+ sandboxExecutionAvailable: false,+ trigger: trigger as RequestTrigger | undefined,+ });+ if (plan.kind !== 'device')+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: ChatErrorType.ShareHeteroDeviceUnavailable,+ });++ return plan.deviceId;+};diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 4a96445fcec..cd46ea0a882 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -14,7 +14,6 @@ import type {} from '@lobechat/types';import {agentShareFileAccessScope,- ChatErrorType,ordinaryFileAccessScope,resolveHeterogeneousModelOverride,resolveHeterogeneousProviderTopicModel,@@ -47,6 +46,7 @@ import type { InternalExecAgentParams } from '../types';import { buildNewTopicMetadata } from './newTopicMetadata';import { createUserTurnAnchor } from './resolveUserMessageParentId';import { createStageTracer, openStageMark } from './sendTracing';+import { assertShareHeteroAllowed } from './shareHeteroGate';import { resolveTurnProjectId, withProjectSandbox } from './topicProject';import { buildUserTurnMetadata } from './userTurnMetadata';@@ -552,22 +552,30 @@ export const setupTurn = async (: providerOverride;let topicEditingGroupId: string | undefined;- // Share-visitor fail-closed gate — reject a heterogeneous (Claude Code /- // Codex / …) agent BEFORE any topic/message row is written. Heterogeneous- // agents are not available for shared visitor runs, even when the share- // grants device access (`shareGate.canUseDevice`): the hetero dispatch path- // signs its gateway token for the run's user (the creator) and registers no- // visitor stream owner, so opening it would hand the visitor creator account- // access. Checked here (using the agent-level config, before any- // topic-pinned model override) rather than at the later hetero-detection- // site (`isHeteroAgent`) so it runs ahead of ALL row creation, not just the- // message rows.- if (shareGate && (heterogeneousProvider?.type || isHeterogeneousAgentModelId(model))) {- throw new TRPCError({- code: 'FORBIDDEN',- message: ChatErrorType.ShareHeterogeneousAgentUnsupported,+ // Share visitors run Claude Code / Codex only on the granted device. Checked+ // against the agent-level config before any row is written, and re-asserted+ // once a reused topic's pinned model and device are applied.+ const assertShareHetero = async (runModel: string) => {+ const shareDeviceId = await assertShareHeteroAllowed({+ agencyConfig: agentConfig.agencyConfig,+ db: deps.db,+ heterogeneousType: heterogeneousProvider?.type,+ model: runModel,+ ownerUserId: deps.userId,+ requestedDeviceId: resolvedRequestedDeviceId,+ shareGate,+ trigger,+ workspaceId: deps.workspaceId,});- }+ // Route the dispatch to the device the gate selected (an `auto` Agent's+ // single online device), which the dispatch would not find on its own.+ // Only the dispatch gets it: pinning the topic to an automatic pick would+ // keep a later turn on that device after it goes offline and another one+ // is online.+ if (shareDeviceId && !resolvedRequestedDeviceId && !isFixedExecutionTargetSelection)+ resolvedRequestedDeviceId = shareDeviceId;+ };+ await assertShareHetero(model);const assertProjectDirectoryAccess = () => {if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))@@ -836,14 +844,9 @@ export const setupTurn = async (log('execAgent: routing topic %s to its bound device %s', topicId, topicPinnedDeviceId);}- // Re-assert the share restriction after topic overrides are applied.- // Heterogeneous agents are not available for shared visitor runs (see above).- if (shareGate && isHeterogeneousAgentModelId(model)) {- throw new TRPCError({- code: 'FORBIDDEN',- message: ChatErrorType.ShareHeterogeneousAgentUnsupported,- });- }+ // Re-assert the share restriction after topic overrides are applied: a+ // topic pin can switch the run to another heterogeneous runtime or device.+ await assertShareHetero(model);// A builder conversation edits exactly one agent, stamped on the topic when// it was created. Continuations rebuilt from the durable operation (approvaldiff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.mdindex 07c0672b6d9..8c891d411e9 100644--- a/apps/server/src/services/aiAgent/shareGate/README.md+++ b/apps/server/src/services/aiAgent/shareGate/README.md@@ -72,9 +72,11 @@ tool does not ship):device(s). A visitor executing arbitrary commands or driving a livebrowser session on the CREATOR's own machine is a far larger blast radiusthan any single data store, so they are never offered through the tool- picker. They are granted only by `shareConfig.deviceAccess` (`all`, or- `allowlist` matching the visitor's verified email), an explicit creator- choice resolved once per gate by `resolveShareVisitorDeviceAccess` into+ picker. They are granted only by `shareConfig.deviceAccess: 'allowlist'`+ naming the visitor in `deviceAllowUserIds`, and only while the visitor is+ still in the address book of the Agent's scope (personal contacts, or the+ workspace's members and external contacts). There is no "every visitor"+ value. The explicit creator choice is resolved once per gate by `resolveShareVisitorDeviceAccess` into`canUseDevice` and re-applied at dispatch. The same grant admitsdevice-only MCP servers (which still need their own tool grant). The deviceis always the Agent's configured execution environment; a visitor never@@ -82,10 +84,9 @@ tool does not ship):engine's device tools (`DEVICE_TOOL_IDENTIFIERS`, so computer use too)except the `lobe-remote-device` picker: with it the visitor's model couldlist and activate the creator's other machines, so it stays default-denied- even under the grant. Heterogeneous agents- (Claude Code / Codex) stay unavailable even with the grant: their dispatch- path signs the gateway token for the creator and registers no visitor- stream owner, so `setupTurn` rejects them for every share run.+ even under the grant. The same grant lets the visitor run a heterogeneous+ Agent (Claude Code / Codex) on that device; without it the run is refused,+ and a share run never falls back to the cloud sandbox.- `lobe-web-onboarding`: reads and WRITES the creator's own onboarding`SOUL.md` document and persona.diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.tsindex f100df1fa8c..f8a5ab5675e 100644--- a/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.test.ts@@ -1,73 +1,79 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { UserModel } from '@/database/models/user';+import { ContactModel } from '@/database/models/contact';import type { LobeChatDatabase } from '@/database/type';-import { resolveShareVisitorDeviceAccess } from './deviceAccess';+import { resolveShareVisitorDeviceAccess, type ShareDeviceAccessSubject } from './deviceAccess';-vi.mock('@/database/models/user', () => ({ UserModel: { findById: vi.fn() } }));+const { filterAddressBookPeople, isChannelEnabled } = vi.hoisted(() => ({+ filterAddressBookPeople: vi.fn(),+ isChannelEnabled: vi.fn(),+}));+vi.mock('@/server/services/channel/featureGate', () => ({ isChannelEnabled }));+vi.mock('@/database/models/contact', () => ({+ ContactModel: vi.fn(function () {+ return { filterAddressBookPeople };+ }),+}));const db = {} as LobeChatDatabase;-const findById = vi.mocked(UserModel.findById);-const visitor = (email: string | null, emailVerified: boolean) =>- findById.mockResolvedValue({ email, emailVerified, id: 'visitor-1' } as any);+const share = (+ shareConfig: ShareDeviceAccessSubject['shareConfig'],+ workspaceId: string | null = null,+): ShareDeviceAccessSubject => ({ ownerId: 'owner', shareConfig, workspaceId });describe('resolveShareVisitorDeviceAccess', () => {- beforeEach(() => findById.mockReset());-- it('denies by default and under `none`', async () => {- expect(await resolveShareVisitorDeviceAccess(db, {}, 'visitor-1')).toBe(false);- expect(await resolveShareVisitorDeviceAccess(db, { deviceAccess: 'none' }, 'visitor-1')).toBe(- false,- );- expect(findById).not.toHaveBeenCalled();- });-- it('grants every visitor under `all` without a user lookup', async () => {- expect(await resolveShareVisitorDeviceAccess(db, { deviceAccess: 'all' }, 'visitor-1')).toBe(- true,- );- expect(findById).not.toHaveBeenCalled();+ beforeEach(() => {+ filterAddressBookPeople.mockReset();+ isChannelEnabled.mockReset().mockResolvedValue(true);+ vi.mocked(ContactModel).mockClear();});- it('grants a listed visitor whose email is verified, case-insensitively', async () => {- visitor('[email protected]', true);+ it('denies by default, under `none`, and for a stored legacy `all`', async () => {+ expect(await resolveShareVisitorDeviceAccess(db, share({}), 'visitor-1')).toBe(false);expect(- await resolveShareVisitorDeviceAccess(- db,- { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },- 'visitor-1',- ),- ).toBe(true);- });-- it('denies a listed email that is not verified', async () => {- visitor('[email protected]', false);+ await resolveShareVisitorDeviceAccess(db, share({ deviceAccess: 'none' }), 'visitor-1'),+ ).toBe(false);expect(- await resolveShareVisitorDeviceAccess(- db,- { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },- 'visitor-1',- ),+ await resolveShareVisitorDeviceAccess(db, share({ deviceAccess: 'all' as any }), 'visitor-1'),).toBe(false);+ expect(filterAddressBookPeople).not.toHaveBeenCalled();});- it('denies an unlisted visitor and an empty allowlist', async () => {- visitor('[email protected]', true);- expect(- await resolveShareVisitorDeviceAccess(- db,- { deviceAccess: 'allowlist', deviceAllowEmails: ['[email protected]'] },- 'visitor-1',- ),- ).toBe(false);+ it('denies an unlisted visitor without reading the address book', async () => {+ const config = { deviceAccess: 'allowlist', deviceAllowUserIds: ['bob'] } as const;+ expect(await resolveShareVisitorDeviceAccess(db, share(config), 'visitor-1')).toBe(false);expect(- await resolveShareVisitorDeviceAccess(- db,- { deviceAccess: 'allowlist', deviceAllowEmails: [] },- 'visitor-1',- ),+ await resolveShareVisitorDeviceAccess(db, share({ deviceAccess: 'allowlist' }), 'visitor-1'),).toBe(false);+ expect(filterAddressBookPeople).not.toHaveBeenCalled();+ });++ it('grants a listed visitor only while they are in the scope address book', async () => {+ const config = { deviceAccess: 'allowlist', deviceAllowUserIds: ['visitor-1'] } as const;++ filterAddressBookPeople.mockResolvedValue(['visitor-1']);+ expect(await resolveShareVisitorDeviceAccess(db, share(config, 'ws-1'), 'visitor-1')).toBe(+ true,+ );+ // The book is the share owner's scope, not the visitor's.+ expect(ContactModel).toHaveBeenCalledWith(db, 'owner', 'ws-1');+ expect(filterAddressBookPeople).toHaveBeenCalledWith(['visitor-1']);++ // Removed from contacts (or left the workspace) after being listed.+ filterAddressBookPeople.mockResolvedValue([]);+ expect(await resolveShareVisitorDeviceAccess(db, share(config), 'visitor-1')).toBe(false);+ });++ it('denies a listed contact while contacts are off for the owner', async () => {+ const config = { deviceAccess: 'allowlist', deviceAllowUserIds: ['visitor-1'] } as const;+ filterAddressBookPeople.mockResolvedValue(['visitor-1']);+ isChannelEnabled.mockResolvedValue(false);++ expect(await resolveShareVisitorDeviceAccess(db, share(config, 'ws-1'), 'visitor-1')).toBe(+ false,+ );+ expect(isChannelEnabled).toHaveBeenCalledWith('owner');});});diff --git a/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts b/apps/server/src/services/aiAgent/shareGate/deviceAccess.tsindex 111066c2e59..ad37f3f111e 100644--- a/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts+++ b/apps/server/src/services/aiAgent/shareGate/deviceAccess.ts@@ -1,8 +1,9 @@import debug from 'debug';-import { UserModel } from '@/database/models/user';+import { ContactModel } from '@/database/models/contact';import type { AgentShareConfig } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { isChannelEnabled } from '@/server/services/channel/featureGate';import { DEVICE_TOOL_IDENTIFIERS, REMOTE_DEVICE_TOOL_IDENTIFIERS } from '../deviceToolRegistry';@@ -27,47 +28,52 @@ export const SHARE_DEVICE_BUILTIN_IDENTIFIERS: ReadonlySet<string> = new Set(export const isShareDeviceBuiltin = (identifier: string) =>SHARE_DEVICE_BUILTIN_IDENTIFIERS.has(identifier);+/** The share fields the device decision reads: its config and the scope that owns its address book. */+export interface ShareDeviceAccessSubject {+ ownerId: string;+ shareConfig: Pick<AgentShareConfig, 'deviceAccess' | 'deviceAllowUserIds'>;+ workspaceId?: string | null;+}+/*** Whether `visitorUserId` may run on the shared agent's execution environment.** The only place `shareConfig.deviceAccess` is interpreted; every share-gate* builder calls it so a fresh turn and a deferred init decide alike.*- * `allowlist` matches the visitor's account email only when it is verified:- * an unverified address is a claim anyone can make at sign-up, and the grant- * hands over the creator's machine. Deployments that never verify email- * therefore fail closed under `allowlist`; `all` still works there.+ * `allowlist` grants a listed visitor only while they are still in the+ * address book of the Agent's scope (`ContactModel.filterAddressBookPeople`):+ * the owner's personal contacts, or the workspace's members and external+ * contacts. The list was checked against the same book when written; checking+ * again here makes removing a contact, or leaving the workspace, revoke the+ * grant without anyone editing the share. The address book exists only while+ * Channels are enabled for the owner, so turning them off grants nothing.*/export const resolveShareVisitorDeviceAccess = async (db: LobeChatDatabase,- shareConfig: Pick<AgentShareConfig, 'deviceAccess' | 'deviceAllowEmails'>,+ share: ShareDeviceAccessSubject,visitorUserId: string,): Promise<boolean> => {- switch (shareConfig.deviceAccess) {- case 'all': {- return true;- }- case 'allowlist': {- const allowEmails = shareConfig.deviceAllowEmails;- if (!allowEmails?.length) {- log('allowlist denied visitor %s: the list is empty', visitorUserId);- return false;- }+ const { deviceAccess, deviceAllowUserIds } = share.shareConfig;+ if (deviceAccess !== 'allowlist') return false;- const visitor = await UserModel.findById(db, visitorUserId);- if (!visitor?.email || !visitor.emailVerified) {- // The most likely creator complaint ("I listed them but it doesn't- // work"), so it gets its own line; never log the address itself.- log('allowlist denied visitor %s: no verified account email', visitorUserId);- return false;- }+ if (!deviceAllowUserIds?.includes(visitorUserId)) {+ log('allowlist denied visitor %s: not listed', visitorUserId);+ return false;+ }- const listed = allowEmails.includes(visitor.email.trim().toLowerCase());- if (!listed) log('allowlist denied visitor %s: email not listed', visitorUserId);- return listed;- }- default: {- return false;- }+ if (!(await isChannelEnabled(share.ownerId))) {+ log('allowlist denied visitor %s: contacts are off for the owner', visitorUserId);+ return false;}++ const [inBook] = await new ContactModel(+ db,+ share.ownerId,+ share.workspaceId,+ ).filterAddressBookPeople([visitorUserId]);+ // The most likely creator complaint ("I listed them but it doesn't work"),+ // so it gets its own line.+ if (!inBook) log('allowlist denied visitor %s: no longer in the address book', visitorUserId);+ return !!inBook;};diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.tsindex 7cd875eb1f8..2dc71790abe 100644--- a/apps/server/src/services/channel/ChannelCoordinator.ts+++ b/apps/server/src/services/channel/ChannelCoordinator.ts@@ -93,7 +93,7 @@ export class ChannelCoordinator {if (!spend.allowed) throw new Error('This shared Agent reached its monthly usage limit');return {agentId,- canUseDevice: await resolveShareVisitorDeviceAccess(this.db, share.shareConfig, requesterId),+ canUseDevice: await resolveShareVisitorDeviceAccess(this.db, share, requesterId),shareConfig: share.shareConfig,shareId: share.shareId,visitorUserId: requesterId,diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex e9d5f5b8625..1ea04743189 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -25,6 +25,7 @@ import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory'import { shouldRecordGatewayError } from '@/server/modules/AgentRuntime/gatewayErrorRecord';import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';+import type { OperationCompletionShareVisitor } from '@/server/services/agentRuntime/CompletionLifecycle/types';import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';import { createDefaultSnapshotStore } from '@/server/services/agentRuntime/snapshotStore';import { releaseHeteroSteers } from '@/server/services/aiAgent/steerQueue/hetero';@@ -178,6 +179,13 @@ export interface HeterogeneousAgentServiceOptions {agentOperationModel?: AgentOperationModel;/** Inject a pre-built persistence handler (used by tests). */persistenceHandler?: HeterogeneousPersistenceHandler;+ /**+ * The share visitor this run belongs to (from the operation row the dispatch+ * stamped). A visitor's topic and messages are hidden from default-scoped+ * models, so without it every write of the run matches nothing; it also+ * marks the completion as a share run.+ */+ shareVisitor?: OperationCompletionShareVisitor;/** Inject a snapshot store (used by tests); defaults to the env-resolved store. */snapshotStore?: ISnapshotStore | null;/**@@ -222,6 +230,7 @@ export class HeterogeneousAgentService {private readonly streamEventManager: IStreamEventManager;private readonly topicModel: TopicModel;private readonly traceRecorder: HeteroTraceRecorder;+ private readonly shareVisitor?: OperationCompletionShareVisitor;private readonly userId: string;private readonly workspaceId?: string;@@ -237,9 +246,12 @@ export class HeterogeneousAgentService {this.queuedFollowUpStarter = options.startQueuedFollowUp;this.agentOperationModel =options.agentOperationModel ?? new AgentOperationModel(db, userId, workspaceId);- this.messageModel = new MessageModel(db, userId, workspaceId);+ this.shareVisitor = options.shareVisitor;+ const visitorScope = { includeShareVisitor: !!options.shareVisitor };+ this.messageModel = new MessageModel(db, userId, workspaceId, undefined, visitorScope);this.streamEventManager = options.streamEventManager ?? createStreamEventManager();- this.topicModel = options.topicModel ?? new TopicModel(db, userId, workspaceId);+ this.topicModel =+ options.topicModel ?? new TopicModel(db, userId, workspaceId, undefined, visitorScope);this.traceRecorder = new HeteroTraceRecorder(options.snapshotStore !== undefined ? options.snapshotStore : createDefaultSnapshotStore(),);@@ -723,7 +735,9 @@ export class HeterogeneousAgentService {// and on success the delivery-checker card + verify gate run against the task's// plan. `completeOperation` owns the (formerly hand-rolled) synthetic-state// build, so the goal+reply turns and trace aggregates are mapped in ONE place.- await new CompletionLifecycle(this.db, this.userId, this.workspaceId).completeOperation(+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId, {+ includeShareVisitor: !!this.shareVisitor,+ }).completeOperation({agentId,assistantMessageId,@@ -737,6 +751,7 @@ export class HeterogeneousAgentService {orchestrationRole,provider: totals?.provider,serializedHooks,+ shareVisitor: this.shareVisitor,stepCount: totals?.stepCount ?? null,topicId,usage: {diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 74655e8d98d..b35c70a1a7a 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -739,12 +739,22 @@"share.settings.permissions.allowReadMemoryHint": "The Agent may draw on your long-term memory while answering a visitor.","share.settings.permissions.desc": "What a visitor’s run may read, and what the visitor gets to see back.","share.settings.permissions.deviceAccess": "Execution environment",- "share.settings.permissions.deviceAccessHint": "Lets visitors use this Agent’s execution environment to run commands and read or write files there.",- "share.settings.permissions.deviceAccessOption.all": "All visitors",- "share.settings.permissions.deviceAccessOption.allowlist": "Specific visitors",+ "share.settings.permissions.deviceAccessConfirm.commands": "They can run any command and read or write any file on the machine this Agent runs on, including through Claude Code or Codex.",+ "share.settings.permissions.deviceAccessConfirm.intro": "People you add will run this Agent on your execution environment:",+ "share.settings.permissions.deviceAccessConfirm.limits": "The monthly spend cap does not limit that usage. Only the turn limit per topic does.",+ "share.settings.permissions.deviceAccessConfirm.ok": "Allow listed people",+ "share.settings.permissions.deviceAccessConfirm.subscription": "Claude Code and Codex runs use the model subscription signed in on that machine.",+ "share.settings.permissions.deviceAccessConfirm.title": "Let people use your execution environment?",+ "share.settings.permissions.deviceAccessHint": "Lets the people you pick run this Agent on its execution environment, including Claude Code and Codex. Everyone else can’t run a Claude Code or Codex Agent.",+ "share.settings.permissions.deviceAccessOption.allowlist": "People from contacts","share.settings.permissions.deviceAccessOption.none": "No visitors",- "share.settings.permissions.deviceAllowEmailsHint": "Matches the visitor’s verified account email. No one can use it until you add one.",- "share.settings.permissions.deviceAllowEmailsPlaceholder": "Enter the visitors’ account emails, then press Enter",+ "share.settings.permissions.deviceAllowContactsUnavailable": "Only people in your contacts can be added, and contacts aren’t available for your account yet.",+ "share.settings.permissions.deviceAllowHint": "Only people in this Agent’s contacts can be added. Removing someone from contacts also removes their access.",+ "share.settings.permissions.deviceAllowLimitReached": "You can add up to {{limit}} people.",+ "share.settings.permissions.deviceAllowLoadFailed": "Couldn’t load your contacts. Refresh to try again.",+ "share.settings.permissions.deviceAllowNoContacts": "Your contacts are empty. Add people to your contacts first.",+ "share.settings.permissions.deviceAllowPlaceholder": "Choose people from your contacts",+ "share.settings.permissions.deviceAllowUnlisted": "No longer in contacts, so they can’t use it: {{names}}. They’re removed the next time you edit this list.","share.settings.permissions.showErrorDetails": "Show error details to visitors","share.settings.permissions.showErrorDetailsHint": "Off by default: visitors see a generic failure notice instead of raw error text.","share.settings.permissions.showModelInfo": "Show which model is used",@@ -839,7 +849,8 @@"share.visitor.access.signInTitle": "Sign in to continue","share.visitor.errors.fileUnavailable": "One of the attachments is no longer available. Remove it and try again.","share.visitor.errors.generic": "Failed to send the message. Please try again.",- "share.visitor.errors.heterogeneousUnsupported": "This shared agent isn't available for visitor chat yet. Please contact its owner.",+ "share.visitor.errors.heteroDeviceUnavailable": "The creator's device is offline. Try again later.",+ "share.visitor.errors.heterogeneousUnsupported": "This agent can run for you only with its creator's permission. Ask its creator for access.","share.visitor.errors.insufficientBudget": "This shared agent has run out of budget. Please contact its owner.","share.visitor.errors.promptTooLong": "Your message is too long. Please shorten it to {{max}} characters or fewer and try again.","share.visitor.errors.providerNotSupported": "This shared agent is not available right now. Please contact its owner.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex a60f1b69f13..7e92bce06b0 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -739,12 +739,22 @@"share.settings.permissions.allowReadMemoryHint": "助手在回答访客时可以参考你的长期记忆。","share.settings.permissions.desc": "访客的运行可以读取什么,以及访客能看到什么。","share.settings.permissions.deviceAccess": "执行环境",- "share.settings.permissions.deviceAccessHint": "允许访客使用这个助手的执行环境,在上面执行命令、读写文件。",- "share.settings.permissions.deviceAccessOption.all": "所有访客",- "share.settings.permissions.deviceAccessOption.allowlist": "指定访客",+ "share.settings.permissions.deviceAccessConfirm.commands": "他们可以在这个助手运行的机器上执行任意命令、读写任意文件,包括通过 Claude Code 或 Codex。",+ "share.settings.permissions.deviceAccessConfirm.intro": "你添加的人会在你的执行环境上运行这个助手:",+ "share.settings.permissions.deviceAccessConfirm.limits": "这部分用量不受每月消费上限限制,只受每个话题的轮次上限约束。",+ "share.settings.permissions.deviceAccessConfirm.ok": "允许指定的人",+ "share.settings.permissions.deviceAccessConfirm.subscription": "Claude Code 和 Codex 会使用那台机器上登录的模型订阅。",+ "share.settings.permissions.deviceAccessConfirm.title": "允许他人使用你的执行环境?",+ "share.settings.permissions.deviceAccessHint": "允许你选中的人在这个助手的执行环境上运行它,包括 Claude Code 和 Codex。其他人无法运行 Claude Code 或 Codex 助手。",+ "share.settings.permissions.deviceAccessOption.allowlist": "通讯录中的人","share.settings.permissions.deviceAccessOption.none": "不允许",- "share.settings.permissions.deviceAllowEmailsHint": "按访客已验证的账号邮箱匹配。添加邮箱前,没有访客能使用。",- "share.settings.permissions.deviceAllowEmailsPlaceholder": "输入访客的账号邮箱,按回车添加",+ "share.settings.permissions.deviceAllowContactsUnavailable": "只能添加通讯录中的人,你的账号暂未开通通讯录。",+ "share.settings.permissions.deviceAllowHint": "只能添加这个助手所在通讯录中的人。把某人移出通讯录,也会同时收回其权限。",+ "share.settings.permissions.deviceAllowLimitReached": "最多可添加 {{limit}} 人。",+ "share.settings.permissions.deviceAllowLoadFailed": "通讯录加载失败,请刷新重试。",+ "share.settings.permissions.deviceAllowNoContacts": "通讯录里还没有人,请先添加联系人。",+ "share.settings.permissions.deviceAllowPlaceholder": "从通讯录选择",+ "share.settings.permissions.deviceAllowUnlisted": "已不在通讯录,无法使用:{{names}}。下次修改名单时会被移除。","share.settings.permissions.showErrorDetails": "向访客展示错误详情","share.settings.permissions.showErrorDetailsHint": "默认关闭:访客只会看到一句通用的失败提示,而不是原始报错。","share.settings.permissions.showModelInfo": "展示使用的模型",@@ -839,7 +849,8 @@"share.visitor.access.signInTitle": "登录后继续","share.visitor.errors.fileUnavailable": "有附件已不可用,请移除后重试。","share.visitor.errors.generic": "消息发送失败,请重试。",- "share.visitor.errors.heterogeneousUnsupported": "该分享助手暂不支持访客对话,请联系创建者。",+ "share.visitor.errors.heteroDeviceUnavailable": "创建者的设备当前离线,请稍后再试。",+ "share.visitor.errors.heterogeneousUnsupported": "该助手需要创建者授权后才能为你运行,请联系创建者开通。","share.visitor.errors.insufficientBudget": "该分享助手的额度已用尽,请联系创建者。","share.visitor.errors.promptTooLong": "消息太长了,请精简到 {{max}} 个字符以内后重试。","share.visitor.errors.providerNotSupported": "该分享助手当前不可用,请联系创建者。",diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsindex 9696366f931..41e0c05f8cd 100644--- a/packages/const/src/agentShare.ts+++ b/packages/const/src/agentShare.ts@@ -238,7 +238,7 @@ export const isShareToolApiGranted = (};/**- * Upper bound on `AgentShareConfig.deviceAllowEmails`. Device access is meant- * for a handful of trusted people; a larger audience should use `all`.+ * Upper bound on `AgentShareConfig.deviceAllowUserIds`. Device access hands+ * over the creator's machine, so it is meant for a handful of trusted people.*/-export const AGENT_SHARE_DEVICE_ALLOW_EMAILS_LIMIT = 100;+export const AGENT_SHARE_DEVICE_ALLOW_USERS_LIMIT = 100;diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex 35aa9e1dbca..6ff451b8899 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -390,7 +390,7 @@ describe('AgentShareModel', () => {allowReadMemory: false,demoCases: [],deviceAccess: 'none',- deviceAllowEmails: [],+ deviceAllowUserIds: [],featuredWorkIds: [],maxFileStorage: 512 * 1024 * 1024,maxTopicsPerVisitor: 5,@@ -410,7 +410,7 @@ describe('AgentShareModel', () => {allowCreatorViewSessions: true,allowReadMemory: true,deviceAccess: 'allowlist',- deviceAllowEmails: ['[email protected]'],+ deviceAllowUserIds: ['user_alice'],maxFileStorage: 256 * 1024 * 1024,maxTopicsPerVisitor: 10,maxTurnsPerTopic: 40,diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.tsindex b63763e151a..aff56d20700 100644--- a/packages/database/src/models/__tests__/contact.test.ts+++ b/packages/database/src/models/__tests__/contact.test.ts@@ -434,6 +434,50 @@ describe('people to message', () => {});});+describe('address book of a scope', () => {+ const dave = 'contact-test-dave';+ const ids = (people: { id: string }[]) => people.map((person) => person.id);++ it('holds personal contacts only, and only for their owner', async () => {+ const { requestId } = await aliceModel.sendRequest(bob);+ await bobModel.acceptRequest(requestId);++ expect(ids(await aliceModel.listAddressBookPeople())).toEqual([bob]);+ expect(await aliceModel.filterAddressBookPeople([bob, carol, alice])).toEqual([bob]);+ expect(await carolModel.filterAddressBookPeople([bob])).toEqual([]);+ });++ it('holds every member and every external contact of a workspace', async () => {+ await serverDB.insert(users).values({ id: dave, username: 'dave' });+ // Alice invites Bob; Carol, who did not invite him, still finds him in the workspace's book.+ const { requestId } = await aliceInTeam.sendRequest(bob);+ await bobModel.acceptRequest(requestId);++ expect(ids(await carolInTeam.listAddressBookPeople())).toEqual([alice, bob]);+ expect(await carolInTeam.filterAddressBookPeople([alice, bob, dave, carol])).toEqual([+ alice,+ bob,+ ]);+ // Personal contacts never count for a workspace.+ const { requestId: personal } = await carolModel.sendRequest(dave);+ await new ContactModel(serverDB, dave).acceptRequest(personal);+ expect(await carolInTeam.filterAddressBookPeople([dave])).toEqual([]);+ });++ it('drops someone who leaves the workspace or the address book', async () => {+ await serverDB+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(eq(workspaceMembers.userId, carol));+ expect(await aliceInTeam.filterAddressBookPeople([carol])).toEqual([]);++ const { requestId } = await aliceModel.sendRequest(bob);+ await bobModel.acceptRequest(requestId);+ await aliceModel.removeUser(bob);+ expect(await aliceModel.filterAddressBookPeople([bob])).toEqual([]);+ });+});+describe('search', () => {it('finds people by exact username, case-insensitively, with their relation', async () => {const [result] = await aliceModel.search('@BOB');diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 6db3a0e63b7..9a9d3f7d3ce 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -46,7 +46,7 @@ const normalizeAgentShareConfig = (allowReadMemory: config?.allowReadMemory ?? DEFAULT_AGENT_SHARE_CONFIG.allowReadMemory,demoCases: config?.demoCases ?? [],deviceAccess: config?.deviceAccess ?? 'none',- deviceAllowEmails: config?.deviceAllowEmails ?? [],+ deviceAllowUserIds: config?.deviceAllowUserIds ?? [],featuredWorkIds: config?.featuredWorkIds ?? [],maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,maxTopicsPerVisitor:diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.tsindex 9f085fad71c..813a8f6679e 100644--- a/packages/database/src/models/contact.ts+++ b/packages/database/src/models/contact.ts@@ -349,6 +349,79 @@ export class ContactModel {return { hasMore: people.length > options.limit, people: people.slice(0, options.limit) };};+ /**+ * Everyone in this scope's address book except the caller: personal contacts; in a workspace,+ * its other members and every external contact of it, whoever invited them. Unlike+ * {@link listPeople} this ignores who the caller is in the scope, because it answers for a+ * resource the scope owns (an Agent's share), not for the caller's own conversations.+ */+ listAddressBookPeople = async (): Promise<ContactUserProfile[]> => {+ if (!this.workspaceId) {+ const rows = await this.db+ .select(userProfileColumns)+ .from(userContacts)+ .innerJoin(users, eq(users.id, userContacts.contactUserId))+ .where(and(this.userEntryWhere(), eq(userContacts.userId, this.userId)))+ .orderBy(desc(userContacts.createdAt));+ return rows;+ }++ const [members, externals] = await Promise.all([+ this.db+ .select(userProfileColumns)+ .from(workspaceMembers)+ .innerJoin(users, eq(users.id, workspaceMembers.userId))+ .where(+ and(+ eq(workspaceMembers.workspaceId, this.workspaceId),+ isNull(workspaceMembers.deletedAt),+ not(eq(workspaceMembers.userId, this.userId)),+ ),+ )+ .orderBy(users.fullName, users.username),+ this.listExternals(),+ ]);+ return [...members, ...externals.map((item) => item.user)];+ };++ /**+ * The subset of `userIds` that {@link listAddressBookPeople} would list, without loading it:+ * the check an access grant re-runs on every use, so removing someone from the address book+ * (or from the workspace) ends what was granted to them.+ */+ filterAddressBookPeople = async (userIds: string[]): Promise<string[]> => {+ const candidates = [...new Set(userIds)].filter((id) => id !== this.userId);+ if (candidates.length === 0) return [];++ const entries = await this.db+ .select({ userId: userContacts.contactUserId })+ .from(userContacts)+ .where(+ and(+ this.userEntryWhere(),+ inArray(userContacts.contactUserId, candidates),+ // Personal: my own entries. Workspace: any member's external contact; the paired+ // member side of the same pair is a member, matched below instead.+ this.workspaceId ? not(this.contactIsMember()) : eq(userContacts.userId, this.userId),+ ),+ );+ const members = this.workspaceId+ ? await this.db+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, this.workspaceId),+ isNull(workspaceMembers.deletedAt),+ inArray(workspaceMembers.userId, candidates),+ ),+ )+ : [];++ const found = new Set([...entries, ...members].map((row) => row.userId));+ return candidates.filter((id) => found.has(id));+ };+relationTo = async (otherUserId: string): Promise<ContactRelation> => {if (otherUserId === this.userId) return 'self';if ((await this.scopeRole()) === 'member' && (await this.isMember(otherUserId)))diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.tsindex 74e458e8a93..eb42b30a10f 100644--- a/packages/database/src/models/message/visitor.ts+++ b/packages/database/src/models/message/visitor.ts@@ -203,6 +203,7 @@ const VISITOR_SAFE_ERROR_TYPES = new Set<string>([ChatErrorType.ShareTopicLimitExceeded,ChatErrorType.ShareSpendLimitExceeded,ChatErrorType.ShareHeterogeneousAgentUnsupported,+ ChatErrorType.ShareHeteroDeviceUnavailable,ChatErrorType.AgentShareProviderNotSupported,]);diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex 6e01b4ceb37..a420637db27 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -4,7 +4,7 @@ import { index, integer, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzleimport { timestamps } from './_helpers';import { agents } from './agent';-export type AgentShareDeviceAccess = 'all' | 'allowlist' | 'none';+export type AgentShareDeviceAccess = 'allowlist' | 'none';export interface AgentShareConfig {/**@@ -22,27 +22,29 @@ export interface AgentShareConfig {demoCases?: AgentShareDemoCase[];/*** Which visitors may run on the Agent's configured execution environment- * (its bound or auto-selected device), mirroring an IM bot's `devicePolicy`:+ * (its bound or auto-selected device):*- * - `none` (default): no visitor reaches a device; device tools are dropped.- * - `all`: every signed-in visitor runs on the Agent's device.- * - `allowlist`: only visitors whose VERIFIED account email is listed in- * {@link deviceAllowEmails}.+ * - `none` (default): no visitor reaches a device; device tools are dropped+ * and a heterogeneous (Claude Code / Codex) Agent refuses the run.+ * - `allowlist`: only the people in {@link deviceAllowUserIds} who are+ * still in the Agent's address book. They get the device tools and, for a+ * heterogeneous Agent, run it on the device.*- * The visitor never picks the device — it always follows the Agent's own- * execution-environment setting. Resolved per run by- * `resolveShareVisitorDeviceAccess`. Heterogeneous (Claude Code / Codex)- * agents stay unavailable to visitors under every value.+ * There is no "every visitor" value: a stranger never reaches the creator's+ * machine. The visitor never picks the device — it always follows the+ * Agent's own execution-environment setting. Resolved per run by+ * `resolveShareVisitorDeviceAccess`.*/deviceAccess?: AgentShareDeviceAccess;/**- * Lower-cased account emails allowed to use the device when- * {@link deviceAccess} is `allowlist`; ignored otherwise. Stored as emails- * rather than user ids so the creator can authorize someone before they sign- * up, and so the settings page never needs a user lookup that would reveal- * whether an email has a LobeHub account.+ * User ids allowed to use the device when {@link deviceAccess} is+ * `allowlist`; ignored otherwise. Each must be in the address book of the+ * Agent's scope when written (personal contacts for a personal Agent; the+ * workspace's members and external contacts for a workspace Agent), and is+ * checked against it again on every run, so removing a contact revokes the+ * grant without editing the share.*/- deviceAllowEmails?: string[];+ deviceAllowUserIds?: string[];/** Ordered, explicitly selected creator Works for this share's public profile. */featuredWorkIds?: string[];/**diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 3c35201aeb0..1ffa0bd6e4a 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -960,14 +960,32 @@ export default {'The Agent may draw on your long-term memory while answering a visitor.','share.settings.permissions.deviceAccess': 'Execution environment','share.settings.permissions.deviceAccessHint':- 'Lets visitors use this Agent’s execution environment to run commands and read or write files there.',- 'share.settings.permissions.deviceAccessOption.all': 'All visitors',- 'share.settings.permissions.deviceAccessOption.allowlist': 'Specific visitors',+ 'Lets the people you pick run this Agent on its execution environment, including Claude Code and Codex. Everyone else can’t run a Claude Code or Codex Agent.',+ 'share.settings.permissions.deviceAccessOption.allowlist': 'People from contacts','share.settings.permissions.deviceAccessOption.none': 'No visitors',- 'share.settings.permissions.deviceAllowEmailsHint':- 'Matches the visitor’s verified account email. No one can use it until you add one.',- 'share.settings.permissions.deviceAllowEmailsPlaceholder':- 'Enter the visitors’ account emails, then press Enter',+ 'share.settings.permissions.deviceAccessConfirm.commands':+ 'They can run any command and read or write any file on the machine this Agent runs on, including through Claude Code or Codex.',+ 'share.settings.permissions.deviceAccessConfirm.intro':+ 'People you add will run this Agent on your execution environment:',+ 'share.settings.permissions.deviceAccessConfirm.limits':+ 'The monthly spend cap does not limit that usage. Only the turn limit per topic does.',+ 'share.settings.permissions.deviceAccessConfirm.ok': 'Allow listed people',+ 'share.settings.permissions.deviceAccessConfirm.subscription':+ 'Claude Code and Codex runs use the model subscription signed in on that machine.',+ 'share.settings.permissions.deviceAccessConfirm.title':+ 'Let people use your execution environment?',+ 'share.settings.permissions.deviceAllowContactsUnavailable':+ 'Only people in your contacts can be added, and contacts aren’t available for your account yet.',+ 'share.settings.permissions.deviceAllowHint':+ 'Only people in this Agent’s contacts can be added. Removing someone from contacts also removes their access.',+ 'share.settings.permissions.deviceAllowLimitReached': 'You can add up to {{limit}} people.',+ 'share.settings.permissions.deviceAllowLoadFailed':+ 'Couldn’t load your contacts. Refresh to try again.',+ 'share.settings.permissions.deviceAllowNoContacts':+ 'Your contacts are empty. Add people to your contacts first.',+ 'share.settings.permissions.deviceAllowPlaceholder': 'Choose people from your contacts',+ 'share.settings.permissions.deviceAllowUnlisted':+ 'No longer in contacts, so they can’t use it: {{names}}. They’re removed the next time you edit this list.','share.settings.permissions.desc':'What a visitor’s run may read, and what the visitor gets to see back.','share.settings.permissions.showErrorDetails': 'Show error details to visitors',@@ -1051,8 +1069,10 @@ export default {'share.visitor.errors.fileUnavailable':'One of the attachments is no longer available. Remove it and try again.','share.visitor.errors.generic': 'Failed to send the message. Please try again.',+ 'share.visitor.errors.heteroDeviceUnavailable':+ "The creator's device is offline. Try again later.",'share.visitor.errors.heterogeneousUnsupported':- "This shared agent isn't available for visitor chat yet. Please contact its owner.",+ "This agent can run for you only with its creator's permission. Ask its creator for access.",'share.visitor.errors.insufficientBudget':'This shared agent has run out of budget. Please contact its owner.','share.visitor.errors.promptTooLong':diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex b94bde508cd..bdd1da18cc2 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -14,6 +14,7 @@ export const ChatErrorType = {ShareTopicLimitExceeded: 'ShareTopicLimitExceeded', // Visitor hit shareConfig.maxTopicsPerVisitor on this shared agentShareSpendLimitExceeded: 'ShareSpendLimitExceeded', // Shared agent reached shareConfig.monthlySpendLimit for the current month — recovers on the next resetShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitors+ ShareHeteroDeviceUnavailable: 'ShareHeteroDeviceUnavailable', // The shared Claude Code / Codex agent's device is offline or not set — visitor can retry laterAgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitorsSupervisorDecisionFailed: 'SupervisorDecisionFailed', // Supervisor decision failedAgentConcurrencyLimitExceeded: 'AgentConcurrencyLimitExceeded', // The user already has as many agent runs in flight as allowed — recovers when one finishesdiff --git a/src/services/agentShare.ts b/src/services/agentShare.tsindex e3eacdb9ff4..b5dfcc69130 100644--- a/src/services/agentShare.ts+++ b/src/services/agentShare.ts@@ -49,6 +49,11 @@ class AgentShareService {return lambdaClient.agentShare.listGrantableSkills.query({ agentId });}+ /** People the creator may grant the execution environment to: the Agent scope's address book. */+ async listDeviceGrantablePeople(agentId: string) {+ return lambdaClient.agentShare.listDeviceGrantablePeople.query({ agentId });+ }+async updateShareConfig(agentId: string, config: AgentShareConfigPatchInput) {return lambdaClient.agentShare.updateShareConfig.mutate({ agentId, config });}diff --git a/src/services/shareChat.ts b/src/services/shareChat.tsindex 8885086f738..61831ed2604 100644--- a/src/services/shareChat.ts+++ b/src/services/shareChat.ts@@ -196,6 +196,25 @@ class ShareChatService {});}+ /**+ * The visitor counterpart of `aiAgent.submitHeteroIntervention`: answers a+ * question Claude Code / Codex asked during the visitor's run.+ */+ async submitHeteroIntervention(+ shareId: string,+ topicId: string,+ resolution: Omit<+ Parameters<typeof lambdaClient.shareChat.submitHeteroIntervention.mutate>[0],+ 'shareId' | 'topicId'+ >,+ ) {+ return await lambdaClient.shareChat.submitHeteroIntervention.mutate({+ ...resolution,+ shareId,+ topicId,+ });+ }+async refreshGatewayToken(shareId: string, topicId: string): Promise<{ token: string }> {return await lambdaClient.shareChat.refreshGatewayToken.query({ shareId, topicId });}diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex dbdedf8c3d8..875a892cf9f 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -11,7 +11,6 @@ import { toast } from '@lobehub/ui';import { t } from 'i18next';import { type ChatInputEditor } from '@/features/ChatInput';-import { lambdaClient } from '@/libs/trpc/client';import {type AgentInterventionSourceAction,aiAgentService,@@ -37,6 +36,7 @@ import {shouldUseGatewayResume as resolveGatewayResume,} from './gatewayResume';import { createInterventionProjection } from './interventionProjection';+import { submitRemoteHeteroIntervention } from './remoteHeteroIntervention';/*** Actions for controlling conversation operations like cancellation and error handling@@ -1730,7 +1730,10 @@ export class ConversationControlActionImpl {optimisticContext,);if (actionType === 'submit') {- await this.setInterventionAnswers(toolMessageId, payload ?? {}, optimisticContext);+ // A share visitor cannot write the creator's rows; the tool result persists it.+ await this.setInterventionAnswers(toolMessageId, payload ?? {}, optimisticContext, {+ persist: !effectiveContext.agentShareId,+ });}if (this.#discardSettledHeteroQuestion(toolMessageId)) return;@@ -1770,22 +1773,13 @@ export class ConversationControlActionImpl {const resolutionRequestId =this.#heteroResolutionRequestIds.get(resolutionKey) ?? globalThis.crypto.randomUUID();this.#heteroResolutionRequestIds.set(resolutionKey, resolutionRequestId);- await lambdaClient.aiAgent.submitHeteroIntervention.mutate(- actionType === 'submit'- ? {- operationId: remoteOperationId,- resolutionRequestId,- result: payload ?? {},- toolCallId,- }- : {- cancelReason: 'user_cancelled',- cancelled: true,- operationId: remoteOperationId,- resolutionRequestId,- toolCallId,- },- );+ await submitRemoteHeteroIntervention(effectiveContext, {+ actionType,+ operationId: remoteOperationId,+ payload,+ resolutionRequestId,+ toolCallId,+ });}} catch (err) {if (this.#discardSettledHeteroQuestion(toolMessageId)) return;@@ -1854,16 +1848,13 @@ export class ConversationControlActionImpl {toolMessageId: string,answers: Record<string, unknown>,context?: OptimisticUpdateContext,+ { persist = true }: { persist?: boolean } = {},): Promise<void> => {this.#get().internal_dispatchMessage(- {- id: toolMessageId,- key: 'askUserAnswers',- type: 'updatePluginState',- value: answers,- },+ { id: toolMessageId, key: 'askUserAnswers', type: 'updatePluginState', value: answers },context,);+ if (!persist) return;try {const { messageService } = await import('@/services/message');const ctx = this.#get().internal_getConversationContext(context);diff --git a/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.test.ts b/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.test.tsnew file mode 100644index 00000000000..a1357999114--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.test.ts@@ -0,0 +1,60 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { submitRemoteHeteroIntervention } from './remoteHeteroIntervention';++const mocks = vi.hoisted(() => ({ lambdaMutate: vi.fn(), shareSubmit: vi.fn() }));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { aiAgent: { submitHeteroIntervention: { mutate: mocks.lambdaMutate } } },+}));+vi.mock('@/services/shareChat', () => ({+ shareChatService: { submitHeteroIntervention: mocks.shareSubmit },+}));++const base = { operationId: 'op-1', resolutionRequestId: 'req-1', toolCallId: 'tool-1' };+const cancelled = { ...base, cancelReason: 'user_cancelled', cancelled: true };++describe('submitRemoteHeteroIntervention', () => {+ beforeEach(() => vi.clearAllMocks());++ it('routes a share visitor answer through the share endpoint', async () => {+ await submitRemoteHeteroIntervention(+ { agentShareId: 'share-1', topicId: 'topic-1' },+ { ...base, actionType: 'submit', payload: { answer: 'yes' } },+ );++ expect(mocks.shareSubmit).toHaveBeenCalledWith('share-1', 'topic-1', {+ ...base,+ result: { answer: 'yes' },+ });+ expect(mocks.lambdaMutate).not.toHaveBeenCalled();+ });++ it('uses the owner endpoint without a share, defaulting the result to {}', async () => {+ await submitRemoteHeteroIntervention({ topicId: 'topic-1' }, { ...base, actionType: 'submit' });++ expect(mocks.lambdaMutate).toHaveBeenCalledWith({ ...base, result: {} });+ expect(mocks.shareSubmit).not.toHaveBeenCalled();+ });++ it('uses the owner endpoint when a share has no topic yet', async () => {+ await submitRemoteHeteroIntervention(+ { agentShareId: 'share-1' },+ { ...base, actionType: 'submit' },+ );++ expect(mocks.lambdaMutate).toHaveBeenCalled();+ expect(mocks.shareSubmit).not.toHaveBeenCalled();+ });++ it.each(['skip', 'cancel'] as const)('maps %s to a user cancellation', async (actionType) => {+ await submitRemoteHeteroIntervention({ topicId: 'topic-1' }, { ...base, actionType });+ expect(mocks.lambdaMutate).toHaveBeenCalledWith(cancelled);++ await submitRemoteHeteroIntervention(+ { agentShareId: 'share-1', topicId: 'topic-1' },+ { ...base, actionType },+ );+ expect(mocks.shareSubmit).toHaveBeenCalledWith('share-1', 'topic-1', cancelled);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.ts b/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.tsnew file mode 100644index 00000000000..e28575a0e60--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/remoteHeteroIntervention.ts@@ -0,0 +1,39 @@+import type { ConversationContext } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';+import { shareChatService } from '@/services/shareChat';++interface RemoteHeteroResolution {+ actionType: 'submit' | 'skip' | 'cancel';+ operationId: string;+ payload?: Record<string, unknown>;+ resolutionRequestId: string;+ toolCallId: string;+}++/**+ * Publish a question answer to a remote (gateway / device) Claude Code or+ * Codex run. A share visitor's run executes on the creator's account, so the+ * owner-scoped endpoint rejects them; the share endpoint authorizes the+ * visitor's own topic and running operation instead.+ */+export const submitRemoteHeteroIntervention = (+ context: Pick<ConversationContext, 'agentShareId' | 'topicId'>,+ { actionType, operationId, payload, resolutionRequestId, toolCallId }: RemoteHeteroResolution,+) => {+ const resolution =+ actionType === 'submit'+ ? { operationId, resolutionRequestId, result: payload ?? {}, toolCallId }+ : {+ cancelReason: 'user_cancelled' as const,+ cancelled: true,+ operationId,+ resolutionRequestId,+ toolCallId,+ };++ const { agentShareId, topicId } = context;+ return agentShareId && topicId+ ? shareChatService.submitHeteroIntervention(agentShareId, topicId, resolution)+ : lambdaClient.aiAgent.submitHeteroIntervention.mutate(resolution);+};