greentic-aw-runtime 1.2.2

Enterprise Agentic Worker runtime — Plan-Act-Observe loop, Redis state, tool dispatch via greentic-ext-runtime
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
//! OpenAI Chat Completions API client (function-calling mode).
//! Single backend MVP; multi-provider routing deferred (spec §10).

use futures::StreamExt;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

use crate::error::LlmError;
use crate::llm::{LlmBackend, LlmRequest, LlmResponse, LlmToolSchema, MALFORMED_ARGS_KEY, OnDelta};
use crate::state::{ChatMessage, ToolCallRecord};
use crate::tool_wire_name::{ToolNameCodec, wire_tool_name};

/// Maximum time to wait between consecutive bytes from the streaming
/// response before treating the connection as dead. reqwest's client
/// `.timeout()` bounds the *whole* request, not the gap between chunks,
/// so a server that opens the stream and then stalls would otherwise hang
/// indefinitely. Overridable only in tests for fast, deterministic checks.
const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(60);

/// TCP connect bound for every request.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Bound on a blocking completion as a whole, and on the wait for a streaming
/// response's head. NOT applied to a streaming body (see `STREAM_IDLE_TIMEOUT`).
const REQUEST_TIMEOUT: Duration = Duration::from_secs(45);

/// Endpoint used when [`ENV_BASE_URL`] names none.
const DEFAULT_BASE_URL: &str = "https://api.openai.com";

/// Names an OpenAI-compatible endpoint (Ollama, vLLM, LiteLLM, a gateway, …).
///
/// This is the ORIGIN, not the API root: the request paths below append
/// `/v1/chat/completions` themselves, so the value is `http://127.0.0.1:11434`
/// and not `http://127.0.0.1:11434/v1`.
///
/// Already read by the `greentic-llm-backend` path in greentic-runner-host;
/// honouring it here too is what lets a STOCK default build reach a non-OpenAI
/// endpoint with no feature flag.
const ENV_BASE_URL: &str = "GREENTIC_LLM_BASE_URL";

pub struct OpenAiLlmBackend {
    api_key: String,
    base_url: String,
    client: Client,
    request_timeout: Duration,
}

impl OpenAiLlmBackend {
    /// Build a backend against the endpoint named by [`ENV_BASE_URL`], falling
    /// back to OpenAI's own host when that variable is unset or blank.
    ///
    /// Reading the env HERE rather than only at the call sites is deliberate.
    /// This type is what `in_process_llm_backend_with_key` constructs on the
    /// default build, where the `greentic-llm-backend` block that reads the same
    /// variable is not compiled in — so until this change an Ollama or other
    /// OpenAI-compatible endpoint was unreachable from a stock binary no matter
    /// how it was configured, and every dw.agent call went to api.openai.com.
    /// The two paths now agree on one variable.
    ///
    /// [`with_base_url`](Self::with_base_url) still takes an explicit endpoint
    /// and ignores the env, for callers that must pin one (tests included).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::with_base_url(api_key, base_url_from_env())
    }

    /// Build a backend against an explicitly supplied endpoint, ignoring
    /// [`ENV_BASE_URL`].
    pub fn with_base_url(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: base_url.into(),
            request_timeout: REQUEST_TIMEOUT,
            // No whole-request `.timeout()`: it would also cut a long
            // streaming body after deltas were already emitted (not
            // retryable). The blocking path sets a per-request timeout, the
            // streaming path bounds time-to-first-byte and each chunk gap.
            client: Client::builder()
                .connect_timeout(CONNECT_TIMEOUT)
                .build()
                .unwrap_or_else(|_| Client::new()),
        }
    }
}

/// Resolve the endpoint from [`ENV_BASE_URL`], falling back to [`DEFAULT_BASE_URL`].
fn base_url_from_env() -> String {
    normalize_base_url(std::env::var(ENV_BASE_URL).ok())
}

/// The pure half of [`base_url_from_env`], split out so it is testable without
/// mutating process-global env (which races every other test in the binary).
///
/// An unset, blank or whitespace-only value means "the operator configured
/// nothing", not "use the empty string" — both fall back to OpenAI's host. A
/// trailing slash is trimmed because the request paths append `/v1/...`, and
/// `https://host//v1/chat/completions` is a 404 on several gateways.
fn normalize_base_url(configured: Option<String>) -> String {
    configured
        .map(|url| url.trim().trim_end_matches('/').to_string())
        .filter(|url| !url.is_empty())
        .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
}

#[derive(Serialize)]
struct OaRequest<'a> {
    model: &'a str,
    messages: Vec<OaMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<OaTool<'a>>>,
    tool_choice: &'static str,
    /// `Some(true)` on the streaming path; `None` (omitted) on the
    /// blocking path so the request body is byte-identical to before.
    #[serde(skip_serializing_if = "Option::is_none")]
    stream: Option<bool>,
    /// `Some({"include_usage": true})` on the streaming path so the final
    /// chunk carries token usage; `None` (omitted) on the blocking path.
    #[serde(skip_serializing_if = "Option::is_none")]
    stream_options: Option<serde_json::Value>,
}

