Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: read AGENTS.md into chat instructions (#13199)

Daniel Han6105cb2d8f86
diff --git a/studio/backend/core/agents_md.py b/studio/backend/core/agents_md.py
new file mode 100644
index 00000000000..54aa3995daa
--- /dev/null
+++ b/studio/backend/core/agents_md.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""AGENTS.md instructions for Studio chats: Studio's own global file, then the project folder's, as Codex reads them."""
+
+from __future__ import annotations
+
+import os
+import stat
+from pathlib import Path
+from typing import Optional
+
+from utils.account_context import is_owner_context
+from utils.paths import workspace_root
+
+# Codex's project_doc_max_bytes default, for the global and project text together.
+MAX_AGENTS_MD_BYTES = 32 * 1024
+TRUNCATED_NOTE = "\n[AGENTS.md truncated at 32 KiB]"
+_DISABLE_ENV = "UNSLOTH_STUDIO_AGENTS_MD"
+
+
+def agents_md_enabled() -> bool:
+ return os.environ.get(_DISABLE_ENV, "").strip().lower() not in ("0", "false", "no", "off")
+
+
+def _owner_home() -> Path:
+ return Path.home()
+
+
+def _read(path: Path, confine: Optional[Path] = None) -> bytes:
+ # The model writes in the sandbox but this read is unsandboxed: no link there may pull in a host file
+ # (project and global files may be links, CLAUDE.md -> AGENTS.md). Non-blocking so a FIFO cannot hang.
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
+ if confine is not None:
+ if os.path.islink(path):
+ return b""
+ if os.path.dirname(os.path.realpath(path)) != os.path.realpath(confine):
+ return b""
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(path, flags)
+ except OSError:
+ return b""
+ with os.fdopen(fd, "rb") as handle:
+ try:
+ status = os.fstat(handle.fileno())
+ # A hard link is the other way to plant a host file in the sandbox.
+ if not stat.S_ISREG(status.st_mode) or (confine is not None and status.st_nlink > 1):
+ return b""
+ # One byte over the cap is enough to know it was cut.
+ return handle.read(MAX_AGENTS_MD_BYTES + 1)
+ except OSError:
+ return b""
+
+
+def _first(paths: tuple[Path, ...], confine: Optional[Path] = None) -> tuple[Optional[Path], bytes]:
+ # A later name only stands in for a missing or empty earlier one, never adds to it.
+ for path in paths:
+ raw = _read(path, confine).strip()
+ if raw:
+ return path, raw
+ return None, b""
+
+
+def _label(path: Path) -> str:
+ # Tells the model which file to edit without sending the account's home directory to a cloud provider.
+ home = os.path.abspath(_owner_home())
+ text = os.path.abspath(path)
+ if text == home or text.startswith(home + os.sep):
+ text = "~" + text[len(home) :]
+ return text.replace(os.sep, "/")
+
+
+def _sources(project: Optional[dict]) -> list[tuple[tuple[Path, ...], Optional[Path]]]:
+ # Studio's own file for every account: another tool's ~/.claude or ~/.codex rules would change existing chats.
+ sources = [((workspace_root() / "AGENTS.md",), None)]
+ # Host project folders are single-user only (see tools._get_project_workdir).
+ if (
+ not project
+ or project.get("archived")
+ or not is_owner_context()
+ or not project.get("rootPath")
+ ):
+ return sources
+ root = Path(project["rootPath"])
+ sources.append(((root / "AGENTS.md", root / "CLAUDE.md"), None))
+ # Where the chat's tools run, so the model can keep notes there; after the user's file, which it refines.
+ sandbox_path = project.get("sandboxPath")
+ # Same containment tools._get_project_workdir requires before running anything there.
+ if sandbox_path and os.path.realpath(sandbox_path).startswith(os.path.realpath(root) + os.sep):
+ sandbox = Path(sandbox_path)
+ sources.append(((sandbox / "AGENTS.md", sandbox / "CLAUDE.md"), sandbox))
+ return sources
+
+
+def agents_md_text(project: Optional[dict]) -> str:
+ """Global then project AGENTS.md, each under its source, capped at 32 KiB; "" when there is none."""
+ if not agents_md_enabled():
+ return ""
+ sections = []
+ for candidates, confine in _sources(project):
+ path, raw = _first(candidates, confine)
+ if path is not None:
+ sections.append(f"# Source: {_label(path)}\n\n".encode("utf-8") + raw)
+ if not sections:
+ return ""
+ joined = b"\n\n".join(sections)
+ truncated = len(joined) > MAX_AGENTS_MD_BYTES
+ text = joined[:MAX_AGENTS_MD_BYTES].decode("utf-8", errors = "ignore").rstrip()
+ return text + TRUNCATED_NOTE if truncated else text
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 885256008e7..03765dab8e8 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -327,6 +327,10 @@ class ChatProject(BaseModel):
updatedAt: int
+class ChatAgentsMd(BaseModel):
+ text: str = ""
+
+
class ChatProjectDeleted(ChatProject):
"""The deleted project, plus the member sandboxes that still hold files."""
@@ -1198,6 +1202,15 @@ def get_project(project_id: str, current_subject: str = Depends(get_current_subj
return ChatProject(**project)
[email protected]("/agents-md", response_model = ChatAgentsMd)
+def get_agents_md(
+ project_id: Optional[str] = Query(None), current_subject: str = Depends(get_current_subject)
+):
+ from core.agents_md import agents_md_text
+ project = get_chat_project(project_id) if project_id else None
+ return ChatAgentsMd(text = agents_md_text(project))
+
+
@router.patch("/projects/{project_id}", response_model = ChatProject)
def patch_project(
project_id: str,
diff --git a/studio/backend/tests/test_agents_md.py b/studio/backend/tests/test_agents_md.py
new file mode 100644
index 00000000000..9130e8ec732
--- /dev/null
+++ b/studio/backend/tests/test_agents_md.py
@@ -0,0 +1,156 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import os
+import sys
+
+import pytest
+
+from core import agents_md
+from routes import chat_history
+
+
+def home(tmp_path, monkeypatch):
+ monkeypatch.setattr(agents_md, "_owner_home", lambda: tmp_path / "home")
+ monkeypatch.setattr(agents_md, "workspace_root", lambda: tmp_path / "home/.unsloth/studio")
+ monkeypatch.setattr(agents_md, "is_owner_context", lambda: True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_AGENTS_MD", raising = False)
+ for name in ("home/.agents", "home/.claude", "home/.unsloth/studio", "proj/sandbox", "host"):
+ (tmp_path / name).mkdir(parents = True)
+ return tmp_path
+
+
+def _project(home, **extra):
+ return {
+ "rootPath": str(home / "proj"),
+ "sandboxPath": str(home / "proj/sandbox"),
+ "archived": False,
+ **extra,
+ }
+
+
+def _write(path, text):
+ path.write_text(text, encoding = "utf-8")
+
+
+def test_nothing_on_disk_reads_as_empty(home):
+ assert agents_md.agents_md_text(None) == ""
+ assert agents_md.agents_md_text(_project(home)) == ""
+
+
+def test_global_then_project_then_sandbox_each_under_its_source(home):
+ _write(home / "home/.unsloth/studio/AGENTS.md", "Be brief.\n")
+ _write(home / "proj/AGENTS.md", "Use pnpm.")
+ _write(home / "proj/sandbox/AGENTS.md", "Notes: tests pass.")
+ assert agents_md.agents_md_text(_project(home)) == (
+ "# Source: ~/.unsloth/studio/AGENTS.md\n\nBe brief.\n\n"
+ f"# Source: {(home / 'proj/AGENTS.md').as_posix()}\n\nUse pnpm.\n\n"
+ f"# Source: {(home / 'proj/sandbox/AGENTS.md').as_posix()}\n\nNotes: tests pass."
+ )
+ # A chat outside any project still gets the global file.
+ assert agents_md.agents_md_text(None) == "# Source: ~/.unsloth/studio/AGENTS.md\n\nBe brief."
+
+
+def test_other_tools_global_files_are_not_read(home):
+ _write(home / "home/.agents/AGENTS.md", "agents rules")
+ _write(home / "home/.claude/CLAUDE.md", "claude rules")
+ assert agents_md.agents_md_text(_project(home)) == ""
+
+
+def test_claude_md_only_stands_in_for_a_missing_agents_md(home):
+ _write(home / "proj/CLAUDE.md", "From CLAUDE.md")
+ assert agents_md.agents_md_text(_project(home)).endswith("From CLAUDE.md")
+ _write(home / "proj/AGENTS.md", "From AGENTS.md")
+ text = agents_md.agents_md_text(_project(home))
+ assert text.endswith("From AGENTS.md") and "CLAUDE.md" not in text
+
+
+ sys.platform == "win32", reason = "symlinks need admin or developer mode on Windows"
+)
+def test_project_root_link_reads_but_sandbox_link_does_not(home):
+ _write(home / "proj/AGENTS.md", "Use pnpm.")
+ # CLAUDE.md -> AGENTS.md at the root is common and stays readable.
+ os.symlink(home / "proj/AGENTS.md", home / "proj/CLAUDE.md")
+ (home / "proj/AGENTS.md").unlink()
+ _write(home / "proj/real.md", "Linked rules")
+ os.symlink(home / "proj/real.md", home / "proj/AGENTS.md")
+ assert agents_md.agents_md_text(_project(home)).endswith("Linked rules")
+ # A link the model plants in its sandbox must not pull a host file into the prompt.
+ _write(home / "host/secret.txt", "HOST SECRET")
+ os.symlink(home / "host/secret.txt", home / "proj/sandbox/AGENTS.md")
+ os.symlink(home / "host/secret.txt", home / "proj/sandbox/CLAUDE.md")
+ assert "HOST SECRET" not in agents_md.agents_md_text(_project(home))
+
+
+def test_edits_are_seen_and_size_is_capped(home):
+ target = home / "home/.unsloth/studio/AGENTS.md"
+ _write(target, "first")
+ assert agents_md.agents_md_text(None).endswith("first")
+ _write(target, "second edit")
+ assert agents_md.agents_md_text(None).endswith("second edit")
+ _write(target, "x" * (agents_md.MAX_AGENTS_MD_BYTES * 2))
+ text = agents_md.agents_md_text(None)
+ assert text.endswith(agents_md.TRUNCATED_NOTE)
+ assert len(text) == agents_md.MAX_AGENTS_MD_BYTES + len(agents_md.TRUNCATED_NOTE)
+
+
+def test_managed_account_reads_its_workspace_never_the_host(home, monkeypatch):
+ _write(home / "proj/AGENTS.md", "Host project rules")
+ monkeypatch.setattr(agents_md, "is_owner_context", lambda: False)
+ monkeypatch.setattr(agents_md, "workspace_root", lambda: home / "account")
+ (home / "account").mkdir()
+ assert agents_md.agents_md_text(_project(home)) == ""
+ _write(home / "account/AGENTS.md", "Account rules")
+ text = agents_md.agents_md_text(_project(home))
+ assert text.endswith("Account rules") and "Host" not in text
+
+
+def test_archived_project_and_kill_switch(home, monkeypatch):
+ _write(home / "home/.unsloth/studio/AGENTS.md", "Be brief.")
+ _write(home / "proj/AGENTS.md", "Use pnpm.")
+ assert "pnpm" not in agents_md.agents_md_text(_project(home, archived = True))
+ for off in ("0", "false", "no", "off"):
+ monkeypatch.setenv("UNSLOTH_STUDIO_AGENTS_MD", off)
+ assert agents_md.agents_md_text(_project(home)) == ""
+
+
+def test_route_returns_the_text(home, monkeypatch):
+ _write(home / "proj/AGENTS.md", "Use pnpm.")
+ project = _project(home)
+ monkeypatch.setattr(
+ chat_history, "get_chat_project", lambda pid: project if pid == "p1" else None
+ )
+ assert chat_history.get_agents_md("p1", current_subject = "owner").text.endswith("Use pnpm.")
+ assert chat_history.get_agents_md(None, current_subject = "owner").text == ""
+ assert chat_history.get_agents_md("missing", current_subject = "owner").text == ""
+
+
+def test_sandbox_hard_link_and_fifo_are_not_read(home):
+ root = home / "p"
+ sandbox = root / "sandbox"
+ sandbox.mkdir(parents = True)
+ project = {"rootPath": str(root), "sandboxPath": str(sandbox), "archived": False}
+ secret = home / "secret.txt"
+ secret.write_text("host secret", encoding = "utf-8")
+ os.link(secret, sandbox / "AGENTS.md")
+ assert "host secret" not in agents_md.agents_md_text(project)
+ if hasattr(os, "mkfifo"):
+ (sandbox / "AGENTS.md").unlink()
+ os.mkfifo(sandbox / "AGENTS.md")
+ assert agents_md.agents_md_text(project) == ""
+
+
+ sys.platform == "win32", reason = "symlinks need admin or developer mode on Windows"
+)
+def test_sandbox_outside_the_project_is_not_read(home):
+ # Same layout tools._get_project_workdir refuses: sandbox linked out of the project folder.
+ (home / "host/elsewhere").mkdir()
+ _write(home / "host/elsewhere/AGENTS.md", "outside rules")
+ root = home / "linked"
+ root.mkdir()
+ os.symlink(home / "host/elsewhere", root / "sandbox")
+ project = {"rootPath": str(root), "sandboxPath": str(root / "sandbox"), "archived": False}
+ assert agents_md.agents_md_text(project) == ""
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index f0a417c9ef9..213b611452e 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -380,6 +380,7 @@ import {
generateAudio,
GenerationLengthError,
fetchGgufStagedMetadata,
+ getChatAgentsMd,
getInferenceStatus,
listCachedGguf,
listCachedModels,
@@ -389,6 +390,11 @@ import {
StreamInterruptedError,
validateModel,
} from "./chat-api";
+import {
+ type AgentsMdRecord,
+ composeChatInstructions,
+ EMPTY_AGENTS_MD,
+} from "../utils/agents-md";
import {
createOpenAIContainer,
listOpenAIContainers,
@@ -2171,15 +2177,16 @@ export async function buildLocalTokenCountHistory(
: "",
)
: "";
- const projectInstructions = await resolveProjectInstructions(threadId);
- const combinedSystemPrompt = [
- projectInstructions
- ? `<project_instructions>\n${projectInstructions}\n</project_instructions>`
- : "",
- safeSystemPrompt.trim(),
- ]
- .filter(Boolean)
- .join("\n\n");
+ const projectId = await resolveProjectId(threadId);
+ const [projectInstructions, agentsMd] = await Promise.all([
+ resolveProjectInstructions(projectId),
+ resolveAgentsMd(projectId),
+ ]);
+ const combinedSystemPrompt = composeChatInstructions({
+ agentsMd,
+ projectInstructions,
+ systemPrompt: safeSystemPrompt,
+ });
if (combinedSystemPrompt) {
outboundMessages.unshift({
role: "system",
@@ -2385,11 +2392,7 @@ async function resolveUseAdapter(
}
}
-async function resolveProjectInstructions(
- threadId: string | undefined,
- readThreadRecord?: ThreadRecordReader,
-): Promise<string> {
- const projectId = await resolveProjectId(threadId, readThreadRecord);
+async function resolveProjectInstructions(projectId: string | null): Promise<string> {
if (!projectId) {
return "";
}
@@ -2401,11 +2404,33 @@ async function resolveProjectInstructions(
return project.instructions?.trim() ?? "";
}
+// Background recounts and the send that follows them ask within moments: one read serves both.
+const AGENTS_MD_TTL_MS = 2_000;
+const agentsMdByProject = new Map<
+ string,
+ { at: number; value: Promise<AgentsMdRecord> }
+>();
+
+/** The AGENTS.md text for a request; a failed read sends what it would without the file. */
+function resolveAgentsMd(projectId: string | null): Promise<AgentsMdRecord> {
+ const key = projectId ?? "";
+ const now = Date.now();
+ const hit = agentsMdByProject.get(key);
+ if (hit && now - hit.at < AGENTS_MD_TTL_MS) {
+ return hit.value;
+ }
+ const value = getChatAgentsMd(projectId).catch(() => EMPTY_AGENTS_MD);
+ agentsMdByProject.set(key, { at: now, value });
+ return value;
+}
+
export async function resolveChatInstructions(
threadId: string | undefined,
systemPrompt: unknown,
systemVariables: unknown,
readThreadRecord?: ThreadRecordReader,
+ // Only what goes to the model carries AGENTS.md; copies and exports of a chat keep its own instructions.
+ opts?: { agentsMd?: boolean },
): Promise<string> {
const safeSystemPrompt =
typeof systemPrompt === "string"
@@ -2414,18 +2439,16 @@ export async function resolveChatInstructions(
typeof systemVariables === "string" ? systemVariables : "",
)
: "";
- const projectInstructions = await resolveProjectInstructions(
- threadId,
- readThreadRecord,
- );
- return [
- projectInstructions
- ? `<project_instructions>\n${projectInstructions}\n</project_instructions>`
- : "",
- safeSystemPrompt.trim(),
- ]
- .filter(Boolean)
- .join("\n\n");
+ const projectId = await resolveProjectId(threadId, readThreadRecord);
+ const [projectInstructions, agentsMd] = await Promise.all([
+ resolveProjectInstructions(projectId),
+ opts?.agentsMd ? resolveAgentsMd(projectId) : undefined,
+ ]);
+ return composeChatInstructions({
+ agentsMd,
+ projectInstructions,
+ systemPrompt: safeSystemPrompt,
+ });
}
// Answered once per thread and reused: sandbox, RAG scope and instructions each resolve the
@@ -4755,6 +4778,7 @@ export function createOpenAIStreamAdapter(
params.systemPrompt,
params.systemVariables,
readThreadRecord,
+ { agentsMd: true },
);
if (transitionSignal.aborted) return;
const ragScope =
@@ -5395,6 +5419,7 @@ export function createOpenAIStreamAdapter(
params.systemPrompt,
params.systemVariables,
readThreadRecord,
+ { agentsMd: true },
);
if (combinedSystemPrompt) {
outboundMessages.unshift({
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index c3339f96e9b..735ae3e7bcf 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -24,6 +24,7 @@ import {
type ModelRuntime,
withModelLoadNotice,
} from "@/lib/model-lifecycle-events";
+import type { AgentsMdRecord } from "../utils/agents-md";
import { showLoadWarning } from "../utils/load-warning-toast";
import type {
MessageRecord,
@@ -1140,6 +1141,14 @@ export async function getChatProject(
return parseJsonOrThrow<ProjectRecord>(response);
}
+export async function getChatAgentsMd(
+ projectId: string | null,
+): Promise<AgentsMdRecord> {
+ const query = projectId ? `?project_id=${encodeURIComponent(projectId)}` : "";
+ const response = await authFetch(`/api/chat/agents-md${query}`);
+ return parseJsonOrThrow<AgentsMdRecord>(response);
+}
+
export async function saveChatProject(
project: ProjectRecord,
): Promise<ProjectRecord> {
diff --git a/studio/frontend/src/features/chat/utils/agents-md.ts b/studio/frontend/src/features/chat/utils/agents-md.ts
new file mode 100644
index 00000000000..bc4e4ce0bc4
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/agents-md.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type AgentsMdRecord = { text: string };
+
+export const EMPTY_AGENTS_MD: AgentsMdRecord = { text: "" };
+
+/** System prompt for one request. AGENTS.md first, so project instructions and the typed system prompt
+ * have the last word; with no AGENTS.md this is byte-identical to the prompt before AGENTS.md support. */
+export function composeChatInstructions(parts: {
+ agentsMd?: AgentsMdRecord;
+ projectInstructions: string;
+ systemPrompt: string;
+}): string {
+ const agentsMd = parts.agentsMd?.text.trim() ?? "";
+ return [
+ agentsMd ? `<agents_md>\n${agentsMd}\n</agents_md>` : "",
+ parts.projectInstructions
+ ? `<project_instructions>\n${parts.projectInstructions}\n</project_instructions>`
+ : "",
+ parts.systemPrompt.trim(),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+}
diff --git a/studio/frontend/tests/agents-md-instructions.test.ts b/studio/frontend/tests/agents-md-instructions.test.ts
new file mode 100644
index 00000000000..12d7b7f6a72
--- /dev/null
+++ b/studio/frontend/tests/agents-md-instructions.test.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ EMPTY_AGENTS_MD,
+ composeChatInstructions,
+} from "../src/features/chat/utils/agents-md.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const ADAPTER = readSrc("features/chat/api/chat-adapter.ts");
+const DIALOG = readSrc(
+ "features/chat/prompt-storage/prompt-storage-dialog.tsx",
+);
+
+// The composition before AGENTS.md support, kept verbatim as the oracle for "no file, no change".
+function legacyCompose(
+ projectInstructions: string,
+ systemPrompt: string,
+): string {
+ return [
+ projectInstructions
+ ? `<project_instructions>\n${projectInstructions}\n</project_instructions>`
+ : "",
+ systemPrompt.trim(),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+}
+
+test("without AGENTS.md the system prompt is byte-identical to before", () => {
+ for (const [instructions, prompt] of [
+ ["", ""],
+ ["Use pnpm.", ""],
+ ["", " You are helpful. "],
+ ["Use pnpm.", "You are helpful."],
+ ]) {
+ const expected = legacyCompose(instructions, prompt);
+ for (const agentsMd of [undefined, EMPTY_AGENTS_MD, { text: " \n\t" }]) {
+ assert.equal(
+ composeChatInstructions({
+ agentsMd,
+ projectInstructions: instructions,
+ systemPrompt: prompt,
+ }),
+ expected,
+ );
+ }
+ }
+});
+
+test("one AGENTS.md block comes first, the typed prompt last", () => {
+ const agentsMd = {
+ text: "# Source: ~/.agents/AGENTS.md\n\nBe brief.\n\n# Source: ~/proj/AGENTS.md\n\nUse pnpm.\n",
+ };
+ const text = composeChatInstructions({
+ agentsMd,
+ projectInstructions: "Cite sources.",
+ systemPrompt: "You are helpful.",
+ });
+ assert.equal(
+ text,
+ [
+ `<agents_md>\n${agentsMd.text.trim()}\n</agents_md>`,
+ "<project_instructions>\nCite sources.\n</project_instructions>",
+ "You are helpful.",
+ ].join("\n\n"),
+ );
+ // Idempotent: the same inputs always give the same single block.
+ assert.equal(
+ composeChatInstructions({
+ agentsMd,
+ projectInstructions: "Cite sources.",
+ systemPrompt: "You are helpful.",
+ }),
+ text,
+ );
+ assert.equal(text.split("<agents_md>").length - 1, 1);
+});
+
+test("only requests sent to the model ask for AGENTS.md; copies and exports do not", () => {
+ const calls =
+ ADAPTER.match(/await resolveChatInstructions\([\s\S]*?\);/g) ?? [];
+ assert.equal(calls.length, 2, "chat send and deep research");
+ for (const call of calls) {
+ assert.match(call, /\{ agentsMd: true \}/);
+ }
+ assert.doesNotMatch(DIALOG, /agentsMd/);
+ // The background token recount must measure the prompt the send will use.
+ const recount = ADAPTER.slice(
+ ADAPTER.indexOf("export async function buildLocalTokenCountHistory"),
+ ADAPTER.indexOf("export function buildLocalTokenCountReasoning"),
+ );
+ assert.match(recount, /resolveAgentsMd\(projectId\)/);
+ assert.match(recount, /composeChatInstructions\(/);
+});
diff --git a/studio/frontend/tests/chat-export-system-prompt.test.ts b/studio/frontend/tests/chat-export-system-prompt.test.ts
index 60bc1806ecc..44ade0b9eab 100644
--- a/studio/frontend/tests/chat-export-system-prompt.test.ts
+++ b/studio/frontend/tests/chat-export-system-prompt.test.ts
@@ -33,6 +33,7 @@ import {
ndjsonBody,
} from "../src/features/chat/utils/ndjson.ts";
import { unwrapPastedTextContent } from "../src/features/chat/utils/pasted-text.ts";
+import { composeChatInstructions } from "../src/features/chat/utils/agents-md.ts";
import { readSrc } from "./helpers/kit.ts";
type Exporters = {
@@ -153,6 +154,7 @@ function loadExporters(
getStoredChatThread: async (id: string) =>
THREADS.find((thread) => thread.id === id),
getStoredChatProject: async (id: string) => PROJECTS[id] ?? null,
+ composeChatInstructions,
useChatRuntimeStore: { getState: () => ({ activeProjectId: "openInComposer" }) },
isThreadIncognito: () => false,
settleThreadScopedSettingsForCopy: async () => {},