Files
html/api/ambre-session-memory.php
2026-04-21 23:35:01 +02:00

89 lines
2.9 KiB
PHP

<?php
/**
* ambre-session-memory.php · AMBRE v1 · per-session memory store
* Stores/retrieves last N messages per session_id in /var/tmp/wevia-sessions/
*/
class AmbreSessionMemory {
const DIR = "/var/tmp/wevia-sessions";
const MAX_TURNS = 20;
const TTL_HOURS = 24;
public static function init() {
if (!is_dir(self::DIR)) @mkdir(self::DIR, 0777, true);
}
public static function path($sid) {
self::init();
$safe = preg_replace("/[^a-zA-Z0-9_-]/", "", $sid);
if (!$safe) $safe = "default";
return self::DIR . "/" . $safe . ".json";
}
public static function load($sid) {
$p = self::path($sid);
if (!file_exists($p)) return [];
$content = @file_get_contents($p);
if (!$content) return [];
$data = @json_decode($content, true);
if (!is_array($data)) return [];
// TTL cleanup
$now = time();
$data = array_filter($data, function($m) use ($now) {
return isset($m["ts"]) && ($now - $m["ts"]) < (self::TTL_HOURS * 3600);
});
return array_values($data);
}
public static function append($sid, $role, $content) {
if (!$sid || !$role || !$content) return;
$msgs = self::load($sid);
$msgs[] = [
"role" => $role,
"content" => substr((string)$content, 0, 4000),
"ts" => time(),
];
// Keep only last N
if (count($msgs) > self::MAX_TURNS) {
$msgs = array_slice($msgs, -self::MAX_TURNS);
}
@file_put_contents(self::path($sid), json_encode($msgs, JSON_UNESCAPED_UNICODE), LOCK_EX);
}
public static function context_messages($sid, $max = 10) {
$msgs = self::load($sid);
$last = array_slice($msgs, -$max);
$out = [];
foreach ($last as $m) {
$out[] = ["role" => $m["role"], "content" => $m["content"]];
}
return $out;
}
public static function summary($sid) {
$msgs = self::load($sid);
return [
"session" => $sid,
"turns" => count($msgs),
"first_ts" => !empty($msgs) ? date("c", $msgs[0]["ts"]) : null,
"last_ts" => !empty($msgs) ? date("c", end($msgs)["ts"]) : null,
];
}
public static function clear($sid) {
$p = self::path($sid);
if (file_exists($p)) @unlink($p);
}
}
// Direct API usage
if (basename($_SERVER["SCRIPT_NAME"]) === "ambre-session-memory.php") {
header("Content-Type: application/json");
$sid = $_GET["sid"] ?? "";
$action = $_GET["action"] ?? "summary";
if ($action === "summary") echo json_encode(AmbreSessionMemory::summary($sid));
elseif ($action === "load") echo json_encode(AmbreSessionMemory::load($sid));
elseif ($action === "clear") { AmbreSessionMemory::clear($sid); echo json_encode(["cleared"=>true]); }
else echo json_encode(["error"=>"unknown action"]);
}