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(cli): stop timed-out eval agents and repair device tools (#21515)

Rylan Cai6183ee3ce162
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/adapter.py b/.agents/skills/run-eval-harbor/scripts/lh/adapter.py
index 3bedd081b61..f177d41f56c 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/adapter.py
+++ b/.agents/skills/run-eval-harbor/scripts/lh/adapter.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import asyncio
import json
+import logging
import shlex
from collections.abc import Callable
from pathlib import Path
@@ -149,6 +151,21 @@ class LhAdapter:
)
return [login, connect, ready, run]
+ async def run(self, environment: Any, exec_as_agent: Callable, instruction: str) -> None:
+ try:
+ for command in self.run_commands(instruction):
+ await exec_as_agent(environment, command=command)
+ except asyncio.CancelledError:
+ try:
+ await exec_as_agent(
+ environment,
+ command=f"node {RUN_AGENT_PATH} --stop",
+ timeout_sec=180,
+ )
+ except Exception:
+ logging.getLogger(__name__).exception("Failed to stop LobeHub agent after cancellation")
+ raise
+
@staticmethod
def populate_context(logs_dir: Path, context: Any) -> None:
try:
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/agent.py b/.agents/skills/run-eval-harbor/scripts/lh/agent.py
index 1dba6ef3307..1c5ab9caaa5 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/agent.py
+++ b/.agents/skills/run-eval-harbor/scripts/lh/agent.py
@@ -83,8 +83,7 @@ class LhInstalledAgent(BaseInstalledAgent):
context: AgentContext,
) -> None:
del context
- for command in self._lh.run_commands(self.render_instruction(instruction)):
- await self.exec_as_agent(environment, command=command)
+ await self._lh.run(environment, self.exec_as_agent, self.render_instruction(instruction))
def populate_context_post_run(self, context: AgentContext) -> None:
self._lh.populate_context(self.logs_dir, context)
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/pier_agent.py b/.agents/skills/run-eval-harbor/scripts/lh/pier_agent.py
index 752bc3057be..0acacac2de8 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/pier_agent.py
+++ b/.agents/skills/run-eval-harbor/scripts/lh/pier_agent.py
@@ -90,8 +90,10 @@ class LhPierInstalledAgent(BaseInstalledAgent):
host_dir / "package.json", f"{DEV_CLI_DIR}/package.json"
)
await environment.upload_dir(host_dir / "dist", f"{DEV_CLI_DIR}/dist")
- for command in self._lh.run_commands(self.render_instruction(instruction)):
- await self.exec_as_agent(environment, command=command)
+ await self.exec_as_root(
+ environment, command="/installed-agent/install-lh.sh --install-runtime"
+ )
+ await self._lh.run(environment, self.exec_as_agent, self.render_instruction(instruction))
self.logs_dir.mkdir(parents=True, exist_ok=True)
status_log = self.logs_dir / "operation-status.jsonl"
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/template/install-lh.sh.j2 b/.agents/skills/run-eval-harbor/scripts/lh/template/install-lh.sh.j2
index a5c44faf781..66eec6d418c 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/template/install-lh.sh.j2
+++ b/.agents/skills/run-eval-harbor/scripts/lh/template/install-lh.sh.j2
@@ -31,9 +31,10 @@ if ! have_compatible_node; then
install_node
fi
-if ! command -v supervisord >/dev/null 2>&1; then
+# tree-kill uses ps to enumerate child processes on Linux.
+if ! command -v supervisord >/dev/null 2>&1 || ! command -v ps >/dev/null 2>&1; then
apt-get update
- DEBIAN_FRONTEND=noninteractive apt-get install -y supervisor
+ DEBIAN_FRONTEND=noninteractive apt-get install -y supervisor procps
fi
for bin in node npm; do
@@ -62,3 +63,24 @@ test -f /opt/lh-dev/dist/index.js
/opt/lh-dev/run-lh.sh --version
{% endif %}
{% endif %}
+
+{% if not use_system_cli %}
+{% if install_cli %}
+install_runtime=true
+{% else %}
+install_runtime=false
+{% endif %}
+if [[ "$install_runtime" == true || "${1:-}" == --install-runtime ]]; then
+ node --input-type=module <<'LH_DEPENDENCIES'
+import fs from 'node:fs/promises';
+const manifest = JSON.parse(await fs.readFile('/opt/lh-dev/package.json', 'utf8'));
+await fs.writeFile('/opt/lh-dev/package.json', JSON.stringify({
+ name: manifest.name,
+ version: manifest.version,
+ type: manifest.type,
+ dependencies: manifest.dependencies,
+}));
+LH_DEPENDENCIES
+ npm install --prefix /opt/lh-dev --omit=dev --no-audit --no-fund --package-lock=false
+fi
+{% endif %}
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.js b/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.js
index e80398c6b89..54347c2cc18 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.js
+++ b/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.js
@@ -5,6 +5,9 @@
const fs = require('node:fs');
const path = require('node:path');
const { spawn } = require('node:child_process');
+const { setTimeout: delay } = require('node:timers/promises');
+
+const CLEANUP_TIMEOUT_MS = 150_000;
const TERMINAL_STATUSES = new Set([
'done',
@@ -64,6 +67,10 @@ function parseArgs(argv) {
]);
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
+ if (flag === '--stop') {
+ options.stop = true;
+ continue;
+ }
if (!values.has(flag)) throw new RunnerError(`Unknown runner option: ${flag}`);
const value = argv[++index];
if (!value || value.startsWith('--')) throw new RunnerError(`Missing value for ${flag}`);
@@ -107,6 +114,7 @@ function parseArgs(argv) {
}
}
+ if (options.stop) return options;
for (const [name, value] of [
['--cli', options.cli],
['--prompt', options.prompt],
@@ -175,6 +183,7 @@ class AgentRunner {
this.taskUsageLog = path.join(options.logDir, 'task-usage.jsonl');
this.statusErrorsLog = path.join(options.logDir, 'operation-status-errors.log');
this.cleanupLog = path.join(options.logDir, 'device-cleanup.log');
+ this.pidPath = path.join(options.logDir, 'runner.pid');
this.operationId = undefined;
this.topicId = undefined;
this.taskId = undefined;
@@ -184,7 +193,7 @@ class AgentRunner {
this.interruptAttempted = false;
this.interruptConfirmed = false;
this.cleanupFailure = false;
- this.activeChild = undefined;
+ this.cleaningUp = false;
this.signalCode = undefined;
this.resolveSignal = undefined;
this.signalPromise = new Promise((resolve) => {
@@ -197,12 +206,23 @@ class AgentRunner {
}
requestSignal(code) {
- if (this.signalCode) return;
+ if (this.signalCode || this.cleaningUp) return;
+ this.startCleanupBudget();
this.signalCode = code;
- if (this.activeChild) this.activeChild.kill('SIGTERM');
this.resolveSignal(code);
}
+ startCleanupBudget() {
+ if (this.cleanupDeadline) return;
+ this.cleanupDeadline = Date.now() + CLEANUP_TIMEOUT_MS;
+ // Include any in-flight startup response in the same budget as cleanup.
+ this.cleanupTimer = setTimeout(() => {
+ this.cleanupFailure = true;
+ this.log('Runner cleanup deadline exceeded', true);
+ this.activeChild?.kill('SIGKILL');
+ }, CLEANUP_TIMEOUT_MS);
+ }
+
installSignalHandlers() {
for (const [signal, handler] of Object.entries(this.signalHandlers))
process.on(signal, handler);
@@ -214,7 +234,7 @@ class AgentRunner {
}
checkSignal() {
- if (this.signalCode)
+ if (this.signalCode && !this.cleaningUp)
throw new RunnerError(`Received signal (exit ${this.signalCode})`, this.signalCode);
}
@@ -224,18 +244,41 @@ class AgentRunner {
}
async wait(ms) {
- await Promise.race([
- new Promise((resolve) => setTimeout(resolve, ms)),
- this.signalPromise.then((code) => {
- throw new RunnerError(`Received signal (exit ${code})`, code);
- }),
- ]);
+ if (this.cleaningUp) {
+ const remaining = this.cleanupDeadline - Date.now();
+ if (remaining <= 0) throw new RunnerError('Runner cleanup deadline exceeded');
+ return delay(Math.min(ms, remaining));
+ }
+ let timer;
+ try {
+ await Promise.race([
+ new Promise((resolve) => {
+ timer = setTimeout(resolve, ms);
+ }),
+ this.signalPromise.then((code) => {
+ throw new RunnerError(`Received signal (exit ${code})`, code);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
this.checkSignal();
}
- exec(command, args) {
+ exec(command, args, timeoutMs = 30_000) {
return new Promise((resolve, reject) => {
- const child = spawn(command, args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ const remaining = this.cleanupDeadline ? this.cleanupDeadline - Date.now() : Infinity;
+ if (remaining <= 0) {
+ reject(new RunnerError('Runner cleanup deadline exceeded'));
+ return;
+ }
+ const timeout = Math.min(timeoutMs || Infinity, remaining);
+ const child = spawn(command, args, {
+ env: process.env,
+ killSignal: 'SIGKILL',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: Number.isFinite(timeout) ? timeout : 0,
+ });
this.activeChild = child;
let stdout = '';
let stderr = '';
@@ -258,10 +301,9 @@ class AgentRunner {
});
}
- async runCli(args) {
- this.checkSignal();
- const result = await this.exec(this.options.cli, args);
+ async runCli(args, timeoutMs) {
this.checkSignal();
+ const result = await this.exec(this.options.cli, args, timeoutMs);
if (result.code !== 0) {
throw new RunnerError(
`CLI failed (${result.code}): ${result.stderr.trim() || result.stdout.trim() || args.join(' ')}`,
@@ -276,35 +318,41 @@ class AgentRunner {
async startRun() {
if (this.options.runMode === 'agent') {
- return this.runCli([
- 'agent',
- 'run',
- '--agent-id',
- this.options.agentId,
- '--prompt',
- this.options.prompt,
- '--device',
- 'local',
- '--detach',
- '--json',
- ]);
+ return this.runCli(
+ [
+ 'agent',
+ 'run',
+ '--agent-id',
+ this.options.agentId,
+ '--prompt',
+ this.options.prompt,
+ '--device',
+ 'local',
+ '--detach',
+ '--json',
+ ],
+ 0,
+ );
}
- const task = await this.runCli([
- 'task',
- 'create',
- '--instruction',
- this.options.prompt,
- '--agent',
- this.options.agentId,
- '--json',
- ]);
+ const task = await this.runCli(
+ [
+ 'task',
+ 'create',
+ '--instruction',
+ this.options.prompt,
+ '--agent',
+ this.options.agentId,
+ '--json',
+ ],
+ 0,
+ );
if (typeof task?.id !== 'string') throw new RunnerError('lh task create returned no task ID');
this.taskId = task.id;
fs.mkdirSync(path.dirname(this.taskUsageLog), { recursive: true });
fs.closeSync(fs.openSync(this.taskUsageLog, 'a'));
this.log(`Task: ${task.identifier || task.id}`);
- return this.runCli(['task', 'run', task.id, '--device', 'local', '--json']);
+ return this.runCli(['task', 'run', task.id, '--device', 'local', '--json'], 0);
}
async resolveAgentId() {
@@ -327,6 +375,8 @@ class AgentRunner {
async run() {
this.installSignalHandlers();
try {
+ await fs.promises.mkdir(this.options.logDir, { recursive: true });
+ await fs.promises.writeFile(this.pidPath, JSON.stringify({ pid: process.pid }));
if (!fs.existsSync(this.options.deviceReady)) {
throw new RunnerError(`lh local device is not ready: ${this.options.deviceReady}`);
}
@@ -387,8 +437,26 @@ class AgentRunner {
await this.wait(this.options.pollMs);
}
} finally {
- await this.cleanup();
- this.removeSignalHandlers();
+ this.startCleanupBudget();
+ this.cleaningUp = true;
+ try {
+ await this.cleanup();
+ } finally {
+ clearTimeout(this.cleanupTimer);
+ await fs.promises.rm(this.pidPath, { force: true });
+ this.removeSignalHandlers();
+ }
+ }
+ }
+
+ async stop() {
+ const pid = readJson(this.pidPath)?.pid;
+ if (!pid) return;
+ process.kill(pid, 'SIGTERM');
+ const deadline = Date.now() + CLEANUP_TIMEOUT_MS + 20_000;
+ while (fs.existsSync(this.pidPath)) {
+ if (Date.now() >= deadline) throw new RunnerError('Timed out waiting for runner cleanup');
+ await delay(200);
}
}
@@ -404,7 +472,7 @@ class AgentRunner {
if (result.kind === 'unavailable') appendLine(this.statusErrorsLog, result.error);
return result;
} catch (error) {
- if (error instanceof RunnerError && this.signalCode) throw error;
+ if (error instanceof RunnerError && this.signalCode && !this.cleaningUp) throw error;
appendLine(this.statusErrorsLog, error.message);
return { kind: 'unavailable', error: error.message };
}
@@ -464,7 +532,7 @@ class AgentRunner {
await this.captureSnapshot();
return true;
}
- await this.wait(Math.min(this.options.pollMs, deadline - Date.now()));
+ await this.wait(Math.min(1000, deadline - Date.now()));
}
} catch (error) {
this.log(`Agent interrupt failed: ${error.message}`, true);
@@ -504,10 +572,10 @@ class AgentRunner {
}
async cleanup() {
- await this.captureSnapshot();
if (this.operationId && !this.operationTerminal && !this.interruptAttempted) {
await this.interruptAndWait();
}
+ await this.captureSnapshot();
if (this.topicId) {
try {
@@ -542,6 +610,7 @@ class AgentRunner {
if (!this.deviceId) return;
if (!this.operationTerminal && !this.interruptConfirmed) {
+ this.cleanupFailure = true;
this.log(`Keeping device ${this.deviceId}: operation termination was not acknowledged`, true);
return;
}
@@ -569,6 +638,7 @@ class AgentRunner {
async function main() {
const runner = new AgentRunner(parseArgs(process.argv.slice(2)));
try {
+ if (runner.options.stop) return await runner.stop();
await runner.run();
if (runner.cleanupFailure) process.exitCode = 1;
} catch (error) {
diff --git a/apps/cli/src/tools/file.test.ts b/apps/cli/src/tools/file.test.ts
index 29e746911d7..5879b957990 100644
--- a/apps/cli/src/tools/file.test.ts
+++ b/apps/cli/src/tools/file.test.ts
@@ -3,7 +3,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
editLocalFile,
@@ -23,6 +23,7 @@ describe('file tools (integration wrapper)', () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
fs.rmSync(tmpDir, { force: true, recursive: true });
});
@@ -77,13 +78,32 @@ describe('file tools (integration wrapper)', () => {
expect(result.files).not.toContain('b.js');
});
- it('should re-export grepContent from shared package', async () => {
- await writeFile(path.join(tmpDir, 'search.txt'), 'hello world');
+ it('searches a single file without external search tools', async () => {
+ vi.stubEnv('PATH', '');
+ const filePath = path.join(tmpDir, 'search.txt');
+ await writeFile(filePath, 'hello world\nother\nHELLO again');
+
+ const result = await grepContent({
+ '-i': true,
+ '-n': true,
+ 'output_mode': 'content',
+ 'pattern': 'hello',
+ 'scope': filePath,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.matches).toEqual([`${filePath}:1:hello world`, `${filePath}:3:HELLO again`]);
+ });
+
+ it('preserves the legacy filePattern filter', async () => {
+ vi.stubEnv('PATH', '');
+ await writeFile(path.join(tmpDir, 'match.ts'), 'hello');
+ await writeFile(path.join(tmpDir, 'ignored.txt'), 'hello');
- const result = await grepContent({ cwd: tmpDir, pattern: 'hello' });
+ const result = await grepContent({ cwd: tmpDir, filePattern: '*.ts', pattern: 'hello' });
- expect(result).toHaveProperty('success');
- expect(result).toHaveProperty('matches');
+ expect(result.success).toBe(true);
+ expect(result.matches).toEqual([path.join(tmpDir, 'match.ts')]);
});
it('should re-export searchLocalFiles from shared package', async () => {
diff --git a/apps/cli/src/tools/file.ts b/apps/cli/src/tools/file.ts
index 95dfcca95a9..7f41b415c71 100644
--- a/apps/cli/src/tools/file.ts
+++ b/apps/cli/src/tools/file.ts
@@ -1,20 +1,28 @@
+import type {
+ GrepContentParams,
+ ReadFileParams,
+ UploadedImageRecord,
+} from '@lobechat/local-file-shell';
import {
getLocalImageMimeType,
- type ReadFileParams,
readLocalFile as readLocalTextFile,
readLocalImageFile,
- type UploadedImageRecord,
} from '@lobechat/local-file-shell';
+import { createContentSearchImpl } from '@lobechat/local-file-shell/content-search';
export {
editLocalFile,
globLocalFiles,
- grepContent,
listLocalFiles,
searchLocalFiles,
writeLocalFile,
} from '@lobechat/local-file-shell';
+const contentSearch = createContentSearchImpl();
+
+export const grepContent = (params: GrepContentParams) =>
+ contentSearch.grep({ ...params, glob: params.glob ?? params.filePattern });
+
/** Uploads a local image to file storage with the connected device's credentials. */
export type ImageUploader = (filePath: string) => Promise<UploadedImageRecord | undefined>;