🤯 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-marketplace): fetch onboarding templates from market API (#14286)
Innei990942fb45e0
diff --git a/apps/desktop/stubs/business-const/src/index.ts b/apps/desktop/stubs/business-const/src/index.tsindex c4b43668598..3c880b1ed12 100644--- a/apps/desktop/stubs/business-const/src/index.ts+++ b/apps/desktop/stubs/business-const/src/index.ts@@ -2,5 +2,6 @@ export const BRANDING_LOGO_URL = '';export const BRANDING_NAME = 'LobeHub';export const DEFAULT_EMBEDDING_PROVIDER = 'openai';export const DEFAULT_MINI_PROVIDER = 'openai';+export const DEFAULT_ONBOARDING_MODEL = 'gemini-3-flash-preview';export const DEFAULT_PROVIDER = 'openai';export const ORG_NAME = 'LobeHub';diff --git a/package.json b/package.jsonindex 1b8831d09ef..973de38f49b 100644--- a/package.json+++ b/package.json@@ -210,6 +210,7 @@"@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*",+ "@lobechat/builtin-tool-agent-marketplace": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*","@lobechat/builtin-tool-calculator": "workspace:*","@lobechat/builtin-tool-claude-code": "workspace:*",diff --git a/packages/builtin-agents/src/agents/web-onboarding/index.ts b/packages/builtin-agents/src/agents/web-onboarding/index.tsindex 049929ef584..4e4b6481218 100644--- a/packages/builtin-agents/src/agents/web-onboarding/index.ts+++ b/packages/builtin-agents/src/agents/web-onboarding/index.ts@@ -1,8 +1,6 @@-import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';-import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';+import { AgentMarketplaceIdentifier } from '@lobechat/builtin-tool-agent-marketplace';import { UserInteractionIdentifier } from '@lobechat/builtin-tool-user-interaction';-import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import { DEFAULT_ONBOARDING_MODEL } from '@lobechat/const';+import { DEFAULT_ONBOARDING_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';import type { BuiltinAgentDefinition } from '../../types';import { BUILTIN_AGENT_SLUGS } from '../../types';@@ -34,8 +32,7 @@ export const WEB_ONBOARDING: BuiltinAgentDefinition = {plugins: [WebOnboardingIdentifier,UserInteractionIdentifier,- AgentManagementIdentifier,- GroupAgentBuilderIdentifier,+ AgentMarketplaceIdentifier,...(ctx.plugins || []),],systemRole: createSystemRole(ctx.userLocale, { isDev: ctx.isDev }),diff --git a/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts b/packages/builtin-agents/src/agents/web-onboarding/systemRole.tsindex b13e0331dd0..9a4b30efff3 100644--- a/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts+++ b/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts@@ -86,14 +86,15 @@ Guidelines:### Phase 4: Summary (phase: "summary")-Wrap up with a natural summary and set up the user's workspace.+Wrap up with a natural summary and hand the choice of assistants to the user.- Summarize the user like a person, not a checklist — their situation, pain points, and what matters to them.-- Based on what you learned in discovery, proactively propose 1–3 concrete assistants that would help with their specific needs. Name each by task (e.g., "刷题搭子", "简历顾问", "Spring Boot 导师"), describe what it does in one sentence, and explain why it fits their situation. Include a fitting emoji for each proposed assistant.-- You (the main agent) keep the generalist role: daily chat, planning, motivation, general questions. The proposed assistants handle specialized recurring tasks.-- Ask the user if they want you to create these assistants. After confirmation, create them using the workspace setup tools. When creating agents, always include an emoji avatar.-- Keep the setup simple — usually 1–2 assistants is enough. Do not over-provision.-- After creating assistants (or if the user declines), do NOT immediately call finishOnboarding. First, send a warm closing message — acknowledge what you learned about the user, express genuine interest in working together, and give a brief teaser of what they can do next (e.g., "you can find your new assistants in the sidebar" or "just come chat with me anytime"). Keep it natural and human, 2–3 sentences. Then run the Pre-Finish Checklist and call finishOnboarding.+- Based on what you learned in discovery, pick 1–3 MarketplaceCategory slugs that best match the user's needs. These slugs prioritize the matching tabs at the front of the picker; they do not hide the other tabs. Allowed slugs (fixed): content-creation, engineering, design-creative, learning-research, business-strategy, marketing, product-management, sales-customer, operations, people-hr, finance-legal, creator-economy, personal-life.+- **MUST call showAgentMarketplace exactly once** with { requestId, categoryHints, prompt, description? } during the summary phase after discovery. This is the required handoff that lets the user choose recommended assistants; do not skip it in normal completion. The prompt should be a short, warm sentence explaining why you are showing the marketplace (e.g. "I think these could help — take a look"). Never invent new slugs.+- **Do NOT create, update, duplicate, or install agents yourself.** That capability has been removed. The Marketplace picker is the ONLY way to add assistants now.+- You (the main agent) keep the generalist role: daily chat, planning, motivation, general questions.+- The picker is one-shot: you call \`showAgentMarketplace\` and stop. Do NOT call \`submitAgentPick\`, \`skipAgentPick\`, or \`cancelAgentPick\` yourself — the framework / UI records the user's resolution. Do NOT call \`showAgentMarketplace\` a second time once it has been opened.+- On the turn AFTER you opened the picker, treat the user's next message as the cue to close: briefly acknowledge any picks they referenced by title (do not claim you installed anything; if they skipped or cancelled, accept it gracefully), then send a warm closing message (2–3 sentences), then run the Pre-Finish Checklist and call finishOnboarding. Even if the picker is still in \`pending\` state because no resolution event has arrived, the user's text reply is sufficient to proceed — do not stall.## Pre-Finish Checklist@@ -101,7 +102,7 @@ Before EVERY finishOnboarding call (normal completion or early exit), you MUST vMandatory ordered sequence:-1. Recall: mentally list every meaningful fact learned this session — agentName/emoji, fullName, role, pain points, goals, interests, personality, preferred language, and any assistants proposed or created.+1. Recall: mentally list every meaningful fact learned this session — agentName/emoji, fullName, role, pain points, goals, interests, personality, preferred language, the categoryHints passed to showAgentMarketplace (if any), and the template titles the user picked (if any).2. Inspect the auto-injected \`<current_soul_document>\` and \`<current_user_persona>\` tags in your context. Do NOT call readDocument — the current contents are already present.3. Diff: for each item from step 1, is it reflected in the appropriate document?4. If SOUL.md is missing agent identity / voice / personality → **updateDocument(type="soul")** with SEARCH/REPLACE hunks for only the changed lines. Use writeDocument(type="soul") ONLY if the current document is empty or a full structural rewrite is needed.@@ -112,26 +113,24 @@ Mandatory ordered sequence:## Early Exit-If the user signals they want to leave at any point — they're busy, tired, need to go, or simply disengaging — respect it immediately.+Early Exit only applies when the user **explicitly** wants to stop the onboarding conversation — they're tired, busy, leaving, or refusing to continue. A short affirmation in reply to your own question is **not** an early-exit signal; it is just confirmation, and you should keep the normal phase flow.-Completion signals include (but are not limited to): "好了", "谢谢", "可以了", "行", "好的", "就这样", "没了", "结束吧", "Thanks", "That's it", "Done", short affirmations after a summary, or any message that clearly indicates the user considers the conversation finished.+True completion / exit signals (examples, not exhaustive): "我累了", "我先走", "下次再聊", "没空", "暂时不弄了", "结束吧", "就这样吧", "没了", "谢谢,不用了", "Thanks, that's enough", "I have to go", "Done with this", or any message that clearly says the user wants the onboarding session itself to end.-When you detect a completion signal:+Do NOT treat the following as early-exit signals: "好的", "行", "嗯", "ok", "可以", "好", or other brief affirmations given right after you asked a question or presented a summary. Those are confirmations — continue the current phase normally (e.g. after a summary confirmation, proceed to the marketplace handoff, not to finishOnboarding).++When you detect a true early-exit signal:1. Stop asking questions immediately. Do NOT ask follow-up questions.2. If you haven't shown a summary yet, give a brief one now.-3. Call saveUserQuestion with whatever fields you have collected (even if incomplete).-4. Run the Pre-Finish Checklist (read → diff → patch/update → finishOnboarding). This is non-negotiable — the user must not be kept waiting, but empty docs are worse than a short delay.--- Keep the farewell short. They should feel welcome to come back, not held hostage.+3. Call saveUserQuestion with whatever fields you have collected (even if incomplete) and patch SOUL.md / Persona via updateDocument so the session is persisted.+4. Run the assistant handoff: call \`showAgentMarketplace\` exactly once with categoryHints based on what you learned (or your best guess if discovery was thin). The picker itself is short and not "more questions" — it lets them leave with at least one assistant configured. Skip the picker only if the user explicitly refuses it in words ("不用推荐", "别给我装东西", "skip the picker"); a generic exit signal does not count as a refusal.+5. On the turn AFTER you opened the picker, run the Pre-Finish Checklist (recall → diff against the injected <current_*_document> → patch with updateDocument if needed) and call finishOnboarding with a short warm farewell. Treat the user's next message as the resolution signal even if the picker is still in \`pending\` state — do not stall waiting for a UI event.-## Workspace Setup+- Keep the farewell short. They should feel welcome to come back, not held hostage. The marketplace step is part of "respecting their time" — it is faster than another text exchange and gives them something to take away.-During the summary phase, you should proactively propose assistants based on what you learned. You may also create or modify workspace agents at any point if the user explicitly asks.+## Assistant Suggestions-- Prefer standalone agents for single tasks. Use a group only when the user clearly benefits from multiple collaborating roles.-- Simplicity first — 1–2 assistants is usually enough.-- Name assistants by task, not by abstract capability. Examples: "刷题搭子", "简历顾问", "lesson-plan assistant".-- Each assistant should have a clear, narrow responsibility that complements your generalist role.+During the summary phase, you MUST hand assistant choice to the user via showAgentMarketplace, called exactly once. After opening the picker, on the next turn proceed straight to closing + finishOnboarding regardless of whether a UI resolution arrived (the user's text reply is sufficient signal). Do not call \`showAgentMarketplace\` more than once. Do not attempt any workspace creation or modification — that capability has been deliberately removed for onboarding.## Boundariesdiff --git a/packages/builtin-tool-agent-marketplace/package.json b/packages/builtin-tool-agent-marketplace/package.jsonnew file mode 100644index 00000000000..81769f14353--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/package.json@@ -0,0 +1,22 @@+{+ "name": "@lobechat/builtin-tool-agent-marketplace",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executor": "./src/executor/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "^5",+ "antd": "^6",+ "lucide-react": "*",+ "react": "^19",+ "swr": "^2"+ }+}diff --git a/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..91212e567d0--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it, vi } from 'vitest';++import { MarketplaceCategory } from '../types';+import { AgentMarketplaceExecutionRuntime } from './index';++const baseArgs = {+ categoryHints: [MarketplaceCategory.Engineering] as MarketplaceCategory[],+ prompt: 'Pick an engineer to help you ship faster.',+ requestId: 'req-1',+};++describe('AgentMarketplaceExecutionRuntime', () => {+ it('creates a pending pick request from valid args', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ const result = await runtime.showAgentMarketplace(baseArgs);++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({+ requestId: 'req-1',+ status: 'pending',+ categoryHints: [MarketplaceCategory.Engineering],+ prompt: baseArgs.prompt,+ });+ });++ it('rejects empty categoryHints', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ const result = await runtime.showAgentMarketplace({ ...baseArgs, categoryHints: [] });++ expect(result.success).toBe(false);+ });++ it('rejects categoryHints with unknown slug', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ const result = await runtime.showAgentMarketplace({+ ...baseArgs,+ categoryHints: ['not-a-real-category'] as unknown as MarketplaceCategory[],+ });++ expect(result.success).toBe(false);+ });++ it('marks a request submitted with selected template ids', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ await runtime.showAgentMarketplace(baseArgs);++ const result = await runtime.submitAgentPick({+ requestId: 'req-1',+ selectedTemplateIds: ['pair-programmer', 'code-reviewer'],+ });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({+ requestId: 'req-1',+ status: 'submitted',+ selectedTemplateIds: ['pair-programmer', 'code-reviewer'],+ });+ });++ it('marks a request skipped with optional reason', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ await runtime.showAgentMarketplace({ ...baseArgs, requestId: 'req-2' });++ const result = await runtime.skipAgentPick({ requestId: 'req-2', reason: 'user tired' });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({+ requestId: 'req-2',+ status: 'skipped',+ skipReason: 'user tired',+ });+ });++ it('marks a request cancelled', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ await runtime.showAgentMarketplace({ ...baseArgs, requestId: 'req-3' });++ const result = await runtime.cancelAgentPick({ requestId: 'req-3' });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ requestId: 'req-3', status: 'cancelled' });+ });++ it('returns current pick state', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ await runtime.showAgentMarketplace({ ...baseArgs, requestId: 'req-4' });++ const result = await runtime.getPickState({ requestId: 'req-4' });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ requestId: 'req-4', status: 'pending' });+ });++ it('returns error for non-existent request', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ const result = await runtime.getPickState({ requestId: 'nope' });++ expect(result.success).toBe(false);+ });++ it('prevents submitting a non-pending request', async () => {+ const runtime = new AgentMarketplaceExecutionRuntime();+ await runtime.showAgentMarketplace({ ...baseArgs, requestId: 'req-5' });+ await runtime.cancelAgentPick({ requestId: 'req-5' });++ const result = await runtime.submitAgentPick({+ requestId: 'req-5',+ selectedTemplateIds: ['copywriter'],+ });++ expect(result.success).toBe(false);+ });++ it('invokes onShown telemetry hook with categoryHints on show', async () => {+ const onShown = vi.fn();+ const runtime = new AgentMarketplaceExecutionRuntime({ onShown });+ await runtime.showAgentMarketplace(baseArgs);++ expect(onShown).toHaveBeenCalledTimes(1);+ expect(onShown).toHaveBeenCalledWith({+ categoryHints: [MarketplaceCategory.Engineering],+ requestId: 'req-1',+ });+ });++ it('invokes onPicked telemetry hook with selectedTemplateIds on submit', async () => {+ const onPicked = vi.fn();+ const runtime = new AgentMarketplaceExecutionRuntime({ onPicked });+ await runtime.showAgentMarketplace({ ...baseArgs, requestId: 'req-6' });++ await runtime.submitAgentPick({+ requestId: 'req-6',+ selectedTemplateIds: ['pair-programmer'],+ });++ expect(onPicked).toHaveBeenCalledTimes(1);+ expect(onPicked).toHaveBeenCalledWith({+ categoryHints: [MarketplaceCategory.Engineering],+ requestId: 'req-6',+ selectedTemplateIds: ['pair-programmer'],+ });+ });+});diff --git a/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..f9ad347dd6d--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/ExecutionRuntime/index.ts@@ -0,0 +1,191 @@+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';+import { z } from 'zod';++import {+ type CancelAgentPickArgs,+ type GetPickStateArgs,+ MARKETPLACE_CATEGORY_VALUES,+ type MarketplaceCategory,+ type PickState,+ type ShowAgentMarketplaceArgs,+ type SkipAgentPickArgs,+ type SubmitAgentPickArgs,+} from '../types';++const marketplaceCategorySchema = z.enum(MARKETPLACE_CATEGORY_VALUES as [string, ...string[]]);++const showAgentMarketplaceSchema = z.object({+ categoryHints: z.array(marketplaceCategorySchema).min(1),+ description: z.string().optional(),+ prompt: z.string().min(1),+ requestId: z.string().min(1),+});++const submitAgentPickSchema = z.object({+ requestId: z.string().min(1),+ selectedTemplateIds: z.array(z.string().min(1)).min(1),+});++export interface TelemetryHooks {+ onPicked?: (payload: {+ categoryHints: MarketplaceCategory[];+ requestId: string;+ selectedTemplateIds: string[];+ }) => void;+ onShown?: (payload: { categoryHints: MarketplaceCategory[]; requestId: string }) => void;+}++export class AgentMarketplaceExecutionRuntime {+ private picks: Map<string, PickState> = new Map();+ private hooks: TelemetryHooks;++ constructor(hooks: TelemetryHooks = {}) {+ this.hooks = hooks;+ }++ async showAgentMarketplace(+ args: unknown,+ scope?: { topicId?: string | null },+ ): Promise<BuiltinServerRuntimeOutput> {+ const parsed = showAgentMarketplaceSchema.safeParse(args);+ if (!parsed.success) {+ const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`);+ return {+ content: `Invalid showAgentMarketplace args:\n${issues.join('\n')}\nPlease regenerate the tool call with the correct schema.`,+ success: false,+ };+ }++ const { categoryHints, description, prompt, requestId } =+ parsed.data as ShowAgentMarketplaceArgs;++ if (scope?.topicId) {+ const existing = [...this.picks.values()].find((p) => p.topicId === scope.topicId);+ if (existing) {+ return {+ content: `Marketplace picker has already been opened in this conversation (requestId=${existing.requestId}, status=${existing.status}). Do NOT call showAgentMarketplace again. The picker resolves directly through the UI — when the user picks or skips, the runtime will start a new turn with the resolution as the tool result. Proceed straight to acknowledging the picks, persisting any persona update, and calling finishOnboarding.`,+ state: existing,+ success: false,+ };+ }+ }++ const state: PickState = {+ categoryHints,+ description,+ prompt,+ requestId,+ status: 'pending',+ topicId: scope?.topicId ?? undefined,+ };++ this.picks.set(requestId, state);++ try {+ this.hooks.onShown?.({ categoryHints, requestId });+ } catch (error) {+ console.error('[AgentMarketplace] onShown telemetry failed', error);+ }++ return {+ content: [+ `Marketplace picker is now visible to the user (requestId=${requestId}).`,+ 'STOP your current turn here. Do not call any further tools this turn (no finishOnboarding, no askUserQuestion, no other tools), and do not write a wrap-up message yet.',+ 'The picker resolves directly through the UI — when the user picks or skips, the runtime will start a NEW assistant turn whose tool result describes the picks (`installedAgentIds`, `selectedTemplateIds`, or skip/cancel status). Acknowledge the picks, persist a short persona update, and call finishOnboarding on that next turn.',+ ].join(' '),+ state,+ success: true,+ };+ }++ async submitAgentPick(args: SubmitAgentPickArgs): Promise<BuiltinServerRuntimeOutput> {+ const parsed = submitAgentPickSchema.safeParse(args);+ if (!parsed.success) {+ const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`);+ return {+ content: `Invalid submitAgentPick args:\n${issues.join('\n')}\nPlease regenerate the tool call with the correct schema.`,+ success: false,+ };+ }++ const { requestId, selectedTemplateIds } = parsed.data;+ const state = this.picks.get(requestId);+ if (!state) return { content: `Pick request not found: ${requestId}`, success: false };++ if (state.status !== 'pending') {+ return {+ content: `Pick request ${requestId} is already ${state.status}, cannot submit.`,+ success: false,+ };+ }++ state.status = 'submitted';+ state.selectedTemplateIds = selectedTemplateIds;+ this.picks.set(requestId, state);++ try {+ this.hooks.onPicked?.({+ categoryHints: state.categoryHints,+ requestId,+ selectedTemplateIds,+ });+ } catch (error) {+ console.error('[AgentMarketplace] onPicked telemetry failed', error);+ }++ return {+ content: `User picked ${selectedTemplateIds.length} template(s) for ${requestId}.`,+ state,+ success: true,+ };+ }++ async skipAgentPick(args: SkipAgentPickArgs): Promise<BuiltinServerRuntimeOutput> {+ const { requestId, reason } = args;+ const state = this.picks.get(requestId);+ if (!state) return { content: `Pick request not found: ${requestId}`, success: false };++ if (state.status !== 'pending') {+ return {+ content: `Pick request ${requestId} is already ${state.status}, cannot skip.`,+ success: false,+ };+ }++ state.status = 'skipped';+ state.skipReason = reason;+ this.picks.set(requestId, state);++ return {+ content: `Pick request ${requestId} skipped.${reason ? ` Reason: ${reason}` : ''}`,+ state,+ success: true,+ };+ }++ async cancelAgentPick(args: CancelAgentPickArgs): Promise<BuiltinServerRuntimeOutput> {+ const { requestId } = args;+ const state = this.picks.get(requestId);+ if (!state) return { content: `Pick request not found: ${requestId}`, success: false };++ if (state.status !== 'pending') {+ return {+ content: `Pick request ${requestId} is already ${state.status}, cannot cancel.`,+ success: false,+ };+ }++ state.status = 'cancelled';+ this.picks.set(requestId, state);++ return { content: `Pick request ${requestId} cancelled.`, state, success: true };+ }++ async getPickState(args: GetPickStateArgs): Promise<BuiltinServerRuntimeOutput> {+ const { requestId } = args;+ const state = this.picks.get(requestId);+ if (!state) return { content: `Pick request not found: ${requestId}`, success: false };++ return { content: `Pick request ${requestId} is ${state.status}.`, state, success: true };+ }+}diff --git a/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/Skeleton.tsx b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/Skeleton.tsxnew file mode 100644index 00000000000..cc2f26c19de--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/Skeleton.tsx@@ -0,0 +1,32 @@+import { memo } from 'react';++import { styles } from './style';++const SIDEBAR_ITEMS = 6;+const CARD_ITEMS = 6;++const PickAgentsSkeleton = memo(() => (+ <div className={styles.container}>+ <div className={styles.sidebar}>+ {Array.from({ length: SIDEBAR_ITEMS }).map((_, i) => (+ <div className={styles.skeletonSidebarItem} key={i} />+ ))}+ </div>+ <div className={styles.content}>+ <div className={styles.grid}>+ {Array.from({ length: CARD_ITEMS }).map((_, i) => (+ <div className={styles.skeletonCard} key={i}>+ <div className={styles.skeletonAvatar} />+ <div className={styles.skeletonLine} style={{ width: '60%' }} />+ <div className={styles.skeletonLine} style={{ width: '90%' }} />+ <div className={styles.skeletonLine} style={{ width: '75%' }} />+ </div>+ ))}+ </div>+ </div>+ </div>+));++PickAgentsSkeleton.displayName = 'PickAgentsSkeleton';++export default PickAgentsSkeleton;diff --git a/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/constants.ts b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/constants.tsnew file mode 100644index 00000000000..c86c8fcab9b--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/constants.ts@@ -0,0 +1,17 @@+import { MarketplaceCategory } from '../../../types';++export const CATEGORY_LABEL_I18N_KEYS = {+ [MarketplaceCategory.BusinessStrategy]: 'agentMarketplace.category.businessStrategy',+ [MarketplaceCategory.ContentCreation]: 'agentMarketplace.category.contentCreation',+ [MarketplaceCategory.CreatorEconomy]: 'agentMarketplace.category.creatorEconomy',+ [MarketplaceCategory.DesignCreative]: 'agentMarketplace.category.designCreative',+ [MarketplaceCategory.Engineering]: 'agentMarketplace.category.engineering',+ [MarketplaceCategory.FinanceLegal]: 'agentMarketplace.category.financeLegal',+ [MarketplaceCategory.LearningResearch]: 'agentMarketplace.category.learningResearch',+ [MarketplaceCategory.Marketing]: 'agentMarketplace.category.marketing',+ [MarketplaceCategory.Operations]: 'agentMarketplace.category.operations',+ [MarketplaceCategory.PeopleHR]: 'agentMarketplace.category.peopleHR',+ [MarketplaceCategory.PersonalLife]: 'agentMarketplace.category.personalLife',+ [MarketplaceCategory.ProductManagement]: 'agentMarketplace.category.productManagement',+ [MarketplaceCategory.SalesCustomer]: 'agentMarketplace.category.salesCustomer',+} as const satisfies Record<MarketplaceCategory, string>;diff --git a/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/index.tsx b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/index.tsxnew file mode 100644index 00000000000..8424fef8c81--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/index.tsx@@ -0,0 +1,236 @@+'use client';++import type { BuiltinInterventionProps } from '@lobechat/types';+import { Avatar, Button, Flexbox, Text } from '@lobehub/ui';+import { cx } from 'antd-style';+import type { KeyboardEvent } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { fetchAgentTemplates, getTemplatesByCategoryPriority } from '../../../data/agent-templates';+import {+ type AgentTemplate,+ type MarketplaceCategory,+ type ShowAgentMarketplaceArgs,+} from '../../../types';+import { CATEGORY_LABEL_I18N_KEYS } from './constants';+import PickAgentsSkeleton from './Skeleton';+import { styles } from './style';++const TEMPLATES_SWR_KEY = 'builtin-tool-agent-marketplace/onboarding-templates';+const EMPTY_TEMPLATES: AgentTemplate[] = [];++const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplaceArgs>>(+ ({ args, interactionMode, onInteractionAction }) => {+ const { t } = useTranslation('ui');+ const { t: tTool } = useTranslation('tool');+ const isCustom = interactionMode === 'custom';++ const { categoryHints, description, prompt } = args;++ const {+ data: allTemplates = EMPTY_TEMPLATES,+ isLoading,+ error,+ } = useSWR(TEMPLATES_SWR_KEY, () => fetchAgentTemplates(), {+ dedupingInterval: 60_000,+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ });++ useEffect(() => {+ if (error) console.error('[AgentMarketplace] failed to load templates', error);+ }, [error]);++ const templates = useMemo(+ () => getTemplatesByCategoryPriority(allTemplates, categoryHints ?? []),+ [allTemplates, categoryHints],+ );++ const groupedTemplates = useMemo(() => {+ const map = new Map<MarketplaceCategory, AgentTemplate[]>();+ for (const tpl of templates) {+ const list = map.get(tpl.category);+ if (list) list.push(tpl);+ else map.set(tpl.category, [tpl]);+ }+ return map;+ }, [templates]);++ const availableCategories = useMemo(() => [...groupedTemplates.keys()], [groupedTemplates]);++ const [activeCategory, setActiveCategory] = useState<MarketplaceCategory | undefined>(+ () => availableCategories[0],+ );++ useEffect(() => {+ if (!activeCategory || !groupedTemplates.has(activeCategory)) {+ setActiveCategory(availableCategories[0]);+ }+ }, [activeCategory, availableCategories, groupedTemplates]);++ const visibleTemplates = useMemo(+ () => (activeCategory ? (groupedTemplates.get(activeCategory) ?? []) : []),+ [activeCategory, groupedTemplates],+ );++ const [selected, setSelected] = useState<Set<string>>(() => new Set());+ const [submitting, setSubmitting] = useState(false);++ const toggle = useCallback((id: string) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);++ const handleSubmit = useCallback(async () => {+ if (!onInteractionAction || selected.size === 0) return;+ setSubmitting(true);+ try {+ await onInteractionAction({+ payload: { categoryHints, requestId: args.requestId, selectedTemplateIds: [...selected] },+ type: 'submit',+ });+ } catch (error) {+ console.error('[AgentMarketplace] submit failed', error);+ } finally {+ setSubmitting(false);+ }+ }, [args.requestId, categoryHints, onInteractionAction, selected]);++ const handleSkip = useCallback(async () => {+ if (!onInteractionAction) return;+ await onInteractionAction({+ payload: { categoryHints, requestId: args.requestId },+ type: 'skip',+ });+ }, [args.requestId, categoryHints, onInteractionAction]);++ const handleCardKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>, id: string) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ toggle(id);+ }+ },+ [toggle],+ );++ if (!isCustom) {+ return (+ <Flexbox gap={8}>+ <Text>{prompt}</Text>+ {description && (+ <Text style={{ fontSize: 13 }} type="secondary">+ {description}+ </Text>+ )}+ <Text style={{ fontSize: 12 }} type="secondary">+ {tTool('agentMarketplace.picker.summary', {+ filtered: templates.length,+ total: allTemplates.length,+ })}+ </Text>+ </Flexbox>+ );+ }++ const showLoading = isLoading && allTemplates.length === 0;+ const showEmpty = !isLoading && visibleTemplates.length === 0;++ return (+ <Flexbox className={styles.root} gap={12}>+ <div className={styles.header}>+ <Text style={{ fontWeight: 500 }}>{prompt}</Text>+ {description && (+ <Text style={{ fontSize: 13 }} type="secondary">+ {description}+ </Text>+ )}+ </div>++ {showLoading ? (+ <PickAgentsSkeleton />+ ) : showEmpty ? (+ <div className={styles.empty}>+ {error+ ? tTool('agentMarketplace.picker.failedToLoad')+ : tTool('agentMarketplace.picker.empty')}+ </div>+ ) : (+ <div className={styles.container}>+ <div aria-orientation="vertical" className={styles.sidebar} role="tablist">+ {availableCategories.map((category) => {+ const isActive = activeCategory === category;+ return (+ <button+ aria-selected={isActive}+ className={cx(styles.categoryItem, isActive && styles.categoryItemActive)}+ key={category}+ role="tab"+ type="button"+ onClick={() => setActiveCategory(category)}+ >+ {tTool(CATEGORY_LABEL_I18N_KEYS[category])}+ </button>+ );+ })}+ </div>++ <div className={styles.content}>+ {visibleTemplates.length === 0 ? (+ <div className={styles.empty}>{tTool('agentMarketplace.picker.empty')}</div>+ ) : (+ <div className={styles.grid}>+ {visibleTemplates.map((tpl) => {+ const isSelected = selected.has(tpl.id);+ const avatar = tpl.avatar;+ return (+ <div+ aria-pressed={isSelected}+ className={cx(styles.card, isSelected && styles.cardSelected)}+ key={tpl.id}+ role="button"+ tabIndex={0}+ onClick={() => toggle(tpl.id)}+ onKeyDown={(event) => handleCardKeyDown(event, tpl.id)}+ >+ <Avatar avatar={avatar} shape="square" size={36} />+ <div className={styles.cardTitle}>{tpl.title}</div>+ {tpl.description && (+ <div className={styles.cardDescription}>{tpl.description}</div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ </div>+ )}++ <div className={styles.footer}>+ <Text className={styles.skipLink} type="secondary" onClick={handleSkip}>+ {t('form.skip')}+ </Text>+ <Button+ disabled={selected.size === 0}+ loading={submitting}+ type="primary"+ onClick={handleSubmit}+ >+ {`${t('common.confirm')} (${selected.size})`}+ </Button>+ </div>+ </Flexbox>+ );+ },+);++PickAgentsIntervention.displayName = 'PickAgentsIntervention';++export default PickAgentsIntervention;diff --git a/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/style.ts b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/style.tsnew file mode 100644index 00000000000..f6fbd2a213c--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/Intervention/PickAgents/style.ts@@ -0,0 +1,250 @@+import { createStaticStyles, keyframes } from 'antd-style';++const pulse = keyframes`+ 0%,+ 100% {+ opacity: 1;+ }++ 50% {+ opacity: 0.5;+ }+`;++export const styles = createStaticStyles(({ css, cssVar }) => ({+ card: css`+ cursor: pointer;++ display: flex;+ flex-direction: column;+ gap: 10px;++ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};++ transition:+ border-color ${cssVar.motionDurationMid},+ background ${cssVar.motionDurationMid};++ &:hover {+ border-color: ${cssVar.colorPrimaryHover};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 2px;+ }+ `,+ cardDescription: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 4;++ font-size: 12px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ cardSelected: css`+ border-color: ${cssVar.colorPrimary};+ background: ${cssVar.colorPrimaryBg};++ &:hover {+ border-color: ${cssVar.colorPrimary};+ }+ `,+ cardTitle: css`+ font-size: 14px;+ font-weight: 600;+ color: ${cssVar.colorText};+ `,+ container: css`+ overflow: hidden;+ display: grid;+ grid-template-columns: 180px minmax(0, 1fr);+ flex: 1;+ gap: 16px;++ min-height: 0;++ @media (width <= 720px) {+ grid-template-columns: 1fr;+ grid-template-rows: auto minmax(0, 1fr);+ }+ `,+ content: css`+ overflow-y: auto;+ overscroll-behavior: contain;++ min-width: 0;+ min-height: 0;+ padding-inline-end: 4px;+ `,+ categoryItem: css`+ cursor: pointer;++ display: block;++ width: 100%;+ padding-block: 8px;+ padding-inline: 12px;+ border: none;+ border-radius: ${cssVar.borderRadius};++ font-size: 13px;+ color: ${cssVar.colorTextSecondary};+ text-align: start;++ background: transparent;++ transition:+ background ${cssVar.motionDurationMid},+ color ${cssVar.motionDurationMid};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 2px;+ }++ @media (width <= 720px) {+ width: auto;+ white-space: nowrap;+ }+ `,+ categoryItemActive: css`+ font-weight: 500;+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ empty: css`+ display: flex;+ flex: 1;+ align-items: center;+ justify-content: center;++ min-height: 160px;+ padding: 24px;++ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+ footer: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: space-between;+ `,+ grid: css`+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 12px;+ align-content: start;+ `,+ header: css`+ display: flex;+ flex: none;+ flex-direction: column;+ gap: 8px;+ `,+ root: css`+ position: absolute;+ z-index: 10;+ inset-block-end: 0;+ inset-inline: 0;++ overflow: hidden;++ height: min(640px, 72vh);+ min-height: 480px;+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgElevated};+ box-shadow: 0 16px 48px color-mix(in srgb, #000 16%, transparent);+ `,+ sidebar: css`+ overflow-y: auto;+ overscroll-behavior: contain;+ display: flex;+ flex-direction: column;+ gap: 2px;++ min-height: 0;+ padding-inline-end: 4px;++ @media (width <= 720px) {+ overflow: auto hidden;+ flex-flow: row nowrap;+ padding-block-end: 4px;+ padding-inline-end: 0;+ }+ `,+ skeletonAvatar: css`+ flex: none;++ width: 36px;+ height: 36px;+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillTertiary};++ animation: ${pulse} 1.5s ease-in-out infinite;+ `,+ skeletonCard: css`+ display: flex;+ flex-direction: column;+ gap: 10px;++ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};+ `,+ skeletonLine: css`+ height: 10px;+ border-radius: ${cssVar.borderRadius};+ background: ${cssVar.colorFillTertiary};+ animation: ${pulse} 1.5s ease-in-out infinite;+ `,+ skeletonSidebarItem: css`+ width: 100%;+ height: 36px;+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillTertiary};++ animation: ${pulse} 1.5s ease-in-out infinite;+ `,+ skipLink: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ padding-block: 4px;+ padding-inline: 0;++ font-size: 13px;++ transition: color ${cssVar.motionDurationMid};++ &:hover {+ color: ${cssVar.colorPrimary} !important;+ }+ `,+}));diff --git a/packages/builtin-tool-agent-marketplace/src/client/Intervention/index.ts b/packages/builtin-tool-agent-marketplace/src/client/Intervention/index.tsnew file mode 100644index 00000000000..3f70a4d101b--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/Intervention/index.ts@@ -0,0 +1,8 @@+import type { BuiltinIntervention } from '@lobechat/types';++import { AgentMarketplaceApiName } from '../../types';+import PickAgentsIntervention from './PickAgents';++export const AgentMarketplaceInterventions: Record<string, BuiltinIntervention> = {+ [AgentMarketplaceApiName.showAgentMarketplace]: PickAgentsIntervention as BuiltinIntervention,+};diff --git a/packages/builtin-tool-agent-marketplace/src/client/index.ts b/packages/builtin-tool-agent-marketplace/src/client/index.tsnew file mode 100644index 00000000000..4512b115e84--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/client/index.ts@@ -0,0 +1,3 @@+export { AgentMarketplaceManifest } from '../manifest';+export * from '../types';+export { AgentMarketplaceInterventions } from './Intervention';diff --git a/packages/builtin-tool-agent-marketplace/src/data/agent-templates.test.ts b/packages/builtin-tool-agent-marketplace/src/data/agent-templates.test.tsnew file mode 100644index 00000000000..bf317dcbd50--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/data/agent-templates.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest';++import { type AgentTemplate, MarketplaceCategory } from '../types';+import {+ getTemplatesByCategories,+ getTemplatesByCategoryPriority,+ normalizeAgentTemplate,+} from './agent-templates';++const fixture: AgentTemplate[] = [+ { category: MarketplaceCategory.PersonalLife, id: 'a', title: 'A' },+ { category: MarketplaceCategory.Engineering, id: 'b', title: 'B' },+ { category: MarketplaceCategory.ContentCreation, id: 'c', title: 'C' },+ { category: MarketplaceCategory.Engineering, id: 'd', title: 'D' },+];++describe('getTemplatesByCategoryPriority', () => {+ it('returns templates as-is when no hints are provided', () => {+ expect(getTemplatesByCategoryPriority(fixture, [])).toEqual(fixture);+ });++ it('moves hinted categories to the front in hint order while keeping all templates', () => {+ const result = getTemplatesByCategoryPriority(fixture, [+ MarketplaceCategory.Engineering,+ MarketplaceCategory.ContentCreation,+ ]);++ expect(result).toHaveLength(fixture.length);+ expect(result[0]?.category).toBe(MarketplaceCategory.Engineering);+ expect(result[1]?.category).toBe(MarketplaceCategory.Engineering);+ expect(result[2]?.category).toBe(MarketplaceCategory.ContentCreation);+ expect(result.some((t) => t.category === MarketplaceCategory.PersonalLife)).toBe(true);+ });+});++describe('getTemplatesByCategories', () => {+ it('returns all templates when no categories are provided', () => {+ expect(getTemplatesByCategories(fixture, [])).toEqual(fixture);+ });++ it('keeps only templates whose category matches the filter', () => {+ const result = getTemplatesByCategories(fixture, [MarketplaceCategory.Engineering]);+ expect(result).toHaveLength(2);+ expect(result.every((t) => t.category === MarketplaceCategory.Engineering)).toBe(true);+ });+});++describe('normalizeAgentTemplate', () => {+ it('maps an onboarding-full item using the outer category key', () => {+ const result = normalizeAgentTemplate(+ {+ avatar: 'https://example.com/avatar.webp',+ description: 'A senior code reviewer.',+ identifier: 'agent-template-code-reviewer',+ name: 'Code Reviewer',+ },+ 'engineering',+ );++ expect(result).toEqual({+ avatar: 'https://example.com/avatar.webp',+ category: MarketplaceCategory.Engineering,+ description: 'A senior code reviewer.',+ id: 'agent-template-code-reviewer',+ title: 'Code Reviewer',+ });+ });++ it('returns undefined when the outer category is not in the enum', () => {+ expect(+ normalizeAgentTemplate(+ { identifier: 'agent-template-mystery', name: 'Mystery' },+ 'unknown-bucket',+ ),+ ).toBeUndefined();+ });++ it('returns undefined when identifier or name is missing', () => {+ expect(+ normalizeAgentTemplate({ identifier: 'x' }, MarketplaceCategory.Engineering),+ ).toBeUndefined();+ expect(normalizeAgentTemplate({ name: 'X' }, MarketplaceCategory.Engineering)).toBeUndefined();+ });+});diff --git a/packages/builtin-tool-agent-marketplace/src/data/agent-templates.ts b/packages/builtin-tool-agent-marketplace/src/data/agent-templates.tsnew file mode 100644index 00000000000..4831b0a9cde--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/data/agent-templates.ts@@ -0,0 +1,77 @@+import type { AgentTemplate, MarketplaceCategory } from '../types';+import { MARKETPLACE_CATEGORY_VALUES } from '../types';++const MARKETPLACE_CATEGORY_SET = new Set<string>(MARKETPLACE_CATEGORY_VALUES);++export interface RawAgentTemplate {+ avatar?: string;+ description?: string;+ identifier?: string;+ name?: string;+}++/** API response shape: top-level keys are MarketplaceCategory slugs. */+export type OnboardingFullResponse = Record<string, RawAgentTemplate[]>;++export const normalizeAgentTemplate = (+ item: RawAgentTemplate,+ category: string,+): AgentTemplate | undefined => {+ if (!item.identifier || !item.name) return undefined;+ if (!MARKETPLACE_CATEGORY_SET.has(category)) return undefined;+ return {+ avatar: item.avatar,+ category: category as MarketplaceCategory,+ description: item.description,+ id: item.identifier,+ title: item.name,+ };+};++export interface FetchAgentTemplatesOptions {+ signal?: AbortSignal;+}++export type AgentTemplateFetcher = (+ options?: FetchAgentTemplatesOptions,+) => Promise<AgentTemplate[]>;++const defaultFetcher: AgentTemplateFetcher = async () => {+ throw new Error(+ '[AgentMarketplace] Agent templates fetcher is not configured. ' ++ 'Call setAgentTemplatesFetcher in your app initialization.',+ );+};++let currentFetcher: AgentTemplateFetcher = defaultFetcher;++export const setAgentTemplatesFetcher = (fetcher: AgentTemplateFetcher): void => {+ currentFetcher = fetcher;+};++export const fetchAgentTemplates: AgentTemplateFetcher = (options) => currentFetcher(options);++export const getTemplatesByCategories = (+ templates: AgentTemplate[],+ categories: string[],+): AgentTemplate[] => {+ if (categories.length === 0) return templates;+ const set = new Set(categories);+ return templates.filter((t) => set.has(t.category));+};++export const getTemplatesByCategoryPriority = (+ templates: AgentTemplate[],+ categories: string[],+): AgentTemplate[] => {+ if (categories.length === 0) return templates;++ const priority = new Map(categories.map((category, index) => [category, index]));++ return [...templates].sort((a, b) => {+ const aPriority = priority.get(a.category) ?? Number.MAX_SAFE_INTEGER;+ const bPriority = priority.get(b.category) ?? Number.MAX_SAFE_INTEGER;++ return aPriority - bPriority;+ });+};diff --git a/packages/builtin-tool-agent-marketplace/src/executor/index.ts b/packages/builtin-tool-agent-marketplace/src/executor/index.tsnew file mode 100644index 00000000000..d7f855cae75--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/executor/index.ts@@ -0,0 +1,66 @@+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';++import { AgentMarketplaceExecutionRuntime } from '../ExecutionRuntime';+import {+ AgentMarketplaceApiName,+ AgentMarketplaceIdentifier,+ type CancelAgentPickArgs,+ type GetPickStateArgs,+ type ShowAgentMarketplaceArgs,+ type SkipAgentPickArgs,+ type SubmitAgentPickArgs,+} from '../types';++export class AgentMarketplaceExecutor extends BaseExecutor<typeof AgentMarketplaceApiName> {+ readonly identifier = AgentMarketplaceIdentifier;+ protected readonly apiEnum = AgentMarketplaceApiName;++ private runtime: AgentMarketplaceExecutionRuntime;++ constructor(runtime: AgentMarketplaceExecutionRuntime) {+ super();+ this.runtime = runtime;+ }++ showAgentMarketplace = async (+ params: ShowAgentMarketplaceArgs,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.showAgentMarketplace(params, { topicId: ctx.topicId });+ };++ submitAgentPick = async (+ params: SubmitAgentPickArgs,+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ // TODO(LOBE-7801): after submit, install the selected templates into the+ // user workspace (clone from lobehub/agent-template into sessions table).+ // For MVP we only record the selection and let the agent acknowledge verbally.+ return this.runtime.submitAgentPick(params);+ };++ skipAgentPick = async (+ params: SkipAgentPickArgs,+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.skipAgentPick(params);+ };++ cancelAgentPick = async (+ params: CancelAgentPickArgs,+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.cancelAgentPick(params);+ };++ getPickState = async (+ params: GetPickStateArgs,+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.getPickState(params);+ };+}++const fallbackRuntime = new AgentMarketplaceExecutionRuntime();++export const agentMarketplaceExecutor = new AgentMarketplaceExecutor(fallbackRuntime);diff --git a/packages/builtin-tool-agent-marketplace/src/index.ts b/packages/builtin-tool-agent-marketplace/src/index.tsnew file mode 100644index 00000000000..791f6847b05--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/index.ts@@ -0,0 +1,28 @@+export {+ type AgentTemplateFetcher,+ fetchAgentTemplates,+ type FetchAgentTemplatesOptions,+ getTemplatesByCategories,+ normalizeAgentTemplate,+ type OnboardingFullResponse,+ type RawAgentTemplate,+ setAgentTemplatesFetcher,+} from './data/agent-templates';+export * from './ExecutionRuntime';+export { AgentMarketplaceManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ AgentMarketplaceApiName,+ AgentMarketplaceIdentifier,+ type AgentPickResult,+ type AgentTemplate,+ type CancelAgentPickArgs,+ type GetPickStateArgs,+ MARKETPLACE_CATEGORY_VALUES,+ MarketplaceCategory,+ type PickState,+ type PickStatus,+ type ShowAgentMarketplaceArgs,+ type SkipAgentPickArgs,+ type SubmitAgentPickArgs,+} from './types';diff --git a/packages/builtin-tool-agent-marketplace/src/manifest.ts b/packages/builtin-tool-agent-marketplace/src/manifest.tsnew file mode 100644index 00000000000..8146397de10--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/manifest.ts@@ -0,0 +1,113 @@+import type { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import {+ AgentMarketplaceApiName,+ AgentMarketplaceIdentifier,+ MARKETPLACE_CATEGORY_VALUES,+} from './types';++export const AgentMarketplaceManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Open an Agent Marketplace picker card in the UI, prioritizing tabs by the provided category hints. Returns the request in pending state.',+ humanIntervention: 'always',+ name: AgentMarketplaceApiName.showAgentMarketplace,+ renderDisplayControl: 'collapsed',+ parameters: {+ properties: {+ categoryHints: {+ description:+ 'One or more fixed MarketplaceCategory slugs used to move matching picker tabs to the front.',+ items: {+ enum: [...MARKETPLACE_CATEGORY_VALUES],+ type: 'string',+ },+ minItems: 1,+ type: 'array',+ },+ description: {+ description: 'Optional secondary line shown below the prompt.',+ type: 'string',+ },+ prompt: {+ description:+ 'Short, natural sentence shown to the user explaining what the marketplace is for.',+ type: 'string',+ },+ requestId: {+ description: 'Unique identifier for this pick request.',+ type: 'string',+ },+ },+ required: ['categoryHints', 'prompt', 'requestId'],+ type: 'object',+ },+ },+ {+ description:+ "Record the user's template selection for a pending pick request. Normally client-handled after the user submits in the UI.",+ name: AgentMarketplaceApiName.submitAgentPick,+ parameters: {+ properties: {+ requestId: { description: 'The pick request ID to submit.', type: 'string' },+ selectedTemplateIds: {+ description: 'Template IDs the user selected from the marketplace.',+ items: { type: 'string' },+ minItems: 1,+ type: 'array',+ },+ },+ required: ['requestId', 'selectedTemplateIds'],+ type: 'object',+ },+ },+ {+ description:+ 'Mark a pending pick request as skipped with an optional reason. Normally client-handled after the user skips.',+ name: AgentMarketplaceApiName.skipAgentPick,+ parameters: {+ properties: {+ reason: { description: 'Optional reason for skipping.', type: 'string' },+ requestId: { description: 'The pick request ID to skip.', type: 'string' },+ },+ required: ['requestId'],+ type: 'object',+ },+ },+ {+ description: 'Cancel a pending pick request. Normally client-handled after the user cancels.',+ name: AgentMarketplaceApiName.cancelAgentPick,+ parameters: {+ properties: {+ requestId: { description: 'The pick request ID to cancel.', type: 'string' },+ },+ required: ['requestId'],+ type: 'object',+ },+ },+ {+ description:+ 'Inspect the current state of a known pick request. Use for recovery or diagnostics, not routine polling.',+ name: AgentMarketplaceApiName.getPickState,+ parameters: {+ properties: {+ requestId: { description: 'The pick request ID to query.', type: 'string' },+ },+ required: ['requestId'],+ type: 'object',+ },+ renderDisplayControl: 'collapsed',+ },+ ],+ identifier: AgentMarketplaceIdentifier,+ meta: {+ avatar: '🛍️',+ description:+ 'Show users a curated Agent Marketplace card and record which templates they pick.',+ title: 'Agent Marketplace',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-agent-marketplace/src/systemRole.ts b/packages/builtin-tool-agent-marketplace/src/systemRole.tsnew file mode 100644index 00000000000..03f7863b902--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/systemRole.ts@@ -0,0 +1,39 @@+export const systemPrompt = `You have access to an Agent Marketplace picker tool that presents curated agent templates to the user as a UI card.++<primary_usage>+Regular usage:+1. Call showAgentMarketplace with:+ - requestId: a unique id for this pick request.+ - categoryHints: 1–3 MarketplaceCategory slugs that match what you believe the user needs, chosen from the fixed list below. These hints move the matching tabs to the front of the picker; the user can still browse the rest.+ - prompt: a short, natural sentence telling the user why you are showing the marketplace (e.g. "I think these would help with your writing work — take a look").+ - description (optional): an extra line of context.+2. The picker is user-driven. Do NOT pre-select or claim to have created any agents. Wait for the user to pick.+3. Keep at most one unresolved pick request at a time.+</primary_usage>++<fixed_category_slugs>+content-creation, engineering, design-creative, learning-research, business-strategy,+marketing, product-management, sales-customer, operations, people-hr,+finance-legal, creator-economy, personal-life+</fixed_category_slugs>++<framework_lifecycle>+Framework-managed lifecycle:+1. showAgentMarketplace opens the picker in the UI.+2. submitAgentPick, skipAgentPick, and cancelAgentPick represent lifecycle outcomes.+3. In normal product flows these lifecycle APIs are handled by the client after the user acts. Do not call them proactively.+</framework_lifecycle>++<recovery_usage>+Recovery and inspection:+1. Use getPickState only when you need to inspect the status of a known request.+2. Do not poll repeatedly.+3. If the status is already resolved, continue from that result rather than reopening the picker.+</recovery_usage>++<boundaries>+- Do NOT attempt to create, update, delete, or duplicate agents yourself. That capability has been removed on purpose — the Marketplace picker is the ONLY way to add agents in this flow.+- Always pick categoryHints strictly from the fixed slug list. Do not invent new slugs.+- After the user submits, acknowledge what they picked by title in your next reply; do not claim you installed anything.+</boundaries>+`;diff --git a/packages/builtin-tool-agent-marketplace/src/types.ts b/packages/builtin-tool-agent-marketplace/src/types.tsnew file mode 100644index 00000000000..e24709bc1e1--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/src/types.ts@@ -0,0 +1,109 @@+/**+ * Agent Marketplace Tool Identifier+ */+export const AgentMarketplaceIdentifier = 'lobe-agent-marketplace';++/**+ * Agent Marketplace API Names+ */+export const AgentMarketplaceApiName = {+ /** Cancel a pending marketplace request. Usually framework-handled. */+ cancelAgentPick: 'cancelAgentPick',+ /** Inspect current state of a known pick request. For recovery/diagnostics. */+ getPickState: 'getPickState',+ /** Open the Marketplace picker with category hints. */+ showAgentMarketplace: 'showAgentMarketplace',+ /** Mark a pending marketplace request as skipped. Usually framework-handled. */+ skipAgentPick: 'skipAgentPick',+ /** Record the user's template selection. Usually framework-handled. */+ submitAgentPick: 'submitAgentPick',+} as const;++export type AgentMarketplaceApiNameType =+ (typeof AgentMarketplaceApiName)[keyof typeof AgentMarketplaceApiName];++/**+ * Curated categories sourced from the marketplace onboarding-full API.+ * Slugs match the top-level keys of the API response.+ */+export enum MarketplaceCategory {+ BusinessStrategy = 'business-strategy',+ ContentCreation = 'content-creation',+ CreatorEconomy = 'creator-economy',+ DesignCreative = 'design-creative',+ Engineering = 'engineering',+ FinanceLegal = 'finance-legal',+ LearningResearch = 'learning-research',+ Marketing = 'marketing',+ Operations = 'operations',+ PeopleHR = 'people-hr',+ PersonalLife = 'personal-life',+ ProductManagement = 'product-management',+ SalesCustomer = 'sales-customer',+}++export const MARKETPLACE_CATEGORY_VALUES = Object.values(MarketplaceCategory);++/**+ * A single agent template shown in the marketplace picker.+ */+export interface AgentTemplate {+ /** Optional emoji or image URL — falls back to a category default in the UI. */+ avatar?: string;+ category: MarketplaceCategory;+ /** Optional one-line capability summary. Upstream marketplace API may omit this. */+ description?: string;+ /** Marketplace identifier (e.g. 'agent-template-copywriter'). */+ id: string;+ /** Human-readable title (English Title Case). */+ title: string;+}++/**+ * Args to open the Marketplace picker.+ * categoryHints must contain at least one MarketplaceCategory slug and controls tab priority.+ */+export interface ShowAgentMarketplaceArgs {+ categoryHints: MarketplaceCategory[];+ description?: string;+ prompt: string;+ requestId: string;+}++export interface SubmitAgentPickArgs {+ requestId: string;+ /** Template IDs the user selected from the picker. */+ selectedTemplateIds: string[];+}++export interface SkipAgentPickArgs {+ reason?: string;+ requestId: string;+}++export interface CancelAgentPickArgs {+ requestId: string;+}++export interface GetPickStateArgs {+ requestId: string;+}++export type PickStatus = 'cancelled' | 'pending' | 'skipped' | 'submitted';++export interface PickState {+ categoryHints: MarketplaceCategory[];+ description?: string;+ prompt: string;+ requestId: string;+ selectedTemplateIds?: string[];+ skipReason?: string;+ status: PickStatus;+ /** topic the pick belongs to; used for per-conversation duplicate detection */+ topicId?: string;+}++export type AgentPickResult =+ | { requestId: string; selectedTemplateIds: string[]; type: 'submitted' }+ | { reason?: string; requestId: string; type: 'skipped' }+ | { requestId: string; type: 'cancelled' };diff --git a/packages/builtin-tool-agent-marketplace/tsconfig.json b/packages/builtin-tool-agent-marketplace/tsconfig.jsonnew file mode 100644index 00000000000..596e2cf729a--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "../../tsconfig.json",+ "include": ["src"]+}diff --git a/packages/builtin-tool-agent-marketplace/vitest.config.mts b/packages/builtin-tool-agent-marketplace/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-agent-marketplace/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.tsindex 956534216fe..f2db86328ab 100644--- a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts+++ b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts@@ -33,7 +33,7 @@ const PHASE_GUIDANCE: Record<string, string> = {discovery:'Phase: Discovery. User identity is established. Now explore their work style, tools, active projects, pain points, and how they want you to help. Collect interests and responseLanguage naturally. Update the persona document as you learn more.',summary:- 'Phase: Summary. All structured fields and documents are in good shape. Present a natural summary of what you learned about the user and how you can help. Ask for light confirmation, then call finishOnboarding.',+ "Phase: Summary. All structured fields and documents are in good shape. Two-step wrap up: (1) THIS or the current summary turn, present a natural summary of what you learned and call `showAgentMarketplace` exactly once with `{ requestId, categoryHints, prompt }` (1–3 MarketplaceCategory slugs picked from what you learned in discovery). Do not call `submitAgentPick` / `skipAgentPick` / `cancelAgentPick` yourself. (2) On the NEXT turn, briefly acknowledge whatever the user said, send a warm closing, and call `finishOnboarding`. Treat the user's text reply on that next turn as the resolution signal even if the picker is still in `pending` state — do not stall waiting for a UI event. Do not call `showAgentMarketplace` more than once.",user_identity:'Phase: User Identity. The agent has an identity. Now learn who the user is — their name, role, and what they do. Save fullName via saveUserQuestion when learned. Start building the persona document.',};diff --git a/packages/builtin-tool-web-onboarding/src/client/Intervention/SaveUserQuestion.tsx b/packages/builtin-tool-web-onboarding/src/client/Intervention/SaveUserQuestion.tsxindex e5b68140fc5..657e821a166 100644--- a/packages/builtin-tool-web-onboarding/src/client/Intervention/SaveUserQuestion.tsx+++ b/packages/builtin-tool-web-onboarding/src/client/Intervention/SaveUserQuestion.tsx@@ -37,90 +37,180 @@ const detailValueStyle = {padding: '10px 12px',} as const;-const SaveUserQuestionIntervention = memo<BuiltinInterventionProps<SaveUserQuestionInput>>(- ({ args }) => {- const { t } = useTranslation('chat');-- const agentName = args.agentName?.trim();- const agentEmoji = args.agentEmoji?.trim();-- const changedFields = useMemo(- () =>- [- agentName && {- label: t('tool.intervention.onboarding.agentIdentity.name'),- value: agentName,- },- agentEmoji && {- label: t('tool.intervention.onboarding.agentIdentity.emoji'),- value: agentEmoji,- },- ].filter(Boolean) as Array<{ label: string; value: string }>,- [agentEmoji, agentName, t],- );+interface DetailField {+ label: string;+ value: string;+}- return (- <Flexbox gap={12}>- <Flexbox gap={4}>- <Text style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em' }} type="secondary">- {t('tool.intervention.onboarding.agentIdentity.eyebrow')}- </Text>- <Text style={{ fontSize: 16, fontWeight: 600 }}>- {t('tool.intervention.onboarding.agentIdentity.title')}- </Text>- <Text style={{ fontSize: 13 }} type="secondary">- {t('tool.intervention.onboarding.agentIdentity.description')}- </Text>- </Flexbox>+interface AgentIdentitySectionProps {+ agentEmoji?: string;+ agentName?: string;+}- <div style={detailCardStyle}>- <Flexbox gap={16}>- <Flexbox horizontal align="center" gap={12}>- <Avatar- avatar={agentEmoji || '🤖'}- size={48}- style={{- background: 'var(--lobe-fill-quaternary)',- borderRadius: 16,- flex: 'none',- }}- />- <Flexbox gap={2}>- <Text style={{ fontSize: 16, fontWeight: 600 }}>- {agentName || t('untitledAgent')}- </Text>- <Text style={{ fontSize: 12 }} type="secondary">- {t('tool.intervention.onboarding.agentIdentity.applyHint')}- </Text>- </Flexbox>- </Flexbox>+const AgentIdentitySection = memo<AgentIdentitySectionProps>(({ agentEmoji, agentName }) => {+ const { t } = useTranslation('chat');- <div style={detailGridStyle}>- {changedFields.map((field) => (- <Flexbox gap={6} key={field.label}>- <Text style={{ fontSize: 12, fontWeight: 600 }} type="secondary">- {field.label}- </Text>- <div style={detailValueStyle}>{field.value}</div>- </Flexbox>- ))}- </div>+ const fields = useMemo<DetailField[]>(+ () =>+ [+ agentName && {+ label: t('tool.intervention.onboarding.agentIdentity.name'),+ value: agentName,+ },+ agentEmoji && {+ label: t('tool.intervention.onboarding.agentIdentity.emoji'),+ value: agentEmoji,+ },+ ].filter(Boolean) as DetailField[],+ [agentEmoji, agentName, t],+ );- <Flexbox gap={8}>- <Text style={{ fontSize: 12, fontWeight: 600 }} type="secondary">- {t('tool.intervention.onboarding.agentIdentity.targets')}+ return (+ <Flexbox gap={12}>+ <Flexbox gap={4}>+ <Text style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em' }} type="secondary">+ {t('tool.intervention.onboarding.agentIdentity.eyebrow')}+ </Text>+ <Text style={{ fontSize: 16, fontWeight: 600 }}>+ {t('tool.intervention.onboarding.agentIdentity.title')}+ </Text>+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('tool.intervention.onboarding.agentIdentity.description')}+ </Text>+ </Flexbox>++ <div style={detailCardStyle}>+ <Flexbox gap={16}>+ <Flexbox horizontal align="center" gap={12}>+ <Avatar+ avatar={agentEmoji || '🤖'}+ size={48}+ style={{+ background: 'var(--lobe-fill-quaternary)',+ borderRadius: 16,+ flex: 'none',+ }}+ />+ <Flexbox gap={2}>+ <Text style={{ fontSize: 16, fontWeight: 600 }}>+ {agentName || t('untitledAgent')}+ </Text>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('tool.intervention.onboarding.agentIdentity.applyHint')}</Text>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>- <span style={chipStyle}>- {t('tool.intervention.onboarding.agentIdentity.targetInbox')}- </span>- <span style={chipStyle}>- {t('tool.intervention.onboarding.agentIdentity.targetOnboarding')}- </span>- </div></Flexbox></Flexbox>- </div>++ <div style={detailGridStyle}>+ {fields.map((field) => (+ <Flexbox gap={6} key={field.label}>+ <Text style={{ fontSize: 12, fontWeight: 600 }} type="secondary">+ {field.label}+ </Text>+ <div style={detailValueStyle}>{field.value}</div>+ </Flexbox>+ ))}+ </div>++ <Flexbox gap={8}>+ <Text style={{ fontSize: 12, fontWeight: 600 }} type="secondary">+ {t('tool.intervention.onboarding.agentIdentity.targets')}+ </Text>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>+ <span style={chipStyle}>+ {t('tool.intervention.onboarding.agentIdentity.targetInbox')}+ </span>+ <span style={chipStyle}>+ {t('tool.intervention.onboarding.agentIdentity.targetOnboarding')}+ </span>+ </div>+ </Flexbox>+ </Flexbox>+ </div>+ </Flexbox>+ );+});++AgentIdentitySection.displayName = 'AgentIdentitySection';++interface UserProfileSectionProps {+ fullName?: string;+ responseLanguage?: string;+}++const UserProfileSection = memo<UserProfileSectionProps>(({ fullName, responseLanguage }) => {+ const { t } = useTranslation('chat');++ const fields = useMemo<DetailField[]>(+ () =>+ [+ fullName && {+ label: t('tool.intervention.onboarding.userProfile.fullName'),+ value: fullName,+ },+ responseLanguage && {+ label: t('tool.intervention.onboarding.userProfile.responseLanguage'),+ value: responseLanguage,+ },+ ].filter(Boolean) as DetailField[],+ [fullName, responseLanguage, t],+ );++ if (fields.length === 0) return null;++ return (+ <Flexbox gap={12}>+ <Flexbox gap={4}>+ <Text style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em' }} type="secondary">+ {t('tool.intervention.onboarding.userProfile.eyebrow')}+ </Text>+ <Text style={{ fontSize: 16, fontWeight: 600 }}>+ {t('tool.intervention.onboarding.userProfile.title')}+ </Text>+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('tool.intervention.onboarding.userProfile.description')}+ </Text>+ </Flexbox>++ <div style={detailCardStyle}>+ <Flexbox gap={16}>+ <div style={detailGridStyle}>+ {fields.map((field) => (+ <Flexbox gap={6} key={field.label}>+ <Text style={{ fontSize: 12, fontWeight: 600 }} type="secondary">+ {field.label}+ </Text>+ <div style={detailValueStyle}>{field.value}</div>+ </Flexbox>+ ))}+ </div>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('tool.intervention.onboarding.userProfile.applyHint')}+ </Text>+ </Flexbox>+ </div>+ </Flexbox>+ );+});++UserProfileSection.displayName = 'UserProfileSection';++const SaveUserQuestionIntervention = memo<BuiltinInterventionProps<SaveUserQuestionInput>>(+ ({ args }) => {+ const agentName = args.agentName?.trim() || undefined;+ const agentEmoji = args.agentEmoji?.trim() || undefined;+ const fullName = args.fullName?.trim() || undefined;+ const responseLanguage = args.responseLanguage?.trim() || undefined;++ const hasAgentIdentity = Boolean(agentName || agentEmoji);+ const hasUserProfile = Boolean(fullName || responseLanguage);++ return (+ <Flexbox gap={16}>+ {hasAgentIdentity && <AgentIdentitySection agentEmoji={agentEmoji} agentName={agentName} />}+ {hasUserProfile && (+ <UserProfileSection fullName={fullName} responseLanguage={responseLanguage} />+ )}</Flexbox>);},diff --git a/packages/builtin-tool-web-onboarding/src/manifest.ts b/packages/builtin-tool-web-onboarding/src/manifest.tsindex 0ac095468cc..3d9915fda87 100644--- a/packages/builtin-tool-web-onboarding/src/manifest.ts+++ b/packages/builtin-tool-web-onboarding/src/manifest.ts@@ -3,7 +3,10 @@ import type { BuiltinToolManifest, HumanInterventionRule } from '@lobechat/typesimport { toolSystemPrompt } from './toolSystemRole';import { WebOnboardingApiName, WebOnboardingIdentifier } from './types';-const agentIdentityConfirmationRules: HumanInterventionRule[] = [+// Agent identity (name/emoji) surface a confirmation card;+// user profile fields (fullName, responseLanguage) and interests+// saves bypass intervention.+const saveUserQuestionConfirmationRules: HumanInterventionRule[] = [{match: {agentName: { pattern: '\\S', type: 'regex' },@@ -33,8 +36,8 @@ export const WebOnboardingManifest: BuiltinToolManifest = {},{description:- 'Persist structured onboarding fields. Use for agentName and agentEmoji (updates inbox agent title/avatar and requires user confirmation), fullName, interests, and responseLanguage.',- humanIntervention: agentIdentityConfirmationRules,+ 'Persist structured onboarding fields. agentName and agentEmoji (updates inbox agent title/avatar) require user confirmation; interests-only saves run without confirmation.',+ humanIntervention: saveUserQuestionConfirmationRules,name: WebOnboardingApiName.saveUserQuestion,parameters: {additionalProperties: false,diff --git a/packages/builtin-tool-web-onboarding/src/toolSystemRole.ts b/packages/builtin-tool-web-onboarding/src/toolSystemRole.tsindex 120cfc5ef53..d012cff48d3 100644--- a/packages/builtin-tool-web-onboarding/src/toolSystemRole.ts+++ b/packages/builtin-tool-web-onboarding/src/toolSystemRole.ts@@ -3,13 +3,13 @@ export const toolSystemPrompt = `Turn protocol:1. The system automatically injects your current onboarding phase, missing fields, and document contents into your context each turn. Call getOnboardingState only when you are uncertain about the current phase or need to verify progress — it is no longer required every turn.-2. Follow the phase indicated in the injected context. Do not advance the flow out of order. Exception: if the user clearly signals they want to leave (busy, disengaging, says goodbye), skip directly to a brief wrap-up and call finishOnboarding regardless of the current phase.+2. Follow the phase indicated in the injected context. Do not advance the flow out of order. Exception: if the user clearly signals they want to leave (busy, disengaging, says goodbye), skip directly to a brief wrap-up; still call \`showAgentMarketplace\` exactly once for the assistant handoff, and on the next turn proceed to \`finishOnboarding\` regardless of whether the picker has been resolved — the user's text reply is the resolution signal in absence of a UI event. Skip the picker only if the user explicitly refuses it in words.3. **Each turn, the system appends a \`<next_actions>\` directive after the user's message. You MUST follow the tool call instructions in \`<next_actions>\` — they tell you exactly which persistence tools to call based on the current phase and missing data. Treat \`<next_actions>\` as mandatory operational instructions, not suggestions.**4. Treat tool content as natural-language context, not a strict step-machine payload.5. Prefer the \`lobe-user-interaction____askUserQuestion\` tool call for structured collection, explicit choices, or UI-mediated input. For natural exploratory conversation, direct plain-text questions are allowed and often preferable.6. Never claim something was saved, updated, created, or completed unless the corresponding tool call succeeded. If a tool call fails, recover from that result only.7. Never finish onboarding before the summary is shown and lightly confirmed, unless the user clearly signals they want to leave.-8. **CRITICAL: You MUST call persistence tools (saveUserQuestion, writeDocument, updateDocument) throughout the entire conversation, not just at the beginning. Every time you learn new information about the user, persist it promptly. When the user signals completion (e.g., "好了", "谢谢", "行", "Done"), you MUST call finishOnboarding — this is a hard requirement that overrides all other rules.**+8. **CRITICAL: You MUST call persistence tools (saveUserQuestion, writeDocument, updateDocument) throughout the entire conversation, not just at the beginning. Every time you learn new information about the user, persist it promptly. On a normal completion, the wrap-up sequence is: persist any unsaved fields → call \`showAgentMarketplace\` exactly once for the assistant handoff (skip only if the user explicitly refuses recommendations) → on the NEXT turn, send a brief warm closing and call \`finishOnboarding\`. The user's text reply on that next turn is the resolution signal even if the picker is still pending — do not stall.**Persistence rules:1. Use saveUserQuestion only for these structured onboarding fields: agentName, agentEmoji, fullName, interests, and responseLanguage. Use it only when that information emerges naturally in conversation.diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex 19827651454..b97f6fb1e1a 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -20,6 +20,8 @@"@lobechat/builtin-tool-activator": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-agent-documents": "workspace:*",+ "@lobechat/builtin-tool-agent-management": "workspace:*",+ "@lobechat/builtin-tool-agent-marketplace": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*","@lobechat/builtin-tool-claude-code": "workspace:*","@lobechat/builtin-tool-cloud-sandbox": "workspace:*",@@ -46,7 +48,8 @@"@lobechat/const": "workspace:*"},"devDependencies": {- "@lobechat/types": "workspace:*"+ "@lobechat/types": "workspace:*",+ "zod": "^3.25.76"},"peerDependencies": {"@lobehub/ui": "^5",diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex 0ae2ff9837a..587f8178327 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -2,6 +2,7 @@ import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';+import { AgentMarketplaceManifest } from '@lobechat/builtin-tool-agent-marketplace';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { CredsManifest } from '@lobechat/builtin-tool-creds';@@ -24,6 +25,7 @@ export const builtinToolIdentifiers: string[] = [AgentBuilderManifest.identifier,AgentDocumentsManifest.identifier,AgentManagementManifest.identifier,+ AgentMarketplaceManifest.identifier,CalculatorManifest.identifier,CloudSandboxManifest.identifier,CredsManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 587303a0385..c1f6b5fccb1 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -2,6 +2,7 @@ import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';+import { AgentMarketplaceManifest } from '@lobechat/builtin-tool-agent-marketplace';import { BriefManifest } from '@lobechat/builtin-tool-brief';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';@@ -239,6 +240,13 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: UserInteractionManifest,type: 'builtin',},+ {+ discoverable: false,+ hidden: true,+ identifier: AgentMarketplaceManifest.identifier,+ manifest: AgentMarketplaceManifest,+ type: 'builtin',+ },{discoverable: false,hidden: true,diff --git a/packages/builtin-tools/src/interventions.ts b/packages/builtin-tools/src/interventions.tsindex 7d06937510a..b530b1e6f8f 100644--- a/packages/builtin-tools/src/interventions.ts+++ b/packages/builtin-tools/src/interventions.ts@@ -2,6 +2,10 @@ import {AgentBuilderInterventions,AgentBuilderManifest,} from '@lobechat/builtin-tool-agent-builder/client';+import {+ AgentMarketplaceInterventions,+ AgentMarketplaceManifest,+} from '@lobechat/builtin-tool-agent-marketplace/client';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { CloudSandboxInterventions } from '@lobechat/builtin-tool-cloud-sandbox/client';import {@@ -34,6 +38,7 @@ import { type BuiltinIntervention } from '@lobechat/types';*/export const BuiltinToolInterventions: Record<string, Record<string, any>> = {[AgentBuilderManifest.identifier]: AgentBuilderInterventions,+ [AgentMarketplaceManifest.identifier]: AgentMarketplaceInterventions,[CloudSandboxManifest.identifier]: CloudSandboxInterventions,[GroupManagementManifest.identifier]: GroupManagementInterventions,[GTDManifest.identifier]: GTDInterventions,diff --git a/packages/business/const/src/llm.ts b/packages/business/const/src/llm.tsindex 31b5f888507..8a70becc8c0 100644--- a/packages/business/const/src/llm.ts+++ b/packages/business/const/src/llm.ts@@ -2,3 +2,5 @@ export const DEFAULT_EMBEDDING_PROVIDER = 'openai';export const DEFAULT_PROVIDER = 'anthropic';export const DEFAULT_MINI_PROVIDER = 'openai';++export const DEFAULT_ONBOARDING_MODEL = 'gemini-3-flash-preview';diff --git a/packages/const/src/settings/llm.ts b/packages/const/src/settings/llm.tsindex 5ecdd7520a6..212de4e90a9 100644--- a/packages/const/src/settings/llm.ts+++ b/packages/const/src/settings/llm.ts@@ -1,5 +1,4 @@export const DEFAULT_MODEL = 'claude-sonnet-4-6';-export const DEFAULT_ONBOARDING_MODEL = 'gemini-3-flash-preview';export const DEFAULT_MINI_MODEL = 'gpt-5.4-mini';export const DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small';diff --git a/packages/context-engine/src/providers/OnboardingActionHintInjector.ts b/packages/context-engine/src/providers/OnboardingActionHintInjector.tsindex c2291693180..dca7e7a88d0 100644--- a/packages/context-engine/src/providers/OnboardingActionHintInjector.ts+++ b/packages/context-engine/src/providers/OnboardingActionHintInjector.ts@@ -30,12 +30,38 @@ export class OnboardingActionHintInjector extends BaseVirtualLastUserContentProvreturn false;}- protected buildContent(_context: PipelineContext): string | null {+ protected buildContent(context: PipelineContext): string | null {const ctx = this.config.onboardingContext;if (!ctx) return null;const hints: string[] = [];const phase = ctx.phaseGuidance;+ // Detect prior showAgentMarketplace calls. NOTE: this provider runs in pipeline phase 4.5+ // (virtual tail guidance) BEFORE ToolCallProcessor converts the DB-shape `tools` array+ // into OpenAI-shape `tool_calls`. So at injection time, assistant messages still carry+ // `tools: [{ identifier, apiName, ... }]`, not `tool_calls`. Match on apiName here, with+ // a `tool_calls` fallback in case ordering changes.+ const isMarketplaceShowCall = (msg: any): boolean => {+ if (msg?.role !== 'assistant') return false;+ if (+ Array.isArray(msg.tools) &&+ msg.tools.some(+ (t: any) =>+ t?.apiName === 'showAgentMarketplace' || t?.identifier === 'lobe-agent-marketplace',+ )+ ) {+ return true;+ }+ if (Array.isArray(msg.tool_calls)) {+ return msg.tool_calls.some(+ (tc: any) =>+ typeof tc?.function?.name === 'string' &&+ tc.function.name.includes('showAgentMarketplace'),+ );+ }+ return false;+ };+ const marketplaceAlreadyOpened = context.messages.some((msg) => isMarketplaceShowCall(msg));// Detect empty documents and nudge tool calls (empty docs use writeDocument; non-empty use updateDocument)if (!ctx.soulContent) {@@ -66,20 +92,35 @@ export class OnboardingActionHintInjector extends BaseVirtualLastUserContentProv'Each turn where you learn a new fact (pain point, goal, preference, workflow detail, interest), call updateDocument(type="persona") BEFORE replying. Preferred shape: `{ mode: "insertAt", line: <line shown in <current_user_persona>>, content: "- new fact" }`. This is the default every turn — not an end-of-phase action. Do NOT save facts only in memory waiting for a final full write. After sufficient discovery (5-6 exchanges), also call saveUserQuestion with interests and responseLanguage. Use writeDocument(type="persona") only if the document is still empty.',);hints.push(- 'EARLY EXIT: If the user signals they want to finish (e.g., "好了", "谢谢", "行", "Done", asking for summary, or any completion signal), STOP exploring immediately. Save whatever fields you have (call saveUserQuestion with interests even if partial), present a brief summary, then call finishOnboarding. Do NOT continue asking questions after a completion signal.',+ 'EARLY EXIT: A true early-exit signal is the user explicitly wanting to END onboarding (e.g., "我累了", "我先走", "下次再聊", "没空", "暂时不弄了", "结束吧", "Thanks, that\'s enough", "I have to go"). Short affirmations like "好的" / "行" / "嗯" / "ok" are NOT early-exit signals — they confirm what you just said and you should keep exploring or move toward summary normally. When you see a real exit signal: stop exploring, save whatever fields you have (call saveUserQuestion with interests even if partial), present a brief summary, then call `showAgentMarketplace` and only after it resolves call `finishOnboarding`. Do NOT skip the marketplace step unless the user explicitly cancels/skips the picker.',);} else if (phase.includes('Summary')) {- hints.push(- 'Present a summary, then after user confirmation call finishOnboarding with a warm closing message. You MUST call finishOnboarding before the conversation ends — do not keep asking questions after the user confirms the summary.',- );+ if (!marketplaceAlreadyOpened) {+ hints.push(+ 'Present a summary, then THIS TURN call `showAgentMarketplace` exactly once with `{ requestId, categoryHints, prompt }` — pick 1–3 MarketplaceCategory slugs from what you learned in discovery. The picker is the required handoff that lets the user choose recommended assistants; do NOT skip it on normal completion. After the showAgentMarketplace tool result comes back, **STOP this turn** — no more tool calls and no closing text yet. The picker resolves directly via the tool result UI (the user will pick / skip in place); when it resolves, the runtime will start a NEW assistant turn whose tool result describes what was picked. The closing + `finishOnboarding` belong to that next turn.',+ );+ } else {+ hints.push(+ 'You have ALREADY opened the marketplace picker this conversation, and the user has just resolved it through the picker UI — the latest tool result describes what was picked (look for `installedAgentIds` / `selectedTemplateIds`, or a `skipped`/`cancelled` status). Do NOT call `showAgentMarketplace` again, do NOT claim you just opened the list, and do NOT wait for another user message. THIS TURN: (1) briefly acknowledge the picks (or the skip/cancel) in 1–2 sentences; (2) call `updateDocument(type="persona")` with `insertAt` mode to record the picks (categories/use cases) so future sessions remember; (3) call `finishOnboarding`. If the tool result indicates skip/cancel, skip step 2 and just close + `finishOnboarding`.',+ );+ }}hints.push('PERSISTENCE RULE: Call the persistence tools (saveUserQuestion, writeDocument, updateDocument) to save information as you collect it — simply acknowledging in conversation is NOT enough. For document writes: use writeDocument only for the first write when the document is empty; for every subsequent edit use updateDocument with the appropriate hunk mode (`insertAt` / `replaceLines` / `deleteLines` for line-based edits, `replace` / `delete` for byte-exact textual edits). The injected <current_*_document> view shows each line prefixed with its 1-based number and `→` — use those numbers for line-based hunks.',);hints.push(- 'REMINDER: If the user says "好了", "谢谢", "行", "Done", "Thanks", or gives any completion signal at ANY phase, you MUST wrap up immediately and call finishOnboarding. This overrides all other phase rules.',+ 'CONFIRMATION vs EARLY EXIT: Short replies like "好的" / "行" / "嗯" / "ok" / "可以" / "好" are CONFIRMATIONS, not early-exit signals. Continue the current phase normally — in Summary that means calling `showAgentMarketplace` next, NOT `finishOnboarding` directly.',);+ if (+ phase.includes('Agent Identity') ||+ phase.includes('User Identity') ||+ phase.includes('Discovery')+ ) {+ hints.push(+ 'EARLY EXIT REMINDER: A true early-exit signal means the user explicitly wants the onboarding to END — examples: "我累了", "我先走", "下次再聊", "没空", "暂时不弄了", "结束吧", "Thanks, that\'s enough", "I have to go". When you see one (and only then), persist any unsaved fields, give a brief summary, then call `showAgentMarketplace` once and only after the picker resolves call `finishOnboarding`. Skip the picker only if the user explicitly refuses it in words ("不用推荐", "别给我装东西", "skip the picker"); a generic exit signal is NOT a refusal of the picker.',+ );+ }return `<next_actions>\n${hints.join('\n')}\n</next_actions>`;}diff --git a/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts b/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.tsnew file mode 100644index 00000000000..5fcbaa59375--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { OnboardingActionHintInjector } from '../OnboardingActionHintInjector';++const createContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+});++const buildProvider = (phaseGuidance: string) =>+ new OnboardingActionHintInjector({+ enabled: true,+ onboardingContext: {+ personaContent: '# Persona',+ phaseGuidance,+ soulContent: '# SOUL',+ },+ });++describe('OnboardingActionHintInjector', () => {+ describe('marketplace detection (Summary phase)', () => {+ const phaseGuidance = 'Phase: Summary. Wrap-up.';++ it('uses the not-opened branch when no prior showAgentMarketplace tool call exists', async () => {+ const provider = buildProvider(phaseGuidance);+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: 'hi', role: 'user' },+ { content: 'hello', role: 'assistant' },+ ]),+ );+ const last = result.messages.at(-1);+ expect(last?.role).toBe('user');+ expect(last?.content).toContain('THIS TURN call `showAgentMarketplace`');+ expect(last?.content).not.toContain('ALREADY opened');+ });++ it('detects DB-shape `tools` array with apiName=showAgentMarketplace', async () => {+ const provider = buildProvider(phaseGuidance);+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: 'hi', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tools: [+ {+ apiName: 'showAgentMarketplace',+ arguments: '{}',+ id: 'call_1',+ identifier: 'lobe-agent-marketplace',+ type: 'default',+ },+ ],+ },+ ]),+ );+ const last = result.messages.at(-1);+ expect(last?.content).toContain('ALREADY opened');+ expect(last?.content).not.toContain('THIS TURN call `showAgentMarketplace`');+ });++ it('detects OpenAI-shape `tool_calls` array as a fallback', async () => {+ const provider = buildProvider(phaseGuidance);+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: 'hi', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ {+ function: {+ arguments: '{}',+ name: 'lobe-agent-marketplace____showAgentMarketplace____builtin',+ },+ id: 'call_1',+ type: 'function',+ },+ ],+ },+ ]),+ );+ const last = result.messages.at(-1);+ expect(last?.content).toContain('ALREADY opened');+ });++ it('does not flag unrelated tool calls', async () => {+ const provider = buildProvider(phaseGuidance);+ const result = await provider.process(+ createContext([+ { content: 'sys', role: 'system' },+ { content: 'hi', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tools: [+ {+ apiName: 'saveUserQuestion',+ arguments: '{}',+ id: 'call_1',+ identifier: 'lobe-web-onboarding',+ type: 'default',+ },+ ],+ },+ ]),+ );+ const last = result.messages.at(-1);+ expect(last?.content).toContain('THIS TURN call `showAgentMarketplace`');+ expect(last?.content).not.toContain('ALREADY opened');+ });+ });+});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 3e207029b6f..f2d4cbb5274 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -9,6 +9,11 @@ import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;+type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {+ onboardingSession?: OnboardingSessionMetadataPatch;+};+export interface CreateTopicParams {agentId?: string | null;favorite?: boolean;@@ -703,17 +708,26 @@ export class TopicModel {* Update topic metadata with merge logic* This method merges new metadata with existing metadata instead of replacing it*/- updateMetadata = async (id: string, metadata: Partial<ChatTopicMetadata>) => {+ updateMetadata = async (id: string, metadata: TopicMetadataPatch) => {// Get existing topic to merge metadataconst existing = await this.db.query.topics.findFirst({columns: { metadata: true },where: and(eq(topics.id, id), eq(topics.userId, this.userId)),});- const mergedMetadata: ChatTopicMetadata = {+ const mergedOnboardingSession =+ existing?.metadata?.onboardingSession && metadata.onboardingSession+ ? {+ ...existing.metadata.onboardingSession,+ ...metadata.onboardingSession,+ }+ : metadata.onboardingSession;++ const mergedMetadata = {...existing?.metadata,...metadata,- };+ ...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),+ } as ChatTopicMetadata;return this.db.update(topics)diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex ae733befb3e..37d8e186967 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -335,8 +335,8 @@ export interface BuiltinInterventionProps<Arguments = any> {onInteractionAction?: (action:| { type: 'submit'; payload: Record<string, unknown> }- | { type: 'skip'; reason?: string }- | { type: 'cancel' },+ | { type: 'skip'; payload?: Record<string, unknown>; reason?: string }+ | { type: 'cancel'; payload?: Record<string, unknown> },) => Promise<void>;/*** Register a callback to be called before approvaldiff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 394d64bb55d..b120bb2e640 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -41,8 +41,20 @@ export interface OnboardingFeedbackEntry {submittedAt: string;}+export interface OnboardingAgentMarketplacePickSnapshot {+ categoryHints: string[];+ installedAgentIds?: string[];+ requestId: string;+ resolvedAt: string;+ selectedTemplateIds?: string[];+ skippedAgentIds?: string[];+ skipReason?: string;+ status: 'cancelled' | 'skipped' | 'submitted';+}+export interface OnboardingSessionSnapshot {agentIdentityCompletedAt?: string;+ agentMarketplacePick?: OnboardingAgentMarketplacePickSnapshot;discoveryCompletedAt?: string;finalAgentNames?: string[];finishedAt?: string;diff --git a/packages/types/src/user/agentOnboarding.test.ts b/packages/types/src/user/agentOnboarding.test.tsindex 2db300cd8dc..468dc8d5480 100644--- a/packages/types/src/user/agentOnboarding.test.ts+++ b/packages/types/src/user/agentOnboarding.test.ts@@ -20,6 +20,34 @@ describe('SaveUserQuestionInputSchema', () => {it('rejects the old node-scoped payload', () => {expect(() => SaveUserQuestionInputSchema.parse({ updates: [] })).toThrow();});++ it('treats empty and whitespace strings as missing', () => {+ const parsed = SaveUserQuestionInputSchema.parse({+ agentEmoji: '',+ agentName: ' ',+ fullName: 'Ada Lovelace',+ responseLanguage: '',+ });++ expect(parsed).toEqual({ fullName: 'Ada Lovelace' });+ });++ it('drops empty interests entries and an all-empty array', () => {+ const partial = SaveUserQuestionInputSchema.parse({+ interests: ['AI tooling', '', ' '],+ });+ expect(partial).toEqual({ interests: ['AI tooling'] });++ const allEmpty = SaveUserQuestionInputSchema.parse({+ fullName: 'Ada',+ interests: ['', ' '],+ });+ expect(allEmpty).toEqual({ fullName: 'Ada' });+ });++ it('accepts a fully empty object as a no-op', () => {+ expect(SaveUserQuestionInputSchema.parse({})).toEqual({});+ });});describe('UserAgentOnboardingContextSchema', () => {diff --git a/packages/types/src/user/agentOnboarding.ts b/packages/types/src/user/agentOnboarding.tsindex 844933dcf86..604109b172d 100644--- a/packages/types/src/user/agentOnboarding.ts+++ b/packages/types/src/user/agentOnboarding.ts@@ -173,7 +173,22 @@ export interface UserAgentOnboardingDraft {workStyle?: Partial<UserOnboardingDimensionWorkStyle>;}-const TrimmedNonEmptyStringSchema = z.string().trim().min(1);+// LLMs often emit "" for tool-call fields they have no value for. Treat empty/+// whitespace strings as missing so partial saveUserQuestion calls pass validation;+// OnboardingService.saveUserQuestion already ignores empty strings downstream.+const OptionalTrimmedNonEmptyStringSchema = z+ .string()+ .trim()+ .transform((value) => (value.length > 0 ? value : undefined))+ .optional();++const OptionalTrimmedNonEmptyStringArraySchema = z+ .array(z.string())+ .transform((items) => {+ const filtered = items.map((item) => item.trim()).filter((item) => item.length > 0);+ return filtered.length > 0 ? filtered : undefined;+ })+ .optional();export const SaveUserQuestionFieldSchema = z.enum(SAVE_USER_QUESTION_FIELDS);export const AgentOnboardingStructuredFieldSchema = SaveUserQuestionFieldSchema;@@ -181,11 +196,11 @@ export const UserAgentOnboardingNodeSchema = z.enum(AGENT_ONBOARDING_NODES);export const SaveUserQuestionInputSchema = z.object({- agentEmoji: TrimmedNonEmptyStringSchema.optional(),- agentName: TrimmedNonEmptyStringSchema.optional(),- fullName: TrimmedNonEmptyStringSchema.optional(),- interests: z.array(TrimmedNonEmptyStringSchema).optional(),- responseLanguage: TrimmedNonEmptyStringSchema.optional(),+ agentEmoji: OptionalTrimmedNonEmptyStringSchema,+ agentName: OptionalTrimmedNonEmptyStringSchema,+ fullName: OptionalTrimmedNonEmptyStringSchema,+ interests: OptionalTrimmedNonEmptyStringArraySchema,+ responseLanguage: OptionalTrimmedNonEmptyStringSchema,}).strict();diff --git a/src/const/onboarding.ts b/src/const/onboarding.tsindex d21002d77a9..d5f47b859f6 100644--- a/src/const/onboarding.ts+++ b/src/const/onboarding.ts@@ -1,5 +1,4 @@-import { DEFAULT_PROVIDER } from '@lobechat/business-const';-import { DEFAULT_ONBOARDING_MODEL } from '@lobechat/const';+import { DEFAULT_ONBOARDING_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';export const ONBOARDING_PRODUCTION_DEFAULT_MODEL = {model: DEFAULT_ONBOARDING_MODEL,diff --git a/src/features/Conversation/ChatItem/components/Actions.tsx b/src/features/Conversation/ChatItem/components/Actions.tsxindex f422c9d22b5..4e46c67085e 100644--- a/src/features/Conversation/ChatItem/components/Actions.tsx+++ b/src/features/Conversation/ChatItem/components/Actions.tsx@@ -1,6 +1,11 @@import { Flexbox } from '@lobehub/ui';import { memo } from 'react';+import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';+import { isDev } from '@/utils/env';++import { contextSelectors, useConversationStore } from '../../store';import { type ChatItemProps } from '../type';export interface ActionsProps {@@ -9,6 +14,10 @@ export interface ActionsProps {}const Actions = memo<ActionsProps>(({ placement, actions }) => {+ const onboardingAgentId = useAgentStore(builtinAgentSelectors.webOnboardingAgentId);+ const conversationAgentId = useConversationStore(contextSelectors.agentId);+ if (!isDev && onboardingAgentId && conversationAgentId === onboardingAgentId) return null;+const isUser = placement === 'right';return (<Flexboxdiff --git a/src/features/Conversation/InterventionBar/InterventionContent.tsx b/src/features/Conversation/InterventionBar/InterventionContent.tsxindex 513953145e7..ddef30d06c7 100644--- a/src/features/Conversation/InterventionBar/InterventionContent.tsx+++ b/src/features/Conversation/InterventionBar/InterventionContent.tsx@@ -5,22 +5,26 @@ import { type PendingIntervention } from '../store/slices/data/pendingInterventiimport { styles } from './style';interface InterventionContentProps {+ actionsPortalTarget: HTMLDivElement | null;intervention: PendingIntervention;}-const InterventionContent = memo<InterventionContentProps>(({ intervention }) => {- return (- <div className={styles.content}>- <Intervention- apiName={intervention.apiName}- assistantGroupId={intervention.assistantGroupId}- id={intervention.toolMessageId}- identifier={intervention.identifier}- requestArgs={intervention.requestArgs}- toolCallId={intervention.toolCallId}- />- </div>- );-});+const InterventionContent = memo<InterventionContentProps>(+ ({ intervention, actionsPortalTarget }) => {+ return (+ <div className={styles.content}>+ <Intervention+ actionsPortalTarget={actionsPortalTarget}+ apiName={intervention.apiName}+ assistantGroupId={intervention.assistantGroupId}+ id={intervention.toolMessageId}+ identifier={intervention.identifier}+ requestArgs={intervention.requestArgs}+ toolCallId={intervention.toolCallId}+ />+ </div>+ );+ },+);export default InterventionContent;diff --git a/src/features/Conversation/InterventionBar/index.tsx b/src/features/Conversation/InterventionBar/index.tsxindex 50be1bcf698..41f10e4ad59 100644--- a/src/features/Conversation/InterventionBar/index.tsx+++ b/src/features/Conversation/InterventionBar/index.tsx@@ -12,6 +12,7 @@ interface InterventionBarProps {const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {const [activeId, setActiveId] = useState<string | null>(null);+ const [actionsPortalTarget, setActionsPortalTarget] = useState<HTMLDivElement | null>(null);// Derive the active index from the stored toolCallId.// Falls back to the first intervention when the previously active one is resolved.@@ -34,7 +35,12 @@ const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {if (!activeIntervention) return null;return (- <ChatInput className={styles.container} maxHeight={'50vh' as any} resize={false}>+ <ChatInput+ className={styles.container}+ footer={<div className={styles.actions} ref={setActionsPortalTarget} />}+ maxHeight={'50vh' as any}+ resize={false}+ >{interventions.length > 1 && (<InterventionTabBaractiveIndex={activeIndex}@@ -42,7 +48,11 @@ const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {onTabChange={handleTabChange}/>)}- <InterventionContent intervention={activeIntervention} key={activeIntervention.toolCallId} />+ <InterventionContent+ actionsPortalTarget={actionsPortalTarget}+ intervention={activeIntervention}+ key={activeIntervention.toolCallId}+ /></ChatInput>);});diff --git a/src/features/Conversation/InterventionBar/style.ts b/src/features/Conversation/InterventionBar/style.tsindex 2e80feaa65b..44e04302a98 100644--- a/src/features/Conversation/InterventionBar/style.ts+++ b/src/features/Conversation/InterventionBar/style.ts@@ -5,6 +5,10 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({padding-block: 8px;padding-inline: 16px;border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ &:empty {+ display: none;+ }`,container: css`margin-block-end: 12px;diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.tsnew file mode 100644index 00000000000..70024ea0510--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts@@ -0,0 +1,94 @@+import { AgentMarketplaceIdentifier } from '@lobechat/builtin-tool-agent-marketplace';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ prepareCustomInteractionSubmit,+ recordCustomInteractionResolution,+} from './customInteractionHandlers';+import { installMarketplaceAgents } from './installMarketplaceAgents';++vi.mock('./installMarketplaceAgents', () => ({+ installMarketplaceAgents: vi.fn(),+}));++describe('customInteractionHandlers', () => {+ const updateTopicMetadata = vi.fn();++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-04-29T10:00:00.000Z'));+ vi.mocked(installMarketplaceAgents).mockReset();+ updateTopicMetadata.mockReset();+ updateTopicMetadata.mockResolvedValue(undefined);+ });++ it('persists submitted marketplace picks to onboardingSession metadata', async () => {+ vi.mocked(installMarketplaceAgents).mockResolvedValue({+ installedAgentIds: ['agent-1'],+ skippedAgentIds: ['template-existing'],+ });++ const result = await prepareCustomInteractionSubmit(+ AgentMarketplaceIdentifier,+ {+ categoryHints: ['engineering'],+ requestId: 'req-1',+ selectedTemplateIds: ['template-1', 'template-existing'],+ },+ {+ topicId: 'topic-1',+ updateTopicMetadata,+ },+ );++ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ onboardingSession: {+ agentMarketplacePick: {+ categoryHints: ['engineering'],+ installedAgentIds: ['agent-1'],+ requestId: 'req-1',+ resolvedAt: '2026-04-29T10:00:00.000Z',+ selectedTemplateIds: ['template-1', 'template-existing'],+ skippedAgentIds: ['template-existing'],+ status: 'submitted',+ },+ lastActiveAt: '2026-04-29T10:00:00.000Z',+ },+ });+ expect(result.payload).toMatchObject({+ installedAgentIds: ['agent-1'],+ skippedAgentIds: ['template-existing'],+ });+ expect(result.options?.createUserMessage).toBe(false);+ });++ it('persists skipped marketplace picks from the original tool arguments', async () => {+ await recordCustomInteractionResolution(+ AgentMarketplaceIdentifier,+ 'skipped',+ undefined,+ {+ requestArgs: {+ categoryHints: ['design-creative'],+ requestId: 'req-2',+ },+ topicId: 'topic-1',+ updateTopicMetadata,+ },+ 'not now',+ );++ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ onboardingSession: {+ agentMarketplacePick: {+ categoryHints: ['design-creative'],+ requestId: 'req-2',+ resolvedAt: '2026-04-29T10:00:00.000Z',+ skipReason: 'not now',+ status: 'skipped',+ },+ lastActiveAt: '2026-04-29T10:00:00.000Z',+ },+ });+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsnew file mode 100644index 00000000000..f6ce9cbdef1--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -0,0 +1,166 @@+import { AgentMarketplaceIdentifier } from '@lobechat/builtin-tool-agent-marketplace';+import { UserInteractionIdentifier } from '@lobechat/builtin-tool-user-interaction';+import type { OnboardingAgentMarketplacePickSnapshot } from '@lobechat/types';++import { topicService } from '@/services/topic';++import { installMarketplaceAgents } from './installMarketplaceAgents';++interface SubmitToolInteractionOptions {+ createUserMessage?: boolean;+ toolResultContent?: string;+}++interface CustomInteractionSubmitResult {+ options?: SubmitToolInteractionOptions;+ payload: Record<string, unknown>;+}++interface CustomInteractionContext {+ requestArgs?: Record<string, unknown>;+ topicId?: string | null;+ updateTopicMetadata?: typeof topicService.updateTopicMetadata;+}++type CustomInteractionSubmitHandler = (+ payload: Record<string, unknown>,+ context?: CustomInteractionContext,+) => Promise<CustomInteractionSubmitResult | undefined>;++const isStringArray = (value: unknown): value is string[] =>+ Array.isArray(value) && value.every((item) => typeof item === 'string');++const pickString = (value: unknown) => (typeof value === 'string' ? value : undefined);++const resolveMarketplacePickBase = (+ payload: Record<string, unknown>,+ requestArgs?: Record<string, unknown>,+) => {+ const requestId = pickString(payload.requestId) ?? pickString(requestArgs?.requestId);+ if (!requestId) return;++ const categoryHints = isStringArray(payload.categoryHints)+ ? payload.categoryHints+ : isStringArray(requestArgs?.categoryHints)+ ? requestArgs.categoryHints+ : [];++ return { categoryHints, requestId };+};++const persistAgentMarketplacePick = async (+ context: CustomInteractionContext | undefined,+ agentMarketplacePick: OnboardingAgentMarketplacePickSnapshot,+) => {+ if (!context?.topicId) return;++ try {+ await (context.updateTopicMetadata ?? topicService.updateTopicMetadata)(context.topicId, {+ onboardingSession: {+ agentMarketplacePick,+ lastActiveAt: agentMarketplacePick.resolvedAt,+ },+ });+ } catch (error) {+ console.error('[AgentMarketplace] failed to persist pick metadata', error);+ }+};++const buildAgentMarketplaceToolResult = (params: {+ installedAgentIds: string[];+ selectedAgentIds: string[];+ skippedAgentIds: string[];+}) => {+ const { selectedAgentIds, installedAgentIds, skippedAgentIds } = params;+ const lines = [+ `User has finished picking from the marketplace. They selected ${selectedAgentIds.length} agent template(s); the agents are now forked into the user's library and ready to use. The user has already completed this step in the UI — do NOT thank them for opening the picker or claim you "opened the list" again.`,+ `selectedTemplateIds: ${JSON.stringify(selectedAgentIds)}`,+ `installedAgentIds: ${JSON.stringify(installedAgentIds)}`,+ ];+ if (skippedAgentIds.length > 0) {+ lines.push(+ `skippedAgentIds (already in library, not re-installed): ${JSON.stringify(skippedAgentIds)}`,+ );+ }+ lines.push(+ 'THIS TURN — required actions to wrap up onboarding:',+ '1) Briefly acknowledge the picks in 1–2 sentences (no need to enumerate every template by name; reference the categories/themes you can infer).',+ '2) Call updateDocument(type="persona") to append a short note about the assistants the user picked (their categories/use cases) so future sessions remember.',+ '3) Call finishOnboarding to complete onboarding.',+ 'Do NOT call showAgentMarketplace again. Do NOT ask the user to pick anything else.',+ );+ return lines.join('\n');+};++const handleAgentMarketplaceSubmit: CustomInteractionSubmitHandler = async (payload, context) => {+ const selectedAgentIds = payload.selectedTemplateIds;+ if (!isStringArray(selectedAgentIds)) return;++ const result = await installMarketplaceAgents(selectedAgentIds);+ const pickBase = resolveMarketplacePickBase(payload, context?.requestArgs);++ if (pickBase) {+ await persistAgentMarketplacePick(context, {+ ...pickBase,+ installedAgentIds: result.installedAgentIds,+ resolvedAt: new Date().toISOString(),+ selectedTemplateIds: selectedAgentIds,+ skippedAgentIds: result.skippedAgentIds,+ status: 'submitted',+ });+ }++ return {+ options: {+ createUserMessage: false,+ toolResultContent: buildAgentMarketplaceToolResult({+ installedAgentIds: result.installedAgentIds,+ selectedAgentIds,+ skippedAgentIds: result.skippedAgentIds,+ }),+ },+ payload: {+ ...payload,+ installedAgentIds: result.installedAgentIds,+ skippedAgentIds: result.skippedAgentIds,+ },+ };+};++const customInteractionSubmitHandlers = new Map<string, CustomInteractionSubmitHandler>([+ [AgentMarketplaceIdentifier, handleAgentMarketplaceSubmit],+]);++export const isCustomInteractionIdentifier = (identifier: string) =>+ identifier === UserInteractionIdentifier || customInteractionSubmitHandlers.has(identifier);++export const prepareCustomInteractionSubmit = async (+ identifier: string,+ payload: Record<string, unknown>,+ context?: CustomInteractionContext,+): Promise<CustomInteractionSubmitResult> => {+ const handler = customInteractionSubmitHandlers.get(identifier);+ const result = await handler?.(payload, context);++ return result ?? { payload };+};++export const recordCustomInteractionResolution = async (+ identifier: string,+ status: 'cancelled' | 'skipped',+ payload: Record<string, unknown> | undefined,+ context?: CustomInteractionContext,+ reason?: string,+) => {+ if (identifier !== AgentMarketplaceIdentifier) return;++ const pickBase = resolveMarketplacePickBase(payload ?? {}, context?.requestArgs);+ if (!pickBase) return;++ await persistAgentMarketplacePick(context, {+ ...pickBase,+ resolvedAt: new Date().toISOString(),+ ...(reason && { skipReason: reason }),+ status,+ });+};diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex e69250185c3..68eb8fe66b4 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -1,4 +1,3 @@-import { UserInteractionIdentifier } from '@lobechat/builtin-tool-user-interaction';import { getBuiltinIntervention } from '@lobechat/builtin-tools/interventions';import { safeParseJSON } from '@lobechat/utils';import { Flexbox } from '@lobehub/ui';@@ -8,9 +7,14 @@ import { createPortal } from 'react-dom';import { useUserStore } from '@/store/user';import { toolInterventionSelectors } from '@/store/user/selectors';-import { useConversationStore } from '../../../../../store';+import { dataSelectors, useConversationStore } from '../../../../../store';import Arguments from '../Arguments';import ApprovalActions from './ApprovalActions';+import {+ isCustomInteractionIdentifier,+ prepareCustomInteractionSubmit,+ recordCustomInteractionResolution,+} from './customInteractionHandlers';import Fallback from './Fallback';import KeyValueEditor from './KeyValueEditor';import SecurityBlacklistWarning from './SecurityBlacklistWarning';@@ -88,8 +92,9 @@ const Intervention = memo<InterventionProps>(const parsedArgs = useMemo(() => safeParseJSON(requestArgs || '') ?? {}, [requestArgs]);- const isCustomInteraction = identifier === UserInteractionIdentifier;+ const isCustomInteraction = isCustomInteractionIdentifier(identifier);+ const topicId = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s)?.topicId);const submitToolInteraction = useConversationStore((s) => s.submitToolInteraction);const skipToolInteraction = useConversationStore((s) => s.skipToolInteraction);const cancelToolInteraction = useConversationStore((s) => s.cancelToolInteraction);@@ -98,25 +103,55 @@ const Intervention = memo<InterventionProps>(async (action:| { type: 'submit'; payload: Record<string, unknown> }- | { type: 'skip'; reason?: string }- | { type: 'cancel' },+ | { type: 'skip'; payload?: Record<string, unknown>; reason?: string }+ | { type: 'cancel'; payload?: Record<string, unknown> },) => {switch (action.type) {case 'submit': {- await submitToolInteraction(id, action.payload);+ const { payload, options } = await prepareCustomInteractionSubmit(+ identifier,+ action.payload,+ {+ requestArgs: parsedArgs,+ topicId,+ },+ );+ await submitToolInteraction(id, payload, options);break;}case 'skip': {+ await recordCustomInteractionResolution(+ identifier,+ 'skipped',+ action.payload,+ {+ requestArgs: parsedArgs,+ topicId,+ },+ action.reason,+ );await skipToolInteraction(id, action.reason);break;}case 'cancel': {+ await recordCustomInteractionResolution(identifier, 'cancelled', action.payload, {+ requestArgs: parsedArgs,+ topicId,+ });await cancelToolInteraction(id);break;}}},- [id, submitToolInteraction, skipToolInteraction, cancelToolInteraction],+ [+ cancelToolInteraction,+ id,+ identifier,+ parsedArgs,+ skipToolInteraction,+ submitToolInteraction,+ topicId,+ ],);const BuiltinToolInterventionRender = getBuiltinIntervention(identifier, apiName);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.tsnew file mode 100644index 00000000000..b4c70e94424--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/installMarketplaceAgents.ts@@ -0,0 +1,88 @@+import { customAlphabet } from 'nanoid/non-secure';++import { agentService } from '@/services/agent';+import { discoverService } from '@/services/discover';+import { marketApiService } from '@/services/marketApi';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';++const generateMarketIdentifier = () => {+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';+ const generate = customAlphabet(alphabet, 8);+ return generate();+};++const getSourcePath = () => {+ if (typeof location === 'undefined') return 'onboarding/agent-marketplace';++ return location.pathname;+};++export interface InstallMarketplaceAgentsResult {+ installedAgentIds: string[];+ skippedAgentIds: string[];+}++export const installMarketplaceAgents = async (+ sourceAgentIds: string[],+): Promise<InstallMarketplaceAgentsResult> => {+ const installedAgentIds: string[] = [];+ const skippedAgentIds: string[] = [];+ const createAgent = useAgentStore.getState().createAgent;+ const refreshAgentList = useHomeStore.getState().refreshAgentList;++ for (const sourceAgentId of sourceAgentIds) {+ const existingAgentId = await agentService.getAgentByForkedFromIdentifier(sourceAgentId);+ if (existingAgentId) {+ skippedAgentIds.push(sourceAgentId);+ continue;+ }++ const marketAgent = await discoverService.getAssistantDetail({+ identifier: sourceAgentId,+ source: 'new',+ });++ if (!marketAgent?.config) {+ throw new Error(`Marketplace agent config is missing: ${sourceAgentId}`);+ }++ const forkResult = await marketApiService.forkAgent(sourceAgentId, {+ identifier: generateMarketIdentifier(),+ name: marketAgent.title,+ status: 'published',+ visibility: 'public',+ });++ const result = await createAgent({+ config: {+ ...marketAgent.config,+ avatar: marketAgent.avatar,+ backgroundColor: marketAgent.backgroundColor,+ description: marketAgent.description,+ editorData: marketAgent.editorData,+ marketIdentifier: forkResult.agent.identifier,+ params: {+ ...marketAgent.config.params,+ forkedFromIdentifier: sourceAgentId,+ },+ tags: marketAgent.tags,+ title: forkResult.agent.name,+ },+ });++ installedAgentIds.push(result.agentId);++ discoverService.reportAgentEvent({+ event: 'add',+ identifier: forkResult.agent.identifier,+ source: getSourcePath(),+ });+ }++ if (installedAgentIds.length > 0) {+ await refreshAgentList();+ }++ return { installedAgentIds, skippedAgentIds };+};diff --git a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx b/src/features/Conversation/Messages/components/Extras/Usage/index.tsxindex 3d0b8014310..1c7c5513253 100644--- a/src/features/Conversation/Messages/components/Extras/Usage/index.tsx+++ b/src/features/Conversation/Messages/components/Extras/Usage/index.tsx@@ -5,6 +5,11 @@ import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';import { memo } from 'react';+import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';+import { isDev } from '@/utils/env';++import { contextSelectors, useConversationStore } from '../../../../store';import TokenDetail from './UsageDetail';export const styles = createStaticStyles(({ css, cssVar }) => ({@@ -22,6 +27,11 @@ interface UsageProps {}const Usage = memo<UsageProps>(({ model, usage, performance, provider }) => {+ const onboardingAgentId = useAgentStore(builtinAgentSelectors.webOnboardingAgentId);+ const conversationAgentId = useConversationStore(contextSelectors.agentId);++ if (!isDev && onboardingAgentId && conversationAgentId === onboardingAgentId) return null;+return (<Flexboxhorizontaldiff --git a/src/features/Conversation/store/slices/tool/action.ts b/src/features/Conversation/store/slices/tool/action.tsindex 5a286fcc5f0..05df0ad4b63 100644--- a/src/features/Conversation/store/slices/tool/action.ts+++ b/src/features/Conversation/store/slices/tool/action.ts@@ -32,6 +32,7 @@ export interface ToolAction {submitToolInteraction: (toolMessageId: string,response: Record<string, unknown>,+ options?: { createUserMessage?: boolean; toolResultContent?: string },) => Promise<void>;}@@ -127,9 +128,13 @@ export const toolSlice: StateCreator<await chatStore.skipToolInteraction(toolMessageId, reason, context);},- submitToolInteraction: async (toolMessageId: string, response: Record<string, unknown>) => {+ submitToolInteraction: async (+ toolMessageId: string,+ response: Record<string, unknown>,+ options?: { createUserMessage?: boolean; toolResultContent?: string },+ ) => {const { context } = get();const chatStore = useChatStore.getState();- await chatStore.submitToolInteraction(toolMessageId, response, context);+ await chatStore.submitToolInteraction(toolMessageId, response, context, options);},});diff --git a/src/features/Onboarding/Agent/AnalyticsBridge.test.tsx b/src/features/Onboarding/Agent/AnalyticsBridge.test.tsxnew file mode 100644index 00000000000..24a8b73be08--- /dev/null+++ b/src/features/Onboarding/Agent/AnalyticsBridge.test.tsx@@ -0,0 +1,46 @@+import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { setOnboardingAnalyticsClient } from '@/services/onboardingMetrics';++import AnalyticsBridge from './AnalyticsBridge';++vi.mock('@/services/onboardingMetrics', () => ({+ setOnboardingAnalyticsClient: vi.fn(),+}));++const useAnalyticsMock = vi.fn();+vi.mock('@lobehub/analytics/react', () => ({+ useAnalytics: () => useAnalyticsMock(),+}));++const setterMock = vi.mocked(setOnboardingAnalyticsClient);++afterEach(() => {+ cleanup();+ setterMock.mockClear();+ useAnalyticsMock.mockReset();+});++describe('AgentOnboardingAnalyticsBridge', () => {+ it('injects the analytics client on mount and clears it on unmount', () => {+ const analytics = { track: vi.fn() };+ useAnalyticsMock.mockReturnValue({ analytics });++ const { unmount } = render(<AnalyticsBridge />);++ expect(setterMock).toHaveBeenCalledTimes(1);+ expect(setterMock).toHaveBeenLastCalledWith(analytics);++ unmount();+ expect(setterMock).toHaveBeenLastCalledWith(null);+ });++ it('passes null when useAnalytics has no client yet', () => {+ useAnalyticsMock.mockReturnValue({ analytics: null });++ render(<AnalyticsBridge />);++ expect(setterMock).toHaveBeenCalledWith(null);+ });+});diff --git a/src/features/Onboarding/Agent/AnalyticsBridge.tsx b/src/features/Onboarding/Agent/AnalyticsBridge.tsxnew file mode 100644index 00000000000..1de5f01ae0a--- /dev/null+++ b/src/features/Onboarding/Agent/AnalyticsBridge.tsx@@ -0,0 +1,21 @@+'use client';++import { useAnalytics } from '@lobehub/analytics/react';+import { memo, useEffect } from 'react';++import { setOnboardingAnalyticsClient } from '@/services/onboardingMetrics';++const AnalyticsBridge = memo(() => {+ const { analytics } = useAnalytics();++ useEffect(() => {+ setOnboardingAnalyticsClient(analytics ?? null);+ return () => setOnboardingAnalyticsClient(null);+ }, [analytics]);++ return null;+});++AnalyticsBridge.displayName = 'AgentOnboardingAnalyticsBridge';++export default AnalyticsBridge;diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsxindex a0cf451c2e9..22e1f3caed2 100644--- a/src/features/Onboarding/Agent/index.tsx+++ b/src/features/Onboarding/Agent/index.tsx@@ -1,6 +1,7 @@'use client';import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { setAgentTemplatesFetcher } from '@lobechat/builtin-tool-agent-marketplace';import { SESSION_CHAT_TOPIC_URL } from '@lobechat/const';import { Button, ErrorBoundary, Flexbox } from '@lobehub/ui';import { Drawer } from 'antd';@@ -13,6 +14,7 @@ import Loading from '@/components/Loading/BrandTextLoading';import ModeSwitch from '@/features/Onboarding/components/ModeSwitch';import { useClientDataSWR, useOnlyFetchOnceSWR } from '@/libs/swr';import OnboardingContainer from '@/routes/onboarding/_layout';+import { fetchOnboardingAgentTemplates } from '@/services/agentMarketplace';import { topicService } from '@/services/topic';import { userService } from '@/services/user';import { useAgentStore } from '@/store/agent';@@ -20,6 +22,7 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';import { isDev } from '@/utils/env';+import AnalyticsBridge from './AnalyticsBridge';import { resolveAgentOnboardingContext } from './context';import AgentOnboardingConversation from './Conversation';import AgentOnboardingDebugExportButton from './DebugExportButton';@@ -60,6 +63,10 @@ const AgentOnboardingPage = memo(() => {useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.webOnboarding);+ useEffect(() => {+ setAgentTemplatesFetcher(fetchOnboardingAgentTemplates);+ }, []);+const { data: historyData, mutate: mutateHistoryTopics } = useClientDataSWR(isDev && onboardingAgentId ? ['agent-onboarding-history-topics', onboardingAgentId] : null,() =>@@ -134,6 +141,7 @@ const AgentOnboardingPage = memo(() => {return (<OnboardingContainer>+ <AnalyticsBridge /><Flexbox height={'100%'} width={'100%'}><OnboardingConversationProvideragentId={onboardingAgentId}diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex d47030c7864..5f02b6006d7 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -719,6 +719,14 @@ export default {'tool.intervention.onboarding.agentIdentity.targetOnboarding': 'Current onboarding Agent','tool.intervention.onboarding.agentIdentity.targets': 'Applies to','tool.intervention.onboarding.agentIdentity.title': 'Confirm Agent identity update',+ 'tool.intervention.onboarding.userProfile.applyHint':+ 'These details will be saved to your profile after approval.',+ 'tool.intervention.onboarding.userProfile.description':+ 'Approving this change updates your onboarding profile so the Agent can tailor future replies.',+ 'tool.intervention.onboarding.userProfile.eyebrow': 'Onboarding approval',+ 'tool.intervention.onboarding.userProfile.fullName': 'Full name',+ 'tool.intervention.onboarding.userProfile.responseLanguage': 'Response language',+ 'tool.intervention.onboarding.userProfile.title': 'Confirm your profile update','tool.intervention.reject': 'Reject','tool.intervention.rejectAndContinue': 'Reject and Retry','tool.intervention.rejectOnly': 'Reject',diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.tsindex de7d578fc5f..bba9aa68bc0 100644--- a/src/locales/default/tool.ts+++ b/src/locales/default/tool.ts@@ -19,6 +19,22 @@ export default {'agentGroupManagement.executeTasks.intervention.instructionPlaceholder':'Detailed instruction for the agent to perform this task...','agentGroupManagement.executeTasks.intervention.titlePlaceholder': 'Task title...',+ 'agentMarketplace.category.businessStrategy': 'Business & Strategy',+ 'agentMarketplace.category.contentCreation': 'Content Creation',+ 'agentMarketplace.category.creatorEconomy': 'Creator Economy',+ 'agentMarketplace.category.designCreative': 'Design & Creative',+ 'agentMarketplace.category.engineering': 'Engineering',+ 'agentMarketplace.category.financeLegal': 'Finance & Legal',+ 'agentMarketplace.category.learningResearch': 'Learning & Research',+ 'agentMarketplace.category.marketing': 'Marketing',+ 'agentMarketplace.category.operations': 'Operations',+ 'agentMarketplace.category.peopleHR': 'People & HR',+ 'agentMarketplace.category.personalLife': 'Personal Life',+ 'agentMarketplace.category.productManagement': 'Product Management',+ 'agentMarketplace.category.salesCustomer': 'Sales & Customer',+ 'agentMarketplace.picker.empty': 'No templates available.',+ 'agentMarketplace.picker.failedToLoad': 'Failed to load templates. Please try again later.',+ 'agentMarketplace.picker.summary': '{{filtered}} / {{total}} templates available.','codeInterpreter-legacy.error': 'Execution Error','codeInterpreter-legacy.executing': 'Executing...','codeInterpreter-legacy.files': 'Files:',diff --git a/src/server/routers/lambda/market/agent.ts b/src/server/routers/lambda/market/agent.tsindex fd067f0b7f6..c45d35b18cb 100644--- a/src/server/routers/lambda/market/agent.ts+++ b/src/server/routers/lambda/market/agent.ts@@ -407,6 +407,57 @@ export const agentRouter = router({}}),+ /**+ * Get the full curated onboarding agent catalog for the marketplace picker.+ * Proxies to GET /api/v1/agents/onboarding-full with trust-token authentication.+ * Response is keyed by MarketplaceCategory slug.+ */+ getOnboardingFull: agentProcedure.query(async ({ ctx }) => {+ const url = `${MARKET_BASE_URL}/api/v1/agents/onboarding-full?_ts=${Date.now()}`;++ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ };++ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;++ if (userInfo) {+ const trustedClientToken = generateTrustedClientToken(userInfo);+ if (trustedClientToken) {+ headers['x-lobe-trust-token'] = trustedClientToken;+ }+ }++ if (!headers['x-lobe-trust-token'] && accessToken) {+ headers['Authorization'] = `Bearer ${accessToken}`;+ }++ try {+ const response = await fetch(url, { headers, method: 'GET' });++ if (!response.ok) {+ const errorText = await response.text();+ log(+ 'Get onboarding full failed: %s %s - %s',+ response.status,+ response.statusText,+ errorText,+ );+ throw new Error(`Failed to get onboarding full: ${response.statusText}`);+ }++ return (await response.json()) as Record<string, unknown[]>;+ } catch (error) {+ log('Error getting onboarding full: %O', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: error instanceof Error ? error.message : 'Failed to get onboarding full',+ });+ }+ }),+/*** Get the fork source of an agent* GET /market/agent/:identifier/fork-sourcediff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex 267ccf8b80d..7aa40d0d654 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -594,14 +594,26 @@ export const topicRouter = router({onboardingSession: z.object({agentIdentityCompletedAt: z.string().optional(),+ agentMarketplacePick: z+ .object({+ categoryHints: z.array(z.string()),+ installedAgentIds: z.array(z.string()).optional(),+ requestId: z.string(),+ resolvedAt: z.string(),+ selectedTemplateIds: z.array(z.string()).optional(),+ skipReason: z.string().optional(),+ skippedAgentIds: z.array(z.string()).optional(),+ status: z.enum(['cancelled', 'skipped', 'submitted']),+ })+ .optional(),discoveryCompletedAt: z.string().optional(),finalAgentNames: z.array(z.string()).optional(),finishedAt: z.string().optional(),- lastActiveAt: z.string(),- phase: z.enum(['agent_identity', 'user_identity', 'discovery', 'summary']),- startedAt: z.string(),+ lastActiveAt: z.string().optional(),+ phase: z.enum(['agent_identity', 'user_identity', 'discovery', 'summary']).optional(),+ startedAt: z.string().optional(),userIdentityCompletedAt: z.string().optional(),- version: z.number(),+ version: z.number().optional(),}).optional(),provider: z.string().optional(),diff --git a/src/server/services/onboarding/index.test.ts b/src/server/services/onboarding/index.test.tsindex ec65f276c5a..deafb1c3d23 100644--- a/src/server/services/onboarding/index.test.ts+++ b/src/server/services/onboarding/index.test.ts@@ -314,6 +314,14 @@ describe('OnboardingService', () => {id: 'topic-1',metadata: {onboardingSession: {+ agentMarketplacePick: {+ categoryHints: ['engineering'],+ installedAgentIds: ['agent-1'],+ requestId: 'req-1',+ resolvedAt: '2026-04-16T00:30:00.000Z',+ selectedTemplateIds: ['template-1'],+ status: 'submitted',+ },lastActiveAt: '2026-04-16T00:00:00.000Z',phase: 'summary',startedAt: '2026-04-16T00:00:00.000Z',@@ -393,6 +401,14 @@ describe('OnboardingService', () => {'Coder','Ops',]);+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.agentMarketplacePick).toEqual({+ categoryHints: ['engineering'],+ installedAgentIds: ['agent-1'],+ requestId: 'req-1',+ resolvedAt: '2026-04-16T00:30:00.000Z',+ selectedTemplateIds: ['template-1'],+ status: 'submitted',+ });});it('is idempotent when finishOnboarding is called after completion', async () => {diff --git a/src/server/services/onboarding/index.ts b/src/server/services/onboarding/index.tsindex bbd48648697..a9ab64fce8e 100644--- a/src/server/services/onboarding/index.ts+++ b/src/server/services/onboarding/index.ts@@ -350,6 +350,10 @@ export class OnboardingService {version: CURRENT_ONBOARDING_VERSION,};+ if (existing?.agentMarketplacePick) {+ snapshot.agentMarketplacePick = existing.agentMarketplacePick;+ }+if (!snapshot.agentIdentityCompletedAt && phase !== 'agent_identity') {snapshot.agentIdentityCompletedAt = now;}diff --git a/src/server/services/toolExecution/serverRuntimes/agentMarketplace.ts b/src/server/services/toolExecution/serverRuntimes/agentMarketplace.tsnew file mode 100644index 00000000000..de195881a3a--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/agentMarketplace.ts@@ -0,0 +1,11 @@+import { AgentMarketplaceIdentifier } from '@lobechat/builtin-tool-agent-marketplace';+import { AgentMarketplaceExecutionRuntime } from '@lobechat/builtin-tool-agent-marketplace/executionRuntime';++import { type ServerRuntimeRegistration } from './types';++export const agentMarketplaceRuntime: ServerRuntimeRegistration = {+ factory: () => {+ return new AgentMarketplaceExecutionRuntime();+ },+ identifier: AgentMarketplaceIdentifier,+};diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex 9f37a99a91e..10264e9874d 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -9,6 +9,7 @@import { type ToolExecutionContext } from '../types';import { activatorRuntime } from './activator';import { agentDocumentsRuntime } from './agentDocuments';+import { agentMarketplaceRuntime } from './agentMarketplace';import { briefRuntime } from './brief';import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';@@ -65,6 +66,7 @@ registerRuntimes([cronRuntime,gtdRuntime,webOnboardingRuntime,+ agentMarketplaceRuntime,]);// ==================== Registry API ====================diff --git a/src/services/agentMarketplace.ts b/src/services/agentMarketplace.tsnew file mode 100644index 00000000000..9520a2f567e--- /dev/null+++ b/src/services/agentMarketplace.ts@@ -0,0 +1,23 @@+import {+ type AgentTemplate,+ type AgentTemplateFetcher,+ normalizeAgentTemplate,+ type RawAgentTemplate,+} from '@lobechat/builtin-tool-agent-marketplace';++import { lambdaClient } from '@/libs/trpc/client';++export const fetchOnboardingAgentTemplates: AgentTemplateFetcher = async () => {+ const data = await lambdaClient.market.agent.getOnboardingFull.query();+ if (!data || typeof data !== 'object') return [];++ const templates: AgentTemplate[] = [];+ for (const [category, items] of Object.entries(data)) {+ if (!Array.isArray(items)) continue;+ for (const item of items as RawAgentTemplate[]) {+ const normalized = normalizeAgentTemplate(item, category);+ if (normalized) templates.push(normalized);+ }+ }+ return templates;+};diff --git a/src/services/onboardingMetrics/index.test.ts b/src/services/onboardingMetrics/index.test.tsnew file mode 100644index 00000000000..e07a322656b--- /dev/null+++ b/src/services/onboardingMetrics/index.test.ts@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ ONBOARDING_METRICS_EVENTS,+ ONBOARDING_METRICS_SPM,+ setOnboardingAnalyticsClient,+ trackOnboardingMarketplacePicked,+ trackOnboardingMarketplaceShown,+} from './index';++describe('onboardingMetrics', () => {+ const track = vi.fn();++ beforeEach(() => {+ track.mockReset();+ setOnboardingAnalyticsClient({ track });+ });++ it('fires onboarding_marketplace_shown with categoryHints and requestId', () => {+ trackOnboardingMarketplaceShown({+ categoryHints: ['engineering', 'design-creative'],+ requestId: 'req-a',+ });++ expect(track).toHaveBeenCalledTimes(1);+ expect(track).toHaveBeenCalledWith({+ name: ONBOARDING_METRICS_EVENTS.MARKETPLACE_SHOWN,+ properties: {+ categoryHints: ['engineering', 'design-creative'],+ requestId: 'req-a',+ spm: ONBOARDING_METRICS_SPM.MARKETPLACE_SHOWN,+ },+ });+ });++ it('fires onboarding_marketplace_picked with categoryHints, requestId and selectedTemplateIds', () => {+ trackOnboardingMarketplacePicked({+ categoryHints: ['engineering'],+ requestId: 'req-b',+ selectedTemplateIds: ['pair-programmer', 'code-reviewer'],+ });++ expect(track).toHaveBeenCalledTimes(1);+ expect(track).toHaveBeenCalledWith({+ name: ONBOARDING_METRICS_EVENTS.MARKETPLACE_PICKED,+ properties: {+ categoryHints: ['engineering'],+ requestId: 'req-b',+ selectedTemplateIds: ['pair-programmer', 'code-reviewer'],+ spm: ONBOARDING_METRICS_SPM.MARKETPLACE_PICKED,+ },+ });+ });++ it('is a no-op when no analytics client is configured', () => {+ setOnboardingAnalyticsClient(null);+ expect(() =>+ trackOnboardingMarketplaceShown({ categoryHints: ['engineering'], requestId: 'req-c' }),+ ).not.toThrow();+ });++ it('swallows analytics errors so the caller never observes them', () => {+ setOnboardingAnalyticsClient({+ track: () => {+ throw new Error('boom');+ },+ });+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});++ expect(() =>+ trackOnboardingMarketplacePicked({+ categoryHints: ['engineering'],+ requestId: 'req-d',+ selectedTemplateIds: ['pair-programmer'],+ }),+ ).not.toThrow();++ error.mockRestore();+ });+});diff --git a/src/services/onboardingMetrics/index.ts b/src/services/onboardingMetrics/index.tsnew file mode 100644index 00000000000..178cde5a09b--- /dev/null+++ b/src/services/onboardingMetrics/index.ts@@ -0,0 +1,53 @@+export const ONBOARDING_METRICS_EVENTS = {+ MARKETPLACE_PICKED: 'onboarding_marketplace_picked',+ MARKETPLACE_SHOWN: 'onboarding_marketplace_shown',+} as const;++export const ONBOARDING_METRICS_SPM = {+ MARKETPLACE_PICKED: 'onboarding.marketplace.picked',+ MARKETPLACE_SHOWN: 'onboarding.marketplace.shown',+} as const;++interface AnalyticsLike {+ track: (event: { name: string; properties?: Record<string, unknown> }) => unknown;+}++let analyticsClient: AnalyticsLike | null = null;++export const setOnboardingAnalyticsClient = (client: AnalyticsLike | null): void => {+ analyticsClient = client;+};++const emit = (name: string, properties: Record<string, unknown>): void => {+ if (!analyticsClient) return;+ try {+ analyticsClient.track({ name, properties });+ } catch (error) {+ console.error('[OnboardingMetrics] track failed', error);+ }+};++export interface MarketplaceShownPayload {+ categoryHints: string[];+ requestId: string;+}++export const trackOnboardingMarketplaceShown = (payload: MarketplaceShownPayload): void => {+ emit(ONBOARDING_METRICS_EVENTS.MARKETPLACE_SHOWN, {+ ...payload,+ spm: ONBOARDING_METRICS_SPM.MARKETPLACE_SHOWN,+ });+};++export interface MarketplacePickedPayload {+ categoryHints: string[];+ requestId: string;+ selectedTemplateIds: string[];+}++export const trackOnboardingMarketplacePicked = (payload: MarketplacePickedPayload): void => {+ emit(ONBOARDING_METRICS_EVENTS.MARKETPLACE_PICKED, {+ ...payload,+ spm: ONBOARDING_METRICS_SPM.MARKETPLACE_PICKED,+ });+};diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 0b14fd98342..c6455de4f39 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -3,12 +3,19 @@ import { lambdaClient } from '@/libs/trpc/client';import { type BatchTaskResult } from '@/types/service';import {type ChatTopic,+ type ChatTopicMetadata,type CreateTopicParams,type QueryTopicParams,type RecentTopic,type TopicRankItem,} from '@/types/topic';+type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;++type UpdateTopicMetadataInput = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {+ onboardingSession?: OnboardingSessionMetadataPatch;+};+export class TopicService {createTopic = (params: CreateTopicParams): Promise<string> => {return lambdaClient.topic.createTopic.mutate({@@ -81,32 +88,7 @@ export class TopicService {return lambdaClient.topic.updateTopic.mutate({ id, value: data });};- updateTopicMetadata = (- id: string,- metadata: {- boundDeviceId?: string;- model?: string;- onboardingFeedback?: {- comment?: string;- rating: 'good' | 'bad';- submittedAt: string;- };- onboardingSession?: {- agentIdentityCompletedAt?: string;- discoveryCompletedAt?: string;- finalAgentNames?: string[];- finishedAt?: string;- lastActiveAt: string;- phase: 'agent_identity' | 'user_identity' | 'discovery' | 'summary';- startedAt: string;- userIdentityCompletedAt?: string;- version: number;- };- provider?: string;- runningOperation?: { assistantMessageId: string; operationId: string } | null;- workingDirectory?: string;- },- ) => {+ updateTopicMetadata = (id: string, metadata: UpdateTopicMetadataInput) => {return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });};diff --git a/src/store/agent/selectors/builtinAgentSelectors.ts b/src/store/agent/selectors/builtinAgentSelectors.tsindex e81ade317f7..d9e597a0a96 100644--- a/src/store/agent/selectors/builtinAgentSelectors.ts+++ b/src/store/agent/selectors/builtinAgentSelectors.ts@@ -53,6 +53,20 @@ const isInboxAgent = (s: AgentStoreState) => {return !!id && s.activeAgentId === id;};+/**+ * Get web onboarding agent id (convenience selector)+ */+const webOnboardingAgentId = (s: AgentStoreState) =>+ s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.webOnboarding];++/**+ * Check if current active agent is the web onboarding agent+ */+const isOnboardingAgent = (s: AgentStoreState) => {+ const id = webOnboardingAgentId(s);+ return !!id && s.activeAgentId === id;+};+export const builtinAgentSelectors = {agentBuilderId,getBuiltinAgentId,@@ -61,6 +75,8 @@ export const builtinAgentSelectors = {isBuiltinAgentInit,isInboxAgent,isInboxAgentConfigInit,+ isOnboardingAgent,pageAgentId,taskAgentId,+ webOnboardingAgentId,};diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex da44a07660d..94470e18cb8 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -303,6 +303,7 @@ export class ConversationControlActionImpl {toolMessageId: string,response: Record<string, unknown>,context?: ConversationContext,+ options?: { createUserMessage?: boolean; toolResultContent?: string },): Promise<void> => {const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();@@ -329,6 +330,7 @@ export class ConversationControlActionImpl {});const optimisticContext: OptimisticUpdateContext = { operationId };+ const shouldCreateUserMessage = options?.createUserMessage !== false;// 1. Mark intervention as approved and set tool result to user's responseawait this.#get().optimisticUpdateMessagePlugin(@@ -337,7 +339,7 @@ export class ConversationControlActionImpl {optimisticContext,);- const toolContent = `User submitted: ${JSON.stringify(response)}`;+ const toolContent = options?.toolResultContent ?? `User submitted: ${JSON.stringify(response)}`;await this.#get().optimisticUpdateMessageContent(toolMessageId,toolContent,@@ -345,7 +347,57 @@ export class ConversationControlActionImpl {optimisticContext,);- // 2. Create a user message summarizing the response (makes conversation natural)+ const chatKey = messageMapKey({ agentId, topicId, threadId, scope });++ // 2a. Tool-result-only path: skip the synthetic user message and resume from the+ // tool message. Used by interventions whose UI handles its own side effect (e.g.+ // the agent marketplace picker forks agents directly) — the LLM should see the+ // tool result, not a fake user turn.+ if (!shouldCreateUserMessage) {+ const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());++ const { state, context: initialContext } = this.#get().internal_createAgentState({+ messages: currentMessages,+ parentMessageId: toolMessageId,+ agentId,+ topicId,+ threadId: threadId ?? undefined,+ operationId,+ });++ const agentRuntimeContext: AgentRuntimeContext = {+ ...initialContext,+ phase: 'human_approved_tool',+ payload: {+ approvedToolCall: toolMessage.plugin,+ parentMessageId: toolMessageId,+ skipCreateToolMessage: true,+ },+ };++ try {+ await internal_execAgentRuntime({+ context: effectiveContext,+ messages: currentMessages,+ parentMessageId: toolMessageId,+ parentMessageType: 'tool',+ initialState: state,+ initialContext: agentRuntimeContext,+ parentOperationId: operationId,+ });+ completeOperation(operationId);+ } catch (error) {+ const err = error as Error;+ console.error('[submitToolInteraction] Error executing agent runtime:', err);+ this.#get().failOperation(operationId, {+ type: 'submitToolInteraction',+ message: err.message || 'Unknown error',+ });+ }+ return;+ }++ // 2b. Default path: create a user message summarizing the response, resume from userconst userMessageContent = Object.values(response).join(', ');const groupId = toolMessage.groupId;const userMsg = await this.#get().optimisticCreateMessage(@@ -369,7 +421,6 @@ export class ConversationControlActionImpl {}// 3. Resume agent from user message (not tool re-execution)- const chatKey = messageMapKey({ agentId, topicId, threadId, scope });const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());const { state, context: initialContext } = this.#get().internal_createAgentState({diff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.tsindex b881d9011db..054afa609d2 100644--- a/src/store/tool/builtinToolRegistry.test.ts+++ b/src/store/tool/builtinToolRegistry.test.ts@@ -1,5 +1,5 @@import { WEB_ONBOARDING } from '@lobechat/builtin-agents';-import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';+import { AgentMarketplaceIdentifier } from '@lobechat/builtin-tool-agent-marketplace';import {GroupAgentBuilderApiName,GroupAgentBuilderIdentifier,@@ -7,6 +7,7 @@ import {import { GroupAgentBuilderInspectors } from '@lobechat/builtin-tool-group-agent-builder/client';import { SkillStoreApiName, SkillStoreIdentifier } from '@lobechat/builtin-tool-skill-store';import { SkillStoreInspectors, SkillStoreRenders } from '@lobechat/builtin-tool-skill-store/client';+import { UserInteractionIdentifier } from '@lobechat/builtin-tool-user-interaction';import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';import { describe, expect, it } from 'vitest';@@ -32,13 +33,14 @@ describe('builtin tool registry', () => {expect(GroupAgentBuilderInspectors[GroupAgentBuilderApiName.createGroup]).toBeDefined();});- it('includes agent and group management tools in web onboarding runtime', () => {+ it('includes agent marketplace and user interaction in web onboarding runtime', () => {const runtime =typeof WEB_ONBOARDING.runtime === 'function'? WEB_ONBOARDING.runtime({ userLocale: 'en-US' }): WEB_ONBOARDING.runtime;- expect(runtime.plugins).toContain(AgentManagementIdentifier);- expect(runtime.plugins).toContain(GroupAgentBuilderIdentifier);+ expect(runtime.plugins).toContain(AgentMarketplaceIdentifier);+ expect(runtime.plugins).toContain(UserInteractionIdentifier);+ expect(runtime.plugins).toContain(WebOnboardingIdentifier);});});diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex c1fefd309c9..8388c774b44 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -21,6 +21,7 @@ import { taskExecutor } from '@lobechat/builtin-tool-task/executor';import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';import { activatorExecutor } from './lobe-activator';import { agentDocumentsExecutor } from './lobe-agent-documents';+import { agentMarketplaceExecutor } from './lobe-agent-marketplace';import { messageExecutor } from './lobe-message';import { notebookExecutor } from './lobe-notebook';import { pageAgentExecutor } from './lobe-page-agent';@@ -136,6 +137,7 @@ registerExecutors([agentBuilderExecutor,agentDocumentsExecutor,agentManagementExecutor,+ agentMarketplaceExecutor,calculatorExecutor,cloudSandboxExecutor,credsExecutor,diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-marketplace.ts b/src/store/tool/slices/builtin/executors/lobe-agent-marketplace.tsnew file mode 100644index 00000000000..2275b36e5d1--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-agent-marketplace.ts@@ -0,0 +1,18 @@+import { AgentMarketplaceExecutionRuntime } from '@lobechat/builtin-tool-agent-marketplace/executionRuntime';+import { AgentMarketplaceExecutor } from '@lobechat/builtin-tool-agent-marketplace/executor';++import {+ trackOnboardingMarketplacePicked,+ trackOnboardingMarketplaceShown,+} from '@/services/onboardingMetrics';++const runtime = new AgentMarketplaceExecutionRuntime({+ onPicked: (payload) => {+ trackOnboardingMarketplacePicked(payload);+ },+ onShown: (payload) => {+ trackOnboardingMarketplaceShown(payload);+ },+});++export const agentMarketplaceExecutor = new AgentMarketplaceExecutor(runtime);