Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
refactor(contracts): centralize input normalization codes
  • Loading branch information
yyjeqhc committed Sep 29, 2026
commit 90fd22dfa75cd73628d7fccb762ffa333e44b8b9
55 changes: 55 additions & 0 deletions crates/webcodex-tool-contracts/src/input_normalization.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//! Closed vocabulary for existing lossless input normalizations.
//!
//! These labels describe observed normalization, never admission or retry authority.
//! Keep the wire spellings and model hints stable; callers own normalization rules.
use serde::{Serialize, Serializer};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolInputNormalizationCode {
ArgvToArgs,
RunProcessShCToRunShell,
RunProcessBashCToRunShell,
RunProcessBashLcToLoginRunShell,
}

impl ToolInputNormalizationCode {
pub const fn all() -> &'static [Self] {
&[
Self::ArgvToArgs,
Self::RunProcessShCToRunShell,
Self::RunProcessBashCToRunShell,
Self::RunProcessBashLcToLoginRunShell,
]
}

pub const fn as_str(self) -> &'static str {
match self {
Self::ArgvToArgs => "argv_to_args",
Self::RunProcessShCToRunShell => "run_process_sh_c_to_run_shell",
Self::RunProcessBashCToRunShell => "run_process_bash_c_to_run_shell",
Self::RunProcessBashLcToLoginRunShell => "run_process_bash_lc_to_login_run_shell",
}
}

/// Exact closed lookup. No trimming, aliases, or arbitrary diagnostic strings.
pub fn from_wire(value: &str) -> Option<Self> {
Self::all().iter().copied().find(|code| code.as_str() == value)
}

pub const fn model_hint(self) -> &'static str {
match self {
Self::ArgvToArgs => "normalized argv→args",
Self::RunProcessShCToRunShell => "normalized run_process sh -c → run_shell",
Self::RunProcessBashCToRunShell => "normalized run_process bash -c → run_shell",
Self::RunProcessBashLcToLoginRunShell => {
"normalized run_process bash -lc → run_shell(login=true)"
}
}
}
}

