1use serde_json::{json, Value};
2use std::time::Duration;
3
4use crate::embedding::EmbeddingProvider;
5use crate::errors::{InnateError, Result};
6use crate::refine::{DistillProvenance, DistilledChunk, Distiller};
7use crate::settings::{EmbeddingConfig, LlmConfig};
8
9const DISTILL_PROMPT_VERSION: &str = "4";
14
15fn safe_prompt_field(value: Option<&str>) -> String {
16 let value = value.unwrap_or("");
17 let (cleaned, action) = crate::utils::sanitize(value);
18 match action {
19 crate::utils::SanitizeAction::Discard => "[removed unsafe content]".to_string(),
20 _ => cleaned,
21 }
22}
23
24fn build_distill_prompt(log: &Value) -> String {
25 let query = safe_prompt_field(log.get("query").and_then(Value::as_str));
26 let output = safe_prompt_field(log.get("output").and_then(Value::as_str));
27 let output_summary = safe_prompt_field(log.get("output_summary").and_then(Value::as_str));
28 let nomination = safe_prompt_field(log.get("nomination").and_then(Value::as_str));
29 let outcome = safe_prompt_field(log.get("outcome").and_then(Value::as_str));
30
31 let mut context_parts = vec![];
32 if !query.is_empty() {
33 context_parts.push(format!("Query: {query}"));
34 }
35 if !nomination.is_empty() {
36 context_parts.push(format!("Nominated insight: {nomination}"));
37 }
38 if !output_summary.is_empty() {
39 context_parts.push(format!("Summary: {output_summary}"));
40 }
41 if !output.is_empty() {
42 let truncated: String = output.chars().take(1500).collect();
43 context_parts.push(format!("Output (truncated): {truncated}"));
44 }
45 if !outcome.is_empty() {
46 context_parts.push(format!("Outcome: {outcome}"));
47 }
48
49 let context = context_parts.join("\n");
50
51 format!(
52 r#"You are a knowledge distillation assistant. Given an agent interaction log, \
53extract zero or more independent reusable procedural principles. Favor GENERAL, \
54transferable skills, methods, and techniques over project-specific facts.
55
56Agent interaction:
57{context}
58
59Output a JSON array. Each item has:
60{{
61 "skill_name": "<1-3 word skill/topic label for this principle>",
62 "content": "<principle; when it applies; what to avoid>",
63 "trigger_desc": "<2-6 word canonical phrase>",
64 "anti_trigger_desc": "<when NOT to apply this, or null>"
65}}
66Return [] if nothing is worth keeping.
67
68Rules:
69- skill_name is a short human label (1-3 words) naming the skill/topic, e.g.
70 "error handling", "git rebase", "async retries"; not a sentence
71- content must be self-contained and actionable for a future agent reading cold
72- Prefer transferable methods and techniques; a principle that helps across many
73 projects is worth far more than one tied to this codebase
74- Abstract away project-specific detail: strip repo/file/function/path/variable names
75 and one-off identifiers, and rephrase the lesson as a general principle whoever the
76 next project is. Keep concrete project-specific detail ONLY when the lesson genuinely
77 cannot be generalized without losing its meaning
78- trigger_desc must match the vocabulary a future agent would use in a search query;
79 prefer general, technology- or domain-level phrasing over project-name phrasing
80- Never store conversation text verbatim; always distil to reusable principle form
81- If outcome is "fail", focus on what to avoid
82- Keep principles independent; do not combine unrelated lessons"#
83 )
84}
85
86fn build_distill_prompt_with_related(log: &Value, logs: &[Value]) -> String {
87 let mut prompt = build_distill_prompt(log);
88 let log_id = log.get("id").and_then(Value::as_str).unwrap_or("");
89 let context_key = log.get("context_key").and_then(Value::as_str);
90 let related: Vec<String> = logs
91 .iter()
92 .filter(|other| other.get("id").and_then(Value::as_str).unwrap_or("") != log_id)
93 .filter(|other| {
94 context_key.is_some() && other.get("context_key").and_then(Value::as_str) == context_key
95 })
96 .take(4)
97 .map(|other| {
98 let query = safe_prompt_field(other.get("query").and_then(Value::as_str));
99 let summary = safe_prompt_field(other.get("output_summary").and_then(Value::as_str));
100 let outcome = safe_prompt_field(other.get("outcome").and_then(Value::as_str));
101 format!("- Query: {query}; outcome: {outcome}; summary: {summary}")
102 })
103 .collect();
104 if !related.is_empty() {
105 prompt.push_str(
106 "\n\nRelated recent interactions (use only to identify repeated patterns or conflicts):\n",
107 );
108 prompt.push_str(&related.join("\n"));
109 }
110 prompt
111}
112
113const HTTP_MAX_ATTEMPTS: u32 = 3;
119const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
121
122fn post_json_retry(
127 url: &str,
128 headers: &[(&str, &str)],
129 body: &Value,
130 label: &str,
131) -> Result<Value> {
132 let start = std::time::Instant::now();
136 let mut attempt = 0;
137 let outcome: Result<Value> = loop {
138 attempt += 1;
139 let mut req = ureq::post(url)
144 .config()
145 .timeout_global(Some(HTTP_TIMEOUT))
146 .http_status_as_error(false)
147 .build()
148 .header("Content-Type", "application/json");
149 for (k, v) in headers {
150 req = req.header(*k, *v);
151 }
152 match req.send_json(body) {
153 Ok(mut response) => {
154 let code = response.status().as_u16();
155 if (200..300).contains(&code) {
156 break response.body_mut().read_json::<Value>().map_err(|e| {
157 InnateError::Other(format!("{label} response parse error: {e}"))
158 });
159 }
160 let retry_after = response
161 .headers()
162 .get("retry-after")
163 .and_then(|h| h.to_str().ok())
164 .and_then(|s| s.trim().parse::<u64>().ok());
165 if status_is_retryable(code) && attempt < HTTP_MAX_ATTEMPTS {
166 std::thread::sleep(backoff_delay(attempt, retry_after));
167 continue;
168 }
169 let detail = response.body_mut().read_to_string().unwrap_or_default();
172 break Err(InnateError::Other(format!(
173 "{label} HTTP error: status: {code} {detail}"
174 )));
175 }
176 Err(err) => {
177 if attempt < HTTP_MAX_ATTEMPTS {
178 std::thread::sleep(backoff_delay(attempt, None));
179 continue;
180 }
181 break Err(InnateError::Other(format!(
183 "{label} HTTP error: transport: {err}"
184 )));
185 }
186 }
187 };
188 crate::llm_trace::record(label, url, body, &outcome, attempt, start.elapsed());
189 outcome
190}
191
192fn status_is_retryable(code: u16) -> bool {
194 code == 429 || (500..=599).contains(&code)
195}
196
197fn backoff_delay(attempt: u32, retry_after_secs: Option<u64>) -> Duration {
200 if let Some(secs) = retry_after_secs {
201 return Duration::from_secs(secs.min(30));
202 }
203 let shift = (attempt - 1).min(6);
204 Duration::from_millis(250u64.saturating_mul(1 << shift))
205}
206
207pub struct HttpDistiller {
215 config: LlmConfig,
216}
217
218impl HttpDistiller {
219 pub fn new(config: LlmConfig) -> Self {
220 Self { config }
221 }
222
223 fn call(&self, prompt: &str) -> Result<String> {
224 if self.config.provider == "anthropic" {
225 self.call_anthropic(prompt)
226 } else {
227 self.call_openai(prompt)
228 }
229 }
230
231 fn call_openai(&self, prompt: &str) -> Result<String> {
232 let api_key = self
233 .config
234 .resolved_api_key()
235 .ok_or_else(|| InnateError::Other("LLM API key not configured".into()))?;
236
237 let base = self.config.resolved_base_url();
238 let url = format!("{base}/chat/completions");
239
240 let body = json!({
241 "model": self.config.model_id,
242 "messages": [{"role": "user", "content": prompt}],
243 "max_tokens": 800,
244 "temperature": 0.2,
245 });
246
247 let auth = format!("Bearer {api_key}");
248 let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "LLM")?;
249
250 resp_json
251 .pointer("/choices/0/message/content")
252 .and_then(Value::as_str)
253 .map(str::to_string)
254 .ok_or_else(|| InnateError::Other("unexpected LLM response shape".into()))
255 }
256
257 fn call_anthropic(&self, prompt: &str) -> Result<String> {
258 let api_key = self
259 .config
260 .resolved_api_key()
261 .ok_or_else(|| InnateError::Other("Anthropic API key not configured".into()))?;
262
263 let base = self.config.resolved_base_url();
264 let url = format!("{base}/v1/messages");
265
266 let body = json!({
267 "model": self.config.model_id,
268 "max_tokens": 800,
269 "messages": [{"role": "user", "content": prompt}],
270 });
271
272 let resp_json = post_json_retry(
273 &url,
274 &[("x-api-key", &api_key), ("anthropic-version", "2023-06-01")],
275 &body,
276 "Anthropic",
277 )?;
278
279 resp_json
280 .pointer("/content/0/text")
281 .and_then(Value::as_str)
282 .map(str::to_string)
283 .ok_or_else(|| InnateError::Other("unexpected Anthropic response shape".into()))
284 }
285}
286
287impl Distiller for HttpDistiller {
288 fn distill(&self, log_entries: &[Value]) -> crate::errors::Result<Vec<DistilledChunk>> {
289 distill_with(log_entries, |prompt| self.call(prompt))
290 }
291
292 fn distill_with_context(
293 &self,
294 primary: &Value,
295 related_logs: &[Value],
296 ) -> crate::errors::Result<Vec<DistilledChunk>> {
297 distill_entry_with(primary, related_logs, |prompt| self.call(prompt))
298 }
299
300 fn provenance(&self) -> DistillProvenance {
301 DistillProvenance {
302 provider: Some(self.config.provider.clone()),
303 model: Some(self.config.model_id.clone()),
304 prompt_version: Some(DISTILL_PROMPT_VERSION.to_string()),
305 }
306 }
307}
308
309fn distill_with(
314 log_entries: &[Value],
315 call: impl Fn(&str) -> Result<String> + Copy,
316) -> Result<Vec<DistilledChunk>> {
317 let mut out = Vec::new();
318 for entry in log_entries {
319 out.extend(distill_entry_with(entry, log_entries, call)?);
320 }
321 Ok(out)
322}
323
324fn distill_entry_with(
325 entry: &Value,
326 related_logs: &[Value],
327 call: impl Fn(&str) -> Result<String>,
328) -> Result<Vec<DistilledChunk>> {
329 let log_id = entry["id"].as_str().unwrap_or("").to_string();
330 let prompt = build_distill_prompt_with_related(entry, related_logs);
331 let mut raw = call(&prompt)?;
332 let mut parsed = parse_distill_response(&raw);
333 if parsed.is_err() {
334 raw = call(&format!(
335 "{prompt}\n\nYour previous response was invalid. Return only a valid JSON array."
336 ))?;
337 parsed = parse_distill_response(&raw);
338 }
339 let items = parsed.map_err(|error| {
340 InnateError::Other(format!("LLM distillation response invalid: {error}"))
341 })?;
342 let mut out = Vec::new();
343 for parsed in items {
344 let content = parsed
345 .get("content")
346 .and_then(Value::as_str)
347 .map(str::trim)
348 .filter(|s| !s.is_empty());
349 let Some(content) = content else { continue };
350 let skill_name = parsed
351 .get("skill_name")
352 .and_then(Value::as_str)
353 .map(|s| {
354 s.trim()
355 .split_whitespace()
356 .take(3)
357 .collect::<Vec<_>>()
358 .join(" ")
359 })
360 .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
361 let trigger_desc = parsed
362 .get("trigger_desc")
363 .and_then(Value::as_str)
364 .map(str::to_string)
365 .filter(|s| !s.is_empty());
366 let anti_trigger_desc = parsed
367 .get("anti_trigger_desc")
368 .and_then(Value::as_str)
369 .map(str::to_string)
370 .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
371 out.push(DistilledChunk {
372 content: content.to_string(),
373 skill_name,
374 trigger_desc,
375 anti_trigger_desc,
376 source_log_id: log_id.clone(),
377 nomination: entry
378 .get("nomination")
379 .and_then(Value::as_str)
380 .map(str::to_string),
381 provider_override: None,
382 });
383 }
384 Ok(out)
385}
386
387fn parse_distill_response(raw: &str) -> std::result::Result<Vec<Value>, String> {
388 let json_str = extract_json(raw);
389 let parsed: Value = serde_json::from_str(json_str.trim()).map_err(|e| e.to_string())?;
390 if parsed.get("skip").and_then(Value::as_bool) == Some(true) {
391 return Ok(vec![]);
392 }
393 match parsed {
394 Value::Array(items) => Ok(items),
395 Value::Object(_) => Ok(vec![parsed]),
396 _ => Err("expected a JSON object or array".to_string()),
397 }
398}
399
400fn extract_json(text: &str) -> &str {
401 let stripped = text.trim();
403 if let Some(inner) = stripped
404 .strip_prefix("```json")
405 .or_else(|| stripped.strip_prefix("```"))
406 {
407 if let Some(end) = inner.rfind("```") {
408 return inner[..end].trim();
409 }
410 }
411 if let (Some(start), Some(end)) = (stripped.find('['), stripped.rfind(']')) {
412 return &stripped[start..=end];
413 }
414 if let (Some(start), Some(end)) = (stripped.find('{'), stripped.rfind('}')) {
416 return &stripped[start..=end];
417 }
418 stripped
419}
420
421pub fn build_distiller(config: &LlmConfig) -> std::sync::Arc<dyn Distiller + Send + Sync> {
426 std::sync::Arc::new(HttpDistiller::new(config.clone()))
427}
428
429pub struct LlmEmbeddingProvider {
434 config: EmbeddingConfig,
435}
436
437#[cfg(test)]
438#[allow(clippy::items_after_test_module)]
439mod tests {
440 use std::cell::Cell;
441
442 use serde_json::json;
443
444 use std::time::Duration;
445
446 use super::{
447 backoff_delay, build_distill_prompt, distill_entry_with, distill_with,
448 parse_distill_response, parse_embedding_response, status_is_retryable,
449 };
450
451 #[test]
452 fn embedding_response_is_parsed_fail_closed() {
453 let resp = json!({"data": [{"embedding": [0.1, 0.2, 0.3]}]});
455 assert_eq!(
456 parse_embedding_response(&resp, 3).unwrap(),
457 vec![0.1f32, 0.2, 0.3]
458 );
459
460 assert!(parse_embedding_response(&resp, 4).is_err());
462
463 let bad = json!({"data": [{"embedding": [0.1, "oops", 0.3]}]});
465 assert!(parse_embedding_response(&bad, 3).is_err());
466
467 let shape = json!({"data": []});
469 assert!(parse_embedding_response(&shape, 3).is_err());
470 }
471
472 #[test]
473 fn only_rate_limit_and_5xx_are_retryable() {
474 assert!(status_is_retryable(429));
475 assert!(status_is_retryable(500));
476 assert!(status_is_retryable(503));
477 assert!(status_is_retryable(599));
478 assert!(!status_is_retryable(400));
479 assert!(!status_is_retryable(401));
480 assert!(!status_is_retryable(404));
481 assert!(!status_is_retryable(200));
482 }
483
484 #[test]
485 fn backoff_is_exponential_and_honors_retry_after() {
486 assert_eq!(backoff_delay(1, None), Duration::from_millis(250));
488 assert_eq!(backoff_delay(2, None), Duration::from_millis(500));
489 assert_eq!(backoff_delay(3, None), Duration::from_millis(1000));
490 assert_eq!(backoff_delay(1, Some(5)), Duration::from_secs(5));
492 assert_eq!(backoff_delay(1, Some(120)), Duration::from_secs(30));
493 }
494
495 #[test]
496 fn prompt_redacts_secrets_before_external_llm_call() {
497 let prompt = build_distill_prompt(&json!({
498 "query": "debug sk-12345678901234567890",
499 "output_summary": "Authorization: Bearer secret-token-value"
500 }));
501 assert!(!prompt.contains("sk-12345678901234567890"));
502 assert!(!prompt.contains("secret-token-value"));
503 assert!(prompt.contains("[REDACTED]"));
504 }
505
506 #[test]
507 fn malformed_response_is_retried_instead_of_silently_skipped() {
508 let calls = Cell::new(0);
509 let chunks = distill_with(&[json!({"id": "log-1", "query": "q"})], |_| {
510 calls.set(calls.get() + 1);
511 if calls.get() == 1 {
512 Ok("not json".to_string())
513 } else {
514 Ok(r#"[{"content":"retry worked","trigger_desc":"retry"}]"#.to_string())
515 }
516 })
517 .unwrap();
518 assert_eq!(calls.get(), 2);
519 assert_eq!(chunks.len(), 1);
520 assert_eq!(chunks[0].content, "retry worked");
521 }
522
523 #[test]
524 fn parser_accepts_multiple_distilled_chunks() {
525 let parsed = parse_distill_response(
526 r#"[{"content":"one"},{"content":"two","anti_trigger_desc":"never"}]"#,
527 )
528 .unwrap();
529 assert_eq!(parsed.len(), 2);
530 }
531
532 #[test]
533 fn nomination_is_distilled_instead_of_bypassing_the_model() {
534 let prompt_seen = Cell::new(false);
535 let entry = json!({
536 "id": "log-1",
537 "query": "original query",
538 "nomination": "raw agent nomination",
539 "output_summary": "summary",
540 "outcome": "ok"
541 });
542 let chunks = distill_entry_with(&entry, std::slice::from_ref(&entry), |prompt| {
543 prompt_seen.set(prompt.contains("raw agent nomination"));
544 Ok(
545 r#"[{"content":"generalized principle","trigger_desc":"generalize","anti_trigger_desc":null}]"#
546 .to_string(),
547 )
548 })
549 .unwrap();
550
551 assert!(prompt_seen.get());
552 assert_eq!(chunks[0].content, "generalized principle");
553 assert_eq!(
554 chunks[0].nomination.as_deref(),
555 Some("raw agent nomination")
556 );
557 }
558}
559
560impl LlmEmbeddingProvider {
561 pub fn new(config: EmbeddingConfig) -> Self {
562 Self { config }
563 }
564
565 fn embed(&self, text: &str) -> Result<Vec<f32>> {
566 let api_key = self
567 .config
568 .resolved_api_key()
569 .ok_or_else(|| InnateError::Other("Embedding API key not configured".into()))?;
570
571 let base = self.config.resolved_base_url();
572 let url = format!("{base}/embeddings");
573
574 let body = json!({
575 "input": text,
576 "model": self.config.model_id,
577 });
578
579 let auth = format!("Bearer {api_key}");
580 let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "Embedding")?;
581
582 parse_embedding_response(&resp_json, self.config.dim)
583 }
584}
585
586fn parse_embedding_response(resp_json: &Value, expected_dim: usize) -> Result<Vec<f32>> {
592 let embedding = resp_json
593 .pointer("/data/0/embedding")
594 .and_then(Value::as_array)
595 .ok_or_else(|| InnateError::Other("unexpected embedding response shape".into()))?;
596 let vec: Vec<f32> = embedding
597 .iter()
598 .map(|v| {
599 v.as_f64().map(|x| x as f32).ok_or_else(|| {
600 InnateError::Other("embedding response contains a non-numeric element".into())
601 })
602 })
603 .collect::<Result<Vec<f32>>>()?;
604 if vec.len() != expected_dim {
605 return Err(InnateError::Other(format!(
606 "embedding dimension mismatch: provider returned {}, expected {expected_dim} (check embedding.dim)",
607 vec.len(),
608 )));
609 }
610 Ok(vec)
611}
612
613impl EmbeddingProvider for LlmEmbeddingProvider {
614 fn model_name(&self) -> &'static str {
615 "llm-embedding"
616 }
617
618 fn content_dim(&self) -> usize {
619 self.config.dim
620 }
621
622 fn trigger_dim(&self) -> usize {
623 self.config.dim
624 }
625
626 fn embed_content(&self, text: &str) -> Result<Vec<f32>> {
627 self.embed(text)
628 }
629
630 fn embed_trigger(&self, text: &str) -> Result<Vec<f32>> {
631 self.embed(text)
632 }
633
634 fn embed_both(&self, text: &str) -> Result<(Vec<f32>, Vec<f32>)> {
637 let v = self.embed(text)?;
638 Ok((v.clone(), v))
639 }
640}
641
642pub fn test_llm(config: &LlmConfig) -> Result<String> {
648 let distiller = build_distiller(config);
649 let dummy_log = json!({
650 "id": "test",
651 "query": "connection test",
652 "output_summary": "test",
653 "outcome": "ok"
654 });
655 distiller.distill(&[dummy_log])?;
657 Ok(format!("OK — model: {}", config.model_id))
658}
659
660pub fn test_embedding(config: &EmbeddingConfig) -> Result<usize> {
662 let provider = LlmEmbeddingProvider::new(config.clone());
663 let vec = provider.embed("connection test")?;
664 Ok(vec.len())
665}