Skip to content

fix(cli): surface model errors and make agent stack traces readable - #625

Merged
kalenkevich merged 3 commits into
google:mainfrom
AmaadMartin:fix/cli-surface-model-errors
Sep 14, 2026
Merged

kalenkevich merged 3 commits into
google:mainfrom
AmaadMartin:fix/cli-surface-model-errors

Conversation

@AmaadMartin

@AmaadMartin AmaadMartin commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A developer whose API key is bad, expired, or simply the wrong variable — the single most
common first-run failure — gets no diagnostic output and exit code 0:

$ npx adk run agent.ts
[user]: INFO: [ADK] Sending out request, model: gemini-flash-latest, backend: GEMINI_API, stream: false
[user]:
EXITCODE=0

Nothing on stderr, nothing on stdout, a success exit code. There is no thread to pull on.

Three independent defects produce that:

  1. Model errors are never printed. llm_agent.ts turns every model failure into an Event
    carrying errorCode/errorMessage and no content. Both event loops in cli_run.ts
    printed only event.content.parts, so the error was silently dropped.
  2. Exceptions went to stdout with exit 0. runAgent's handler was catch (e) { console.log(e) }.
  3. Stack traces were useless. The agent loader esbuild-bundles and minifies the user's file
    into a temp dir that is deleted on exit, so every frame looked like
    at new H_ (/tmp/adk_agent_loader/29d078dd-.../agent.cjs:537:1742) — mangled name,
    meaningless line, file gone.

