Skip to content

Phase 1: Server, client-executed tools and the two-run continuation - #435

Merged
neuromechanist merged 22 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-430-phase1-client-tools
Sep 22, 2026
Merged

neuromechanist merged 22 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-430-phase1-client-tools

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Phase 1 of the browser-execution epic: the server learns to call a tool it does not execute. The model sees one tool surface; a call to a client-executed entry ends the run instead of running anything, and the browser answers it on a second request.

Implements .context/browser-execution-tool-design.md. No community enables the feature in this PR, so nothing changes in production behavior. What ships is a complete, tested server contract plus a kill switch, so phase 2 (#431) has something real to execute against.

Transport is the decided one, two-run continuation: no interrupt(), no Command(resume=), no checkpointer. A resumed LangGraph node re-runs from its start, so any pre-interrupt side effect runs twice, and every interrupt raised in one ToolNode task shares an Interrupt.id, so two calls in one message cannot be told apart. Neither bites a continuation, because nothing is resumed. The 120-second edge timeout keeps bounding only a single streaming response and must not be raised.

Decisions worth reviewing rather than skimming

One browser call per assistant message. The router returns one destination for a whole message, so a mixed batch is resolved inside the new client_tools node: server calls run through a ToolNode over server tools only and get real results, the first client call is parked, and every further client call gets a written refusal. Every tool_use ends up with a matching tool_result, which the provider requires, and the model learns the constraint from the message rather than from a system rule it might ignore.

Images never enter stored history. A result reaches run 2 with its images attached, so the model sees the plot; what the session keeps has each image replaced by a text placeholder. One rule, three problems: session memory stays bounded, the prompt-cache prefix stays stable because bytes that are never stored cannot be re-sent, and the design note's "attach real images only for the most recent execution" falls out with no separate ageing pass.

Authorization binds to the call_id, not the session id. get_or_create_session does new_id = session_id or str(uuid.uuid4()), so a client may choose its own session id and it is a routing key rather than a credential. The call_id is the provider's own tool-call id, which a caller only learns from a tool_request on its own stream.

claim_pending_call is synchronous and must stay that way. The session store is a module-global dict with no locking anywhere. The only thing keeping check-then-clear atomic is that no await appears between them. Making it async for symmetry would reintroduce a window in which one result is accepted twice, and accepting once is the entire idempotency story for a transport with no checkpointer.

An abandoned call repairs the history. The trap the design note does not name: if a tool_request is never answered and the person just types again, the session holds an assistant message with tool_calls and no matching result, which the provider rejects outright. That does not lose one turn, it makes every later turn fail. Both the next /chat and the expiry path now append a synthetic cancelled result.

A client tool is bound only if the caller declared it. Rather than binding everything configured and then checking declarations at emit time, build_client_tools intersects configured with declared. The model cannot call what it cannot see, so "never send a tool_request the client cannot answer" is structural instead of a rule that has to hold at one more call site. /ask passes no declaration and therefore binds none, which is how it refuses client tools without a special case.

A correction this PR carries

The design note, #422, and my own first reading of the source are wrong about token counting. All three say count_tokens_approximately cannot count images, citing a repr() fallback that measures a 250 KB PNG at roughly 85,000 tokens against an 80,000 budget, and conclude this repository needs its own image-aware counter.

I read that fallback in a cached wheel and reported it as current. It is not. That wheel is 1.2.6; this project runs and locks 1.6.3, where the helper walks content blocks and charges tokens_per_image per image. Measured rather than read: a 400,008-character base64 image counts as 90 tokens, not ~100,000.

So there is no custom counter here. What is real is that pyproject.toml floored the dependency at >=1.2.0, which admits the broken version, and #374 records that CI resolves without the lockfile, so it was reachable. The fix is the floor, now >=1.6.0, plus tests/test_agents/test_image_token_budget.py pinning the behavior against a fixture larger than any figure measured in #422. The failure mode is silent context loss rather than an error, so it needs a test that fails loudly if the floor ever slips.

Edge

workers/osa-worker/index.js gains a three-segment matcher for /{community}/chat/resume, routed rate-limit-only like /feedback, because protected POSTs verify a single-use Turnstile token the widget clears after each message and the resume POST cannot carry one. Latent today because Turnstile is disabled, fatal the day it is switched on.

Resume is exempt from the hourly counter and keeps the per-minute limiter. Production is 10/minute and 20/hour per IP, and a turn with N executions costs 1 + N requests, so two executions would burn three of a user's twenty hourly budget, shared across a NAT'd lab.

This is also the repository's first worker test: there was no vitest, miniflare or unstable_dev anywhere. It follows the existing hand-rolled bun precedent from frontend/test-streaming.js and asserts against the actual regexes fetch uses, not a copy of them.

Test plan

The offline suite drives the real graph: real config and validator, real CommunityAssistant, real compiled graph, real routing, real client_tools node, real astream_events, real SSE assembly, real session store. Only the chat model stands in, plus the router's create_community_assistant, which .rules/testing_guidelines.md permits for LangGraph-shaped fixtures provided a companion nearer the wire exists.

An earlier draft replayed canned LangGraph events and was discarded: the single most load-bearing fact in this phase is that the root graph's on_chain_end carries pending_client_call, and a canned event proves nothing about that. It is now asserted against the installed langgraph, so an upstream change to the event shape fails a test rather than silently losing every browser turn.

tests/test_integration/test_client_tool_round_trip.py is the companion: it checks that a real provider accepts the message lists this phase builds, including the abandoned-call and refused-second-call repairs, and that the model actually reads a figure the browser drew.

Not run here, and stated plainly: that live tier needs ANTHROPIC_API_KEY, which is not present in this worktree, so it is marked and skipped locally and will first execute in CI's integration job.

Known, not caused here

tests/test_cli/test_main.py::TestVersionCommand::test_version_shows_version fails on a color terminal and passes in CI, because rich colorizes on a TTY. Filed as #434, not touched here; src/cli/ is unchanged by this branch.

Closes #422.
Part of epic #429.

POST /{community}/chat/resume had no matcher (three path segments vs
the two-segment ask|chat pattern) and fell through to 404. Route it
like /feedback: rate-limit-only, no Turnstile, since the resume POST
follows a client-executed tool call rather than a widget-composed
message and cannot carry a fresh single-use Turnstile token.

Also exempt it from the per-hour KV counter (checkRateLimit gains a
countHourly option) so that a turn with N browser executions costs
only its per-minute budget, not N extra hourly requests shared across
a NAT'd lab. The per-minute limiter is unaffected.

Route matchers are now exported as ROUTE_PATTERNS, and
isValidCommunityId/validateCommunityId are exported, so routing
behavior can be tested directly against the real patterns used by
fetch().
Hand-rolled bun script (matching frontend/test-streaming.js's style,
no test framework) covering: /chat/resume matches the new route and
the existing (ask|chat) route still matches unaffected; an extra
trailing segment matches neither; validateCommunityId rejects a
malformed or reserved community id on the resume path exactly as it
does on ask/chat; reserved top-level paths never match either
community route pattern. Imports and exercises the same ROUTE_PATTERNS
and validateCommunityId used by fetch(), not a parallel copy.
Wire bun workers/osa-worker/test-routing.js into the frontend-tests
job in tests.yml and test.yml, beside the existing frontend checks.
What a browser execution may send back, and what the session keeps of it.
Images ride into run 2 and never enter stored history; the text is fenced and
labeled as data because the return path is an injection channel; every field is
sized before use.

Part of #430.
count_tokens_approximately only learned to charge image blocks a per-image
penalty in 1.6. Before that any non-string content was repr()-ed whole, so one
figure measured near 100,000 tokens against an 80,000 budget and trim_messages
silently discarded the conversation. The floor admitted 1.2.0, and CI resolves
without the lockfile (#374), so this was reachable.

Corrects the claim in the design note and in #422 that this repository needs its
own image-aware counter. It does not; it needs a floor.

Part of #430.
ChatSession widens to BaseMessage, learns to adopt a graph run's final message
list whole, and holds at most one pending browser call. Claiming is synchronous
on purpose: the session store has no locking, so the only thing keeping
check-then-clear atomic is that no await appears between them.

Adds POST /{community}/chat/resume, which is run 2 of the two-run continuation.
Authorization binds to the server-generated call_id rather than the session id,
because a client may choose its own session id.

An unanswered call is closed out with a synthetic tool message before the next
turn, since an assistant message carrying tool_calls with no matching result is
rejected outright and would make every later turn fail, not just that one.

Closes #422. Part of #430.
The graph, the routing, the client_tools node, the astream_events shape, the
SSE assembly and the session store are all real; only the chat model stands in.
An earlier draft replayed canned LangGraph events and was dropped: the fact this
phase most depends on is that the root graph's on_chain_end carries
pending_client_call, and a canned event proves nothing about that.

Adds a scripted chat model helper, because every langchain-core fake raises from
bind_tools, which BaseAgent catches and then runs with no tools bound at all,
silently removing the thing under test.

Allowlists /chat/resume in the verify_api_key guard test. It genuinely spends
the credential against an LLM, which is what that allowlist is for.

Part of #430.
Asserted against a community that configures the tool AND a caller that
declared it, since that is the only case where the switch is reached. A switch
tested against a config that binds nothing would pass while doing nothing.

Part of #430.
Walks every cut point rather than one. A browser turn is four messages, so
three caps in four land where a naive cut is already safe; the first version of
this test picked such a cap and passed while measuring nothing. A companion
assertion confirms the hazard is real at some of the same points, so the two
together say the function both acts and is needed.

Verified by mutation: replacing the boundary search with a naive cut fails two
of these tests.

Part of #430.
ClientToolConfig, RuntimeLimits, PythonRuntimeConfig, RuntimeConfig;
ExtensionsConfig.client_tools and CommunityConfig.runtime, plus a
cross-field validator requiring a matching runtime section. limits
defaults to RuntimeLimits() so a community need not spell out {}.
ClientTool (BaseTool subclass whose _run/_arun always raise),
client_tools_disabled kill switch, and build_client_tools, which binds
only the intersection of configured and caller-declared tool names.
BaseAgentState gains pending_client_call. BaseAgent takes
client_tool_names (derived from tools if omitted); _should_use_tools
adds a client_tools destination for any batch touching a client tool.
build_graph adds the client_tools node/edge-to-END only when needed,
so a community with none keeps the pre-existing graph unchanged.
The node runs server calls through a lazily-built ToolNode, parks the
first client call as pending_client_call with the provider's own
tool_call id, and rejects further client calls and unknown names with
an error ToolMessage.
count_tokens_approximately defaults tokens_per_image to 85, which is OpenAI's
low-resolution cost. Anthropic bills roughly width*height/750 and caps near
1600, so the default under-counts a real plot by more than an order of
magnitude. Under-counting is the direction that fails: it means believing a
conversation fits when it does not.

Introduces count_conversation_tokens so the agent's budget check, its trimmer,
its post-trim log and the API's warning threshold cannot drift apart by one of
them forgetting the rate.

Part of #430.
Silent failures:
- A dropped root on_chain_end ended the turn as an ordinary empty done,
  dropping the model's request to run code platform-wide with nothing to alert
  on. The node's own event is now independent evidence a call was parked, and a
  disagreement between the two is a loud error carrying an id.
- from_state now requires every key. A renamed one parked a call with EMPTY
  args: no exception, no log, no failing test.
- _finish_with_tool_request validated after mutating, so a malformed payload
  left a session permanently unanswerable. It validates first now.
- claim_pending_call and the kill switch logged nothing. An operator flipping
  OSA_CLIENT_TOOLS_DISABLED had no server-side proof it took effect, and browser
  call timeouts were unmeasurable.

Correctness:
- set_pending_call refuses to silently replace an unanswered call.
- The tools node is built from server tools only, so a ClientTool is
  structurally unreachable rather than relying on langgraph's default handler.
- Resume metrics were recorded as /chat, folding the half that actually spends
  the credential into run 1's numbers.
- artifacts are bounded per item, not only in count.

Adds HTTP-level tests for /chat/resume, which had none. That gap let a real bug
through during this very change: the handler passed an argument the streaming
function did not accept, and the whole suite stayed green.

Part of #430.
Every invoke sent an unbound model a message list containing tool_use/
tool_result blocks. Follows the proven pattern in
test_anthropic_platform.py: declare a matching tool, bind it, invoke
the bound model everywhere. Cannot run locally (no ANTHROPIC_API_KEY);
confirmed it still imports and collects.
The three tests built a dict literal annotated : BaseAgentState and
asserted on exactly what they wrote; TypedDict enforces nothing at
runtime, so deleting the field would not have failed any of them.
Replaced with introspection of __annotations__/__optional_keys__/
__required_keys__ against BaseAgentState and PendingClientCallPayload,
mirroring test_tool_results.py's technique for the reader's side.
Verified by deleting the field and confirming 3 of 5 tests fail, then
restoring.
pytest.raises(Exception, match=...) would also pass if a missing field
became a mere warning. ExecuteCodeArgs is a pydantic BaseModel, so
narrow to pydantic.ValidationError, matching every other test in the
file.
Every existing case in TestShouldUseTools either binds no client tool
at all (client_tool_names empty, so the & check in
BaseAgent._should_use_tools is never reached) or already includes a
client call (where & and | agree). Add the one case that
distinguishes them: an agent with both a server and a client tool
bound, given a server-only batch, must route to "tools". Verified by
mutating & to | in src/agents/base.py: only this new test fails (19
others still pass), then reverted.
AskRequest has no client_tools field and neither ask() branch passes
declared_client_tools to create_community_assistant, so it defaults to
None; nothing pinned this, and a copy-paste from ChatRequest would
silently violate it. Asserts on real behavior: the field is absent
from AskRequest.model_fields (and a passed value is dropped, not
rejected -- AskRequest is extra="ignore" by default, not
extra="forbid" as initially assumed), and a CommunityAssistant built
the way ask() builds one, against a config with a client tool
configured, binds none of it (checked via the model's own recorded
bound_tool_names).
test-routing.js only exercised ROUTE_PATTERNS regexes directly, so wiring
bugs in the fetch() dispatcher and options bugs in the rate-limit calls
were invisible. Add dispatch-level tests that call the real, exported
fetch() handler with a stub env (KV, per-minute limiter, and outbound
fetch stand-ins), and assert on response status/body:

- /chat/resume never requires or verifies a Turnstile token; /chat does.
- /chat/resume is exempt from the /chat hourly KV counter; /chat is not.
- the per-minute limiter is still consulted for resume, and its rejection
  still yields a 429.

Confirmed each new assertion can fail: deleting the countHourly:false
option from handleChatResume's rateLimitOrReject call, and wiring the
resume route to handleProtectedEndpoint instead of handleChatResume, each
independently turn tests red.
/chat/resume is exempt from the /chat hourly counter because one turn
with N tool executions costs 1 + N requests. But a resume can itself end
in another tool_request, so nothing bounded how many times that repeats:
an hourly-counted /chat call could chain resume calls up to the
per-minute limiter's ceiling alone (10/min * 60 = 600/hour in production,
~30x the 20/hour /chat budget), and the tool's stdout is an explicit
injection channel that could drive such a chain without the user's
cooperation.

Add a separate per-IP KV counter for resume calls (RESUME_LIMIT_PER_HOUR:
100/hour prod, 500/hour dev -- 5x the /chat hourly cap, generous for a
legitimate multi-step analysis while capping the worst-case amplification
at 5x instead of ~30x). Exceeding it 429s with a reason distinct from the
/chat hourly rejection. Document the new budget in handleRoot and README.
Review findings addressed:
- LRU eviction spared a session waiting on a browser call unless every session
  is waiting. A person reading code before approving it does not touch
  last_active, so that session was exactly the one a naive rule evicted first,
  and their resume then 404s with the running work gone.
- Overlapping turns on one session silently discarded each other: both copy the
  message list and write the whole thing back, so the later one wins. Refused
  now, with a self-healing claim so a dropped connection cannot wedge a session.
- A client tool sharing a name with a server tool would drop the server tool
  from the node that executes it and park its calls for a browser with no
  executor, hanging the turn. Refused at construction.
- Client tool calls never reached tools_called, so per-tool usage metrics would
  have read zero for browser execution forever.
- RuntimeLimits is now bounded by the server's own caps, so a community cannot
  declare a limit the server is guaranteed to reject with a 422.
- The runtime check is a mapping rather than a chain with no else, so adding a
  runtime and forgetting a branch is a KeyError at config load, not a tool that
  binds and can never be answered.

Corrections to earlier claims in this branch:
- The image-counting fix landed in langchain-core 1.2.8, not 1.6. Bisected
  release by release. The 1.6.0 floor stays as a margin, and now says so.
- tool_results' docstring said the browser enforces its own copy of the caps.
  No such client exists yet; that is phase 2.
- ANTHROPIC_TOKENS_PER_IMAGE is right for the offered models, which are all
  standard tier. Noted that a higher-resolution tier would undercount by ~3x.

Moves the shared caps into src/core/limits.py, which imports nothing. Reaching
into src.api.tool_results from the config module pulled langchain-core into
every CLI import and broke the "works without the server extra" contract that
tests/test_cli/test_validate.py pins. Measured after the move: importing the
config module now pulls in zero langchain modules.

Part of #430.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round: what changed, and the two things the review got right that I had wrong

Five reviewers ran over this branch (code, tests, silent failures, comments, type design). Every finding is addressed; nothing is deferred except one item explicitly tracked for phase 2, named at the bottom. The branch grew from 13 commits to 22.

The findings that mattered most

A dropped langgraph event would have silently killed the feature platform-wide. The run recovers the parked browser call from the root graph's on_chain_end. If an upgrade ever changes that event's shape, final_state stays None, the turn falls through to the ordinary path, the model's tool-calling message carries no text so nothing is persisted, and the client receives a perfectly normal done. The model's request to run code would be dropped forever with every metric green. The node's own event is now independent evidence a call was parked, and a disagreement between the two is a loud error with an id. Tested by dropping the root event exactly as an upstream change would.

/chat/resume had no HTTP-level tests at all. Every "resume" test called _stream_chat_response or ChatSession directly, one layer below the endpoint. That gap let a real bug through during this very review round: I added an argument at the call site and not to the function, and the entire suite stayed green. There are now 11 tests driving the real ASGI app, and they catch that exact mutation.

Overlapping turns silently discarded each other. Two turns on one session each copy the message list, run, and write the whole list back; the later one wins and the earlier one's messages and parked call vanish with no error. Refused now, with a self-healing claim so a dropped connection cannot wedge a conversation until its 24-hour TTL.

LRU eviction preferred exactly the wrong session. A person reading code before approving it does not touch last_active, so the session waiting on them was the first one evicted, and their resume then 404s with the running work gone. Idle sessions are evicted first; parked ones only when every session is parked.

Unbounded resume chains skipped the hourly rate limit indefinitely. The hourly exemption is sound within one turn, but run 2 can itself end in another tool_request whose resume is also exempt, and so on. That is roughly a 30x amplification over the intended budget, drivable by a prompt injection through the tool's own stdout. Bounded by a separate resume-chain budget.

Also fixed: set_pending_call could silently clobber an unanswered call; from_state accepted partial payloads, so a renamed key parked a call with EMPTY arguments with no error anywhere; _finish_with_tool_request mutated the session before validating, leaving a malformed payload to make a session permanently unanswerable; the tools node was built over every tool rather than server tools only; resume metrics were recorded as /chat, folding the half that actually spends the credential into run 1's numbers; artifacts was bounded in count but not per item; a client tool could shadow a server tool and hang the turn; client tool calls never reached tools_called; RuntimeLimits could declare a limit the server is guaranteed to reject; the runtime check was a chain with no else.

Two corrections to my own claims

The langchain-core floor rationale was wrong. This PR originally said image-aware token counting landed in 1.6, which I inferred from two endpoints without bisecting. A reviewer bisected release by release: 1.2.6 and 1.2.7 have the repr() fallback, and 1.2.8 onward has tokens_per_image. The >=1.6.0 floor stays, as a deliberate margin rather than the boundary, and now says so in both places it is stated. Note this is a correction to a correction: the original claim in the design note and #422 was still wrong for the version this project runs.

tool_results' docstring described phase 2 as already existing, saying the browser enforces its own copy of the caps. No such client exists. Reworded.

A regression this round introduced and caught

Bounding RuntimeLimits by the server's caps meant importing them from src/api/tool_results.py, which imports langchain-core, which made src.core.config require it too. That breaks the "CLI validates configs without the server extra" contract that tests/test_cli/test_validate.py pins. The caps now live in src/core/limits.py, which imports nothing. Measured after the move: importing the config module pulls in zero langchain modules.

Tracked for phase 2, not done here

ClientToolResult.is_error collapses error, timeout, denied, cancelled and oom into a boolean. The distinction is real (an out-of-memory abort is not a raised exception, and no seconds-based deadline catches it) but nothing branches on it yet, and retry and permission behavior are phase 2's (#431). Flagged so it is not inherited as settled.

Also verified, so nobody re-checks

claim_pending_call's atomicity argument holds: no await between check and clear, single process, no workers=. Authorization binding to call_id rather than the caller-choosable session_id is sound. It is structurally impossible to emit a tool_request for an undeclared tool, because such a tool is never bound. No em-dashes, no British spellings, no AI co-author attribution in any of the 22 commits.

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.

1 participant