Lightweight coding agent that runs in your terminal
Rust
Honor response budgets when reading skill resources (#40491)
Tamir Dubersteinc941572917b9
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lockindex c097016f57..5555218770 100644--- a/codex-rs/Cargo.lock+++ b/codex-rs/Cargo.lock@@ -4233,6 +4233,7 @@ dependencies = [name = "codex-skills-extension"version = "0.0.0"dependencies = [+ "assert_matches","codex-analytics","codex-config","codex-exec-server",diff --git a/codex-rs/app-server/tests/suite/v2/executor_skills.rs b/codex-rs/app-server/tests/suite/v2/executor_skills.rsindex 2d138526d5..d49c683cb4 100644--- a/codex-rs/app-server/tests/suite/v2/executor_skills.rs+++ b/codex-rs/app-server/tests/suite/v2/executor_skills.rs@@ -1,3 +1,4 @@+use std::collections::HashMap;use std::time::Duration;use anyhow::Result;@@ -183,10 +184,9 @@ stream_max_retries = 0let reference_path = reference_dir.join("details.md")?;let reference_size = match scenario {ExecutorSkillScenario::VisibleWithBudgetWarning => 600 * 1024,- ExecutorSkillScenario::ExplicitOnly- | ExecutorSkillScenario::RestrictedPermittedReference- | ExecutorSkillScenario::RestrictedDeniedReference- | ExecutorSkillScenario::RestrictedVisible => 40 * 1024,+ ExecutorSkillScenario::RestrictedPermittedReference+ | ExecutorSkillScenario::RestrictedDeniedReference => 1024,+ ExecutorSkillScenario::ExplicitOnly | ExecutorSkillScenario::RestrictedVisible => 40 * 1024,};let allow_implicit_invocation = matches!(scenario,@@ -228,7 +228,10 @@ stream_max_retries = 0let external_reference = external_reference_dir.join("details.md");std::fs::write(&external_reference,- format!("DENIED_REFERENCE_MARKER\n{REFERENCE_MARKER}"),+ format!(+ "DENIED_REFERENCE_MARKER\n{REFERENCE_MARKER}\n{}",+ "x".repeat(reference_size)+ ),)?;let reference_native_path = reference_path.to_abs_path()?;std::fs::remove_file(reference_native_path.as_path())?;@@ -381,6 +384,12 @@ stream_max_retries = 0let request_id = app_server.send_thread_start_request_with_auto_env(ThreadStartParams {model: Some("mock-model".to_string()),+ config: matches!(+ scenario,+ ExecutorSkillScenario::RestrictedPermittedReference+ | ExecutorSkillScenario::RestrictedDeniedReference+ )+ .then(|| HashMap::from([("tool_output_token_limit".to_string(), json!(250))])),selected_capability_roots: Some(vec![SelectedCapabilityRoot {id: "demo-plugin@1".to_string(),location: CapabilityRootLocation::Environment {@@ -450,7 +459,7 @@ stream_max_retries = 0}}).await??;- assert_eq!(warning.thread_id, Some(thread_id));+ assert_eq!(warning.thread_id, Some(thread_id.clone()));assert!(is_skills_budget_warning(&warning.message));}timeout(@@ -585,9 +594,46 @@ stream_max_retries = 0.function_call_output_text("approved-reference").expect("approved skill reference output");assert!(approved_reference_output.contains(REFERENCE_MARKER));+ let approved_reference: serde_json::Value =+ serde_json::from_str(&approved_reference_output)?;+ let cursor = approved_reference["next_cursor"]+ .as_str()+ .expect("approved reference should paginate");+ let expired = responses::mount_sse_sequence(+ &server,+ vec![+ tool_response(+ "expired-reference",+ "read",+ json!({+ "package": package,+ "resource": reference_resource,+ "cursor": cursor,+ }),+ ),+ responses::sse(vec![responses::ev_completed("resp-expired-done")]),+ ],+ )+ .await;+ timeout(+ READ_TIMEOUT,+ app_server.start_turn_and_wait_for_completion(TurnStartParams {+ thread_id,+ input: vec![UserInput::Text {+ text: "Continue after the turn-scoped permission expired.".to_string(),+ text_elements: Vec::new(),+ }],+ ..Default::default()+ }),+ )+ .await??;+ assert_eq!(+ expired.function_call_output_text("expired-reference"),+ Some("failed to read skill resource".to_string())+ );return Ok(());}- let reference_output = serde_json::from_str::<serde_json::Value>(&reference_output_text)?;+ let mut reference_output = serde_json::from_str::<serde_json::Value>(&reference_output_text)?;assert!(reference_output["contents"].as_str()@@ -597,16 +643,130 @@ stream_max_retries = 0reference_output["skill_root"],json!(skill_dir.inferred_native_path_string()));- match scenario {- ExecutorSkillScenario::VisibleWithBudgetWarning => {- assert!(reference_output["next_cursor"].is_string());- }- ExecutorSkillScenario::ExplicitOnly- | ExecutorSkillScenario::RestrictedPermittedReference- | ExecutorSkillScenario::RestrictedDeniedReference- | ExecutorSkillScenario::RestrictedVisible => {- assert!(reference_output["next_cursor"].is_null());+ assert!(reference_output["next_cursor"].is_string());++ if scenario == ExecutorSkillScenario::RestrictedPermittedReference {+ // 250 tokens gives both byte- and token-based policies a 1200-byte response budget.+ assert!(reference_output_text.len() <= 1200);+ let expected_contents = format!("{REFERENCE_MARKER}\n{}", "x".repeat(reference_size));+ let original_cursor = reference_output["next_cursor"]+ .as_str()+ .expect("reference cursor")+ .to_string();+ let changed_contents = format!("CHANGED_REFERENCE\n{}", "y".repeat(reference_size));+ file_system+ .write_file(+ &reference_path,+ changed_contents.clone().into_bytes(),+ Default::default(),+ /*sandbox*/ None,+ )+ .await?;+ let mut contents = reference_output["contents"]+ .as_str()+ .expect("reference contents")+ .to_string();+ while let Some(cursor) = reference_output["next_cursor"].as_str() {+ let call_id = format!("reference-{}", contents.len());+ let continuation = responses::mount_sse_sequence(+ &server,+ vec![+ tool_response(+ &call_id,+ "read",+ json!({+ "package": package,+ "resource": reference_resource,+ "cursor": cursor,+ }),+ ),+ responses::sse(vec![responses::ev_completed(&format!(+ "resp-{call_id}-done"+ ))]),+ ],+ )+ .await;+ timeout(+ READ_TIMEOUT,+ app_server.start_turn_and_wait_for_completion(TurnStartParams {+ thread_id: thread_id.clone(),+ input: vec![UserInput::Text {+ text: "Continue reading the reference.".to_string(),+ text_elements: Vec::new(),+ }],+ ..Default::default()+ }),+ )+ .await??;+ let output = continuation+ .function_call_output_text(&call_id)+ .expect("continued reference output");+ assert!(output.len() <= 1200);+ reference_output = serde_json::from_str(&output)?;+ let page_contents = reference_output["contents"]+ .as_str()+ .expect("continued reference contents");+ assert!(!page_contents.is_empty());+ assert_eq!(+ reference_output,+ json!({+ "resource": reference_resource,+ "contents": page_contents,+ "skill_root": skill_dir.inferred_native_path_string(),+ "next_cursor": reference_output["next_cursor"].as_str(),+ })+ );+ contents.push_str(page_contents);+ assert!(expected_contents.starts_with(&contents));}+ assert_eq!(contents, expected_contents);++ let restarted = responses::mount_sse_sequence(+ &server,+ vec![+ tool_response(+ "fresh-reference",+ "read",+ json!({"package": package, "resource": reference_resource}),+ ),+ tool_response(+ "evicted-reference",+ "read",+ json!({+ "package": package,+ "resource": reference_resource,+ "cursor": original_cursor,+ }),+ ),+ responses::sse(vec![responses::ev_completed("resp-restarted-done")]),+ ],+ )+ .await;+ timeout(+ READ_TIMEOUT,+ app_server.start_turn_and_wait_for_completion(TurnStartParams {+ thread_id,+ input: vec![UserInput::Text {+ text: "Read the changed reference, then try its old cursor.".to_string(),+ text_elements: Vec::new(),+ }],+ ..Default::default()+ }),+ )+ .await??;+ let fresh_output = restarted+ .function_call_output_text("fresh-reference")+ .expect("fresh reference output");+ assert!(fresh_output.len() <= 1200);+ let fresh: serde_json::Value = serde_json::from_str(&fresh_output)?;+ assert!(fresh["contents"].as_str().is_some_and(|page| {+ page.starts_with("CHANGED_REFERENCE") && changed_contents.starts_with(page)+ }));+ assert!(fresh["next_cursor"].is_string());+ assert_eq!(+ restarted.function_call_output_text("evicted-reference"),+ Some("skills.read cursor is stale; restart from the first page".to_string())+ );}Ok(())diff --git a/codex-rs/core/tests/suite/skills_extension.rs b/codex-rs/core/tests/suite/skills_extension.rsindex 21d0038872..df1b80d500 100644--- a/codex-rs/core/tests/suite/skills_extension.rs+++ b/codex-rs/core/tests/suite/skills_extension.rs@@ -824,15 +824,20 @@ async fn explicit_only_orchestrator_skill_is_hidden_but_can_be_invoked() -> Resuconst SKILL_PACKAGE: &str = "skill://demo/explicit-only";const MAIN_RESOURCE: &str = "skill://demo/explicit-only/SKILL.md";const REFERENCED_RESOURCE: &str = "skill://demo/explicit-only/references/guide.md";- const REFERENCED_CONTENTS: &str = "# Referenced guide";const READ_CALL_ID: &str = "read-explicit-only-resource";const LIST_CALL_ID: &str = "list-model-visible-skills";const CODE_MODE_LIST_CALL_ID: &str = "list-skills-through-code-mode";+ const CONTINUATION_CALL_ID: &str = "read-explicit-only-resource-continuation";const MAIN_READ_CALL_ID: &str = "read-explicit-only-main";const REPEATED_MAIN_READ_CALL_ID: &str = "read-explicit-only-main-again";const INVALID_CURSOR_CALL_ID: &str = "read-explicit-only-invalid-cursor";const MISSING_PACKAGE_CALL_ID: &str = "read-missing-package";+ const CODE_MODE_CALL_ID: &str = "code-mode-skill-read";+ // Fill the shared 300-byte page through the emoji; ignoring escaping would fit everything.+ let read_prefix = "a".repeat(184);+ let referenced_contents = format!("{read_prefix}π\"\\\nabcdefghijklm");+ let read_contents = referenced_contents.clone();let server = responses::start_mock_server().await;let apps_server = AppsTestServer::mount(&server).await?;let response = responses::mount_sse_sequence(@@ -868,35 +873,6 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,ev_completed("resp-1"),]),sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),- sse(vec![- ev_response_created("resp-3"),- responses::ev_function_call_with_namespace(- MAIN_READ_CALL_ID,- "skills",- "read",- &json!({ "package": SKILL_PACKAGE }).to_string(),- ),- responses::ev_function_call_with_namespace(- REPEATED_MAIN_READ_CALL_ID,- "skills",- "read",- &json!({ "package": SKILL_PACKAGE, "resource": MAIN_RESOURCE }).to_string(),- ),- responses::ev_function_call_with_namespace(- INVALID_CURSOR_CALL_ID,- "skills",- "read",- &json!({ "package": SKILL_PACKAGE, "cursor": "invalid" }).to_string(),- ),- responses::ev_function_call_with_namespace(- MISSING_PACKAGE_CALL_ID,- "skills",- "read",- &json!({ "package": "skill://demo/missing" }).to_string(),- ),- ev_completed("resp-3"),- ]),- sse(vec![ev_response_created("resp-4"), ev_completed("resp-4")]),],).await;@@ -911,7 +887,7 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,)})})- .respond_with(|request: &Request| {+ .respond_with(move |request: &Request| {let body: Value = serde_json::from_slice(&request.body).expect("MCP resource request should be valid JSON");let result = match body["method"].as_str() {@@ -947,7 +923,7 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,MAIN_RESOURCE => {format!("# Explicit-only instructions\nRead {REFERENCED_RESOURCE}.")}- REFERENCED_RESOURCE => REFERENCED_CONTENTS.to_string(),+ REFERENCED_RESOURCE => read_contents.clone(),_ => unreachable!("unexpected MCP resource URI: {uri}"),};json!({@@ -1044,16 +1020,21 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,"main_resource": MAIN_RESOURCE,}));+ let first_output = requests[1]+ .function_call_output_text(READ_CALL_ID)+ .expect("skills.read should return the referenced resource");+ assert!(first_output.len() <= 300);+ let first_page = serde_json::from_str::<Value>(&first_output)?;+ let cursor = first_page["next_cursor"]+ .as_str()+ .ok_or_else(|| anyhow::anyhow!("skills.read should return a continuation cursor"))?+ .to_string();assert_eq!(- serde_json::from_str::<Value>(- &requests[1]- .function_call_output_text(READ_CALL_ID)- .expect("skills.read should return the referenced resource"),- )?,+ first_page,json!({"resource": REFERENCED_RESOURCE,- "contents": REFERENCED_CONTENTS,- "next_cursor": null,+ "contents": format!("{read_prefix}π"),+ "next_cursor": cursor,}));let mut list_output = requests[1]@@ -1080,12 +1061,80 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,assert_eq!(events[0]["skill_name"], "demo:explicit-only");assert_eq!(events[0]["event_params"]["invoke_type"], "explicit");+ let response = responses::mount_sse_sequence(+ &server,+ vec![+ sse(vec![+ ev_response_created("resp-3"),+ responses::ev_function_call_with_namespace(+ CONTINUATION_CALL_ID,+ "skills",+ "read",+ &json!({+ "package": SKILL_PACKAGE,+ "resource": REFERENCED_RESOURCE,+ "cursor": cursor,+ })+ .to_string(),+ ),+ responses::ev_function_call_with_namespace(+ MAIN_READ_CALL_ID,+ "skills",+ "read",+ &json!({ "package": SKILL_PACKAGE }).to_string(),+ ),+ responses::ev_function_call_with_namespace(+ REPEATED_MAIN_READ_CALL_ID,+ "skills",+ "read",+ &json!({ "package": SKILL_PACKAGE, "resource": MAIN_RESOURCE }).to_string(),+ ),+ responses::ev_function_call_with_namespace(+ INVALID_CURSOR_CALL_ID,+ "skills",+ "read",+ &json!({ "package": SKILL_PACKAGE, "cursor": "invalid" }).to_string(),+ ),+ responses::ev_function_call_with_namespace(+ MISSING_PACKAGE_CALL_ID,+ "skills",+ "read",+ &json!({ "package": "skill://demo/missing" }).to_string(),+ ),+ ev_completed("resp-3"),+ ]),+ sse(vec![ev_response_created("resp-4"), ev_completed("resp-4")]),+ ],+ )+ .await;+test.submit_turn("Continue without explicitly selecting a skill.").await?;let requests = response.requests();- assert_eq!(requests.len(), 4);+ assert_eq!(requests.len(), 2);+ let continuation_output = requests[1]+ .function_call_output_text(CONTINUATION_CALL_ID)+ .expect("skills.read should return the next referenced-resource page");+ assert!(continuation_output.len() <= 300);+ let continuation_page = serde_json::from_str::<Value>(&continuation_output)?;+ assert_eq!(+ continuation_page,+ json!({+ "resource": REFERENCED_RESOURCE,+ "contents": "\"\\\nabcdefghijklm",+ "next_cursor": null,+ })+ );+ assert_eq!(+ format!(+ "{}{}",+ first_page["contents"].as_str().unwrap_or_default(),+ continuation_page["contents"].as_str().unwrap_or_default()+ ),+ referenced_contents+ );for call_id in [MAIN_READ_CALL_ID, REPEATED_MAIN_READ_CALL_ID] {- let output = requests[3]+ let output = requests[1].function_call_output_text(call_id).expect("skills.read should return the main resource");assert_eq!(@@ -1095,7 +1144,7 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,}for call_id in [INVALID_CURSOR_CALL_ID, MISSING_PACKAGE_CALL_ID] {assert!(- requests[3].function_call_output_text(call_id).is_some(),+ requests[1].function_call_output_text(call_id).is_some(),"failed skills.read should return a tool error for {call_id}");}@@ -1162,6 +1211,39 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,}}+ let response = responses::mount_sse_sequence(+ &server,+ vec![+ sse(vec![+ ev_response_created("resp-5"),+ responses::ev_custom_tool_call(+ CODE_MODE_CALL_ID,+ "exec",+ &format!(+ "const result = await tools.skills__read({{package: {SKILL_PACKAGE:?}, resource: {REFERENCED_RESOURCE:?}}}); text(JSON.stringify({{contents: result.contents, next_cursor: result.next_cursor}}));"+ ),+ ),+ ev_completed("resp-5"),+ ]),+ sse(vec![ev_response_created("resp-6"), ev_completed("resp-6")]),+ ],+ )+ .await;+ test.submit_turn("Read the complete skill resource using code mode.")+ .await?;+ let requests = response.requests();+ assert_eq!(requests.len(), 2);+ let output = requests[1].custom_tool_call_output(CODE_MODE_CALL_ID);+ let nested_result = output["output"]+ .as_array()+ .and_then(|items| items.last())+ .and_then(|item| item["text"].as_str())+ .ok_or_else(|| anyhow::anyhow!("code mode should return the nested skill result"))?;+ assert_eq!(+ serde_json::from_str::<Value>(nested_result)?,+ json!({"contents": referenced_contents, "next_cursor": null})+ );+Ok(())}diff --git a/codex-rs/ext/skills/Cargo.toml b/codex-rs/ext/skills/Cargo.tomlindex 256d0aaa87..59af40c035 100644--- a/codex-rs/ext/skills/Cargo.toml+++ b/codex-rs/ext/skills/Cargo.toml@@ -38,6 +38,7 @@ tracing = { workspace = true }url = { workspace = true }[dev-dependencies]+assert_matches = { workspace = true }codex-models-manager = { workspace = true }codex-utils-cargo-bin = { workspace = true }dunce = { workspace = true }diff --git a/codex-rs/ext/skills/src/state.rs b/codex-rs/ext/skills/src/state.rsindex b9acc5815c..dde1aa4c68 100644--- a/codex-rs/ext/skills/src/state.rs+++ b/codex-rs/ext/skills/src/state.rs@@ -2,7 +2,9 @@ use std::collections::HashMap;use std::collections::HashSet;use std::sync::Arc;use std::sync::Mutex;+use std::sync::Weak;+use codex_exec_server::Environment;use codex_exec_server::FileSystemSandboxContext;use codex_extension_api::ExtensionMetrics;use codex_mcp::McpResourceClient;@@ -41,6 +43,7 @@ pub(crate) struct SkillsThreadState {executor_discovery_cache: Mutex<Option<CachedExecutorDiscoveryCatalog>>,orchestrator_cache: Mutex<Option<Arc<OrchestratorGenerationCache>>>,shadow_selection_turn: Mutex<Option<ShadowSelectionTurn>>,+ pub(crate) executor_read_snapshot: Mutex<Option<ExecutorReadSnapshot>>,pub(crate) recent_skill_invocations: Arc<RecentSkillInvocations>,pub(crate) shadow_task_context: Arc<ShadowTaskContext>,}@@ -54,6 +57,7 @@ impl SkillsThreadState {executor_discovery_cache: Mutex::new(None),orchestrator_cache: Mutex::new(None),shadow_selection_turn: Mutex::new(None),+ executor_read_snapshot: Mutex::new(None),recent_skill_invocations: Arc::new(RecentSkillInvocations::default()),shadow_task_context: Arc::new(ShadowTaskContext::default()),}@@ -305,6 +309,17 @@ impl SkillsThreadState {}}+/// One bounded executor resource, retained for continuations until replacement or thread drop.+/// Interleaved resources may evict it; misses reread and validate the content-bound cursor.+pub(crate) struct ExecutorReadSnapshot {+ pub(crate) authority: SkillAuthority,+ pub(crate) package: SkillPackageId,+ // Named environments can be replaced; do not reuse their old resource or keep them alive.+ pub(crate) environment: Weak<Environment>,+ pub(crate) sandbox: Option<FileSystemSandboxContext>,+ pub(crate) result: Arc<SkillReadResult>,+}+struct ShadowSelectionTurn {turn_id: String,state: Arc<ShadowSelectionTurnState>,diff --git a/codex-rs/ext/skills/src/tools/read.rs b/codex-rs/ext/skills/src/tools/read.rsindex 6b5b19ef6c..4c901224ff 100644--- a/codex-rs/ext/skills/src/tools/read.rs+++ b/codex-rs/ext/skills/src/tools/read.rs@@ -1,3 +1,5 @@+use std::sync::Arc;+use codex_analytics::InvocationType;use codex_extension_api::FunctionCallError;use codex_extension_api::ToolCall;@@ -10,8 +12,10 @@ use serde::Deserialize;use serde::Serialize;use crate::catalog::SkillResourceId;+use crate::provider::MAX_SKILL_RESOURCE_CONTENT_BYTES;use crate::provider::SkillReadRequest;use crate::render::build_alias_plan;+use crate::state::ExecutorReadSnapshot;use super::MAX_HANDLE_BYTES;use super::MAX_SKILL_RESPONSE_BYTES;@@ -58,13 +62,14 @@ impl ToolExecutor<ToolCall> for ReadTool {fn spec(&self) -> ToolSpec {skill_function_tool::<ReadArgs, ReadResponse>(TOOL_NAME,- "Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue.",+ "Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue the same snapshot while it is cached; omit cursor to read again.",)}fn handle(&self, call: ToolCall) -> ToolExecutorFuture<'_> {Box::pin(async move {let args: ReadArgs = parse_args(&call)?;+ let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);validate_handle("package", &args.package, MAX_HANDLE_BYTES)?;if let Some(resource) = args.resource.as_deref() {validate_handle("resource", resource, MAX_HANDLE_BYTES)?;@@ -118,6 +123,10 @@ impl ToolExecutor<ToolCall> for ReadTool {.as_ref().map(|query| query.resolved_executor_roots.clone()).unwrap_or_default();+ let executor_environment = resolved_executor_roots+ .iter()+ .find(|root| root.selected_root().id == authority.id)+ .map(|root| Arc::downgrade(root.environment()));let sandbox = requested_resource.environment_path().and_then(|(environment_id, _)| {@@ -139,53 +148,86 @@ impl ToolExecutor<ToolCall> for ReadTool {"failed to read skill resource".to_string(),));}- let result = self- .context- .thread_state- .read_skill(- &self.context.providers,- SkillReadRequest {- authority,- package,- resource: requested_resource.clone(),- resolved_executor_roots,- sandbox,- host_snapshot: None,- mcp_resources: self.context.mcp_resources.clone(),- },- )- .await- .map_err(|err| {- tracing::warn!(- error = %err,- turn_id = %call.turn_id,- call_id = %call.call_id,- resource = requested_resource.as_str(),- "skills.read provider request failed"- );- FunctionCallError::RespondToModel("failed to read skill resource".to_string())- })?;- if result.resource != requested_resource {- return Err(FunctionCallError::Fatal(- "skill provider returned a different resource".to_string(),- ));- }- if output_authority == super::SkillToolAuthoritySelector::Orchestrator- && let Some(state) = self+ // Reuse the snapshot to avoid reading the whole file for each page. File edits+ // are not detected on cache hits, so a continuation can return old contents.+ // Snapshots have no expiry and are not cleared after the final page.+ let cached = args.cursor.as_deref().and_then(|cursor| {+ let environment = executor_environment.as_ref()?;+ let snapshot = self.context.thread_state- .shadow_selection_turn(&call.turn_id)- {- self.context- .shadow_selection- .record_invocation(&state, main_prompt.as_str());- }-- let start = parse_pagination_cursor(- args.cursor.as_deref(),- result.contents.as_str(),- "skills.read",- )?;+ .executor_read_snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let snapshot = snapshot.as_ref().filter(|snapshot| {+ snapshot.authority == authority+ && snapshot.package == package+ && snapshot.result.resource == requested_resource+ && snapshot.environment.ptr_eq(environment)+ && snapshot.sandbox == sandbox+ })?;+ let start = parse_pagination_cursor(+ Some(cursor),+ snapshot.result.contents.as_str(),+ "skills.read",+ )+ .ok()?;+ Some((Arc::clone(&snapshot.result), start))+ });+ let (result, start) = match cached {+ Some(cached) => cached,+ None => {+ let result = self+ .context+ .thread_state+ .read_skill(+ &self.context.providers,+ SkillReadRequest {+ authority: authority.clone(),+ package: package.clone(),+ resource: requested_resource.clone(),+ resolved_executor_roots,+ sandbox: sandbox.clone(),+ host_snapshot: None,+ mcp_resources: self.context.mcp_resources.clone(),+ },+ )+ .await+ .map_err(|err| {+ tracing::warn!(+ error = %err,+ turn_id = %call.turn_id,+ call_id = %call.call_id,+ resource = requested_resource.as_str(),+ "skills.read provider request failed"+ );+ FunctionCallError::RespondToModel(+ "failed to read skill resource".to_string(),+ )+ })?;+ if result.resource != requested_resource {+ return Err(FunctionCallError::Fatal(+ "skill provider returned a different resource".to_string(),+ ));+ }+ if output_authority == super::SkillToolAuthoritySelector::Orchestrator+ && let Some(state) = self+ .context+ .thread_state+ .shadow_selection_turn(&call.turn_id)+ {+ self.context+ .shadow_selection+ .record_invocation(&state, main_prompt.as_str());+ }+ let start = parse_pagination_cursor(+ args.cursor.as_deref(),+ result.contents.as_str(),+ "skills.read",+ )?;+ (Arc::new(result), start)+ }+ };if start > result.contents.len() || !result.contents.is_char_boundary(start) {return Err(FunctionCallError::RespondToModel("skills.read cursor is invalid".to_string(),@@ -204,8 +246,28 @@ impl ToolExecutor<ToolCall> for ReadTool {&result.contents,skill_root.as_deref(),start,+ response_byte_budget,)?;let output = skill_json_output(&response, output_authority)?;+ if output_authority == super::SkillToolAuthoritySelector::Executor+ && response.next_cursor.is_some()+ && result.contents.len() <= MAX_SKILL_RESOURCE_CONTENT_BYTES+ && let Some(environment) = executor_environment+ {+ *self+ .context+ .thread_state+ .executor_read_snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) =+ Some(ExecutorReadSnapshot {+ authority,+ package,+ environment,+ sandbox,+ result,+ });+ }if requested_resource == main_prompt&& args.cursor.is_none()@@ -229,6 +291,7 @@ fn page_response(contents: &str,skill_root: Option<&str>,start: usize,+ max_response_bytes: usize,) -> Result<ReadResponse, FunctionCallError> {let response = |end, next_cursor| ReadResponse {resource: resource.to_string(),@@ -237,22 +300,27 @@ fn page_response(next_cursor,};let complete = response(contents.len(), None);- if serialized_len(&complete)? <= MAX_SKILL_RESPONSE_BYTES {+ if serialized_len(&complete)? <= max_response_bytes {return Ok(complete);}- let mut end = contents.len();- while end > start {- end = start + (end - start) / 2;- while !contents.is_char_boundary(end) {- end -= 1;- }+ let mut lower = start;+ let mut upper = contents.len();+ let mut best = None;+ while lower < upper {+ // Probe strictly above lower so a multibyte character cannot stall the search.+ let end = contents.ceil_char_boundary(lower.midpoint(upper).saturating_add(1));let candidate = response(end, Some(pagination_cursor(contents, end)));- if serialized_len(&candidate)? <= MAX_SKILL_RESPONSE_BYTES {- return Ok(candidate);+ if serialized_len(&candidate)? <= max_response_bytes {+ lower = end;+ best = Some(candidate);+ } else {+ upper = contents.floor_char_boundary(end.saturating_sub(1));}}- Err(FunctionCallError::Fatal(- "skill resource handle leaves no room for contents".to_string(),- ))+ best.ok_or_else(|| {+ FunctionCallError::RespondToModel(+ "skills.read response budget leaves no room for contents".to_string(),+ )+ })}diff --git a/codex-rs/ext/skills/tests/skills_extension.rs b/codex-rs/ext/skills/tests/skills_extension.rsindex 960afe882e..dc371257ca 100644--- a/codex-rs/ext/skills/tests/skills_extension.rs+++ b/codex-rs/ext/skills/tests/skills_extension.rs@@ -4,6 +4,7 @@ use std::sync::Mutex;use std::sync::atomic::AtomicUsize;use std::sync::atomic::Ordering;+use assert_matches::assert_matches;use codex_config::ConfigLayerEntry;use codex_config::ConfigLayerSource;use codex_config::ConfigLayerStack;@@ -1767,6 +1768,40 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult)));+ let read_tool = tools+ .iter()+ .find(|tool| tool.tool_name().name == "read")+ .ok_or("skills.read tool should be registered")?;+ // The resource fits the 2400-byte budget before escaping, but not after.+ let insufficient_budget_payload = ToolPayload::Function {+ arguments: serde_json::json!({+ "package": format!("orchestrator/{opaque_suffix}"),+ })+ .to_string(),+ };+ let error = read_tool+ .handle(ToolCall {+ turn_id: "turn-1".to_string(),+ call_id: "insufficient-read-budget".to_string(),+ tool_name: read_tool.tool_name(),+ model: "gpt-test".to_string(),+ codex_turn_metadata: None,+ truncation_policy: TruncationPolicy::Bytes(2_000),+ source: ToolCallSource::Direct,+ conversation_history: ConversationHistory::default(),+ turn_item_emitter: Arc::new(NoopTurnItemEmitter),+ environments: Vec::new(),+ payload: insufficient_budget_payload,+ })+ .await+ .err()+ .expect("skills.read should reject a response that cannot fit any contents");+ let error = assert_matches!(error, FunctionCallError::RespondToModel(error) => error);+ assert_eq!(+ error,+ "skills.read response budget leaves no room for contents"+ );+Ok(())}