#[derive(Serialize)]
#[serde(tag = "role", rename_all = "snake_case")]
enum OaMessage {
    System {
        content: String,
    },
    User {
        content: String,
    },
    Assistant {
        content: Option<String>,
        // OpenAI rejects `tool_calls: []` (400, code `empty_array`) on a
        // multi-turn request — omit the field entirely for a text-only
        // assistant turn (it's only valid with >=1 call).
        #[serde(skip_serializing_if = "Vec::is_empty")]
        tool_calls: Vec<OaToolCallEmit>,
    },
    Tool {
        tool_call_id: String,
        content: String,
    },
}

#[derive(Serialize)]
struct OaToolCallEmit {
    id: String,
    #[serde(rename = "type")]
    typ: &'static str,
    function: OaToolFn,
}

#[derive(Serialize)]
struct OaToolFn {
    name: String,
    arguments: String,
}

#[derive(Serialize)]
struct OaTool<'a> {
    #[serde(rename = "type")]
    typ: &'static str,
    function: OaToolDef<'a>,
}

#[derive(Serialize)]
struct OaToolDef<'a> {
    name: String,
    description: &'a str,
    parameters: &'a serde_json::Value,
}

#[derive(Deserialize)]
struct OaResponse {
    choices: Vec<OaChoice>,
    /// Some OpenAI-compatible endpoints omit `usage`: that must not fail an
    /// otherwise good reply (tokens then count as 0).
    #[serde(default)]
    usage: Option<OaUsage>,
}

#[derive(Deserialize)]
struct OaChoice {
    message: OaMessageIn,
    #[serde(default)]
    finish_reason: Option<String>,
}

#[derive(Deserialize)]
struct OaMessageIn {
    content: Option<String>,
    tool_calls: Option<Vec<OaToolCallIn>>,
}

#[derive(Deserialize)]
struct OaToolCallIn {
    id: String,
    function: OaToolFnIn,
}

#[derive(Deserialize)]
struct OaToolFnIn {
    name: String,
    arguments: String, // JSON-encoded string per OpenAI spec
}

#[derive(Deserialize)]
struct OaUsage {
    #[serde(default)]
    prompt_tokens: u32,
    #[serde(default)]
    completion_tokens: u32,
}

impl LlmBackend for OpenAiLlmBackend {
    fn complete<'a>(
        &'a self,
        req: LlmRequest,
    ) -> Pin<Box<dyn Future<Output = Result<LlmResponse, LlmError>> + Send + 'a>> {
        Box::pin(async move {
            let messages = build_messages(&req);
            // Built from the list the model is about to be shown: a sanitised
            // wire name cannot be split back apart by string surgery.
            let codec = ToolNameCodec::for_tools(&req.tools);
            let tools: Option<Vec<OaTool<'_>>> = if req.tools.is_empty() {
                None
            } else {
                Some(req.tools.iter().map(build_tool).collect())
            };
            let body = OaRequest {
                model: &req.provider.model,
                messages,
                tools,
                tool_choice: "auto",
                stream: None,
                stream_options: None,
            };
            let url = format!("{}/v1/chat/completions", self.base_url);
            let resp = self
                .client
                .post(&url)
                .bearer_auth(&self.api_key)
                .json(&body)
                .timeout(self.request_timeout)
                .send()
                .await
                .map_err(|e| LlmError::Transport(e.without_url().to_string()))?;
            let status = resp.status();
            if status.is_server_error() {
                return Err(LlmError::ServiceUnavailable);
            }
            if !status.is_success() {
                let text = resp.text().await.unwrap_or_default();
                return Err(map_client_error(status, &text));
            }
            let oa: OaResponse = resp
                .json()
                .await
                .map_err(|e| LlmError::Decode(e.without_url().to_string()))?;
            let choice = oa
                .choices
                .into_iter()
                .next()
                .ok_or_else(|| LlmError::Decode("no choices".into()))?;
            check_finish_reason(
                choice.finish_reason.as_deref(),
                choice
                    .message
                    .tool_calls
                    .as_ref()
                    .is_some_and(|calls| !calls.is_empty()),
            )?;
            let tool_calls = choice
                .message
                .tool_calls
                .unwrap_or_default()
                .into_iter()
                .map(|c| {
                    build_tool_call_record(&codec, c.id, &c.function.name, &c.function.arguments)
                })
                .collect();
            Ok(LlmResponse {
                content: choice.message.content,
                tool_calls,
                tokens_in: oa.usage.as_ref().map_or(0, |u| u.prompt_tokens),
                tokens_out: oa.usage.as_ref().map_or(0, |u| u.completion_tokens),
            })
        })
    }

    /// Streaming completion over the OpenAI SSE protocol.
    ///
    /// The response body is split into lines at the byte level (so a
    /// multi-byte UTF-8 scalar straddling a network-chunk boundary is never
    /// corrupted to `U+FFFD`) and each complete line is fed to
    /// [`StreamAccumulator::push_line`]. Each `stream.next()` await is bounded
    /// by a 60s idle timeout ([`STREAM_IDLE_TIMEOUT`]): reqwest's client
    /// `.timeout()` bounds the whole request, not the gap between chunks, so a
    /// stalled-but-open stream would otherwise hang. On idle elapse this
    /// returns [`LlmError::Transport`] `"stream idle timeout"`.
    fn complete_streaming<'a>(
        &'a self,
        req: LlmRequest,
        on_delta: OnDelta,
    ) -> Pin<Box<dyn Future<Output = Result<LlmResponse, LlmError>> + Send + 'a>> {
        Box::pin(async move {
            let messages = build_messages(&req);
            // Built from the list the model is about to be shown: a sanitised
            // wire name cannot be split back apart by string surgery.
            let codec = ToolNameCodec::for_tools(&req.tools);
            let tools: Option<Vec<OaTool<'_>>> = if req.tools.is_empty() {
                None
            } else {
                Some(req.tools.iter().map(build_tool).collect())
            };
            let body = OaRequest {
                model: &req.provider.model,
                messages,
                tools,
                tool_choice: "auto",
                stream: Some(true),
                stream_options: Some(serde_json::json!({ "include_usage": true })),
            };
            let url = format!("{}/v1/chat/completions", self.base_url);
            let resp = self
                .client
                .post(&url)
                .bearer_auth(&self.api_key)
                .json(&body)
                .send();
            // Bound only the wait for the response head; the body is bounded
            // per chunk below, never as a whole.
            let resp = tokio::time::timeout(self.request_timeout, resp)
                .await
                .map_err(|_| LlmError::Transport("response header timeout".into()))?
                .map_err(|e| LlmError::Transport(e.without_url().to_string()))?;
            let status = resp.status();
            // A non-2xx response is an error body, not an SSE stream — read
            // it whole and map exactly like the blocking path.
            if status.is_server_error() {
                return Err(LlmError::ServiceUnavailable);
            }
            if !status.is_success() {
                let text = resp.text().await.unwrap_or_default();
                return Err(map_client_error(status, &text));
            }

            let mut acc = StreamAccumulator::new();
            let mut line_buf = SseLineBuffer::new();
            let mut stream = resp.bytes_stream();
            // Bound the gap between chunks: reqwest's request timeout does not
            // cover an open-but-stalled stream.
            while let Some(chunk) = tokio::time::timeout(STREAM_IDLE_TIMEOUT, stream.next())
                .await
                .map_err(|_| LlmError::Transport("stream idle timeout".into()))?
            {
                let bytes = chunk.map_err(|e| LlmError::Transport(e.without_url().to_string()))?;
                for line in line_buf.push_bytes(&bytes) {
                    if let Some(text) = acc.push_line(&line)? {
                        on_delta(&text);
                    }
                }
            }
            // Flush any trailing line without a terminating newline so a
            // missing final newline does not drop the last event.
            if let Some(line) = line_buf.take_remainder()
                && let Some(text) = acc.push_line(&line)?
            {
                on_delta(&text);
            }
            // A body that ends without `[DONE]` or a `finish_reason` was cut
            // off (proxy reset, server crash): never treat it as a reply.
            acc.check_complete()?;
            Ok(acc.finish(&codec))
        })
    }
}

