🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 fix(builtin-tool-agent-documents): wire Inspectors into registry, switch to chip UI (#14404)
Arvin Xud5097c796404
diff --git a/.agents/skills/builtin-tool/SKILL.md b/.agents/skills/builtin-tool/SKILL.mdnew file mode 100644index 00000000000..6b35a749664--- /dev/null+++ b/.agents/skills/builtin-tool/SKILL.md@@ -0,0 +1,130 @@+---+name: builtin-tool+description: Build a new builtin tool package under `packages/builtin-tool-<name>/`. Use when adding a new agent-callable toolset, designing its API surface (manifest / ApiName / Params / State), implementing the Executor + ExecutionRuntime, building the Inspector / Render / Placeholder / Streaming / Intervention / Portal UI, or wiring a tool into the central registries (`packages/builtin-tools/src/{index,identifiers,inspectors,renders,placeholders,streamings,interventions,portals}.ts` and `src/store/tool/slices/builtin/executors/index.ts`). Triggers on "new builtin tool", "add a tool", "tool inspector", "tool render", "tool placeholder", "tool streaming", "tool intervention", "BuiltinToolManifest", "BaseExecutor", "ExecutionRuntime".+---++# Builtin Tool Authoring Guide++A builtin tool is a package the agent runtime can call. It ships **five faces**:++| Face | Lives in | Audience |+| -------------------- | -------------------------------------------------------------------------------------- | ------------------------------------- |+| **Manifest + types** | `src/{manifest,types,systemRole}.ts` | The LLM (tool spec + system prompt) |+| **ExecutionRuntime** | `src/ExecutionRuntime/` | Server / desktop / any runtime caller |+| **Executor** | `src/client/executor/` | Frontend (wraps stores/services) |+| **Client UI** | `src/client/{Inspector,Render,…}/` | Chat UI |+| **Registry wiring** | `packages/builtin-tools/src/*.ts` + `src/store/tool/slices/builtin/executors/index.ts` | Framework |++---++## Read These First++| Question | Doc |+| ------------------------------------------------------------------------------------ | ---------------------------------- |+| Where do files live? What does each face do? Wiring? | [architecture.md](architecture.md) |+| How do I name the tool, design APIs, write the manifest, executor, ExecutionRuntime? | [tool-design.md](tool-design.md) |+| How do I build Inspector / Render / Placeholder / Streaming / Intervention / Portal? | [ui.md](ui.md) |++---++## When to Use This Skill++- Creating a new `packages/builtin-tool-<name>/` package+- Adding a new API method to an existing builtin tool+- Building or restyling any of the 6 client surfaces for a tool+- Wiring a tool into the central registries+- Debugging "tool not found / API not found / render not showing / placeholder stuck" errors++---++## Top-Level Design Principles++1. **`lobe-<domain>` identifier is permanent.** It's stored in message history. Renames need `@deprecated` aliases (see `packages/builtin-tools/src/inspectors.ts:88-89`). Get it right the first time.+2. **ApiName is an `as const` object**, not a TS enum. It doubles as the runtime list `BaseExecutor` iterates over.+3. **Three result fields, three audiences:**+ - `content: string` → the LLM reads it+ - `state: Record<…>` → the UI's `pluginState`; **result-domain only**, never echo all params back+ - `error: { type, message, body? }` → both LLM and UI; `type` is a stable code+4. **Split execution from frontend wiring.**+ - `src/ExecutionRuntime/` — pure runtime, no React, no Zustand, accepts services via constructor. **The default place for new logic.**+ - `src/client/executor/` — `BaseExecutor` subclass that calls `ExecutionRuntime` (or stores/services directly when frontend-only).+5. **UI defaults to "do nothing".** Inspector is required (the header strip). Render/Placeholder/Streaming/Intervention/Portal are added **only when there's something specific to show** — empty registries are fine.+6. **Style with `createStaticStyles + cssVar.*`** (zero-runtime). Fall back to `createStyles + token` only when you genuinely need runtime values. Use `@lobehub/ui` components, not raw antd.+7. **i18n keys live in `src/locales/default/plugin.ts`.** Inspector titles must come from `t('builtins.<identifier>.apiName.<api>')` so something renders while args stream.++---++## Package Layout (preferred, post-2026 convention)++```+packages/builtin-tool-<name>/+├── package.json+└── src/+ ├── index.ts # exports manifest + types + systemRole + Identifier (no React, no stores)+ ├── manifest.ts # BuiltinToolManifest with JSON Schema for every API+ ├── types.ts # ApiName const + Params/State interfaces per API+ ├── systemRole.ts # System prompt teaching the model when/how to use the APIs+ ├── ExecutionRuntime/ # ✅ Default home for runtime logic (server- or anywhere-callable)+ │ └── index.ts+ └── client/+ ├── index.ts # Re-exports for the registries+ ├── executor/ # ✅ Frontend executor — extends BaseExecutor, often delegates to ExecutionRuntime+ │ └── index.ts+ ├── Inspector/ # required — header chip per API+ ├── Render/ # optional — rich result card+ ├── Placeholder/ # optional — skeleton during streaming/execution+ ├── Streaming/ # optional — live output renderer (e.g. RunCommand, WriteFile)+ ├── Intervention/ # optional — approval / edit-before-run UI+ ├── Portal/ # optional — full-screen detail view+ └── components/ # shared subcomponents used by the surfaces above+```++**Older packages** (`builtin-tool-task`, `builtin-tool-calculator`, etc.) still have `src/executor/` as a sibling of `src/client/`. That's grandfathered; **don't relocate without a deliberate refactor**. New packages and new APIs added to existing packages should follow the layout above.++`package.json` exports map:++```json+"exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executor": "./src/client/executor/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+}+```++---++## Authoring Checklist++Before opening the PR:++- [ ] Identifier follows `lobe-<domain>` and is **stable** (lives in message history).+- [ ] Every `<Name>ApiName` value has: a manifest `api[]` entry, an executor method, an Inspector, an i18n `apiName.*` key.+- [ ] `Params` interfaces match the JSON Schema; `State` interfaces match what the executor returns and what the UI surfaces read.+- [ ] System prompt disambiguates confusable APIs and points to batch variants.+- [ ] Runtime logic lives in `ExecutionRuntime/`; the `client/executor/` only wires stores/services and delegates.+- [ ] Executor returns `{ success, content, state, error? }` via a single `toResult()` funnel — `content` always non-empty (default to `error.message`).+- [ ] Inspector handles `isArgumentsStreaming`, `isLoading`, `partialArgs`, missing `pluginState`.+- [ ] Render returns `null` until it has data; only created for APIs with rich results.+- [ ] Placeholder added if the API has a perceivable execution lag (search, list, crawl).+- [ ] Streaming added for APIs that emit incremental output (run command, write file, code execution).+- [ ] Intervention added if `humanIntervention` is set in the manifest.+- [ ] All registry files updated (see [architecture.md → Registry wiring](architecture.md#registry-wiring)).+- [ ] i18n keys in `src/locales/default/plugin.ts` plus dev seeds in `en-US`/`zh-CN`.+- [ ] `bunx vitest run --silent='passed-only' 'packages/builtin-tool-<name>'` passes.+- [ ] `bun run type-check` passes.++---++## Reference Tools++Pick the closest neighbor and copy:++| If your tool is… | Read first |+| ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| Pure-compute, no UI state | `packages/builtin-tool-calculator/` — `ExecutionRuntime` reuses executor (mathjs/nerdamer work everywhere) |+| CRUD over a domain entity | `packages/builtin-tool-task/` — full Inspector + Render set, batch variants |+| Heavy UI (Inspector/Render/Placeholder/Portal) | `packages/builtin-tool-web-browsing/` — search-style result UI, Portal for detail view |+| Desktop / filesystem with all surfaces (incl. Streaming + Intervention) | `packages/builtin-tool-local-system/` — `ExecutionRuntime` injects an `ILocalSystemService`, executor calls it |+| Server-side pure (no client executor) | `packages/builtin-tool-web-browsing/` — only `ExecutionRuntime` is exported; the chat client doesn't run it |+| Needs human approval before running | `packages/builtin-tool-local-system/src/client/Intervention/` — per-API approval components |diff --git a/.agents/skills/builtin-tool/architecture.md b/.agents/skills/builtin-tool/architecture.mdnew file mode 100644index 00000000000..7f7375d1291--- /dev/null+++ b/.agents/skills/builtin-tool/architecture.md@@ -0,0 +1,315 @@+# Builtin Tool Architecture++## The Five Faces++A builtin tool ships five distinct faces, each compiled into a different bundle:++```+┌─────────────────────────────────────────────────────────────────┐+│ ./ │+│ Manifest + Types + systemRole │+│ ─ Pure data, no React, no Node-only deps. │+│ ─ Imported by: server (LLM tool spec), client (registries), │+│ anyone who needs to know "what tools exist". │+└─────────────────────────────────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ ./executionRuntime │+│ src/ExecutionRuntime/index.ts │+│ ─ Pure runtime logic. Accepts services via constructor — │+│ never imports concrete services or stores directly. │+│ ─ Imported by: server (BuiltinServerRuntimeOutput), tests, │+│ and the client executor as a delegate. │+│ ─ Returns: BuiltinServerRuntimeOutput { content, state, … } │+└─────────────────────────────────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ ./executor │+│ src/client/executor/index.ts │+│ ─ BaseExecutor subclass. Wires Zustand stores and frontend │+│ services into ExecutionRuntime, then funnels through │+│ toResult() into BuiltinToolResult { content, state, error, │+│ success }. │+│ ─ Imported by: src/store/tool/slices/builtin/executors/ │+│ index.ts (registered as a singleton). │+└─────────────────────────────────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ ./client │+│ src/client/{Inspector,Render,Placeholder,Streaming, │+│ Intervention,Portal,components}/ │+│ ─ React 'use client' surfaces. Read args + pluginState. │+│ ─ Imported by: packages/builtin-tools/src/{inspectors, │+│ renders,placeholders,streamings,interventions,portals}.ts. │+└─────────────────────────────────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ Registry wiring │+│ packages/builtin-tools/src/*.ts │+│ src/store/tool/slices/builtin/executors/index.ts │+│ ─ Aggregator maps: identifier → { apiName → component }. │+└─────────────────────────────────────────────────────────────────┘+```++The split exists so:++- Server bundles import only `./` and `./executionRuntime` and never touch React.+- Frontend bundles import `./client` and never touch Node-only services.+- The runtime is testable without React or Electron present.++---++## Why ExecutionRuntime is the Default Home for Logic++**Old pattern (grandfathered):** business logic in `src/executor/` directly. Examples: `builtin-tool-task`, older tools. Works, but the executor mixes runtime logic with frontend service plumbing — hard to reuse on the server.++**New pattern (preferred):** business logic in `src/ExecutionRuntime/`, frontend wiring in `src/client/executor/`. Examples: `builtin-tool-local-system`, `builtin-tool-web-browsing`, `builtin-tool-calculator`.++```+ExecutionRuntime+ ├─ accepts services via constructor (or `static create(opts)`)+ ├─ returns BuiltinServerRuntimeOutput (content + state + success)+ └─ no React, no Zustand, no `@/services/...` direct imports++client/executor+ ├─ extends BaseExecutor<typeof <Name>ApiName>+ ├─ holds a `runtime = new <Name>ExecutionRuntime(realService)` instance+ ├─ each ApiName method:+ │ 1. resolve scope / pull defaults from BuiltinToolContext+ │ 2. call runtime.<method>(args)+ │ 3. funnel through toResult() → BuiltinToolResult+ └─ exported singleton: export const <name>Executor = new <Name>Executor()+```++### Service injection++`ExecutionRuntime` should declare a TypeScript interface for the services it needs and accept the implementation via constructor. Server callers wire in real implementations; tests wire in mocks. Example from `local-system`:++```ts+export interface ILocalSystemService {+ readLocalFile: (params: any) => Promise<any>;+ writeFile: (params: any) => Promise<any>;+ /* … */+}++export class LocalSystemExecutionRuntime extends ComputerRuntime {+ constructor(private service: ILocalSystemService) {+ super();+ }+ /* methods delegate to this.service.* */+}+```++The `client/executor` instantiates it once with the real service:++```ts+import { localFileService } from '@/services/electron/localFileService';+import { LocalSystemExecutionRuntime } from '../../ExecutionRuntime';++class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {+ private runtime = new LocalSystemExecutionRuntime(localFileService);+ /* … */+}+```++### When ExecutionRuntime is the only thing you ship++Some tools are server-only — there's no frontend executor. `builtin-tool-web-browsing` is the canonical example: only `./` and `./executionRuntime` are exported, no `./executor`, and the runtime is constructed by the server-side `ToolExecutionService`. Skip `client/executor/` entirely for those.++### When the executor reuses the runtime as-is++Pure-compute tools (`builtin-tool-calculator`) often have an executor whose ApiName methods call `executor.calculate(args)` and an `ExecutionRuntime` whose methods call `calculatorExecutor.calculate(args)` — same logic, two thin wrappers. That's fine; the duplication buys you the bundle split.++---++## The Result Contract++### `BuiltinServerRuntimeOutput` (what ExecutionRuntime returns)++```ts+{+ content: string; // the LLM-facing text — never undefined; default to error message+ state?: any; // result-domain object the UI reads as pluginState+ success: boolean; // mandatory+ error?: any; // raw error; the executor will repackage+}+```++### `BuiltinToolResult` (what the executor returns to the runtime)++```ts+{+ success: boolean;+ content?: string;+ state?: any;+ error?: { type: string; message: string; body?: any };+ metadata?: Record<string, any>; // rare; e.g. { agentCouncil: true }+ stop?: boolean; // rare; halt the orchestration step+}+```++### The `toResult` funnel (mandatory)++Every executor method returns through a single `toResult()` to enforce two invariants:++1. **`content` is never undefined.** A missing content collapses downstream into `''`, leaving the Debug pane blank while `pluginState` was already saved. See the `globLocalFiles` regression in `local-system/src/client/executor/index.ts:60-84`.+2. **`state` survives failures.** Renderers can keep showing partial output even when `success: false`.++```ts+private toResult(output: BuiltinServerRuntimeOutput): BuiltinToolResult {+ const errorMessage = typeof output.error?.message === 'string' ? output.error.message : undefined;+ const safeContent = output.content || errorMessage || 'Tool execution failed';++ if (!output.success) {+ return {+ success: false,+ content: safeContent,+ state: output.state,+ error: output.error+ ? { type: 'PluginServerError', message: errorMessage ?? safeContent, body: output.error }+ : undefined,+ };+ }+ return { success: true, content: safeContent, state: output.state };+}+```++---++## `BaseExecutor` — How Method Dispatch Works++`BaseExecutor.invoke(apiName, params, ctx)` does:++```ts+if (!this.hasApi(apiName)) return { error: { type: 'ApiNotFound', … }, success: false };+return (this as any)[apiName](params, ctx); // method name MUST equal apiName value+```++So:++- **Method names must equal `<Name>ApiName` values, exactly.** A typo silently routes to "ApiNotFound".+- **Methods must be class fields, not class methods**, because `this` is lost when registry calls `executor.invoke(apiName, params, ctx)`. Always declare as `methodName = async (…) => { … }`.+- **Always destructure `apiEnum` and `identifier` as `readonly` instance fields**, not getters — `BaseExecutor.hasApi/getApiNames` reads them synchronously.++---++## `BuiltinToolContext` — What the Executor Receives++The runtime hands every executor method an optional `BuiltinToolContext` as the second argument:++| Field | Use |+| ----------------------------- | -------------------------------------------------------------- |+| `agentId` | Default agent for "current agent" semantics (e.g. `listTasks`) |+| `groupId` | Group chat scope |+| `topicId` | Current topic — needed when creating messages/operations |+| `taskId` | Current task identifier — fallback for "implicit" param |+| `documentId` | Current page/document scope |+| `messageId` | The tool message being created (for state attachments) |+| `sourceMessageId` | The user message that triggered this tool turn |+| `operationId` | Operation lineage (use for cancellation, tracing) |+| `scope` | `'task' \| 'agent' \| …` — toggles default behaviors |+| `signal: AbortSignal` | Honor for long-running ops |+| `stepContext` | Cross-message runtime state (GTD todos, etc.) |+| `registerAfterCompletion(cb)` | Defer side-effects past message-update race |+| `groupOrchestration` | Group orchestration callbacks |++**Use rule:** read with `?.`, fall back to explicit params, **never silently override** an explicit param with a context value.++---++## i18n Integration++Source of truth: `src/locales/default/plugin.ts`. Keys follow `builtins.<identifier>.<topic>.<…>`:++| Key | Use |+| ------------------------------------- | ------------------------------------------------------------ |+| `builtins.<identifier>.title` | Display title (overrides `manifest.meta.title` when present) |+| `builtins.<identifier>.apiName.<api>` | Inspector header label (one per ApiName) |+| `builtins.<identifier>.inspector.<…>` | Extra Inspector strings ("no results", chips, counters) |+| `builtins.<identifier>.<feature>.<…>` | Render / Intervention strings, free-form per tool |++For dev preview, also seed `locales/zh-CN/plugin.json` and `locales/en-US/plugin.json`. Run `pnpm i18n` before opening a PR — it's slow, so do it once at the end. (See the **i18n** skill for the full workflow.)++---++## Registry Wiring++Five core files plus optional ones. Miss any and you'll see "tool not found", a missing chip, a blank result card, a stuck spinner, or an approval dialog that never appears.++| File | Add what |+| -------------------------------------------------- | ----------------------------------------------------------------------------------------- |+| **Required** | |+| `packages/builtin-tools/src/index.ts` | Import `<Name>Manifest`; push entry to `builtinTools`. Set `hidden`/`discoverable` flags. |+| `packages/builtin-tools/src/identifiers.ts` | Add `<Name>Manifest.identifier` to `builtinToolIdentifiers`. |+| `packages/builtin-tools/src/inspectors.ts` | Import `<Name>Inspectors, <Name>Manifest`; add to `BuiltinToolInspectors`. |+| `src/store/tool/slices/builtin/executors/index.ts` | Import `<name>Executor`; add to `registerExecutors([…])`. |+| **Conditional — add only if the surface exists** | |+| `packages/builtin-tools/src/renders.ts` | Add to `BuiltinToolsRenders` if any API has a Render. |+| `packages/builtin-tools/src/placeholders.ts` | Add to `BuiltinToolPlaceholders` if any API has a Placeholder. |+| `packages/builtin-tools/src/streamings.ts` | Add to `BuiltinToolStreamings` if any API has a Streaming renderer. |+| `packages/builtin-tools/src/interventions.ts` | Add to `BuiltinToolInterventions` if any API has an Intervention component. |+| `packages/builtin-tools/src/portals.ts` | Add to `BuiltinToolsPortals` if the tool has a Portal. |+| `packages/builtin-tools/src/displayControls.ts` | Add if Render must show/hide based on result content (rare; see ClaudeCode/Codex). |++### Optional flags in `packages/builtin-tools/src/index.ts`++```ts+{+ identifier: TaskManifest.identifier,+ manifest: TaskManifest,+ type: 'builtin',+ hidden: true, // hide from chat-input Tools popover+ discoverable: false, // exclude from agent builder / skill discovery+}+```++Lists in the same file you may need to touch:++- `defaultToolIds` — added to the agent's tool list by default+- `alwaysOnToolIds` — forced on regardless of user selection (use sparingly)+- `runtimeManagedToolIds` — enable state controlled by runtime, not user UI; **must mirror the rules map** in `src/server/modules/Mecha/AgentToolsEngine/index.ts` and `src/helpers/toolEngineering/index.ts`++---++## File-Map at a Glance++```+packages/builtin-tool-<name>/+├── package.json # exports: ., ./client, ./executor, ./executionRuntime+└── src/+ ├── index.ts # export Manifest, Identifier, types, systemPrompt+ ├── manifest.ts # BuiltinToolManifest + Identifier const+ ├── types.ts # ApiName + Params/State per API+ ├── systemRole.ts # System prompt (multiple variants OK: systemRole.desktop.ts)+ ├── ExecutionRuntime/+ │ └── index.ts # <Name>ExecutionRuntime — pure runtime, service injection+ └── client/+ ├── index.ts # exports for the registries+ ├── executor/+ │ └── index.ts # <Name>Executor extends BaseExecutor; export <name>Executor+ ├── Inspector/+ │ ├── index.ts # <Name>Inspectors record+ │ └── <ApiName>/index.tsx # one folder per API (or .tsx file when trivial)+ ├── Render/+ │ ├── index.ts # <Name>Renders record+ │ └── <ApiName>/ # rich renders → folder with subcomponents+ ├── Placeholder/+ │ ├── index.ts+ │ └── <ApiName>.tsx # usually a single skeleton file+ ├── Streaming/+ │ ├── index.ts+ │ └── <ApiName>/ # live-output renderer+ ├── Intervention/+ │ ├── index.ts+ │ └── <ApiName>/ # approval / edit-before-run UI+ ├── Portal/+ │ ├── index.tsx # routing component (switch on apiName)+ │ └── <ApiName>/ # full-screen detail view+ └── components/ # FileItem, EngineAvatar, etc. — shared subcomponents+```++Skip every `client/<surface>/` directory you don't need — empty registries are fine.diff --git a/.agents/skills/builtin-tool/tool-design.md b/.agents/skills/builtin-tool/tool-design.mdnew file mode 100644index 00000000000..05e288a61a7--- /dev/null+++ b/.agents/skills/builtin-tool/tool-design.md@@ -0,0 +1,478 @@+# Tool Design (Naming, Manifest, Executor, Runtime)++This doc covers everything that **isn't UI**: the tool's identifier, API surface, manifest, types, system prompt, ExecutionRuntime, and the executor that wires it into the frontend.++For UI surfaces (Inspector / Render / Placeholder / Streaming / Intervention / Portal), see [ui.md](ui.md).+For where files live and how registries work, see [architecture.md](architecture.md).++---++## 1. Naming++| Thing | Convention | Example |+| ----------------------- | -------------------------------------------------------------- | ------------------------------------------------------------ |+| Package directory | `packages/builtin-tool-<kebab>/` | `builtin-tool-task` |+| npm name | `@lobechat/builtin-tool-<kebab>` | `@lobechat/builtin-tool-task` |+| Tool `identifier` | `lobe-<kebab-domain>` — **persisted in message history** | `lobe-task`, `lobe-calculator`, `lobe-knowledge-base` |+| Identifier const | `<Name>Identifier` exported from `manifest.ts` (or `types.ts`) | `export const TaskIdentifier = 'lobe-task'` |+| API name const | `<Name>ApiName` — `as const` object, **camelCase verbs** | `createTask`, `listTasks`, `runTask` |+| Executor class | `<Name>Executor extends BaseExecutor<typeof <Name>ApiName>` | `TaskExecutor` |+| Executor singleton | `<name>Executor` (camelCase) | `export const taskExecutor = new TaskExecutor()` |+| ExecutionRuntime class | `<Name>ExecutionRuntime` | `LocalSystemExecutionRuntime`, `WebBrowsingExecutionRuntime` |+| Inspector / Render etc. | `<ApiName>Inspector` / `<ApiName>Render` | `CreateTaskInspector`, `SearchInspector` |++### Identifier rules++- **`lobe-` prefix is mandatory** — many switches in the codebase key off it.+- Pick a **domain noun**, not a verb (`lobe-task`, not `lobe-task-manager`).+- The identifier is **persisted in message history** — renaming after release means the `@deprecated` alias trick (see `packages/builtin-tools/src/inspectors.ts:88-89` for how `lobe-tools` aliases `lobe-activator`). Get it right the first time.++### ApiName rules++- Verb + noun, camelCase: `createTask`, `viewTask`, `runTasks`.+- **Plural variant for batch** (`createTasks`, `runTasks`) — describe in the manifest description that it's preferred over multiple single calls. The system prompt should also push the batch form.+- Reserve **clear separation between mutating verbs** (`updateTaskStatus`, `editTask`) and **execution verbs** (`runTask`). The system prompt must warn the model when these are confusable — see `task` for the canonical "do NOT use updateTaskStatus(running) to start a task" warning.+- Read-only verbs: `list*`, `view*`, `get*`, `search*`. Mutating: `create*`, `edit*`, `update*`, `delete*`. Triggers/effects: `run*`, `execute*`, `submit*`.++---++## 2. `types.ts` — ApiName + Params/State++Define `<Name>ApiName` as `as const` so it doubles as a runtime enum (used by `BaseExecutor`) and a literal type. Then declare `Params` and `State` per API.++```ts+export const TaskIdentifier = 'lobe-task';++export const TaskApiName = {+ createTask: 'createTask',+ createTasks: 'createTasks',+ listTasks: 'listTasks',+ /* …one entry per API, group logically (CRUD then run-style) */+} as const;++export type TaskApiNameType = (typeof TaskApiName)[keyof typeof TaskApiName];++// One block per API+export interface CreateTaskParams {+ name: string;+ instruction: string; /* … */+}+export interface CreateTaskState {+ identifier?: string;+ success: boolean;+}++export interface CreateTasksParams {+ tasks: CreateTaskParams[];+}+export interface CreateTasksItemResult {+ error?: string;+ identifier?: string;+ name: string;+ success: boolean;+}+export interface CreateTasksState {+ failed: number;+ results: CreateTasksItemResult[];+ succeeded: number;+}+```++**The result-domain rule for `State`** (memory: "pluginState is result-domain, not call-domain"):++- Include only fields the UI **renders after the call returns** — ids the LLM didn't have when calling, counts, summary numbers, server-assigned status.+- **Don't echo all params.** The Inspector/Render gets `args` for free.+- Keep batch results as `{ succeeded, failed, results }` so the Render can show a one-line summary plus a detail list.++---++## 3. `manifest.ts` — JSON Schema for the LLM++```ts+import type { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { TaskApiName, TaskIdentifier } from './types';++export const TaskManifest: BuiltinToolManifest = {+ identifier: TaskIdentifier,+ type: 'builtin',+ systemRole: systemPrompt,+ meta: {+ avatar: '📋',+ title: 'Task Tools',+ description: 'Create, list, edit, delete tasks with dependencies',+ readme: 'Optional long description shown in tool detail pages',+ },+ api: [+ {+ name: TaskApiName.createTask,+ description:+ 'Create a new task. Optionally attach as a subtask via parentIdentifier. ' ++ 'Prefer createTasks when planning a batch.',+ parameters: {+ type: 'object',+ required: ['name', 'instruction'],+ properties: {+ name: { type: 'string', description: 'Short, descriptive name.' },+ instruction: {+ type: 'string',+ description: 'Detailed instruction for what the task should accomplish.',+ },+ parentIdentifier: {+ type: 'string',+ description:+ 'Identifier of the parent task (e.g. "TASK-1"). If provided, the new task becomes a subtask.',+ },+ priority: {+ type: 'number',+ description: 'Priority level: 0=none, 1=urgent, 2=high, 3=normal, 4=low. Default is 0.',+ },+ },+ },+ },+ /* …one entry per ApiName */+ ],+};+```++### Manifest writing checklist++- **Every API in `<Name>ApiName` has exactly one entry in `api[]`.** Easy to drift after a refactor.+- **`description` on each API is the model's only docs.** Make it long enough for the LLM to pick the right tool. Mention edge cases ("If you provide any filter, omitted filters are not applied implicitly"), defaults, and the relationship to sibling APIs ("To START a task, use runTask — updateTaskStatus only flips a flag").+- **`parameters` is JSON Schema** (`LobeChatPluginApi`). Use `enum`, `required`, `items`, `oneOf`, `additionalProperties: false` etc. — these survive into the LLM's tool spec.+- **Use `additionalProperties: false`** on parameter objects so the model can't sneak unknown fields past validation.+- **Number parameters with semantic values** (`priority: 0=none, 1=urgent, …`) should describe the mapping in the description. Don't rely on `enum` alone for numbers — the model often fills the wrong one.+- **`enum` arrays for known string sets** (statuses, categories, engines). Spread from a constants module (`enum: [...TASK_STATUSES]`) so the manifest stays in sync.++### Optional manifest fields++```ts+{+ /* Where this tool can run.+ 'client' → Agent Gateway dispatches to the desktop client (filesystem, Electron only)+ 'server' → ToolExecutionService runs it on the server+ omitted → server only */+ executors: ['client', 'server'],++ /* Default human intervention policy for all APIs that don't specify one.+ Pair with an Intervention component (see ui.md). */+ humanIntervention: 'never' | 'always' | { /* extended config */ },+}+```++Per-API `humanIntervention` and `renderDisplayControl` go inside each `api[]` entry.++---++## 4. `systemRole.ts` — Operator Instructions for the Model++This is appended to the agent system prompt whenever the tool is enabled. Treat it as a **how-to-use guide for the LLM**, not marketing copy.++```ts+export const systemPrompt = `You have access to Task management tools. Use them to:++- **createTask**: Create a new task. Use parentIdentifier to make it a subtask.+- **createTasks**: Prefer this over multiple createTask calls when planning a batch+ (e.g. all subtasks under one parent, or all chapters of an outline).+- **runTask**: Actually START a task — kicks off the agent in a new (or continued)+ topic. Do NOT use updateTaskStatus(running) to start a task; that only flips a+ flag without executing. The task must have an assigneeAgentId.+- **updateTaskStatus**: Change a task's status (completed/cancelled/paused/failed).+ If you mark a task as failed, include an error message explaining why.+- ...++When planning work:+1. Create tasks for each major piece (use parentIdentifier to organize as subtasks).+2. Use editTask with addDependencies to control execution order.+3. Use updateTaskStatus to mark the current task completed when done.`;+```++### Patterns that work well++- **Bulleted list, bold the API name, one line per API.** The model picks tools by skimming.+- **Disambiguate confusable APIs explicitly** (`runTask` vs `updateTaskStatus`).+- **Push toward batched APIs** ("Prefer this when…").+- **End with a numbered workflow** if the tool has a typical sequence.+- **For tools with multiple environments** (e.g. desktop vs cloud), keep variants in `systemRole.ts` and `systemRole.desktop.ts` and pick at the manifest level. See `builtin-tool-local-system`.++### Dynamic system prompts++If the prompt depends on runtime state (current date, available models), export a function and call it in the manifest:++```ts+// systemRole.ts+export const systemPrompt = (today: string) => `Today is ${today}. You have web search tools…`;++// manifest.ts+import dayjs from 'dayjs';+systemRole: systemPrompt(dayjs(new Date()).format('YYYY-MM-DD')),+```++---++## 5. `ExecutionRuntime/index.ts` — Pure Runtime++This is **the default home for new tool logic** going forward. The runtime is a class that:++- Has no React, no Zustand, no `@/services/...` direct imports.+- Receives services as **constructor injection** (or as method args).+- Returns `BuiltinServerRuntimeOutput` from each method.+- Is unit-testable by passing in mocks.++### Pattern A: Inject a service interface++Use when the runtime calls out to IPC, network, or DB.++```ts+// ExecutionRuntime/index.ts+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';++export interface IWebBrowsingService {+ search: (q: SearchQuery) => Promise<UniformSearchResponse>;+ crawlPages: (urls: string[]) => Promise<CrawlResults>;+}++export interface WebBrowsingRuntimeOptions {+ searchService: IWebBrowsingService;+ documentService?: WebBrowsingDocumentService;+ agentId?: string;+ topicId?: string;+}++export class WebBrowsingExecutionRuntime {+ constructor(private opts: WebBrowsingRuntimeOptions) {}++ async search(+ args: SearchQuery,+ options?: { signal?: AbortSignal },+ ): Promise<BuiltinServerRuntimeOutput> {+ try {+ const data = await this.opts.searchService.search(args, options);+ if (data.errorDetail) {+ return {+ success: false,+ content: data.errorDetail,+ error: { message: data.errorDetail },+ state: data,+ };+ }+ return {+ success: true,+ content: searchResultsPrompt(data.results.slice(0, 10)),+ state: data,+ };+ } catch (e) {+ return { success: false, content: (e as Error).message, error: e };+ }+ }+}+```++### Pattern B: Reuse the executor++Use when the same logic runs in browser and Node (e.g. mathjs, nerdamer). The runtime is a thin wrapper that imports the executor and re-types the state per API. See `builtin-tool-calculator/src/ExecutionRuntime/index.ts` for the canonical example.++### Pattern C: Extend a shared base++When you're implementing a domain that already has a base runtime (file ops via `ComputerRuntime`), extend and only override `callService` + result normalization. See `builtin-tool-local-system/src/ExecutionRuntime/index.ts`.++### Runtime contract++Every method returns:++```ts+{+ content: string; // LLM-facing — never undefined; default to error message+ state?: any; // result-domain — what the UI's pluginState becomes+ success: boolean; // mandatory+ error?: any; // raw error object; the executor will repackage+}+```++Use `@lobechat/prompts` formatters (`searchResultsPrompt`, `crawlResultsPrompt`, `formatTaskCreated`, etc.) to produce structured `content`. They emit XML/markdown that's already tuned for token efficiency.++---++## 6. `client/executor/index.ts` — Frontend Wiring++The executor's job is to **resolve frontend defaults** (current agent, current task, scope) and **call the runtime**. It then funnels through `toResult()` into the `BuiltinToolResult` shape.++```ts+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';+import debug from 'debug';++import { taskService } from '@/services/task';+import { getTaskStoreState } from '@/store/task';++import { TaskIdentifier } from '../../manifest';+import { TaskApiName, type CreateTaskParams } from '../../types';++const log = debug('lobe-task:executor');++class TaskExecutor extends BaseExecutor<typeof TaskApiName> {+ readonly identifier = TaskIdentifier;+ protected readonly apiEnum = TaskApiName;++ // ⚠ class FIELD, not a method — preserves `this` when invoked via registry+ createTask = async (+ params: CreateTaskParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ log('createTask params=%o', params);+ const task = await getTaskStoreState().createTask({+ name: params.name,+ instruction: params.instruction,+ // Default assignee from context — never silently override an explicit value+ assigneeAgentId:+ params.assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),+ parentTaskId: params.parentIdentifier?.trim() || undefined,+ priority: params.priority,+ });++ if (!task) return this.errorResult('Failed to create task', 'CreateFailed');++ return {+ success: true,+ content: formatTaskCreated({ identifier: task.identifier, name: task.name /* … */ }),+ state: { identifier: task.identifier, success: true },+ };+ } catch (error) {+ return this.errorResult(error, 'CreateTaskFailed');+ }+ };++ private errorResult(err: unknown, type: string): BuiltinToolResult {+ const message = err instanceof Error ? err.message : String(err) || 'Unknown error';+ return { success: false, content: `Failed: ${message}`, error: { type, message } };+ }+}++export const taskExecutor = new TaskExecutor();+```++### Hard rules++1. **Methods are class fields** (`name = async (…) => {…}`), not class methods. The registry calls `(executor as any)[apiName](params, ctx)`; arrow-function fields keep `this` bound.+2. **`identifier` and `apiEnum` are `readonly` instance fields**, not getters — `BaseExecutor.hasApi/getApiNames` reads them synchronously at registration time.+3. **Default missing params from `ctx`**, but never silently override explicit values. Use `params.foo ?? ctx?.foo`, not `ctx?.foo ?? params.foo`.+4. **One funnel for all returns.** Either always return through `toResult(runtime.x())` (when delegating) or through `errorResult(…)` for the catch arm. Never inline `{ success: false, content: '' }` — `content: ''` collapses the Debug pane to blank.+5. **`debug('lobe-<name>:executor')`.** Match the namespace to the identifier minus `lobe-` when convenient.+6. **Singleton export.** `export const <name>Executor = new <Name>Executor()` — the registry imports the instance, not the class.++### When the executor delegates to ExecutionRuntime++```ts+class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {+ readonly identifier = LocalSystemIdentifier;+ protected readonly apiEnum = LocalSystemApiEnum;+ private runtime = new LocalSystemExecutionRuntime(localFileService);++ readLocalFile = async (params: LocalReadFileParams): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.readFile({+ path: params.path,+ startLine: params.loc?.[0],+ endLine: params.loc?.[1],+ });+ return this.toResult(result);+ } catch (error) {+ return this.errorResult(error);+ }+ };++ private toResult(out: BuiltinServerRuntimeOutput): BuiltinToolResult {+ const errMsg = typeof out.error?.message === 'string' ? out.error.message : undefined;+ const safe = out.content || errMsg || 'Tool execution failed';+ if (!out.success) {+ return {+ success: false,+ content: safe,+ state: out.state, // ← preserve partial state on failure+ error: out.error+ ? { type: 'PluginServerError', message: errMsg ?? safe, body: out.error }+ : undefined,+ };+ }+ return { success: true, content: safe, state: out.state };+ }+}+```++The `toResult` funnel is **mandatory**: it enforces never-undefined `content` and partial-state preservation. Both invariants caught real production bugs (`globLocalFiles` Response empty, `editLocalFile` partial state lost).++---++## 7. `index.ts` — Package Entry Point++Keep it pure data + the manifest. **No React, no stores, no Node-only imports.**++```ts+export { TaskIdentifier, TaskManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ TaskApiName,+ type TaskApiNameType,+ type CreateTaskParams,+ type CreateTaskState,+ /* …all Params/State types */+} from './types';++// Optional helpers used by both the runtime and the UI+export { TASK_STATUSES, UNFINISHED_TASK_STATUSES } from './constants';+```++This entry is what `packages/builtin-tools/src/index.ts` and `identifiers.ts` import — it must be importable from server bundles.++---++## 8. `package.json`++```json+{+ "dependencies": {+ "@lobechat/prompts": "workspace:*"+ },+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executor": "./src/client/executor/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "name": "@lobechat/builtin-tool-<name>",+ "peerDependencies": {+ "@lobehub/ui": "^5",+ "antd": "^6",+ "antd-style": "*",+ "lucide-react": "*",+ "react": "*",+ "react-i18next": "*"+ },+ "private": true,+ "version": "1.0.0"+}+```++**Why peer not direct deps for client libs:** the `./` and `./executionRuntime` entry points must be importable from server code. Listing React etc. as peer deps prevents bundlers from following them when only the runtime is consumed.++**Skip `./executor`** if the package has no frontend executor (server-only tools like `builtin-tool-web-browsing`).++---++## 9. Common Pitfalls++| Symptom | Likely cause |+| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |+| "ApiNotFound" at runtime | Method name in executor doesn't match `ApiName` value (typo, wrong case) |+| Method works once, then "this is undefined" | Method declared as `async fn() {}` instead of `fn = async () => {}` — `this` lost when registry invokes |+| Debug "Response" pane blank but `pluginState` populated | Returning `content: ''` or letting `output.content` be undefined — use the `toResult` funnel |+| Partial result vanishes on failure | `toResult` discarded `state` when `success: false`; preserve it |+| Tool shows up but doesn't run on desktop | `executors` in manifest doesn't include `'client'` (or vice versa for server-only) |+| Same tool registered twice / "lobe-tools" ghost | Identifier collision; check `@deprecated` aliases in `inspectors.ts`/`renders.ts` |+| Manifest test fails after adding API | Forgot to add the corresponding i18n `apiName.<api>` key |+| TypeScript error on `BaseExecutor<typeof X>` | `X` declared with `enum` instead of `as const` object — must be the const-object form |diff --git a/.agents/skills/builtin-tool/ui.md b/.agents/skills/builtin-tool/ui.mdnew file mode 100644index 00000000000..7b6e597eb49--- /dev/null+++ b/.agents/skills/builtin-tool/ui.md@@ -0,0 +1,721 @@+# Tool UI Surfaces++A builtin tool can ship up to **six client-side surfaces**, each with a different role in the chat UI. Only `Inspector` is required; the other five are added on demand and registered in their own central files.++| Surface | Required? | When the chat shows it | Registered in |+| ------------ | --------- | --------------------------------------------------------------------- | --------------------------------------------- |+| Inspector | ✅ Always | Header strip of every tool call (one-line chip) | `packages/builtin-tools/src/inspectors.ts` |+| Render | Optional | Rich result card below the header, after the call returns | `packages/builtin-tools/src/renders.ts` |+| Placeholder | Optional | Skeleton between "args streaming complete" and "result arrives" | `packages/builtin-tools/src/placeholders.ts` |+| Streaming | Optional | Live output during execution (e.g. command stdout) | `packages/builtin-tools/src/streamings.ts` |+| Intervention | Optional | Approval / edit-before-run dialog (when `humanIntervention` triggers) | `packages/builtin-tools/src/interventions.ts` |+| Portal | Optional | Full-screen detail view (right-side or modal) | `packages/builtin-tools/src/portals.ts` |++The two reference tools to read end-to-end:++- **`builtin-tool-web-browsing/src/client/`** — Inspector + Render + Placeholder + Portal (no Intervention/Streaming).+- **`builtin-tool-local-system/src/client/`** — all six surfaces, including `components/` for shared building blocks.++---++## 0. Shared Style Rules++These apply across every surface.++### 0.1 Use `'use client'` at the top of every component file++Tool surfaces are leaves in the chat tree and must not block server rendering.++### 0.2 Prefer `createStaticStyles + cssVar.*`++Zero-runtime CSS-in-JS — the styles compile once and read CSS variables at runtime.++```tsx+import { createStaticStyles, cssVar } from 'antd-style';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 999px;+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ `,+}));+```++Fall back to `createStyles + token` only when you need runtime token computation (rare). Inline `style={{ color: cssVar.colorTextSecondary }}` is fine for one-off dynamic values.++### 0.3 Use `@lobehub/ui`, not raw `antd`++`Block`, `Text`, `Flexbox`, `Highlighter`, `Alert`, `Tooltip`, `Skeleton` all come from `@lobehub/ui`. Modals come from `@lobehub/ui/base-ui` (`createModal`, `useModalContext`, `confirmModal`) — see the **modal** skill.++Memory note: `@lobehub/ui`'s `<Text type='secondary'>` is a lighter shade than `colorTextSecondary`. If you need that exact token color, write `<Text style={{ color: cssVar.colorTextSecondary }}>`.++### 0.4 Always `memo` and set `displayName`++```tsx+export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSearchResponse>>(+ ({ args /* … */ }) => {+ /* … */+ },+);+SearchInspector.displayName = 'SearchInspector';+export default SearchInspector;+```++### 0.5 Always type with `BuiltinXProps<Args, State>` generics++Don't widen to `any`. The Args generic is the JSON Schema params, the State generic is the executor's `state` field. The two should match `<Name>Params` and `<Name>State` from `types.ts`.++### 0.6 Pull strings from `t('plugin')`++```tsx+const { t } = useTranslation('plugin');+t('builtins.<identifier>.apiName.<api>');+```++Every Inspector should default to `t('builtins.<identifier>.apiName.<api>')` so it shows something while args stream in.++### 0.7 Read store state from `@/store/chat`, not props++Tool surfaces sometimes need cross-cutting state (loading, streaming buffer). Read it inside the component via Zustand selectors, not from props — props only carry args/state/messageId.++---++## 1. Inspector — Header Chip (required)++**Lifecycle:** Inspector renders for **every phase** of a tool call: while args are streaming in, while the executor is running, and after results come back. It's the only surface that's always visible.++**Goal:** keep it to a single line. Show what's happening with as much context as is currently available.++### Props (`BuiltinInspectorProps<Args, State>`)++```ts+interface BuiltinInspectorProps<Arguments = any, State = any> {+ apiName: string;+ args: Arguments; // final args (only after the assistant stops streaming)+ identifier: string;+ isArgumentsStreaming?: boolean; // args still arriving+ isLoading?: boolean; // args complete, executor running+ partialArgs?: Arguments; // partial JSON during streaming+ pluginState?: State; // executor's `state` after success+ result?: { content: string | null; error?: any };+}+```++### State machine++| Phase | What's available | What to show |+| ----------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- |+| Args streaming, no useful field yet | `isArgumentsStreaming === true`, `partialArgs.X` undefined | Just the API title with `shinyTextStyles.shinyText` |+| Args streaming, key field arrived | `partialArgs.X` populated | Title + key field chip, still pulse-animated |+| Args complete, executor running | `args` populated, `isLoading === true` | Same as above, still pulse-animated |+| Result arrived | `pluginState` populated, `isLoading === false` | Title + chips + result summary (count, identifier, status) |++### Canonical example — Search++`packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx`:++```tsx+'use client';++import type { BuiltinInspectorProps, SearchQuery, UniformSearchResponse } from '@lobechat/types';+import { Text } from '@lobehub/ui';+import { cssVar, cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSearchResponse>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const query = args?.query || partialArgs?.query || '';+ const resultCount = pluginState?.results?.length ?? 0;+ const hasResults = resultCount > 0;++ if (isArgumentsStreaming && !query) {+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-web-browsing.apiName.search')}</span>+ </div>+ );+ }++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>{t('builtins.lobe-web-browsing.apiName.search')}: </span>+ {query && <span className={highlightTextStyles.primary}>{query}</span>}+ {!isLoading &&+ !isArgumentsStreaming &&+ pluginState?.results &&+ (hasResults ? (+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>+ ) : (+ <Text as="span" color={cssVar.colorTextDescription} fontSize={12}>+ ({t('builtins.lobe-web-browsing.inspector.noResults')})+ </Text>+ ))}+ </div>+ );+ },+);+SearchInspector.displayName = 'SearchInspector';+export default SearchInspector;+```++### Inspector rules++- Wrap the whole row with `inspectorTextStyles.root` (provides correct flex / line-height baseline).+- Pulse with `shinyTextStyles.shinyText` whenever `isArgumentsStreaming || isLoading`.+- Show the i18n title first so the row is non-empty during the earliest streaming phase.+- Read both `args?.X` and `partialArgs?.X` together — `args` is final, `partialArgs` is in-stream.+- Use chips/tags for distinct facets (identifier, name, parent, status, count). Each chip should clip with `text-overflow: ellipsis` and have a `max-width` so long values don't blow out the chat bubble.+- Append `pluginState`-derived suffixes only **after** loading finishes — count or "(no results)" should not appear while still searching.++### Inspector registry — `client/Inspector/index.ts`++```ts+import type { BuiltinInspector } from '@lobechat/types';++import { TaskApiName } from '../../types';+import { CreateTaskInspector } from './CreateTask';+import { ListTasksInspector } from './ListTasks';+/* … */++export const TaskInspectors: Record<string, BuiltinInspector> = {+ [TaskApiName.createTask]: CreateTaskInspector as BuiltinInspector,+ [TaskApiName.listTasks]: ListTasksInspector as BuiltinInspector,+ /* one entry per ApiName */+};++export { CreateTaskInspector } from './CreateTask';+export { ListTasksInspector } from './ListTasks';+/* re-export each */+```++---++## 2. Render — Rich Result Card (optional)++**Lifecycle:** rendered **once the result arrives** (after Placeholder/Streaming hand off). Sits below the Inspector header.++**Skip if** the API is read-only or the result is just text — the framework already shows the executor's `content` string. Add a Render only when there's a structured artifact worth seeing: a card, a chart, a diff, a list of files.++### Props (`BuiltinRenderProps<Args, State, Content>`)++```ts+interface BuiltinRenderProps<Arguments = any, State = any, Content = any> {+ apiName?: string;+ args: Arguments; // final params from the LLM+ content: Content; // executor's content string (or parsed)+ identifier?: string;+ messageId: string; // for store lookups+ pluginError?: any; // from BuiltinToolResult.error+ pluginState?: State; // executor's state+ toolCallId?: string;+}+```++### Two patterns++**Pattern A — Single-file Render** (web-browsing CrawlSinglePage):++```tsx+// client/Render/CrawlSinglePage.tsx+import type { BuiltinRenderProps, CrawlPluginState, CrawlSinglePageQuery } from '@lobechat/types';+import { memo } from 'react';++import PageContent from './PageContent';++const CrawlSinglePage = memo<BuiltinRenderProps<CrawlSinglePageQuery, CrawlPluginState>>(+ ({ messageId, pluginState, args }) => (+ <PageContent messageId={messageId} results={pluginState?.results} urls={[args?.url]} />+ ),+);+export default CrawlSinglePage;+```++**Pattern B — Folder with subcomponents** (web-browsing Search):++```+client/Render/Search/+├── index.tsx # composes the subcomponents, handles error states+├── ConfigForm.tsx # appears when pluginError.type === 'PluginSettingsInvalid'+├── SearchQuery.tsx # editable query header+└── SearchResult.tsx # result list+```++Use Pattern B when the Render has internal state (editing mode, expanded items), error variants, or is large enough to benefit from splitting.++### Error handling in Render++Renders are the canonical place to surface `pluginError` because the chat doesn't auto-render typed errors:++```tsx+if (pluginError) {+ if (pluginError?.type === 'PluginSettingsInvalid') {+ return <ConfigForm id={messageId} provider={pluginError.body?.provider} />;+ }+ return (+ <Alert+ title={pluginError?.message}+ type="error"+ extra={<Highlighter language="json">{JSON.stringify(pluginError.body, null, 2)}</Highlighter>}+ />+ );+}+```++### Render rules++- **Return `null`** if there's nothing useful to draw yet (avoids empty cards during stream).+- Use `pluginState` for server-truth (ids, counts, server-assigned status) and `args` for what the LLM asked. **Combine — neither alone is enough.**+- For lists, summarize with a header line and show top N items with a "+N more" tail rather than rendering everything.+- For modals from a Render, use `@lobehub/ui/base-ui` (`createModal`, `useModalContext`, `confirmModal`) — see the **modal** skill.++### Render registry — `client/Render/index.ts`++```ts+import type { BuiltinRender } from '@lobechat/types';++import { TaskApiName } from '../../types';+import CreateTaskRender from './CreateTask';+import RunTasksRender from './RunTasks';++export const TaskRenders: Record<string, BuiltinRender> = {+ [TaskApiName.createTask]: CreateTaskRender as BuiltinRender,+ [TaskApiName.runTasks]: RunTasksRender as BuiltinRender,+ /* only the APIs with rich result UI — others fall back to text content */+};++export { default as CreateTaskRender } from './CreateTask';+export { default as RunTasksRender } from './RunTasks';+```++### Render display control (rare)++If the Render should hide for certain results (e.g. ClaudeCode's TodoWrite hides when the agent is mid-stream), add a `RenderDisplayControl` to `packages/builtin-tools/src/displayControls.ts`. See `ClaudeCodeRenderDisplayControls` for the pattern.++---++## 3. Placeholder — Skeleton Between Args and Result (optional)++**Lifecycle:** rendered when the args have finished streaming but the executor hasn't returned yet. Disappears when `pluginState` arrives. Bridges the moment of perceived lag.++**Add for** APIs with noticeable execution time: web search, network crawl, file list, large grep. **Skip for** instant ops (status flips, calculator).++### Props (`BuiltinPlaceholderProps<Args>`)++```ts+interface BuiltinPlaceholderProps<T extends Record<string, any> = any> {+ apiName: string;+ args?: T;+ identifier: string;+}+```++No `pluginState` — Placeholder lives entirely in the "executing" gap.++### Canonical example — Search Placeholder++`packages/builtin-tool-web-browsing/src/client/Placeholder/Search.tsx`:++```tsx+import type { BuiltinPlaceholderProps, SearchQuery } from '@lobechat/types';+import { Flexbox, Icon, Skeleton } from '@lobehub/ui';+import { createStaticStyles, cx } from 'antd-style';+import { SearchIcon } from 'lucide-react';+import { memo } from 'react';++import { useIsMobile } from '@/hooks/useIsMobile';+import { shinyTextStyles } from '@/styles';++const styles = createStaticStyles(({ css, cssVar }) => ({+ query: cx(+ css`+ padding: 4px 8px;+ border-radius: 8px;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ shinyTextStyles.shinyText,+ ),+}));++export const Search = memo<BuiltinPlaceholderProps<SearchQuery>>(({ args }) => {+ const { query } = args || {};+ const isMobile = useIsMobile();++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal={!isMobile} gap={isMobile ? 8 : 40}>+ <Flexbox horizontal align="center" className={styles.query} gap={8}>+ <Icon icon={SearchIcon} />+ {query ? query : <Skeleton.Block active style={{ height: 20, width: 40 }} />}+ </Flexbox>+ <Skeleton.Block active style={{ height: 20, width: 40 }} />+ </Flexbox>+ <Flexbox horizontal gap={12}>+ {[1, 2, 3, 4, 5].map((id) => (+ <Skeleton.Button active key={id} style={{ borderRadius: 8, height: 80, width: 160 }} />+ ))}+ </Flexbox>+ </Flexbox>+ );+});+```++### Placeholder rules++- **Mirror the eventual Render's layout.** When the result arrives the Placeholder unmounts and the Render mounts; if they share dimensions, the chat doesn't jump.+- Use `Skeleton.Block` / `Skeleton.Button` from `@lobehub/ui` for placeholder shapes.+- Embed any args you have (e.g. the query text) — context helps the user know what's loading.+- Pulse with `shinyTextStyles.shinyText` if the Placeholder includes literal text.++### Placeholder registry — `client/Placeholder/index.ts`++```ts+import { WebBrowsingApiName } from '../../types';+import CrawlMultiPages from './CrawlMultiPages';+import CrawlSinglePage from './CrawlSinglePage';+import { Search } from './Search';++export const WebBrowsingPlaceholders = {+ [WebBrowsingApiName.crawlMultiPages]: CrawlMultiPages,+ [WebBrowsingApiName.crawlSinglePage]: CrawlSinglePage,+ [WebBrowsingApiName.search]: Search,+};++export { CrawlMultiPages, CrawlSinglePage, Search };+```++---++## 4. Streaming — Live Output During Execution (optional)++**Lifecycle:** rendered **while the executor is still running** for APIs that emit incremental output. The component is responsible for fetching the in-flight stream from the chat store and rendering it.++**Add for** long-running ops with continuous output: shell command execution (stdout/stderr), file write progress, code interpreter cells.++### Props (`BuiltinStreamingProps<Args>`)++```ts+interface BuiltinStreamingProps<Arguments = any> {+ apiName: string;+ args: Arguments;+ identifier: string;+ messageId: string; // use to fetch the streaming buffer from store+ toolCallId: string;+}+```++Note there's **no `state` or `result` prop** — the Streaming component is for the in-flight phase. It pulls the live buffer from the store itself (typically via `chatToolSelectors.streamingContent(messageId)` or similar).++### Canonical example — RunCommandStreaming++`packages/builtin-tool-local-system/src/client/Streaming/RunCommand/index.tsx`:++```tsx+'use client';++import type { BuiltinStreamingProps } from '@lobechat/types';+import { Highlighter } from '@lobehub/ui';+import { memo } from 'react';++interface RunCommandParams {+ command?: string;+ description?: string;+ timeout?: number;+}++export const RunCommandStreaming = memo<BuiltinStreamingProps<RunCommandParams>>(({ args }) => {+ const { command } = args || {};+ if (!command) return null;++ return (+ <Highlighter+ animated+ wrap+ language="sh"+ showLanguage={false}+ style={{ padding: '4px 8px' }}+ variant="outlined"+ >+ {command}+ </Highlighter>+ );+});+RunCommandStreaming.displayName = 'RunCommandStreaming';+```++For real-time output beyond just the command (stderr/stdout streaming), pull from the chat store:++```tsx+const buffer = useChatStore((state) =>+ chatToolSelectors.streamingBuffer(messageId, toolCallId)(state),+);+```++### Streaming rules++- Render `null` until you have something to display (avoids flash).+- For terminal-style output, use `Highlighter` with `animated` to show typing-like effect.+- The Streaming component must **unmount cleanly** when execution ends — typically the framework swaps it out for the Render automatically.++### Streaming registry — `client/Streaming/index.ts`++```ts+import { LocalSystemApiName } from '../..';+import { RunCommandStreaming } from './RunCommand';+import { WriteFileStreaming } from './WriteFile';++export const LocalSystemStreamings = {+ [LocalSystemApiName.runCommand]: RunCommandStreaming,+ [LocalSystemApiName.writeLocalFile]: WriteFileStreaming,+};+```++---++## 5. Intervention — Approval / Edit-Before-Run (optional)++**Lifecycle:** rendered **before the executor runs** for APIs whose manifest sets `humanIntervention`. The user sees a preview of the args, can edit them, then approves or skips/cancels.++**Add for** destructive or sensitive ops: shell commands, file writes, file moves, payments, message broadcasts.++### Props (`BuiltinInterventionProps<Args>`)++```ts+interface BuiltinInterventionProps<Arguments = any> {+ apiName?: string;+ args: Arguments;+ identifier?: string;+ interactionMode?: 'approval' | 'custom';+ messageId: string;++ /** Called when the user edits the args; the approve action awaits this. */+ onArgsChange?: (args: Arguments) => void | Promise<void>;++ /** Called on approve / skip / cancel. */+ onInteractionAction?: (+ action:+ | { type: 'submit'; payload: Record<string, unknown> }+ | { type: 'skip'; payload?: Record<string, unknown>; reason?: string }+ | { type: 'cancel'; payload?: Record<string, unknown> },+ ) => Promise<void>;++ /** Register a callback to flush pending saves before approval. Returns cleanup. */+ registerBeforeApprove?: (id: string, callback: () => void | Promise<void>) => () => void;+}+```++### Canonical example — RunCommand Intervention++`packages/builtin-tool-local-system/src/client/Intervention/RunCommand/index.tsx`:++```tsx+import type { RunCommandParams } from '@lobechat/electron-client-ipc';+import type { BuiltinInterventionProps } from '@lobechat/types';+import { Flexbox, Highlighter, Text } from '@lobehub/ui';+import { memo } from 'react';++const RunCommand = memo<BuiltinInterventionProps<RunCommandParams>>(({ args }) => {+ const { description, command, timeout } = args;+ return (+ <Flexbox gap={8}>+ <Flexbox horizontal justify="space-between">+ {description && <Text>{description}</Text>}+ {timeout && (+ <Text style={{ fontSize: 12 }} type="secondary">+ timeout: {formatTimeout(timeout)}+ </Text>+ )}+ </Flexbox>+ {command && (+ <Highlighter wrap language="sh" showLanguage={false} variant="outlined">+ {command}+ </Highlighter>+ )}+ </Flexbox>+ );+});+export default RunCommand;+```++### Intervention rules++- **Show a preview, not a form by default.** Editing UI is opt-in via `onArgsChange` and is usually inline (click to edit a code block, etc.).+- For args with debounced edit state (text fields), use `registerBeforeApprove(id, flushFn)` so the approve action waits for the debounce to flush. Always return the cleanup function.+- Call `onInteractionAction({ type: 'submit', payload })` when the user approves; `'skip'` if they skip with a reason; `'cancel'` if they cancel the whole turn.+- Add a corresponding `interventionAudit.ts` in the package root if the tool needs scope/path validation before approval (see `local-system/src/interventionAudit.ts`).++### Intervention registry — `client/Intervention/index.ts`++```ts+import { LocalSystemApiName } from '../..';+import EditLocalFile from './EditLocalFile';+import RunCommand from './RunCommand';+import WriteFile from './WriteFile';+/* … */++export const LocalSystemInterventions = {+ [LocalSystemApiName.editLocalFile]: EditLocalFile,+ [LocalSystemApiName.runCommand]: RunCommand,+ [LocalSystemApiName.writeLocalFile]: WriteFile,+ /* one entry per API that needs approval */+};+```++---++## 6. Portal — Full-Screen Detail View (optional)++**Lifecycle:** rendered when the user opens the tool message in a side panel or full-screen modal. One Portal per **tool**, not per API — the Portal switches on `apiName` internally.++**Add for** tools whose results deserve a deep-dive view: search results with editable filters, page content with reader mode, code interpreter sessions.++### Props (`BuiltinPortalProps<Args, State>`)++```ts+interface BuiltinPortalProps<Arguments = Record<string, any>, State = any> {+ apiName?: string;+ arguments: Arguments;+ identifier: string;+ messageId: string;+ state: State;+}+```++### Canonical example — Web-Browsing Portal++`packages/builtin-tool-web-browsing/src/client/Portal/index.tsx`:++```tsx+import type { BuiltinPortalProps, CrawlPluginState, SearchQuery } from '@lobechat/types';+import { memo } from 'react';++import { WebBrowsingApiName } from '../../types';+import PageContent from './PageContent';+import PageContents from './PageContents';+import Search from './Search';++const Portal = memo<BuiltinPortalProps>(({ arguments: args, messageId, state, apiName }) => {+ switch (apiName) {+ case WebBrowsingApiName.search:+ return <Search messageId={messageId} query={args as SearchQuery} response={state} />;++ case WebBrowsingApiName.crawlSinglePage: {+ const result = (state as CrawlPluginState).results.find((r) => r.originalUrl === args.url);+ return <PageContent messageId={messageId} result={result} />;+ }++ case WebBrowsingApiName.crawlMultiPages:+ return (+ <PageContents+ messageId={messageId}+ results={(state as CrawlPluginState).results}+ urls={args.urls}+ />+ );+ }+ return null;+});+export default Portal;+```++### Portal rules++- One Portal per tool — the file is the routing layer, subcomponents implement each API's view.+- Portals can read the chat store directly to detect "still streaming" and render a Skeleton internally (see `Search/index.tsx:20-46`).+- Layout assumes more space than the Render — use `Flexbox` with `height={'100%'}` and structure for a side panel viewport.++### Portal registry — `packages/builtin-tools/src/portals.ts`++```ts+import { WebBrowsingManifest, WebBrowsingPortal } from '@lobechat/builtin-tool-web-browsing/client';+import { type BuiltinPortal } from '@lobechat/types';++export const BuiltinToolsPortals: Record<string, BuiltinPortal> = {+ [WebBrowsingManifest.identifier]: WebBrowsingPortal as BuiltinPortal,+};+```++---++## 7. `client/components/` — Shared Subcomponents++Cross-cutting building blocks used by multiple surfaces live here, not duplicated in each surface folder.++Examples from `web-browsing/src/client/components/`:++- `CategoryAvatar.tsx` — search category icon+- `EngineAvatar.tsx` — search engine logo (used in Inspector chip + Render list + Portal header)+- `SearchBar.tsx` — editable query bar (used in Render and Portal)++Examples from `local-system/src/client/components/`:++- `FileItem.tsx` — single file row (used in ListFiles Render, SearchFiles Render, MoveLocalFiles Render)+- `FilePathDisplay.tsx` — path with truncation (used everywhere)++### Rules++- Live under `client/components/`, exported via `client/components/index.ts`.+- Re-export from `client/index.ts` only if other packages need them; otherwise keep internal.+- Keep them dumb — props in, JSX out, no store reads. The store reads belong in the surface that composes them.++---++## 8. `client/index.ts` — Package Public API++Re-exports everything the registries need plus useful types/manifest:++```ts+// Inspector — required+export { TaskInspectors } from './Inspector';++// Render — only if any API has one+export { TaskRenders, CreateTaskRender, RunTasksRender } from './Render';++// Placeholder / Streaming / Intervention — only if used+export { LocalSystemListFilesPlaceholder, LocalSystemSearchFilesPlaceholder } from './Placeholder';+export { LocalSystemStreamings } from './Streaming';+export { LocalSystemInterventions } from './Intervention';++// Portal — single export per tool+export { default as WebBrowsingPortal } from './Portal';++// Reusable components if other packages need them+export { CategoryAvatar, EngineAvatar, SearchBar } from './components';++// Re-export manifest, identifier, types for convenience+export { TaskManifest, TaskIdentifier } from '../manifest';+export * from '../types';+```++---++## 9. Diagnostic Quick-Lookup++| Symptom | Surface to check | | |+| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | --- | ------------------------- |+| No header at all on the tool call | Inspector missing from `client/Inspector/index.ts` registry | | |+| Header shows the API name but no chips | Inspector missing \`args?.X | | partialArgs?.X\` fallback |+| Header doesn't pulse during loading | Missing `shinyTextStyles.shinyText` on `isArgumentsStreaming \|\| isLoading` | | |+| Empty result card under header | Render returned `<div />` instead of `null` when no data | | |+| Layout jump when result arrives | Placeholder dimensions don't match Render dimensions | | |+| Approval dialog never appears | Manifest missing `humanIntervention`, or Intervention not in registry | | |+| Approval click doesn't wait for inline edit | Missing `registerBeforeApprove(id, flushFn)` | | |+| Portal opens but blank | Switch in `Portal/index.tsx` doesn't cover the apiName | | |+| Strings show as `builtins.lobe-foo.apiName.bar` | Missing i18n key in `src/locales/default/plugin.ts` (or not seeded in dev locale files) | | |+| Wrong color shade on `<Text type="secondary">` | `type='secondary'` is lighter than `colorTextSecondary` — pass via `style={{ color: cssVar.colorTextSecondary }}` | | |diff --git a/locales/ar/plugin.json b/locales/ar/plugin.jsonindex e77964cd26c..a50b6bfd4a8 100644--- a/locales/ar/plugin.json+++ b/locales/ar/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "إعادة تسمية المستند","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "استبدال محتوى المستند","builtins.lobe-agent-documents.apiName.updateLoadRule": "تحديث قاعدة التحميل",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} أحرف",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} مستندات",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} عمليات",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} عمليات",+ "builtins.lobe-agent-documents.inspector.target.agent": "في الوكيل",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "في الموضوع","builtins.lobe-agent-documents.title": "مستندات الوكيل","builtins.lobe-agent-management.apiName.callAgent": "وكيل الاتصال","builtins.lobe-agent-management.apiName.createAgent": "إنشاء وكيل",diff --git a/locales/bg-BG/plugin.json b/locales/bg-BG/plugin.jsonindex 2bf1cabeb0d..8b6dbba48da 100644--- a/locales/bg-BG/plugin.json+++ b/locales/bg-BG/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Преименуване на документ","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Замени съдържанието на документа","builtins.lobe-agent-documents.apiName.updateLoadRule": "Актуализиране на правило за зареждане",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} символа",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} документа",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} операции",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} операции",+ "builtins.lobe-agent-documents.inspector.target.agent": "в агент",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "в тема","builtins.lobe-agent-documents.title": "Документи на агент","builtins.lobe-agent-management.apiName.callAgent": "Обаждане на агент","builtins.lobe-agent-management.apiName.createAgent": "Създаване на агент",diff --git a/locales/de-DE/plugin.json b/locales/de-DE/plugin.jsonindex a06ac41298c..3f8a1c3a75f 100644--- a/locales/de-DE/plugin.json+++ b/locales/de-DE/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Dokument umbenennen","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Dokumentinhalt ersetzen","builtins.lobe-agent-documents.apiName.updateLoadRule": "Laderegel aktualisieren",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} Zeichen",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} Dokumente",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} Vorgänge",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} Vorgänge",+ "builtins.lobe-agent-documents.inspector.target.agent": "im Agenten",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "im Thema","builtins.lobe-agent-documents.title": "Agentendokumente","builtins.lobe-agent-management.apiName.callAgent": "Agent anrufen","builtins.lobe-agent-management.apiName.createAgent": "Agent erstellen",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex ddefbe149d8..0c455039fdc 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Rename document","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Replace document content","builtins.lobe-agent-documents.apiName.updateLoadRule": "Update load rule",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} chars",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} docs",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} ops",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} ops",+ "builtins.lobe-agent-documents.inspector.target.agent": "in agent",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "in topic","builtins.lobe-agent-documents.title": "Agent Documents","builtins.lobe-agent-management.apiName.callAgent": "Call agent","builtins.lobe-agent-management.apiName.createAgent": "Create agent",diff --git a/locales/es-ES/plugin.json b/locales/es-ES/plugin.jsonindex 70a11b42e25..241add0e94d 100644--- a/locales/es-ES/plugin.json+++ b/locales/es-ES/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Renombrar documento","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Reemplazar contenido del documento","builtins.lobe-agent-documents.apiName.updateLoadRule": "Actualizar regla de carga",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} caracteres",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} documentos",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} operaciones",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} operaciones",+ "builtins.lobe-agent-documents.inspector.target.agent": "en agente",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "en tema","builtins.lobe-agent-documents.title": "Documentos del Agente","builtins.lobe-agent-management.apiName.callAgent": "Agente de llamada","builtins.lobe-agent-management.apiName.createAgent": "Crear agente",diff --git a/locales/fa-IR/plugin.json b/locales/fa-IR/plugin.jsonindex be0db1dd503..a57cfc70ab6 100644--- a/locales/fa-IR/plugin.json+++ b/locales/fa-IR/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "تغییر نام سند","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "جایگزینی محتوای سند","builtins.lobe-agent-documents.apiName.updateLoadRule": "بهروزرسانی قانون بارگذاری",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} کاراکتر",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} سند",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} عملیات",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} عملیات",+ "builtins.lobe-agent-documents.inspector.target.agent": "در عامل",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "در موضوع","builtins.lobe-agent-documents.title": "اسناد عامل","builtins.lobe-agent-management.apiName.callAgent": "نماینده تماس","builtins.lobe-agent-management.apiName.createAgent": "ایجاد نماینده",diff --git a/locales/fr-FR/plugin.json b/locales/fr-FR/plugin.jsonindex 8bbe30112ce..0147347708d 100644--- a/locales/fr-FR/plugin.json+++ b/locales/fr-FR/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Renommer le document","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Remplacer le contenu du document","builtins.lobe-agent-documents.apiName.updateLoadRule": "Mettre à jour la règle de chargement",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} caractères",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} documents",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} opérations",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} opérations",+ "builtins.lobe-agent-documents.inspector.target.agent": "dans l'agent",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "dans le sujet","builtins.lobe-agent-documents.title": "Documents de l'agent","builtins.lobe-agent-management.apiName.callAgent": "Appeler un agent","builtins.lobe-agent-management.apiName.createAgent": "Créer un agent",diff --git a/locales/it-IT/plugin.json b/locales/it-IT/plugin.jsonindex 4d507e614fa..6a215f77802 100644--- a/locales/it-IT/plugin.json+++ b/locales/it-IT/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Rinomina documento","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Sostituisci contenuto del documento","builtins.lobe-agent-documents.apiName.updateLoadRule": "Aggiorna regola di caricamento",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} caratteri",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} documenti",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} operazioni",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} operazioni",+ "builtins.lobe-agent-documents.inspector.target.agent": "nell'agente",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "nell'argomento","builtins.lobe-agent-documents.title": "Documenti dell'agente","builtins.lobe-agent-management.apiName.callAgent": "Chiamare agente","builtins.lobe-agent-management.apiName.createAgent": "Creare agente",diff --git a/locales/ja-JP/plugin.json b/locales/ja-JP/plugin.jsonindex 1a6cdf55968..e08e9e993d0 100644--- a/locales/ja-JP/plugin.json+++ b/locales/ja-JP/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "文書の名前を変更","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "ドキュメント内容を置き換え","builtins.lobe-agent-documents.apiName.updateLoadRule": "ロードルールを更新",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} 文字",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} ドキュメント",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} 操作",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} 操作",+ "builtins.lobe-agent-documents.inspector.target.agent": "エージェント内",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "トピック内","builtins.lobe-agent-documents.title": "エージェント文書","builtins.lobe-agent-management.apiName.callAgent": "エージェントを呼び出す","builtins.lobe-agent-management.apiName.createAgent": "エージェントを作成する",diff --git a/locales/ko-KR/plugin.json b/locales/ko-KR/plugin.jsonindex ec7d542c22c..dadecae77d1 100644--- a/locales/ko-KR/plugin.json+++ b/locales/ko-KR/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "문서 이름 변경","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "문서 내용 교체","builtins.lobe-agent-documents.apiName.updateLoadRule": "로드 규칙 업데이트",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} 문자",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} 문서",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} 작업",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} 작업",+ "builtins.lobe-agent-documents.inspector.target.agent": "에이전트에서",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "주제에서","builtins.lobe-agent-documents.title": "에이전트 문서","builtins.lobe-agent-management.apiName.callAgent": "통화 에이전트","builtins.lobe-agent-management.apiName.createAgent": "에이전트 생성",diff --git a/locales/nl-NL/plugin.json b/locales/nl-NL/plugin.jsonindex 2f3c2a99b63..f3a5be49346 100644--- a/locales/nl-NL/plugin.json+++ b/locales/nl-NL/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Document hernoemen","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Documentinhoud vervangen","builtins.lobe-agent-documents.apiName.updateLoadRule": "Laadregel bijwerken",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} tekens",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} documenten",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} bewerkingen",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} bewerkingen",+ "builtins.lobe-agent-documents.inspector.target.agent": "in agent",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "in onderwerp","builtins.lobe-agent-documents.title": "Agentdocumenten","builtins.lobe-agent-management.apiName.callAgent": "Bel agent","builtins.lobe-agent-management.apiName.createAgent": "Maak agent aan",diff --git a/locales/pl-PL/plugin.json b/locales/pl-PL/plugin.jsonindex 588f7d1138b..8e05aee4841 100644--- a/locales/pl-PL/plugin.json+++ b/locales/pl-PL/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Zmień nazwę dokumentu","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Zastąp zawartość dokumentu","builtins.lobe-agent-documents.apiName.updateLoadRule": "Zaktualizuj regułę ładowania",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} znaków",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} dokumentów",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} operacji",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} operacji",+ "builtins.lobe-agent-documents.inspector.target.agent": "w agencie",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "w temacie","builtins.lobe-agent-documents.title": "Dokumenty agenta","builtins.lobe-agent-management.apiName.callAgent": "Zadzwoń do agenta","builtins.lobe-agent-management.apiName.createAgent": "Utwórz agenta",diff --git a/locales/pt-BR/plugin.json b/locales/pt-BR/plugin.jsonindex ac33f1f1f98..be4af250e4e 100644--- a/locales/pt-BR/plugin.json+++ b/locales/pt-BR/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Renomear documento","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Substituir conteúdo do documento","builtins.lobe-agent-documents.apiName.updateLoadRule": "Atualizar regra de carregamento",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} caracteres",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} documentos",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} operações",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} operações",+ "builtins.lobe-agent-documents.inspector.target.agent": "no agente",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "no tópico","builtins.lobe-agent-documents.title": "Documentos do Agente","builtins.lobe-agent-management.apiName.callAgent": "Agente de chamada","builtins.lobe-agent-management.apiName.createAgent": "Criar agente",diff --git a/locales/ru-RU/plugin.json b/locales/ru-RU/plugin.jsonindex d98e459932f..28dd37d9914 100644--- a/locales/ru-RU/plugin.json+++ b/locales/ru-RU/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Переименовать документ","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Заменить содержимое документа","builtins.lobe-agent-documents.apiName.updateLoadRule": "Обновить правило загрузки",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} символов",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} документов",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} операций",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} операций",+ "builtins.lobe-agent-documents.inspector.target.agent": "в агенте",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "в теме","builtins.lobe-agent-documents.title": "Документы агента","builtins.lobe-agent-management.apiName.callAgent": "Вызвать агента","builtins.lobe-agent-management.apiName.createAgent": "Создать агента",diff --git a/locales/tr-TR/plugin.json b/locales/tr-TR/plugin.jsonindex 87d3c601b77..2dba0c4675c 100644--- a/locales/tr-TR/plugin.json+++ b/locales/tr-TR/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Belgeyi yeniden adlandır","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Belge içeriğini değiştir","builtins.lobe-agent-documents.apiName.updateLoadRule": "Yükleme kuralını güncelle",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} karakter",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} belge",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} işlem",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} işlem",+ "builtins.lobe-agent-documents.inspector.target.agent": "ajan içinde",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "konu içinde","builtins.lobe-agent-documents.title": "Aracı Belgeleri","builtins.lobe-agent-management.apiName.callAgent": "Çağrı temsilcisi","builtins.lobe-agent-management.apiName.createAgent": "Temsilci oluştur",diff --git a/locales/vi-VN/plugin.json b/locales/vi-VN/plugin.jsonindex d8d43ddf69d..b06e13c4256 100644--- a/locales/vi-VN/plugin.json+++ b/locales/vi-VN/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "Đổi tên tài liệu","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Thay thế nội dung tài liệu","builtins.lobe-agent-documents.apiName.updateLoadRule": "Cập nhật quy tắc tải",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} ký tự",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} tài liệu",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} thao tác",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} thao tác",+ "builtins.lobe-agent-documents.inspector.target.agent": "trong tác nhân",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "trong chủ đề","builtins.lobe-agent-documents.title": "Tài liệu của Agent","builtins.lobe-agent-management.apiName.callAgent": "Gọi đại lý","builtins.lobe-agent-management.apiName.createAgent": "Tạo đại lý",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 1f0306bf712..3da2c38a286 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "重命名文档","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "替换文档内容","builtins.lobe-agent-documents.apiName.updateLoadRule": "更新加载规则",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} 字",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} 篇",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} 项操作",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} 项",+ "builtins.lobe-agent-documents.inspector.target.agent": "Agent 范围",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "当前话题","builtins.lobe-agent-documents.title": "Agent 文档","builtins.lobe-agent-management.apiName.callAgent": "呼叫代理","builtins.lobe-agent-management.apiName.createAgent": "创建代理",diff --git a/locales/zh-TW/plugin.json b/locales/zh-TW/plugin.jsonindex 53012511aa9..cd44c3a3dc3 100644--- a/locales/zh-TW/plugin.json+++ b/locales/zh-TW/plugin.json@@ -35,6 +35,12 @@"builtins.lobe-agent-documents.apiName.renameDocument": "重新命名文件","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "替換文件內容","builtins.lobe-agent-documents.apiName.updateLoadRule": "更新載入規則",+ "builtins.lobe-agent-documents.inspector.chars": "{{count}} 字元",+ "builtins.lobe-agent-documents.inspector.docCount": "{{count}} 文件",+ "builtins.lobe-agent-documents.inspector.opsCount": "{{count}} 操作",+ "builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} 操作",+ "builtins.lobe-agent-documents.inspector.target.agent": "在代理中",+ "builtins.lobe-agent-documents.inspector.target.currentTopic": "在主題中","builtins.lobe-agent-documents.title": "代理文件","builtins.lobe-agent-management.apiName.callAgent": "呼叫代理","builtins.lobe-agent-management.apiName.createAgent": "建立代理",diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/CopyDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/CopyDocument/index.tsxindex 575ace85fc6..c0d5f3e6a36 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/CopyDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/CopyDocument/index.tsx@@ -5,17 +5,21 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { CopyDocumentArgs, CopyDocumentState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const CopyDocumentInspector = memo<BuiltinInspectorProps<CopyDocumentArgs, CopyDocumentState>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');- const summary = args?.newTitle || partialArgs?.newTitle || args?.id || partialArgs?.id;- if (isArgumentsStreaming && !summary) {+ const id = args?.id || partialArgs?.id;+ const newTitle = args?.newTitle || partialArgs?.newTitle;+ const styles = inspectorChipStyles;++ if (isArgumentsStreaming && !id && !newTitle) {return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-agent-documents.apiName.copyDocument')}</span>@@ -25,13 +29,20 @@ export const CopyDocumentInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.copyDocument')}: </span>- {summary && <span className={highlightTextStyles.primary}>{summary}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.copyDocument')}</span>+ {id && <span className={styles.idChip}>{formatDocumentId(id)}</span>}+ {newTitle && (+ <>+ <span className={styles.separator}>→</span>+ <span className={styles.chip}>{newTitle}</span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/CreateDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/CreateDocument/index.tsxindex acdefccfd89..c019b0c8a28 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/CreateDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/CreateDocument/index.tsx@@ -5,15 +5,19 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { CreateDocumentArgs, CreateDocumentState } from '../../../types';+import { inspectorChipStyles } from '../_styles';export const CreateDocumentInspector = memo<BuiltinInspectorProps<CreateDocumentArgs, CreateDocumentState>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');+const title = args?.title || partialArgs?.title;+ const target = args?.target || partialArgs?.target;+ const styles = inspectorChipStyles;if (isArgumentsStreaming && !title) {return (@@ -25,13 +29,22 @@ export const CreateDocumentInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.createDocument')}: </span>- {title && <span className={highlightTextStyles.primary}>{title}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.createDocument')}</span>+ {title && <span className={styles.chip}>{title}</span>}+ {target && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>+ {t(`builtins.lobe-agent-documents.inspector.target.${target}` as const)}+ </span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsxindex 18cc764ab8b..a968e665105 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx@@ -8,20 +8,42 @@ import { useTranslation } from 'react-i18next';import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ListDocumentsArgs, ListDocumentsState } from '../../../types';+import { inspectorChipStyles } from '../_styles';export const ListDocumentsInspector = memo<BuiltinInspectorProps<ListDocumentsArgs, ListDocumentsState>->(({ isArgumentsStreaming, isLoading }) => {+>(({ args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');+ const target = args?.target || partialArgs?.target;+ const count = pluginState?.documents?.length;+ const styles = inspectorChipStyles;+return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}><span>{t('builtins.lobe-agent-documents.apiName.listDocuments')}</span>+ {target && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>+ {t(`builtins.lobe-agent-documents.inspector.target.${target}` as const)}+ </span>+ </>+ )}+ {typeof count === 'number' && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>+ {t('builtins.lobe-agent-documents.inspector.docCount', { count })}+ </span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsxindex a61f605f503..390940bc1e2 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx@@ -5,15 +5,22 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ModifyDocumentNodesArgs, ModifyDocumentNodesState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const ModifyNodesInspector = memo<BuiltinInspectorProps<ModifyDocumentNodesArgs, ModifyDocumentNodesState>->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+>(({ args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');+const id = args?.id || partialArgs?.id;+ const operations = args?.operations || partialArgs?.operations;+ const opCount = operations?.length ?? 0;+ const successCount = pluginState?.successCount;+ const totalCount = pluginState?.totalCount;+ const styles = inspectorChipStyles;if (isArgumentsStreaming && !id) {return (@@ -25,13 +32,27 @@ export const ModifyNodesInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.modifyNodes')}: </span>- {id && <span className={highlightTextStyles.primary}>{id}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.modifyNodes')}</span>+ {id && <span className={styles.idChip}>{formatDocumentId(id)}</span>}+ {(typeof totalCount === 'number' || opCount > 0) && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>+ {typeof successCount === 'number' && typeof totalCount === 'number'+ ? t('builtins.lobe-agent-documents.inspector.opsResult', {+ success: successCount,+ total: totalCount,+ })+ : t('builtins.lobe-agent-documents.inspector.opsCount', { count: opCount })}+ </span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/ReadDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ReadDocument/index.tsxindex e5cd023caa9..b6d66cd9d40 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/ReadDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ReadDocument/index.tsx@@ -5,17 +5,21 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ReadDocumentArgs, ReadDocumentState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const ReadDocumentInspector = memo<BuiltinInspectorProps<ReadDocumentArgs, ReadDocumentState>>(({ args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');- const summary = pluginState?.title || args?.id || partialArgs?.id;- if (isArgumentsStreaming && !summary) {+ const id = args?.id || partialArgs?.id;+ const title = pluginState?.title;+ const styles = inspectorChipStyles;++ if (isArgumentsStreaming && !title && !id) {return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-agent-documents.apiName.readDocument')}</span>@@ -25,13 +29,18 @@ export const ReadDocumentInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.readDocument')}: </span>- {summary && <span className={highlightTextStyles.primary}>{summary}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.readDocument')}</span>+ {title ? (+ <span className={styles.chip}>{title}</span>+ ) : (+ id && <span className={styles.idChip}>{formatDocumentId(id)}</span>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsxindex a6036dae8d5..d42eadf1151 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/RemoveDocument/index.tsx@@ -1,37 +1,52 @@'use client';import type { BuiltinInspectorProps } from '@lobechat/types';-import { cx } from 'antd-style';+import { createStaticStyles, cssVar, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { RemoveDocumentArgs, RemoveDocumentState } from '../../../types';+import { formatDocumentId } from '../_styles';++const styles = createStaticStyles(({ css, cssVar }) => ({+ removeChip: css`+ flex-shrink: 0;++ padding-block: 2px;+ padding-inline: 8px;+ border: 1px dashed ${cssVar.colorErrorBorder};+ border-radius: 999px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorError};+ text-decoration: line-through;++ background: transparent;+ `,+}));export const RemoveDocumentInspector = memo<BuiltinInspectorProps<RemoveDocumentArgs, RemoveDocumentState>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');- const id = args?.id || partialArgs?.id;- if (isArgumentsStreaming && !id) {- return (- <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>- <span>{t('builtins.lobe-agent-documents.apiName.removeDocument')}</span>- </div>- );- }+ const id = args?.id || partialArgs?.id;return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.removeDocument')}: </span>- {id && <span className={highlightTextStyles.primary}>{id}</span>}+ <span style={{ color: cssVar.colorError }}>+ {t('builtins.lobe-agent-documents.apiName.removeDocument')}+ </span>+ {id && <span className={styles.removeChip}>{formatDocumentId(id)}</span>}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/RenameDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/RenameDocument/index.tsxindex 932c1370d1a..89adfa3345d 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/RenameDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/RenameDocument/index.tsx@@ -5,17 +5,21 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { RenameDocumentArgs, RenameDocumentState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const RenameDocumentInspector = memo<BuiltinInspectorProps<RenameDocumentArgs, RenameDocumentState>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');++ const id = args?.id || partialArgs?.id;const newTitle = args?.newTitle || partialArgs?.newTitle;+ const styles = inspectorChipStyles;- if (isArgumentsStreaming && !newTitle) {+ if (isArgumentsStreaming && !id && !newTitle) {return (<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}><span>{t('builtins.lobe-agent-documents.apiName.renameDocument')}</span>@@ -25,13 +29,20 @@ export const RenameDocumentInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.renameDocument')}: </span>- {newTitle && <span className={highlightTextStyles.primary}>{newTitle}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.renameDocument')}</span>+ {id && <span className={styles.idChip}>{formatDocumentId(id)}</span>}+ {newTitle && (+ <>+ <span className={styles.separator}>→</span>+ <span className={styles.chip}>{newTitle}</span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/ReplaceDocumentContent/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ReplaceDocumentContent/index.tsxindex 0ed0dde67b1..19ae9e5e14b 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/ReplaceDocumentContent/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ReplaceDocumentContent/index.tsx@@ -5,15 +5,19 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { ReplaceDocumentContentArgs, ReplaceDocumentContentState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const ReplaceDocumentContentInspector = memo<BuiltinInspectorProps<ReplaceDocumentContentArgs, ReplaceDocumentContentState>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');+const id = args?.id || partialArgs?.id;+ const content = args?.content || partialArgs?.content;+ const styles = inspectorChipStyles;if (isArgumentsStreaming && !id) {return (@@ -25,13 +29,22 @@ export const ReplaceDocumentContentInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.replaceDocumentContent')}: </span>- {id && <span className={highlightTextStyles.primary}>{id}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.replaceDocumentContent')}</span>+ {id && <span className={styles.idChip}>{formatDocumentId(id)}</span>}+ {typeof content === 'string' && content.length > 0 && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>+ {t('builtins.lobe-agent-documents.inspector.chars', { count: content.length })}+ </span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/UpdateLoadRule/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/UpdateLoadRule/index.tsxindex 76cb27cce4b..4930c7a672f 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/UpdateLoadRule/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/UpdateLoadRule/index.tsx@@ -5,15 +5,19 @@ import { cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';+import { inspectorTextStyles, shinyTextStyles } from '@/styles';import type { UpdateLoadRuleArgs, UpdateLoadRuleState } from '../../../types';+import { formatDocumentId, inspectorChipStyles } from '../_styles';export const UpdateLoadRuleInspector = memo<BuiltinInspectorProps<UpdateLoadRuleArgs, UpdateLoadRuleState>->(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+>(({ args, partialArgs, pluginState, isArgumentsStreaming, isLoading }) => {const { t } = useTranslation('plugin');+const id = args?.id || partialArgs?.id;+ const ruleType = args?.rule?.rule || partialArgs?.rule?.rule || pluginState?.rule?.rule;+ const styles = inspectorChipStyles;if (isArgumentsStreaming && !id) {return (@@ -25,13 +29,20 @@ export const UpdateLoadRuleInspector = memo<return (<div+ style={{ flexWrap: 'wrap', gap: 4 }}className={cx(inspectorTextStyles.root,(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,)}>- <span>{t('builtins.lobe-agent-documents.apiName.updateLoadRule')}: </span>- {id && <span className={highlightTextStyles.primary}>{id}</span>}+ <span>{t('builtins.lobe-agent-documents.apiName.updateLoadRule')}</span>+ {id && <span className={styles.idChip}>{formatDocumentId(id)}</span>}+ {ruleType && (+ <>+ <span className={styles.separator}>·</span>+ <span className={styles.subdued}>{ruleType}</span>+ </>+ )}</div>);});diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/_styles.ts b/packages/builtin-tool-agent-documents/src/client/Inspector/_styles.tsnew file mode 100644index 00000000000..b6a5616a2ec--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/_styles.ts@@ -0,0 +1,69 @@+import { createStaticStyles } from 'antd-style';++/**+ * Shared chip styles used by every Agent Documents inspector.+ *+ * Inlining these in each inspector means changing the visual language+ * touches 9 files; keeping one source of truth keeps the toolset coherent+ * (e.g. the doc-id chip should look the same whether you Read or Rename).+ */+export const inspectorChipStyles = createStaticStyles(({ css, cssVar }) => ({+ /** Highlighted chip for the primary subject (title, new title, etc.) */+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ max-width: 280px;+ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillTertiary};+ `,+ /** Compact, code-styled chip for raw identifiers */+ idChip: css`+ flex-shrink: 0;++ padding-block: 2px;+ padding-inline: 8px;+ border-radius: 999px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ /** Inline middot used between segments */+ separator: css`+ flex-shrink: 0;+ color: ${cssVar.colorTextQuaternary};+ `,+ /** Secondary, lower-contrast chip for metadata (counts, target scope, …) */+ subdued: css`+ flex-shrink: 0;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++const UUID_LIKE = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;++/**+ * Render a friendly short label for a document id. Full UUIDs are noisy in a+ * one-line header; their first 8 chars are unique enough for cross-referencing+ * within a single conversation. Prefixed ids (e.g. `agd_…`) are left intact —+ * they're already short and meaningful.+ */+export const formatDocumentId = (id?: string): string | undefined => {+ if (!id) return undefined;+ return UUID_LIKE.test(id) ? id.slice(0, 8) : id;+};diff --git a/packages/builtin-tools/src/inspectors.ts b/packages/builtin-tools/src/inspectors.tsindex fc21858694b..aced806aa29 100644--- a/packages/builtin-tools/src/inspectors.ts+++ b/packages/builtin-tools/src/inspectors.ts@@ -6,6 +6,10 @@ import {AgentBuilderInspectors,AgentBuilderManifest,} from '@lobechat/builtin-tool-agent-builder/client';+import {+ AgentDocumentsInspectors,+ AgentDocumentsManifest,+} from '@lobechat/builtin-tool-agent-documents/client';import {AgentManagementInspectors,AgentManagementManifest,@@ -62,6 +66,7 @@ import { CodexInspectors } from './codex';*/const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> = {[AgentBuilderManifest.identifier]: AgentBuilderInspectors as Record<string, BuiltinInspector>,+ [AgentDocumentsManifest.identifier]: AgentDocumentsInspectors as Record<string, BuiltinInspector>,[AgentManagementManifest.identifier]: AgentManagementInspectors as Record<string,BuiltinInspectordiff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 6d978f69cbe..d9469ceba7b 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -162,6 +162,12 @@ export default {'builtins.lobe-agent-documents.apiName.renameDocument': 'Rename document','builtins.lobe-agent-documents.apiName.replaceDocumentContent': 'Replace document content','builtins.lobe-agent-documents.apiName.updateLoadRule': 'Update load rule',+ 'builtins.lobe-agent-documents.inspector.chars': '{{count}} chars',+ 'builtins.lobe-agent-documents.inspector.docCount': '{{count}} docs',+ 'builtins.lobe-agent-documents.inspector.opsCount': '{{count}} ops',+ 'builtins.lobe-agent-documents.inspector.opsResult': '{{success}}/{{total}} ops',+ 'builtins.lobe-agent-documents.inspector.target.agent': 'in agent',+ 'builtins.lobe-agent-documents.inspector.target.currentTopic': 'in topic','builtins.lobe-agent-documents.title': 'Agent Documents','builtins.lobe-notebook.actions.collapse': 'Collapse','builtins.lobe-notebook.actions.copy': 'Copy',