Fix

  • cli_run.ts: one printEvent helper used by both the interactive and the --replay loop.
    Text still goes to stdout; errorCode/errorMessage go to stderr and set
    process.exitCode = 1. An event carrying both is printed both ways.
  • runAgent's catch → console.error + non-zero exit code. Same for the run subcommand
    handler and the CLI entrypoint.
  • Minification is now opt-in (AgentFileOptions.minify, default false). adk run,
    adk web and adk api_server build unminified with an inline source map (inline because
    the bundle's temp dir is deleted before anyone reads the trace) and enable Node's source-map
    support. adk deploy cloud_run / deploy agent_engine pass minify: true and skip the map,
    so deployment artifacts are unchanged.
  • replaceDirnamePlugin now returns a chained inline map for the entry file. Without it the
    outer build can only map back to the plugin's pre-transformed text and traces land on the
    wrong line of the agent file (off by one or two in practice).

Before / after — bad API key

Real run against the Gemini API with a deliberately invalid key.

Before

$ node adk run agent.ts
Running agent demo_agent, type exit to exit.
[user]: INFO: [ADK] Sending out request, model: gemini-flash-latest, backend: GEMINI_API, stream: false
[user]:
--- stderr: (empty) ---
EXITCODE=0

After

$ node adk run agent.ts
Running agent demo_agent, type exit to exit.
[user]: INFO: [ADK] Sending out request, model: gemini-flash-latest, backend: GEMINI_API, stream: false
[demo_agent] ERROR (400): API key not valid. Please pass a valid API key.   <-- stderr
[user]:
EXITCODE=1

Before / after — stack trace from the developer's own code

runtime_boom_agent.ts throws from a beforeAgentCallback at line 4 (loadUserProfile),
called at line 12.

Before — printed to stdout, exit 0, every frame inside a minified bundle in a
temp dir that no longer exists:

[user]: Error: profile store unreachable
    at DGn (file:///…/adk_agent_loader-4YUlW0/runtime_boom_agent.mjs?t=…:716:55077)
    at beforeAgentCallback (file:///…/adk_agent_loader-4YUlW0/runtime_boom_agent.mjs?t=…:716:55251)
    at t.handleBeforeAgentCallback (file:///…/adk_agent_loader-4YUlW0/runtime_boom_agent.mjs?t=…:547:60939)
    at t.<anonymous> (file:///…/adk_agent_loader-4YUlW0/runtime_boom_agent.mjs?t=…:547:59755)
    at t.runAsync (file:///…/adk_agent_loader-4YUlW0/runtime_boom_agent.mjs?t=…:547:59668)
EXITCODE=0

After — stderr, exit 1, real function names and real line numbers in the user's file:

Error: profile store unreachable
    at loadUserProfile (/home/…/runtime_boom_agent.ts:4:9)
    at beforeAgentCallback (/home/…/runtime_boom_agent.ts:12:5)
    at _LlmAgent.handleBeforeAgentCallback (…/core/dist/esm/agents/base_agent.js:219:29)
    …
EXITCODE=1

Same for a throw at agent construction time (the at new H_ (…) shape from the original report):
at new WeatherClient (/home/…/boom_agent.ts:6:13) / at <anonymous> (/home/…/boom_agent.ts:11:16).

Tests

dev/test/cli/cli_run_bad_api_key_test.ts is the headline regression test: a real LlmAgent
and a real Runner (only the file loader is faked) driven by a model that throws the verbatim
{"error":{"code":400,"message":"API key not valid…"}} body the Gemini API returns. It asserts
stderr is non-empty, contains the reason, and process.exitCode === 1. It fails on main
(expected "error" to be called at least once).

Also added:

  • cli_run_test.ts — error event surfaces in interactive and --replay mode, text
    accompanying an error event still prints, a successful run leaves the exit code alone, and a
    thrown error goes to console.error rather than console.log. 4 of these fail on main.
    The mocked Runner/session service are now re-established per test; restoreAllMocks was
    wiping the implementations set in the module factory, which left the runner inert from the
    second test onwards — invisible before because runAgent swallowed the resulting TypeError.
  • agent_loader_test.ts — an explicit {minify: false} gives sourcemap: 'inline' with Node
    source maps enabled; the default gives minify: true, sourcemap: false and no global
    source-map opt-in, plus a regression test that concurrent callers share one preload pass.
  • cli_test.ts — run/web/api_server pass minify: false, both deploy targets pass true.

Verified: npm run build, npx vitest run --project unit:dev (only pre-existing
cli_create_test.ts > Vertex AI selection with gcloud defaults fails, on main too — it
depends on local gcloud config), eslint, prettier --check, and
vitest --project integration tests/integration/build_setup (20 passed, incl. both
native-addon fixtures).

Trade-off worth knowing

An unminified bundle with an inline source map is a debug build: it is what makes the trace
readable, and it is ~3.5x larger. Measured over the four agents the app_loader discovery
fixture loads (min of 3, esbuild + import, Linux workstation):

build bundle build import total
main (minified, no map) 23.6 MB 1554 ms 1940 ms 3527 ms
unminified, no map 48.5 MB 1611 ms 2016 ms 3629 ms
debug build (unminified + inline map, sourcesContent: false) 83.1 MB 1931 ms 2332 ms 4301 ms

So the debug build is worth about +1 s of adk run startup, which is a good trade when a human
is about to read the output — and a bad one for a caller that will never look at a stack trace.

It is therefore opt-in per call site. adk run, adk web and adk api_server pass
minify: false and get readable traces; both deploy targets pass minify: true; anything that
says nothing keeps the historical minified bundle. Every CLI entry point already routed through
getAgentFileOptions, so this costs the fix nothing: deployment artifacts are unchanged, and
adk run still prints

Error: weather endpoint must be https
    at new WeatherClient (/…/boom_agent.ts:6:13)
    at Object.<anonymous> (/…/boom_agent.ts:11:16)

on stderr with exit code 1.

Alternatives measured and rejected:

  • External .map — 48.5 MB + a 25.9 MB map, and still 2.05x main's bundle. Worse, runAgent's
    await using agentFile deletes the temp dir when the try block exits, before the catch
    formats the stack, so a lazily-read external map would already be gone. Slower and broken.
  • minify: true + keepNames: true + map — 59.4 MB and slower than the debug build
    (4415 ms), while still degrading names in the developer's own frames. Strictly worse.
  • packages: 'external' — the real prize: 0.008 MB and 25 ms, ~140x faster than main,
    because the temp dir already symlinks the project's node_modules. It would make adk run
    faster than today and fully debuggable. But it changes what --bundle means and can break
    agents outside a node_modules-bearing project, so it belongs in its own PR rather than
    smuggled into a CI fix.

Out of scope (noticed while verifying)

An exception thrown inside a tool never reaches the CLI at all: FunctionTool.runAsync
rethrows with only error.message (core/src/tools/function_tool.ts:167) and
core/src/agents/functions.ts keeps only e.message in the tool response so the model can
recover. The stack is discarded in core before the CLI sees anything, so no CLI-side change can
surface it. Left alone here — this PR only touches dev/.

tests/integration/skills/script_js/agent_test.ts has the same
beforeAll(…, TEST_EXECUTION_TIMEOUT) bug fixed here for app_loader_test.ts — an npm install
held to a per-test budget. Not touched, but worth a follow-up.

The macOS failure, and the two bugs underneath it

The earlier revision of this PR failed run-tests (macos-latest) three times running. It was
not flake, and the cause was mine — but it landed on a test that was already close to the edge.

1. This PR's regression (fixed). The debug build was the loader's default, so
app_loader_test.ts's discovery test — which bundles four agents through AgentLoader — paid
for it. Measured locally, same machine, same fixture:

loader discovery test budget used
main 18,322 ms 46%
this PR, before this commit 29,626 ms 74%
this PR, now 15,725 ms 26%

On a green macos-latest run of main that test takes 29,806 ms. Applying the measured
+62% gives ~48 s against a 40 s budget: a deterministic failure, which is exactly what CI showed.

2. preloadAgents() had no in-flight dedup (fixed). The "already preloaded" flag was only
set after the whole pass finished, so any caller arriving during the pass started its own.
Three overlapping callers → 12 esbuild builds instead of 4, 5.1 s instead of 13.6 s. When
the first it() timed out mid-pass, the next two each kicked off a fresh full pass, which is
why the failures arrived in clusters of two or three and why build_setup_test.ts sometimes got
dragged down with them — 12 concurrent 83 MB bundles starve every other test file in the pool.
This is also a live adk web bug: several routes call listAgents() and requests are
concurrent. agent_loader_test.ts gains a regression test (9 builds before, 3 after).

3. app_loader_test.ts pinned everything to 40 s (fixed). That predates #548, which gave the
integration project a 60 s test budget and a 120 s hook budget precisely because these fixtures
run npm install and bundle agent trees. The local override applied to hooks too, so a cold
npm install (~60 s) blew a 40 s hook budget — reproducible locally by clearing the fixture's
node_modules. And 40 s never suited the discovery test: 29.8 s on a green macOS run is 25%
headroom on a shared runner. Both budgets now come from vitest.config.ts like every other
integration test. (Diff looks large; it is mostly reindentation — ?w=1 shows 29 lines.)

This is the standing tax #622 describes. main itself failed 5 of its last 12 validation runs.

build_setup_test.ts's 20 s budget is not touched: on green macOS it uses 5.9 s, and the
debug build's +1 s takes that to ~7 s. Its "Don't raise TEST_EXECUTION_TIMEOUT" comment stands.

Verified locally: full --project integration suite — app_loader_test.ts 6/6 green (discovery
16.5 s), build_setup_test.ts green. --project unit:dev 255/256, the one failure being the
pre-existing gcloud-dependent cli_create_test.ts case that also fails on main. eslint,
prettier --check, and tsc --noEmit (280 pre-existing errors, identical count on main).

Comment thread dev/src/cli/cli.ts Outdated
// Minification destroys stack traces, so it is opt-in and reserved for
// deployment bundles where the artifact size matters more than a readable
// trace. Local commands (run/web/api_server) keep readable output.
minify = false,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be part of the options

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — minify is now a field of the options object getAgentFileOptions already takes, so the deploy call sites read getAgentFileOptions({...options, minify: true}) and the /* minify= */ marker comments are gone. Behaviour is unchanged: run/web/api_server still get minify: false and both deploy commands true, as the matrix in cli_test.ts asserts.

Pushed in 573aee14, all checks green.

Comment thread dev/src/cli/cli.ts Outdated
agentFileLoadOptions: getAgentFileOptions(options),
agentFileLoadOptions: getAgentFileOptions(
options,
/* minify= */ true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minify should be part of the options

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered by the refactor in 573aee14 — see the thread on the getAgentFileOptions signature above. This call site is now getAgentFileOptions({...options, minify: true}).

Comment thread dev/src/cli/cli.ts Outdated
agentFileLoadOptions: getAgentFileOptions(options),
agentFileLoadOptions: getAgentFileOptions(
options,
/* minify= */ true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Covered by the refactor in 573aee14 — see the thread on the getAgentFileOptions signature above. This call site is now getAgentFileOptions({...options, minify: true}).

Comment thread dev/src/cli/cli_run.ts

@kalenkevich kalenkevich Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too much done for one pr.

The actaul fix is only this file, so can you please strip out the rest and create separate prs
Thanks

Amaad Martin added 3 commits September 14, 2026 15:32
`adk run` with a bad, expired, or wrong API key -- the most common
first-run failure -- printed nothing at all and exited 0:

    $ npx adk run agent.ts
    [user]: INFO: [ADK] Sending out request, model: gemini-flash-latest...
    [user]:
    EXITCODE=0

Three separate defects:

1. Model failures ride on `Event.errorCode` / `Event.errorMessage` with
   no `content` (llm_agent.ts), but both event loops in cli_run.ts only
   printed `event.content.parts`, so the error was dropped. Print it to
   stderr and set a non-zero exit code, in interactive and replay mode.

2. `runAgent`'s catch was `console.log(e)` -> stdout, exit 0. Now
   `console.error` plus `process.exitCode = 1` (same for the run
   subcommand and the CLI entrypoint).

3. The agent loader esbuild-bundled and minified the user's file, so
   every trace pointed into a mangled, already-deleted temp bundle:
   `at new H_ (/tmp/adk_agent_loader/.../agent.cjs:537:1742)`.
   Minification is now opt-in and used only for `adk deploy`; local
   commands emit an inline source map, so traces name the developer's
   own file and line.
The unminified, source-mapped bundle is what makes an agent's stack trace
readable, but it is 3.5x larger (23.6 MB -> 83.1 MB over the four agents in
the app_loader fixture) and it was applied to every caller, including ones
that never read a trace. That pushed `app_loader_test.ts`'s discovery test
from 18.3s to 29.6s locally against a 40s budget, and made macos-latest fail
deterministically.

Every CLI entry point already passes `minify` explicitly - run/web/api_server
ask for the debug build, both deploy targets opt out - so the loader-level
default is reached only by programmatic callers. Restore it to the historical
"minify when bundling", and gate the source map (and the plugin's chained
entry map) on an explicit `minify: false`. `adk run` still prints
`at new WeatherClient (/path/boom_agent.ts:6:13)` on stderr with exit 1;
nobody else pays for it.

Two pre-existing problems in the same area, which is why this test also failed
on unrelated PRs such as the docs-only #623:

- `preloadAgents()` only set its "done" flag after the whole pass finished, so
  overlapping callers each re-bundled every agent - 4 esbuild builds became 12
  and 5.1s became 13.6s. One timing-out test therefore made the next two
  slower, which is why the failures arrived in clusters. `adk web` hits the
  same path from several routes on concurrent requests.
- `app_loader_test.ts` pinned tests *and hooks* to 40s, overriding the 60s/120s
  budgets vitest.config.ts sets for the integration project in #548. A cold
  `npm install` (~60s) blew the hook budget, and 40s never suited the discovery
  test: it takes 29.8s on a *green* macos-latest run of main.
getAgentFileOptions took minify as a trailing positional parameter, so
the two deploy call sites had to spell out what the bare `true` meant
with a `/* minify= */` marker comment. Making it a field of the options
object the function already takes lets the call site name it directly.
@AmaadMartin
AmaadMartin force-pushed the fix/cli-surface-model-errors branch from c01c8cd to 6e78092 Compare September 14, 2026 22:34
@AmaadMartin

Copy link
Copy Markdown
Collaborator Author

Rebased onto main and resolved the conflict in dev/test/cli/cli_run_test.ts. The conflict was two adjacent top-level declarations; I kept both the AskUser type and the createMockSessionService helper, since both are used below. Build, ts:check, format:check, and the four touched dev CLI test files (128 tests) pass. Now at 6e78092.

@kalenkevich
kalenkevich merged commit 9508dee into google:main Sep 14, 2026
14 checks passed
@kalenkevich kalenkevich mentioned this pull request Sep 14, 2026
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
…oogle#625)

* fix(cli): surface model errors and make agent stack traces readable

`adk run` with a bad, expired, or wrong API key -- the most common
first-run failure -- printed nothing at all and exited 0:

    $ npx adk run agent.ts
    [user]: INFO: [ADK] Sending out request, model: gemini-flash-latest...
    [user]:
    EXITCODE=0

Three separate defects:

1. Model failures ride on `Event.errorCode` / `Event.errorMessage` with
   no `content` (llm_agent.ts), but both event loops in cli_run.ts only
   printed `event.content.parts`, so the error was dropped. Print it to
   stderr and set a non-zero exit code, in interactive and replay mode.

2. `runAgent`'s catch was `console.log(e)` -> stdout, exit 0. Now
   `console.error` plus `process.exitCode = 1` (same for the run
   subcommand and the CLI entrypoint).

3. The agent loader esbuild-bundled and minified the user's file, so
   every trace pointed into a mangled, already-deleted temp bundle:
   `at new H_ (/tmp/adk_agent_loader/.../agent.cjs:537:1742)`.
   Minification is now opt-in and used only for `adk deploy`; local
   commands emit an inline source map, so traces name the developer's
   own file and line.

* fix(dev): make the debug build opt-in and share one agent preload pass

The unminified, source-mapped bundle is what makes an agent's stack trace
readable, but it is 3.5x larger (23.6 MB -> 83.1 MB over the four agents in
the app_loader fixture) and it was applied to every caller, including ones
that never read a trace. That pushed `app_loader_test.ts`'s discovery test
from 18.3s to 29.6s locally against a 40s budget, and made macos-latest fail
deterministically.

Every CLI entry point already passes `minify` explicitly - run/web/api_server
ask for the debug build, both deploy targets opt out - so the loader-level
default is reached only by programmatic callers. Restore it to the historical
"minify when bundling", and gate the source map (and the plugin's chained
entry map) on an explicit `minify: false`. `adk run` still prints
`at new WeatherClient (/path/boom_agent.ts:6:13)` on stderr with exit 1;
nobody else pays for it.

Two pre-existing problems in the same area, which is why this test also failed
on unrelated PRs such as the docs-only google#623:

- `preloadAgents()` only set its "done" flag after the whole pass finished, so
  overlapping callers each re-bundled every agent - 4 esbuild builds became 12
  and 5.1s became 13.6s. One timing-out test therefore made the next two
  slower, which is why the failures arrived in clusters. `adk web` hits the
  same path from several routes on concurrent requests.
- `app_loader_test.ts` pinned tests *and hooks* to 40s, overriding the 60s/120s
  budgets vitest.config.ts sets for the integration project in google#548. A cold
  `npm install` (~60s) blew the hook budget, and 40s never suited the discovery
  test: it takes 29.8s on a *green* macos-latest run of main.

* refactor(cli): carry minify inside the agent file options object

getAgentFileOptions took minify as a trailing positional parameter, so
the two deploy call sites had to spell out what the bare `true` meant
with a `/* minify= */` marker comment. Making it a field of the options
object the function already takes lets the call site name it directly.

---------

Co-authored-by: Amaad Martin <[email protected]>
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