π€― 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(market): re-mint the trust token for LobeHub Skills in long inline runs (#19982)
Arvin Xu181538040d51
diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.tsindex 6767cb00a40..62775a5b205 100644--- a/apps/server/src/services/market/index.test.ts+++ b/apps/server/src/services/market/index.test.ts@@ -468,6 +468,30 @@ describe('MarketService', () => {});});+ it('should keep error_description when Market rejects the request with a flat auth error', async () => {+ const service = new MarketService();+ const authError = Object.assign(new Error('invalid_trust_token'), {+ errorBody: { error: 'invalid_trust_token', error_description: 'Token expired' },+ status: 401,+ });+ (service as any).market.skills.callTool = vi.fn().mockRejectedValue(authError);++ const result = await service.executeLobehubSkill({+ args: {},+ provider: 'notion',+ toolName: 'notion-fetch',+ });++ expect(result).toEqual({+ content: JSON.stringify({+ error: 'invalid_trust_token',+ error_description: 'Token expired',+ }),+ error: { code: 'invalid_trust_token', message: 'invalid_trust_token: Token expired' },+ success: false,+ });+ });+it('should use a generic failure message when an unsuccessful response has no detail', async () => {const service = new MarketService();const mockCallTool = vi.fn().mockResolvedValue({diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 1f431a77e97..6d5c452166a 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -747,6 +747,24 @@ export class MarketService {const denial = getToolAccessDeniedError(error, err.message);if (denial)return { content: JSON.stringify({ error: denial }), error: denial, success: false };++ // Market's auth middleware answers with a flat OAuth-style body, e.g.+ // `{ error: 'invalid_trust_token', error_description: 'Token expired' }`.+ // Keep the description so the model can tell an expired token from a+ // revoked authorization, and the code so callers can react to it.+ if (typeof skillError === 'string') {+ const description =+ typeof errorBody.error_description === 'string' ? errorBody.error_description : undefined;+ return {+ content: JSON.stringify({ error: skillError, error_description: description }),+ error: {+ code: skillError,+ message: description ? `${skillError}: ${description}` : skillError,+ },+ success: false,+ };+ }+const content = skillError ? JSON.stringify(skillError) : err.message;return {diff --git a/apps/server/src/services/toolExecution/__tests__/trustTokenExpiry.test.ts b/apps/server/src/services/toolExecution/__tests__/trustTokenExpiry.test.tsnew file mode 100644index 00000000000..97e36d265e2--- /dev/null+++ b/apps/server/src/services/toolExecution/__tests__/trustTokenExpiry.test.ts@@ -0,0 +1,164 @@+/**+ * Regression: a LobeHub Skill (github / notion / twitter β¦) started failing with+ * `"invalid_trust_token"` once the executor had been alive for > 5 minutes β+ * the inline step loop keeps one executor alive for a whole `/api/agent/run`+ * invocation (up to 450s), but the trusted-client token was minted only once.+ *+ * Real code under test: BuiltinToolsExecutor β MarketService β trusted-client+ * token minting (real `buildTrustedClientPayload` / `createTrustedClientToken`).+ * Only the network edge (`MarketSDK`) is faked, and the fake applies Market's own+ * server-side rule: decrypt the token and reject it when+ * `now - payload.timestamp > 5 min` with+ * `401 { error: 'invalid_trust_token', error_description: 'Token expired' }`.+ */+import { createDecipheriv, createHash } from 'node:crypto';++import type * as MarketSDKModule from '@lobehub/market-sdk';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { BuiltinToolsExecutor } from '../builtin';+import type { ToolExecutionContext } from '../types';++const SECRET = 'lobehub-market_tcs_repro-secret';+const EXPIRY_MS = 5 * 60 * 1000;++vi.mock('@/envs/app', () => ({+ appEnv: {+ MARKET_TRUSTED_CLIENT_ID: 'lobehub-cloud',+ MARKET_TRUSTED_CLIENT_SECRET: 'lobehub-market_tcs_repro-secret',+ },+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return { getUserSettings: vi.fn(async () => ({})) };+ }),+}));++vi.mock('../serverRuntimes', () => ({+ getServerRuntime: vi.fn(),+ hasServerRuntime: vi.fn().mockReturnValue(false),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn(),+}));++/** Market's validator, mirrored: aes-256-gcm(iv|ciphertext|tag), sha256(secret) key. */+const marketValidate = (token: string) => {+ const raw = Buffer.from(token, 'base64');+ const iv = raw.subarray(0, 12);+ const tag = raw.subarray(raw.length - 16);+ const ciphertext = raw.subarray(12, raw.length - 16);+ const key = createHash('sha256').update(SECRET).digest();+ const decipher = createDecipheriv('aes-256-gcm', key, iv);+ decipher.setAuthTag(tag);+ const payload = JSON.parse(+ Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'),+ );+ return { expired: Date.now() - payload.timestamp > EXPIRY_MS, payload };+};++const market = vi.hoisted(() => ({+ calls: [] as { expired: boolean; token: string }[],+ minted: [] as number[],+ /** Tokens Market rejects regardless of age (e.g. clock skew between hosts). */+ rejectAll: false,+ rejectOnce: new Set<string>(),+}));++vi.mock('@lobehub/market-sdk', async (importOriginal) => {+ const actual = await importOriginal<typeof MarketSDKModule>();++ class FakeMarketSDK {+ skills: { callTool: () => Promise<unknown> };++ constructor(opts: { trustedClientToken?: string }) {+ const token = opts.trustedClientToken!;+ market.minted.push(marketValidate(token).payload.timestamp);+ this.skills = {+ callTool: async () => {+ const { expired } = marketValidate(token);+ market.calls.push({ expired, token });+ const rejectedOnce = market.rejectOnce.delete(token);+ if (market.rejectAll || rejectedOnce || expired) {+ throw new actual.MarketAPIError(401, 'Unauthorized', {+ error: 'invalid_trust_token',+ error_description: 'Token expired',+ });+ }+ return { data: { exitCode: 0, output: 'ok' }, success: true };+ },+ };+ }+ }++ return { ...actual, MarketSDK: FakeMarketSDK };+});++const githubRunCommand = {+ apiName: 'runCommand',+ arguments: '{"command":"gh auth status"}',+ id: 'call-1',+ identifier: 'github',+ source: 'lobehubSkill',+ type: 'default',+} as any;++const context = { topicId: 'tpc_repro', userId: 'user_repro' } as ToolExecutionContext;++describe('LobeHub Skill trust token lifetime vs executor lifetime', () => {+ beforeEach(() => {+ market.calls.length = 0;+ market.minted.length = 0;+ market.rejectAll = false;+ market.rejectOnce.clear();+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-21T14:50:58Z'));+ });++ it('keeps working past 5 minutes inside one executor (one /api/agent/run inline loop)', async () => {+ // One BuiltinToolsExecutor lives for the whole runStep invocation, which the+ // inline step loop keeps alive for up to INLINE_STEP_START_DEADLINE_MS (450s).+ const executor = new BuiltinToolsExecutor({} as any, 'user_repro');++ const first = await executor.execute(githubRunCommand, context);+ expect(first.success).toBe(true);++ vi.advanceTimersByTime(299_000);+ const at299s = await executor.execute(githubRunCommand, context);+ expect(at299s.success).toBe(true);++ vi.advanceTimersByTime(2_000); // 301s after the first token was minted+ const at301s = await executor.execute(githubRunCommand, context);++ expect(at301s).toMatchObject({ success: true });+ // Market never saw an expired token: it was re-minted before the deadline+ expect(market.calls.map(({ expired }) => expired)).toEqual([false, false, false]);+ });++ it('re-mints the token and retries once when Market rejects it as invalid_trust_token', async () => {+ const executor = new BuiltinToolsExecutor({} as any, 'user_repro');+ await executor.execute(githubRunCommand, context);+ market.rejectOnce.add(market.calls[0].token);++ const result = await executor.execute(githubRunCommand, context);++ expect(result.success).toBe(true);+ expect(market.calls).toHaveLength(3);+ expect(market.calls[2].token).not.toBe(market.calls[1].token);+ });++ it('tells the model why the token was rejected when the retry is rejected too', async () => {+ market.rejectAll = true;+ const executor = new BuiltinToolsExecutor({} as any, 'user_repro');++ const result = await executor.execute(githubRunCommand, context);++ expect(result.success).toBe(false);+ expect(market.calls).toHaveLength(2);+ expect(result.content).toContain('invalid_trust_token');+ expect(result.content).toContain('Token expired');+ expect(result.error).toMatchObject({ code: 'invalid_trust_token' });+ });+});diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex 6a007e64557..076f2fb1280 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -19,6 +19,17 @@ import { resolveBuiltinToolWorkIntent } from './workRegistration';const log = debug('lobe-server:builtin-tools-executor');+/**+ * Market rejects a trusted-client token 5 minutes after it was minted, while one+ * executor can outlive that (the inline step loop keeps it for a whole+ * `/api/agent/run` invocation). Rebuild the MarketService β and so re-mint the+ * token β well before the deadline.+ */+const MARKET_SERVICE_MAX_AGE_MS = 4 * 60 * 1000;++/** Market's 401 code for a trusted-client token it refuses (expired, skewed, β¦). */+const INVALID_TRUST_TOKEN = 'invalid_trust_token';+/*** Declared API names for a builtin tool, read from its manifest β the* authoritative source. Runtime instances declare their APIs as prototype@@ -53,15 +64,20 @@ const collectRuntimeApiNames = (runtime: Record<string, any>): string[] => {export class BuiltinToolsExecutor implements IToolExecutor {private db: LobeChatDatabase;private userId: string;- private _marketService?: MarketService;+ private _marketService?: { createdAt: number; service: MarketService };constructor(db: LobeChatDatabase, userId: string) {this.db = db;this.userId = userId;}- private async getMarketService(): Promise<MarketService> {- if (this._marketService) return this._marketService;+ private async getMarketService({ fresh }: { fresh?: boolean } = {}): Promise<MarketService> {+ if (+ !fresh &&+ this._marketService &&+ Date.now() - this._marketService.createdAt < MARKET_SERVICE_MAX_AGE_MS+ )+ return this._marketService.service;let accessToken: string | undefined;try {@@ -72,11 +88,12 @@ export class BuiltinToolsExecutor implements IToolExecutor {// non-fatal β MarketService will fall back to trustedClientToken}- this._marketService = new MarketService({+ const service = new MarketService({accessToken,userInfo: { userId: this.userId },});- return this._marketService;+ this._marketService = { createdAt: Date.now(), service };+ return service;}async execute(@@ -148,16 +165,25 @@ export class BuiltinToolsExecutor implements IToolExecutor {// Route LobeHub Skills to MarketServiceif (source === 'lobehubSkill') {- const marketService = await this.getMarketService();- const result = await marketService.executeLobehubSkill({- args,- context: {- topicId: context.topicId,- },- provider: identifier,- timeoutMs: context.executionTimeoutMs,- toolName: apiName,- });+ const callSkill = (marketService: MarketService) =>+ marketService.executeLobehubSkill({+ args,+ context: {+ topicId: context.topicId,+ },+ provider: identifier,+ timeoutMs: context.executionTimeoutMs,+ toolName: apiName,+ });++ let result = await callSkill(await this.getMarketService());++ // Market refuses the token at its auth middleware, before the skill runs,+ // so re-minting and retrying once cannot repeat a side effect.+ if (result.error?.code === INVALID_TRUST_TOKEN) {+ log('Trust token rejected for %s:%s, retrying with a fresh token', identifier, apiName);+ result = await callSkill(await this.getMarketService({ fresh: true }));+ }if (result.success && isWorkSkillProvider(identifier)) {// Defer Work registration to the agent runtime so the version is written