Skip to content

Latest commit

 

History

History
223 lines (168 loc) · 9.99 KB

File metadata and controls

223 lines (168 loc) · 9.99 KB

API Reference

The amplifier-foundation API is fully documented via Python docstrings and type hints. This overview lists what's exported; for details, read the source files directly.

Why this approach? Documentation that duplicates code becomes context poisoning when it drifts. The code IS the authoritative reference.

Quick Import

from amplifier_foundation import Bundle, BundleRegistry, load_bundle

Core Classes

Export Source Purpose
Bundle bundle.py Composable unit with mount plan config
BundleRegistry registry.py Named bundle management and loading
BundleValidator validator.py Bundle structure validation
ValidationResult validator.py Validation result with errors/warnings
BundleState registry.py Tracked state for loaded bundles
UpdateInfo registry.py Available update information

Convenience Functions

Export Source Purpose
load_bundle registry.py Load bundle from URI
validate_bundle validator.py Validate bundle, return result
validate_bundle_or_raise validator.py Validate bundle, raise on error

Exceptions

Export Source Purpose
BundleError exceptions.py Base exception
BundleNotFoundError exceptions.py Bundle not found
BundleLoadError exceptions.py Bundle load/parse failed
BundleValidationError exceptions.py Validation failed
BundleDependencyError exceptions.py Dependency resolution failed

Protocols

Export Source Purpose
MentionResolverProtocol mentions/protocol.py @mention resolution contract
SourceResolverProtocol sources/protocol.py URI resolution contract
SourceHandlerProtocol sources/protocol.py Source type handler contract
CacheProviderProtocol cache/protocol.py Cache provider contract

Reference Implementations

Export Source Purpose
BaseMentionResolver mentions/resolver.py Default @mention resolver
SimpleSourceResolver sources/resolver.py Git/file source resolver
SimpleCache cache/simple.py In-memory cache
DiskCache cache/disk.py Persistent disk cache

Mentions

Export Source Purpose
parse_mentions mentions/parser.py Extract @mentions from text
load_mentions mentions/loader.py Load @mention content (async)
ContentDeduplicator mentions/deduplicator.py SHA-256 content deduplication
ContextFile mentions/models.py Loaded context file data
MentionResult mentions/models.py @mention resolution result

I/O Utilities

Export Source Purpose
read_yaml io/yaml.py Read YAML file (async)
write_yaml io/yaml.py Write YAML file (async)
parse_frontmatter io/frontmatter.py Parse YAML frontmatter
read_with_retry io/files.py Read with cloud sync retry (async)
write_with_retry io/files.py Write with cloud sync retry (async)

Dict Utilities

Export Source Purpose
deep_merge dicts/merge.py Deep merge dictionaries
merge_module_lists dicts/merge.py Merge module lists by ID
get_nested dicts/navigation.py Get nested dict value by path
set_nested dicts/navigation.py Set nested dict value by path

Path Utilities

Export Source Purpose
parse_uri paths/resolution.py Parse source URI
ParsedURI paths/resolution.py Parsed URI dataclass
normalize_path paths/resolution.py Normalize/resolve path
construct_agent_path paths/construction.py Build agent file path
construct_context_path paths/construction.py Build context file path
find_files paths/discovery.py Find files by pattern (async)
find_bundle_root paths/discovery.py Find bundle root upward (async)

Session Capabilities

Export Source Purpose
get_working_dir session/capabilities.py Get session working directory from coordinator
set_working_dir session/capabilities.py Update session working directory dynamically
WORKING_DIR_CAPABILITY session/capabilities.py Capability name constant ("session.working_dir")

Shared Session State

Portable same-host checkpoints live in session/shared_state.py. They are supported for POSIX local filesystems and coordinate one writer per canonical workspace and session ID.

