dsh-tool-repair is a native Cordis plugin and DSH bundle for provider outputs that almost form a valid tool call. It wraps the provider-neutral llm/stream waterfall, inspects finalized tool-call blocks against the exact schemas sent in that request, and commits a repair only when DSH's authoritative JSON Schema validator accepts the result.
The plugin is an external companion rather than one of the Harness monorepo's packages. The official DSH application pins the version it tests and layers the bundle into its shipped Web and Headless profiles, while this repository keeps its own release and maintenance cycle.
Why repair at this point?
flowchart LR
Model[Model / gateway] --> Stream[DSH llm/stream]
Stream --> Check{Exact request schema}
Check -->|valid| Same[Byte-for-byte passthrough]
Check -->|recoverable| Repair[Deterministic repair]
Repair --> Recheck{Revalidate}
Recheck -->|valid| Log[assistant/message + tool/call]
Recheck -->|invalid| Reject[Fail closed]
Log --> Runtime[DSH ToolRuntime]
Runtime --> Policy[Policy + tool body]
Repairing after ToolRuntime starts would let the durable assistant message disagree with what executed. Repairing before the provider finishes would guess from partial JSON. The finalized block-end is the first point that has the complete call, the request's schema snapshot, and time to replace provider replay metadata before the agent loop logs the message.
What it repairs
| Input problem | Behavior |
|---|
| Valid arguments | Returned byte-for-byte unchanged. |
| Balanced malformed JSON | Repaired through jsonrepair, then schema-validated. |
GLM <arg_key> / <arg_value> wrappers at key or value boundaries | Stripped only for configured provider/model routes and only when the result validates. |
| Complete GLM key/value argument pairs | Decoded when every key/value tag is complete and the remaining envelope names the same tool. |
Optional property sent as null | Removed when the property is not required and its schema rejects null. |
| Array/object sent as a JSON string | Parsed when the property schema accepts the parsed collection. |
| Known alternate field name | Renamed only through an explicit per-tool alias map and only to a property in the live schema. |
What it refuses to guess
- Missing required operational values are never invented.
- Unknown fields are never dropped to force validation.
- Field names are never fuzzy-matched.
- Truncated strings, objects, arrays, programs, commands, and file contents are never auto-closed.
- A grammar marker in the middle of a value is not cut out. For a configured route, a residual marker is handed to a monotonic ToolRuntime guard and denied before the tool body.
- Key collisions reject the candidate rather than choosing a winner.
- Complete tool grammars leaked as ordinary assistant prose are not converted into tool calls. This package repairs finalized tool-call arguments, not free text.
These rules matter most for mutating tools: schema validity cannot prove that an auto-completed file body or command contains the model's full intent.
Install
Requirements: Node.js ^22.19.0 || >=24, pnpm 11 for this checkout, DeepSeek Harness ^0.1.0-rc.7, and Cordis ^4.0.1.
The package is included in the tested DSH distribution. For another profile or checkout:
# Registry install into one profile
pnpm dlx @monotykamary/dsh@0.1.0 plugin --profile web add dsh-tool-repair
# Local development checkout
pnpm install
pnpm run install:local
The local installer builds the package, records any dependency it replaces, links this checkout through the DSH plugin command, and verifies one active dsh-tool-repair row. It never starts or restarts DSH. Reload the selected profile after installation.
Other profiles, homes, and uninstall
pnpm run install:local -- --profile headless
DSH_HOME=/path/to/home pnpm run install:local -- --profile web
pnpm run install:local -- --skip-build
pnpm run uninstall:local -- --profile web
The uninstaller removes only a local link proven to belong to this checkout and restores the exact previous dependency specification.
Configuration
The bundle inserts one row with id dsh-tool-repair. A later profile patch can replace its config:
- id: dsh-tool-repair
config:
grammarLeakModels:
- glm
repairJsonSyntax: true
dropOptionalNulls: true
parseStringifiedCollections: true
aliases:
read:
path: [file_path, filePath]
debug: false
| Key | Bundle value | Meaning |
|---|
grammarLeakModels | [glm] | Case-insensitive substrings matched against provider/model; only matching routes receive grammar-token handling. |
repairJsonSyntax | true | Permit jsonrepair only after the input passes the balanced-container check. |
dropOptionalNulls | true | Treat schema-invalid null optional properties as omitted. |
parseStringifiedCollections | true | Parse embedded JSON only where the property requires an array or object. |
aliases | {} | Explicit tool → canonical field → aliases[] map. No aliases are implicit. |
debug | false | Log tool identity, status, rule names, and bounded diagnostics; arguments are never logged. |
An empty grammarLeakModels list disables marker-specific mutation while leaving schema-guided JSON and collection repairs active. Unknown config keys fail plugin loading.
Repair lifecycle
- Snapshot tool schemas from the immutable
GenerateOptions request.
- Let the configured adapter produce its stream by calling
next().
- Strictly parse each finalized tool call. An invalid input may use complete GLM-pair decoding or balanced JSON syntax repair.
- For configured grammar-leaking routes, normalize exact key/value boundary wrappers and reject residual markers or collisions.
- Apply explicit aliases and schema-directed optional-null or collection normalization.
- Revalidate against the request schema. A changed call is emitted only after validation succeeds.
- Drop the response replay envelope after any call changes because provider-private metadata describes the original content.
- ToolRuntime validates the repaired arguments again against the live definition and retains all normal policy, approval, timeout, sandbox, logging, and result behavior.
A tool definition can change while a response streams. Validation against the request snapshot establishes what the model was asked to produce; ToolRuntime's later validation against the current definition remains authoritative for execution.
Model Experience
Model-visible behavior
The plugin adds no prompt section and changes no tool schema. Valid calls and ordinary assistant text are unchanged. A recovered call proceeds as if the provider had emitted the canonical JSON. An ambiguous configured grammar leak returns a normal denied tool result explaining that the complete call must be regenerated.
Token effect
There is no steady-state prompt cost. A successful repair can avoid a full error-and-retry model round trip; an unrepairable call adds only the ordinary bounded tool error already returned by DSH.
KV Cache effect
None. The request prefix, tool schemas, and system prompt are untouched. Repairs affect only the newly generated assistant suffix.
Programmatic API
import { repairToolCall } from 'dsh-tool-repair'
const outcome = repairToolCall({
name: 'read',
arguments: '{"<arg_key>path":"README.md"}',
schema: request.tools?.find(tool => tool.name === 'read'),
grammarLeak: true,
config,
})
if (outcome.status === 'repaired') {
console.log(outcome.arguments)
}
The package also exports repairToolCallStream and BlockedCallStore for tested embedding. These APIs accept DSH's public message, schema, and stream types; they do not construct another registry or execution pipeline.
Development and release
pnpm install --frozen-lockfile
pnpm run check
# Inspect the exact npm payload; prepack runs the complete check again
pnpm pack --dry-run
# Release after the repository and npm metadata are ready
pnpm publish --access public
pnpm run check type-checks source, emits declarations and the ESM runtime bundle, runs the complete tests, and verifies built exports, bundle metadata, required files, and absence of Pi host dependencies or source-checkout paths.
Known limitations and deferred work
- The plugin can only repair data exposed by a DSH adapter. An upstream library that throws before emitting a finalized block must be fixed in that adapter or provider parser.
- Text-to-tool grammar recovery is deliberately absent; adding it requires preserving block order, call ids, finish reasons, and replay semantics across mixed prose and tool envelopes.
- Route matching uses explicit case-insensitive substrings rather than regexes so invalid patterns cannot break plugin load or turn a broad expression into accidental mutation.
- Schema-valid strings containing literal grammar tokens are indistinguishable from provider leakage without route knowledge. Configure
grammarLeakModels narrowly, especially when an agent edits documentation about those tokens.
Relationship to the other projects
- pi-tool-repair established the validate-then-repair strategy for Pi and supplies the provider-corruption corpus adapted here.
- dsh-fabric owns Fabric's optional inferred
run_code labels. Cosmetic label omission is resolved there; this package handles provider serialization corruption without fabricating missing work inputs.
- dsh-fovea established the single-package external DSH bundle, package verifier, and ownership-safe local installer conventions.
- DeepSeek Harness owns request schemas, session logging, ToolRuntime validation, policy, and execution.
License and acknowledgments
MIT © Tom Nguyen. See LICENSE and THIRD_PARTY_NOTICES.md.