Skip to content

Latest commit

 

History

History
1181 lines (917 loc) · 59.9 KB

third_party_plugin_development.md

File metadata and controls

1181 lines (917 loc) · 59.9 KB

Third-Party Plugin Development Specification

Audience: External developers building plugins for LeapFlow.
Authoritative source: Derived from production code at src/leapflow/plugins/ (contracts, registry, lifecycle, sandbox, marketplace), src/leapflow/tools/ (tool behaviour), src/leapflow/domain/, src/leapflow/learning/, and src/leapflow/gateway/.


1. Overview & Philosophy

LeapFlow treats everything as a plugin. The agent's capabilities — tool execution, LLM access, platform adapters, signal ingestion, computer vision, and frame storage — are all governed by typing.Protocol contracts with @runtime_checkable. Third-party code extends LeapFlow by satisfying one of these Protocols and registering with the appropriate registry.

1.0 Where the plugin subsystem lives

leapflow.plugins is a first-class package and the only owner of plugin contracts, discovery, lifecycle, isolation, and distribution:

src/leapflow/plugins/
├── __init__.py         # public API: get_registry / get_scoped_registry / reload_plugin
├── protocol.py         # ToolPlugin Protocol + ToolMetadata (SSOT per tool)
├── registry.py         # ToolPluginRegistry — discovery, DI, assembly, runtime gates
├── scoped_registry.py  # ScopedToolRegistry — PluginFiber lifecycle, hot-reload
├── tool_plugins/       # built-in ToolPlugin declarations (the only layer that
│                       # imports tool implementations)
├── sandbox/            # subprocess isolation for untrusted plugins
└── marketplace/        # manifest, client, HTTP source, prototype server

leapflow.tools holds what tools do (file ops, shell, terminal, web, SCM, config, gateway dispatch) plus the Tool Capability Contract in tools/name_resolver.py. The dependency direction is one-way and enforced by tests/test_architecture_contracts.py: plugin core never imports a tool module; tool_plugins/ is the single place allowed to wrap one.

1.1 Extension Protocols

Protocol Module Purpose
ToolPlugin plugins/protocol.py Register callable tools exposed to the LLM agent
GatewayAdapterPlugin gateway/adapter_registry.py Factory for IM/platform adapters (Feishu, Telegram, etc.)
LLMProviderPlugin llm/provider_registry.py Register alternative LLM backends
SelectionPolicyPlugin plugins/selection_policy.py Decide which admissible tool candidate to use, and learn from the result
SignalSource perception/signal_source.py Stateless event → signal transform
ActiveSignalSource perception/active_signal_source.py Long-running signal emitter (webhook listener, polling bot)
CVProcessor perception/cv_processor.py Frame-pair visual diff processing
HardwareContextProvider hardware/providers/__init__.py Discover physical devices and declare their channels
HardwareTransport hardware/transport.py Execute reads/writes against one device (six methods)
FrameTransport hardware/transport.py Optional side protocol: a device that produces frames

Additionally, FrameStore (perception/storage/frame_store.py) is a @runtime_checkable Protocol for pluggable frame persistence backends.

Node skills may implement PreparedPlanningSkill (hardware/skills/planning.py) to prepare immutable jobs for bounded parallel evaluation. Two optional, runtime-checkable extensions keep domain decisions in the plugin: PlanningAlternativesSkill.alternatives offers bounded task-equivalent programs after an infeasible single request; PlanConfirmationSkill.confirm performs read-only live checks before a selected plan is sealed. PlanningSettings.auto_variants defaults to true; no alternative executes without the normal approval, permit, freshness, and lease gates. ScenePort.grasps returns live sibling proposals, while relocate(commit=False) measures without refreshing object, grasp, or observation memory.

When to use each:

  • ToolPlugin — You want the LLM agent to invoke your functionality as a tool call (most common).
  • GatewayAdapterPlugin — You are integrating a new IM/collaboration platform.
  • LLMProviderPlugin — You are adding a new LLM API backend (e.g., a private deployment).
  • SelectionPolicyPlugin — You are implementing a strategy for choosing between tools that provide the same capability (greedy, Thompson sampling, UCB). Your policy sees only candidates that already passed every hard constraint, and must be able to explain each choice.
  • SignalSource — You need to normalize external events into LeapFlow's signal pipeline (stateless, transform-only).
  • ActiveSignalSource — You need a long-running listener that emits signals (websocket, polling loop).
  • CVProcessor — You are implementing a visual diff algorithm for the perception subsystem.
  • HardwareContextProvider / HardwareTransport — You are adding a peripheral. Both have their own entry-point groups (leapflow.hardware.providers, leapflow.hardware.transports), so pip install is enough. See hardware_peripherals_board.md for the full contract, including how a declared channel becomes a LeapBoard preview or control with no board code, and hardware_init_calibration.md for declaring readiness preconditions.

2. Interface Specification

2.1 ToolPlugin Protocol

from typing import Any, Protocol, runtime_checkable

@runtime_checkable
class ToolPlugin(Protocol):
    @property
    def plugin_id(self) -> str: ...

    @property
    def category(self) -> str: ...

    @property
    def tools(self) -> list[ToolMetadata]: ...

    @property
    def dependencies(self) -> list[str]: ...

    def bind_runtime(self, **deps: Any) -> None: ...
Attribute Description
plugin_id Globally unique string (e.g., "weather_lookup"). Used for registry keys, trust tracking, fiber IDs.
category Category label for PCD grouping (e.g., "general", "system", "integration"). Must match x_leapflow.category on tools.
tools List of ToolMetadata instances — the single source of truth for tool schemas, handlers, and metadata.
dependencies List of runtime dependency names this plugin requires (e.g., ["memory_manager", "file_read_gate"]).
bind_runtime Receives injected dependencies matching the dependencies list. Ignore unknown kwargs.

2.2 ToolMetadata

from dataclasses import dataclass, field
from typing import Any, Callable

@dataclass(frozen=True)
class ToolMetadata:
    name: str
    description: str
    parameters_schema: dict[str, Any]   # OpenAI JSON Schema format
    handler: Callable[..., Any]
    x_leapflow: dict[str, Any] = field(default_factory=dict)
    mutates_state: bool = False
    execution_policy: str = ""

    def to_openai_schema(self) -> dict[str, Any]:
        """Generate OpenAI function-calling schema dict."""
        ...

to_openai_schema() output shape:

{
  "type": "function",
  "function": {
    "name": "tool_name",
    "description": "What the tool does",
    "parameters": { "type": "object", "properties": {...}, "required": [...] },
    "x_leapflow": {
      "category": "integration",
      "mutates_state": true,
      "risk_level": "medium",
      "execution_policy": "mutating_once"
    }
  }
}