Export Source Purpose
FileStamp, file_stamp(path) session/shared_state.py Metadata-only checkpoint change detection; never reads JSON.
SharedSessionStore session/shared_state.py Addresses a checkpoint; acquire(app=...) returns the exclusive writer capability.
HeldSession session/shared_state.py Process-bound, non-copyable writer; atomically writes messages, portable bundle reference, and credential-safe metadata. Its live delete_checkpoint() safely removes only the authoritative checkpoint.
SessionBusyError session/shared_state.py Contention error with advisory, bounded owner diagnostics.
SessionTransferFencedError, HeldTransfer session/shared_state.py Durable native-history admission fence and restricted receipt-matched resolution capability; see session transfer fences.

Import these names from amplifier_foundation.session. Store construction, read, stamp, and list_ids never create state directories. acquire alone creates or validates private state directories and the stable session.lock; it rejects symlinked, foreign-owned, or group/world-accessible state paths. release never rewrites the authoritative checkpoint. See SHARED_SESSION_STATE.md for the same-host participant contract, warm-reuse guidance, and safe checkpoint deletion.

Spawn Utilities

Utilities for spawning sub-sessions with provider/model preferences.

Export Source Purpose
ProviderPreference spawn_utils.py Dataclass for provider/model preference (supports glob patterns)
apply_provider_preferences spawn_utils.py Apply ordered preferences to mount plan
resolve_model_pattern spawn_utils.py Resolve glob patterns (e.g., claude-haiku-*) to concrete model names
is_glob_pattern spawn_utils.py Check if model string contains glob characters

Cost Bridge Utilities

Utilities for propagating child-session costs to parent coordinators in app-layer spawn wrappers. Import via from amplifier_foundation import ....

Export Source Purpose
bridge_child_cost bundle/_prepared.py Collect child session's session.cost contributions and register them as a single contributor on the parent coordinator. Never raises — errors are logged as warnings.
sum_cost_usd bundle/_prepared.py Sum a list of collect_contributions() results into a single Decimal | None. Returns None when no cost data is present. Tolerates both Decimal and str values.

Reading the Source

Each source file has comprehensive docstrings. To read them:

# In your editor
code amplifier_foundation/bundle.py

# Or via Python
python -c "from amplifier_foundation import Bundle; help(Bundle)"

# Or via pydoc
python -m pydoc amplifier_foundation.Bundle

Common Patterns

Load and Use a Bundle

from amplifier_foundation import load_bundle

bundle = await load_bundle("git+https://github.com/org/my-bundle@main")
mount_plan = bundle.to_mount_plan()

Compose Bundles

from amplifier_foundation import load_bundle

base = await load_bundle(
    "git+https://github.com/microsoft/amplifier-foundation@main"
    "#subdirectory=bundles/anchors/bundle.md"
)
overlay = await load_bundle("./local-overlay.md")
composed = base.compose(overlay)

Registry Management

from amplifier_foundation import BundleRegistry

registry = BundleRegistry()
registry.register({"my-bundle": "git+https://github.com/org/bundle@main"})
bundle = await registry.load("my-bundle")

Load @Mentions

from amplifier_foundation import load_mentions, BaseMentionResolver

resolver = BaseMentionResolver(bundles={"foundation": foundation_bundle})
results = await load_mentions("See @foundation:context/guidelines.md", resolver)

Local mentions in the initial text use the resolver's base directory, or the explicit relative_to passed to load_mentions. Inside an included file, explicit relative mentions (@./journal.md or @../rules.md) use that file's directory. Bare local mentions such as @AGENTS.md retain the resolver's workspace root; this preserves bundles that intentionally include the current project's rules. Bundle namespaces and explicit home/absolute paths retain their own roots. The resolver is never mutated while loading a nested file. Content is included once, but identical instruction files in different directories still load their own relative references. Missing files remain optional; recursion depth and canonical-path cycle detection bound traversal.

Bundle-declared context: files use the same recursive loading rules. load_mentions_from_file(path, resolver, deduplicator) exposes that path-based entry point without reparsing filenames as mention syntax. This affects context assembly, not ordinary file-tool results or attachments, whose content remains literal.

Custom resolvers keep the existing resolve(mention) contract. To support per-file relative resolution, also implement the optional RelativeMentionResolverProtocol.resolve_relative(mention, relative_to) method. App shortcuts such as @user: and @project: should retain their configured roots. Legacy resolvers without that method continue to resolve exactly as before.