Skip to content

🚥 feat: Inspect Selected Tool Results Before Use - #719

Merged
danny-avila merged 3 commits into
mainfrom
danny-avila/tool-result-protection
Nov 23, 2026
Merged

danny-avila merged 3 commits into
mainfrom
danny-avila/tool-result-protection

Conversation

@danny-avila

Copy link
Copy Markdown
Collaborator

Summary

Adds default-off RunConfig.toolResultProtection. A host names the tools whose output must be inspected; for those tools the SDK replaces the text the tool returned with the text the host's inspect returned before anything else reads it. A failed inspection ends the run with a coded ToolResultProtectionError.

Supersedes #597, which implemented the same public option. That branch treated code in the host process as hostile and grew to 12k lines without converging. With its policy on, a follow-up turn failed once history held a protected result, unselected tools were rejected for returning non-plain artifacts, and every model call revalidated the whole history. This PR keeps the option's shape and starts from a written trust boundary instead.

Contract

Guaranteed. For a selected tool, post-tool hooks, the error handler, run-step completion events, the output reference registry, checkpoints and every later model request receive the inspected text. This holds for in-process tools, tools the host runs through ON_TOOL_EXECUTE, error text from either, and the same tools inside subagents.

Trust boundary. The tool's text is untrusted data. Code running in the host process is trusted: tools, hooks, handlers, callbacks and checkpoint savers are not defended against, and text they author is not inspected. History the host supplies is not inspected; the host only ever received inspected text for selected tools.

Limits, all explicit.

  • A selected tool must return plain text. Structured content, an artifact or a Command ends the run as unsupported.
  • Selected tools are listed as disallowed for programmatic tool calling, are never started eagerly, and skip the per-call early completion path.
  • A selected tool cannot be client delegated, and remote SDK runs reject a policy. Both fail at Run.create.
  • Tracing callbacks on an in-process tool still observe its raw return; trace redaction is the existing tool-output tracing configuration.
  • Unselected tools are untouched, whatever they return.

docs/tool-result-protection.md carries the same contract for hosts.

Mechanism

ToolNode
├─ runTool (in-process)
│  ├─ tool returned ──► inspectToolOutput ──► compaction, registry, hooks, completion
│  └─ tool threw ─────► inspectToolText ────► error handler, error ToolMessage
├─ dispatchToolEvents (host-executed)
│  ├─ onResult early completion: skipped for selected calls
│  └─ results settled ► inspectToolExecuteResult ► hooks, registry, completion, ToolMessage
└─ getProgrammaticTools: selected tools moved to disallowedToolDefs
stream.ts isEagerExecutionExcludedTool: selected tools never prestart

Inspection reuses ProviderTextAttempt for the timeout, abort handling and the byte budget, which is shared per policy object across every graph of a run. Inspector exceptions surface as unavailable; their message is never forwarded.

src/protection/toolResult.ts   new, 272 lines: policy type, gate, three inspect functions
src/tools/ToolNode.ts          four call sites and two helpers
src/stream.ts                  eager exclusion
src/graphs/Graph.ts, run.ts,   option plumbing, mirrored on providerTextProtection
  SubagentExecutor.ts, types
src/runtime/client.ts          remote runs reject the policy

With no policy, every added branch is skipped; no existing statement changes behaviour.

The first commit is commit-hook formatting of three existing files and changes no logic. Review the second commit for the change.

Verification

Check Result
New unit tests, src/protection/toolResult.test.ts 34 passed
New end-to-end tests, ToolNode.toolResultProtection.test.ts 24 passed
Added cases in stream.eagerEventExecution and ToolNode.lazyCodeFiles passed
Full npx jest 371 suites passed; the 3 llm.spec.ts live-provider suites fail without API keys and are excluded from the CI unit shards
npx tsc --noEmit, npm run build:types passed
npx eslint "src/**/*.ts" 0 errors
check:circular-deps, test:light-entries passed

Each call site was disabled in turn and a test failed for it: in-process output, in-process error, host results, early completion, programmatic exclusion, eager exclusion, client delegation, subagent inheritance, and code-session retention on failure.

Not run: live provider integrations, a packed-package consumer install, and any LibreChat integration. No host adopts the option yet.

Related to AI-2213.

