aid-runtime-python 0.1.132__tar.gz → 0.1.134__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/__init__.py +1 -1
  4. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/__init__.py +4 -0
  5. aid_runtime_python-0.1.134/src/aid_runtime/retrieval/connectors.py +528 -0
  6. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/types.py +3 -2
  7. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  8. aid_runtime_python-0.1.134/tests/test_retrieval_connectors.py +434 -0
  9. aid_runtime_python-0.1.132/src/aid_runtime/retrieval/connectors.py +0 -131
  10. aid_runtime_python-0.1.132/tests/test_retrieval_connectors.py +0 -156
  11. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/README.md +0 -0
  12. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/setup.cfg +0 -0
  13. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/__init__.py +0 -0
  14. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/chat_model.py +0 -0
  15. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/deep_agents.py +0 -0
  16. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/engine.py +0 -0
  17. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/guardrails.py +0 -0
  18. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/ir.py +0 -0
  19. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/loop.py +0 -0
  20. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/managed.py +0 -0
  21. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/memory.py +0 -0
  22. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/policy.py +0 -0
  23. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/agents/state.py +0 -0
  24. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/cache.py +0 -0
  25. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/concurrency.py +0 -0
  26. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/control.py +0 -0
  27. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/cost.py +0 -0
  28. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/decisions.py +0 -0
  29. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/errors.py +0 -0
  30. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/__init__.py +0 -0
  31. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/dataset.py +0 -0
  32. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/gate.py +0 -0
  33. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/metrics.py +0 -0
  34. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/predicate.py +0 -0
  35. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/evals/runner.py +0 -0
  36. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/gateway.py +0 -0
  37. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/local_trace.py +0 -0
  38. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/pipeline.py +0 -0
  39. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/prompts.py +0 -0
  40. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/__init__.py +0 -0
  41. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/anthropic.py +0 -0
  42. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/base.py +0 -0
  43. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/bedrock.py +0 -0
  44. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/fake.py +0 -0
  45. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/gemini.py +0 -0
  46. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/gemini_wire.py +0 -0
  47. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/http.py +0 -0
  48. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/providers/vertex.py +0 -0
  49. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/py.typed +0 -0
  50. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/chunking.py +0 -0
  51. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/citations.py +0 -0
  52. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/embedding.py +0 -0
  53. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/filters.py +0 -0
  54. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/gate.py +0 -0
  55. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/hybrid.py +0 -0
  56. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
  57. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/metrics.py +0 -0
  58. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/pgvector.py +0 -0
  59. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/rerank.py +0 -0
  60. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/retriever.py +0 -0
  61. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/retrieval/stores.py +0 -0
  62. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/steps.py +0 -0
  63. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/structured.py +0 -0
  64. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/tools.py +0 -0
  65. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/tracing.py +0 -0
  66. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime/types.py +0 -0
  67. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime_python.egg-info/SOURCES.txt +0 -0
  68. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  69. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  70. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  71. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_agents_budget.py +0 -0
  72. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_agents_deep_agents.py +0 -0
  73. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_agents_hitl.py +0 -0
  74. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_agents_loop.py +0 -0
  75. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_agents_memory.py +0 -0
  76. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_anthropic_provider.py +0 -0
  77. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_bedrock_provider.py +0 -0
  78. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_cache.py +0 -0
  79. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_concurrency.py +0 -0
  80. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_control.py +0 -0
  81. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_cost.py +0 -0
  82. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_dataset.py +0 -0
  83. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_decisions.py +0 -0
  84. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_evals.py +0 -0
  85. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_evals_assert_gate.py +0 -0
  86. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_evals_decision.py +0 -0
  87. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_evals_gate.py +0 -0
  88. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_evals_predicate.py +0 -0
  89. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_gateway.py +0 -0
  90. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_gemini_provider.py +0 -0
  91. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_guardrails.py +0 -0
  92. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_guardrails_managed.py +0 -0
  93. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_guardrails_model_armor.py +0 -0
  94. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_http_provider.py +0 -0
  95. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_local_trace.py +0 -0
  96. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_package.py +0 -0
  97. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_pipeline.py +0 -0
  98. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_prompts.py +0 -0
  99. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_chunking.py +0 -0
  100. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_citations.py +0 -0
  101. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_embedding.py +0 -0
  102. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_filters.py +0 -0
  103. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_gate.py +0 -0
  104. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_hybrid.py +0 -0
  105. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_knowledge_base.py +0 -0
  106. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_metrics.py +0 -0
  107. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_rerank.py +0 -0
  108. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_stores.py +0 -0
  109. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_retrieval_types.py +0 -0
  110. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_steps.py +0 -0
  111. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_streaming.py +0 -0
  112. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_structured.py +0 -0
  113. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_tool_permissions.py +0 -0
  114. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_tools.py +0 -0
  115. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_tracing.py +0 -0
  116. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_types.py +0 -0
  117. {aid_runtime_python-0.1.132 → aid_runtime_python-0.1.134}/tests/test_vertex_provider.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.132
