Deduplicate model catalog strings in memory (#63735)

## Why

Identical instructions and tool descriptions can appear in multiple
model catalog records. Each decode or clone previously allocated its own
copy of that text.

## What changed

Use `CodexCachedStr` for catalog instructions, messages, and tool
overrides. It stores short strings inline and interns longer strings so
independent decodes and clones can share storage. Resolved incremental
tool messages also reuse cached text from overrides and bundled defaults.
JSON and generated TypeScript still represent these values as strings.

## Testing

Add tests for shared storage across catalog fields, independent decodes,
clones, and incremental tool defaults. Cover plain JSON string round
trips and borrowed access to short inline UTF-8 strings.

GitOrigin-RevId: 6f53b4e19f01f6ed52a8fd364279b924cf794be2
This commit is contained in:
Adam Perry @ OpenAI
2026-11-24 20:21:47 +00:00
committed by copyberry
parent 7a24022794
commit 9a3c131eb4
91 changed files with 799 additions and 508 deletions
+55 -4
View File
@@ -3118,6 +3118,7 @@ dependencies = [
"codex-utils-absolute-path",
"codex-utils-audio",
"codex-utils-cache",
"codex-utils-cached-str",
"codex-utils-cargo-bin",
"codex-utils-critical-path",
"codex-utils-git-discovery",
@@ -4384,6 +4385,7 @@ dependencies = [
"codex-protocol",
"codex-state",
"codex-tools",
"codex-utils-cached-str",
"codex-utils-output-truncation",
"futures",
"pretty_assertions",
@@ -4512,6 +4514,7 @@ dependencies = [
"codex-otel",
"codex-prompts",
"codex-protocol",
"codex-utils-cached-str",
"codex-utils-output-truncation",
"pretty_assertions",
"serde",
@@ -4771,6 +4774,7 @@ dependencies = [
"codex-protocol",
"codex-protocol-test-support",
"codex-utils-absolute-path",
"codex-utils-cached-str",
"codex-utils-template",
"pretty_assertions",
"tracing",
@@ -4790,6 +4794,7 @@ dependencies = [
"codex-http-client",
"codex-network-proxy",
"codex-utils-absolute-path",
"codex-utils-cached-str",
"codex-utils-image",
"codex-utils-model-facing-id",
"codex-utils-path-uri",
@@ -5580,6 +5585,17 @@ dependencies = [
"tokio",
]
[[package]]
name = "codex-utils-cached-str"
version = "0.0.0"
dependencies = [
"schemars 0.8.22",
"serde",
"serde_json",
"string_cache",
"ts-rs",
]
[[package]]
name = "codex-utils-cargo-bin"
version = "0.0.0"
@@ -6307,6 +6323,7 @@ dependencies = [
"codex-protocol",
"codex-thread-store",
"codex-utils-absolute-path",
"codex-utils-cached-str",
"codex-utils-cargo-bin",
"codex-utils-path-uri",
"codex-utils-rustls-provider",
@@ -11015,6 +11032,12 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nibble_vec"
version = "0.1.0"
@@ -12164,7 +12187,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.11.3",
]
[[package]]
@@ -12174,7 +12197,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.11.3",
]
[[package]]
@@ -12183,7 +12206,7 @@ version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
dependencies = [
"phf_shared",
"phf_shared 0.11.3",
"rand 0.8.6",
]
@@ -12194,7 +12217,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.11.3",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -12209,6 +12232,15 @@ dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"
dependencies = [
"siphasher",
]
[[package]]
name = "pin-project"
version = "1.1.10"
@@ -12407,6 +12439,12 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "predicates"
version = "3.1.3"
@@ -15490,6 +15528,19 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"
[[package]]
name = "string_cache"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared 0.14.0",
"precomputed-hash",
"serde",
]
[[package]]
name = "stringprep"
version = "0.1.5"
+3
View File
@@ -135,6 +135,7 @@ members = [
"utils/cargo-bin",
"git-utils",
"utils/cache",
"utils/cached-str",
"utils/critical-path",
"utils/git-discovery",
"utils/head-tail-buffer",
@@ -323,6 +324,7 @@ codex-utils-absolute-path = { path = "utils/absolute-path" }
codex-utils-approval-presets = { path = "utils/approval-presets" }
codex-utils-audio = { path = "utils/audio" }
codex-utils-cache = { path = "utils/cache" }
codex-utils-cached-str = { path = "utils/cached-str" }
codex-utils-cargo-bin = { path = "utils/cargo-bin" }
codex-utils-cli = { path = "utils/cli" }
codex-utils-critical-path = { path = "utils/critical-path" }
@@ -536,6 +538,7 @@ sqlx-macros = { version = "=0.9.0", default-features = false, features = ["deriv
# Preserve the target driver's query-description support without building it on the host.
sqlx-sqlite = { version = "=0.9.0", default-features = false, features = ["offline"] }
starlark = { version = "0.14.2", default-features = false }
string_cache = "0.11"
strum = "0.27.2"
strum_macros = "0.28.0"
supports-color = "3.0.2"
@@ -36,7 +36,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo {
content_filter_guidance: None,
persistent_instructions: None,
tools: None,
instructions_template: Some("base instructions".to_string()),
instructions_template: Some("base instructions".into()),
approvals: None,
collaboration_modes: None,
auto_review: None,
+1 -1
View File
@@ -41,7 +41,7 @@ async fn remote_exec_forwards_model_and_effort_and_preserves_omitted_settings()
let mut model = template.clone();
model.slug = slug.to_string();
model.model_messages = Some(codex_protocol::openai_models::ModelMessages {
instructions_template: Some(format!("Base instructions for {slug}")),
instructions_template: Some(format!("Base instructions for {slug}").into()),
..Default::default()
});
model
@@ -40,7 +40,7 @@ fn exec_override_renders_only_known_literal_placeholders() {
/*incremental_exec_enabled*/ true,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(" \nDefaults to 10000 ms. {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}\n{{ unknown }} {{default_exec_yield_time_ms}}\t ".to_string()),
description: Some(" \nDefaults to 10000 ms. {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}\n{{ unknown }} {{default_exec_yield_time_ms}}\t ".into()),
..Default::default()
}),
..Default::default()
@@ -72,13 +72,11 @@ fn exec_override_preserves_empty_and_whitespace_only_text() {
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(description_override.to_string()),
description: Some(description_override.into()),
..Default::default()
}),
deferred_nested_tools_guidance: Some(
"No deferred tools; omit this.".to_string()
),
mcp_typescript_preamble: Some("No MCP tools; omit this.".to_string()),
deferred_nested_tools_guidance: Some("No deferred tools; omit this.".into()),
mcp_typescript_preamble: Some("No MCP tools; omit this.".into()),
..Default::default()
}),
)
@@ -165,11 +163,11 @@ fn exec_override_preserves_runtime_sections() {
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: preamble.map(str::to_string),
deferred_nested_tools_guidance: guidance.map(Into::into),
mcp_typescript_preamble: preamble.map(Into::into),
..Default::default()
}),
)
@@ -214,11 +212,11 @@ fn ranked_search_guidance_honors_overrides() {
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: Some(String::new()),
deferred_nested_tools_guidance: guidance.map(Into::into),
mcp_typescript_preamble: Some("".into()),
..Default::default()
}),
);
@@ -249,7 +247,7 @@ fn mcp_types_stay_stable_when_a_deferred_tool_changes_its_output_schema() {
DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
mcp_typescript_preamble: preamble.map(str::to_string),
mcp_typescript_preamble: preamble.map(Into::into),
..Default::default()
}),
)
@@ -295,11 +293,11 @@ fn nested_guidance_survives_catalog_changes_and_respects_overrides() {
/*incremental_exec_enabled*/ false,
Some(&CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
deferred_nested_tools_guidance: guidance.map(str::to_string),
mcp_typescript_preamble: Some(String::new()),
deferred_nested_tools_guidance: guidance.map(Into::into),
mcp_typescript_preamble: Some("".into()),
..Default::default()
}),
)
+1
View File
@@ -79,6 +79,7 @@ codex-user-input = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-audio = { workspace = true }
codex-utils-cache = { workspace = true }
codex-utils-cached-str = { workspace = true }
codex-utils-critical-path = { workspace = true }
codex-utils-git-discovery = { workspace = true }
codex-utils-head-tail-buffer = { workspace = true }
+7 -2
View File
@@ -56,6 +56,7 @@ use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_models_manager::manager::ModelCatalogSettings;
use codex_models_manager::model_info::model_info_from_slug;
use codex_prompts::ResolvedIncrementalToolMessages;
use codex_protocol::AgentPath;
use codex_protocol::RequestCountry;
use codex_protocol::ResponseItemId;
@@ -3334,7 +3335,9 @@ async fn spawn_agent_fork_strips_parent_usage_hints_from_compacted_history() {
tools: Arc::from([serde_json::json!({"type": "function", "name": "compacted_tool"})]),
};
let tools_update = ContextualUserFragment::into(IncrementalToolsUpdate(
codex_prompts::ResolvedIncrementalToolMessages::default().tool_update_hint,
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow(),
));
let replacement_history = vec![
tools_update.clone(),
@@ -3911,7 +3914,9 @@ async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_onc
]);
rollout_items.push(rollout_response_item(ContextualUserFragment::into(
IncrementalToolsUpdate(
codex_prompts::ResolvedIncrementalToolMessages::default().tool_update_hint,
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow(),
),
)));
rollout_items.push(rollout_response_item(ResponseItem::AdditionalTools {
@@ -94,8 +94,8 @@ fn catalog_collaboration_messages_select_mode_variant() {
model.model_messages = Some(ModelMessages {
collaboration_modes: Some(CollaborationModeMessages {
initial: None,
default: Some(default.to_string()),
plan: Some(plan.to_string()),
default: Some(default.into()),
plan: Some(plan.into()),
}),
..Default::default()
});
@@ -201,11 +201,11 @@ fn initially_blank_permissions_preserve_saved_prefix_updates(per_environment: bo
let mut model = model_info_from_slug("test-model");
model.model_messages = Some(ModelMessages {
approvals: Some(ApprovalMessages {
never: Some(String::new()),
never: Some("".into()),
..Default::default()
}),
permissions: Some(PermissionMessages {
read_only: Some(" \t ".to_string()),
read_only: Some(" \t ".into()),
..Default::default()
}),
..Default::default()
@@ -377,7 +377,7 @@ fn permissions_state(
approval_policy: AskForApproval,
) -> PermissionsState {
let approval_messages = ApprovalMessages {
on_request: Some("Ask for approval.".to_string()),
on_request: Some("Ask for approval.".into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -385,9 +385,9 @@ fn permissions_state(
..Default::default()
};
let permission_messages = PermissionMessages {
danger_full_access: Some("Full access.".to_string()),
workspace_write: Some("Workspace write.".to_string()),
read_only: Some("Read only.".to_string()),
danger_full_access: Some("Full access.".into()),
workspace_write: Some("Workspace write.".into()),
read_only: Some("Read only.".into()),
approved_prefixes: None,
..PermissionMessages::default()
};
@@ -30,9 +30,11 @@ use codex_protocol::models::ContentItemKind;
use codex_protocol::models::ContentItemMetadata;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::input_text;
use codex_utils_cached_str::CodexCachedStr;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -236,7 +238,7 @@ impl WorldStateSection for TopLevelToolsState {
updates.insert(
index,
WorldStateUpdate::prefix_item(ContextualUserFragment::into(
IncrementalToolsUpdate(self.messages.tool_update_hint.clone()),
IncrementalToolsUpdate(self.messages.tool_update_hint.as_cow()),
)),
);
}
@@ -491,13 +493,13 @@ impl TopLevelToolsState {
}
/// An appended catalog hint or exec definition update, retained or discarded with its baseline.
pub(crate) struct IncrementalToolsUpdate(pub(crate) String);
pub(crate) struct IncrementalToolsUpdate<'a>(pub(crate) Cow<'a, str>);
impl IncrementalToolsUpdate {
impl IncrementalToolsUpdate<'_> {
pub(crate) const KIND: &str = "tools.incremental_update";
}
impl ContextualUserFragment for IncrementalToolsUpdate {
impl ContextualUserFragment for IncrementalToolsUpdate<'_> {
fn role(&self) -> &'static str {
"developer"
}
@@ -515,7 +517,7 @@ impl ContextualUserFragment for IncrementalToolsUpdate {
}
fn body(&self) -> ContentItem {
input_text(self.0.clone())
input_text(self.0.as_ref())
}
}
@@ -571,7 +573,10 @@ impl ContextualUserFragment for RemovedTools {
}
/// Render a nonempty batch of complete replacement definitions with the exec update hint.
fn render_exec_update(definitions: &[&ExecDefinition], hint: &str) -> IncrementalToolsUpdate {
fn render_exec_update(
definitions: &[&ExecDefinition],
hint: &str,
) -> IncrementalToolsUpdate<'static> {
let description = definitions
.iter()
.map(|entry| entry.description.as_str())
@@ -583,13 +588,13 @@ fn render_exec_update(definitions: &[&ExecDefinition], hint: &str) -> Incrementa
}
text.push_str("## Namespace: functions\n");
text.push_str(&description);
IncrementalToolsUpdate(text)
IncrementalToolsUpdate(Cow::Owned(text))
}
/// Removal notice containing the stable keys of withdrawn tools or namespace instructions.
struct RemovedExecDefinitions {
/// Guidance preceding the removed keys; an empty header emits only the keys.
header: String,
header: CodexCachedStr,
/// Stable entry keys that are no longer present in the current catalog.
names: Vec<String>,
}
@@ -612,7 +617,7 @@ impl ContextualUserFragment for RemovedExecDefinitions {
}
fn body(&self) -> ContentItem {
let mut text = self.header.clone();
let mut text = self.header.to_string();
if !text.is_empty() {
text.push('\n');
}
@@ -414,8 +414,8 @@ fn initial_catalog_preserves_order_and_unchanged_catalog_emits_nothing() {
let reworded = TopLevelToolsState::new(
ResolvedIncrementalToolMessages {
tool_update_hint: "New wording".to_string(),
removed_tools_header: "Removed".to_string(),
tool_update_hint: "New wording".into(),
removed_tools_header: "Removed".into(),
..Default::default()
},
definitions,
@@ -464,7 +464,9 @@ fn empty_catalog_is_persisted_and_can_add_tools_again() {
merge_world_state_updates(updates),
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default().tool_update_hint
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow()
)),
item(definitions),
]
@@ -514,7 +516,9 @@ fn namespace_diff_contains_only_changed_and_added_tools() {
merge_world_state_updates(updates),
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default().tool_update_hint
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow()
)),
item(vec![expected]),
ContextualUserFragment::into(RemovedTools {
@@ -558,13 +562,15 @@ fn new_namespaces_share_one_notice_before_their_declarations() {
prefix,
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default().tool_update_hint
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow()
)),
item(additions.clone()),
]
);
assert!(remaining.is_empty());
state.messages.tool_update_hint.clear();
state.messages.tool_update_hint = "".into();
let (_, updates) = state.render_diff(PreviousSectionState::Known(&previous));
let (prefix, remaining) = super::super::split_prefix_updates(updates);
assert_eq!(prefix, vec![item(additions)]);
@@ -617,8 +623,8 @@ fn namespace_description_change_does_not_repeat_unchanged_tools(
updated["description"] = json!(instructions);
let mut messages = ResolvedIncrementalToolMessages::default();
if let Some((prefix, cleared_template)) = wording {
messages.namespace_instructions_prefix = prefix.to_string();
messages.namespace_instructions_cleared = cleared_template.to_string();
messages.namespace_instructions_prefix = prefix.into();
messages.namespace_instructions_cleared = cleared_template.into();
}
let current = TopLevelToolsState::new(messages, vec![updated], /*metrics*/ None).unwrap();
let (snapshot, updates) = current.render_diff(PreviousSectionState::Known(&snapshot));
@@ -673,7 +679,9 @@ fn tool_type_change_keeps_the_callable_name_available() {
merge_world_state_updates(updates),
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default().tool_update_hint
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow()
)),
item(vec![updated]),
ContextualUserFragment::into(RemovedTools {
@@ -805,7 +813,9 @@ fn hidden_exec_is_not_reintroduced_and_returning_exec_restores_full_catalog() {
let restored: TopLevelToolsSnapshot =
serde_json::from_value(serde_json::to_value(empty.unwrap()).unwrap()).unwrap();
let hint = ContextualUserFragment::into(IncrementalToolsUpdate(
ResolvedIncrementalToolMessages::default().tool_update_hint,
ResolvedIncrementalToolMessages::default()
.tool_update_hint
.as_cow(),
));
let namespace_instructions = ContextualUserFragment::into(
DeveloperInstructions::new(
@@ -919,15 +929,18 @@ fn changed_and_added_entries_share_one_update_and_removed_entries_are_withdrawn(
])));
let (snapshot, updates) = current.render_diff(PreviousSectionState::Known(&baseline));
let defaults = ResolvedIncrementalToolMessages::default();
let expected_update_hint = expected_update_hint.unwrap_or(defaults.exec_tools_update_hint);
let expected_removal_header =
expected_removal_header.unwrap_or(defaults.exec_tools_removed_definitions_header);
let expected_update_hint = expected_update_hint
.as_deref()
.unwrap_or(&defaults.exec_tools_update_hint);
let expected_removal_header = expected_removal_header
.map(Into::into)
.unwrap_or(defaults.exec_tools_removed_definitions_header);
assert_eq!(
merge_world_state_updates(updates),
vec![
ContextualUserFragment::into(IncrementalToolsUpdate(format!(
ContextualUserFragment::into(IncrementalToolsUpdate(Cow::Owned(format!(
"{expected_update_hint}\n\n## Namespace: functions\n### a\nChanged a.\ndeclare const tools: {{ a(value: number): Promise<number> }};\n\n### c\ndeclare const tools: {{ c(): Promise<boolean> }};",
))),
)))),
ContextualUserFragment::into(RemovedExecDefinitions {
header: expected_removal_header,
names: vec!["Tool: tools.b".to_string()],
@@ -652,8 +652,8 @@ async fn guardian_review_session_config_resolves_policy_and_template(
let mut model = model_info_from_slug("active-model");
model.model_messages = Some(ModelMessages {
auto_review: Some(AutoReviewMessages {
policy: Some(catalog_policy.to_string()),
policy_template: catalog_template.map(str::to_owned),
policy: Some(catalog_policy.into()),
policy_template: catalog_template.map(Into::into),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
+1 -1
View File
@@ -1360,7 +1360,7 @@ async fn guardian_reuse_respects_effective_policy_and_personality_opt_out(
.auto_review
.as_mut()
.unwrap()
.policy = Some("changed action policy".to_string());
.policy = Some("changed action policy".into());
let mut different_personality = changed_policy.clone();
different_personality.personality = Some(codex_protocol::config_types::Personality::Pragmatic);
let mut omit_personality = different_personality.clone();
+4 -1
View File
@@ -1536,7 +1536,10 @@ fn build_confirmation_policies_request_meta(
("computer_use", confirmation_policies.computer_use.as_ref()),
] {
if let Some(policy) = policy {
policies.insert(name.to_string(), serde_json::Value::String(policy.clone()));
policies.insert(
name.to_string(),
serde_json::Value::String(policy.to_string()),
);
}
}
}
@@ -597,9 +597,9 @@ async fn submitted_sparse_updates_preserve_captured_steps_and_ordering() {
enabled: false,
use_history_notes_extension: false,
reminder_threshold_tokens: 2_000,
reminder_message_template: "{n_remaining} tokens remain.".to_string(),
guidance_message: format!("Guidance for {}.", model.slug),
auto_compact_fallback_prompt: "Save state before rollover.".to_string(),
reminder_message_template: "{n_remaining} tokens remain.".into(),
guidance_message: format!("Guidance for {}.", model.slug).into(),
auto_compact_fallback_prompt: "Save state before rollover.".into(),
auto_compact_fallback_buffer_tokens: 4_000,
});
}
@@ -624,7 +624,7 @@ async fn submitted_sparse_updates_preserve_captured_steps_and_ordering() {
.model_messages
.as_mut()
.expect("model messages")
.instructions_template = Some("Destination-model instructions.".to_string());
.instructions_template = Some("Destination-model instructions.".into());
let expected_destination = destination.clone();
let ActivationFixture {
session,
@@ -1414,8 +1414,8 @@ async fn parent_fallback_policy_uses_both_config_lifetimes(
let mut live_config = admitted_config.clone();
live_config.guardian_policy_config = live_policy.map(str::to_string);
let (mut admitted, mut destination) = safety_models();
parent_review_messages(&mut admitted).policy = Some("catalog policy A".to_string());
parent_review_messages(&mut destination).policy = Some("catalog policy B".to_string());
parent_review_messages(&mut admitted).policy = Some("catalog policy A".into());
parent_review_messages(&mut destination).policy = Some("catalog policy B".into());
assert_eq!(
check_legacy_model_safety(
&admitted,
@@ -1442,24 +1442,24 @@ async fn parent_fallback_preserves_explicit_empty_and_bundled_defaults() {
let check = |destination: &CatalogModel| {
check_legacy_model_safety(&admitted, &admitted, destination, &config, &config)
};
parent_review_messages(&mut destination).policy = Some(defaults.policy.to_string());
parent_review_messages(&mut destination).policy = Some(defaults.policy.into());
parent_review_messages(&mut destination).policy_template =
Some(defaults.policy_template.to_string());
Some(defaults.policy_template.into());
assert_eq!(check(&destination), Ok(()));
parent_review_messages(&mut destination).policy_template = Some(String::new());
parent_review_messages(&mut destination).policy_template = Some("".into());
assert_eq!(
check(&destination),
Err("the destination changes the Guardian parent-fallback policy template".to_string())
);
parent_review_messages(&mut destination).policy_template = None;
parent_review_messages(&mut destination).policy = Some(String::new());
parent_review_messages(&mut destination).policy = Some("".into());
assert_eq!(
check(&destination),
Err("the destination changes the Guardian parent-fallback policy".to_string())
);
parent_review_messages(&mut destination).policy = None;
assert_eq!(check(&destination), Ok(()));
parent_review_messages(&mut destination).node_repl_policy = Some(String::new());
parent_review_messages(&mut destination).node_repl_policy = Some("".into());
assert_eq!(
check(&destination),
Err("the destination changes the Guardian parent-fallback node REPL policy".to_string())
@@ -1473,10 +1473,10 @@ async fn unchanged_explicit_reviewer_does_not_use_parent_policy() {
for model in [&mut admitted, &mut destination] {
model.auto_review_model_override = Some("shared-reviewer".to_string());
}
parent_review_messages(&mut admitted).policy = Some("catalog policy A".to_string());
parent_review_messages(&mut destination).policy = Some("catalog policy B".to_string());
parent_review_messages(&mut destination).policy_template = Some(String::new());
parent_review_messages(&mut destination).node_repl_policy = Some(String::new());
parent_review_messages(&mut admitted).policy = Some("catalog policy A".into());
parent_review_messages(&mut destination).policy = Some("catalog policy B".into());
parent_review_messages(&mut destination).policy_template = Some("".into());
parent_review_messages(&mut destination).node_repl_policy = Some("".into());
assert_eq!(
check_legacy_model_safety(
&admitted,
@@ -1490,7 +1490,7 @@ async fn unchanged_explicit_reviewer_does_not_use_parent_policy() {
}
#[test_case(GuardianV2ModelConfig {
classifier_instructions: Some("Review the complete action.".to_string()),
classifier_instructions: Some("Review the complete action.".into()),
..Default::default()
}; "classifier instructions")]
#[test_case(GuardianV2ModelConfig {
@@ -1503,7 +1503,7 @@ async fn unchanged_explicit_reviewer_does_not_use_parent_policy() {
}; "classifier effort")]
#[test_case(GuardianV2ModelConfig {
transcript: Some(GuardianV2TranscriptModelConfig {
sources: Some(vec!["reasoning".to_string()]),
sources: Some(vec!["reasoning".into()]),
..Default::default()
}),
..Default::default()
@@ -416,14 +416,14 @@ async fn model_resolution_preserves_startup_overrides_and_instruction_provenance
) {
let configured_instructions = "explicit instructions";
let auto_review = AutoReviewMessages {
policy: Some("catalog review policy".to_string()),
policy_template: Some("catalog review template".to_string()),
policy: Some("catalog review policy".into()),
policy_template: Some("catalog review template".into()),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
};
let guardian_v2 = GuardianV2ModelConfig {
classifier_instructions: Some("catalog classifier".to_string()),
classifier_instructions: Some("catalog classifier".into()),
review_threshold_basis_points: Some(7_500),
..Default::default()
};
@@ -437,7 +437,7 @@ async fn model_resolution_preserves_startup_overrides_and_instruction_provenance
.as_mut()
.expect("test model should have instruction metadata");
messages.instructions_template =
Some("Catalog B.\n# Personality\nfixed\n# Rules\nKeep the rules.".to_string());
Some("Catalog B.\n# Personality\nfixed\n# Rules\nKeep the rules.".into());
messages.auto_review = Some(auto_review);
messages.guardian_v2 = Some(guardian_v2);
let catalog = ModelsResponse {
+2 -2
View File
@@ -11353,7 +11353,7 @@ async fn build_initial_context_uses_retained_step_after_model_change() {
model_info.context_window = None;
model_info.max_context_window = None;
let messages = model_info.model_messages.as_mut().unwrap();
messages.instructions_template = Some("A instructions".to_string());
messages.instructions_template = Some("A instructions".into());
});
session.state.lock().await.base_instructions_provenance =
Some(codex_protocol::models::BaseInstructionsProvenance::Model {
@@ -11401,7 +11401,7 @@ async fn build_initial_context_uses_retained_step_after_model_change() {
.model_messages
.as_mut()
.unwrap()
.instructions_template = Some("B instructions".to_string());
.instructions_template = Some("B instructions".into());
turn_context
.next_step_settings
.store(Arc::new(ResolvedStepSettings::new(
+3 -3
View File
@@ -103,9 +103,9 @@ pub(super) fn resolve_token_budget(
use_history_notes_extension: configured_token_budget
.is_some_and(|token_budget| token_budget.use_history_notes_extension),
reminder_threshold_tokens: Some(model_defaults.reminder_threshold_tokens),
reminder_message_template: model_defaults.reminder_message_template.clone(),
guidance_message: Some(model_defaults.guidance_message.clone()),
auto_compact_fallback_prompt: Some(model_defaults.auto_compact_fallback_prompt.clone()),
reminder_message_template: model_defaults.reminder_message_template.to_string(),
guidance_message: Some(model_defaults.guidance_message.to_string()),
auto_compact_fallback_prompt: Some(model_defaults.auto_compact_fallback_prompt.to_string()),
auto_compact_fallback_buffer_tokens: Some(
model_defaults.auto_compact_fallback_buffer_tokens,
),
@@ -451,10 +451,7 @@ mod tests {
assert!(!Arc::ptr_eq(&without_sources, &replacement));
registry.apply_functions_namespace_function_prefixes(Some(
&std::collections::BTreeMap::from([(
"create_event".to_string(),
"Guidance.".to_string(),
)]),
&std::collections::BTreeMap::from([("create_event".into(), "Guidance.".into())]),
));
let prefixed = cache.get_or_build(&registry, ToolSearchSourceListing::Include);
let reused = cache.get_or_build(&registry, ToolSearchSourceListing::Include);
+2 -1
View File
@@ -40,6 +40,7 @@ use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::ToolResultMetadata;
use codex_protocol::openai_models::ToolDescriptionPrefixes;
use codex_protocol::parse_command::ParsedCommand;
use codex_protocol::protocol::EventMsg;
use codex_rollout::state_db;
@@ -493,7 +494,7 @@ impl ToolRegistry {
/// Prepare registered functions and the exec/wait wrappers added later in the plan.
pub(crate) fn apply_functions_namespace_function_prefixes(
&mut self,
prefixes: Option<&BTreeMap<String, String>>,
prefixes: Option<&ToolDescriptionPrefixes>,
) {
let registered = self
.tools
+1
View File
@@ -36,6 +36,7 @@ codex-network-proxy = { workspace = true }
codex-protocol = { workspace = true }
codex-thread-store = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cached-str = { workspace = true }
codex-utils-cargo-bin = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
@@ -2,6 +2,7 @@
//! Request grouping stays independent of these display rules.
use super::ContextSnapshotOptions;
use codex_utils_cached_str::CodexCachedStr;
use regex_lite::Regex;
use serde_json::Value;
use std::sync::OnceLock;
@@ -543,7 +544,7 @@ pub(super) fn portable_tool_schema(tool: &Value) -> Value {
}
pub(super) fn is_bundled_model_instructions(text: &str) -> bool {
static PROMPTS: OnceLock<Vec<String>> = OnceLock::new();
static PROMPTS: OnceLock<Vec<CodexCachedStr>> = OnceLock::new();
text == codex_models_manager::model_info::BASE_INSTRUCTIONS
|| PROMPTS
.get_or_init(|| {
@@ -555,7 +556,7 @@ pub(super) fn is_bundled_model_instructions(text: &str) -> bool {
.collect()
})
.iter()
.any(|prompt| prompt == text)
.any(|prompt| prompt.as_str() == text)
}
// Only complete, balanced wrappers identify guidance. Adjacent or malformed wrappers remain text.
+2 -2
View File
@@ -2310,11 +2310,11 @@ async fn approving_execpolicy_amendment_emits_one_saved_prefix_notice(
model_info.use_responses_lite = true;
model_info.model_messages = Some(ModelMessages {
permissions: Some(PermissionMessages {
approved_command_prefix_saved: catalog_heading.map(str::to_owned),
approved_command_prefix_saved: catalog_heading.map(Into::into),
..Default::default()
}),
approvals: full_approval_override.then(|| ApprovalMessages {
on_request: Some("Full catalog approval message".to_string()),
on_request: Some("Full catalog approval message".into()),
..Default::default()
}),
..Default::default()
@@ -42,7 +42,7 @@ fn managed_model(slug: &str, instructions: &str) -> ModelInfo {
.model_messages
.as_mut()
.expect("model messages")
.instructions_template = Some(instructions.to_string());
.instructions_template = Some(instructions.into());
model
}
@@ -47,7 +47,7 @@ async fn catalog_permission_message_loaded_from_remote_models_is_sent(
tools: None,
instructions_template: None,
approvals: catalog_approval.map(|on_request| ApprovalMessages {
on_request: Some(on_request.to_string()),
on_request: Some(on_request.into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -59,8 +59,8 @@ async fn catalog_permission_message_loaded_from_remote_models_is_sent(
permissions: Some(PermissionMessages {
danger_full_access: None,
workspace_write: None,
read_only: Some("remote catalog permissions: {{ network_access }}".to_string()),
approved_prefixes: Some(prefix_template.to_string()),
read_only: Some("remote catalog permissions: {{ network_access }}".into()),
approved_prefixes: Some(prefix_template.into()),
..PermissionMessages::default()
}),
multi_agent: None,
+2 -2
View File
@@ -8960,8 +8960,8 @@ async fn code_mode_search_normalizes_and_calls_deferred_dynamic_tools(
);
tools.functions_namespace_functions_description_prefixes =
Some(std::collections::BTreeMap::from([(
"hidden-dynamic-tool".to_string(),
"Function guidance.".to_string(),
"hidden-dynamic-tool".into(),
"Function guidance.".into(),
)]));
})
.with_config(|config| {
@@ -91,8 +91,8 @@ fn model_with_collaboration_messages(
});
model_messages.collaboration_modes = Some(CollaborationModeMessages {
initial: None,
default: default.map(str::to_string),
plan: plan.map(str::to_string),
default: default.map(Into::into),
plan: plan.map(Into::into),
});
model
}
@@ -270,7 +270,7 @@ async fn switching_models_suppresses_and_restores_saved_prefix_approvals() -> Re
let server = start_mock_server().await;
let messages = |heading: &str| ModelMessages {
permissions: Some(PermissionMessages {
approved_command_prefix_saved: Some(heading.to_string()),
approved_command_prefix_saved: Some(heading.into()),
..Default::default()
}),
..Default::default()
@@ -427,7 +427,7 @@ async fn explicit_guardian_provider_is_separate(
.expect("catalog policy"),
);
messages.guardian_v2 = Some(GuardianV2ModelConfig {
classifier_instructions: Some("Trusted Guardian classifier instructions.".to_owned()),
classifier_instructions: Some("Trusted Guardian classifier instructions.".into()),
reasoning_effort: Some(ReasoningEffort::Minimal),
review_threshold_basis_points: Some(guardian_threshold),
..Default::default()
@@ -441,7 +441,7 @@ async fn explicit_guardian_provider_is_separate(
.auto_review
.as_mut()
.expect("classifier policy")
.policy = Some("Classifier-only policy that must not authorize actions.".to_owned());
.policy = Some("Classifier-only policy that must not authorize actions.".into());
reviewer_model.slug = reviewer_model_name.to_owned();
models.push(reviewer_model);
}
@@ -485,9 +485,7 @@ review_threshold = ACTOR_THRESHOLD
.expect("catalog policy"),
);
messages.guardian_v2 = Some(GuardianV2ModelConfig {
classifier_instructions: Some(
"Actor catalog classifier instructions.".to_owned(),
),
classifier_instructions: Some("Actor catalog classifier instructions.".into()),
reasoning_effort: Some(ReasoningEffort::High),
review_threshold_basis_points: Some(5_000 - guardian_threshold),
..Default::default()
@@ -256,8 +256,8 @@ async fn review_respects_complete_context_budget(
.as_mut()
.expect("bundled reviewer model messages")
.auto_review = Some(AutoReviewMessages {
policy: Some("Review actions against user authorization.".to_owned()),
policy_template: Some("{{ tenant_policy_config }}".to_owned()),
policy: Some("Review actions against user authorization.".into()),
policy_template: Some("{{ tenant_policy_config }}".into()),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
@@ -291,7 +291,7 @@ async fn server_initiated_mcp_elicitation_can_require_synchronous_auto_review(
policy: None,
policy_template: None,
node_repl_policy: None,
rejection_instructions: Some(REJECTION_INSTRUCTIONS.to_string()),
rejection_instructions: Some(REJECTION_INSTRUCTIONS.into()),
timeout_instructions: None,
});
})
+10 -10
View File
@@ -658,9 +658,9 @@ async fn guardian_review_recovers_after_compaction(
enabled: !with_parent_checkpoint,
use_history_notes_extension: true,
reminder_threshold_tokens: 6_144,
reminder_message_template: "{n_remaining} tokens remain.".to_string(),
guidance_message: "Save state before resetting context.".to_string(),
auto_compact_fallback_prompt: "Save important state.".to_string(),
reminder_message_template: "{n_remaining} tokens remain.".into(),
guidance_message: "Save state before resetting context.".into(),
auto_compact_fallback_prompt: "Save important state.".into(),
auto_compact_fallback_buffer_tokens: 16_384,
});
})
@@ -1404,7 +1404,7 @@ async fn guardian_node_repl_policy_follows_production_approval_path(
.auto_review = Some(AutoReviewMessages {
policy: None,
policy_template: None,
node_repl_policy: node_repl_policy.map(str::to_string),
node_repl_policy: node_repl_policy.map(Into::into),
rejection_instructions: None,
timeout_instructions: None,
});
@@ -1419,7 +1419,7 @@ async fn guardian_node_repl_policy_follows_production_approval_path(
.auto_review = Some(AutoReviewMessages {
policy: None,
policy_template: None,
node_repl_policy: Some("Acting-model REPL policy.".to_string()),
node_repl_policy: Some("Acting-model REPL policy.".into()),
rejection_instructions: None,
timeout_instructions: None,
});
@@ -1930,8 +1930,8 @@ async fn guardian_reviews_delayed_and_new_actions_after_catalog_refresh() -> Res
.as_mut()
.unwrap()
.auto_review = Some(AutoReviewMessages {
policy: Some("refreshed policy".to_string()),
policy_template: Some("refreshed template: {{ tenant_policy_config }}".to_string()),
policy: Some("refreshed policy".into()),
policy_template: Some("refreshed template: {{ tenant_policy_config }}".into()),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
@@ -2547,7 +2547,7 @@ async fn guardian_denial_rejects_tool_call_with_rationale(
policy: None,
policy_template: None,
node_repl_policy: None,
rejection_instructions: Some("Reviewer-only rejection instructions.".to_string()),
rejection_instructions: Some("Reviewer-only rejection instructions.".into()),
timeout_instructions: None,
});
})
@@ -2561,7 +2561,7 @@ async fn guardian_denial_rejects_tool_call_with_rationale(
policy: None,
policy_template: None,
node_repl_policy: None,
rejection_instructions: rejection_instructions.map(str::to_string),
rejection_instructions: rejection_instructions.map(Into::into),
timeout_instructions: None,
});
})
@@ -2890,7 +2890,7 @@ async fn guardian_timeout_rejects_tool_call_with_acting_model_instructions(
policy_template: None,
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: timeout_instructions.map(str::to_string),
timeout_instructions: timeout_instructions.map(Into::into),
});
})
.with_config(|config| {
+1 -1
View File
@@ -412,7 +412,7 @@ async fn model_change_respects_personality_opt_out_updates(
.expect("test model should have instruction metadata")
.instructions_template = Some(
"Catalog instructions.\n# Personality\nCatalog style.\n# Rules\nKeep the rules."
.to_string(),
.into(),
);
})
.with_model("gpt-5.5")
@@ -706,7 +706,7 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo {
content_filter_guidance: None,
persistent_instructions: None,
tools: None,
instructions_template: Some("base instructions".to_string()),
instructions_template: Some("base instructions".into()),
approvals: None,
collaboration_modes: None,
auto_review: None,
@@ -54,13 +54,13 @@ fn set_multi_agent_mode(
if let Some(model_messages) = model_info.model_messages.as_mut() {
model_messages.multi_agent = Some(MultiAgentMessages {
role: root_role.map(|root| MultiAgentRoleMessages {
root: Some(root.to_string()),
root: Some(root.into()),
subagent: None,
}),
mode: Some(MultiAgentModeMessages {
explicit: Some(explicit.to_string()),
proactive: proactive.map(str::to_string),
hint_text: hint_text.map(str::to_string),
explicit: Some(explicit.into()),
proactive: proactive.map(Into::into),
hint_text: hint_text.map(Into::into),
}),
});
}
@@ -3350,10 +3350,8 @@ pub(super) fn guardian_parent_catalog() -> ModelsResponse {
.as_mut()
.expect("model messages")
.auto_review = Some(AutoReviewMessages {
policy: Some("captured policy".to_string()),
policy_template: Some(
"captured template: {{ tenant_policy_config }}".to_string(),
),
policy: Some("captured policy".into()),
policy_template: Some("captured template: {{ tenant_policy_config }}".into()),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
@@ -90,8 +90,8 @@ fn model_with_approval_messages(
let mut model = model_info_from_slug(slug);
model.model_messages = Some(ModelMessages {
approvals: Some(ApprovalMessages {
on_request: Some(on_request.to_string()),
on_request_auto_review: Some(on_request_auto_review.to_string()),
on_request: Some(on_request.into()),
on_request_auto_review: Some(on_request_auto_review.into()),
..Default::default()
}),
..Default::default()
@@ -189,9 +189,9 @@ async fn catalog_approval_instruction_parts_are_sent_in_initial_permissions(
.await;
let model_slug = "catalog-approvals-model";
let heading =
|value: &str| (!matches!(case, ApprovalInstructionCase::Absent)).then(|| value.to_string());
|value: &str| (!matches!(case, ApprovalInstructionCase::Absent)).then(|| value.into());
let sandbox = PermissionMessages {
read_only: Some(String::new()),
read_only: Some("".into()),
..Default::default()
};
let mut model = model_info_from_slug(model_slug);
@@ -199,7 +199,7 @@ async fn catalog_approval_instruction_parts_are_sent_in_initial_permissions(
model.model_messages = Some(ModelMessages {
approvals: Some(ApprovalMessages {
on_request_auto_review: matches!(case, ApprovalInstructionCase::Complete)
.then(|| "Complete catalog approval instructions".to_string()),
.then(|| "Complete catalog approval instructions".into()),
request_permissions: heading("Catalog permission tool"),
auto_review_suffix: heading("Catalog automatic review"),
..Default::default()
@@ -342,7 +342,7 @@ async fn catalog_non_on_request_approval_messages_are_sent_in_initial_permission
(
AskForApproval::Never,
ApprovalMessages {
never: Some("catalog never approval instructions".to_string()),
never: Some("catalog never approval instructions".into()),
..Default::default()
},
"catalog never approval instructions",
@@ -351,7 +351,7 @@ async fn catalog_non_on_request_approval_messages_are_sent_in_initial_permission
(
AskForApproval::UnlessTrusted,
ApprovalMessages {
unless_trusted: Some("catalog unless-trusted approval instructions".to_string()),
unless_trusted: Some("catalog unless-trusted approval instructions".into()),
..Default::default()
},
"catalog unless-trusted approval instructions",
@@ -412,7 +412,7 @@ async fn catalog_permission_message_is_sent_initially_and_after_model_change() -
PermissionMessages {
danger_full_access: None,
workspace_write: None,
read_only: Some("model A permissions: {{ network_access }}".to_string()),
read_only: Some("model A permissions: {{ network_access }}".into()),
approved_prefixes: None,
writable_root: None,
writable_roots: None,
@@ -424,7 +424,7 @@ async fn catalog_permission_message_is_sent_initially_and_after_model_change() -
PermissionMessages {
danger_full_access: None,
workspace_write: None,
read_only: Some("model B permissions: {{ network_access }}".to_string()),
read_only: Some("model B permissions: {{ network_access }}".into()),
approved_prefixes: None,
writable_root: None,
writable_roots: None,
@@ -498,11 +498,11 @@ async fn empty_catalog_permission_message_with_never_approval(
let mut model = model_info_from_slug(model_slug);
model.model_messages = Some(ModelMessages {
permissions: Some(PermissionMessages {
read_only: Some(String::new()),
read_only: Some("".into()),
..Default::default()
}),
approvals: Some(ApprovalMessages {
never: never_approval.map(str::to_owned),
never: never_approval.map(Into::into),
..Default::default()
}),
..Default::default()
@@ -937,7 +937,7 @@ const WORKSPACE_PERMISSIONS_PREFIX: &str = concat!(
#[test_case(
1,
PermissionMessages {
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".to_string()),
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".into()),
..Default::default()
},
" The writable root is {roots}.",
@@ -954,9 +954,9 @@ const WORKSPACE_PERMISSIONS_PREFIX: &str = concat!(
#[test_case(
1,
PermissionMessages {
writable_root: Some("Catalog single: {{ roots }}!".to_string()),
writable_roots: Some("Catalog plural: {{ roots }}!".to_string()),
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".to_string()),
writable_root: Some("Catalog single: {{ roots }}!".into()),
writable_roots: Some("Catalog plural: {{ roots }}!".into()),
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".into()),
..Default::default()
},
"Catalog single: {roots}!",
@@ -966,9 +966,9 @@ const WORKSPACE_PERMISSIONS_PREFIX: &str = concat!(
#[test_case(
2,
PermissionMessages {
writable_root: Some("Catalog single: {{ roots }}!".to_string()),
writable_roots: Some("Catalog plural: {{ roots }}!".to_string()),
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".to_string()),
writable_root: Some("Catalog single: {{ roots }}!".into()),
writable_roots: Some("Catalog plural: {{ roots }}!".into()),
denied_reads: Some("## Catalog denied reads\n{{ denied_reads }}\nCatalog footer.".into()),
..Default::default()
},
"Catalog plural: {roots}!",
+2 -2
View File
@@ -66,7 +66,7 @@ async fn config_personality_controls_baked_personality_section(
let mut builder = test_codex()
.with_model_info_override("gpt-5.5", |model_info| {
if let Some(model_messages) = model_info.model_messages.as_mut() {
model_messages.instructions_template = Some("Base instructions\n# Personality\nBaked personality\n## Writing Style\nNested writing style\n# General\nGeneral instructions".to_string());
model_messages.instructions_template = Some("Base instructions\n# Personality\nBaked personality\n## Writing Style\nNested writing style\n# General\nGeneral instructions".into());
}
})
.with_pre_build_hook(move |home| {
@@ -116,7 +116,7 @@ async fn config_personality_none_preserves_explicit_base_instructions(
let mut builder = test_codex()
.with_model_info_override("gpt-5.5", |model_info| {
if let Some(model_messages) = model_info.model_messages.as_mut() {
model_messages.instructions_template = Some("Base instructions\n# Personality\nBaked personality\n## Writing Style\nNested writing style\n# General\nGeneral instructions".to_string());
model_messages.instructions_template = Some("Base instructions\n# Personality\nBaked personality\n## Writing Style\nNested writing style\n# General\nGeneral instructions".into());
}
})
.with_pre_build_hook(move |home| {
+1 -1
View File
@@ -151,7 +151,7 @@ async fn prompt_tools_are_consistent_across_requests(
.model_messages
.as_mut()
.expect("bundled model messages")
.instructions_template = Some(MODEL_BASE_INSTRUCTIONS.to_string());
.instructions_template = Some(MODEL_BASE_INSTRUCTIONS.into());
// Supply model instructions without making them an explicit config catalog override.
let models_manager = Arc::new(StaticModelsManager::new(
/*auth_manager*/ None,
+7 -7
View File
@@ -330,7 +330,7 @@ async fn disabled_update_plan_preserves_custom_catalog_instructions() -> Result<
.model_messages
.as_mut()
.expect("model prompt templates");
messages.instructions_template = Some(INSTRUCTIONS.to_string());
messages.instructions_template = Some(INSTRUCTIONS.into());
let test = test_codex()
.with_model("gpt-5.5")
.with_config(move |config| {
@@ -401,7 +401,7 @@ async fn remote_models_get_model_info_uses_longest_matching_prefix() -> Result<(
let specific = ModelInfo {
display_name: "GPT 5.3 Codex".to_string(),
model_messages: Some(ModelMessages {
instructions_template: Some("use specific prefix".to_string()),
instructions_template: Some("use specific prefix".into()),
..Default::default()
}),
..specific
@@ -409,7 +409,7 @@ async fn remote_models_get_model_info_uses_longest_matching_prefix() -> Result<(
let generic = ModelInfo {
display_name: "GPT 5.3".to_string(),
model_messages: Some(ModelMessages {
instructions_template: Some("use generic prefix".to_string()),
instructions_template: Some("use generic prefix".into()),
..Default::default()
}),
..generic
@@ -675,8 +675,8 @@ async fn remote_models_long_model_slug_is_sent_with_supported_reasoning(
];
remote_model.default_reasoning_summary = ReasoningSummary::Detailed;
remote_model.model_messages = Some(ModelMessages {
persistent_instructions: catalog_instructions.map(str::to_string),
instructions_template: Some(base_instructions.to_string()),
persistent_instructions: catalog_instructions.map(Into::into),
instructions_template: Some(base_instructions.into()),
..Default::default()
});
mount_models_once(
@@ -1120,7 +1120,7 @@ async fn remote_models_apply_legacy_instructions(auth: CodexAuth) -> Result<()>
available_access_programs: None,
upgrade: None,
model_messages: Some(ModelMessages {
instructions_template: Some(remote_instructions.to_string()),
instructions_template: Some(remote_instructions.into()),
..Default::default()
}),
include_skills_usage_instructions: false,
@@ -1789,7 +1789,7 @@ async fn model_catalog_url_supplies_conversation_model_and_instructions() -> Res
.model_messages
.as_mut()
.expect("fallback instructions")
.instructions_template = Some(instructions.to_string());
.instructions_template = Some(instructions.into());
let catalog = ModelsResponse {
models: vec![model],
};
@@ -160,7 +160,7 @@ async fn persistent_async_message_guidance_follows_tool_availability(
messages.persistent_instructions = None;
messages.tools = Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some("Catalog async message description.".to_string()),
description: Some("Catalog async message description.".into()),
..Default::default()
}),
..Default::default()
@@ -455,7 +455,7 @@ async fn freeform_async_message_emits_an_item_without_ending_the_turn(
.expect("model instruction metadata")
.tools = Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some("Questions only.".to_string()),
description: Some("Questions only.".into()),
..Default::default()
}),
..Default::default()
@@ -574,12 +574,12 @@ const CATALOG_ASYNC_PARAMETERS: &str = r#"{
#[test_case(None, "request_user_input_async", None; "current_catalog_name")]
#[test_case(Some(ToolMessages::default()), "send_user_message_async", None; "missing_tool")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage::default()), ..Default::default() }), "send_user_message_async", None; "missing_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".to_string()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "catalog_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some(String::new()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "empty_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { parameters: Some(CATALOG_ASYNC_PARAMETERS.to_string()), ..Default::default() }), ..Default::default() }), "send_user_message_async", Some(CATALOG_ASYNC_PARAMETERS); "catalog_parameters")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".to_string()), parameters: Some(CATALOG_ASYNC_PARAMETERS.to_string()) }), ..Default::default() }), "request_user_input_async", Some(CATALOG_ASYNC_PARAMETERS); "catalog_description_and_parameters")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { parameters: Some(String::new()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "empty_parameters_fallback")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".to_string()), parameters: Some(r#"{"type":"object","properties":{"questions":{"type":"unsupported"}}}"#.to_string()) }), ..Default::default() }), "send_user_message_async", None; "invalid_parameters_preserve_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".into()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "catalog_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("".into()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "empty_description")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { parameters: Some(CATALOG_ASYNC_PARAMETERS.into()), ..Default::default() }), ..Default::default() }), "send_user_message_async", Some(CATALOG_ASYNC_PARAMETERS); "catalog_parameters")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".into()), parameters: Some(CATALOG_ASYNC_PARAMETERS.into()) }), ..Default::default() }), "request_user_input_async", Some(CATALOG_ASYNC_PARAMETERS); "catalog_description_and_parameters")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { parameters: Some("".into()), ..Default::default() }), ..Default::default() }), "send_user_message_async", None; "empty_parameters_fallback")]
#[test_case(Some(ToolMessages { send_user_message_async: Some(ToolMessage { description: Some("Catalog async message description.".into()), parameters: Some(r#"{"type":"object","properties":{"questions":{"type":"unsupported"}}}"#.into()) }), ..Default::default() }), "send_user_message_async", None; "invalid_parameters_preserve_description")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn request_user_input_async_emits_item_and_does_not_end_the_turn(
tool_messages: Option<ToolMessages>,
+1 -1
View File
@@ -183,7 +183,7 @@ async fn resume_switches_models_preserves_base_instructions() -> Result<()> {
model
.model_messages
.get_or_insert_default()
.instructions_template = Some(legacy_instructions.to_string());
.instructions_template = Some(legacy_instructions.into());
})
.with_config(|config| {
config.personality = Some(Personality::Pragmatic);
+3 -3
View File
@@ -631,9 +631,9 @@ async fn review_uses_updated_turn_permissions_and_approval_policy() {
enabled: false,
use_history_notes_extension: false,
reminder_threshold_tokens: 6_144,
reminder_message_template: "Reminder: {n_remaining} tokens remain.".to_string(),
guidance_message: guidance_message.to_string(),
auto_compact_fallback_prompt: "Preserve the important context.".to_string(),
reminder_message_template: "Reminder: {n_remaining} tokens remain.".into(),
guidance_message: guidance_message.into(),
auto_compact_fallback_prompt: "Preserve the important context.".into(),
auto_compact_fallback_buffer_tokens: 16_384,
}
}
+2 -2
View File
@@ -2561,8 +2561,8 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta(
.as_mut()
.expect("bundled model messages");
messages.confirmation_policies = Some(ConfirmationPolicies {
browser_use: browser_policy.map(str::to_owned),
computer_use: computer_policy.map(str::to_owned),
browser_use: browser_policy.map(Into::into),
computer_use: computer_policy.map(Into::into),
});
let models_mock = mount_models_once(&server, models).await;
+8 -8
View File
@@ -1189,7 +1189,7 @@ async fn astra_asks_an_async_question_and_receives_the_answer_while_working() ->
.tools
.get_or_insert_with(Default::default)
.send_user_message_async = Some(ToolMessage {
parameters: Some(catalog_parameters),
parameters: Some(catalog_parameters.into()),
..Default::default()
});
config.model_provider.base_url = Some(base_url);
@@ -2940,11 +2940,11 @@ async fn code_mode_catalog_messages(ranked_search: bool) -> Result<()> {
model.model_messages.as_mut().expect("model messages").tools
.get_or_insert_with(Default::default).code_mode = Some(CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("Catalog exec instructions. Default yield: {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}".to_string()),
description: Some("Catalog exec instructions. Default yield: {{ default_exec_yield_time_ms }} ms.\n{{ image_helper }}".into()),
..Default::default()
}),
wait: Some(ToolMessage {
description: Some("Catalog wait instructions: resume the yielded cell.".to_string()),
description: Some("Catalog wait instructions: resume the yielded cell.".into()),
parameters: Some(json!({
"type": "object",
"properties": {
@@ -2955,10 +2955,10 @@ async fn code_mode_catalog_messages(ranked_search: bool) -> Result<()> {
},
"required": ["cell_id"],
"additionalProperties": false
}).to_string()),
}).to_string().into()),
}),
deferred_nested_tools_guidance: Some("Catalog discovery: find nested tools by name and description in ALL_TOOLS.".to_string()),
mcp_typescript_preamble: Some("type CallToolResult<T = unknown> = { content: unknown[]; structuredContent?: T; isError?: boolean };".to_string()),
deferred_nested_tools_guidance: Some("Catalog discovery: find nested tools by name and description in ALL_TOOLS.".into()),
mcp_typescript_preamble: Some("type CallToolResult<T = unknown> = { content: unknown[]; structuredContent?: T; isError?: boolean };".into()),
});
})
.build_with_auto_env(&server)
@@ -4504,8 +4504,8 @@ async fn astra_async_compaction_preserves_exec_catalog(change: ExecCatalogRefres
.code_mode
.get_or_insert_default();
messages.exec.get_or_insert_default().description =
Some("Previous exec instructions.".to_string());
messages.mcp_typescript_preamble = Some("type PreviousResult = string;".to_string());
Some("Previous exec instructions.".into());
messages.mcp_typescript_preamble = Some("type PreviousResult = string;".into());
}
}
mount_models_once_with_etag(&model_server, catalog.clone(), "\"exec-mode-v2\"").await;
@@ -46,8 +46,8 @@ async fn catalog_approval_headings_follow_selected_model() -> Result<()> {
model.use_responses_lite = true;
model.model_messages = Some(ModelMessages {
approvals: Some(ApprovalMessages {
request_permissions: Some(format!("# {label} permission requests")),
auto_review_suffix: Some(format!("# {label} automatic review")),
request_permissions: Some(format!("# {label} permission requests").into()),
auto_review_suffix: Some(format!("# {label} automatic review").into()),
..Default::default()
}),
..Default::default()
@@ -16,9 +16,8 @@ async fn content_filter_guidance_is_appended_after_each_block() -> Result<()> {
model
.model_messages
.get_or_insert_default()
.content_filter_guidance = Some(
"Your previous response was blocked. Offer a permitted alternative.".to_string(),
);
.content_filter_guidance =
Some("Your previous response was blocked. Offer a permitted alternative.".into());
})
.build_with_auto_env(&server)
.await?;
@@ -7,8 +7,8 @@ use pretty_assertions::assert_eq;
fn configure_tools(model: &mut ModelInfo, description: &str) {
let message = ToolMessage {
description: Some(description.to_string()),
parameters: Some(r#"{"type":"object","properties":{},"additionalProperties":false,"description":"Catalog arguments."}"#.to_string()),
description: Some(description.into()),
parameters: Some(r#"{"type":"object","properties":{},"additionalProperties":false,"description":"Catalog arguments."}"#.into()),
};
model
.model_messages
@@ -88,8 +88,8 @@ async fn changed_sections_and_entries_append_without_repeating_the_catalog(
.tools
.get_or_insert_default()
.incremental_tools = Some(IncrementalToolMessages {
exec_tools_update_hint: Some(hint.to_string()),
exec_tools_removed_definitions_header: Some(header.to_string()),
exec_tools_update_hint: Some(hint.into()),
exec_tools_removed_definitions_header: Some(header.into()),
..Default::default()
});
}
@@ -91,9 +91,7 @@ async fn async_elastic_classifier_request_history() -> anyhow::Result<()> {
.with_model_info_override("gpt-5.5", |model| {
model.guardian = None;
model.model_messages.as_mut().unwrap().guardian_v2 = Some(GuardianV2ModelConfig {
classifier_instructions: Some(
"Classify risk using the supplied evidence.".to_owned(),
),
classifier_instructions: Some("Classify risk using the supplied evidence.".into()),
transcript: Some(GuardianV2TranscriptModelConfig {
max_message_entry_tokens: Some(FIXED_ENTRY_TOKENS),
..Default::default()
@@ -120,7 +120,7 @@ guardian_extra_policy = "Draft reminders without sending them."
.auto_review
.as_mut()
.expect("reviewer policy")
.policy_template = Some(format!("{template}\n{catalog_instruction}"));
.policy_template = Some(format!("{template}\n{catalog_instruction}").into());
})
.with_model("gpt-5.5")
.build_with_auto_env(&server)
@@ -213,7 +213,7 @@ async fn incremental_tools_append_changed_catalog_without_rewriting_history(
.as_mut()
.expect("model messages")
.instructions_template =
Some("Use the available tools to help the user.".to_string());
Some("Use the available tools to help the user.".into());
}
})
.with_config(move |config| {
@@ -248,7 +248,7 @@ async fn incremental_tools_append_changed_catalog_without_rewriting_history(
.model_messages
.as_mut()
.expect("model messages")
.instructions_template = Some("Review results before responding.".to_string());
.instructions_template = Some("Review results before responding.".into());
}
updated
.model_messages
@@ -257,7 +257,7 @@ async fn incremental_tools_append_changed_catalog_without_rewriting_history(
.get_or_insert_default()
.code_mode = Some(CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some("Updated execution instructions.".to_string()),
description: Some("Updated execution instructions.".into()),
..Default::default()
}),
..Default::default()
@@ -504,13 +504,12 @@ async fn tool_removal_appends_a_standalone_notice_without_rewriting_history(
.get_or_insert_default()
.incremental_tools = Some(IncrementalToolMessages {
tool_update_hint: Some(
"Catalog update: retain earlier tools unless explicitly removed."
.to_string(),
"Catalog update: retain earlier tools unless explicitly removed.".into(),
),
removed_tools_header: Some("Unavailable tools:".to_string()),
removed_namespaces_header: Some("Unavailable namespaces:".to_string()),
namespace_instructions_prefix: Some("Catalog {name}: ".to_string()),
namespace_instructions_cleared: Some("Cleared {name}.".to_string()),
removed_tools_header: Some("Unavailable tools:".into()),
removed_namespaces_header: Some("Unavailable namespaces:".into()),
namespace_instructions_prefix: Some("Catalog {name}: ".into()),
namespace_instructions_cleared: Some("Cleared {name}.".into()),
..Default::default()
});
}
@@ -193,7 +193,7 @@ async fn catalog_refresh_replaces_instructions_and_compaction_installs_latest_ba
model
.model_messages
.get_or_insert_default()
.instructions_template = Some("Help the user complete their task.".to_string());
.instructions_template = Some("Help the user complete their task.".into());
responses::mount_models_once_with_etag(
&server,
ModelsResponse {
@@ -239,7 +239,7 @@ async fn catalog_refresh_replaces_instructions_and_compaction_installs_latest_ba
model
.model_messages
.get_or_insert_default()
.instructions_template = Some("Check your work before responding.".to_string());
.instructions_template = Some("Check your work before responding.".into());
responses::mount_models_once_with_etag(
&server,
ModelsResponse {
@@ -310,7 +310,7 @@ async fn protected_model_settings_use_the_proposed_permissions(
let messages = protected.model_messages.as_mut().expect("model messages");
messages.approvals = Some(ApprovalMessages {
on_request: None,
on_request_auto_review: Some(REVIEW_INSTRUCTIONS.to_string()),
on_request_auto_review: Some(REVIEW_INSTRUCTIONS.into()),
never: None,
unless_trusted: None,
granular: None,
@@ -319,7 +319,7 @@ async fn protected_model_settings_use_the_proposed_permissions(
messages.permissions = Some(PermissionMessages {
danger_full_access: None,
workspace_write: None,
read_only: Some(PERMISSION_INSTRUCTIONS.to_string()),
read_only: Some(PERMISSION_INSTRUCTIONS.into()),
approved_prefixes: None,
..PermissionMessages::default()
});
+31 -26
View File
@@ -1085,25 +1085,25 @@ async fn active_model_switch_updates_core_context_from_captured_settings(
model.max_context_window = None;
}
let messages = model.model_messages.as_mut().expect("model messages");
messages.instructions_template = Some(format!("Instructions for {slug}."));
messages.instructions_template = Some(format!("Instructions for {slug}.").into());
messages.collaboration_modes = Some(CollaborationModeMessages {
initial: None,
default: None,
plan: Some(format!("Plan collaboration for {slug}.")),
plan: Some(format!("Plan collaboration for {slug}.").into()),
});
messages.multi_agent = Some(MultiAgentMessages {
role: Some(MultiAgentRoleMessages {
root: Some(format!("Root role for {slug}.")),
root: Some(format!("Root role for {slug}.").into()),
subagent: None,
}),
mode: Some(MultiAgentModeMessages {
explicit: Some(format!("Delegation policy for {slug}.")),
explicit: Some(format!("Delegation policy for {slug}.").into()),
proactive: None,
hint_text: None,
}),
});
messages.approvals = Some(ApprovalMessages {
on_request: Some(format!("Approval instructions for {slug}.")),
on_request: Some(format!("Approval instructions for {slug}.").into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -1117,9 +1117,9 @@ async fn active_model_switch_updates_core_context_from_captured_settings(
reminder_threshold_tokens: if initial_model { 8_000 } else { 2_000 },
reminder_message_template: format!(
"Reminder for {slug}: {{n_remaining}} tokens remain."
),
guidance_message: format!("Use {slug} token-budget guidance."),
auto_compact_fallback_prompt: format!("Save {slug} state before rollover."),
).into(),
guidance_message: format!("Use {slug} token-budget guidance.").into(),
auto_compact_fallback_prompt: format!("Save {slug} state before rollover.").into(),
auto_compact_fallback_buffer_tokens: if initial_model {
16_000
} else {
@@ -1430,20 +1430,20 @@ async fn mcp_confirmation_policy_follows_step_model_changes() -> Result<()> {
.expect("bundled model messages");
messages.confirmation_policies = match model.slug.as_str() {
MODEL_A => Some(ConfirmationPolicies {
browser_use: Some(BROWSER_POLICY_A.to_string()),
computer_use: Some(COMPUTER_POLICY_A.to_string()),
browser_use: Some(BROWSER_POLICY_A.into()),
computer_use: Some(COMPUTER_POLICY_A.into()),
}),
MODEL_B => Some(ConfirmationPolicies {
browser_use: Some(BROWSER_POLICY_B.to_string()),
computer_use: Some(COMPUTER_POLICY_B.to_string()),
browser_use: Some(BROWSER_POLICY_B.into()),
computer_use: Some(COMPUTER_POLICY_B.into()),
}),
BROWSER_ONLY_MODEL => Some(ConfirmationPolicies {
browser_use: Some(BROWSER_POLICY_B.to_string()),
browser_use: Some(BROWSER_POLICY_B.into()),
computer_use: None,
}),
COMPUTER_ONLY_MODEL => Some(ConfirmationPolicies {
browser_use: None,
computer_use: Some(COMPUTER_POLICY_B.to_string()),
computer_use: Some(COMPUTER_POLICY_B.into()),
}),
MODEL_C => None,
_ => unreachable!("unexpected test model"),
@@ -2173,8 +2173,7 @@ async fn model_activation_uses_destination_metadata_defaults(
.model_messages
.as_mut()
.expect("model instruction metadata")
.instructions_template =
Some("Destination model instructions.".to_string());
.instructions_template = Some("Destination model instructions.".into());
}
}
})
@@ -2331,8 +2330,8 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
.push("send_user_message_async".to_string());
let tool_message = |name| {
Some(ToolMessage {
description: Some(format!("{name} description for {}.", model.slug)),
parameters: Some(parameters(&model.slug).to_string()),
description: Some(format!("{name} description for {}.", model.slug).into()),
parameters: Some(parameters(&model.slug).to_string().into()),
})
};
model
@@ -2341,8 +2340,10 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
.expect("model instruction metadata")
.tools = Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(format!("Async message description for {}.", model.slug)),
parameters: Some(async_parameters(&model.slug).to_string()),
description: Some(
format!("Async message description for {}.", model.slug).into(),
),
parameters: Some(async_parameters(&model.slug).to_string().into()),
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: tool_message("spawn_agent"),
@@ -2356,12 +2357,16 @@ async fn tool_messages_follow_mid_turn_model_changes() -> Result<()> {
}),
code_mode: Some(CodeModeToolMessages {
exec: Some(ToolMessage {
description: Some(format!("Exec description for {}.", model.slug)),
description: Some(
format!("Exec description for {}.", model.slug).into(),
),
..Default::default()
}),
wait: Some(ToolMessage {
description: Some(format!("Wait description for {}.", model.slug)),
parameters: Some(wait_parameters(&model.slug).to_string()),
description: Some(
format!("Wait description for {}.", model.slug).into(),
),
parameters: Some(wait_parameters(&model.slug).to_string().into()),
}),
..Default::default()
}),
@@ -2477,7 +2482,7 @@ async fn persistent_instructions_follow_mid_turn_model_changes() -> Result<()> {
.as_mut()
.expect("model instruction metadata")
.persistent_instructions =
Some(format!("Persistent instructions for {}.", model.slug));
Some(format!("Persistent instructions for {}.", model.slug).into());
}
})
.build_with_auto_env(&server)
@@ -3182,8 +3187,8 @@ async fn captured_step_controls_mcp_resource_output() -> Result<()> {
.get_or_insert_with(Default::default)
.mcp_resources = Some(McpResourceToolMessages {
read_mcp_resource: Some(ToolMessage {
description: Some(format!("Read resource for {}.", model.slug)),
parameters: Some(parameters(&model.slug).to_string()),
description: Some(format!("Read resource for {}.", model.slug).into()),
parameters: Some(parameters(&model.slug).to_string().into()),
}),
..Default::default()
});
@@ -1646,8 +1646,8 @@ async fn spawned_full_history_v2_child_uses_model_precedence_without_dropping_co
.multi_agent
.get_or_insert_with(MultiAgentMessages::default);
multi_agent.role = Some(MultiAgentRoleMessages {
root: Some(format!("{model} root role.")),
subagent: Some(format!("{model} subagent role.")),
root: Some(format!("{model} root role.").into()),
subagent: Some(format!("{model} subagent role.").into()),
});
if matches!(
selection,
+8 -8
View File
@@ -73,9 +73,9 @@ fn model_token_budget_config() -> ModelTokenBudgetConfig {
enabled: false,
use_history_notes_extension: false,
reminder_threshold_tokens: 6_144,
reminder_message_template: "Model reminder: {n_remaining} tokens remain.".to_string(),
guidance_message: "Use the model-owned context-window guidance.".to_string(),
auto_compact_fallback_prompt: AUTO_COMPACT_FALLBACK_PROMPT.to_string(),
reminder_message_template: "Model reminder: {n_remaining} tokens remain.".into(),
guidance_message: "Use the model-owned context-window guidance.".into(),
auto_compact_fallback_prompt: AUTO_COMPACT_FALLBACK_PROMPT.into(),
auto_compact_fallback_buffer_tokens: 16_384,
}
}
@@ -579,7 +579,7 @@ async fn token_budget_defaults_follow_the_active_model(activation: Feature) -> R
.with_model_info_override("gpt-5.2", |model_info| {
model_info.supports_experimental_context = true;
let mut defaults = model_token_budget_config();
defaults.guidance_message = "Use first-model context-window guidance.".to_string();
defaults.guidance_message = "Use first-model context-window guidance.".into();
model_info
.model_messages
.as_mut()
@@ -588,7 +588,7 @@ async fn token_budget_defaults_follow_the_active_model(activation: Feature) -> R
})
.with_model_info_override("gpt-5.4", |model_info| {
let mut defaults = model_token_budget_config();
defaults.guidance_message = "Use second-model context-window guidance.".to_string();
defaults.guidance_message = "Use second-model context-window guidance.".into();
model_info
.model_messages
.as_mut()
@@ -666,11 +666,11 @@ async fn token_budget_ignores_invalid_model_message_defaults() -> Result<()> {
let mut negative_fallback_buffer = model_token_budget_config();
negative_fallback_buffer.auto_compact_fallback_buffer_tokens = -1;
let mut oversized_reminder = model_token_budget_config();
oversized_reminder.reminder_message_template = "x".repeat(2_001);
oversized_reminder.reminder_message_template = "x".repeat(2_001).into();
let mut oversized_guidance = model_token_budget_config();
oversized_guidance.guidance_message = "x".repeat(2_001);
oversized_guidance.guidance_message = "x".repeat(2_001).into();
let mut oversized_fallback = model_token_budget_config();
oversized_fallback.auto_compact_fallback_prompt = "x".repeat(2_001);
oversized_fallback.auto_compact_fallback_prompt = "x".repeat(2_001).into();
for model_defaults in [
zero_reminder_threshold,
@@ -155,9 +155,12 @@ impl GuardianV2Config {
) -> Result<Self, String> {
let mut configured = self.local_overrides.clone();
if let Some(model_defaults) = model_defaults {
configured.classifier_instructions = configured
.classifier_instructions
.or_else(|| model_defaults.classifier_instructions.clone());
configured.classifier_instructions = configured.classifier_instructions.or_else(|| {
model_defaults
.classifier_instructions
.as_deref()
.map(str::to_owned)
});
configured.review_threshold = configured.review_threshold.or_else(|| {
model_defaults
.review_threshold_basis_points
@@ -134,7 +134,7 @@ fn model_prompt_and_explicit_threshold_precedence_are_preserved() {
ResolvedModelMessages::bundled().guardian_classifier_instructions(),
] {
let defaults = GuardianV2ModelConfig {
classifier_instructions: Some(prompt.to_owned()),
classifier_instructions: Some(prompt.into()),
..Default::default()
};
let resolved = builtin.with_model_defaults(Some(&defaults)).unwrap();
@@ -162,7 +162,7 @@ fn model_prompt_and_explicit_threshold_precedence_are_preserved() {
}
let model_threshold = GuardianV2ModelConfig {
classifier_instructions: Some("Model-owned instructions.".to_owned()),
classifier_instructions: Some("Model-owned instructions.".into()),
review_threshold_basis_points: Some(6_000),
..Default::default()
};
@@ -197,7 +197,7 @@ fn model_defaults_preserve_transcript_mode_and_matching_instructions() {
})
.unwrap()
.with_model_defaults(Some(&GuardianV2ModelConfig {
classifier_instructions: Some("Model-owned prompt.".to_owned()),
classifier_instructions: Some("Model-owned prompt.".into()),
..Default::default()
}))
.unwrap();
@@ -220,7 +220,7 @@ fn classifier_caps_preserve_complete_provenance_and_output_contract() {
let prompt = "Return a JSON action_risk score. ".repeat(200);
let policy = "Require approval for unsafe actions.";
let model_defaults = GuardianV2ModelConfig {
classifier_instructions: Some(prompt.clone()),
classifier_instructions: Some(prompt.as_str().into()),
max_classifier_instruction_tokens: Some(100),
..Default::default()
};
@@ -256,7 +256,7 @@ fn classifier_caps_preserve_complete_provenance_and_output_contract() {
fn model_runtime_settings_preserve_local_overrides() {
let prompt = "legacy instructions ".repeat(3_000);
let defaults = GuardianV2ModelConfig {
classifier_instructions: Some(prompt.clone()),
classifier_instructions: Some(prompt.as_str().into()),
max_classifier_instruction_tokens: Some(256),
max_tool_call_lag: Some(1),
async_classifier_conversation_token_limit: Some(80_000),
@@ -1123,7 +1123,7 @@ async fn sample_configured_conversation_history_with_delivery(
.auto_review
.as_mut()
.expect("reviewer model should have Guardian policy")
.policy = Some(TEST_CATALOG_GUARDIAN_POLICY.to_owned());
.policy = Some(TEST_CATALOG_GUARDIAN_POLICY.into());
})
.with_model("gpt-5.5")
.with_config(move |config| {
@@ -2340,12 +2340,12 @@ async fn contributor_uses_model_defaults_and_preserves_local_overrides() -> Resu
let model_defaults = GuardianV2ModelConfig {
async_classifier_mode: Some(codex_protocol::openai_models::AsyncClassifierMode::Snapshot),
async_classifier_conversation_token_limit: None,
classifier_instructions: Some("Use the experimental model-owned prompt.".to_owned()),
classifier_instructions: Some("Use the experimental model-owned prompt.".into()),
review_threshold_basis_points: Some(6_000),
max_tool_call_lag: Some(2),
reasoning_effort: Some(ReasoningEffort::Minimal),
transcript: Some(GuardianV2TranscriptModelConfig {
sources: Some(vec!["reasoning".to_owned()]),
sources: Some(vec!["reasoning".into()]),
include_images: Some(true),
max_message_entry_tokens: Some(128),
max_message_transcript_tokens: Some(256),
@@ -175,10 +175,10 @@ fn sparse_catalog_messages_preserve_defaults_and_explicit_empty_descriptions() {
};
tool.description.clear();
let messages = codex_protocol::openai_models::NotesToolMessages {
namespace_description: Some(String::new()),
namespace_description: Some("".into()),
read_file: Some(codex_protocol::openai_models::ToolMessage {
description: Some(String::new()),
parameters: Some(String::new()),
description: Some("".into()),
parameters: Some("".into()),
}),
..Default::default()
};
@@ -142,7 +142,7 @@ async fn installed_extension_exposes_and_invokes_history_notes_tools() -> TestRe
let step_store = ExtensionData::new("step-1");
let mut messages = NotesToolMessages {
read_file: Some(ToolMessage {
description: Some("Catalog read instructions".to_string()),
description: Some("Catalog read instructions".into()),
..Default::default()
}),
..Default::default()
@@ -155,7 +155,7 @@ async fn installed_extension_exposes_and_invokes_history_notes_tools() -> TestRe
.find(|tool| tool.tool_name() == ToolName::namespaced("notes", "read_file"))
.expect("notes.read_file should be exposed");
let captured_spec = captured_tool.spec();
messages.read_file.as_mut().expect("read_file").description = Some(String::new());
messages.read_file.as_mut().expect("read_file").description = Some("".into());
step_store.insert(messages);
let next_tools =
registry.tool_contributors()[0].tools_for_step(&session_store, &thread_store, &step_store);
+1
View File
@@ -19,6 +19,7 @@ chrono = { workspace = true, features = ["serde"] }
codex-protocol = { workspace = true }
codex-state = { workspace = true }
codex-tools = { workspace = true }
codex-utils-cached-str = { workspace = true }
futures = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
+2 -1
View File
@@ -34,6 +34,7 @@ use codex_tools::ToolExecutor;
use codex_tools::ToolExecutorFuture;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_utils_cached_str::CodexCachedStr;
use futures::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;
@@ -89,7 +90,7 @@ struct BoardTool {
board: Arc<dyn AgentMessageBoard>,
namespace: Option<String>,
namespace_description: String,
description: Option<String>,
description: Option<CodexCachedStr>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for BoardTool {
+1
View File
@@ -19,6 +19,7 @@ codex-login = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-prompts = { workspace = true }
codex-utils-cached-str = { workspace = true }
codex-utils-output-truncation = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
@@ -55,7 +55,7 @@ async fn api_key_discovery_flag_controls_fetches_and_cached_catalogs() {
expected_model
.model_messages
.get_or_insert_default()
.instructions_template = overrides.base_instructions.clone();
.instructions_template = overrides.base_instructions.as_deref().map(Into::into);
assert_eq!(
manager
.get_model_info(&bundled_model.slug, &overrides)
+9 -7
View File
@@ -8,6 +8,7 @@ use codex_protocol::openai_models::TruncationMode;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::openai_models::WebSearchToolType;
use codex_protocol::openai_models::default_input_modalities;
use codex_utils_cached_str::CodexCachedStr;
use crate::config::ModelsManagerConfig;
use codex_utils_output_truncation::approx_bytes_for_tokens;
@@ -45,20 +46,20 @@ pub fn with_config_overrides(mut model: ModelInfo, config: &ModelsManagerConfig)
if let Some(base_instructions) = &config.base_instructions {
let model_messages = model.model_messages.get_or_insert_default();
model_messages.instructions_template = Some(base_instructions.clone());
model_messages.instructions_template = Some(base_instructions.as_str().into());
} else if config.personality == Some(Personality::None)
&& let Some(instructions_template) = model
.model_messages
.as_mut()
.and_then(|messages| messages.instructions_template.as_mut())
{
*instructions_template = strip_personality_section(std::mem::take(instructions_template));
strip_personality_section(instructions_template);
}
model
}
fn strip_personality_section(mut instructions: String) -> String {
fn strip_personality_section(instructions: &mut CodexCachedStr) {
let mut section_start = None;
let mut section_end = None;
let mut offset = 0;
@@ -81,10 +82,11 @@ fn strip_personality_section(mut instructions: String) -> String {
if let Some(section_start) = section_start {
let section_end = section_end.unwrap_or(instructions.len());
instructions.replace_range(section_start..section_end, "");
let mut text = String::with_capacity(instructions.len() - (section_end - section_start));
text.push_str(&instructions[..section_start]);
text.push_str(&instructions[section_end..]);
*instructions = text.into();
}
instructions
}
fn is_h1_heading(line: &str) -> bool {
@@ -150,7 +152,7 @@ pub fn model_info_from_slug(slug: &str) -> ModelInfo {
fn local_model_messages() -> ModelMessages {
ModelMessages {
instructions_template: Some(BASE_INSTRUCTIONS.to_string()),
instructions_template: Some(BASE_INSTRUCTIONS.into()),
..Default::default()
}
}
+41 -41
View File
@@ -33,86 +33,86 @@ fn base_instruction_override_is_literal_and_preserves_catalog_messages() {
let async_message_description = "Catalog async message description.";
let mut model = model_info_from_slug("unknown-model");
let approvals = ApprovalMessages {
on_request: Some("user approvals".to_string()),
on_request_auto_review: Some("auto approvals".to_string()),
never: Some("never approvals".to_string()),
unless_trusted: Some("unless-trusted approvals".to_string()),
on_request: Some("user approvals".into()),
on_request_auto_review: Some("auto approvals".into()),
never: Some("never approvals".into()),
unless_trusted: Some("unless-trusted approvals".into()),
granular: Some(GranularApprovalMessages {
intro: Some("Catalog: {{ policy }}".to_string()),
prompted_categories: Some("Allowed: {{ categories }}".to_string()),
rejected_categories: Some("Denied: {{ categories }}".to_string()),
intro: Some("Catalog: {{ policy }}".into()),
prompted_categories: Some("Allowed: {{ categories }}".into()),
rejected_categories: Some("Denied: {{ categories }}".into()),
}),
..Default::default()
};
let collaboration_modes = CollaborationModeMessages {
initial: Some("initial instructions".to_string()),
default: Some("default instructions".to_string()),
plan: Some("plan instructions".to_string()),
initial: Some("initial instructions".into()),
default: Some("default instructions".into()),
plan: Some("plan instructions".into()),
};
let auto_review = AutoReviewMessages {
policy: Some("review policy".to_string()),
policy_template: Some("review policy template".to_string()),
policy: Some("review policy".into()),
policy_template: Some("review policy template".into()),
node_repl_policy: None,
rejection_instructions: Some("rejection instructions".to_string()),
timeout_instructions: Some(String::new()),
rejection_instructions: Some("rejection instructions".into()),
timeout_instructions: Some("".into()),
};
let permissions = PermissionMessages {
danger_full_access: Some("danger".to_string()),
workspace_write: Some(String::new()),
danger_full_access: Some("danger".into()),
workspace_write: Some("".into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
};
let multi_agent = MultiAgentMessages {
role: Some(MultiAgentRoleMessages {
root: Some("root base".to_string()),
subagent: Some("subagent base".to_string()),
root: Some("root base".into()),
subagent: Some("subagent base".into()),
}),
mode: Some(MultiAgentModeMessages {
explicit: Some("explicit mode".to_string()),
proactive: Some("proactive mode".to_string()),
hint_text: Some("mode hint".to_string()),
explicit: Some("explicit mode".into()),
proactive: Some("proactive mode".into()),
hint_text: Some("mode hint".into()),
}),
};
let token_budget = ModelTokenBudgetConfig {
enabled: false,
use_history_notes_extension: false,
reminder_threshold_tokens: 128,
reminder_message_template: "budget reminder".to_string(),
guidance_message: "budget guidance".to_string(),
auto_compact_fallback_prompt: "compact prompt".to_string(),
reminder_message_template: "budget reminder".into(),
guidance_message: "budget guidance".into(),
auto_compact_fallback_prompt: "compact prompt".into(),
auto_compact_fallback_buffer_tokens: 64,
};
let guardian_v2 = GuardianV2ModelConfig {
classifier_instructions: Some("Guardian experiment".to_string()),
classifier_instructions: Some("Guardian experiment".into()),
..Default::default()
};
let confirmation_policies = ConfirmationPolicies {
browser_use: Some("# Browser policy\n\n{{literal_markdown}}\n".to_string()),
computer_use: Some(" # Native policy\r\n\n${native_markdown}\n".to_string()),
browser_use: Some("# Browser policy\n\n{{literal_markdown}}\n".into()),
computer_use: Some(" # Native policy\r\n\n${native_markdown}\n".into()),
};
let mut messages = ModelMessages {
apps: Some(AppsMessages {
usage_instructions: Some("Catalog Apps instructions.".to_string()),
usage_instructions: Some("Catalog Apps instructions.".into()),
}),
plugins: None,
content_filter_guidance: None,
persistent_instructions: Some(persistent_instructions.to_string()),
persistent_instructions: Some(persistent_instructions.into()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(async_message_description.to_string()),
description: Some(async_message_description.into()),
..Default::default()
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: Some(ToolMessage {
description: Some("Catalog spawn description.".to_string()),
description: Some("Catalog spawn description.".into()),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}),
instructions_template: Some("template".to_string()),
instructions_template: Some("template".into()),
approvals: Some(approvals),
collaboration_modes: Some(collaboration_modes),
auto_review: Some(auto_review),
@@ -131,7 +131,7 @@ fn base_instruction_override_is_literal_and_preserves_catalog_messages() {
let updated = with_config_overrides(model, &config);
messages.instructions_template = Some(override_instructions.to_string());
messages.instructions_template = Some(override_instructions.into());
assert_eq!(updated.model_messages, Some(messages));
assert_eq!(render_model_instructions(&updated), override_instructions);
}
@@ -159,16 +159,16 @@ fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
),
] {
let mut messages = ModelMessages {
instructions_template: Some(instructions.to_string()),
persistent_instructions: Some(String::new()),
instructions_template: Some(instructions.into()),
persistent_instructions: Some("".into()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
..Default::default()
@@ -176,7 +176,7 @@ fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
..Default::default()
}),
approvals: Some(ApprovalMessages {
on_request: Some("user approvals".to_string()),
on_request: Some("user approvals".into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -190,7 +190,7 @@ fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
let updated = with_config_overrides(model, &config);
messages.instructions_template = Some(expected.to_string());
messages.instructions_template = Some(expected.into());
assert_eq!(updated.model_messages, Some(messages));
}
}
@@ -210,7 +210,7 @@ fn baked_personality_section_is_preserved_without_explicit_none() {
.model_messages
.as_mut()
.expect("fallback model messages")
.instructions_template = Some(instructions.to_string());
.instructions_template = Some(instructions.into());
assert_eq!(
render_model_instructions(&with_config_overrides(model, &config)),
@@ -226,7 +226,7 @@ fn explicit_empty_base_instructions_stay_empty_with_personality_none() {
.model_messages
.as_mut()
.expect("fallback model messages")
.instructions_template = Some("Intro\n# Personality\nRemove me".to_string());
.instructions_template = Some("Intro\n# Personality\nRemove me".into());
let config = ModelsManagerConfig {
base_instructions: Some(String::new()),
personality: Some(Personality::None),
+1
View File
@@ -21,6 +21,7 @@ codex-git-utils = { workspace = true }
codex-guardian-context = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cached-str = { workspace = true }
codex-utils-template = { workspace = true }
tracing = { workspace = true }
whoami = { workspace = true }
@@ -63,7 +63,7 @@ fn test_model(model_messages: Option<ModelMessages>) -> ModelInfo {
fn renders_literal_templates() {
let template = "Hello {{ personality }}\n\n# Personality\n\nFixed instructions";
let model = test_model(Some(ModelMessages {
instructions_template: Some(template.to_string()),
instructions_template: Some(template.into()),
..Default::default()
}));
assert_eq!(
@@ -82,7 +82,7 @@ fn missing_and_empty_templates_render_empty_but_retain_presence() {
(Some(ModelMessages::default()), None),
(
Some(ModelMessages {
instructions_template: Some(String::new()),
instructions_template: Some("".into()),
..Default::default()
}),
Some(""),
+2 -1
View File
@@ -9,6 +9,7 @@ use codex_protocol::openai_models::IndirectDescriptionPrefixes;
use codex_protocol::openai_models::McpResourceToolMessages;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelMessages;
use codex_protocol::openai_models::ToolDescriptionPrefixes;
use codex_protocol::openai_models::ToolMessage;
use permissions::ResolvedApprovalMessages;
use permissions::ResolvedPermissionMessages;
@@ -279,7 +280,7 @@ impl<'a> ResolvedModelMessages<'a> {
/// Selects per-function guidance restricted to the default `functions` namespace.
pub fn functions_namespace_functions_description_prefixes(
&self,
) -> Option<&'a std::collections::BTreeMap<String, String>> {
) -> Option<&'a ToolDescriptionPrefixes> {
self.catalog_messages?
.tools
.as_ref()?
@@ -12,13 +12,13 @@ fn apps_resolution_preserves_literal_bytes_and_rejects_invalid_overrides() {
None,
Some(AppsMessages::default()),
Some(AppsMessages {
usage_instructions: Some(" \t\n".to_string()),
usage_instructions: Some(" \t\n".into()),
}),
Some(AppsMessages {
usage_instructions: Some("é".repeat(401)),
usage_instructions: Some("é".repeat(401).into()),
}),
Some(AppsMessages {
usage_instructions: Some("x".repeat(801)),
usage_instructions: Some("x".repeat(801).into()),
}),
] {
let messages = ModelMessages {
@@ -45,7 +45,7 @@ fn apps_resolution_keeps_empty_boundary_and_placeholder_text_literal() {
] {
let messages = ModelMessages {
apps: Some(AppsMessages {
usage_instructions: Some(text.clone()),
usage_instructions: Some(text.as_str().into()),
}),
..Default::default()
};
@@ -2,17 +2,18 @@
//! Text is owned because world-state sections outlive the borrowed model metadata.
use codex_protocol::openai_models::IncrementalToolMessages;
use codex_utils_cached_str::CodexCachedStr;
/// Resolved static wording; consumers retain ownership of runtime names and instructions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedIncrementalToolMessages {
pub tool_update_hint: String,
pub removed_tools_header: String,
pub removed_namespaces_header: String,
pub namespace_instructions_prefix: String,
pub namespace_instructions_cleared: String,
pub exec_tools_update_hint: String,
pub exec_tools_removed_definitions_header: String,
pub tool_update_hint: CodexCachedStr,
pub removed_tools_header: CodexCachedStr,
pub removed_namespaces_header: CodexCachedStr,
pub namespace_instructions_prefix: CodexCachedStr,
pub namespace_instructions_cleared: CodexCachedStr,
pub exec_tools_update_hint: CodexCachedStr,
pub exec_tools_removed_definitions_header: CodexCachedStr,
}
impl Default for ResolvedIncrementalToolMessages {
@@ -23,9 +24,9 @@ impl Default for ResolvedIncrementalToolMessages {
impl ResolvedIncrementalToolMessages {
pub(crate) fn new(messages: Option<&IncrementalToolMessages>) -> Self {
let resolve = |text: Option<&String>, bundled: &str| {
let resolve = |text: Option<&CodexCachedStr>, bundled: &str| {
text.filter(|text| text.len() <= 512)
.map_or_else(|| bundled.to_owned(), Clone::clone)
.map_or_else(|| bundled.into(), Clone::clone)
};
Self {
tool_update_hint: resolve(
@@ -59,3 +60,28 @@ impl ResolvedIncrementalToolMessages {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Resolving a catalog override shares its storage, including when it matches a default.
#[test]
fn resolved_overrides_share_storage_with_catalog_and_defaults() {
let defaults = ResolvedIncrementalToolMessages::default();
let catalog = IncrementalToolMessages {
tool_update_hint: Some(defaults.tool_update_hint.as_str().into()),
removed_tools_header: Some("Custom removal instructions".into()),
..Default::default()
};
let resolved = ResolvedIncrementalToolMessages::new(Some(&catalog));
assert!(std::ptr::eq(
defaults.tool_update_hint.as_str(),
resolved.tool_update_hint.as_str()
));
assert!(std::ptr::eq(
catalog.removed_tools_header.as_deref().unwrap(),
resolved.removed_tools_header.as_str()
));
}
}
@@ -15,9 +15,9 @@ fn plugin_fields_fall_back_independently_without_losing_valid_siblings() {
let bundled = ResolvedModelMessages::bundled();
for invalid in [
None,
Some(String::new()),
Some("".into()),
Some(" \t\r\n".into()),
Some("é".repeat(251)),
Some("é".repeat(251).into()),
] {
let messages = ModelMessages {
plugins: Some(PluginMessages {
@@ -102,10 +102,16 @@ fn plugin_templates_require_exactly_one_harness_fact_placeholder() {
catalog_messages: Some(&messages),
}
.selected_plugin();
assert_eq!(resolved.intro, selected.intro.unwrap());
assert_eq!(resolved.skill_namespace, selected.skill_namespace.unwrap());
assert_eq!(resolved.apps, selected.apps.unwrap());
assert_eq!(resolved.mcp_servers, selected.mcp_servers.unwrap());
assert_eq!(resolved.intro, selected.intro.as_deref().unwrap());
assert_eq!(
resolved.skill_namespace,
selected.skill_namespace.as_deref().unwrap()
);
assert_eq!(resolved.apps, selected.apps.as_deref().unwrap());
assert_eq!(
resolved.mcp_servers,
selected.mcp_servers.as_deref().unwrap()
);
}
#[test]
@@ -118,15 +124,15 @@ fn plugin_wording_limits_count_utf8_bytes_and_keep_boundary_values_literal() {
let messages = ModelMessages {
plugins: Some(PluginMessages {
generic: Some(GenericPluginMessages {
intro: Some(intro.clone()),
usage_instructions: Some(usage.clone()),
intro: Some(intro.as_str().into()),
usage_instructions: Some(usage.as_str().into()),
}),
selected: Some(SelectedPluginMessages {
omitted: Some(intro.clone()),
omitted: Some(intro.as_str().into()),
..Default::default()
}),
recommendations: Some(PluginRecommendationMessages {
intro: Some(intro.clone()),
intro: Some(intro.as_str().into()),
}),
}),
..Default::default()
@@ -63,7 +63,7 @@ fn bounds_template_bytes_and_rendered_output_before_allocation() {
assert!(render_roots_override(&exact, "`/a`").is_some());
for oversized in [exact + "x", format!("{}{{{{ roots }}}}", "é".repeat(495))] {
let messages = PermissionMessages {
writable_root: Some(oversized),
writable_root: Some(oversized.into()),
..PermissionMessages::default()
};
assert_eq!(
@@ -190,9 +190,9 @@ fn renders_sandbox_mode_text() {
#[test]
fn catalog_permission_messages_select_sandbox_mode_and_render_network_access() {
let messages = PermissionMessages {
danger_full_access: Some("catalog danger".to_string()),
workspace_write: Some("catalog workspace {{ network_access }}".to_string()),
read_only: Some("catalog read only {{ network_access }}".to_string()),
danger_full_access: Some("catalog danger".into()),
workspace_write: Some("catalog workspace {{ network_access }}".into()),
read_only: Some("catalog read only {{ network_access }}".into()),
approved_prefixes: None,
..PermissionMessages::default()
};
@@ -217,7 +217,7 @@ fn catalog_permission_messages_select_sandbox_mode_and_render_network_access() {
fn catalog_permission_text_equal_to_bundled_template_preserves_literal_whitespace() {
let messages = PermissionMessages {
danger_full_access: None,
workspace_write: Some(WORKSPACE_WRITE_TEMPLATE.to_string()),
workspace_write: Some(WORKSPACE_WRITE_TEMPLATE.into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -251,7 +251,7 @@ fn missing_catalog_permission_message_uses_legacy_sandbox_text() {
let messages = PermissionMessages {
danger_full_access: None,
workspace_write: None,
read_only: Some("unused".to_string()),
read_only: Some("unused".into()),
approved_prefixes: None,
..PermissionMessages::default()
};
@@ -271,7 +271,7 @@ fn invalid_catalog_permission_message_is_preserved_verbatim() {
for workspace_write in ["{{ unterminated", "{{ unsupported }}"] {
let messages = PermissionMessages {
danger_full_access: None,
workspace_write: Some(workspace_write.to_string()),
workspace_write: Some(workspace_write.into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -292,7 +292,7 @@ fn catalog_permission_message_renders_network_access_and_preserves_other_placeho
let source = "network={{ network_access }} compact={{network_access}} other={{ other }}";
let messages = PermissionMessages {
danger_full_access: None,
workspace_write: Some(source.to_string()),
workspace_write: Some(source.into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -312,7 +312,7 @@ fn catalog_permission_message_renders_network_access_and_preserves_other_placeho
fn empty_catalog_permission_message_preserves_non_sandbox_sections() {
let messages = PermissionMessages {
danger_full_access: None,
workspace_write: Some(String::new()),
workspace_write: Some("".into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -422,10 +422,10 @@ fn on_request_permission_guidance_matches_enabled_capabilities() {
#[test]
fn catalog_approval_messages_select_reviewer_variant() {
let messages = ApprovalMessages {
on_request: Some("user catalog approvals".to_string()),
on_request_auto_review: Some("auto-review catalog approvals".to_string()),
never: Some("never catalog approvals".to_string()),
unless_trusted: Some("unless-trusted catalog approvals".to_string()),
on_request: Some("user catalog approvals".into()),
on_request_auto_review: Some("auto-review catalog approvals".into()),
never: Some("never catalog approvals".into()),
unless_trusted: Some("unless-trusted catalog approvals".into()),
granular: None,
..Default::default()
};
@@ -472,7 +472,7 @@ fn catalog_approval_messages_select_reviewer_variant() {
#[test]
fn empty_catalog_approval_message_suppresses_legacy_approval_section() {
let messages = ApprovalMessages {
on_request: Some(String::new()),
on_request: Some("".into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -515,7 +515,7 @@ fn missing_catalog_key_uses_legacy_approval_text() {
ApprovalsReviewer::User,
ApprovalMessages {
on_request: None,
on_request_auto_review: Some("unused catalog approvals".to_string()),
on_request_auto_review: Some("unused catalog approvals".into()),
never: None,
unless_trusted: None,
granular: None,
@@ -525,7 +525,7 @@ fn missing_catalog_key_uses_legacy_approval_text() {
(
ApprovalsReviewer::AutoReview,
ApprovalMessages {
on_request: Some("unused catalog approvals".to_string()),
on_request: Some("unused catalog approvals".into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -572,8 +572,8 @@ fn empty_catalog_non_on_request_approval_messages_suppress_legacy_approval_text(
let messages = ApprovalMessages {
on_request: None,
on_request_auto_review: None,
never: Some(String::new()),
unless_trusted: Some(String::new()),
never: Some("".into()),
unless_trusted: Some("".into()),
granular: None,
..Default::default()
};
@@ -665,8 +665,8 @@ fn saved_prefix_heading_requires_rollout_and_plain_bounded_wording() {
(None, None),
] {
let messages = PermissionMessages {
approved_command_prefix_saved: heading.map(str::to_owned),
approved_prefixes: Some("Unrelated full-list template".to_owned()),
approved_command_prefix_saved: heading.map(Into::into),
approved_prefixes: Some("Unrelated full-list template".into()),
..Default::default()
};
let context = ApprovalPromptContext {
@@ -844,7 +844,7 @@ fn preserves_supplied_path_spellings_and_order() {
let denied_read_paths = vec![r"C:\private".to_string(), "/private".to_string()];
let denied_read_globs = vec![r"C:\private\**".to_string(), "/private/**".to_string()];
let approval_messages = ApprovalMessages {
on_request: Some(String::new()),
on_request: Some("".into()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
@@ -853,7 +853,7 @@ fn preserves_supplied_path_spellings_and_order() {
};
let permission_messages = PermissionMessages {
danger_full_access: None,
workspace_write: Some(String::new()),
workspace_write: Some("".into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -1079,8 +1079,8 @@ fn unusable_path_warning_copy_falls_back_independently() {
denied_reads
};
let messages = PermissionMessages {
omitted_paths: Some(omitted_paths),
denied_reads: Some(denied_reads),
omitted_paths: Some(omitted_paths.into()),
denied_reads: Some(denied_reads.into()),
..Default::default()
};
let actual = PermissionsInstructions::from_resolved(
@@ -1121,8 +1121,8 @@ fn path_warning_copy_is_bounded_without_suppressing_omitted_denials() {
let lead = "x".repeat(bytes);
let heading = "y".repeat(bytes - "\n{{ denied_reads }}".len());
let messages = PermissionMessages {
omitted_paths: Some(lead.clone()),
denied_reads: Some(format!("{heading}\n{{{{ denied_reads }}}}")),
omitted_paths: Some(lead.as_str().into()),
denied_reads: Some(format!("{heading}\n{{{{ denied_reads }}}}").into()),
..Default::default()
};
for paths in [&denied[..], &denied[..1], &denied[..0]] {
+1
View File
@@ -21,6 +21,7 @@ codex-extension-items = { workspace = true }
codex-http-client = { workspace = true }
codex-network-proxy = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cached-str = { workspace = true }
codex-utils-image = { workspace = true }
codex-utils-model-facing-id = { workspace = true }
codex-utils-path-uri = { workspace = true }
+126 -102
View File
@@ -9,6 +9,7 @@ use std::sync::Arc;
use chrono::DateTime;
use chrono::Utc;
use codex_utils_cached_str::CodexCachedStr;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::InstanceType;
@@ -600,14 +601,14 @@ pub struct ModelMessages {
/// Developer guidance after a content-filter block. Missing, null, blank, or values over
/// 512 UTF-8 bytes use the bundled guidance.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_filter_guidance: Option<String>,
pub content_filter_guidance: Option<CodexCachedStr>,
/// Additional developer instructions for persistent mode. Missing or null uses the built-in
/// instructions; an empty string disables them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub persistent_instructions: Option<String>,
pub persistent_instructions: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<ToolMessages>,
pub instructions_template: Option<String>,
pub instructions_template: Option<CodexCachedStr>,
pub approvals: Option<ApprovalMessages>,
pub collaboration_modes: Option<CollaborationModeMessages>,
pub auto_review: Option<AutoReviewMessages>,
@@ -628,7 +629,7 @@ pub struct AppsMessages {
/// Missing/null uses bundled guidance; empty clears it. Whitespace-only or more than
/// 800 UTF-8 bytes falls back to bundled guidance. Other values preserve exact bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_instructions: Option<String>,
pub usage_instructions: Option<CodexCachedStr>,
}
/// Model-owned confirmation-policy Markdown, forwarded unchanged to actor tools.
@@ -636,12 +637,15 @@ pub struct AppsMessages {
pub struct ConfirmationPolicies {
/// Replacement Markdown for the Browser Use confirmation-policy document.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub browser_use: Option<String>,
pub browser_use: Option<CodexCachedStr>,
/// Replacement Markdown for the native Computer Use confirmation policy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub computer_use: Option<String>,
pub computer_use: Option<CodexCachedStr>,
}
/// Catalog selectors and the model-owned description prefixes they apply.
pub type ToolDescriptionPrefixes = std::collections::BTreeMap<CodexCachedStr, CodexCachedStr>;
/// Model-owned tool messages and description prefixes.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ToolMessages {
@@ -663,8 +667,7 @@ pub struct ToolMessages {
/// `description_prefix_budget_bytes` limit with indirect namespace guidance.
/// Other namespaces are never affected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub functions_namespace_functions_description_prefixes:
Option<std::collections::BTreeMap<String, String>>,
pub functions_namespace_functions_description_prefixes: Option<ToolDescriptionPrefixes>,
/// Maximum total UTF-8 bytes of trimmed prefix values in this model's catalog entry.
/// Defaults to 512. Each configured dictionary entry counts once, including unused
/// selectors. Keys, paragraph separators, and rendered copies are excluded.
@@ -692,16 +695,16 @@ pub struct IndirectDescriptionPrefixes {
/// Exact rendered namespaces, including `functions` for plain tools.
/// Overlapping selectors must have the same trimmed value.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespaces: Option<std::collections::BTreeMap<String, String>>,
pub namespaces: Option<ToolDescriptionPrefixes>,
/// Exact rendered namespaces of registered built-in tools, including `functions` for plain tools.
/// Adds guidance once to the namespace header, including a header shared with client tools.
/// Flat listings have no header and omit this selector. External-only namespaces are ignored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub builtin_tool_namespaces: Option<std::collections::BTreeMap<String, String>>,
pub builtin_tool_namespaces: Option<ToolDescriptionPrefixes>,
/// Configured MCP server names, before callable namespace normalization.
/// Each prefix applies to all namespaces exposed by that server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<std::collections::BTreeMap<String, String>>,
pub mcp_servers: Option<ToolDescriptionPrefixes>,
}
/// Model-owned messages for a built-in tool.
@@ -710,7 +713,7 @@ pub struct ToolMessage {
/// Missing or null uses the built-in description; an empty string suppresses its static
/// text without disabling the tool. Tool-owned runtime guidance is retained.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub description: Option<CodexCachedStr>,
/// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools, Code Mode wait,
/// request_user_input_async (the send_user_message_async catalog key), MCP resource helpers,
/// and Memento V2 tools.
@@ -720,7 +723,7 @@ pub struct ToolMessage {
/// Overrides must declare harness-encrypted properties so their annotations can be retained.
/// Argument handling is unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<String>,
pub parameters: Option<CodexCachedStr>,
}
/// Model-owned descriptions and parameters for Multi-Agent V2 tools, independent of their namespace.
@@ -811,12 +814,12 @@ pub struct CodeModeToolMessages {
/// Literal guidance appended when deferred nested tools exist.
/// Missing or null uses bundled text; an empty string omits the section.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deferred_nested_tools_guidance: Option<String>,
pub deferred_nested_tools_guidance: Option<CodexCachedStr>,
/// Literal shared TypeScript definitions, emitted when Code Mode Only exposes MCP results.
/// Missing or null uses bundled definitions; an empty string omits the section.
/// Custom definitions must remain compatible with the generated tool declarations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_typescript_preamble: Option<String>,
pub mcp_typescript_preamble: Option<CodexCachedStr>,
}
/// Model-owned defaults for the context-window token-budget feature.
@@ -827,28 +830,28 @@ pub struct ModelTokenBudgetConfig {
#[serde(default)]
pub use_history_notes_extension: bool,
pub reminder_threshold_tokens: i64,
pub reminder_message_template: String,
pub guidance_message: String,
pub auto_compact_fallback_prompt: String,
pub reminder_message_template: CodexCachedStr,
pub guidance_message: CodexCachedStr,
pub auto_compact_fallback_prompt: CodexCachedStr,
pub auto_compact_fallback_buffer_tokens: i64,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ApprovalMessages {
pub on_request: Option<String>,
pub on_request_auto_review: Option<String>,
pub never: Option<String>,
pub unless_trusted: Option<String>,
pub on_request: Option<CodexCachedStr>,
pub on_request_auto_review: Option<CodexCachedStr>,
pub never: Option<CodexCachedStr>,
pub unless_trusted: Option<CodexCachedStr>,
/// Optional replacement heading for the request_permissions tool instructions.
#[serde(
default,
alias = "request_permissions_tool",
skip_serializing_if = "Option::is_none"
)]
pub request_permissions: Option<String>,
pub request_permissions: Option<CodexCachedStr>,
/// Optional introduction to the harness-owned automatic escalation review policy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_review_suffix: Option<String>,
pub auto_review_suffix: Option<CodexCachedStr>,
/// Optional catalog templates for harness-owned granular approval facts.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub granular: Option<GranularApprovalMessages>,
@@ -861,67 +864,67 @@ pub struct GranularApprovalMessages {
/// Rendering contract: at most 500 UTF-8 bytes with exactly one `{{ policy }}` marker.
/// Consumers must use bundled text for missing, null, empty, invalid, or oversized templates.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
pub intro: Option<CodexCachedStr>,
/// Presentation around `{{ categories }}`, including the fixed prompted-bucket label.
/// Uses the same byte limit and fallback rules as `intro`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prompted_categories: Option<String>,
pub prompted_categories: Option<CodexCachedStr>,
/// Presentation around `{{ categories }}`, including the fixed rejected-bucket label.
/// Uses the same byte limit and fallback rules as `intro`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rejected_categories: Option<String>,
pub rejected_categories: Option<CodexCachedStr>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct CollaborationModeMessages {
/// Optional guidance for Default before the first Plan turn.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial: Option<String>,
pub default: Option<String>,
pub plan: Option<String>,
pub initial: Option<CodexCachedStr>,
pub default: Option<CodexCachedStr>,
pub plan: Option<CodexCachedStr>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct AutoReviewMessages {
pub policy: Option<String>,
pub policy_template: Option<String>,
pub policy: Option<CodexCachedStr>,
pub policy_template: Option<CodexCachedStr>,
/// Extra developer policy for `node_repl` and `cua_repl` reviews.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_repl_policy: Option<String>,
pub rejection_instructions: Option<String>,
pub timeout_instructions: Option<String>,
pub node_repl_policy: Option<CodexCachedStr>,
pub rejection_instructions: Option<CodexCachedStr>,
pub timeout_instructions: Option<CodexCachedStr>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct PermissionMessages {
pub danger_full_access: Option<String>,
pub workspace_write: Option<String>,
pub read_only: Option<String>,
pub danger_full_access: Option<CodexCachedStr>,
pub workspace_write: Option<CodexCachedStr>,
pub read_only: Option<CodexCachedStr>,
/// Supports `{{ approved_prefixes }}`. Missing or null uses the bundled text;
/// an empty string suppresses the approved-prefix section.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approved_prefixes: Option<String>,
pub approved_prefixes: Option<CodexCachedStr>,
/// Optional plain heading for the separate saved-command-prefix notification.
/// The harness formats the prefix list and falls back to its bundled heading for invalid text.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approved_command_prefix_saved: Option<String>,
pub approved_command_prefix_saved: Option<CodexCachedStr>,
/// Single writable-root sentence with exactly one `{{ roots }}` placeholder.
/// Missing, null, empty, invalid, or oversized templates use the bundled sentence.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub writable_root: Option<String>,
pub writable_root: Option<CodexCachedStr>,
/// Multiple writable-roots sentence with exactly one `{{ roots }}` placeholder.
/// Missing, null, empty, invalid, or oversized templates use the bundled sentence.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub writable_roots: Option<String>,
pub writable_roots: Option<CodexCachedStr>,
/// Optional presentation before the harness-owned omission and no-bypass warning.
/// Empty, invalid, or oversized text uses the bundled warning without a lead-in.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub omitted_paths: Option<String>,
pub omitted_paths: Option<CodexCachedStr>,
/// Presentation with exactly one `{{ denied_reads }}` placeholder for the
/// harness-owned denial explanation, no-escalation rule, and path/glob list.
/// Empty, invalid, or oversized templates use the bundled presentation.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub denied_reads: Option<String>,
pub denied_reads: Option<CodexCachedStr>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
@@ -932,17 +935,17 @@ pub struct MultiAgentMessages {
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentRoleMessages {
pub root: Option<String>,
pub subagent: Option<String>,
pub root: Option<CodexCachedStr>,
pub subagent: Option<CodexCachedStr>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentModeMessages {
pub explicit: Option<String>,
pub explicit: Option<CodexCachedStr>,
/// Ultra-only mode instructions. Missing or null uses the built-in proactive hint;
/// an empty string suppresses the mode message. `hint_text` takes precedence.
pub proactive: Option<String>,
pub hint_text: Option<String>,
pub proactive: Option<CodexCachedStr>,
pub hint_text: Option<CodexCachedStr>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
@@ -998,13 +1001,13 @@ pub struct ModelsResponse {
struct ModelInfoWithLegacyBaseInstructionsRef<'a> {
#[serde(flatten)]
model: &'a ModelInfo,
base_instructions: String,
base_instructions: &'a str,
}
#[derive(Deserialize)]
struct ModelInfoWithLegacyBaseInstructions {
#[serde(default)]
base_instructions: Option<String>,
base_instructions: Option<CodexCachedStr>,
#[serde(flatten)]
model: ModelInfo,
}
@@ -1028,13 +1031,13 @@ where
.as_ref()
.and_then(|messages| messages.instructions_template.as_deref())
{
template.to_owned()
template
} else {
warn!(
model = %model.slug,
"Model has no instruction template; returning empty instructions."
);
String::new()
""
};
ModelInfoWithLegacyBaseInstructionsRef {
model,
@@ -1264,6 +1267,29 @@ mod tests {
assert_eq!(messages, ModelMessages::default());
}
/// Independent catalog decodes and clones must reuse storage for identical long messages.
#[test]
fn model_messages_share_text_across_fields_and_decodes() {
let text = "Use the same instructions across models.\n";
let first: ModelMessages = serde_json::from_value(serde_json::json!({
"instructions_template": text,
}))
.unwrap();
let second: ModelMessages = serde_json::from_value(serde_json::json!({
"confirmation_policies": { "browser_use": text },
}))
.unwrap();
let cloned = first.clone();
let template = first.instructions_template.as_deref().unwrap();
let browser = second.confirmation_policies.unwrap().browser_use.unwrap();
assert_eq!(browser.as_str(), text);
assert!(std::ptr::eq(template, browser.as_str()));
assert!(std::ptr::eq(
template,
cloned.instructions_template.as_deref().unwrap()
));
}
#[test]
fn apps_messages_preserve_nullable_and_literal_wire_values() {
for apps in [
@@ -1311,14 +1337,14 @@ mod tests {
(
serde_json::json!({"tools": {"send_user_message_async": {"description": ""}}}),
Some(Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
})),
),
(
serde_json::json!({"tools": {"send_user_message_async": {"description": "Catalog description"}}}),
Some(Some(ToolMessage {
description: Some("Catalog description".to_string()),
description: Some("Catalog description".into()),
..Default::default()
})),
),
@@ -1403,10 +1429,10 @@ mod tests {
assert_eq!(
messages.approvals,
Some(ApprovalMessages {
on_request: Some(String::new()),
request_permissions: Some(String::new()),
on_request: Some("".into()),
request_permissions: Some("".into()),
on_request_auto_review: None,
never: Some(String::new()),
never: Some("".into()),
unless_trusted: None,
granular: None,
..Default::default()
@@ -1509,7 +1535,7 @@ mod tests {
assert_eq!(
missing_template.auto_review,
Some(AutoReviewMessages {
policy: Some("policy".to_string()),
policy: Some("policy".into()),
policy_template: None,
node_repl_policy: None,
rejection_instructions: None,
@@ -1519,11 +1545,11 @@ mod tests {
assert_eq!(
empty_template.auto_review,
Some(AutoReviewMessages {
policy: Some("policy".to_string()),
policy_template: Some(String::new()),
node_repl_policy: Some(String::new()),
rejection_instructions: Some(String::new()),
timeout_instructions: Some(String::new()),
policy: Some("policy".into()),
policy_template: Some("".into()),
node_repl_policy: Some("".into()),
rejection_instructions: Some("".into()),
timeout_instructions: Some("".into()),
})
);
}
@@ -1544,7 +1570,7 @@ mod tests {
messages.permissions,
Some(PermissionMessages {
danger_full_access: None,
workspace_write: Some(String::new()),
workspace_write: Some("".into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -1597,13 +1623,13 @@ mod tests {
messages.multi_agent,
Some(MultiAgentMessages {
role: Some(MultiAgentRoleMessages {
root: Some(String::new()),
subagent: Some("subagent base".to_string()),
root: Some("".into()),
subagent: Some("subagent base".into()),
}),
mode: Some(MultiAgentModeMessages {
explicit: Some("explicit mode".to_string()),
proactive: Some(String::new()),
hint_text: Some(String::new()),
explicit: Some("explicit mode".into()),
proactive: Some("".into()),
hint_text: Some("".into()),
}),
})
);
@@ -1629,10 +1655,10 @@ mod tests {
assert_eq!(
messages,
ModelMessages {
instructions_template: Some("legacy catalog instructions".to_string()),
instructions_template: Some("legacy catalog instructions".into()),
collaboration_modes: Some(CollaborationModeMessages {
initial: None,
default: Some(String::new()),
default: Some("".into()),
plan: None,
}),
..Default::default()
@@ -1732,7 +1758,7 @@ mod tests {
assert_eq!(
model.model_messages,
Some(ModelMessages {
instructions_template: Some("legacy instructions".to_string()),
instructions_template: Some("legacy instructions".into()),
..Default::default()
})
);
@@ -1777,7 +1803,7 @@ mod tests {
] {
let response = ModelsResponse {
models: vec![test_model(Some(ModelMessages {
instructions_template: template.map(str::to_owned),
instructions_template: template.map(Into::into),
..Default::default()
}))],
};
@@ -1790,19 +1816,19 @@ mod tests {
fn models_response_prefers_template_and_preserves_message_siblings() {
let messages = ModelMessages {
apps: Some(AppsMessages {
usage_instructions: Some("Literal Apps {{guidance}}".to_string()),
usage_instructions: Some("Literal Apps {{guidance}}".into()),
}),
plugins: None,
content_filter_guidance: Some("Offer a permitted alternative.".to_string()),
persistent_instructions: Some("Persistent catalog instructions".to_string()),
content_filter_guidance: Some("Offer a permitted alternative.".into()),
persistent_instructions: Some("Persistent catalog instructions".into()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some("Catalog description".to_string()),
description: Some("Catalog description".into()),
..Default::default()
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: Some(ToolMessage {
description: Some("Catalog spawn description".to_string()),
description: Some("Catalog spawn description".into()),
..Default::default()
}),
..Default::default()
@@ -1811,32 +1837,32 @@ mod tests {
}),
instructions_template: None,
approvals: Some(ApprovalMessages {
on_request: Some("approval".to_string()),
on_request: Some("approval".into()),
on_request_auto_review: None,
never: Some("never approval".to_string()),
unless_trusted: Some("unless-trusted approval".to_string()),
never: Some("never approval".into()),
unless_trusted: Some("unless-trusted approval".into()),
granular: Some(GranularApprovalMessages {
intro: Some("Catalog: {{ policy }}".to_string()),
prompted_categories: Some("Allowed: {{ categories }}".to_string()),
rejected_categories: Some("Denied: {{ categories }}".to_string()),
intro: Some("Catalog: {{ policy }}".into()),
prompted_categories: Some("Allowed: {{ categories }}".into()),
rejected_categories: Some("Denied: {{ categories }}".into()),
}),
..Default::default()
}),
collaboration_modes: Some(CollaborationModeMessages {
initial: Some("initial collaboration".to_string()),
default: Some("default collaboration".to_string()),
plan: Some("plan collaboration".to_string()),
initial: Some("initial collaboration".into()),
default: Some("default collaboration".into()),
plan: Some("plan collaboration".into()),
}),
auto_review: Some(AutoReviewMessages {
policy: Some("policy".to_string()),
policy: Some("policy".into()),
policy_template: None,
node_repl_policy: None,
rejection_instructions: Some("rejection instructions".to_string()),
timeout_instructions: Some("timeout instructions".to_string()),
rejection_instructions: Some("rejection instructions".into()),
timeout_instructions: Some("timeout instructions".into()),
}),
permissions: Some(PermissionMessages {
danger_full_access: None,
workspace_write: Some("workspace".to_string()),
workspace_write: Some("workspace".into()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
@@ -1844,19 +1870,17 @@ mod tests {
multi_agent: None,
token_budget: None,
confirmation_policies: Some(ConfirmationPolicies {
browser_use: Some(
"# Browser confirmations\n\nKeep {{literal_markdown}}.\n".to_string(),
),
browser_use: Some("# Browser confirmations\n\nKeep {{literal_markdown}}.\n".into()),
computer_use: Some(
" # Native confirmations\r\n\nKeep ${native_markdown}.\n".to_string(),
" # Native confirmations\r\n\nKeep ${native_markdown}.\n".into(),
),
}),
guardian_v2: Some(GuardianV2ModelConfig {
classifier_instructions: Some("Guardian classification".to_string()),
classifier_instructions: Some("Guardian classification".into()),
review_threshold_basis_points: Some(7_500),
reasoning_effort: Some(ReasoningEffort::Minimal),
transcript: Some(GuardianV2TranscriptModelConfig {
sources: Some(vec!["reasoning".to_string()]),
sources: Some(vec!["reasoning".into()]),
max_tool_entry_tokens: Some(500),
..Default::default()
}),
@@ -1879,19 +1903,19 @@ mod tests {
let response: ModelsResponse =
serde_json::from_value(value).expect("deserialize legacy models response");
let mut expected_messages = messages;
expected_messages.instructions_template = Some("legacy instructions".to_string());
expected_messages.instructions_template = Some("legacy instructions".into());
assert_eq!(response.models[0].model_messages, Some(expected_messages));
let canonical_messages = ModelMessages {
persistent_instructions: Some(String::new()),
persistent_instructions: Some("".into()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(String::new()),
description: Some("".into()),
..Default::default()
}),
..Default::default()
}),
instructions_template: Some("canonical instructions".to_string()),
instructions_template: Some("canonical instructions".into()),
..Default::default()
};
let mut value = serde_json::to_value(ModelsResponse {
@@ -4,6 +4,7 @@ use serde::Serialize;
use ts_rs::TS;
use super::ReasoningEffort;
use codex_utils_cached_str::CodexCachedStr;
/// Legacy classifier modes retained for configuration and model-catalog compatibility.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
@@ -25,7 +26,7 @@ pub struct GuardianV2ModelConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub async_classifier_conversation_token_limit: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub classifier_instructions: Option<String>,
pub classifier_instructions: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review_threshold_basis_points: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -48,7 +49,7 @@ pub struct GuardianV2ModelConfig {
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct GuardianV2TranscriptModelConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sources: Option<Vec<String>>,
pub sources: Option<Vec<CodexCachedStr>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub include_images: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -1,5 +1,6 @@
//! Optional model-catalog overrides for harness-owned incremental tool notices.
use codex_utils_cached_str::CodexCachedStr;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -10,21 +11,21 @@ use ts_rs::TS;
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct IncrementalToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_update_hint: Option<String>,
pub tool_update_hint: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub removed_tools_header: Option<String>,
pub removed_tools_header: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub removed_namespaces_header: Option<String>,
pub removed_namespaces_header: Option<CodexCachedStr>,
/// Prefix supporting `{name}`; the namespace instructions are appended verbatim.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_instructions_prefix: Option<String>,
pub namespace_instructions_prefix: Option<CodexCachedStr>,
/// Message supporting `{name}` when a namespace's instructions are cleared.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_instructions_cleared: Option<String>,
pub namespace_instructions_cleared: Option<CodexCachedStr>,
/// Literal hint before changed Code Mode tool definitions and namespace instructions.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exec_tools_update_hint: Option<String>,
pub exec_tools_update_hint: Option<CodexCachedStr>,
/// Literal header before removed Code Mode tool and namespace-instruction identities.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exec_tools_removed_definitions_header: Option<String>,
pub exec_tools_removed_definitions_header: Option<CodexCachedStr>,
}
@@ -1,6 +1,7 @@
//! Sparse Memento V2 tool definitions. Runtime data remains with consumers.
use super::ToolMessage;
use codex_utils_cached_str::CodexCachedStr;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -10,7 +11,7 @@ use ts_rs::TS;
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct HistoryToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_description: Option<String>,
pub namespace_description: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_windows: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -25,7 +26,7 @@ pub struct HistoryToolMessages {
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct NotesToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_description: Option<String>,
pub namespace_description: Option<CodexCachedStr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_files_by_prefix: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
+11 -10
View File
@@ -1,5 +1,6 @@
//! Sparse model-catalog wording for generic, selected, and recommended plugins.
use codex_utils_cached_str::CodexCachedStr;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -21,10 +22,10 @@ pub struct PluginMessages {
pub struct GenericPluginMessages {
/// Literal text, up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
pub intro: Option<CodexCachedStr>,
/// Up to 2,000 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_instructions: Option<String>,
pub usage_instructions: Option<CodexCachedStr>,
}
/// Selected-plugin wording. Fact-bearing fields require exactly one documented placeholder.
@@ -32,25 +33,25 @@ pub struct GenericPluginMessages {
pub struct SelectedPluginMessages {
/// Up to 500 UTF-8 bytes. Selected intro requires `{{ plugin_name }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
pub intro: Option<CodexCachedStr>,
/// Up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_tools: Option<String>,
pub search_tools: Option<CodexCachedStr>,
/// Up to 500 UTF-8 bytes; requires `{{ skill_namespace }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skill_namespace: Option<String>,
pub skill_namespace: Option<CodexCachedStr>,
/// Up to 500 UTF-8 bytes; requires `{{ apps }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub apps: Option<String>,
pub apps: Option<CodexCachedStr>,
/// Up to 500 UTF-8 bytes; requires `{{ mcp_servers }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<String>,
pub mcp_servers: Option<CodexCachedStr>,
/// Up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub closing: Option<String>,
pub closing: Option<CodexCachedStr>,
/// Nonblank omission notice, up to 500 UTF-8 bytes, including any desired separator.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub omitted: Option<String>,
pub omitted: Option<CodexCachedStr>,
}
/// Literal recommendation introduction; plugin identities remain supplied by the harness.
@@ -58,7 +59,7 @@ pub struct SelectedPluginMessages {
pub struct PluginRecommendationMessages {
/// Literal text, up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
pub intro: Option<CodexCachedStr>,
}
#[cfg(test)]
+1 -1
View File
@@ -14,7 +14,7 @@ pub fn with_catalog_tool_message(
return tool;
};
if let Some(description) = &messages.description {
tool.description.clone_from(description);
description.as_str().clone_into(&mut tool.description);
}
if let Some(parameters) = &messages.parameters {
let parameters = parse_catalog_tool_parameters(parameters).and_then(|mut parameters| {
@@ -67,8 +67,8 @@ fn catalog_overrides_preserve_tool_fields_and_encryption_with_independent_fallba
),
] {
let messages = ToolMessage {
description: description.map(str::to_owned),
parameters: schema.map(str::to_owned),
description: description.map(Into::into),
parameters: schema.map(Into::into),
};
let mut expected = bundled.clone();
if let Some(description) = description {
@@ -5,6 +5,7 @@ use crate::ResponsesApiNamespaceTool;
use crate::ToolName;
use crate::ToolSpec;
use crate::indirect_namespace_prefixes::prepend;
use codex_protocol::openai_models::ToolDescriptionPrefixes;
use std::collections::BTreeMap;
/// Trimmed description prefixes for the available `functions.*` tools.
@@ -13,7 +14,7 @@ pub struct FunctionsNamespaceFunctionPrefixes(BTreeMap<String, String>);
impl FunctionsNamespaceFunctionPrefixes {
pub fn new(
prefixes: Option<&BTreeMap<String, String>>,
prefixes: Option<&ToolDescriptionPrefixes>,
available_tools: impl IntoIterator<Item = ToolName>,
) -> Self {
let Some(prefixes) = prefixes.filter(|prefixes| !prefixes.is_empty()) else {
@@ -24,7 +25,7 @@ impl FunctionsNamespaceFunctionPrefixes {
if !tool.is_default_namespace() || normalized.contains_key(&tool.name) {
continue;
}
let Some(prefix) = prefixes.get(&tool.name) else {
let Some(prefix) = prefixes.get(tool.name.as_str()) else {
continue;
};
let prefix = prefix.trim();
@@ -41,7 +41,7 @@ impl<'a> IndirectNamespacePrefixes<'a> {
if let Some(namespaces) = prefixes.and_then(|prefixes| prefixes.namespaces.as_ref()) {
for (namespace, prefix) in namespaces {
resolved.insert(
namespace.clone(),
namespace.to_string(),
(prefix.trim(), format!("namespaces.{namespace}")),
);
}
@@ -73,7 +73,7 @@ impl<'a> IndirectNamespacePrefixes<'a> {
if !registered.contains(namespace.as_str()) {
continue;
}
if resolved.contains_key(namespace) {
if resolved.contains_key(namespace.as_str()) {
insert_prefix(
&mut resolved,
namespace,
@@ -67,8 +67,8 @@ fn plain_tools_join_an_existing_functions_group_only_with_a_prefix() {
}
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"functions".to_string(),
"Catalog guidance.".to_string(),
"functions".into(),
"Catalog guidance.".into(),
)])),
..Default::default()
};
@@ -171,8 +171,8 @@ fn plain_tools_join_an_existing_functions_group_only_with_a_prefix() {
fn flat_tool_descriptions_use_trimmed_namespace_prefixes() {
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"functions".to_string(),
" \nFunction guidance.\t ".to_string(),
"functions".into(),
" \nFunction guidance.\t ".into(),
)])),
..Default::default()
};
@@ -201,13 +201,10 @@ fn flat_tool_descriptions_use_trimmed_namespace_prefixes() {
#[test]
fn matching_prefixes_cover_each_namespace_once() {
let servers = BTreeMap::from([
("codex_apps".to_string(), " App guidance. ".to_string()),
("apps_alias".to_string(), "App guidance.\n".to_string()),
("codex_apps".into(), " App guidance. ".into()),
("apps_alias".into(), "App guidance.\n".into()),
]);
let exact = BTreeMap::from([(
"mcp__codex_apps__gmail".to_string(),
"App guidance.".to_string(),
)]);
let exact = BTreeMap::from([("mcp__codex_apps__gmail".into(), "App guidance.".into())]);
let configured = IndirectDescriptionPrefixes {
namespaces: Some(exact),
mcp_servers: Some(servers),
@@ -252,12 +249,12 @@ fn conflicting_namespace_and_server_prefixes_report_keys_without_values() {
] {
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"mcp__reports_one".to_string(),
namespace_prefix.to_string(),
"mcp__reports_one".into(),
namespace_prefix.into(),
)])),
mcp_servers: Some(BTreeMap::from([(
"reports.one".to_string(),
server_prefix.to_string(),
"reports.one".into(),
server_prefix.into(),
)])),
..Default::default()
};
@@ -280,8 +277,8 @@ fn conflicting_namespace_and_server_prefixes_report_keys_without_values() {
fn conflicting_mcp_servers_report_the_shared_namespace() {
let configured = IndirectDescriptionPrefixes {
mcp_servers: Some(BTreeMap::from([
("reports.one".to_string(), "First guidance.".to_string()),
("reports.two".to_string(), "Second guidance.".to_string()),
("reports.one".into(), "First guidance.".into()),
("reports.two".into(), "Second guidance.".into()),
])),
..Default::default()
};
+6
View File
@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "cached-str",
crate_name = "codex_utils_cached_str",
)
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "codex-utils-cached-str"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
string_cache = { workspace = true }
ts-rs = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
[lib]
doctest = false
+116
View File
@@ -0,0 +1,116 @@
//! Immutable strings that share repeated text across independently loaded records.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::fmt;
use std::ops::Deref;
use string_cache::DefaultAtom;
use ts_rs::TS;
/// Stores short strings inline and shares reference-counted storage for longer strings.
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct CodexCachedStr(#[schemars(with = "String")] DefaultAtom);
impl CodexCachedStr {
pub fn as_str(&self) -> &str {
&self.0
}
/// Returns a borrowed view without cloning the cached string.
pub fn as_cow(&self) -> Cow<'_, str> {
Cow::Borrowed(self.as_str())
}
}
impl Deref for CodexCachedStr {
type Target = str;
fn deref(&self) -> &str {
self.as_str()
}
}
impl Borrow<str> for CodexCachedStr {
fn borrow(&self) -> &str {
self.as_str()
}
}
impl From<&str> for CodexCachedStr {
fn from(text: &str) -> Self {
Self(text.into())
}
}
impl From<String> for CodexCachedStr {
fn from(text: String) -> Self {
Self(text.into())
}
}
impl fmt::Debug for CodexCachedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl fmt::Display for CodexCachedStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.as_str(), f)
}
}
// A derived TS implementation would introduce a named type in client bindings.
impl TS for CodexCachedStr {
type WithoutGenerics = Self;
type OptionInnerType = Self;
fn name() -> String {
String::name()
}
fn inline() -> String {
String::inline()
}
fn inline_flattened() -> String {
String::inline_flattened()
}
fn decl() -> String {
String::decl()
}
fn decl_concrete() -> String {
String::decl_concrete()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Independently decoded text and clones share storage while remaining plain strings on the wire.
#[test]
fn long_strings_share_storage_across_roundtrips_and_clones() {
let text = CodexCachedStr::from("local message override");
let wire = serde_json::to_string(&text).unwrap();
assert_eq!(wire, r#""local message override""#);
let decoded: CodexCachedStr = serde_json::from_str(&wire).unwrap();
let cloned = text.clone();
assert!(std::ptr::eq(text.as_str(), decoded.as_str()));
assert!(std::ptr::eq(text.as_str(), cloned.as_str()));
}
/// Short UTF-8 strings survive inline storage and borrow directly from the handle.
#[test]
fn short_text_borrows_without_allocation() {
let short: CodexCachedStr = serde_json::from_str(r#""é""#).unwrap();
assert!(short.0.is_inline());
assert!(matches!(short.as_cow(), Cow::Borrowed("é")));
}
}