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(skills): restore device execution branch for execScript in gateway mode (#16807)

YuTengjing25e5307d9611
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.md
index b17b66b2179..ccfa2ab8332 100644
--- a/.agents/skills/agent-tracing/SKILL.md
+++ b/.agents/skills/agent-tracing/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-tracing
-description: 'Agent tracing CLI for execution snapshots. Use for agent-tracing, traces, snapshots, LLM call inspection, context engine data, agent step analysis, execution debugging, or pulling remote/production traces ("ζ‹‰ηΊΏδΈŠ tracing") by operation id.'
+description: 'Agent tracing CLI for execution snapshots. Use for agent-tracing, traces, snapshots, LLM call inspection, context engine data, agent step analysis, execution debugging, or pulling remote/production traces ("ζ‹‰ηΊΏδΈŠ tracing") by operation id. Also the first stop for debugging agent tool calls β€” wrong or missing tool_calls, unexpected tool arguments or results, which tools were available at a step, or why a tool ran where it did.'
user-invocable: false
---
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index cb045095610..16084c15dc7 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -384,6 +384,9 @@ export default class GatewayConnectionCtr extends ControllerModule {
getLocalFilePreview: (params) => this.localFileCtr.getLocalFilePreview(params),
getProjectFileIndex: (params) => this.localFileCtr.getProjectFileIndex(params),
searchProjectFiles: (params) => this.localFileCtr.searchProjectFiles(params),
+ // Skill-archive cache (`prepareSkillDirectory` RPC): reuse LocalFileCtr's
+ // deps so gateway-prepared skills share one cache with the renderer-IPC path.
+ ...this.localFileCtr.getSkillDirectoryDeps(),
};
}
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index bf076433a53..30f03972982 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -1,8 +1,12 @@
import { constants } from 'node:fs';
-import { access, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
+import { access, readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
-import { defaultSearchProjectFiles } from '@lobechat/device-control';
+import {
+ defaultSearchProjectFiles,
+ prepareSkillDirectory,
+ type SkillDirectoryDeps,
+} from '@lobechat/device-control';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
@@ -55,7 +59,6 @@ import {
} from '@lobechat/local-file-shell';
import { dialog, shell } from 'electron';
import { execa } from 'execa';
-import { unzipSync } from 'fflate';
import ContentSearchService from '@/services/contentSearchSrv';
import FileSearchService from '@/services/fileSearchSrv';
@@ -494,66 +497,25 @@ export default class LocalFileCtr extends ControllerModule {
}
}
- @IpcMethod()
- async handlePrepareSkillDirectory({
- forceRefresh,
- url,
- zipHash,
- }: PrepareSkillDirectoryParams): Promise<PrepareSkillDirectoryResult> {
- const cacheRoot = path.join(this.app.appStoragePath, 'file-storage', 'skills');
- const extractedDir = path.join(cacheRoot, 'extracted', zipHash);
- const markerPath = path.join(extractedDir, '.prepared');
- const zipPath = path.join(cacheRoot, 'archives', `${zipHash}.zip`);
-
- try {
- if (!forceRefresh) {
- await access(markerPath, constants.F_OK);
- return { extractedDir, success: true, zipPath };
- }
- } catch {
- // Cache miss, continue preparing the local copy.
- }
-
- try {
- const response = await netFetch(url);
- if (!response.ok) {
- throw new Error(
- `Failed to download skill package: ${response.status} ${response.statusText}`,
- );
- }
-
- const buffer = Buffer.from(await response.arrayBuffer());
- const extractedFiles = unzipSync(new Uint8Array(buffer));
-
- await rm(extractedDir, { force: true, recursive: true });
- await mkdir(path.dirname(zipPath), { recursive: true });
- await mkdir(extractedDir, { recursive: true });
- await writeFile(zipPath, buffer);
-
- for (const [relativePath, fileContent] of Object.entries(extractedFiles)) {
- if (relativePath.endsWith('/')) continue;
-
- const targetPath = path.resolve(extractedDir, relativePath);
- const normalizedRoot = `${path.resolve(extractedDir)}${path.sep}`;
- if (targetPath !== path.resolve(extractedDir) && !targetPath.startsWith(normalizedRoot)) {
- throw new Error(`Unsafe file path in skill archive: ${relativePath}`);
- }
-
- await mkdir(path.dirname(targetPath), { recursive: true });
- await writeFile(targetPath, Buffer.from(fileContent as Uint8Array));
- }
-
- await writeFile(markerPath, JSON.stringify({ preparedAt: Date.now(), url, zipHash }), 'utf8');
+ /**
+ * Host deps for the shared skill-archive cache: this keeps the renderer-IPC
+ * path (here) and the gateway RPC path (`GatewayConnectionCtr` β†’
+ * `@lobechat/device-control`) on ONE cache directory and one proxy-aware
+ * fetch, so a skill prepared by either entry point is a cache hit for the
+ * other.
+ */
+ getSkillDirectoryDeps(): SkillDirectoryDeps {
+ return {
+ fetchSkillArchive: netFetch,
+ skillCacheRoot: path.join(this.app.appStoragePath, 'file-storage', 'skills'),
+ };
+ }
- return { extractedDir, success: true, zipPath };
- } catch (error) {
- return {
- error: (error as Error).message,
- extractedDir,
- success: false,
- zipPath,
- };
- }
+ @IpcMethod()
+ async handlePrepareSkillDirectory(
+ params: PrepareSkillDirectoryParams,
+ ): Promise<PrepareSkillDirectoryResult> {
+ return prepareSkillDirectory(params, this.getSkillDirectoryDeps());
}
@IpcMethod()
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 7e067490762..c6249e99fb7 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -520,14 +520,20 @@ describe('LocalFileCtr', () => {
'/mock/app/storage/file-storage/skills/archives/zip-hash-123.zip',
expect.any(Buffer),
);
+ // Extraction goes into a staging dir that is swapped in via rename so
+ // the live cache path never exposes a partially written tree.
expect(mockFsPromises.writeFile).toHaveBeenCalledWith(
- '/mock/app/storage/file-storage/skills/extracted/zip-hash-123/SKILL.md',
+ '/mock/app/storage/file-storage/skills/extracted/.staging-zip-hash-123/SKILL.md',
expect.any(Buffer),
);
expect(mockFsPromises.writeFile).toHaveBeenCalledWith(
- '/mock/app/storage/file-storage/skills/extracted/zip-hash-123/docs/reference.txt',
+ '/mock/app/storage/file-storage/skills/extracted/.staging-zip-hash-123/docs/reference.txt',
expect.any(Buffer),
);
+ expect(mockFsPromises.rename).toHaveBeenCalledWith(
+ '/mock/app/storage/file-storage/skills/extracted/.staging-zip-hash-123',
+ '/mock/app/storage/file-storage/skills/extracted/zip-hash-123',
+ );
});
it('should reuse the cached extracted directory when it is already prepared', async () => {
diff --git a/apps/desktop/vitest.config.mts b/apps/desktop/vitest.config.mts
index 2bee4129129..1f96271a558 100644
--- a/apps/desktop/vitest.config.mts
+++ b/apps/desktop/vitest.config.mts
@@ -1,4 +1,5 @@
import { resolve } from 'node:path';
+
import { defineConfig } from 'vitest/config';
export default defineConfig({
@@ -11,6 +12,9 @@ export default defineConfig({
__dirname,
'../../packages/device-control/src/workspace',
),
+ // Not hoisted to the (super)project root node_modules, so resolve it to
+ // workspace source like the packages above.
+ '@lobechat/device-identity': resolve(__dirname, '../../packages/device-identity/src'),
'@lobechat/local-file-shell': resolve(__dirname, '../../packages/local-file-shell/src'),
},
coverage: {
diff --git a/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
new file mode 100644
index 00000000000..ca28543e55c
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveRunActiveDeviceId } from '../resolveRunActiveDeviceId';
+
+describe('resolveRunActiveDeviceId', () => {
+ it('passes the id through when the plan routed a device', () => {
+ expect(
+ resolveRunActiveDeviceId({
+ activeDeviceId: 'device-1',
+ executionPlan: { deviceId: 'device-1', kind: 'device' },
+ }),
+ ).toBe('device-1');
+ });
+
+ // Mid-run device activation: the model selects a device via the
+ // lobe-remote-device tool while the run-start plan still says unrouted β€”
+ // the folded-back id must survive the gate.
+ it('passes a mid-run activated id through under a device-unrouted plan', () => {
+ expect(
+ resolveRunActiveDeviceId({
+ activeDeviceId: 'device-1',
+ executionPlan: { kind: 'device-unrouted', reason: 'no-bound-device' },
+ }),
+ ).toBe('device-1');
+ });
+
+ it('swallows a preset/stale id when the plan is not device-capable', () => {
+ for (const kind of ['sandbox', 'none']) {
+ expect(
+ resolveRunActiveDeviceId({
+ activeDeviceId: 'device-1',
+ executionPlan: { kind },
+ }),
+ ).toBeUndefined();
+ }
+ });
+
+ it('swallows the id when the device access policy denies the sender', () => {
+ expect(
+ resolveRunActiveDeviceId({
+ activeDeviceId: 'device-1',
+ deviceAccessPolicy: { canUseDevice: false, reason: 'external-bot' },
+ executionPlan: { deviceId: 'device-1', kind: 'device' },
+ }),
+ ).toBeUndefined();
+ });
+
+ it('falls back to the policy-only gate when no plan exists (old/resumed operations)', () => {
+ expect(resolveRunActiveDeviceId({ activeDeviceId: 'device-1' })).toBe('device-1');
+ expect(resolveRunActiveDeviceId(undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index c2e15993a8c..0effa62564c 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -72,11 +72,9 @@ import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import { fileEnv } from '@/envs/file';
-import { type ExecutionPlan, isDeviceCapablePlan } from '@/helpers/executionTarget';
import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
-import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import { OnboardingService } from '@/server/services/onboarding';
@@ -101,6 +99,7 @@ import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';
export const callLlm =
(ctx: RuntimeExecutorContext): InstructionExecutor =>
@@ -118,20 +117,10 @@ export const callLlm =
//
// Single-track device gate: `buildStepToolDelta` treats activeDeviceId as
// an independent activation signal (it only dedupes against already-
- // enabled tools), so any id that reaches it WILL inject local-system. The
- // execution plan is the only authority on whether this session may touch
- // a device β€” swallow the id for non-device-capable plans (`none`,
- // `sandbox`) and for denied senders, even if `state.metadata.activeDeviceId`
- // was populated by a bug or a mid-run side effect. Plans absent on old /
- // resumed operations fall back to the policy-only gate.
- const devicePolicy = state.metadata?.deviceAccessPolicy as
- { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
- const executionPlan = state.metadata?.executionPlan as ExecutionPlan | undefined;
- const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
- const activeDeviceId =
- devicePolicy?.canUseDevice === false || !planAllowsDevice
- ? undefined
- : state.metadata?.activeDeviceId;
+ // enabled tools), so any id that reaches it WILL inject local-system.
+ // `resolveRunActiveDeviceId` swallows the id whenever the plan/policy
+ // forbids devices β€” the same filter the tool executors apply.
+ const activeDeviceId = resolveRunActiveDeviceId(state.metadata);
const operationToolSet: OperationToolSet = state.operationToolSet ?? {
enabledToolIds: [],
executorMap: state.toolExecutorMap ?? {},
diff --git a/apps/server/src/modules/AgentRuntime/executors/callTool.ts b/apps/server/src/modules/AgentRuntime/executors/callTool.ts
index 3696707dcf8..4d1b629a00f 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callTool.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callTool.ts
@@ -1,6 +1,7 @@
import {
type AgentEvent,
type AgentInstruction,
+ extractActivatedSkillsFromMessages,
type InstructionExecutor,
UsageCounter,
} from '@lobechat/agent-runtime';
@@ -43,6 +44,8 @@ import {
markPersistFatal,
} from '../messagePersistErrors';
import { resolveToolTimeoutMs } from '../resolveToolTimeout';
+import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';
+import { resolveRunProjectSkills } from './resolveRunProjectSkills';
export const callTool =
(ctx: RuntimeExecutorContext): InstructionExecutor =>
@@ -260,7 +263,16 @@ export const callTool =
execution = await executeToolWithRetry(
() =>
toolExecutionService.executeTool(chatToolPayload, {
- activeDeviceId: state.metadata?.activeDeviceId,
+ // Server-side equivalent of the client transport's
+ // computeStepContext: state.messages carries the DB rows
+ // (pluginState included), so skills execScript can resolve the
+ // activated skill archives. Without this the device/sandbox
+ // skill preparation silently runs with zero skills.
+ activatedSkills: extractActivatedSkillsFromMessages(state.messages),
+ // Plan/policy-filtered: a preset or stale metadata id must not route
+ // tool execution (e.g. skills execScript) onto a device the resolved
+ // plan didn't authorize.
+ activeDeviceId: resolveRunActiveDeviceId(state.metadata),
agentId: toolCallAgentId,
agentMember: buildServerAgentMemberRunner(
ctx,
@@ -283,16 +295,7 @@ export const callTool =
memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
operationId,
- projectSkills: (state.metadata?.operationSkillSet?.skills ?? [])
- .filter(
- (skill: { location?: string; source?: string }) =>
- (skill.source === 'project' || skill.source === 'device') && !!skill.location,
- )
- .map((skill: { location: string; name: string; source?: string }) => ({
- location: skill.location,
- name: skill.name,
- source: skill.source === 'device' ? 'device' : 'project',
- })),
+ projectSkills: resolveRunProjectSkills(state.metadata),
scope: state.metadata?.scope,
serverDB: ctx.serverDB,
skipResultTruncation: true,
@@ -473,8 +476,14 @@ export const callTool =
const newState = structuredClone(state);
+ // Keep plugin/pluginState on the in-state copy: the batch executor
+ // refreshes state.messages from full DB rows, but this single-tool path
+ // never does β€” without these fields a later step could not extract the
+ // skill activation this call just produced (activatedSkills above).
newState.messages.push({
content: executionResult.content,
+ plugin: chatToolPayload,
+ pluginState: executionResult.state,
role: 'tool',
tool_call_id: chatToolPayload.id,
});
diff --git a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
index d676a35872e..8ccda3fdb80 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts
@@ -1,6 +1,7 @@
import {
type AgentEvent,
type AgentInstruction,
+ extractActivatedSkillsFromMessages,
type InstructionExecutor,
UsageCounter,
} from '@lobechat/agent-runtime';
@@ -44,6 +45,8 @@ import {
markPersistFatal,
} from '../messagePersistErrors';
import { resolveToolTimeoutMs } from '../resolveToolTimeout';
+import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';
+import { resolveRunProjectSkills } from './resolveRunProjectSkills';
export const callToolsBatch =
(ctx: RuntimeExecutorContext): InstructionExecutor =>
@@ -114,6 +117,11 @@ export const callToolsBatch =
// Execute server tools concurrently (skip client tools in mixed batch)
const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;
+ // Server-side equivalent of the client transport's computeStepContext
+ // (mirrors the single-tool `callTool` context): skills execScript resolves
+ // activated skill archives from the message history, which the raw LLM
+ // args never carry. Computed once β€” identical for every tool in the batch.
+ const runActivatedSkills = extractActivatedSkillsFromMessages(state.messages);
await Promise.all(
toolsToExecute.map(async (chatToolPayload: ChatToolPayload) => {
const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;
@@ -259,7 +267,11 @@ export const callToolsBatch =
execution = await executeToolWithRetry(
() =>
toolExecutionService.executeTool(chatToolPayload, {
- activeDeviceId: state.metadata?.activeDeviceId,
+ activatedSkills: runActivatedSkills,
+ // Plan/policy-filtered: a preset or stale metadata id must not route
+ // tool execution (e.g. skills execScript) onto a device the resolved
+ // plan didn't authorize.
+ activeDeviceId: resolveRunActiveDeviceId(state.metadata),
agentId: state.metadata?.agentId,
agentMember: buildServerAgentMemberRunner(
ctx,
@@ -280,6 +292,10 @@ export const callToolsBatch =
memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
messageId: state.metadata?.sourceMessageId,
operationId,
+ // Mirrors the single-tool `callTool` context: without these
+ // a batched device execScript loses the SKILL.md / selected
+ // working directory and runs from the daemon's default cwd.
+ projectSkills: resolveRunProjectSkills(state.metadata),
scope: state.metadata?.scope,
serverDB: ctx.serverDB,
skipResultTruncation: true,
@@ -296,6 +312,10 @@ export const callToolsBatch =
toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,
topicId: ctx.topicId,
userId: ctx.userId,
+ // Device-bound cwd folded into deviceSystemInfo at operation
+ // creation; resume-safe via computeDeviceContext (recovers it
+ // from the prior tool message's pluginState.metadata).
+ workingDirectory: state.metadata?.deviceSystemInfo?.workingDirectory,
workspaceId: state.metadata?.workspaceId ?? ctx.workspaceId,
}),
{
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
new file mode 100644
index 00000000000..e297dcb034d
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
@@ -0,0 +1,35 @@
+import { type ExecutionPlan, isDeviceCapablePlan } from '@/helpers/executionTarget';
+import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
+
+/**
+ * Single-track device gate shared by the run executors: the execution plan
+ * (and the device access policy) is the only authority on whether this run
+ * may touch a device. `metadata.activeDeviceId` alone is NOT sufficient β€” a
+ * mid-run side effect can leave it stale β€” so every consumer (LLM tool
+ * injection in `callLlm`, tool execution contexts in `callTool` /
+ * `callToolsBatch`) must read the id through this filter. Plans absent on
+ * old / resumed operations fall back to the policy-only gate.
+ *
+ * `device-unrouted` deliberately passes the id through (via
+ * `isDeviceCapablePlan`): the run-start id is derived strictly from the plan
+ * (`aiAgent` sets it only for `kind === 'device'`), so an id appearing under
+ * a `device-unrouted` plan can only come from a legitimate mid-run activation
+ * β€” the model selecting a device with the `lobe-remote-device` tool, whose
+ * pluginState `computeDeviceContext` folds back into the metadata at the next
+ * step boundary while the plan still says unrouted. Tightening the gate to
+ * `kind === 'device'` would swallow exactly that flow.
+ */
+export const resolveRunActiveDeviceId = (metadata?: {
+ activeDeviceId?: string;
+ deviceAccessPolicy?: unknown;
+ executionPlan?: unknown;
+}): string | undefined => {
+ const devicePolicy = metadata?.deviceAccessPolicy as
+ { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
+ const executionPlan = metadata?.executionPlan as ExecutionPlan | undefined;
+ const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
+
+ if (devicePolicy?.canUseDevice === false || !planAllowsDevice) return undefined;
+
+ return metadata?.activeDeviceId;
+};
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts
new file mode 100644
index 00000000000..2ae0b46c1f6
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts
@@ -0,0 +1,19 @@
+/**
+ * Project/device filesystem skills (SKILL.md on the execution device) from the
+ * operation's skill set, shaped for the tool-execution context. Shared by
+ * `callTool` and `callToolsBatch` so batched device `execScript` calls resolve
+ * the same SKILL.md cwd as single calls β€” an unshared copy is exactly how the
+ * batch path silently dropped these fields once already.
+ */
+export const resolveRunProjectSkills = (metadata?: {
+ operationSkillSet?: { skills?: { location?: string; name: string; source?: string }[] };
+}): { location: string; name: string; source: 'device' | 'project' }[] =>
+ (metadata?.operationSkillSet?.skills ?? [])
+ .filter(
+ (skill) => (skill.source === 'project' || skill.source === 'device') && !!skill.location,
+ )
+ .map((skill) => ({
+ location: skill.location as string,
+ name: skill.name,
+ source: skill.source === 'device' ? ('device' as const) : ('project' as const),
+ }));
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 9287e9008fb..75d72154820 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -203,6 +203,50 @@ export class DeviceGateway {
}
}
+ /**
+ * Prepare a skill archive on the device: download the presigned zip and
+ * extract it into the device-local cache (idempotent by `zipHash`). Runs on
+ * the generic device RPC relay like `initWorkspace`, but unlike the
+ * read-oriented helpers, failures are RETURNED with their reason instead of
+ * collapsing to `undefined` β€” the skills exec path must tell the model why
+ * the device can't run the skill (offline, outdated client, download
+ * failure) rather than silently degrading to the sandbox.
+ */
+ async prepareSkillDirectory(params: {
+ deviceId: string;
+ forceRefresh?: boolean;
+ timeout?: number;
+ url: string;
+ userId: string;
+ workspaceId?: string;
+ zipHash: string;
+ }): Promise<{ error?: string; extractedDir?: string; success: boolean }> {
+ const { deviceId, forceRefresh, timeout = 60_000, url, userId, workspaceId, zipHash } = params;
+ const client = this.getClient();
+ if (!client) return { error: 'Device Gateway is not configured', success: false };
+
+ try {
+ const result = await client.invokeRpc<{
+ error?: string;
+ extractedDir: string;
+ success: boolean;
+ }>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'prepareSkillDirectory', params: { forceRefresh, url, zipHash } },
+ );
+
+ if (!result.success || !result.data) {
+ return { error: result.error || 'prepareSkillDirectory failed', success: false };
+ }
+
+ return result.data;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log('prepareSkillDirectory: error for deviceId=%s β€” %s', deviceId, message);
+ return { error: message, success: false };
+ }
+ }
+
/**
* Generic helper for the granular git read RPCs (branch / PR / working-tree /
* ahead-behind). Returns `undefined` when the gateway is unconfigured, the
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 47bbba30a81..ed05e86c847 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => {
return {
checkHash: vi.fn(),
createSandboxService: vi.fn(() => sandboxService),
+ executeToolCall: vi.fn(),
fileService: {
getFullFileUrl: vi.fn(),
},
@@ -28,6 +29,7 @@ const mocks = vi.hoisted(() => {
getAgentSkills: vi.fn(),
getUserSettings: vi.fn(),
marketService: {},
+ prepareSkillDirectory: vi.fn(),
readResource: vi.fn(),
sandboxService,
};
@@ -90,6 +92,17 @@ vi.mock('@/server/services/skill/resource', () => ({
})),
}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ executeToolCall: mocks.executeToolCall,
+ prepareSkillDirectory: mocks.prepareSkillDirectory,
+ },
+}));
+
+vi.mock('../resolveWorkspaceScope', () => ({
+ resolveRunWorkspaceId: vi.fn(async () => undefined),
+}));
+
describe('skillsRuntime', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -156,6 +169,547 @@ describe('skillsRuntime', () => {
);
});
+ it('tags sandbox exec results with executionEnv for plugin-state observability', async () => {
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [],
+ command: 'echo hi',
+ description: 'plain command',
+ });
+
+ expect(result.state).toMatchObject({ executionEnv: 'sandbox' });
+ });
+
+ // Regression guard for the server/gateway migration: when the execution plan
+ // routed a device (activeDeviceId present), execScript must run ON the device
+ // β€” prepare the skill archives via the prepareSkillDirectory RPC and execute
+ // through local-system over the gateway β€” never in the cloud sandbox.
+ describe('device execution branch', () => {
+ it('prepares archives on the device and runs the command with cwd = extracted dir', async () => {
+ mocks.prepareSkillDirectory.mockResolvedValue({
+ extractedDir: '/home/user/.lobehub/skills/extracted/zip-hash-1',
+ success: true,
+ });
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [{ id: 'user-skill-id', name: 'user-skill' }],
+ command: 'python scripts/run.py',
+ description: 'Run skill script',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({ executionEnv: 'device' });
+ expect(mocks.prepareSkillDirectory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ deviceId: 'device-1',
+ url: 'https://files.example.com/user-skill.zip',
+ userId: 'user-1',
+ zipHash: 'zip-hash-1',
+ }),
+ );
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-1', userId: 'user-1' }),
+ expect.objectContaining({
+ apiName: 'runCommand',
+ arguments: JSON.stringify({
+ command: 'python scripts/run.py',
+ cwd: '/home/user/.lobehub/skills/extracted/zip-hash-1',
+ }),
+ identifier: 'lobe-local-system',
+ }),
+ undefined,
+ );
+ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('fails explicitly (no sandbox fallback) when the device cannot prepare a skill', async () => {
+ mocks.prepareSkillDirectory.mockResolvedValue({
+ error: 'Failed to download skill archive: 404 Not Found',
+ success: false,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [{ id: 'user-skill-id', name: 'user-skill' }],
+ command: 'python scripts/run.py',
+ description: 'Run skill script',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('404 Not Found');
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();
+ });
+
+ // Version-skew window: an old client build replies with the dispatcher's
+ // deterministic unknown-method error β€” the ONE prepare failure that falls
+ // back to the sandbox, with an explicit disclosure note for the model.
+ it('falls back to the sandbox (with a disclosure note) when the client predates the RPC', async () => {
+ mocks.prepareSkillDirectory.mockResolvedValue({
+ error: 'Unknown device RPC method: prepareSkillDirectory',
+ success: false,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [{ id: 'user-skill-id', name: 'user-skill' }],
+ command: 'python scripts/run.py',
+ description: 'Run skill script',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({ executionEnv: 'sandbox' });
+ expect(result.content).toContain('update their LobeHub app');
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(
+ 'execScript',
+ expect.objectContaining({ command: 'python scripts/run.py' }),
+ );
+ });
+
+ it('runs without a skill dir (workingDirectory cwd) when no archive exists', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workingDirectory: '/Users/me/project',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [{ id: 'builtin-skill-id', name: 'builtin-skill' }],
+ command: 'echo hi',
+ description: 'no archive',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.prepareSkillDirectory).not.toHaveBeenCalled();
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ arguments: JSON.stringify({ command: 'echo hi', cwd: '/Users/me/project' }),
+ }),
+ undefined,
+ );
+ });
+
+ // Filesystem (project/device) skills have no DB archive β€” their SKILL.md
+ // directory on the device is the cwd, and the last activated skill wins
+ // over earlier archive-backed ones.
+ it('uses the project skill directory as cwd, winning over earlier archives', async () => {
+ mocks.prepareSkillDirectory.mockResolvedValue({
+ extractedDir: '/home/user/.lobehub/skills/extracted/zip-hash-1',
+ success: true,
+ });
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ projectSkills: [
+ { location: '/ws/.agents/skills/foo/SKILL.md', name: 'foo', source: 'project' },
+ ],
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [
+ { id: 'user-skill-id', name: 'user-skill' },
+ // Filesystem activations carry no DB id β€” matching is by name only.
+ { name: 'foo' },
+ ],
+ command: 'python scripts/run.py',
+ description: 'Run project skill script',
+ });
+
+ expect(result.success).toBe(true);
+ // The archive-backed skill is still prepared (activated earlier)...
+ expect(mocks.prepareSkillDirectory).toHaveBeenCalledTimes(1);
+ // ...but the project skill activated last wins the cwd.
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ arguments: JSON.stringify({
+ command: 'python scripts/run.py',
+ cwd: '/ws/.agents/skills/foo',
+ }),
+ }),
+ undefined,
+ );
+ });
+
+ // Archive prepares are full device-gateway round-trips and activatedSkills
+ // accumulates over the conversation β€” they must fire concurrently, while
+ // the activation-order semantics (last resolvable wins the cwd) stay
+ // intact.
+ it('fires archive prepares concurrently and the last resolvable skill wins the cwd', async () => {
+ mocks.findByName.mockImplementation(async (name: string) => {
+ if (name === 'skill-a') return { id: 'a-id', name: 'skill-a', zipFileHash: 'hash-a' };
+ if (name === 'skill-b') return { id: 'b-id', name: 'skill-b', zipFileHash: 'hash-b' };
+ return undefined;
+ });
+ mocks.checkHash.mockImplementation(async (hash: string) => ({
+ isExist: true,
+ url: `skills/${hash}.zip`,
+ }));
+ mocks.fileService.getFullFileUrl.mockImplementation(
+ async (url: string) => `https://files.example.com/${url}`,
+ );
+
+ // Hold both prepares pending to prove the second RPC fires before the
+ // first resolves (a sequential await chain would deadlock this test).
+ const resolvers: ((value: { extractedDir: string; success: boolean }) => void)[] = [];
+ mocks.prepareSkillDirectory.mockImplementation(
+ () => new Promise((resolve) => resolvers.push(resolve)),
+ );
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const pending = runtime.execScript({
+ activatedSkills: [
+ { id: 'a-id', name: 'skill-a' },
+ { id: 'b-id', name: 'skill-b' },
+ ],
+ command: 'python scripts/run.py',
+ description: 'multi skill',
+ });
+
+ await vi.waitFor(() => expect(mocks.prepareSkillDirectory).toHaveBeenCalledTimes(2));
+ resolvers[0]({ extractedDir: '/dev/extracted/hash-a', success: true });
+ resolvers[1]({ extractedDir: '/dev/extracted/hash-b', success: true });
+
+ const result = await pending;
+ expect(result.success).toBe(true);
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ arguments: JSON.stringify({
+ command: 'python scripts/run.py',
+ cwd: '/dev/extracted/hash-b',
+ }),
+ }),
+ undefined,
+ );
+ });
+
+ // With concurrent prepares, error reporting must still follow activation
+ // order: the FIRST failing skill is the one surfaced, regardless of which
+ // RPC settles first.
+ it('reports the first failing skill in activation order despite concurrent prepares', async () => {
+ mocks.findByName.mockImplementation(async (name: string) => {
+ if (name === 'skill-a') return { id: 'a-id', name: 'skill-a', zipFileHash: 'hash-a' };
+ if (name === 'skill-b') return { id: 'b-id', name: 'skill-b', zipFileHash: 'hash-b' };
+ return undefined;
+ });
+ mocks.checkHash.mockImplementation(async (hash: string) => ({
+ isExist: true,
+ url: `skills/${hash}.zip`,
+ }));
+ mocks.fileService.getFullFileUrl.mockImplementation(
+ async (url: string) => `https://files.example.com/${url}`,
+ );
+ mocks.prepareSkillDirectory.mockImplementation(async ({ zipHash }: { zipHash: string }) =>
+ zipHash === 'hash-a'
+ ? { error: 'Failed to download skill archive: 404 Not Found', success: false }
+ : { extractedDir: '/dev/extracted/hash-b', success: true },
+ );
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [
+ { id: 'a-id', name: 'skill-a' },
+ { id: 'b-id', name: 'skill-b' },
+ ],
+ command: 'python scripts/run.py',
+ description: 'multi skill',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('skill-a');
+ expect(result.content).toContain('404 Not Found');
+ expect(mocks.executeToolCall).not.toHaveBeenCalled();
+ expect(mocks.sandboxService.callTool).not.toHaveBeenCalled();
+ });
+
+ // A command that outlives the shell observation window comes back with no
+ // exitCode β€” it must surface as still running (with a pollable shell_id),
+ // not as a successful completion.
+ it('reports a still-running command instead of pretending completion', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'Command is still running after the wait window.',
+ state: { commandId: 'shell-9', stdout: '', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [],
+ command: 'sleep 600',
+ description: 'long script',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({ executionEnv: 'device', shellId: 'shell-9' });
+ expect(result.state).not.toHaveProperty('exitCode', 0);
+ expect(result.content).toContain('still running');
+ expect(result.content).toContain('shell-9');
+ expect(result.content).not.toContain('completed successfully');
+ });
+
+ // The device ComputerRuntime reports service failures (spawn error, shell
+ // lost) with a delivered envelope: `success: true`, `state.success:
+ // false`, and no exitCode β€” they must surface as failures, not as a
+ // still-running command.
+ it('reports failure when the device service fails without an exit code', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'spawn ENOENT',
+ state: { error: 'spawn ENOENT', isBackground: false, success: false },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [],
+ command: 'python scripts/run.py',
+ description: 'spawn failure',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('spawn ENOENT');
+ expect(result.content).not.toContain('still running');
+ });
+
+ // The device shell observation reports success: true for any delivered
+ // observation β€” the actual exit status only lives in exitCode.
+ it('reports failure when the script exits non-zero despite a successful observation', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: '',
+ state: { exitCode: 2, stderr: 'boom', stdout: '', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [],
+ command: 'exit 2',
+ description: 'failing script',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.state).toMatchObject({ executionEnv: 'device', exitCode: 2 });
+ expect(result.content).toContain('boom');
+ });
+
+ it('forwards executionTimeoutMs as the shell observation timeout in the runCommand args', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'ok',
+ state: { exitCode: 0, stdout: 'ok', success: true },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ executionTimeoutMs: 300_000,
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ await runtime.execScript({
+ activatedSkills: [],
+ command: 'sleep 60',
+ description: 'long script',
+ });
+
+ expect(mocks.executeToolCall).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ arguments: JSON.stringify({ command: 'sleep 60', timeout: 300_000 }),
+ }),
+ 300_000,
+ );
+ });
+
+ // Large streams are truncated to a preview device-side with the full
+ // output saved to disk β€” dropping state.outputFiles would lose the only
+ // retrieval path for the truncated output.
+ it('carries saved-output file paths through for truncated device output', async () => {
+ mocks.executeToolCall.mockResolvedValue({
+ content: 'preview…',
+ state: {
+ exitCode: 0,
+ outputFiles: {
+ stdout: {
+ path: '/tmp/lobe-shell/shell-1.stdout.log',
+ size: 5_242_880,
+ truncated: true,
+ },
+ },
+ stdout: 'preview…',
+ success: true,
+ },
+ success: true,
+ });
+
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.execScript({
+ activatedSkills: [],
+ command: 'cat big.log',
+ description: 'noisy script',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('/tmp/lobe-shell/shell-1.stdout.log');
+ expect(result.state).toMatchObject({
+ outputFiles: { stdout: expect.objectContaining({ truncated: true }) },
+ });
+ });
+
+ // The device manifest hides the sandbox-only APIs, but the builtin
+ // executor dispatches any method on the runtime regardless of the
+ // manifest β€” a prompt-following or hallucinated call must be refused at
+ // execution time, not silently run in the sandbox.
+ it('refuses the sandbox runCommand while a device is routed', async () => {
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.runCommand({ command: 'ls' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('lobe-local-system');
+ expect(mocks.createSandboxService).not.toHaveBeenCalled();
+ });
+
+ it('refuses the sandbox exportFile while a device is routed', async () => {
+ const { skillsRuntime } = await import('../skills');
+ const runtime = await skillsRuntime.factory({
+ activeDeviceId: 'device-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.exportFile({ filename: 'out.csv', path: '/tmp/out.csv' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain("already on the user's machine");
+ expect(mocks.sandboxService.exportAndUploadFile).not.toHaveBeenCalled();
+ });
+ });
+
// 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).
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 7233ea37e33..c9063733d26 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -10,6 +10,7 @@ import {
import {
type DeviceFileAccess,
type ExportFileResult,
+ getDirname,
type SkillRuntimeService,
SkillsExecutionRuntime,
} from '@lobechat/builtin-tool-skills/executionRuntime';
@@ -29,6 +30,7 @@ import { createSandboxService, normalizeSandboxCommandResult } from '@/server/se
import { SkillResourceService } from '@/server/services/skill/resource';
import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';
+import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:skills-runtime');
@@ -39,6 +41,53 @@ interface UserSettingsWithMarketToken {
};
}
+/**
+ * Device-execution wiring for the exec APIs, present only when the run's
+ * execution plan routed a device (`plan.kind === 'device'` β€” the aiAgent sets
+ * `context.activeDeviceId` from exactly that condition). When present,
+ * `execScript` runs ON the device instead of the cloud sandbox: skill archives
+ * are prepared device-side via the `prepareSkillDirectory` RPC and the command
+ * executes through the local-system tool over the device gateway.
+ */
+interface SkillDeviceExecution {
+ deviceId: string;
+ executionTimeoutMs?: number;
+ operationId?: string;
+ /**
+ * Filesystem skills already living on the device (project/device SKILL.md).
+ * execScript resolves their SKILL.md directory as cwd, mirroring the
+ * prepared-archive skills.
+ */
+ projectSkills?: { location: string; name: string }[];
+ /** Lazily resolved workspace principal β€” see `resolveRunWorkspaceId`. */
+ resolveWorkspaceId: () => Promise<string | undefined>;
+ /** cwd fallback when no activated skill resolves to a directory. */
+ workingDirectory?: string;
+}
+
+interface ActivatedSkillArchive {
+ name: string;
+ url: string;
+ zipHash: string;
+}
+
+/**
+ * Sentinel returned by `execScriptOnDevice` when the routed device runs a
+ * client build that predates the `prepareSkillDirectory` RPC (shipped with
+ * this feature). The device dispatcher replies deterministically with an
+ * unknown-method error, so this is a reliable capability probe β€” distinct
+ * from network failures/timeouts, which must NOT trigger a fallback.
+ */
+const LEGACY_DEVICE_CLIENT = Symbol('legacy-device-client');
+
+/**
+ * Appended to the sandbox result on a legacy-client fallback so the model
+ * discloses the degradation β€” the manifest already told it the command would
+ * run on the user's device.
+ */
+const LEGACY_FALLBACK_NOTE =
+ "Note: the user's device client is outdated and does not support on-device skill execution, so this command ran in the cloud sandbox instead. Tell the user to update their LobeHub app to run skills on their device.";
+
class SkillServerRuntimeService implements SkillRuntimeService {
private resourceService: SkillResourceService;
private skillModel: AgentSkillModel;
@@ -48,8 +97,10 @@ class SkillServerRuntimeService implements SkillRuntimeService {
private serverDB: LobeChatDatabase;
private topicId?: string;
private userId: string;
+ private device?: SkillDeviceExecution;
constructor(options: {
+ device?: SkillDeviceExecution;
fileModel: FileModel;
fileService: FileService;
marketService: MarketService;
@@ -67,6 +118,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
this.serverDB = options.serverDB;
this.topicId = options.topicId;
this.userId = options.userId;
+ this.device = options.device;
}
findAll = (): Promise<{ data: SkillListItem[]; total: number }> => {
@@ -89,6 +141,21 @@ class SkillServerRuntimeService implements SkillRuntimeService {
};
runCommand = async (options: { command: string }): Promise<CommandResult> => {
+ // The device manifest hides this sandbox API (`DEVICE_HIDDEN_API_NAMES` in
+ // `resolveManifest`), but the builtin executor dispatches any method that
+ // exists on this runtime regardless of the manifest β€” enforce the same
+ // decision at execution time so a prompt-following or hallucinated call
+ // can't silently run in the sandbox while the user expects their device.
+ if (this.device) {
+ return {
+ exitCode: 1,
+ output: '',
+ stderr:
+ 'runCommand targets the cloud sandbox and is unavailable while a local device is routed. Use execScript for skill scripts, or lobe-local-system runCommand for other shell commands on the device.',
+ success: false,
+ };
+ }
+
if (!this.topicId) {
throw new Error('topicId is required for runCommand');
}
@@ -96,7 +163,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
// Preprocess lh commands: rewrite to npx @lobehub/cli + inject auth env vars
const lhResult = await preprocessLhCommand(options.command, this.userId);
if (lhResult.error) {
- return { exitCode: 1, output: '', stderr: lhResult.error, success: false };
+ return {
+ executionEnv: 'sandbox',
+ exitCode: 1,
+ output: '',
+ stderr: lhResult.error,
+ success: false,
+ };
}
try {
@@ -113,6 +186,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
if (!response.success) {
return {
+ executionEnv: 'sandbox',
exitCode: 1,
output: '',
stderr: response.error?.message || 'Command execution failed',
@@ -120,10 +194,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {
};
}
- return normalizeSandboxCommandResult(response);
+ return { ...normalizeSandboxCommandResult(response), executionEnv: 'sandbox' };
} catch (error) {
log('Error running command: %O', error);
return {
+ executionEnv: 'sandbox',
exitCode: 1,
output: '',
stderr: (error as Error).message || 'Command execution failed',
@@ -132,12 +207,258 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
};
+ /**
+ * Resolve the presigned zip URLs (+ content hashes) of the activated skills
+ * that have a persisted archive, preserving activation order. Shared by the
+ * sandbox path (needs name β†’ url) and the device path (needs the zipHash as
+ * the device-cache idempotency key).
+ */
+ private resolveActivatedSkillArchives = async (
+ activatedSkills?: ExecScriptActivatedSkill[],
+ ): Promise<ActivatedSkillArchive[]> => {
+ const archives: ActivatedSkillArchive[] = [];
+ if (!activatedSkills?.length) return archives;
+
+ for (const activatedSkill of activatedSkills) {
+ if (!activatedSkill.name) continue;
+
+ const skill = await this.skillModel.findByName(activatedSkill.name);
+
+ if (!skill) {
+ log('No persisted skill bundle found for activated skill: %s', activatedSkill.name);
+ continue;
+ }
+
+ if (!skill.zipFileHash) continue;
+
+ const fileInfo = await this.fileModel.checkHash(skill.zipFileHash);
+ if (!fileInfo.isExist || !fileInfo.url) continue;
+
+ const fullUrl = await this.fileService.getFullFileUrl(fileInfo.url);
+ if (fullUrl) {
+ archives.push({ name: skill.name, url: fullUrl, zipHash: skill.zipFileHash });
+ log('Resolved zipUrl for skill %s', skill.name);
+ }
+ }
+
+ return archives;
+ };
+
+ /**
+ * Run execScript ON the routed device: prepare every activated skill archive
+ * device-side (idempotent by zipHash), then execute the command through the
+ * local-system tool over the device gateway with cwd = the extracted skill
+ * directory.
+ *
+ * Failures return an explicit error and NEVER fall back to the sandbox β€” a
+ * silent sandbox run against a user who chose their device is exactly the
+ * regression this path fixes. Single exception: an older client build that
+ * doesn't know the `prepareSkillDirectory` RPC yet (version-skew window)
+ * returns the `LEGACY_DEVICE_CLIENT` sentinel, and the caller runs the
+ * sandbox path with an explicit disclosure note instead.
+ */
+ private execScriptOnDevice = async (
+ command: string,
+ activatedSkills?: ExecScriptActivatedSkill[],
+ ): Promise<CommandResult | typeof LEGACY_DEVICE_CLIENT> => {
+ const device = this.device!;
+ const fail = (stderr: string): CommandResult => ({
+ executionEnv: 'device',
+ exitCode: 1,
+ output: '',
+ stderr,
+ success: false,
+ });
+
+ try {
+ const archives = await this.resolveActivatedSkillArchives(activatedSkills);
+ const archiveByName = new Map(archives.map((a) => [a.name.toLowerCase(), a]));
+ const workspaceId = await device.resolveWorkspaceId();
+
+ // Resolve each activated skill to a device directory in activation
+ // order; the LAST resolvable one wins as cwd β€” mirrors the sandbox
+ // provider's resolveExecScriptSkillName. Filesystem (project/device)
+ // skills already live on the device, so their SKILL.md directory is the
+ // cwd directly; archive-backed skills are prepared device-side first
+ // (idempotent by zipHash).
+ //
+ // Prepares fire concurrently (deduped by zipHash β€” concurrent extraction
+ // of the same archive would also race device-side): each call is a full
+ // device-gateway round-trip and activatedSkills accumulates over the
+ // conversation, so awaiting one by one scales exec latency linearly with
+ // skill count. The walk below consumes the settled results in activation
+ // order, preserving the sequential semantics: last resolvable wins, and
+ // the FIRST failure in activation order is the one reported (including
+ // the legacy-client sentinel).
+ const isProjectSkill = (lowerName: string) =>
+ device.projectSkills?.some((s) => s.name.toLowerCase() === lowerName);
+ const prepareByHash = new Map<
+ string,
+ ReturnType<typeof deviceGateway.prepareSkillDirectory>
+ >();
+ for (const activated of activatedSkills ?? []) {
+ const lowerName = activated.name?.toLowerCase();
+ if (!lowerName || isProjectSkill(lowerName)) continue;
+ const archive = archiveByName.get(lowerName);
+ if (!archive || prepareByHash.has(archive.zipHash)) continue;
+ prepareByHash.set(
+ archive.zipHash,
+ deviceGateway.prepareSkillDirectory({
+ deviceId: device.deviceId,
+ url: archive.url,
+ userId: this.userId,
+ workspaceId,
+ zipHash: archive.zipHash,
+ }),
+ );
+ }
+ // Settle everything up front so the early return on a first failure
+ // below can't leave a later rejection unhandled (prepareSkillDirectory
+ // reports failures as `success: false` rather than throwing, so this is
+ // belt-and-braces; re-awaiting a settled entry in the walk is free).
+ await Promise.allSettled(prepareByHash.values());
+
+ let runDir: string | undefined;
+ for (const activated of activatedSkills ?? []) {
+ if (!activated.name) continue;
+ const lowerName = activated.name.toLowerCase();
+
+ // Filesystem skills take precedence on name collision, matching
+ // `activateSkill` in the ExecutionRuntime.
+ const projectSkill = device.projectSkills?.find((s) => s.name.toLowerCase() === lowerName);
+ if (projectSkill) {
+ runDir = getDirname(projectSkill.location) || runDir;
+ continue;
+ }
+
+ const archive = archiveByName.get(lowerName);
+ if (!archive) continue;
+
+ const prepared = await prepareByHash.get(archive.zipHash)!;
+
+ if (!prepared.success || !prepared.extractedDir) {
+ // The device dispatcher's deterministic reply for a method it does
+ // not know β€” the client predates this RPC, hand back to the caller
+ // for the sandbox fallback.
+ if (prepared.error?.includes('Unknown device RPC method')) {
+ log('Device %s predates prepareSkillDirectory, falling back', device.deviceId);
+ return LEGACY_DEVICE_CLIENT;
+ }
+
+ return fail(
+ `Failed to prepare skill "${archive.name}" on the user's device: ${prepared.error ?? 'unknown error'}. ` +
+ 'Do not retry elsewhere β€” report this to the user (their LobeHub app may need an update).',
+ );
+ }
+ runDir = prepared.extractedDir;
+ }
+
+ const cwd = runDir ?? device.workingDirectory;
+ const response = await deviceGateway.executeToolCall(
+ {
+ deviceId: device.deviceId,
+ operationId: device.operationId,
+ userId: this.userId,
+ workspaceId,
+ },
+ {
+ apiName: LocalSystemApiName.runCommand,
+ // `timeout` is the device-side shell observation window (default
+ // 30s, clamped at the device's MAX_OBSERVATION_TIMEOUT_MS) β€” without
+ // it a long script returns early while still running.
+ arguments: JSON.stringify({
+ command,
+ ...(cwd && { cwd }),
+ ...(device.executionTimeoutMs && { timeout: device.executionTimeoutMs }),
+ }),
+ identifier: LocalSystemIdentifier,
+ },
+ device.executionTimeoutMs,
+ );
+
+ log('execScript device response: %O', response);
+
+ const state = (response.state ?? {}) as {
+ commandId?: string;
+ error?: string;
+ exitCode?: number;
+ outputFiles?: CommandResult['outputFiles'];
+ stderr?: string;
+ stdout?: string;
+ success?: boolean;
+ };
+
+ // `response.success` is the delivery envelope only: the device-side
+ // ComputerRuntime reports service failures (spawn error, shell lost,
+ // missing params) as `success: true` with `state.success: false` and no
+ // exitCode (`errorOutput`) β€” without this check they'd fall through to
+ // the still-running branch below and read as a successful run.
+ if (!response.success || state.success === false) {
+ return fail(
+ state.stderr ||
+ state.error ||
+ response.error ||
+ response.content ||
+ 'Command execution failed on the device',
+ );
+ }
+
+ // The device shell reports success for any delivered observation, even
+ // when the command exited non-zero (the exit status only lives in
+ // exitCode) β€” derive success from the exit status instead. An undefined
+ // exitCode means the command is still running past the observation
+ // window: pass it through with the shell handle so the formatter
+ // reports a running command (pollable via local-system.getCommandOutput)
+ // instead of pretending completion.
+ const exitCode = state.exitCode;
+ return {
+ executionEnv: 'device',
+ exitCode,
+ output: state.stdout ?? response.content ?? '',
+ // Large streams are truncated to a preview device-side with the full
+ // output saved to disk β€” the paths are the only retrieval handle.
+ outputFiles: state.outputFiles,
+ shellId: state.commandId,
+ stderr: state.stderr,
+ success: exitCode === undefined || exitCode === 0,
+ };
+ } catch (error) {
+ log('Error executing script on device: %O', error);
+ return fail((error as Error).message || 'Command execution failed on the device');
+ }
+ };
+
execScript = async (
command: string,
options: {
activatedSkills?: ExecScriptActivatedSkill[];
description: string;
},
+ ): Promise<CommandResult> => {
+ // Execution target follows the run's plan: a routed device wins over the
+ // sandbox (restores the pre-gateway desktop behavior).
+ if (this.device) {
+ const deviceResult = await this.execScriptOnDevice(command, options.activatedSkills);
+ if (deviceResult !== LEGACY_DEVICE_CLIENT) return deviceResult;
+
+ // Version-skew fallback: the client predates the RPC. Run the sandbox
+ // path but disclose the degradation in stderr so the model relays it.
+ const sandboxResult = await this.execScriptInSandbox(command, options);
+ return {
+ ...sandboxResult,
+ stderr: [sandboxResult.stderr, LEGACY_FALLBACK_NOTE].filter(Boolean).join('\n'),
+ };
+ }
+
+ return this.execScriptInSandbox(command, options);
+ };
+
+ private execScriptInSandbox = async (
+ command: string,
+ options: {
+ activatedSkills?: ExecScriptActivatedSkill[];
+ description: string;
+ },
): Promise<CommandResult> => {
const { activatedSkills, description } = options;
@@ -152,35 +473,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
description,
};
- if (activatedSkills?.length) {
- const skillZipUrls: Record<string, string> = {};
-
- for (const activatedSkill of activatedSkills) {
- if (!activatedSkill.name) continue;
-
- const skill = await this.skillModel.findByName(activatedSkill.name);
-
- if (!skill) {
- log('No persisted skill bundle found for activated skill: %s', activatedSkill.name);
- continue;
- }
-
- if (!skill.zipFileHash) continue;
-
- const fileInfo = await this.fileModel.checkHash(skill.zipFileHash);
- if (!fileInfo.isExist || !fileInfo.url) continue;
-
- const fullUrl = await this.fileService.getFullFileUrl(fileInfo.url);
- if (fullUrl) {
- skillZipUrls[skill.name] = fullUrl;
- log('Resolved zipUrl for skill %s', skill.name);
- }
- }
-
- if (Object.keys(skillZipUrls).length > 0) {
- enhancedParams.skillZipUrls = skillZipUrls;
- log('Added skillZipUrls to execScript params: %O', Object.keys(skillZipUrls));
- }
+ const archives = await this.resolveActivatedSkillArchives(activatedSkills);
+ if (archives.length > 0) {
+ enhancedParams.skillZipUrls = Object.fromEntries(archives.map((a) => [a.name, a.url]));
+ log(
+ 'Added skillZipUrls to execScript params: %O',
+ archives.map((a) => a.name),
+ );
}
const sandboxService = createSandboxService({
@@ -196,6 +495,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
if (!response.success) {
return {
+ executionEnv: 'sandbox',
exitCode: 1,
output: '',
stderr: response.error?.message || 'Command execution failed',
@@ -203,10 +503,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {
};
}
- return normalizeSandboxCommandResult(response);
+ return { ...normalizeSandboxCommandResult(response), executionEnv: 'sandbox' };
} catch (error) {
log('Error executing script: %O', error);
return {
+ executionEnv: 'sandbox',
exitCode: 1,
output: '',
stderr: (error as Error).message || 'Command execution failed',
@@ -216,6 +517,14 @@ class SkillServerRuntimeService implements SkillRuntimeService {
};
exportFile = async (path: string, filename: string): Promise<ExportFileResult> => {
+ // Same manifest-hidden guard as `runCommand`: the message reaches the
+ // model through the ExecutionRuntime catch ("Failed to export file: ...").
+ if (this.device) {
+ throw new Error(
+ "exportFile pulls artifacts out of the cloud sandbox and is unavailable while a local device is routed β€” files created on the device are already on the user's machine.",
+ );
+ }
+
if (!this.topicId) {
throw new Error('topicId is required for exportFile');
}
@@ -289,7 +598,29 @@ export const skillsRuntime: ServerRuntimeRegistration = {
const fileService = new FileService(context.serverDB, context.userId, context.workspaceId);
const fileModel = new FileModel(context.serverDB, context.userId, context.workspaceId);
+ // `activeDeviceId` presence is the device-branch switch: execScript then
+ // runs on the device instead of the cloud sandbox. The executors filter
+ // the raw metadata id through `resolveRunActiveDeviceId` (plan/policy
+ // gate) before it reaches this context, so a preset or stale id cannot
+ // route execution onto a device the resolved plan didn't authorize;
+ // `device-unrouted` runs keep the sandbox path (with the unrouted
+ // disclosure in the manifest).
+ let workspaceIdPromise: Promise<string | undefined> | undefined;
+ const device: SkillDeviceExecution | undefined = context.activeDeviceId
+ ? {
+ deviceId: context.activeDeviceId,
+ executionTimeoutMs: context.executionTimeoutMs,
+ operationId: context.operationId,
+ projectSkills: context.projectSkills,
+ // Same lazy workspace-principal recovery as the local-system runtime,
+ // so workspace devices are addressed under the right gateway pool.
+ resolveWorkspaceId: () => (workspaceIdPromise ??= resolveRunWorkspaceId(context)),
+ workingDirectory: context.workingDirectory,
+ }
+ : undefined;
+
const service = new SkillServerRuntimeService({
+ device,
fileModel,
fileService,
marketService,
@@ -390,6 +721,10 @@ export const skillsRuntime: ServerRuntimeRegistration = {
}
return new SkillsExecutionRuntime({
+ // Resolved by the runtime executors from the operation's message
+ // history (the server-side stepContext equivalent); execScript falls
+ // back to these because the raw LLM args never carry activatedSkills.
+ activatedSkills: context.activatedSkills,
builtinSkills: [
// Device-only skills resolve in device-capable runs β€” mirrors the
// SkillEngine gate in aiAgent that builds <available_skills>, so a
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 22f0d8f2468..45e6a86d17e 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -4,6 +4,7 @@ import {
type ChatToolPayload,
type ClientSecretPayload,
type ExecSubAgentParams,
+ type StepActivatedSkill,
} from '@lobechat/types';
export interface ToolExecutionMemoryEmbeddingRuntime {
@@ -115,6 +116,15 @@ export interface ServerAgentMemberRunner {
}
export interface ToolExecutionContext {
+ /**
+ * Skills activated so far in the conversation (activateSkill /
+ * activateTools tool results), extracted by the runtime executors from the
+ * operation's message history β€” the server-side equivalent of the client
+ * transport's stepContext. The skills runtime uses this to resolve skill
+ * archives for `execScript` (device `prepareSkillDirectory` + sandbox
+ * `skillZipUrls`); the raw LLM args never carry it.
+ */
+ activatedSkills?: StepActivatedSkill[];
/** Target device ID for device proxy tool calls */
activeDeviceId?: string;
/** Agent ID executing the tool call */
diff --git a/packages/agent-runtime/src/utils/messageSelectors.test.ts b/packages/agent-runtime/src/utils/messageSelectors.test.ts
index ab0a466a373..9d05cb0da1b 100644
--- a/packages/agent-runtime/src/utils/messageSelectors.test.ts
+++ b/packages/agent-runtime/src/utils/messageSelectors.test.ts
@@ -1,7 +1,11 @@
import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { collectFromMessages, findInMessages } from './messageSelectors';
+import {
+ collectFromMessages,
+ extractActivatedSkillsFromMessages,
+ findInMessages,
+} from './messageSelectors';
const createMessage = (overrides: Partial<UIChatMessage> = {}): UIChatMessage =>
({
@@ -95,3 +99,288 @@ describe('collectFromMessages', () => {
expect(result).toEqual(['tool']);
});
});
+
+describe('extractActivatedSkillsFromMessages', () => {
+ it('should return undefined when no skill activations exist', () => {
+ const messages = [
+ createMessage({ content: 'hi', role: 'user' } as any),
+ createToolMessage({ plugin: { apiName: 'execScript', identifier: 'lobe-skills' } } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toBeUndefined();
+ });
+
+ it('should extract skills from direct activateSkill results', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { description: 'PDF tools', id: 'skl_1', name: 'pdf' },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: 'PDF tools', id: 'skl_1', name: 'pdf' },
+ ]);
+ });
+
+ it('should extract skills from activator activateSkill and activateTools results', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-activator' },
+ pluginState: { id: 'skl_1', name: 'pdf' },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: {
+ activatedSkills: [
+ { description: 'sheets', id: 'skl_2', name: 'xlsx' },
+ { id: 'missing-name-dropped' },
+ ],
+ },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: undefined, id: 'skl_1', name: 'pdf' },
+ { description: 'sheets', id: 'skl_2', name: 'xlsx' },
+ ]);
+ });
+
+ it('should deduplicate by skill id with later activations winning', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { description: 'old', id: 'skl_1', name: 'pdf' },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { description: 'new', id: 'skl_1', name: 'pdf' },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: 'new', id: 'skl_1', name: 'pdf' },
+ ]);
+ });
+
+ // Exec paths pick the LAST entry as the most recent activation for the
+ // script cwd, so a reactivation must move the skill to the end.
+ it('should move a reactivated skill to the end of the activation order', () => {
+ const activate = (id: string, name: string) =>
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { id, name },
+ } as any);
+
+ const messages = [
+ activate('skl_a', 'alpha'),
+ activate('skl_b', 'beta'),
+ activate('skl_a', 'alpha'),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: undefined, id: 'skl_b', name: 'beta' },
+ { description: undefined, id: 'skl_a', name: 'alpha' },
+ ]);
+ });
+
+ // Filesystem (project/device) and builtin skill activations persist no DB
+ // id β€” dropping them broke device-exec cwd resolution, which matches
+ // activated skills against device.projectSkills by name.
+ it('should keep activateSkill states without an id (filesystem/builtin skills)', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: {
+ hasResources: false,
+ location: '/repo/.agents/skills/foo/SKILL.md',
+ name: 'foo',
+ source: 'project',
+ },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { activatedSkills: [{ description: 'builtin', name: 'bar' }] },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: undefined, name: 'foo' },
+ { description: 'builtin', name: 'bar' },
+ ]);
+ });
+
+ it('should deduplicate id-less activations by name with later activations winning', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { name: 'foo', source: 'project' },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { description: 'reactivated', name: 'foo', source: 'project' },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: 'reactivated', name: 'foo' },
+ ]);
+ });
+
+ it('should ignore non-tool roles and other tool identifiers', () => {
+ const messages = [
+ createMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },
+ pluginState: { id: 'skl_1', name: 'pdf' },
+ role: 'assistant',
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateSkill', identifier: 'lobe-web-browsing' },
+ pluginState: { id: 'skl_2', name: 'web' },
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toBeUndefined();
+ });
+
+ // The server runtime rehydrates state.messages from the DB at every step
+ // (rehydrateStateMessagesFromDB), which runs conversation-flow parse():
+ // completed turns are folded into assistantGroup virtual nodes where tool
+ // rows live on children[].tools[] with pluginState as result.state.
+ it('should extract skills folded into assistantGroup nodes (cross-turn rehydrated state)', () => {
+ const messages = [
+ createMessage({ content: 'activate xlsx', role: 'user' } as any),
+ createMessage({
+ children: [
+ {
+ content: '',
+ id: 'msg-asst-1',
+ tools: [
+ {
+ apiName: 'activateSkill',
+ arguments: '{"name":"xlsx"}',
+ id: 'call_1',
+ identifier: 'lobe-skills',
+ result: {
+ content: 'activated',
+ id: 'msg-tool-1',
+ state: { description: 'sheets', id: 'skl_1', name: 'xlsx' },
+ },
+ },
+ ],
+ },
+ {
+ content: 'done',
+ id: 'msg-asst-2',
+ tools: [
+ {
+ apiName: 'execScript',
+ id: 'call_2',
+ identifier: 'lobe-skills',
+ result: { content: 'ok', id: 'msg-tool-2', state: { executionEnv: 'device' } },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ } as any),
+ createMessage({ content: 'run it again', role: 'user' } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: 'sheets', id: 'skl_1', name: 'xlsx' },
+ ]);
+ });
+
+ it('should extract activateTools skills from assistantGroup nodes', () => {
+ const messages = [
+ createMessage({
+ children: [
+ {
+ content: '',
+ id: 'msg-asst-1',
+ tools: [
+ {
+ apiName: 'activateTools',
+ id: 'call_1',
+ identifier: 'lobe-activator',
+ result: {
+ content: 'activated',
+ id: 'msg-tool-1',
+ state: { activatedSkills: [{ id: 'skl_2', name: 'pdf' }] },
+ },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: undefined, id: 'skl_2', name: 'pdf' },
+ ]);
+ });
+
+ it('should recurse into compressedGroup compressedMessages', () => {
+ const messages = [
+ createMessage({
+ compressedMessages: [
+ createMessage({
+ children: [
+ {
+ content: '',
+ id: 'msg-asst-1',
+ tools: [
+ {
+ apiName: 'activateSkill',
+ id: 'call_1',
+ identifier: 'lobe-skills',
+ result: {
+ content: 'ok',
+ id: 'msg-tool-1',
+ state: { id: 'skl_3', name: 'docx' },
+ },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ } as any),
+ ],
+ role: 'compressedGroup',
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toEqual([
+ { description: undefined, id: 'skl_3', name: 'docx' },
+ ]);
+ });
+
+ it('should ignore assistantGroup tools without activation state or with other identifiers', () => {
+ const messages = [
+ createMessage({
+ children: [
+ {
+ content: '',
+ id: 'msg-asst-1',
+ tools: [
+ // Tool without a captured result (still pending)
+ { apiName: 'activateSkill', id: 'call_1', identifier: 'lobe-skills' },
+ // Non-skill identifier
+ {
+ apiName: 'activateSkill',
+ id: 'call_2',
+ identifier: 'lobe-web-browsing',
+ result: { content: 'ok', id: 'msg-tool-2', state: { id: 'skl_9', name: 'web' } },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ } as any),
+ ];
+
+ expect(extractActivatedSkillsFromMessages(messages)).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/utils/messageSelectors.ts b/packages/agent-runtime/src/utils/messageSelectors.ts
index 194d9225473..09e30308370 100644
--- a/packages/agent-runtime/src/utils/messageSelectors.ts
+++ b/packages/agent-runtime/src/utils/messageSelectors.ts
@@ -1,4 +1,15 @@
-import type { UIChatMessage } from '@lobechat/types';
+import type { StepActivatedSkill, UIChatMessage } from '@lobechat/types';
+
+/**
+ * Wire-format tool identifiers that carry skill activations in their
+ * pluginState. Literal copies of `SkillsIdentifier`
+ * (@lobechat/builtin-tool-skills) and `LobeActivatorIdentifier`
+ * (@lobechat/builtin-tool-activator) β€” both are frozen, persisted in DB
+ * message rows, and not importable here without adding tool-package deps to
+ * the runtime core.
+ */
+const SKILLS_IDENTIFIER = 'lobe-skills';
+const ACTIVATOR_IDENTIFIER = 'lobe-activator';
/**
* Options for message visitor traversal
@@ -80,3 +91,139 @@ export const collectFromMessages = <T>(
return results;
};
+
+/**
+ * A single tool invocation observed in the conversation, normalized across the
+ * two message shapes activations can arrive in (see
+ * `collectToolInvocations`).
+ */
+interface ToolInvocation {
+ apiName?: string;
+ identifier?: string;
+ state?: any;
+}
+
+/**
+ * Normalize one message into the tool invocations it carries.
+ *
+ * Two shapes must be handled:
+ * 1. Flat DB rows β€” `role='tool'` messages with `plugin` / `pluginState`
+ * (client store, `execAgent` initialMessages, same-run pushed results).
+ * 2. Virtual grouped nodes produced by conversation-flow `parse()` β€” the
+ * server runtime rehydrates `state.messages` from the DB at every step
+ * (`rehydrateStateMessagesFromDB`), which folds completed turns into
+ * `assistantGroup` / `supervisor` nodes: tool rows disappear as standalone
+ * entries and live on `children[].tools[]` instead, with the original
+ * `pluginState` re-attached as `result.state` (see
+ * FlatListBuilder.createAssistantGroupMessage). Without this branch,
+ * cross-turn skill activations are invisible to later runs.
+ * `compressedGroup` nodes keep their members on `compressedMessages` in
+ * the same flat-list shape, so recurse into them.
+ */
+const collectToolInvocations = (msg: UIChatMessage): ToolInvocation[] => {
+ if (msg.role === 'tool') {
+ return [
+ { apiName: msg.plugin?.apiName, identifier: msg.plugin?.identifier, state: msg.pluginState },
+ ];
+ }
+
+ const invocations: ToolInvocation[] = [];
+
+ const { children } = msg;
+ if (Array.isArray(children)) {
+ for (const child of children) {
+ if (!Array.isArray(child?.tools)) continue;
+ for (const tool of child.tools) {
+ invocations.push({
+ apiName: tool?.apiName,
+ identifier: tool?.identifier,
+ state: tool?.result?.state,
+ });
+ }
+ }
+ }
+
+ const { compressedMessages } = msg;
+ if (Array.isArray(compressedMessages)) {
+ for (const compressed of compressedMessages) {
+ invocations.push(...collectToolInvocations(compressed));
+ }
+ }
+
+ return invocations;
+};
+
+/**
+ * Accumulate activated skills from all activateSkill / activateTools tool
+ * messages. Skills once activated remain active for the rest of the
+ * conversation; the skill id (or name, for filesystem/builtin activations that
+ * persist no id) deduplicates β€” a reactivation updates the entry AND moves it
+ * to the end, since exec paths treat the last entry as the most recent
+ * activation when picking the script cwd.
+ *
+ * Shared by the client transport (chat store dbMessage selector feeding
+ * `computeStepContext`) and the server runtime executors (`callTool` /
+ * `callToolsBatch`), so both execution paths resolve the same activation set
+ * for skills `execScript`. Handles both flat `role='tool'` rows and the
+ * conversation-flow grouped shape (`assistantGroup` etc.) β€” see
+ * `collectToolInvocations`.
+ */
+export const extractActivatedSkillsFromMessages = (
+ messages: UIChatMessage[],
+): StepActivatedSkill[] | undefined => {
+ const skillsMap = new Map<string, StepActivatedSkill>();
+
+ for (const msg of messages) {
+ for (const invocation of collectToolInvocations(msg)) {
+ if (!(
+ invocation.identifier === SKILLS_IDENTIFIER ||
+ invocation.identifier === ACTIVATOR_IDENTIFIER
+ ))
+ continue;
+
+ // Direct activateSkill calls β€” state has top-level name (id only for DB
+ // skills; filesystem/builtin activations persist no id, so `name` alone
+ // must be enough to keep them β€” server exec paths match by name anyway).
+ if (invocation.apiName === 'activateSkill' && invocation.state?.name) {
+ const id = invocation.state.id as string | undefined;
+ const name = invocation.state.name as string;
+ const key = id ?? name;
+ // Delete before set so reactivation moves the skill to the end β€”
+ // downstream exec paths pick the LAST resolvable skill as cwd, so
+ // insertion order must reflect activation recency (A β†’ B β†’ A must
+ // yield [B, A], not Map#set's kept-in-place [A, B]).
+ skillsMap.delete(key);
+ skillsMap.set(key, {
+ description: invocation.state.description as string | undefined,
+ ...(id && { id }),
+ name,
+ });
+ }
+
+ // activateTools fallback β€” skills nested in pluginState.activatedSkills[]
+ if (
+ invocation.apiName === 'activateTools' &&
+ Array.isArray(invocation.state?.activatedSkills)
+ ) {
+ for (const skill of invocation.state.activatedSkills as Array<{
+ description?: string;
+ id?: string;
+ name?: string;
+ }>) {
+ if (skill.name) {
+ const key = skill.id ?? skill.name;
+ // Same delete-before-set as above: keep activation recency.
+ skillsMap.delete(key);
+ skillsMap.set(key, {
+ description: skill.description,
+ ...(skill.id && { id: skill.id }),
+ name: skill.name,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ return skillsMap.size > 0 ? [...skillsMap.values()] : undefined;
+};
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
index a50388dd833..2a4aa435ef6 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
@@ -96,6 +96,46 @@ describe('SkillsExecutionRuntime', () => {
expect(result.success).toBe(false);
expect(result.content).toBe('Failed to execute command: sandbox timeout');
});
+
+ it('should fall back to constructor activatedSkills when args carry none', async () => {
+ const execScript = vi.fn().mockResolvedValue({
+ exitCode: 0,
+ output: 'ok',
+ success: true,
+ } satisfies CommandResult);
+ const contextSkills = [{ description: 'PDF tools', id: 'skl_1', name: 'pdf' }];
+ const runtime = new SkillsExecutionRuntime({
+ activatedSkills: contextSkills,
+ service: createMockService({ execScript }),
+ });
+
+ await runtime.execScript(args);
+
+ expect(execScript).toHaveBeenCalledWith('echo hello', {
+ activatedSkills: contextSkills,
+ description: 'test command',
+ });
+ });
+
+ it('should prefer args activatedSkills over the constructor fallback', async () => {
+ const execScript = vi.fn().mockResolvedValue({
+ exitCode: 0,
+ output: 'ok',
+ success: true,
+ } satisfies CommandResult);
+ const argsSkills = [{ id: 'skl_2', name: 'xlsx' }];
+ const runtime = new SkillsExecutionRuntime({
+ activatedSkills: [{ id: 'skl_1', name: 'pdf' }],
+ service: createMockService({ execScript }),
+ });
+
+ await runtime.execScript({ ...args, activatedSkills: argsSkills });
+
+ expect(execScript).toHaveBeenCalledWith('echo hello', {
+ activatedSkills: argsSkills,
+ description: 'test command',
+ });
+ });
});
describe('via runCommand fallback', () => {
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
index 489aece4741..8f1fcd204ee 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
@@ -11,6 +11,7 @@ import type {
import type {
ActivateSkillParams,
CommandResult,
+ ExecScriptActivatedSkill,
ExecScriptParams,
ExportFileParams,
ReadReferenceParams,
@@ -41,7 +42,7 @@ export interface SkillRuntimeService {
execScript?: (
command: string,
options: {
- activatedSkills?: Array<{ description?: string; id: string; name: string }>;
+ activatedSkills?: Array<{ description?: string; id?: string; name: string }>;
description: string;
},
) => Promise<CommandResult>;
@@ -85,6 +86,14 @@ export interface DeviceFileAccess {
}
export interface SkillsExecutionRuntimeOptions {
+ /**
+ * Activated skills resolved by the caller from the conversation history.
+ * Fallback for `execScript` when the args carry none: the client executor
+ * injects stepContext.activatedSkills into the args, but the server runtime
+ * registry passes the raw LLM args, so the server factory threads them here
+ * instead.
+ */
+ activatedSkills?: ExecScriptActivatedSkill[];
builtinSkills?: BuiltinSkill[];
/** Reads project skill files from the device (local-system over the gateway). */
deviceFileAccess?: DeviceFileAccess;
@@ -93,8 +102,12 @@ export interface SkillsExecutionRuntimeOptions {
service: SkillRuntimeService;
}
-/** Cross-platform dirname for absolute paths (POSIX or Windows separators). */
-const getDirname = (filePath: string): string => {
+/**
+ * Cross-platform dirname for absolute paths (POSIX or Windows separators).
+ * Exported for the server skills runtime, which resolves device paths that may
+ * use either separator β€” server-side `path.dirname` would mishandle `\`.
+ */
+export const getDirname = (filePath: string): string => {
const idx = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
return idx === -1 ? '' : filePath.slice(0, idx);
};
@@ -144,6 +157,7 @@ const buildProjectDirectoryHint = (skillName: string, skillDir: string): string
This filesystem skill lives in \`${skillDir}\`. Use \`local-system.globFiles\` with scope="${skillDir}" and pattern="**/*" to discover reference files, then \`readReference\` with skillName="${skillName}" + the relative path to load any of them.`;
export class SkillsExecutionRuntime {
+ private activatedSkills?: ExecScriptActivatedSkill[];
private builtinSkills: BuiltinSkill[];
private projectSkills: ProjectSkillRuntimeItem[];
private deviceFileAccess?: DeviceFileAccess;
@@ -151,13 +165,17 @@ export class SkillsExecutionRuntime {
constructor(options: SkillsExecutionRuntimeOptions) {
this.service = options.service;
+ this.activatedSkills = options.activatedSkills;
this.builtinSkills = options.builtinSkills || [];
this.projectSkills = options.projectSkills || [];
this.deviceFileAccess = options.deviceFileAccess;
}
async execScript(args: ExecScriptParams): Promise<BuiltinServerRuntimeOutput> {
- const { activatedSkills, command, description } = args;
+ const { command, description } = args;
+ // Args win when the caller (client executor) already injected stepContext;
+ // the constructor option covers the server path where args are raw LLM output.
+ const activatedSkills = args.activatedSkills ?? this.activatedSkills;
// Try new execScript method first (with cloud sandbox support)
if (this.service.execScript) {
@@ -498,13 +516,22 @@ export class SkillsExecutionRuntime {
stdout: result.output,
success: result.success,
exitCode: result.exitCode,
+ // Renders the saved-output paths when the shell truncated the inline
+ // stream β€” without them the full output is unreachable.
+ outputFiles: result.outputFiles,
+ // Surfaces the still-running message with a pollable handle when the
+ // command outlived the observation window (exitCode undefined).
+ shellId: result.shellId,
});
return {
content,
state: {
command,
+ ...(result.executionEnv && { executionEnv: result.executionEnv }),
exitCode: result.exitCode,
+ ...(result.outputFiles && { outputFiles: result.outputFiles }),
+ ...(result.shellId && { shellId: result.shellId }),
success: result.success,
},
success: result.success,
diff --git a/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
index 61128bad48e..6dfb60fa893 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
+++ b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx
@@ -1,8 +1,9 @@
'use client';
import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { Check, X } from 'lucide-react';
+import { Check, LoaderCircle, X } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -41,13 +42,20 @@ export const ExecScriptInspector = memo<BuiltinInspectorProps<ExecScriptParams,
}
const isSuccess = pluginState?.success;
+ // A command that outlived the shell's observation window has no exitCode
+ // yet and reports `success: true` for the model loop (still running β‰ 
+ // failed) β€” but the UI must not show a completed checkmark while the
+ // command is in fact still executing (pollable via shellId).
+ const isStillRunning = pluginState?.exitCode === undefined && !!pluginState?.shellId;
return (
<div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
<span style={{ marginInlineStart: 2 }}>
<span>{t('builtins.lobe-skills.apiName.execScript')}: </span>
{description && <span className={highlightTextStyles.primary}>{description}</span>}
- {isLoading ? null : pluginState?.success !== undefined ? (
+ {isLoading ? null : isStillRunning ? (
+ <Icon spin className={styles.statusIcon} icon={LoaderCircle} size={14} />
+ ) : pluginState?.success !== undefined ? (
isSuccess ? (
<Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
) : (
diff --git a/packages/builtin-tool-skills/src/resolveManifest.test.ts b/packages/builtin-tool-skills/src/resolveManifest.test.ts
index 08528f77c1e..accdf3ac478 100644
--- a/packages/builtin-tool-skills/src/resolveManifest.test.ts
+++ b/packages/builtin-tool-skills/src/resolveManifest.test.ts
@@ -26,21 +26,29 @@ describe('resolveSkillsManifest', () => {
},
);
- it('prefixes exec APIs with the fallback framing when a device is online', () => {
+ // Device runs execute execScript ON the device (serverRuntimes/skills.ts
+ // device branch) β€” the description must say so, and the sandbox-only APIs
+ // (runCommand / exportFile) are dropped, restoring the original desktop
+ // manifest shape.
+ it('declares device execution and hides sandbox-only APIs when a device is routed', () => {
const result = resolveSkillsManifest({ executionEnv: 'device' })!;
- for (const name of EXEC_APIS) {
- const description = apiByName(result, name).description;
- expect(description).toMatch(/^Fallback execution environment: an isolated cloud sandbox/);
- expect(description).toContain('GITHUB_TOKEN');
- // the original mechanics stay after the preamble
- expect(description).toContain(apiByName(SkillsManifest, name).description);
- }
+ const description = apiByName(result, SkillsApiName.execScript).description;
+ expect(description).toMatch(/^Execution environment: the user's selected device/);
+ expect(description).toContain('NOT injected');
+ // the original mechanics stay after the preamble
+ expect(description).toContain(apiByName(SkillsManifest, SkillsApiName.execScript).description);
+
+ const apiNames = result.api.map((a) => a.name);
+ expect(apiNames).not.toContain(SkillsApiName.runCommand);
+ expect(apiNames).not.toContain(SkillsApiName.exportFile);
+ expect(apiNames).toContain(SkillsApiName.activateSkill);
+ expect(apiNames).toContain(SkillsApiName.readReference);
+
// cross-tool arbitration rides the tool systemRole, not the descriptions
expect(result.systemRole).toContain(systemPrompt);
- expect(result.systemRole).toContain(
- 'Default shell execution to `lobe-local-system` runCommand',
- );
+ expect(result.systemRole).toContain('`execScript` runs skill scripts on the device');
+ expect(result.systemRole).toContain('`lobe-local-system` runCommand');
});
it.each(['bound-device-offline', 'no-online-device'] as const)(
@@ -109,7 +117,7 @@ describe('resolveSkillsManifest', () => {
expect(result.systemRole).toBe(systemPrompt);
});
- it.each(['device', 'device-unrouted', 'sandbox'] as const)(
+ it.each(['device-unrouted', 'sandbox'] as const)(
'keeps non-exec APIs, api shape, and humanIntervention intact for %s',
(executionEnv) => {
const result = resolveSkillsManifest({ executionEnv })!;
@@ -125,6 +133,16 @@ describe('resolveSkillsManifest', () => {
},
);
+ it('keeps non-exec APIs and humanIntervention intact for device', () => {
+ const result = resolveSkillsManifest({ executionEnv: 'device' })!;
+
+ for (const name of NON_EXEC_APIS) {
+ expect(apiByName(result, name)).toBe(apiByName(SkillsManifest, name));
+ }
+ expect(apiByName(result, SkillsApiName.execScript).humanIntervention).toBe('required');
+ expect(result.identifier).toBe(SkillsManifest.identifier);
+ });
+
it('does not mutate the static manifest', () => {
const staticDescriptions = SkillsManifest.api.map((a) => a.description);
diff --git a/packages/builtin-tool-skills/src/resolveManifest.ts b/packages/builtin-tool-skills/src/resolveManifest.ts
index 03bea38a30b..27dcfe8a984 100644
--- a/packages/builtin-tool-skills/src/resolveManifest.ts
+++ b/packages/builtin-tool-skills/src/resolveManifest.ts
@@ -4,12 +4,11 @@ import { SkillsManifest } from './manifest';
import { SkillsApiName } from './types';
/**
- * The exec-class APIs whose runtime is the server-side cloud sandbox
- * (`apps/server/.../serverRuntimes/skills.ts`), regardless of the run's
- * execution target. Their static descriptions never say where they run, so a
- * desktop user who picked "local device" can have commands silently land in
- * the sandbox β€” most damagingly when the bound device is judged offline and
- * `lobe-local-system` is not injected at all (plan kind `device-unrouted`).
+ * The exec-class APIs. Their runtime target follows the run's execution plan
+ * (`apps/server/.../serverRuntimes/skills.ts`): a routed device
+ * (`executionEnv: 'device'`) runs `execScript` ON the device; every other
+ * environment runs in the server-side cloud sandbox. Descriptions are resolved
+ * per plan below so the model is never told a location the runtime won't honor.
*/
const EXEC_API_NAMES = new Set<string>([
SkillsApiName.execScript,
@@ -17,14 +16,28 @@ const EXEC_API_NAMES = new Set<string>([
SkillsApiName.runCommand,
]);
+/**
+ * APIs hidden when a device is routed β€” the sandbox-oriented surface makes no
+ * sense there. `runCommand` duplicates `lobe-local-system` runCommand on the
+ * device, and `exportFile` exists to pull artifacts OUT of the sandbox; device
+ * runs leave artifacts on the user's machine, where they already are. This
+ * also restores the original desktop manifest shape, which only ever exposed
+ * `execScript` (see `manifest.desktop.ts`).
+ */
+const DEVICE_HIDDEN_API_NAMES = new Set<string>([
+ SkillsApiName.exportFile,
+ SkillsApiName.runCommand,
+]);
+
/**
* Per-environment description preambles for the exec-class APIs. Descriptions
* carry tool semantics only (where it runs, what credentials it has);
* cross-tool arbitration lives in `EXEC_ENV_FACTS`.
*
- * - `device`: a local device is online β€” the sandbox is the FALLBACK.
- * Credential fact: `injectCredsToSandbox` only injects into the sandbox;
- * devices deliberately get nothing.
+ * - `device`: a device is routed β€” `execScript` runs ON it: the skill archive
+ * is downloaded/extracted device-side and the command runs in the skill
+ * directory. LobeHub-managed credentials are deliberately NOT injected into
+ * devices (`injectCredsToSandbox` only targets the sandbox).
* - `device-unrouted`: the user chose local-device execution but no device is
* routed this run β€” the model must disclose that instead of silently
* running machine-specific commands in the sandbox. Wording varies by
@@ -38,7 +51,7 @@ const EXEC_ENV_PREAMBLES: Partial<
Record<NonNullable<BuiltinToolResolveContext['executionEnv']>, string>
> = {
'device':
- "Fallback execution environment: an isolated cloud sandbox, not the user's machine (LobeHub-managed credentials injected, e.g. `GITHUB_TOKEN`).",
+ "Execution environment: the user's selected device, not a cloud sandbox. The skill archive is auto-extracted on the device and the command runs in the skill directory. LobeHub-managed credentials (e.g. `GITHUB_TOKEN`) are NOT injected.",
'device-unrouted':
'Fallback execution environment: an isolated cloud sandbox. The user chose local-device execution but no device is routed this run β€” say so before running commands that assume their machine.',
'sandbox': "Execution environment: an isolated cloud sandbox, not the user's machine.",
@@ -55,7 +68,7 @@ const EXEC_ENV_FACTS: Partial<
Record<NonNullable<BuiltinToolResolveContext['executionEnv']>, string>
> = {
'device':
- 'A local device is online. Default shell execution to `lobe-local-system` runCommand; use the skills exec APIs only when the local run lacks a required tool, the task needs LobeHub-managed credentials, or the task needs isolation.',
+ 'A local device is routed: `execScript` runs skill scripts on the device (archive auto-extracted, cwd = skill directory); use `lobe-local-system` runCommand for other shell commands. LobeHub-managed credentials are not available on the device.',
'device-unrouted':
'No local device is routed; shell commands execute in the cloud sandbox this run.',
};
@@ -98,12 +111,14 @@ const resolveUnroutedTexts = (
/**
* Context-aware manifest for the lobe-skills tool: prefixes the exec-class API
* descriptions with where they actually run, derived from the resolved
- * execution plan (see `BuiltinToolResolveContext.executionEnv`).
+ * execution plan (see `BuiltinToolResolveContext.executionEnv`). Device runs
+ * additionally drop the sandbox-only APIs (`runCommand` / `exportFile`).
*/
export const resolveSkillsManifest: BuiltinManifestResolver = (context) => {
const basePreamble = context.executionEnv && EXEC_ENV_PREAMBLES[context.executionEnv];
if (!basePreamble) return SkillsManifest;
+ const isDeviceRun = context.executionEnv === 'device';
const unrouted =
context.executionEnv === 'device-unrouted'
? resolveUnroutedTexts(context.executionEnvUnroutedReason)
@@ -113,11 +128,13 @@ export const resolveSkillsManifest: BuiltinManifestResolver = (context) => {
return {
...SkillsManifest,
- api: SkillsManifest.api.map((api) =>
- EXEC_API_NAMES.has(api.name)
- ? { ...api, description: `${preamble} ${api.description}` }
- : api,
- ),
+ api: SkillsManifest.api
+ .filter((api) => !isDeviceRun || !DEVICE_HIDDEN_API_NAMES.has(api.name))
+ .map((api) =>
+ EXEC_API_NAMES.has(api.name)
+ ? { ...api, description: `${preamble} ${api.description}` }
+ : api,
+ ),
...(fact && {
systemRole: `${SkillsManifest.systemRole}\n<execution_environment>\n${fact}\n</execution_environment>\n`,
}),
diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.ts
index cc98e86e898..81693ba2593 100644
--- a/packages/builtin-tool-skills/src/types.ts
+++ b/packages/builtin-tool-skills/src/types.ts
@@ -30,7 +30,8 @@ export interface ActivateSkillState {
*/
export interface ExecScriptActivatedSkill {
description?: string;
- id: string;
+ /** DB skill id; absent for filesystem/builtin activations β€” match by `name`. */
+ id?: string;
name: string;
}
@@ -46,7 +47,18 @@ export interface ExecScriptParams {
export interface ExecScriptState {
command: string;
- exitCode: number;
+ executionEnv?: 'device' | 'sandbox';
+ /**
+ * Undefined means the command was still running when the observation window
+ * elapsed β€” mirrors `CommandResult.exitCode`.
+ */
+ exitCode?: number;
+ outputFiles?: CommandResult['outputFiles'];
+ /**
+ * Shell handle for a still-running command, pollable via
+ * `local-system.getCommandOutput`.
+ */
+ shellId?: string;
success: boolean;
}
@@ -56,8 +68,31 @@ export interface RunCommandOptions {
}
export interface CommandResult {
- exitCode: number;
+ /**
+ * Where the command actually ran. Flows into the tool call's plugin state so
+ * execution-target degradation is observable in the product UI.
+ */
+ executionEnv?: 'device' | 'sandbox';
+ /**
+ * Undefined means the command was still running when the observation window
+ * elapsed β€” the formatter reports it as still running instead of completed.
+ */
+ exitCode?: number;
output: string;
+ /**
+ * Saved-output file handles reported by the shell when stdout/stderr exceed
+ * the inline preview (device runs save the full stream to disk) β€” the only
+ * retrieval path for output the preview truncated.
+ */
+ outputFiles?: {
+ stderr?: { path: string; size?: number; truncated?: boolean };
+ stdout?: { path: string; size?: number; truncated?: boolean };
+ };
+ /**
+ * Shell handle for a still-running command, pollable via
+ * `local-system.getCommandOutput`.
+ */
+ shellId?: string;
stderr?: string;
success: boolean;
}
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index 9ca4149eab0..383848a91c1 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -16,6 +16,7 @@
"dependencies": {
"@lobechat/local-file-shell": "workspace:*",
"fast-glob": "^3.3.3",
+ "fflate": "^0.8.3",
"gray-matter": "^4.0.3"
},
"devDependencies": {
diff --git a/packages/device-control/src/__tests__/skillDirectory.test.ts b/packages/device-control/src/__tests__/skillDirectory.test.ts
new file mode 100644
index 00000000000..96a059616e8
--- /dev/null
+++ b/packages/device-control/src/__tests__/skillDirectory.test.ts
@@ -0,0 +1,155 @@
+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { zipSync } from 'fflate';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { prepareSkillDirectory } from '../skillDirectory';
+
+let cacheRoot: string;
+
+const buildZip = (entries: Record<string, string>) =>
+ zipSync(
+ Object.fromEntries(
+ Object.entries(entries).map(([name, content]) => [name, new TextEncoder().encode(content)]),
+ ),
+ );
+
+const okResponse = (zip: Uint8Array) =>
+ ({
+ arrayBuffer: async () => zip.buffer.slice(zip.byteOffset, zip.byteOffset + zip.byteLength),
+ ok: true,
+ }) as Response;
+
+beforeEach(async () => {
+ cacheRoot = await mkdtemp(path.join(tmpdir(), 'skill-dir-'));
+});
+
+afterEach(async () => {
+ await rm(cacheRoot, { force: true, recursive: true });
+});
+
+describe('prepareSkillDirectory', () => {
+ it('downloads, extracts and marks the directory prepared', async () => {
+ const zip = buildZip({ 'SKILL.md': '# skill', 'scripts/run.sh': 'echo hi' });
+ const fetchSkillArchive = vi.fn(async () => okResponse(zip));
+
+ const result = await prepareSkillDirectory(
+ { url: 'https://example.com/skill.zip', zipHash: 'hash-1' },
+ { fetchSkillArchive, skillCacheRoot: cacheRoot },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.extractedDir).toBe(path.join(cacheRoot, 'extracted', 'hash-1'));
+ await expect(readFile(path.join(result.extractedDir, 'SKILL.md'), 'utf8')).resolves.toBe(
+ '# skill',
+ );
+ await expect(
+ readFile(path.join(result.extractedDir, 'scripts', 'run.sh'), 'utf8'),
+ ).resolves.toBe('echo hi');
+ const marker = JSON.parse(await readFile(path.join(result.extractedDir, '.prepared'), 'utf8'));
+ expect(marker.zipHash).toBe('hash-1');
+ });
+
+ it('is idempotent on zipHash: second call skips the download', async () => {
+ const zip = buildZip({ 'SKILL.md': '# skill' });
+ const fetchSkillArchive = vi.fn(async () => okResponse(zip));
+ const deps = { fetchSkillArchive, skillCacheRoot: cacheRoot };
+
+ await prepareSkillDirectory({ url: 'https://example.com/a.zip', zipHash: 'hash-1' }, deps);
+ const second = await prepareSkillDirectory(
+ { url: 'https://example.com/a.zip', zipHash: 'hash-1' },
+ deps,
+ );
+
+ expect(second.success).toBe(true);
+ expect(fetchSkillArchive).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-downloads when forceRefresh is set', async () => {
+ const zip = buildZip({ 'SKILL.md': '# skill' });
+ const fetchSkillArchive = vi.fn(async () => okResponse(zip));
+ const deps = { fetchSkillArchive, skillCacheRoot: cacheRoot };
+
+ await prepareSkillDirectory({ url: 'https://example.com/a.zip', zipHash: 'hash-1' }, deps);
+ await prepareSkillDirectory(
+ { forceRefresh: true, url: 'https://example.com/a.zip', zipHash: 'hash-1' },
+ deps,
+ );
+
+ expect(fetchSkillArchive).toHaveBeenCalledTimes(2);
+ });
+
+ // Two concurrent cache-missed prepares of the same zipHash used to both
+ // pass the marker check and interleave rm/extract on the live directory.
+ it('serializes concurrent prepares of the same zipHash so the follower reuses the cache', async () => {
+ const zip = buildZip({ 'SKILL.md': '# skill' });
+ let releaseFetch!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ releaseFetch = resolve;
+ });
+ const fetchSkillArchive = vi.fn(async () => {
+ await gate;
+ return okResponse(zip);
+ });
+ const deps = { fetchSkillArchive, skillCacheRoot: cacheRoot };
+
+ const first = prepareSkillDirectory(
+ { url: 'https://example.com/a.zip', zipHash: 'hash-1' },
+ deps,
+ );
+ const second = prepareSkillDirectory(
+ { url: 'https://example.com/a.zip', zipHash: 'hash-1' },
+ deps,
+ );
+ releaseFetch();
+
+ const [firstResult, secondResult] = await Promise.all([first, second]);
+ expect(firstResult.success).toBe(true);
+ expect(secondResult.success).toBe(true);
+ expect(fetchSkillArchive).toHaveBeenCalledTimes(1);
+ // The staging dir is swapped in via rename, never left behind.
+ await expect(readdir(path.join(cacheRoot, 'extracted'))).resolves.toEqual(['hash-1']);
+ });
+
+ it('rejects zipHash values that are not plain content-hash tokens', async () => {
+ const fetchSkillArchive = vi.fn();
+
+ const result = await prepareSkillDirectory(
+ { url: 'https://example.com/a.zip', zipHash: '../../../etc' },
+ { fetchSkillArchive, skillCacheRoot: cacheRoot },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('Invalid zipHash');
+ expect(result.extractedDir).toBe('');
+ expect(fetchSkillArchive).not.toHaveBeenCalled();
+ });
+
+ it('rejects archives with path traversal entries', async () => {
+ const zip = buildZip({ '../evil.txt': 'pwned' });
+
+ const result = await prepareSkillDirectory(
+ { url: 'https://example.com/evil.zip', zipHash: 'hash-evil' },
+ { fetchSkillArchive: async () => okResponse(zip), skillCacheRoot: cacheRoot },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('Unsafe file path');
+ });
+
+ it('returns a failure result when the download fails', async () => {
+ const result = await prepareSkillDirectory(
+ { url: 'https://example.com/missing.zip', zipHash: 'hash-404' },
+ {
+ fetchSkillArchive: async () =>
+ ({ ok: false, status: 404, statusText: 'Not Found' }) as Response,
+ skillCacheRoot: cacheRoot,
+ },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('404');
+ });
+});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 702ddecdf37..e82e9306964 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -22,11 +22,13 @@ import {
writeLocalFile,
} from '@lobechat/local-file-shell';
+import { prepareSkillDirectory } from './skillDirectory';
import type {
DeviceControlDeps,
InitWorkspaceParams,
ListProjectSkillsParams,
LocalFilePreviewUrlParams,
+ PrepareSkillDirectoryParams,
ProjectFileIndexParams,
ProjectFileSearchParams,
} from './types';
@@ -41,6 +43,7 @@ import { initWorkspace, listProjectSkills, statPath } from './workspace';
export const DEVICE_RPC_METHODS = [
'initWorkspace',
'listProjectSkills',
+ 'prepareSkillDirectory',
'statPath',
'getProjectFileIndex',
'searchProjectFiles',
@@ -95,6 +98,10 @@ export const executeDeviceRpc = async (
return listProjectSkills(params as ListProjectSkillsParams, deps);
}
+ case 'prepareSkillDirectory': {
+ return prepareSkillDirectory(params as PrepareSkillDirectoryParams, deps);
+ }
+
case 'statPath': {
return statPath(params as { path: string });
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 36f010303dc..51f100ad803 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -1,5 +1,6 @@
export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';
export { defaultGetLocalFilePreview } from './filePreview';
export { defaultGetProjectFileIndex, defaultSearchProjectFiles } from './projectFileIndex';
+export { defaultSkillCacheRoot, prepareSkillDirectory } from './skillDirectory';
export * from './types';
export { initWorkspace, listProjectSkills, statPath } from './workspace';
diff --git a/packages/device-control/src/skillDirectory.ts b/packages/device-control/src/skillDirectory.ts
new file mode 100644
index 00000000000..2240c350772
--- /dev/null
+++ b/packages/device-control/src/skillDirectory.ts
@@ -0,0 +1,144 @@
+import { constants } from 'node:fs';
+import { access, mkdir, rename, rm, writeFile } from 'node:fs/promises';
+import * as os from 'node:os';
+import path from 'node:path';
+
+import { unzipSync } from 'fflate';
+
+import type {
+ PrepareSkillDirectoryParams,
+ PrepareSkillDirectoryResult,
+ SkillDirectoryDeps,
+} from './types';
+
+/**
+ * Portable default cache root, following the CLI's `~/.lobehub` convention
+ * (see `apps/cli/src/settings`). The desktop injects its
+ * `<appStoragePath>/file-storage/skills` dir instead so the gateway RPC path
+ * shares one cache with the renderer-IPC path (`LocalFileCtr`).
+ */
+export const defaultSkillCacheRoot = () => path.join(os.homedir(), '.lobehub', 'skills');
+
+/**
+ * In-flight preparations keyed by extraction dir. Concurrent same-hash calls
+ * (e.g. two execScript tool calls batched in one step, or a forceRefresh
+ * racing a cache miss) would otherwise both miss the `.prepared` marker and
+ * interleave rm/extract on the live cache path β€” deleting files out from
+ * under a command that already received that directory as its cwd. Chaining
+ * serializes them per key; the follower then hits the marker fast-path.
+ * In-process is enough: the desktop main process and the CLI daemon use
+ * separate cache roots, so a key is never contended across processes.
+ */
+const inflightPrepares = new Map<string, Promise<PrepareSkillDirectoryResult>>();
+
+/**
+ * Download and extract a skill archive into the device-local cache, keyed by
+ * `zipHash` with a `.prepared` marker for idempotency. Shared by the desktop
+ * main process (renderer IPC + gateway RPC) and the CLI daemon so both hosts
+ * expose the same skill-execution surface.
+ *
+ * Layout mirrors the original desktop implementation (`LocalFileCtr`):
+ * `<cacheRoot>/extracted/<zipHash>/` + `<cacheRoot>/archives/<zipHash>.zip`.
+ */
+export const prepareSkillDirectory = async (
+ params: PrepareSkillDirectoryParams,
+ deps: SkillDirectoryDeps = {},
+): Promise<PrepareSkillDirectoryResult> => {
+ const { forceRefresh, url, zipHash } = params;
+
+ // `zipHash` arrives over the device RPC channel and keys filesystem paths β€”
+ // including a recursive rm of the extraction dir on refresh β€” so reject
+ // anything that isn't a plain content-hash-like token before deriving any
+ // path (defense in depth alongside the zip-slip guard below).
+ if (!/^[\w-]+$/.test(zipHash)) {
+ return {
+ error: `Invalid zipHash: expected a content hash, got "${zipHash}"`,
+ extractedDir: '',
+ success: false,
+ zipPath: '',
+ };
+ }
+
+ const cacheRoot = deps.skillCacheRoot ?? defaultSkillCacheRoot();
+ const extractedDir = path.join(cacheRoot, 'extracted', zipHash);
+ const markerPath = path.join(extractedDir, '.prepared');
+ const zipPath = path.join(cacheRoot, 'archives', `${zipHash}.zip`);
+
+ const run = async (): Promise<PrepareSkillDirectoryResult> => {
+ try {
+ if (!forceRefresh) {
+ await access(markerPath, constants.F_OK);
+ return { extractedDir, success: true, zipPath };
+ }
+ } catch {
+ // Cache miss, continue preparing the local copy.
+ }
+
+ try {
+ const fetchImpl = deps.fetchSkillArchive ?? fetch;
+ const response = await fetchImpl(url);
+ if (!response.ok) {
+ throw new Error(
+ `Failed to download skill package: ${response.status} ${response.statusText}`,
+ );
+ }
+
+ const buffer = Buffer.from(await response.arrayBuffer());
+ const extractedFiles = unzipSync(new Uint8Array(buffer));
+
+ // Extract into a staging dir and swap it in with a rename: the live
+ // cache path never exposes a partially written tree, and the window
+ // where a running command's cwd is replaced shrinks from the whole
+ // download+extract to two metadata ops. The zipHash validation above
+ // (no leading dot allowed) guarantees staging dirs can't collide with
+ // real hash dirs.
+ const stagingDir = path.join(cacheRoot, 'extracted', `.staging-${zipHash}`);
+ await rm(stagingDir, { force: true, recursive: true });
+ await mkdir(path.dirname(zipPath), { recursive: true });
+ await mkdir(stagingDir, { recursive: true });
+ await writeFile(zipPath, buffer);
+
+ for (const [relativePath, fileContent] of Object.entries(extractedFiles)) {
+ if (relativePath.endsWith('/')) continue;
+
+ const targetPath = path.resolve(stagingDir, relativePath);
+ const normalizedRoot = `${path.resolve(stagingDir)}${path.sep}`;
+ if (targetPath !== path.resolve(stagingDir) && !targetPath.startsWith(normalizedRoot)) {
+ throw new Error(`Unsafe file path in skill archive: ${relativePath}`);
+ }
+
+ await mkdir(path.dirname(targetPath), { recursive: true });
+ await writeFile(targetPath, Buffer.from(fileContent as Uint8Array));
+ }
+
+ await writeFile(
+ path.join(stagingDir, '.prepared'),
+ JSON.stringify({ preparedAt: Date.now(), url, zipHash }),
+ 'utf8',
+ );
+
+ await rm(extractedDir, { force: true, recursive: true });
+ await rename(stagingDir, extractedDir);
+
+ return { extractedDir, success: true, zipPath };
+ } catch (error) {
+ return {
+ error: (error as Error).message,
+ extractedDir,
+ success: false,
+ zipPath,
+ };
+ }
+ };
+
+ // Serialize per extraction dir (see inflightPrepares). `run` never rejects,
+ // so chaining with `.then(run)` is safe.
+ const previous = inflightPrepares.get(extractedDir);
+ const task = previous ? previous.then(run) : run();
+ inflightPrepares.set(extractedDir, task);
+ try {
+ return await task;
+ } finally {
+ if (inflightPrepares.get(extractedDir) === task) inflightPrepares.delete(extractedDir);
+ }
+};
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 12c8e788a8e..5fb8a72c3ea 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -133,6 +133,36 @@ export interface ProjectFileSearchResult {
source: 'git' | 'glob';
}
+// ─── Skill directory ───
+
+export interface PrepareSkillDirectoryParams {
+ forceRefresh?: boolean;
+ /** Presigned download URL of the skill zip archive. */
+ url: string;
+ /** Content hash of the archive β€” the idempotency key for the local cache. */
+ zipHash: string;
+}
+
+export interface PrepareSkillDirectoryResult {
+ error?: string;
+ /** Device-local directory the archive was extracted into. */
+ extractedDir: string;
+ success: boolean;
+ zipPath: string;
+}
+
+/**
+ * Host hooks for the skill-archive cache. Both are optional: the CLI daemon
+ * runs on the portable defaults; the desktop injects both so the gateway RPC
+ * path shares the cache (and proxy-aware fetch) with its renderer-IPC path.
+ */
+export interface SkillDirectoryDeps {
+ /** Fetch used to download skill archives. Desktop injects Electron's `net` fetch (proxy-aware); defaults to global `fetch`. */
+ fetchSkillArchive?: (url: string) => Promise<Response>;
+ /** Skill zip cache root. Desktop: `<appStoragePath>/file-storage/skills`; defaults to `~/.lobehub/skills`. */
+ skillCacheRoot?: string;
+}
+
/**
* The subset of platform hooks the workspace-scan helpers need. Kept narrow so
* the desktop's local-IPC `WorkspaceCtr` can reuse `initWorkspace` /
@@ -156,7 +186,7 @@ export interface WorkspaceScanDeps {
* - The CLI uses the portable defaults exported from this package
* (`defaultGetLocalFilePreview`, `defaultGetProjectFileIndex`).
*/
-export interface DeviceControlDeps extends WorkspaceScanDeps {
+export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps {
/** Read a local file preview (host-gated on desktop; disk read on CLI). */
getLocalFilePreview: (params: LocalFilePreviewUrlParams) => Promise<LocalFilePreviewResult>;
/** Build the project file index. */
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index 88171e8da89..d02725aaef1 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -35,7 +35,12 @@ export interface StepContextTodos {
*/
export interface StepActivatedSkill {
description?: string;
- id: string;
+ /**
+ * DB skill id. Absent for filesystem (project/device) and builtin skill
+ * activations, whose persisted state carries no id β€” consumers match by
+ * `name` (the server exec paths resolve archives/project skills by name).
+ */
+ id?: string;
name: string;
}
diff --git a/src/services/electron/__tests__/desktopSkillRuntime.test.ts b/src/services/electron/__tests__/desktopSkillRuntime.test.ts
index 760d9a5f6ac..f4522d191f7 100644
--- a/src/services/electron/__tests__/desktopSkillRuntime.test.ts
+++ b/src/services/electron/__tests__/desktopSkillRuntime.test.ts
@@ -92,6 +92,64 @@ describe('desktopSkillRuntimeService', () => {
expect(result).toBe('/tmp/demo-skill');
});
+ // id-less builtin/filesystem activations reach the desktop runtime since the
+ // shared extractor keeps them β€” they never resolve to a packaged skill and
+ // must not shadow one activated before/after them (last resolvable wins).
+ it('should skip id-less unresolvable activations and use the last packaged skill', async () => {
+ getByIdMock.mockResolvedValue({
+ id: 'skill-1',
+ name: 'demo-skill',
+ zipFileHash: 'zip-hash-1',
+ });
+ getByNameMock.mockResolvedValue(undefined);
+ getZipUrlMock.mockResolvedValue({
+ name: 'demo-skill',
+ url: 'https://example.com/demo-skill.zip',
+ });
+ prepareSkillDirectoryMock.mockResolvedValue({
+ extractedDir: '/tmp/demo-skill',
+ success: true,
+ zipPath: '/tmp/demo-skill.zip',
+ });
+
+ const result = await desktopSkillRuntimeService.resolveExecutionDirectory([
+ { name: 'builtin-skill' },
+ { id: 'skill-1', name: 'demo-skill' },
+ { name: 'project-skill' },
+ ]);
+
+ expect(getByNameMock).toHaveBeenCalledWith('project-skill');
+ expect(getByIdMock).toHaveBeenCalledWith('skill-1');
+ expect(result).toBe('/tmp/demo-skill');
+ // The walk stops at the packaged skill β€” earlier activations are not resolved.
+ expect(getByNameMock).not.toHaveBeenCalledWith('builtin-skill');
+ });
+
+ it('should prepare the most recently activated packaged skill when several resolve', async () => {
+ getByIdMock.mockImplementation(async (id: string) =>
+ id === 'skill-1'
+ ? { id: 'skill-1', name: 'first-skill', zipFileHash: 'zip-hash-1' }
+ : { id: 'skill-2', name: 'second-skill', zipFileHash: 'zip-hash-2' },
+ );
+ getZipUrlMock.mockResolvedValue({
+ name: 'second-skill',
+ url: 'https://example.com/second-skill.zip',
+ });
+ prepareSkillDirectoryMock.mockResolvedValue({
+ extractedDir: '/tmp/second-skill',
+ success: true,
+ zipPath: '/tmp/second-skill.zip',
+ });
+
+ const result = await desktopSkillRuntimeService.resolveExecutionDirectory([
+ { id: 'skill-1', name: 'first-skill' },
+ { id: 'skill-2', name: 'second-skill' },
+ ]);
+
+ expect(getZipUrlMock).toHaveBeenCalledWith('skill-2');
+ expect(result).toBe('/tmp/second-skill');
+ });
+
it('should return undefined when the skill has no packaged zip', async () => {
getByIdMock.mockResolvedValue({
id: 'skill-1',
diff --git a/src/services/electron/desktopSkillRuntime.ts b/src/services/electron/desktopSkillRuntime.ts
index ea76ad18f28..fc13d183b87 100644
--- a/src/services/electron/desktopSkillRuntime.ts
+++ b/src/services/electron/desktopSkillRuntime.ts
@@ -35,12 +35,21 @@ class DesktopSkillRuntimeService {
async resolveExecutionDirectory(
activatedSkills?: ExecScriptActivatedSkill[],
): Promise<string | undefined> {
- // Use the first activated skill to resolve the execution directory
- const firstSkill = activatedSkills?.[0];
- if (!firstSkill) return undefined;
+ if (!activatedSkills?.length) return undefined;
+
+ // Walk from the most recent activation and use the first one that
+ // resolves to a packaged (zip-backed) DB skill β€” id-less filesystem/
+ // builtin activations never resolve here and must not shadow a packaged
+ // skill activated before/after them. Mirrors the server exec paths'
+ // "last resolvable skill wins the cwd" semantics.
+ for (const activated of [...activatedSkills].reverse()) {
+ const skill = await this.resolveSkill({ id: activated.id, name: activated.name });
+ if (!skill?.zipFileHash) continue;
+
+ return this.prepareSkillDirectoryForSkill(skill);
+ }
- const skill = await this.resolveSkill({ id: firstSkill.id, name: firstSkill.name });
- return this.prepareSkillDirectoryForSkill(skill);
+ return undefined;
}
async resolveReferenceFullPath(params: {
diff --git a/src/store/chat/slices/message/selectors/dbMessage.ts b/src/store/chat/slices/message/selectors/dbMessage.ts
index d66488582a9..5a007788ecd 100644
--- a/src/store/chat/slices/message/selectors/dbMessage.ts
+++ b/src/store/chat/slices/message/selectors/dbMessage.ts
@@ -1,5 +1,5 @@
+import { extractActivatedSkillsFromMessages } from '@lobechat/agent-runtime';
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
-import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import {
type StepActivatedSkill,
type StepContextTodos,
@@ -202,52 +202,7 @@ export const selectActivatedToolIdsFromMessages = (
*/
export const selectActivatedSkillsFromMessages = (
messages: UIChatMessage[],
-): StepActivatedSkill[] | undefined => {
- const skillsMap = new Map<string, StepActivatedSkill>();
-
- for (const msg of messages) {
- if (
- msg.role !== 'tool' ||
- !(
- msg.plugin?.identifier === SkillsIdentifier ||
- msg.plugin?.identifier === LobeActivatorIdentifier
- )
- )
- continue;
-
- // Direct activateSkill calls β€” state has top-level id/name
- if (msg.plugin?.apiName === 'activateSkill' && msg.pluginState?.id && msg.pluginState?.name) {
- const id = msg.pluginState.id as string;
- skillsMap.set(id, {
- description: msg.pluginState.description as string | undefined,
- id,
- name: msg.pluginState.name as string,
- });
- }
-
- // activateTools fallback β€” skills nested in pluginState.activatedSkills[]
- if (
- msg.plugin?.apiName === 'activateTools' &&
- Array.isArray(msg.pluginState?.activatedSkills)
- ) {
- for (const skill of msg.pluginState.activatedSkills as Array<{
- description?: string;
- id?: string;
- name?: string;
- }>) {
- if (skill.id && skill.name) {
- skillsMap.set(skill.id, {
- description: skill.description,
- id: skill.id,
- name: skill.name,
- });
- }
- }
- }
- }
-
- return skillsMap.size > 0 ? [...skillsMap.values()] : undefined;
-};
+): StepActivatedSkill[] | undefined => extractActivatedSkillsFromMessages(messages);
// ============= Todos Selectors ========== //