aft icon indicating copy to clipboard operation
aft copied to clipboard

OpenCode 2: the plugin converts each tool's input schema to JSON Schema again for each Location and each read

Open iceteaSA opened this issue 5 days ago • 0 comments

What occurs

On OpenCode 2, the plugin converts the input schema of each tool to JSON Schema many times. The plugin does this work again for each project directory (Location) that the server opens, on the main thread of the server.

projectV2Tool in packages/opencode-plugin/src/tools/definitions/v2.ts builds a new Zod object and runs assertV2Contract (one full toJSONSchema) at projection time. It does the same work again on each read of input. The ~standard.jsonSchema functions on that object then convert the same schema again for each host call.

Measurement

Test setup: OpenCode 2.4.2, one server with 20 Locations, no prompts, plugin @cortexkit/aft-opencode 0.68.0. We changed only the package path of this plugin, which makes the host reload it, and recorded a CPU profile of the main thread.

Build Plugin main-thread CPU for each reload For each Location
Published 0.68.0 1.317 s 65.8 ms
Local build of v0.68.0, no change 1.386 s 69.3 ms
Local build of v0.68.0 with the cache below 0.400 s 20.0 ms

Before the change, JSON Schema conversion was 76% to 82% of the plugin's samples. Zod emit was the heaviest frame. With the change, all converter frames together fell from 998 ms to 89 ms in the 20 Locations.

In a unit test with one args map and 20 projected Locations, the current code does 62 conversions. With the cache, it does 1 conversion.

Proposed change

Keep one projected input for each (tool name, args map) in a module-level WeakMap, and use it for each Location and each read of input:

  • Run the V2 contract check one time for each build, and use its JSON for host input calls. Make the output schema one time, at the first host call for it.
  • Give each host call its own copy (structuredClone), as Zod does.
  • Make a new build when a caller replaces the args map or one of its entries. Live schema updates, which #1144 keeps, continue to work.

The JSON Schema output does not change. The tool factories make a new args map for each Location, so the first conversion in each Location stays. The cache removes the conversions that occur again after the first.

I have a branch with this change and a regression test. I can open it as a draft pull request that refers to this issue.

iceteaSA avatar Nov 29 '26 05:11 iceteaSA