pub fn recover_tool_args(
raw: &str,
expected_top_keys: &[String],
) -> Option<String>Expand description
Recover a flat schema-shaped JSON object from possibly-mangled tool args.
Background: the atomgit api-ai.gitcode.com gateway (and its internal
10.205.128.41:6538 deployment) wraps tool_call function.arguments into
extra envelopes that violate the OpenAI tool-call protocol. Observed
shapes:
variant A1 (stream) — {"arguments": "<stringified-json-object>"}
variant A2 (non-stream) — {"arguments": <object>}
variant B (double) — {"arguments": "{\"arguments\": ...}"}
variant C (multi-key) — {"arguments": "...", "timeout": 120}
variant D (alt key) — {"content": "<stringified-json-object>"}
(Variant E is function.name field corruption — caller-side detection,
not handled here.)
This function recovers the original schema-shaped object by:
- trying direct parse first — if the JSON already contains an expected schema field, return None (caller uses raw),
- otherwise iteratively unwrapping any single-key wrapper (A/A2/B), stringified or object-valued, up to 5 levels deep,
- on multi-key wrapper (C), unwrapping the wrapper key and merging in
the sibling keys that match
expected_top_keys, - final-validating that the recovered object contains at least one
expected_top_keysfield — otherwise returns None to signal unrecoverable.
Safety against false positives: ARGS_WRAPPER_KEYS (arguments, input,
content) are never used as top-level field names by any tool registered
in atomcode (verified across all 22 builtin tools and MCP tool naming
convention). When a future tool adds such a field, callers using
recover_tool_args with that tool’s expected_top_keys will short-circuit
at step 1 and never invoke unwrap.