flowvane 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. apflow/__init__.py +16 -0
  2. flowvane/__init__.py +193 -0
  3. flowvane/_environment.py +20 -0
  4. flowvane/_version.py +8 -0
  5. flowvane/adapters/__init__.py +5 -0
  6. flowvane/adapters/function_executor.py +187 -0
  7. flowvane/api/__init__.py +14 -0
  8. flowvane/api/auth.py +140 -0
  9. flowvane/api/combined.py +252 -0
  10. flowvane/api/rest.py +534 -0
  11. flowvane/api/webhook.py +129 -0
  12. flowvane/app.py +225 -0
  13. flowvane/bridge/__init__.py +5 -0
  14. flowvane/bridge/access.py +212 -0
  15. flowvane/bridge/errors.py +22 -0
  16. flowvane/bridge/execution_modules.py +221 -0
  17. flowvane/bridge/governance_modules.py +255 -0
  18. flowvane/bridge/module_adapter.py +118 -0
  19. flowvane/bridge/output_schema.py +111 -0
  20. flowvane/bridge/protocol.py +242 -0
  21. flowvane/bridge/registry_setup.py +191 -0
  22. flowvane/bridge/scanner_bridge.py +176 -0
  23. flowvane/bridge/schedule_modules.py +432 -0
  24. flowvane/bridge/session.py +105 -0
  25. flowvane/bridge/task_modules.py +1273 -0
  26. flowvane/cli.py +720 -0
  27. flowvane/core/__init__.py +230 -0
  28. flowvane/core/base/__init__.py +10 -0
  29. flowvane/core/base/base_task.py +356 -0
  30. flowvane/core/builders.py +155 -0
  31. flowvane/core/config/__init__.py +69 -0
  32. flowvane/core/config/registry.py +846 -0
  33. flowvane/core/config_manager.py +316 -0
  34. flowvane/core/decorators.py +83 -0
  35. flowvane/core/distributed/__init__.py +25 -0
  36. flowvane/core/distributed/config.py +184 -0
  37. flowvane/core/distributed/events.py +71 -0
  38. flowvane/core/distributed/idempotency.py +132 -0
  39. flowvane/core/distributed/leader_election.py +237 -0
  40. flowvane/core/distributed/lease_manager.py +429 -0
  41. flowvane/core/distributed/node_registry.py +186 -0
  42. flowvane/core/distributed/placement.py +123 -0
  43. flowvane/core/distributed/runtime.py +397 -0
  44. flowvane/core/distributed/types.py +12 -0
  45. flowvane/core/distributed/worker.py +446 -0
  46. flowvane/core/execution/__init__.py +57 -0
  47. flowvane/core/execution/context.py +7 -0
  48. flowvane/core/execution/dispatch.py +459 -0
  49. flowvane/core/execution/error_info.py +196 -0
  50. flowvane/core/execution/errors.py +231 -0
  51. flowvane/core/execution/result_protocol.py +181 -0
  52. flowvane/core/execution/run_retry.py +347 -0
  53. flowvane/core/execution/runs.py +260 -0
  54. flowvane/core/execution/streaming_callbacks.py +143 -0
  55. flowvane/core/execution/submission.py +103 -0
  56. flowvane/core/execution/task_creator.py +1562 -0
  57. flowvane/core/execution/task_executor.py +1286 -0
  58. flowvane/core/execution/task_manager.py +2193 -0
  59. flowvane/core/execution/task_tracker.py +65 -0
  60. flowvane/core/extensions/__init__.py +49 -0
  61. flowvane/core/extensions/base.py +134 -0
  62. flowvane/core/extensions/decorators.py +347 -0
  63. flowvane/core/extensions/executor_metadata.py +208 -0
  64. flowvane/core/extensions/hook.py +71 -0
  65. flowvane/core/extensions/manager.py +375 -0
  66. flowvane/core/extensions/protocol.py +72 -0
  67. flowvane/core/extensions/registry.py +658 -0
  68. flowvane/core/extensions/scanner.py +575 -0
  69. flowvane/core/extensions/storage.py +86 -0
  70. flowvane/core/extensions/types.py +63 -0
  71. flowvane/core/interfaces/__init__.py +26 -0
  72. flowvane/core/interfaces/executable_task.py +150 -0
  73. flowvane/core/storage/__init__.py +41 -0
  74. flowvane/core/storage/context.py +313 -0
  75. flowvane/core/storage/dialects/__init__.py +13 -0
  76. flowvane/core/storage/dialects/postgres.py +76 -0
  77. flowvane/core/storage/dialects/registry.py +71 -0
  78. flowvane/core/storage/dialects/sqlite.py +96 -0
  79. flowvane/core/storage/factory.py +1200 -0
  80. flowvane/core/storage/migrate.py +208 -0
  81. flowvane/core/storage/migrations/001_add_task_tree_fields.py +261 -0
  82. flowvane/core/storage/migrations/002_add_scheduling_fields.py +155 -0
  83. flowvane/core/storage/migrations/003_add_distributed_support.py +223 -0
  84. flowvane/core/storage/migrations/004_add_durability_and_governance.py +180 -0
  85. flowvane/core/storage/migrations/005_add_idempotency_key_unique_index.py +110 -0
  86. flowvane/core/storage/migrations/006_add_service_execution_contracts.py +50 -0
  87. flowvane/core/storage/migrations/007_add_workflow_runs_usage_events.py +99 -0
  88. flowvane/core/storage/migrations/__init__.py +83 -0
  89. flowvane/core/storage/session.py +28 -0
  90. flowvane/core/storage/sqlalchemy/__init__.py +15 -0
  91. flowvane/core/storage/sqlalchemy/invariants.py +199 -0
  92. flowvane/core/storage/sqlalchemy/models.py +856 -0
  93. flowvane/core/storage/sqlalchemy/schedule_calculator.py +466 -0
  94. flowvane/core/storage/sqlalchemy/task_repository.py +1892 -0
  95. flowvane/core/types.py +328 -0
  96. flowvane/core/utils/__init__.py +3 -0
  97. flowvane/core/utils/credentials.py +283 -0
  98. flowvane/core/utils/helpers.py +484 -0
  99. flowvane/core/utils/network_security.py +92 -0
  100. flowvane/core/utils/project_detection.py +81 -0
  101. flowvane/core/validator/__init__.py +20 -0
  102. flowvane/core/validator/dependency_validator.py +479 -0
  103. flowvane/core/validator/user_validator.py +40 -0
  104. flowvane/durability/__init__.py +21 -0
  105. flowvane/durability/attempts.py +266 -0
  106. flowvane/durability/checkpoint.py +168 -0
  107. flowvane/durability/circuit_breaker.py +209 -0
  108. flowvane/durability/retry.py +224 -0
  109. flowvane/extensions/__init__.py +46 -0
  110. flowvane/extensions/core/__init__.py +12 -0
  111. flowvane/extensions/core/aggregate_results_executor.py +232 -0
  112. flowvane/extensions/email/__init__.py +9 -0
  113. flowvane/extensions/email/send_email_executor.py +456 -0
  114. flowvane/extensions/flowvane/__init__.py +10 -0
  115. flowvane/extensions/flowvane/api_executor.py +770 -0
  116. flowvane/extensions/hooks/__init__.py +11 -0
  117. flowvane/extensions/hooks/post_execution_hook.py +71 -0
  118. flowvane/extensions/hooks/pre_execution_hook.py +71 -0
  119. flowvane/extensions/http/__init__.py +10 -0
  120. flowvane/extensions/http/rest_executor.py +458 -0
  121. flowvane/extensions/storage/__init__.py +16 -0
  122. flowvane/extensions/storage/postgres_storage.py +98 -0
  123. flowvane/extensions/storage/sqlite_storage.py +47 -0
  124. flowvane/governance/__init__.py +21 -0
  125. flowvane/governance/budget.py +256 -0
  126. flowvane/governance/ledger.py +368 -0
  127. flowvane/governance/policy.py +159 -0
  128. flowvane/governance/provider_router.py +69 -0
  129. flowvane/governance/reporter.py +222 -0
  130. flowvane/governance/usage.py +310 -0
  131. flowvane/logger.py +77 -0
  132. flowvane/py.typed +0 -0
  133. flowvane/scheduler/__init__.py +27 -0
  134. flowvane/scheduler/base.py +215 -0
  135. flowvane/scheduler/gateway/__init__.py +23 -0
  136. flowvane/scheduler/gateway/ical.py +469 -0
  137. flowvane/scheduler/gateway/webhook.py +608 -0
  138. flowvane/scheduler/internal.py +640 -0
  139. flowvane-0.25.0.dist-info/METADATA +301 -0
  140. flowvane-0.25.0.dist-info/RECORD +144 -0
  141. flowvane-0.25.0.dist-info/WHEEL +5 -0
  142. flowvane-0.25.0.dist-info/entry_points.txt +3 -0
  143. flowvane-0.25.0.dist-info/licenses/LICENSE +18 -0
  144. flowvane-0.25.0.dist-info/top_level.txt +2 -0