When mutates_state=True, to_openai_schema() folds it into x_leapflow.mutates_state. A non-empty execution_policy is folded into x_leapflow.execution_policy as well, so schema-only consumers use the same declared execution semantics as the runtime.

x_leapflow well-known keys:

x_leapflow is required for every generated ToolMetadata and must be a dict. category and risk_level are mandatory; the validator rejects None, missing category/risk, malformed schemas, non-callable handlers, and mutating tools that omit approval/idempotency metadata.

Key Type Purpose
category str PCD disclosure grouping
disclosure str "bootstrap" or "on_demand"; omitted values default to "on_demand", independently of risk or schema cost
risk_level str "read_only" / "low" / "medium" / "high"
schema_cost str "low" / "medium" / "high" — token cost hint for PCD
requires_approval bool Whether the engine gates this tool behind approval
mutates_state bool Auto-populated from the field when True
execution_policy str read_only, mutating_idempotent, mutating_once, or external_side_effect; undeclared policies fail safe as external

A published handler is discoverable, not automatically callable. With agent.admission_policy=demand_driven (default), fresh turns expose self_describe, tool_search, tool_describe, capability_expand, and policy-required emergency controls. Known names go directly to tool_describe(tool_name="..."); its activate_tools names are resolved against the owning frame's catalog/handler snapshot, never arbitrary schema bodies. Independent descriptions may be batched; category expansion remains available for broad work. Native and text-fallback dispatch both refuse unloaded tools with recoverable capability_unavailable feedback and an exact discovery route. Activation grants no approval, trust, or side-effect exemption. Explicitly invoked SKILL.md dependencies or a validated current-turn plan may preload exact tools. Earlier turns preload nothing by category: only the exact tools the same session already called stay disclosed, so a follow-up call needs no discovery round trip while a sibling tool of that category still does. The legacy rollout value rolls back disclosure behavior only, not turn ownership, canonical finalization, or scope isolation.

2.3 GatewayAdapterPlugin Protocol

@dataclass(frozen=True)
class PlatformCapabilities:
    """Typed declaration of what a platform adapter natively supports."""
    supports_streaming: bool = False
    supports_rich_text: bool = False
    supports_images: bool = False
    supports_files: bool = False
    supports_reactions: bool = False
    supports_threads: bool = False
    supports_group_chat: bool = False
    supports_edit: bool = False
    supports_async_delivery: bool = True
    splits_long_messages: bool = False
    max_message_length: int = 4000

@runtime_checkable
class PlatformAdapter(Protocol):
    @property
    def platform_id(self) -> str: ...
    @property
    def capabilities(self) -> PlatformCapabilities: ...
    # Legacy class-level flags retained for structural compatibility:
    supports_async_delivery: bool
    splits_long_messages: bool
    max_message_length: int
    ...

@runtime_checkable
class GatewayAdapterPlugin(Protocol):
    @property
    def platform_id(self) -> str: ...

    @property
    def display_name(self) -> str: ...

    @property
    def adapter_class_path(self) -> str: ...  # "module.path:ClassName"

    @property
    def config_schema(self) -> Dict[str, Any]: ...

    def create_adapter(self, config: Dict[str, Any]) -> PlatformAdapter: ...

PlatformAdapterMixin provides a default capabilities property that builds from the three legacy class-level flags. Adapters that natively support additional features (images, threading, editing, …) override the property.

2.4 LLMProviderPlugin Protocol

@runtime_checkable
class LLMProviderPlugin(Protocol):
    @property
    def provider_id(self) -> str: ...

    @property
    def display_name(self) -> str: ...

    @property
    def supported_models(self) -> List[str]: ...

    @property
    def capabilities(self) -> Dict[str, Any]: ...
    # Keys: supports_streaming, supports_tools, supports_vision,
    #        supports_thinking, max_context_length, credential_rotation

    def create_provider(self, config: Dict[str, Any]) -> LLMProvider: ...

LLM provider plugins support entry_point discovery via setuptools group "leapflow.llm_providers".

Primary inference accounting is caller-scoped. Providers can use ProviderAttempt from llm/services/telemetry.py around each actual request attempt, sharing one logical call ID across retries. Observe usage before extracting domain payloads; return LLMChatResponse.inference_call_id intact through response wrappers so the engine can deduplicate response-level accounting. Streaming recorders must not hold ContextVar tokens across yields. Accounting sinks and optional usage extraction must never change provider retry/failure behavior.

Opaque providers remain supported: the owning LearningBridge records a call_boundary with unknown inner retry count. Combined usage reports observed attempts as a lower bound, call_boundaries, and attempt_count_complete=False; missing token usage stays unknown. Specialist services use runtime-owned accounting and suppress nested primary-provider records. Receipts contain no prompts or images, are admitted privately through the typed signal boundary, and remain bound to the owning profile/workspace/session. Neither usage nor advice grants physical authority.

Structured model services

A supported specialist uses a profile-only llm.services declaration and the existing model_describe / model_query tools, not a new provider or tool per model. See the onboarding example. OpenAI-compatible Chat Completions and Anthropic Messages are reused; serving-engine names do not determine client routing. Native processor/head execution and decoding belong on the serving side.

The existing configuration plugin also exposes config_model_service before any specialist is configured. Per-ID show/set/enable/disable/unset/check reuse ConfigService; validation precedes ApprovalOrchestrator.evaluate(runtime.configure), with the active ToolExecutionContext's session/turn and ID/key-only metadata. Durable writes reread under a cross-process lock; approval waits never hold the lock. File and inline text fixtures share staged validation. Runtime publication uses the existing profile-owner reload and per-turn catalog invalidation. The declaration's enabled is strictly boolean, defaulting to true when omitted. Toggle transactions merge only that field, preserving concurrent endpoint/budget/secret-ref edits. Disabled declarations remain discoverable; acquisition refuses before secret/provider/artifact access. Disabling or removing an ID irreversibly revokes prior handles, including late results; re-enabling creates fresh admission. Ordinary enabled edits preserve generation pinning. Durable save and effective runtime publication are separate outcomes; external processes reload through their existing entry points, not an additional watcher. Do not change the primary model or reroute a denied save through shell/file tools.

The extension contracts are runtime_checkable Protocols in llm/services/protocol.py:

