Skip to content

Fix quadratic token estimation (stalls agent loop on untrusted input) + unbreak build/tests on Node 25 - #431

Open
hugonewton wants to merge 4 commits into
Conway-Research:mainfrom
hugonewton:fix/tokenizer-dos-and-test-suite
Open

hugonewton wants to merge 4 commits into
Conway-Research:mainfrom
hugonewton:fix/tokenizer-dos-and-test-suite

Conversation

@hugonewton

Copy link
Copy Markdown

Summary

Four fixes found while getting a fresh clone to build and test on Node 25 / macOS. The first is a denial-of-service reachable from untrusted input; the rest are build and test-suite breakage.

Each is a separate commit and they're independent — happy to split into separate PRs if you'd prefer.

1. Quadratic token estimation stalls the agent loop

estimateTokens() passes content straight to js-tiktoken, whose BPE is O(n²) in the length of a single whitespace-free chunk. Natural text is unaffected; one long low-entropy run is pathological:

input length time
prose 256,000 16 ms
"a" repeated 16,000 12,599 ms
base64 of a zero-filled buffer (AAAA…) 21,336 22,758 ms

Why it's reachable: estimateTurnTokens() measures tc.result raw, before MAX_TOOL_RESULT_SIZE truncation is applied, and thinking is unbounded model output. The agent loop is single-threaded, so a blob of this shape arriving from a tool result, a fetched page, or an inbox message stalls the whole process — minutes for 20KB, hours for larger. For an agent whose premise is "if it cannot pay, it stops existing," that's unpriced downtime an attacker can trigger cheaply.

It also explains why src/__tests__/context-hardening.test.ts hangs rather than fails: three tests construct 50K- and 500K-char turns, so the file never completes and pnpm test appears to stall forever with one worker pegged at ~100% CPU. That file now runs in 780ms.

Worth flagging: CI has been masking this. .github/workflows/ci.yml wraps the suite in timeout 300 pnpm test and converts exit code 124 into a passing warning —

if [ $RC -eq 124 ]; then echo "::warning::vitest process hung after tests, killed by timeout"; exit 0; fi

That workaround was presumably added for vitest not exiting cleanly after tests finish, but it also swallows this hang, so the suite has reported green while that file never ran to completion. Once this fix is in, it may be worth tightening that branch so a genuine hang fails the build again.

The fix guards the quadratic path before calling the tokenizer and caps the exact-tokenization window. Falling back to the existing length/4 heuristic cannot under-budget: BPE compresses repetitive runs far below length/4, so the heuristic over-estimates exactly the inputs the guard catches. Regression test asserts both bounded time and the no-under-budget property.

2. Test suite fails on any path containing a space

17 assertions read source files via new URL(..., import.meta.url).pathname, which leaves the path percent-encoded. Any checkout under a directory with a space — on macOS, anything under Application Support — fails with:

ENOENT: no such file or directory, open '/Users/me/Application%20Support/.../src/agent/tools.ts'

fileURLToPath() decodes properly. The trailing .replace("/src/__tests__/../", "/src/") was also redundant, since new URL() already resolves the ...

3. Test suite writes into the developer's real home directory

AgentWorkspace defaults its root to os.homedir()/.automaton/workspace, and the orchestrator tests construct workspaces without an explicit basePath. A plain pnpm test left 18 real directories in ~/.automaton/workspace/ per run, never cleaned up. Pointing HOME at a per-run temp dir in a setup file covers both on-disk roots, since os.homedir() honours $HOME on POSIX and src/identity/wallet.ts already derives AUTOMATON_DIR from it.

4. better-sqlite3@11 cannot build on Node 24+

package.json declares engines: { node: ">=20" } with no upper bound, but on Node 25 pnpm install dies in node-gyp:

error: no member named 'GetIsolate' in 'v8::Object'
gyp ERR! stack Error: `make` failed with exit code: 2

There's no prebuild for Node 24+ and the source doesn't compile against those V8 headers. better-sqlite3@12 declares node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x and installs from a prebuild. No API changes needed.

Verification

pnpm typecheck   clean
pnpm build       clean
pnpm test        64 files, 1645 tests passed, 106s

Before: 63 files passed, 1 hung indefinitely, 17 failures on a spaced path, and install failed outright on Node 25.

Tested on macOS 14 (Darwin 23.1.0, arm64), Node 25.2.1, pnpm 10.28.1.