Commit-hook output only (sort-imports, prettier, eslint --fix) for three
existing files the next commit edits, kept separate so that commit shows
only the change.
Adds default-off RunConfig.toolResultProtection. For the tools a host policy
names, the text a tool returns is replaced by the host inspector's text before
hooks, the error handler, completion events, the output reference registry,
checkpoints or the model read it. A failed inspection ends the run with a coded
ToolResultProtectionError.

Covers in-process tools, host-executed tools, error text and subagents.
Selected tools are kept out of eager start, per-call early completion and
programmatic tool calling; client delegation and remote SDK runs reject the
policy. Unselected tools are untouched.

Host process code is trusted: text authored by hooks or handlers and history
the host supplies are not inspected.

Supersedes #597.
@danny-avila
danny-avila marked this pull request as ready for review November 20, 2026 03:13
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review the latest head, final review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T13:51:18.571298Z 1191d80 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f64587dbc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/tools/ToolNode.ts Outdated
Comment on lines +2246 to +2249
const gate = this.protectedResultGate(call.name);
if (gate != null) {
e = new Error(
await inspectToolText(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Inspect selected tool errors before the fail-fast rethrow

When an exported ToolNode is configured with both toolResultProtection and handleToolErrors: false, a selected tool that throws bypasses this inspection entirely: the earlier if (!this.handleToolErrors) rethrows its original error first. Consequently, uninspected error text escapes through the node's rejection and enclosing runnable callbacks, despite the policy's guarantee that selected tool errors are inspected before SDK consumption. Sanitize selected tool failures before that early rethrow while preserving the requested fail-fast behavior.

Useful? React with 👍 / 👎.

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.

Valid, fixed in 1191d80.

A ToolNode built with handleToolErrors: false rethrew a protected tool's failure before the inspection ran. The catch block now inspects first, for both the fail-fast rethrow and the error-message path, so the rethrown error is a plain Error carrying the inspected message (no original type or stack). Interrupts and run safety aborts (StreamLimitExceededError, PreparedSubagentError, ProviderTextProtectionError) still pass through untouched, and an unselected tool's error is rethrown as the same object.

Tests in ToolNode.toolResultProtection.test.ts: "inspects a selected tool error before a fail-fast rethrow" (fails with the rethrow reverted to the original error) and "rethrows an unselected tool error unchanged in fail-fast mode".

Comment thread src/stream.ts
Comment on lines +199 to +201
if (graph.toolResultProtection?.toolNames.includes(name) === true) {
return true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply the protection exclusion to eager subagents too

When eager subagent execution is enabled and toolNames includes subagent, this exclusion does not prevent that selected tool from starting speculatively. The separate startPreparedSubagents() path calls Graph.prestartSubagent() and then ToolNode.prestartSubagent(), neither of which checks the protection policy. Besides violating the documented guarantee that selected tools never start eagerly, this means a subsequently revised or discarded call triggers the fatal PreparedSubagentError in PreparedSubagents.finish() instead of remaining on the committed execution path. Apply the protected-tool exclusion to the prepared-subagent path as well.

Useful? React with 👍 / 👎.

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.

Accepted, fixed in 1191d80, with one correction to the premise.

No raw text was published by this path: a prestarted subagent's output is only read through preparedSubagents.take() in runTool, which is where the inspection sits, so the result was inspected either way. The PreparedSubagentError on a revised call is existing prestart behaviour and not specific to protection.

The documented rule should still hold without an exception, so ToolNode.prestartSubagent now returns early for a protected tool, next to the existing excludeToolNames check. The call then runs on the committed path like every other protected tool.

Test in ToolNode.preparedSubagents.test.ts: "leaves a subagent tool with protected results on the normal path" (fails without the check: the child starts before the batch).

… Prestart

A ToolNode built with handleToolErrors false rethrew a protected tool's
failure before it was inspected. The failure is now inspected first, for both
the rethrow and the error-message path; interrupts and run safety aborts
still pass through untouched.

A protected subagent tool could still be started ahead of its batch by
prestartSubagent. It now stays on the committed path like every other
protected tool.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review 1191d80

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 1191d80bb1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danny-avila
danny-avila merged commit 11405f0 into main Nov 23, 2026
13 checks passed
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