API Reference

Core data types, discovery functions, and the search pipeline used by every surface (CLI, TUI, MCP).

Core data

class agentgrep.PrivatePath
class
class
class agentgrep.PrivatePath

Bases: PosixPath

Path subclass that hides the user’s home directory in textual output.

agentgrep.format_display_path(path, *, directory=False)
function
function
agentgrep.format_display_path(path, *, directory=False)

Return a privacy-safe display path.

Parameters:
Return type:

str

class agentgrep.BackendSelection
class
class
class agentgrep.BackendSelection

Bases: object

Selected optional subprocess backends.

class agentgrep.SearchQuery
class
class
class agentgrep.SearchQuery

Bases: object

Compiled search configuration.

compiled carries the parsed-query predicates from agentgrep.query. When None (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_events consults compiled.source_predicate to prune sources before any file is opened, and matches_record() consults compiled.record_predicate after the existing text match. match_surface lets line-oriented callers such as grep require a match in record text while fuzzy search and filtering can keep using the metadata-rich haystack. origin_filter carries explicit CLI/MCP project filters outside the compiled query so plain text searches keep the legacy fast path.

class agentgrep.RecordOrigin
class
class
class agentgrep.RecordOrigin

Bases: object

Project/workspace origin attached to a normalized record.

class agentgrep.SourceHandle
class
class
class agentgrep.SourceHandle

Bases: object

A discovered, parseable source file or SQLite database.

class agentgrep.SearchRecord
class
class
class agentgrep.SearchRecord

Bases: object

Normalized prompt/history record.

class agentgrep.FindRecord
class
class
class agentgrep.FindRecord

Bases: object

Normalized discovery record for agentgrep find.

class agentgrep.ProjectContext
class
class
class agentgrep.ProjectContext

Bases: object

Best-effort description of the invoking project.

agentgrep.detect_project_context(cwd=None)
function
function
agentgrep.detect_project_context(cwd=None)

Detect the current project without spawning subprocesses.

The detector only walks upward from cwd looking for .git. It reads .git/HEAD directly when present, and supports both normal repositories and worktrees whose .git is a gitdir: pointer file.

Parameters:

cwd (Path | None)

Return type:

ProjectContext

Search control and progress

class agentgrep.SearchControl
class
class
class agentgrep.SearchControl

Bases: object

Thread-safe cooperative controls for an active search.

class agentgrep.SearchProgress
class
class
class agentgrep.SearchProgress

Bases: Protocol

Progress reporter used by search internals.

class agentgrep.NoopSearchProgress
class
class
class agentgrep.NoopSearchProgress

Bases: object

Silent search progress reporter.

class agentgrep.ConsoleSearchProgress
class
class
class agentgrep.ConsoleSearchProgress

Bases: object

Human progress reporter for potentially long searches.

class agentgrep.SearchRuntime
class
class
class agentgrep.SearchRuntime

Bases: object

Reusable, explicit runtime state for one search frontend/session.

class agentgrep.SourceScanCache
class
class
class agentgrep.SourceScanCache

Bases: object

Bounded, in-process cache for reusable source-scan results.

class agentgrep.SourceScanCacheStats
class
class
class agentgrep.SourceScanCacheStats

Bases: object

Privacy-safe counters for one source-scan cache.

Event streams

class agentgrep.events.SearchStarted
class
class
class agentgrep.events.SearchStarted

Bases: _BaseEvent

Engine resolved its sources and is about to begin scanning.

Emitted exactly once per agentgrep.iter_search_events() call, immediately after agentgrep.discover_sources() returns and before the first SourceStarted event.

class agentgrep.events.SourceStarted
class
class
class agentgrep.events.SourceStarted

Bases: _BaseEvent

One source has been picked up and is about to be scanned.

index is 1-based; total matches the source_count from the preceding SearchStarted event. adapter_id uniquely identifies the source (e.g. codex.sessions_jsonl.v1); the full path is on the SourceFinished event’s records_seen / matches_seen tally if a consumer wants per-source detail.

class agentgrep.events.RecordEmitted
class
class
class agentgrep.events.RecordEmitted

Bases: _BaseEvent

A unique, included record. The hot-path event consumers care about.

The embedded record is agentgrep’s existing agentgrep.SearchRecord dataclass, not a pydantic copy — consumers (CLI renderer, TUI list) use the record’s attributes directly without a conversion step. Pydantic allows this via arbitrary_types_allowed=True on the model config; the trade-off is that model_dump_json() won’t round-trip these events unmodified, so transport-layer consumers should serialise the record via agentgrep.mcp.models.SearchRecordModel at the boundary.

class agentgrep.events.SourceFinished
class
class
class agentgrep.events.SourceFinished

Bases: _BaseEvent

One source finished scanning. Carries per-source counters.

records_seen is every record the adapter parsed from this source; matches_seen is the subset that matched the query (pre-dedup). The dedup decision happens later in the engine, so a RecordEmitted event may fire for fewer records than matches_seen reports.

class agentgrep.events.SearchFinished
class
class
class agentgrep.events.SearchFinished

Bases: _BaseEvent

Scan complete. Emitted exactly once per stream.

match_count is the total of unique, included records — every RecordEmitted that 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
data
data
agentgrep.events.SearchEvent

Discriminated union of every event agentgrep.iter_search_events() emits.

Tagged on the type literal field. Use isinstance(event, RecordEmitted) to narrow inside a loop; pydantic’s discriminator metadata lets ty / mypy understand 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
class
class agentgrep.events.FindStarted

Bases: _BaseEvent

Engine 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 no SourceStarted / SourceFinished event pair.

class agentgrep.events.FindRecordEmitted
class
class
class agentgrep.events.FindRecordEmitted

Bases: _BaseEvent

One discovered source that survived the filter chain.

The embedded record is agentgrep.FindRecord. Same arbitrary_types_allowed trade-off as RecordEmitted: consumers get the dataclass directly; transport-layer consumers convert via agentgrep.mcp.models.FindRecordModel.

class agentgrep.events.FindFinished
class
class
class agentgrep.events.FindFinished

Bases: _BaseEvent

Enumeration complete. match_count totals the emitted records.

agentgrep.events.FindEvent
data
data
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)
function
function
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 to agentgrep.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). None selects backends via agentgrep.select_backends().

  • control (SearchControl or None) – Optional control handle. The generator polls agentgrep.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)
