-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprovider.rs
More file actions
6770 lines (6509 loc) · 270 KB
/
Copy pathprovider.rs
File metadata and controls
6770 lines (6509 loc) · 270 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Multi-provider chat client. The internal conversation is always kept in
// OpenAI chat-completions shape (role:"tool", assistant `tool_calls`, ...)
// because every other layer (compaction, sanitization, subagents, session
// persistence) understands that shape. Translation to/from other wire
// protocols (Anthropic Messages API) happens only at the HTTP boundary,// driven by the active `ResolvedProvider`'s `kind`. Streams SSE chunks; emits
// delta/thinking/tool_call events. Retries on transient HTTP errors with
// exponential backoff (honors Retry-After).
use crate::config::{ProviderKind, ResolvedProvider};
use crate::logging::{self, estimate_tokens, TurnTimer};
use crate::message::{self, Message, ThinkingBlock};
#[cfg(test)]
use crate::protocol::ModelInfo;
use crate::protocol::{emit, Event};
use crate::providers::adapter::{
is_non_retryable_provider_message, is_retryable_http_error, malformed_response,
ProviderAdapter, ProviderProtocol, ProviderRequest,
};
pub use crate::providers::discovery::*;
use crate::providers::registry::{adapter_for, protocol_for};
use crate::providers::sse::{SseDecoder, SseFrame};
use crate::providers::streaming::{
append_stream_tool_args, ensure_stream_tool_slot, NormalizedStreamEvent,
};
pub use crate::providers::usage::*;
use futures_util::StreamExt;
use serde_json::{json, Value};
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
#[allow(dead_code)]
pub const DEFAULT_BASE_URL: &str = "https://api.code.umans.ai/v1";
pub(crate) const MODELS_INFO_PATH: &str = "/models/info";
/// Standard OpenAI `/models` list endpoint (first-party OpenAI + Gemini's
/// OpenAI-compatible shim). Used as a fallback when `/models/info` (Umans)
/// isn't served by the endpoint.
pub(crate) const OPENAI_MODELS_PATH: &str = "/models";
const CHAT_PATH: &str = "/chat/completions";
/// Anthropic Messages API requires an `anthropic-version` header.
pub(crate) const ANTHROPIC_VERSION: &str = "2023-06-01";
/// Identity betas Anthropic's gateway expects for Claude subscription (OAuth)
/// Bearer tokens on the Messages API. Plugin OAuth providers that use Claude
/// Pro/Max should also send matching UA / x-app via plugin headers.
pub(crate) const CLAUDE_OAUTH_BETA: &str = "claude-code-20250219,oauth-2025-04-20";
pub(crate) const CLAUDE_OAUTH_USER_AGENT: &str = "claude-cli/2.1.160";
pub(crate) const CLAUDE_OAUTH_X_APP: &str = "cli";
/// True if the base URL points at an Umans endpoint. Umans accepts extra
/// fields (reasoning_effort, reasoning_content replay) that vanilla OpenAI
/// servers reject with a 400 — gate those on this check.
pub fn is_umans(base_url: &str) -> bool {
// Parse the HOST so a look-alike such as `https://api.umans.ai.evil.com/v1`
// (host `api.umans.ai.evil.com`) is NOT mistaken for Umans. A naive
// `contains("umans.ai")` substring match would enable Umans-only wire
// fields (reasoning_effort / reasoning_content) on the wrong endpoint and
// trigger 400s. Match `umans.ai` exactly or as a parent domain (subdomain).
let host = base_url
.split("://")
.nth(1)
.unwrap_or(base_url)
.split(['/', '?'])
.next()
.unwrap_or("")
.split(':')
.next()
.unwrap_or("")
.to_ascii_lowercase();
host == "umans.ai" || host.ends_with(".umans.ai")
}
/// True if the base URL points at a Kimi / Moonshot endpoint
/// (`api.kimi.com` coding subscription or `api.moonshot.ai` platform API).
/// Kimi accepts non-standard fields — top-level `thinking` / `reasoning_effort`
/// and streams `reasoning_content` — that vanilla OpenAI servers reject.
pub fn is_kimi(base_url: &str) -> bool {
let host = endpoint_host(base_url);
host == "api.kimi.com" || host == "api.moonshot.ai"
}
/// True if the base URL points at DeepSeek's official API endpoint
/// (`https://api.deepseek.com`). DeepSeek's OpenAI-compatible API accepts the
/// vendor `thinking` and `reasoning_effort` fields and streams
/// `reasoning_content`; those fields are host-gated so ordinary OpenAI
/// compatible endpoints never receive them accidentally.
pub fn is_deepseek(base_url: &str) -> bool {
endpoint_host(base_url) == "api.deepseek.com"
}
/// True if the base URL points at Zhipu / Z.ai OpenAI-compatible endpoints.
/// Exact hosts only — no suffix matching that would accept lookalikes.
pub fn is_zhipu(base_url: &str) -> bool {
let host = endpoint_host(base_url);
host == "api.z.ai" || host == "open.bigmodel.cn" || host == "open.bigmodel.com"
}
/// True if the base URL points at MiniMax Anthropic/OpenAI-compatible hosts.
/// Exact hosts only — no suffix matching that would accept lookalikes.
pub fn is_minimax(base_url: &str) -> bool {
let host = endpoint_host(base_url);
host == "api.minimax.io" || host == "api.minimaxi.com"
}
fn endpoint_host(base_url: &str) -> String {
base_url
.split("://")
.nth(1)
.unwrap_or(base_url)
.split(['/', '?'])
.next()
.unwrap_or("")
.split(':')
.next()
.unwrap_or("")
.to_ascii_lowercase()
}
/// True only for the loopback Catalyst Cursor SDK sidecar. The dedicated path
/// is intentional: it lets the OpenAI-compatible transport preserve streamed
/// SDK thinking text without enabling non-standard fields for arbitrary local
/// OpenAI servers.
pub fn is_cursor_bridge(base_url: &str) -> bool {
let Ok(url) = reqwest::Url::parse(base_url) else {
return false;
};
let loopback = match url.host_str().unwrap_or("").to_ascii_lowercase().as_str() {
"localhost" | "127.0.0.1" | "::1" | "[::1]" => true,
_ => false,
};
loopback && url.path().trim_end_matches('/') == "/cursor/v1"
}
/// LiteLLM's OpenAI-compatible proxy accepts the standard reasoning_effort
/// field and returns replayable thinking_blocks for Anthropic-backed routes.
/// Match an explicit provider name or hostname label; do not enable this for
/// every generic OpenAI-compatible server.
pub fn is_litellm_proxy(provider: &ResolvedProvider) -> bool {
provider.name.to_ascii_lowercase().contains("litellm")
|| endpoint_host(&provider.base_url)
.split('.')
.any(|label| label.contains("litellm"))
}
/// The reasoning levels offered when a model advertises none of its own
/// (and as the fallback set the TUI cycles through).
pub const DEFAULT_THINKING_LEVELS: &[&str] = &["low", "medium", "high"];
/// Resolve a requested reasoning effort against a model's advertised thinking
/// levels. If the model declares no levels (empty slice) the request passes
/// through unchanged. If it does, an unsupported effort is clamped to the
/// closest preferred level (high → medium → low → … → first listed) so the
/// model never receives an effort it can't handle (e.g. GLM only takes "high").
/// Comparison is case-insensitive; the returned string preserves the model's
/// own casing so the wire field matches what the endpoint expects.
pub fn resolve_effort(requested: &str, levels: &[String]) -> String {
if levels.is_empty() {
return requested.to_string();
}
if let Some(hit) = levels.iter().find(|l| l.eq_ignore_ascii_case(requested)) {
return hit.clone();
}
for pref in ["high", "medium", "low", "xhigh", "max", "minimal", "none"] {
if let Some(hit) = levels.iter().find(|l| l.eq_ignore_ascii_case(pref)) {
return hit.clone();
}
}
levels[0].clone()
}
/// Hard cap on a single summarize request's user payload. Larger middles are
/// map-reduced in chunks so the summarize call itself never blows the model
/// context (which used to make compaction fall back to an empty drop marker).
const MAX_SUMMARY_INPUT_CHARS: usize = 100_000;
/// Per-tool-result char budget inside the summarize payload (after digesting
/// oversized results). Keeps path/command signal without re-sending 48KB dumps.
const SUMMARY_TOOL_RESULT_CHARS: usize = 1_500;
/// Max tokens for the combined summary+facts reply.
const SUMMARY_MAX_TOKENS: u32 = 3072;
/// Truncate `s` at a char boundary, appending an ellipsis when cut.
fn trunc_chars(s: &str, n: usize) -> String {
if s.chars().count() <= n {
return s.to_string();
}
let mut out: String = s.chars().take(n).collect();
out.push('…');
out
}
/// Build a compact, image-stripped string of a message for the summarization
/// prompt. Re-serializing a multimodal message verbatim would POST megabytes
/// of base64 image data to the model (costly, and it can blow the summary
/// request's own context); image parts are replaced with a short placeholder.
/// Oversized tool results and write/edit payloads are truncated so a tool-heavy
/// middle can still be summarized instead of failing the HTTP call.
fn message_for_summary(m: &Message) -> String {
let v: Value = m.into();
let mut clean = v;
if let Some(arr) = clean.get_mut("content").and_then(|v| v.as_array_mut()) {
for part in arr.iter_mut() {
if part.get("type").and_then(|v| v.as_str()) == Some("image_url") {
*part = json!({ "type": "text", "text": "[image omitted in summary]" });
}
}
}
// Truncate large tool-result content strings.
if clean.get("role").and_then(|r| r.as_str()) == Some("tool") {
if let Some(c) = clean.get("content").and_then(|c| c.as_str()) {
if c.len() > SUMMARY_TOOL_RESULT_CHARS {
let head = trunc_chars(c, SUMMARY_TOOL_RESULT_CHARS / 2);
let tail = {
let chars: Vec<char> = c.chars().collect();
let n = SUMMARY_TOOL_RESULT_CHARS / 2;
if chars.len() > n {
chars[chars.len() - n..].iter().collect::<String>()
} else {
String::new()
}
};
clean["content"] = json!(format!(
"{head}\n…[truncated {} chars for summary]…\n{tail}",
c.len()
));
}
}
}
// Truncate huge tool-call argument payloads (write_file content, etc.).
if let Some(calls) = clean.get_mut("tool_calls").and_then(|v| v.as_array_mut()) {
for tc in calls.iter_mut() {
if let Some(args) = tc
.pointer_mut("/function/arguments")
.and_then(|a| a.as_str().map(|s| s.to_string()))
{
if args.len() > SUMMARY_TOOL_RESULT_CHARS {
*tc.pointer_mut("/function/arguments").unwrap() =
json!(trunc_chars(&args, SUMMARY_TOOL_RESULT_CHARS));
}
}
}
}
serde_json::to_string(&clean).unwrap_or_default()
}
/// Serialize messages for a summarize call, then split into char-budgeted chunks
/// so each HTTP request stays under `MAX_SUMMARY_INPUT_CHARS`.
fn summary_payload_chunks(messages: &[Message]) -> Vec<String> {
let parts: Vec<String> = messages.iter().map(message_for_summary).collect();
let mut chunks: Vec<String> = Vec::new();
let mut cur = String::new();
for p in parts {
if !cur.is_empty() && cur.len() + 1 + p.len() > MAX_SUMMARY_INPUT_CHARS {
chunks.push(std::mem::take(&mut cur));
}
if p.len() > MAX_SUMMARY_INPUT_CHARS {
// A single message still oversized after truncation — hard-slice it.
let mut offset = 0;
let bytes = p.as_bytes();
while offset < bytes.len() {
let mut end = (offset + MAX_SUMMARY_INPUT_CHARS).min(bytes.len());
while end > offset && !p.is_char_boundary(end) {
end -= 1;
}
if end == offset {
break;
}
chunks.push(p[offset..end].to_string());
offset = end;
}
continue;
}
if !cur.is_empty() {
cur.push('\n');
}
cur.push_str(&p);
}
if !cur.is_empty() {
chunks.push(cur);
}
if chunks.is_empty() {
chunks.push(String::new());
}
chunks
}
fn summary_system_prompt(instructions: Option<&str>) -> String {
const BASE_SYS: &str = "Summarize the following conversation turns in structured format. Preserve: decisions made, file paths touched, the user's goal, and any unresolved errors.\n\nAlso extract durable project facts worth remembering across future sessions (conventions, structure, key decisions, gotchas). If none, put the single word none under <facts>.\n\nUse this exact format:\n<summary>\n 1. Primary Request and Intent\n 2. Key Technical Concepts\n 3. Files and Code Sections\n 4. Errors and Fixes\n 5. Problem Solving\n 6. All User Messages\n 7. Pending Tasks\n 8. Current Work\n 9. Optional Next Step\n</summary>\n<facts>\n- fact one\n- fact two\n</facts>";
match instructions.map(str::trim).filter(|s| !s.is_empty()) {
Some(extra) => format!(
"{BASE_SYS}\n\nThe user provided the following guidance for what to preserve in this summary — honor it above the default priorities:\n{extra}"
),
None => BASE_SYS.to_string(),
}
}
/// Parse a combined summarize+facts reply into `(summary, optional_facts)`.
fn parse_summary_and_facts(raw: &str) -> (String, Option<String>) {
let trimmed = raw.trim();
let facts = {
let lower = trimmed.to_ascii_lowercase();
if let Some(start) = lower.find("<facts>") {
let after = start + "<facts>".len();
let end = lower[after..]
.find("</facts>")
.map(|i| after + i)
.unwrap_or(trimmed.len());
let body = trimmed[after..end].trim();
if body.is_empty() || body.eq_ignore_ascii_case("none") {
None
} else {
Some(body.to_string())
}
} else {
None
}
};
let summary = {
let lower = trimmed.to_ascii_lowercase();
if let Some(start) = lower.find("<summary>") {
let after = start + "<summary>".len();
let end = lower[after..]
.find("</summary>")
.map(|i| after + i)
.unwrap_or_else(|| {
lower[after..]
.find("<facts>")
.map(|i| after + i)
.unwrap_or(trimmed.len())
});
trimmed[after..end].trim().to_string()
} else if let Some(facts_at) = lower.find("<facts>") {
trimmed[..facts_at].trim().to_string()
} else {
trimmed.to_string()
}
};
(summary, facts)
}
/// Summarize a slice of messages into one system message. Used by context
/// compaction so dropped turns become a short recap instead of vanishing.
/// Non-streaming, cheap; returns None on any failure (caller keeps the
/// naive drop-oldest fallback). Protocol-agnostic: branches on the provider's
/// `kind` (OpenAI chat-completions vs Anthropic Messages).
///
/// Oversized middles are truncated per-message and map-reduced in chunks so the
/// summarize HTTP call itself rarely fails from context overflow.
#[allow(dead_code)] // convenience wrapper: production uses summarize_and_extract;
// retained as API + exercised by the mock tests below
pub async fn summarize(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
messages: &[Message],
cancel: &CancellationToken,
instructions: Option<&str>,
) -> Option<String> {
summarize_and_extract(client, provider, model, messages, cancel, instructions)
.await
.map(|(s, _)| s)
}
/// One-shot summarize + durable-fact extraction (single model call). Returns
/// `(summary, facts)` where facts is `None` when the model reported nothing
/// durable. Prefer this over separate `summarize` + `extract_facts` calls.
pub async fn summarize_and_extract(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
messages: &[Message],
cancel: &CancellationToken,
instructions: Option<&str>,
) -> Option<(String, Option<String>)> {
let sys = summary_system_prompt(instructions);
let chunks = summary_payload_chunks(messages);
if chunks.len() == 1 {
let raw = complete_text(
client,
provider,
model,
&sys,
&chunks[0],
SUMMARY_MAX_TOKENS,
cancel,
)
.await?;
return Some(parse_summary_and_facts(&raw));
}
// Map-reduce: summarize each chunk, then merge.
let mut partials: Vec<String> = Vec::with_capacity(chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
let chunk_sys = format!(
"{sys}\n\nThis is partial chunk {} of {}. Summarize only this chunk; a later merge will combine them.",
i + 1,
chunks.len()
);
let part = complete_text(
client,
provider,
model,
&chunk_sys,
chunk,
SUMMARY_MAX_TOKENS,
cancel,
)
.await?;
partials.push(part);
}
let merge_user = {
let joined = partials.join("\n\n---\n\n");
if joined.len() <= MAX_SUMMARY_INPUT_CHARS {
joined
} else {
// Hierarchical reduce would be nicer; hard-cap keeps the merge call
// from itself blowing the model context (which used to make compact
// fall back to an empty drop marker).
let mut out = String::new();
for p in &partials {
if out.len() + p.len() + 8 > MAX_SUMMARY_INPUT_CHARS {
break;
}
if !out.is_empty() {
out.push_str("\n\n---\n\n");
}
out.push_str(p);
}
if out.is_empty() {
trunc_chars(&joined, MAX_SUMMARY_INPUT_CHARS)
} else {
out
}
}
};
let merge_sys = format!(
"{sys}\n\nBelow are partial summaries of earlier conversation chunks. Merge them into one final <summary> and one <facts> block. Deduplicate; prefer later info when they conflict."
);
let raw = complete_text(
client,
provider,
model,
&merge_sys,
&merge_user,
SUMMARY_MAX_TOKENS,
cancel,
)
.await?;
Some(parse_summary_and_facts(&raw))
}
/// Extract durable facts worth remembering across future sessions from a slice of
/// the conversation. Best-effort (returns None on any failure, or if there is
/// nothing durable). Used by the session memory extraction hook on compaction.
/// Prefer [`summarize_and_extract`] when a summary is also needed (one call).
/// Protocol-agnostic: branches on the provider's `kind`.
#[allow(dead_code)] // convenience wrapper over summarize_and_extract; kept for API + tests
pub async fn extract_facts(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
messages: &[Message],
cancel: &CancellationToken,
) -> Option<String> {
summarize_and_extract(client, provider, model, messages, cancel, None)
.await
.and_then(|(_, facts)| facts)
}
/// One-shot text completion (no tools, no streaming). Returns the model's text
/// reply. Branches on provider kind so callers (summarize/extract_facts) stay
/// protocol-agnostic. `max_tokens` caps the reply (Anthropic requires it;
/// OpenAI servers ignore/apply it tolerantly).
pub(crate) async fn complete_text(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
system: &str,
user: &str,
max_tokens: u32,
cancel: &CancellationToken,
) -> Option<String> {
match provider.kind {
ProviderKind::OpenAI => {
openai_complete(client, provider, model, system, user, max_tokens, cancel).await
}
ProviderKind::Anthropic => {
anthropic_complete(client, provider, model, system, user, max_tokens, cancel).await
}
}
}
async fn openai_complete(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
system: &str,
user: &str,
max_tokens: u32,
cancel: &CancellationToken,
) -> Option<String> {
let body = json!({
"model": model,
"stream": false,
"max_tokens": max_tokens.max(256),
"messages": [
{ "role": "system", "content": system },
{ "role": "user", "content": user }
]
});
let url = format!("{}{CHAT_PATH}", provider.base_url);
// Never send `Authorization: Bearer ` with an empty token — some proxies
// treat that as present-but-invalid and return 401 instead of anonymous.
let mut req = client
.post(&url)
.json(&body)
.timeout(Duration::from_secs(120));
if let Some(k) = provider.api_key.as_deref().filter(|k| !k.is_empty()) {
req = req.bearer_auth(k);
}
// Honor provider.headers on the non-stream helper too (OpenRouter Referer,
// custom gateway keys, etc.). Without this, compaction/summary calls drop
// headers the streaming path always sends.
for (k, v) in &provider.headers {
req = req.header(k, v);
}
let resp = tokio::select! {
r = req.send() => r.ok()?,
_ = cancel.cancelled() => return None,
};
if !resp.status().is_success() {
return None;
}
let v: Value = resp.json().await.ok()?;
v.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("message"))
.and_then(|m| m.get("content"))
.and_then(|c| c.as_str())
.map(|s| s.to_string())
}
async fn anthropic_complete(
client: &reqwest::Client,
provider: &ResolvedProvider,
model: &str,
system: &str,
user: &str,
max_tokens: u32,
cancel: &CancellationToken,
) -> Option<String> {
let messages: Vec<Message> = vec![Message::system(system), Message::user(user)];
// Same floor as the streaming adapter: Anthropic rejects max_tokens:0, and
// a 1-token floor would silently truncate compact/summary replies.
let mut body =
message::build_anthropic_request(&messages, &[], "none", &[], max_tokens.max(256));
body["model"] = json!(model);
let url = crate::providers::anthropic_compatible::anthropic_messages_url(&provider.base_url);
let req = crate::providers::anthropic_compatible::apply_anthropic_auth(
client
.post(&url)
.header("anthropic-version", ANTHROPIC_VERSION)
.json(&body)
.timeout(Duration::from_secs(120)),
provider,
);
let resp = tokio::select! {
r = req.send() => r.ok()?,
_ = cancel.cancelled() => return None,
};
if !resp.status().is_success() {
return None;
}
let v: Value = resp.json().await.ok()?;
// content is an array of blocks; return the first text block's text.
v.get("content")
.and_then(|c| c.as_array())
.and_then(|blocks| {
blocks.iter().find_map(|b| {
(b.get("type").and_then(|t| t.as_str()) == Some("text"))
.then(|| b.get("text").and_then(|t| t.as_str()).map(String::from))
.flatten()
})
})
}
/// True when `k` is a primary Anthropic auth header name (case-insensitive).
fn is_anthropic_primary_auth_header(k: &str) -> bool {
k.eq_ignore_ascii_case("authorization") || k.eq_ignore_ascii_case("x-api-key")
}
/// Pick the non-empty trimmed Anthropic credential, if any.
pub(crate) fn anthropic_nonempty_key(api_key: Option<&str>) -> Option<&str> {
api_key.map(str::trim).filter(|k| !k.is_empty())
}
/// Sanitize orphaned tool_calls: ensure every tool_calls entry has a matching
/// tool result message. Context compaction can drop tool results while keeping
/// the assistant message that made the call, causing a 400. Mirrors the Umans
/// extension's before_provider_request handler.
/// Also verifies that the sanitizer doesn't leave behind a broken conversation
/// (validate that every assistant with tool_calls has corresponding tool results).
#[allow(clippy::ptr_arg)]
pub fn sanitize_orphaned_tool_calls(messages: &mut Vec<Message>) -> usize {
// Number of fixes applied (orphaned results dropped + synthetic results
// inserted). Callers persist only when this is non-zero, so clean turns pay
// just the scan with no session rewrite.
// All tool_call ids emitted by any assistant message in the kept history.
let call_ids: std::collections::HashSet<String> = messages
.iter()
.filter_map(|m| {
if m.is_assistant() {
m.tool_calls()
} else {
None
}
})
.flatten()
.map(|tc| tc.id.clone())
.collect();
// All tool_call ids that currently have a matching `role:"tool"` result.
let result_ids: std::collections::HashSet<String> = messages
.iter()
.filter_map(|m| {
if m.is_tool() {
m.tool_call_id().map(String::from)
} else {
None
}
})
.collect();
// Drop orphaned RESULTS: a `tool` message whose `tool_call_id` is not
// emitted by any remaining assistant `tool_calls`. Compaction can keep a
// tool result while dropping (or summarizing) the assistant call that
// requested it — OpenAI APIs then reject the orphaned `tool` message with a
// 400 that bricks the turn (and persists into the next). This is the
// symmetric fix to the orphaned-CALL handling below.
let before = messages.len();
messages.retain(|m| {
if m.is_tool() {
m.tool_call_id()
.map(|id| call_ids.contains(id))
.unwrap_or(false)
} else {
true
}
});
let dropped_results = before - messages.len();
// Insert synthetic results for orphaned CALLS (assistant tool_calls with no
// matching tool message). Computed against the original result_ids — the
// retain above only removed results that had no matching call, so the set
// of calls-with-results is unchanged.
let orphaned: Vec<String> = call_ids
.iter()
.filter(|id| !result_ids.contains(*id))
.cloned()
.collect();
if orphaned.is_empty() {
return dropped_results;
}
// Insert synthetic tool results right after the assistant message that made each call.
// For `finish`, never tell the model to "re-issue" — that makes the next user
// turn ignore the new prompt and call finish again. Use the same completion
// text the live finish path emits.
let mut inserted = 0;
let mut i = 0;
while i < messages.len() {
let is_assistant_with_calls =
messages[i].is_assistant() && messages[i].tool_calls().is_some();
if !is_assistant_with_calls {
i += 1;
continue;
}
let calls: Vec<(String, String)> = messages[i]
.tool_calls()
.unwrap()
.iter()
.filter(|tc| orphaned.contains(&tc.id))
.map(|tc| (tc.id.clone(), tc.function.name.clone()))
.collect();
let insert_at = i + 1;
for (k, (id, name)) in calls.iter().enumerate() {
let body = if name == "finish" {
crate::tools::FINISH_MESSAGE
} else {
"[tool result was lost — this call did not complete (the turn may have been aborted or its result dropped during context compaction). Re-issue the tool call if still needed.]"
};
messages.insert(insert_at + k, Message::tool(id, body));
inserted += 1;
}
i = insert_at + calls.len();
}
dropped_results + inserted
}
/// Read a token count from a usage field, tolerating the integer, float, and
/// string encodings different OpenAI-compatible servers emit. `as_u64` alone
/// misses floats (some proxies serialize counts as `100.0`) and quoted numbers,
/// which silently drops the context budget to zero.
/// Sanitize tool-call `arguments`: ensure every assistant tool_call's
/// `arguments` field is a valid JSON string. Some models (notably the GLM
/// family) occasionally emit malformed `arguments` for long, quote-heavy
/// commands wrapped inside `bulk`'s nested JSON. When such a message is
/// replayed in the conversation history, the API rejects the whole request
/// with "Assistant tool call function.arguments must be valid JSON", which
/// then repeats on every subsequent turn and bricks the session. This
/// replaces any malformed `arguments` (and any non-string `arguments`) with
/// the valid string `"{}"` so the history is always API-valid; the matching
/// tool dispatch already returned an actionable error to the model. Returns
/// the number of tool calls fixed.
#[allow(clippy::ptr_arg)]
pub fn sanitize_tool_call_arguments(messages: &mut Vec<Message>) -> usize {
let mut fixed = 0;
for m in messages.iter_mut() {
if !m.is_assistant() {
continue;
}
// Get mutable access to tool_calls via the Message enum
let calls = match m {
Message::Assistant {
tool_calls: Some(ref mut tc),
..
} => tc,
_ => continue,
};
for tc in calls.iter_mut() {
let malformed = serde_json::from_str::<Value>(&tc.function.arguments).is_err();
if malformed {
tc.function.arguments = "{}".to_string();
fixed += 1;
}
}
}
fixed
}
#[cfg(test)]
fn token_count(value: &Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_f64().map(|number| number as u64))
.or_else(|| value.as_str()?.trim().parse().ok())
}
/// Detect the provider failure mode where a model writes a DSML function call
/// into hidden reasoning instead of returning structured `tool_calls`.
///
/// Keep this deliberately narrow: reasoning is untrusted model output and must
/// never become executable merely because it resembles a tool invocation. The
/// caller uses this only to reject/retry an otherwise empty completion.
fn reasoning_contains_dsml_tool_call(reasoning: &str) -> bool {
let lower = reasoning.to_ascii_lowercase();
lower.contains("<|dsml|invoke")
|| lower.contains("<|dsml|invoke")
|| lower.contains("dsml|tool_calls")
|| lower.contains("dsml|tool_calls")
}
/// Add a one-shot recovery instruction without persisting it in conversation
/// history. Inserting a system message at the front is accepted by the broadest
/// set of OpenAI-compatible providers and leaves the original user turn intact.
fn add_structured_tool_call_recovery_instruction(body: &mut Value) {
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
return;
};
messages.insert(
0,
json!({
"role": "system",
"content": "Protocol recovery: your previous response had no visible assistant content and no structured tool call. Continue the task; do not end with reasoning alone. If a tool is needed, return it through the API's structured tool_calls field. If the task is complete, return a visible final response and use the finish tool when available. Do not write DSML, XML, or tool-call syntax in normal content."
}),
);
}
fn parse_dsml_tag_attributes(
tag: &str,
expected_kind: &str,
) -> Result<serde_json::Map<String, Value>, String> {
let Some(mut rest) = tag.strip_prefix(expected_kind) else {
return Err(format!("expected DSML {expected_kind} tag"));
};
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return Err(format!("invalid DSML {expected_kind} tag"));
}
let mut attrs = serde_json::Map::new();
while !rest.trim_start().is_empty() {
rest = rest.trim_start();
let Some(eq) = rest.find('=') else {
return Err(format!("invalid DSML {expected_kind} attribute"));
};
let key = &rest[..eq];
if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(format!("invalid DSML {expected_kind} attribute name"));
}
rest = &rest[eq + 1..];
let Some(quoted) = rest.strip_prefix('"') else {
return Err(format!("DSML {expected_kind} attributes must be quoted"));
};
let Some(end_quote) = quoted.find('"') else {
return Err(format!("unterminated DSML {expected_kind} attribute"));
};
if attrs
.insert(key.to_string(), json!("ed[..end_quote]))
.is_some()
{
return Err(format!("duplicate DSML {expected_kind} attribute '{key}'"));
}
rest = "ed[end_quote + 1..];
}
Ok(attrs)
}
fn recovered_dsml_call_id(index: usize) -> String {
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let sequence = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default();
format!("call_dsml_{nanos:x}_{sequence:x}_{index:x}")
}
/// Recover the model's DSML wire format into ordinary, untrusted structured
/// calls. The returned calls still go through the normal JSON parsing, tool
/// implementation validation, approval gates, sandbox, and dispatch path.
fn parse_reasoning_dsml_tool_calls(
reasoning: &str,
registered_tools: &[Value],
) -> Result<Option<Vec<ToolAccum>>, String> {
if !reasoning_contains_dsml_tool_call(reasoning) {
return Ok(None);
}
// Some model templates use ASCII bars while others use full-width bars.
let normalized = reasoning.replace("|DSML|", "|DSML|");
const WRAPPER_OPEN: &str = "<|DSML|tool_calls>";
const WRAPPER_CLOSE: &str = "</|DSML|tool_calls>";
const INVOKE_OPEN: &str = "<|DSML|invoke";
const INVOKE_CLOSE: &str = "</|DSML|invoke>";
const PARAM_OPEN: &str = "<|DSML|parameter";
const PARAM_CLOSE: &str = "</|DSML|parameter>";
let start = normalized
.rfind(WRAPPER_OPEN)
.ok_or_else(|| "missing DSML tool_calls opening tag".to_string())?;
let after_open = &normalized[start + WRAPPER_OPEN.len()..];
let close = after_open
.find(WRAPPER_CLOSE)
.ok_or_else(|| "missing DSML tool_calls closing tag".to_string())?;
if !after_open[close + WRAPPER_CLOSE.len()..].trim().is_empty() {
return Err("unexpected text after DSML tool_calls".into());
}
let mut body = &after_open[..close];
let mut calls = Vec::new();
while !body.trim_start().is_empty() {
body = body.trim_start();
if !body.starts_with(INVOKE_OPEN) {
return Err("unexpected content inside DSML tool_calls".into());
}
let open_end = body
.find('>')
.ok_or_else(|| "unterminated DSML invoke tag".to_string())?;
let invoke_tag = &body["<|DSML|".len()..open_end];
let mut invoke_attrs = parse_dsml_tag_attributes(invoke_tag, "invoke")?;
if invoke_attrs.len() != 1 {
return Err("DSML invoke must contain only a name attribute".into());
}
let name = invoke_attrs
.remove("name")
.and_then(|v| v.as_str().map(str::to_string))
.filter(|s| !s.is_empty())
.ok_or_else(|| "DSML invoke has no valid tool name".to_string())?;
let registered = registered_tools.iter().any(|tool| {
tool.get("function")
.and_then(|f| f.get("name"))
.and_then(Value::as_str)
== Some(name.as_str())
});
if !registered {
return Err(format!("DSML requested unavailable tool '{name}'"));
}
let after_invoke_open = &body[open_end + 1..];
let invoke_close = after_invoke_open
.find(INVOKE_CLOSE)
.ok_or_else(|| "missing DSML invoke closing tag".to_string())?;
let mut params_text = &after_invoke_open[..invoke_close];
let mut args = serde_json::Map::new();
while !params_text.trim_start().is_empty() {
params_text = params_text.trim_start();
if !params_text.starts_with(PARAM_OPEN) {
return Err("unexpected content inside DSML invoke".into());
}
let param_open_end = params_text
.find('>')
.ok_or_else(|| "unterminated DSML parameter tag".to_string())?;
let param_tag = ¶ms_text["<|DSML|".len()..param_open_end];
let mut param_attrs = parse_dsml_tag_attributes(param_tag, "parameter")?;
if param_attrs.len() != 2 {
return Err("DSML parameter requires only name and string attributes".into());
}
let param_name = param_attrs
.remove("name")
.and_then(|v| v.as_str().map(str::to_string))
.filter(|s| !s.is_empty())
.ok_or_else(|| "DSML parameter has no valid name".to_string())?;
let string_mode = param_attrs
.remove("string")
.and_then(|v| v.as_str().map(str::to_string))
.ok_or_else(|| "DSML parameter has no string mode".to_string())?;
let after_param_open = ¶ms_text[param_open_end + 1..];
let param_close = after_param_open
.find(PARAM_CLOSE)
.ok_or_else(|| "missing DSML parameter closing tag".to_string())?;
let raw_value = &after_param_open[..param_close];
let value = match string_mode.as_str() {
"true" => Value::String(raw_value.to_string()),
"false" => serde_json::from_str(raw_value)
.map_err(|e| format!("invalid JSON in DSML parameter '{param_name}': {e}"))?,
_ => return Err("DSML parameter string mode must be true or false".into()),
};
if args.insert(param_name.clone(), value).is_some() {
return Err(format!("duplicate DSML parameter '{param_name}'"));
}
params_text = &after_param_open[param_close + PARAM_CLOSE.len()..];
}
if calls.len() >= 32 {
return Err("too many recovered DSML tool calls".into());
}
calls.push(ToolAccum {
id: recovered_dsml_call_id(calls.len()),
name,
args: Value::Object(args).to_string(),
});
body = &after_invoke_open[invoke_close + INVOKE_CLOSE.len()..];
}
if calls.is_empty() {
return Err("DSML tool_calls wrapper contained no invocations".into());
}
Ok(Some(calls))
}
/// One streamed assistant turn. Emits `thinking`/`delta`/`tool_call` events as it goes.
/// Retries the initial POST on 429/5xx with exponential backoff (honors Retry-After).
/// Returns the finalized assistant message, finish_reason, and (in/out) token counts.
pub async fn stream_turn(
client: &reqwest::Client,
provider: &ResolvedProvider,
idle_timeout_secs: u64,
model: &str,
messages: &[Message],
tools: &[Value],
reasoning_effort: &str,
thinking_levels: &[String],
max_tokens: u32,
cancel: &CancellationToken,
timer: &mut TurnTimer,
prompt_est: u64,
quiet: bool,
cache: crate::prompt_cache::PromptCacheRequest,
) -> Result<(Value, String, u64, u64, u64, u64), String> {
timer.begin_provider_call();
let adapter = adapter_for(provider);
if !adapter.capabilities().streaming {
return Err(format!(
"provider adapter '{}' does not support streaming",
adapter.id()
));
}
let result = match protocol_for(provider) {
ProviderProtocol::GoogleCodeAssist => {
stream_turn_gemini(
client,
provider,
idle_timeout_secs,
model,
messages,
tools,
reasoning_effort,
thinking_levels,
max_tokens,
cancel,
timer,
prompt_est,
quiet,
cache,
)
.await
}
ProviderProtocol::CodexResponses => {
stream_turn_codex(
client,
provider,
idle_timeout_secs,
model,
messages,
tools,
reasoning_effort,
thinking_levels,