API Reference¶
Core data types, discovery functions, and the search pipeline used by every surface (CLI, TUI, MCP).
Core data¶
-
class agentgrep.PrivatePath¶class agentgrep.PrivatePath¶
Bases:
PosixPathPath subclass that hides the user’s home directory in textual output.
-
agentgrep.format_display_path(path, *, directory=False)¶agentgrep.format_display_path(path, *, directory=False)¶
Return a privacy-safe display path.
-
class agentgrep.BackendSelection¶class agentgrep.BackendSelection¶
Bases:
objectSelected optional subprocess backends.
-
class agentgrep.SearchQuery¶class agentgrep.SearchQuery¶
Bases:
objectCompiled search configuration.
compiledcarries the parsed-query predicates fromagentgrep.query. WhenNone(the default), the engine takes its legacy code path — pure-text queries and flag-only invocations stay on the fast path with no extra evaluation cost. When set,iter_search_eventsconsultscompiled.source_predicateto prune sources before any file is opened, andmatches_record()consultscompiled.record_predicateafter the existing text match.match_surfacelets line-oriented callers such asgreprequire a match in record text while fuzzy search and filtering can keep using the metadata-rich haystack.origin_filtercarries explicit CLI/MCP project filters outside the compiled query so plain text searches keep the legacy fast path.
-
class agentgrep.RecordOrigin¶class agentgrep.RecordOrigin¶
Bases:
objectProject/workspace origin attached to a normalized record.
-
class agentgrep.SourceHandle¶class agentgrep.SourceHandle¶
Bases:
objectA discovered, parseable source file or SQLite database.
-
class agentgrep.SearchRecord¶class agentgrep.SearchRecord¶
Bases:
objectNormalized prompt/history record.
-
class agentgrep.FindRecord¶class agentgrep.FindRecord¶
Bases:
objectNormalized discovery record for
agentgrep find.
-
class agentgrep.ProjectContext¶class agentgrep.ProjectContext¶
Bases:
objectBest-effort description of the invoking project.
-
agentgrep.detect_project_context(cwd=None)¶agentgrep.detect_project_context(cwd=None)¶
Detect the current project without spawning subprocesses.
The detector only walks upward from
cwdlooking for.git. It reads.git/HEADdirectly when present, and supports both normal repositories and worktrees whose.gitis agitdir:pointer file.- Parameters:
- Return type:
Search control and progress¶
-
class agentgrep.SearchControl¶class agentgrep.SearchControl¶
Bases:
objectThread-safe cooperative controls for an active search.
-
class agentgrep.SearchProgress¶class agentgrep.SearchProgress¶
Bases:
ProtocolProgress reporter used by search internals.
-
class agentgrep.NoopSearchProgress¶class agentgrep.NoopSearchProgress¶
Bases:
objectSilent search progress reporter.
-
class agentgrep.ConsoleSearchProgress¶class agentgrep.ConsoleSearchProgress¶
Bases:
objectHuman progress reporter for potentially long searches.
-
class agentgrep.SearchRuntime¶class agentgrep.SearchRuntime¶
Bases:
objectReusable, explicit runtime state for one search frontend/session.
Event streams¶
-
class agentgrep.events.SearchStarted¶class agentgrep.events.SearchStarted¶
Bases:
_BaseEventEngine resolved its sources and is about to begin scanning.
Emitted exactly once per
agentgrep.iter_search_events()call, immediately afteragentgrep.discover_sources()returns and before the firstSourceStartedevent.
-
class agentgrep.events.SourceStarted¶class agentgrep.events.SourceStarted¶
Bases:
_BaseEventOne source has been picked up and is about to be scanned.
indexis 1-based;totalmatches thesource_countfrom the precedingSearchStartedevent.adapter_iduniquely identifies the source (e.g.codex.sessions_jsonl.v1); the full path is on theSourceFinishedevent’srecords_seen/matches_seentally if a consumer wants per-source detail.
-
class agentgrep.events.RecordEmitted¶class agentgrep.events.RecordEmitted¶
Bases:
_BaseEventA unique, included record. The hot-path event consumers care about.
The embedded
recordis agentgrep’s existingagentgrep.SearchRecorddataclass, not a pydantic copy — consumers (CLI renderer, TUI list) use the record’s attributes directly without a conversion step. Pydantic allows this viaarbitrary_types_allowed=Trueon the model config; the trade-off is thatmodel_dump_json()won’t round-trip these events unmodified, so transport-layer consumers should serialise the record viaagentgrep.mcp.models.SearchRecordModelat the boundary.
-
class agentgrep.events.SourceFinished¶class agentgrep.events.SourceFinished¶
Bases:
_BaseEventOne source finished scanning. Carries per-source counters.
records_seenis every record the adapter parsed from this source;matches_seenis the subset that matched the query (pre-dedup). The dedup decision happens later in the engine, so aRecordEmittedevent may fire for fewer records thanmatches_seenreports.
-
class agentgrep.events.SearchFinished¶class agentgrep.events.SearchFinished¶
Bases:
_BaseEventScan complete. Emitted exactly once per stream.
match_countis the total of unique, included records — everyRecordEmittedthat fired earlier counts once. Always the last event in a stream that ran to completion. A stream that raised an exception mid-scan will skip this event.
-
agentgrep.events.SearchEvent¶agentgrep.events.SearchEvent¶
Discriminated union of every event
agentgrep.iter_search_events()emits.Tagged on the
typeliteral field. Useisinstance(event, RecordEmitted)to narrow inside a loop; pydantic’s discriminator metadata letsty/mypyunderstand the narrowing without extra annotations.alias of
Annotated[SearchStarted|SourceStarted|RecordEmitted|SourceFinished|SearchFinished, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]
-
class agentgrep.events.FindStarted¶class agentgrep.events.FindStarted¶
Bases:
_BaseEventEngine resolved sources and is about to begin enumerating.
Emitted exactly once per
agentgrep.iter_find_events()call. Unlike search, find has no per-source scan loop, so there is noSourceStarted/SourceFinishedevent pair.
-
class agentgrep.events.FindRecordEmitted¶class agentgrep.events.FindRecordEmitted¶
Bases:
_BaseEventOne discovered source that survived the filter chain.
The embedded
recordisagentgrep.FindRecord. Samearbitrary_types_allowedtrade-off asRecordEmitted: consumers get the dataclass directly; transport-layer consumers convert viaagentgrep.mcp.models.FindRecordModel.
-
class agentgrep.events.FindFinished¶class agentgrep.events.FindFinished¶
Bases:
_BaseEventEnumeration complete.
match_counttotals the emitted records.
-
agentgrep.events.FindEvent¶agentgrep.events.FindEvent¶
Discriminated union of every event
agentgrep.iter_find_events()emits.alias of
Annotated[FindStarted|FindRecordEmitted|FindFinished, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]
-
agentgrep.iter_search_events(home, query, *, backends=None, control=None, runtime=None)¶agentgrep.iter_search_events(home, query, *, backends=None, control=None, runtime=None)¶
Yield typed events as the search engine scans sources.
- Parameters:
home (
pathlib.Path) – User home directory passed through toagentgrep.discover_sources().query (
SearchQuery) – Compiled query — terms, agents, dedup choice, limit.backends (
BackendSelection or None) – Override the auto-detected backend selection (mainly used by tests).Noneselects backends viaagentgrep.select_backends().control (
SearchControl or None) – Optional control handle. The generator pollsagentgrep.SearchControl.answer_now_requested()between records so consumers can break the scan early.runtime (
agentgrep.SearchRuntime or None) – Optional reusable runtime state; supplies the source-scan cache when one is configured.
- Yields:
_events.SearchEvent – Discriminated-union events. See module docstring for the guaranteed sequence.
- Return type:
Iterator[SearchEvent]
Examples
Stream events, collecting matching records:
for event in iter_search_events(pathlib.Path.home(), query): if isinstance(event, _events.RecordEmitted): print(event.record.text)
-
agentgrep.aiter_search_events(home, query, *, backends=None, control=None, runtime=None, max_queue_size=32)¶agentgrep.aiter_search_events(home, query, *, backends=None, control=None, runtime=None, max_queue_size=32)¶
Yield search events from a worker thread through an async queue.
Closing the returned generator — via
contextlib.aclosing(), or by any exception that unwinds through it — requests cancellation and stops the worker. Consumers that may leave the stream partially consumed must close it explicitly rather than relying on the event loop’s async-generator finalization hook.- Parameters:
home (
pathlib.Path) – User home directory passed through toiter_search_events().query (
SearchQuery) – Compiled query — terms, agents, dedupe choice, limit.backends (
BackendSelection or None) – Optional backend override, mostly used by tests.control (
SearchControl or None) – Optional cooperative cancellation handle.runtime (
agentgrep.SearchRuntime or None) – Optional reusable runtime state; supplies the source-scan cache when one is configured.max_queue_size (
int) – Bounded async queue size used to apply consumer backpressure.
- Yields:
_events.SearchEvent – The same event sequence produced by
iter_search_events().- Return type:
AsyncGenerator[SearchEvent]
-
agentgrep.iter_find_events(home, agents, *, pattern, limit, backends=None, compiled=None, type_filter='all')¶agentgrep.iter_find_events(home, agents, *, pattern, limit, backends=None, compiled=None, type_filter='all')¶
Yield typed events as the find engine enumerates sources.
- Parameters:
home (
pathlib.Path) – User home directory passed through toagentgrep.discover_sources().agents (
tuple[AgentName, ...]) – Agent backends to query.pattern (
str or None) – Optional case-insensitive substring filter. WhenNoneevery discovered source qualifies.limit (
int or None) – Optional cap on the number of records emitted.backends (
BackendSelection or None) – Override the auto-detected backend selection (mainly used by tests).Noneselects viaagentgrep.select_backends().compiled (
agentgrep.CompiledQuery or None) – OptionalCompiledQueryfromagentgrep.query.parse_query()+compile_query. When set, itssource_predicateprunes sources before they’re emitted as records. Therecord_predicateis not honored — find emits one record per source by construction, and the per-record query semantics only make sense for the search pipeline.type_filter (
{“prompts”, “history”, “sessions”, “all”}, default “all”) – Coarse source type filter used to prune catalogue roles before discovery. CLI renderers still apply their exact fd-shaped path-kind filter after records are emitted.
- Yields:
_events.FindEvent – Discriminated-union events. See module docstring for the guaranteed sequence.
- Return type:
Iterator[FindEvent]
Examples
Iterate events, collecting only the records:
for event in iter_find_events(home, ("codex",), pattern="sessions", limit=None): if isinstance(event, _events.FindRecordEmitted): print(event.record.path)
Query language helpers¶
Registry-driven query-language documentation.
Single source of truth for the query-language help shown in MCP tool
descriptions, the agentgrep://query-language resource, and the MCP
server instructions. Field docs derive from
agentgrep.query.default_registry() so they cannot drift from what
the compiler actually accepts. Operator docs live here because the
operator grammar is owned by the parser, not the registry.
The CLI --help example blocks deliberately use literal strings (see
agentgrep) rather than this renderer so the root help path stays
cold-start cheap; this module is consumed by the MCP layer, which is not
cold-start sensitive.
-
agentgrep.query.help.query_language_fields(registry=None)¶agentgrep.query.help.query_language_fields(registry=None)¶
Return one
FieldDocper registered field, in registry order.- Parameters:
registry (
FieldRegistry or None) – Registry to render. Defaults todefault_registry().- Returns:
Structured field documentation derived from the registry.
- Return type:
tuple[FieldDoc, ...]
Discovery and search¶
-
agentgrep.select_backends()¶agentgrep.select_backends()¶
Return the best available subprocess helpers.
- Return type:
-
agentgrep.discover_sources(home, agents, backends, *, include_non_default=False, version_detail='shape', store_roles=None)¶agentgrep.discover_sources(home, agents, backends, *, include_non_default=False, version_detail='shape', store_roles=None)¶
Discover all known parseable sources for the selected agents.
version_detailcontrols how eagerly source handles are enriched:"none"leavesversion_detectionempty for fast search paths,"catalog"attaches low-cost catalog observations, and"shape"inspects concrete source shape for inventory surfaces.store_roleslets latency-sensitive search paths enumerate only the catalogue roles that can satisfy a coarse query scope.- Parameters:
home (
Path)agents (
tuple[AgentName, ...])backends (
BackendSelection)include_non_default (
bool)version_detail (
DiscoveryVersionDetail)store_roles (
DiscoveryStoreRoles)
- Return type:
-
agentgrep.run_search_query(home, query, *, backends=None, progress=None, control=None, runtime=None)¶agentgrep.run_search_query(home, query, *, backends=None, progress=None, control=None, runtime=None)¶
Discover sources and run a normalized search query.
- Parameters:
home (
Path)query (
SearchQuery)backends (
BackendSelection|None)progress (
SearchProgress|None)control (
SearchControl|None)runtime (
SearchRuntime|None)
- Return type:
-
agentgrep.search_sources(query, sources, backends, *, progress=None, control=None, runtime=None)¶agentgrep.search_sources(query, sources, backends, *, progress=None, control=None, runtime=None)¶
Parse and filter search results across all selected sources.
- Parameters:
query (
SearchQuery)sources (
list[SourceHandle])backends (
BackendSelection)progress (
SearchProgress|None)control (
SearchControl|None)runtime (
SearchRuntime|None)
- Return type:
-
agentgrep.run_find_query(home, agents, *, pattern, limit, backends=None)¶agentgrep.run_find_query(home, agents, *, pattern, limit, backends=None)¶
Discover sources and build normalized
findresults.- Parameters:
- Return type:
Store catalog¶
-
agentgrep.stores.AgentName¶agentgrep.stores.AgentName¶
alias of
Literal[‘claude’, ‘cursor-cli’, ‘cursor-ide’, ‘codex’, ‘gemini’, ‘antigravity-cli’, ‘antigravity-ide’, ‘grok’, ‘pi’, ‘opencode’, ‘windsurf’, ‘vscode’]
-
agentgrep.stores.PathKind¶agentgrep.stores.PathKind¶
alias of
Literal[‘history_file’, ‘session_file’, ‘sqlite_db’, ‘store_file’]
-
agentgrep.stores.SourceKind¶agentgrep.stores.SourceKind¶
alias of
Literal[‘json’, ‘jsonl’, ‘sqlite’, ‘text’, ‘opaque’]
-
class agentgrep.stores.StoreFormat¶class agentgrep.stores.StoreFormat¶
Bases:
StrEnumOn-disk encoding of a store’s payload.
-
class agentgrep.stores.StoreRole¶class agentgrep.stores.StoreRole¶
Bases:
StrEnumSemantic role a store plays for the owning agent.
The role drives the default search policy decisions downstream adapters make — chat transcripts are usually searched, app-state and cache stores are usually not. The role itself is descriptive; the policy decision is captured separately on each
StoreDescriptor.
-
class agentgrep.stores.StoreCoverage¶class agentgrep.stores.StoreCoverage¶
Bases:
StrEnumHow agentgrep treats a known store at runtime.
DEFAULT_SEARCHstores are opened by normal search and find flows.INSPECTABLEstores are hidden from the default prompt scope but are opt-in searchable:--scope conversationsand--scope allopen them, and inventory tools list them.CATALOG_ONLYstores are never searched at any scope — inventory tools list them andfindenumerates the ones that carry discovery specs, but their payloads are config, logs, caches, or undecodable bytes rather than recall content.PRIVATEstores are documented in the catalogue but intentionally not enumerated from disk.
-
class agentgrep.stores.VersionDetectionStrategy¶class agentgrep.stores.VersionDetectionStrategy¶
Bases:
StrEnumHow agentgrep detected a concrete source’s app or data version.
-
class agentgrep.stores.VersionDetectionConfidence¶class agentgrep.stores.VersionDetectionConfidence¶
Bases:
StrEnumConfidence level for a detected source version.
-
class agentgrep.stores.DiscoverySpec¶class agentgrep.stores.DiscoverySpec¶
Bases:
BaseModelRuntime metadata for discovering one store’s source files.
Catalogue rows whose store agentgrep actually scans at runtime carry a
DiscoverySpec. Rows that are documentary (planned support, opaque formats, source trees) leaveStoreDescriptor.discoveryasNone.Path resolution¶
The discover function for an agent resolves a base directory (typically
${HOME}/.<agent>or an env-override). Thehome_subpathsegments are appended to that base. Two enumeration modes are then available, used independently or together:fileslists specific relative filenames to check viais_file().globis a pattern walked under the resolved root viaagentgrep.list_files_matching().path_parts_requiredandpath_parts_excludedfilter glob results by path components (e.g., Cursor CLI transcripts must live underagent-transcriptsbut the primary transcript store excludes nestedsubagentsfiles).
platform_pathslists absolute paths to check unconditionally, for stores whose canonical location depends on the operating system.-
model_config: ClassVar[ConfigDict] = {'frozen': True}¶model_config: ClassVar[ConfigDict] = {'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Runtime store key (e.g.
"claude.projects").
Runtime adapter identifier (e.g.
"claude.projects_jsonl.v1").
Known data-shape version for this discovery path, when stable.
Path segments appended to the agent’s resolved base directory.
Absolute paths to check unconditionally.
Named discovery root to resolve this spec against.
Specific relative filenames to check via
is_file().
Glob pattern walked under the resolved root.
Each named segment must appear in a glob result’s
path.parts.
A glob result is skipped when any named segment appears in
path.parts.
-
class agentgrep.stores.StoreDescriptor¶class agentgrep.stores.StoreDescriptor¶
Bases:
BaseModelOne on-disk storage location for one CLI agent.
Each descriptor is a snapshot of how the store looked when an agentgrep contributor observed it. The
observed_versionandobserved_atfields stamp that snapshot so future readers know whether a description is current or stale.Path patterns use
${HOME}and${<ENV>}tokens so the catalogue stays portable. Resolving a pattern against a concrete environment is the consumer’s job — adapters typically expand the tokens themselves.
-
class agentgrep.stores.StoreCatalog¶class agentgrep.stores.StoreCatalog¶
Bases:
BaseModelVersioned registry of every store agentgrep knows about.
-
agentgrep.store_catalog.gemini_project_hash(project_root)¶agentgrep.store_catalog.gemini_project_hash(project_root)¶
Reproduce Gemini CLI’s project-hash derivation.
Mirrors the
getProjectHashhelper atpackages/core/src/utils/paths.ts:187-189ingithub.com/google-gemini/gemini-cli(HEAD927170fc):export function getProjectHash(projectRoot: string): string { return crypto.createHash('sha256').update(projectRoot).digest('hex'); }
- Parameters:
project_root (
pathlib.Path) – Absolute project root path.- Returns:
Lower-case hex SHA-256 of the absolute path string.
- Return type:
Examples
>>> gemini_project_hash(pathlib.Path("/example")) '99d0533064c83d0483dc07145a0aa887cb104311dac8cc2ca57843c6723a5b69'