Contract Responsibility
StructuredModelClient Cached describe, generation-pinned acquire, owned aclose
ServiceHandle Immutable spec, generation, contract, codec_revision, bounded invoke(request, schema, validate=...), aclose
ServiceCodec Provider-native messages/options from encode; strict structured result from decode
TaskContract (llm/services/contracts.py) Domain schemas, semantic validation, evidence references, revision, description, and read-only/governed-actuation classification
ModelBackend (hardware/model_contract.py) Owned open/close/describe/infer binding behind existing model_service

Camera retention is composed through SessionEvidenceSink in hardware/snapshot_evidence.py, injected as hardware_evidence_sink into the hardware plugin. EvidenceReference and EvidenceFailure are frozen values; EvidenceError is mutable. Only the fresh passive snapshot's explicit export_evidence option invokes this sink. No model-supplied path, owner, base64, or URL is accepted as an artifact authority.

RecordSignalPort, RecordNoiseGate, RecordScope, and RecordAdmission in domain/events.py define private RECORD admission. The production EventBus uses its normalizer/privacy boundary, noise gate, dedup, and redaction, returning a scoped receipt without global memory, subscriber delivery, or agent activation. Metadata only crosses that boundary. Bytes are validated and retained by the cache only after separate retention approval; refusal and no-op statuses remain visible to the hardware caller. hardware.snapshot_evidence bounds TTL/quota/media/cleanup and is read per export; frame-sharing switch changes still require restart. The Context owns the sink's EffectScope and closes it in both runtime modes. Cancellation suppresses references and schedules cleanup for disk work that cannot be preempted.

ServiceSpec, ServiceLimits, and StructuredResult are immutable. Expected refusals use mutable ServiceError carrying a frozen ServiceFailure; tool adapters convert them into the existing typed failure/recovery boundary. Never execute generated tool calls.

LLMProviderRegistry.create_isolated(provider_id, config) bypasses the primary provider cache. A specialist-capable provider must accept the supplied bounded HTTP client and provider-wrapper max_retries=1 (one attempt), disable SDK retries (max_retries=0), and implement AsyncCloseableProvider.aclose; unsupported capabilities refuse. The service runtime owns retries, total work deadline, byte/decompression limits, concurrency, queue admission, and cleanup. Default limits are 5 seconds, one attempt, one in-flight request, no queue, 8 MiB request, 2 MiB response, and 1,024 output tokens. Approval waits do not consume inference work time. Calls are nonstreaming.

A plugin declares model_services, settings, model_approval_gate, and effect_scope in dependencies and accepts them through bind_runtime, without capturing global settings or opening clients at import time. Use the existing wrapper in plugins/tool_plugins/model_services.py as a reference: domain behavior lives in tools/model_tools.py; publication and cleanup belong to the plugin wrapper. Acquire a handle for one consumer and release it in finally; register longer-lived cleanup with effect_scope.async_effect(...). Register a codec using ModelServiceRuntime.register_codec(name, codec) and attach its returned undo callback to the registering plugin's scope. Register a domain contract with ModelServiceRuntime.register_contract(contract) and attach its returned undo in the same way. TaskContract.schemas() returns object input/output schemas; validate_input(request) and validate_result(request, result) enforce domain semantics; evidence_references(request) maps labels to caller-owned session cache IDs. The contract declares task, revision, description, and classification (read_only or governed_actuation). Built-in advisory contracts are domain-owned by world_model, geometry/actuation contracts by hardware, and composed with EffectScope cleanup. A new text contract can arrive through an ordinary dependency-bound plugin; new physical/tensor semantics still need qualified adapters.

Task and codec names are structurally parsed at configuration bootstrap; composed CLI/chat/runtime admission resolves the registered provider, codec, and contract. Unknown contracts are unavailable, never implicitly advisory. Removing/replacing a provider, codec, or contract invalidates calls and late results. Contract registration identity and codec revision are pinned even when the same implementation is re-registered.

json.v1 supports json_text, OpenAI-compatible json_schema, and tool_call output; duplicate keys, excessive nesting, truncation, malformed results, and schema violations refuse. Strict OpenAI wire schemas require closed, explicitly typed objects. Optional domain fields compile to required nullable wire fields, and only optional nulls normalize back to absence before domain validation. Open/unrepresentable strict schemas refuse before HTTP; choose json_text or an admitted codec explicitly, with no silent downgrade. Anthropic seed is refused at admission; portable stop strings/lists become native stop_sequences. Images are shaped for the chosen provider. Unknown eligible candidate IDs refuse; predictions remain hypothetical and evaluations remain teacher assessments. Scores are uncalibrated unless separately qualified. action_chunk cannot execute via model_query.

Artifact IDs resolve only within the caller's profile/workspace/session. Evidence must be sensitive, nonsyncable, checksum-bound, TTL-limited, and inside the owned session cache. File consent and network disclosure use ApprovalOrchestrator.evaluate; missing gates fail closed, and ownership/TTL/checksum are rechecked around consent and reads. Do not substitute paths, URLs, inline images, or a second approval interface. Localhost alone is not processing-locality evidence; unknown locality refuses sensitive media/evidence.

For hardware, retain kind: model_service and explicitly choose backend: provider with service: <ID> and an existing model task. Bind model_transport_factories at the owning CLI/LHP registry; do not mutate process-global factories for one endpoint. The serving adapter must implement the leapflow.model.v1.1 describe/infer envelope, supply actual native metadata, and insert checkpoint/instance identity outside generation. Managed qualification binds checkpoint, native metadata, effective service declaration, adapter, endpoint, locality, expiry, and operator approval. A YAML identity or successful fixture check is not qualification. Existing HCP/LHP skill consent, adaptation, SafetyShield, permits, leases, and controlled stops continue to govern physical use; no transparent native-model failover is permitted.

Collaboration accounting uses frozen InferenceAttempt, ConsultationRecord, and GovernedPlanRecord values in llm/services/telemetry.py. InferenceUsageSink counts unique attempt IDs; ConsultationLookup resolves only admitted, exact profile/workspace/ session/task references. Primary and specialist totals are separate, with a deduplicated combined view. Opaque provider boundaries are labeled call_boundary; their attempt counts are incomplete. Missing token usage stays unknown, including on failure or cancellation. Provider usage is retained before hardware payload extraction. Consultation timing records measured acquisition, approval evaluation/wait, artifact and codec encoding, provider-attempt network/inference, validation, queue, and cleanup intervals. Missing/unentered phases stay absent; network/inference sums attempts and excludes retry backoff. Nested captures forward phase samples only within their owning scope. Client ownership and pooling are unchanged. Telemetry defects are logged with tracebacks and never reclassified as provider or physical failures.

