π€― 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(skills): discover device skills without a working directory (#23141)
AmAzing-c59946420399
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.tsindex c6e9fab28db..7a1d9115148 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts@@ -105,6 +105,33 @@ vi.mock('@/server/services/agent', () => ({}),}));+vi.mock('@/database/models/agentSkill', () => ({+ AgentSkillModel: vi.fn().mockImplementation(function () {+ return {+ findAll: vi.fn().mockResolvedValue({ data: [], total: 0 }),+ findByIds: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn().mockImplementation(function () {+ return {+ getAgentSkills: vi.fn().mockResolvedValue([]),+ hasDocuments: vi.fn().mockResolvedValue(false),+ };+ }),+}));++vi.mock('@/server/services/userSkill', () => ({+ UserSkillService: vi.fn().mockImplementation(function () {+ return {+ listCatalog: vi.fn().mockResolvedValue([]),+ loadRuntimeSkills: vi.fn().mockResolvedValue([]),+ };+ }),+}));+vi.mock('@/database/models/plugin', () => ({PluginModel: vi.fn().mockImplementation(function () {return {@@ -576,6 +603,69 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', { boundDeviceId: DEVICE_ID });});+ it('lists device skills in a directory-less run without binding a directory or loading project rules', async () => {+ mockGetAgentConfig.mockResolvedValue({+ ...createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),+ // Like project skills, device skills remain discoverable in manual mode.+ chatConfig: { skillActivateMode: 'manual' },+ });+ mockInitWorkspace.mockResolvedValue({+ instructions: [],+ skills: [+ {+ description: 'Device writing guidance',+ name: 'writing',+ path: '/home/user/.agents/skills/writing/SKILL.md',+ scope: 'device',+ },+ ],+ });++ await service.execAgent(topicRunInput());++ const operation = mockCreateOperation.mock.calls[0][0];+ expect(operation.operationSkillSet?.skills).toEqual([+ {+ description: 'Device writing guidance',+ identifier: 'device:writing',+ location: '/home/user/.agents/skills/writing/SKILL.md',+ name: 'writing',+ source: 'device',+ },+ ]);+ expect(operation.deviceSystemInfo?.workingDirectory).toBeUndefined();+ expect(operation.projectInstructions).toBeUndefined();+ expect(mockUpdateDevice).not.toHaveBeenCalled();+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ workingDirectory: expect.anything() }),+ );+ });++ it('continues without device skills when a directory-less device scan is unavailable', async () => {+ mockGetAgentConfig.mockResolvedValue({+ ...createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),+ chatConfig: { skillActivateMode: 'manual' },+ });+ mockInitWorkspace.mockResolvedValue(undefined);++ await service.execAgent(topicRunInput());++ expect(mockInitWorkspace).toHaveBeenCalledOnce();+ const operation = mockCreateOperation.mock.calls[0][0];+ expect(operation.operationSkillSet?.skills).toEqual([]);+ expect(operation.projectInstructions).toBeUndefined();+ expect(operation.deviceSystemInfo?.workingDirectory).toBeUndefined();+ });++ it('does not scan device skills for a cloud-only run', async () => {+ mockGetAgentConfig.mockResolvedValue(createAgentConfig({ executionTarget: 'cloud' }));++ await service.execAgent(topicRunInput());++ expect(mockInitWorkspace).not.toHaveBeenCalled();+ });+it('leaves the topic unbound when neither the agent nor the device has a directory', async () => {mockGetAgentConfig.mockResolvedValue(createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex c3f6d4c2c34..c50658385d5 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -294,7 +294,18 @@ const resolveWorkspaceInit = async (workingDirByDevice: agencyConfig?.workingDirByDevice,});const boundCwd = getWorkingDirEffectivePath(boundCwdConfig);- if (!boundCwd) return { workspace: empty };+ if (!boundCwd) {+ // Device-level skills do not require a project. Do not substitute the+ // device's home or daemon cwd, bind a directory, or cache this result as+ // a workingDirs entry (those entries also authorize file-operation roots).+ if (deviceWaking) return { workspace: empty };+ const scanned = await deviceGateway.initWorkspace({+ deviceId: activeDeviceId,+ userId: deps.userId,+ workspaceId: deviceWorkspaceId,+ });+ return { workspace: scanned ?? empty };+ }const resolved = {boundCwd,boundCwdConfig,@@ -772,11 +783,11 @@ export const prepareOperation = async (};}- // Project skills + AGENTS.md are discovered server-side by scanning the- // device's bound project directory and its parents up to the repository- // root ("workspace init"), cached- // on `devices.workingDirs` and reused within the TTL. Skills surface in- // `<available_skills>` (metadata only β SKILL.md bodies are read lazily at+ // On device runs, workspace init discovers home-directory skills. A bound directory+ // also contributes project skills + AGENTS.md up to the repository root;+ // those combined scans are cached on `devices.workingDirs` within the TTL.+ // Without a bound directory, only home skill directories are scanned.+ // Skills surface in `<available_skills>` (metadata only β SKILL.md bodies are read lazily at// activation via `local-system` readFile, which `serverRuntimes/skills.ts`// re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md// path) flows through; the directory tree is enumerated lazily, keeping thediff --git a/apps/server/src/services/deviceGateway/index.projectFiles.test.ts b/apps/server/src/services/deviceGateway/index.projectFiles.test.tsindex 3b3613c4da2..67194e03315 100644--- a/apps/server/src/services/deviceGateway/index.projectFiles.test.ts+++ b/apps/server/src/services/deviceGateway/index.projectFiles.test.ts@@ -111,6 +111,46 @@ describe('DeviceGateway', () => {);});+ it('supports a device-only scan without inventing a working directory', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: {+ instructions: [],+ skills: [+ {+ description: 'Device writing guidance',+ name: 'writing',+ path: '/home/user/.agents/skills/writing/SKILL.md',+ scope: 'device',+ },+ ],+ },+ success: true,+ });++ const result = await new DeviceGateway().initWorkspace({+ deviceId: 'dev-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(result).toEqual({+ instructions: [],+ skills: [+ {+ description: 'Device writing guidance',+ name: 'writing',+ path: '/home/user/.agents/skills/writing/SKILL.md',+ scope: 'device',+ },+ ],+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1', workspaceId: 'workspace-1' },+ { method: 'initWorkspace', params: { scope: undefined } },+ );+ });+it('defaults instructions and skills to empty arrays when absent', async () => {configure();mockClient.invokeRpc.mockResolvedValue({ data: {}, success: true });diff --git a/apps/server/src/services/deviceGateway/workspace.ts b/apps/server/src/services/deviceGateway/workspace.tsindex 5e552cd1f78..0ff3155b892 100644--- a/apps/server/src/services/deviceGateway/workspace.ts+++ b/apps/server/src/services/deviceGateway/workspace.ts@@ -14,9 +14,9 @@ import type { DeviceClientGetter } from './types';const log = debug('lobe-server:device-gateway');/**- * Scan a bound project directory on the device in a single round-trip:- * project skills (`.agents/skills` + `.claude/skills`) plus the root- * `AGENTS.md` / `CLAUDE.md`. Routed through the generic device RPC relay+ * Discover device skills, optionally including a bound project's skills and+ * `AGENTS.md` / `CLAUDE.md`, in a single round-trip. With no scope, only the+ * device's home skill directories are scanned. Routed through the generic device RPC relay* (`invokeRpc`) β a server-internal channel the agent never sees, distinct* from the LLM-facing tool-call path.*@@ -27,7 +27,7 @@ export async function initWorkspace(getClient: DeviceClientGetter,params: {deviceId: string;- scope: string;+ scope?: string;timeout?: number;userId: string;workspaceId?: string;diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex c220a8c26b9..47b2e9059fa 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -33,8 +33,8 @@ export interface ProjectSkillItem {}export interface InitWorkspaceParams {- /** Working directory used to resolve the project root. */- scope: string;+ /** Working directory; omitted to discover only device-level skills. */+ scope?: string;}export interface WorkspaceInstructionsItem {@@ -46,7 +46,8 @@ export interface WorkspaceInstructionsItem {export interface InitWorkspaceResult {instructions: WorkspaceInstructionsItem[];- root: string;+ /** Absent for a device-only scan; no working directory is selected implicitly. */+ root?: string;skills: ProjectSkillItem[];}diff --git a/packages/device-control/src/workspace.deviceSkills.test.ts b/packages/device-control/src/workspace.deviceSkills.test.tsnew file mode 100644index 00000000000..861da000d1a--- /dev/null+++ b/packages/device-control/src/workspace.deviceSkills.test.ts@@ -0,0 +1,100 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import type * as NodeOs from 'node:os';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { initWorkspace } from './workspace';++let base: string;+let home: string;++vi.mock('node:os', async (importOriginal) => ({+ ...(await importOriginal<typeof NodeOs>()),+ homedir: () => home,+}));++const writeSkill = async (source: string, directory: string, name = directory) => {+ const skillDir = path.join(home, source, 'skills', directory);+ await mkdir(skillDir, { recursive: true });+ await writeFile(+ path.join(skillDir, 'SKILL.md'),+ `---\nname: ${name}\ndescription: ${directory} description\n---\nPrivate skill body`,+ );+ return path.join(skillDir, 'SKILL.md');+};++beforeEach(async () => {+ base = await mkdtemp(path.join(tmpdir(), 'device-skill-scan-'));+ home = path.join(base, 'home');+ await mkdir(home, { recursive: true });+});++afterEach(async () => {+ vi.restoreAllMocks();+ await rm(base, { force: true, recursive: true });+});++describe('initWorkspace without a working directory', () => {+ it('discovers all home skill sources without importing home or process-cwd project rules', async () => {+ const agentsPath = await writeSkill('.agents', 'writing');+ const claudePath = await writeSkill('.claude', 'analysis');+ const codexPath = await writeSkill('.codex', 'review');+ await writeFile(path.join(home, 'AGENTS.md'), 'Unselected home instructions');+ await writeFile(path.join(home, 'CLAUDE.md'), 'Unselected home instructions');+ // Even when the daemon starts inside a repository, it is not the user's+ // selected working directory and must not contribute project context.+ const repo = path.join(base, 'repo');+ await mkdir(path.join(repo, '.git'), { recursive: true });+ await mkdir(path.join(repo, '.agents', 'skills', 'project-only'), { recursive: true });+ await writeFile(path.join(repo, 'AGENTS.md'), 'Unselected project instructions');+ await writeFile(+ path.join(repo, '.agents', 'skills', 'project-only', 'SKILL.md'),+ '---\nname: project-only\n---\nProject skill body',+ );+ vi.spyOn(process, 'cwd').mockReturnValue(repo);+ const approveProjectRoot = vi.fn<(root: string) => Promise<void>>().mockResolvedValue();++ const result = await initWorkspace({}, { approveProjectRoot });++ expect(result.root).toBeUndefined();+ expect(result.instructions).toEqual([]);+ expect(result.skills.map(({ name, path, scope }) => ({ name, path, scope }))).toEqual([+ { name: 'analysis', path: claudePath, scope: 'device' },+ { name: 'review', path: codexPath, scope: 'device' },+ { name: 'writing', path: agentsPath, scope: 'device' },+ ]);+ expect(JSON.stringify(result)).not.toContain('Private skill body');+ expect(approveProjectRoot.mock.calls.map(([root]) => root).sort()).toEqual(+ ['.agents', '.claude', '.codex'].map((source) => path.join(home, source, 'skills')).sort(),+ );+ });++ it('keeps the existing source priority when device skills share a name', async () => {+ const preferred = await writeSkill('.agents', 'primary', 'shared');+ await writeSkill('.claude', 'secondary', 'shared');+ await writeSkill('.codex', 'last', 'shared');++ const result = await initWorkspace({});++ expect(result.skills).toHaveLength(1);+ expect(result.skills[0]).toMatchObject({+ description: 'primary description',+ name: 'shared',+ path: preferred,+ scope: 'device',+ });+ });++ it('returns an empty unbound scan when no device skills are installed', async () => {+ const approveProjectRoot = vi.fn<(root: string) => Promise<void>>().mockResolvedValue();++ const result = await initWorkspace({}, { approveProjectRoot });++ expect(result.instructions).toEqual([]);+ expect(result.skills).toEqual([]);+ expect(result.root).toBeUndefined();+ expect(approveProjectRoot).not.toHaveBeenCalled();+ });+});diff --git a/packages/device-control/src/workspace.ts b/packages/device-control/src/workspace.tsindex d361ff99bd5..469a333c1ec 100644--- a/packages/device-control/src/workspace.ts+++ b/packages/device-control/src/workspace.ts@@ -339,8 +339,10 @@ export const listProjectSkills = async (/*** One-call "workspace init" scan: merge project and execution-device skills* (deduped by name, project winning) and read the agent instructions from the- * working directory up to the repository root. Approves the project root regardless of what was found, since- * the run is now bound to this root.+ * working directory up to the repository root. Without a working directory,+ * discover only home-directory skills: neither the daemon's cwd nor the home+ * directory becomes an implicit project or supplies project instructions.+ * Approves the selected project root and discovered skill preview roots.*/export const initWorkspace = async (params: InitWorkspaceParams,@@ -348,14 +350,14 @@ export const initWorkspace = async (): Promise<InitWorkspaceResult> => {const root = params.scope;- const dirs = await resolveAgentFileDirs(root);+ const dirs = root ? await resolveAgentFileDirs(root) : [];const skills = await collectSkills([- ...createProjectSkillRoots(root, dirs),+ ...(root ? createProjectSkillRoots(root, dirs) : []),...createDeviceSkillRoots(),]);const instructions = await readWorkspaceInstructions(dirs);- await approvePreviewRoots(skills, deps, [root]);+ await approvePreviewRoots(skills, deps, root ? [root] : []);return { instructions, root, skills };};diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 48858f73a78..a315c1368e1 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -804,8 +804,8 @@ export interface ListProjectSkillsResult {}export interface InitWorkspaceParams {- /** Working directory used to resolve the project root. */- scope: string;+ /** Working directory; omitted to discover only device-level skills. */+ scope?: string;}/**@@ -828,6 +828,7 @@ export interface WorkspaceInstructionsItem {*/export interface InitWorkspaceResult {instructions: WorkspaceInstructionsItem[];- root: string;+ /** Absent for a device-only scan; no working directory is selected implicitly. */+ root?: string;skills: ProjectSkillItem[];}