返回 CodeWhale
streaming.rs
根目录 / crates / engine / src / core / engine / streaming.rs
1 //! Streaming response state and guardrails.
2 //!
3 //! This module owns the local state used while decoding one model stream:
4 //! content block kind tracking, streamed tool-use buffers, retry observations,
5 //! and scrubbers for text that looks like a forged tool-call wrapper.
6
7 use crate::core::events::TurnOutcomeStatus;
8 use codewhale_models::ToolCaller;
9
10 /// A send that did not enter the existing event queue. Cancellation is not
11 /// evidence that the consumer closed, and neither is user-visible delivery.
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 pub(super) enum EventSendError {
14 Cancelled,
15 Closed,
16 }
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 pub(super) enum EventReservationPolicy {
20 /// Cancellation wins before admitting work or a new stream observation.
21 Strict,
22 /// Preserve a completed observation when capacity is already available.
23 Receipt,
24 }
25
26 /// Reserve from the one event queue. Lifecycle and terminal handoff permits
27 /// are held locally; ordinary receipts consume theirs immediately. Receipts
28 /// may enter available capacity after cancellation, but cancellation always
29 /// releases a wait on a full queue. Idle sends have no turn token to cancel.
30 pub(super) async fn reserve_event_capacity(
31 tx: &tokio::sync::mpsc::Sender<super::Event>,
32 cancel: Option<&tokio_util::sync::CancellationToken>,
33 policy: EventReservationPolicy,
34 ) -> Result<tokio::sync::mpsc::OwnedPermit<super::Event>, EventSendError> {
35 if policy == EventReservationPolicy::Receipt {
36 match tx.clone().try_reserve_owned() {
37 Ok(permit) => return Ok(permit),
38 Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
39 return Err(EventSendError::Closed);
40 }
41 Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {}
42 }
43 }
44 let reserve = tx.clone().reserve_owned();
45 match cancel {
46 Some(cancel) => tokio::select! {
47 biased;
48 () = cancel.cancelled() => Err(EventSendError::Cancelled),
49 result = reserve => result.map_err(|_| EventSendError::Closed),
50 },
51 None => reserve.await.map_err(|_| EventSendError::Closed),
52 }
53 }
54
55 /// Selective quiet affects only attempt observations; completed summaries and
56 /// counters survive. Admission and delivery use the same existing queue guard.
57 async fn emit_retry_status(
58 tx: &tokio::sync::mpsc::Sender<super::Event>,
59 cancel: &tokio_util::sync::CancellationToken,
60 quiet: bool,
61 message: String,
62 ) -> Result<(), EventSendError> {
63 let attempt = message.starts_with("Retry attempt:");
64 if quiet && attempt {
65 return Ok(());
66 }
67 let policy = if attempt {
68 EventReservationPolicy::Strict
69 } else {
70 EventReservationPolicy::Receipt
71 };
72 let permit = reserve_event_capacity(tx, Some(cancel), policy).await?;
73 permit.send(super::Event::status(message));
74 Ok(())
75 }
76
77 impl super::Engine {
78 pub(super) fn request_retry_observation(&self) -> crate::llm_client::RequestRetryObservation {
79 let tx = self.tx_event.clone();
80 let cancel = self.cancel_token.clone();
81 let quiet = self.api_config.notifications_config().quiet;
82 crate::llm_client::RequestRetryObservation {
83 request_id: format!("primary:{}", uuid::Uuid::new_v4().simple()),
84 wire_observations: Default::default(),
85 retries: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)),
86 emit: std::sync::Arc::new(move |message| {
87 let tx = tx.clone();
88 let cancel = cancel.clone();
89 Box::pin(async move {
90 let _ = emit_retry_status(&tx, &cancel, quiet, message).await;
91 })
92 }),
93 }
94 }
95
96 // The existing turn owns these cumulative counters. Closing observations
97 // describe its actual outcome, without attributing a later tool failure
98 // to an earlier provider response or changing any recovery budget.
99 pub(super) async fn send_answer_retry_summary(
100 &self,
101 diagnostics: &crate::tool_inspection::TurnStopDiagnostics,
102 status: TurnOutcomeStatus,
103 ) {
104 let (prefix, outcome) = match status {
105 TurnOutcomeStatus::Completed => ("Retry recovery", "turn completed"),
106 TurnOutcomeStatus::Failed => ("Retry stopped", "turn failed"),
107 TurnOutcomeStatus::Interrupted => ("Retry interrupted", "turn interrupted"),
108 };
109 let reasoning_kind = if self.config.reasoning_only_on_output_limit {
110 codewhale_localization::tr(
111 codewhale_localization::resolve_locale(&self.config.locale_tag),
112 codewhale_localization::MessageId::AnswerRetryCounter,
113 )
114 .into_owned()
115 } else {
116 "reasoning-only".to_string()
117 };
118 for (kind, retries, limit) in [
119 (
120 reasoning_kind.as_str(),
121 diagnostics.reasoning_only_reprompts,
122 self.config.reasoning_only_max_reprompts,
123 ),
124 (
125 "empty-stop",
126 diagnostics.empty_stop_retries,
127 super::turn_loop::EMPTY_STOP_MAX_RETRIES,
128 ),
129 ] {
130 if retries > 0 {
131 let _ = self
132 .send_retry_status(format!(
133 "{prefix}: per-kind counter {kind} used {retries}/{limit} retries; {outcome}"
134 ))
135 .await;
136 }
137 }
138 }
139
140 pub(super) async fn send_retry_status(&self, message: String) -> Result<(), EventSendError> {
141 emit_retry_status(
142 &self.tx_event,
143 &self.cancel_token,
144 self.api_config.notifications_config().quiet,
145 message,
146 )
147 .await
148 }
149
150 /// Stream observations always belong to the decoder's current turn,
151 /// including direct test/embedding calls that do not enqueue an Op.
152 pub(super) async fn send_stream_event(&self, event: super::Event) -> bool {
153 match reserve_event_capacity(
154 &self.tx_event,
155 Some(&self.cancel_token),
156 EventReservationPolicy::Strict,
157 )
158 .await
159 {
160 Ok(permit) => {
161 permit.send(event);
162 true
163 }
164 Err(_) => false,
165 }
166 }
167
168 /// Every instance emitter uses the same queue authority. Available
169 /// capacity preserves post-cancel usage/status receipts; cancellation
170 /// releases a wait for capacity. An idle refresh must not inherit the
171 /// token of an earlier interrupted turn. Stream/admission/terminal handoff
172 /// reservations retain their strict cancellation floor.
173 pub(super) async fn send_event(&self, event: super::Event) -> Result<(), EventSendError> {
174 let cancel = self
175 .turn_controls
176 .lock()
177 .unwrap_or_else(std::sync::PoisonError::into_inner)
178 .active
179 .as_ref()
180 .map(|control| control.cancel.clone());
181 let permit = reserve_event_capacity(
182 &self.tx_event,
183 cancel.as_ref(),
184 EventReservationPolicy::Receipt,
185 )
186 .await?;
187 permit.send(event);
188 Ok(())
189 }
190 }
191
192 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
193 pub(super) enum ContentBlockKind {
194 Text,
195 Thinking,
196 ToolUse,
197 }
198
199 #[derive(Debug, Clone)]
200 pub(super) struct ToolUseState {
201 pub(super) id: String,
202 pub(super) execution_id: String,
203 pub(super) name: String,
204 pub(super) input: serde_json::Value,
205 pub(super) caller: Option<ToolCaller>,
206 /// Google thought signature captured on the tool call; replayed with the
207 /// assistant tool-call message on later turns.
208 pub(super) thought_signature: Option<String>,
209 pub(super) input_buffer: String,
210 pub(super) input_parse_error: Option<String>,
211 }
212
213 impl ToolUseState {
214 pub(super) fn model_call(&self) -> crate::core::events::ModelToolCall {
215 crate::core::events::ModelToolCall {
216 provider_id: self.id.clone(),
217 caller: self.caller.clone(),
218 thought_signature: self.thought_signature.clone(),
219 }
220 }
221 }
222
223 /// A response can contain many empty tool starts without spending the byte
224 /// budget. Bound that batch before any call is retained or admitted. A lower
225 /// configured per-turn tool budget remains authoritative at execution.
226 pub(super) const MAX_TOOL_CALLS_PER_RESPONSE: usize = 256;
227
228 pub(super) fn tool_call_limit_error() -> codewhale_error_taxonomy::ErrorEnvelope {
229 codewhale_error_taxonomy::ErrorEnvelope::new(
230 codewhale_error_taxonomy::ErrorCategory::InvalidInput,
231 codewhale_error_taxonomy::ErrorSeverity::Error,
232 false,
233 "response_tool_call_limit",
234 format!(
235 "Model response exceeded the maximum of {MAX_TOOL_CALLS_PER_RESPONSE} tool calls; no call from this response was executed"
236 ),
237 )
238 }
239
240 /// Bounded authorization for re-sending a request before any output is streamed.
241 /// The turn loop holds separate budgets for proven pre-dispatch connection
242 /// failures (`stream.max_resumes`), response-header timeouts
243 /// (`stream.open_retries`), and pre-output unknown-outcome transport/stream
244 /// failures (`stream.unknown_outcome_retries`).
245 ///
246 /// Mechanism, not comment: [`StreamRetryBudget::authorize`] is the only way
247 /// to spend a resume and it returns `None` once `limit` resumes (default
248 /// [`DEFAULT_STREAM_MAX_RESUMES`]) have been issued, so no call site can loop past
249 /// the budget even if a guard predicate is relaxed. A healthy stream round
250 /// resets it.
251 ///
252 /// Not covered: a header-timeout or unknown-outcome re-send does not know
253 /// whether the provider processed (and billed) the first request, so that
254 /// request's usage stays recorded as unknown. A stream that emitted output is
255 /// never re-sent, and neither is an RLM completion request.
256 #[derive(Debug)]
257 pub(super) struct StreamRetryBudget {
258 spent: u32,
259 limit: u32,
260 }
261
262 impl Default for StreamRetryBudget {
263 fn default() -> Self {
264 Self::with_limit(codewhale_runtime::turn_budget::DEFAULT_STREAM_MAX_RESUMES)
265 }
266 }
267
268 impl StreamRetryBudget {
269 /// A fresh budget allowing at most `limit` resumes.
270 pub(super) fn with_limit(limit: u32) -> Self {
271 Self { spent: 0, limit }
272 }
273
274 /// The configured resume ceiling.
275 pub(super) fn limit(&self) -> u32 {
276 self.limit
277 }
278
279 /// Safe stream-open retries already issued without a healthy round in between.
280 pub(super) fn spent(&self) -> u32 {
281 self.spent
282 }
283
284 /// Spend one resume and return its 1-based attempt number, or `None`
285 /// when the budget is exhausted.
286 pub(super) fn authorize(&mut self) -> Option<u32> {
287 if self.spent >= self.limit {
288 return None;
289 }
290 self.spent = self.spent.saturating_add(1);
291 Some(self.spent)
292 }
293
294 /// A healthy round clears the chain: the next drop starts a fresh,
295 /// still-bounded budget.
296 pub(super) fn reset(&mut self) {
297 self.spent = 0;
298 }
299 }
300
301 fn is_excluded_from_unknown_outcome_retry(error: &anyhow::Error, message: &str) -> bool {
302 if error.chain().any(|cause| {
303 matches!(
304 cause.downcast_ref::<crate::llm_client::LlmError>(),
305 Some(
306 crate::llm_client::LlmError::QuotaExhausted(_)
307 | crate::llm_client::LlmError::QuotaWindow { .. }
308 | crate::llm_client::LlmError::RateLimited { .. }
309 | crate::llm_client::LlmError::AuthenticationError(_)
310 | crate::llm_client::LlmError::AuthorizationError(_)
311 | crate::llm_client::LlmError::InvalidRequest { .. }
312 | crate::llm_client::LlmError::ModelError(_)
313 | crate::llm_client::LlmError::ContentPolicyError(_)
314 | crate::llm_client::LlmError::ContextLengthError(_)
315 | crate::llm_client::LlmError::ServerError { .. }
316 | crate::llm_client::LlmError::HeaderTimeout { .. }
317 | crate::llm_client::LlmError::ConnectError { .. }
318 | crate::llm_client::LlmError::Other(_)
319 )
320 )
321 }) {
322 return true;
323 }
324 let full_chain = format!("{error:#}");
325 for text in [message, full_chain.as_str()] {
326 if matches!(
327 codewhale_error_taxonomy::classify_error_message(text),
328 codewhale_error_taxonomy::ErrorCategory::Authentication
329 | codewhale_error_taxonomy::ErrorCategory::Authorization
330 | codewhale_error_taxonomy::ErrorCategory::Budget
331 | codewhale_error_taxonomy::ErrorCategory::RateLimit
332 | codewhale_error_taxonomy::ErrorCategory::InvalidInput
333 ) {
334 return true;
335 }
336 let lower = text.to_ascii_lowercase();
337 if [
338 "quota",
339 "credit",
340 "billing",
341 "subscription",
342 "insufficient balance",
343 "insufficient_quota",
344 "payment required",
345 "plan limit",
346 "plan expired",
347 "upgrade your plan",
348 "unauthorized",
349 "forbidden",
350 "invalid api key",
351 "http 401",
352 "http 402",
353 "http 403",
354 "http 429",
355 "status 401",
356 "status 402",
357 "status 403",
358 "status 429",
359 "(401",
360 "(402",
361 "(403",
362 "(429",
363 ]
364 .iter()
365 .any(|needle| lower.contains(needle))
366 {
367 return true;
368 }
369 }
370 false
371 }
372
373 pub(super) fn unknown_outcome_open_retry_reason(
374 error: &anyhow::Error,
375 message: &str,
376 ) -> Option<&'static str> {
377 if is_excluded_from_unknown_outcome_retry(error, message) {
378 return None;
379 }
380 error.chain().find_map(|cause| {
381 if let Some(llm) = cause.downcast_ref::<crate::llm_client::LlmError>() {
382 return match llm {
383 crate::llm_client::LlmError::NetworkError(_) => {
384 Some("transport error with unknown outcome")
385 }
386 crate::llm_client::LlmError::Timeout(_) => {
387 Some("transport timeout with unknown outcome")
388 }
389 _ => None,
390 };
391 }
392 cause.downcast_ref::<reqwest::Error>().and_then(|err| {
393 match crate::llm_client::LlmError::from_reqwest(err) {
394 crate::llm_client::LlmError::NetworkError(_) => {
395 Some("transport error with unknown outcome")
396 }
397 crate::llm_client::LlmError::Timeout(_) => {
398 Some("transport timeout with unknown outcome")
399 }
400 _ => None,
401 }
402 })
403 })
404 }
405
406 pub(super) fn unknown_outcome_stream_retry_reason(
407 error: &anyhow::Error,
408 message: &str,
409 ) -> Option<&'static str> {
410 if is_excluded_from_unknown_outcome_retry(error, message) {
411 return None;
412 }
413 let full_chain = format!("{error:#}");
414 let combined_lower = format!(
415 "{}\n{}",
416 message.to_ascii_lowercase(),
417 full_chain.to_ascii_lowercase()
418 );
419 if [
420 "anthropic stream error",
421 "responses api error",
422 "anthropic api error",
423 "server error",
424 "http 5",
425 ]
426 .iter()
427 .any(|needle| combined_lower.contains(needle))
428 {
429 return None;
430 }
431 if combined_lower.contains("stream closed before") {
432 return Some("stream closed before completion marker with no output");
433 }
434 if unknown_outcome_open_retry_reason(error, message).is_some() {
435 return Some("stream transport failed before any output");
436 }
437 if [
438 "stream read error",
439 "error decoding response body",
440 "chunk decode error",
441 "body decode",
442 "error reading a body from connection",
443 ]
444 .iter()
445 .any(|needle| combined_lower.contains(needle))
446 {
447 return Some("stream dropped before any output");
448 }
449 None
450 }
451
452 /// Failures in a row, on one model with one upstream HTTP status, at which the
453 /// error starts saying so (#6889). Every counted failure has already spent its
454 /// transport retries, so two means two full rounds of them.
455 pub(super) const REPEATED_UPSTREAM_FAILURE_NOTICE_AT: u32 = 2;
456
457 /// Model requests that failed the same way with nothing succeeding in
458 /// between: same model, same upstream HTTP status (#6889). One 502 is a
459 /// transient fault worth retrying. The same 502 on every request is a model
460 /// that is listed but not serving, and no amount of retrying fixes that.
461 #[derive(Debug, Clone, PartialEq, Eq)]
462 pub(super) struct RepeatedUpstreamFailure {
463 model: String,
464 status: u16,
465 count: u32,
466 }
467
468 /// Record one upstream failure for `model`. Returns the line to add to its
469 /// error once the same failure has repeated
470 /// [`REPEATED_UPSTREAM_FAILURE_NOTICE_AT`] times. A different model or status
471 /// starts a new count; the caller clears the streak when a request succeeds
472 /// or fails some other way.
473 pub(super) fn note_upstream_failure(
474 streak: &mut Option<RepeatedUpstreamFailure>,
475 model: &str,
476 status: u16,
477 ) -> Option<String> {
478 let count = match streak {
479 Some(prior) if prior.model == model && prior.status == status => {
480 prior.count = prior.count.saturating_add(1);
481 prior.count
482 }
483 _ => {
484 *streak = Some(RepeatedUpstreamFailure {
485 model: model.to_string(),
486 status,
487 count: 1,
488 });
489 1
490 }
491 };
492 (count >= REPEATED_UPSTREAM_FAILURE_NOTICE_AT).then(|| {
493 format!(
494 "`{model}` has now failed {count} times in a row with HTTP {status}, after retries each time. A provider can list a model that is not serving requests. If this keeps happening, choose another model with /model."
495 )
496 })
497 }
498
499 #[cfg(test)]
500 mod repeated_upstream_failure_tests {
501 use super::{REPEATED_UPSTREAM_FAILURE_NOTICE_AT, note_upstream_failure};
502
503 #[test]
504 fn the_same_upstream_failure_is_named_once_it_repeats() {
505 let mut streak = None;
506 for _ in 1..REPEATED_UPSTREAM_FAILURE_NOTICE_AT {
507 assert_eq!(note_upstream_failure(&mut streak, "model-a", 502), None);
508 }
509 let notice = note_upstream_failure(&mut streak, "model-a", 502)
510 .expect("a repeated identical failure is named");
511 assert!(notice.contains("`model-a`"), "{notice}");
512 assert!(notice.contains("HTTP 502"), "{notice}");
513 assert!(
514 notice.contains(&format!(
515 "{REPEATED_UPSTREAM_FAILURE_NOTICE_AT} times in a row"
516 )),
517 "{notice}"
518 );
519 assert!(notice.contains("/model"), "{notice}");
520
521 // It keeps counting while nothing changes.
522 let next = note_upstream_failure(&mut streak, "model-a", 502).expect("still repeating");
523 assert!(
524 next.contains(&format!(
525 "{} times in a row",
526 REPEATED_UPSTREAM_FAILURE_NOTICE_AT + 1
527 )),
528 "{next}"
529 );
530 }
531
532 #[test]
533 fn a_different_model_or_status_or_a_success_starts_over() {
534 let mut streak = None;
535 assert_eq!(note_upstream_failure(&mut streak, "model-a", 502), None);
536 // Another status is another failure, not a repeat of the first.
537 assert_eq!(note_upstream_failure(&mut streak, "model-a", 503), None);
538 // So is another model.
539 assert_eq!(note_upstream_failure(&mut streak, "model-b", 503), None);
540 // The caller clears the streak on a success.
541 streak = None;
542 assert_eq!(note_upstream_failure(&mut streak, "model-b", 503), None);
543 assert!(note_upstream_failure(&mut streak, "model-b", 503).is_some());
544 }
545 }
546
547 /// Convert low-level reqwest/hyper stream read errors into an operator-facing
548 /// message. The raw provider error remains attached, but the lead sentence
549 /// retains the interrupted output and the unknown provider outcome.
550 pub(super) fn stream_read_error_user_message(message: &str, any_content_received: bool) -> String {
551 let lower = message.to_ascii_lowercase();
552 let is_stream_read = lower.contains("stream read error")
553 || lower.contains("error decoding response body")
554 || lower.contains("chunk decode error")
555 || lower.contains("body decode");
556 if !is_stream_read {
557 return message.to_string();
558 }
559
560 let retry_note = if any_content_received {
561 "Some output had already streamed, so Codewhale is surfacing the warning instead of replaying the request and risking duplicated output."
562 } else {
563 "No output had streamed yet; the provider request outcome is unknown and Codewhale will not replay it automatically."
564 };
565 format!(
566 "Provider stream connection dropped while reading the response body. {retry_note} Details: {message}"
567 )
568 }
569
570 /// Wrapper shapes a model may emit as plain text instead of using the API tool
571 /// channel. Each pair is `(start, end)`; the tables below are projections of
572 /// this one and must stay in sync with it.
573 ///
574 /// Three families are covered:
575 ///
576 /// 1. Generic/Anthropic-style (`[TOOL_CALL]`, `<invoke …>`, `<function_calls>`).
577 /// 2. DSML wrappers, in fullwidth `|` (U+FF5C) and ASCII `|` delimiters, upper
578 /// and lower case. DeepSeek also emits a doubled-delimiter form
579 /// (`<||DSML|| calls>`) when a request offers no tools; one-shot
580 /// `codewhale exec` printed it verbatim as the answer.
581 /// 3. **DeepSeek's native tool-call tokens** (#3880). DeepSeek's chat template
582 /// separates words with `▁` (U+2581 LOWER ONE EIGHTH BLOCK), not a space or
583 /// underscore, so `<|tool▁calls▁begin|>` does not match any DSML entry and
584 /// leaked into visible output. Both the `▁` and `_` separators are listed
585 /// because a partially-normalizing tokenizer can emit either, and both
586 /// delimiter forms because the ASCII fallback shows up in some renderings.
587 ///
588 /// When adding a shape, add it here and to the two marker tables below.
589 /// `marker_tables_are_consistent` enforces that they agree.
590 pub const TOOL_CALL_MARKER_PAIRS: [(&str, &str); 30] = [
591 ("[TOOL_CALL]", "[/TOOL_CALL]"),
592 ("<codewhale:tool_call", "</codewhale:tool_call>"),
593 ("<tool_call", "</tool_call>"),
594 ("<invoke ", "</invoke>"),
595 ("<function_calls>", "</function_calls>"),
596 ("<|DSML|tool_calls>", "</|DSML|tool_calls>"),
597 ("<|DSML|invoke ", "</|DSML|invoke>"),
598 ("<|DSML|tool_calls>", "</|DSML|tool_calls>"),
599 ("<|DSML|invoke ", "</|DSML|invoke>"),
600 ("<|dsml|tool_calls>", "</|dsml|tool_calls>"),
601 ("<|dsml|invoke ", "</|dsml|invoke>"),
602 ("<||DSML|| calls>", "</||DSML|| calls>"),
603 ("<||DSML|| invoke ", "</||DSML|| invoke>"),
604 ("<|tool_calls>", "</|tool_calls>"),
605 // DeepSeek native, fullwidth delimiters, U+2581 separator.
606 ("<|tool▁calls▁begin|>", "<|tool▁calls▁end|>"),
607 ("<|tool▁call▁begin|>", "<|tool▁call▁end|>"),
608 ("<|tool▁outputs▁begin|>", "<|tool▁outputs▁end|>"),
609 ("<|tool▁output▁begin|>", "<|tool▁output▁end|>"),
610 // DeepSeek native, ASCII delimiters, U+2581 separator.
611 ("<|tool▁calls▁begin|>", "<|tool▁calls▁end|>"),
612 ("<|tool▁call▁begin|>", "<|tool▁call▁end|>"),
613 ("<|tool▁outputs▁begin|>", "<|tool▁outputs▁end|>"),
614 ("<|tool▁output▁begin|>", "<|tool▁output▁end|>"),
615 // DeepSeek native, underscore separator.
616 ("<|tool_calls_begin|>", "<|tool_calls_end|>"),
617 ("<|tool_call_begin|>", "<|tool_call_end|>"),
618 ("<|tool_outputs_begin|>", "<|tool_outputs_end|>"),
619 ("<|tool_output_begin|>", "<|tool_output_end|>"),
620 ("<|tool_calls_begin|>", "<|tool_calls_end|>"),
621 ("<|tool_call_begin|>", "<|tool_call_end|>"),
622 ("<|tool_outputs_begin|>", "<|tool_outputs_end|>"),
623 ("<|tool_output_begin|>", "<|tool_output_end|>"),
624 ];
625
626 pub const TOOL_CALL_START_MARKERS: [&str; 30] = [
627 "[TOOL_CALL]",
628 "<codewhale:tool_call",
629 "<tool_call",
630 "<invoke ",
631 "<function_calls>",
632 "<|DSML|tool_calls>",
633 "<|DSML|invoke ",
634 "<|DSML|tool_calls>",
635 "<|DSML|invoke ",
636 "<|dsml|tool_calls>",
637 "<|dsml|invoke ",
638 "<||DSML|| calls>",
639 "<||DSML|| invoke ",
640 "<|tool_calls>",
641 "<|tool▁calls▁begin|>",
642 "<|tool▁call▁begin|>",
643 "<|tool▁outputs▁begin|>",
644 "<|tool▁output▁begin|>",
645 "<|tool▁calls▁begin|>",
646 "<|tool▁call▁begin|>",
647 "<|tool▁outputs▁begin|>",
648 "<|tool▁output▁begin|>",
649 "<|tool_calls_begin|>",
650 "<|tool_call_begin|>",
651 "<|tool_outputs_begin|>",
652 "<|tool_output_begin|>",
653 "<|tool_calls_begin|>",
654 "<|tool_call_begin|>",
655 "<|tool_outputs_begin|>",
656 "<|tool_output_begin|>",
657 ];
658
659 pub const TOOL_CALL_END_MARKERS: [&str; 30] = [
660 "[/TOOL_CALL]",
661 "</codewhale:tool_call>",
662 "</tool_call>",
663 "</invoke>",
664 "</function_calls>",
665 "</|DSML|tool_calls>",
666 "</|DSML|invoke>",
667 "</|DSML|tool_calls>",
668 "</|DSML|invoke>",
669 "</|dsml|tool_calls>",
670 "</|dsml|invoke>",
671 "</||DSML|| calls>",
672 "</||DSML|| invoke>",
673 "</|tool_calls>",
674 "<|tool▁calls▁end|>",
675 "<|tool▁call▁end|>",
676 "<|tool▁outputs▁end|>",
677 "<|tool▁output▁end|>",
678 "<|tool▁calls▁end|>",
679 "<|tool▁call▁end|>",
680 "<|tool▁outputs▁end|>",
681 "<|tool▁output▁end|>",
682 "<|tool_calls_end|>",
683 "<|tool_call_end|>",
684 "<|tool_outputs_end|>",
685 "<|tool_output_end|>",
686 "<|tool_calls_end|>",
687 "<|tool_call_end|>",
688 "<|tool_outputs_end|>",
689 "<|tool_output_end|>",
690 ];
691
692 #[derive(Debug, Default)]
693 pub struct ToolCallDeltaFilterState {
694 in_tool_call: bool,
695 marker_carry: String,
696 active_end_marker: Option<&'static str>,
697 }
698
699 /// Compact one-shot notice emitted when a model attempts to forge a tool-call
700 /// wrapper in plain text instead of using the API tool channel. The visible
701 /// content is still scrubbed; this exists so the user can see why their text
702 /// shrank.
703 pub const FAKE_WRAPPER_NOTICE: &str =
704 "Stripped non-API tool-call wrapper from model output (use the API tool channel)";
705
706 /// True if `text` contains any of the known fake-wrapper start markers. Used by
707 /// the streaming loop to decide whether to emit `FAKE_WRAPPER_NOTICE`.
708 pub fn contains_fake_tool_wrapper(text: &str) -> bool {
709 TOOL_CALL_START_MARKERS.iter().any(|m| text.contains(m))
710 }
711
712 fn find_first_marker(text: &str, markers: &[&str]) -> Option<(usize, usize)> {
713 markers
714 .iter()
715 .filter_map(|marker| text.find(marker).map(|idx| (idx, marker.len())))
716 .min_by_key(|(idx, _)| *idx)
717 }
718
719 fn find_first_start_marker(text: &str) -> Option<(usize, usize, &'static str)> {
720 TOOL_CALL_MARKER_PAIRS
721 .iter()
722 .filter_map(|(start, end)| text.find(start).map(|idx| (idx, start.len(), *end)))
723 .min_by_key(|(idx, _, _)| *idx)
724 }
725
726 /// Cheap rejection: every marker prefix ends with the marker's own first
727 /// byte, so a text without any marker's first byte cannot end with one.
728 /// Every tool-call marker starts with `<` or `[`, so this is one scan of a
729 /// usually short delta and keeps per-token `ends_with` probing off the hot
730 /// path for plain prose deltas.
731 fn fast_reject_marker_text(text: &str) -> bool {
732 !text.bytes().any(|b| b == b'<' || b == b'[')
733 }
734
735 fn trailing_marker_prefix_len(text: &str, markers: &[&str]) -> usize {
736 if fast_reject_marker_text(text) {
737 return 0;
738 }
739 markers
740 .iter()
741 .flat_map(|marker| {
742 marker
743 .char_indices()
744 .map(|(idx, _)| idx)
745 .filter(|idx| *idx > 0)
746 .chain(std::iter::once(marker.len()))
747 .filter(|idx| *idx < marker.len())
748 .filter(|idx| {
749 let prefix = &marker[..*idx];
750 text.ends_with(prefix)
751 })
752 })
753 .max()
754 .unwrap_or(0)
755 }
756
757 #[cfg(any(test, feature = "test-support"))]
758 pub fn filter_tool_call_delta(delta: &str, in_tool_call: &mut bool) -> String {
759 let mut state = ToolCallDeltaFilterState {
760 in_tool_call: *in_tool_call,
761 ..ToolCallDeltaFilterState::default()
762 };
763 let output = filter_tool_call_delta_with_state(delta, &mut state);
764 *in_tool_call = state.in_tool_call;
765 output
766 }
767
768 pub fn filter_tool_call_delta_with_state(
769 delta: &str,
770 state: &mut ToolCallDeltaFilterState,
771 ) -> String {
772 if delta.is_empty() {
773 return String::new();
774 }
775
776 let chunk;
777 let mut rest = if state.marker_carry.is_empty() {
778 delta
779 } else {
780 chunk = format!("{}{delta}", state.marker_carry);
781 state.marker_carry.clear();
782 &chunk
783 };
784 let mut output = String::new();
785
786 loop {
787 if state.in_tool_call {
788 // Close only on the opener's own end marker when it is known.
789 // Falling back to any end marker let a nested closer inside a
790 // DSML block (`</|DSML|invoke>`) end the block whenever a delta
791 // lacked the outer closer, leaking `</|DSML|tool_calls>`.
792 let active_end_marker = state.active_end_marker;
793 let found = match active_end_marker {
794 Some(marker) => rest.find(marker).map(|idx| (idx, marker.len())),
795 None => find_first_marker(rest, &TOOL_CALL_END_MARKERS),
796 };
797 let Some((idx, len)) = found else {
798 let keep = active_end_marker.map_or_else(
799 || trailing_marker_prefix_len(rest, &TOOL_CALL_END_MARKERS),
800 |marker| trailing_marker_prefix_len(rest, &[marker]),
801 );
802 if keep > 0 {
803 state.marker_carry.push_str(&rest[rest.len() - keep..]);
804 }
805 break;
806 };
807 rest = &rest[idx + len..];
808 state.in_tool_call = false;
809 state.active_end_marker = None;
810 } else {
811 let Some((idx, len, end_marker)) = find_first_start_marker(rest) else {
812 let keep = trailing_marker_prefix_len(rest, &TOOL_CALL_START_MARKERS);
813 if keep > 0 {
814 let split = rest.len() - keep;
815 output.push_str(&rest[..split]);
816 state.marker_carry.push_str(&rest[split..]);
817 } else {
818 output.push_str(rest);
819 }
820 break;
821 };
822 output.push_str(&rest[..idx]);
823 rest = &rest[idx + len..];
824 state.in_tool_call = true;
825 state.active_end_marker = Some(end_marker);
826 }
827 }
828
829 output
830 }
831
832 pub fn flush_tool_call_delta_state(state: &mut ToolCallDeltaFilterState) -> String {
833 if state.in_tool_call {
834 state.marker_carry.clear();
835 return String::new();
836 }
837 std::mem::take(&mut state.marker_carry)
838 }
839
839 lines RUST