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
157 .body_mut()
158 .read_json::<Value>()
159 .map_err(|e| {
160 InnateError::Other(format!("{label} response parse error: {e}"))
161 });
162 }
163 let retry_after = response
164 .headers()
165 .get("retry-after")
166 .and_then(|h| h.to_str().ok())
167 .and_then(|s| s.trim().parse::<u64>().ok());
168 if status_is_retryable(code) && attempt < HTTP_MAX_ATTEMPTS {
169 std::thread::sleep(backoff_delay(attempt, retry_after));
170 continue;
171 }
172 let detail = response.body_mut().read_to_string().unwrap_or_default();
175 break Err(InnateError::Other(format!(
176 "{label} HTTP error: status: {code} {detail}"
177 )));
178 }
179 Err(err) => {
180 if attempt < HTTP_MAX_ATTEMPTS {
181 std::thread::sleep(backoff_delay(attempt, None));
182 continue;
183 }
184 break Err(InnateError::Other(format!(
186 "{label} HTTP error: transport: {err}"
187 )));
188 }
189 }
190 };
191 crate::llm_trace::record(label, url, body, &outcome, attempt, start.elapsed());
192 outcome
193}
194
195fn status_is_retryable(code: u16) -> bool {
197 code == 429 || (500..=599).contains(&code)
198}
199
200fn backoff_delay(attempt: u32, retry_after_secs: Option<u64>) -> Duration {
203 if let Some(secs) = retry_after_secs {
204 return Duration::from_secs(secs.min(30));
205 }
206 let shift = (attempt - 1).min(6);
207 Duration::from_millis(250u64.saturating_mul(1 << shift))
208}
209
210pub struct HttpDistiller {
218 config: LlmConfig,
219}
220
221impl HttpDistiller {
222 pub fn new(config: LlmConfig) -> Self {
223 Self { config }
224 }
225
226 fn call(&self, prompt: &str) -> Result<String> {
227 if self.config.provider == "anthropic" {
228 self.call_anthropic(prompt)
229 } else {
230 self.call_openai(prompt)
231 }
232 }
233
234 fn call_openai(&self, prompt: &str) -> Result<String> {
235 let api_key = self
236 .config
237 .resolved_api_key()
238 .ok_or_else(|| InnateError::Other("LLM API key not configured".into()))?;
239
240 let base = self.config.resolved_base_url();
241 let url = format!("{base}/chat/completions");
242
243 let body = json!({
244 "model": self.config.model_id,
245 "messages": [{"role": "user", "content": prompt}],
246 "max_tokens": 800,
247 "temperature": 0.2,
248 });
249
250 let auth = format!("Bearer {api_key}");
251 let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "LLM")?;
252
253 resp_json
254 .pointer("/choices/0/message/content")
255 .and_then(Value::as_str)
256 .map(str::to_string)
257 .ok_or_else(|| InnateError::Other("unexpected LLM response shape".into()))
258 }
259
260 fn call_anthropic(&self, prompt: &str) -> Result<String> {
261 let api_key = self
262 .config
263 .resolved_api_key()
264 .ok_or_else(|| InnateError::Other("Anthropic API key not configured".into()))?;
265
266 let base = self.config.resolved_base_url();
267 let url = format!("{base}/v1/messages");
268
269 let body = json!({
270 "model": self.config.model_id,
271 "max_tokens": 800,
272 "messages": [{"role": "user", "content": prompt}],
273 });
274
275 let resp_json = post_json_retry(
276 &url,
277 &[("x-api-key", &api_key), ("anthropic-version", "2023-06-01")],
278 &body,
279 "Anthropic",
280 )?;
281
282 resp_json
283 .pointer("/content/0/text")
284 .and_then(Value::as_str)
285 .map(str::to_string)
286 .ok_or_else(|| InnateError::Other("unexpected Anthropic response shape".into()))
287 }
288}
289
290impl Distiller for HttpDistiller {
291 fn distill(&self, log_entries: &[Value]) -> crate::errors::Result<Vec<DistilledChunk>> {
292 distill_with(log_entries, |prompt| self.call(prompt))
293 }
294
295 fn distill_with_context(
296 &self,
297 primary: &Value,
298 related_logs: &[Value],
299 ) -> crate::errors::Result<Vec<DistilledChunk>> {
300 distill_entry_with(primary, related_logs, |prompt| self.call(prompt))
301 }
302
303 fn provenance(&self) -> DistillProvenance {
304 DistillProvenance {
305 provider: Some(self.config.provider.clone()),
306 model: Some(self.config.model_id.clone()),
307 prompt_version: Some(DISTILL_PROMPT_VERSION.to_string()),
308 }
309 }
310}
311
312fn distill_with(
317 log_entries: &[Value],
318 call: impl Fn(&str) -> Result<String> + Copy,
319) -> Result<Vec<DistilledChunk>> {
320 let mut out = Vec::new();
321 for entry in log_entries {
322 out.extend(distill_entry_with(entry, log_entries, call)?);
323 }
324 Ok(out)
325}
326
327fn distill_entry_with(
328 entry: &Value,
329 related_logs: &[Value],
330 call: impl Fn(&str) -> Result<String>,
331) -> Result<Vec<DistilledChunk>> {
332 let log_id = entry["id"].as_str().unwrap_or("").to_string();
333 let prompt = build_distill_prompt_with_related(entry, related_logs);
334 let mut raw = call(&prompt)?;
335 let mut parsed = parse_distill_response(&raw);
336 if parsed.is_err() {
337 raw = call(&format!(
338 "{prompt}\n\nYour previous response was invalid. Return only a valid JSON array."
339 ))?;
340 parsed = parse_distill_response(&raw);
341 }
342 let items = parsed.map_err(|error| {
343 InnateError::Other(format!("LLM distillation response invalid: {error}"))
344 })?;
345 let mut out = Vec::new();
346 for parsed in items {
347 let content = parsed
348 .get("content")
349 .and_then(Value::as_str)
350 .map(str::trim)
351 .filter(|s| !s.is_empty());
352 let Some(content) = content else { continue };
353 let skill_name = parsed
354 .get("skill_name")
355 .and_then(Value::as_str)
356 .map(|s| s.trim().split_whitespace().take(3).collect::<Vec<_>>().join(" "))
357 .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
358 let trigger_desc = parsed
359 .get("trigger_desc")
360 .and_then(Value::as_str)
361 .map(str::to_string)
362 .filter(|s| !s.is_empty());
363 let anti_trigger_desc = parsed
364 .get("anti_trigger_desc")
365 .and_then(Value::as_str)
366 .map(str::to_string)
367 .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
368 out.push(DistilledChunk {
369 content: content.to_string(),
370 skill_name,
371 trigger_desc,
372 anti_trigger_desc,
373 source_log_id: log_id.clone(),
374 nomination: entry
375 .get("nomination")
376 .and_then(Value::as_str)
377 .map(str::to_string),
378 provider_override: None,
379 });
380 }
381 Ok(out)
382}
383
384fn parse_distill_response(raw: &str) -> std::result::Result<Vec<Value>, String> {
385 let json_str = extract_json(raw);
386 let parsed: Value = serde_json::from_str(json_str.trim()).map_err(|e| e.to_string())?;
387 if parsed.get("skip").and_then(Value::as_bool) == Some(true) {
388 return Ok(vec![]);
389 }
390 match parsed {
391 Value::Array(items) => Ok(items),
392 Value::Object(_) => Ok(vec![parsed]),
393 _ => Err("expected a JSON object or array".to_string()),
394 }
395}
396
397fn extract_json(text: &str) -> &str {
398 let stripped = text.trim();
400 if let Some(inner) = stripped
401 .strip_prefix("```json")
402 .or_else(|| stripped.strip_prefix("```"))
403 {
404 if let Some(end) = inner.rfind("```") {
405 return inner[..end].trim();
406 }
407 }
408 if let (Some(start), Some(end)) = (stripped.find('['), stripped.rfind(']')) {
409 return &stripped[start..=end];
410 }
411 if let (Some(start), Some(end)) = (stripped.find('{'), stripped.rfind('}')) {
413 return &stripped[start..=end];
414 }
415 stripped
416}
417
418pub fn build_distiller(config: &LlmConfig) -> std::sync::Arc<dyn Distiller + Send + Sync> {
423 std::sync::Arc::new(HttpDistiller::new(config.clone()))
424}
425
426pub struct LlmEmbeddingProvider {
431 config: EmbeddingConfig,
432}
433
434#[cfg(test)]
435#[allow(clippy::items_after_test_module)]
436mod tests {
437 use std::cell::Cell;
438
439 use serde_json::json;
440
441 use std::time::Duration;
442
443 use super::{
444 backoff_delay, build_distill_prompt, distill_entry_with, distill_with,
445 parse_distill_response, parse_embedding_response, status_is_retryable,
446 };
447
448 #[test]
449 fn embedding_response_is_parsed_fail_closed() {
450 let resp = json!({"data": [{"embedding": [0.1, 0.2, 0.3]}]});
452 assert_eq!(parse_embedding_response(&resp, 3).unwrap(), vec![0.1f32, 0.2, 0.3]);
453
454 assert!(parse_embedding_response(&resp, 4).is_err());
456
457 let bad = json!({"data": [{"embedding": [0.1, "oops", 0.3]}]});
459 assert!(parse_embedding_response(&bad, 3).is_err());
460
461 let shape = json!({"data": []});
463 assert!(parse_embedding_response(&shape, 3).is_err());
464 }
465
466 #[test]
467 fn only_rate_limit_and_5xx_are_retryable() {
468 assert!(status_is_retryable(429));
469 assert!(status_is_retryable(500));
470 assert!(status_is_retryable(503));
471 assert!(status_is_retryable(599));
472 assert!(!status_is_retryable(400));
473 assert!(!status_is_retryable(401));
474 assert!(!status_is_retryable(404));
475 assert!(!status_is_retryable(200));
476 }
477
478 #[test]
479 fn backoff_is_exponential_and_honors_retry_after() {
480 assert_eq!(backoff_delay(1, None), Duration::from_millis(250));
482 assert_eq!(backoff_delay(2, None), Duration::from_millis(500));
483 assert_eq!(backoff_delay(3, None), Duration::from_millis(1000));
484 assert_eq!(backoff_delay(1, Some(5)), Duration::from_secs(5));
486 assert_eq!(backoff_delay(1, Some(120)), Duration::from_secs(30));
487 }
488
489 #[test]
490 fn prompt_redacts_secrets_before_external_llm_call() {
491 let prompt = build_distill_prompt(&json!({
492 "query": "debug sk-12345678901234567890",
493 "output_summary": "Authorization: Bearer secret-token-value"
494 }));
495 assert!(!prompt.contains("sk-12345678901234567890"));
496 assert!(!prompt.contains("secret-token-value"));
497 assert!(prompt.contains("[REDACTED]"));
498 }
499
500 #[test]
501 fn malformed_response_is_retried_instead_of_silently_skipped() {
502 let calls = Cell::new(0);
503 let chunks = distill_with(&[json!({"id": "log-1", "query": "q"})], |_| {
504 calls.set(calls.get() + 1);
505 if calls.get() == 1 {
506 Ok("not json".to_string())
507 } else {
508 Ok(r#"[{"content":"retry worked","trigger_desc":"retry"}]"#.to_string())
509 }
510 })
511 .unwrap();
512 assert_eq!(calls.get(), 2);
513 assert_eq!(chunks.len(), 1);
514 assert_eq!(chunks[0].content, "retry worked");
515 }
516
517 #[test]
518 fn parser_accepts_multiple_distilled_chunks() {
519 let parsed = parse_distill_response(
520 r#"[{"content":"one"},{"content":"two","anti_trigger_desc":"never"}]"#,
521 )
522 .unwrap();
523 assert_eq!(parsed.len(), 2);
524 }
525
526 #[test]
527 fn nomination_is_distilled_instead_of_bypassing_the_model() {
528 let prompt_seen = Cell::new(false);
529 let entry = json!({
530 "id": "log-1",
531 "query": "original query",
532 "nomination": "raw agent nomination",
533 "output_summary": "summary",
534 "outcome": "ok"
535 });
536 let chunks = distill_entry_with(&entry, std::slice::from_ref(&entry), |prompt| {
537 prompt_seen.set(prompt.contains("raw agent nomination"));
538 Ok(
539 r#"[{"content":"generalized principle","trigger_desc":"generalize","anti_trigger_desc":null}]"#
540 .to_string(),
541 )
542 })
543 .unwrap();
544
545 assert!(prompt_seen.get());
546 assert_eq!(chunks[0].content, "generalized principle");
547 assert_eq!(
548 chunks[0].nomination.as_deref(),
549 Some("raw agent nomination")
550 );
551 }
552}
553
554impl LlmEmbeddingProvider {
555 pub fn new(config: EmbeddingConfig) -> Self {
556 Self { config }
557 }
558
559 fn embed(&self, text: &str) -> Result<Vec<f32>> {
560 let api_key = self
561 .config
562 .resolved_api_key()
563 .ok_or_else(|| InnateError::Other("Embedding API key not configured".into()))?;
564
565 let base = self.config.resolved_base_url();
566 let url = format!("{base}/embeddings");
567
568 let body = json!({
569 "input": text,
570 "model": self.config.model_id,
571 });
572
573 let auth = format!("Bearer {api_key}");
574 let resp_json = post_json_retry(
575 &url,
576 &[("Authorization", &auth)],
577 &body,
578 "Embedding",
579 )?;
580
581 parse_embedding_response(&resp_json, self.config.dim)
582 }
583}
584
585fn parse_embedding_response(resp_json: &Value, expected_dim: usize) -> Result<Vec<f32>> {
591 let embedding = resp_json
592 .pointer("/data/0/embedding")
593 .and_then(Value::as_array)
594 .ok_or_else(|| InnateError::Other("unexpected embedding response shape".into()))?;
595 let vec: Vec<f32> = embedding
596 .iter()
597 .map(|v| {
598 v.as_f64().map(|x| x as f32).ok_or_else(|| {
599 InnateError::Other("embedding response contains a non-numeric element".into())
600 })
601 })
602 .collect::<Result<Vec<f32>>>()?;
603 if vec.len() != expected_dim {
604 return Err(InnateError::Other(format!(
605 "embedding dimension mismatch: provider returned {}, expected {expected_dim} (check embedding.dim)",
606 vec.len(),
607 )));
608 }
609 Ok(vec)
610}
611
612impl EmbeddingProvider for LlmEmbeddingProvider {
613 fn model_name(&self) -> &'static str {
614 "llm-embedding"
615 }
616
617 fn content_dim(&self) -> usize {
618 self.config.dim
619 }
620
621 fn trigger_dim(&self) -> usize {
622 self.config.dim
623 }
624
625 fn embed_content(&self, text: &str) -> Result<Vec<f32>> {
626 self.embed(text)
627 }
628
629 fn embed_trigger(&self, text: &str) -> Result<Vec<f32>> {
630 self.embed(text)
631 }
632
633 fn embed_both(&self, text: &str) -> Result<(Vec<f32>, Vec<f32>)> {
636 let v = self.embed(text)?;
637 Ok((v.clone(), v))
638 }
639}
640
641pub fn test_llm(config: &LlmConfig) -> Result<String> {
647 let distiller = build_distiller(config);
648 let dummy_log = json!({
649 "id": "test",
650 "query": "connection test",
651 "output_summary": "test",
652 "outcome": "ok"
653 });
654 distiller.distill(&[dummy_log])?;
656 Ok(format!("OK — model: {}", config.model_id))
657}
658
659pub fn test_embedding(config: &EmbeddingConfig) -> Result<usize> {
661 let provider = LlmEmbeddingProvider::new(config.clone());
662 let vec = provider.embed("connection test")?;
663 Ok(vec.len())
664}