| 1 | use super::*; |
| 2 | |
| 3 | pub(super) fn wall_deadline(runtime: &SubAgentRuntime) -> Option<Instant> { |
| 4 | runtime |
| 5 | .worker_profile |
| 6 | .wall_deadline_ms |
| 7 | .and_then(|deadline| { |
| 8 | Instant::now().checked_add(Duration::from_millis( |
| 9 | deadline.saturating_sub(epoch_millis_now()), |
| 10 | )) |
| 11 | }) |
| 12 | } |
| 13 | |
| 14 | pub(super) fn repair_stopped_tool_calls(messages: &mut Vec<Message>, cause: &str) { |
| 15 | // Keep the final call blocks, so keys remain borrowed from their original |
| 16 | // identities while repair changes the message vector. |
| 17 | let final_calls = messages |
| 18 | .iter() |
| 19 | .rev() |
| 20 | .find(|message| message.role == Role::Assistant) |
| 21 | .map(|message| message.content.clone()) |
| 22 | .unwrap_or_default(); |
| 23 | let repair = |
| 24 | codewhale_runtime::tool_history_repair::repair_tool_call_pairs_for_provider(messages); |
| 25 | let final_message = messages |
| 26 | .iter() |
| 27 | .rposition(|message| message.role == Role::Assistant); |
| 28 | for (message_index, block_index) in repair.repaired_result_positions { |
| 29 | if !final_message.is_some_and(|index| message_index > index) { |
| 30 | continue; |
| 31 | } |
| 32 | let block = &mut messages[message_index].content[block_index]; |
| 33 | let key = block.tool_call_key(); |
| 34 | let is_final_call = key.is_some_and(|key| !key.as_str().trim().is_empty()) |
| 35 | && final_calls.iter().any(|call| { |
| 36 | matches!(call, ContentBlock::ToolUse { .. }) && call.tool_call_key() == key |
| 37 | }); |
| 38 | if is_final_call && let ContentBlock::ToolResult { content, .. } = block { |
| 39 | *content = format!( |
| 40 | "Tool call not executed: task execution stopped at its budget boundary. Terminal status: budget_exhausted. {cause}" |
| 41 | ); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | const HANDBACK_DIGEST_DIR: &str = "subagent-results"; |
| 47 | |
| 48 | /// Private state-root path of a child's budget-death result artifact |
| 49 | /// (#6536). Derived from `agent_id`, never accepted from input. |
| 50 | fn digest_artifact_relative_path(agent_id: &str) -> PathBuf { |
| 51 | let digest = codewhale_runtime::hashing::sha256_hex(agent_id.as_bytes()); |
| 52 | Path::new(".codewhale") |
| 53 | .join("state") |
| 54 | .join(HANDBACK_DIGEST_DIR) |
| 55 | .join(format!("{digest}.md")) |
| 56 | } |
| 57 | |
| 58 | /// Record the child's budget-death deliverable as a private file under the |
| 59 | /// manager state root (#6536). The host stores its retained result |
| 60 | /// here before terminal delivery. Blocking IO runs under `spawn_blocking`. |
| 61 | /// |
| 62 | /// Known limitation: the file outlives the agent record; removing an agent |
| 63 | /// does not delete it. |
| 64 | pub(super) async fn write_digest_artifact( |
| 65 | runtime: &SubAgentRuntime, |
| 66 | agent_id: &str, |
| 67 | body: String, |
| 68 | ) -> Option<PathBuf> { |
| 69 | let state_root = runtime.manager.read().await.state_root.clone(); |
| 70 | let agent = agent_id.to_string(); |
| 71 | let written = tokio::task::spawn_blocking(move || -> Result<PathBuf> { |
| 72 | let relative = digest_artifact_relative_path(&agent); |
| 73 | let path = checked_subagent_state_path(&state_root, &relative)?; |
| 74 | create_private_subagent_transcript(&state_root, &path, body.as_bytes())?; |
| 75 | Ok(path) |
| 76 | }) |
| 77 | .await; |
| 78 | match written { |
| 79 | Ok(Ok(path)) => Some(path), |
| 80 | Ok(Err(error)) => { |
| 81 | tracing::warn!(target: "subagent", agent_id, %error, "budget digest artifact not written"); |
| 82 | None |
| 83 | } |
| 84 | Err(error) => { |
| 85 | tracing::warn!(target: "subagent", agent_id, %error, "budget digest artifact task failed"); |
| 86 | None |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | pub(super) fn preview_partial_text(text: &str) -> String { |
| 92 | const MAX_TEXT_CHARS: usize = 4_000; |
| 93 | let total = text.chars().count(); |
| 94 | if total <= MAX_TEXT_CHARS { |
| 95 | return text.to_string(); |
| 96 | } |
| 97 | let preview: String = text.chars().take(MAX_TEXT_CHARS).collect(); |
| 98 | format!( |
| 99 | "[Partial output truncated: {MAX_TEXT_CHARS} of {total} characters shown. To inspect the retained transcript, request agent status with detail and read its transcript_handle.]\n{preview}" |
| 100 | ) |
| 101 | } |
| 102 | |
| 103 | /// Everything is bounded; the parent gets evidence, never a report. |
| 104 | pub fn fallback_partial_text(messages: &[Message]) -> String { |
| 105 | const MAX_TOOL_ENTRIES: usize = 12; |
| 106 | const MAX_THINKING_BYTES: usize = 1_500; |
| 107 | |
| 108 | if let Some(text) = messages |
| 109 | .iter() |
| 110 | .rev() |
| 111 | .filter(|message| message.role == Role::Assistant) |
| 112 | .flat_map(|message| message.content.iter().rev()) |
| 113 | .find_map(|block| match block { |
| 114 | ContentBlock::Text { text, .. } if !text.trim().is_empty() => Some(text), |
| 115 | _ => None, |
| 116 | }) |
| 117 | { |
| 118 | return preview_partial_text(text); |
| 119 | } |
| 120 | let mut tools = Vec::new(); |
| 121 | let mut extra_tools = 0usize; |
| 122 | let mut thinking = None; |
| 123 | for message in messages.iter().rev() { |
| 124 | if message.role != Role::Assistant { |
| 125 | continue; |
| 126 | } |
| 127 | for block in message.content.iter().rev() { |
| 128 | match block { |
| 129 | ContentBlock::ToolUse { name, input, .. } => { |
| 130 | if tools.len() < MAX_TOOL_ENTRIES { |
| 131 | tools.push(format!("{name} {}", tool_target_preview(input))); |
| 132 | } else { |
| 133 | extra_tools += 1; |
| 134 | } |
| 135 | } |
| 136 | ContentBlock::Thinking { thinking: text, .. } |
| 137 | if thinking.is_none() && !text.trim().is_empty() => |
| 138 | { |
| 139 | thinking = Some(text); |
| 140 | } |
| 141 | _ => {} |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | if tools.is_empty() && thinking.is_none() { |
| 146 | return "No assistant text was recorded; inspect the checkpoint for completed tool work." |
| 147 | .to_string(); |
| 148 | } |
| 149 | let mut digest = |
| 150 | String::from("No assistant text was recorded. Work recorded before the budget death:"); |
| 151 | if !tools.is_empty() { |
| 152 | digest.push_str("\nTool calls (newest first):"); |
| 153 | for entry in &tools { |
| 154 | digest.push_str(&format!("\n- {entry}")); |
| 155 | } |
| 156 | if extra_tools > 0 { |
| 157 | digest.push_str(&format!("\n- ...and {extra_tools} more")); |
| 158 | } |
| 159 | } |
| 160 | if let Some(text) = thinking { |
| 161 | digest.push_str("\nLatest reasoning (unverified, may be incomplete):\n"); |
| 162 | digest.push_str(&lifecycle::text_preview(text, MAX_THINKING_BYTES)); |
| 163 | } |
| 164 | digest |
| 165 | } |
| 166 | |
| 167 | /// One-line target for a recorded tool call: the well-known path/commandish |
| 168 | /// key when present, else a truncated rendering of the whole input. |
| 169 | fn tool_target_preview(input: &serde_json::Value) -> String { |
| 170 | const KEYS: [&str; 7] = [ |
| 171 | "path", |
| 172 | "file", |
| 173 | "file_path", |
| 174 | "command", |
| 175 | "pattern", |
| 176 | "query", |
| 177 | "url", |
| 178 | ]; |
| 179 | for key in KEYS { |
| 180 | if let Some(hit) = input.get(key).and_then(serde_json::Value::as_str) |
| 181 | && !hit.trim().is_empty() |
| 182 | { |
| 183 | return lifecycle::text_preview(hit, 120); |
| 184 | } |
| 185 | } |
| 186 | if let Some(hit) = input.as_str() { |
| 187 | return lifecycle::text_preview(hit, 120); |
| 188 | } |
| 189 | lifecycle::text_preview(&input.to_string(), 120) |
| 190 | } |
| 191 |