From 79dadd86551e4deb254163dd1f952f2908f1d351 Mon Sep 17 00:00:00 2001 From: Zhou rui <121232618+Canyon-netizen@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:08:22 +0000 Subject: [PATCH] fix(hermes): keep a non-numeric cost out of the run accounting (#17266) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip runs a Hermes agent through the `hermes_local` adapter > - The adapter reads the run's cost out of the Hermes CLI output, because Hermes prints it > - The cost is read with a regex over the whole output, and the whole output includes the model's own answer > - The capture group of that regex matches text that is not a number, so an answer that happens to contain a word like "spent." is read as a cost > - `parseFloat(".")` is NaN, and NaN does not survive the run accounting: the server refuses to store it and marks the run failed > - The agent did the work and left its answer on the issue, but the run is red > - A failed run is not settled either, so the session is not carried into the next heartbeat, and the memory the run was meant to keep is lost > - The token parse next to the cost parse already guards exactly this shape, and the cost parse does not > - This pull request keeps the cost only when it is a finite number ## Linked Issues or Issue Description There is no public GitHub issue for this defect. The description below follows `.github/ISSUE_TEMPLATE/bug_report.yml`. **Pre-submission checklist** - [x] I have searched existing open and closed issues and this is not a duplicate. The repository was searched for the cost regex, the `costUsd` accounting and the `adapter_failed` error. The related items are listed at the end of this section. None of them covers this case. - [x] I am on the latest released version of Paperclip (or can reproduce on `master`). The change is based on `master` at `043f2514e`. The new test fails on that revision. - [x] I have confirmed the error originates in Paperclip itself — not in my agent adapter, API provider, or local configuration. The Hermes adapter is part of this repository, not an external plugin. The defect is in `packages/adapters/hermes/src/server/execute.ts`. The new test fails on unmodified `master` and passes with the fix. **What happened?** A Hermes agent answered on its issue, and the answer was correct and still on the issue. The run was recorded as failed anyway, with: ``` adapter_failed Invalid input: expected number, received NaN path: ["costUsd"] ``` The adapter reads the cost out of the Hermes output with: ```ts const COST_REGEX = /(?:cost|spent)[:\s]*\$?([\d.]+)/i; ``` The regex runs over the whole output, and the whole output contains the model's own answer. The answer contained the word `spent.` — as ordinary English prose, at the end of a sentence. The regex matched it, the capture group was `.`, and `parseFloat(".")` is `NaN`. The server then refused to store `NaN` as the run's cost, and marked the run failed. Because the run failed, it did not settle, and the session was not carried into the next heartbeat — so the memory the Hermes runtime exists for was lost as well. **Expected behavior** A cost that is not a number must not fail a run. The run should be recorded with no cost, the same way a run with no cost line at all is recorded. **Steps to reproduce** 1. Give an agent a Hermes adapter (`hermes_local`). 2. Let the agent answer with text that contains the word `cost` or `spent` followed by a full stop, for example `the round it spent.` 3. Start a run of the agent. 4. The run is marked `failed` with `adapter_failed` and `Invalid input: expected number, received NaN`. 5. The answer the agent left on the issue is still there, but the run is red, it does not settle, and the next heartbeat does not resume the session. **Paperclip version or commit** `master` at `043f2514e`. **Deployment mode** Self-hosted server. **Installation method** Built from source. **Agent adapter(s) involved** Hermes. The change is in `packages/adapters/hermes`, so no other adapter changes. **Database mode** Not database-related. **Node.js version** v24.22.1 on the author's own Linux host, where the tests ran before the push. **Operating system** Linux on the author's own Linux host, where the tests ran before the push. **Relevant logs or output** The error above is the complete error from the server. The adapter's own output at that point was a normal, successful answer. **Additional context** The same defect has a second effect that is easy to miss. The Hermes runtime is the one runtime in the company that keeps a session between heartbeats, so that the second heartbeat resumes the first one's thread. A run that fails is not settled, so its session is not recorded, and the next heartbeat starts from nothing. A single unlucky word in one answer therefore costs the agent its memory. ## What Changed - `packages/adapters/hermes/src/server/execute.ts`: the cost that the adapter reads out of the Hermes output is kept only when it is a finite number. The capture group of the cost regex is `[\d.]+`, which also matches text that is not a number, so an answer that contains a word like `spent.` was read as a cost of `NaN`. The server refuses to store a `NaN` cost and marks the whole run failed, even though the agent did its work and the answer is on the issue. A cost that is not finite is now left unset, which is the same state a run without a cost line ends up in. - `packages/adapters/hermes/src/server/execute.cost.test.ts`: new test file with three cases, run against a capture process that prints a fixture answer. The cases check that an answer containing `spent.` leaves the cost unset, that a real cost is still reported, and that the session is still handed back so that the next heartbeat can resume it. - No code comments are added. The upstream contributing guide asks that a pull request carries none, so the explanation of the failure mode lives in this description. ## Verification The commands below ran on the author's own Linux host, before the push. They did not run on CI. The host used Node.js v24.22.1 and vitest 5.0.3. The tree was the upstream `master` revision `043f2514e`, with this repository's own harness on top of it; the adapter files under test are identical in both trees. ```sh cd packages/adapters/hermes ./node_modules/.bin/vitest run src/server/execute.cost.test.ts ``` Before the change, the new case failed. The failure was the production symptom itself. ``` FAIL src/server/execute.cost.test.ts > Hermes cost parsing (real capture process) > leaves the cost out when the output does not carry a number AssertionError: expected NaN to be undefined ❯ src/server/execute.cost.test.ts:68:28 Test Files 1 failed (1) Tests 1 failed | 2 passed (3) ``` After the change, the file passes. ``` Test Files 1 passed (1) Tests 3 passed (3) ``` The whole package suite was re-run after the change, so that the fix is not traded against the rest of the adapter. ``` Test Files 11 passed (11) Tests 176 passed (176) ``` The type check of the package passes as well. ```sh cd packages/adapters/hermes ./node_modules/.bin/tsc --noEmit ``` ### The pull request carries no code comments The contributing guide asks that a pull request adds no code comments, so the explanatory block of this change was removed and the reasoning moved into this description. The tree of the branch was rebuilt from the branch content alone, and the whole package suite was run again on that tree. ``` Test Files 11 passed (11) Tests 176 passed (176) ``` The new test runs the adapter against a capture process that prints a fixture answer, the same way the other adapter tests do. It checks three things: an answer that contains `spent.` leaves the cost unset, a real cost is still reported, and the session is still handed back so that the next heartbeat can resume it. ## Risks - The change is local to the Hermes adapter. No other adapter and no server code changes. - A cost that is not a number is now recorded as no cost. That is the same state a run without a cost line ends up in, and the run's accounting already handles it. - A real cost is still reported. The change only rejects values that are not finite, so `0` is still a cost and `0.0123` is still a cost. - The regex itself is not tightened. It still matches the same text as before; the difference is that a capture that does not parse as a number is dropped instead of being carried into the accounting. - The upstream contributing guide asks that a pull request carries no code comments, so this change adds none. The explanation that the code would have carried lives in this description instead: the failure mode is not obvious from the diff, so a reviewer has to read the description above to follow the change. ## Model Used - Provider: MiniMax - Model id: `minimax-M3.1-Flash` - Context window: not published in this environment. The size is unknown. - Reasoning mode: the environment does not expose a reasoning or thinking mode for this model. - Capabilities used: tool use, code execution, shell, file editing. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../hermes/src/server/execute.cost.test.ts | 71 +++++++++++++++++++ .../adapters/hermes/src/server/execute.ts | 5 +- 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 packages/adapters/hermes/src/server/execute.cost.test.ts diff --git a/packages/adapters/hermes/src/server/execute.cost.test.ts b/packages/adapters/hermes/src/server/execute.cost.test.ts new file mode 100644 index 00000000000..973696fda46 --- /dev/null +++ b/packages/adapters/hermes/src/server/execute.cost.test.ts @@ -0,0 +1,71 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import type { AdapterExecutionContext } from "@paperclipai/adapter-utils"; + +import { execute } from "./execute.js"; + +const SESSION_ID = "20261022_170000_abcdef"; + +describe("Hermes cost parsing (real capture process)", () => { + let dir: string; + let command: string; + let capturePath: string; + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-hermes-cost-")); + command = path.join(dir, "hermes.cjs"); + capturePath = path.join(dir, "invocations.jsonl"); + await fs.writeFile(command, `#!${process.execPath} +const fs = require("node:fs"); +fs.appendFileSync(process.env.CAPTURE_PATH, JSON.stringify({ args: process.argv.slice(2) }) + "\\n"); +if (process.env.FIXTURE_STDOUT) console.log(process.env.FIXTURE_STDOUT); +console.log("Fixture completed\\nsession_id: ${SESSION_ID}"); +`, { mode: 0o700 }); + }); + + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + function context(stdout: string, overrides: Partial = {}): AdapterExecutionContext { + return { + runId: "run-cost", + agent: { + id: "agent-synthetic", companyId: "company-synthetic", name: "Hermes fixture", + adapterType: "hermes_local", adapterConfig: {}, + }, + runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: "task-synthetic" }, + config: { + hermesCommand: command, provider: "openrouter", model: "fixture-model", cwd: dir, + env: { CAPTURE_PATH: capturePath, FIXTURE_STDOUT: stdout }, timeoutSec: 10, graceSec: 1, + }, + context: { + issueId: "task-synthetic", + paperclipTaskMarkdownAssignment: "Complete current synthetic task.", + paperclipTaskMarkdownCompact: "Current synthetic task.", + }, + onLog: async () => {}, + ...overrides, + }; + } + + it("reports the cost when the output carries one", async () => { + const result = await execute(context("cost: $0.0123")); + expect(result.costUsd).toBeCloseTo(0.0123, 6); + expect(result.resultJson?.cost_usd).toBeCloseTo(0.0123, 6); + }); + + it("leaves the cost out when the output does not carry a number", async () => { + const result = await execute(context("the round it spent.")); + expect(result.costUsd).toBeUndefined(); + expect(result.resultJson?.cost_usd ?? null).toBeNull(); + }); + + it("still reports the session, so the next heartbeat can resume it", async () => { + const result = await execute(context("the round it spent.")); + expect(result.sessionParams).toEqual({ sessionId: SESSION_ID }); + expect(result.sessionDisplayId).toBe(SESSION_ID.slice(0, 16)); + }); +}); diff --git a/packages/adapters/hermes/src/server/execute.ts b/packages/adapters/hermes/src/server/execute.ts index b018acab243..cae03c22c0f 100644 --- a/packages/adapters/hermes/src/server/execute.ts +++ b/packages/adapters/hermes/src/server/execute.ts @@ -321,7 +321,10 @@ function parseHermesOutput(stdout: string, stderr: string): ParsedOutput { // Extract cost const costMatch = combined.match(COST_REGEX); if (costMatch?.[1]) { - result.costUsd = parseFloat(costMatch[1]); + const cost = parseFloat(costMatch[1]); + if (Number.isFinite(cost)) { + result.costUsd = cost; + } } // Check for error patterns in stderr