impl Serialize for ToolInputNormalizationCode {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
2 changes: 2 additions & 0 deletions crates/webcodex-tool-contracts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! Execution, authorization enforcement, connector orchestration, and side effects remain in
//! the root application crate.

pub mod input_normalization;
pub mod metadata;
pub mod registry;
pub mod request_schema;
Expand All @@ -22,6 +23,7 @@ pub mod test_support;
#[cfg(test)]
mod tests;

pub use input_normalization::ToolInputNormalizationCode;
pub use metadata::*;
pub use registry::*;
pub use request_schema::*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ fn input_normalization_schema() -> Value {
"type": "object", "additionalProperties": false,
"description": "Known lossless input normalization used to avoid a mechanical retry. No raw payload is repeated.",
"properties": {
"code": {"type": "string", "enum": ["argv_to_args", "run_process_sh_c_to_run_shell", "run_process_bash_c_to_run_shell", "run_process_bash_lc_to_login_run_shell"]},
"code": {"type": "string", "enum": crate::ToolInputNormalizationCode::all()},
"hint": {"type": "string", "maxLength": 80}
},
"required": ["code", "hint"]
Expand Down
35 changes: 35 additions & 0 deletions crates/webcodex-tool-contracts/src/tests/input_normalization.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use super::*;

#[test]
fn input_normalization_vocabulary_is_unique_closed_and_wire_stable() {
let codes = ToolInputNormalizationCode::all();
let spellings = codes.iter().map(|code| code.as_str()).collect::<Vec<_>>();
// Frozen wire contract, intentionally independent of the implementation.
assert_eq!(spellings, [
"argv_to_args",
"run_process_sh_c_to_run_shell",
"run_process_bash_c_to_run_shell",
"run_process_bash_lc_to_login_run_shell",
]);
assert_eq!(spellings.iter().collect::<BTreeSet<_>>().len(), codes.len());
for code in codes {
assert_eq!(ToolInputNormalizationCode::from_wire(code.as_str()), Some(*code));
assert_eq!(serde_json::to_value(code).unwrap(), code.as_str());
assert!(code.model_hint().chars().count() <= 80);
}
for unknown in ["", "ARGV_TO_ARGS", " argv_to_args", "argv_to_args ", "private/parser/error"] {
assert_eq!(ToolInputNormalizationCode::from_wire(unknown), None);
}
}

#[test]
fn input_normalization_output_enums_derive_from_canonical_vocabulary() {
for name in ["run_process", "run_detached_process"] {
let schema = output_schema_for_tool(name);
assert_eq!(
schema.pointer("/properties/output/properties/input_normalization/properties/code/enum").unwrap(),
&serde_json::to_value(ToolInputNormalizationCode::all()).unwrap(),
"{name}"
);
}
}
1 change: 1 addition & 0 deletions crates/webcodex-tool-contracts/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ mod computer_schemas;
mod definitions;
mod edit_schemas;
mod identifier_schemas;
mod input_normalization;
mod input_schemas;
mod metadata_policy;
mod migration_contracts;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -967,7 +967,7 @@ fn process_argv_alias_is_exact_and_canonical() {
alias["argv"] = json!(["status"]);
let (call, code) =
ToolCall::from_tool_name_with_normalization(name, alias.clone()).unwrap();
assert_eq!(code, Some("argv_to_args"));
assert_eq!(code, Some(ToolInputNormalizationCode::ArgvToArgs));
assert_eq!(
serde_json::to_value(&call).unwrap()["params"]["args"],
json!(["status"])
Expand Down Expand Up @@ -995,7 +995,7 @@ fn process_argv_alias_is_exact_and_canonical() {
ToolCall::from_tool_name_with_normalization(name, alias.clone())
.unwrap()
.1,
Some("argv_to_args")
Some(ToolInputNormalizationCode::ArgvToArgs)
);
alias["args"] = json!(["different"]);
assert_eq!(
Expand Down
5 changes: 3 additions & 2 deletions crates/webcodex-tool-contracts/src/tool_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5475,7 +5475,7 @@ impl ToolCall {
pub fn from_tool_name_with_normalization(
name: &str,
arguments: Value,
) -> Result<(Self, Option<&'static str>), String> {
) -> Result<(Self, Option<crate::ToolInputNormalizationCode>), String> {
validate_model_facing_assertion_name(name, &arguments)?;
validate_model_facing_result_expectation(name, &arguments)?;
if name == "create_project"
Expand Down Expand Up @@ -5527,7 +5527,8 @@ impl ToolCall {
let mut arguments = strip_tool_call_expectation_metadata(arguments);
validate_run_shell_login(name, &arguments)?;
let normalization =
canonicalize_process_argv_alias(name, &mut arguments)?.then_some("argv_to_args");
canonicalize_process_argv_alias(name, &mut arguments)?
.then_some(crate::ToolInputNormalizationCode::ArgvToArgs);
canonicalize_cargo_check_packages(name, &mut arguments)?;
if name == "tool_manifest" {
if let Some(object) = arguments.as_object_mut() {
Expand Down
15 changes: 4 additions & 11 deletions src/tool_runtime/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,13 +811,13 @@ impl ToolRuntime {
}
session_contract = super::sessions::session_tool_contract("run_shell");
shell_normalization = Some(if login {
"run_process_bash_lc_to_login_run_shell"
webcodex_tool_contracts::ToolInputNormalizationCode::RunProcessBashLcToLoginRunShell
} else {
match &call {
ToolCall::RunShell {
shell: Some(shell), ..
} if shell.as_str() == "sh" => "run_process_sh_c_to_run_shell",
_ => "run_process_bash_c_to_run_shell",
} if shell.as_str() == "sh" => webcodex_tool_contracts::ToolInputNormalizationCode::RunProcessShCToRunShell,
_ => webcodex_tool_contracts::ToolInputNormalizationCode::RunProcessBashCToRunShell,
}
});
}
Expand Down Expand Up @@ -1057,15 +1057,8 @@ impl ToolRuntime {
result.output["requested_surface"] = serde_json::json!("run_process");
result.output["execution_source"] = serde_json::json!("run_shell");
if result.success {
let hint = match code {
"run_process_bash_lc_to_login_run_shell" => {
"normalized run_process bash -lc → run_shell(login=true)"
}
"run_process_sh_c_to_run_shell" => "normalized run_process sh -c → run_shell",
_ => "normalized run_process bash -c → run_shell",
};
result.output["input_normalization"] =
serde_json::json!({"code": code, "hint": hint});
serde_json::json!({"code": code, "hint": code.model_hint()});
}
}
let permission = permission.filter(|_| {
Expand Down
6 changes: 1 addition & 5 deletions src/tool_runtime/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1112,12 +1112,8 @@ impl ToolRuntime {
.await;
if result.success {
if let Some(code) = input_normalization {
let hint = match code {
"argv_to_args" => "normalized argv→args",
_ => unreachable!("parser returns only stable known normalization codes"),
};
result.output["input_normalization"] =
serde_json::json!({"code": code, "hint": hint});
serde_json::json!({"code": code, "hint": code.model_hint()});
}
}
if let Some(control) = control.as_mut() {
Expand Down
8 changes: 8 additions & 0 deletions src/tool_runtime/tests/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2558,6 +2558,14 @@ async fn run_process_shell_command_mode_recovery_is_lossless_parser_ready_and_pr
if args[0] == "-lc" {
assert_eq!(result.output["shell"], "bash_login");
}
let expected_code = if args[0] == "-lc" {
"run_process_bash_lc_to_login_run_shell"
} else if shell == "sh" {
"run_process_sh_c_to_run_shell"
} else {
"run_process_bash_c_to_run_shell"
};
assert_eq!(result.output["input_normalization"]["code"], expected_code);
assert!(result.output["input_normalization"]["hint"]
.as_str()
.unwrap()
Expand Down