/// Byte-level line splitter for an SSE response body.
///
/// SSE chunks arrive as arbitrary byte slices: a single multi-byte UTF-8
/// scalar (e.g. `é`, an emoji) can be split across two network chunks.
/// Decoding each raw chunk independently with `from_utf8_lossy` would turn
/// the split bytes into `U+FFFD`, corrupting the emitted delta. This buffer
/// holds raw bytes and only decodes **complete** lines (terminated by `\n`),
/// so a scalar straddling a chunk boundary is reassembled before decoding.
struct SseLineBuffer {
    buf: Vec<u8>,
}

impl SseLineBuffer {
    fn new() -> Self {
        Self { buf: Vec::new() }
    }

    /// Append `bytes` and return every newly-completed line, with trailing
    /// `\r`/`\n` stripped. Bytes after the last `\n` are retained for the
    /// next call. Decoding happens only on whole lines, so a multi-byte
    /// scalar split across calls is never turned into `U+FFFD`.
    fn push_bytes(&mut self, bytes: &[u8]) -> Vec<String> {
        self.buf.extend_from_slice(bytes);
        let mut lines = Vec::new();
        while let Some(idx) = self.buf.iter().position(|&b| b == b'\n') {
            let line_bytes: Vec<u8> = self.buf.drain(..=idx).collect();
            let line = String::from_utf8_lossy(&line_bytes);
            lines.push(line.trim_end_matches(['\r', '\n']).to_string());
        }
        lines
    }

    /// Decode any remaining bytes that were never newline-terminated as a
    /// final line. Returns `None` when the buffer is empty. Call once after
    /// the stream ends so a missing trailing newline does not drop the last
    /// event.
    fn take_remainder(&mut self) -> Option<String> {
        if self.buf.is_empty() {
            return None;
        }
        let line = String::from_utf8_lossy(&self.buf);
        let line = line.trim_end_matches(['\r', '\n']).to_string();
        self.buf.clear();
        Some(line)
    }
}

/// Pure accumulator for OpenAI streaming (SSE) chat-completion chunks.
///
/// Fed one `data: ...` line at a time via [`StreamAccumulator::push_line`],
/// it concatenates content deltas, reassembles indexed tool-call fragments
/// (`id`/`name` arrive once; `arguments` concatenate across chunks), and
/// captures token usage from the final chunk. [`StreamAccumulator::finish`]
/// projects the accumulated state into an [`LlmResponse`], reusing the same
/// `split_tool_name` + `unwrap_or(json!({}))` argument parsing as the
/// blocking path.
struct StreamAccumulator {
    content: String,
    /// Tool-call fragments keyed by their stream `index` (stable ordering).
    tool_calls: BTreeMap<u32, ToolCallFrag>,
    tokens_in: u32,
    tokens_out: u32,
    /// Saw the `data: [DONE]` terminator.
    done: bool,
    /// Last non-null `finish_reason` any choice reported.
    finish_reason: Option<String>,
}

