Skip to content

refactor(ai): one canonical tool path, mapped to wire names per request - #65739

Open
rekram1-node wants to merge 3 commits into
devfrom
tool-paths
Open

rekram1-node wants to merge 3 commits into
devfrom
tool-paths

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Issue for this PR

No issue. Follows #65292 and #65726.

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

A tool in a group (crm → lookup) used to have three unconnected names. Requests flattened it to crm_lookup on every protocol except OpenAI Responses, nothing mapped the model's crm_lookup call back, and a runtime tool({ name: "crm.lookup" }) was sent literally, which OpenAI and Anthropic reject with a 400. On OpenAI Chat a grouped tool never ran:

 tools: [{ type: "namespace", name: "crm", tools: [lookup] }]   // runtime tool({ name: "crm.lookup" })
 model calls "crm_lookup"
-tool result: No tool named "crm_lookup" is currently available
+tool runs; call and result are { namespace: "crm", name: "lookup" }

Now public inputs and outputs only use canonical tool paths, and provider names exist only inside one compiled request:

compile(request):                       // route/client.ts, shared by steps, /compact and trigger compaction
  plan tool updates, project schemas, apply cache policy   (canonical)
  ToolNames.lower(request)                                 (tool-names.ts)
    table: path "crm.deals.get" -> wire name
      native namespaces (route.namespaces, OpenAI Responses): { namespace: "crm", name: "deals_get" }
      everything else:                                        { name: "crm_deals_get" }
      two paths -> same wire name: InvalidRequest error (was: last one silently won)
    encode tools, Message.tools changes, past calls/results and toolChoice through the table
      old history with "crm_lookup": mapped through the table
      undeclared names ("a.b.c"): provider-safe "a_b_c", history keeps "a.b.c"
  protocol.body.from(lowered)            // protocols only ever see wire names
stream: every tool event decoded wire -> canonical; unknown names kept as received