3
+ Version: 0.1.134
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aid-runtime-python"
7
- version = "0.1.132"
7
+ version = "0.1.134"
8
8
  description = "The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -310,7 +310,7 @@ from aid_runtime.types import (
310
310
  )
311
311
 
312
312
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
313
- __version__ = "0.1.132"
313
+ __version__ = "0.1.134"
314
314
 
315
315
  __all__ = [
316
316
  "ANTHROPIC_VERSION",
@@ -41,6 +41,8 @@ from aid_runtime.retrieval.citations import (
41
41
  from aid_runtime.retrieval.connectors import (
42
42
  Connector,
43
43
  FileConnector,
44
+ HttpConnector,
45
+ S3Connector,
44
46
  SourceDocument,
45
47
  open_connector,
46
48
  )
@@ -161,6 +163,7 @@ __all__ = [
161
163
  "FixedChunker",
162
164
  "FixtureKnowledgeBaseClient",
163
165
  "GeminiEmbedder",
166
+ "HttpConnector",
164
167
  "InMemoryVectorStore",
165
168
  "IndexSpec",
166
169
  "IngestReport",
@@ -196,6 +199,7 @@ __all__ = [
196
199
  "Retriever",
197
200
  "RetrieverBinding",
198
201
  "RetrieverSpec",
202
+ "S3Connector",
199
203
  "ScoredChunk",
200
204
  "SearchHit",
201
205
  "SourceDocument",
@@ -0,0 +1,528 @@
1
+ """Reading a ``file``, ``s3`` or ``http`` source.
2
+
3
+ ``file`` indexes a local directory and is implemented at every spec version. ``s3``
4
+ loads an object-store corpus and ``http`` loads exactly one document; both shipped in
5
+ spec 0.21. ``db`` and ``mcp`` are still reserved by the design, so they raise
6
+ :class:`~aid_runtime.errors.FeatureDeferredError` here rather than indexing an empty
7
+ corpus and looking healthy.
8
+
9
+ **Document identity is the POSIX path relative to the source root.** That is the
10
+ vocabulary the IR's retrieval metric already uses -- its ``expectDocs`` hold
11
+ ``getting-started.md``, not ``./docs/getting-started.md`` -- and it is
12
+ machine-independent, so the same corpus indexed on Windows and on Linux yields the
13
+ same ids and the same eval outcome. Absolute paths would make a baseline
14
+ non-portable. The remote connectors keep the same rule: an ``s3`` object's ``doc_id``
15
+ is its key with the source prefix stripped, and an ``http`` document's is the last
16
+ non-empty segment of its path.
17
+
18
+ The protocol is ``async`` because the remote kinds are genuinely concurrent. The file
19
+ connector reads synchronously behind that seam so its behaviour is unchanged.
20
+
21
+ **The s3 signer is the Bedrock adapter's.** ``sigv4_headers`` already computes the
22
+ canonical request, scope and signing key for every other AWS call this runtime makes;
23
+ signing a ``GET`` with it -- ``service="s3"``, ``method="GET"`` and the canonical query
24
+ string -- avoids a second implementation that could disagree about encoding. There is
25
+ deliberately no boto3 dependency: ListObjectsV2 is one signed ``GET`` parsed with the
26
+ standard library's XML reader, and GetObject is another.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import os
33
+ from collections.abc import Callable
34
+ from dataclasses import dataclass
35
+ from datetime import UTC, datetime
36
+ from pathlib import Path
37
+ from typing import Protocol, runtime_checkable
38
+ from urllib.parse import quote, urlparse
39
+ from xml.etree import ElementTree
40
+
41
+ import httpx
42
+ from pydantic import BaseModel, ConfigDict, Field
43
+
44
+ from aid_runtime.errors import ConfigurationError, FeatureDeferredError
45
+ from aid_runtime.providers.bedrock import rfc3986, sigv4_headers
46
+ from aid_runtime.retrieval.types import SourceKind, SourceSpec
47
+
48
+ __all__ = [
49
+ "Connector",
50
+ "FileConnector",
51
+ "HttpConnector",
52
+ "S3Connector",
53
+ "SourceDocument",
54
+ "open_connector",
55
+ ]
56
+
57
+ _RECORD = ConfigDict(frozen=True, extra="forbid")
58
+
59
+ #: The largest body either remote connector will read into one document.
60
+ _MAX_DOCUMENT_BYTES = 10 * 1024 * 1024
61
+
62
+ #: How many GetObject requests an s3 source keeps in flight.
63
+ _S3_CONCURRENCY = 8
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class _ListedObject:
68
+ """One ``ListObjectsV2`` entry, before its body is fetched."""
69
+
70
+ key: str
71
+ etag: str
72
+ last_modified: str
73
+
74
+
75
+ class SourceDocument(BaseModel):
76
+ """One document read from a source, before chunking."""
77
+
78
+ model_config = _RECORD
79
+
80
+ #: POSIX path relative to the source root; the document's identity everywhere.
81
+ doc_id: str = Field(min_length=1)
82
+ #: The absolute resolved location, for a human reading a citation. Never matched on.
83
+ uri: str = Field(min_length=1)
84
+ text: str
85
+ metadata: dict[str, str] = Field(default_factory=dict)
86
+
87
+
88
+ @runtime_checkable
89
+ class Connector(Protocol):
90
+ """A source that yields documents in a deterministic order."""
91
+
92
+ @property
93
+ def kind(self) -> SourceKind: ...
94
+
95
+ async def documents(self) -> tuple[SourceDocument, ...]: ...
96
+
97
+ async def aclose(self) -> None: ...
98
+
99
+
100
+ class FileConnector:
101
+ """Reads ``*.md``-style files under a local directory.
102
+
103
+ Files are read and returned in sorted ``doc_id`` order, never in directory
104
+ order: directory order is a filesystem accident, and a corpus whose chunk ids
105
+ depend on it would reindex itself differently on a different machine.
106
+ """
107
+
108
+ def __init__(self, root: str | Path, *, glob: str | None = None) -> None:
109
+ self._root = Path(root)
110
+ if not self._root.exists():
111
+ raise ConfigurationError(f"source path {str(self._root)!r} does not exist")
112
+ if not self._root.is_dir():
113
+ raise ConfigurationError(f"source path {str(self._root)!r} is not a directory")
114
+ self._glob = glob
115
+
116
+ @property
117
+ def kind(self) -> SourceKind:
118
+ return SourceKind.FILE
119
+
120
+ async def documents(self) -> tuple[SourceDocument, ...]:
121
+ return tuple(self._read(path) for path in self._paths())
122
+
123
+ async def aclose(self) -> None:
124
+ return None
125
+
126
+ def _paths(self) -> tuple[Path, ...]:
127
+ pattern = self._glob or "**/*"
128
+ found = [
129
+ path
130
+ for path in self._root.glob(pattern)
131
+ if path.is_file() and not path.name.startswith(".")
132
+ ]
133
+ return tuple(sorted(found, key=self._doc_id))
134
+
135
+ def _doc_id(self, path: Path) -> str:
136
+ return path.relative_to(self._root).as_posix()
137
+
138
+ def _read(self, path: Path) -> SourceDocument:
139
+ doc_id = self._doc_id(path)
140
+ return SourceDocument(
141
+ doc_id=doc_id,
142
+ uri=str(path.resolve()),
143
+ text=path.read_text(encoding="utf-8"),
144
+ metadata={"path": doc_id, "suffix": path.suffix},
145
+ )
146
+
147
+
148
+ def _tokenize_glob(pattern: str) -> tuple[tuple[str, str], ...]:
149
+ """Split a glob into the same tokens the TypeScript runtime's `compileGlob` uses."""
150
+ tokens: list[tuple[str, str]] = []
151
+ index = 0
152
+ while index < len(pattern):
153
+ char = pattern[index]
154
+ if char == "*":
155
+ if pattern[index + 1 : index + 2] == "*":
156
+ index += 1
157
+ if pattern[index + 1 : index + 2] == "/":
158
+ index += 1
159
+ tokens.append(("globstar_segment", ""))
160
+ else:
161
+ tokens.append(("globstar", ""))
162
+ else:
163
+ tokens.append(("star", ""))
164
+ elif char == "?":
165
+ tokens.append(("any_one", ""))
166
+ else:
167
+ tokens.append(("literal", char))
168
+ index += 1
169
+ return tuple(tokens)
170
+
171
+
172
+ def _glob_matcher(pattern: str | None) -> Callable[[str], bool]:
173
+ """Compile a ``*``/``**``/``?`` glob into a matcher over POSIX relative keys.
174
+
175
+ Deliberately the same token walk as the file connector's documented grammar and the
176
+ TypeScript runtime's ``compileGlob``: ``*`` and ``?`` stop at ``/``, ``**`` crosses
177
+ them, and anything else matches literally. Walking tokens is linear in the key
178
+ length whatever the pattern; a translated regular expression would let a pattern
179
+ with repeated double-stars cost a pathological number of steps to fail.
180
+ """
181
+ if pattern is None:
182
+ return lambda _key: True
183
+ tokens = _tokenize_glob(pattern)
184
+
185
+ def matches(key: str) -> bool:
186
+ reachable = [False] * (len(key) + 1)
187
+ reachable[0] = True
188
+ for kind, char in tokens:
189
+ nxt = [False] * (len(key) + 1)
190
+ if kind == "literal":
191
+ for end in range(1, len(key) + 1):
192
+ nxt[end] = reachable[end - 1] and key[end - 1] == char
193
+ elif kind == "any_one":
194
+ for end in range(1, len(key) + 1):
195
+ nxt[end] = reachable[end - 1] and key[end - 1] != "/"
196
+ elif kind == "star":
197
+ for end in range(len(key) + 1):
198
+ extends = end > 0 and nxt[end - 1] and key[end - 1] != "/"
199
+ nxt[end] = reachable[end] or extends
200
+ elif kind == "globstar":
201
+ for end in range(len(key) + 1):
202
+ extends = end > 0 and nxt[end - 1]
203
+ nxt[end] = reachable[end] or extends
204
+ else: # globstar_segment
205
+ any_before = False
206
+ for end in range(len(key) + 1):
207
+ lands = any_before and end > 0 and key[end - 1] == "/"
208
+ nxt[end] = reachable[end] or lands
209
+ if reachable[end]:
210
+ any_before = True
211
+ reachable = nxt
212
+ return reachable[len(key)]
213
+
214
+ return matches
215
+
216
+
217
+ def _suffix(doc_id: str) -> str:
218
+ """The extension of a document's final path segment, or ``''``."""
219
+ name = doc_id.rsplit("/", 1)[-1]
220
+ dot = name.rfind(".")
221
+ return "" if dot <= 0 else name[dot:]
222
+
223
+
224
+ def _local_name(tag: str) -> str:
225
+ """An element's tag without its XML namespace, so parsing ignores the prefix."""
226
+ return tag.rsplit("}", 1)[-1]
227
+
228
+
229
+ def _s3_environment() -> tuple[dict[str, str], str, str | None]:
230
+ """The credentials, region and optional endpoint an ``s3`` source reads."""
231
+ access_key = os.environ.get("AWS_ACCESS_KEY_ID", "")
232
+ secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY", "")
233
+ if not access_key or not secret_key:
234
+ raise ConfigurationError(
235
+ "an s3 source needs AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the environment"
236
+ )
237
+ region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
238
+ if not region:
239
+ raise ConfigurationError(
240
+ "an s3 source needs a region: set AWS_REGION or AWS_DEFAULT_REGION"
241
+ )
242
+ credentials = {"access_key_id": access_key, "secret_access_key": secret_key}
243
+ token = os.environ.get("AWS_SESSION_TOKEN")
244
+ if token:
245
+ credentials["session_token"] = token
246
+ endpoint = os.environ.get("AWS_ENDPOINT_URL_S3") or os.environ.get("AWS_ENDPOINT_URL")
247
+ return credentials, region, endpoint.rstrip("/") if endpoint else None
248
+
249
+
250
+ def _parse_listing(body: bytes) -> tuple[list[_ListedObject], str | None]:
251
+ """Read one ListObjectsV2 page: its objects and the next continuation token."""
252
+ try:
253
+ # The body is the response to a signed request this process made to its own
254
+ # configured endpoint, not a document supplied by a third party.
255
+ root = ElementTree.fromstring(body) # noqa: S314
256
+ except ElementTree.ParseError as error:
257
+ raise ConfigurationError(
258
+ f"the s3 ListObjectsV2 response is not valid XML: {error}"
259
+ ) from error
260
+ listed: list[_ListedObject] = []
261
+ is_truncated = False
262
+ next_token: str | None = None
263
+ for element in root.iter():
264
+ name = _local_name(element.tag)
265
+ if name == "Contents":
266
+ key = etag = last_modified = ""
267
+ for child in element:
268
+ child_name = _local_name(child.tag)
269
+ if child_name == "Key":
270
+ key = child.text or ""
271
+ elif child_name == "ETag":
272
+ etag = (child.text or "").strip('"')
273
+ elif child_name == "LastModified":
274
+ last_modified = child.text or ""
275
+ if key:
276
+ listed.append(_ListedObject(key=key, etag=etag, last_modified=last_modified))
277
+ elif name == "IsTruncated":
278
+ is_truncated = (element.text or "").strip().lower() == "true"
279
+ elif name == "NextContinuationToken":
280
+ text = (element.text or "").strip()
281
+ next_token = text or None
282
+ return listed, next_token if is_truncated else None
283
+
284
+
285
+ async def _get_bytes(
286
+ client: httpx.AsyncClient,
287
+ url: str,
288
+ headers: dict[str, str],
289
+ *,
290
+ label: str,
291
+ ) -> bytes:
292
+ """One ``GET``, requiring a 2xx and refusing a body over the document limit."""
293
+ async with client.stream("GET", url, headers=headers) as response:
294
+ if not 200 <= response.status_code < 300:
295
+ detail = (await response.aread())[:200].decode("utf-8", "replace").strip()
296
+ suffix = f": {detail}" if detail else ""
297
+ raise ConfigurationError(f"{label} returned HTTP {response.status_code}{suffix}")
298
+ declared = response.headers.get("content-length")
299
+ if declared is not None and declared.isdigit() and int(declared) > _MAX_DOCUMENT_BYTES:
300
+ raise ConfigurationError(
301
+ f"{label} is {declared} bytes, over the {_MAX_DOCUMENT_BYTES}-byte limit"
302
+ )
303
+ chunks: list[bytes] = []
304
+ total = 0
305
+ async for chunk in response.aiter_bytes():
306
+ total += len(chunk)
307
+ if total > _MAX_DOCUMENT_BYTES:
308
+ raise ConfigurationError(
309
+ f"{label} exceeds the {_MAX_DOCUMENT_BYTES}-byte document limit"
310
+ )
311
+ chunks.append(chunk)
312
+ return b"".join(chunks)
313
+
314
+
315
+ class S3Connector:
316
+ """Reads an ``s3://bucket[/prefix]`` corpus, one document per object.
317
+
318
+ An object's ``doc_id`` is its key with the source prefix stripped, so the same
319
+ corpus indexed out of a bucket and out of a directory yields the same ids. Objects
320
+ are fetched concurrently -- bounded, so a bucket with a thousand keys does not open
321
+ a thousand sockets -- and emitted in sorted ``doc_id`` order regardless.
322
+ """
323
+
324
+ def __init__(
325
+ self,
326
+ uri: str,
327
+ *,
328
+ glob: str | None = None,
329
+ transport: httpx.AsyncBaseTransport | None = None,
330
+ timeout: float = 30.0,
331
+ now: Callable[[], datetime] | None = None,
332
+ ) -> None:
333
+ parsed = urlparse(uri)
334
+ if parsed.scheme != "s3" or not parsed.netloc:
335
+ raise ConfigurationError(
336
+ f"s3 source uri {uri!r} must be an absolute 's3://<bucket>[/<prefix>]' uri"
337
+ )
338
+ self._bucket = parsed.netloc
339
+ raw_prefix = parsed.path.lstrip("/")
340
+ # A prefix names a directory: without the trailing slash, ``docs`` would also
341
+ # list ``docs-archive/`` objects that are not under the source at all.
342
+ self._prefix = (
343
+ f"{raw_prefix}/" if raw_prefix and not raw_prefix.endswith("/") else raw_prefix
344
+ )
345
+ self._glob = glob
346
+ self._credentials, self._region, self._endpoint = _s3_environment()
347
+ self._now = now or (lambda: datetime.now(UTC))
348
+ self._client = httpx.AsyncClient(transport=transport, timeout=timeout)
349
+
350
+ @property
351
+ def kind(self) -> SourceKind:
352
+ return SourceKind.S3
353
+
354
+ async def documents(self) -> tuple[SourceDocument, ...]:
355
+ matcher = _glob_matcher(self._glob)
356
+ candidates = [
357
+ (item, self._relative_key(item.key))
358
+ for item in await self._list_objects()
359
+ if not item.key.endswith("/")
360
+ ]
361
+ selected = [(item, doc_id) for item, doc_id in candidates if matcher(doc_id)]
362
+ semaphore = asyncio.Semaphore(_S3_CONCURRENCY)
363
+ documents = await asyncio.gather(
364
+ *(self._fetch_object(item, doc_id, semaphore) for item, doc_id in selected)
365
+ )
366
+ return tuple(sorted(documents, key=lambda document: document.doc_id))
367
+
368
+ async def aclose(self) -> None:
369
+ await self._client.aclose()
370
+
371
+ def _relative_key(self, key: str) -> str:
372
+ if self._prefix and key.startswith(self._prefix):
373
+ return key[len(self._prefix) :].lstrip("/")
374
+ return key.lstrip("/")
375
+
376
+ def _list_request(self, token: str | None) -> tuple[str, str]:
377
+ params = {"list-type": "2"}
378
+ if self._prefix:
379
+ params["prefix"] = self._prefix
380
+ if token is not None:
381
+ params["continuation-token"] = token
382
+ query = "&".join(
383
+ f"{quote(name, safe='-_.~')}={quote(value, safe='-_.~')}"
384
+ for name, value in sorted(params.items())
385
+ )
386
+ if self._endpoint is not None:
387
+ return f"{self._endpoint}/{self._bucket}?{query}", query
388
+ return f"https://{self._bucket}.s3.{self._region}.amazonaws.com/?{query}", query
389
+
390
+ def _object_url(self, key: str) -> str:
391
+ encoded = "/".join(rfc3986(segment) for segment in key.split("/"))
392
+ if self._endpoint is not None:
393
+ return f"{self._endpoint}/{self._bucket}/{encoded}"
394
+ return f"https://{self._bucket}.s3.{self._region}.amazonaws.com/{encoded}"
395
+
396
+ async def _list_objects(self) -> list[_ListedObject]:
397
+ listed: list[_ListedObject] = []
398
+ token: str | None = None
399
+ while True:
400
+ url, query = self._list_request(token)
401
+ headers = sigv4_headers(
402
+ url=url,
403
+ body="",
404
+ region=self._region,
405
+ credentials=self._credentials,
406
+ moment=self._now(),
407
+ service="s3",
408
+ method="GET",
409
+ query=query,
410
+ )
411
+ body = await _get_bytes(self._client, url, headers, label="the s3 listing")
412
+ page, token = _parse_listing(body)
413
+ listed.extend(page)
414
+ if token is None:
415
+ return listed
416
+
417
+ async def _fetch_object(
418
+ self,
419
+ item: _ListedObject,
420
+ doc_id: str,
421
+ semaphore: asyncio.Semaphore,
422
+ ) -> SourceDocument:
423
+ url = self._object_url(item.key)
424
+ async with semaphore:
425
+ headers = sigv4_headers(
426
+ url=url,
427
+ body="",
428
+ region=self._region,
429
+ credentials=self._credentials,
430
+ moment=self._now(),
431
+ service="s3",
432
+ method="GET",
433
+ )
434
+ body = await _get_bytes(self._client, url, headers, label=f"the s3 object {item.key!r}")
435
+ try:
436
+ text = body.decode("utf-8")
437
+ except UnicodeDecodeError as error:
438
+ raise ConfigurationError(
439
+ f"the s3 object {item.key!r} is not valid UTF-8: {error}"
440
+ ) from error
441
+ return SourceDocument(
442
+ doc_id=doc_id,
443
+ uri=f"s3://{self._bucket}/{item.key}",
444
+ text=text,
445
+ metadata={
446
+ "path": doc_id,
447
+ "suffix": _suffix(doc_id),
448
+ "etag": item.etag,
449
+ "lastModified": item.last_modified,
450
+ },
451
+ )
452
+
453
+
454
+ class HttpConnector:
455
+ """Reads exactly one document from an absolute ``http://`` or ``https://`` url.
456
+
457
+ An http source names a document, not a set, which is why it takes no ``glob``: a
458
+ pattern there would describe documents the connector deliberately does not fetch.
459
+ """
460
+
461
+ def __init__(
462
+ self,
463
+ uri: str,
464
+ *,
465
+ glob: str | None = None,
466
+ transport: httpx.AsyncBaseTransport | None = None,
467
+ timeout: float = 30.0,
468
+ ) -> None:
469
+ if glob is not None:
470
+ raise ConfigurationError(
471
+ f"http source {uri!r} takes no 'glob': an http source is exactly one "
472
+ "document, and a pattern describes a set"
473
+ )
474
+ parsed = urlparse(uri)
475
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
476
+ raise ConfigurationError(
477
+ f"http source uri {uri!r} must be an absolute 'http://' or 'https://' url"
478
+ )
479
+ self._uri = uri
480
+ self._segments = [segment for segment in parsed.path.split("/") if segment]
481
+ self._client = httpx.AsyncClient(transport=transport, timeout=timeout)
482
+
483
+ @property
484
+ def kind(self) -> SourceKind:
485
+ return SourceKind.HTTP
486
+
487
+ async def documents(self) -> tuple[SourceDocument, ...]:
488
+ body = await _get_bytes(self._client, self._uri, {}, label=f"the http source {self._uri!r}")
489
+ try:
490
+ text = body.decode("utf-8")
491
+ except UnicodeDecodeError as error:
492
+ raise ConfigurationError(
493
+ f"the http source {self._uri!r} is not valid UTF-8: {error}"
494
+ ) from error
495
+ doc_id = self._segments[-1] if self._segments else "index"
496
+ return (
497
+ SourceDocument(
498
+ doc_id=doc_id,
499
+ uri=self._uri,
500
+ text=text,
501
+ metadata={"path": doc_id, "suffix": _suffix(doc_id)},
502
+ ),
503
+ )
504
+
505
+ async def aclose(self) -> None:
506
+ await self._client.aclose()
507
+
508
+
509
+ def open_connector(spec: SourceSpec, *, base_dir: str | Path | None = None) -> Connector:
510
+ """Open the connector for a source entry.
511
+
512
+ ``base_dir`` resolves a relative ``file`` source ``uri``; it is explicit because the
513
+ runtime has no opinion about a working directory, and a corpus must not depend on
514
+ where a process happened to be started.
515
+ """
516
+ if spec.kind is SourceKind.S3:
517
+ return S3Connector(spec.uri, glob=spec.glob)
518
+ if spec.kind is SourceKind.HTTP:
519
+ return HttpConnector(spec.uri, glob=spec.glob)
520
+ if spec.kind is not SourceKind.FILE:
521
+ raise FeatureDeferredError(
522
+ f"source kind {spec.kind.value!r} is still reserved: the s3 and http loaders "
523
+ "shipped in spec 0.21, and db and mcp remain part of the design but unimplemented"
524
+ )
525
+ root = Path(spec.uri)
526
+ if not root.is_absolute() and base_dir is not None:
527
+ root = Path(base_dir) / root
528
+ return FileConnector(root, glob=spec.glob)
@@ -88,8 +88,9 @@ class DistanceMetric(StrEnum):
88
88
  class SourceKind(StrEnum):
89
89
  """``retriever.source.kind``.
90
90
 
91
- ``FILE`` is the only kind the Phase 1 connector implements; the rest are part
92
- of the IR contract and fail loudly rather than silently indexing nothing.
91
+ ``FILE``, ``S3`` and ``HTTP`` are implemented; ``S3`` and ``HTTP`` shipped in spec
92
+ 0.21. ``DB`` and ``MCP`` are part of the IR contract and fail loudly rather than
93
+ silently indexing nothing.
93
94
  """
94
95
 
95
96
  FILE = "file"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.132
3
+ Version: 0.1.134
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0