#[derive(Default)]
struct ToolCallFrag {
    id: String,
    name: String,
    arguments: String,
}

impl StreamAccumulator {
    fn new() -> Self {
        Self {
            content: String::new(),
            tool_calls: BTreeMap::new(),
            tokens_in: 0,
            tokens_out: 0,
            done: false,
            finish_reason: None,
        }
    }

    /// Whether the stream ended the way a provider ends a finished reply:
    /// `[DONE]` or a `finish_reason`. Also rejects a reply cut at the token
    /// limit while it was still emitting a tool call.
    fn check_complete(&self) -> Result<(), LlmError> {
        if !self.done && self.finish_reason.is_none() {
            return Err(LlmError::Transport(
                "stream ended before [DONE] or a finish_reason".into(),
            ));
        }
        check_finish_reason(self.finish_reason.as_deref(), !self.tool_calls.is_empty())
    }

    /// Parse one streaming line. Returns `Ok(Some(text))` when the line
    /// carried a content delta to emit, `Ok(None)` for non-content lines
    /// (tool-call fragments, usage, keep-alives, `[DONE]`, blank lines).
    fn push_line(&mut self, line: &str) -> Result<Option<String>, LlmError> {
        let line = line.trim();
        if line.is_empty() {
            return Ok(None);
        }
        let payload = match line.strip_prefix("data:") {
            Some(rest) => rest.trim(),
            None => return Ok(None), // comments / keep-alives
        };
        if payload == "[DONE]" {
            self.done = true;
            return Ok(None);
        }
        let chunk: OaStreamChunk =
            serde_json::from_str(payload).map_err(|e| LlmError::Decode(e.to_string()))?;
        if let Some(usage) = chunk.usage {
            self.tokens_in = usage.prompt_tokens;
            self.tokens_out = usage.completion_tokens;
        }
        let mut emit: Option<String> = None;
        for choice in chunk.choices {
            if let Some(reason) = choice.finish_reason {
                self.finish_reason = Some(reason);
            }
            let delta = choice.delta;
            if let Some(text) = delta.content
                && !text.is_empty()
            {
                self.content.push_str(&text);
                emit = Some(text);
            }
            for tc in delta.tool_calls.unwrap_or_default() {
                let frag = self.tool_calls.entry(tc.index).or_default();
                if let Some(id) = tc.id {
                    frag.id = id;
                }
                if let Some(func) = tc.function {
                    if let Some(name) = func.name {
                        frag.name = name;
                    }
                    if let Some(args) = func.arguments {
                        frag.arguments.push_str(&args);
                    }
                }
            }
        }
        Ok(emit)
    }

    fn finish(self, codec: &ToolNameCodec) -> LlmResponse {
        let tool_calls = self
            .tool_calls
            .into_values()
            .map(|frag| build_tool_call_record(codec, frag.id, &frag.name, &frag.arguments))
            .collect();
        let content = if self.content.is_empty() {
            None
        } else {
            Some(self.content)
        };
        LlmResponse {
            content,
            tool_calls,
            tokens_in: self.tokens_in,
            tokens_out: self.tokens_out,
        }
    }
}

#[derive(Deserialize)]
struct OaStreamChunk {
    #[serde(default)]
    choices: Vec<OaStreamChoice>,
    #[serde(default)]
    usage: Option<OaUsage>,
}

#[derive(Deserialize)]
struct OaStreamChoice {
    delta: OaStreamDelta,
    #[serde(default)]
    finish_reason: Option<String>,
}

#[derive(Deserialize, Default)]
struct OaStreamDelta {
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    tool_calls: Option<Vec<OaStreamToolCall>>,
}

#[derive(Deserialize)]
struct OaStreamToolCall {
    index: u32,
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    function: Option<OaStreamToolFn>,
}

#[derive(Deserialize)]
struct OaStreamToolFn {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    arguments: Option<String>,
}

/// Build a [`ToolCallRecord`] from the raw pieces an OpenAI tool call
/// carries: the call id, the dotted `extension.tool` name, and the
/// JSON-encoded `arguments` string. Shared by the blocking ([`complete`])
/// and streaming ([`StreamAccumulator::finish`]) paths so both decode
/// arguments and split the name identically. Malformed argument JSON does NOT
/// degrade to `{}` (that would run the tool with no arguments): the raw text is
/// parked under [`MALFORMED_ARGS_KEY`] and the loop answers the call with a
/// tool error instead of dispatching it.
///
/// [`complete`]: OpenAiLlmBackend::complete
fn build_tool_call_record(
    codec: &ToolNameCodec,
    call_id: String,
    name: &str,
    raw_args: &str,
) -> ToolCallRecord {
    let args = parse_tool_args(raw_args);
    let (extension_id, tool_name) = codec.decode(name);
    ToolCallRecord {
        call_id,
        extension_id,
        tool_name,
        args,
    }
}