model_query returns a consultation ID and canonical result digest. Optional hw_skill_run.consultation_refs entries are {call_id, disposition}, where disposition is adopted, overridden, or unused. This is explicit LLM attribution, not permission: unknown/foreign references remain unlinked, and ineligible advice cannot become eligible. Only verified node plans establish plan/permit identity. Later owner-scoped status/stop observations append immutable records with origin_record_id and the same confirmed run, workcell, and plan digest. Node grasp-verifier notes supply bounded operation_verification metadata with sensor/scene/calibration identity and complete-note digests; contact is not proof of lifting. Full-task success stays unverified pending independent rubric review. Model labels and teacher scores do not qualify as measured outcomes.

The owning LearningBridge admits model.inference_attempt, model.consultation, and model.plan_link through private RECORD signals. Detached admission receipts are stored in transcript metadata even when result text is truncated. Replay excludes bulky receipts but retains compact consultation identity. Bounded feedback is retrieved through the normal tool surface outside the stable prompt prefix. Unified skill/delegate calls use the same governance; child identity is bound before calls, child artifacts/consultation authority stay child-owned, and only original-scope inference accounting is merged into parent totals. No mandatory consultation, second execution loop, or generated-action dispatch is introduced.

2.5 SelectionPolicyPlugin Protocol

When several tools provide the same capability, a selection policy decides which one runs. It is a core extension point, not a tool plugin: it is invoked by the framework inside a turn, reads host-side services, and therefore is not sandboxed, not approval-gated, and earns no Progressive Trust — trust is earned by executing tools, and a policy executes none.

@runtime_checkable
class SelectionPolicyPlugin(Protocol):
    @property
    def policy_id(self) -> str: ...        # config value, e.g. "greedy"

    @property
    def display_name(self) -> str: ...

    def create(self, params: Mapping[str, Any], deps: PolicyDeps) -> SelectionPolicy: ...


@runtime_checkable
class SelectionPolicy(Protocol):
    policy_id: str

    def select(self, requirement, eligible, context) -> SelectionOutcome: ...
    def observe(self, requirement, chosen_tool: str, reward: RewardSignal) -> None: ...

Discovery: setuptools group "leapflow.selection_policies". Activation: selection.policy via leap config set selection.policy <policy_id>.

Built in: greedy (default, highest score), thompson (Beta posterior sampling), ucb1 (deterministic upper confidence bound), bucketed (routes capabilities between several policies for an A/B experiment; arms come from selection.buckets). The learners share selection.prior_strength; ucb1 also reads selection.exploration.

Competition is required for a learning policy to do anything. With built-in tools alone, every capability name is provided by exactly one tool (55 tools, 55 names), so there is one arm per capability and nothing to learn. Multiple candidates appear when self-evolution generates a plugin providing a capability an existing tool already provides. Until then thompson and ucb1 behave as greedy-with-prior.

Three rules the runtime enforces, each of which will otherwise bite you:

  • eligible is pre-filtered and never empty. Any candidate a configured scorer marked excluded is removed before select is called, and your policy cannot reach it. With the default scorer set that covers: a candidate not declaring the capability, a missing host platform capability, and a risk level above the requirement's ceiling. Two further exclusions — app-level affordance and frozen-trust — come from scorers that are opt-in (CapabilityResolver(scorers=...)), so they apply only where a caller injects them. Exploration is never permitted to trade off safety, but do not read this list as the complete set of guards in every configuration.
  • SelectionOutcome.reason is rendered to operators, and explored=True is how a deliberate departure from the highest score is distinguished from a scoring bug. "Chose at random" is not an explanation; a posterior and a bonus term are.
  • RewardSignal.value is None means no information, not failure. A successful call whose handler declared no observable effect abstains. Treating that as a zero would drive every arm's posterior down and, through trust, quarantine healthy plugins for a reporting omission. Only observed_effect in a tool result carries a confirmable effect.

Registration is first-wins: an id already taken is refused and the collision recorded, rather than silently replacing how the framework chooses its own tools. Instance lifetime is owned by the registry (activate() builds once and caches, current() never creates), so a stateful policy accumulates across turns instead of being rebuilt per call.

A policy that carries a posterior must persist it. PolicyDeps.stats_store provides a durable per-(policy, capability, arm) counter store; keeping the posterior in memory instead means restarting cold on every daemon restart and never converging. Reads are answered from memory because select() is on the turn path; writes happen in observe(), which runs on the cold-path sweep.

2.6 SignalSource Protocol

@runtime_checkable
class SignalSource(Protocol):
    @property
    def channel_id(self) -> str: ...

    @property
    def event_types(self) -> FrozenSet[str]: ...

    @property
    def bypasses_privacy(self) -> bool: ...

    def transform(self, event_type: str, payload: Dict[str, Any],
                  context: SignalTransformContext) -> Optional[InteractionSignal]: ...

Stateless; not fiber-managed. Registered with SignalSourceRegistry.

2.7 ActiveSignalSource Protocol

EmitCallback = Callable[[InteractionSignal], None]

@runtime_checkable
class ActiveSignalSource(Protocol):
    @property
    def source_id(self) -> str: ...

    @property
    def channel_id(self) -> str: ...

    async def start(self, emit: EmitCallback) -> None: ...
    async def stop(self) -> None: ...

Managed by ActiveSourceManager (bounded asyncio queue, per-source task, thread-safe emit callback). Note: ActiveSignalSource is not yet integrated with PluginFiber lifecycle; lifecycle is owned by PerceptionSession directly.

2.8 CVProcessor Protocol

@runtime_checkable
class CVProcessor(Protocol):
    @property
    def processor_id(self) -> str: ...

    @property
    def description(self) -> str: ...

    def process(self, frame_a: bytes, frame_b: bytes, **kwargs: Any) -> Dict[str, Any]: ...

3. Development Standards

3.1 Plugin ID Naming

  • Must be globally unique across the registry.
  • Use lowercase snake_case (e.g., "weather_lookup", "jira_integration").
  • Duplicates at registration time raise ValueError.

3.2 Dependency Injection via bind_runtime

Plugins declare needed services in dependencies and receive them through bind_runtime(**deps). This is late dependency injection — plugins must not import runtime services at module level.

@property
def dependencies(self) -> list[str]:
    return ["memory_manager", "file_read_gate"]

def bind_runtime(self, **deps: Any) -> None:
    if "memory_manager" in deps:
        self._memory = deps["memory_manager"]
    if "file_read_gate" in deps:
        self._gate = deps["file_read_gate"]