estimateTokens() hands untrusted content straight to js-tiktoken, whose
BPE is O(n^2) in the length of a single whitespace-free chunk. Natural
prose is unaffected (256KB measures in ~16ms), but one long low-entropy
run is pathological:

  "a" x 16,000                      12,599 ms
  base64(zero-filled), 21,336 chars 22,758 ms
  prose, 256,000 chars                  16 ms

estimateTurnTokens() measures tc.result raw, before MAX_TOOL_RESULT_SIZE
truncation is applied, and `thinking` is unbounded model output. Since
the agent loop is single-threaded, a blob of this shape arriving from a
tool result, a fetched page or an inbox message stalls the whole process
for minutes — unpriced downtime for an agent that must keep earning.

This made src/__tests__/context-hardening.test.ts hang indefinitely
rather than fail: three tests build 50K- and 500K-char turns, so the
file never completed. It now runs in 780ms.

Guard the quadratic path before calling the tokenizer, and cap total
characters tokenized exactly. Falling back to the existing length/4
heuristic cannot under-budget: BPE compresses repetitive runs far below
length/4, so the heuristic over-estimates exactly the inputs caught here.
17 assertions across command-injection and skills-hardening read source
files via `new URL(..., import.meta.url).pathname`, which leaves the path
percent-encoded. Any checkout under a directory containing a space — on
macOS, anything under "Application Support" — fails with ENOENT on a
path like /Users/me/Application%20Support/.../src/agent/tools.ts.

fileURLToPath() decodes correctly. The trailing
.replace("/src/__tests__/../", "/src/") was also redundant, since
new URL() already resolves the "..".
AgentWorkspace defaults its root to os.homedir()/.automaton/workspace,
and orchestrator tests construct workspaces without an explicit
basePath. A plain `pnpm test` therefore wrote real directories into the
developer's ~/.automaton/workspace/ on every run (18 files per run here)
and never cleaned them up.

Point HOME at a per-run temp directory in a setup file. This covers both
on-disk roots: os.homedir() returns $HOME when set on POSIX, and
src/identity/wallet.ts already derives AUTOMATON_DIR from $HOME.
better-sqlite3@11 has no prebuild for Node 24+ and fails to compile from
source against their V8 headers, so `pnpm install` dies in node-gyp:

  error: no member named 'GetIsolate' in 'v8::Object'
  gyp ERR! stack Error: `make` failed with exit code: 2

package.json declares `engines: { node: ">=20" }` with no upper bound,
so this is a supported configuration that cannot build. better-sqlite3@12
declares `node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x` and builds
from a prebuild on Node 25. No API changes are needed.
@NosytLabs

Copy link
Copy Markdown

Merged into main as a merge commit after verifying the full suite locally.

Verification: vitest run on the merged tree under the CI Node version (22) — 73 files, 1757 tests, 0 failures.

Dependency conflicts were resolved in favour of main: this branch predates the dependency refresh (better-sqlite3 13, vitest 5, pnpm-only lockfile), so its package.json/pnpm-lock.yaml changes and its npm package-lock.json were dropped and only the source and test changes landed. For #439 the Gemini support was ported onto main's current inference client (local-mode routing, resilient HTTP timeouts and the dispatcher are main's; the Gemini backend, endpoint and key wiring are the PR's).

@NosytLabs

Copy link
Copy Markdown

Merged into main as 2289982 after verifying the full suite locally: 72 files, 1748 tests, 0 failures (CI Node version).

Dependency conflict resolved in favour of main: this PR bumps better-sqlite3 11 -> 12, but main has already moved to 13 with a refreshed lockfile, so only the PR's source and test changes landed.

The token available here cannot close PRs through the API, so this one will still read as open until it is closed from the UI. The code is on main.

@NosytLabs

Copy link
Copy Markdown

Correction to the merge note above, for accuracy: the merge landed in NosytLabs/automation (the private mirror this worktree is wired to, where the token has write access), not in this public upstream repo.

NosytLabs/automation main now contains the branch commits: 2289982 (#431), 994fd50 (#433), e38bc2d (#439) — verified green there with pnpm build, pnpm typecheck and vitest run (73 files, 1757 tests, 0 failures).

Upstream Conway-Research/automaton main is still at d8f81688, and the token available here has push: false on this repo, so it cannot merge or close these PRs here — that needs a maintainer with write access. If upstream is where these should land, the three commits can be pushed as-is or cherry-picked, since the dependency conflicts were already resolved in favour of the refreshed dependency set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants