swarmauri_invoker_default 0.1.0__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ Swarmauri SDK
2
+
3
+ This package is part of the Swarmauri SDK and is distributed under the
4
+ Apache License, Version 2.0. See LICENSE for the license terms.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_invoker_default
3
+ Version: 0.1.0
4
+ Summary: Invoke services over existing Swarmauri transports.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Keywords: swarmauri,invocations,composition,execution,authorization
9
+ Author: Jacob Stewart
10
+ Author-email: jacob@swarmauri.com
11
+ Requires-Python: >=3.10,<3.13
12
+ Classifier: Development Status :: 1 - Planning
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Dist: swarmauri_base (>=0.11.0.dev13,<0.12)
18
+ Requires-Dist: swarmauri_core (>=0.11.0.dev8,<0.12)
19
+ Project-URL: Repository, https://github.com/swarmauri/swarmauri-sdk
20
+ Description-Content-Type: text/markdown
21
+
22
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
23
+
24
+ # swarmauri_invoker_default
25
+
26
+ [![Downloads](https://img.shields.io/pypi/dm/swarmauri_invoker_default)](https://pepy.tech/project/swarmauri_invoker_default)
27
+ [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_invoker_default.svg)](https://github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_invoker_default)
28
+ [![Python](https://img.shields.io/pypi/pyversions/swarmauri_invoker_default)](https://pypi.org/project/swarmauri_invoker_default)
29
+ [![License](https://img.shields.io/pypi/l/swarmauri_invoker_default)](LICENSE)
30
+ [![Version](https://img.shields.io/pypi/v/swarmauri_invoker_default?label=swarmauri_invoker_default&color=green)](https://pypi.org/project/swarmauri_invoker_default)
31
+
32
+ Interchangeable invocations component for the composable execution framework.
33
+
34
+ ## Features
35
+
36
+ - Export `DefaultInvoker` with SDK interface/base-class inheritance and entry-point discovery.
37
+ - Keep user authority, workload identity, lifecycle and delivery dependencies explicit.
38
+ - Reuse existing service registries, transports, checkpoints and token providers.
39
+ - Support Python 3.10, 3.11 and 3.12.
40
+
41
+ ## Installation
42
+
43
+ These packages introduce unreleased core/base APIs. Install the matching workspace revision together; do not combine with older published core/base releases. Release validation must publish compatible dependency versions first.
44
+
45
+ ```sh
46
+ uv pip install ./pkgs/standards/swarmauri_invoker_default
47
+ pip install ./pkgs/standards/swarmauri_invoker_default
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ The following is composition code. Injected dependency names are host configuration, not bundled mock providers. Async statements run inside an async function.
53
+
54
+ ```python
55
+ from swarmauri_transport_httpx import HttpxClient
56
+ from swarmauri_invoker_default import DefaultInvoker
57
+
58
+ invoker = DefaultInvoker(
59
+ services=service_registry, policy=permission_policy,
60
+ edges=edge_bindings, authorities=authority_strategies,
61
+ http_client=HttpxClient(), local_endpoints=receiving_apps,
62
+ )
63
+ result = await invoker.invoke(request, trusted_invocation_context)
64
+ # Model arguments do not supply actor identities, grants, or JWTs.
65
+ ```
66
+
67
+ See [the complete architecture and deployment guide](../../../docs/examples/composable-execution/README.md) for concrete local commands, live OIDC integration, HTTP hosting, lifecycle semantics and failure recovery.
68
+
69
+ ## Verification
70
+
71
+ From `pkgs/`, with the workspace dependencies installed:
72
+
73
+ ```sh
74
+ uv run --package swarmauri_invoker_default --directory standards/swarmauri_invoker_default pytest
75
+ uv run --package swarmauri_invoker_default --directory standards/swarmauri_invoker_default ruff check .
76
+ ```
77
+
78
+ Tests use real signing and stores where applicable; scripted models are explicitly identified fixtures. No live provider interoperability is claimed by offline tests.
79
+
80
+ ## Contributing
81
+
82
+ Follow the repository [contribution guide](https://github.com/swarmauri/swarmauri-sdk/blob/master/AGENTS.md).
83
+
@@ -0,0 +1,61 @@
1
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
2
+
3
+ # swarmauri_invoker_default
4
+
5
+ [![Downloads](https://img.shields.io/pypi/dm/swarmauri_invoker_default)](https://pepy.tech/project/swarmauri_invoker_default)
6
+ [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_invoker_default.svg)](https://github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_invoker_default)
7
+ [![Python](https://img.shields.io/pypi/pyversions/swarmauri_invoker_default)](https://pypi.org/project/swarmauri_invoker_default)
8
+ [![License](https://img.shields.io/pypi/l/swarmauri_invoker_default)](LICENSE)
9
+ [![Version](https://img.shields.io/pypi/v/swarmauri_invoker_default?label=swarmauri_invoker_default&color=green)](https://pypi.org/project/swarmauri_invoker_default)
10
+
11
+ Interchangeable invocations component for the composable execution framework.
12
+
13
+ ## Features
14
+
15
+ - Export `DefaultInvoker` with SDK interface/base-class inheritance and entry-point discovery.
16
+ - Keep user authority, workload identity, lifecycle and delivery dependencies explicit.
17
+ - Reuse existing service registries, transports, checkpoints and token providers.
18
+ - Support Python 3.10, 3.11 and 3.12.
19
+
20
+ ## Installation
21
+
22
+ These packages introduce unreleased core/base APIs. Install the matching workspace revision together; do not combine with older published core/base releases. Release validation must publish compatible dependency versions first.
23
+
24
+ ```sh
25
+ uv pip install ./pkgs/standards/swarmauri_invoker_default
26
+ pip install ./pkgs/standards/swarmauri_invoker_default
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ The following is composition code. Injected dependency names are host configuration, not bundled mock providers. Async statements run inside an async function.
32
+
33
+ ```python
34
+ from swarmauri_transport_httpx import HttpxClient
35
+ from swarmauri_invoker_default import DefaultInvoker
36
+
37
+ invoker = DefaultInvoker(
38
+ services=service_registry, policy=permission_policy,
39
+ edges=edge_bindings, authorities=authority_strategies,
40
+ http_client=HttpxClient(), local_endpoints=receiving_apps,
41
+ )
42
+ result = await invoker.invoke(request, trusted_invocation_context)
43
+ # Model arguments do not supply actor identities, grants, or JWTs.
44
+ ```
45
+
46
+ See [the complete architecture and deployment guide](../../../docs/examples/composable-execution/README.md) for concrete local commands, live OIDC integration, HTTP hosting, lifecycle semantics and failure recovery.
47
+
48
+ ## Verification
49
+
50
+ From `pkgs/`, with the workspace dependencies installed:
51
+
52
+ ```sh
53
+ uv run --package swarmauri_invoker_default --directory standards/swarmauri_invoker_default pytest
54
+ uv run --package swarmauri_invoker_default --directory standards/swarmauri_invoker_default ruff check .
55
+ ```
56
+
57
+ Tests use real signing and stores where applicable; scripted models are explicitly identified fixtures. No live provider interoperability is claimed by offline tests.
58
+
59
+ ## Contributing
60
+
61
+ Follow the repository [contribution guide](https://github.com/swarmauri/swarmauri-sdk/blob/master/AGENTS.md).
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "swarmauri_invoker_default"
3
+ version = "0.1.0"
4
+ description = "Invoke services over existing Swarmauri transports."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.10,<3.13"
8
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
9
+ keywords = ["swarmauri", "invocations", "composition", "execution", "authorization"]
10
+ classifiers = [
11
+ "Development Status :: 1 - Planning",
12
+ "License :: OSI Approved :: Apache Software License",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ ]
17
+ dependencies = ["swarmauri_core>=0.11.0.dev8,<0.12", "swarmauri_base>=0.11.0.dev13,<0.12"]
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/swarmauri/swarmauri-sdk"
21
+
22
+ [project.entry-points."swarmauri.invocations"]
23
+ DefaultInvoker = "swarmauri_invoker_default:DefaultInvoker"
24
+
25
+ [project.entry-points."swarmauri.authority_strategies"]
26
+ DelegatedAuthorityStrategy = "swarmauri_invoker_default:DelegatedAuthorityStrategy"
27
+ WorkloadAuthorityStrategy = "swarmauri_invoker_default:WorkloadAuthorityStrategy"
28
+
29
+ [tool.uv.sources]
30
+ swarmauri_workflow_documentassistant = { workspace = true }
31
+ swarmauri_transport_httpx = { workspace = true }
32
+ swarmauri_core = { workspace = true }
33
+ swarmauri_base = { workspace = true }
34
+
35
+ [dependency-groups]
36
+ dev = ["pytest>=8", "pytest-asyncio", "ruff==0.15.21", "swarmauri_workflow_documentassistant", "swarmauri_transport_httpx"]
37
+
38
+ [tool.pytest.ini_options]
39
+ asyncio_mode = "auto"
40
+ asyncio_default_fixture_loop_scope = "function"
41
+ markers = ["unit: Unit tests", "i9n: Integration tests"]
42
+
43
+ [build-system]
44
+ requires = ["poetry-core>=1.0.0"]
45
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,102 @@
1
+ """Invocation orchestration over existing service and transport contracts."""
2
+
3
+ from typing import Any, Literal
4
+ from dataclasses import replace
5
+ from urllib.parse import urlsplit
6
+
7
+ from pydantic import Field
8
+ from swarmauri_base.ComponentBase import ComponentBase
9
+ from swarmauri_base.invocations import InvokerBase
10
+ from swarmauri_core.invocations import (
11
+ EdgeAuthorizationBinding,
12
+ IAuthorityStrategy,
13
+ )
14
+ from swarmauri_core.permissions import IPermissionPolicy
15
+ from swarmauri_core.service_registries.IServiceRegistry import IServiceRegistry
16
+ from swarmauri_core.transports.i_http_client import IHttpClient
17
+ from swarmauri_core.workflows import ServiceBinding
18
+
19
+ from .codec import (
20
+ decode_request,
21
+ decode_result,
22
+ encode_request,
23
+ encode_result,
24
+ )
25
+
26
+
27
+ @ComponentBase.register_type(InvokerBase, "DefaultInvoker")
28
+ class DefaultInvoker(InvokerBase):
29
+ """Authorize configured edges and reuse HTTP or local delivery.
30
+
31
+ InvocationContext is host-established, never an LLM tool argument.
32
+ """
33
+
34
+ type: Literal["DefaultInvoker"] = "DefaultInvoker"
35
+ services: IServiceRegistry = Field(exclude=True, repr=False)
36
+ policy: IPermissionPolicy = Field(exclude=True, repr=False)
37
+ edges: dict[str, EdgeAuthorizationBinding]
38
+ authorities: dict[str, IAuthorityStrategy] = Field(
39
+ exclude=True, repr=False
40
+ )
41
+ http_client: IHttpClient | None = Field(default=None, exclude=True)
42
+ local_endpoints: dict[str, Any] = Field(
43
+ default_factory=dict, exclude=True, repr=False
44
+ )
45
+ timeout: float = Field(default=30, gt=0)
46
+
47
+ async def invoke(self, request, context):
48
+ request = replace(request, parent_execution_id=context.execution_id)
49
+ edge = self.edges[request.edge_id]
50
+ if (
51
+ edge.caller != context.actor
52
+ or edge.operation != request.operation
53
+ or context.task_id != request.task_id
54
+ or request.arguments.get("resource") != request.permission.resource
55
+ or not self.policy.authorize(
56
+ edge.permissions, request.permission
57
+ ).allowed
58
+ ):
59
+ raise PermissionError("Invocation is outside the edge policy")
60
+ details = self.services.get_service(edge.service)
61
+ if details is None:
62
+ raise KeyError(edge.service)
63
+ service = ServiceBinding(
64
+ service=edge.service,
65
+ subject=details["subject"],
66
+ audience=details["audience"],
67
+ endpoint=details["endpoint"],
68
+ protocol=details.get("protocol", "local"),
69
+ )
70
+ token = await self.authorities[edge.edge_id].credential(
71
+ request, context, service.audience
72
+ )
73
+ body = encode_request(request)
74
+ if service.protocol == "local":
75
+ # Use the same codec and receiver checks for both delivery paths.
76
+ result = await self.local_endpoints[service.endpoint].invoke(
77
+ decode_request(body), token
78
+ )
79
+ return decode_result(encode_result(result), request.invocation_id)
80
+ url = urlsplit(service.endpoint)
81
+ if url.scheme != "https" and not (
82
+ url.scheme == "http"
83
+ and url.hostname in {"127.0.0.1", "localhost", "::1"}
84
+ ):
85
+ raise ValueError("Remote invocation requires HTTPS")
86
+ if self.http_client is None:
87
+ raise ValueError("Configure an existing IHttpClient")
88
+ response = await self.http_client.arequest(
89
+ "POST",
90
+ service.endpoint,
91
+ headers={
92
+ "Content-Type": "application/json",
93
+ "Authorization": f"Bearer {token}",
94
+ },
95
+ body=body,
96
+ timeout=self.timeout,
97
+ )
98
+ if response.status_code == 403:
99
+ raise PermissionError("Remote invocation denied")
100
+ if response.status_code != 200:
101
+ raise RuntimeError("Remote invocation failed")
102
+ return decode_result(response.read(), request.invocation_id)
@@ -0,0 +1,14 @@
1
+ """Invoke services over existing Swarmauri transports."""
2
+
3
+ from .DefaultInvoker import DefaultInvoker
4
+ from .authority import DelegatedAuthorityStrategy, WorkloadAuthorityStrategy
5
+ from .app import InvocationEndpoint
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "DefaultInvoker",
11
+ "DelegatedAuthorityStrategy",
12
+ "WorkloadAuthorityStrategy",
13
+ "InvocationEndpoint",
14
+ ]
@@ -0,0 +1,200 @@
1
+ """Receiving authorization and durable duplicate handling for invocations."""
2
+
3
+ import hashlib
4
+ import json
5
+ import time
6
+ from dataclasses import asdict
7
+ from typing import Callable
8
+
9
+ from swarmauri_core.invocations import InvocationContext, InvocationResult
10
+ from swarmauri_core.run_stores import RunCheckpoint, RunConflictError
11
+ from swarmauri_core.transports.i_appserver import HttpApp
12
+
13
+ from .codec import (
14
+ decode_request,
15
+ encode_request,
16
+ encode_result,
17
+ )
18
+
19
+
20
+ class InvocationEndpoint(HttpApp):
21
+ """Admit local/HTTP requests before invoking a host-bound handler.
22
+
23
+ Handlers receive trusted context separately from model-visible arguments.
24
+ Completed retries return a saved result. Uncertain in-flight requests are
25
+ rejected instead of repeating an external side effect.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ service,
32
+ audience,
33
+ edges,
34
+ tokens,
35
+ issuer,
36
+ tasks,
37
+ policy,
38
+ checkpoints,
39
+ handler: Callable,
40
+ delegations=None,
41
+ ):
42
+ self.service = service
43
+ self.audience = audience
44
+ self.edges = edges
45
+ self.tokens = tokens
46
+ self.issuer = issuer
47
+ self.tasks = tasks
48
+ self.policy = policy
49
+ self.checkpoints = checkpoints
50
+ self.handler = handler
51
+ self.delegations = delegations
52
+
53
+ async def invoke(self, request, token):
54
+ edge = self.edges[request.edge_id]
55
+ if (
56
+ edge.operation != request.operation
57
+ or request.arguments.get("resource") != request.permission.resource
58
+ or not self.policy.authorize(
59
+ edge.permissions, request.permission
60
+ ).allowed
61
+ ):
62
+ raise PermissionError("Invocation binding mismatch")
63
+ task = self.tasks.load(request.task_id)
64
+ if (
65
+ task.status != "active"
66
+ or task.expires_at <= int(time.time())
67
+ or task.tenant != request.permission.tenant
68
+ ):
69
+ raise PermissionError("Task is inactive or expired")
70
+ claims = await self.tokens.verify(
71
+ token, issuer=self.issuer, audience=self.audience, leeway_s=0
72
+ )
73
+ if not {"sub", "exp", "task_id"}.issubset(claims):
74
+ raise PermissionError("Required token claims are missing")
75
+ if claims["task_id"] != request.task_id:
76
+ raise PermissionError("Token belongs to another task")
77
+ if edge.delegated:
78
+ if self.delegations is None:
79
+ raise PermissionError("Delegation is not configured")
80
+ grant = await self.delegations.verify(
81
+ token, self.audience, request.permission
82
+ )
83
+ if (
84
+ grant.holder != self.service
85
+ or claims.get("act", {}).get("sub") != edge.caller
86
+ ):
87
+ raise PermissionError("Delegated recipient/caller mismatch")
88
+ context = InvocationContext(
89
+ self.service,
90
+ request.task_id,
91
+ grant.grant_id,
92
+ request.parent_execution_id,
93
+ )
94
+ else:
95
+ if claims["sub"] != edge.caller or claims.get(
96
+ "permission"
97
+ ) != asdict(request.permission):
98
+ raise PermissionError("Workload credential mismatch")
99
+ context = InvocationContext(
100
+ self.service,
101
+ request.task_id,
102
+ execution_id=request.parent_execution_id,
103
+ )
104
+ key = f"invocation:{self.service}:{request.invocation_id}"
105
+ digest = hashlib.sha256(
106
+ encode_request(request) + edge.caller.encode()
107
+ ).hexdigest()
108
+ record = {"digest": digest, "status": "dispatching"}
109
+ try:
110
+ self.checkpoints.create(RunCheckpoint(key, 0, json.dumps(record)))
111
+ except RunConflictError:
112
+ saved = json.loads(self.checkpoints.load(key).payload)
113
+ if saved["digest"] != digest:
114
+ raise PermissionError("Invocation ID was reused")
115
+ if saved["status"] != "completed":
116
+ raise RuntimeError(
117
+ "Invocation outcome requires reconciliation"
118
+ )
119
+ return InvocationResult(request.invocation_id, saved["value"])
120
+ try:
121
+ value = await self.handler(request, context)
122
+ payload = json.dumps(
123
+ {**record, "status": "completed", "value": value}
124
+ )
125
+ except BaseException:
126
+ self.checkpoints.save(
127
+ RunCheckpoint(
128
+ key, 0, json.dumps({**record, "status": "failed"})
129
+ )
130
+ )
131
+ raise
132
+ self.checkpoints.save(RunCheckpoint(key, 0, payload))
133
+ return InvocationResult(request.invocation_id, value)
134
+
135
+ async def __call__(self, method, path, headers, body):
136
+ if method != "POST" or path != "/invocations":
137
+ return 404, {}, b""
138
+ try:
139
+ if len(body) > 1_048_576:
140
+ raise ValueError("Request is too large")
141
+ normalized = {k.lower(): v for k, v in headers.items()}
142
+ authorization = normalized.get("authorization", "")
143
+ if not authorization.startswith("Bearer "):
144
+ raise PermissionError("Missing credential")
145
+ result = await self.invoke(
146
+ decode_request(body), authorization.removeprefix("Bearer ")
147
+ )
148
+ return (
149
+ 200,
150
+ {"content-type": "application/json"},
151
+ encode_result(result),
152
+ )
153
+ except PermissionError:
154
+ return 403, {}, b""
155
+ except (ValueError, KeyError, TypeError):
156
+ return 400, {}, b""
157
+ except Exception:
158
+ return 500, {}, b""
159
+
160
+ async def asgi(self, scope, receive, send):
161
+ """Adapt HttpApp explicitly to ASGI; transport still hosts the app."""
162
+ if scope["type"] != "http":
163
+ raise ValueError("Only HTTP scopes are supported")
164
+ body = bytearray()
165
+ while True:
166
+ event = await receive()
167
+ if event["type"] == "http.disconnect":
168
+ return
169
+ body.extend(event.get("body", b""))
170
+ if len(body) > 1_048_576:
171
+ await send(
172
+ {
173
+ "type": "http.response.start",
174
+ "status": 413,
175
+ "headers": [],
176
+ }
177
+ )
178
+ await send({"type": "http.response.body", "body": b""})
179
+ return
180
+ if not event.get("more_body"):
181
+ break
182
+ status, headers, response = await self(
183
+ scope["method"],
184
+ scope["path"],
185
+ {
186
+ k.decode("latin1"): v.decode("latin1")
187
+ for k, v in scope["headers"]
188
+ },
189
+ bytes(body),
190
+ )
191
+ await send(
192
+ {
193
+ "type": "http.response.start",
194
+ "status": status,
195
+ "headers": [
196
+ (k.encode(), v.encode()) for k, v in headers.items()
197
+ ],
198
+ }
199
+ )
200
+ await send({"type": "http.response.body", "body": response})
@@ -0,0 +1,73 @@
1
+ """Interchangeable standing-workload and delegated authority strategies."""
2
+
3
+ from dataclasses import asdict
4
+ from typing import Literal
5
+
6
+ from pydantic import Field
7
+ from swarmauri_base.ComponentBase import ComponentBase
8
+ from swarmauri_base.invocations import AuthorityStrategyBase
9
+ from swarmauri_core.delegation import IDelegationService
10
+ from swarmauri_core.permissions import IPermissionPolicy, Permission
11
+ from swarmauri_core.tokens import ITokenService
12
+
13
+
14
+ @ComponentBase.register_type(
15
+ AuthorityStrategyBase, "DelegatedAuthorityStrategy"
16
+ )
17
+ class DelegatedAuthorityStrategy(AuthorityStrategyBase):
18
+ """Narrow a task grant for the configured receiving workload."""
19
+
20
+ type: Literal["DelegatedAuthorityStrategy"] = "DelegatedAuthorityStrategy"
21
+ delegations: IDelegationService = Field(exclude=True, repr=False)
22
+ recipient: str
23
+
24
+ async def credential(self, request, context, audience):
25
+ if context.task_id != request.task_id or not context.grant_id:
26
+ raise PermissionError("A matching task grant is required")
27
+ parent = self.delegations.validate(
28
+ context.grant_id, context.actor, request.permission
29
+ )
30
+ if parent.task_id != request.task_id:
31
+ raise PermissionError("Grant belongs to another task")
32
+ child = self.delegations.delegate(
33
+ parent.grant_id,
34
+ context.actor,
35
+ self.recipient,
36
+ (request.permission,),
37
+ )
38
+ credential = await self.delegations.credential(
39
+ child.grant_id, context.actor, audience, request.permission
40
+ )
41
+ return credential.token
42
+
43
+
44
+ @ComponentBase.register_type(
45
+ AuthorityStrategyBase, "WorkloadAuthorityStrategy"
46
+ )
47
+ class WorkloadAuthorityStrategy(AuthorityStrategyBase):
48
+ """Use standing service permissions without inheriting user authority."""
49
+
50
+ type: Literal["WorkloadAuthorityStrategy"] = "WorkloadAuthorityStrategy"
51
+ tokens: ITokenService = Field(exclude=True, repr=False)
52
+ policy: IPermissionPolicy = Field(exclude=True, repr=False)
53
+ permissions: dict[str, tuple[Permission, ...]]
54
+ issuer: str
55
+ kid: str
56
+ algorithm: str = "RS256"
57
+
58
+ async def credential(self, request, context, audience):
59
+ available = self.permissions.get(context.actor, ())
60
+ if not self.policy.authorize(available, request.permission).allowed:
61
+ raise PermissionError("Workload permission denied")
62
+ return await self.tokens.mint(
63
+ {
64
+ "sub": context.actor,
65
+ "task_id": context.task_id,
66
+ "permission": asdict(request.permission),
67
+ },
68
+ alg=self.algorithm,
69
+ kid=self.kid,
70
+ issuer=self.issuer,
71
+ audience=audience,
72
+ lifetime_s=120,
73
+ )
@@ -0,0 +1,46 @@
1
+ """Strict JSON invocation encoding shared by local and HTTP delivery."""
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+
6
+ from swarmauri_core.invocations import InvocationRequest, InvocationResult
7
+ from swarmauri_core.permissions import Permission
8
+
9
+
10
+ def encode_request(request):
11
+ return json.dumps(asdict(request), sort_keys=True).encode()
12
+
13
+
14
+ def decode_request(body):
15
+ data = json.loads(body)
16
+ expected = {
17
+ "invocation_id",
18
+ "edge_id",
19
+ "task_id",
20
+ "operation",
21
+ "permission",
22
+ "arguments",
23
+ "parent_execution_id",
24
+ }
25
+ if not isinstance(data, dict) or set(data) != expected:
26
+ raise ValueError("Invalid invocation envelope")
27
+ if not isinstance(data["arguments"], dict):
28
+ raise ValueError("Arguments must be a mapping")
29
+ for name in ("invocation_id", "edge_id", "task_id", "operation"):
30
+ if not isinstance(data[name], str) or not data[name]:
31
+ raise ValueError("Invalid invocation identity")
32
+ data["permission"] = Permission(**data["permission"])
33
+ return InvocationRequest(**data)
34
+
35
+
36
+ def encode_result(result):
37
+ return json.dumps(asdict(result)).encode()
38
+
39
+
40
+ def decode_result(body, expected_id):
41
+ data = json.loads(body)
42
+ if set(data) != {"invocation_id", "value"}:
43
+ raise ValueError("Invalid invocation result")
44
+ if data["invocation_id"] != expected_id:
45
+ raise ValueError("Invocation result identity mismatch")
46
+ return InvocationResult(**data)