Available dependency names (wired by the daemon): plugin_approval_gate, llm_provider, plugin_generation_enabled, plugin_install_dir, marketplace_client, marketplace_trusted_pubkeys, memory_manager, gateway_server, research_ledger, reentry_scheduler, file_read_gate, file_write_gate, desktop_gate, capability_catalog_provider, subagent_manager, model_services, model_approval_gate, settings, effect_scope.

The shared subagent_manager does not own a caller's session. Production tool dispatch supplies ToolExecutionContext through current_tool_context(); unified delegation uses its live run_subagent callback and binds the child's parent to that context's session. A scoped call without an owning runner fails closed. This callback is internal execution context, not another bind_runtime dependency or a sandbox permission grant. Children use the same unified loop with fresh prompt, memory, compression, and dispatch state. Only explicitly delegated context enters the child; parent artifact references and approval authority are not inherited. delegate_task returns the persisted child session_id, tool_calls, and terminal status, including failures and cancellation; classified failures carry JSON-safe failure metadata. An advisory specialist result never dispatches model-generated actions or supplies an execution permit.

Session-sensitive tools also use the owning ToolExecutionContext callbacks: capability_catalog reads the filtered frame snapshot, evidence_detail retrieves bounded session-local records, research_ledger selects the current task's notes, and capability_knowledge reads workspace/session-scoped observations. These are optional internal execution-context fields, not process-global ownership or sandbox permission grants. tool_describe(include_observations=True) explicitly retrieves scoped historical observations; ordinary description does not. session_detail(message_ids=[...]) selects at most 32 exact messages with bounded content and truncation metadata. Foreign workspace/session data cannot substitute for absent evidence. Tool results remain observations; successful execution does not establish task usefulness, a verified fact, or a user preference. Completed-turn consumers receive the originating immutable TurnOutcome, including final visible answer, terminal status, current executions, scope, and captured telemetry, rather than reverse-scanning history.

3.3 Side-Effect-Free Import

Plugin modules must not perform I/O, network calls, or state mutation at import time. Use the lazy __getattr__ pattern for heavy optional imports:

def __getattr__(name: str):
    if name == "heavy_client":
        import some_heavy_sdk
        return some_heavy_sdk.Client()
    raise AttributeError(name)

3.4 Handler Contract

All tool handlers must:

  1. Be async (signature: async def handler(params: dict) -> dict).
  2. Accept a single dict of parameters matching parameters_schema.
  3. Return a structured dict result (never raw strings).
  4. Never raise for expected errors — return {"ok": False, "error": "..."}.
  5. Reserve exceptions for truly unexpected internal failures.

3.5 Mutating Tools and Approval

Tools that produce side effects must set mutates_state=True on their ToolMetadata. The engine routes mutating tool calls through the ApprovalGate. To declare risk level and trigger approval:

ToolMetadata(
    name="delete_resource",
    description="Delete a cloud resource permanently.",
    parameters_schema={...},
    handler=handle_delete,
    mutates_state=True,
    execution_policy="external_side_effect",
    x_leapflow={
        "category": "cloud_ops",
        "risk_level": "high",
        "requires_approval": True,
    },
)

For platform actions (gateway send, external API write), use execution_policy="external_side_effect" and ActionDescriptor.platform_action(platform, action, metadata). The action descriptor requests approval; the execution policy controls durable evidence, duplicate suppression, batch stopping, and uncertain-effect reporting. Runtime policy is derived only from these declarations, never from the tool name.

3.6 Code Quality

  • English docstrings and comments.
  • Type annotations on all public APIs.
  • No bare except — always specify exception types.
  • No global mutable state besides the module-level plugin instance.

4. Execution Chain

The following is the ordered sequence from plugin source to tool invocation:

Step 1: Discovery & Registration

  1. Built-in discovery: ToolPluginRegistry.discover_builtin() imports leapflow.plugins.tool_plugins.get_all_plugins(), which lazily imports each plugin module and collects plugin instances. Plugins listed in Settings.disabled_plugins are skipped.
  2. Registration: registry.register(plugin) stores the plugin keyed by plugin_id, validates Protocol conformance, bumps _version.

Step 2: Dependency Injection

  1. registry.bind_runtime(**deps): Iterates all plugins; for each, filters deps to only those declared in plugin.dependencies, then calls plugin.bind_runtime(**relevant_deps). Tracks _last_bound_deps for re-injection on hot-reload.

Step 3: Assembly

  1. registry.assemble(): One-shot pass over all plugins → all tools. For each ToolMetadata: calls to_openai_schema() to produce the LLM-facing schema, maps tool.name → tool.handler into _tool_handlers. Plugins that arrive after assembly (install, hot-reload) publish their tools through registry.publish_plugin_tools(plugin), which returns the published names and bumps the version counter.

Step 4: PluginFiber Lifecycle

  1. ScopedToolRegistry.adopt_existing_plugins(): Called on first leapflow.plugins.get_scoped_registry() access. It creates a PluginFiber for every already-registered plugin. Dependency-free built-ins use PENDING → ACTIVE; dependency-bearing plugins use PENDING → LOADING → ACTIVE when providers become available.

Fiber domain state machine: PENDING → DRAFT → ACTIVE → UNLOADING → DISPOSED for isolated candidates, plus PENDING → LOADING → ACTIVE and LOADING → FAILED → LOADING for dependency-driven activation. DRAFT plugins expose no live handlers until atomic promotion.

Step 5: Per-Turn Engine Assembly

  1. engine._unified_tool_catalog(): Produces the OpenAI schema list sent to the LLM. Cache key: ((id(desktop_plugin), desktop_plugin.version), len(registry.tool_definitions)). Invalidated when registry version changes.
  2. engine._unified_tool_handlers(): Returns dict(registry.tool_handlers) — a fresh copy per turn. This per-turn snapshot is the concurrency-safety mechanism: in-flight turns keep their snapshot; a hot-reload mid-session only affects turns started after the reload.

Step 6: Tool Dispatch

  1. _execute_general_tool(tool_call, handlers): Resolves the tool name (canonical/normalized resolution via ToolRegistry.resolve()), looks up the handler in the per-turn snapshot, and invokes it through the shared handler adapter (invoke_tool_handler). The adapter supports both generated **kwargs handlers and older params: dict handlers, so native function calls with {} work for no-argument tools such as plugin_list.
  2. Approval gate: If the tool's metadata declares mutates_state=True or requires approval, the engine checks the approval gate before execution.

Step 7: Usage & Trust Recording

  1. TurnUsageTracker.record_tool_call(name, ok, duration): Records per-turn sample.
  2. Forwarding: If _plugin_stats_sink is set (wired by session_factory._wire_plugin_stats_sink()), forwards to PluginUsageTracker.record().
  3. Trust update: PluginUsageTracker resolves tool_name → plugin_id via a lazy reverse index (invalidated by registry _version), then calls PluginTrustLedger.record_success() or record_failure().
  4. Persistence: PluginStatsStore (DuckDB) persists trust state. An atexit handler ensures durability on shutdown.

