Files
agent-zero/tests/test_document_query_plugin.py
T
Alessandro Frau d6d9f0507d Register Document Query from its skill
Let loaded skills declare callable schemas and bind them through plugin extensions using normal scoped skill resolution. Use the same binding for native tool declarations, Tool Access, and dispatch.

Move Document Query behind the skill registration and remove both standalone entry points. Preserve saved denials, destination permissions, and the existing indexing, worker, and streaming backend.
2026-11-24 21:49:00 +01:00

898 lines
28 KiB
Python

from __future__ import annotations
import asyncio
import ipaddress
import subprocess
import sys
import threading
from types import SimpleNamespace
from plugins._document_query.helpers.chunks import index_chunks
from pathlib import Path
import pytest
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from helpers import network as network_helper
from plugins._document_query import hooks as document_query_hooks
from plugins._document_query.helpers import ocr_dependencies
from plugins._document_query.helpers.fetch import FetchedDocument, fetch_public_resource
import plugins._document_query.helpers.document_query as document_query_module
from plugins._document_query.helpers.document_query import (
DocumentQueryHelper,
DocumentQueryStore,
)
from plugins._document_query.helpers.parsers.base import BaseParser
from plugins._document_query.helpers.parsers import get_parsers_for_mimetype
from plugins._document_query.helpers.parsers import liteparse as liteparse_module
from plugins._document_query.helpers.parsers import pdf as pdf_module
from plugins._document_query.helpers.parsers import unstructured as unstructured_module
from plugins._document_query.helpers.parsers.liteparse import LiteParseParser
from plugins._document_query.helpers.parsers.pdf import PdfParser
from plugins._document_query.helpers.parsers.text import TextParser
from plugins._document_query.helpers.parsers.unstructured import UnstructuredParser
def run_async(coro):
with asyncio.Runner() as runner:
return runner.run(coro)
class CountingAsyncParser(BaseParser):
mimetypes = ["text/plain"]
active = 0
max_active = 0
async def _parse_async(self, document: FetchedDocument, config: dict) -> str:
type(self).active += 1
type(self).max_active = max(type(self).max_active, type(self).active)
try:
await asyncio.sleep(0.02)
return document.uri
finally:
type(self).active -= 1
def _parse_sync(self, document: FetchedDocument, config: dict) -> str:
return document.uri
class _StoreContext:
def __init__(self, context_id: str):
self.id = context_id
self.data = {}
def get_data(self, key: str, recursive: bool = True):
return self.data.get(key)
def set_data(self, key: str, value, recursive: bool = True):
self.data[key] = value
class _StoreAgent:
def __init__(self, context_id: str):
self.config = object()
self.context = _StoreContext(context_id)
def test_fetch_file_detects_mimetype_and_reads_once(tmp_path):
document = tmp_path / "notes.txt"
document.write_text("hello\nworld\n", encoding="utf-8")
fetched = run_async(fetch_public_resource(str(document), {}))
assert fetched.scheme == "file"
assert fetched.mimetype == "text/plain"
assert fetched.local_path == str(document)
assert fetched.text() == "hello\nworld\n"
def test_fetch_http_blocks_non_public_destinations():
with pytest.raises(ValueError, match="Blocked non-public address"):
run_async(
fetch_public_resource(
"http://127.0.0.1/internal.txt",
{"fetch_retries": 1},
)
)
def test_fetch_http_blocks_redirects_to_non_public_destinations(monkeypatch):
source = "https://public.example/start"
calls = []
class RedirectResponse:
status_code = 302
headers = {"Location": "http://127.0.0.1/internal.txt"}
encoding = None
def __enter__(self):
return self
def __exit__(self, *_args):
return False
class FakeSession:
trust_env = True
def get(self, url, **kwargs):
calls.append((url, kwargs, self.trust_env))
return RedirectResponse()
def resolve_host_ips(hostname):
address = "127.0.0.1" if hostname == "127.0.0.1" else "93.184.216.34"
return (ipaddress.ip_address(address),)
monkeypatch.setattr(network_helper, "resolve_host_ips", resolve_host_ips)
monkeypatch.setattr(network_helper.requests, "Session", FakeSession)
with pytest.raises(ValueError, match="Blocked non-public address"):
run_async(fetch_public_resource(source, {"fetch_retries": 1}))
assert [url for url, _kwargs, _trust_env in calls] == [source]
def test_fetch_http_preserves_public_redirects_and_request_compatibility(monkeypatch):
source = "https://public.example/start"
destination = "https://public.example/report.txt"
calls = []
class FakeResponse:
def __init__(self, status_code, headers, body=b""):
self.status_code = status_code
self.headers = headers
self.encoding = "utf-8"
self.body = body
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def iter_content(self, chunk_size):
assert chunk_size == 64 * 1024
yield self.body
class FakeSession:
trust_env = True
def get(self, url, **kwargs):
calls.append((url, kwargs, self.trust_env))
if url == source:
return FakeResponse(302, {"Location": "/report.txt"})
return FakeResponse(
200,
{
"Content-Length": "9",
"Content-Type": "text/plain; charset=utf-8",
},
b"public ok",
)
monkeypatch.setattr(
network_helper,
"resolve_host_ips",
lambda _hostname: (ipaddress.ip_address("93.184.216.34"),),
)
monkeypatch.setattr(network_helper.requests, "Session", FakeSession)
monkeypatch.setenv("USER_AGENT", "AgentZeroTest")
fetched = run_async(
fetch_public_resource(
source,
{
"fetch_retries": 1,
"fetch_timeout": 2,
"max_remote_bytes": 1024,
},
)
)
assert fetched.uri == destination
assert fetched.mimetype == "text/plain"
assert fetched.text() == "public ok"
assert [url for url, _kwargs, _trust_env in calls] == [source, destination]
assert all(not trust_env for _url, _kwargs, trust_env in calls)
assert all(
kwargs["allow_redirects"] is False
for _url, kwargs, _trust_env in calls
)
assert all(kwargs["timeout"] == (2.0, 2.0) for _url, kwargs, _trust_env in calls)
assert all(
kwargs["headers"] == {"User-Agent": "AgentZeroTest"}
for _url, kwargs, _trust_env in calls
)
def test_parser_registry_prefers_liteparse_for_pdf():
parsers = get_parsers_for_mimetype("application/pdf", {"liteparse_enabled": True})
assert [parser.__class__.__name__ for parser in parsers[:2]] == [
"LiteParseParser",
"PdfParser",
]
def test_parser_registry_can_disable_liteparse():
parsers = get_parsers_for_mimetype("application/pdf", {"liteparse_enabled": False})
assert parsers
assert parsers[0].__class__.__name__ == "PdfParser"
def test_text_parser_uses_prefetched_content():
fetched = FetchedDocument(
uri="/tmp/example.json",
source_uri="/tmp/example.json",
scheme="file",
mimetype="application/json",
content=b'{"ok": true}',
local_path=None,
)
text = run_async(TextParser().parse(fetched, {}, timeout=1))
assert text == '{"ok": true}'
def test_unstructured_parser_uses_local_partitioner(monkeypatch, tmp_path):
document_path = tmp_path / "notes.bin"
document_path.write_bytes(b"opaque")
fetched = FetchedDocument(
uri=str(document_path),
source_uri=str(document_path),
scheme="file",
mimetype="application/octet-stream",
content=b"opaque",
local_path=str(document_path),
)
seen = []
monkeypatch.setattr(
unstructured_module,
"_partition_file",
lambda file_path: seen.append(file_path) or ["first", "second"],
)
assert UnstructuredParser()._parse_sync(fetched, {}) == "first\nsecond"
assert seen == [str(document_path)]
def test_requirements_omit_legacy_langchain_unstructured_wrapper():
root_requirements = (ROOT / "requirements.txt").read_text(encoding="utf-8")
assert "langchain-unstructured" not in root_requirements
def test_outer_image_omits_legacy_ocr_system_packages():
dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")
assert "tesseract-ocr" not in dockerfile
assert "poppler-utils" not in dockerfile
def test_ocr_dependencies_skip_apt_when_already_available(monkeypatch):
monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set())
monkeypatch.setattr(
ocr_dependencies,
"_dependencies_present",
lambda _packages, _commands: True,
)
monkeypatch.setattr(
ocr_dependencies,
"_run_apt_command",
lambda *_args, **_kwargs: pytest.fail("apt must not run"),
)
ocr_dependencies.ensure_pdf_ocr_dependencies()
assert ocr_dependencies._READY_PROFILES == {"pdf_ocr", "tesseract"}
def test_ocr_dependencies_fail_only_at_fallback_without_apt_access(monkeypatch):
monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set())
monkeypatch.setattr(
ocr_dependencies,
"_dependencies_present",
lambda _packages, _commands: False,
)
monkeypatch.setattr(ocr_dependencies, "_apt_command_prefix", lambda: [])
with pytest.raises(RuntimeError, match="Automatic installation requires apt-get"):
ocr_dependencies.ensure_tesseract_dependencies()
def test_pdf_ocr_dependencies_install_once_across_threads(monkeypatch):
monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set())
installed = False
calls = []
def dependencies_present(_packages, _commands):
return installed
def run_apt(command, *, timeout):
nonlocal installed
calls.append((command, timeout))
if "install" in command:
installed = True
return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
monkeypatch.setattr(ocr_dependencies, "_dependencies_present", dependencies_present)
monkeypatch.setattr(
ocr_dependencies,
"_missing_apt_packages",
lambda packages: list(packages),
)
monkeypatch.setattr(
ocr_dependencies,
"_apt_command_prefix",
lambda: ["apt-get"],
)
monkeypatch.setattr(ocr_dependencies, "_run_apt_command", run_apt)
monkeypatch.setattr(ocr_dependencies.logging, "info", lambda _message: None)
threads = [
threading.Thread(target=ocr_dependencies.ensure_pdf_ocr_dependencies)
for _ in range(4)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert calls == [
(["apt-get", "update"], 300),
(
[
"apt-get",
"install",
"-y",
"--no-install-recommends",
"tesseract-ocr",
"tesseract-ocr-script-latn",
"poppler-utils",
],
900,
),
]
assert ocr_dependencies._READY_PROFILES == {"pdf_ocr", "tesseract"}
def test_pdf_full_page_ocr_installs_before_poppler_and_tesseract(monkeypatch):
events = []
pdf2image = pytest.importorskip("pdf2image")
pytesseract = pytest.importorskip("pytesseract")
monkeypatch.setattr(
pdf_module,
"ensure_pdf_ocr_dependencies",
lambda: events.append("install"),
)
monkeypatch.setattr(
pdf2image,
"convert_from_path",
lambda _path: events.append("render") or ["page"],
)
monkeypatch.setattr(
pytesseract,
"image_to_string",
lambda _page: events.append("ocr") or "text",
)
assert PdfParser()._parse_with_ocr("scan.pdf") == "text"
assert events == ["install", "render", "ocr"]
def test_embedded_image_tesseract_install_is_lazy(monkeypatch):
events = []
pytesseract = pytest.importorskip("pytesseract")
monkeypatch.setattr(
pdf_module,
"ensure_tesseract_dependencies",
lambda: events.append("install"),
)
monkeypatch.setattr(
pytesseract,
"image_to_string",
lambda _image, lang: events.append(f"ocr:{lang}") or "embedded text",
)
import io
pixels = io.BytesIO()
Image.new("RGB", (2, 2)).save(pixels, format="PNG")
assert events == []
assert pdf_module._image_text(pixels.getvalue()) == "embedded text"
assert events == ["install", "ocr:eng"]
def test_unstructured_installs_ocr_packages_only_for_pdf_and_images(monkeypatch):
events = []
monkeypatch.setattr(
unstructured_module,
"ensure_tesseract_dependencies",
lambda: events.append("tesseract"),
)
monkeypatch.setattr(
unstructured_module,
"ensure_pdf_ocr_dependencies",
lambda: events.append("pdf"),
)
unstructured_module._ensure_ocr_dependencies("text/plain", "notes.txt")
unstructured_module._ensure_ocr_dependencies("image/png", "scan.png")
unstructured_module._ensure_ocr_dependencies("application/pdf", "scan.pdf")
assert events == ["tesseract", "pdf"]
def test_compatibility_helper_import_points_to_plugin():
pytest.importorskip("langchain_core")
from helpers.document_query import DocumentQueryHelper as CompatHelper
from plugins._document_query.helpers.document_query import DocumentQueryHelper
assert CompatHelper is DocumentQueryHelper
def test_liteparse_is_installed_only_in_the_guest():
assert 'liteparse==' not in (ROOT / 'requirements.txt').read_text()
assert 'liteparse==2.21.1' in (ROOT / 'plugins/_document_query/sandbox/requirements.txt').read_text()
assert document_query_hooks.install() is True
def test_default_config_bounds_liteparse_runtime_concurrency():
default_config = (
ROOT / "plugins" / "_document_query" / "default_config.yaml"
).read_text(encoding="utf-8")
assert "parser_concurrency: 1" in default_config
assert "context_intro_chunks: 2" in default_config
assert "max_index_chunks: 1200" in default_config
assert "liteparse_num_workers: 2" in default_config
assert "liteparse_ocr_auto_disable_pages: 30" in default_config
assert "liteparse_subprocess" not in default_config
def test_config_panel_exposes_document_query_settings():
config_html = (
ROOT / "plugins" / "_document_query" / "webui" / "config.html"
).read_text(encoding="utf-8")
assert "Max parser concurrency" in config_html
for setting in [
"parser_concurrency",
"per_document_timeout",
"gather_timeout",
"chunk_size",
"chunk_overlap",
"max_index_chunks",
"search_threshold",
"search_limit",
"context_intro_chunks",
"fetch_timeout",
"fetch_retries",
"fetch_retry_backoff",
"max_remote_bytes",
"liteparse_enabled",
"liteparse_ocr_enabled",
"liteparse_ocr_language",
"liteparse_ocr_server_url",
"liteparse_tessdata_path",
"liteparse_max_pages",
"liteparse_target_pages",
"liteparse_dpi",
"liteparse_preserve_very_small_text",
"liteparse_output_format",
"liteparse_num_workers",
"pdf_ocr_fallback",
"thread_offload",
]:
assert f"config.{setting}" in config_html
assert "liteparse_subprocess" not in config_html
def test_document_query_adapts_chunk_size_for_large_documents():
config = {
"chunk_size": 100,
"chunk_overlap": 10,
"max_index_chunks": 10,
}
chunks = index_chunks(("alpha beta gamma delta " * 400).strip(), config)
assert 1 < len(chunks) <= 10
def test_document_query_allows_uncapped_index_chunks():
config = {
"chunk_size": 100,
"chunk_overlap": 10,
"max_index_chunks": 0,
}
chunks = index_chunks(("alpha beta gamma delta " * 400).strip(), config)
assert len(chunks) > 10
def test_document_query_store_reuses_vector_db_per_context(monkeypatch):
from plugins._sandboxing.helpers.storage import prepare_workspace
monkeypatch.setattr('plugins._document_query.helpers.sandbox.worker.prepare_directory', prepare_workspace)
monkeypatch.setattr(
document_query_module,
"_load_config",
lambda _agent: {
"chunk_size": 100,
"chunk_overlap": 10,
"max_index_chunks": 20,
},
)
from plugins._document_query.sandbox.index import handle
async def call(request, *, mounts):
return handle(request, mounts[0].source)
async def vectors(chunks):
return [[1., 0.] for _ in chunks]
async def query(text):
return [1., 0.]
monkeypatch.setattr(document_query_module.worker, "acall", call)
monkeypatch.setattr(_StoreAgent, "get_embedding_model", lambda self: SimpleNamespace(
aembed_documents=vectors, aembed_query=query), raising=False)
agent = _StoreAgent("ctx-one")
store = DocumentQueryStore.get(agent)
success, ids = run_async(
store.add_document("alpha beta gamma " * 20, "/tmp/book.txt")
)
second_store = DocumentQueryStore.get(agent)
assert success is True
assert ids
assert second_store is store
hits = run_async(store.search_document("/tmp/book.txt", "alpha"))
assert {doc.metadata["id"] for doc in hits} == set(ids)
assert run_async(store.search_document("/tmp/other.txt", "alpha")) == []
assert run_async(store.add_document("", "/tmp/book.txt")) == (False, [])
assert run_async(store.search_document("/tmp/book.txt", "alpha")) == hits
assert run_async(second_store.document_exists("/tmp/book.txt")) is True
isolated_store = DocumentQueryStore.get(_StoreAgent("ctx-two"))
assert isolated_store is not store
assert run_async(isolated_store.document_exists("/tmp/book.txt")) is False
def test_document_query_thumbnail_matches_plugin_hub_limits():
thumbnail = ROOT / "plugins" / "_document_query" / "webui" / "thumbnail.jpg"
assert thumbnail.exists()
assert thumbnail.stat().st_size <= 20 * 1024
with Image.open(thumbnail) as image:
assert image.format == "JPEG"
assert image.size == (256, 256)
def test_liteparse_parser_caps_workers_by_default():
parser = LiteParseParser()
assert parser._liteparse_kwargs({})["num_workers"] == 2
assert parser._liteparse_kwargs({"liteparse_num_workers": "3"})["num_workers"] == 3
assert parser._liteparse_kwargs({"liteparse_num_workers": ""})["num_workers"] == 2
def test_liteparse_parser_always_uses_subprocess(monkeypatch):
fetched = FetchedDocument(
uri="/tmp/report.pdf",
source_uri="/tmp/report.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/report.pdf",
)
parser = LiteParseParser()
monkeypatch.setattr(parser, "_parse_subprocess", lambda _document, _config: "ok")
def fail_in_process(_document, _config):
raise AssertionError("LiteParse must stay isolated from the Web UI process")
monkeypatch.setattr(parser, "_parse_in_process", fail_in_process)
assert parser._parse_sync(fetched, {"liteparse_subprocess": False}) == "ok"
@pytest.mark.parametrize("symlink_plugin", [False, True])
def test_liteparse_subprocess_uses_package_root(tmp_path, monkeypatch, symlink_plugin):
fetched = FetchedDocument(
uri="/tmp/report.pdf",
source_uri="/tmp/report.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/report.pdf",
)
parser = LiteParseParser()
calls = []
project_root = tmp_path / "app"
plugin = project_root / "plugins" / "_document_query"
plugin.parent.mkdir(parents=True)
if symlink_plugin:
mounted_plugin = tmp_path / "plugin"
mounted_plugin.mkdir()
plugin.symlink_to(mounted_plugin, target_is_directory=True)
else:
plugin.mkdir()
monkeypatch.setattr(liteparse_module, "__file__", str(plugin / "helpers/parsers/liteparse.py"))
monkeypatch.delenv("PYTHONPATH", raising=False)
def fake_run(command, **kwargs):
calls.append((command, kwargs))
return subprocess.CompletedProcess(command, 0, stdout='{"text": "ok"}', stderr="")
monkeypatch.setattr(liteparse_module.subprocess, "run", fake_run)
monkeypatch.setattr(parser, "_liteparse_kwargs", lambda *_args: {})
assert parser._parse_subprocess(fetched, {}) == "ok"
assert calls[0][0] == [
sys.executable,
"-m",
"plugins._document_query.helpers.parsers.liteparse_worker",
]
assert calls[0][1]["cwd"] == str(project_root)
assert calls[0][1]["env"]["PYTHONPATH"] == str(project_root)
def test_liteparse_auto_disables_ocr_for_large_text_pdf(monkeypatch):
parser = LiteParseParser()
fetched = FetchedDocument(
uri="/tmp/report.pdf",
source_uri="/tmp/report.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/report.pdf",
)
monkeypatch.setattr(
liteparse_module,
"_pdf_text_profile",
lambda _file_path, _config: liteparse_module._PdfTextProfile(
page_count=277,
sampled_pages=5,
text_chars=2500,
),
)
kwargs = parser._liteparse_kwargs({}, fetched, "/tmp/report.pdf")
assert kwargs["ocr_enabled"] is False
def test_liteparse_keeps_ocr_for_small_pdf(monkeypatch):
parser = LiteParseParser()
fetched = FetchedDocument(
uri="/tmp/bill.pdf",
source_uri="/tmp/bill.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/bill.pdf",
)
monkeypatch.setattr(
liteparse_module,
"_pdf_text_profile",
lambda _file_path, _config: liteparse_module._PdfTextProfile(
page_count=10,
sampled_pages=5,
text_chars=2500,
),
)
kwargs = parser._liteparse_kwargs({}, fetched, "/tmp/bill.pdf")
assert kwargs["ocr_enabled"] is True
def test_liteparse_disables_ocr_for_large_text_sparse_pdf(monkeypatch):
parser = LiteParseParser()
fetched = FetchedDocument(
uri="/tmp/scan.pdf",
source_uri="/tmp/scan.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/scan.pdf",
)
monkeypatch.setattr(
liteparse_module,
"_pdf_text_profile",
lambda _file_path, _config: liteparse_module._PdfTextProfile(
page_count=277,
sampled_pages=5,
text_chars=20,
),
)
kwargs = parser._liteparse_kwargs({}, fetched, "/tmp/scan.pdf")
assert kwargs["ocr_enabled"] is False
def test_liteparse_respects_explicit_ocr_disabled(monkeypatch):
parser = LiteParseParser()
fetched = FetchedDocument(
uri="/tmp/bill.pdf",
source_uri="/tmp/bill.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/bill.pdf",
)
monkeypatch.setattr(
liteparse_module,
"_pdf_text_profile",
lambda _file_path, _config: liteparse_module._PdfTextProfile(
page_count=10,
sampled_pages=5,
text_chars=0,
),
)
kwargs = parser._liteparse_kwargs(
{"liteparse_ocr_enabled": False},
fetched,
"/tmp/bill.pdf",
)
assert kwargs["ocr_enabled"] is False
def test_liteparse_target_pages_can_keep_ocr_enabled_for_large_pdf(monkeypatch):
parser = LiteParseParser()
fetched = FetchedDocument(
uri="/tmp/report.pdf",
source_uri="/tmp/report.pdf",
scheme="file",
mimetype="application/pdf",
content=b"",
local_path="/tmp/report.pdf",
)
monkeypatch.setattr(
liteparse_module,
"_pdf_text_profile",
lambda _file_path, _config: liteparse_module._PdfTextProfile(
page_count=277,
sampled_pages=5,
text_chars=2500,
),
)
small_range = parser._liteparse_kwargs(
{"liteparse_target_pages": "1-10"},
fetched,
"/tmp/report.pdf",
)
large_range = parser._liteparse_kwargs(
{"liteparse_target_pages": "1-40"},
fetched,
"/tmp/report.pdf",
)
assert small_range["ocr_enabled"] is True
assert large_range["ocr_enabled"] is False
def test_query_optimize_prompt_filename_is_spelled_correctly():
prompt_dir = ROOT / "plugins" / "_document_query" / "prompts"
helper_source = (
ROOT / "plugins" / "_document_query" / "helpers" / "document_query.py"
).read_text(encoding="utf-8")
assert (prompt_dir / "fw.document_query.optimize_query.md").exists()
assert "fw.document_query.optimize_query.md" in helper_source
def test_parser_progress_is_user_facing_and_generic(monkeypatch):
from plugins._document_query.helpers.sandbox import worker
async def parse(payload, **kwargs):
assert payload['mimetype'] == 'text/plain'
return 'parsed'
monkeypatch.setattr(worker, 'acall', parse)
fetched = FetchedDocument(
uri="/tmp/example.txt",
source_uri="/tmp/example.txt",
scheme="file",
mimetype="text/plain",
content=b"content",
local_path=None,
)
progress = []
helper = object.__new__(DocumentQueryHelper)
helper.config = {}
helper.store = SimpleNamespace(settings=lambda: ({}, []))
helper.progress_callback = progress.append
content = run_async(
helper._parse_document(
document=fetched,
timeout=1,
)
)
assert content == "parsed"
assert progress == ["Parsing document content in sandbox"]
def test_parse_document_limits_parser_concurrency_across_helpers(monkeypatch):
from plugins._document_query.helpers.sandbox import worker
async def parse(payload, **kwargs):
document = FetchedDocument(uri=payload['uri'], scheme='file', mimetype='text/plain', content=b'')
return await CountingAsyncParser()._parse_async(document, {})
monkeypatch.setattr(worker, 'acall', parse)
CountingAsyncParser.active = 0
CountingAsyncParser.max_active = 0
fetched_a = FetchedDocument(
uri="/tmp/a.txt",
source_uri="/tmp/a.txt",
scheme="file",
mimetype="text/plain",
content=b"a",
local_path=None,
)
fetched_b = FetchedDocument(
uri="/tmp/b.txt",
source_uri="/tmp/b.txt",
scheme="file",
mimetype="text/plain",
content=b"b",
local_path=None,
)
helper_a = object.__new__(DocumentQueryHelper)
helper_a.config = {"parser_concurrency": 1}
helper_a.progress_callback = lambda _msg: None
helper_b = object.__new__(DocumentQueryHelper)
helper_b.config = {"parser_concurrency": 1}
helper_a.store = helper_b.store = SimpleNamespace(settings=lambda: ({}, []))
helper_b.progress_callback = lambda _msg: None
async def parse_both():
return await asyncio.gather(
helper_a._parse_document(
document=fetched_a,
timeout=1,
),
helper_b._parse_document(
document=fetched_b,
timeout=1,
),
)
assert sorted(run_async(parse_both())) == ["/tmp/a.txt", "/tmp/b.txt"]
assert CountingAsyncParser.max_active == 1
def test_document_query_prompt_uses_progressive_skill_disclosure():
from helpers.skills import find_skill
main_prompt = (ROOT / "prompts" / "agent.system.main.tips.md").read_text(
encoding="utf-8"
)
skill = find_skill("document-query", include_content=True)
assert skill is not None
assert "document_query" not in main_prompt
assert "vision_load" not in main_prompt
assert skill.metadata["tool"]["name"] == "document_query"
assert not (ROOT / "tools/document_query.py").exists()
assert not (ROOT / "plugins/_document_query/tools/document_query.py").exists()
assert not (ROOT / "plugins/_document_query/prompts/agent.system.tool.document_query.md").exists()
assert "`destination`" in skill.content
assert "OCR when vision fails" in skill.description
assert "PDFs" in skill.description
assert "### Answer Questions Over A Document" in skill.content
assert "Use vision tools first" in skill.content
assert "### Fallback OCR After Vision Cannot Read A Document Image" in skill.content