/// Longest slice of unparseable arguments echoed back to the model.
const MALFORMED_ARGS_ECHO_BYTES: usize = 512;

/// Parse a tool call's JSON-encoded `arguments`. A blank string is a call with
/// no arguments (`{}`); text that is not valid JSON becomes
/// `{ MALFORMED_ARGS_KEY: "<prefix of the raw text>" }`.
fn parse_tool_args(raw_args: &str) -> serde_json::Value {
    if raw_args.trim().is_empty() {
        return serde_json::json!({});
    }
    match serde_json::from_str(raw_args) {
        Ok(value) => value,
        Err(_) => {
            let mut cut = raw_args.len().min(MALFORMED_ARGS_ECHO_BYTES);
            while !raw_args.is_char_boundary(cut) {
                cut -= 1;
            }
            serde_json::json!({ MALFORMED_ARGS_KEY: &raw_args[..cut] })
        }
    }
}

/// Map a non-2xx, non-5xx reply: 429 is a retryable rate limit, the rest are
/// deterministic client errors.
fn map_client_error(status: reqwest::StatusCode, body: &str) -> LlmError {
    if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
        LlmError::RateLimited(format!("{status}: {body}"))
    } else {
        LlmError::BadRequest(format!("{status}: {body}"))
    }
}

/// Reject a reply the model cut off at its token limit while writing a tool
/// call: the arguments are a truncated prefix and must not be executed. A
/// text reply cut the same way is kept (it is still the model's answer).
fn check_finish_reason(finish_reason: Option<&str>, has_tool_calls: bool) -> Result<(), LlmError> {
    if finish_reason == Some("length") {
        if has_tool_calls {
            return Err(LlmError::Decode(
                "response hit the token limit in the middle of a tool call".into(),
            ));
        }
        tracing::warn!("llm reply truncated at the token limit (finish_reason=length)");
    }
    Ok(())
}

/// Encode an `(extension_id, tool_name)` pair into a single OpenAI function
/// name. OpenAI requires `^[a-zA-Z0-9_-]+$` (no dots), but `extension_id`s are
/// dotted (e.g. `greentic.telco-x-tools`) and the historical `{ext}.{tool}`
/// join inserted yet another dot — so every extension tool was rejected with a
/// 400 (`tools[..].function.name` invalid). We escape dots to `_DOT_` and join
/// with `_FN_`, both of which round-trip exactly via [`split_tool_name`]. An
/// empty extension id encodes to the bare tool name (legacy "no dot" case).
pub fn encode_tool_name(extension_id: &str, tool_name: &str) -> String {
    if extension_id.is_empty() {
        return tool_name.to_string();
    }
    format!("{}_FN_{}", extension_id.replace('.', "_DOT_"), tool_name)
}

/// Inverse of [`encode_tool_name`]: split an LLM-emitted function name back into
/// `(extension_id, tool_name)`, restoring escaped dots. No separator → the whole
/// string is the tool name with an empty extension id.
pub fn split_tool_name(name: &str) -> (String, String) {
    match name.split_once("_FN_") {
        Some((ext, tool)) => (ext.replace("_DOT_", "."), tool.to_string()),
        None => (String::new(), name.to_string()),
    }
}

fn build_messages(req: &LlmRequest) -> Vec<OaMessage> {
    let mut out: Vec<OaMessage> = Vec::with_capacity(req.history.len() + 1);
    out.push(OaMessage::System {
        content: req.system_prompt.clone(),
    });
    for m in &req.history {
        match m {
            ChatMessage::System { content } => out.push(OaMessage::System {
                content: content.clone(),
            }),
            // This backend cannot open attachments: the agent gets the fixed
            // notice, and no reference, id or name is sent.
            ChatMessage::User {
                content,
                attachments,
            } => {
                let mut content = content.clone();
                if !attachments.is_empty() {
                    content.push_str(&crate::attachments_materialize::unreadable_note(
                        attachments.len(),
                    ));
                }
                out.push(OaMessage::User { content });
            }
            ChatMessage::Assistant {
                content,
                tool_calls,
            } => {
                let calls = tool_calls
                    .iter()
                    .map(|tc| OaToolCallEmit {
                        id: tc.call_id.clone(),
                        typ: "function",
                        function: OaToolFn {
                            name: wire_tool_name(&tc.extension_id, &tc.tool_name),
                            arguments: tc.args.to_string(),
                        },
                    })
                    .collect();
                out.push(OaMessage::Assistant {
                    content: Some(content.clone()),
                    tool_calls: calls,
                });
            }
            ChatMessage::Tool { call_id, content } => {
                out.push(OaMessage::Tool {
                    tool_call_id: call_id.clone(),
                    content: content.to_string(),
                });
            }
        }
    }
    out
}

