$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"]); }