apflow/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Compatibility exports for the former base package name."""
2
+
3
+ from typing import Any
4
+
5
+ import flowvane as _flowvane
6
+ from flowvane import __all__ as __all__
7
+
8
+
9
+ def __getattr__(name: str) -> Any:
10
+ if name in __all__:
11
+ return getattr(_flowvane, name)
12
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
13
+
14
+
15
+ def __dir__() -> list[str]:
16
+ return sorted(set(globals()) | set(__all__))
flowvane/__init__.py ADDED
@@ -0,0 +1,193 @@
1
+ """
2
+ FlowVane — AI-Perceivable Distributed Orchestration
3
+
4
+ A distributed task orchestration engine where every capability is
5
+ AI-perceivable — discoverable, understandable, and invocable by
6
+ AI agents through the apcore module standard.
7
+
8
+ Core:
9
+ - core.execution: Task orchestration (dependency graphs, priority, parallel)
10
+ - core.distributed: Leader election, task leasing, worker management
11
+ - core.storage: SQLite (default) / PostgreSQL
12
+ - bridge: apcore Module registration (auto-discovery)
13
+ - durability: Checkpoint/resume, retry, circuit breaker
14
+ - governance: Token budget, cost policy, model downgrade
15
+
16
+ APCore Surfaces provides MCP, A2A, and CLI access to FlowVane's modules.
17
+ """
18
+
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ from flowvane._version import __version__ as __version__
22
+
23
+ if TYPE_CHECKING:
24
+ from flowvane.adapters.function_executor import (
25
+ function_executor,
26
+ )
27
+ from flowvane.core import (
28
+ BaseTask,
29
+ ExecutableTask,
30
+ StreamingCallbacks,
31
+ TaskManager,
32
+ create_session,
33
+ get_default_session,
34
+ get_hook_repository,
35
+ get_hook_session,
36
+ )
37
+ from flowvane.core.decorators import (
38
+ clear_config,
39
+ executor_register,
40
+ get_require_existing_tasks,
41
+ get_task_model_class,
42
+ get_task_tree_hooks,
43
+ get_use_task_creator,
44
+ get_webhook_verify_hook,
45
+ hook_register,
46
+ register_post_hook,
47
+ register_pre_hook,
48
+ register_task_tree_hook,
49
+ register_webhook_verify_hook,
50
+ set_require_existing_tasks,
51
+ set_task_model_class,
52
+ set_use_task_creator,
53
+ storage_register,
54
+ task_model_register,
55
+ )
56
+ from flowvane.core.extensions import (
57
+ add_executor_hook,
58
+ )
59
+ from flowvane.core.types import (
60
+ WebhookVerifyContext,
61
+ WebhookVerifyResult,
62
+ )
63
+
64
+ __all__ = [
65
+ # Core framework
66
+ "ExecutableTask",
67
+ "BaseTask",
68
+ "TaskManager",
69
+ "StreamingCallbacks",
70
+ "create_session",
71
+ "get_default_session",
72
+ "get_hook_session",
73
+ "get_hook_repository",
74
+ # Adapters
75
+ "function_executor",
76
+ # Unified decorators
77
+ "register_pre_hook",
78
+ "register_post_hook",
79
+ "register_task_tree_hook",
80
+ "get_task_tree_hooks",
81
+ "set_task_model_class",
82
+ "get_task_model_class",
83
+ "task_model_register",
84
+ "clear_config",
85
+ "set_use_task_creator",
86
+ "get_use_task_creator",
87
+ "set_require_existing_tasks",
88
+ "get_require_existing_tasks",
89
+ "register_webhook_verify_hook",
90
+ "get_webhook_verify_hook",
91
+ "WebhookVerifyContext",
92
+ "WebhookVerifyResult",
93
+ "executor_register",
94
+ "storage_register",
95
+ "hook_register",
96
+ # Extension utilities
97
+ "add_executor_hook",
98
+ # Version
99
+ "__version__",
100
+ ]
101
+
102
+
103
+ def __getattr__(name: str) -> Any:
104
+ """Lazy import to avoid loading heavy flowvane.core at package import time"""
105
+
106
+ # Core interfaces
107
+ if name in (
108
+ "ExecutableTask",
109
+ "BaseTask",
110
+ "TaskManager",
111
+ "StreamingCallbacks",
112
+ "create_session",
113
+ "get_default_session",
114
+ "get_hook_session",
115
+ "get_hook_repository",
116
+ ):
117
+ from flowvane.core import (
118
+ ExecutableTask, # noqa: F401
119
+ BaseTask, # noqa: F401
120
+ TaskManager, # noqa: F401
121
+ StreamingCallbacks, # noqa: F401
122
+ create_session, # noqa: F401
123
+ get_default_session, # noqa: F401
124
+ get_hook_session, # noqa: F401
125
+ get_hook_repository, # noqa: F401
126
+ )
127
+
128
+ return locals()[name]
129
+
130
+ # Decorators
131
+ if name in (
132
+ "register_pre_hook",
133
+ "register_post_hook",
134
+ "register_task_tree_hook",
135
+ "get_task_tree_hooks",
136
+ "set_task_model_class",
137
+ "get_task_model_class",
138
+ "task_model_register",
139
+ "clear_config",
140
+ "set_use_task_creator",
141
+ "get_use_task_creator",
142
+ "set_require_existing_tasks",
143
+ "get_require_existing_tasks",
144
+ "register_webhook_verify_hook",
145
+ "get_webhook_verify_hook",
146
+ "executor_register",
147
+ "storage_register",
148
+ "hook_register",
149
+ ):
150
+ from flowvane.core.decorators import (
151
+ register_pre_hook, # noqa: F401
152
+ register_post_hook, # noqa: F401
153
+ register_task_tree_hook, # noqa: F401
154
+ get_task_tree_hooks, # noqa: F401
155
+ set_task_model_class, # noqa: F401
156
+ get_task_model_class, # noqa: F401
157
+ task_model_register, # noqa: F401
158
+ clear_config, # noqa: F401
159
+ set_use_task_creator, # noqa: F401
160
+ get_use_task_creator, # noqa: F401
161
+ set_require_existing_tasks, # noqa: F401
162
+ get_require_existing_tasks, # noqa: F401
163
+ register_webhook_verify_hook, # noqa: F401
164
+ get_webhook_verify_hook, # noqa: F401
165
+ executor_register, # noqa: F401
166
+ storage_register, # noqa: F401
167
+ hook_register, # noqa: F401
168
+ )
169
+
170
+ return locals()[name]
171
+
172
+ # Adapters
173
+ if name == "function_executor":
174
+ from flowvane.adapters.function_executor import function_executor
175
+
176
+ return function_executor
177
+
178
+ # Core types
179
+ if name in ("WebhookVerifyContext", "WebhookVerifyResult"):
180
+ from flowvane.core.types import (
181
+ WebhookVerifyContext, # noqa: F401
182
+ WebhookVerifyResult, # noqa: F401
183
+ )
184
+
185
+ return locals()[name]
186
+
187
+ # Extension utilities
188
+ if name == "add_executor_hook":
189
+ from flowvane.core.extensions import add_executor_hook
190
+
191
+ return add_executor_hook
192
+
193
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,20 @@
1
+ """Read FlowVane settings with a fallback to their legacy spelling."""
2
+
3
+ import os
4
+ from typing import TypeVar, overload
5
+
6
+ Default = TypeVar("Default")
7
+
8
+
9
+ @overload
10
+ def get_environment(name: str) -> str | None: ...
11
+
12
+
13
+ @overload
14
+ def get_environment(name: str, default: Default) -> str | Default: ...
15
+
16
+
17
+ def get_environment(name: str, default: Default | None = None) -> str | Default | None:
18
+ if name in os.environ:
19
+ return os.environ[name]
20
+ return os.environ.get("APFLOW_" + name.removeprefix("FLOWVANE_"), default)
flowvane/_version.py ADDED
@@ -0,0 +1,8 @@
1
+ """Read the installed FlowVane version without importing the application."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("flowvane")
7
+ except PackageNotFoundError:
8
+ __version__ = "unknown"
@@ -0,0 +1,5 @@
1
+ """Adapter utilities for simplified executor registration."""
2
+
3
+ from flowvane.adapters.function_executor import function_executor
4
+
5
+ __all__ = ["function_executor"]
@@ -0,0 +1,187 @@
1
+ """
2
+ Decorator that wraps a plain function as a registered ExecutableTask.
3
+
4
+ Generates a BaseTask subclass dynamically, registers it via executor_register,
5
+ and returns the original function unchanged.
6
+
7
+ Example:
8
+ @function_executor(id="fetch_data", description="Fetch data from URL")
9
+ async def fetch_data(inputs: dict) -> dict:
10
+ return {"data": await httpx.get(inputs["url"])}
11
+ """
12
+
13
+ import asyncio
14
+ import inspect
15
+ from typing import Any, Callable, Dict, Optional, Type, Union
16
+
17
+ from pydantic import BaseModel
18
+
19
+ from flowvane.core.base import BaseTask
20
+ from flowvane.core.execution.result_protocol import (
21
+ ResultFormat,
22
+ executor_result_schema,
23
+ normalize_executor_result,
24
+ )
25
+ from flowvane.core.extensions.decorators import executor_register
26
+ from flowvane.logger import get_logger
27
+
28
+ logger = get_logger(__name__)
29
+
30
+ # Module-level registry so the bridge can discover function executors
31
+ _function_executor_classes: Dict[str, type] = {}
32
+
33
+
34
+ def function_executor(
35
+ id: str,
36
+ description: str,
37
+ name: Optional[str] = None,
38
+ input_schema: Optional[Dict[str, Any]] = None,
39
+ output_schema: Optional[Dict[str, Any]] = None,
40
+ input_model: Optional[Type[BaseModel]] = None,
41
+ output_model: Optional[Type[BaseModel]] = None,
42
+ tags: Optional[list[str]] = None,
43
+ override: bool = False,
44
+ result_format: ResultFormat = "raw",
45
+ ) -> Callable:
46
+ """Decorator that registers an async/sync function as an flowvane executor.
47
+
48
+ The generated executor is discoverable by the bridge and automatically
49
+ exposed via MCP/A2A/CLI. The decorated function itself is returned unchanged.
50
+
51
+ Args:
52
+ id: Unique executor identifier (used in task trees).
53
+ description: Human-readable description (exposed to AI agents).
54
+ name: Display name; defaults to id title-cased.
55
+ input_schema: JSON Schema dict for inputs.
56
+ output_schema: JSON Schema dict for outputs.
57
+ input_model: Pydantic model for inputs (mutually exclusive with input_schema).
58
+ output_model: Pydantic model for outputs (mutually exclusive with output_schema).
59
+ tags: Tags for categorization.
60
+ override: Force re-registration if id already exists.
61
+ result_format: Format returned by the function (raw by default). The
62
+ generated executor always returns an envelope. Output schema/model
63
+ describes the function return value in the declared format.
64
+
65
+ Returns:
66
+ The original function, unchanged.
67
+
68
+ Raises:
69
+ ValueError: If id/description empty, or schema/model conflict.
70
+ """
71
+ if not id:
72
+ raise ValueError("id must be non-empty")
73
+ if not description:
74
+ raise ValueError("description must be non-empty")
75
+
76
+ if result_format not in ("legacy", "raw", "envelope"):
77
+ raise ValueError(f"Unknown function result format: {result_format}")
78
+
79
+ resolved_input = _resolve_schema(input_schema, input_model)
80
+ resolved_output = _resolve_schema(output_schema, output_model)
81
+
82
+ def decorator(fn: Callable) -> Callable:
83
+ executor_name = name or id.replace("_", " ").title()
84
+
85
+ cls = _build_executor_class(
86
+ executor_id=id,
87
+ executor_name=executor_name,
88
+ executor_description=description,
89
+ fn=fn,
90
+ inputs_schema=resolved_input,
91
+ outputs_schema=resolved_output,
92
+ tags=tags or [],
93
+ result_format=result_format,
94
+ )
95
+
96
+ # Register in extension registry. When override=False and `id` is
97
+ # already registered, this returns the previously registered class,
98
+ # not `cls` — the bridge-discovery entry must track whichever class
99
+ # the extension registry actually uses at execution time, or MCP/CLI
100
+ # would advertise one implementation while execution runs another.
101
+ registered_cls = executor_register(override=override)(cls)
102
+
103
+ # Store for bridge discovery
104
+ _function_executor_classes[id] = registered_cls
105
+
106
+ logger.info(f"Registered function executor: {id}")
107
+ return fn
108
+
109
+ return decorator
110
+
111
+
112
+ def _resolve_schema(
113
+ explicit_schema: Optional[Dict[str, Any]],
114
+ pydantic_model: Optional[Type[BaseModel]],
115
+ ) -> Optional[Union[Type[BaseModel], Dict[str, Any]]]:
116
+ """Resolve schema from explicit dict or Pydantic model.
117
+
118
+ Raises ValueError if both are provided.
119
+ """
120
+ if explicit_schema is not None and pydantic_model is not None:
121
+ raise ValueError(
122
+ "input_schema/output_schema and input_model/output_model are mutually exclusive"
123
+ )
124
+ if pydantic_model is not None:
125
+ return pydantic_model
126
+ return explicit_schema
127
+
128
+
129
+ def _build_executor_class(
130
+ executor_id: str,
131
+ executor_name: str,
132
+ executor_description: str,
133
+ fn: Callable,
134
+ inputs_schema: Optional[Union[Type[BaseModel], Dict[str, Any]]],
135
+ outputs_schema: Optional[Union[Type[BaseModel], Dict[str, Any]]],
136
+ tags: list[str],
137
+ result_format: ResultFormat,
138
+ ) -> type:
139
+ """Create a BaseTask subclass dynamically from a function."""
140
+ is_async = inspect.iscoroutinefunction(fn)
141
+
142
+ async def execute(self: Any, inputs: Dict[str, Any]) -> Dict[str, Any]:
143
+ value = await fn(inputs) if is_async else await asyncio.to_thread(fn, inputs)
144
+ normalized = normalize_executor_result(value, result_format)
145
+ usage = normalized.get("token_usage")
146
+ if result_format == "legacy" and isinstance(usage, dict):
147
+ # Provider-specific counters remain in the complete legacy business output.
148
+ normalized["token_usage"] = {
149
+ key: count for key, count in usage.items() if key in ("input", "output", "total")
150
+ }
151
+ # Declared envelope schemas describe the function's actual wire shape.
152
+ return value if result_format == "envelope" else dict(normalized)
153
+
154
+ # Build class name: "analyze_pr" → "AnalyzePrFunctionExecutor"
155
+ class_name = "".join(part.capitalize() for part in executor_id.split("_")) + "FunctionExecutor"
156
+
157
+ attrs: Dict[str, Any] = {
158
+ "id": executor_id,
159
+ "name": executor_name,
160
+ "description": executor_description,
161
+ "tags": tags,
162
+ "execute": execute,
163
+ "result_format": "envelope",
164
+ }
165
+
166
+ if inputs_schema is not None:
167
+ attrs["inputs_schema"] = inputs_schema
168
+ schema = (
169
+ outputs_schema.model_json_schema()
170
+ if isinstance(outputs_schema, type) and issubclass(outputs_schema, BaseModel)
171
+ else outputs_schema or {}
172
+ )
173
+ attrs["outputs_schema"] = (
174
+ schema if result_format == "envelope" and schema else executor_result_schema(schema)
175
+ )
176
+
177
+ cls = type(class_name, (BaseTask,), attrs)
178
+ return cls
179
+
180
+
181
+ def get_function_executor_classes() -> Dict[str, type]:
182
+ """Return a copy of the function executor registry.
183
+
184
+ Used by the bridge to discover runtime-registered function executors
185
+ that are invisible to the AST scanner.
186
+ """
187
+ return dict(_function_executor_classes)
@@ -0,0 +1,14 @@
1
+ """FlowVane REST/HTTP API adapter (registry-driven, Starlette-based)."""
2
+
3
+ from flowvane.api.combined import assemble_combined, serve_all
4
+ from flowvane.api.rest import build_openapi, build_rest_app, serve_rest
5
+ from flowvane.api.webhook import build_webhook_routes
6
+
7
+ __all__ = [
8
+ "assemble_combined",
9
+ "build_openapi",
10
+ "build_rest_app",
11
+ "build_webhook_routes",
12
+ "serve_all",
13
+ "serve_rest",
14
+ ]
flowvane/api/auth.py ADDED
@@ -0,0 +1,140 @@
1
+ """Shared JWT authentication wiring for FlowVane's REST, A2A, and MCP faces.
2
+
3
+ All three protocols validate the SAME Bearer token, built from ConfigManager's
4
+ ``api.jwt_*`` settings, so one token minted with ``api.jwt_secret`` authenticates
5
+ everywhere:
6
+
7
+ - REST : ``apcore_surfaces.mcp.auth.AuthMiddleware`` wraps the Starlette app
8
+ - A2A : ``apcore_surfaces.a2a.auth.JWTAuthenticator`` passed to ``a2a serve(auth=...)``
9
+ - MCP : ``apcore_surfaces.mcp.auth.JWTAuthenticator`` passed to ``mcp serve(authenticator=...)``
10
+
11
+ The two SDK ``JWTAuthenticator`` classes share an identical constructor
12
+ (``key``, ``algorithms``, ``audience``, ``issuer``) and verify the same token;
13
+ REST reuses the apcore-mcp authenticator via its ASGI ``AuthMiddleware``.
14
+
15
+ When no secret is configured the builders return ``None`` (auth disabled — the
16
+ caller decides whether that is a hard error or a dev-mode warning).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from pathlib import Path
22
+ from typing import Any, Optional
23
+
24
+ from flowvane.core.config_manager import ConfigManager, get_config_manager
25
+
26
+ # Public REST paths that must stay reachable without a token: service metadata,
27
+ # liveness probe, and the self-documenting OpenAPI / Swagger surface.
28
+ REST_EXEMPT_PATHS: set[str] = {"/", "/healthz", "/readyz", "/docs", "/openapi.json"}
29
+ # The inbound webhook authenticates standalone via HMAC, so it bypasses JWT to
30
+ # avoid forcing external schedulers to carry both credentials.
31
+ REST_EXEMPT_PREFIXES: set[str] = {"/webhook"}
32
+
33
+
34
+ def _algorithms(cm: ConfigManager) -> list[str]:
35
+ """Parse the configured algorithm(s), supporting a comma-separated list."""
36
+ return [a.strip() for a in cm.jwt_algorithm.split(",") if a.strip()]
37
+
38
+
39
+ def _reject_mixed_algorithm_families(algorithms: list[str]) -> None:
40
+ """Refuse a list mixing symmetric (HS*) and asymmetric (RS*/ES*/PS*) algorithms.
41
+
42
+ A mixed list is a JWT algorithm-confusion hazard: the verification key would
43
+ be the asymmetric *public* key, but an HS* entry lets an attacker HMAC-sign a
44
+ token with that public key (which is public by design) and be accepted. The
45
+ two families use fundamentally different keys, so a single config can only
46
+ safely use one of them.
47
+ """
48
+ has_symmetric = any(a.upper().startswith("HS") for a in algorithms)
49
+ has_asymmetric = any(not a.upper().startswith("HS") for a in algorithms)
50
+ if has_symmetric and has_asymmetric:
51
+ raise ValueError(
52
+ "api.jwt_algorithm must not mix symmetric (HS*) and asymmetric "
53
+ f"(RS*/ES*/PS*) algorithms: {algorithms}. They use different keys; "
54
+ "mixing them enables JWT algorithm-confusion attacks. Configure one "
55
+ "family only."
56
+ )
57
+
58
+
59
+ def resolve_verification_key(cm: ConfigManager) -> Optional[str]:
60
+ """Return the key used to VERIFY tokens, picked by algorithm family.
61
+
62
+ Symmetric (HS*) verifies with the shared ``api.jwt_secret``. Asymmetric
63
+ (RS*/ES*/PS*) verifies with a public key — provided inline via
64
+ ``api.jwt_public_key`` or read from ``api.jwt_public_key_path``. Returns
65
+ None when the relevant key is not configured (auth cannot be enabled).
66
+ Raises ValueError on a mixed-family algorithm list (algorithm-confusion guard).
67
+ """
68
+ algorithms = _algorithms(cm)
69
+ _reject_mixed_algorithm_families(algorithms)
70
+ is_asymmetric = any(not a.upper().startswith("HS") for a in algorithms)
71
+ if is_asymmetric:
72
+ if cm.jwt_public_key:
73
+ return cm.jwt_public_key
74
+ if cm.jwt_public_key_path:
75
+ return Path(cm.jwt_public_key_path).read_text(encoding="utf-8")
76
+ return None
77
+ return cm.jwt_secret
78
+
79
+
80
+ def _jwt_kwargs(cm: ConfigManager) -> Optional[dict[str, Any]]:
81
+ """Read JWT settings into JWTAuthenticator kwargs, or None when no key."""
82
+ key = resolve_verification_key(cm)
83
+ if not key:
84
+ return None
85
+ return {
86
+ "key": key,
87
+ "algorithms": _algorithms(cm),
88
+ "audience": cm.jwt_audience,
89
+ "issuer": cm.jwt_issuer,
90
+ }
91
+
92
+
93
+ def build_mcp_authenticator(cm: Optional[ConfigManager] = None) -> Optional[Any]:
94
+ """Build an apcore-mcp JWTAuthenticator from config (None if no secret).
95
+
96
+ Used both for the MCP server and, via ``apply_rest_auth``, for REST.
97
+ """
98
+ kwargs = _jwt_kwargs(cm or get_config_manager())
99
+ if kwargs is None:
100
+ return None
101
+ from apcore_surfaces.mcp.auth import JWTAuthenticator
102
+
103
+ return JWTAuthenticator(**kwargs)
104
+
105
+
106
+ def build_a2a_authenticator(cm: Optional[ConfigManager] = None) -> Optional[Any]:
107
+ """Build an apcore-a2a JWTAuthenticator from config (None if no secret)."""
108
+ kwargs = _jwt_kwargs(cm or get_config_manager())
109
+ if kwargs is None:
110
+ return None
111
+ from apcore_surfaces.a2a.auth import JWTAuthenticator
112
+
113
+ return JWTAuthenticator(**kwargs)
114
+
115
+
116
+ def apply_rest_auth(
117
+ app: Any,
118
+ authenticator: Any,
119
+ *,
120
+ extra_exempt_prefixes: Optional[set[str]] = None,
121
+ ) -> Any:
122
+ """Wrap a Starlette/ASGI app so REST module calls require a valid Bearer token.
123
+
124
+ Public metadata paths (:data:`REST_EXEMPT_PATHS`) and the HMAC-guarded
125
+ webhook (:data:`REST_EXEMPT_PREFIXES`) bypass JWT. ``extra_exempt_prefixes``
126
+ lets the combined server also exempt the A2A / MCP sub-apps, which carry
127
+ their own authentication.
128
+ """
129
+ from apcore_surfaces.mcp.auth import AuthMiddleware
130
+
131
+ prefixes = set(REST_EXEMPT_PREFIXES)
132
+ if extra_exempt_prefixes:
133
+ prefixes |= extra_exempt_prefixes
134
+ return AuthMiddleware(
135
+ app,
136
+ authenticator,
137
+ exempt_paths=set(REST_EXEMPT_PATHS),
138
+ exempt_prefixes=prefixes,
139
+ require_auth=True,
140
+ )