async function
async function
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 to iter_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')
function
function
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 to agentgrep.discover_sources().

  • agents (tuple[AgentName, ...]) – Agent backends to query.

  • pattern (str or None) – Optional case-insensitive substring filter. When None every 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). None selects via agentgrep.select_backends().

  • compiled (agentgrep.CompiledQuery or None) – Optional CompiledQuery from agentgrep.query.parse_query() + compile_query. When set, its source_predicate prunes sources before they’re emitted as records. The record_predicate is 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)
function
function
agentgrep.query.help.query_language_fields(registry=None)

Return one FieldDoc per registered field, in registry order.

Parameters:

registry (FieldRegistry or None) – Registry to render. Defaults to default_registry().

Returns:

Structured field documentation derived from the registry.

Return type:

tuple[FieldDoc, ...]

agentgrep.query.help.query_language_operators()
function
function
agentgrep.query.help.query_language_operators()

Return the documented query-language operators.

Return type:

tuple[OperatorDoc, ...]

Store catalog

agentgrep.stores.AgentName
data
data
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
data
data
agentgrep.stores.PathKind

alias of Literal[‘history_file’, ‘session_file’, ‘sqlite_db’, ‘store_file’]

agentgrep.stores.SourceKind
data
data
agentgrep.stores.SourceKind

alias of Literal[‘json’, ‘jsonl’, ‘sqlite’, ‘text’, ‘opaque’]

class agentgrep.stores.StoreFormat
class
class
class agentgrep.stores.StoreFormat

Bases: StrEnum

On-disk encoding of a store’s payload.

class agentgrep.stores.StoreRole
class
class
class agentgrep.stores.StoreRole

Bases: StrEnum

Semantic 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
class
class agentgrep.stores.StoreCoverage

Bases: StrEnum

How agentgrep treats a known store at runtime.