Why Per-Turn Snapshots Make Hot-Reload Safe

The engine calls dict(registry.tool_handlers) at the start of each turn, creating an isolated copy. A ScopedToolRegistry.reload(plugin_id) in a concurrent session:

  • Disposes the old fiber (removes tools from the registry).
  • Re-imports and re-registers the fresh plugin.
  • Bumps _version → invalidates cache for future turns.

But the currently-executing turn still holds its snapshot with the old handlers and finishes safely. LeapFlow's single-threaded asyncio model guarantees no pre-emption mid-turn.

Tool Execution Pipeline & Interceptors

Tool dispatch is wrapped by a ToolExecutionPipeline that implements a waterfall (middleware) pattern. Before and after actual handler invocation, registered ToolInterceptor instances run composable pre/post hooks.

from typing import Any, Protocol, runtime_checkable

@runtime_checkable
class ToolInterceptor(Protocol):
    async def before(self, context: dict[str, Any]) -> dict[str, Any]: ...
    async def after(self, context: dict[str, Any], result: Any) -> Any: ...

Registering an interceptor from a third-party plugin:

from leapflow.plugins import get_registry

def bind_runtime(self, **deps: Any) -> None:
    registry = get_registry()
    registry.tool_pipeline.register(self._my_interceptor)  # priority comes from interceptor.priority

Interceptors are process-global once registered on registry.tool_pipeline. If a plugin registers one dynamically, it must also register an explicit cleanup effect on its PluginFiber/EffectScope (or unregister it during disposal); automatic scope-bound interceptor removal is a planned convenience, not current runtime behavior.

Typical interceptor use cases include audit logging, execution timeout, approval gating, rate limiting, and result redaction. The repository currently ships the pipeline primitives and example audit/timeout interceptors; production plugins must register and unregister any additional interceptor explicitly.

Dependency Binding and Activation

Plugins declare dependencies, and ToolPluginRegistry.bind_runtime() distributes matching runtime dependencies in topological plugin order. ScopedToolRegistry activates dependency-free plugins immediately and keeps dependency-bearing fibers in LOADING until their providers are active; handlers must still degrade gracefully when optional runtime dependencies are absent.


5. Deployment

5.1 Built-in Package Plugins

Plugins shipped with LeapFlow live in src/leapflow/plugins/tool_plugins/. Each module defines a module-level plugin = MyPlugin() instance. Discovery is via the _BUILTIN_PLUGIN_MODULES tuple in plugins/tool_plugins/__init__.py.

To add a new built-in plugin: Add the module path to _BUILTIN_PLUGIN_MODULES and ensure the module exposes plugin.

5.2 Profile-Scoped Install (Dynamic)

Third-party plugins are installed into the active profile's plugin directory:

~/.leapflow/profiles/<profile>/plugins/<entry_point>.py

Installation is performed by the plugin_install tool (part of the self_management plugin). The path is derived from ProfileLayout.plugins_dir or overridden by Settings.plugin_install_dir. Profile-scoped .py plugins are discovered on registry boot by discover_profile_plugins() and loaded with file-backed import specs so reload does not depend on global sys.path.

Install flow: Validated code → write to profile plugins dir → sandbox smoke test → dynamic import → register in live registry → activate fiber.

5.2a Generating plugins via slash command (/plugin generate)

For a zero-boilerplate path, the TUI/CLI exposes /plugin generate <description>, which synthesizes, validates, and installs a plugin directly from a natural-language description:

/plugin generate a tool that fetches the current weather for a city
  • Zero-prompt happy path — the description is sent to the configured LLM, the generated code is run through the staged validators (syntax → import → Protocol conformance → sandbox smoke test), and on success the plugin is installed into the profile plugins dir and hot-loaded. A single bounded refinement retry runs on a refinable validation failure (syntax/protocol/structure).
  • --preview — generate and validate only, then return the code for inspection without installing. Use this to review before committing.
  • --dry-run — validate the generated code without writing it to disk.
  • --id <plugin_id> — override the auto-derived plugin id (a slug of the description). A colliding id is rejected cleanly.

Generation is controlled by plugin.generation_enabled and requires an LLM provider. Proposal-backed generation stores validated source in profile CAS and requires explicit content approval. Installation remains a separate mutation approval.

Difference from the plugin_generate agent tool: /plugin generate is a user-initiated control-plane command — the user's invocation is the consent, so it runs without an approval gate and produces a DRAFT-trust plugin. The plugin_generate tool is agent-initiated: the agent proposes generation from capability-gap evidence, and every mutation routes through the ApprovalGate at HIGH risk. Both share the same generator, validators, and install path.

5.3 LLM Provider Entry Points

Only LLMProviderPlugin supports setuptools entry_point discovery:

# pyproject.toml of the external package
[project.entry-points."leapflow.llm_providers"]
my_provider = "my_package.provider:plugin"

LLMProviderRegistry.discover_entry_points() loads these at startup.

Important: ToolPlugin supports built-in package discovery, profile-scoped file discovery, marketplace install, and explicit registration. It does NOT yet support setuptools entry_point discovery. GatewayAdapterPlugin remains registered through the gateway adapter registry.

5.4 Marketplace Distribution

PluginManifest

@dataclass(frozen=True)
class PluginManifest:
    name: str                       # unique plugin identifier
    version: str                    # semver
    author: str
    description: str
    entry_point: str                # module filename (without .py)
    plugin_type: str = "tool"       # "tool" | "active_signal_source" | "gateway" | "llm"
    source_url: str = ""
    checksum_sha256: str = ""       # SHA-256 of the source code
    requires_sandbox: bool = True   # untrusted by default
    dependencies: List[str] = field(default_factory=list)
    min_leapflow_version: str = ""
    signature: str = ""             # hex Ed25519 signature
    signer_pubkey: str = ""         # hex Ed25519 public key

Integrity: SHA-256 Checksum

checksum = PluginManifest.compute_checksum(code_bytes)
manifest.verify_checksum(code_bytes)  # -> bool

Authenticity: Ed25519 Signing

# Generate keypair (author does this once)
private_hex, public_hex = PluginManifest.generate_keypair()

# Sign (author signs before publishing)
signed_manifest = manifest.sign(code_bytes, private_hex)

# Verify (client checks on install)
signed_manifest.verify_signature(code_bytes, trusted_pubkeys={"<public_hex>"})

