Skip to content

🤯 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.

⚡️ perf(builtin-tools): slim lobe-agent and web-browsing prompts and add analyzeMedia maxItems (#23595)

AmAzing-f105f043ab9d
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.test.ts b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
index 7f5ff5ce186..12c38e6867d 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { LobeAgentManifest } from './manifest';
+import { MAX_MEDIA_URLS } from './media';
import { LobeAgentApiName } from './types';
describe('LobeAgentManifest', () => {
@@ -35,6 +36,21 @@ describe('LobeAgentManifest', () => {
expect(LobeAgentManifest.systemRole).toContain(
'active model lacks the needed audio/image/video capability',
);
+ expect(LobeAgentManifest.systemRole).toContain('media only appears as remote URLs');
+ });
+
+ it('should state the media URL cap once, from the runtime constant', () => {
+ const { urls } = LobeAgentManifest.api[0].parameters.properties;
+
+ expect(urls.maxItems).toBe(MAX_MEDIA_URLS);
+ expect(urls.description).toContain(`at most ${MAX_MEDIA_URLS} per call`);
+ // The cap is a limit, not a batching recipe: no guidance to fan out over it.
+ expect(urls.description).not.toContain('parallel');
+ expect(LobeAgentManifest.systemRole).not.toMatch(/at most \d+ URLs/i);
+ });
+
+ it('should allow todos without a plan when the user asks for that', () => {
+ expect(LobeAgentManifest.systemRole).toContain('unless the user explicitly asks otherwise');
});
it('should route local media through file refs instead of local URLs or base64 text', () => {
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
index 84cf8f4db9e..b3adfe6dcd6 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -1,6 +1,7 @@
import type { BuiltinToolManifest } from '@lobechat/types';
import { isDesktop } from './const';
+import { MAX_MEDIA_URLS } from './media';
import { systemPrompt } from './systemRole';
import {
LobeAgentApiName,
@@ -14,18 +15,18 @@ export const LobeAgentManifest: BuiltinToolManifest = {
api: [
{
description:
- "Analyze audio, images, or videos selected by media file refs or direct media URLs and answer a question about them. Prefer the active model's native multimodal capability when it can inspect the media directly; use this tool only as a fallback when the active model lacks the required audio, image, or video capability. Provide either refs or urls; at least one is required. Prefer refs when stable refs are available in <files_info>, such as msg_xxx.audio_1, msg_xxx.image_1, or msg_xxx.video_1, and use urls only for direct media URLs that are not available as message refs. For media stored on a local filesystem, never pass an OS path or file:// URL through urls and never convert or copy the media as base64 text. If this fallback is needed, first use an available local file-reading tool to upload the media, then pass its stable ref through refs. After this tool returns, answer the user directly with the result.",
+ "Analyze audio, images, or videos via refs or direct URLs and answer a question about them. Prefer the active model's native multimodal capability when it can inspect the media directly; use this tool only as a fallback when native capability is unavailable or media appears only as remote URLs. Provide either refs or urls (at least one required). Prefer refs when stable refs are available in <files_info> (e.g. msg_xxx.audio_1, msg_xxx.image_1, msg_xxx.video_1), and use urls only for direct media URLs not available as refs. For local filesystem media, never pass OS paths or file:// URLs or copy base64 text — upload with a local file-reading tool first and pass its stable ref. After this tool returns, answer the user directly with the result.",
name: LobeAgentApiName.analyzeMedia,
parameters: {
additionalProperties: false,
properties: {
question: {
- description: 'The question or task to answer about the selected media.',
+ description: 'Question or task to answer about the media.',
type: 'string',
},
refs: {
description:
- 'Stable media file ref strings from <files_info>, including refs created for media uploaded by local file-reading tools, such as ["msg_xxx.audio_1"], ["msg_xxx.image_1"], or ["msg_xxx.video_1"].',
+ 'Stable media refs from <files_info> (including uploads from local file-reading tools), e.g. ["msg_xxx.image_1"].',
items: {
type: 'string',
},
@@ -33,11 +34,11 @@ export const LobeAgentManifest: BuiltinToolManifest = {
type: 'array',
},
urls: {
- description:
- 'Direct provider-readable HTTP(S) or data URLs to analyze when no stable media ref exists. Local filesystem paths and file:// URLs are unsupported; use an available local file-reading tool first, then pass its stable ref through refs.',
+ description: `Direct provider-readable HTTP(S) or data URLs (at most ${MAX_MEDIA_URLS} per call). Local filesystem paths and file:// URLs are unsupported — use a local file-reading tool first and pass its stable ref via refs.`,
items: {
type: 'string',
},
+ maxItems: MAX_MEDIA_URLS,
minItems: 1,
type: 'array',
},
@@ -49,24 +50,22 @@ export const LobeAgentManifest: BuiltinToolManifest = {
// ==================== Planning ====================
{
- description:
- 'Create a high-level plan document. Plans define the strategic direction (the "what" and "why"), while todos handle the actionable steps.',
+ description: 'Create a high-level strategic plan document (goal, summary, and context).',
name: LobeAgentApiName.createPlan,
humanIntervention: 'required',
renderDisplayControl: 'expand',
parameters: {
properties: {
goal: {
- description: 'The main goal or objective to achieve (used as document title).',
+ description: 'Main objective (used as document title).',
type: 'string',
},
description: {
- description: 'A brief summary of the plan (1-2 sentences).',
+ description: 'Brief 1-2 sentence summary.',
type: 'string',
},
context: {
- description:
- 'Detailed context, constraints, background information, or strategic considerations relevant to the goal.',
+ description: 'Constraints, background, and strategic context.',
type: 'string',
},
},
@@ -75,14 +74,13 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
},
{
- description:
- 'Update an existing plan document. Only use this when the goal fundamentally changes. Plans should remain stable once created - do not update plans just because details change.',
+ description: 'Update an existing plan document when the overarching goal changes.',
name: LobeAgentApiName.updatePlan,
parameters: {
properties: {
planId: {
description:
- 'The document ID of the plan to update (e.g., "docs_xxx"). This ID is returned in the createPlan response. Do NOT use the goal text as planId.',
+ 'Plan document ID (e.g. "docs_xxx") returned by createPlan. Do NOT use the goal text as planId.',
type: 'string',
},
goal: {
@@ -94,7 +92,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {
type: 'string',
},
context: {
- description: 'Updated detailed context.',
+ description: 'Updated context.',
type: 'string',
},
},
@@ -105,13 +103,13 @@ export const LobeAgentManifest: BuiltinToolManifest = {
// ==================== Quick Todo ====================
{
- description: 'Create new todo items. Pass an array of text strings.',
+ description: 'Create new todo items from a list of strings.',
name: LobeAgentApiName.createTodos,
humanIntervention: 'required',
parameters: {
properties: {
adds: {
- description: 'Array of todo item texts to create.',
+ description: 'Todo item texts to create.',
items: { type: 'string' },
type: 'array',
},
@@ -121,43 +119,34 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
},
{
- description: `Update todo items with batch operations. Each operation type requires specific fields:
-- "add": requires "text" (the todo text to add)
-- "update": requires "index", optional "newText" and/or "status"
-- "remove": requires "index" only
-- "complete": requires "index" only (marks item as completed)
-- "processing": requires "index" only (marks item as in progress)`,
+ description:
+ 'Batch update todos: add (text), update (index + newText/status), or remove/complete/processing (index only).',
name: LobeAgentApiName.updateTodos,
renderDisplayControl: 'expand',
parameters: {
properties: {
operations: {
- description:
- 'Array of update operations. IMPORTANT: For "complete", "processing" and "remove" operations, only pass "type" and "index" - no other fields needed.',
+ description: 'Operations to apply in order.',
items: {
properties: {
type: {
- description:
- 'Operation type. "add" needs text, "update" needs index + optional newText/status, "remove", "complete" and "processing" need index only.',
enum: ['add', 'update', 'remove', 'complete', 'processing'],
type: 'string',
},
text: {
- description: 'Required for "add" only: the text to add.',
+ description: 'For "add": item text.',
type: 'string',
},
index: {
- description:
- 'Required for "update", "remove", "complete", "processing": the item index (0-based).',
+ description: '0-based index (for update/remove/complete/processing).',
type: 'number',
},
newText: {
- description: 'Optional for "update" only: the new text.',
+ description: 'For "update": replacement text.',
type: 'string',
},
status: {
- description:
- 'Optional for "update" only: set status (todo, processing, completed).',
+ description: 'For "update": new status.',
enum: ['todo', 'processing', 'completed'],
type: 'string',
},
@@ -173,14 +162,13 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
},
{
- description: 'Clear todo items. Can clear only completed items or all items.',
+ description: 'Clear completed or all todo items.',
name: LobeAgentApiName.clearTodos,
humanIntervention: 'required',
renderDisplayControl: 'expand',
parameters: {
properties: {
mode: {
- description: '"completed" clears only done items, "all" clears the entire list.',
enum: ['completed', 'all'],
type: 'string',
},
@@ -234,42 +222,41 @@ export const LobeAgentManifest: BuiltinToolManifest = {
// ==================== Sub-Agent ====================
{
description:
- 'Dispatch a single sub-agent that runs in an isolated context to handle a long-running, multi-step request. Use this when the request requires extended processing (web research, multi-source synthesis, deep investigation) that benefits from running independently of the main conversation. Pass `subAgentId` to send a follow-up message to an earlier sub-agent instead of starting a new one.',
+ 'Dispatch an isolated sub-agent for multi-step work, or pass `subAgentId` to continue or steer an existing sub-agent.',
name: LobeAgentApiName.callSubAgent,
parameters: {
properties: {
description: {
- description: 'Brief description of what this sub-agent does (shown in UI).',
+ description: 'Short UI label for the task.',
type: 'string',
},
instruction: {
- description: 'Detailed instruction/prompt for the sub-agent execution.',
+ description: 'Detailed prompt for the sub-agent.',
type: 'string',
},
inheritMessages: {
- description:
- 'Whether to inherit context messages from the parent conversation. Default is false.',
+ description: 'Inherit parent conversation history (default false).',
type: 'boolean',
},
subAgentId: {
description:
- 'Optional. The id from the `<sub_agent id="..." />` tag at the end of an earlier callSubAgent result. Sends `instruction` as a new message to that same sub-agent, which keeps all of its previous work and history — use it to continue a sub-agent that stopped or failed, ask it to hand over what it has found so far, or follow up on its answer. If that sub-agent is still running, the instruction is queued and it reads it at its next step to correct course. Leave empty (or omit) to start a new sub-agent; never invent an id.',
+ 'ID from an earlier `<sub_agent id="..." />` tag to resume a stopped sub-agent or steer a running one. Omit to start a new sub-agent; never invent an ID.',
type: 'string',
},
runInBackground: {
description:
- 'Optional. Start the sub-agent and get control back immediately instead of waiting for it. Use it only when you have other independent work to do meanwhile, or when the user should not wait on this result. The result arrives later as a new message (waking you up if your turn has ended) — never poll or wait for it. Default is false: wait for the result in this turn.',
+ 'Return immediately with the sub-agent ID and deliver `<sub_agent_result>` later (default false: wait in this turn). Never poll.',
type: 'boolean',
},
...(isDesktop && {
runInClient: {
description:
- 'Whether to run on the desktop client (for local file/shell access). MUST be true when the sub-agent requires local-system tools. Default is false (server execution).',
+ 'Run on the desktop client (must be true for local-system file/shell access; default false).',
type: 'boolean',
},
}),
timeout: {
- description: 'Optional timeout in milliseconds. Default is 30 minutes.',
+ description: 'Timeout in ms (default 30 min).',
type: 'number',
},
},
@@ -279,18 +266,17 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
{
description:
- 'Cancel a sub-agent that is still running — typically one started with `runInBackground` — whose work is no longer needed. It stops at its next step, no result is delivered for it, and its history is kept. To correct a sub-agent that has gone off track, do not cancel it: send the correction with `callSubAgent` and the same `subAgentId` while it runs.',
+ 'Cancel a running sub-agent whose result is no longer needed (to steer one instead, use `callSubAgent` with its `subAgentId`).',
name: LobeAgentApiName.cancelSubAgent,
parameters: {
additionalProperties: false,
properties: {
subAgentId: {
- description:
- 'The id from the `<sub_agent id="..." />` tag of the sub-agent to cancel. Never invent an id.',
+ description: 'ID from `<sub_agent id="..." />`. Never invent an ID.',
type: 'string',
},
reason: {
- description: 'Optional. One short sentence on why it is no longer needed.',
+ description: 'Optional short reason.',
type: 'string',
},
},
@@ -298,58 +284,51 @@ export const LobeAgentManifest: BuiltinToolManifest = {
type: 'object',
},
},
+
+ // ==================== Vent ====================
{
description:
- 'Privately report friction in your own working conditions to the platform builders when you are genuinely blocked — a missing tool, a parameter/schema mismatch, conflicting or wrong docs, anomalous platform behavior, or an environment limit causing repeated failure. Not user-facing; it only records the report and does not fix anything. Use sparingly: at most one vent per run, only for the single worst blocker. It never stops a tool loop or ends your turn — to stop, just reply to the user; repeated or empty vents are rejected.',
+ 'Privately report genuine platform friction to platform builders (not user-facing; fixes nothing). Use sparingly: at most one vent per run, only for the single worst blocker. It never stops a tool loop or ends your turn — to stop, reply to the user; repeated or empty vents are rejected.',
name: LobeAgentApiName.vent,
parameters: {
additionalProperties: false,
properties: {
category: {
description:
- 'Friction category: missing_tool, schema_mismatch, doc_conflict, platform_bug, env_limitation, or other.',
+ 'missing_tool (no tool exists), schema_mismatch (params disagree with docs/behavior), doc_conflict (wrong/contradictory docs), platform_bug (anomalous surface error), env_limitation (sandbox/network/timeout/resource limit), or other.',
enum: [...VENT_CATEGORIES],
type: 'string',
},
severity: {
- description:
- 'How badly it blocked the task: high = could not complete, medium = forced a costly workaround, low = friction but recovered.',
+ description: 'high = blocked, medium = costly workaround, low = minor friction.',
enum: [...VENT_SEVERITIES],
type: 'string',
},
summary: {
- description:
- 'One short sentence naming the specific friction. Name the tool/surface if one is at fault.',
+ description: 'One short sentence naming the specific friction/surface.',
type: 'string',
},
details: {
- description:
- 'What you tried, what you expected, what actually happened, and why it blocked you. Specific enough for an engineer to reproduce or fix.',
+ description: 'What you tried, expected, observed, and why it blocked you.',
type: 'string',
},
attempts: {
- description: 'How many times you hit this wall before venting, when countable.',
+ description: 'How many times you hit this blocker.',
minimum: 1,
type: 'integer',
},
toolName: {
- description:
- 'Exact tool/API/surface involved, when one specific component is at fault.',
+ description: 'Exact tool/API/surface involved, if applicable.',
type: 'string',
},
evidenceRefs: {
- description:
- 'Optional stable references that ground the report. Prefer tool_call, message, operation, topic, or task refs.',
+ description: 'Optional stable refs (tool_call, message, operation, topic, task).',
items: {
additionalProperties: false,
properties: {
- id: { description: 'Stable evidence identifier.', type: 'string' },
- summary: {
- description: 'Optional short note explaining why this evidence matters.',
- type: 'string',
- },
+ id: { type: 'string' },
+ summary: { type: 'string' },
type: {
- description: 'Evidence object type.',
enum: [...VENT_EVIDENCE_REF_TYPES],
type: 'string',
},
diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.ts
index ea7ececb5b8..ad983718c3b 100644
--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts
+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts
@@ -2,267 +2,58 @@ import { isDesktop } from './const';
const runInClientSection = `
<run_in_client>
-**IMPORTANT: When to use \`runInClient: true\` for sub-agents**
-
-The \`runInClient\` parameter controls WHERE the sub-agent executes:
-- \`runInClient: false\` (default): Sub-agent runs on the **server** - suitable for web searches, API calls, general research
-- \`runInClient: true\`: Sub-agent runs on the **desktop client** - required for local system access
-
-**MUST set \`runInClient: true\` when the sub-agent involves:**
-- Reading or writing local files (via \`local-system\` tool)
-- Executing shell commands on the user's machine
-- Accessing local directories or file system
-- Any operation that requires desktop-only local tools
-
-**Keep \`runInClient: false\` (or omit) when:**
-- Sub-agent only needs web searches or API calls
-- Sub-agent processes data that doesn't require local file access
-- Sub-agent can be fully completed with server-side capabilities
-
-**Note:** \`runInClient\` only has effect on the **desktop app**. On web platform, sub-agents always run on the server regardless of this setting.
-
-**Examples:**
-- "Research Python best practices" → \`runInClient: false\` (web search only)
-- "Organize files in my Downloads folder" → \`runInClient: true\` (local file access required)
-- "Read the project README and summarize it" → \`runInClient: true\` (local file read required)
-- "Find trending tech news" → \`runInClient: false\` (web search only)
-- "Create a new directory structure for my project" → \`runInClient: true\` (local shell/file required)
+\`runInClient\` controls where a desktop sub-agent runs (ignored on web, which always runs on the server):
+- \`false\` (default): server — web searches, API calls, general research.
+- \`true\`: desktop client — required whenever the sub-agent needs local file/directory access or shell commands via \`local-system\`.
</run_in_client>
`;
const subAgentSection = `
<sub_agents>
-You can dispatch **sub-agents** to handle long-running, multi-step work in isolated contexts.
-
-**Sub-Agent Tool:**
-- \`callSubAgent\`: Dispatch a single sub-agent. **Required params: description (brief UI label), instruction (detailed prompt)** - both must be provided.
-- To run several independent investigations **in parallel**, emit multiple \`callSubAgent\` calls in the same turn — each runs in its own isolated context concurrently.
-
-**Background sub-agents (\`runInBackground: true\`):**
-- By default you wait for a sub-agent's result in the same turn. That is the right choice whenever your next step depends on the result.
-- Set \`runInBackground: true\` only when you have other independent work to do meanwhile, or when the user should not have to wait for this result. The call returns right away with the sub-agent's id.
-- The background result is delivered to you later as a message from the sub-agent wrapped in \`<sub_agent_result>\`; if your turn has already ended, it starts a new turn. Do not poll, sleep, or call the sub-agent again to check on it — continue with your other work, or end your turn and tell the user what is running.
-- When the result arrives, use it to finish what the user asked for; the user has not seen it yet.
-
-**Continuing an earlier sub-agent:**
-- Every sub-agent result ends with \`<sub_agent id="..." />\`. Pass that id as \`subAgentId\` to send the same sub-agent a new instruction; it resumes with all of its previous work (searches, pages read, tool results) instead of starting over.
-- When a sub-agent stops or fails partway (step limit, error, interruption), prefer continuing it — e.g. ask it to hand over what it has gathered so far or to finish the remaining work — rather than redoing its work yourself or dispatching a new sub-agent.
-- If it failed because of the account's budget or quota, do not resend right away; tell the user, and continue the same sub-agent only after they say it is resolved.
-
-**Cancelling or steering a running sub-agent:**
-- To correct a background sub-agent that is still running (it went off track, or the user changed what they want), pass its id as \`subAgentId\` with the correction; do not cancel it first. The instruction is queued and the sub-agent reads it at its next step, then keeps going with everything it has done so far; its result still arrives as before. Only send it to change course, never to check on progress.
-- \`cancelSubAgent({ subAgentId })\` stops a sub-agent that is still running (typically a background one). Use it when its result is no longer needed (the user changed their mind, another result already answered it). No result is delivered for a cancelled sub-agent.
-- Do not cancel a sub-agent just because it is taking a while.
-
-**Use sub-agents when:**
-- **The request requires gathering external information**: The user wants you to research, investigate, or find information that you don't already know. This needs web searches, reading multiple sources, and synthesizing information.
-- **The task involves multiple steps**: The request cannot be answered in one simple response - it requires searching, reading, analyzing, and summarizing.
-- **Quality depends on thorough investigation**: A superficial answer would be insufficient; the user expects comprehensive, well-researched results.
-- **Independent execution is beneficial**: The task can run separately while freeing up the main conversation.
+Use \`callSubAgent\` (\`description\`, \`instruction\`) to delegate multi-step external research or independent investigations to an isolated sub-agent. Answer directly when no external gathering is needed. Emit multiple \`callSubAgent\` calls in one turn to run independent tasks in parallel.
-**How to identify sub-agent scenarios:**
-Ask yourself: "Can I answer this well from my existing knowledge, or does this require actively gathering new information?"
-- If you need to search the web, read articles, or investigate → Dispatch a sub-agent
-- If you can answer directly from knowledge → Just respond
-
-Use a single \`callSubAgent\` for one task; emit multiple \`callSubAgent\` calls in the same turn to run independent tasks in parallel.
-
-**Example scenarios:**
-- User asks about best restaurants in a city → \`callSubAgent\` (needs current info from reviews, searches)
-- User wants research on a topic → \`callSubAgent\` (multi-step: search, read, analyze, summarize)
-- User asks to compare products/services → \`callSubAgent\` (needs data from multiple sources)
-- User asks a factual question you know → Just answer directly
-- User wants multiple independent analyses → multiple \`callSubAgent\` calls in one turn (parallel execution)
+- **Background (\`runInBackground: true\`)**: Default \`false\` waits in the same turn. Set \`true\` only when you have other independent work or shouldn't block the user; it returns an id immediately and delivers \`<sub_agent_result>\` later (starting a new turn if ended). Never poll, sleep, or re-call to check progress; if you end your turn while it runs, tell the user what is running. Use the delivered result to finish the user's request — the user has not seen it.
+- **Continue / steer (\`subAgentId\`)**: Every result ends with \`<sub_agent id="..." />\`. Pass that \`subAgentId\` to resume a stopped/failed sub-agent with its existing history instead of restarting (if it failed due to budget/quota, tell the user and wait before continuing). To steer a running background sub-agent, pass \`subAgentId\` with the correction rather than cancelling it.
+- **Cancel**: Use \`cancelSubAgent({ subAgentId })\` only when a running sub-agent's result is no longer needed — never just because it is slow.
</sub_agents>
${isDesktop ? runInClientSection : ''}`;
const planTodoSection = `
<plan_and_todos>
-You have **plan and todo management** tools to organize multi-step work over time.
-
-- **Plan**: A high-level strategic document describing goals, context, and overall direction. Plans do NOT contain actionable steps - they define the "what" and "why". **Plans should be stable once created** - they represent the overarching objective that rarely changes.
-- **Todo**: The concrete execution list with actionable items. Todos define the "how" - specific tasks to accomplish the plan. **Todos are dynamic** - they can be added, updated, completed, and removed as work progresses.
-
-**Planning Tools** - For high-level goal documentation:
-- \`createPlan\`: Create a strategic plan document. **Required params: goal, description (brief summary), context** - all three must be provided
-- \`updatePlan\`: Update plan details (only planId is required)
-
-**Todo Tools** - For actionable execution items:
-- \`createTodos\`: Create new todo items from text array
-- \`updateTodos\`: Batch update todos (add, update, remove, complete, processing operations)
-- \`clearTodos\`: Clear completed or all items
-
-**Todo Status Workflow:** todo → processing → completed (use "processing" when actively working on an item)
-
-<default_workflow>
-**CRITICAL: Most tasks do NOT need plan/todo tools. Only use them for complex, multi-step projects.**
-
-**DO NOT use plan/todo tools for:**
-- Simple one-step tasks (rename a file, send a message, search something)
-- Quick questions or lookups
-- Tasks that can be completed immediately with a single action
-- Any request that doesn't require tracking progress over time
-
-**ONLY use plan/todo tools when ALL of these are true:**
-1. The task has multiple distinct steps that need tracking
-2. The user explicitly wants to plan or organize something
-3. Progress needs to be tracked over time (not completed in one response)
+Only use plan/todo tools for complex, multi-step projects that need ongoing progress tracking across turns/sessions, or when the user explicitly asks to plan/organize. Do NOT use them for one-step actions, quick lookups, or single-response tasks. For recurring/scheduled tasks (daily/weekly/routine), use \`lobe-task\` instead.
-**When plan/todo tools ARE appropriate:**
-1. **First**, use \`createPlan\` to document the goal and relevant context
-2. **Then**, use \`createTodos\` to break down the plan into actionable steps
-
-**Examples:**
-- ❌ "Rename this file" → Just do it, no plan/todo needed
-- ❌ "What's the weather?" → Just answer, no plan/todo needed
-- ❌ "Help me write an email" → Just write it, no plan/todo needed
-- ✅ "Help me plan a trip to Japan" → Use createPlan + createTodos
-- ✅ "I want to learn Python, create a study plan" → Use createPlan + createTodos
-- ✅ "Help me organize my project tasks" → Use createTodos (user explicitly wants organization)
-</default_workflow>
-
-<when_to_use>
-**Use Plans when:**
-- User explicitly asks to "plan", "organize", or "break down" a complex goal
-- The project spans multiple sessions or days
-- There's significant context, constraints, or background worth documenting
-- The task has 5+ distinct steps that benefit from strategic organization
-
-**Use Todos when:**
-- Breaking down a plan into actionable steps (after creating a plan)
-- User explicitly requests a checklist or task list
-- Tracking progress on a multi-step project
-
-**DO NOT use Plans/Todos when:**
-- The task can be done in one action (rename, delete, send, search, etc.)
-- The user just wants something done, not organized
-- The task will be completed in this single conversation
-- The user wants a task to repeat automatically on a schedule (daily/weekly/hourly) — use **lobe-task** and its scheduling capability instead. Keywords like "daily task", "routine", "recurring", "every day/morning/week", "set as daily", "make it regular" all indicate scheduled automation, not plan/todo management.
-</when_to_use>
-
-<best_practices>
-- **Plan first, then todos**: Always start with a plan unless explicitly told otherwise
-- **Separate concerns**: Plans describe goals; Todos list actions
-- **Actionable todos**: Each todo should be a concrete, completable task
-- **Context in plans**: Use plan's context field to capture constraints and background
-- **Regular cleanup**: Clear completed todos to keep the list focused
-- **Track progress**: Use todo completion to measure plan progress
-</best_practices>
-
-<updateTodos_usage>
-When using \`updateTodos\`, each operation type requires specific fields:
-
-**Todo Status:**
-- \`todo\`: Not started yet
-- \`processing\`: Currently in progress
-- \`completed\`: Done
-
-**Minimal required fields per operation type:**
-- \`{ "type": "add", "text": "todo text" }\` - only type + text
-- \`{ "type": "complete", "index": 0 }\` - only type + index (marks as completed)
-- \`{ "type": "processing", "index": 0 }\` - only type + index (marks as in progress)
-- \`{ "type": "remove", "index": 0 }\` - only type + index
-- \`{ "type": "update", "index": 0, "newText": "..." }\` - type + index + optional newText/status
-
-**Example - mark item 0 as processing, item 1 as complete:**
-\`\`\`json
-{
- "operations": [
- { "type": "processing", "index": 0 },
- { "type": "complete", "index": 1 }
- ]
-}
-\`\`\`
-
-**DO NOT** add extra fields like \`"status": "completed"\` for complete/processing operations - they are ignored.
-</updateTodos_usage>
-
-<todo_granularity>
-**IMPORTANT: Keep todos focused on major stages, not detailed sub-tasks.**
-
-- **Limit to 5-10 items**: A todo list should contain around 5-10 major milestones or stages, not 20+ detailed tasks.
-- **Think in phases**: Group related tasks into higher-level stages (e.g., "Plan itinerary" instead of listing every city separately).
-- **Use hierarchical numbering** when more detail is needed: Use "1.", "2.", "2.1", "2.2", "3." format to show parent-child relationships.
-
-**Good example** (Japan trip - 7 items, stage-focused):
-- 1. Determine travel dates and duration
-- 2. Handle visa and documentation
-- 3. Book flights and accommodation
-- 4. Plan city itineraries
-- 5. Arrange local transportation
-- 6. Prepare for departure
-- 7. Final confirmation before trip
-
-**Bad example** (20+ detailed items):
-- Book Tokyo hotel
-- Book Kyoto hotel
-- Book Osaka hotel
-- Buy Suica card
-- Download Google Maps
-- Download translation app
-- ... (too granular!)
-</todo_granularity>
-
-<plan_stability>
-**IMPORTANT: Plans should remain stable once created. Each conversation has only ONE plan.**
-
-- **Do NOT update plans** when details change (dates, locations, preferences). Instead, update the todos to reflect new information.
-- **Only use updatePlan** when the user's goal fundamentally changes (e.g., destination changes from Japan to Korea).
-- When user provides more specific information (like exact dates or preferences), **update or add todos** - not the plan.
-</plan_stability>
-
-<response_format>
-When working with plan/todo tools:
-- Confirm actions: "Created plan: [goal]" or "Added [n] todo items"
-- Show progress: "Completed [n] items, [m] remaining"
-- Be concise: Brief confirmations, not verbose explanations
-- **NEVER repeat the todo list in your response** - Users can already see the todos in the UI component. Do not list or enumerate the todo items in your text output.
-</response_format>
+- **Plan** (\`createPlan\`, \`updatePlan\`): One stable high-level goal/context document per conversation. Only call \`updatePlan\` if the overarching goal fundamentally changes; reflect detail changes in todos.
+- **Todos** (\`createTodos\`, \`updateTodos\`, \`clearTodos\`): Start with \`createPlan\` then \`createTodos\`, unless the user explicitly asks otherwise (e.g. only wants a checklist). Keep 5–10 stage-level milestones (use \`1.\`, \`2.1\` numbering if needed) with workflow \`todo → processing → completed\`. For \`updateTodos\` \`complete\`/\`processing\`/\`remove\`, pass only \`type\` and \`index\`.
+- **Response**: Confirm concisely; **never repeat the todo list in your text response** (users already see it in the UI).
</plan_and_todos>
`;
const multimodalAnalysisSection = `
<multimodal_analysis>
-\`analyzeMedia\` is only a fallback when the active model cannot inspect the requested audio/image/video natively.
-If the media is already visible in the current multimodal context, answer directly without this tool.
-Use it only for refs/URLs you cannot inspect directly, or when the active model lacks the needed audio/image/video capability.
-When this fallback is needed for media stored on a local filesystem:
-- Never pass local filesystem paths or \`file://\` URLs to \`analyzeMedia.urls\`.
-- Never convert or copy the media as base64/data URI text between tool calls.
-- First use an available local file-reading tool to upload the media, then call \`analyzeMedia\` with the stable ref exposed by the tool result or <files_info>.
-- If no local file-reading tool is available, explain that the file cannot be accessed instead of inventing a URL.
+\`analyzeMedia\` is only a fallback when the active model cannot inspect the media natively (because the active model lacks the needed audio/image/video capability, or the media only appears as remote URLs in webpage/tool text rather than attached media blocks). If the media is already visible in the current multimodal context, answer directly without this tool.
+- For local filesystem media: Never pass local filesystem paths or \`file://\` URLs to \`analyzeMedia.urls\`, and never copy media as base64/data URI text. Upload it via an available local file-reading tool first, then pass the resulting stable ref from \`<files_info>\` (or explain it cannot be accessed instead of inventing a URL if no local reader is available).
</multimodal_analysis>
`;
const askUserQuestionSection = `
<ask_user_question>
-\`askUserQuestion\` opens a UI-mediated question so the user can clarify their intent before you act.
-
-- Use "form" mode with \`fields\` when you need structured or constrained choices (select / multiselect / text / textarea).
-- Use "freeform" mode for a single open-ended response.
-- Reach for it only when the request is genuinely ambiguous and the clarification would materially change your answer — do NOT interrogate the user for details you can reasonably infer or that don't affect the outcome.
-- Ask at most one question at a time, then wait for the user's answer before continuing.
-- Prefer asking in plain text for trivial confirmations; use this tool when a structured picker or explicit options improve the experience.
+Use \`askUserQuestion\` only when the request is genuinely ambiguous and structured choices would materially change your answer. Ask concise questions with clear options, then wait for the user's answer. Prefer plain text for trivial confirmations and never interrogate for inferable details.
</ask_user_question>
`;
const ventSection = `
<vent>
-\`vent\` is a private side channel for telling the people who built this platform that something about your *own working conditions* got in the way: a missing tool, a parameter/schema that does not match the docs or actual behavior, conflicting or wrong documentation, anomalous platform behavior, or an environment limitation that made you fail repeatedly.
-
-- It is NOT shown to the user, is NOT an answer, apology, or progress update, and does NOT fix anything by itself. Recording a vent never changes what you do next — continue the task normally after venting.
-- Be reluctant, not eager. Most tasks run fine and need no vent. Vent only when you are *genuinely blocked or clearly frustrated* by the platform itself — typically after the friction has actually cost you (a failed tool call, a retry that hit the same wall, a doc that contradicted reality).
-- Emit at most ONE vent per run, only for the single worst blocker. Do not vent about your own mistakes, a hard user request, normal model limitations, or things you simply chose not to do. Never put secrets or sensitive user data in a vent.
-- \`vent\` is never a control action: it does not stop a tool loop, end your turn, cancel anything, or reset state. If you want to stop calling tools, simply reply to the user in plain text without a tool call. The runtime records only the first vent of a run and rejects repeats and empty reports — when a vent comes back "not recorded", do not call it again.
-- **category**: missing_tool (no tool could do what was needed) · schema_mismatch (params/schema disagreed with docs or behavior) · doc_conflict (docs/instructions wrong, contradictory, or missing) · platform_bug (a surface errored or behaved anomalously, not your input) · env_limitation (sandbox/network/timeout/resource limit caused repeated failure) · other.
-- **severity**: high = could not complete, medium = forced a costly workaround, low = friction but recovered. **details**: what you tried, expected, what happened, and why it blocked you — specific enough to reproduce or fix.
+\`vent\` is a private side channel to report genuine platform friction (missing tool, schema mismatch, doc conflict, platform bug, or env limit) that actually blocked you or forced a costly workaround.
+- Be reluctant, not eager. Not shown to the user and fixes nothing; continue the task normally after venting. Never include secrets or sensitive user data.
+- Emit at most one vent per run for the single worst blocker — do not vent about your own mistakes, hard user requests, normal model limitations, or things you chose not to do.
+- \`vent\` is never a control action: it does not stop a tool loop or end your turn (to stop, reply in plain text). When a vent returns "not recorded", do not call it again.
</vent>
`;
// Sections independent of sub-agent dispatch (multimodal fallback + ask-user + plan/todo + vent).
// Kept as a base so contexts where callSubAgent is unavailable can drop the sub-agent
// guidance without leaving dangling references to a tool the model can't call.
-const baseSystemPrompt = `Use Lobe Agent capabilities only when the active model needs built-in assistance. Prefer the active model's native capabilities whenever they are sufficient. Follow each tool's description and schema, and use tool results to answer the user directly.
+const baseSystemPrompt = `Use Lobe Agent capabilities only when needed; prefer native model capabilities whenever sufficient, follow each tool's schema, and use results to answer the user directly.
${multimodalAnalysisSection}
${askUserQuestionSection}
${planTodoSection}
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.test.ts b/packages/builtin-tool-web-browsing/src/systemRole.test.ts
new file mode 100644
index 00000000000..21e7730eec5
--- /dev/null
+++ b/packages/builtin-tool-web-browsing/src/systemRole.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { systemPrompt } from './systemRole';
+
+describe('web browsing systemPrompt', () => {
+ const prompt = systemPrompt();
+
+ it('keeps the time range opt-in for time-sensitive queries', () => {
+ expect(prompt).toContain('Set `searchTimeRange` only for time-sensitive queries');
+ expect(prompt).not.toMatch(/Default to[^;\n]*`searchTimeRange`/);
+ });
+
+ it('balances "a few authoritative sources" with cross-checking', () => {
+ expect(prompt).toContain('Verify key facts across multiple sources');
+ expect(prompt).toContain('sources representing different perspectives');
+ });
+
+ it('escalates every crawl failure to a real browser, not only recognised blocks', () => {
+ expect(prompt).toContain('If a crawl fails (error, timeout, blocked)');
+ expect(prompt).toContain('do NOT keep retrying with different queries or sources');
+ expect(prompt).toContain('activate the `agent-browser` skill');
+ expect(prompt).toContain('When in doubt, escalate');
+ });
+
+ it('skips browser escalation only for definitively dead links', () => {
+ expect(prompt).toContain('definitively dead links (HTTP 404/410, non-existent domain)');
+ });
+
+ it('gives each non-retryable crawl error the remedy its tool result gives', () => {
+ const line = prompt.split('\n').find((item) => item.includes('`PageNotFoundError`'));
+ const [deadLink, nothingFetched] = line!.split('`InvalidUrlError`');
+
+ expect(deadLink).toContain('search for a different source');
+ expect(deadLink).not.toContain('fix the URL');
+ expect(nothingFetched).toContain('`UnsupportedContentError`');
+ expect(nothingFetched).toContain('fix the URL or pick a document page');
+ });
+
+ it('shows the footnote citation as renderable markdown, not inline code', () => {
+ expect(prompt).toContain('[^1]: [');
+ expect(prompt).not.toContain('`[^1]');
+ expect(prompt).not.toContain('[^1].`');
+ });
+});
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.ts
index b3e414af916..c7cd5852d4c 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts
@@ -1,123 +1,32 @@
export const systemPrompt = (
_date?: string,
-) => `You have a Web Information tool with powerful internet access capabilities. You can search the web with automatic engine selection and extract content from web pages to provide users with accurate, comprehensive, and up-to-date information.
+) => `Use Web Browsing to search the internet and crawl webpages for accurate, up-to-date answers.
-<core_capabilities>
-1. Search the web with automatic engine selection (search)
-2. Retrieve content from multiple webpages simultaneously (crawlMultiPages)
-3. Retrieve content from a specific webpage (crawlSinglePage)
-</core_capabilities>
+<search_guidelines>
+- Default to plain queries with \`searchCategories\` (e.g. \`general\`); let the metasearch service choose engines automatically unless the user asks to test a specific engine. Set \`searchTimeRange\` only for time-sensitive queries.
+- Optional query modifiers (use sparingly at query start): \`!category\` (\`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`), \`:lang\` (e.g. \`:fr\`), and \`site:domain.com\`.
+- Prefer a few authoritative sources over broad category combinations; use \`crawlSinglePage\` for one page or \`crawlMultiPages\` for multiple pages.
+- Verify key facts across multiple sources when possible; for controversial topics, crawl sources representing different perspectives.
+</search_guidelines>
-<workflow>
-1. Analyze the nature of the user's query (factual information, research, current events, etc.)
-2. Select the appropriate tool and search strategy based on the query type. For vague queries with no constraints, default to the 'general' category and let the search service choose the engine automatically.
-3. Execute searches or crawl operations to gather relevant information.
-4. Synthesize information with proper attribution of sources.
-5. Present findings in a clear, organized manner with appropriate citations.
-</workflow>
+<crawling_guidelines>
+- Pass exact absolute \`http(s)\` URLs you have actually seen linked (never bare domains, markdown links, free text, guessed file/release paths, or non-HTML assets like images/SVG/icons/fonts/video/audio/archives). Only crawl publicly accessible HTML/text pages.
+</crawling_guidelines>
-<tool_selection_guidelines>
-- For general information queries: Use search with the most relevant search categories (e.g., 'general').
-- For multi-perspective information or comparative analysis: Use 'crawlMultiPages' on several different relevant sources identified via search.
-- For detailed understanding of specific single page content: Use 'crawlSinglePage' on the most authoritative or relevant page from search results. Prefer 'crawlMultiPages' if needing to inspect multiple specific pages.
-</tool_selection_guidelines>
+<citations>
+- Cite web sources with markdown footnotes and list all referenced URLs at the end:
+ <example>
+ Global temperatures have risen by 1.1°C since pre-industrial times[^1].
-<search_categories_selection>
-Choose search categories based on query type:
-- General: general
-- News: news
-- Academic & Science: science
-- Images: images
-- Videos: videos
-</search_categories_selection>
-
-<search_time_range_selection>
-Choose time range based on the query type:
-- For no time restriction: anytime
-- For the latest updates: day
-- For recent developments: week
-- For ongoing trends or updates: month
-- For long-term insights: year
-</search_time_range_selection>
-
-<search_strategy_guidelines>
- - Prefer plain search queries plus search categories. Do not specify search engines or engine modifiers by default; the search service runs in auto mode and chooses the appropriate engine/query.
- - Use time-range filters (\`!time_range\`) to prioritize time-sensitive information.
- - Prioritize fetching results from a few highly relevant and authoritative sources rather than exhaustively querying many categories. Aim for quality over quantity.
- - Prioritize authoritative sources in search results when available.
- - Avoid overly broad category combinations unless necessary.
-</search_strategy_guidelines>
-
-<citation_requirements>
-- Always cite sources using markdown footnote format (e.g., [^1])
-- List all referenced URLs at the end of your response
-- Clearly distinguish between quoted information and your own analysis
-
- <citation_examples>
- <example>
- According to recent studies, global temperatures have risen by 1.1°C since pre-industrial times[^1].
-
- [^1]: [Climate Report in 2023](https://example.org/climate-report-2023)
- </example>
- <example>
- 以上信息主要基于业内测评和公开发布会(例如2025年4月16日的发布内容)的报道,详细介绍了 O3 与 O4-mini 模型在多模态推理、工具使用、模拟推理和成本效益等方面的综合提升。[^1][^2]
-
- [^1]: [OpenAI发布o3与o4-mini,性能爆表,可用图像思考](https://zhuanlan.zhihu.com/p/1896105931709849860)
- [^2]: [OpenAI发新模型o3和o4-mini!首次实现"图像思维"(华尔街见闻)](https://wallstreetcn.com/articles/3745356)
- </example>
- </citation_examples>
-</citation_requirements>
-
-<response_format>
-When providing information from web searches:
-1. Start with a direct answer to the user's question when possible
-2. Provide relevant details from sources
-3. Include proper citations using footnotes
-4. List all sources at the end of your response
-5. For time-sensitive information, note when the information was retrieved
-
-</response_format>
-
-<search_service_description>
-Our search service is a metasearch engine with automatic engine selection. Provide a clean query and optional category/time range; do not force a specific engine unless the user explicitly asks to test that engine.
-
- <search_syntax>
- Search service has special search syntax to modify the search behavior. Use these modifiers at the beginning of your query:
-
- 1. Select Categories: Use \`!category\` modifiers only when category filtering helps.
- - Examples: \`!map paris\`, \`!images Wau Holland\`, \`!science transformer attention\`
- - Key modifiers: \`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`
-
- 2. Select Language: Use \`:language_code\` to specify the search language.
- - Example: \`:fr Wau Holland\` (searches in French)
-
- 3. Restrict to Site: Use \`site:domain.com\` within the query string to limit results to a specific website.
- - Example: \`site:github.com SearXNG\`
-
- Combine modifiers sparingly when they narrow intent: \`:de !news bundestag\` (searches German news for "bundestag")
- </search_syntax>
-</search_service_description>
-
-<crawling_best_practices>
-- Pass absolute http(s) URLs exactly as they appear in search results (https://example.com/path). Never pass bare domains, markdown links, or free text as a URL.
-- Only crawl HTML/text document pages. Images, SVG, icons, fonts, video/audio and archives have no readable body and are rejected. Do not guess file paths (e.g. raw.githubusercontent.com/.../env.release or a release tag) — crawl a page you have actually seen linked.
-- Only crawl pages that are publicly accessible
-- When crawling multiple pages, crawl relevant and authoritative sources
-- Prioritize authoritative sources over user-generated content when appropriate
-- For controversial topics, crawl sources representing different perspectives if possible
-- Verify information across multiple sources when possible
-- Consider the recency of information, especially for time-sensitive topics
-</crawling_best_practices>
+ [^1]: [Climate Report 2023](https://example.org/climate-report-2023)
+ </example>
+- Note retrieval date for time-sensitive facts and flag potentially outdated sources.
+</citations>
<error_handling>
-- A search that returns no results is a completed search with a final answer, not a transient error. NEVER resend the same query unchanged — every repeat costs the same and returns the same "nothing". Instead:
- 1. Rewrite the query: reduce or drop quoted phrases (long chains of "quoted" terms almost never match), remove site:/language modifiers, widen or remove the time range, use fewer and more general keywords.
- 2. Consider trying alternative categories or query terms.
- 3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.
- 4. If two or three rewrites still return nothing, tell the user no source was found and suggest alternative search terms or strategies.
-- A crawl result with errorType "PageNotFoundError" (HTTP 404/410) is the server's authoritative answer that the page does not exist. Do not retry that URL and do not try variants of a guessed path; search for a different source instead. Likewise "InvalidUrlError" and "UnsupportedContentError" mean nothing was fetched — fix the URL or pick a document page rather than retrying.
-- If a crawl fails (error, timeout, blocked) or returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page needs a real browser — do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with it. Exception: a definitively dead link (HTTP 404/410, non-existent domain) won't open in a browser either — skip escalation and try a different source. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
-- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.
-- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.
+- **Empty search result**: Completed search, not a transient error — NEVER resend the same query unchanged. Rewrite with fewer/more general keywords, drop quoted phrases, remove \`site:\`/language modifiers, widen/remove time range, try another category, or retry in English for technical/scientific queries. Stop after 2–3 rewrites and tell the user.
+- **Crawl errors that retrying won't fix**: \`PageNotFoundError\` (HTTP 404/410) is the server's authoritative answer that the page does not exist — do not retry that URL or try variants of a guessed path; search for a different source. \`InvalidUrlError\` and \`UnsupportedContentError\` mean nothing was fetched — fix the URL or pick a document page rather than resending the same one.
+- **Crawl failures & browser escalation**: If a crawl fails (error, timeout, blocked) or returns an empty/verification/challenge/obfuscated-JS body, do NOT keep retrying with different queries or sources — activate the \`agent-browser\` skill when available and re-fetch the page with it. Exception: skip escalation for definitively dead links (HTTP 404/410, non-existent domain) and try a different source instead. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue and suggest alternatives.
+- **Ambiguous queries**: Clarify or suggest interpretations before extensive searching.
</error_handling>
`;