fn build_tool(t: &LlmToolSchema) -> OaTool<'_> {
    OaTool {
        typ: "function",
        function: OaToolDef {
            name: wire_tool_name(&t.extension_id, &t.tool_name),
            description: &t.description,
            parameters: &t.parameters,
        },
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn base_url_falls_back_to_openai_when_unconfigured() {
        // Unset, empty and whitespace-only all mean "operator configured
        // nothing" — none of them may produce an empty base URL, which would
        // build the request path `/v1/chat/completions` against no host.
        assert_eq!(normalize_base_url(None), "https://api.openai.com");
        assert_eq!(
            normalize_base_url(Some(String::new())),
            "https://api.openai.com"
        );
        assert_eq!(
            normalize_base_url(Some("   ".to_string())),
            "https://api.openai.com"
        );
    }

    #[test]
    fn base_url_honours_a_configured_endpoint_and_trims_it() {
        assert_eq!(
            normalize_base_url(Some("http://127.0.0.1:11434".to_string())),
            "http://127.0.0.1:11434"
        );
        // Surrounding whitespace and a trailing slash are operator typos, not
        // part of the host: `https://host//v1/chat/completions` 404s on several
        // OpenAI-compatible gateways.
        assert_eq!(
            normalize_base_url(Some("  http://127.0.0.1:11434/  ".to_string())),
            "http://127.0.0.1:11434"
        );
    }

    #[test]
    fn tool_name_round_trips_and_is_openai_safe() {
        // Dotted extension ids are the common case. OpenAI forbids dots in
        // function names (^[a-zA-Z0-9_-]+$), so encode escapes them; split must
        // restore the exact id (it's used for dispatch lookup).
        for (ext, tool) in [
            ("greentic.telco-x-tools", "tx_resolve_prefix"),
            ("greentic.tavily", "tavily_search"),
            ("http", "fetch"),
        ] {
            let encoded = encode_tool_name(ext, tool);
            assert!(
                !encoded.contains('.'),
                "encoded name must be OpenAI-safe (no dots): {encoded}"
            );
            assert_eq!(split_tool_name(&encoded), (ext.into(), tool.into()));
        }
        // No extension id → bare tool name, both directions.
        assert_eq!(encode_tool_name("", "toolname-no-ext"), "toolname-no-ext");
        assert_eq!(
            split_tool_name("toolname-no-ext"),
            (String::new(), "toolname-no-ext".into())
        );
    }

    #[test]
    fn line_buffer_reassembles_multibyte_char_split_across_chunks() {
        // The two bytes of `é` (0xC3 0xA9) are split across two chunks.
        // Decoding each chunk independently would yield U+FFFD; the buffer
        // must reassemble them so the emitted line contains no replacement
        // characters.
        let full = "data: {\"choices\":[{\"delta\":{\"content\":\"héllo\"}}]}\n";
        let bytes = full.as_bytes();
        // Find a split point inside the `é` (between its two UTF-8 bytes).
        let e_pos = full.find('é').expect("contains é");
        let split = e_pos + 1; // mid-scalar boundary
        let (a, b) = bytes.split_at(split);

        let mut lb = SseLineBuffer::new();
        let mut lines = lb.push_bytes(a);
        lines.extend(lb.push_bytes(b));
        assert_eq!(lines.len(), 1, "one complete line expected");
        assert!(
            !lines[0].contains('\u{FFFD}'),
            "line must not contain U+FFFD: {:?}",
            lines[0]
        );

        // Feed the reassembled line through the accumulator and verify the
        // delta is the intact string.
        let mut acc = StreamAccumulator::new();
        let delta = acc.push_line(&lines[0]).expect("parse");
        assert_eq!(delta.as_deref(), Some("héllo"));
    }

    #[test]
    fn line_buffer_reassembles_emoji_split_across_chunks() {
        // A 4-byte emoji split across two chunks must not corrupt.
        let full = "data: {\"choices\":[{\"delta\":{\"content\":\"hi 😀\"}}]}\n";
        let bytes = full.as_bytes();
        let emoji_pos = full.find('😀').expect("contains emoji");
        let (a, b) = bytes.split_at(emoji_pos + 2); // mid-scalar
        let mut lb = SseLineBuffer::new();
        let mut lines = lb.push_bytes(a);
        lines.extend(lb.push_bytes(b));
        assert_eq!(lines.len(), 1);
        let mut acc = StreamAccumulator::new();
        let delta = acc.push_line(&lines[0]).expect("parse");
        assert_eq!(delta.as_deref(), Some("hi 😀"));
    }

    #[test]
    fn line_buffer_yields_remainder_without_trailing_newline() {
        // A final event with no terminating newline must still be emitted
        // via take_remainder.
        let mut lb = SseLineBuffer::new();
        let lines = lb.push_bytes(b"data: {\"choices\":[{\"delta\":{\"content\":\"x\"}}]}");
        assert!(lines.is_empty(), "no newline yet: no complete line");
        let rem = lb.take_remainder().expect("remainder present");
        let mut acc = StreamAccumulator::new();
        assert_eq!(acc.push_line(&rem).expect("parse").as_deref(), Some("x"));
        assert!(lb.take_remainder().is_none(), "remainder consumed");
    }

    #[test]
    fn line_buffer_splits_two_events_in_one_chunk() {
        // Two `data:` events arriving in one byte chunk are both returned.
        let mut lb = SseLineBuffer::new();
        let chunk = "data: {\"choices\":[{\"delta\":{\"content\":\"A\"}}]}\n\
                     data: {\"choices\":[{\"delta\":{\"content\":\"B\"}}]}\n";
        let lines = lb.push_bytes(chunk.as_bytes());
        assert_eq!(lines.len(), 2);
        let mut acc = StreamAccumulator::new();
        let d0 = acc.push_line(&lines[0]).expect("parse");
        let d1 = acc.push_line(&lines[1]).expect("parse");
        assert_eq!(d0.as_deref(), Some("A"));
        assert_eq!(d1.as_deref(), Some("B"));
    }

    #[test]
    fn push_line_handles_crlf_line_ending() {
        // A line carrying a trailing "\r" (CRLF wire format) parses cleanly.
        let mut acc = StreamAccumulator::new();
        // Simulate what SseLineBuffer produces after trimming: but feed a raw
        // CRLF-tailed payload to confirm push_line's own trim() handles it.
        let line = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\r";
        let delta = acc.push_line(line).expect("parse");
        assert_eq!(delta.as_deref(), Some("hi"));
    }

    #[test]
    fn push_line_ignores_sse_comment_keepalive() {
        // An SSE comment / keep-alive line (starts with ':') must yield no
        // delta and no error.
        let mut acc = StreamAccumulator::new();
        assert_eq!(acc.push_line(": keep-alive").expect("no error"), None);
        assert_eq!(acc.push_line(":").expect("no error"), None);
        // A blank line is also a no-op.
        assert_eq!(acc.push_line("").expect("no error"), None);
    }

    #[test]
    fn accumulates_stream_lines_into_response() {
        let lines = [
            r#"data: {"choices":[{"delta":{"content":"Hel"}}]}"#,
            r#"data: {"choices":[{"delta":{"content":"lo"}}]}"#,
            r#"data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"kb_FN_lookup","arguments":"{\"q\":"}}]}}]}"#,
            r#"data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"x\"}"}}]}}]}"#,
            r#"data: {"usage":{"prompt_tokens":7,"completion_tokens":9},"choices":[]}"#,
            "data: [DONE]",
        ];
        let mut acc = StreamAccumulator::new();
        let mut deltas = Vec::new();
        for l in lines {
            if let Some(text) = acc.push_line(l).expect("parse") {
                deltas.push(text);
            }
        }
        let resp = acc.finish(&ToolNameCodec::default());
        assert_eq!(deltas, vec!["Hel".to_string(), "lo".to_string()]);
        assert_eq!(resp.content.as_deref(), Some("Hello"));
        assert_eq!(resp.tool_calls.len(), 1);
        assert_eq!(resp.tool_calls[0].tool_name, "lookup");
        assert_eq!(resp.tool_calls[0].args, serde_json::json!({"q":"x"}));
        assert_eq!(resp.tokens_in, 7);
        assert_eq!(resp.tokens_out, 9);
    }

    #[test]
    fn malformed_tool_arguments_are_flagged_not_silently_emptied() {
        let args = parse_tool_args(r#"{"q": "unterminated"#);
        assert!(args.get(MALFORMED_ARGS_KEY).is_some(), "{args}");
        assert_eq!(parse_tool_args(""), serde_json::json!({}));
        assert_eq!(parse_tool_args(r#"{"q":1}"#), serde_json::json!({"q":1}));
    }

    #[test]
    fn a_stream_without_done_or_finish_reason_is_a_transport_error() {
        let mut acc = StreamAccumulator::new();
        acc.push_line(r#"data: {"choices":[{"delta":{"content":"par"}}]}"#)
            .expect("parse");
        assert!(matches!(acc.check_complete(), Err(LlmError::Transport(_))));
        acc.push_line("data: [DONE]").expect("parse");
        assert!(acc.check_complete().is_ok());
    }

    #[test]
    fn a_finish_reason_alone_completes_the_stream() {
        let mut acc = StreamAccumulator::new();
        acc.push_line(r#"data: {"choices":[{"delta":{"content":"hi"},"finish_reason":"stop"}]}"#)
            .expect("parse");
        assert!(acc.check_complete().is_ok());
    }

    #[test]
    fn length_cutoff_inside_a_tool_call_is_rejected() {
        let mut acc = StreamAccumulator::new();
        acc.push_line(
            r#"data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"kb_FN_lookup","arguments":"{"}}]},"finish_reason":"length"}]}"#,
        )
        .expect("parse");
        assert!(matches!(acc.check_complete(), Err(LlmError::Decode(_))));
        assert!(check_finish_reason(Some("length"), false).is_ok());
    }

    #[test]
    fn http_429_is_a_retryable_rate_limit() {
        let err = map_client_error(reqwest::StatusCode::TOO_MANY_REQUESTS, "slow down");
        assert!(matches!(err, LlmError::RateLimited(_)));
        assert!(err.is_retryable());
        let err = map_client_error(reqwest::StatusCode::BAD_REQUEST, "no");
        assert!(matches!(err, LlmError::BadRequest(_)));
    }

    #[test]
    fn assistant_with_empty_tool_calls_omits_field() {
        // Regression: a text-only assistant turn must NOT serialise
        // `tool_calls: []` (OpenAI 400, code `empty_array`).
        use crate::config::LlmProviderRef;
        use crate::state::ChatMessage;
        let req = LlmRequest {
            system_prompt: "sys".into(),
            history: vec![ChatMessage::Assistant {
                content: "hi".into(),
                tool_calls: vec![],
            }],
            tools: vec![],
            provider: LlmProviderRef {
                provider: "openai".into(),
                model: "gpt-4o".into(),
                credential_ref: None,
            },
            turn_attachments: Default::default(),
            attachment_text_guard: None,
        };
        let value = serde_json::to_value(build_messages(&req)).unwrap();
        // [0] = system prompt, [1] = the assistant turn.
        assert_eq!(value[1]["role"], "assistant");
        assert!(
            value[1].get("tool_calls").is_none(),
            "empty tool_calls must be omitted, got: {}",
            value[1]
        );
    }

    /// This backend cannot open attachments: the agent is told so with the
    /// same fixed sentence the multi-provider backend uses, and no name or
    /// reference of the file reaches the provider.
    #[test]
    fn attachments_are_announced_with_the_fixed_notice_and_never_sent() {
        use crate::attachments::{AttachmentKind, AttachmentRef};
        use crate::config::LlmProviderRef;
        use crate::state::ChatMessage;
        let file = |id: &str| AttachmentRef {
            id: id.into(),
            mime_type: "image/png".into(),
            name: Some("secret-plan.png".into()),
            size_bytes: None,
            kind: AttachmentKind::Image,
            text_ref: None,
        };
        let req = LlmRequest {
            system_prompt: "sys".into(),
            history: vec![ChatMessage::User {
                content: "look".into(),
                attachments: vec![file("artifact://a"), file("artifact://b")],
            }],
            tools: vec![],
            provider: LlmProviderRef {
                provider: "openai".into(),
                model: "gpt-4o".into(),
                credential_ref: None,
            },
            turn_attachments: Default::default(),
            attachment_text_guard: None,
        };
        let value = serde_json::to_value(build_messages(&req)).unwrap();
        let content = value[1]["content"].as_str().unwrap();
        assert!(content.starts_with("look"), "{content}");
        assert!(
            content.contains(&crate::attachments_materialize::unreadable_note(2)),
            "{content}"
        );
        let all = value.to_string();
        assert!(
            !all.contains("secret-plan") && !all.contains("artifact://"),
            "{all}"
        );
    }

    fn plain_req() -> LlmRequest {
        LlmRequest {
            system_prompt: "sys".into(),
            history: vec![ChatMessage::User {
                content: "hi".into(),
                attachments: Vec::new(),
            }],
            tools: vec![],
            provider: crate::config::LlmProviderRef {
                provider: "openai".into(),
                model: "m".into(),
                credential_ref: None,
            },
            turn_attachments: Default::default(),
            attachment_text_guard: None,
        }
    }

    /// One-shot HTTP server: reads the request, then runs `respond` on the
    /// socket. Returns its base URL.
    async fn serve_once<F, Fut>(respond: F) -> String
    where
        F: FnOnce(tokio::net::TcpStream) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        use tokio::io::AsyncReadExt;
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = vec![0u8; 65536];
            // The request is small and sent in one go; one read drains it.
            let _ = sock.read(&mut buf).await;
            respond(sock).await;
        });
        format!("http://{addr}")
    }

    #[tokio::test]
    async fn a_reply_without_usage_is_accepted() {
        use tokio::io::AsyncWriteExt;
        let body = r#"{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}"#;
        let url = serve_once(move |mut sock| async move {
            let resp = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            sock.write_all(resp.as_bytes()).await.unwrap();
        })
        .await;
        let backend = OpenAiLlmBackend::with_base_url("k", url);
        let out = backend.complete(plain_req()).await.unwrap();
        assert_eq!(out.content.as_deref(), Some("ok"));
        assert_eq!((out.tokens_in, out.tokens_out), (0, 0));
    }

    /// The stream outlives the per-request timeout; only idle gaps are bounded,
    /// so the full reply arrives (a whole-request timeout would cut it).
    #[tokio::test]
    async fn a_long_stream_is_not_cut_by_the_request_timeout() {
        use tokio::io::AsyncWriteExt;
        let url = serve_once(|mut sock| async move {
            sock.write_all(
                b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
            )
            .await
            .unwrap();
            for word in ["a", "b", "c", "d", "e", "f"] {
                let line = format!(
                    "data: {{\"choices\":[{{\"delta\":{{\"content\":\"{word}\"}}}}]}}\n\n"
                );
                sock.write_all(line.as_bytes()).await.unwrap();
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
            sock.write_all(
                b"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n",
            )
            .await
            .unwrap();
        })
        .await;
        let mut backend = OpenAiLlmBackend::with_base_url("k", url);
        backend.request_timeout = Duration::from_millis(250);
        let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
        let sink = seen.clone();
        let out = backend
            .complete_streaming(
                plain_req(),
                Box::new(move |chunk: &str| sink.lock().unwrap().push_str(chunk)),
            )
            .await
            .unwrap();
        assert_eq!(out.content.as_deref(), Some("abcdef"));
        assert_eq!(seen.lock().unwrap().as_str(), "abcdef");
        assert_eq!(out.tokens_out, 2);
    }

    #[tokio::test]
    async fn the_blocking_path_still_times_out() {
        let url = serve_once(|sock| async move {
            tokio::time::sleep(Duration::from_secs(5)).await;
            drop(sock);
        })
        .await;
        let mut backend = OpenAiLlmBackend::with_base_url("k", url);
        backend.request_timeout = Duration::from_millis(150);
        let err = backend.complete(plain_req()).await.unwrap_err();
        assert!(matches!(err, LlmError::Transport(_)), "{err:?}");
    }
}