Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: gate device-only builtin skills on execution plan + dynamic-page scraping guidance (#16722)

YuTengjinge9e3ef5f37f9
diff --git a/.agents/scripts/check/autofix.ts b/.agents/scripts/check/autofix.ts
new file mode 100644
index 00000000000..960136fab27
--- /dev/null
+++ b/.agents/scripts/check/autofix.ts
@@ -0,0 +1,87 @@
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { run } from './exec';
+import { rootDir } from './paths';
+import type { FileDiff } from './types';
+
+/** Max diff lines per file printed to stdout; longer diffs go to the temp file only. */
+export const STDOUT_DIFF_LINE_LIMIT = 50;
+
+/** Count added/removed lines in a unified diff body. */
+export const diffStat = (diff: string): { added: number; removed: number } => {
+ let added = 0;
+ let removed = 0;
+ for (const line of diff.split('\n')) {
+ if (line.startsWith('+') && !line.startsWith('+++')) added += 1;
+ else if (line.startsWith('-') && !line.startsWith('---')) removed += 1;
+ }
+ return { added, removed };
+};
+
+/** Render per-file diffs for stdout, truncating any diff beyond the line limit. */
+export const renderDiffsForStdout = (diffs: FileDiff[], limit = STDOUT_DIFF_LINE_LIMIT): string =>
+ diffs
+ .map(({ added, diff, file, removed }) => {
+ const lines = diff.split('\n').filter(Boolean);
+ return lines.length > limit
+ ? `${file}\n (diff ${lines.length} lines > ${limit}, truncated β€” see full diff file) +${added} -${removed}`
+ : `${file}\n${lines.join('\n')}`;
+ })
+ .join('\n\n');
+
+/** Snapshot current file contents (missing files are skipped) to diff against after autofix. */
+export const snapshot = async (files: string[]): Promise<Map<string, string>> => {
+ const entries = await Promise.all(
+ files.map(async (file): Promise<[string, string] | null> => {
+ try {
+ return [file, await readFile(path.join(rootDir(), file), 'utf8')];
+ } catch {
+ return null;
+ }
+ }),
+ );
+ const map = new Map<string, string>();
+ for (const entry of entries) if (entry) map.set(entry[0], entry[1]);
+ return map;
+};
+
+/**
+ * Diff each snapshotted file against its post-autofix content via the system
+ * `diff` (git diff would mix in the agent's own uncommitted edits).
+ */
+export const collectAutofixDiffs = async (before: Map<string, string>): Promise<FileDiff[]> => {
+ const diffs: FileDiff[] = [];
+ const scratchDir = await mkdtemp(path.join(tmpdir(), 'check-orig-'));
+
+ for (const [file, original] of before) {
+ const abs = path.join(rootDir(), file);
+ let current: string;
+ try {
+ current = await readFile(abs, 'utf8');
+ } catch {
+ continue;
+ }
+ if (current === original) continue;
+
+ const origCopy = path.join(scratchDir, path.basename(file));
+ await writeFile(origCopy, original);
+ const result = await run(
+ 'diff',
+ ['-u', '-L', `a/${file}`, '-L', `b/${file}`, origCopy, abs],
+ rootDir(),
+ );
+ const { added, removed } = diffStat(result.stdout);
+ diffs.push({ added, diff: result.stdout.trim(), file, removed });
+ }
+
+ return diffs;
+};
+
+/** Write the untruncated combined diff to a temp file and return its path. */
+export const writeFullDiff = async (diffs: FileDiff[]): Promise<string> => {
+ const diffFile = path.join(tmpdir(), `check-autofix-${Date.now()}.diff`);
+ await writeFile(diffFile, diffs.map((entry) => entry.diff).join('\n\n') + '\n');
+ return diffFile;
+};
diff --git a/.agents/scripts/check/check.test.ts b/.agents/scripts/check/check.test.ts
new file mode 100644
index 00000000000..553fa874d3e
--- /dev/null
+++ b/.agents/scripts/check/check.test.ts
@@ -0,0 +1,218 @@
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+import { diffStat, renderDiffsForStdout } from './autofix';
+import { hostRootFromGitdir } from './delegate';
+import { lobehubPipelines } from './pipelines';
+import {
+ findVitestConfigDir,
+ isTestFile,
+ pipelineFor,
+ relatedTestCandidates,
+ resolveMount,
+ stylelintApplies,
+} from './routing';
+import type { RepoMount } from './types';
+import { compactVitestOutput } from './vitest';
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+
+describe('resolveMount', () => {
+ const root: RepoMount = { dir: '', pipelines: lobehubPipelines };
+ const sub: RepoMount = { dir: 'vendor/sub', pipelines: [] };
+ const repos = [root, sub];
+
+ it('routes mount-prefixed paths to the mount with a mount-relative subPath', () => {
+ expect(resolveMount(repos, 'vendor/sub/src/utils/uuid.ts')).toEqual({
+ mount: sub,
+ subPath: 'src/utils/uuid.ts',
+ });
+ });
+
+ it('routes everything else to the root mount', () => {
+ expect(resolveMount(repos, 'src/auth.ts')).toEqual({ mount: root, subPath: 'src/auth.ts' });
+ // A root path that merely starts with the same letters is not the mount
+ expect(resolveMount(repos, 'vendor/sub-tools/a.ts').mount).toBe(root);
+ });
+
+ it('prefers the longest matching mount dir', () => {
+ const nested: RepoMount = { dir: 'vendor/sub/nested', pipelines: [] };
+ expect(resolveMount([root, sub, nested], 'vendor/sub/nested/a.ts').mount).toBe(nested);
+ });
+});
+
+describe('pipelineFor', () => {
+ it('maps ts/tsx to the stylelint+eslint+prettier pipeline', () => {
+ const pipeline = pipelineFor(lobehubPipelines, 'src/auth.ts');
+ expect(pipeline?.tools.map(([tool]) => tool)).toEqual(['stylelint', 'eslint', 'prettier']);
+ });
+
+ it('maps md to remark+prettier and json to prettier only', () => {
+ expect(pipelineFor(lobehubPipelines, 'AGENTS.md')?.tools.map(([tool]) => tool)).toEqual([
+ 'remark',
+ 'prettier',
+ ]);
+ expect(pipelineFor(lobehubPipelines, 'package.json')?.tools.map(([tool]) => tool)).toEqual([
+ 'prettier',
+ ]);
+ });
+
+ it('returns null for extensions with no pipeline', () => {
+ expect(pipelineFor(lobehubPipelines, '.github/workflows/ci.yml')).not.toBeNull();
+ expect(pipelineFor(lobehubPipelines, 'image.png')).toBeNull();
+ expect(pipelineFor([], 'a.ts')).toBeNull();
+ });
+});
+
+describe('lobehubPipelines drift', () => {
+ /**
+ * Guards the handwritten mirror in pipelines.ts against drifting from the
+ * real lint-staged config in package.json. Compares tool-name sequences
+ * only β€” flags legitimately differ (e.g. `--parser=typescript`,
+ * `--no-error-on-unmatched-pattern`).
+ */
+ const globExts = (glob: string): string[] => {
+ const match = glob.match(/^\*\.(?:\{([^}]+)\}|(\w+))$/);
+ if (!match) throw new Error(`unrecognized lint-staged glob: ${glob}`);
+ return (match[1]?.split(',') ?? [match[2]]).map((ext) => `.${ext}`);
+ };
+
+ it('mirrors the lint-staged config', async () => {
+ const pkg = JSON.parse(await readFile(path.join(repoRoot, 'package.json'), 'utf8')) as {
+ 'lint-staged': Record<string, string[]>;
+ };
+ const entries = Object.entries(pkg['lint-staged']);
+ expect(entries.length).toBeGreaterThan(0);
+
+ for (const [glob, commands] of entries) {
+ const expected = commands.map((command) => command.split(' ')[0]);
+ for (const ext of globExts(glob)) {
+ expect(
+ pipelineFor(lobehubPipelines, `sample${ext}`)?.tools.map(([tool]) => tool),
+ `lint-staged "${glob}" (${ext})`,
+ ).toEqual(expected);
+ }
+ }
+ });
+});
+
+describe('stylelintApplies', () => {
+ it('scopes stylelint to src/tests like the lint:style scripts', () => {
+ expect(stylelintApplies('src/auth.ts')).toBe(true);
+ expect(stylelintApplies('tests/foo.ts')).toBe(true);
+ // stylelint's CSS-in-JS fixer corrupts files outside its configured scope
+ expect(stylelintApplies('.agents/scripts/check/index.ts')).toBe(false);
+ expect(stylelintApplies('packages/utils/src/a.ts')).toBe(false);
+ });
+});
+
+describe('relatedTestCandidates', () => {
+ it('returns the file itself when it is already a test', () => {
+ expect(isTestFile('src/auth.test.ts')).toBe(true);
+ expect(relatedTestCandidates('src/auth.test.ts')).toEqual(['src/auth.test.ts']);
+ });
+
+ it('lists sibling and __tests__ candidates for source files', () => {
+ expect(relatedTestCandidates('src/auth.ts')).toEqual([
+ 'src/auth.test.ts',
+ 'src/__tests__/auth.test.ts',
+ 'src/auth.test.tsx',
+ 'src/__tests__/auth.test.tsx',
+ 'src/auth.test.mts',
+ 'src/__tests__/auth.test.mts',
+ ]);
+ });
+
+ it('returns nothing for non-source files', () => {
+ expect(relatedTestCandidates('AGENTS.md')).toEqual([]);
+ expect(relatedTestCandidates('image.png')).toEqual([]);
+ });
+});
+
+describe('findVitestConfigDir', () => {
+ const configs = new Set([
+ 'vitest.config.mts',
+ 'vendor/sub/vitest.config.mts',
+ 'vendor/sub/packages/utils/vitest.config.mts',
+ ]);
+ const exists = async (candidate: string) => configs.has(candidate);
+
+ it('picks the nearest config walking up from the test file', async () => {
+ await expect(
+ findVitestConfigDir('vendor/sub/packages/utils/src/apiKey.test.ts', exists),
+ ).resolves.toBe('vendor/sub/packages/utils');
+ await expect(findVitestConfigDir('vendor/sub/src/utils/uuid.test.ts', exists)).resolves.toBe(
+ 'vendor/sub',
+ );
+ await expect(findVitestConfigDir('src/auth.test.ts', exists)).resolves.toBe('.');
+ });
+
+ it('falls back to the repo root when no config is found', async () => {
+ await expect(
+ findVitestConfigDir('somewhere/deep/file.test.ts', async () => false),
+ ).resolves.toBe('.');
+ });
+});
+
+describe('hostRootFromGitdir', () => {
+ it('extracts the superproject root from a submodule gitdir', () => {
+ expect(hostRootFromGitdir('/work/host/.git/modules/vendor/sub')).toBe('/work/host');
+ });
+
+ it('returns null for standalone clones and linked worktrees', () => {
+ expect(hostRootFromGitdir('/work/repo/.git')).toBeNull();
+ expect(hostRootFromGitdir('/work/repo/.git/worktrees/feature')).toBeNull();
+ });
+});
+
+describe('diffStat', () => {
+ it('counts added/removed lines, ignoring file headers', () => {
+ const diff = ['--- a/f', '+++ b/f', '@@ -1,2 +1,2 @@', '-old', '+new', '+extra'].join('\n');
+ expect(diffStat(diff)).toEqual({ added: 2, removed: 1 });
+ });
+});
+
+describe('renderDiffsForStdout', () => {
+ it('prints short diffs in full and truncates long ones to a stat line', () => {
+ const shortDiff = { added: 1, diff: '--- a/f\n+++ b/f\n+new', file: 'f.ts', removed: 0 };
+ const longDiff = {
+ added: 30,
+ diff: Array.from({ length: 40 }, (_, index) => `+line${index}`).join('\n'),
+ file: 'g.ts',
+ removed: 10,
+ };
+ const output = renderDiffsForStdout([shortDiff, longDiff], 10);
+ expect(output).toContain('+new');
+ expect(output).toContain('g.ts\n (diff 40 lines > 10, truncated');
+ expect(output).toContain('+30 -10');
+ expect(output).not.toContain('+line5');
+ });
+});
+
+describe('compactVitestOutput', () => {
+ it('keeps only the failed-tests detail section without banners', () => {
+ const raw = [
+ ' RUN v3.2.4 /repo',
+ '',
+ ' ❯ src/a.test.ts (1 test | 1 failed) 3ms',
+ ' Start at 19:13:49',
+ ' Duration 193ms',
+ '',
+ '⎯⎯⎯ Failed Tests 1 ⎯⎯⎯',
+ '',
+ ' FAIL src/a.test.ts > fails',
+ 'AssertionError: expected 1 to be 2',
+ '⎯⎯⎯⎯⎯⎯[1/1]⎯',
+ ].join('\n');
+ const compact = compactVitestOutput(raw);
+ expect(compact).toBe('FAIL src/a.test.ts > fails\nAssertionError: expected 1 to be 2');
+ });
+
+ it('falls back to filtering noise when no failed-tests section exists', () => {
+ const raw = [' RUN v3.2.4 /repo', 'Error: config not found', ' Duration 1ms'].join('\n');
+ expect(compactVitestOutput(raw)).toBe('Error: config not found');
+ });
+});
diff --git a/.agents/scripts/check/cli.ts b/.agents/scripts/check/cli.ts
new file mode 100644
index 00000000000..ac8f0bf90e0
--- /dev/null
+++ b/.agents/scripts/check/cli.ts
@@ -0,0 +1,37 @@
+/**
+ * Standalone entry for this repo: `bun run check` routes every file through
+ * this repo's own pipelines. When this repo is checked out as a submodule of
+ * a superproject that ships its own `check` script, the run is delegated to
+ * that entry instead (see `delegate.ts`), so the unified host behavior
+ * applies no matter which directory the command is invoked from.
+ */
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { detectHostCheckRoot } from './delegate';
+import { runCli } from './index';
+import { lobehubPipelines } from './pipelines';
+
+const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+
+const main = async () => {
+ const hostRoot = await detectHostCheckRoot(rootDir);
+ if (hostRoot) {
+ console.log(`β†’ submodule checkout: delegating to the superproject check (${hostRoot})`);
+ // Absolute file args survive the cwd change; flags pass through untouched.
+ const args = process.argv
+ .slice(2)
+ .map((arg) => (arg.startsWith('--') ? arg : path.resolve(process.cwd(), arg)));
+ const child = spawn('bun', ['run', 'check', ...args], { cwd: hostRoot, stdio: 'inherit' });
+ child.on('close', (code) => process.exit(code ?? 1));
+ return;
+ }
+
+ await runCli({ repos: [{ dir: '', pipelines: lobehubPipelines }], rootDir });
+};
+
+main().catch((error) => {
+ console.error(`βœ— check crashed: ${error?.stack ?? error}`);
+ process.exit(2);
+});
diff --git a/.agents/scripts/check/collect.ts b/.agents/scripts/check/collect.ts
new file mode 100644
index 00000000000..a238e23dfd0
--- /dev/null
+++ b/.agents/scripts/check/collect.ts
@@ -0,0 +1,50 @@
+import path from 'node:path';
+
+import { git } from './exec';
+import { getConfig, mountDir } from './paths';
+import type { RepoMount } from './types';
+
+const prefixed = (mount: RepoMount, files: string[]) =>
+ mount.dir === '' ? files : files.map((file) => `${mount.dir}/${file}`);
+
+/**
+ * Changed files across the host repo and all mounted sub-repos, root-relative.
+ * Default scope is the whole working tree vs HEAD (staged + unstaged +
+ * untracked) so an agent's freshest edits are never skipped just because
+ * something else is staged; `stagedOnly` narrows to the pre-commit scope.
+ */
+export const collectFromGit = async (stagedOnly = false): Promise<string[]> => {
+ const { repos } = getConfig();
+ // The host repo lists a mounted sub-repo as a bare gitlink entry β€” drop those.
+ const gitlinks = new Set(repos.map((repo) => repo.dir).filter(Boolean));
+
+ const perRepo = await Promise.all(
+ repos.map(async (repo) => {
+ const dir = mountDir(repo);
+ if (stagedOnly) {
+ return prefixed(
+ repo,
+ await git(['diff', '--name-only', '--cached', '--diff-filter=d'], dir),
+ );
+ }
+ return prefixed(repo, [
+ ...(await git(['diff', '--name-only', 'HEAD', '--diff-filter=d'], dir)),
+ ...(await git(['ls-files', '--others', '--exclude-standard'], dir)),
+ ]);
+ }),
+ );
+
+ return perRepo.flat().filter((file) => !gitlinks.has(file));
+};
+
+/** Resolve CLI file args to root-relative paths; exits on paths outside the repo. */
+export const normalizeArgs = (args: string[]): string[] =>
+ args.map((arg) => {
+ const abs = path.resolve(process.cwd(), arg);
+ const rel = path.relative(getConfig().rootDir, abs);
+ if (rel.startsWith('..')) {
+ console.error(`βœ— file outside repo: ${arg}`);
+ process.exit(2);
+ }
+ return rel;
+ });
diff --git a/.agents/scripts/check/delegate.ts b/.agents/scripts/check/delegate.ts
new file mode 100644
index 00000000000..f3ec443357b
--- /dev/null
+++ b/.agents/scripts/check/delegate.ts
@@ -0,0 +1,48 @@
+import { readFile, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+/**
+ * Derive the superproject root from a submodule's resolved gitdir: a
+ * submodule checkout stores its git data under the host's
+ * `<hostRoot>/.git/modules/<name>`. Returns null for anything else (a
+ * standalone clone has a `.git` directory, a linked worktree points into
+ * `.git/worktrees`).
+ */
+export const hostRootFromGitdir = (gitdir: string): string | null => {
+ const marker = `${path.sep}.git${path.sep}modules${path.sep}`;
+ const index = gitdir.lastIndexOf(marker);
+ return index === -1 ? null : gitdir.slice(0, index);
+};
+
+/**
+ * When this repo is mounted as a git submodule of a superproject that ships
+ * its own `check` script, return that superproject's root so the standalone
+ * entry can delegate β€” the host entry routes this repo's files through the
+ * same engine with the host's full config, so both entries behave
+ * identically no matter where they are invoked from.
+ */
+export const detectHostCheckRoot = async (repoRoot: string): Promise<string | null> => {
+ const gitPath = path.join(repoRoot, '.git');
+ let content: string;
+ try {
+ if ((await stat(gitPath)).isDirectory()) return null;
+ content = await readFile(gitPath, 'utf8');
+ } catch {
+ return null;
+ }
+
+ // The gitfile format is exactly `gitdir: <path>` (git's repository-layout docs)
+ const match = content.match(/^gitdir: ?(.+)$/m);
+ if (!match) return null;
+ const hostRoot = hostRootFromGitdir(path.resolve(repoRoot, match[1].trim()));
+ if (!hostRoot) return null;
+
+ try {
+ const pkg = JSON.parse(await readFile(path.join(hostRoot, 'package.json'), 'utf8')) as {
+ scripts?: Record<string, string>;
+ };
+ return pkg.scripts?.check ? hostRoot : null;
+ } catch {
+ return null;
+ }
+};
diff --git a/.agents/scripts/check/exec.ts b/.agents/scripts/check/exec.ts
new file mode 100644
index 00000000000..b67900fa40c
--- /dev/null
+++ b/.agents/scripts/check/exec.ts
@@ -0,0 +1,51 @@
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+
+import { exists, mountDir, rootDir } from './paths';
+import type { RepoMount, RunResult } from './types';
+
+export const run = (command: string, args: string[], cwd: string): Promise<RunResult> =>
+ new Promise((resolvePromise) => {
+ const child = spawn(command, args, {
+ cwd,
+ env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (chunk) => (stdout += chunk));
+ child.stderr.on('data', (chunk) => (stderr += chunk));
+ child.on('error', (error) => resolvePromise({ code: 127, stderr: String(error), stdout }));
+ child.on('close', (code) => resolvePromise({ code: code ?? 1, stderr, stdout }));
+ });
+
+/**
+ * Resolve a tool to the nearest node_modules/.bin walking up to the host root.
+ * No bunx fallback: downloading an unpinned copy on the fly can disagree with
+ * the repo's locked version β€” a missing bin means deps aren't installed, which
+ * should fail loudly instead.
+ */
+export const toolCommand = async (dir: string, tool: string): Promise<string> => {
+ const root = rootDir();
+ for (let current = dir; ; current = path.dirname(current)) {
+ const bin = path.join(current, 'node_modules/.bin', tool);
+ if (await exists(bin)) return bin;
+ if (current === root || current === path.dirname(current)) break;
+ }
+ console.error(
+ `βœ— ${tool} not found in node_modules/.bin (from ${path.relative(root, dir) || '.'}) β€” install dependencies from the repo root first`,
+ );
+ process.exit(2);
+};
+
+export const runTool = async (mount: RepoMount, toolArgs: string[], files: string[]) => {
+ const [tool, ...flags] = toolArgs;
+ const dir = mountDir(mount);
+ const bin = await toolCommand(dir, tool);
+ return run(bin, [...flags, ...files], dir);
+};
+
+export const git = async (args: string[], cwd = rootDir()): Promise<string[]> => {
+ const result = await run('git', args, cwd);
+ return result.stdout.split('\n').filter(Boolean);
+};
diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.ts
new file mode 100644
index 00000000000..526092c04d9
--- /dev/null
+++ b/.agents/scripts/check/index.ts
@@ -0,0 +1,151 @@
+/// <reference types="node" />
+
+/**
+ * Agent-oriented quality check engine: `bun run check [files...] [--lint] [--test] [--type]`.
+ *
+ * Runs the lint-staged toolchain (with autofix) and/or related tests on the
+ * given files, auto-routing each file to the right eslint/stylelint config
+ * root (the host repo or a mounted sub-repo) and the nearest owning vitest
+ * config. Output is compact and colorless so agents burn minimal tokens
+ * reading it.
+ *
+ * `--lint` / `--test` / `--type` are composable selectors; no selector means
+ * lint + test. File selection: explicit args, else all working-tree changes
+ * (staged + unstaged + untracked) from every configured repo; `--staged`
+ * narrows the default to staged files only.
+ *
+ * This module is the reusable engine: hosts call `runCli` with a
+ * `CheckConfig`. This repo's standalone entry is `cli.ts`; a superproject
+ * mounting this repo provides its own entry that adds its root pipelines and
+ * mounts this repo's via `pipelines.ts`.
+ */
+import { collectAutofixDiffs, snapshot, writeFullDiff } from './autofix';
+import { collectFromGit, normalizeArgs } from './collect';
+import { run } from './exec';
+import { lintGroup } from './lint';
+import { existsInRepo, setConfig } from './paths';
+import { printReport } from './report';
+import { pipelineFor, relatedTestCandidates, resolveMount } from './routing';
+import type { CheckConfig, FileDiff, LintProblem, RepoMount, TestOutcome } from './types';
+import { runTestGroups } from './vitest';
+
+const USAGE = `Usage: bun run check [files...] [--lint] [--test] [--type] [--staged]
+ Selectors compose; no selector = --lint --test.
+ files explicit paths; default = all working-tree changes (staged + unstaged + untracked)
+ --staged collect staged files only (pre-commit scope); ignored with explicit files
+ --lint lint pipelines (with autofix)
+ --test related tests
+ --type full type-check; alone, file collection is skipped`;
+
+const KNOWN_FLAGS = new Set(['--lint', '--test', '--type', '--staged']);
+
+/** Keep only candidates that exist on disk, preserving order. */
+const filterExisting = async (candidates: string[]): Promise<string[]> => {
+ const present = await Promise.all(candidates.map((candidate) => existsInRepo(candidate)));
+ return candidates.filter((_, index) => present[index]);
+};
+
+export const runCli = async (config: CheckConfig) => {
+ setConfig(config);
+
+ const rawArgs = process.argv.slice(2);
+ if (rawArgs.includes('--help') || rawArgs.includes('-h')) {
+ console.log(USAGE);
+ return;
+ }
+ const unknownFlags = rawArgs.filter((arg) => arg.startsWith('--') && !KNOWN_FLAGS.has(arg));
+ if (unknownFlags.length > 0) {
+ console.error(`βœ— unknown flag: ${unknownFlags.join(' ')}\n${USAGE}`);
+ process.exit(2);
+ }
+
+ const wantLint = rawArgs.includes('--lint');
+ const wantTest = rawArgs.includes('--test');
+ const runType = rawArgs.includes('--type');
+ const noSelector = !wantLint && !wantTest && !runType;
+ const runLint = wantLint || noSelector;
+ const runTest = wantTest || noSelector;
+
+ const fileArgs = rawArgs.filter((arg) => !arg.startsWith('--'));
+
+ let files: string[] = [];
+ if (runLint || runTest) {
+ files = await filterExisting(
+ fileArgs.length > 0
+ ? normalizeArgs(fileArgs)
+ : await collectFromGit(rawArgs.includes('--staged')),
+ );
+ if (files.length === 0 && !runType) {
+ console.log('βœ“ nothing to check (no changed files)');
+ return;
+ }
+ } else if (fileArgs.length > 0) {
+ console.log(`(files ignored: --type alone runs the full type-check)`);
+ }
+
+ /* ---- Lint (with autofix) first so tests run against the fixed code ---- */
+ let problems: LintProblem[] = [];
+ let fatal: string[] = [];
+ let diffs: FileDiff[] = [];
+ let skipped = 0;
+ if (runLint) {
+ // Group lintable files by (mount, pipeline); remember files with no matching linter.
+ const lintGroups = new Map<
+ string,
+ { mount: RepoMount; subPaths: string[]; tools: string[][] }
+ >();
+ for (const file of files) {
+ const { mount, subPath } = resolveMount(config.repos, file);
+ const pipeline = pipelineFor(mount.pipelines, subPath);
+ if (!pipeline) {
+ skipped += 1;
+ continue;
+ }
+ const key = `${mount.dir}:${pipeline.exts[0]}`;
+ const group = lintGroups.get(key) ?? { mount, subPaths: [], tools: pipeline.tools };
+ group.subPaths.push(subPath);
+ lintGroups.set(key, group);
+ }
+
+ const before = await snapshot(files);
+ const outcomes = await Promise.all(
+ [...lintGroups.values()].map((group) => lintGroup(group.mount, group.tools, group.subPaths)),
+ );
+ problems = outcomes.flatMap((outcome) => outcome.problems);
+ fatal = outcomes.flatMap((outcome) => outcome.fatal);
+ diffs = await collectAutofixDiffs(before);
+ }
+
+ /* ---- Related tests ---- */
+ let tests: TestOutcome | null = null;
+ let testFiles: string[] = [];
+ if (runTest) {
+ testFiles = await filterExisting([
+ ...new Set(files.flatMap((file) => relatedTestCandidates(file))),
+ ]);
+ tests = await runTestGroups(testFiles);
+ }
+
+ /* ---- Type check ---- */
+ let typeOutput: string | null = null;
+ if (runType) {
+ const result = await run('bun', ['run', 'type-check'], config.rootDir);
+ typeOutput = result.code === 0 ? '' : (result.stdout + result.stderr).trim();
+ }
+
+ const fullDiffPath = diffs.length > 0 ? await writeFullDiff(diffs) : null;
+ const { failed } = printReport({
+ diffs,
+ fatal,
+ fileCount: files.length,
+ fullDiffPath,
+ lintRan: runLint,
+ problems,
+ skipped,
+ testFileCount: testFiles.length,
+ tests,
+ typeOutput,
+ });
+
+ process.exit(failed ? 1 : 0);
+};
diff --git a/.agents/scripts/check/lint.ts b/.agents/scripts/check/lint.ts
new file mode 100644
index 00000000000..a502496fce1
--- /dev/null
+++ b/.agents/scripts/check/lint.ts
@@ -0,0 +1,101 @@
+import path from 'node:path';
+
+import { runTool } from './exec';
+import { mountDir } from './paths';
+import { stylelintApplies } from './routing';
+import type { LintOutcome, LintProblem, RepoMount } from './types';
+
+const filePrefix = (mount: RepoMount) => (mount.dir === '' ? '' : `${mount.dir}/`);
+
+const parseEslintJson = (stdout: string, mount: RepoMount): LintProblem[] | null => {
+ try {
+ const results = JSON.parse(stdout) as {
+ filePath: string;
+ messages: { line?: number; message: string; ruleId: string | null; severity: number }[];
+ }[];
+ return results.flatMap((result) =>
+ result.messages
+ // ruleId=null entries are eslint's own notices (e.g. ignored-file warnings)
+ .filter((message) => message.ruleId !== null)
+ .map((message) => ({
+ file: filePrefix(mount) + path.relative(mountDir(mount), result.filePath),
+ line: message.line ?? 0,
+ message: message.message,
+ rule: message.ruleId ?? '',
+ severity: message.severity === 2 ? ('error' as const) : ('warning' as const),
+ })),
+ );
+ } catch {
+ return null;
+ }
+};
+
+const parseStylelintJson = (stdout: string, mount: RepoMount): LintProblem[] | null => {
+ try {
+ const results = JSON.parse(stdout) as {
+ source: string;
+ warnings: { line?: number; rule: string; severity: string; text: string }[];
+ }[];
+ return results.flatMap((result) =>
+ result.warnings.map((warning) => ({
+ file: filePrefix(mount) + path.relative(mountDir(mount), result.source),
+ line: warning.line ?? 0,
+ message: warning.text,
+ rule: warning.rule,
+ severity: warning.severity === 'error' ? ('error' as const) : ('warning' as const),
+ })),
+ );
+ } catch {
+ return null;
+ }
+};
+
+const mountLabel = (mount: RepoMount) => mount.dir || '.';
+
+/** Run one mount's pipeline (autofix mode) over a file group, collecting remaining problems. */
+export const lintGroup = async (
+ mount: RepoMount,
+ tools: string[][],
+ subPaths: string[],
+): Promise<LintOutcome> => {
+ const outcome: LintOutcome = { fatal: [], problems: [] };
+
+ for (const toolArgs of tools) {
+ const [tool] = toolArgs;
+ if (tool === 'eslint') {
+ const result = await runTool(
+ mount,
+ [...toolArgs, '--format', 'json', '--no-warn-ignored'],
+ subPaths,
+ );
+ const problems = parseEslintJson(result.stdout, mount);
+ if (problems) outcome.problems.push(...problems);
+ else if (result.code !== 0)
+ outcome.fatal.push(
+ `eslint(${mountLabel(mount)}): ${result.stderr.trim() || result.stdout.trim()}`,
+ );
+ } else if (tool === 'stylelint') {
+ const scoped = subPaths.filter((subPath) => stylelintApplies(subPath));
+ if (scoped.length === 0) continue;
+ const result = await runTool(
+ mount,
+ [...toolArgs, '--formatter', 'json', '--allow-empty-input'],
+ scoped,
+ );
+ const problems = parseStylelintJson(result.stdout || result.stderr, mount);
+ if (problems) outcome.problems.push(...problems);
+ else if (result.code !== 0)
+ outcome.fatal.push(
+ `stylelint(${mountLabel(mount)}): ${result.stderr.trim() || result.stdout.trim()}`,
+ );
+ } else {
+ const result = await runTool(mount, toolArgs, subPaths);
+ if (result.code !== 0)
+ outcome.fatal.push(
+ `${tool}(${mountLabel(mount)}): ${result.stderr.trim() || result.stdout.trim()}`,
+ );
+ }
+ }
+
+ return outcome;
+};
diff --git a/.agents/scripts/check/paths.ts b/.agents/scripts/check/paths.ts
new file mode 100644
index 00000000000..3b26a85cc24
--- /dev/null
+++ b/.agents/scripts/check/paths.ts
@@ -0,0 +1,36 @@
+import { access } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { CheckConfig, RepoMount } from './types';
+
+/**
+ * Active config, set once by `runCli` before any IO helper runs. A module
+ * singleton (instead of threading config through every call) keeps the IO
+ * layer signatures small; the pure routing helpers take their inputs
+ * explicitly and stay independently testable.
+ */
+let config: CheckConfig | undefined;
+
+export const setConfig = (next: CheckConfig) => {
+ config = next;
+};
+
+export const getConfig = (): CheckConfig => {
+ if (!config) throw new Error('check engine not configured β€” call runCli with a CheckConfig');
+ return config;
+};
+
+export const rootDir = () => getConfig().rootDir;
+
+/** Absolute directory of a mounted repo. */
+export const mountDir = (mount: RepoMount) => path.join(rootDir(), mount.dir);
+
+export const exists = (target: string): Promise<boolean> =>
+ access(target).then(
+ () => true,
+ () => false,
+ );
+
+/** Whether a root-relative path exists on disk. */
+export const existsInRepo = (relPath: string): Promise<boolean> =>
+ exists(path.join(rootDir(), relPath));
diff --git a/.agents/scripts/check/pipelines.ts b/.agents/scripts/check/pipelines.ts
new file mode 100644
index 00000000000..6b02a72242d
--- /dev/null
+++ b/.agents/scripts/check/pipelines.ts
@@ -0,0 +1,50 @@
+import type { PipelineEntry } from './types';
+
+/**
+ * This repo's extension β†’ tool pipeline, mirroring the lint-staged config in
+ * `package.json`. A drift test in `check.test.ts` keeps them in sync.
+ * Superprojects that mount this repo import this table for the mount and
+ * provide their own table for their root.
+ */
+export const lobehubPipelines: PipelineEntry[] = [
+ {
+ exts: ['.md'],
+ tools: [
+ ['remark', '--silent', '--output', '--'],
+ ['prettier', '--write'],
+ ],
+ },
+ {
+ exts: ['.mdx'],
+ tools: [
+ ['remark', '-r', './.remarkrc.mdx.mjs', '--silent', '--output', '--'],
+ ['eslint', '--quiet', '--fix'],
+ ],
+ },
+ { exts: ['.json'], tools: [['prettier', '--write']] },
+ {
+ exts: ['.mjs', '.cjs'],
+ tools: [
+ ['eslint', '--fix'],
+ ['prettier', '--write'],
+ ],
+ },
+ {
+ exts: ['.js', '.jsx'],
+ tools: [
+ ['eslint', '--fix'],
+ ['stylelint', '--fix'],
+ ['prettier', '--write'],
+ ],
+ },
+ {
+ // .mts/.cts are outside lint-staged's globs but belong to the same pipeline
+ exts: ['.ts', '.tsx', '.mts', '.cts'],
+ tools: [
+ ['stylelint', '--fix'],
+ ['eslint', '--fix'],
+ ['prettier', '--write'],
+ ],
+ },
+ { exts: ['.yml', '.yaml'], tools: [['eslint', '--fix']] },
+];
diff --git a/.agents/scripts/check/report.ts b/.agents/scripts/check/report.ts
new file mode 100644
index 00000000000..25f966176ea
--- /dev/null
+++ b/.agents/scripts/check/report.ts
@@ -0,0 +1,96 @@
+import { renderDiffsForStdout } from './autofix';
+import type { FileDiff, LintProblem, TestOutcome } from './types';
+
+export interface ReportInput {
+ diffs: FileDiff[];
+ fatal: string[];
+ fileCount: number;
+ /** Path of the untruncated autofix diff file, when any diff exists. */
+ fullDiffPath: string | null;
+ lintRan: boolean;
+ problems: LintProblem[];
+ /** Files with no matching lint pipeline (only counted when lint ran). */
+ skipped: number;
+ testFileCount: number;
+ /** null when tests were not selected. */
+ tests: TestOutcome | null;
+ /** null = type-check not run; '' = clean; non-empty = failure output. */
+ typeOutput: string | null;
+}
+
+/** Print the compact report; the summary line mentions only checks that ran. */
+export const printReport = (input: ReportInput): { failed: boolean } => {
+ const {
+ diffs,
+ fatal,
+ fileCount,
+ fullDiffPath,
+ lintRan,
+ problems,
+ skipped,
+ testFileCount,
+ tests,
+ typeOutput,
+ } = input;
+
+ const errors = problems.filter((problem) => problem.severity === 'error');
+ const warnings = problems.filter((problem) => problem.severity === 'warning');
+ const failed =
+ errors.length > 0 ||
+ fatal.length > 0 ||
+ (tests?.failedOutput.length ?? 0) > 0 ||
+ Boolean(typeOutput);
+
+ const parts: string[] = [];
+ if (lintRan || tests) parts.push(`${fileCount} files`);
+ if (lintRan) {
+ const lintPart =
+ errors.length > 0 || warnings.length > 0
+ ? `lint ${[
+ errors.length > 0 ? `${errors.length} errors` : '',
+ warnings.length > 0 ? `${warnings.length} warnings` : '',
+ ]
+ .filter(Boolean)
+ .join(' ')}`
+ : 'lint clean';
+ parts.push(`${lintPart}${diffs.length > 0 ? ` (${diffs.length} auto-fixed)` : ''}`);
+ }
+ if (tests) {
+ parts.push(
+ testFileCount === 0
+ ? 'tests none'
+ : tests.failedOutput.length > 0
+ ? 'tests failed'
+ : `tests ${tests.passed} passed`,
+ );
+ }
+ if (typeOutput !== null) parts.push(typeOutput ? 'types failed' : 'types clean');
+ if (skipped > 0) parts.push(`${skipped} skipped (no linter)`);
+
+ console.log(`${failed ? 'βœ—' : 'βœ“'} ${parts.join(' Β· ')}`);
+
+ if (problems.length > 0) {
+ console.log('\nlint:');
+ for (const problem of problems)
+ console.log(
+ `${problem.file}:${problem.line} ${problem.rule} ${problem.message}${problem.severity === 'warning' ? ' (warning)' : ''}`,
+ );
+ }
+ for (const message of fatal) console.log(`\nlint fatal:\n${message}`);
+
+ if (tests && tests.failedOutput.length > 0)
+ console.log(`\ntests:\n${tests.failedOutput.join('\n\n')}`);
+ if (tests && tests.noMatch.length > 0)
+ console.log(
+ `\ntests skipped (not matched by owning vitest config): ${tests.noMatch.join(', ')}`,
+ );
+
+ if (typeOutput) console.log(`\ntypes:\n${typeOutput}`);
+
+ if (diffs.length > 0 && fullDiffPath) {
+ console.log(`\nauto-fixed (${diffs.length} files, full diff: ${fullDiffPath}):`);
+ console.log(renderDiffsForStdout(diffs));
+ }
+
+ return { failed };
+};
diff --git a/.agents/scripts/check/routing.ts b/.agents/scripts/check/routing.ts
new file mode 100644
index 00000000000..91b3aa097f2
--- /dev/null
+++ b/.agents/scripts/check/routing.ts
@@ -0,0 +1,77 @@
+import path from 'node:path';
+
+import type { PipelineEntry, RepoMount } from './types';
+
+/**
+ * stylelint's CSS-in-JS parser mangles ordinary template literals in files it
+ * was never configured for (it corrupted this very script once): the repos
+ * scope stylelint to `{src,tests}/**` in their `lint:style` scripts, so apply
+ * the same boundary here instead of lint-staged's blanket `*.{ts,tsx}` glob.
+ */
+export const stylelintApplies = (subPath: string) => /^(?:src|tests)\//.test(subPath);
+
+/**
+ * Resolve a root-relative path to its owning mount and the path relative to
+ * that mount. Longest mount dir prefix wins; the root mount (`dir: ''`) is the
+ * fallback.
+ */
+export const resolveMount = (
+ repos: RepoMount[],
+ relPath: string,
+): { mount: RepoMount; subPath: string } => {
+ const match = repos
+ .filter(
+ (repo) => repo.dir !== '' && (relPath === repo.dir || relPath.startsWith(`${repo.dir}/`)),
+ )
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
+ if (match) return { mount: match, subPath: relPath.slice(match.dir.length + 1) };
+
+ const root = repos.find((repo) => repo.dir === '');
+ if (!root) throw new Error('CheckConfig.repos must contain a root mount (dir: "")');
+ return { mount: root, subPath: relPath };
+};
+
+/** Find the lint pipeline for a file, or null when no linter applies. */
+export const pipelineFor = (pipelines: PipelineEntry[], subPath: string) => {
+ const ext = path.extname(subPath).toLowerCase();
+ return pipelines.find((entry) => entry.exts.includes(ext)) ?? null;
+};
+
+export const isTestFile = (relPath: string) => /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(relPath);
+
+/**
+ * Related-test candidates for a source file: the file itself when it is a test,
+ * otherwise sibling `<base>.test.*` and `__tests__/<base>.test.*`. Pure β€” the
+ * caller filters candidates by on-disk existence.
+ */
+export const relatedTestCandidates = (relPath: string): string[] => {
+ if (isTestFile(relPath)) return [relPath];
+ if (!/\.[cm]?[jt]sx?$/.test(relPath)) return [];
+
+ const dir = path.dirname(relPath);
+ const base = path.basename(relPath).replace(/\.[^.]+$/, '');
+ return ['.ts', '.tsx', '.mts'].flatMap((ext) => [
+ path.join(dir, `${base}.test${ext}`),
+ path.join(dir, '__tests__', `${base}.test${ext}`),
+ ]);
+};
+
+/**
+ * Nearest directory (walking up to the host root) containing a vitest config β€”
+ * the "run vitest from the owning package" rule, automated.
+ */
+export const findVitestConfigDir = async (
+ relPath: string,
+ exists: (candidate: string) => Promise<boolean>,
+): Promise<string> => {
+ const configNames = ['vitest.config.mts', 'vitest.config.ts', 'vitest.config.mjs'];
+ let dir = path.dirname(relPath);
+
+ while (true) {
+ const candidates = configNames.map((name) => (dir === '.' ? name : path.join(dir, name)));
+ const found = await Promise.all(candidates.map((candidate) => exists(candidate)));
+ if (found.some(Boolean)) return dir;
+ if (dir === '.') return '.';
+ dir = path.dirname(dir);
+ }
+};
diff --git a/.agents/scripts/check/types.ts b/.agents/scripts/check/types.ts
new file mode 100644
index 00000000000..60c1ace9692
--- /dev/null
+++ b/.agents/scripts/check/types.ts
@@ -0,0 +1,52 @@
+/** One extension group of a repo's lint toolchain (mirrors its lint-staged config). */
+export interface PipelineEntry {
+ exts: string[];
+ /** Tools run sequentially on the same file group (fix order matters). */
+ tools: string[][];
+}
+
+/** A repository participating in the check: the host root or a vendored sub-repo. */
+export interface RepoMount {
+ /** Root-relative directory of the repo; '' means the host repo itself. */
+ dir: string;
+ pipelines: PipelineEntry[];
+}
+
+export interface CheckConfig {
+ /** Mounts in routing order; exactly one entry must have `dir: ''` (the host root). */
+ repos: RepoMount[];
+ /** Absolute path of the host repo root. */
+ rootDir: string;
+}
+
+export interface LintProblem {
+ file: string;
+ line: number;
+ message: string;
+ rule: string;
+ severity: 'error' | 'warning';
+}
+
+export interface FileDiff {
+ added: number;
+ diff: string;
+ file: string;
+ removed: number;
+}
+
+export interface RunResult {
+ code: number;
+ stderr: string;
+ stdout: string;
+}
+
+export interface LintOutcome {
+ fatal: string[];
+ problems: LintProblem[];
+}
+
+export interface TestOutcome {
+ failedOutput: string[];
+ noMatch: string[];
+ passed: number;
+}
diff --git a/.agents/scripts/check/vitest.config.mts b/.agents/scripts/check/vitest.config.mts
new file mode 100644
index 00000000000..1e9e166cb10
--- /dev/null
+++ b/.agents/scripts/check/vitest.config.mts
@@ -0,0 +1,13 @@
+import { defineConfig } from 'vitest/config';
+
+/**
+ * Dedicated config: the repo root vitest config excludes dot-directories and
+ * carries a DOM environment + heavy setup this plain Node script doesn't
+ * want. The check engine's own nearest-config routing picks this file up, so
+ * `bun run check` runs these tests from here automatically.
+ */
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/.agents/scripts/check/vitest.ts b/.agents/scripts/check/vitest.ts
new file mode 100644
index 00000000000..5c939223702
--- /dev/null
+++ b/.agents/scripts/check/vitest.ts
@@ -0,0 +1,59 @@
+import path from 'node:path';
+
+import { run, toolCommand } from './exec';
+import { existsInRepo, rootDir } from './paths';
+import { findVitestConfigDir } from './routing';
+import type { TestOutcome } from './types';
+
+/**
+ * Compact vitest failure output: keep only the "Failed Tests" detail section
+ * (assertions + code frames) and drop banners, timings, and separator noise.
+ */
+export const compactVitestOutput = (output: string): string => {
+ const lines = output.split('\n');
+ const failedIndex = lines.findIndex((line) => line.includes('Failed Tests'));
+ const kept = (failedIndex === -1 ? lines : lines.slice(failedIndex + 1)).filter(
+ (line) =>
+ !/^\s*(?:RUN\s+v|Start at\s|Duration\s)/.test(line) &&
+ !/^[⎯\s]*(?:\[\d+\/\d+\][⎯\s]*)?$/.test(line),
+ );
+ return kept.join('\n').trim();
+};
+
+/** Group test files by their owning vitest config dir and run each group from there. */
+export const runTestGroups = async (testFiles: string[]): Promise<TestOutcome> => {
+ const groups = new Map<string, string[]>();
+ for (const file of testFiles) {
+ const configDir = await findVitestConfigDir(file, existsInRepo);
+ const list = groups.get(configDir) ?? [];
+ list.push(path.relative(configDir, file));
+ groups.set(configDir, list);
+ }
+
+ const outcome: TestOutcome = { failedOutput: [], noMatch: [], passed: 0 };
+
+ await Promise.all(
+ [...groups.entries()].map(async ([configDir, files]) => {
+ const cwd = path.join(rootDir(), configDir);
+ const vitestBin = await toolCommand(cwd, 'vitest');
+ const result = await run(
+ vitestBin,
+ ['run', '--silent=passed-only', '--passWithNoTests', ...files],
+ cwd,
+ );
+
+ const passedMatch = result.stdout.match(/Tests\s+(\d+) passed/);
+ if (passedMatch) outcome.passed += Number(passedMatch[1]);
+
+ if (result.code !== 0) {
+ outcome.failedOutput.push(
+ `# vitest (${configDir})\n${compactVitestOutput(result.stdout + result.stderr)}`,
+ );
+ } else if (!passedMatch) {
+ outcome.noMatch.push(...files.map((file) => path.join(configDir, file)));
+ }
+ }),
+ );
+
+ return outcome;
+};
diff --git a/AGENTS.md b/AGENTS.md
index 34a76fad6fc..0c2a8ab15f1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -104,23 +104,19 @@ Open this URL to develop locally against the production backend (app.lobehub.com
- `bun` to run npm scripts
- `bunx` for executable npm packages
-### Testing
+### Quality Check
```bash
-# Run specific test (NEVER run `bun run test` - takes ~10 minutes)
-bunx vitest run --silent='passed-only' '[file-path]'
-
-# Database package
-cd packages/database && bunx vitest run --silent='passed-only' '[file]'
+# Lint (with autofix) + related tests for changed files, or explicit paths
+bun run check [files...] [--lint] [--test] [--type]
```
+- `--lint` / `--test` / `--type` are composable selectors; no selector = lint + test. Default files = all working-tree changes (staged + unstaged + untracked); explicit paths override.
+- Tests are auto-routed to the nearest owning vitest config (e.g. `packages/database`) β€” no need to `cd` into packages. `--type` runs the full type-check.
+- NEVER run `bun run test` β€” the full suite takes \~10 minutes.
- Prefer `vi.spyOn` over `vi.mock`
-
-### Type Checking
-
-```bash
-bun run type-check
-```
+- Manual fallback when you need unusual flags or a single tool: `bunx vitest run --silent='passed-only' '[file-path]'` from the owning package directory, `bun run type-check` for types.
+- The implementation lives in `.agents/scripts/check/` as a reusable engine. A superproject that vendors this repo as a submodule can ship its own `check` entry that mounts this repo's pipelines; when this repo is checked out as such a submodule, `bun run check` here detects that and delegates to the superproject's entry automatically.
### i18n
diff --git a/apps/server/src/modules/AgentRuntime/executors/callTool.ts b/apps/server/src/modules/AgentRuntime/executors/callTool.ts
index da1ee4a01ca..3696707dcf8 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callTool.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callTool.ts
@@ -14,6 +14,7 @@ import {
import { type ChatToolPayload } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
+import { isDeviceCapablePlan } from '@/helpers/executionTarget';
import {
type DeviceAccessReason,
isDeviceToolIdentifier,
@@ -270,6 +271,9 @@ export const callTool =
agentVisibility,
// Assistant message owning this tool call (β‰  source user message).
assistantMessageId: payload.parentMessageId,
+ deviceCapable: state.metadata?.executionPlan
+ ? isDeviceCapablePlan(state.metadata.executionPlan)
+ : undefined,
documentId: state.metadata?.documentId,
editingAgentId: state.metadata?.editingAgentId,
execSubAgent: ctx.execSubAgent,
diff --git a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
index 03811c9d961..d676a35872e 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
@@ -14,6 +14,7 @@ import {
} from '@lobechat/observability-otel/modules/agent-runtime';
import { type ChatToolPayload } from '@lobechat/types';
+import { isDeviceCapablePlan } from '@/helpers/executionTarget';
import {
type DeviceAccessReason,
isDeviceToolIdentifier,
@@ -204,8 +205,7 @@ export const callToolsBatch =
if (isDeviceToolIdentifier(chatToolPayload.identifier) && !batchHookResult?.isMocked) {
const policy = state.metadata?.deviceAccessPolicy as
- | { canUseDevice: boolean; reason: DeviceAccessReason }
- | undefined;
+ { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
logDeviceToolAudit({
apiName: chatToolPayload.apiName,
botContext: state.metadata?.botContext,
@@ -269,6 +269,9 @@ export const callToolsBatch =
),
// Assistant message owning this tool call (β‰  source user message).
assistantMessageId: payload.parentMessageId,
+ deviceCapable: state.metadata?.executionPlan
+ ? isDeviceCapablePlan(state.metadata.executionPlan)
+ : undefined,
documentId: state.metadata?.documentId,
execSubAgent: ctx.execSubAgent,
executionTimeoutMs: timeoutMs,
@@ -521,8 +524,7 @@ export const callToolsBatch =
);
for (const result of toolResults) {
const discovered = result.data?.state?.activatedTools as
- | Array<{ identifier: string }>
- | undefined;
+ Array<{ identifier: string }> | undefined;
if (discovered?.length) {
const newActivations = discovered
.filter((t) => !existingActivationIds.has(t.identifier))
diff --git a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts
index d9a143b2dc3..31105b11ed8 100644
--- a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts
+++ b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts
@@ -1,6 +1,6 @@
import { builtinSkills } from '@lobechat/builtin-skills';
-import { filterBuiltinSkills } from '@/helpers/skillFilters';
+import { USER_HIDDEN_BUILTIN_SKILLS } from '@/helpers/skillFilters';
import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
import type { SkillMountProvider, SkillMountProviderRequest } from '../SkillMount';
@@ -13,7 +13,14 @@ import {
} from './ProviderSkillsReadonly';
export class ProviderSkillsBuiltin implements SkillMountProvider {
- private readonly skills = filterBuiltinSkills(builtinSkills);
+ // No device gating on purpose: the VFS is a read-only file view of skill
+ // content, so device-only skills (agent-browser) stay browsable here β€”
+ // executability gating lives in the runtime entry points (SkillEngine /
+ // skills / activator). User-hidden skills stay excluded: that axis is about
+ // visibility, not executability.
+ private readonly skills = builtinSkills.filter(
+ (skill) => !USER_HIDDEN_BUILTIN_SKILLS.has(skill.identifier),
+ );
async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
if (!input.resolvedPath.skillName) {
diff --git a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts
index c0689d84134..ab3990c702e 100644
--- a/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts
+++ b/apps/server/src/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts
@@ -2,15 +2,19 @@
import { builtinSkills } from '@lobechat/builtin-skills';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { filterBuiltinSkills } from '@/helpers/skillFilters';
+import { USER_HIDDEN_BUILTIN_SKILLS } from '@/helpers/skillFilters';
import { ProviderSkillsBuiltin } from './ProviderSkillsBuiltin';
import { ProviderSkillsInstalledActive } from './ProviderSkillsInstalledActive';
import { ProviderSkillsInstalledAll } from './ProviderSkillsInstalledAll';
describe('readonly skill providers', () => {
- const builtinSkill = filterBuiltinSkills(builtinSkills)[0];
- const builtinSkillWithResources = filterBuiltinSkills(builtinSkills).find(
+ // Mirrors the provider's own set: user-hidden skills excluded, no device gating.
+ const visibleBuiltinSkills = builtinSkills.filter(
+ (skill) => !USER_HIDDEN_BUILTIN_SKILLS.has(skill.identifier),
+ );
+ const builtinSkill = visibleBuiltinSkills[0];
+ const builtinSkillWithResources = visibleBuiltinSkills.find(
(skill) => skill.resources && Object.keys(skill.resources).length > 0,
);
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index c74ec7fd8f2..206cef4c59c 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -3188,8 +3188,20 @@ export class AiAgentService {
},
);
+ // Device-only builtin skills (agent-browser) are gated on the run's
+ // execution plan, not the compile-time `isDesktop` constant (always false
+ // on the server). Gate the static `<available_skills>` listing on the
+ // device-CAPABLE plan rather than `activeDeviceId`: `device-unrouted`
+ // runs let the model pick a device mid-run, and this skill set is built
+ // once per operation β€” gating on `activeDeviceId` would hide the skill
+ // forever in those runs. Activation/loading apply the same plan gate via
+ // `ToolExecutionContext.deviceCapable`; only actual command execution is
+ // gated at the device tool layer.
const skillEngine = new SkillEngine({
- enableChecker: (skill) => shouldEnableBuiltinSkill(skill.identifier),
+ enableChecker: (skill) =>
+ shouldEnableBuiltinSkill(skill.identifier, {
+ canExecuteOnDevice: executionPlan ? isDeviceCapablePlan(executionPlan) : false,
+ }),
skills,
});
operationSkillSet = skillEngine.generate(agentPlugins ?? []);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
index 2a223b12805..47bbba30a81 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -155,4 +155,35 @@ describe('skillsRuntime', () => {
}),
);
});
+
+ // Regression guard for the device-gating fix: builtin skills must be filtered
+ // with canExecuteOnDevice derived from the run's activeDeviceId, not the
+ // compile-time isDesktop constant (always false on the server).
+ it('gates device-only builtin skills on activeDeviceId presence', async () => {
+ const { filterBuiltinSkills } = await import('@/helpers/skillFilters');
+ const { skillsRuntime } = await import('../skills');
+
+ await skillsRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(filterBuiltinSkills).toHaveBeenLastCalledWith(expect.anything(), {
+ canExecuteOnDevice: false,
+ });
+
+ await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(filterBuiltinSkills).toHaveBeenLastCalledWith(expect.anything(), {
+ canExecuteOnDevice: true,
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index f4a022a06af..848698c08a4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -69,7 +69,12 @@ export const activatorRuntime: ServerRuntimeRegistration = {
if (context.serverDB && context.userId) {
const skillModel = new AgentSkillModel(context.serverDB, context.userId, context.workspaceId);
skillsRuntime = new SkillsExecutionRuntime({
- builtinSkills: filterBuiltinSkills(builtinSkills),
+ // Same device gate as the skills runtime: device-only skills are
+ // activatable in device-capable runs (matching <available_skills>),
+ // with `activeDeviceId` as the fallback for callers without a plan.
+ builtinSkills: filterBuiltinSkills(builtinSkills, {
+ canExecuteOnDevice: context.deviceCapable ?? !!context.activeDeviceId,
+ }),
service: {
findAll: () => skillModel.findAll(),
findById: (id) => skillModel.findById(id),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index d1c9933e328..7233ea37e33 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -390,7 +390,17 @@ export const skillsRuntime: ServerRuntimeRegistration = {
}
return new SkillsExecutionRuntime({
- builtinSkills: [...filterBuiltinSkills(builtinSkills), ...agentSkillBuiltins],
+ builtinSkills: [
+ // Device-only skills resolve in device-capable runs β€” mirrors the
+ // SkillEngine gate in aiAgent that builds <available_skills>, so a
+ // `device-unrouted` run can activate/read them before the model routes
+ // a device. `activeDeviceId` is the fallback for callers without an
+ // execution plan.
+ ...filterBuiltinSkills(builtinSkills, {
+ canExecuteOnDevice: context.deviceCapable ?? !!activeDeviceId,
+ }),
+ ...agentSkillBuiltins,
+ ],
deviceFileAccess,
projectSkills,
service,
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index e249b48a005..22f0d8f2468 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -143,6 +143,16 @@ export interface ToolExecutionContext {
* `messageId`.
*/
assistantMessageId?: string;
+ /**
+ * Whether the run's execution plan is device-capable (`device` or
+ * `device-unrouted`) β€” derived from `state.metadata.executionPlan` by the
+ * runtime executors. Device-only skills gate listing/activation/loading on
+ * this consistently, so a `device-unrouted` run can activate them before the
+ * model routes a device; actual command execution stays gated at the device
+ * tool layer. Undefined when the caller carries no execution plan (device
+ * gates then fall back to `activeDeviceId`).
+ */
+ deviceCapable?: boolean;
/** Current page document ID for page-scoped conversations */
documentId?: string | null;
/**
diff --git a/package.json b/package.json
index 8614c5ad0ad..7fcfb2332cf 100644
--- a/package.json
+++ b/package.json
@@ -52,6 +52,7 @@
"build:spa:raw": "rm -rf public/_spa && vite build",
"build:vercel": "cross-env-shell NODE_OPTIONS=--max-old-space-size=8192 \"bun run build:raw && bun run db:migrate\"",
"build-migrate-db": "bun run db:migrate",
+ "check": "bun run .agents/scripts/check/cli.ts",
"clean:node_modules": "bash -lc 'set -e; echo \"Removing all node_modules...\"; rm -rf node_modules; pnpm -r exec rm -rf node_modules; rm -rf apps/desktop/node_modules; echo \"All node_modules removed.\"'",
"db:generate": "drizzle-kit generate && npm run workflow:dbml",
"db:migrate": "cross-env MIGRATION_DB=1 tsx ./scripts/migrateServerDB/index.ts",
diff --git a/packages/builtin-skills/src/agent-browser/content.ts b/packages/builtin-skills/src/agent-browser/content.ts
index 0948ae4decf..b80b619f319 100644
--- a/packages/builtin-skills/src/agent-browser/content.ts
+++ b/packages/builtin-skills/src/agent-browser/content.ts
@@ -16,6 +16,16 @@ agent-browser snapshot -i # 4. re-snapshot after any page change
Refs become **stale on every page change** (click that navigates, form submit, dynamic re-render, dialog open). Always re-snapshot before the next ref interaction.
+## Dynamic pages & anti-bot escalation
+
+When scraping dynamic or anti-bot pages, escalate from cheap to heavy and stop at the first rung that yields real content:
+
+1. **Lightweight first**: builtin web search/crawl tools (or \`curl\`) β€” if the main text comes back, done.
+2. **Empty body, verification page, or obfuscated JS** β†’ the page needs a real JS run: \`agent-browser open <url>\`, \`agent-browser wait --load networkidle\`, then \`agent-browser read\` (or \`snapshot\`).
+3. **Still blocked** (anti-bot that fingerprints headless Chrome) β†’ connect to a real browser: launch Chrome with \`--remote-debugging-port=9222\` (Chrome 136+ also requires a separate \`--user-data-dir\`), then drive it with \`agent-browser --cdp 9222 <command>\` β€” a real browser fingerprint usually passes in one go.
+
+Discipline: the crux of anti-bot checks is "did a real browser execute the JS", so the closer to a human environment, the easier it passes. Verify you actually got content with \`agent-browser eval "document.body.innerText.length"\` (0 means blocked). Dump large output to a file first, then \`grep\`/\`head\` it. Close the debug-port browser session when done.
+
## Discovering everything else
Run \`agent-browser --help\` for the full command list, then \`agent-browser <subcommand> --help\` for any subcommand whose flags you're unsure about. The CLI also ships specialized skills (\`agent-browser skills list\`, \`agent-browser skills get <name>\`) covering Electron apps, Slack, dogfooding, Vercel Sandbox, and AWS Bedrock AgentCore β€” load one only when the task falls outside ordinary web pages.
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.ts
index 68680f47f0f..9ac015e9628 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts
@@ -115,6 +115,7 @@ Our search service is a metasearch engine with automatic engine selection. Provi
3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.
4. If needed, explain the issue to the user and suggest alternative search terms or strategies.
- If a page cannot be crawled, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
+- If a crawled page returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page requires a real browser to execute its JS β€” do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with headless Chrome instead.
- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.
- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.
</error_handling>
diff --git a/src/helpers/skillFilters.test.ts b/src/helpers/skillFilters.test.ts
index ef7cd779443..b761b7f4fe9 100644
--- a/src/helpers/skillFilters.test.ts
+++ b/src/helpers/skillFilters.test.ts
@@ -8,37 +8,35 @@ afterEach(() => {
});
describe('skillFilters', () => {
- it('should disable agent-browser on web environment', () => {
- expect(shouldEnableBuiltinSkill('lobe-agent-browser', { isDesktop: false })).toBe(false);
+ it('should disable agent-browser when the run cannot execute on a device', () => {
+ expect(shouldEnableBuiltinSkill('lobe-agent-browser', { canExecuteOnDevice: false })).toBe(
+ false,
+ );
});
it('should disable task builtin skill globally', () => {
- expect(shouldEnableBuiltinSkill('task', { isDesktop: false })).toBe(false);
- expect(shouldEnableBuiltinSkill('task', { isDesktop: true })).toBe(false);
+ expect(shouldEnableBuiltinSkill('task', { canExecuteOnDevice: false })).toBe(false);
+ expect(shouldEnableBuiltinSkill('task', { canExecuteOnDevice: true })).toBe(false);
});
- it('should enable agent-browser on desktop (non-Windows) environment', () => {
- expect(shouldEnableBuiltinSkill('lobe-agent-browser', { isDesktop: true })).toBe(true);
+ it('should enable agent-browser when the run can execute on a device', () => {
+ expect(shouldEnableBuiltinSkill('lobe-agent-browser', { canExecuteOnDevice: true })).toBe(true);
});
- it('should enable agent-browser on desktop Windows', () => {
- expect(shouldEnableBuiltinSkill('lobe-agent-browser', { isDesktop: true })).toBe(true);
- });
-
- it('should not be affected by Windows platform detection when desktop is enabled', async () => {
+ it('should not be affected by Windows platform detection when device execution is enabled', async () => {
vi.stubGlobal('process', { ...process, platform: 'win32' });
vi.resetModules();
const { shouldEnableBuiltinSkill } = await import('./skillFilters');
- expect(shouldEnableBuiltinSkill('lobe-agent-browser', { isDesktop: true })).toBe(true);
+ expect(shouldEnableBuiltinSkill('lobe-agent-browser', { canExecuteOnDevice: true })).toBe(true);
});
- it('should keep non-desktop-only skills enabled', () => {
- expect(shouldEnableBuiltinSkill('lobe-artifacts', { isDesktop: false })).toBe(true);
+ it('should keep non-device-only skills enabled', () => {
+ expect(shouldEnableBuiltinSkill('lobe-artifacts', { canExecuteOnDevice: false })).toBe(true);
});
- it('should filter builtin skills by platform context', () => {
+ it('should filter builtin skills by device execution context', () => {
const skills = [
{
content: 'agent-browser',
@@ -63,7 +61,7 @@ describe('skillFilters', () => {
},
];
- const filtered = filterBuiltinSkills(skills, { isDesktop: false });
+ const filtered = filterBuiltinSkills(skills, { canExecuteOnDevice: false });
expect(filtered).toHaveLength(1);
expect(filtered[0].identifier).toBe('lobe-artifacts');
diff --git a/src/helpers/skillFilters.ts b/src/helpers/skillFilters.ts
index c64be1c7bf9..70603795016 100644
--- a/src/helpers/skillFilters.ts
+++ b/src/helpers/skillFilters.ts
@@ -3,20 +3,26 @@ import { isDesktop } from '@lobechat/const';
import { type BuiltinSkill } from '@lobechat/types';
export interface BuiltinSkillFilterContext {
- isDesktop: boolean;
+ /**
+ * Whether the current run can execute commands on a local device. Server-side
+ * callers must derive this from the run's execution plan (`activeDeviceId`
+ * presence) β€” the compile-time `isDesktop` constant is always false there.
+ */
+ canExecuteOnDevice: boolean;
}
-const DESKTOP_ONLY_BUILTIN_SKILLS = new Set([AgentBrowserIdentifier]);
+const DEVICE_ONLY_BUILTIN_SKILLS = new Set([AgentBrowserIdentifier]);
const USER_HIDDEN_BUILTIN_SKILLS = new Set(['task']);
+// Client default: the desktop app is itself the execution device.
const DEFAULT_CONTEXT: BuiltinSkillFilterContext = {
- isDesktop,
+ canExecuteOnDevice: isDesktop,
};
const resolveBuiltinSkillFilterContext = (
context: BuiltinSkillFilterContext = DEFAULT_CONTEXT,
): BuiltinSkillFilterContext => ({
- isDesktop: context.isDesktop ?? DEFAULT_CONTEXT.isDesktop,
+ canExecuteOnDevice: context.canExecuteOnDevice ?? DEFAULT_CONTEXT.canExecuteOnDevice,
});
export const shouldEnableBuiltinSkill = (
@@ -27,10 +33,7 @@ export const shouldEnableBuiltinSkill = (
if (USER_HIDDEN_BUILTIN_SKILLS.has(skillId)) return false;
- if (DESKTOP_ONLY_BUILTIN_SKILLS.has(skillId)) {
- if (!resolvedContext.isDesktop) return false;
- return true;
- }
+ if (DEVICE_ONLY_BUILTIN_SKILLS.has(skillId)) return resolvedContext.canExecuteOnDevice;
return true;
};
diff --git a/src/helpers/toolAvailability.ts b/src/helpers/toolAvailability.ts
index f2da694c161..692d93e036c 100644
--- a/src/helpers/toolAvailability.ts
+++ b/src/helpers/toolAvailability.ts
@@ -28,7 +28,7 @@ export const isBuiltinSkillAvailableInCurrentEnv = (
}
return shouldEnableBuiltinSkill(id, {
- isDesktop: context.isDesktop ?? isDesktop,
+ canExecuteOnDevice: context.isDesktop ?? isDesktop,
});
};