#![forbid(unsafe_code)]
use serde::{Deserialize, Serialize};
const INVALID_ARGUMENTS: &str = "invalid KtoolDocs arguments";
const UNKNOWN_KTOOL: &str = "unknown Ktool";
struct Entry {
name: &'static str,
version: &'static str,
docs: &'static str,
replacement: Option<&'static str>,
}
impl Entry {
const fn new(name: &'static str, docs: &'static str) -> Self {
Self {
name,
version: "1.0.0",
docs,
replacement: None,
}
}
}
static CATALOG: [Entry; 19] = [
Entry::new(
"KtoolDocs",
r#"Invoke as KtoolDocs {"name":"<exact Ktool name>"}. Arguments must be exactly one nonempty string field, name; matching is exact and case-sensitive. Success returns compact JSON with exactly name, latest_version, docs, deprecated, and replacement. Malformed arguments return invalid KtoolDocs arguments; an unrecognized exact name returns unknown Ktool. The operation is stateless metadata lookup only and does not list, search, suggest, authorize, register, or prove live availability."#,
),
Entry::new(
"CurrentTime",
r#"Invoke as CurrentTime {}. Returns current system UTC in RFC3339 with exactly three fractional digits and Z. Any nonempty or nonobject arguments return invalid CurrentTime arguments. It is stateless and needs no Kmap authorization."#,
),
Entry::new(
"KmapCreateNode",
r#"Invoke as KmapCreateNode {"title":string,"navigation_hint":string,"narrative":string,"connections":[string,...]}. Each connection must be an exact 24-character lowercase hexadecimal Kmap node ID. Using the active Kmap authorization, it creates one node under the bound profile and policy, adds the supplied Navigation connections, marks the new node loaded, and returns Node successfully created with id <id>. Malformed arguments or IDs return invalid KmapCreateNode arguments; missing authorization and Kmap dependency failures remain errors."#,
),
Entry::new(
"KmapOpenNode",
r#"Invoke as KmapOpenNode {"node_id":string,"budget":number}. node_id must be an exact 24-character lowercase hexadecimal Kmap node ID and budget must be finite and nonnegative. It opens in Full mode at temperature 1, records loaded nodes and first-pull provenance, and returns only components not already returned during the session. If no new components remain, it returns No new Kmap node components. Malformed arguments return invalid KmapOpenNode arguments; missing authorization and Kmap dependency failures remain errors."#,
),
Entry::new(
"KmapUpdateNode",
r#"Invoke as KmapUpdateNode {"node_id":string,"title":string,"navigation_hint":string,"narrative":string,"connections":[string,...]}. All IDs must be exact 24-character lowercase hexadecimal Kmap node IDs. It replaces the node text fields, additively upserts the supplied Navigation connections, marks the updated node loaded, and returns success. Naming another node does not itself load that node. Malformed arguments return invalid KmapUpdateNode arguments; missing authorization and Kmap dependency failures remain errors."#,
),
Entry::new(
"KmapPenalizeNodes",
r#"Invoke as KmapPenalizeNodes {"node_ids":[string,...]}. Every ID must be an exact 24-character lowercase hexadecimal Kmap node ID. It deduplicates the input and applies one noncritical negative measurement to each newly penalized eligible loaded node with first-pull provenance. Penalized nodes are excluded from the session’s later KmapConnectNodes operation. Unknown, unloaded, or already penalized valid IDs have no additional effect. Success returns success. Malformed arguments return invalid KmapPenalizeNodes arguments; missing authorization and Kmap dependency failures remain errors."#,
),
Entry::new(
"KmapConnectNodes",
r#"Invoke as KmapConnectNodes {}. Using the active Kmap authorization, it adds every missing directed Automated connection among loaded, unpenalized session nodes. Existing connections remain unchanged and self-connections are not added. Success returns success. Nonempty or nonobject arguments return invalid KmapConnectNodes arguments; missing authorization and Kmap dependency failures remain errors."#,
),
Entry::new(
"SendMessage",
r#"Invoke as SendMessage {"message":string}. Arguments must contain exactly one nonempty message string. It durably appends one visible Agent Message to the authenticated current conversation between the Tool Call and Tool Result, returns success, and leaves the provider turn open for continued generation. It has no recipient argument, network effect, or cross-conversation capability. Malformed arguments return invalid SendMessage arguments without appending a message; persistence failures remain errors."#,
),
Entry::new(
"WebSearch",
r#"Invoke as WebSearch {"query":string,"model":"codex/<model>","reasoning_effort":string?}. Arguments are strict: query and model are required strings, model must have the exact case-sensitive codex/ prefix, and reasoning_effort is optional, non-null, and defaults to medium. It starts one isolated asynchronous search with an absolute 60-minute deadline and emits no progress. Malformed arguments return invalid WebSearch arguments. This metadata does not authorize a provider call or prove runtime availability."#,
),
Entry::new(
"SetLaunchNode",
r#"Invoke as SetLaunchNode {"target":string,"node_id":string}. Arguments are strict: target is validated as an exact target name and node_id must be a visible AccessId of exactly 24 lowercase hexadecimal characters. With current-user authority, it creates or updates that target’s launch-node reference. It makes no runtime-selection claim."#,
),
Entry::new(
"ListContacts",
r#"Invoke as ListContacts {}. Arguments are strict and must be an empty object. It returns the complete caller-owned exact Known Contacts union. Every row has exactly user_id, username, person_id, full_name, and nullable kmap_launch_node. Authorization and dependency failures remain errors."#,
),
Entry::new(
"ListGroups",
r#"Invoke as ListGroups {}. Arguments are strict and must be an empty object. It returns complete visible ordinary human memberships, excluding Known Contacts and filtered groups. Every row has exactly group_id, name, revision, caller_role, and kmap_launch_node. It returns no counts. Authorization and dependency failures remain errors."#,
),
Entry::new(
"GetGroup",
r#"Invoke as GetGroup {"group_id":string}. Arguments are strict and require group_id. Mere user-or-active-model visibility is sufficient. It returns exactly top-level fields group_id, name, revision, kmap_launch_node, users, and models; each user row has user_id, username, person_id, full_name, role, and kmap_launch_node; each model row has model_id and nullable name. It returns no messages, history, narrative, or counts. Authorization and dependency failures remain errors."#,
),
Entry::new(
"RustCodeCreate",
r#"Invoke as RustCodeCreate with exact string arguments authority, library, and version. It starts an unpublished three-file library and emits editable Documentation.md, Cargo.toml, and Rust source boxes. Edit those boxes with RustCodeOverwrite, then check or publish the library."#,
),
Entry::new(
"RustCodeDocs",
r#"Invoke as RustCodeDocs with exact string arguments authority, library, and version. It returns only the exact Documentation.md contents of the published supported three-file library and does not open editable source."#,
),
Entry::new(
"RustCodeOpen",
r#"Invoke as RustCodeOpen with exact string arguments authority, library, and version. It opens a published supported three-file library and emits editable Documentation.md, Cargo.toml, and ordered Rust source boxes."#,
),
Entry::new(
"RustCodeOverwrite",
r#"Invoke as RustCodeOverwrite with box_id from the current RustCodeCreate or RustCodeOpen output and contents containing the complete replacement for that source box. It changes only that segment; later edits keep using the original box ID."#,
),
Entry::new(
"RustCodeCheck",
r#"Invoke as RustCodeCheck with box_id from any box in the current Rust library. It always runs a fresh complete check and returns only the plain success or failure text."#,
),
Entry::new(
"RustCodePublish",
r#"Invoke as RustCodePublish with box_id from any box in the current Rust library. It may be called without RustCodeCheck; it checks automatically when needed, aborts on failure, and immutably publishes only when authorized."#,
),
];
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Arguments {
name: String,
}
#[derive(Serialize)]
struct Response<'a> {
name: &'a str,
latest_version: &'static str,
docs: &'a str,
deprecated: bool,
replacement: Option<&'a str>,
}
fn find_entry(name: &str) -> Option<&'static Entry> {
CATALOG.iter().find(|entry| entry.name == name)
}
fn render(entry: &Entry) -> Result<String, String> {
let response = Response {
name: entry.name,
latest_version: entry.version,
docs: entry.docs,
deprecated: entry.replacement.is_some(),
replacement: entry.replacement,
};
serde_json::to_string(&response)
.map_err(|error| format!("KtoolDocs response serialization failed: {error}"))
}
/// Returns whether `name` is an exact, case-sensitive catalog name.
pub fn is_known_ktool(name: &str) -> bool {
find_entry(name).is_some()
}
/// Looks up the exact Ktool name supplied in a strict JSON argument object.
pub fn ktool_docs(arguments: &str) -> Result<String, String> {
let arguments: Arguments =
serde_json::from_str(arguments).map_err(|_| INVALID_ARGUMENTS.to_owned())?;
if arguments.name.is_empty() {
return Err(INVALID_ARGUMENTS.to_owned());
}
let entry = find_entry(&arguments.name).ok_or_else(|| UNKNOWN_KTOOL.to_owned())?;
render(entry)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
fn arguments_for(name: &str) -> String {
format!("{{\"name\":{}}}", serde_json::to_string(name).unwrap())
}
#[test]
fn every_catalog_entry_has_an_exact_five_field_active_response() {
assert_eq!(CATALOG.len(), 19);
for entry in &CATALOG {
let output = ktool_docs(&arguments_for(entry.name)).unwrap();
let value: Value = serde_json::from_str(&output).unwrap();
let object = value.as_object().unwrap();
assert_eq!(object.len(), 5);
assert_eq!(object.get("name").and_then(Value::as_str), Some(entry.name));
assert_eq!(
object.get("latest_version").and_then(Value::as_str),
Some("1.0.0")
);
assert_eq!(object.get("docs").and_then(Value::as_str), Some(entry.docs));
assert_eq!(
object.get("deprecated").and_then(Value::as_bool),
Some(false)
);
assert!(object.get("replacement").is_some_and(Value::is_null));
}
}
#[test]
fn known_lookup_uses_the_same_exact_catalog() {
for entry in &CATALOG {
assert!(is_known_ktool(entry.name));
}
for name in ["websearch", " WebSearch", "GetGroup ", "Unknown"] {
assert!(!is_known_ktool(name));
assert_eq!(
ktool_docs(&arguments_for(name)),
Err(UNKNOWN_KTOOL.to_owned())
);
}
assert!(!is_known_ktool(""));
assert_eq!(
ktool_docs(&arguments_for("")),
Err(INVALID_ARGUMENTS.to_owned())
);
}
#[test]
fn new_contracts_state_the_approved_boundaries() {
let docs = |name| find_entry(name).unwrap().docs;
assert!(docs("WebSearch").contains("exact case-sensitive codex/ prefix"));
assert!(docs("WebSearch").contains("defaults to medium"));
assert!(docs("WebSearch").contains("one isolated asynchronous search"));
assert!(docs("WebSearch").contains("absolute 60-minute deadline"));
assert!(docs("SetLaunchNode").contains("visible AccessId"));
assert!(docs("SetLaunchNode").contains("current-user authority"));
assert!(docs("SetLaunchNode").contains("creates or updates"));
assert!(docs("ListContacts").contains("complete caller-owned exact Known Contacts union"));
assert!(docs("ListGroups").contains("excluding Known Contacts and filtered groups"));
assert!(docs("ListGroups").contains("no counts"));
let get_group = docs("GetGroup");
assert!(get_group.contains("Mere user-or-active-model visibility"));
assert!(get_group.contains(
"top-level fields group_id, name, revision, kmap_launch_node, users, and models"
));
assert!(
get_group
.contains("user_id, username, person_id, full_name, role, and kmap_launch_node")
);
assert!(get_group.contains("model_id and nullable name"));
assert!(get_group.contains("no messages, history, narrative, or counts"));
assert!(!get_group.contains("caller_role"));
assert!(docs("RustCodeCreate").contains("authority, library, and version"));
assert!(docs("RustCodeCreate").contains("emits editable"));
assert!(docs("RustCodeDocs").contains("returns only the exact Documentation.md"));
assert!(docs("RustCodeOpen").contains("ordered Rust source boxes"));
assert!(docs("RustCodeOverwrite").contains("complete replacement"));
assert!(docs("RustCodeOverwrite").contains("original box ID"));
assert!(docs("RustCodeCheck").contains("always runs a fresh complete check"));
assert!(docs("RustCodePublish").contains("without RustCodeCheck"));
assert!(docs("RustCodePublish").contains("checks automatically"));
assert!(docs("RustCodePublish").contains("aborts on failure"));
}
#[test]
fn malformed_arguments_are_strictly_rejected() {
for input in [
"",
"null",
"[]",
"{}",
r#"{"name":""}"#,
r#"{"name":1}"#,
r#"{"name":"KtoolDocs","extra":false}"#,
r#"{"name":"KtoolDocs","name":"CurrentTime"}"#,
] {
assert_eq!(
ktool_docs(input),
Err(INVALID_ARGUMENTS.to_owned()),
"{input:?}"
);
}
}
#[test]
fn response_serialization_escapes_strings() {
let entry = Entry {
name: "quote\"",
version: "1.0.0",
docs: "line\n",
replacement: None,
};
let output = render(&entry).unwrap();
assert!(output.contains("\\\""));
assert!(output.contains("\\n"));
assert_eq!(
serde_json::from_str::<Value>(&output).unwrap()["docs"],
"line\n"
);
}
}