Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(scripts): collapse multi-line expressions and update comments

Steven Enamakelefdd8b07bb07
diff --git a/scripts/life-scenarios/run.mjs b/scripts/life-scenarios/run.mjs
index 1411ed6875..53b7dfc5c0 100644
--- a/scripts/life-scenarios/run.mjs
+++ b/scripts/life-scenarios/run.mjs
@@ -94,10 +94,7 @@ function parseArgs(argv) {
return v;
};
if (a === "--only")
- o.only = next()
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean);
+ o.only = next().split(",").map((s) => s.trim()).filter(Boolean);
else if (a === "--driver") o.driver = next();
else if (a === "--agent") o.agentId = next();
else if (a === "--model") o.model = next();
@@ -167,11 +164,7 @@ async function snapshotTree(root) {
else {
const st = await fsp.stat(p).catch(() => null);
if (st)
- out.push({
- rel: path.relative(root, p),
- bytes: st.size,
- mtimeMs: st.mtimeMs,
- });
+ out.push({ rel: path.relative(root, p), bytes: st.size, mtimeMs: st.mtimeMs });
}
}
}
@@ -231,13 +224,11 @@ async function prepareHome(runDir, { searchBase } = {}) {
const config = [
"schema_version = 13",
// The backend base every non-inference call resolves through
- // (`api::config::effective_backend_api_url`). Pointing it at the local
- // mock is what gives `web_search_tool` something to talk to: it posts to
+ // (`api::config::effective_backend_api_url`). Pointed at the local mock so
+ // `web_search_tool` has something to talk to: it posts to
// `/agent-integrations/parallel/search` on this base, and against the
- // hosted backend the run's offline token is rejected 401 on every call.
- // Loopback on an ephemeral port is passed through as a backend override —
- // `looks_like_local_ai_endpoint` only treats loopback as an inference
- // signal when it is paired with an LLM-ish port or path.
+ // hosted backend this run's offline token is rejected 401 every time.
+ // See also BACKEND_URL in `Core.start` — this file alone is not enough.
searchBase
? `api_url = "${searchBase}"`
: 'api_url = "https://api.tinyhumans.ai"',
@@ -300,9 +291,7 @@ async function withRetries(fn, { attempts, delayMs, what }) {
await new Promise((r) => setTimeout(r, delayMs));
}
}
- throw new Error(
- `${what} never settled after ${attempts} attempts: ${last?.message ?? last}`,
- );
+ throw new Error(`${what} never settled after ${attempts} attempts: ${last?.message ?? last}`);
}
// ---------------------------------------------------------------------------
@@ -322,14 +311,7 @@ class Core {
return `http://127.0.0.1:${this.port}`;
}
- async start({
- actionDir,
- logPath,
- home,
- composioBase,
- searchBase,
- approvals,
- }) {
+ async start({ actionDir, logPath, home, composioBase, searchBase, approvals }) {
this.port = await freePort();
const log = fs.createWriteStream(logPath, { flags: "a" });
@@ -356,17 +338,16 @@ class Core {
};
if (!approvals) env.OPENHUMAN_APPROVAL_GATE = "0";
if (process.env.BACKEND_URL) env.BACKEND_URL = process.env.BACKEND_URL;
- // The backend base, for `web_search_tool`'s POST to
- // `/agent-integrations/parallel/search`. Set as an env var and not only as
- // `api_url` in `config.toml`, because the config file loses a race it is
- // easy to miss: `auth.set_credential` activates a per-user config dir
+ // The same backend base as `api_url` above, set again as an env var
+ // because the config file loses a race that is easy to miss:
+ // `auth.set_credential` activates a per-user config dir
// (`users/<id>/config.toml`) whose id the core derives at runtime, and a
- // config written there takes precedence over the root one. `prepareHome`
- // cannot know that id, so it writes `users/local/` — the core activates
- // `users/local-dragonfly/`, finds no `api_url`, and falls back to the
- // hosted backend. `api_base_from_env` reads `BACKEND_URL` ahead of the
- // compile-time default and is consulted whichever config wins, so this is
- // the override that actually holds.
+ // config there takes precedence over the root one. `prepareHome` cannot
+ // know that id, so it writes `users/local/`; the core activates
+ // `users/local-dragonfly/`, finds no `api_url` and falls back to the
+ // hosted backend. `api_base_from_env` reads BACKEND_URL ahead of the
+ // compile-time default whichever config wins, so this is the override
+ // that actually holds.
if (searchBase) env.BACKEND_URL = searchBase;
if (composioBase) {
// Both are read by `integrations/composio/client/factory.rs`; the match
@@ -405,9 +386,7 @@ class Core {
}
await sleep(500);
}
- throw new Error(
- `core did not become healthy on ${this.url}; see ${logPath}`,
- );
+ throw new Error(`core did not become healthy on ${this.url}; see ${logPath}`);
}
async rpc(method, params, timeoutMs = 120_000) {
@@ -417,19 +396,12 @@ class Core {
"content-type": "application/json",
authorization: `Bearer ${this.token}`,
},
- body: JSON.stringify({
- jsonrpc: "2.0",
- id: `ls-${Date.now()}`,
- method,
- params,
- }),
+ body: JSON.stringify({ jsonrpc: "2.0", id: `ls-${Date.now()}`, method, params }),
signal: AbortSignal.timeout(timeoutMs),
});
const text = await res.text();
if (!res.ok)
- throw new Error(
- `RPC ${method} HTTP ${res.status}: ${text.slice(0, 400)}`,
- );
+ throw new Error(`RPC ${method} HTTP ${res.status}: ${text.slice(0, 400)}`);
let body;
try {
body = JSON.parse(text);
@@ -437,13 +409,10 @@ class Core {
throw new Error(`RPC ${method} non-JSON: ${text.slice(0, 300)}`);
}
if (body.error)
- throw new Error(
- `RPC ${method} error: ${JSON.stringify(body.error).slice(0, 500)}`,
- );
+ throw new Error(`RPC ${method} error: ${JSON.stringify(body.error).slice(0, 500)}`);
// `apply_log_envelope` wraps a result that carried log lines.
const r = body.result;
- if (r && typeof r === "object" && "result" in r && "logs" in r)
- return r.result;
+ if (r && typeof r === "object" && "result" in r && "logs" in r) return r.result;
return r;
}
@@ -481,10 +450,7 @@ class EventStream {
async connect() {
const url = `${this.core.url}/events?client_id=${encodeURIComponent(this.clientId)}`;
const res = await fetch(url, {
- headers: {
- authorization: `Bearer ${this.core.token}`,
- accept: "text/event-stream",
- },
+ headers: { authorization: `Bearer ${this.core.token}`, accept: "text/event-stream" },
signal: this.controller.signal,
});
if (!res.ok || !res.body)
@@ -558,16 +524,10 @@ class ApprovalResponder {
this.loop = (async () => {
while (this.running) {
try {
- const pending = await this.core.rpc(
- "openhuman.approval_list_pending",
- {},
- 15_000,
- );
+ const pending = await this.core.rpc("openhuman.approval_list_pending", {}, 15_000);
const rows = Array.isArray(pending)
? pending
- : (pending &&
- (pending.requests || pending.pending || pending.items)) ||
- [];
+ : (pending && (pending.requests || pending.pending || pending.items)) || [];
for (const row of rows) {
// `PendingApproval.request_id` — the decide RPC takes `request_id`,
// not `id`, and a wrong key comes back as a redacted
@@ -620,10 +580,7 @@ class ApprovalResponder {
* while a turn runs, and a window would sweep them in.
*/
async function usageIds(core) {
- const log = await core.rpc("openhuman.cost_get_usage_log", {
- days: 1,
- limit: 1000,
- });
+ const log = await core.rpc("openhuman.cost_get_usage_log", { days: 1, limit: 1000 });
const records = (log && log.records) || [];
return new Map(records.map((r) => [r.id, r]));
}
@@ -654,8 +611,7 @@ function foldUsage(rows) {
...t,
models: [...models],
cost_sources: [...sources],
- cache_hit_pct:
- t.input_tokens > 0 ? (t.cached_input_tokens / t.input_tokens) * 100 : 0,
+ cache_hit_pct: t.input_tokens > 0 ? (t.cached_input_tokens / t.input_tokens) * 100 : 0,
};
}
@@ -705,11 +661,7 @@ function gradeScenario(scenario, sandbox, transcript) {
({ checks } = scenario.grade(ctx));
} catch (e) {
checks = [
- {
- id: "grader_crashed",
- ok: false,
- detail: String(e.message).slice(0, 200),
- },
+ { id: "grader_crashed", ok: false, detail: String(e.message).slice(0, 200) },
];
}
const passed = checks.filter((c) => c.ok).length;
@@ -729,14 +681,7 @@ function gradeScenario(scenario, sandbox, transcript) {
* The desktop path: `channel_web_chat` acks immediately and the answer arrives
* on the event stream as `chat_done`, carrying the turn's own usage payload.
*/
-async function sendDesktopTurn({
- core,
- events,
- clientId,
- threadId,
- message,
- opts,
-}) {
+async function sendDesktopTurn({ core, events, clientId, threadId, message, opts }) {
const toolCalls = [];
let done = null;
let requestId = null;
@@ -781,11 +726,7 @@ async function sendDesktopTurn({
const timeout = sleep(opts.turnTimeoutMs).then(() => "timeout");
const outcome = await Promise.race([finished, timeout]);
if (outcome === "timeout")
- return {
- error: `turn did not emit chat_done within ${opts.turnTimeoutMs}ms`,
- requestId,
- toolCalls,
- };
+ return { error: `turn did not emit chat_done within ${opts.turnTimeoutMs}ms`, requestId, toolCalls };
if (done && done.event === "chat_error")
return {
@@ -823,28 +764,14 @@ async function sendRpcTurn({ core, threadId, message, sandbox, opts }) {
},
opts.turnTimeoutMs,
);
- return {
- reply: typeof reply === "string" ? reply : "",
- usage: null,
- requestId: null,
- toolCalls: [],
- };
+ return { reply: typeof reply === "string" ? reply : "", usage: null, requestId: null, toolCalls: [] };
}
// ---------------------------------------------------------------------------
// run one scenario
// ---------------------------------------------------------------------------
-async function runScenario({
- core,
- events,
- clientId,
- approvals,
- scenario,
- runDir,
- opts,
- attempt,
-}) {
+async function runScenario({ core, events, clientId, approvals, scenario, runDir, opts, attempt }) {
const sandboxRoot = path.join(runDir, "sandbox");
const sandbox = path.join(sandboxRoot, scenario.id);
await fsp.rm(sandbox, { recursive: true, force: true });
@@ -870,14 +797,7 @@ async function runScenario({
try {
turn =
opts.driver === "desktop"
- ? await sendDesktopTurn({
- core,
- events,
- clientId,
- threadId,
- message,
- opts,
- })
+ ? await sendDesktopTurn({ core, events, clientId, threadId, message, opts })
: await sendRpcTurn({ core, threadId, message, sandbox, opts });
if (turn.error) error = turn.error;
} catch (e) {
@@ -922,8 +842,7 @@ async function runScenario({
ok: !error,
error,
latency_ms: latencyMs,
- ledger_elapsed_ms:
- ledger && ledger.telemetry ? ledger.telemetry.elapsedMs : null,
+ ledger_elapsed_ms: ledger && ledger.telemetry ? ledger.telemetry.elapsedMs : null,
tool_calls: turn.toolCalls,
tool_call_count:
ledger && ledger.telemetry && ledger.telemetry.toolCount != null
@@ -977,17 +896,7 @@ function printReport(results) {
a.total += r.grade.total;
return a;
},
- {
- input: 0,
- cached: 0,
- output: 0,
- cost: 0,
- latency: 0,
- tools: 0,
- approvals: 0,
- passed: 0,
- total: 0,
- },
+ { input: 0, cached: 0, output: 0, cost: 0, latency: 0, tools: 0, approvals: 0, passed: 0, total: 0 },
);
console.log(
`TOTAL completion ${tot.passed}/${tot.total} (${Math.round(
@@ -1056,9 +965,7 @@ async function main() {
);
console.log(`run dir : ${runDir}`);
- console.log(
- `driver : ${opts.driver}${opts.agentId ? ` agent=${opts.agentId}` : " agent=orchestrator"}`,
- );
+ console.log(`driver : ${opts.driver}${opts.agentId ? ` agent=${opts.agentId}` : " agent=orchestrator"}`);
let search = null;
if (opts.mockSearch) {
@@ -1072,9 +979,7 @@ async function main() {
);
}
- const home = await prepareHome(runDir, {
- searchBase: search ? search.url : "",
- });
+ const home = await prepareHome(runDir, { searchBase: search ? search.url : "" });
let composio = null;
if (opts.mockComposio) {
@@ -1097,9 +1002,7 @@ async function main() {
searchBase: search ? search.url : "",
approvals: opts.approvals,
});
- console.log(
- `core : ${core.url} (pid ${health.pid}, healthy=${health.healthy})`,
- );
+ console.log(`core : ${core.url} (pid ${health.pid}, healthy=${health.healthy})`);
// Stand in for login.
const localUserId = "life-scenarios-local";
@@ -1144,12 +1047,7 @@ async function main() {
// `config.get` wraps the config under `config` (see
// `snapshot_config_json`), and the RPC envelope may wrap that again.
const snap = await core.rpc("openhuman.config_get", {});
- const cfg =
- snap?.config ??
- snap?.snapshot?.config ??
- snap?.snapshot ??
- snap ??
- {};
+ const cfg = snap?.config ?? snap?.snapshot?.config ?? snap?.snapshot ?? snap ?? {};
const providers = cfg.cloud_providers ?? [];
const routed =
cfg.inference_url === opts.inferenceUrl &&
@@ -1181,9 +1079,7 @@ async function main() {
try {
for (let attempt = 1; attempt <= opts.repeat; attempt += 1) {
for (const scenario of selected) {
- process.stdout.write(
- `running ${scenario.id} (attempt ${attempt}) ... `,
- );
+ process.stdout.write(`running ${scenario.id} (attempt ${attempt}) ... `);
const r = await runScenario({
core,
events,
@@ -1214,11 +1110,7 @@ async function main() {
if (approvals)
await fsp.writeFile(
path.join(runDir, "approvals.json"),
- JSON.stringify(
- { decisions: approvals.decisions, errors: approvals.errors },
- null,
- 2,
- ),
+ JSON.stringify({ decisions: approvals.decisions, errors: approvals.errors }, null, 2),
);
if (composio) {
await fsp.writeFile(
@@ -1232,8 +1124,8 @@ async function main() {
await composio.close();
}
// `close` flushes the search log itself, so the record survives a run that
- // failed partway: it is the only evidence of what discovery actually
- // returned, and a post-mortem needs it most on the runs that went wrong.
+ // failed partway: it is the only evidence of what discovery returned, and
+ // a post-mortem needs it most on the runs that went wrong.
if (search) await search.close();
}