Spaces:
Running

File size: 4,567 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Pack interface and discovery. Packs hold all industry knowledge; core never imports them.



Packs register under the ``workpilot.packs`` entry point group in their ``pyproject.toml``.



Optional members (not part of the runtime-checked ``Pack`` protocol; looked up with

``getattr`` so packs without them stay valid):



* ``routers() -> list[fastapi.APIRouter]``: read-only API routes, mounted by

  ``core.api.main`` under ``/packs/<name>``.

* ``seeders() -> dict[str, async (db, tenant_id) -> Any]``: named seed-data builders used by

  the eval harness (``Scenario.seed``) and demos, e.g. ``{"ecommerce": seed_ecommerce}``.

* ``event_types() -> list[str]``: event types the pack handles (event intake maps external

  webhooks to these; each is also an intent name so the router dispatches it directly).

* ``event_aliases() -> dict[str, str]``: external event type -> intent name, e.g.

  ``{"shopify.orders.create": "ecommerce.order.created"}``. The router resolves these

  deterministically (``core.agent.router.route``) before falling back to unsupported.

* ``outboxes() -> list[core.channels.outbox.Outbox]``: the pack's outbound-message tables,

  delivered by the core channel worker (``core.channels.delivery``). An outbox claims due

  rows (``claim_due``: ``queued`` and ``send_after <= now`` -> ``sending``, with

  ``FOR UPDATE SKIP LOCKED``), renders them for their channel (``OutboxItem``), and records

  outcomes (``mark_sent`` / ``mark_retry`` / ``mark_failed``), stale claims

  (``release_stale``) and provider receipts (``apply_receipt``). Rows are queued only by

  gateway tools, so delivery itself needs no further authorization.

* ``workflow_templates() -> list[WorkflowDefinition | dict]``: the workflow gallery

  (``core.workflows.catalog``). Each item is a ``core.workflows.dsl.WorkflowDefinition`` (or

  its JSON), or ``{"definition": ..., "nl": "plain-language request", "tags": [...]}``.

  Installing one creates a draft that still needs a dry run, owner approval and activation.

* ``tenant_event_aliases() -> dict[str, str]`` (Phase 15, ADR-0009 G1): like

  ``event_aliases`` but opt-in: active only for tenants that bind the event to this pack

  (``settings.event_bindings`` or a channel account's ``config.route_to``). Several packs

  may claim one external event; each tenant's binding chooses (``core.agent.tenant_config``).

* ``settings_schema() -> type[BaseModel] | dict`` (Phase 15, G4): schema of the pack's

  ``tenants.settings[<pack name>]`` block; ``PUT /settings`` (``pack_settings``) validates

  writes against it and ``GET /settings`` exposes it for the dashboard.



Graphs read the tenant's non-secret config snapshot from ``state["tenant_config"]`` (time

zone, locale, safety profile, enabled packs, scrubbed pack blocks; Phase 15, G5).

"""

from __future__ import annotations

from dataclasses import dataclass
from importlib.metadata import entry_points
from pathlib import Path
from typing import Any, Protocol, runtime_checkable

from core.agent.models import ModelTiers
from core.agent.tools import ToolCaller
from core.memory.client import MemoryClient
from core.tools.spec import RegisteredTool


@dataclass(frozen=True)
class AgentDeps:
    """What a pack's subgraphs may use. No raw DB access, no direct API clients."""

    tools: ToolCaller
    models: ModelTiers
    # Phase 12: knowledge search, episodic memory and prompts, all through the gateway.
    memory: MemoryClient | None = None


@dataclass(frozen=True)
class IntentInfo:
    name: str  # also the subgraph / node name, e.g. "demo.refund_request"
    description: str  # shown to the router and planner models
    chat_enabled: bool = True  # may an operator's chat request route here?


@runtime_checkable
class Pack(Protocol):
    name: str
    version: str

    def tools(self) -> list[RegisteredTool]: ...

    def intents(self) -> list[IntentInfo]: ...

    def subgraphs(self, deps: AgentDeps) -> dict[str, Any]: ...  # intent -> compiled graph

    def policies(self) -> list[Path]: ...

    def eval_scenarios_dir(self) -> Path | None: ...


def discover_packs(names: list[str] | None = None) -> list[Pack]:
    packs: list[Pack] = []
    for ep in entry_points(group="workpilot.packs"):
        if names is not None and ep.name not in names:
            continue
        pack = ep.load()()
        if not isinstance(pack, Pack):
            raise TypeError(f"{ep.name} does not implement the Pack protocol")
        packs.append(pack)
    return packs