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.

✨ feat(cli): support detached Harbor agent runs (#19657)

Rylan Caice857cbc69db
diff --git a/.agents/skills/run-eval-harbor/SKILL.md b/.agents/skills/run-eval-harbor/SKILL.md
index fee7934c64d..183f953de47 100644
--- a/.agents/skills/run-eval-harbor/SKILL.md
+++ b/.agents/skills/run-eval-harbor/SKILL.md
@@ -1,6 +1,6 @@
---
name: run-eval-harbor
-description: 'Run and diagnose existing Harbor evaluations against local production LobeHub or LobeHub Cloud. Use for eval infrastructure, target preflight, lh CLI injection, Harbor smoke or job runs, resume, and failure triage. Excludes authoring Harbor tasks and product acceptance.'
+description: 'Run and diagnose existing Harbor or FrontierHarness evaluations against local production LobeHub or LobeHub Cloud, on a local Docker host, SSH worker, or Runta. Use for eval infrastructure, target preflight, lh CLI injection, Harbor smoke or job runs, resume, and failure triage. Excludes authoring Harbor tasks and product acceptance.'
---
# Run Eval Harbor
@@ -11,19 +11,33 @@ grade tasks and `acceptance` for product acceptance.
## Ask First
-Before preparing or running anything, obtain these independent choices:
-
-1. Target: `local` production server from this checkout, or `cloud`/remote.
-2. CLI: `checkout` build from `apps/cli`, or published `npm` release.
-3. Exact `LH_AGENT_ID`; the selected agent already owns its model.
-4. Eval repository path and whether the user wants a new job or a resume.
-5. Credentials: for cloud, require its CLI API key in the eval repository's
- ignored `.env`. For local, ask whether the selected agent's provider
- credential is already stored in LobeHub; if not, ask for the provider's real
- environment variable name and secret before starting the server.
-6. For local, obtain explicit confirmation that port `3210` and every configured
- eval infrastructure port are unreachable from the public internet and other
- untrusted networks. Do not bootstrap the local stack without confirmation.
+Before preparing or running anything, obtain these independent choices. Do not
+use `runta` as a LobeHub server target or `checkout` as an execution environment:
+
+1. LobeHub server: `local` production server from this checkout, or
+ `cloud`/remote.
+2. Execution environment: this local host, an SSH Docker worker, or Runta runtimes. The maintained
+ Runta workflow currently targets a cloud/remote LobeHub server.
+3. CLI source: `checkout` build from `apps/cli`, or published `npm` release.
+4. Agent selection: cloud requires an exact `LH_AGENT_ID`; local uses the seeded
+ user's builtin `inbox` agent unless the user explicitly selects a different
+ agent.
+5. Eval repository path and whether the user wants a new job or a resume.
+6. Credentials: for cloud, require its CLI API key in the eval repository's
+ ignored `.env`. Local bootstrap seeds its CLI key. Reuse a provider
+ credential already configured in LobeHub or the ignored local env; if the
+ smoke reports `InvalidProviderAPIKey`, report the resolved agent's
+ provider/model and ask only for that provider's real credential.
+7. For a local LobeHub server, obtain explicit confirmation that port `3210` and
+ every configured eval infrastructure port are unreachable from the public
+ internet and other untrusted networks. Do not bootstrap the local stack
+ without confirmation.
+
+For the Runta execution environment, also collect the harness repository and
+pinned commit, provider/key choice required by FrontierHarness, and the
+Terminal-Bench versus DeepSWE task subset. The Lh Cloud agent's model remains
+selected by `LH_AGENT_ID`; do not replace it with FrontierHarness's `--model`
+unless the run is explicitly non-comparable.
Do not infer these choices. DeepSeek is only one provider example, not a
required credential or model.
@@ -40,8 +54,10 @@ required credential or model.
- The local Compose stack publishes host ports and uses fixed development
credentials, including the seeded CLI key and gateway service token. Never
run it on a host where those ports are reachable by an untrusted network.
-- Never infer `inbox`, choose a separate model, or override the agent with
- `DEFAULT_AGENT_CONFIG`. Never invent, print, or commit secrets.
+- Never infer `inbox` for a cloud server, choose a separate model, or override
+ the agent with `DEFAULT_AGENT_CONFIG`. A local server may resolve the isolated
+ seeded user's builtin `inbox` through the authenticated CLI. Never invent,
+ print, or commit secrets.
- LobeHub uses localhost service URLs. Harbor containers use Docker-reachable
host URLs. Never interchange them.
- Preflight is target-specific and read-only: local checks the local production
@@ -49,19 +65,44 @@ required credential or model.
agents, provider credentials, or model access.
- Do not run a model-backed Harbor job without an explicit user request.
- Before every requested real job or resume, run the shared model-backed smoke
- for the chosen target and CLI mode. Stop if either preflight or smoke fails.
+ for the chosen server target and CLI source. Stop if either preflight or smoke
+ fails.
## Run
-Read exactly one route after the answers above:
-
-- Local target: [references/local.md](references/local.md)
-- Cloud/remote target: [references/cloud.md](references/cloud.md)
-
-The CLI selection is orthogonal to the target. `checkout` injects the built
-`apps/cli`; `npm` installs the release package. Both routes run their preflight
-and then `scripts/run-smoke.sh <local|cloud> <checkout|npm> ...` before the
-external eval repository's own job command.
+Read exactly one reference for the selected LobeHub server:
+
+- Local server: [references/local.md](references/local.md)
+- Cloud/remote server: [references/cloud.md](references/cloud.md)
+
+When the execution environment is Runta, additionally read the
+[Runta/FrontierHarness playbook](references/runta.md). It overlays the cloud
+server route; it is not a third server target.
+
+For FrontierHarness on a local Docker host or SSH worker, use
+`scripts/frontierharness-local.py start` to launch Harbor/Pier queues and
+`collect` to prepare results and usage for reporting. See each subcommand's `--help`.
+
+CLI source is orthogonal to the server target and execution environment:
+`checkout` injects the built `apps/cli`; `npm` installs the release package. For
+local execution, run the selected server preflight and then
+`scripts/run-smoke.sh <local|cloud> <checkout|npm> ...` before the external eval
+repository's own job command. The maintained Runta workflow uses a checkout CLI
+artifact, two restored suite runtimes, and a detached start/status/collect
+workflow; do not substitute a normal Harbor job for it.
+
+Harbor and Pier default to `LH_RUN_MODE=agent`. Set `LH_RUN_MODE=task` to create
+one persistent LobeHub Task per trial and run it on the connected eval device;
+operation polling, output collection, and device cleanup remain the same. Task
+mode records usage with `lh task usage`; agent mode keeps the existing usage
+evidence flow scoped to the operation.
+
+The runner exports persisted topic interactions to `agent/trajectory.json` with
+`lh topic export` during cleanup, including interrupted runs. This requires a
+CLI/server with ATIF export support. Export currently supports single-agent
+topics without threads or branches; failures are logged without changing the
+trial result. The trajectory includes recorded reasoning, tool calls/results,
+and message usage; it does not reconstruct runtime-only model context.
## Diagnose
diff --git a/.agents/skills/run-eval-harbor/agents/openai.yaml b/.agents/skills/run-eval-harbor/agents/openai.yaml
index 764a0fe133a..e6e5ca1c6a3 100644
--- a/.agents/skills/run-eval-harbor/agents/openai.yaml
+++ b/.agents/skills/run-eval-harbor/agents/openai.yaml
@@ -1,4 +1,4 @@
interface:
display_name: 'Run Eval Harbor'
- short_description: 'Run Harbor evals against local or cloud LobeHub'
- default_prompt: 'Use $run-eval-harbor to choose a LobeHub target and CLI source, preflight it, smoke-test the full path, and run an existing Harbor evaluation.'
+ short_description: 'Run Harbor or FrontierHarness evals with LobeHub'
+ default_prompt: 'Use $run-eval-harbor to choose a LobeHub target and CLI source, preflight it, smoke-test the path, and run an existing Harbor or Runta FrontierHarness evaluation.'
diff --git a/.agents/skills/run-eval-harbor/references/cloud.md b/.agents/skills/run-eval-harbor/references/cloud.md
index 34bbc2ba2db..a3c0ca067ef 100644
--- a/.agents/skills/run-eval-harbor/references/cloud.md
+++ b/.agents/skills/run-eval-harbor/references/cloud.md
@@ -11,8 +11,15 @@ The external eval repository's ignored `.env` must contain:
```env
LH_AGENT_ID=<selected-agent-id>
LOBEHUB_CLI_API_KEY=<cloud-cli-api-key>
+# Workspace agents only:
+LOBEHUB_WORKSPACE_ID=<workspace-id>
```
+For a workspace agent, also set `LOBEHUB_WORKSPACE_ID` to the workspace that
+owns the agent. The Harbor adapter uses it both to scope the agent request and
+to enroll the task container with `lh connect --workspace`. Leave it unset for
+personal agents.
+
For official LobeHub Cloud, leave `LH_SERVER_URL`, `LOBEHUB_SERVER`,
`LH_GATEWAY_URL`, and `AGENT_GATEWAY_URL` unset so the CLI uses its official
defaults. For a custom remote deployment, preserve its supplied URLs and require
diff --git a/.agents/skills/run-eval-harbor/references/local.md b/.agents/skills/run-eval-harbor/references/local.md
index d2b152bd7d9..7a319a3a967 100644
--- a/.agents/skills/run-eval-harbor/references/local.md
+++ b/.agents/skills/run-eval-harbor/references/local.md
@@ -8,24 +8,29 @@ is development-only; Harbor always targets the production server on `3210`.
Before starting anything, ask the user to confirm that this machine is trusted
and that LobeHub port `3210` plus all configured eval ports are unreachable from
the public internet and other untrusted networks. The defaults are PostgreSQL
-`15433`, Redis `6380`, RustFS `9100`/`9101`, QStash `8080`/`8081`, and the
+`15433`, Redis `6380`, RustFS `9100`, QStash `8080`/`8081`, and the
gateways `8787`/`8788`. Stop if the user cannot confirm this.
-Compose port publishing is separate from container routing through the Docker
-bridge: an unqualified mapping such as `15433:5432` normally listens on every
-host interface. Compose services use their private bridge internally, the host
-LobeHub process uses published data-service ports, and Harbor containers use the
-host bridge address only for LobeHub and the gateways. The stack uses fixed
-development credentials, including its seeded CLI key and gateway service
-token, so it is not suitable for an internet-facing host.
+PostgreSQL, Redis, and the RustFS API bind only to host loopback. The RustFS
+admin port is not published. Gateways bind to loopback for LobeHub and to
+`EVAL_DOCKER_BRIDGE_ADDRESS` for Harbor containers. QStash is the exception: its
+dev binary has no bind-address option and uses host networking so callbacks to
+the host LobeHub `APP_URL` work; firewall isolation is therefore still required
+for `8080`/`8081`. The stack uses fixed development credentials, including its
+seeded CLI key and gateway service token, so it is not suitable for an
+internet-facing host.
## Prepare
Create `docker-compose/eval/.env` from `.env.example` only when it is absent.
-Set the user-selected `LH_AGENT_ID`. The agent already owns its model. Ask
-whether its provider credential is stored in LobeHub; when it is not, add the
-provider's actual environment variable to this ignored env before server
-startup. `DEEPSEEK_API_KEY` is one example, not a required or generic key.
+The seeded CLI key resolves the isolated user's builtin `inbox` agent
+automatically; no Web login or copied agent id is required. Set `LH_AGENT_ID`
+only to override that default with a specific agent. For a workspace agent, also
+set `LOBEHUB_WORKSPACE_ID` to its workspace id. Reuse a provider credential
+already stored in LobeHub or configured in this ignored env. If smoke reports
+`InvalidProviderAPIKey`, inspect the resolved agent's provider/model, ask only
+for that provider's actual credential, add it to the ignored env, and restart
+the server. `DEEPSEEK_API_KEY` is one example, not a required or generic key.
```bash
bash .agents/skills/run-eval-harbor/scripts/bootstrap.sh
@@ -74,9 +79,21 @@ bash .agents/skills/run-eval-harbor/scripts/run-smoke.sh local checkout /absolut
# or: run-smoke.sh local npm /absolute/eval/repo
```
-The smoke requires `LH_AGENT_ID` and `LOBEHUB_CLI_API_KEY`, calls the selected
-agent, requires `hello world`, and exits. Preflight intentionally checks neither
-credential nor model access; that is smoke's job.
+The default smoke invokes `lh agent run`. To evaluate the persistent Task path
+instead, select `task`; the adapter creates one Task for the trial and starts it
+on the connected Harbor device with `lh task run --device local`:
+
+```bash
+LH_RUN_MODE=task bash .agents/skills/run-eval-harbor/scripts/run-smoke.sh local checkout
+```
+
+Task mode snapshots `lh task usage` into the trial logs every five minutes and
+at termination; it does not derive the Task bill from the root operation.
+
+The local smoke requires `LOBEHUB_CLI_API_KEY`. Unless `LH_AGENT_ID` overrides
+it, the installed CLI resolves `LH_AGENT_SLUG=inbox` to a concrete id before the
+run. The smoke calls that agent, requires `hello world`, and exits. Preflight
+intentionally checks neither credential nor model access; that is smoke's job.
Use the external eval repository's own run/resume command after smoke. Inspect
failures from `<jobs-dir>/<job-id>/job.log`, then the failed trial's
diff --git a/.agents/skills/run-eval-harbor/references/runta.md b/.agents/skills/run-eval-harbor/references/runta.md
new file mode 100644
index 00000000000..eddc7d91e8f
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/references/runta.md
@@ -0,0 +1,167 @@
+# Runta Execution Environment / FrontierHarness
+
+Use this execution-environment overlay to run the FrontierHarness task set with
+an Lh Cloud workspace agent. Runta is the sandbox host, not the LobeHub server
+target; the current playbook overlays the cloud server route and does not expose
+a local LobeHub server to Runta. Build and smoke-test the adapter first; a full
+run spends real credits and starts two Runta runtimes.
+
+## Required Inputs
+
+- An official `frontierharness-eval` checkout pinned to a commit. Its `tasks/`
+ directory is the task index used below.
+- A ready golden checkpoint containing Harbor, Pier, and DeepSWE under
+ `/work/deep-swe`. The launcher downloads Terminal-Bench once on its Harbor
+ runtime when the checkpoint does not already contain it.
+- An ignored dotenv file with `LH_AGENT_ID`, `LOBEHUB_CLI_API_KEY`, and
+ `LOBEHUB_WORKSPACE_ID`.
+- An authenticated `runta` CLI. The controller also needs an authenticated `lh`
+ CLI when collecting billing usage.
+
+The Lh agent owns the actual model. The required `--model` value is a benchmark
+reporting label; it does not reconfigure the agent. Verify that the selected
+agent uses the intended model before spending on a comparable run.
+
+Prepare the generic benchmark checkpoint with the pinned FrontierHarness
+provisioner. It installs Harbor, Pier, and DeepSWE; Lh does not need to be baked
+into it:
+
+```bash
+FH=/absolute/path/to/frontierharness-eval/skills/frontierharness-eval/scripts
+
+bash "$FH/provision-golden-checkpoint.sh" \
+ --runtime fh-lh-build \
+ --checkpoint fh-lh-public-golden \
+ --harness lh \
+ --provider fireworks \
+ --repo \
+ 4 --memory 8192 --disk-size-gib 50 < this-repository-url > --commit < pinned-commit > --cpus
+```
+
+Build `apps/cli` on the controller before `start`:
+
+```bash
+(cd /absolute/path/to/this-repository/apps/cli && pnpm build)
+```
+
+The launcher packs its
+`package.json` and `dist/` together with this skill's `scripts/lh/`, then uploads
+that small artifact to both restored runtimes. It does not rebuild the repository
+inside the runtimes or task containers.
+
+## Execution Topology
+
+A full run restores two machines from the same golden checkpoint:
+
+```text
+controller
+β”œβ”€β”€ Harbor runtime
+β”‚ └── Harbor schedules all Terminal-Bench tasks (default concurrency: 2)
+└── Pier runtime
+ └── Pier schedules all DeepSWE tasks (default concurrency: 1)
+```
+
+The controller does not launch tasks individually and does not stay attached.
+It uploads one suite configuration per machine and starts Harbor/Pier as a
+transient systemd unit. Harbor and Pier own their task queues and task-container
+lifecycles. The systemd unit is only a durable launcher because `runta exec` has
+no persistent-job API; it is not part of the public workflow.
+
+Tasks within a suite share the Runta host and its image cache, but each task
+still gets the container isolation implemented by its runner. Record the
+topology as `two-shared-runta-runtimes`; it is not the published one-fresh-Runta-
+runtime-per-task topology, so do not silently compare the resulting score with
+that baseline.
+
+## Public Network Policy
+
+`public` is three separate decisions:
+
+1. Each Runta runtime uses an empty denylist, allowing outbound traffic.
+2. Each copied task definition sets only `[agent].network_mode = "public"`, so
+ the Lh CLI can reach LobeHub Cloud, the device gateway, repositories, and
+ package registries.
+3. The original verifier and environment policy remains unchanged. In
+ particular, opening the agent does not open a no-network verifier.
+
+The launcher checks that its task rewrite did not alter the task's
+`[verifier]` or `[environment]` data. It also mounts Runta's CA certificates
+into Harbor/Pier task containers. Runtime egress alone is insufficient: without
+the task-level change, the agent container remains offline.
+
+## Start
+
+Use the single orchestration script from this checkout. `start`
+restores and prepares both runtimes, starts both suite schedulers, writes
+`runs/<run-id>/run.json`, prints the runtime names, and exits.
+
+```bash
+RUNTA=/absolute/path/to/this-repository/.agents/skills/run-eval-harbor/scripts/frontierharness-runta.py
+
+python3 "$RUNTA" start \
+ --checkpoint fh-lh-public-golden \
+ --run-id lh-kimi-k3-YYYYMMDD \
+ --tasks /absolute/path/to/frontierharness-eval/tasks \
+ --env-file /absolute/path/to/frontierharness-eval/.env \
+ --model kimi-k3 \
+ --out /absolute/path/to/frontierharness-eval/runs
+```
+
+Use a new run ID when the agent, model, checkpoint, task set, network policy, or
+runner topology changes. `start` refuses to reuse an existing run record.
+
+For a smoke test, pass one or more full task IDs with `--task`. Only the runtimes
+needed by those tasks are restored:
+
+```bash
+python3 "$RUNTA" start \
+ --checkpoint fh-lh-public-golden \
+ --run-id lh-smoke-YYYYMMDD \
+ --tasks /absolute/path/to/frontierharness-eval/tasks \
+ --task terminal-bench/openssl-selfsigned-cert \
+ --env-file /absolute/path/to/frontierharness-eval/.env \
+ --model kimi-k3 \
+ --out /absolute/path/to/frontierharness-eval/runs
+```
+
+## Inspect
+
+`status` is deliberately one-shot. It reports the Runta and systemd states plus
+completed/expected trial counts, then exits. Call it again when needed; do not
+keep a controller process alive merely to sleep.
+
+```bash
+python3 "$RUNTA" status \
+ --run /absolute/path/to/frontierharness-eval/runs/<run-id>
+```
+
+The inline launch command writes a `completion.json` with the scheduler's exit
+code and duration. This survives even if systemd later unloads its transient
+unit. `Result` and `ExecMainStatus` remain useful diagnostics. Individual task
+failures are normal benchmark results and usually do not make the suite process
+fail.
+
+## Collect And Pause
+
+Run `collect` only after both suites have completion records. It creates final
+archives on the runtimes, verifies their SHA-256 hashes after download, extracts
+them under each suite's `final/` directory, and then pauses both runtimes.
+
+```bash
+python3 "$RUNTA" collect \
+ --run /absolute/path/to/frontierharness-eval/runs/ \
+ /absolute/path/to/frontierharness-eval/.env < run-id > --env-file
+```
+
+The collector extracts operation IDs from the final agent logs and invokes
+`lh usage --month ... --agent-id ... --json`. It retains the complete queried
+rows as `lh-usage-raw.json` and exact-operation matches as `lh-usage.json`.
+`spend` from this command is the actual LobeHub bill. Any FrontierHarness cost
+computed by repricing the recorded tokens is a normalized comparison metric;
+report the two separately.
+
+Do not treat a running snapshot as final evidence. Final evidence consists of
+the verified suite archives, `run.json`, final unit status, operation IDs, and
+usage records. If usage collection fails, the runtimes are still paused because
+billing lookup does not depend on them; repair authentication and collect usage
+from the preserved operation IDs.
diff --git a/.agents/skills/run-eval-harbor/scripts/frontierharness-chart-icon.mjs b/.agents/skills/run-eval-harbor/scripts/frontierharness-chart-icon.mjs
new file mode 100644
index 00000000000..c462bcd8d27
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/frontierharness-chart-icon.mjs
@@ -0,0 +1,39 @@
+// Add the LobeHub favicon to a FrontierHarness-generated candidate chart.
+import { readFile, writeFile } from 'node:fs/promises';
+
+import sharp from 'sharp';
+
+const [chartPath, faviconPath] = process.argv.slice(2);
+if (!chartPath || !faviconPath) {
+ throw new Error('usage: node frontierharness-chart-icon.mjs <chart.svg> <favicon.ico>');
+}
+
+const ico = await readFile(faviconPath);
+const offset = ico.readUInt32LE(18);
+const size = ico.readUInt32LE(14);
+const png = ico.subarray(offset, offset + size);
+if (!png.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) {
+ throw new Error('favicon does not contain a PNG image');
+}
+
+const source = await readFile(chartPath, 'utf8');
+const candidate =
+ /<text class="point-name" x="([\d.]+)" y="([\d.]+)" fill="#ff7a12" text-anchor="(start|end)"><tspan x="[\d.]+">LobeHub<\/tspan>/;
+const match = source.match(candidate);
+if (!match) throw new Error('LobeHub candidate label is missing from the chart');
+const [, rawX, rawY, anchor] = match;
+const x = Number(rawX) + (anchor === 'end' ? -88 : -23);
+const y = Number(rawY) - 14;
+const image = `<image x="${x}" y="${y}" width="18" height="18" href="data:image/png;base64,${png.toString('base64')}"/>`;
+const chart = source
+ .replace(candidate, `${image}${match[0]}`)
+ .replace(
+ 'Provisional comparison Β· Cost coverage: see report data',
+ 'LobeHub Β· local Docker run Β· shown for context, not ranked',
+ )
+ .replace('>Third-party harness</text>', '>LobeHub</text>');
+await writeFile(chartPath, chart);
+await sharp(Buffer.from(chart))
+ .png()
+ .toFile(chartPath.replace(/\.svg$/, '.png'));
+console.log(`Branded ${chartPath}`);
diff --git a/.agents/skills/run-eval-harbor/scripts/frontierharness-local.py b/.agents/skills/run-eval-harbor/scripts/frontierharness-local.py
new file mode 100644
index 00000000000..3103e70495e
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/frontierharness-local.py
@@ -0,0 +1,370 @@
+#!/usr/bin/env python3
+"""Run FrontierHarness tasks on a Docker host and collect their results."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.util
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+import tomllib
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import datetime, timezone
+from pathlib import Path
+
+SUITES = {
+ "terminal-bench": ("harbor", "lh.agent:LhInstalledAgent"),
+ "datacurve": ("pier", "lh.pier_agent:LhPierInstalledAgent"),
+}
+SCRIPT_DIR = Path(__file__).resolve().parent
+
+
+def credentials(path: Path) -> dict[str, str]:
+ values = {}
+ for raw in path.read_text().splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.removeprefix("export ").split("=", 1)
+ values[key.strip()] = value.strip().strip("'\"")
+ required = ("LH_AGENT_ID", "LOBEHUB_CLI_API_KEY", "LOBEHUB_WORKSPACE_ID")
+ missing = [key for key in required if not values.get(key)]
+ if missing:
+ raise ValueError(f"missing Cloud credentials: {', '.join(missing)}")
+ return {key: values[key] for key in required}
+
+
+def save(path: Path, value: object) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(value, indent=2) + "\n")
+ temporary.replace(path)
+
+
+def start(args: argparse.Namespace) -> None:
+ if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", args.run_id):
+ raise ValueError("run-id must contain only letters, digits, dots, dashes and underscores")
+ eval_dir = args.eval_dir.resolve()
+ cli_dir = args.cli_dir.resolve()
+ env_file = args.env_file.resolve()
+ for required in (cli_dir / "package.json", cli_dir / "dist/index.js", eval_dir / "benchmark.json"):
+ if not required.is_file():
+ raise FileNotFoundError(required)
+ creds = credentials(env_file)
+ concurrency = {"terminal-bench": args.harbor_concurrency, "datacurve": args.pier_concurrency}
+ if any(value < 1 for value in concurrency.values()):
+ raise ValueError("suite concurrency must be positive")
+ if args.after_run and (args.after_pid is None or args.after_pid < 1):
+ raise ValueError("--after-run requires a positive --after-pid")
+ notify_dir = Path.home() / "scripts"
+ if args.notify and not all((notify_dir / name).is_file() for name in ("notify-on-exit.sh", ".env")):
+ raise FileNotFoundError("notification script or its .env is missing")
+ sources = {
+ "terminal-bench": args.terminal_bench.resolve(),
+ "datacurve": (args.deep_swe.resolve() / "tasks"),
+ }
+ if not all(path.is_dir() for path in sources.values()):
+ raise ValueError("Terminal-Bench or DeepSWE task directory is missing")
+ network_script = eval_dir / "skills/frontierharness-eval/scripts/set-agent-network-mode.py"
+ if not network_script.is_file():
+ raise FileNotFoundError(network_script)
+
+ tasks = []
+ for task in sorted((eval_dir / "tasks").glob("*/task.toml")):
+ task_id = tomllib.loads(task.read_text())["task"]["name"]
+ if args.task and task_id not in args.task:
+ continue
+ suite, _, _ = task_id.partition("/")
+ if suite not in SUITES:
+ raise ValueError(f"unknown FrontierHarness suite: {task_id}")
+ source = sources[suite] / task.parent.name
+ if not (source / "task.toml").is_file():
+ raise FileNotFoundError(source / "task.toml")
+ source_task = tomllib.loads((source / "task.toml").read_text())
+ source_name = source_task.get("task", {}).get("name")
+ if suite == "terminal-bench" and source_name is None:
+ source_name = f"terminal-bench/{source.name}"
+ if source_name != task_id:
+ raise ValueError(f"task identity differs from the benchmark: {task_id}")
+ tasks.append({"id": task_id, "suite": suite, "dir": task.parent.name})
+ if args.task and set(args.task) != {task["id"] for task in tasks}:
+ raise ValueError("requested task is not in the FrontierHarness benchmark")
+ if not args.task and len(tasks) != 30:
+ raise ValueError(f"expected 30 FrontierHarness tasks, found {len(tasks)}")
+
+ run_dir = (args.out.resolve() / args.run_id)
+ if run_dir.exists():
+ raise FileExistsError(f"run already exists: {run_dir}")
+ run_dir.mkdir(parents=True)
+ for task in tasks:
+ suite, name = task["suite"], task["dir"]
+ target = run_dir / "tasks" / suite / name
+ shutil.copytree(sources[suite] / name, target)
+ subprocess.run([sys.executable, str(network_script), str(target / "task.toml"), "public"], check=True)
+ runner, adapter = SUITES[suite]
+ agent = {
+ "model_name": args.model,
+ "env": {
+ **{key: "${" + key + "}" for key in creds},
+ "LH_CLI_SOURCE": f"host-dir:{cli_dir}",
+ "LH_RUN_MODE": "agent",
+ },
+ }
+ agent["name" if runner == "harbor" else "import_path"] = adapter
+ job_name = f"{args.run_id}-{name}"
+ config = {
+ "job_name": job_name,
+ "jobs_dir": str(run_dir / "jobs" / suite),
+ "n_concurrent_trials": 1,
+ "retry": {"max_retries": 0},
+ "tasks": [{"path": str(target)}],
+ "environment": {"type": "docker"},
+ "agents": [agent],
+ }
+ save(run_dir / "config" / suite / f"{name}.json", config)
+ record = {
+ "run_id": args.run_id,
+ "model": args.model,
+ "started_at": datetime.now(timezone.utc).isoformat(),
+ "topology": "docker-host-suite-queues",
+ "concurrency": concurrency,
+ "eval_commit": subprocess.check_output(["git", "-C", str(eval_dir), "rev-parse", "HEAD"], text=True).strip(),
+ "deep_swe_commit": subprocess.check_output(["git", "-C", str(args.deep_swe), "rev-parse", "HEAD"], text=True).strip(),
+ "cli_sha256": hashlib.sha256((cli_dir / "dist/index.js").read_bytes()).hexdigest(),
+ "env_file": str(env_file),
+ "agent_id": creds["LH_AGENT_ID"],
+ "tasks": tasks,
+ }
+ if args.after_run:
+ record["after_run"] = str(args.after_run.resolve())
+ record["after_pid"] = args.after_pid
+ save(run_dir / "run.json", record)
+ save(run_dir / "status.json", {"state": "queued", "total": len(tasks)})
+ command = [sys.executable, str(Path(__file__).resolve()), "worker", "--run", str(run_dir)]
+ if args.notify:
+ notifier = notify_dir / "notify-on-exit.sh"
+ command = [
+ str(notifier), "--title", f"FrontierHarness local: {args.run_id}",
+ "--content", f"Result directory: {run_dir}", "--", *command,
+ ]
+ with (run_dir / "worker.log").open("a") as log:
+ process = subprocess.Popen(
+ command,
+ stdin=subprocess.DEVNULL,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ cwd=notify_dir if args.notify else run_dir,
+ start_new_session=True,
+ )
+ (run_dir / "worker.pid").write_text(f"{process.pid}\n")
+ print(json.dumps({"run": str(run_dir), "pid": process.pid, "tasks": len(tasks)}, indent=2))
+
+
+def run_task(run_dir: Path, record: dict, task: dict, env: dict) -> tuple[int, Path, Path]:
+ suite, name = task["suite"], task["dir"]
+ runner = SUITES[suite][0]
+ config = run_dir / "config" / suite / f"{name}.json"
+ command = (["uv", "run", "--with", "harbor==0.23.0", "harbor"] if runner == "harbor" else ["pier"])
+ command += ["run", "--config", str(config), "--yes"]
+ log_path = run_dir / "logs" / suite / f"{name}.log"
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ with log_path.open("w") as log:
+ result = subprocess.run(command, cwd=run_dir, env=env, stdout=log, stderr=subprocess.STDOUT, check=False)
+ result_path = run_dir / "jobs" / suite / f"{record['run_id']}-{name}" / "result.json"
+ return result.returncode, result_path, log_path
+
+
+def worker(args: argparse.Namespace) -> None:
+ run_dir = args.run.resolve()
+ record = json.loads((run_dir / "run.json").read_text())
+ if "after_run" in record:
+ previous = Path(record["after_run"])
+ while True:
+ state_file = previous / "status.json"
+ state = json.loads(state_file.read_text()).get("state") if state_file.is_file() else ""
+ if state == "complete":
+ break
+ if state == "failed":
+ save(run_dir / "status.json", {"state": "failed", "reason": f"smoke failed: {previous}"})
+ raise SystemExit(1)
+ try:
+ os.kill(record["after_pid"], 0)
+ except ProcessLookupError:
+ save(run_dir / "status.json", {"state": "failed", "reason": f"smoke stopped without completion: {previous}"})
+ raise SystemExit(1)
+ time.sleep(30)
+ env = os.environ.copy()
+ for key in ("LH_SERVER_URL", "LOBEHUB_SERVER", "LH_GATEWAY_URL", "AGENT_GATEWAY_URL", "LH_AGENT_SLUG"):
+ env.pop(key, None)
+ env.update(credentials(Path(record["env_file"])))
+ env["PYTHONPATH"] = str(SCRIPT_DIR) + (":" + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
+ completed = 0
+ failure = None
+ save(run_dir / "status.json", {"state": "running", "completed": completed, "total": len(record["tasks"]), "concurrency": record["concurrency"]})
+ with ThreadPoolExecutor(record["concurrency"]["terminal-bench"]) as harbor, ThreadPoolExecutor(record["concurrency"]["datacurve"]) as pier:
+ queues = {"terminal-bench": harbor, "datacurve": pier}
+ futures = {queues[task["suite"]].submit(run_task, run_dir, record, task, env): task for task in record["tasks"]}
+ for future in as_completed(futures):
+ if future.cancelled():
+ continue
+ task = futures[future]
+ try:
+ exit_code, result_path, log_path = future.result()
+ if exit_code or not result_path.is_file():
+ raise RuntimeError(f"runner exit={exit_code}; result={result_path}; log={log_path}")
+ completed += 1
+ print(f"{completed}/{len(record['tasks'])}: {task['id']} -> {result_path}", flush=True)
+ except Exception as error:
+ if failure is None:
+ failure = {"task": task["id"], "reason": str(error)}
+ for pending in futures:
+ pending.cancel()
+ save(run_dir / "status.json", {"state": "draining" if failure else "running", "completed": completed, "total": len(record["tasks"]), "failure": failure})
+ if failure:
+ save(run_dir / "status.json", {"state": "failed", "completed": completed, "total": len(record["tasks"]), **failure})
+ raise SystemExit(1)
+ save(run_dir / "status.json", {
+ "state": "complete", "total": len(record["tasks"]),
+ "finished_at": datetime.now(timezone.utc).isoformat(),
+ })
+
+
+def collect(args: argparse.Namespace) -> None:
+ run_dir = args.run.resolve()
+ eval_dir = args.eval_dir.resolve()
+ record_path = run_dir / "run.json"
+ record = json.loads(record_path.read_text())
+ status = json.loads((run_dir / "status.json").read_text())
+ if status["state"] != "complete":
+ raise RuntimeError("local run has not completed")
+ model = record["model"]
+ env = os.environ.copy()
+ for key in ("LH_SERVER_URL", "LOBEHUB_SERVER", "LH_GATEWAY_URL", "AGENT_GATEWAY_URL", "LH_AGENT_SLUG"):
+ env.pop(key, None)
+ env.update(credentials(args.env_file or Path(record["env_file"])))
+
+ scripts = eval_dir / "skills/frontierharness-eval/scripts"
+ sys.path.insert(0, str(scripts))
+ spec = importlib.util.spec_from_file_location("fh_calculate_cost", scripts / "calculate-cost.py")
+ if spec is None or spec.loader is None:
+ raise RuntimeError("FrontierHarness cost calculator is unavailable")
+ calculator = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(calculator)
+ pricing = json.loads((scripts / "pricing.json").read_text())
+
+ operations = {}
+ for task in record["tasks"]:
+ name, suite = task["dir"], task["suite"]
+ job = run_dir / "jobs" / suite / f"{record['run_id']}-{name}"
+ status_logs = list(job.rglob("operation-status.jsonl"))
+ if len(status_logs) != 1:
+ raise RuntimeError(f"expected one operation log: {job}")
+ ids = {json.loads(line)["operationId"] for line in status_logs[0].read_text().splitlines()}
+ if not ids:
+ raise RuntimeError(f"no operation ID: {job}")
+ operations[task["id"]] = ids
+
+ cli = args.cli_dir.resolve() / "dist/index.js"
+ year, month = map(int, record["started_at"][:7].split("-"))
+ end = status.get("finished_at", datetime.now(timezone.utc).isoformat())
+ end_year, end_month = map(int, end[:7].split("-"))
+ usage = []
+ while (year, month) <= (end_year, end_month):
+ usage.extend(json.loads(subprocess.check_output(
+ ["node", str(cli), "usage", "--month", f"{year:04d}-{month:02d}",
+ "--agent-id", record["agent_id"], "--json"], text=True, env=env,
+ )))
+ year, month = (year + 1, 1) if month == 12 else (year, month + 1)
+ all_ids = set().union(*operations.values())
+ matched = [row for row in usage if (row.get("metadata") or {}).get("operationId") in all_ids]
+ if {row["metadata"]["operationId"] for row in matched} != all_ids:
+ raise RuntimeError("lh usage is missing one or more run operations")
+
+ trials = run_dir / "trials"
+ for task in record["tasks"]:
+ name, suite = task["dir"], task["suite"]
+ trial_dir = trials / f"{suite}__{name}"
+ job_dir = trial_dir / "jobs"
+ original = run_dir / "jobs" / suite / f"{record['run_id']}-{name}"
+ trial_dir.mkdir(parents=True, exist_ok=True)
+ if job_dir.is_symlink():
+ job_dir.unlink()
+ if not job_dir.exists():
+ shutil.copytree(original, job_dir)
+ agents = list(job_dir.rglob("operation-status.jsonl"))
+ if len(agents) != 1:
+ raise RuntimeError(f"expected one agent log: {job_dir}")
+ rows = sorted(
+ (row for row in matched if row["metadata"]["operationId"] in operations[task["id"]]),
+ key=lambda row: row.get("createdAt", ""),
+ )
+ (agents[0].parent / "lh-usage.jsonl").write_text(
+ "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)
+ )
+ title_path = eval_dir / "tasks" / name / "task.toml"
+ title = tomllib.loads(title_path.read_text()).get("metadata", {}).get("display_title", name)
+ scored = calculator.calculate(trial_dir, model, "lh", pricing, True, True)
+ trial = {
+ "id": task["id"], "title": title, "suite": suite, "harness": "lh",
+ "run_id": record["run_id"], "attempt": 1,
+ "operations": sorted(operations[task["id"]]), "usage_requests": len(rows),
+ **scored,
+ }
+ (trial_dir / "trial.json").write_text(json.dumps(trial, indent=2) + "\n")
+
+ record.update({
+ "harness": "lh", "model": model, "provider": "lobehub-cloud",
+ "checkpoint": "none (local Docker)", "methodology_comparable": False,
+ "egress_policy": {"mode": "public", "scope": "agent task"},
+ "methodology_notes": [
+ f"Docker executes tasks on a shared host without checkpoint restores; image caches persist. Suite concurrency: {record.get('concurrency', 'legacy sequential')}.",
+ "Only the agent task network is public; verifier and environment policy remain task-defined.",
+ f"The Cloud agent selects the model; {model} is the recorded reporting label and frozen benchmark prices are used for comparison.",
+ ],
+ })
+ record_path.write_text(json.dumps(record, indent=2) + "\n")
+ (run_dir / "lh-usage.json").write_text(json.dumps(matched, indent=2) + "\n")
+ print(f"Prepared {len(record['tasks'])} trials; {len(matched)} usage requests across {len(all_ids)} operations")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ start_parser = commands.add_parser("start")
+ start_parser.add_argument("--run-id", required=True)
+ start_parser.add_argument("--eval-dir", type=Path, required=True)
+ start_parser.add_argument("--terminal-bench", type=Path, required=True)
+ start_parser.add_argument("--deep-swe", type=Path, required=True)
+ start_parser.add_argument("--env-file", type=Path, required=True)
+ start_parser.add_argument("--cli-dir", type=Path, default=SCRIPT_DIR.parents[3] / "apps/cli")
+ start_parser.add_argument("--out", type=Path, default=Path("runs"))
+ start_parser.add_argument("--model", default="kimi-k3")
+ start_parser.add_argument("--task", action="append")
+ start_parser.add_argument("--harbor-concurrency", type=int, default=2)
+ start_parser.add_argument("--pier-concurrency", type=int, default=1)
+ start_parser.add_argument("--after-run", type=Path, help="wait for a smoke run to finish successfully")
+ start_parser.add_argument("--after-pid", type=int, help="fail if the smoke worker exits without a result")
+ start_parser.add_argument("--notify", action="store_true", help="send a notification when the worker exits")
+ start_parser.set_defaults(handler=start)
+ collect_parser = commands.add_parser("collect", help="prepare results and usage for FrontierHarness reports")
+ collect_parser.add_argument("--run", required=True, type=Path)
+ collect_parser.add_argument("--eval-dir", required=True, type=Path)
+ collect_parser.add_argument("--cli-dir", required=True, type=Path)
+ collect_parser.add_argument("--env-file", type=Path, help="override the original worker's credential file")
+ collect_parser.set_defaults(handler=collect)
+ worker_parser = commands.add_parser("worker", help=argparse.SUPPRESS)
+ worker_parser.add_argument("--run", type=Path, required=True)
+ worker_parser.set_defaults(handler=worker)
+ args = parser.parse_args()
+ args.handler(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/run-eval-harbor/scripts/frontierharness-runta.py b/.agents/skills/run-eval-harbor/scripts/frontierharness-runta.py
new file mode 100755
index 00000000000..b22057320bd
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/frontierharness-runta.py
@@ -0,0 +1,659 @@
+#!/usr/bin/env python3
+"""Run FrontierHarness suites on two shared Runta runtimes."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import hashlib
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tarfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import tomllib
+
+SUITES = {
+ "terminal-bench": {
+ "runner": "harbor",
+ "agent": "lh.agent:LhInstalledAgent",
+ "source": "/work/terminal-bench/terminal-bench",
+ },
+ "datacurve": {
+ "runner": "pier",
+ "agent": "lh.pier_agent:LhPierInstalledAgent",
+ "source": "/work/deep-swe/tasks",
+ },
+}
+CA_OVERLAY = """services:
+ main:
+ volumes:
+ - /etc/ssl/certs/ca-certificates.crt:/etc/ssl/certs/runta-ca-bundle.crt:ro
+ - /usr/local/share/ca-certificates/runta-egress.crt:/usr/local/share/ca-certificates/runta-egress.crt:ro
+ environment:
+ CURL_CA_BUNDLE: /etc/ssl/certs/runta-ca-bundle.crt
+ SSL_CERT_FILE: /etc/ssl/certs/runta-ca-bundle.crt
+ REQUESTS_CA_BUNDLE: /etc/ssl/certs/runta-ca-bundle.crt
+ PIP_CERT: /etc/ssl/certs/runta-ca-bundle.crt
+ GIT_SSL_CAINFO: /etc/ssl/certs/runta-ca-bundle.crt
+ NODE_EXTRA_CA_CERTS: /usr/local/share/ca-certificates/runta-egress.crt
+ UV_NATIVE_TLS: "1"
+"""
+NETWORK_SCRIPT = r"""
+import pathlib, re, sys, tomllib
+root = pathlib.Path(sys.argv[1])
+for path in root.glob("*/task.toml"):
+ source = path.read_text()
+ before = tomllib.loads(source)
+ section = re.search(r"(?ms)^\[agent\]\s*\n(?P<body>.*?)(?=^\[|\Z)", source)
+ if section is None:
+ raise SystemExit(f"missing [agent] section: {path}")
+ body = section.group("body")
+ setting = 'network_mode = "public"'
+ if re.search(r"(?m)^network_mode\s*=.*$", body):
+ body = re.sub(r"(?m)^network_mode\s*=.*$", setting, body, count=1)
+ else:
+ body = setting + "\n" + body
+ updated = source[:section.start("body")] + body + source[section.end("body"):]
+ after = tomllib.loads(updated)
+ if before.get("environment") != after.get("environment") or before.get("verifier") != after.get("verifier"):
+ raise SystemExit(f"refusing to change verifier/environment policy: {path}")
+ path.write_text(updated)
+"""
+
+
+def command(args: list[str], *, capture: bool = False, check: bool = True) -> str:
+ result = subprocess.run(args, check=False, text=True, capture_output=capture)
+ if check and result.returncode:
+ detail = (result.stderr or result.stdout or "").strip()
+ raise RuntimeError(
+ f"command failed ({result.returncode}): {shlex.join(args)}\n{detail}"
+ )
+ return result.stdout if capture else ""
+
+
+def retry(args: list[str], *, capture: bool = False) -> str:
+ error: Exception | None = None
+ for attempt in range(3):
+ try:
+ return command(args, capture=capture)
+ except RuntimeError as caught:
+ error = caught
+ if attempt < 2:
+ time.sleep(2)
+ assert error is not None
+ raise error
+
+
+def remote(runtime: str, script: str, *, capture: bool = False) -> str:
+ return retry(["runta", "exec", runtime, "--", "sh", "-lc", script], capture=capture)
+
+
+def quote(value: str | Path) -> str:
+ return shlex.quote(str(value))
+
+
+def read_env(path: Path) -> dict[str, str]:
+ values: dict[str, str] = {}
+ for raw in path.read_text().splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.removeprefix("export ").split("=", 1)
+ values[key.strip()] = value.strip().strip("'\"")
+ return values
+
+
+def runtime_name(run_id: str, suffix: str) -> str:
+ raw = re.sub(r"[^a-zA-Z0-9-]", "-", f"fh-{run_id}-{suffix}")
+ if len(raw) <= 52:
+ return raw
+ digest = hashlib.sha256(f"{run_id}-{suffix}".encode()).hexdigest()[:16]
+ return f"fh-{suffix}-{digest}"
+
+
+def runtime_states() -> dict[str, str]:
+ data = json.loads(command(["runta", "ps", "-a", "--json"], capture=True))
+ rows = data if isinstance(data, list) else data.get("runtimes", [])
+ return {
+ row.get("display_name", row.get("name")): row.get("status", "") for row in rows
+ }
+
+
+def ensure_runtime(name: str, checkpoint: str, idle_timeout: int) -> None:
+ state = runtime_states().get(name)
+ if state == "paused":
+ retry(["runta", "resume", name])
+ elif state == "shutdown":
+ retry(["runta", "boot", name])
+ elif state != "running":
+ if state:
+ raise RuntimeError(f"runtime {name} is in unsupported state: {state}")
+ retry(
+ [
+ "runta",
+ "checkpoint",
+ "restore",
+ checkpoint,
+ name,
+ "--idle-mode",
+ "suspend-and-wakeup",
+ "--idle-timeout",
+ str(idle_timeout),
+ ]
+ )
+ for _ in range(90):
+ if runtime_states().get(name) == "running":
+ return
+ time.sleep(2)
+ raise RuntimeError(f"runtime {name} did not become ready")
+
+
+def discover_tasks(
+ root: Path, selected: list[str] | None = None
+) -> dict[str, list[dict[str, str]]]:
+ tasks: dict[str, list[dict[str, str]]] = {suite: [] for suite in SUITES}
+ wanted = set(selected or [])
+ for path in sorted(root.glob("*/task.toml")):
+ name = tomllib.loads(path.read_text()).get("task", {}).get("name", "")
+ suite, separator, _ = name.partition("/")
+ if separator and suite in tasks and (not wanted or name in wanted):
+ tasks[suite].append({"id": name, "dir": path.parent.name})
+ found = {row["id"] for rows in tasks.values() for row in rows}
+ missing = wanted - found
+ if missing:
+ raise RuntimeError(f"tasks not found: {', '.join(sorted(missing))}")
+ if not wanted:
+ missing_suites = [suite for suite, rows in tasks.items() if not rows]
+ if missing_suites:
+ raise RuntimeError(f"no tasks found for: {', '.join(missing_suites)}")
+ return {suite: rows for suite, rows in tasks.items() if rows}
+
+
+def suite_config(
+ run_id: str, suite: str, tasks: list[dict[str, str]], model: str, concurrency: int
+) -> dict[str, Any]:
+ details = SUITES[suite]
+ agent_env = {
+ "LH_AGENT_ID": "${LH_AGENT_ID}",
+ "LOBEHUB_CLI_API_KEY": "${LOBEHUB_CLI_API_KEY}",
+ "LOBEHUB_WORKSPACE_ID": "${LOBEHUB_WORKSPACE_ID}",
+ "LH_CLI_SOURCE": "host-dir:/work/lh-cli",
+ }
+ common: dict[str, Any] = {
+ "job_name": f"{run_id}-{suite}",
+ "jobs_dir": f"/work/jobs/{suite}",
+ "n_concurrent_trials": concurrency,
+ "retry": {"max_retries": 0},
+ "tasks": [
+ {"path": f"/work/fh-suite-tasks/{suite}/{row['dir']}"} for row in tasks
+ ],
+ }
+ if suite == "terminal-bench":
+ common.update(
+ {
+ "environment": {
+ "type": "docker",
+ "extra_docker_compose": ["/work/runta-ca-overlay.yaml"],
+ },
+ "agents": [
+ {"name": details["agent"], "model_name": model, "env": agent_env}
+ ],
+ }
+ )
+ else:
+ agent_env.update(
+ {
+ "CURL_CA_BUNDLE": "/etc/ssl/certs/runta-ca-bundle.crt",
+ "SSL_CERT_FILE": "/etc/ssl/certs/runta-ca-bundle.crt",
+ "NODE_EXTRA_CA_CERTS": "/usr/local/share/ca-certificates/runta-egress.crt",
+ }
+ )
+ common.update(
+ {
+ "environment": {
+ "type": "docker",
+ "mounts": [
+ {
+ "type": "bind",
+ "source": "/etc/ssl/certs/ca-certificates.crt",
+ "target": "/etc/ssl/certs/runta-ca-bundle.crt",
+ "read_only": True,
+ },
+ {
+ "type": "bind",
+ "source": "/usr/local/share/ca-certificates/runta-egress.crt",
+ "target": "/usr/local/share/ca-certificates/runta-egress.crt",
+ "read_only": True,
+ },
+ ],
+ },
+ "agents": [
+ {
+ "import_path": details["agent"],
+ "model_name": model,
+ "env": agent_env,
+ }
+ ],
+ }
+ )
+ return common
+
+
+def unit_status(runtime: str, suite: str) -> dict[str, str]:
+ unit = f"fh-suite-{suite}.service"
+ output = remote(
+ runtime,
+ "systemctl show "
+ + quote(unit)
+ + " --no-pager --property=LoadState,ActiveState,SubState,Result,ExecMainStatus 2>/dev/null || true",
+ capture=True,
+ )
+ return dict(line.split("=", 1) for line in output.splitlines() if "=" in line)
+
+
+def launch(runtime: str, suite: str) -> None:
+ state = unit_status(runtime, suite)
+ if state.get("LoadState") == "loaded":
+ return
+ runner = SUITES[suite]["runner"]
+ state_dir = f"/work/fh-suite-state/{suite}"
+ inner = (
+ "set -u; set -a; . /work/fh-input/runtime.env || exit $?; set +a; "
+ "export HOME=/root PATH=/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin "
+ "PYTHONPATH=/work/lh-harness; "
+ "started=$(date +%s); "
+ f"{runner} run --config /work/fh-input/suite-config.json --yes; exit_code=$?; "
+ "duration=$(( $(date +%s) - started )); "
+ f'jq -n --argjson exit_code "$exit_code" --argjson duration "$duration" '
+ f"'{{exit_code:$exit_code,duration_seconds:$duration}}' > {state_dir}/completion.json.tmp; "
+ f'mv {state_dir}/completion.json.tmp {state_dir}/completion.json; exit "$exit_code"'
+ )
+ log = f"{state_dir}/runner.log"
+ remote(
+ runtime,
+ f"mkdir -p /work/fh-suite-state/{suite} /work/jobs/{suite}; "
+ + "systemd-run --quiet "
+ + f"--unit={quote(f'fh-suite-{suite}')} "
+ + "--property=Type=exec "
+ + f"--property={quote(f'StandardOutput=append:{log}')} "
+ + f"--property={quote(f'StandardError=append:{log}')} "
+ + f"/bin/bash -lc {quote(inner)}",
+ )
+
+
+def write_json(path: Path, value: Any) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(value, indent=2) + "\n")
+ temporary.replace(path)
+
+
+def copy_to_runtime(local: Path, runtime: str, target: str) -> None:
+ retry(["runta", "cp", str(local), f"{runtime}:{target}"])
+
+
+def pack_lh_artifacts(run_dir: Path, cli_dir: Path) -> tuple[Path, str]:
+ required = (cli_dir / "package.json", cli_dir / "dist" / "index.js")
+ for path in required:
+ if not path.is_file():
+ raise RuntimeError(f"missing local CLI build artifact: {path}")
+ lh_dir = Path(__file__).with_name("lh")
+ run_dir.mkdir(parents=True, exist_ok=True)
+ archive = run_dir / "lh-artifacts.tar.gz"
+ with tarfile.open(archive, "w:gz") as bundle:
+ bundle.add(cli_dir / "package.json", arcname="lh-cli/package.json")
+ bundle.add(cli_dir / "dist", arcname="lh-cli/dist")
+ for path in lh_dir.rglob("*"):
+ if path.is_file() and "__pycache__" not in path.parts:
+ bundle.add(
+ path,
+ arcname=Path("lh-harness/lh") / path.relative_to(lh_dir),
+ )
+ return archive, hashlib.sha256(archive.read_bytes()).hexdigest()
+
+
+def start(args: argparse.Namespace) -> None:
+ tasks_root = args.tasks.resolve()
+ env_file = args.env_file.resolve()
+ if not tasks_root.is_dir() or not env_file.is_file():
+ raise RuntimeError("--tasks must be a directory and --env-file must be a file")
+ env = read_env(env_file)
+ missing = [
+ key
+ for key in ("LH_AGENT_ID", "LOBEHUB_CLI_API_KEY", "LOBEHUB_WORKSPACE_ID")
+ if not env.get(key)
+ ]
+ if missing:
+ raise RuntimeError(f"missing from runtime env file: {', '.join(missing)}")
+ if (
+ args.harbor_concurrency < 1
+ or args.pier_concurrency < 1
+ or args.idle_timeout < 1
+ ):
+ raise RuntimeError("concurrency and idle timeout must be positive integers")
+
+ run_dir = (args.out / args.run_id).resolve()
+ run_file = run_dir / "run.json"
+ if run_file.exists():
+ raise RuntimeError(f"run already exists; use status or collect: {run_file}")
+ tasks = discover_tasks(tasks_root, args.task)
+ runtimes = {
+ suite: runtime_name(args.run_id, SUITES[suite]["runner"]) for suite in tasks
+ }
+ artifact, artifact_hash = pack_lh_artifacts(run_dir, args.cli_dir.resolve())
+ record = {
+ "version": 1,
+ "run_id": args.run_id,
+ "started_at": datetime.now(timezone.utc).isoformat(),
+ "checkpoint": args.checkpoint,
+ "model_label": args.model,
+ "agent_id": env["LH_AGENT_ID"],
+ "lh_artifact_sha256": artifact_hash,
+ "topology": "two-shared-runta-runtimes",
+ "network": {
+ "runtime_egress": "public",
+ "agent": "public",
+ "verifier": "task-defined",
+ },
+ "runtimes": runtimes,
+ "concurrency": {
+ "terminal-bench": args.harbor_concurrency,
+ "datacurve": args.pier_concurrency,
+ },
+ "tasks": tasks,
+ }
+ write_json(run_file, record)
+ write_json(run_dir / "task-index.json", tasks)
+ (run_dir / "runta-ca-overlay.yaml").write_text(CA_OVERLAY)
+ for suite in tasks:
+ config = suite_config(
+ args.run_id,
+ suite,
+ tasks[suite],
+ args.model,
+ record["concurrency"][suite],
+ )
+ write_json(run_dir / f"{suite}-config.json", config)
+
+ encoded_network_script = base64.b64encode(NETWORK_SCRIPT.encode()).decode()
+ for suite, runtime in runtimes.items():
+ print(f"Preparing {suite} on {runtime}", file=sys.stderr)
+ ensure_runtime(runtime, args.checkpoint, args.idle_timeout)
+ retry(["runta", "egress", "set", runtime, "--mode", "denylist"])
+ remote(
+ runtime,
+ "mkdir -p /work/fh-input /work/fh-suite-tasks /work/jobs",
+ )
+ copy_to_runtime(artifact, runtime, "/work/fh-input/lh-artifacts.tar.gz")
+ copy_to_runtime(env_file, runtime, "/work/fh-input/runtime.env")
+ copy_to_runtime(run_file, runtime, "/work/fh-input/run.json")
+ copy_to_runtime(
+ run_dir / "task-index.json", runtime, "/work/fh-input/task-index.json"
+ )
+ copy_to_runtime(
+ run_dir / f"{suite}-config.json",
+ runtime,
+ "/work/fh-input/suite-config.json",
+ )
+ if suite == "terminal-bench":
+ copy_to_runtime(
+ run_dir / "runta-ca-overlay.yaml",
+ runtime,
+ "/work/runta-ca-overlay.yaml",
+ )
+ source = SUITES[suite]["source"]
+ directories = " ".join(quote(row["dir"]) for row in tasks[suite])
+ target = f"/work/fh-suite-tasks/{suite}"
+ remote(
+ runtime,
+ "set -eu; chmod 600 /work/fh-input/runtime.env; "
+ "rm -rf /work/lh-cli /work/lh-harness; "
+ "tar -xzf /work/fh-input/lh-artifacts.tar.gz -C /work; "
+ + (
+ "test -d /work/terminal-bench/terminal-bench || "
+ "harbor datasets download [email protected] --output-dir /work/terminal-bench --overwrite; "
+ if suite == "terminal-bench"
+ else ""
+ )
+ + f"rm -rf {quote(target)}; "
+ f"mkdir -p {quote(target)}; for task in {directories}; do "
+ f'test -f {quote(source)}/"$task/task.toml"; cp -a {quote(source)}/"$task" {quote(target)}/; done; '
+ f"printf %s {quote(encoded_network_script)} | base64 -d | python3 - {quote(target)}",
+ )
+ launch(runtime, suite)
+
+ print(json.dumps({"run": str(run_file), "runtimes": runtimes}, indent=2))
+
+
+def load_run(path: Path) -> tuple[Path, dict[str, Any]]:
+ run_file = path / "run.json" if path.is_dir() else path
+ if not run_file.is_file():
+ raise RuntimeError(f"run record not found: {run_file}")
+ return run_file.resolve(), json.loads(run_file.read_text())
+
+
+def get_status(record: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ result: dict[str, dict[str, Any]] = {}
+ states = runtime_states()
+ for suite, runtime in record["runtimes"].items():
+ runtime_state = states.get(runtime, "missing")
+ unit: dict[str, str] = {}
+ completion: dict[str, Any] | None = None
+ completed = 0
+ if runtime_state != "missing":
+ unit = unit_status(runtime, suite)
+ completion_raw = remote(
+ runtime,
+ f"test ! -f /work/fh-suite-state/{quote(suite)}/completion.json || "
+ f"cat /work/fh-suite-state/{quote(suite)}/completion.json",
+ capture=True,
+ ).strip()
+ completion = json.loads(completion_raw) if completion_raw else None
+ count = remote(
+ runtime,
+ f"find /work/jobs/{quote(suite)} -mindepth 3 -type f -name result.json 2>/dev/null | wc -l",
+ capture=True,
+ ).strip()
+ completed = int(count or 0)
+ result[suite] = {
+ "runtime": runtime,
+ "runtime_state": runtime_state,
+ "unit": unit,
+ "completion": completion,
+ "completed_trials": completed,
+ "expected_trials": len(record["tasks"][suite]),
+ }
+ return result
+
+
+def status(args: argparse.Namespace) -> None:
+ _, record = load_run(args.run)
+ print(json.dumps(get_status(record), indent=2))
+
+
+def download_verified(runtime: str, source: str, target: Path, expected: str) -> None:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ for _ in range(3):
+ temporary = target.with_suffix(target.suffix + ".part")
+ temporary.unlink(missing_ok=True)
+ command(["runta", "cp", f"{runtime}:{source}", str(temporary)], check=False)
+ if (
+ temporary.is_file()
+ and hashlib.sha256(temporary.read_bytes()).hexdigest() == expected
+ ):
+ temporary.replace(target)
+ return
+ time.sleep(2)
+ raise RuntimeError(f"failed to copy a verified archive from {runtime}:{source}")
+
+
+def collect_usage(run_dir: Path, record: dict[str, Any], env_file: Path | None) -> None:
+ operation_ids: set[str] = set()
+ for snapshot in run_dir.glob("suites/*/final/**/operation-status.jsonl"):
+ for line in snapshot.read_text(errors="replace").splitlines():
+ try:
+ operation_id = json.loads(line).get("operationId")
+ if isinstance(operation_id, str):
+ operation_ids.add(operation_id)
+ except json.JSONDecodeError:
+ continue
+ write_json(run_dir / "operation-ids.json", sorted(operation_ids))
+ if not operation_ids or shutil.which("lh") is None:
+ print(
+ "Warning: operation IDs or local lh CLI unavailable; usage was not collected",
+ file=sys.stderr,
+ )
+ return
+
+ started = datetime.fromisoformat(record["started_at"])
+ now = datetime.now(timezone.utc)
+ months: list[str] = []
+ year, month = started.year, started.month
+ while (year, month) <= (now.year, now.month):
+ months.append(f"{year:04d}-{month:02d}")
+ year, month = (year + 1, 1) if month == 12 else (year, month + 1)
+ process_env = os.environ.copy()
+ if env_file and env_file.is_file():
+ process_env.update(read_env(env_file))
+ rows: list[dict[str, Any]] = []
+ for month_value in months:
+ result = subprocess.run(
+ [
+ "lh",
+ "usage",
+ "--month",
+ month_value,
+ "--agent-id",
+ record["agent_id"],
+ "--json",
+ ],
+ check=False,
+ text=True,
+ capture_output=True,
+ env=process_env,
+ )
+ if result.returncode:
+ print(
+ f"Warning: lh usage failed for {month_value}: {result.stderr.strip()}",
+ file=sys.stderr,
+ )
+ return
+ value = json.loads(result.stdout)
+ if isinstance(value, list):
+ rows.extend(value)
+ write_json(run_dir / "lh-usage-raw.json", rows)
+ filtered = [
+ row
+ for row in rows
+ if row.get("metadata", {}).get("operationId") in operation_ids
+ ]
+ write_json(run_dir / "lh-usage.json", filtered)
+
+
+def collect(args: argparse.Namespace) -> None:
+ run_file, record = load_run(args.run)
+ run_dir = run_file.parent
+ current = get_status(record)
+ incomplete = [
+ suite for suite, value in current.items() if value["completion"] is None
+ ]
+ if incomplete:
+ raise RuntimeError(f"suites have no completion record: {', '.join(incomplete)}")
+
+ for suite, runtime in record["runtimes"].items():
+ remote_dir = f"/work/fh-suite-state/{suite}"
+ unit = f"fh-suite-{suite}.service"
+ archive = f"{remote_dir}/final-evidence.tar.gz"
+ hash_value = remote(
+ runtime,
+ f"set -eu; mkdir -p {quote(remote_dir)}; "
+ f"systemctl show {quote(unit)} --no-pager > {quote(remote_dir + '/unit-status.txt')} 2>&1 || true; "
+ f"journalctl -u {quote(unit)} --no-pager > {quote(remote_dir + '/journal.log')} 2>&1 || true; "
+ f"tar -czf {quote(archive + '.tmp')} -C /work/jobs {quote(suite)} "
+ f"-C {quote(remote_dir)} unit-status.txt journal.log runner.log completion.json "
+ f"-C /work/fh-input run.json suite-config.json task-index.json; "
+ f"mv {quote(archive + '.tmp')} {quote(archive)}; sha256sum {quote(archive)}",
+ capture=True,
+ ).split()[0]
+ local_dir = run_dir / "suites" / suite
+ local_archive = local_dir / "final-evidence.tar.gz"
+ download_verified(runtime, archive, local_archive, hash_value)
+ final_dir = local_dir / "final"
+ shutil.rmtree(final_dir, ignore_errors=True)
+ final_dir.mkdir(parents=True)
+ with tarfile.open(local_archive) as bundle:
+ bundle.extractall(final_dir, filter="data")
+ (local_dir / "SHA256SUMS").write_text(f"{hash_value} final-evidence.tar.gz\n")
+
+ for runtime in record["runtimes"].values():
+ retry(["runta", "pause", runtime])
+ collect_usage(run_dir, record, args.env_file.resolve() if args.env_file else None)
+ write_json(run_dir / "final-status.json", current)
+ print(
+ json.dumps(
+ {"run": str(run_file), "evidence": str(run_dir / "suites")}, indent=2
+ )
+ )
+
+
+def parser() -> argparse.ArgumentParser:
+ root = argparse.ArgumentParser(description=__doc__)
+ commands = root.add_subparsers(dest="command", required=True)
+ start_parser = commands.add_parser("start", help="start both suites and return")
+ start_parser.add_argument("--checkpoint", required=True)
+ start_parser.add_argument("--run-id", required=True)
+ start_parser.add_argument("--tasks", type=Path, required=True)
+ start_parser.add_argument("--env-file", type=Path, required=True)
+ start_parser.add_argument(
+ "--model", required=True, help="reporting label; the Lh agent owns its model"
+ )
+ start_parser.add_argument(
+ "--task",
+ action="append",
+ help="run only this suite/task id; repeat to select multiple tasks",
+ )
+ start_parser.add_argument("--out", type=Path, default=Path("runs"))
+ start_parser.add_argument(
+ "--cli-dir",
+ type=Path,
+ default=Path(__file__).resolve().parents[4] / "apps/cli",
+ help="built apps/cli directory",
+ )
+ start_parser.add_argument("--harbor-concurrency", type=int, default=2)
+ start_parser.add_argument("--pier-concurrency", type=int, default=1)
+ start_parser.add_argument("--idle-timeout", type=int, default=900)
+ start_parser.set_defaults(handler=start)
+
+ status_parser = commands.add_parser("status", help="print one status snapshot")
+ status_parser.add_argument("--run", type=Path, required=True)
+ status_parser.set_defaults(handler=status)
+
+ collect_parser = commands.add_parser(
+ "collect", help="collect final evidence and pause runtimes"
+ )
+ collect_parser.add_argument("--run", type=Path, required=True)
+ collect_parser.add_argument("--env-file", type=Path)
+ collect_parser.set_defaults(handler=collect)
+ return root
+
+
+def main() -> None:
+ args = parser().parse_args()
+ try:
+ args.handler(args)
+ except (OSError, RuntimeError, ValueError, json.JSONDecodeError) as error:
+ print(f"error: {error}", file=sys.stderr)
+ raise SystemExit(1) from error
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/adapter.py b/.agents/skills/run-eval-harbor/scripts/lh/adapter.py
new file mode 100644
index 00000000000..3bedd081b61
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/lh/adapter.py
@@ -0,0 +1,204 @@
+from __future__ import annotations
+
+import json
+import shlex
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+from jinja2 import Environment, FileSystemLoader, StrictUndefined
+
+DEV_CLI_DIR = "/opt/lh-dev"
+DEV_CLI_RUNNER = f"{DEV_CLI_DIR}/run-lh.sh"
+CHECK_LH_PATH = "/installed-agent/check-lh.sh"
+RUN_AGENT_PATH = "/installed-agent/run-agent.js"
+
+_HOST_DIR_PREFIX = "host-dir:"
+_CONNECT_SCRIPT = "/tmp/lh-connect-supervised.sh"
+_LOGIN_READY = "/tmp/lh-login-ready"
+_DEVICE_READY = "/tmp/lh-device-ready"
+_SUPERVISOR_CONFIG = "/tmp/lh-supervisord.conf"
+_SUPERVISOR_SOCKET = "/tmp/lh-supervisor.sock"
+_TEMPLATES = Environment(
+ autoescape=False,
+ keep_trailing_newline=True,
+ loader=FileSystemLoader(Path(__file__).with_name("template")),
+ undefined=StrictUndefined,
+)
+
+
+class LhAdapter:
+ def __init__(
+ self,
+ get_env: Callable[[str], str | None],
+ *,
+ agent_id: str | None,
+ workspace_id: str | None,
+ server_url: str | None,
+ gateway_url: str | None,
+ cli_source: str | None,
+ run_mode: str | None,
+ ) -> None:
+ self.get_env = get_env
+ self.agent_id = agent_id
+ self.workspace_id = workspace_id
+ self.server_url = server_url
+ self.gateway_url = gateway_url
+ self.cli_source_arg = cli_source
+ self.run_mode_arg = run_mode
+
+ def value(self, direct: str | None, env_name: str, default: str = "") -> str:
+ return (direct or self.get_env(env_name) or default).strip()
+
+ @property
+ def cli_source(self) -> str:
+ return self.value(self.cli_source_arg, "LH_CLI_SOURCE", "system")
+
+ @property
+ def uses_system_cli(self) -> bool:
+ return self.cli_source == "system"
+
+ @property
+ def run_mode(self) -> str:
+ value = self.value(self.run_mode_arg, "LH_RUN_MODE", "agent")
+ if value not in {"agent", "task"}:
+ raise ValueError("LH_RUN_MODE must be 'agent' or 'task'")
+ return value
+
+ def host_cli_dir(self) -> Path | None:
+ if self.uses_system_cli:
+ return None
+ if not self.cli_source.startswith(_HOST_DIR_PREFIX):
+ raise ValueError(f"Unsupported LH_CLI_SOURCE: {self.cli_source}")
+ path = Path(self.cli_source.removeprefix(_HOST_DIR_PREFIX)).expanduser()
+ if not path.is_absolute():
+ raise ValueError("LH_CLI_SOURCE host-dir path must be absolute")
+ for required in (path / "package.json", path / "dist" / "index.js"):
+ if not required.is_file():
+ raise FileNotFoundError(f"Missing local LH CLI build input: {required}")
+ return path
+
+ def render(self, name: str, **values: object) -> str:
+ return _TEMPLATES.get_template(name).render(**values)
+
+ def install_script(self, *, install_cli: bool) -> str:
+ return self.render(
+ "install-lh.sh.j2",
+ cli_package=shlex.quote("@lobehub/cli"),
+ node_version=shlex.quote(self.value(None, "LH_NODE_VERSION", "24")),
+ install_cli=install_cli,
+ use_system_cli=self.uses_system_cli,
+ )
+
+ def run_commands(self, instruction: str) -> list[str]:
+ agent_id = self.value(self.agent_id, "LH_AGENT_ID")
+ agent_slug = self.value(None, "LH_AGENT_SLUG")
+ if not agent_id and not agent_slug:
+ raise ValueError("LH_AGENT_ID or LH_AGENT_SLUG is required")
+ server_url = self.value(self.server_url, "LH_SERVER_URL")
+ gateway_url = self.value(self.gateway_url, "LH_GATEWAY_URL")
+ workspace_id = self.value(self.workspace_id, "LOBEHUB_WORKSPACE_ID")
+ run_mode = self.run_mode
+ cli = "lh" if self.uses_system_cli else f"bash {DEV_CLI_RUNNER}"
+ cli_path = "/usr/local/bin/lh" if self.uses_system_cli else DEV_CLI_RUNNER
+ agent_option = (
+ f" --agent-id {shlex.quote(agent_id)}"
+ if agent_id
+ else f" --agent-slug {shlex.quote(agent_slug)}"
+ )
+ self.host_cli_dir()
+ workspace_env = (
+ f"export LOBEHUB_WORKSPACE_ID={shlex.quote(workspace_id)}; "
+ if workspace_id
+ else ""
+ )
+
+ login = (
+ workspace_env + f"rm -f {_LOGIN_READY} {_DEVICE_READY}; "
+ f"({cli} whoami >/dev/null 2>&1 || {cli} login"
+ )
+ if server_url:
+ login += f" --server {shlex.quote(server_url)}"
+ login += f") && touch {_LOGIN_READY}"
+
+ connect = self.render(
+ "connect-lh.sh.j2",
+ cli_command=cli,
+ connect_script=_CONNECT_SCRIPT,
+ device_ready=_DEVICE_READY,
+ gateway_url=shlex.quote(gateway_url) if gateway_url else "",
+ login_ready=_LOGIN_READY,
+ workspace_id=shlex.quote(workspace_id) if workspace_id else "",
+ supervisor_config=_SUPERVISOR_CONFIG,
+ supervisor_socket=_SUPERVISOR_SOCKET,
+ )
+ ready = (
+ workspace_env + f"test -f {_LOGIN_READY} || exit 1; "
+ f"{CHECK_LH_PATH} -- {cli} && touch {_DEVICE_READY}"
+ )
+ run = (
+ workspace_env + f"test -f {_LOGIN_READY} || exit 1; "
+ f"node {shlex.quote(RUN_AGENT_PATH)}"
+ f" --cli {shlex.quote(cli_path)}"
+ f"{agent_option}"
+ f" --run-mode {shlex.quote(run_mode)}"
+ f" --prompt {shlex.quote(instruction)}"
+ f" --device-ready {shlex.quote(_DEVICE_READY)}"
+ ' --status-path "$HOME/.lobehub/daemon.status.json"'
+ f" --supervisor-config {shlex.quote(_SUPERVISOR_CONFIG)}"
+ )
+ return [login, connect, ready, run]
+
+ @staticmethod
+ def populate_context(logs_dir: Path, context: Any) -> None:
+ try:
+ lines = (logs_dir / "task-usage.jsonl").read_text().splitlines()
+ except OSError:
+ lines = []
+
+ for line in reversed(lines):
+ try:
+ usage = json.loads(line)
+ found = False
+ if isinstance(usage.get("totalInputTokens"), int):
+ context.n_input_tokens = usage["totalInputTokens"]
+ found = True
+ if isinstance(usage.get("totalOutputTokens"), int):
+ context.n_output_tokens = usage["totalOutputTokens"]
+ found = True
+ if isinstance(usage.get("totalCost"), (int, float)):
+ context.cost_usd = usage["totalCost"]
+ found = True
+ if found:
+ return
+ except (TypeError, ValueError, AttributeError):
+ continue
+
+ try:
+ lines = (logs_dir / "operation-status.jsonl").read_text().splitlines()
+ except OSError:
+ return
+
+ for line in reversed(lines):
+ try:
+ state = json.loads(line)["currentState"]
+ tokens = state.get("usage", {}).get("llm", {}).get("tokens", {})
+ cost = state.get("cost") or {}
+ if isinstance(tokens.get("input"), int):
+ context.n_input_tokens = tokens["input"]
+ if isinstance(tokens.get("output"), int):
+ context.n_output_tokens = tokens["output"]
+ if cost.get("currency") == "USD" and isinstance(
+ cost.get("total"), (int, float)
+ ):
+ context.cost_usd = cost["total"]
+ cached = [
+ model.get("usage", {}).get("inputCachedTokens")
+ for model in cost.get("llm", {}).get("byModel", [])
+ if isinstance(model, dict)
+ ]
+ if cached and all(isinstance(value, int) for value in cached):
+ context.n_cache_tokens = sum(cached)
+ return
+ except (KeyError, TypeError, ValueError, AttributeError):
+ continue
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/agent.py b/.agents/skills/run-eval-harbor/scripts/lh/agent.py
index c18d1cbca4c..1dba6ef3307 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/agent.py
+++ b/.agents/skills/run-eval-harbor/scripts/lh/agent.py
@@ -1,29 +1,11 @@
from __future__ import annotations
-import shlex
from pathlib import Path
from harbor.agents.installed.base import BaseInstalledAgent
from harbor.environments.base import BaseEnvironment
from harbor.models.agent.context import AgentContext
-from jinja2 import Environment, FileSystemLoader, StrictUndefined
-
-_HOST_DIR_PREFIX = "host-dir:"
-_DEV_CLI_DIR = "/opt/lh-dev"
-_DEV_CLI_RUNNER = f"{_DEV_CLI_DIR}/run-lh.sh"
-_CHECK_LH_PATH = "/installed-agent/check-lh.sh"
-_CONNECT_SCRIPT = "/tmp/lh-connect-supervised.sh"
-_LOGIN_READY = "/tmp/lh-login-ready"
-_DEVICE_READY = "/tmp/lh-device-ready"
-_SUPERVISOR_CONFIG = "/tmp/lh-supervisord.conf"
-_SUPERVISOR_SOCKET = "/tmp/lh-supervisor.sock"
-_TEMPLATE_DIR = Path(__file__).with_name("template")
-_TEMPLATES = Environment(
- autoescape=False,
- keep_trailing_newline=True,
- loader=FileSystemLoader(_TEMPLATE_DIR),
- undefined=StrictUndefined,
-)
+from lh.adapter import CHECK_LH_PATH, DEV_CLI_DIR, RUN_AGENT_PATH, LhAdapter
class LhInstalledAgent(BaseInstalledAgent):
@@ -37,134 +19,63 @@ class LhInstalledAgent(BaseInstalledAgent):
server_url: str | None = None,
gateway_url: str | None = None,
cli_source: str | None = None,
+ run_mode: str | None = None,
+ workspace_id: str | None = None,
*args,
**kwargs,
):
- self._agent_id = agent_id
- self._server_url = server_url
- self._gateway_url = gateway_url
- self._cli_source_arg = cli_source
super().__init__(
+ *args,
logs_dir=logs_dir,
prompt_template_path=prompt_template_path,
version=version,
extra_env=extra_env,
- *args,
**kwargs,
)
+ self._lh = LhAdapter(
+ self._get_env,
+ agent_id=agent_id,
+ workspace_id=workspace_id,
+ server_url=server_url,
+ gateway_url=gateway_url,
+ cli_source=cli_source,
+ run_mode=run_mode,
+ )
@staticmethod
def name() -> str:
return "lh"
- def _value(self, direct: str | None, env_name: str, default: str = "") -> str:
- return (direct or self._get_env(env_name) or default).strip()
-
- @property
- def _cli_source(self) -> str:
- return self._value(self._cli_source_arg, "LH_CLI_SOURCE", "system")
-
- def _render_template(self, name: str, **values: object) -> str:
- return _TEMPLATES.get_template(name).render(**values)
-
- def _host_cli_dir(self) -> Path:
- if not self._cli_source.startswith(_HOST_DIR_PREFIX):
- raise ValueError(f"Unsupported LH_CLI_SOURCE: {self._cli_source}")
-
- path = Path(self._cli_source.removeprefix(_HOST_DIR_PREFIX)).expanduser()
- if not path.is_absolute():
- raise ValueError("LH_CLI_SOURCE host-dir path must be absolute")
- for required in (path / "package.json", path / "dist" / "index.js"):
- if not required.is_file():
- raise FileNotFoundError(f"Missing local LH CLI build input: {required}")
- return path
-
- def _cli_command(self) -> str:
- if self._cli_source == "system":
- return "lh"
- self._host_cli_dir()
- return f"bash {_DEV_CLI_RUNNER}"
-
- def _agent_target(self) -> tuple[str, str]:
- agent_id = self._value(self._agent_id, "LH_AGENT_ID")
- if agent_id:
- return "--agent-id", agent_id
- raise ValueError("LH_AGENT_ID is required")
-
async def install(self, environment: BaseEnvironment) -> None:
self.logs_dir.mkdir(parents=True, exist_ok=True)
await self.exec_as_root(
- environment,
- command=f"mkdir -p /installed-agent {shlex.quote(_DEV_CLI_DIR)}",
+ environment, command=f"mkdir -p /installed-agent {DEV_CLI_DIR}"
)
- if self._cli_source != "system":
- host_dir = self._host_cli_dir()
- await environment.upload_file(host_dir / "package.json", f"{_DEV_CLI_DIR}/package.json")
- await environment.upload_dir(host_dir / "dist", f"{_DEV_CLI_DIR}/dist")
-
- install_script = self.logs_dir / "install-lh.sh"
- install_script.write_text(
- self._render_template(
- "install-lh.sh.j2",
- cli_package=shlex.quote("@lobehub/cli"),
- node_version=shlex.quote(self._value(None, "LH_NODE_VERSION", "24")),
- use_system_cli=self._cli_source == "system",
+ host_dir = self._lh.host_cli_dir()
+ if host_dir is not None:
+ await environment.upload_file(
+ host_dir / "package.json", f"{DEV_CLI_DIR}/package.json"
)
- )
- await environment.upload_file(install_script, "/installed-agent/install-lh.sh")
+ await environment.upload_dir(host_dir / "dist", f"{DEV_CLI_DIR}/dist")
+
+ scripts = {
+ "/installed-agent/install-lh.sh": self._lh.install_script(install_cli=True),
+ CHECK_LH_PATH: self._lh.render("check-lh.sh.j2"),
+ RUN_AGENT_PATH: self._lh.render("run-agent.js"),
+ }
+ for remote_path, contents in scripts.items():
+ local_path = self.logs_dir / Path(remote_path).name
+ local_path.write_text(contents)
+ await environment.upload_file(local_path, remote_path)
await self.exec_as_root(
environment,
- command="chmod +x /installed-agent/install-lh.sh && /installed-agent/install-lh.sh",
+ command=(
+ f"chmod +x /installed-agent/install-lh.sh {CHECK_LH_PATH} && "
+ "/installed-agent/install-lh.sh"
+ ),
)
- check_script = self.logs_dir / "check-lh.sh"
- check_script.write_text(self._render_template("check-lh.sh.j2"))
- await environment.upload_file(check_script, _CHECK_LH_PATH)
- await self.exec_as_root(
- environment,
- command=f"chmod +x {shlex.quote(_CHECK_LH_PATH)}",
- )
-
- def create_run_agent_commands(self, instruction: str) -> list[str]:
- selector_flag, selector_value = self._agent_target()
- server_url = self._value(self._server_url, "LH_SERVER_URL")
- gateway_url = self._value(self._gateway_url, "LH_GATEWAY_URL")
- cli = self._cli_command()
-
- login = (
- f"rm -f {_LOGIN_READY} {_DEVICE_READY}; "
- f"({cli} whoami >/dev/null 2>&1 || {cli} login"
- )
- if server_url:
- login += f" --server {shlex.quote(server_url)}"
- login += f") && touch {_LOGIN_READY}"
-
- connect = self._render_template(
- "connect-lh.sh.j2",
- cli_command=cli,
- connect_script=_CONNECT_SCRIPT,
- device_ready=_DEVICE_READY,
- gateway_url=shlex.quote(gateway_url) if gateway_url else "",
- login_ready=_LOGIN_READY,
- supervisor_config=_SUPERVISOR_CONFIG,
- supervisor_socket=_SUPERVISOR_SOCKET,
- )
- ready = (
- f"test -f {_LOGIN_READY} || exit 1; "
- f"{_CHECK_LH_PATH} -- {cli} && touch {_DEVICE_READY}"
- )
- run = self._render_template(
- "run-agent.sh.j2",
- cli_command=cli,
- device_ready=_DEVICE_READY,
- instruction=shlex.quote(instruction),
- selector_flag=selector_flag,
- selector_value=shlex.quote(selector_value),
- supervisor_config=_SUPERVISOR_CONFIG,
- )
- return [login, connect, ready, run]
-
async def run(
self,
instruction: str,
@@ -172,5 +83,8 @@ class LhInstalledAgent(BaseInstalledAgent):
context: AgentContext,
) -> None:
del context
- for command in self.create_run_agent_commands(self.render_instruction(instruction)):
+ for command in self._lh.run_commands(self.render_instruction(instruction)):
await self.exec_as_agent(environment, command=command)
+
+ 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
new file mode 100644
index 00000000000..752bc3057be
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/lh/pier_agent.py
@@ -0,0 +1,113 @@
+from __future__ import annotations
+
+import base64
+import shlex
+from pathlib import Path
+
+from lh.adapter import CHECK_LH_PATH, DEV_CLI_DIR, RUN_AGENT_PATH, LhAdapter
+from pier.agents.installed.base import BaseInstalledAgent
+from pier.environments.base import BaseEnvironment
+from pier.models.agent.context import AgentContext
+from pier.models.agent.install import AgentInstallSpec, InstallStep
+
+
+class LhPierInstalledAgent(BaseInstalledAgent):
+ def __init__(
+ self,
+ logs_dir: Path,
+ prompt_template_path: Path | str | None = None,
+ version: str | None = None,
+ extra_env: dict[str, str] | None = None,
+ agent_id: str | None = None,
+ server_url: str | None = None,
+ gateway_url: str | None = None,
+ cli_source: str | None = None,
+ run_mode: str | None = None,
+ workspace_id: str | None = None,
+ *args,
+ **kwargs,
+ ):
+ super().__init__(
+ *args,
+ logs_dir=logs_dir,
+ prompt_template_path=prompt_template_path,
+ version=version,
+ extra_env=extra_env,
+ **kwargs,
+ )
+ self._lh = LhAdapter(
+ self._get_env,
+ agent_id=agent_id,
+ workspace_id=workspace_id,
+ server_url=server_url,
+ gateway_url=gateway_url,
+ cli_source=cli_source,
+ run_mode=run_mode,
+ )
+
+ @staticmethod
+ def name() -> str:
+ return "lh"
+
+ @staticmethod
+ def _write_file_command(path: str, contents: str) -> str:
+ encoded = base64.b64encode(contents.encode()).decode()
+ return f"printf %s {shlex.quote(encoded)} | base64 -d > {shlex.quote(path)}"
+
+ def install_spec(self) -> AgentInstallSpec:
+ install_script = self._lh.install_script(
+ install_cli=self._lh.host_cli_dir() is None
+ )
+ setup = "set -euo pipefail; mkdir -p /installed-agent /opt/lh-dev; "
+ setup += self._write_file_command(
+ "/installed-agent/install-lh.sh", install_script
+ )
+ setup += "; " + self._write_file_command(
+ CHECK_LH_PATH, self._lh.render("check-lh.sh.j2")
+ )
+ setup += "; " + self._write_file_command(
+ RUN_AGENT_PATH, self._lh.render("run-agent.js")
+ )
+ setup += (
+ f"; chmod +x /installed-agent/install-lh.sh {CHECK_LH_PATH}; "
+ "/installed-agent/install-lh.sh"
+ )
+ return AgentInstallSpec(
+ agent_name=self.name(),
+ version=self._version,
+ steps=[InstallStep(user="root", run=setup)],
+ )
+
+ async def run(
+ self,
+ instruction: str,
+ environment: BaseEnvironment,
+ context: AgentContext,
+ ) -> None:
+ host_dir = self._lh.host_cli_dir()
+ if host_dir is not None:
+ await environment.upload_file(
+ 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)
+
+ self.logs_dir.mkdir(parents=True, exist_ok=True)
+ status_log = self.logs_dir / "operation-status.jsonl"
+ downloaded = status_log.with_suffix(".jsonl.download")
+ await environment.download_file(
+ "/logs/agent/operation-status.jsonl", downloaded
+ )
+ downloaded.replace(status_log)
+ if self._lh.run_mode == "task":
+ usage_log = self.logs_dir / "task-usage.jsonl"
+ downloaded_usage = usage_log.with_suffix(".jsonl.download")
+ await environment.download_file(
+ "/logs/agent/task-usage.jsonl", downloaded_usage
+ )
+ downloaded_usage.replace(usage_log)
+ self._lh.populate_context(self.logs_dir, context)
+
+ 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/template/connect-lh.sh.j2 b/.agents/skills/run-eval-harbor/scripts/lh/template/connect-lh.sh.j2
index f6ea8da02dc..e994d6b1b91 100644
--- a/.agents/skills/run-eval-harbor/scripts/lh/template/connect-lh.sh.j2
+++ b/.agents/skills/run-eval-harbor/scripts/lh/template/connect-lh.sh.j2
@@ -15,7 +15,7 @@ cat > {{ connect_script }} <<'LH_CONNECT'
set -euo pipefail
mkdir -p "$HOME/.lobehub" /logs/agent
printf "%s\n" "$$" > "$HOME/.lobehub/daemon.pid"
-exec {{ cli_command }} connect --daemon-child{% if gateway_url %} --gateway {{ gateway_url }}{% endif %}
+exec {{ cli_command }} connect --daemon-child{% if workspace_id %} --workspace {{ workspace_id }}{% endif %}{% if gateway_url %} --gateway {{ gateway_url }}{% endif %}
LH_CONNECT
chmod +x {{ connect_script }}
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 c005618c7e8..a5c44faf781 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
@@ -41,6 +41,16 @@ for bin in node npm; do
[[ "$bin_path" == "/usr/local/bin/$bin" ]] || ln -sf "$bin_path" "/usr/local/bin/$bin"
done
+{% if not use_system_cli %}
+cat >/opt/lh-dev/run-lh.sh <<'LH_RUNNER'
+#!/usr/bin/env bash
+set -euo pipefail
+exec node /opt/lh-dev/dist/index.js "$@"
+LH_RUNNER
+chmod +x /opt/lh-dev/run-lh.sh
+{% endif %}
+
+{% if install_cli %}
{% if use_system_cli %}
npm install -g "$CLI_PACKAGE"
lh_path="$(command -v lh)"
@@ -49,11 +59,6 @@ lh_path="$(command -v lh)"
{% else %}
test -f /opt/lh-dev/package.json
test -f /opt/lh-dev/dist/index.js
-cat >/opt/lh-dev/run-lh.sh <<'LH_RUNNER'
-#!/usr/bin/env bash
-set -euo pipefail
-exec node /opt/lh-dev/dist/index.js "$@"
-LH_RUNNER
-chmod +x /opt/lh-dev/run-lh.sh
/opt/lh-dev/run-lh.sh --version
{% endif %}
+{% 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
new file mode 100644
index 00000000000..e80398c6b89
--- /dev/null
+++ b/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.js
@@ -0,0 +1,586 @@
+#!/usr/bin/env node
+/* eslint-disable @typescript-eslint/no-require-imports */
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawn } = require('node:child_process');
+
+const TERMINAL_STATUSES = new Set([
+ 'done',
+ 'error',
+ 'interrupted',
+ 'cancelled',
+ 'canceled',
+ 'aborted',
+]);
+const DEFAULTS = {
+ idleMs: 5 * 60 * 1000,
+ interruptGraceMs: 30 * 1000,
+ pollMs: 60 * 1000,
+ snapshotMs: 5 * 60 * 1000,
+};
+
+class RunnerError extends Error {
+ constructor(message, exitCode = 1) {
+ super(message);
+ this.name = 'RunnerError';
+ this.exitCode = exitCode;
+ }
+}
+
+function envDuration(name, fallback) {
+ const value = Number.parseInt(process.env[name] || '', 10);
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function parseArgs(argv) {
+ const options = {
+ cli: undefined,
+ agentId: undefined,
+ agentSlug: undefined,
+ runMode: 'agent',
+ prompt: undefined,
+ deviceReady: '/tmp/lh-device-ready',
+ logDir: '/logs/agent',
+ statusPath: `${process.env.HOME || ''}/.lobehub/daemon.status.json`,
+ supervisorConfig: '/tmp/lh-supervisord.conf',
+ idleMs: envDuration('LH_RUNNER_IDLE_MS', DEFAULTS.idleMs),
+ interruptGraceMs: envDuration('LH_RUNNER_INTERRUPT_GRACE_MS', DEFAULTS.interruptGraceMs),
+ pollMs: envDuration('LH_RUNNER_POLL_MS', DEFAULTS.pollMs),
+ snapshotMs: envDuration('LH_RUNNER_SNAPSHOT_MS', DEFAULTS.snapshotMs),
+ };
+
+ const values = new Set([
+ '--agent-id',
+ '--agent-slug',
+ '--cli',
+ '--device-ready',
+ '--log-dir',
+ '--prompt',
+ '--run-mode',
+ '--status-path',
+ '--supervisor-config',
+ ]);
+ for (let index = 0; index < argv.length; index += 1) {
+ const flag = argv[index];
+ 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}`);
+ switch (flag) {
+ case '--agent-id': {
+ options.agentId = value;
+ break;
+ }
+ case '--agent-slug': {
+ options.agentSlug = value;
+ break;
+ }
+ case '--cli': {
+ options.cli = value;
+ break;
+ }
+ case '--device-ready': {
+ options.deviceReady = value;
+ break;
+ }
+ case '--log-dir': {
+ options.logDir = value;
+ break;
+ }
+ case '--prompt': {
+ options.prompt = value;
+ break;
+ }
+ case '--run-mode': {
+ options.runMode = value;
+ break;
+ }
+ case '--status-path': {
+ options.statusPath = value;
+ break;
+ }
+ case '--supervisor-config': {
+ options.supervisorConfig = value;
+ break;
+ }
+ }
+ }
+
+ for (const [name, value] of [
+ ['--cli', options.cli],
+ ['--prompt', options.prompt],
+ ]) {
+ if (!value) throw new RunnerError(`Missing required option: ${name}`);
+ }
+ if (!options.agentId && !options.agentSlug) {
+ throw new RunnerError('Missing required option: --agent-id or --agent-slug');
+ }
+ if (!['agent', 'task'].includes(options.runMode)) {
+ throw new RunnerError('--run-mode must be agent or task');
+ }
+ return options;
+}
+
+function readJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function parseOperationStatus(response) {
+ if (response === null) return { kind: 'missing' };
+ const currentState = response && typeof response === 'object' ? response.currentState : undefined;
+ if (!currentState || typeof currentState !== 'object') {
+ return { kind: 'unavailable', error: 'status response has no currentState' };
+ }
+ return { kind: 'state', currentState, status: currentState.status || 'unknown' };
+}
+
+function snapshotRecord(response, operationId, topicId) {
+ const currentState = response?.currentState;
+ if (!currentState || typeof currentState !== 'object') return null;
+ return {
+ capturedAt: new Date().toISOString(),
+ operationId,
+ topicId,
+ currentState: {
+ cost: currentState.cost,
+ lastModified: currentState.lastModified,
+ status: currentState.status,
+ stepCount: currentState.stepCount,
+ usage: currentState.usage,
+ },
+ };
+}
+
+function isIdle(status, startedAt, now, idleMs) {
+ if (now - startedAt < idleMs) return false;
+ const lastRequestAt = Date.parse(status?.lastRequestAt || '');
+ return !Number.isFinite(lastRequestAt) || now - lastRequestAt >= idleMs;
+}
+
+function appendLine(filePath, line) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.appendFileSync(filePath, `${line}\n`);
+}
+
+class AgentRunner {
+ constructor(options) {
+ this.options = options;
+ this.agentLog = path.join(options.logDir, 'agent-run.log');
+ this.statusLog = path.join(options.logDir, 'operation-status.jsonl');
+ 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.operationId = undefined;
+ this.topicId = undefined;
+ this.taskId = undefined;
+ this.deviceId = undefined;
+ this.latestStatus = undefined;
+ this.operationTerminal = false;
+ this.interruptAttempted = false;
+ this.interruptConfirmed = false;
+ this.cleanupFailure = false;
+ this.activeChild = undefined;
+ this.signalCode = undefined;
+ this.resolveSignal = undefined;
+ this.signalPromise = new Promise((resolve) => {
+ this.resolveSignal = resolve;
+ });
+ this.signalHandlers = {
+ SIGINT: () => this.requestSignal(130),
+ SIGTERM: () => this.requestSignal(143),
+ };
+ }
+
+ requestSignal(code) {
+ if (this.signalCode) return;
+ this.signalCode = code;
+ if (this.activeChild) this.activeChild.kill('SIGTERM');
+ this.resolveSignal(code);
+ }
+
+ installSignalHandlers() {
+ for (const [signal, handler] of Object.entries(this.signalHandlers))
+ process.on(signal, handler);
+ }
+
+ removeSignalHandlers() {
+ for (const [signal, handler] of Object.entries(this.signalHandlers))
+ process.off(signal, handler);
+ }
+
+ checkSignal() {
+ if (this.signalCode)
+ throw new RunnerError(`Received signal (exit ${this.signalCode})`, this.signalCode);
+ }
+
+ log(message, error = false) {
+ appendLine(this.agentLog, message);
+ (error ? console.error : console.log)(message);
+ }
+
+ async wait(ms) {
+ await Promise.race([
+ new Promise((resolve) => setTimeout(resolve, ms)),
+ this.signalPromise.then((code) => {
+ throw new RunnerError(`Received signal (exit ${code})`, code);
+ }),
+ ]);
+ this.checkSignal();
+ }
+
+ exec(command, args) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ this.activeChild = child;
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk;
+ });
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk;
+ });
+ child.once('error', (error) => {
+ this.activeChild = undefined;
+ reject(error);
+ });
+ child.once('close', (code, signal) => {
+ this.activeChild = undefined;
+ resolve({ code: code ?? 1, signal, stdout, stderr });
+ });
+ });
+ }
+
+ async runCli(args) {
+ this.checkSignal();
+ const result = await this.exec(this.options.cli, args);
+ this.checkSignal();
+ if (result.code !== 0) {
+ throw new RunnerError(
+ `CLI failed (${result.code}): ${result.stderr.trim() || result.stdout.trim() || args.join(' ')}`,
+ );
+ }
+ try {
+ return JSON.parse(result.stdout);
+ } catch {
+ throw new RunnerError(`CLI returned invalid JSON: ${args.join(' ')}`);
+ }
+ }
+
+ 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',
+ ]);
+ }
+
+ const task = await this.runCli([
+ 'task',
+ 'create',
+ '--instruction',
+ this.options.prompt,
+ '--agent',
+ this.options.agentId,
+ '--json',
+ ]);
+ 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']);
+ }
+
+ async resolveAgentId() {
+ if (this.options.agentId) return;
+ const agent = await this.runCli([
+ 'agent',
+ 'view',
+ '--slug',
+ this.options.agentSlug,
+ '--json',
+ 'id',
+ ]);
+ if (typeof agent?.id !== 'string') {
+ throw new RunnerError(`lh agent view returned no ID for slug: ${this.options.agentSlug}`);
+ }
+ this.options.agentId = agent.id;
+ this.log(`Agent: ${agent.id} (${this.options.agentSlug})`);
+ }
+
+ async run() {
+ this.installSignalHandlers();
+ try {
+ if (!fs.existsSync(this.options.deviceReady)) {
+ throw new RunnerError(`lh local device is not ready: ${this.options.deviceReady}`);
+ }
+ const deviceStatus = readJson(this.options.statusPath);
+ this.deviceId =
+ deviceStatus?.connectionStatus === 'connected' ? deviceStatus.deviceId : undefined;
+ await this.resolveAgentId();
+ const started = await this.startRun();
+ if (typeof started?.operationId !== 'string' || typeof started?.topicId !== 'string') {
+ throw new RunnerError(`lh ${this.options.runMode} run returned no operation/topic IDs`);
+ }
+ this.operationId = started.operationId;
+ this.topicId = started.topicId;
+ this.log(`Operation: ${this.operationId} Topic: ${this.topicId}`);
+
+ const startedAt = Date.now();
+ let nextSnapshotAt = 0;
+ while (true) {
+ this.checkSignal();
+ const polled = await this.pollStatus();
+ const now = Date.now();
+ if (polled.kind === 'missing') {
+ throw new RunnerError('Operation status disappeared before reaching a terminal state');
+ }
+ if (polled.kind === 'state') {
+ this.latestStatus = { currentState: polled.currentState };
+ if (now >= nextSnapshotAt) {
+ await this.captureSnapshot();
+ nextSnapshotAt = now + this.options.snapshotMs;
+ }
+ if (TERMINAL_STATUSES.has(polled.status)) {
+ this.operationTerminal = true;
+ await this.captureSnapshot();
+ if (polled.status === 'done') {
+ await this.collectTopicOutput();
+ this.log('Agent finished');
+ }
+ if (polled.status !== 'done') {
+ throw new RunnerError(
+ `Agent ended with status: ${polled.status}`,
+ polled.status === 'interrupted' ? 130 : 1,
+ );
+ }
+ return;
+ }
+ }
+
+ if (isIdle(readJson(this.options.statusPath), startedAt, now, this.options.idleMs)) {
+ const confirmed = await this.interruptAndWait();
+ if (confirmed) {
+ throw new RunnerError('No device request for 5 minutes; agent interrupted', 124);
+ }
+ throw new RunnerError(
+ 'No device request for 5 minutes; interrupt was not acknowledged',
+ 124,
+ );
+ }
+ await this.wait(this.options.pollMs);
+ }
+ } finally {
+ await this.cleanup();
+ this.removeSignalHandlers();
+ }
+ }
+
+ async pollStatus() {
+ try {
+ const response = await this.runCli([
+ 'agent',
+ 'status',
+ this.operationId,
+ '--json=currentState',
+ ]);
+ const result = parseOperationStatus(response);
+ if (result.kind === 'unavailable') appendLine(this.statusErrorsLog, result.error);
+ return result;
+ } catch (error) {
+ if (error instanceof RunnerError && this.signalCode) throw error;
+ appendLine(this.statusErrorsLog, error.message);
+ return { kind: 'unavailable', error: error.message };
+ }
+ }
+
+ writeSnapshot() {
+ const record = snapshotRecord(this.latestStatus, this.operationId, this.topicId);
+ if (record) appendLine(this.statusLog, JSON.stringify(record));
+ }
+
+ async captureSnapshot() {
+ this.writeSnapshot();
+ if (this.options.runMode !== 'task' || !this.taskId) return;
+
+ try {
+ const usage = await this.runCli(['task', 'usage', this.taskId, '--json']);
+ appendLine(
+ this.taskUsageLog,
+ JSON.stringify({ capturedAt: new Date().toISOString(), ...usage }),
+ );
+ } catch (error) {
+ appendLine(this.statusErrorsLog, `task usage: ${error.message}`);
+ }
+ }
+
+ async interruptAndWait() {
+ if (this.interruptAttempted) return this.interruptConfirmed;
+ this.interruptAttempted = true;
+ try {
+ const result = await this.runCli([
+ 'agent',
+ 'interrupt',
+ '--operation-id',
+ this.operationId,
+ '--json',
+ ]);
+ if (result?.success !== true) {
+ const polled = await this.pollStatus();
+ if (polled.kind === 'state' && TERMINAL_STATUSES.has(polled.status)) {
+ this.latestStatus = { currentState: polled.currentState };
+ this.operationTerminal = true;
+ this.interruptConfirmed = true;
+ await this.captureSnapshot();
+ return true;
+ }
+ this.log('Agent interrupt was not acknowledged', true);
+ return false;
+ }
+
+ const deadline = Date.now() + this.options.interruptGraceMs;
+ while (Date.now() < deadline) {
+ const polled = await this.pollStatus();
+ if (polled.kind === 'state' && TERMINAL_STATUSES.has(polled.status)) {
+ this.latestStatus = { currentState: polled.currentState };
+ this.operationTerminal = true;
+ this.interruptConfirmed = true;
+ await this.captureSnapshot();
+ return true;
+ }
+ await this.wait(Math.min(this.options.pollMs, deadline - Date.now()));
+ }
+ } catch (error) {
+ this.log(`Agent interrupt failed: ${error.message}`, true);
+ }
+ return false;
+ }
+
+ async collectTopicOutput() {
+ const pageSize = 100;
+ const messages = [];
+ for (let page = 1; page <= 100; page += 1) {
+ const result = await this.runCli([
+ 'message',
+ 'list',
+ '--topic-id',
+ this.topicId,
+ '--role',
+ 'assistant',
+ '--limit',
+ String(pageSize),
+ '--page',
+ String(page),
+ '--json',
+ ]);
+ if (!Array.isArray(result))
+ throw new RunnerError('message list returned a non-array response');
+ messages.push(...result);
+ if (result.length < pageSize) break;
+ }
+ for (const message of messages.reverse()) {
+ if (message?.content) {
+ fs.mkdirSync(path.dirname(this.agentLog), { recursive: true });
+ fs.appendFileSync(this.agentLog, `${message.content}\n`);
+ process.stdout.write(`${message.content}\n`);
+ }
+ }
+ }
+
+ async cleanup() {
+ await this.captureSnapshot();
+ if (this.operationId && !this.operationTerminal && !this.interruptAttempted) {
+ await this.interruptAndWait();
+ }
+
+ if (this.topicId) {
+ try {
+ const result = await this.exec(this.options.cli, [
+ 'topic',
+ 'export',
+ this.topicId,
+ '--output',
+ path.join(this.options.logDir, 'trajectory.json'),
+ ]);
+ if (result.code !== 0) {
+ throw new RunnerError(
+ result.stderr.trim() || result.stdout.trim() || 'topic export failed',
+ );
+ }
+ } catch (error) {
+ this.log(`Trajectory export failed: ${error.message}`, true);
+ }
+ }
+
+ try {
+ const result = await this.exec('supervisorctl', [
+ '-c',
+ this.options.supervisorConfig,
+ 'shutdown',
+ ]);
+ if (result.code !== 0 && result.stderr.trim())
+ appendLine(this.cleanupLog, result.stderr.trim());
+ } catch (error) {
+ appendLine(this.cleanupLog, `supervisor shutdown failed: ${error.message}`);
+ }
+
+ if (!this.deviceId) return;
+ if (!this.operationTerminal && !this.interruptConfirmed) {
+ this.log(`Keeping device ${this.deviceId}: operation termination was not acknowledged`, true);
+ return;
+ }
+ try {
+ const result = await this.exec(this.options.cli, [
+ 'device',
+ 'delete',
+ '--yes',
+ this.deviceId,
+ ]);
+ if (result.code !== 0) {
+ this.cleanupFailure = true;
+ appendLine(
+ this.cleanupLog,
+ result.stderr.trim() || result.stdout.trim() || 'device delete failed',
+ );
+ }
+ } catch (error) {
+ this.cleanupFailure = true;
+ appendLine(this.cleanupLog, `device delete failed: ${error.message}`);
+ }
+ }
+}
+
+async function main() {
+ const runner = new AgentRunner(parseArgs(process.argv.slice(2)));
+ try {
+ await runner.run();
+ if (runner.cleanupFailure) process.exitCode = 1;
+ } catch (error) {
+ runner.log(error.message, true);
+ process.exitCode = error.exitCode || 1;
+ }
+}
+
+if (require.main === module)
+ main().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ });
+
+module.exports = { isIdle, parseArgs, parseOperationStatus, snapshotRecord };
diff --git a/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.sh.j2 b/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.sh.j2
deleted file mode 100644
index 2eddb93b8d8..00000000000
--- a/.agents/skills/run-eval-harbor/scripts/lh/template/run-agent.sh.j2
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-test -f {{ device_ready }} || {
- echo "lh local device is not ready" >&2
- exit 1
-}
-
-agent_log=/logs/agent/agent-run.log
-rm -f "$agent_log"
-
-cleanup() {
- supervisorctl -c {{ supervisor_config }} shutdown >/dev/null 2>&1 || true
-}
-trap cleanup EXIT
-
-set +e
-{{ cli_command }} agent run {{ selector_flag }} {{ selector_value }} \
- --prompt {{ instruction }} \
- --device local \
- 2>&1 | tee -a "$agent_log"
-rc="${PIPESTATUS[0]}"
-set -e
-exit "$rc"
diff --git a/.agents/skills/run-eval-harbor/scripts/run-smoke.sh b/.agents/skills/run-eval-harbor/scripts/run-smoke.sh
index fc84a2db2d5..38a4423d4ea 100755
--- a/.agents/skills/run-eval-harbor/scripts/run-smoke.sh
+++ b/.agents/skills/run-eval-harbor/scripts/run-smoke.sh
@@ -9,13 +9,14 @@ CLI_ENV_FILE="$REPO_ROOT/.records/env/eval-harbor-cli.env"
TARGET="${1:-}"
CLI_MODE="${2:-}"
EVAL_REPO="${3:-}"
+RUN_MODE="${4:-${LH_RUN_MODE:-agent}}"
SMOKE_DIR="$SCRIPT_DIR/smoke"
JOBS_DIR="$REPO_ROOT/.records/harbor/jobs"
JOB_NAME="smoke-$(date +%Y%m%d-%H%M%S)-$$"
JOB_DIR="$JOBS_DIR/$JOB_NAME"
usage() {
- printf 'Usage: %s <local|cloud> <checkout|npm> [absolute-eval-repository]\n' "$0"
+ printf 'Usage: %s <local|cloud> <checkout|npm> [absolute-eval-repository] [agent|task]\n' "$0"
}
if [[ "$TARGET" == '-h' || "$TARGET" == '--help' ]]; then
@@ -24,6 +25,7 @@ if [[ "$TARGET" == '-h' || "$TARGET" == '--help' ]]; then
fi
[[ "$TARGET" == 'local' || "$TARGET" == 'cloud' ]] || { usage >&2; exit 2; }
[[ "$CLI_MODE" == 'checkout' || "$CLI_MODE" == 'npm' ]] || { usage >&2; exit 2; }
+[[ "$RUN_MODE" == 'agent' || "$RUN_MODE" == 'task' ]] || { usage >&2; exit 2; }
if [[ -n "$EVAL_REPO" ]]; then
[[ -d "$EVAL_REPO" ]] || { printf 'Eval repository does not exist: %s\n' "$EVAL_REPO" >&2; exit 2; }
EVAL_REPO="$(cd -- "$EVAL_REPO" && pwd)"
@@ -55,7 +57,17 @@ else
fi
set +a
-[[ -n "${LH_AGENT_ID:-}" ]] || { printf 'LH_AGENT_ID is required for smoke.\n' >&2; exit 1; }
+if [[ "$TARGET" == 'local' ]]; then
+ if [[ -z "${LH_AGENT_ID:-}" ]]; then
+ export LH_AGENT_SLUG="${LH_AGENT_SLUG:-inbox}"
+ fi
+else
+ [[ -n "${LH_AGENT_ID:-}" ]] || {
+ printf 'LH_AGENT_ID is required for cloud smoke.\n' >&2
+ exit 1
+ }
+ unset LH_AGENT_SLUG
+fi
[[ -n "${LOBEHUB_CLI_API_KEY:-}" ]] || { printf 'LOBEHUB_CLI_API_KEY is required for smoke.\n' >&2; exit 1; }
if [[ "$CLI_MODE" == 'checkout' ]]; then
@@ -87,11 +99,12 @@ harbor_args=(
--disable-verification
--yes
--agent lh.agent:LhInstalledAgent
- --agent-env 'LH_AGENT_ID=${LH_AGENT_ID}'
--agent-env 'LOBEHUB_CLI_API_KEY=${LOBEHUB_CLI_API_KEY}'
--agent-env 'LH_CLI_SOURCE=${LH_CLI_SOURCE}'
+ --agent-env 'LH_RUN_MODE=${LH_RUN_MODE}'
)
-for key in LH_SERVER_URL LH_GATEWAY_URL AGENT_GATEWAY_URL LOBEHUB_SERVER; do
+export LH_RUN_MODE="$RUN_MODE"
+for key in LH_AGENT_ID LH_AGENT_SLUG LH_SERVER_URL LH_GATEWAY_URL AGENT_GATEWAY_URL LOBEHUB_SERVER LOBEHUB_WORKSPACE_ID; do
[[ -n "${!key:-}" ]] && harbor_args+=(--agent-env "$key=\${$key}")
done
uv run --with 'harbor==0.23.0' harbor "${harbor_args[@]}"
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index 57ca15fa266..69c1892bf8f 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -384,6 +384,7 @@ export function registerAgentCommand(program: Command) {
"Disable headless mode: tool calls that need approval park the run for a human (default: headless β€” tools auto-run, matching the CLI's non-interactive nature). The CLI does not wait for that approval; it returns with exit code 2 and the run continues once it is answered in LobeHub",
)
.option('--json', 'Output full JSON event stream')
+ .option('--detach', 'Start the operation and return its IDs without waiting for events')
.option('-v, --verbose', 'Show detailed tool call info')
.option('--replay <file>', 'Replay events from a saved JSON file (offline)')
.option('--sse', 'Force SSE stream instead of WebSocket gateway')
@@ -406,6 +407,7 @@ Exit codes:
agentId?: string;
autoStart?: boolean;
device?: string;
+ detach?: boolean;
headless?: boolean;
json?: boolean;
prompt?: string;
@@ -502,6 +504,17 @@ Exit codes:
}
const operationId = r.operationId;
+ if (options.detach) {
+ const started = {
+ autoStarted: r.autoStarted,
+ operationId,
+ status: r.status,
+ topicId: r.topicId,
+ };
+ if (options.json) outputJson(started);
+ else log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
+ return;
+ }
if (!options.json) {
log.info(`Operation: ${pc.dim(operationId)} Β· Topic: ${pc.dim(r.topicId || 'n/a')}`);
}
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 37e57dd197d..19b73917b0d 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -156,6 +156,7 @@ describe('connect command', () => {
if (!existing.has(listener)) process.removeListener(signal, listener);
}
}
+ exitSpy.mockRestore();
vi.restoreAllMocks();
vi.clearAllMocks();
});
@@ -213,6 +214,31 @@ describe('connect command', () => {
expect(clientReportMetrics).toHaveBeenCalledWith(samples);
});
+ it('records the request on arrival and retains its timestamp across connection updates', async () => {
+ const pending = Promise.withResolvers<{ content: string; success: boolean }>();
+ vi.mocked(executeToolCall).mockImplementationOnce(() => pending.promise);
+ await createProgram().parseAsync(['node', 'test', 'connect', '--daemon-child']);
+
+ const running = clientEventHandlers.tool_call_request?.({
+ requestId: 'req-1',
+ toolCall: { apiName: 'readLocalFile', arguments: '{}', identifier: 'test' },
+ type: 'tool_call_request',
+ });
+ const received = vi.mocked(writeStatus).mock.lastCall?.[0];
+ expect(received).toEqual(
+ expect.objectContaining({ deviceId: 'mock-device-id', lastRequestAt: expect.any(String) }),
+ );
+ clientEventHandlers.connected?.();
+ expect(vi.mocked(writeStatus).mock.lastCall?.[0]).toEqual(
+ expect.objectContaining({
+ connectionStatus: 'connected',
+ lastRequestAt: received?.lastRequestAt,
+ }),
+ );
+ pending.resolve({ content: 'ok', success: true });
+ await running;
+ });
+
it('should connect to gateway', async () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index a4df7e59ed2..63053c9dd53 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -420,15 +420,23 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
info('───────────────────');
// Update local connection status so other CLI commands can resolve the current device
- const updateStatus = (connectionStatus: string) => {
+ let connectionStatus = 'connecting';
+ let lastRequestAt: string | undefined;
+ const updateStatus = (status: string) => {
+ connectionStatus = status;
writeStatus({
connectionStatus,
deviceId: client.currentDeviceId,
gatewayUrl: resolvedGatewayUrl,
+ lastRequestAt,
pid: process.pid,
startedAt: startedAt.toISOString(),
});
};
+ const recordRequest = () => {
+ lastRequestAt = new Date().toISOString();
+ updateStatus(connectionStatus);
+ };
const startedAt = new Date();
updateStatus('connecting');
@@ -479,6 +487,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
info,
isDaemonChild,
maintenance,
+ recordRequest,
};
// Request handlers (system info / tool calls / device RPCs / agent runs) β€”
@@ -891,6 +900,7 @@ interface GatewayHandlerContext {
info: (msg: string) => void;
isDaemonChild: boolean;
maintenance: CliMaintenance;
+ recordRequest: () => void;
}
/**
@@ -904,7 +914,7 @@ function bindGatewayClientHandlers(
ctx: GatewayHandlerContext,
connectionWorkspaceId?: string,
) {
- const { deps, error, getServerUrl, info, isDaemonChild, maintenance } = ctx;
+ const { deps, error, getServerUrl, info, isDaemonChild, maintenance, recordRequest } = ctx;
// Handle system info requests
client.on('system_info_request', (request: SystemInfoRequestMessage) => {
@@ -918,6 +928,7 @@ function bindGatewayClientHandlers(
// Handle tool call requests
client.on('tool_call_request', async (request: ToolCallRequestMessage) => {
+ recordRequest();
const { operationId, requestId, timeout, toolCall } = request;
if (isDaemonChild) {
appendLog(
@@ -989,6 +1000,7 @@ function bindGatewayClientHandlers(
// once the child starts, `rejected` if it fails to spawn (e.g. bad cwd) β€” so
// a failed dispatch surfaces as an error instead of a stuck assistant message.
client.on('agent_run_request', async (request: AgentRunRequestMessage) => {
+ recordRequest();
info(
`Received agent_run_request: operationId=${request.operationId} type=${request.agentType}`,
);
diff --git a/apps/cli/src/commands/task.test.ts b/apps/cli/src/commands/task.test.ts
index 174199d0046..c9f89e46ca2 100644
--- a/apps/cli/src/commands/task.test.ts
+++ b/apps/cli/src/commands/task.test.ts
@@ -143,3 +143,37 @@ describe('task edit', () => {
expect(mockUpdateStatus).not.toHaveBeenCalled();
});
});
+
+describe('task usage', () => {
+ const mockUsage = vi.fn();
+
+ beforeEach(() => {
+ mockUsage.mockReset().mockResolvedValue({
+ data: {
+ byTask: [],
+ runs: 2,
+ taskId: 'task_1',
+ taskIdentifier: 'T-1',
+ totalCost: 0.125,
+ totalInputTokens: 1200,
+ totalOutputTokens: 300,
+ totalTokens: 1500,
+ },
+ success: true,
+ });
+ mockGetTrpcClient.mockResolvedValue({ task: { usage: { query: mockUsage } } });
+ });
+
+ it('prints the task aggregate as JSON', async () => {
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const program = new Command();
+ program.exitOverride();
+ registerTaskCommand(program);
+
+ await program.parseAsync(['node', 'test', 'task', 'usage', 'T-1', '--json']);
+
+ expect(mockUsage).toHaveBeenCalledWith({ id: 'T-1' });
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('"totalCost": 0.125'));
+ consoleSpy.mockRestore();
+ });
+});
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 983dc32bb61..595f1fb6ea9 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -736,6 +736,33 @@ export function registerTaskCommand(program: Command) {
else log.info('Root task not found in tree.');
});
+ // ── usage ──────────────────────────────────────────────
+
+ task
+ .command('usage <id>')
+ .description('Show task run usage')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options: { json?: string | boolean }) => {
+ const client = await getTrpcClient();
+ const result = await client.task.usage.query({ id });
+
+ if (options.json !== undefined) {
+ outputJson(result.data, options.json);
+ return;
+ }
+
+ const usage = result.data;
+ console.log(`${pc.dim('Task:')} ${pc.bold(usage.taskIdentifier)}`);
+ console.log(`${pc.dim('Runs:')} ${usage.runs.toLocaleString('en-US')}`);
+ console.log(
+ `${pc.dim('Tokens:')} ${usage.totalTokens.toLocaleString('en-US')} ` +
+ pc.dim(
+ `(input ${usage.totalInputTokens.toLocaleString('en-US')}, output ${usage.totalOutputTokens.toLocaleString('en-US')})`,
+ ),
+ );
+ console.log(`${pc.dim('Cost:')} $${usage.totalCost.toFixed(6)}`);
+ });
+
// Register subcommand groups
registerLifecycleCommands(task);
registerCheckpointCommands(task);
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.ts
index ce0662469d3..ab16878c497 100644
--- a/apps/cli/src/commands/task/lifecycle.ts
+++ b/apps/cli/src/commands/task/lifecycle.ts
@@ -4,6 +4,8 @@ import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { getAuthInfo } from '../../api/http';
import { streamAgentEvents } from '../../utils/agentStream';
+import { resolveLocalDeviceId } from '../../utils/device';
+import { outputJson } from '../../utils/format';
import { log } from '../../utils/logger';
export function registerLifecycleCommands(task: Command) {
@@ -98,10 +100,14 @@ export function registerLifecycleCommands(task: Command) {
.description('Run a task β€” trigger agent execution')
.option('-p, --prompt <text>', 'Additional context for the agent')
.option('-c, --continue <topicId>', 'Continue running on an existing topic')
+ .option(
+ '--device <target>',
+ 'Target device ID, or use "local" for the current connected device',
+ )
.option('-f, --follow', 'Follow agent output in real-time (default: run in background)')
.option('--topics <n>', 'Run N topics in sequence (default: 1, implies --follow)', '1')
.option('--delay <s>', 'Delay between topics in seconds', '0')
- .option('--json', 'Output full JSON event stream')
+ .option('--json', 'Output startup result as JSON, or full event stream with --follow')
.option('-v, --verbose', 'Show detailed tool call info')
.action(
async (
@@ -109,6 +115,7 @@ export function registerLifecycleCommands(task: Command) {
options: {
continue?: string;
delay?: string;
+ device?: string;
follow?: boolean;
json?: boolean;
prompt?: string;
@@ -119,6 +126,20 @@ export function registerLifecycleCommands(task: Command) {
const topicCount = Number.parseInt(options.topics || '1', 10);
const delaySec = Number.parseInt(options.delay || '0', 10);
+ let deviceId: string | undefined;
+ if (options.device === 'local') {
+ deviceId = resolveLocalDeviceId();
+ if (!deviceId) {
+ log.error(
+ "No local device found. Run 'lh connect' first, then retry with --device local.",
+ );
+ process.exitCode = 1;
+ return;
+ }
+ } else {
+ deviceId = options.device;
+ }
+
// --topics > 1 implies --follow
const shouldFollow = options.follow || topicCount > 1;
@@ -146,6 +167,7 @@ export function registerLifecycleCommands(task: Command) {
// Only pass extra prompt and continue on first topic
const result = (await client.task.run.mutate({
id,
+ ...(deviceId && { deviceId }),
...(i === 0 && options.prompt && { prompt: options.prompt }),
...(i === 0 && options.continue && { continueTopicId: options.continue }),
})) as any;
@@ -156,6 +178,17 @@ export function registerLifecycleCommands(task: Command) {
}
const operationId = result.operationId;
+ if (!shouldFollow && options.json) {
+ outputJson({
+ autoStarted: result.autoStarted,
+ operationId,
+ status: result.status,
+ taskId: result.taskId,
+ taskIdentifier: result.taskIdentifier,
+ topicId: result.topicId,
+ });
+ return;
+ }
if (i === 0) {
log.info(`Task ${pc.bold(result.taskIdentifier)} running`);
}
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.ts
index 3f675275614..574e5934aa6 100644
--- a/apps/cli/src/commands/topic.ts
+++ b/apps/cli/src/commands/topic.ts
@@ -6,6 +6,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
+import { registerTopicExportCommand } from './topic/export';
import { registerTopicViewCommand } from './topic/view';
export function registerTopicCommand(program: Command) {
@@ -334,5 +335,6 @@ export function registerTopicCommand(program: Command) {
printTable(rows, ['ID', 'TITLE', 'UPDATED']);
});
+ registerTopicExportCommand(topic);
registerTopicViewCommand(topic);
}
diff --git a/apps/cli/src/commands/topic/atif.ts b/apps/cli/src/commands/topic/atif.ts
new file mode 100644
index 00000000000..09a01e830a2
--- /dev/null
+++ b/apps/cli/src/commands/topic/atif.ts
@@ -0,0 +1,167 @@
+import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const/plugin';
+import type { ChatToolPayload } from '@lobechat/types';
+import { isPlainRecord } from '@lobechat/utils/object';
+
+import type { TrpcClient } from '../../api/client';
+import { cliVersion } from '../../pkg';
+
+export type TopicTranscript = Awaited<
+ ReturnType<TrpcClient['topic']['getTopicTranscript']['query']>
+>;
+
+interface AtifMetrics {
+ cached_tokens?: number;
+ completion_tokens?: number;
+ cost_usd?: number;
+ prompt_tokens?: number;
+}
+
+interface AtifStep {
+ extra: { error?: unknown; message_id: string; parent_id: string | null; provider?: string };
+ is_copied_context?: boolean;
+ message: string;
+ metrics?: AtifMetrics;
+ model_name?: string;
+ observation?: {
+ results: {
+ content: string | null;
+ extra: { error?: unknown; message_id: string };
+ source_call_id: string;
+ }[];
+ };
+ reasoning_content?: string;
+ source: 'system' | 'user' | 'agent';
+ step_id: number;
+ timestamp: string;
+ tool_calls?: ReturnType<typeof toToolCall>[];
+}
+
+function toToolCall(tool: ChatToolPayload) {
+ let args: unknown;
+ try {
+ args = JSON.parse(tool.arguments);
+ } catch {
+ // Preserve malformed model output instead of losing the invocation.
+ }
+ return {
+ arguments: isPlainRecord(args) ? args : {},
+ extra: {
+ ...(!isPlainRecord(args) && { arguments_raw: tool.arguments }),
+ identifier: tool.identifier,
+ },
+ function_name: `${tool.identifier}${PLUGIN_SCHEMA_SEPARATOR}${tool.apiName}`,
+ tool_call_id: tool.id,
+ };
+}
+
+/** Export persisted interactions, not reconstructed LLM input/context snapshots. */
+export function toAtif(transcript: TopicTranscript) {
+ const { items, topic } = transcript;
+ if (items.length === 0) throw new Error('Cannot export an empty topic as ATIF.');
+ if (items.some((message) => !('usage' in message) || !('toolCallId' in message))) {
+ throw new Error('The server lacks topic export fields. Update the LobeHub server first.');
+ }
+ const agentIds = new Set(
+ items
+ .filter((message) => message.role === 'assistant')
+ .map((message) => message.agentId)
+ .filter(Boolean),
+ );
+ if (agentIds.size > 1 || items.some((message) => message.threadId)) {
+ throw new Error('ATIF export currently supports single-agent topics without threads.');
+ }
+
+ const steps: AtifStep[] = [];
+ const calls = new Map<string, AtifStep>();
+ const resultCallIds = new Map<string, string>();
+ const parents = new Set<string>();
+ for (const message of items) {
+ if (message.role === 'tool') continue;
+ if (!['system', 'user', 'assistant'].includes(message.role)) {
+ throw new Error(
+ `ATIF export does not support message role: ${message.role} (${message.id}).`,
+ );
+ }
+ if (message.parentId && message.role !== 'system') {
+ if (parents.has(message.parentId)) {
+ throw new Error('ATIF export currently does not support branched conversations.');
+ }
+ parents.add(message.parentId);
+ }
+ const step: AtifStep = {
+ extra: {
+ error: message.error ?? undefined,
+ message_id: message.id,
+ parent_id: message.parentId,
+ },
+ message: message.content ?? '',
+ source: message.role === 'assistant' ? 'agent' : (message.role as 'system' | 'user'),
+ step_id: steps.length + 1,
+ timestamp: new Date(message.createdAt).toISOString(),
+ };
+ if (message.metadata?.copied) step.is_copied_context = true;
+ if (step.source === 'agent') {
+ step.model_name = message.model ?? undefined;
+ step.extra.provider = message.provider ?? undefined;
+ step.reasoning_content = message.reasoning?.content;
+ const usage = message.usage ?? message.metadata?.usage ?? message.metadata;
+ if (usage) {
+ const metrics: AtifMetrics = {
+ cached_tokens: usage.inputCachedTokens,
+ completion_tokens: usage.totalOutputTokens,
+ cost_usd: usage.cost,
+ prompt_tokens: usage.totalInputTokens,
+ };
+ if (Object.values(metrics).some((value) => value !== undefined)) step.metrics = metrics;
+ }
+ if (message.tools?.length) {
+ step.tool_calls = message.tools.map(toToolCall);
+ for (const tool of message.tools) {
+ if (calls.has(tool.id)) throw new Error(`Duplicate tool call ID: ${tool.id}.`);
+ calls.set(tool.id, step);
+ if (tool.result_msg_id) resultCallIds.set(tool.result_msg_id, tool.id);
+ }
+ }
+ }
+ steps.push(step);
+ }
+
+ for (const message of items.filter((item) => item.role === 'tool')) {
+ const callId = message.toolCallId ?? resultCallIds.get(message.id);
+ const step = callId ? calls.get(callId) : undefined;
+ if (!step || !callId) {
+ throw new Error(`Cannot associate tool result ${message.id} with its tool call.`);
+ }
+ step.observation ??= { results: [] };
+ step.observation.results.push({
+ content: message.content,
+ extra: { error: message.error ?? message.pluginError ?? undefined, message_id: message.id },
+ source_call_id: callId,
+ });
+ }
+
+ // A partial sum is not a total. Omit any aggregate whose inputs are incomplete.
+ const generatedSteps = steps.filter((step) => step.source === 'agent' && !step.is_copied_context);
+ const total = (field: keyof AtifMetrics) => {
+ const values = generatedSteps.map((step) => step.metrics?.[field]);
+ return values.length > 0 && values.every((value) => value !== undefined)
+ ? values.reduce((sum, value) => sum + value, 0)
+ : undefined;
+ };
+ return {
+ agent: { name: 'lobehub', version: cliVersion, extra: { agent_id: topic.agentId } },
+ extra: { topic_id: topic.id, title: topic.title },
+ final_metrics: {
+ total_cached_tokens: total('cached_tokens'),
+ total_completion_tokens: total('completion_tokens'),
+ total_cost_usd: total('cost_usd'),
+ total_prompt_tokens: total('prompt_tokens'),
+ total_steps: steps.length,
+ },
+ notes:
+ 'Text-only persisted topic interactions; excludes attachments, runtime-only context and other topics. Aggregate usage excludes copied context and is omitted when incomplete.',
+ schema_version: 'ATIF-v1.7',
+ session_id: topic.id,
+ steps,
+ };
+}
diff --git a/apps/cli/src/commands/topic/export.ts b/apps/cli/src/commands/topic/export.ts
new file mode 100644
index 00000000000..1d4714506f8
--- /dev/null
+++ b/apps/cli/src/commands/topic/export.ts
@@ -0,0 +1,48 @@
+import { writeFile } from 'node:fs/promises';
+
+import type { Command } from 'commander';
+import { Option } from 'commander';
+
+import { getTrpcClient } from '../../api/client';
+import type { TopicTranscript } from './atif';
+import { toAtif } from './atif';
+
+export function registerTopicExportCommand(topic: Command) {
+ topic
+ .command('export <id>')
+ .description(
+ 'Export text-only topic interactions as an ATIF trajectory (single agent, no threads or branches)',
+ )
+ .addOption(new Option('--format <format>', 'Export format').choices(['atif']).default('atif'))
+ .option('-o, --output <path>', 'Write to a file instead of stdout (use - for stdout)')
+ .option('--workspace <id>', 'Read the topic from this workspace')
+ .action(async (id: string, options: { output?: string; workspace?: string }) => {
+ const client = await getTrpcClient(options.workspace);
+ let transcript: TopicTranscript | undefined;
+ const items: TopicTranscript['items'] = [];
+ do {
+ const page = await client.topic.getTopicTranscript.query({
+ includeMessages: true,
+ limit: 500,
+ offset: items.length,
+ topicId: id,
+ });
+ if (transcript && page.total !== transcript.total) {
+ throw new Error('Topic changed during export. Retry after the run finishes.');
+ }
+ transcript ??= page;
+ items.push(...page.items);
+ if (page.items.length === 0 && items.length < (transcript.total ?? 0)) {
+ throw new Error(
+ 'Topic transcript ended before all messages were retrieved. Retry export.',
+ );
+ }
+ } while (items.length < (transcript.total ?? 0));
+ const output = `${JSON.stringify(toAtif({ ...transcript, items }), null, 2)}\n`;
+ if (options.output && options.output !== '-') {
+ await writeFile(options.output, output, 'utf8');
+ } else {
+ process.stdout.write(output);
+ }
+ });
+}
diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.ts
index 2c999c20f12..892e7b1e74e 100644
--- a/apps/cli/src/daemon/manager.ts
+++ b/apps/cli/src/daemon/manager.ts
@@ -31,6 +31,7 @@ export interface DaemonStatus {
connectionStatus: string;
deviceId?: string;
gatewayUrl: string;
+ lastRequestAt?: string;
pid: number;
startedAt: string;
}
@@ -127,7 +128,10 @@ export function getRunningDaemonPid(): number | null {
export function writeStatus(status: DaemonStatus): void {
ensureDir();
- fs.writeFileSync(getStatusPath(), JSON.stringify(status, null, 2), { mode: 0o600 });
+ const statusPath = getStatusPath();
+ const tempPath = `${statusPath}.${process.pid}.tmp`;
+ fs.writeFileSync(tempPath, JSON.stringify(status, null, 2), { mode: 0o600 });
+ fs.renameSync(tempPath, statusPath);
}
export function readStatus(): DaemonStatus | null {
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
index 18e044fdb37..be8c9ae7570 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
@@ -1001,6 +1001,39 @@ describe('Task Router Integration', () => {
});
});
+ describe('usage', () => {
+ it('aggregates the task topic usage', async () => {
+ const task = await caller.create({ instruction: 'Measure this task' });
+ await new TaskTopicModel(serverDB, userId).add(task.data.id, testTopicId, {
+ operationId: 'op_usage',
+ seq: 1,
+ });
+ const { topics } = await import('@/database/schemas');
+ const { eq } = await import('drizzle-orm');
+ await serverDB
+ .update(topics)
+ .set({
+ totalCost: '0.125',
+ totalInputTokens: 1200,
+ totalOutputTokens: 300,
+ totalTokens: 1500,
+ })
+ .where(eq(topics.id, testTopicId));
+
+ const result = await caller.usage({ id: task.data.identifier });
+
+ expect(result.data).toMatchObject({
+ runs: 1,
+ taskId: task.data.id,
+ taskIdentifier: task.data.identifier,
+ totalCost: 0.125,
+ totalInputTokens: 1200,
+ totalOutputTokens: 300,
+ totalTokens: 1500,
+ });
+ });
+ });
+
describe('run error rollback', () => {
it('should rollback task status to paused on run failure', async () => {
mockExecAgent.mockRejectedValueOnce(new Error('LLM failed'));
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 83c978c496f..43344d1d07a 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -1039,6 +1039,7 @@ export const taskRouter = router({
idInput.merge(
z.object({
continueTopicId: z.string().optional(),
+ deviceId: z.string().optional(),
prompt: z.string().optional(),
}),
),
@@ -1054,6 +1055,7 @@ export const taskRouter = router({
);
return await runner.runTask({
continueTopicId: input.continueTopicId,
+ deviceId: input.deviceId,
extraPrompt: input.prompt,
taskId: task.id,
});
@@ -1700,6 +1702,26 @@ export const taskRouter = router({
}
}),
+ usage: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
+ try {
+ const task = await resolveOrThrow(ctx.taskModel, input.id);
+ const usage = await ctx.taskTopicModel.sumRunCostByTaskIds([task.id]);
+
+ return {
+ data: { ...usage, taskId: task.id, taskIdentifier: task.identifier },
+ success: true,
+ };
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ console.error('[task:usage]', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to get task usage',
+ });
+ }
+ }),
+
// Cross-workspace task *transfer* is intentionally not supported anymore:
// moving a task drags its whole subtree plus history (dependencies,
// documents, comments) out of the workspace. Use `copyTaskToWorkspace`,
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 3580624c667..1631a312524 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1028,7 +1028,14 @@ describe('GoalService', () => {
// The cost panel lists WHERE the money went, so the same read carries the
// per-Task split rather than only the total the budget is checked against.
expect(spend?.byTask).toEqual([
- { runs: 2, taskId: created.taskId!, totalCost: 6.4, totalTokens: 1200 },
+ {
+ runs: 2,
+ taskId: created.taskId!,
+ totalCost: 6.4,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalTokens: 1200,
+ },
]);
});
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 3124df244d0..63dd79bf12a 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -31,6 +31,8 @@ export interface RunTaskParams {
/** Extra builtin tools this run mounts beside the Task skill, e.g. the Goal report tool. */
additionalPluginIds?: string[];
continueTopicId?: string;
+ /** Explicit device target for this run only. The Task itself does not retain the binding. */
+ deviceId?: string;
extraPrompt?: string;
/** Optional per-operation cap. Omitted means the agent runtime remains uncapped. */
maxSteps?: number;
@@ -105,6 +107,7 @@ export class TaskRunnerService {
additionalPluginIds,
taskId: idOrIdentifier,
continueTopicId,
+ deviceId,
extraPrompt,
maxSteps,
trigger = 'manual',
@@ -284,6 +287,7 @@ export class TaskRunnerService {
const result = await aiAgentService.execAgent({
...(isSlug ? { slug: agentRef } : { agentId: agentRef }),
additionalPluginIds: pluginIds,
+ ...(deviceId && { deviceId }),
...(typeof taskConfig.model === 'string' && { model: taskConfig.model }),
...(typeof taskConfig.provider === 'string' && { provider: taskConfig.provider }),
hooks: createTaskRunHooks({
diff --git a/docker-compose/eval/.env.example b/docker-compose/eval/.env.example
index 3bc2e5e2c89..7a9a18f9785 100644
--- a/docker-compose/eval/.env.example
+++ b/docker-compose/eval/.env.example
@@ -3,11 +3,11 @@ EVAL_COMPOSE_PROJECT_NAME=lobehub-eval
EVAL_POSTGRES_PORT=15433
EVAL_REDIS_PORT=6380
EVAL_RUSTFS_PORT=9100
-EVAL_RUSTFS_ADMIN_PORT=9101
EVAL_QSTASH_PORT=8080
EVAL_QSTASH_LOG_PORT=8081
EVAL_DEVICE_GATEWAY_PORT=8787
EVAL_AGENT_GATEWAY_PORT=8788
+EVAL_DOCKER_BRIDGE_ADDRESS=172.17.0.1
# Local infrastructure credentials. The two LobeHub gateway token variables must
# use the same value because the unified gateway exposes one SERVICE_TOKEN.
@@ -64,3 +64,4 @@ LH_SERVER_URL=http://172.17.0.1:3210
LH_GATEWAY_URL=http://172.17.0.1:8787
HARBOR_AGENT_GATEWAY_URL=http://172.17.0.1:8788
LH_AGENT_ID=
+LH_AGENT_SLUG=inbox
diff --git a/docker-compose/eval/docker-compose.yml b/docker-compose/eval/docker-compose.yml
index 58b7239e6b9..64cd2988072 100644
--- a/docker-compose/eval/docker-compose.yml
+++ b/docker-compose/eval/docker-compose.yml
@@ -4,7 +4,7 @@ services:
postgresql:
image: paradedb/paradedb:latest-pg17
ports:
- - '${EVAL_POSTGRES_PORT:-15433}:5432'
+ - '127.0.0.1:${EVAL_POSTGRES_PORT:-15433}:5432'
volumes:
- 'postgresql-data:/var/lib/postgresql/data'
command: ['postgres', '-c', 'shared_preload_libraries=pg_search']
@@ -24,7 +24,7 @@ services:
redis:
image: redis:7-alpine
ports:
- - '${EVAL_REDIS_PORT:-6380}:6379'
+ - '127.0.0.1:${EVAL_REDIS_PORT:-6380}:6379'
command: ['redis-server', '--save', '60', '1000', '--appendonly', 'yes']
volumes:
- 'redis-data:/data'
@@ -40,8 +40,7 @@ services:
rustfs:
image: rustfs/rustfs:latest
ports:
- - '${EVAL_RUSTFS_PORT:-9100}:9000'
- - '${EVAL_RUSTFS_ADMIN_PORT:-9101}:9001'
+ - '127.0.0.1:${EVAL_RUSTFS_PORT:-9100}:9000'
environment:
RUSTFS_ACCESS_KEY: ${EVAL_RUSTFS_ACCESS_KEY:-admin}
RUSTFS_CONSOLE_ENABLE: 'true'
@@ -88,6 +87,7 @@ services:
# Host networking lets local QStash call an APP_URL on localhost without a tunnel.
# This eval stack targets the same Linux environment used by Harbor task containers.
+ # qstash dev has no bind-address option, so host firewall isolation remains required.
qstash:
image: public.ecr.aws/upstash/qstash:2.37.18
network_mode: host
@@ -108,8 +108,10 @@ services:
rustfs-init:
condition: service_completed_successfully
ports:
- - '${EVAL_DEVICE_GATEWAY_PORT:-8787}:8787'
- - '${EVAL_AGENT_GATEWAY_PORT:-8788}:8788'
+ - '127.0.0.1:${EVAL_DEVICE_GATEWAY_PORT:-8787}:8787'
+ - '${EVAL_DOCKER_BRIDGE_ADDRESS:-172.17.0.1}:${EVAL_DEVICE_GATEWAY_PORT:-8787}:8787'
+ - '127.0.0.1:${EVAL_AGENT_GATEWAY_PORT:-8788}:8788'
+ - '${EVAL_DOCKER_BRIDGE_ADDRESS:-172.17.0.1}:${EVAL_AGENT_GATEWAY_PORT:-8788}:8788'
environment:
AGENT_PORT: 8788
DEVICE_PORT: 8787
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 4a9082a51f5..1c92035a8fb 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -18,6 +18,7 @@ import type {
MessageMetadata,
MessagePluginItem,
ModelRankItem,
+ ModelReasoning,
ModelUsage,
NewMessageQueryParams,
QueryMessageParams,
@@ -291,10 +292,16 @@ export interface TopicTranscriptMessage {
id: string;
messageGroupId: string | null;
metadata: MessageMetadata | null;
+ model: string | null;
parentId: string | null;
+ pluginError: unknown;
+ provider: string | null;
+ reasoning: ModelReasoning | null;
role: string;
threadId: string | null;
+ toolCallId: string | null;
tools: ChatToolPayload[] | null;
+ usage: ModelUsage | null;
}
export interface TopicTranscriptResult {
@@ -1514,6 +1521,12 @@ export class MessageModel {
agentId: messages.agentId,
error: messages.error,
metadata: messages.metadata,
+ model: messages.model,
+ pluginError: messagePlugins.error,
+ provider: messages.provider,
+ reasoning: messages.reasoning,
+ toolCallId: messagePlugins.toolCallId,
+ usage: messages.usage,
content: messages.content,
createdAt: messages.createdAt,
id: messages.id,
@@ -1524,6 +1537,7 @@ export class MessageModel {
tools: messages.tools,
})
.from(messages)
+ .leftJoin(messagePlugins, and(eq(messagePlugins.id, messages.id), this.pluginsOwnership()))
.where(where)
.orderBy(asc(messages.createdAt), asc(messages.id))
.limit(limit)
@@ -1535,11 +1549,12 @@ export class MessageModel {
]);
return {
- items: items.map(({ tools, ...message }) => ({
+ items: items.map(({ tools, usage, ...message }) => ({
...message,
error: message.error as ChatMessageError | null,
metadata: message.metadata as MessageMetadata | null,
tools: Array.isArray(tools) ? (tools as ChatToolPayload[]) : null,
+ usage: usage ?? message.metadata?.usage ?? null,
})),
total: totalResult[0]?.count ?? 0,
};
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index ca7189e5e03..917f8dad7f6 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -455,8 +455,8 @@ export class TaskTopicModel {
}
/**
- * A goal's spend and round count in one aggregate: how many runs those tasks
- * produced and what they cost.
+ * Usage for one or more Tasks in one aggregate: how many runs they produced,
+ * their tokens, and what they cost.
*
* The Goal page renders these numbers and the coordinator enforces the budget
* against them, so both read them from here β€” a second definition of "what
@@ -467,12 +467,30 @@ export class TaskTopicModel {
* as a round but contribute nothing to the sum.
*/
async sumRunCostByTaskIds(taskIds: string[]): Promise<{
- byTask: { runs: number; taskId: string; totalCost: number; totalTokens: number }[];
+ byTask: {
+ runs: number;
+ taskId: string;
+ totalCost: number;
+ totalInputTokens: number;
+ totalOutputTokens: number;
+ totalTokens: number;
+ }[];
runs: number;
totalCost: number;
+ totalInputTokens: number;
+ totalOutputTokens: number;
totalTokens: number;
}> {
- if (taskIds.length === 0) return { byTask: [], runs: 0, totalCost: 0, totalTokens: 0 };
+ if (taskIds.length === 0) {
+ return {
+ byTask: [],
+ runs: 0,
+ totalCost: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalTokens: 0,
+ };
+ }
// Grouped once, then folded β€” one round trip serves both the enforced
// total and the per-Task breakdown the cost panel lists.
@@ -481,6 +499,8 @@ export class TaskTopicModel {
runs: count(),
taskId: taskTopics.taskId,
totalCost: sql<string>`coalesce(sum(${topics.totalCost}), 0)`,
+ totalInputTokens: sql<string>`coalesce(sum(${topics.totalInputTokens}), 0)`,
+ totalOutputTokens: sql<string>`coalesce(sum(${topics.totalOutputTokens}), 0)`,
totalTokens: sql<string>`coalesce(sum(${topics.totalTokens}), 0)`,
})
.from(taskTopics)
@@ -492,6 +512,8 @@ export class TaskTopicModel {
runs: row.runs,
taskId: row.taskId,
totalCost: Number(row.totalCost ?? 0),
+ totalInputTokens: Number(row.totalInputTokens ?? 0),
+ totalOutputTokens: Number(row.totalOutputTokens ?? 0),
totalTokens: Number(row.totalTokens ?? 0),
}));
@@ -499,6 +521,8 @@ export class TaskTopicModel {
byTask,
runs: byTask.reduce((sum, row) => sum + row.runs, 0),
totalCost: byTask.reduce((sum, row) => sum + row.totalCost, 0),
+ totalInputTokens: byTask.reduce((sum, row) => sum + row.totalInputTokens, 0),
+ totalOutputTokens: byTask.reduce((sum, row) => sum + row.totalOutputTokens, 0),
totalTokens: byTask.reduce((sum, row) => sum + row.totalTokens, 0),
};
}