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): never auto-retry failed lobe-skills runCommand / execScript (#19989)

Arvin Xuf5107f74ea78
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 affed7fc147..e95d075b287 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts
@@ -217,6 +217,81 @@ describe('skillsRuntime', () => {
30_000,
);
+ it.each(
+ (['runCommand', 'execScript', 'exportFile'] as const).flatMap((api) =>
+ (['returned', 'thrown', 'stderr'] as const)
+ .filter((mode) => api !== 'exportFile' || mode !== 'stderr')
+ .map((mode) => ({ api, mode })),
+ ),
+ )(
+ 'does not replay the side-effecting $api after a $mode timeout',
+ async ({ api, mode }) => {
+ const { executeToolWithRetry } = await import('@lobechat/agent-runtime');
+ const { skillsRuntime } = await import('../skills');
+ const { ToolExecutionService } = await import('../../index');
+ // A timeout at the gateway says nothing about whether the command ran:
+ // the sandbox may already have launched it, so replaying it re-runs any
+ // non-idempotent side effect (a background script started three times).
+ const error = { message: 'Gateway Timeout', name: 'MarketAPIError' };
+ const call =
+ mode === 'returned'
+ ? vi
+ .fn()
+ .mockResolvedValue({ error, filename: 'page.html', result: null, success: false })
+ : mode === 'thrown'
+ ? vi
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('Gateway Timeout'), { status: 504 }))
+ : vi.fn().mockResolvedValue({
+ result: {
+ exitCode: 28,
+ stderr: 'curl: (28) Connection timed out after 30001 milliseconds',
+ stdout: '',
+ success: false,
+ },
+ success: true,
+ });
+ mocks.sandboxService.callTool.mockImplementation(call);
+ mocks.sandboxService.exportAndUploadFile.mockImplementation(call);
+ const runtime = await skillsRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ const execute = () =>
+ api === 'exportFile'
+ ? runtime.exportFile({ path: '/page.html', filename: 'page.html' })
+ : runtime[api]({ command: 'nohup python extract.py &', description: 'Extract' });
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: { execute } as never,
+ mcpService: {} as never,
+ });
+
+ const { attempts, result } = await executeToolWithRetry(
+ () =>
+ service.executeTool(
+ {
+ apiName: api,
+ arguments: '{}',
+ id: 'side-effect',
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ },
+ { toolManifestMap: {} },
+ ),
+ // Same budget as the server tool transport (TOOL_MAX_RETRIES).
+ { maxRetries: 2 },
+ );
+
+ expect(call).toHaveBeenCalledTimes(1);
+ expect(attempts).toBe(1);
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ kind: 'stop' });
+ },
+ 60_000,
+ );
+
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
index 116fae42183..081807144f6 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts
@@ -22,6 +22,7 @@ import {
type SkillListItem,
type SkillResourceContent,
} from '@lobechat/types';
+import { toRecord } from '@lobechat/utils/object';
import debug from 'debug';
import { AgentModel } from '@/database/models/agent';
@@ -49,6 +50,18 @@ import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:skills-runtime');
+/**
+ * Shell runs and file exports have side effects, so a failure must never be
+ * replayed: a gateway timeout or dropped response says nothing about whether
+ * the sandbox already ran the command, and a non-zero exit proves it did.
+ * Without an explicit kind the tool error classifier matches words like
+ * "timeout" in the message and the transport re-executes the call β€” a
+ * background launch then ran three times. Mirrors ComputerRuntime, where only
+ * read-only operations may use the classifier's retry.
+ */
+const withoutReplay = <T extends { error?: unknown; success: boolean }>(result: T): T =>
+ result.success ? result : { ...result, error: { ...toRecord(result.error), kind: 'stop' } };
+
interface UserSettingsWithMarketToken {
market?: {
accessToken?: string;
@@ -250,7 +263,10 @@ class SkillServerRuntimeService implements SkillRuntimeService {
return this.resourceService.readResource(skill.resources, path);
};
- runCommand = async (options: { command: string }): Promise<CommandResult> => {
+ runCommand = async (options: { command: string }): Promise<CommandResult> =>
+ withoutReplay(await this.runCommandInSandbox(options));
+
+ private runCommandInSandbox = 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
@@ -569,18 +585,18 @@ class SkillServerRuntimeService implements SkillRuntimeService {
// 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;
+ if (deviceResult !== LEGACY_DEVICE_CLIENT) return withoutReplay(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 {
+ return withoutReplay({
...sandboxResult,
stderr: [sandboxResult.stderr, LEGACY_FALLBACK_NOTE].filter(Boolean).join('\n'),
- };
+ });
}
- return this.execScriptInSandbox(command, options);
+ return withoutReplay(await this.execScriptInSandbox(command, options));
};
private execScriptInSandbox = async (
@@ -664,7 +680,13 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}
};
- exportFile = async (path: string, filename: string): Promise<ExportFileResult> => {
+ exportFile = async (path: string, filename: string): Promise<ExportFileResult> =>
+ withoutReplay(await this.exportFileFromSandbox(path, filename));
+
+ private exportFileFromSandbox = 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) {