mirror of
https://github.com/R0m1k3/Loki.git
synced 2026-10-22 22:48:11 +02:00
Façade : see_video exécuté par la façade, vidéos jointes rangées relues
Comme see_image (lot 45), see_video est tenu par la façade : imagetools::see_video porte toolSeeVideo (mêmes refus, même ordre, sonde du moteur en dernier) et video_input_supported la capacité du moteur (aide du binaire, --video-fps, relue quand il change). La vidéo relayée est toujours éphémère, KEEP_TURN_IMAGES compris (turn.rs) ; vision_video relu de /tool/exec quand le Go exécute l'outil. Vidéos jointes rangées (loki-vid:) : remises en data-URL avant l'envoi avec les images (expand_image_refs, cache des médias élargi à chatvid). Libellé et non-dédup de see_video, videoLostMarker à la compaction et au rechargement d'un fil, élision dans l'export. Parité : journal tiré du Go (parity_video_tool_test.go → tests/parity_images/video.json : refus, moteur sans vidéo, moteur aveugle, vidéos relayées à l'octet), rejoué par tests/videotools.rs ; journal multiplateforme (ni faux Playwright ni sh). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
776de75dd0
commit
ac74ecde0b
12 files changed
+1084
-42
No files matched your search
@@ -58,6 +58,9 @@ pub const COMPACT_SUMMARY_PREFIX: &str = "[CONTEXT COMPACTED]";
|
||||
/// Remplace la partie `image_url` d'un message multimodal dans [`msg_text`].
|
||||
pub const IMAGE_LOST_MARKER: &str = " [image — not kept in the conversation past this point; look at it again (see_image on the file, or a new screenshot) if you still need to see it]";
|
||||
|
||||
/// `videoLostMarker` : remplace la partie `input_video` (chat_video.go).
|
||||
pub const VIDEO_LOST_MARKER: &str = " [video — not kept in the conversation past this point; call see_video on the file again if you still need to watch it]";
|
||||
|
||||
/// La réponse assistant synthétique qui suit le résumé.
|
||||
pub const COMPACT_ACK_MSG: &str = "Understood. I'll resume from exactly where I left off, using the findings above, and call recall(id) if I need the full content of an archived block, without redoing work that is already done.";
|
||||
|
||||
@@ -265,6 +268,7 @@ pub fn msg_text(m: &Message) -> String {
|
||||
}
|
||||
}
|
||||
Some("image_url") => b.push_str(IMAGE_LOST_MARKER),
|
||||
Some("input_video") => b.push_str(VIDEO_LOST_MARKER),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
+101
-16
@@ -14,8 +14,9 @@
|
||||
//! - compaction par [`Compactor`] : résumé demandé au moteur
|
||||
//! ([`EngineSummarizer`]), blocs archivés pour recall par le Go
|
||||
//! ([`StoreRecall`]) ;
|
||||
//! - images jointes (`loki-img:…`) lues sur disque et ouvertes par le Go
|
||||
//! (déchiffrées), gardées en cache comme `chatImageDataURL` ;
|
||||
//! - images et vidéos jointes (`loki-img:…`, `loki-vid:…`) lues sur disque
|
||||
//! et ouvertes par le Go (déchiffrées), gardées en cache comme
|
||||
//! `chatImageDataURL` / `chatVideoDataURL` ;
|
||||
//! - slots du moteur (lot 31) : avant chaque requête au moteur local, le Go
|
||||
//! rend le slot où l'envoyer (SIDE_SLOT) et recharge au besoin l'état
|
||||
//! gardé de la discussion (SLOT_PERSIST) ; la requête est comptée en vol,
|
||||
@@ -46,8 +47,8 @@ use super::stream::{CacheHintFn, PreflightFn, RetryPatterns};
|
||||
use super::turn::{CompactPhase, PerfMarks, PerfRec, Reply, SendError, ToolOutcome, TurnHost};
|
||||
use super::types::{AskEvent, DiffLine, Message, Tool};
|
||||
use super::wire::{
|
||||
ChatEndpoint, ChatPayloadOpts, EchoRefusals, EffortFallbacks, IMG_REF_SCHEME,
|
||||
build_chat_payload, content_parts, part_image_url, wire_messages,
|
||||
ChatEndpoint, ChatPayloadOpts, EchoRefusals, EffortFallbacks, IMG_REF_SCHEME, VID_REF_SCHEME,
|
||||
build_chat_payload, content_parts, part_image_url, part_video_url, wire_messages,
|
||||
};
|
||||
use crate::store::{BK_STATE, Store};
|
||||
|
||||
@@ -97,10 +98,32 @@ fn image_mime(name: &str) -> &'static str {
|
||||
|
||||
/// Nom d'une image rangée, si la référence est sûre (ni chemin ni `..`).
|
||||
fn image_name(r: &str) -> Option<&str> {
|
||||
let name = r.strip_prefix(IMG_REF_SCHEME)?;
|
||||
safe_media_name(r.strip_prefix(IMG_REF_SCHEME)?)
|
||||
}
|
||||
|
||||
fn safe_media_name(name: &str) -> Option<&str> {
|
||||
(!name.is_empty() && !name.contains(['/', '\\']) && !name.contains("..")).then_some(name)
|
||||
}
|
||||
|
||||
/// Média rangé : (clé du cache, fichier relatif à `LOKI_HOME`, type MIME).
|
||||
/// Une image a pour clé son nom (dossier `chatimg`), une vidéo jointe
|
||||
/// (`loki-vid:`, chat_video.go) sa référence entière (dossier `chatvid`).
|
||||
fn media_ref(r: &str) -> Option<(String, PathBuf, &'static str)> {
|
||||
if let Some(name) = image_name(r) {
|
||||
return Some((
|
||||
name.to_string(),
|
||||
Path::new("chatimg").join(name),
|
||||
image_mime(name),
|
||||
));
|
||||
}
|
||||
let name = safe_media_name(r.strip_prefix(VID_REF_SCHEME)?)?;
|
||||
let mime = match crate::imagetools::video_mime(name) {
|
||||
"" => "video/mp4",
|
||||
m => m,
|
||||
};
|
||||
Some((r.to_string(), Path::new("chatvid").join(name), mime))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ImgCacheInner {
|
||||
map: HashMap<String, String>,
|
||||
@@ -129,9 +152,10 @@ impl ImageCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Data-URL d'une image (`loki-img:`) ou d'une vidéo (`loki-vid:`) rangée.
|
||||
pub fn get(&self, r: &str) -> Option<String> {
|
||||
let name = image_name(r)?;
|
||||
self.inner.lock().ok()?.map.get(name).cloned()
|
||||
let (key, _, _) = media_ref(r)?;
|
||||
self.inner.lock().ok()?.map.get(&key).cloned()
|
||||
}
|
||||
|
||||
fn put(&self, name: &str, url: String) {
|
||||
@@ -151,27 +175,30 @@ impl ImageCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lit et ouvre (par le Go) les images référencées pas encore en cache.
|
||||
/// Une image illisible reste absente : la requête dira « indisponible ».
|
||||
/// Lit et ouvre (par le Go) les images et vidéos référencées pas encore
|
||||
/// en cache. Un média illisible reste absent : la requête dira
|
||||
/// « indisponible ».
|
||||
pub async fn prefetch(&self, store: &Store, msgs: &[Message]) {
|
||||
let home = self.home();
|
||||
for m in msgs {
|
||||
for p in content_parts(m.content.as_ref()) {
|
||||
let Some(name) = image_name(part_image_url(p)) else {
|
||||
let u = match part_image_url(p) {
|
||||
"" => part_video_url(p),
|
||||
u => u,
|
||||
};
|
||||
let Some((key, rel, mime)) = media_ref(u) else {
|
||||
continue;
|
||||
};
|
||||
if self.inner.lock().is_ok_and(|g| g.map.contains_key(name)) {
|
||||
if self.inner.lock().is_ok_and(|g| g.map.contains_key(&key)) {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = tokio::fs::read(self.dir.join(name)).await else {
|
||||
let Ok(raw) = tokio::fs::read(home.join(rel)).await else {
|
||||
continue;
|
||||
};
|
||||
let Ok(b) = store.open(raw).await else {
|
||||
continue;
|
||||
};
|
||||
self.put(
|
||||
name,
|
||||
format!("data:{};base64,{}", image_mime(name), b64(&b)),
|
||||
);
|
||||
self.put(&key, format!("data:{mime};base64,{}", b64(&b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -586,6 +613,11 @@ pub fn tool_outcome(v: &Value, label: &str) -> ToolOutcome {
|
||||
{
|
||||
relay = Some(see_image_message(label, img.clone()));
|
||||
}
|
||||
if relay.is_none()
|
||||
&& let Some(vid) = v.get("vision_video").filter(|i| i.is_object())
|
||||
{
|
||||
relay = Some(see_video_message(label, vid.clone()));
|
||||
}
|
||||
ToolOutcome {
|
||||
result: s("result"),
|
||||
diff: v
|
||||
@@ -617,6 +649,20 @@ pub fn see_image_message(label: &str, img: Value) -> Message {
|
||||
}
|
||||
}
|
||||
|
||||
/// `seeVideoMessage` : la vidéo relayée au modèle.
|
||||
pub fn see_video_message(label: &str, vid: Value) -> Message {
|
||||
let text = if label.is_empty() {
|
||||
"Vidéo :".to_string()
|
||||
} else {
|
||||
format!("Vidéo demandée ({label}) :")
|
||||
};
|
||||
Message {
|
||||
role: "user".into(),
|
||||
content: Some(json!([{"type": "text", "text": text}, vid])),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl GoTurnHost {
|
||||
/// Les outils exécutés par la façade, sauf `subagent` ; le reste par le
|
||||
/// Go (`/tool/exec`). Aussi celui des tours d'un sous-agent.
|
||||
@@ -751,6 +797,45 @@ impl GoTurnHost {
|
||||
};
|
||||
}
|
||||
}
|
||||
// see_video (chat_video_tool.go) : comme see_image, dans le dossier de
|
||||
// la discussion ; la vidéo relayée au modèle, toujours éphémère.
|
||||
if name == "see_video" {
|
||||
let cfg = self.shared.store.config().await;
|
||||
let vision = crate::system::vision_enabled(&cfg);
|
||||
let st = crate::tools::GoToolState {
|
||||
store: self.shared.store.clone(),
|
||||
caps: self.caps.clone(),
|
||||
};
|
||||
match crate::tools::ToolState::context(&st).await {
|
||||
Ok(ctx) => {
|
||||
let home = self.shared.images.home();
|
||||
let vcfg = cfg.clone();
|
||||
let video_ok = tokio::task::spawn_blocking(move || {
|
||||
crate::imagetools::video_input_supported(&vcfg, &home)
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
let sees = self.shared.vision.sees(&self.shared.store, &cfg);
|
||||
let (result, vid) = crate::imagetools::see_video(
|
||||
label,
|
||||
&ctx.cwd,
|
||||
&ctx.target,
|
||||
vision,
|
||||
video_ok,
|
||||
sees,
|
||||
)
|
||||
.await;
|
||||
return ToolOutcome {
|
||||
result,
|
||||
relay: vid.map(|v| see_video_message(label, v)),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[outils] contexte indisponible, see_video par le Go : {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Navigateur piloté (lot 44) : la session est ici ; aperçu de la page
|
||||
// après une action qui la change (jamais après une erreur), capture
|
||||
// relayée au modèle.
|
||||
|
||||
@@ -141,10 +141,13 @@ pub fn steer_system(msgs: &[Message], hint: &str) -> Vec<Message> {
|
||||
}
|
||||
|
||||
/// `dedupableTool` : un appel identique se court-circuite, sauf bash et ses
|
||||
/// jobs (effets de bord), see_image et le navigateur (état vivant, image à
|
||||
/// part).
|
||||
/// jobs (effets de bord), see_image, see_video et le navigateur (état
|
||||
/// vivant, image ou vidéo à part).
|
||||
pub fn dedupable_tool(name: &str) -> bool {
|
||||
!matches!(name, "bash" | "bash_bg" | "bash_tail" | "see_image") && !name.starts_with("browser_")
|
||||
!matches!(
|
||||
name,
|
||||
"bash" | "bash_bg" | "bash_tail" | "see_image" | "see_video"
|
||||
) && !name.starts_with("browser_")
|
||||
}
|
||||
|
||||
/// `repeatedCallResult` : réponse à un appel RIGOUREUSEMENT identique déjà
|
||||
|
||||
@@ -49,7 +49,7 @@ use serde::{Deserialize, Serialize, Serializer};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use super::compact::{IMAGE_LOST_MARKER, is_loki_injected, without_ctx_update};
|
||||
use super::compact::{IMAGE_LOST_MARKER, VIDEO_LOST_MARKER, is_loki_injected, without_ctx_update};
|
||||
use super::journal::compact_log;
|
||||
use super::types::{LogEvent, Message};
|
||||
use crate::store::{CryptError, Store};
|
||||
@@ -269,24 +269,39 @@ fn decode_list<T: DeserializeOwned>(v: Value) -> Vec<T> {
|
||||
/// `stripImageParts` : un message multimodal persisté (base64 d'une capture
|
||||
/// d'avant les captures éphémères) est aplati en son texte suivi de
|
||||
/// [`IMAGE_LOST_MARKER`] — rejoué à chaque tour, il dépassait le contexte.
|
||||
/// Une vidéo jointe (`input_video`) a le même sort, marquée par
|
||||
/// [`VIDEO_LOST_MARKER`].
|
||||
pub fn strip_image_parts(msgs: &mut [Message]) {
|
||||
for m in msgs.iter_mut() {
|
||||
let Some(Value::Array(parts)) = &m.content else {
|
||||
continue;
|
||||
};
|
||||
let mut texts: Vec<&str> = Vec::new();
|
||||
let mut dropped = false;
|
||||
let (mut dropped, mut dropped_vid) = (false, false);
|
||||
for p in parts.iter().filter_map(Value::as_object) {
|
||||
if p.get("type").and_then(Value::as_str) == Some("image_url") {
|
||||
dropped = true;
|
||||
continue;
|
||||
match p.get("type").and_then(Value::as_str) {
|
||||
Some("image_url") => {
|
||||
dropped = true;
|
||||
continue;
|
||||
}
|
||||
Some("input_video") => {
|
||||
dropped_vid = true;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(Value::String(t)) = p.get("text") {
|
||||
texts.push(t);
|
||||
}
|
||||
}
|
||||
if dropped {
|
||||
let text = texts.join("\n") + IMAGE_LOST_MARKER;
|
||||
if dropped || dropped_vid {
|
||||
let mut text = texts.join("\n");
|
||||
if dropped {
|
||||
text += IMAGE_LOST_MARKER;
|
||||
}
|
||||
if dropped_vid {
|
||||
text += VIDEO_LOST_MARKER;
|
||||
}
|
||||
m.content = Some(Value::String(text));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -621,7 +621,7 @@ pub fn tool_call_label(name: &str, args: &Map<String, Value>) -> String {
|
||||
match name {
|
||||
"mem_search" | "web_search" | "web_images" | "recall_search" => arg_str(args, "query"),
|
||||
"mem_read" | "mem_add" | "mem_edit" | "edit" | "write" | "read" | "git_diff"
|
||||
| "see_image" => arg_str(args, "file"),
|
||||
| "see_image" | "see_video" => arg_str(args, "file"),
|
||||
"recall" | "bash_tail" => arg_str(args, "id"),
|
||||
"tracker" => (go_str(args.get("action")) + " " + &go_str(args.get("name")))
|
||||
.trim()
|
||||
|
||||
@@ -384,6 +384,13 @@ pub fn side_slot_pool_error(msg: &str) -> bool {
|
||||
&& !REQ_EXCEEDS.is_match(msg)
|
||||
}
|
||||
|
||||
/// Le relais porte-t-il une vidéo (see_video, partie `input_video`) ?
|
||||
fn is_video_relay(m: &Message) -> bool {
|
||||
super::wire::content_parts(m.content.as_ref())
|
||||
.iter()
|
||||
.any(|p| p.get("type").and_then(Value::as_str) == Some("input_video"))
|
||||
}
|
||||
|
||||
fn text_msg(role: &str, text: impl Into<String>) -> Message {
|
||||
Message {
|
||||
role: role.into(),
|
||||
@@ -1071,8 +1078,11 @@ async fn run_turn_loop<H: TurnHost>(
|
||||
push_result(&mut messages, &mut extra, cap_tool_result(&ex.result));
|
||||
if let Some(img) = ex.relay {
|
||||
match kt.as_mut() {
|
||||
// Éphémère : jamais dans l'historique.
|
||||
// Éphémère : jamais dans l'historique. Une vidéo
|
||||
// (see_video) l'est toujours, KEEP_TURN_IMAGES compris :
|
||||
// le rangement ne sait garder que des images.
|
||||
None => messages.push(img),
|
||||
Some(_) if is_video_relay(&img) => messages.push(img),
|
||||
// KEEP_TURN_IMAGES : gardée par référence, à l'essai
|
||||
// jusqu'à la mesure de son coût.
|
||||
Some(k) => {
|
||||
|
||||
@@ -60,6 +60,10 @@ pub const TOOLS_OFF_HINT: &str = "Do not call any more tools. Answer now, direct
|
||||
/// `imgRefScheme` : adresse d'une image rangée sur disque (chat_images.go).
|
||||
pub const IMG_REF_SCHEME: &str = "loki-img:";
|
||||
|
||||
/// `vidRefScheme` : adresse d'une vidéo jointe rangée sur disque
|
||||
/// (chat_video.go).
|
||||
pub const VID_REF_SCHEME: &str = "loki-vid:";
|
||||
|
||||
/// Préfixes des messages système propres au projet ou à la conversation
|
||||
/// (`isProjectSystem`).
|
||||
pub const PROJECT_CONTEXT_PREFIX: &str = "Project context";
|
||||
@@ -308,35 +312,61 @@ pub fn part_image_url(p: &Map<String, Value>) -> &str {
|
||||
.unwrap_or("")
|
||||
}
|
||||
|
||||
/// `expandImageRefs` : COPIE des messages prête pour le modèle — chaque
|
||||
/// référence `loki-img:` redevient sa data-URL (`image_data_url`, qui tient
|
||||
/// lieu de `chatImageDataURL` : disque, cache, déchiffrement). Les messages
|
||||
/// sans référence sont repris tels quels ; aucune référence : pas de copie.
|
||||
/// Une image introuvable devient une mention textuelle.
|
||||
/// `partVideoURL` : l'adresse d'une partie `input_video` (`url`, sinon
|
||||
/// `data`), "" pour toute autre partie (chat_video.go).
|
||||
pub fn part_video_url(p: &Map<String, Value>) -> &str {
|
||||
if p.get("type").and_then(Value::as_str) != Some("input_video") {
|
||||
return "";
|
||||
}
|
||||
let Some(iv) = p.get("input_video").and_then(Value::as_object) else {
|
||||
return "";
|
||||
};
|
||||
match iv.get("url").and_then(Value::as_str).unwrap_or("") {
|
||||
"" => iv.get("data").and_then(Value::as_str).unwrap_or(""),
|
||||
u => u,
|
||||
}
|
||||
}
|
||||
|
||||
/// `expandVideoRefs(expandImageRefs(…))` : COPIE des messages prête pour le
|
||||
/// modèle — chaque référence `loki-img:` ou `loki-vid:` redevient sa
|
||||
/// data-URL (`image_data_url`, qui tient lieu de `chatImageDataURL` et
|
||||
/// `chatVideoDataURL` : disque, cache, déchiffrement). Les messages sans
|
||||
/// référence sont repris tels quels ; aucune référence : pas de copie. Un
|
||||
/// média introuvable devient une mention textuelle.
|
||||
pub fn expand_image_refs<'a>(
|
||||
msgs: &'a [Message],
|
||||
image_data_url: &dyn Fn(&str) -> Option<String>,
|
||||
) -> Cow<'a, [Message]> {
|
||||
let is_ref = |p: &Map<String, Value>| {
|
||||
part_image_url(p).starts_with(IMG_REF_SCHEME)
|
||||
|| part_video_url(p).starts_with(VID_REF_SCHEME)
|
||||
};
|
||||
let mut out: Option<Vec<Message>> = None;
|
||||
for (i, m) in msgs.iter().enumerate() {
|
||||
let parts = content_parts(m.content.as_ref());
|
||||
if !parts
|
||||
.iter()
|
||||
.any(|p| part_image_url(p).starts_with(IMG_REF_SCHEME))
|
||||
{
|
||||
if !parts.iter().any(|p| is_ref(p)) {
|
||||
continue;
|
||||
}
|
||||
let mut np: Vec<Value> = Vec::with_capacity(parts.len());
|
||||
for p in parts {
|
||||
let u = part_image_url(p);
|
||||
if !u.starts_with(IMG_REF_SCHEME) {
|
||||
if !is_ref(p) {
|
||||
np.push(Value::Object(p.clone()));
|
||||
continue;
|
||||
}
|
||||
match image_data_url(u) {
|
||||
Some(d) => np.push(json!({"type": "image_url", "image_url": {"url": d}})),
|
||||
let u = part_image_url(p);
|
||||
if u.starts_with(IMG_REF_SCHEME) {
|
||||
match image_data_url(u) {
|
||||
Some(d) => np.push(json!({"type": "image_url", "image_url": {"url": d}})),
|
||||
None => np.push(
|
||||
json!({"type": "text", "text": "[image indisponible : fichier supprimé]"}),
|
||||
),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match image_data_url(part_video_url(p)) {
|
||||
Some(d) => np.push(json!({"type": "input_video", "input_video": {"url": d}})),
|
||||
None => np.push(
|
||||
json!({"type": "text", "text": "[image indisponible : fichier supprimé]"}),
|
||||
json!({"type": "text", "text": "[vidéo indisponible : fichier supprimé]"}),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -1807,6 +1837,51 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
// --- chat_video_test.go (partie envoi) ----------------------------------
|
||||
|
||||
#[test]
|
||||
fn video_refs_round_trip() {
|
||||
let url = "data:video/mp4;base64,AAAAGGZ0eXA=";
|
||||
let reference = format!("{VID_REF_SCHEME}0123abcd.mp4");
|
||||
let img_ref = format!("{IMG_REF_SCHEME}ab.png");
|
||||
let set = vec![Message {
|
||||
role: "user".into(),
|
||||
content: Some(json!([
|
||||
{"type": "text", "text": "regarde"},
|
||||
{"type": "image_url", "image_url": {"url": img_ref}},
|
||||
{"type": "input_video", "input_video": {"url": reference}},
|
||||
{"type": "input_video", "input_video": {"data": "data:video/webm;base64,AA=="}}
|
||||
])),
|
||||
..Default::default()
|
||||
}];
|
||||
let resolver = |r: &str| {
|
||||
if r == reference {
|
||||
Some(url.to_string())
|
||||
} else if r == img_ref {
|
||||
Some("data:image/png;base64,AA==".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let out = expand_image_refs(&set, &resolver);
|
||||
let parts = content_parts(out[0].content.as_ref());
|
||||
assert_eq!(part_image_url(parts[1]), "data:image/png;base64,AA==");
|
||||
assert_eq!(part_video_url(parts[2]), url);
|
||||
assert_eq!(parts[2]["type"], "input_video");
|
||||
// Vidéo déjà en ligne (champ data) : reprise telle quelle.
|
||||
assert_eq!(part_video_url(parts[3]), "data:video/webm;base64,AA==");
|
||||
let first = content_parts(set[0].content.as_ref());
|
||||
assert!(
|
||||
part_video_url(first[2]).starts_with(VID_REF_SCHEME),
|
||||
"l'historique n'est pas touché"
|
||||
);
|
||||
let out = expand_image_refs(&set, &|_: &str| None);
|
||||
assert_eq!(
|
||||
content_parts(out[0].content.as_ref())[2]["text"],
|
||||
json!("[vidéo indisponible : fichier supprimé]")
|
||||
);
|
||||
}
|
||||
|
||||
// --- chat_compact_cont_test.go ------------------------------------------
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -194,6 +194,20 @@ pub fn strip_inline_images(msgs: Vec<Message>) -> Vec<Message> {
|
||||
let e = elide_data_uri(url);
|
||||
iu.insert("url".into(), Value::String(e));
|
||||
}
|
||||
// Vidéo jointe (input_video, chat_video.go) : même
|
||||
// élision, sur ses deux champs.
|
||||
if let Value::Object(part) = p
|
||||
&& let Some(Value::Object(iv)) = part.get_mut("input_video")
|
||||
{
|
||||
for key in ["url", "data"] {
|
||||
if let Some(Value::String(u)) = iv.get(key)
|
||||
&& u.starts_with("data:")
|
||||
{
|
||||
let e = elide_data_uri(u);
|
||||
iv.insert(key.into(), Value::String(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
|
||||
@@ -225,6 +225,169 @@ pub async fn see_image(
|
||||
)
|
||||
}
|
||||
|
||||
// --- see_video (chat_video.go, chat_video_tool.go) ------------------------------
|
||||
|
||||
/// `maxVideoBytes` : au-delà, des dizaines de milliers de jetons visuels.
|
||||
pub const MAX_VIDEO_BYTES: i64 = 200 << 20;
|
||||
|
||||
/// `videoFallbackNote` : consigne quand le moteur ne lit pas la vidéo.
|
||||
pub const VIDEO_FALLBACK_NOTE: &str = "Le moteur actif ne lit pas la vidéo directement. Pour en voir le contenu, extrais quelques images avec ffmpeg (par exemple `ffmpeg -i <vidéo> -vf fps=1 frame_%03d.jpg`) puis regarde-les avec see_image ; si ffmpeg est absent, dis-le plutôt que de deviner le contenu.\n";
|
||||
|
||||
/// `videoMimes` : les vidéos qu'on sait montrer au modèle.
|
||||
pub fn video_mime(name: &str) -> &'static str {
|
||||
let ext = Path::new(name)
|
||||
.extension()
|
||||
.map(|e| format!(".{}", e.to_string_lossy().to_lowercase()))
|
||||
.unwrap_or_default();
|
||||
match ext.as_str() {
|
||||
".mp4" => "video/mp4",
|
||||
".webm" => "video/webm",
|
||||
".mov" => "video/quicktime",
|
||||
".mkv" => "video/x-matroska",
|
||||
".avi" => "video/x-msvideo",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// `videoPart` : la partie `input_video` que lit llama-server.
|
||||
pub fn video_part(b: &[u8], mime: &str) -> Value {
|
||||
json!({
|
||||
"type": "input_video",
|
||||
"input_video": { "url": format!("data:{mime};base64,{}", base64::engine::general_purpose::STANDARD.encode(b)) },
|
||||
})
|
||||
}
|
||||
|
||||
/// `videoInputSupported` : preset local avec projecteur (MMPROJ) et moteur
|
||||
/// dont l'aide annonce `--video-fps`. Lit le disque et lance le moteur :
|
||||
/// à appeler hors du runtime (`spawn_blocking`). `home` : `LOKI_HOME`.
|
||||
pub fn video_input_supported(cfg: &crate::serve::Cfg, home: &Path) -> bool {
|
||||
use crate::serve::{get, trim};
|
||||
if crate::serve::is_external(cfg)
|
||||
|| crate::serve::is_strata(cfg)
|
||||
|| trim(get(cfg, "MMPROJ")).is_empty()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut bin = trim(get(cfg, "BIN")).to_string();
|
||||
if bin.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if !crate::paths::go_is_abs(&bin) {
|
||||
bin = home.join(&bin).to_string_lossy().into_owned();
|
||||
}
|
||||
let ep = crate::serve::run::EnginePaths {
|
||||
home: home.to_path_buf(),
|
||||
};
|
||||
bin_help_has_video(&ep.prebuilt_resolve_bin(&bin))
|
||||
}
|
||||
|
||||
/// `binHelpHasVideo` : l'aide du binaire, une fois par binaire et par date
|
||||
/// de modification, chemin des bibliothèques passé à la seule commande.
|
||||
pub fn bin_help_has_video(bin: &str) -> bool {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
|
||||
let Ok(st) = std::fs::metadata(bin) else {
|
||||
return false;
|
||||
};
|
||||
if st.is_dir() {
|
||||
return false;
|
||||
}
|
||||
let key = format!("{bin}\0{:?}", st.modified().ok());
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
if let Some(v) = cache.lock().ok().and_then(|c| c.get(&key).copied()) {
|
||||
return v;
|
||||
}
|
||||
let mut env = crate::serve::run::Env::default();
|
||||
let dir = Path::new(bin)
|
||||
.parent()
|
||||
.map(|d| d.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let (k, v) = crate::serve::run::library_path_value(&env, &dir);
|
||||
env.set(&k, &v);
|
||||
let help = crate::serve::run::bin_help(&env, bin);
|
||||
let ok = help.contains("--video-fps");
|
||||
if let Ok(mut c) = cache.lock() {
|
||||
c.insert(key, ok);
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// `toolSeeVideo` : (accusé, partie vidéo). Même ordre de refus que
|
||||
/// [`see_image`] ; `video_ok` : [`video_input_supported`], `sees` : la sonde
|
||||
/// du moteur, appelée en dernier.
|
||||
pub async fn see_video(
|
||||
path: &str,
|
||||
cwd: &Path,
|
||||
target: &str,
|
||||
vision: bool,
|
||||
video_ok: bool,
|
||||
sees: impl std::future::Future<Output = bool>,
|
||||
) -> (String, Option<Value>) {
|
||||
let err = |m: String| (m, None);
|
||||
if !vision {
|
||||
return err("[erreur] la vision n'est pas active sur ce preset (aucun projecteur MMPROJ configuré) — impossible de voir une vidéo".into());
|
||||
}
|
||||
if !target.is_empty() {
|
||||
return err("[erreur] voir une vidéo n'est pas possible sur un poste distant (le fichier est sur l'autre machine)".into());
|
||||
}
|
||||
if path.is_empty() {
|
||||
return err("[erreur] chemin de fichier manquant".into());
|
||||
}
|
||||
if !video_ok {
|
||||
return err(format!(
|
||||
"[erreur] {}",
|
||||
VIDEO_FALLBACK_NOTE.trim_end_matches('\n')
|
||||
));
|
||||
}
|
||||
let abs = crate::tools::policy::resolve_agent_path(cwd, path);
|
||||
let mime = video_mime(&abs.to_string_lossy());
|
||||
if mime.is_empty() {
|
||||
return err(format!(
|
||||
"[erreur] format non reconnu comme vidéo (attendu : mp4, webm, mov, mkv, avi) : {path}"
|
||||
));
|
||||
}
|
||||
let st = match std::fs::metadata(&abs) {
|
||||
Ok(m) => m,
|
||||
Err(_) => return err(format!("[erreur] fichier introuvable : {path}")),
|
||||
};
|
||||
if st.is_dir() {
|
||||
return err(format!("[erreur] c'est un dossier, pas une vidéo : {path}"));
|
||||
}
|
||||
if st.len() as i64 > MAX_VIDEO_BYTES {
|
||||
return err(format!(
|
||||
"[erreur] vidéo trop lourde ({}, max {}) — coupe-la en un clip plus court : {path}",
|
||||
crate::downloads::human_bytes(st.len() as i64),
|
||||
crate::downloads::human_bytes(MAX_VIDEO_BYTES)
|
||||
));
|
||||
}
|
||||
if !sees.await {
|
||||
return err(format!(
|
||||
"[erreur] le moteur en service ne traite pas les images (projecteur non chargé ?) — impossible de voir {path}"
|
||||
));
|
||||
}
|
||||
let b = match std::fs::read(&abs) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
return err(format!(
|
||||
"[erreur] lecture impossible : {}",
|
||||
crate::paths::os_err("open", &abs.to_string_lossy(), &e)
|
||||
));
|
||||
}
|
||||
};
|
||||
if b.is_empty() {
|
||||
return err(format!("[erreur] fichier vide : {path}"));
|
||||
}
|
||||
let base = abs
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
(
|
||||
format!("[ok] vidéo chargée : {base}"),
|
||||
Some(video_part(&b, mime)),
|
||||
)
|
||||
}
|
||||
|
||||
// --- web_screenshot -------------------------------------------------------------
|
||||
|
||||
/// Le résultat de `web_screenshot` : le texte, et la capture rangée
|
||||
|
||||
Reference in new issue
Block a user