Protocol.make no longer wraps body.from with flattenRequest, so the xAI compaction special case is gone and OpenAI trigger compaction (whose internal protocol didn't forward namespaces) now sends the same names as its steps.

OpenAI Responses rejects a forced tool_choice for a tool inside a namespace (checked live: crm.lookup, lookup, namespace field and allowed_tools all 400), so a request that forces a grouped tool sends flat names for that one request. The table decodes them back, so callers still see crm.lookup.

Breaking changes (@opencode/ai) and migration

-tool({ name: "crm.lookup", ... })                     // sent literally, 400 on OpenAI/Anthropic
+namespace("crm", { description: "CRM tools" }, [tool({ name: "lookup", ... })])
-ToolDefinition.make({ name: "a.b" })                  // accepted
+throws: Invalid tool name "a.b": use letters, digits, "_" or "-", and group tools with a namespace ...
-ProviderShared.flattenRequest(request), flattenToolRequest(request)
+ToolNames.lower(request)  // Result<{ request, names }>, from @opencode/ai/route
-Message.tools({ remove: ["crm"] })                    // top-level names only
+Message.tools({ remove: ["crm.lookup"] })             // paths; "crm" still removes the whole group
-tool-call events on Chat/Anthropic/...: { name: "crm_lookup" }
+every provider: { namespace: "crm", name: "lookup" }   // ToolCallPart.path(part) === "crm.lookup"
  • Tool and namespace names are one segment (`^[a-zA-Z0-9_-]+### Issue for this PR

No issue. Follows #65292 and #65726.

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

A tool in a group (crm → lookup) used to have three unconnected names. Requests flattened it to crm_lookup on every protocol except OpenAI Responses, nothing mapped the model's crm_lookup call back, and a runtime tool({ name: "crm.lookup" }) was sent literally, which OpenAI and Anthropic reject with a 400. On OpenAI Chat a grouped tool never ran:

 tools: [{ type: "namespace", name: "crm", tools: [lookup] }]   // runtime tool({ name: "crm.lookup" })
 model calls "crm_lookup"
-tool result: No tool named "crm_lookup" is currently available
+tool runs; call and result are { namespace: "crm", name: "lookup" }

Now public inputs and outputs only use canonical tool paths, and provider names exist only inside one compiled request:

compile(request):                       // route/client.ts, shared by steps, /compact and trigger compaction
  plan tool updates, project schemas, apply cache policy   (canonical)
  ToolNames.lower(request)                                 (tool-names.ts)
    table: path "crm.deals.get" -> wire name
      native namespaces (route.namespaces, OpenAI Responses): { namespace: "crm", name: "deals_get" }
      everything else:                                        { name: "crm_deals_get" }
      two paths -> same wire name: InvalidRequest error (was: last one silently won)
    encode tools, Message.tools changes, past calls/results and toolChoice through the table
      old history with "crm_lookup": mapped through the table
      undeclared names ("a.b.c"): provider-safe "a_b_c", history keeps "a.b.c"
  protocol.body.from(lowered)            // protocols only ever see wire names
stream: every tool event decoded wire -> canonical; unknown names kept as received

Protocol.make no longer wraps body.from with flattenRequest, so the xAI compaction special case is gone and OpenAI trigger compaction (whose internal protocol didn't forward namespaces) now sends the same names as its steps.

OpenAI Responses rejects a forced tool_choice for a tool inside a namespace (checked live: crm.lookup, lookup, namespace field and allowed_tools all 400), so a request that forces a grouped tool sends flat names for that one request. The table decodes them back, so callers still see crm.lookup.

Breaking changes (@opencode/ai) and migration

-tool({ name: "crm.lookup", ... })                     // sent literally, 400 on OpenAI/Anthropic
+namespace("crm", { description: "CRM tools" }, [tool({ name: "lookup", ... })])
-ToolDefinition.make({ name: "a.b" })                  // accepted
+throws: Invalid tool name "a.b": use letters, digits, "_" or "-", and group tools with a namespace ...
-ProviderShared.flattenRequest(request), flattenToolRequest(request)
+ToolNames.lower(request)  // Result<{ request, names }>, from @opencode/ai/route
-Message.tools({ remove: ["crm"] })                    // top-level names only
+Message.tools({ remove: ["crm.lookup"] })             // paths; "crm" still removes the whole group
-tool-call events on Chat/Anthropic/...: { name: "crm_lookup" }
+every provider: { namespace: "crm", name: "lookup" }   // ToolCallPart.path(part) === "crm.lookup"
  • Tool and namespace names are one segment ; length limits differ by provider and are left to them, so names OpenCode accepts today still work). Nest with namespace(...) (runtime tools, dispatched by ai.loop) or ToolNamespace (definitions).
  • toolChoice takes a path ("crm.lookup") or the tool/definition; an object matching two grouped tools fails and asks for the path.
  • Protocol.namespaces is now read by the request compiler rather than Protocol.make. A protocol's body.from called directly no longer flattens; go through the client or ToolNames.lower first.

OpenCode core

Core flattens MCP/plugin tools itself and never declares groups, so its requests don't change. aisdk.ts calls ToolNames.lower in place of flattenRequest. I compiled one request with flat tools (a duplicate name, a tool update with a removal, a call to a withdrawn tool, with and without a forced choice) on OpenAI Chat, OpenAI Responses, Anthropic, Bedrock, Gemini and xAI on dev and on this branch: the 12 bodies are byte-identical.

One wire difference: on OpenAI Responses, a replayed call to an undeclared dotted name (a Code Mode path like a.b.c) now goes out as a_b_c, as it already did on every other protocol. Responses accepts both (checked live), so it costs at most one prompt-cache miss for such histories.

How did you verify your code works?

  • packages/ai: bun typecheck; bun test 2300 pass, 0 fail. New test/tool-names.test.ts (13 tests): round trip on Chat and Responses, nested crm.deals.get on both, collision error, Responses ↔ Chat replay, undeclared a.b.c on Chat and Bedrock, old crm_lookup histories, toolChoice by path/object/ambiguous, Message.tools removal by path, and /responses/compact (OpenAI, xAI) and trigger compaction using the step names. Run against dev, the 9 new-behavior tests fail; the 4 that guard kept behavior (undeclared names, compaction names) pass there too.
  • packages/core: bun typecheck; aisdk, provider, model-resolver, session-runner*, plugin, tool*, codemode, generate and session tests: 2316 pass, 2 fail. The 2 (ShellTool conditional process substitution) fail the same way on dev.
  • bun run check at the root passes.
  • Live, through the package with ai.loop and a crm group holding lookup and a nested deals.get, prompted and forced (toolChoice: "crm.lookup"): OpenAI Chat gpt-4.1-mini, OpenAI Responses gpt-5.4-mini, Anthropic claude-haiku-4-5. All 6 runs called crm.lookup and crm.deals.get, ran the tools and finished with stop after the follow-up request.

Review carefully: packages/ai/src/tool-names.ts (the table and encode/decode) and the path-aware foldTools/planToolUpdates in packages/ai/src/tool-updates.ts.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Added by the opencode bot (AI-generated).

Public API: @opencode/ai: tool/namespace names restricted to one segment (dotted names now throw), removes ProviderShared.flattenRequest/flattenToolRequest, adds ToolNames.lower, namespace(), ToolCallPart.path; tool events use canonical { namespace, name } (breaking)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fix works. On the base I reproduced the OpenAI Chat failure: crm.lookup is sent as is, and the model's crm_lookup call fails with No tool named "crm_lookup". With this PR, test/tool-names.test.ts covers that flow and passes. The full packages/ai suite passes (2300 tests), the core aisdk tests pass, and tsc passes in packages/ai and packages/core. Core's request path doesn't change: core already checks tool names against the same character set before building definitions.

Public API (@opencode/ai), not backwards compatible for callers that rely on dotted names or flattened names:

  • ToolDefinition / ToolDefinition.make, ToolNamespace.make and tool(...) now throw unless the name matches ^[a-zA-Z0-9_-]{1,128}$. Before, dotted names were accepted and very long names were not rejected; callers must group tools with namespace(...) / ToolNamespace instead.
  • Removed ProviderShared.flattenRequest and ProviderShared.flattenToolRequest. Added ToolNames.lower (from @opencode/ai/route).
  • Added namespace(...), the ToolGroup type, ToolCallPart.path and Route.namespaces. ai.loop and tools accept groups.
  • Message.tools({ remove }) takes paths now, and toolChoice takes a path or a tool(...).
  • Tool events on non-Responses protocols now report { namespace, name } instead of crm_lookup.
  • Protocol.make no longer flattens, so a protocol's body.from called directly gets unflattened requests.

One concern, inline: removing a namespace's last tool by path leaves an empty namespace, and OpenAI Responses still sends it.

Comment thread packages/ai/src/tool-updates.ts Outdated
path.startsWith(`${tool.name}.`) ? [path.slice(tool.name.length + 1)] : [],
)
if (inner.length === 0 || tool.type !== "namespace" || tool.tools === undefined) return [tool]
return [{ ...tool, tools: removePaths(tool.tools, inner) }]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When the paths remove every member of a namespace, this keeps the namespace with tools: []. I tried a namespace crm holding only lookup, then Message.tools({ remove: ["crm.lookup"] }). On OpenAI Responses the compiled body sends { type: "namespace", name: "crm", tools: [] }, while flat protocols just drop it. I couldn't check live whether Responses accepts an empty namespace, but it looks like a likely 400. Consider dropping a namespace that is left empty, the same as removing crm. That also makes withdrawnTools and the remove list match what's sent.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The empty-namespace point is fixed: removing a namespace's last tool now drops the namespace, and the new test covers it on OpenAI Responses. Dropping the 128-character limit matches core, which also checks only the characters in tool names. In packages/ai, bun test and typecheck:tsc pass. The public API impact is the same as in my earlier review, except that tool names no longer have a length limit (letters, digits, _ or - only). No new concerns.

This branch has not been deployed

No deployments
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