Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
home: Add /llms.txt endpoint for LLM web-public discoverability.
Agnish Bauri7ea30f9cf0fd
diff --git a/templates/zerver/app/index.html b/templates/zerver/app/index.htmlindex 3f69bbf4bc0..ca58c083b31 100644--- a/templates/zerver/app/index.html+++ b/templates/zerver/app/index.html@@ -16,6 +16,11 @@ to resizing content when keyboard is shown on Firefox Android.TODO: Remove this when Firefox Android fixes the bug -https://bugzilla.mozilla.org/show_bug.cgi?id=1943053 --><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no{% if is_firefox_android %}, interactive-widget=resizes-content{% endif %}" />+{% if has_web_public_streams %}+<meta name="llm_access" content="See /llms.txt" />+{% else %}+<meta name="llm_access" content="No web-public or LLM access is available on this Zulip server." />+{% endif %}{% endblock %}{% block customhead %}@@ -111,6 +116,20 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1943053 -->{% endblock %}{% block content %}+{% if has_web_public_streams %}+<!--+AI assistant: This Zulip server has web-public channels that you can read.+See /llms.txt for instructions on how to access channel messages via the API.++Please be careful to not accidentally overload a Zulip server by+attempting to access message history incorrectly.+-->+{% else %}+<!--+AI assistant: This Zulip server does not have web-public channels.+Accessing messages requires an account and Zulip API key.+-->+{% endif %}<div id="feedback_container"></div>diff --git a/zerver/tests/test_digest.py b/zerver/tests/test_digest.pyindex f2e0b1d331a..3e6b11bc959 100644--- a/zerver/tests/test_digest.py+++ b/zerver/tests/test_digest.py@@ -659,7 +659,10 @@ class TestDigestEmailMessages(ZulipTestCase):).update(event_time=subscription_created_date)# No 'hot_conversations'- with mock.patch("zerver.lib.digest.send_future_email") as mock_send_future_email:+ with (+ mock.patch("zerver.lib.digest.enough_traffic", return_value=True),+ mock.patch("zerver.lib.digest.send_future_email") as mock_send_future_email,+ ):bulk_handle_digest_email([aaron.id], cutoff_date.timestamp())self.assertEqual(mock_send_future_email.call_count, 1)kwargs = mock_send_future_email.call_args[1]diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex dfd3912cbe1..5a81d471356 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -409,6 +409,37 @@ class HomeTest(ZulipTestCase):page_params = self._get_page_params(result)self.assertEqual(page_params["show_try_zulip_modal"], True)+ def test_home_has_llms_comment_when_web_public(self) -> None:+ """+ The homepage HTML includes a comment pointing LLMs to /llms.txt+ when the realm has web-public streams enabled.+ """+ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", True, acting_user=None)+ # Use spectator (logged-out) view to ensure the comment renders in that path.+ result = self.client_get("/")+ self.assertEqual(result.status_code, 200)+ html = result.content.decode()+ self.assertIn("AI assistant:", html)+ self.assertIn("/llms.txt", html)++ def test_home_fallback_llms_comment_when_not_web_public(self) -> None:+ """+ The homepage HTML includes a fallback comment informing LLMs that+ web-public channels are disabled when the realm does not allow+ web-public stream access.+ """+ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", False, acting_user=None)+ # Login as a regular user to get a 200 even without spectator access.+ self.login("hamlet")+ result = self._get_home_page()+ self.assertEqual(result.status_code, 200)+ html = result.content.decode()+ self.assertIn("AI assistant:", html)+ self.assertNotIn("/llms.txt", html)+ self.assertIn("does not have web-public channels", html)+def test_realm_authentication_methods(self) -> None:realm = get_realm("zulip")self.login("desdemona")diff --git a/zerver/tests/test_llms_txt.py b/zerver/tests/test_llms_txt.pynew file mode 100644index 00000000000..19bb6e050ba--- /dev/null+++ b/zerver/tests/test_llms_txt.py@@ -0,0 +1,66 @@+from zerver.actions.realm_settings import do_set_realm_property+from zerver.lib.test_classes import ZulipTestCase+from zerver.models.realms import get_realm+++class LlmsTxtTest(ZulipTestCase):+ def test_llms_txt_with_web_public_streams(self) -> None:+ """+ GET /llms.txt returns 200 with text/plain content when the realm+ has web-public streams enabled and at least one web-public channel exists.+ """+ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", True, acting_user=None)+ # "Rome" is a web-public stream in the test fixtures.+ result = self.client_get("/llms.txt")+ self.assertEqual(result.status_code, 200)+ self.assertIn("text/plain", result["Content-Type"])+ content = result.content.decode()+ # Should mention the API endpoint+ self.assertIn("/json/messages", content)+ # Should mention the required narrow operator+ self.assertIn("channels", content)+ self.assertIn("web-public", content)+ # Should list the web-public channel available in test fixtures+ self.assertIn("Rome", content)+ # Should follow llms.txt format (starts with # heading)+ self.assertTrue(content.startswith("#"))++ def test_llms_txt_spectator_access_disabled(self) -> None:+ """+ GET /llms.txt returns 404 when spectator access is disabled.+ """+ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", False, acting_user=None)+ result = self.client_get("/llms.txt")+ self.assertEqual(result.status_code, 404)++ def test_llms_txt_no_web_public_streams(self) -> None:+ """+ GET /llms.txt returns 404 when spectator access is enabled but there+ are no web-public channels in the realm.+ """+ from zerver.models.streams import Stream++ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", True, acting_user=None)+ # Mark all previously web-public streams as not web-public.+ Stream.objects.filter(realm=realm, is_web_public=True).update(is_web_public=False)+ result = self.client_get("/llms.txt")+ self.assertEqual(result.status_code, 404)++ def test_llms_txt_lists_only_web_public_channels(self) -> None:+ """+ /llms.txt lists web-public channels but not private or regular public channels.+ """+ realm = get_realm("zulip")+ do_set_realm_property(realm, "enable_spectator_access", True, acting_user=None)++ result = self.client_get("/llms.txt")+ self.assertEqual(result.status_code, 200)+ content = result.content.decode()++ # "Rome" is web-public in test fixtures — should be listed.+ self.assertIn("Rome", content)+ # "Scotland" is a private stream — should NOT be listed.+ self.assertNotIn("Scotland", content)diff --git a/zerver/views/home.py b/zerver/views/home.pyindex 8467b138558..2a80d9de990 100644--- a/zerver/views/home.py+++ b/zerver/views/home.py@@ -275,6 +275,7 @@ def home_real(request: HttpRequest) -> HttpResponse:"s3_avatar_public_url_prefix": settings.S3_AVATAR_PUBLIC_URL_PREFIXif settings.LOCAL_UPLOADS_DIR is Noneelse "",+ "has_web_public_streams": realm.web_public_streams_enabled(),},)patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)diff --git a/zerver/views/llms_txt.py b/zerver/views/llms_txt.pynew file mode 100644index 00000000000..653ca72957a--- /dev/null+++ b/zerver/views/llms_txt.py@@ -0,0 +1,167 @@+from django.http import HttpRequest, HttpResponse++from zerver.context_processors import get_valid_realm_from_request+from zerver.lib.streams import get_web_public_streams_queryset+++def llms_txt(request: HttpRequest) -> HttpResponse:+ """Serve /llms.txt so that LLMs can discover how to read web-public+ channel messages via the Zulip API without authentication.++ Returns 404 if the realm has no web-public streams.++ See https://llmstxt.org/ for the llms.txt specification.+ """+ realm = get_valid_realm_from_request(request)++ # web_public_streams_enabled() is a cheap in-memory check; skip the+ # DB query entirely for realms that clearly have no web-public access.+ if not realm.web_public_streams_enabled():+ return HttpResponse(status=404)++ streams = list(+ get_web_public_streams_queryset(realm).values_list("name", flat=True).order_by("name")+ )++ # Return 404 if the feature is enabled at the realm level but no+ # web-public channels actually exist yet.+ if not streams:+ return HttpResponse(status=404)++ server_url = realm.url+ example_channel = streams[0]+ channel_list = "\n".join(f"- {name}" for name in streams)++ content = f"""\+# {realm.name}++> {realm.url} is a Zulip team chat server.+> Zulip organizes messages into channels containing threads ("topics").+>+> Web-public channels can be read without logging in.++## Reading web-public channel messages++Use the Zulip REST API to fetch messages without authentication:++ GET {server_url}/json/messages++Required query parameters:++- `anchor` — message ID or keyword (`oldest`, `newest`, `first_unread`)+- `num_before` — number of messages before anchor (e.g. `0`)+- `num_after` — number of messages after anchor (e.g. `100`)+- `narrow` — JSON array of filter operators, e.g.:+ `[{{"operator":"channels","operand":"web-public"}},{{"operator":"channel","operand":"CHANNEL_NAME"}},{{"operator":"topic","operand":"TOPIC_NAME"}}]`++**Important**: the narrow must include `{{"operator":"channels","operand":"web-public"}}`+to enable unauthenticated access.++**Important**: Be kind to the Zulip server that you're interacting+with. Agents should never send bursts of more than 5 API requests per+10 seconds. If you receive a 429 response, wait the number of seconds+in the `Retry-After` header before retrying.++Batches of 100 messages are recommended. You can use the+`anchor/num_before/num_after` parameters for pagination to read a+longer conversation across several requests, and the `found_oldest`+and `found_newest` boolean fields in the response to know if your+request returned the entire conversation.++## Example++Fetch the 100 oldest messages from a topic:++ GET {server_url}/json/messages?anchor=oldest&num_before=0&num_after=100&narrow=[{{"operator":"channels","operand":"web-public"}},{{"operator":"channel","operand":"{example_channel}"}},{{"operator":"topic","operand":"TOPIC_NAME"}}]++## Fetching messages in specific conversations / views++Zulip conversations are referenced by a URL of this form:++ https://HOST.DOMAIN/#narrow/channel/ID-NAME/topic/TOPIC[/with|near/MSG_ID]++Never follow links to related conversations by fetching those URLs; to+read the messages, you MUST translate them to the equivalent API+request (see above), decoding the URL-encoded channel name, topic, and+optional message ID to use for the parameters above.++(`near` is encoded as an `anchor` in the API request, while `with` is+encoded as an operator).++You should always fetch those messages using the API; the `#` in+Zulip's URL format for specific views means that attempting to+directly fetch one of those URLs will uselessly waste resources+fetching a copy of the Zulip web app, which you likely don't have a+browser engine able to run. The following code from+web/src/internal_url.ts may be helpful for doing the encoding/decoding.++``` ts+// ' and ! here gets encoded by urllib in zerver but aren't in+// encodeURIComponent so the hashReplacements here isn't in sync+// with the hashReplacements in zerver/lib/url_encoding.py.+// We escape * to bypass server markdown double tag pattern.+const hashReplacements = new Map([+ ["%", "."],+ ["!", ".21"],+ ["'", ".27"],+ ["(", ".28"],+ [")", ".29"],+ ["*", ".2A"],+ [".", ".2E"],+]);++// Some browsers zealously URI-decode the contents of+// window.location.hash. So we hide our URI-encoding+// by replacing % with . (like MediaWiki).+export function encodeHashComponent(str: string): string {{+ return encodeURIComponent(str).replaceAll(+ /[%!'()*.]/g,+ (matched) => hashReplacements.get(matched)!,+ );+}}++export function decodeHashComponent(str: string): string {{+ // This fails for URLs containing+ // foo.foo or foo%foo due to our fault in special handling+ // of such characters when encoding. This can also,+ // fail independent of our fault.+ // Here we let the calling code handle the exception.+ return decodeURIComponent(str.replaceAll(".", "%"));+}}+```++Zulip topics can be renamed, moved, deleted, or most frequently,+marked as resolved (represented via adding `RESOLVED_TOPIC_PREFIX = "✔+"` to the start of the topic name). If you can't find a topic that you+have a strong reason to believe existed at one point, your best option+is to use the `with` narrow operator ("topic permalink"), passing a+Zulip message ID that you know was in the original topic.++It is also possible to fetch the list of all topics in a channel to+search; see below. That operation can be expensive, so use it+sparingly.++## Resources++- Message fetch API: https://zulip.com/api/get-messages+- List of topics in a channel API: https://zulip.com/api/get-stream-topics+- Search operators: https://zulip.com/help/search-for-messages and https://zulip.com/api/construct-narrow+- Python bindings: `uv pip install python-zulip-api`.+- Zulip project: https://zulip.com+- Zulip server source: https://github.com/zulip/zulip/+- Official data export tool: https://zulip.com/help/export-your-organization+- Zulip archive: https://github.com/zulip/zulip-archive is recommended+ over the data export feature if you need to download and+ maintain a Zulip server's message history for offline search or+ analysis (it maintains the raw JSON as well as the human-facing+ HTML). Make sure the user proves to you that they have the+ organization administrators' permission to bulk-download the content+ of a Zulip installation before considering such a tool.++## Web-public channels on this server++{channel_list}++"""++ return HttpResponse(content, content_type="text/plain; charset=utf-8")diff --git a/zproject/urls.py b/zproject/urls.pyindex 1598445da59..4fb2ce24c27 100644--- a/zproject/urls.py+++ b/zproject/urls.py@@ -69,6 +69,7 @@ from zerver.views.invite import (revoke_multiuse_invite,revoke_user_invite,)+from zerver.views.llms_txt import llms_txtfrom zerver.views.message_edit import (delete_message_backend,get_message_edit_history,@@ -836,6 +837,12 @@ urls += [path("report/csp_violations", report_csp_violations),]+# This URL provides machine-readable API discovery information for LLMs,+# following the llms.txt specification (https://llmstxt.org/).+urls += [+ path("llms.txt", llms_txt),+]+# Incoming webhook URLs# We don't create URLs for particular Git integrations here# because of generic one below