π€― 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
π fix: read market accessToken from DB in server-side runtimes to prevent 401 error (#16325)
Hardya96e35fa3c18
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 74ee7a83d8c..3242d178534 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -317,7 +317,24 @@ export const buildServerCallLlmContext = async ({let credsListStr = '';if (ctx.userId) {try {- const marketService = new MarketService({ userInfo: { userId: ctx.userId } });+ // Read market accessToken from DB so the server-side runtime can+ // authenticate with the Market API instead of falling back to an+ // anonymous trustedClientToken (which 401s on creds endpoints).+ let marketAccessToken: string | undefined;+ if (ctx.serverDB) {+ try {+ const userModel = new UserModel(ctx.serverDB, ctx.userId);+ const settings = await userModel.getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }+ }++ const marketService = new MarketService({+ accessToken: marketAccessToken,+ userInfo: { userId: ctx.userId },+ });// Inside a workspace, the agent must only see the workspace's shared// organization credentials β personal creds are not visible here.const credsResult = ctx.workspaceIddiff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex c8761c8eaca..e7fad65c0e5 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -21,6 +21,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';+import { UserModel } from '@/database/models/user';import { agentOperations, topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';@@ -631,12 +632,24 @@ const aiAgentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;+ // Read market accessToken from user_settings.market so server-side agent runtime+ // can authenticate with the Market API for creds operations.+ let marketAccessToken: string | undefined;+ try {+ const userModel = new UserModel(ctx.serverDB!, ctx.userId);+ const settings = await userModel.getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }+return opts.next({ctx: {agentRuntimeService: new AgentRuntimeService(ctx.serverDB, ctx.userId, {workspaceId: wsId,}),aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId, {+ marketAccessToken,withholdGatewayToken:ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes),workspaceId: wsId,diff --git a/apps/server/src/routers/lambda/taskTemplate.ts b/apps/server/src/routers/lambda/taskTemplate.tsindex 7c16f22bdde..bae39c73f4b 100644--- a/apps/server/src/routers/lambda/taskTemplate.ts+++ b/apps/server/src/routers/lambda/taskTemplate.ts@@ -3,6 +3,7 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { TaskTemplateService } from '@/server/services/taskTemplate';const listDailyRecommendSchema = z.object({@@ -16,14 +17,16 @@ const templateIdSchema = z.object({templateId: z.number().int().positive(),});+const taskTemplateProcedure = authedProcedure.use(serverDatabase);+export const taskTemplateRouter = router({- dismiss: authedProcedure.input(templateIdSchema).mutation(async () => ({ success: true })),+ dismiss: taskTemplateProcedure.input(templateIdSchema).mutation(async () => ({ success: true })),- listDailyRecommend: authedProcedure+ listDailyRecommend: taskTemplateProcedure.input(listDailyRecommendSchema).query(async ({ input, ctx }) => {try {- const service = new TaskTemplateService(ctx.userId);+ const service = new TaskTemplateService(ctx.userId, ctx.serverDB);const data = await service.listDailyRecommend(input.interestKeys, {count: input.count,locale: input.locale,@@ -40,5 +43,7 @@ export const taskTemplateRouter = router({}}),- recordCreated: authedProcedure.input(templateIdSchema).mutation(async () => ({ success: true })),+ recordCreated: taskTemplateProcedure+ .input(templateIdSchema)+ .mutation(async () => ({ success: true })),});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 90084f57a90..68ab638b850 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -570,7 +570,7 @@ export class AiAgentService {private readonly threadModel: ThreadModel;private readonly topicModel: TopicModel;private readonly agentRuntimeService: AgentRuntimeService;- private readonly marketService: MarketService;+ private _marketService?: MarketService;private readonly composioService: ComposioService;private readonly workspaceId?: string;@@ -586,6 +586,7 @@ export class AiAgentService {db: LobeChatDatabase,userId: string,options?: {+ marketAccessToken?: string;runtimeOptions?: AgentRuntimeServiceOptions;withholdGatewayToken?: boolean;workspaceId?: string;@@ -625,10 +626,37 @@ export class AiAgentService {},workspaceId: wsId,});- this.marketService = new MarketService({ userInfo: { userId } });++ // marketService is used for creds, sandbox, skills etc.+ // Read accessToken from DB; if options.marketAccessToken is provided, use it as override.+ if (options?.marketAccessToken) {+ this._marketService = new MarketService({+ accessToken: options.marketAccessToken,+ userInfo: { userId },+ });+ }this.composioService = new ComposioService({ db, userId, workspaceId: wsId });}+ private async getMarketService(): Promise<MarketService> {+ if (this._marketService) return this._marketService;++ let accessToken: string | undefined;+ try {+ const userModel = new UserModel(this.db, this.userId);+ const settings = await userModel.getUserSettings();+ accessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }++ this._marketService = new MarketService({+ accessToken,+ userInfo: { userId: this.userId },+ });+ return this._marketService;+ }+private async resolveOperationTaskId(idOrIdentifier?: string | null,): Promise<string | undefined> {@@ -2161,11 +2189,12 @@ export class AiAgentService {const githubCredKey =agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';try {+ const marketService = await this.getMarketService();// Inside a workspace, the GitHub cred must come from the workspace's shared// organization credentials, not the operator's personal creds.const credsAccessor = this.workspaceId- ? this.marketService.market.organizations.creds({ workspaceId: this.workspaceId })- : this.marketService.market.creds;+ ? marketService.market.organizations.creds({ workspaceId: this.workspaceId })+ : marketService.market.creds;const list = await credsAccessor.list();const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);if (cred) {@@ -2649,6 +2678,7 @@ export class AiAgentService {// `aiAgent` import. Only this cloud-CLI branch needs it.const { spawnHeteroSandbox } =await import('@/server/services/heterogeneousAgent/sandboxRunner');+ const marketService = await this.getMarketService();// The sandbox authenticates its nested `lh` calls with this JWT. The// narrow `hetero-operation` token (used for the device-dispatch path// above) is rejected by `oidcAuth`, so CC capabilities that hit@@ -2663,7 +2693,7 @@ export class AiAgentService {agentType: heteroType as 'claude-code' | 'codex',args: heteroExecArgs,jwt: sandboxJwt,- marketService: this.marketService,+ marketService,}).catch(async (err) => {// Fire-and-forget: execAgent has already returned `autoStarted`, and// the sandbox never reached the point of calling heteroFinish. Drive@@ -3015,7 +3045,8 @@ export class AiAgentService {// 5c. Fetch LobeHub Skills manifeststry {- lobehubSkillManifests = await this.marketService.getLobehubSkillManifests();+ const marketService = await this.getMarketService();+ lobehubSkillManifests = await marketService.getLobehubSkillManifests();} catch (error) {log('execAgent: failed to fetch lobehub skill manifests: %O', error);}diff --git a/apps/server/src/services/taskTemplate/index.ts b/apps/server/src/services/taskTemplate/index.tsindex 4fb771f03ed..cafb95f9ffd 100644--- a/apps/server/src/services/taskTemplate/index.ts+++ b/apps/server/src/services/taskTemplate/index.ts@@ -10,8 +10,10 @@ import {TASK_TEMPLATE_RECOMMEND_COUNT,TASK_TEMPLATE_RECOMMEND_MAX_COUNT,} from '@lobechat/const';+import type { LobeChatDatabase } from '@lobechat/database';import { z } from 'zod';+import { UserModel } from '@/database/models/user';import { appEnv } from '@/envs/app';import { isTrustedClientEnabled } from '@/libs/trusted-client';import { MarketService } from '@/server/services/market';@@ -111,10 +113,32 @@ const parseTaskTemplateRecommendations = (value: unknown): TaskTemplate[] => {};export class TaskTemplateService {- private marketService: MarketService;+ private marketService?: MarketService;++ constructor(+ private userId: string,+ private db?: LobeChatDatabase,+ ) {}++ private async getMarketService(): Promise<MarketService> {+ if (this.marketService) return this.marketService;++ let accessToken: string | undefined;+ if (this.db) {+ try {+ const userModel = new UserModel(this.db, this.userId);+ const settings = await userModel.getUserSettings();+ accessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }+ }- constructor(private userId: string) {- this.marketService = new MarketService({ userInfo: { userId } });+ this.marketService = new MarketService({+ accessToken,+ userInfo: { userId: this.userId },+ });+ return this.marketService;}async listDailyRecommend(@@ -127,7 +151,8 @@ export class TaskTemplateService {} = {},): Promise<TaskTemplate[]> {try {- const result = await this.marketService.market.taskTemplates.getTaskTemplateRecommendations({+ const marketService = await this.getMarketService();+ const result = await marketService.market.taskTemplates.getTaskTemplateRecommendations({count: clampRecommendationCount(options.count),excludeIds: options.excludeIds,interestKeys,diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex 16f9e8e8ed5..b6ed68dbfbe 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -8,6 +8,7 @@ import {import { detectTruncatedJSON, safeParseJSON } from '@lobechat/utils';import debug from 'debug';+import { UserModel } from '@/database/models/user';import { ComposioService } from '@/server/services/composio';import { MarketService } from '@/server/services/market';@@ -49,14 +50,32 @@ const collectRuntimeApiNames = (runtime: Record<string, any>): string[] => {};export class BuiltinToolsExecutor implements IToolExecutor {- private marketService: MarketService;private db: LobeChatDatabase;private userId: string;+ private _marketService?: MarketService;constructor(db: LobeChatDatabase, userId: string) {this.db = db;this.userId = userId;- this.marketService = new MarketService({ userInfo: { userId } });+ }++ private async getMarketService(): Promise<MarketService> {+ if (this._marketService) return this._marketService;++ let accessToken: string | undefined;+ try {+ const userModel = new UserModel(this.db, this.userId);+ const settings = await userModel.getUserSettings();+ accessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }++ this._marketService = new MarketService({+ accessToken,+ userInfo: { userId: this.userId },+ });+ return this._marketService;}async execute(@@ -107,7 +126,8 @@ export class BuiltinToolsExecutor implements IToolExecutor {// Route LobeHub Skills to MarketServiceif (source === 'lobehubSkill') {- const result = await this.marketService.executeLobehubSkill({+ const marketService = await this.getMarketService();+ const result = await marketService.executeLobehubSkill({args,context: {topicId: context.topicId,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.tsindex 515d4c86fde..7a1b805610e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts@@ -70,7 +70,7 @@ describe('cloudSandboxRuntime', () => {});const { cloudSandboxRuntime } = await import('../cloudSandbox');- const runtime = cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));+ const runtime = await cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));await runtime.runCommand({ command: 'lh agent edit agt_1 -t x', description: 'edit self' });@@ -90,7 +90,7 @@ describe('cloudSandboxRuntime', () => {it('leaves non-shell tools untouched', async () => {const { cloudSandboxRuntime } = await import('../cloudSandbox');- const runtime = cloudSandboxRuntime.factory(buildContext());+ const runtime = await cloudSandboxRuntime.factory(buildContext());await runtime.executeCode({ code: 'print(1)', language: 'python' });@@ -110,7 +110,7 @@ describe('cloudSandboxRuntime', () => {});const { cloudSandboxRuntime } = await import('../cloudSandbox');- const runtime = cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));+ const runtime = await cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));const result = await runtime.runCommand({ command: 'lh agent list', description: 'list' });@@ -126,7 +126,7 @@ describe('cloudSandboxRuntime', () => {});const { cloudSandboxRuntime } = await import('../cloudSandbox');- const runtime = cloudSandboxRuntime.factory(buildContext());+ const runtime = await cloudSandboxRuntime.factory(buildContext());await runtime.exportFile({ path: './out/result.csv' });diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex 11a3cd04e20..f608dfd88e5 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -1,6 +1,7 @@import { CloudSandboxIdentifier, type ISandboxService } from '@lobechat/builtin-tool-cloud-sandbox';import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';+import { UserModel } from '@/database/models/user';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';@@ -61,7 +62,7 @@ const withLhPreprocessing = (* Per-request runtime (needs topicId, userId)*/export const cloudSandboxRuntime: ServerRuntimeRegistration = {- factory: (context) => {+ factory: async (context) => {if (!context.userId || !context.topicId) {throw new Error('userId and topicId are required for Cloud Sandbox execution');}@@ -70,7 +71,20 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {throw new Error('serverDB is required for Cloud Sandbox execution');}- const marketService = new MarketService({ userInfo: { userId: context.userId } });+ // Read market accessToken from DB so server-side sandbox runtime can authenticate.+ let accessToken: string | undefined;+ try {+ const userModel = new UserModel(context.serverDB, context.userId);+ const settings = await userModel.getUserSettings();+ accessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }++ const marketService = new MarketService({+ accessToken,+ userInfo: { userId: context.userId },+ });const fileService = new FileService(context.serverDB, context.userId, context.workspaceId);const sandboxService = createSandboxService({fileService,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex 8ccc37cda3f..60b4a7faafb 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -2,6 +2,7 @@ import { CredsIdentifier, type ICredsService } from '@lobechat/builtin-tool-credimport { CredsExecutionRuntime } from '@lobechat/builtin-tool-creds/executionRuntime';import debug from 'debug';+import { UserModel } from '@/database/models/user';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import { MarketService } from '@/server/services/market';@@ -183,7 +184,20 @@ export const credsRuntime: ServerRuntimeRegistration = {context.workspaceId,);+ // Read market accessToken from DB so server-side creds runtime can authenticate.+ let accessToken: string | undefined;+ if (context.serverDB) {+ try {+ const userModel = new UserModel(context.serverDB, context.userId);+ const settings = await userModel.getUserSettings();+ accessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }+ }+const marketService = new MarketService({+ accessToken,userInfo: { userId: context.userId, workspaceId: context.workspaceId },});const credsService = new ServerCredsService(marketService, context.workspaceId);