Canonical signed payload: name|version|entry_point|checksum_sha256 (UTF-8 encoded).

Marketplace Sources

Source Class Discovery
Local directory LocalDirectorySource <root>/<plugin_name>/manifest.json + <entry_point>.py
HTTP registry HttpMarketplaceSource GET /plugins/, GET /plugins/<name>/manifest.json, GET /plugins/<name>/<entry_point>.py

MarketplaceClient

client = MarketplaceClient(source=LocalDirectorySource(root), install_dir=path)
manifests = client.discover()
result = client.install("plugin_name", verify=True, trusted_pubkeys={"..."})

Caveat — Marketplace HTTP server: The HTTP server (plugins/marketplace/server.py) is a prototype. Production readiness is not guaranteed.

Removal: Use the plugin_remove(plugin_id, delete_source=true) self-management tool for live removal. It disposes the fiber, unregisters tools, drops reload metadata, and optionally deletes the profile-scoped source file. MarketplaceClient.uninstall() remains a low-level file deletion primitive and does not by itself operate on live runtime state.

5.5 Configuration Keys

Key Default Purpose
disabled_plugins () Tuple of plugin_ids to skip at discovery time
plugin_generation_enabled True Gate for LLM-driven code generation; set false to disable synthesis
plugin_install_dir None (→ ProfileLayout.plugins_dir) Override install directory
plugin_marketplace_root None Local directory marketplace source
plugin_marketplace_url None HTTP marketplace URL (takes precedence over local)
plugin_marketplace_trusted_pubkeys () Hex Ed25519 public keys for signature verification

5.6 Slash Commands

  • /plugin — List all registered plugins.
  • /plugin status <id> — Show plugin details and trust level.

Mutating operations (install, rollback, reload, disable, remove, enable) are only available through the self-management tools in daemon mode, and require explicit approval. Read-only governance tools such as plugin_versions can inspect recorded profile-scoped source snapshots without approval.

5.7 Compatibility Assessment (Pre-Install Gate)

Before a marketplace install writes any file, LeapFlow runs the Compatibility Assessment Engine (leapflow.learning.compatibility) against the resolved manifest. The engine is a six-stage pipeline (manifest parsing → category resolution → interface analysis → dependency checking → execution model → security classification) that produces a CompatibilityReport with a final verdict. Marketplace installs are gated on it: an INCOMPATIBLE verdict is rejected before file write with a structured error; an ADAPTABLE verdict proceeds and surfaces its adaptation_notes alongside the install result.

Verdict meaning for developers:

Verdict What it means for you
COMPATIBLE Direct install; no modification needed.
ADAPTABLE A thin bridge/shim is needed and is auto-generated (see adapter_generator).
PARTIAL Only a subset of the plugin's features is usable; the unusable surfaces are documented in the report.
INCOMPATIBLE The plugin targets a system layer LeapFlow does not expose (e.g. agent-loop, session, context, storage); LeapFlow cannot host it.

Pre-check a manifest manually with the assess_compatibility tool (read-only, no approval). It accepts a manifest dict in LeapFlow or DSH format and returns the verdict, target protocol, adaptation notes, adapter spec, and per-stage results:

from leapflow.learning.compatibility import assess_plugin

report = assess_plugin(manifest_dict)          # dict, LeapFlow or DSH format
print(report.final_verdict.value)               # "compatible" | "adaptable" | "partial" | "incompatible"
print(report.is_installable())                  # True unless INCOMPATIBLE

File-path loading: assess_plugin() also accepts a path (string or Path) to a manifest JSON file; it is read from disk and flows through the same pipeline:

report = assess_plugin("/path/to/manifest.json")

DSH → LeapFlow interop: convert_dsh_to_leapflow() translates a deepseek-harness package.json-style manifest into a LeapFlow PluginManifest-compatible dict (name normalization, main → entry_point, requires_sandbox=True, original manifest preserved under x_dsh_original):

from leapflow.learning.compatibility.manifest_converter import convert_dsh_to_leapflow

leapflow_manifest = convert_dsh_to_leapflow(dsh_package_json)

6. Security Model

6.1 Validation Pipeline

Stage When What
Syntax Generate-time ast.parse() — valid Python
Structure Generate-time AST check: module-level plugin assignment; flag dangerous patterns (os.system, eval, exec)
Import Generate-time Temp-file import in throwaway namespace; Protocol conformance check
Sandbox smoke Install-time First tool invoked in isolated subprocess via SandboxHost
Human approval Install-time ApprovalGate evaluation (see below)

6.2 Approval Gating

All plugin mutation operations are classified as HIGH risk with allow_permanent=False:

# From security/risk.py
platform "plugin_management" → RiskLevel.HIGH, allow_permanent=False

This means:

  • Every install/reload/disable/enable requires explicit approval per invocation.
  • Permanent grants are never issued for plugin mutations.
  • No gate installed (non-daemon mode) → fail-closed (mutations denied).

6.3 Progressive Trust

Plugins earn trust through consistent successful execution:

Level Consecutive Successes Required Behavior
DRAFT 0 (initial) Untrusted; full sandbox
CANDIDATE 5 Partially trusted
VERIFIED 20 Established reliability
PRODUCTION 50 Auto-approves plugin_reload

Demotion: 3 consecutive failures → demote one level.
Hard failure (internal defect): Immediate freeze to DRAFT permanently.

6.4 Sandbox Isolation

Untrusted plugins (requires_sandbox=True, the default) execute in a subprocess:

  • SandboxHost launches a worker subprocess (leapflow.plugins.sandbox.worker).
  • Communication: JSON-RPC over stdin/stdout.
  • Timeout: 30s default per invocation.
  • SandboxedToolPlugin wraps the plugin Protocol with proxied handlers.
  • Sandboxed plugins receive no host-side runtime dependencies (empty bind_runtime).

7. End-to-End Example

7.1 Author a ToolPlugin

"""Weather lookup plugin — demonstrates a minimal third-party ToolPlugin."""
from __future__ import annotations
from typing import Any
from leapflow.plugins.protocol import ToolMetadata, ToolPlugin