DEFAULT_SEARCH stores are opened by normal search and find flows. INSPECTABLE stores are hidden from the default prompt scope but are opt-in searchable: --scope conversations and --scope all open them, and inventory tools list them. CATALOG_ONLY stores are never searched at any scope — inventory tools list them and find enumerates the ones that carry discovery specs, but their payloads are config, logs, caches, or undecodable bytes rather than recall content. PRIVATE stores are documented in the catalogue but intentionally not enumerated from disk.

class agentgrep.stores.VersionDetectionStrategy
class
class
class agentgrep.stores.VersionDetectionStrategy

Bases: StrEnum

How agentgrep detected a concrete source’s app or data version.

class agentgrep.stores.VersionDetectionConfidence
class
class
class agentgrep.stores.VersionDetectionConfidence

Bases: StrEnum

Confidence level for a detected source version.

class agentgrep.stores.DiscoverySpec
class
class
class agentgrep.stores.DiscoverySpec

Bases: BaseModel

Runtime 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) leave StoreDescriptor.discovery as None.

Path resolution

The discover function for an agent resolves a base directory (typically ${HOME}/.<agent> or an env-override). The home_subpath segments are appended to that base. Two enumeration modes are then available, used independently or together:

  • files lists specific relative filenames to check via is_file().

  • glob is a pattern walked under the resolved root via agentgrep.list_files_matching(). path_parts_required and path_parts_excluded filter glob results by path components (e.g., Cursor CLI transcripts must live under agent-transcripts but the primary transcript store excludes nested subagents files).

platform_paths lists absolute paths to check unconditionally, for stores whose canonical location depends on the operating system.

model_config: ClassVar[ConfigDict] = {'frozen': True}
attribute
attribute
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

store: str
attribute
attribute
store: str

Runtime store key (e.g. "claude.projects").

adapter_id: str
attribute
attribute
adapter_id: str

Runtime adapter identifier (e.g. "claude.projects_jsonl.v1").

data_version: str | None
attribute
attribute
data_version: str | None

Known data-shape version for this discovery path, when stable.

path_kind: PathKind
attribute
attribute
path_kind: PathKind

Kind of filesystem entry the records live in.

source_kind: SourceKind
attribute
attribute
source_kind: SourceKind

Parse format (json / jsonl / sqlite).

home_subpath: tuple[str, ...]
attribute
attribute
home_subpath: tuple[str, ...]

Path segments appended to the agent’s resolved base directory.

platform_paths: tuple[str, ...]
attribute
attribute
platform_paths: tuple[str, ...]

Absolute paths to check unconditionally.

root_key: str
attribute
attribute
root_key: str

Named discovery root to resolve this spec against.

files: tuple[str, ...]
attribute
attribute
files: tuple[str, ...]

Specific relative filenames to check via is_file().

glob: str | None
attribute
attribute
glob: str | None

Glob pattern walked under the resolved root.

path_parts_required: tuple[str, ...]
attribute
attribute
path_parts_required: tuple[str, ...]

Each named segment must appear in a glob result’s path.parts.

path_parts_excluded: tuple[str, ...]
attribute
attribute
path_parts_excluded: tuple[str, ...]

A glob result is skipped when any named segment appears in path.parts.

_abc_impl = <_abc._abc_data object>
attribute
attribute
_abc_impl = <_abc._abc_data object>
class agentgrep.stores.StoreDescriptor
class
class
class agentgrep.stores.StoreDescriptor

Bases: BaseModel

One 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_version and observed_at fields 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
class
class agentgrep.stores.StoreCatalog

Bases: BaseModel

Versioned registry of every store agentgrep knows about.

agentgrep.store_catalog.gemini_project_hash(project_root)
function
function
agentgrep.store_catalog.gemini_project_hash(project_root)

Reproduce Gemini CLI’s project-hash derivation.

Mirrors the getProjectHash helper at packages/core/src/utils/paths.ts:187-189 in github.com/google-gemini/gemini-cli (HEAD 927170fc):

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:

str

Examples

>>> gemini_project_hash(pathlib.Path("/example"))
'99d0533064c83d0483dc07145a0aa887cb104311dac8cc2ca57843c6723a5b69'