class WeatherPlugin:
    """Provides a single tool to look up weather data."""

    @property
    def plugin_id(self) -> str:
        return "weather_lookup"

    @property
    def category(self) -> str:
        return "integration"

    @property
    def tools(self) -> list[ToolMetadata]:
        return [
            ToolMetadata(
                name="get_weather",
                description="Get current weather for a city.",
                parameters_schema={
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "City name",
                        },
                    },
                    "required": ["city"],
                },
                handler=self._handle_get_weather,
                x_leapflow={
                    "category": "integration",
                    "risk_level": "read_only",
                    "schema_cost": "low",
                },
            ),
        ]

    @property
    def dependencies(self) -> list[str]:
        return []  # No runtime deps needed

    def bind_runtime(self, **deps: Any) -> None:
        pass  # No-op

    async def _handle_get_weather(self, params: dict) -> dict:
        """Handler: fetch weather data."""
        city = params.get("city", "")
        if not city:
            return {"ok": False, "error": "city parameter is required"}
        # Real implementation would call a weather API here
        return {
            "ok": True,
            "city": city,
            "temperature_c": 22,
            "condition": "partly_cloudy",
        }


# Module-level instance — REQUIRED for discovery
plugin = WeatherPlugin()

7.2 Validate

The PluginValidator runs automatically during plugin_generate or can be triggered programmatically:

from leapflow.learning.plugin_generator import PluginValidator

validator = PluginValidator()
result = await validator.validate("weather_lookup", source_code)
# result.ok == True, result.stage == "passed", result.exposed_tools == ["get_weather"]

7.3 Install (Code Path)

Using the plugin_install tool (requires daemon mode + approval):

Agent: I'll install the weather plugin.
→ plugin_install(code="<validated source>", plugin_id="weather_lookup")
→ ApprovalGate: HIGH risk, requires user confirmation
→ User approves
→ Code written to ~/.leapflow/profiles/default/plugins/weather_lookup.py
→ Sandbox smoke test passes
→ Dynamic import → register → fiber created (ACTIVE)
→ Result: {"ok": true, "plugin_id": "weather_lookup", "tools": ["get_weather"]}

7.4 Invoke

Once installed, the LLM agent can call the tool naturally:

User: What's the weather in Tokyo?
Agent: [calls get_weather(city="Tokyo")]
→ Engine: _unified_tool_handlers() snapshot includes "get_weather"
→ _execute_general_tool → handler invoked → result returned
→ TurnUsageTracker.record_tool_call("get_weather", ok=True, duration_ms=45)

7.5 Observe Trust Accrual

→ PluginUsageTracker.record("get_weather", ok=True, 45.0)
→ Resolves "get_weather" → plugin_id "weather_lookup"
→ PluginTrustLedger.record_success("weather_lookup")
→ After 5 consecutive successes: DRAFT → CANDIDATE
→ After 20: CANDIDATE → VERIFIED
→ After 50: VERIFIED → PRODUCTION (reload auto-approves)

Query trust via plugin_status("weather_lookup") to see current level and advisor recommendations.


8. Reference Tables

8.1 Module Path Index

Subsystem Key File(s)
ToolPlugin Protocol src/leapflow/plugins/protocol.py
ToolPluginRegistry src/leapflow/plugins/registry.py
ScopedToolRegistry src/leapflow/plugins/scoped_registry.py
Built-in plugin discovery src/leapflow/plugins/tool_plugins/__init__.py
EffectScope src/leapflow/domain/effect_scope.py
PluginFiber src/leapflow/domain/plugin_fiber.py
Self-management tools src/leapflow/plugins/tool_plugins/self_management.py
Sandbox host + protocol src/leapflow/plugins/sandbox/sandbox_host.py, plugins/sandbox/protocol.py
Marketplace manifest src/leapflow/plugins/marketplace/manifest.py
Marketplace client src/leapflow/plugins/marketplace/client.py
HTTP marketplace source src/leapflow/plugins/marketplace/http_source.py
Marketplace server (prototype) src/leapflow/plugins/marketplace/server.py
Plugin generator + validator src/leapflow/learning/plugin_generator.py
Trust ledger src/leapflow/learning/plugin_trust.py
Usage tracker src/leapflow/learning/plugin_stats.py
Plugin advisor src/leapflow/learning/plugin_advisor.py
Stats persistence (DuckDB) src/leapflow/learning/plugin_stats_store.py
Health producer src/leapflow/monitor/plugin_health_producer.py
GatewayAdapterPlugin src/leapflow/gateway/adapter_registry.py
LLMProviderPlugin src/leapflow/llm/provider_registry.py
Settings (config keys) src/leapflow/config.py
Profile layout (plugins_dir) src/leapflow/layout.py

8.2 Configuration Key Table

Config Key Type Default Description
disabled_plugins tuple[str, ...] () Plugin IDs to skip during built-in discovery
plugin_generation_enabled bool True Enable LLM-driven plugin code generation; set false to disable synthesis
plugin_install_dir str | None None Override profile plugins dir path
plugin_marketplace_root str | None None Local marketplace directory
plugin_marketplace_url str | None None HTTP marketplace URL
plugin_marketplace_trusted_pubkeys tuple[str, ...] () Trusted Ed25519 public keys (hex)

8.3 Test Files for Contributors

Subsystem Test File
Plugin reload / lifecycle tests/test_plugin_reload.py
Self-management tools tests/test_self_management.py
Sandbox tests/test_plugin_sandbox.py
Marketplace + signing tests/test_plugin_marketplace.py, tests/test_marketplace_signing.py
Generator + validator tests/test_plugin_generator.py
Trust / learning tests/test_plugin_learning.py
Stats persistence tests/test_plugin_stats_persistence.py
Scoped registry tests/test_scoped_registry.py
Full fiberization tests/test_full_fiberization.py
Effect scope tests/test_effect_scope.py
Architecture contracts tests/test_architecture_contracts.py
LLM provider registry tests/test_llm_provider_registry.py
Gateway adapters tests/test_gateway_adapters.py, tests/test_gateway_adapter_registry.py
CV plugins tests/test_cv_plugins.py
Active signal sources tests/test_active_signal_source.py
Marketplace HTTP server tests/test_marketplace_server.py
Monitor (health producer) tests/test_monitor_subsystem.py

Appendix: Roadmap / Not Yet Available

The following features exist in code but are partial, prototype, or unwired:

Feature Status
Entry-point discovery for ToolPlugin / GatewayAdapterPlugin Not implemented. Only LLMProviderPlugin uses entry_points.
ActiveSignalSource fiber integration Not wired. Lifecycle owned by PerceptionSession, not PluginFiber.
Marketplace HTTP server Prototype (asyncio HTTP, no auth/rate-limiting).
PluginHealthProducer → automatic remediation Advisory-only. Detects anomalies but does not auto-disable plugins.
MarketplaceClient.uninstall() live unregister Deletes file only; does not dispose fiber or remove from live registry.
Gateway adapter fiber lifecycle (scoped reload) Protocol exists but scoped fiber-based reload for gateway adapters is not confirmed wired.