bazaar-compute 0.3.0rc17__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.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-compute
3
+ Version: 0.3.0rc17
4
+ Summary: The Bazaar Compute Application
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: bazaar-core~=0.3.0rc1
8
+ Requires-Dist: bazaar-contrib-config~=0.3.0rc1
9
+ Requires-Dist: bazaar-contrib-config-versions~=0.3.0rc1
10
+ Requires-Dist: bazaar-contrib-manager~=0.3.0rc1
11
+ Requires-Dist: bazaar-contrib-invoke~=0.3.0rc1
12
+ Requires-Dist: click>=8.1.0
13
+ Requires-Dist: bazaar-contrib-node-management~=0.3.0rc1 ; extra == 'node'
14
+ Requires-Python: >=3.15
15
+ Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
16
+ Provides-Extra: node
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Bazaar Compute Node
20
+
21
+ Bring Your Own Agents to the bazaar, and build with your teams in the open.
22
+
23
+ 不必独自建造——带上你的智能体,来集市。
24
+
25
+ <p align="left">
26
+ <a href="https://github.com/yuchanns/bazaar-compute-node/actions"><img
27
+ src="https://github.com/yuchanns/bazaar-compute-node/actions/workflows/release.yml/badge.svg"
28
+ alt="Release"
29
+ /></a>
30
+ <a href="https://pypi.org/project/bazaar-compute-node"><img
31
+ src="https://img.shields.io/pypi/v/bazaar-compute-node.svg"
32
+ alt="Python Package Index"
33
+ /></a>
34
+ </p>
35
+
36
+ **Documentation is coming soon...**
37
+
38
+ ## Quick Start / 快速开始
39
+
40
+ Python 3.15+ is required.
41
+
42
+ 需要 Python 3.15 或更高版本:
43
+
44
+ ```sh
45
+ uv tool install bazaar-compute-node
46
+ bcn contrib add codex --enable
47
+ bcn contrib add telegram --enable
48
+ bcn agent add \
49
+ --name Tifa \
50
+ --channel telegram \
51
+ --harness codex \
52
+ --set channel.token_env=BCN_TELEGRAM_TIFA_TOKEN
53
+
54
+ # Set BCN_TELEGRAM_TIFA_TOKEN in the shell, then start the node.
55
+ bcn run
56
+ ```
57
+
58
+ Contrib packages and enabled entries are saved in `~/.bcn/config.toml`:
59
+
60
+ ```toml
61
+ version = "5"
62
+
63
+ [[contribs]]
64
+ package = "bazaar-contrib-logging==0.3.*"
65
+ [[contribs.enabled]]
66
+ entry = "logging"
67
+ [contribs.enabled.config]
68
+ level = "info"
69
+ ```
70
+
71
+ Use `bcn --configer-options ./config.toml run` to select another file.
72
+ See [agent commands](contrib/agent-command/README.md) for conversation approval.
73
+
74
+ ## Features / 功能
75
+
76
+ - ✅ Done / 已完成
77
+ - 🚧 Working in progress / 开发中
78
+
79
+ ### Facilities / 通用能力
80
+
81
+ | Status / 状态 | Ability / 能力 |
82
+ | --- | --- |
83
+ | ✅ | Reminders / 定时器 |
84
+ | ✅ | Attachments / 附件 |
85
+ | ✅ | Multi-Agents / 多智能体 |
86
+ | ✅ | Teams / 团队协作 |
87
+
88
+ ### Channels / 渠道
89
+
90
+ | Status / 状态 | Channel / 渠道 |
91
+ | --- | --- |
92
+ | ✅ | WeCom / 企业微信 |
93
+ | ✅ | Telegram |
94
+ | ✅ | Lark / 飞书 |
95
+ | 🚧 | GitHub |
96
+ | 🚧 | GitLab |
97
+
98
+ ### Harnesses
99
+
100
+ | Status / 状态 | Runtime / 运行时 |
101
+ | --- | --- |
102
+ | ✅ | Codex |
103
+ | ✅ | Claude Code |
104
+ | 🚧 | Pi |
105
+ | 🚧 | Hermes Agent |
106
+ | 🚧 | DeepSeek Harness |
107
+
108
+ ### Platforms / 平台
109
+
110
+ | Status / 状态 | Platform / 平台 |
111
+ | --- | --- |
112
+ | ✅ | Windows |
113
+ | ✅ | macOS |
114
+ | ✅ | Linux |
115
+
116
+ ## License / 许可证
117
+
118
+ This project is licensed under the [Apache License 2.0](./LICENSE).
119
+ 本项目采用 [Apache License 2.0](./LICENSE) 许可证。
120
+
121
+ ## Credits / 致谢
122
+
123
+ This project is inspired by [raft.build](https://raft.build).
124
+ 本项目的灵感来自 [raft.build](https://raft.build)。
@@ -0,0 +1,10 @@
1
+ bazaar_compute_node/__init__.py,sha256=faGEuftFU8Y96wa1OTxneszffwrH7Oo6ELowIBxSVOg,719
2
+ bazaar_compute_node/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
3
+ bazaar_compute_node/boot.py,sha256=9BF2tmlkIpcTtspsWcJaTOB53UWc22akDP24lIK7XbM,8183
4
+ bazaar_compute_node/cli.py,sha256=H9Xry0eC1l1KLmYAcqrbIU76d1ZX0b93X3Ndqn9kOyY,6610
5
+ bazaar_compute_node/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
+ bazaar_compute-0.3.0rc17.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
7
+ bazaar_compute-0.3.0rc17.dist-info/WHEEL,sha256=xTCBFIZIIyRSxyowOv5Wqg_jFU6KsdIffuulBB09Ph8,80
8
+ bazaar_compute-0.3.0rc17.dist-info/entry_points.txt,sha256=5OGargpNC-qZ2GvKzK59IBHr-rRDh2-omctB0Ixj0hw,54
9
+ bazaar_compute-0.3.0rc17.dist-info/METADATA,sha256=n4q-sEOtcBpSapW4YXwFQ9LZAnbGC2XIuMRyYr7VGts,3126
10
+ bazaar_compute-0.3.0rc17.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ bcn = bazaar_compute_node.cli:main
3
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,24 @@
1
+ """Application entry into the shared contrib composition framework."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ lazy from collections.abc import AsyncIterator, Awaitable, Callable
7
+
8
+ lazy from bazaar_core import Composition, ContribEntry, ContribHub
9
+
10
+ __all__ = ["run"]
11
+
12
+
13
+ @asynccontextmanager
14
+ async def run(
15
+ bootstrap: Composition,
16
+ load: ContribEntry,
17
+ *,
18
+ prepare: Callable[[ContribHub], Awaitable[None]] | None = None,
19
+ ) -> AsyncIterator[ContribHub]:
20
+ """Run a caller's bootstrap and loader in one concrete instance graph."""
21
+ async with ContribHub().run(bootstrap, load) as hub:
22
+ if prepare is not None:
23
+ await prepare(hub)
24
+ yield hub
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,254 @@
1
+ """Node bootstrap inputs, packaged combinations, and concrete input graphs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ lazy import asyncio
7
+ lazy import importlib
8
+ lazy from collections.abc import AsyncIterator, Callable, Mapping, Sequence
9
+ lazy from importlib.metadata import entry_points
10
+ lazy from typing import Any
11
+
12
+ lazy from bazaar_contrib_config import (
13
+ CONFIG_PREPARE,
14
+ CONFIG_PREPARED,
15
+ CONFIG_STORE,
16
+ CONFIGURATION,
17
+ ConfigDocument,
18
+ ConfigFormatError,
19
+ Configuration,
20
+ ConfigurationEnvironment,
21
+ ContribPackage,
22
+ EnabledContrib,
23
+ configuration,
24
+ )
25
+ lazy from bazaar_contrib_config_versions import VERSIONS
26
+ lazy from bazaar_contrib_manager import CONTRIB_MANAGER, ContribManager
27
+ lazy from bazaar_core import (
28
+ Composition,
29
+ Context,
30
+ Contrib,
31
+ ContribEntry,
32
+ ContribHub,
33
+ ContribSpec,
34
+ discover,
35
+ load,
36
+ )
37
+
38
+ lazy from . import run
39
+
40
+ DEFAULTS = "bazaar_compute_node.defaults"
41
+
42
+
43
+ def defaults() -> dict[str, Any]:
44
+ """Merge the default configurations of installed packages in entry name order.
45
+
46
+ A package several of them declare is declared once, enabling each entry once."""
47
+ merged: dict[str, Any] = {}
48
+ declared: dict[str, dict[str, Any]] = {}
49
+ enabled: set[str] = set()
50
+ for point in sorted(entry_points(group=DEFAULTS), key=lambda point: point.name):
51
+ document = point.load()()
52
+ merged.setdefault("version", document["version"])
53
+ indexes = merged.setdefault("contrib_indexes", [])
54
+ for index in document.get("contrib_indexes", ()):
55
+ if index not in indexes:
56
+ indexes.append(index)
57
+ for package in document.get("contribs", ()):
58
+ entries = [
59
+ entry
60
+ for entry in package.get("enabled", ())
61
+ if entry["entry"] not in enabled
62
+ ]
63
+ enabled.update(entry["entry"] for entry in entries)
64
+ name = ContribPackage.model_validate(package).distribution
65
+ if name in declared:
66
+ declared[name]["enabled"].extend(entries)
67
+ else:
68
+ declared[name] = package | {"enabled": entries}
69
+ merged.setdefault("contribs", []).append(declared[name])
70
+ return merged
71
+
72
+
73
+ def build(document: ConfigDocument) -> Composition:
74
+ """Load enabled contrib declarations without interpreting their business input."""
75
+ return load(
76
+ [
77
+ ContribSpec(
78
+ contrib=entry.entry,
79
+ config=entry.config,
80
+ location=f"contribs[{index}].enabled[{position}]",
81
+ )
82
+ for index, package in enumerate(document.contribs)
83
+ if package.applies
84
+ for position, entry in enumerate(package.enabled)
85
+ ]
86
+ )
87
+
88
+
89
+ def bootstrap(
90
+ *,
91
+ configer: str = "config-filesystem",
92
+ configer_options: Sequence[str] = (),
93
+ start: Callable[[ConfigDocument], Composition] | None = None,
94
+ document: Mapping[str, object] | None = None,
95
+ ) -> tuple[Composition, ContribEntry]:
96
+ definitions = load(
97
+ [
98
+ ContribSpec(
99
+ contrib=configer,
100
+ config={"options": configer_options} if configer_options else {},
101
+ location="--configer/--configer-options/--config",
102
+ required_offers=[CONFIG_STORE],
103
+ ),
104
+ *VERSIONS,
105
+ ]
106
+ )
107
+ if definitions.diagnostics:
108
+ raise ConfigFormatError(
109
+ "; ".join(
110
+ f"{record.name}: {record.state}" for record in definitions.diagnostics
111
+ )
112
+ )
113
+ entries = []
114
+ for entry in definitions.entries:
115
+ config = entry.definition.validate_config(entry.config, context=definitions)
116
+ entries.append(
117
+ EnabledContrib(
118
+ entry=entry.name,
119
+ config=config.model_dump(mode="json") if config is not None else {},
120
+ )
121
+ )
122
+ if document is None:
123
+ document = defaults()
124
+ return (
125
+ definitions,
126
+ ContribEntry(
127
+ name="node-configuration",
128
+ definition=configuration(
129
+ document,
130
+ build,
131
+ environment=ConfigurationEnvironment(
132
+ hub="bazaar_core:ContribHub",
133
+ entries=tuple(entries),
134
+ ),
135
+ start=start,
136
+ ),
137
+ location=DEFAULTS,
138
+ ),
139
+ )
140
+
141
+
142
+ @asynccontextmanager
143
+ async def node(
144
+ *,
145
+ configer: str = "config-filesystem",
146
+ configer_options: Sequence[str] = (),
147
+ start: Callable[[ConfigDocument], Composition] | None = None,
148
+ ) -> AsyncIterator[ContribHub]:
149
+ """Prepare configured dependencies before selecting business definitions."""
150
+
151
+ packages: list[ContribPackage] = []
152
+ if configer == "config-filesystem" and not any(
153
+ source.name == configer for source in await asyncio.to_thread(discover)
154
+ ):
155
+ packages.append(
156
+ ContribPackage(package="bazaar-contrib-config-filesystem~=0.3.0rc1")
157
+ )
158
+ # The host installed alone runs as a node.
159
+ if not await asyncio.to_thread(entry_points, group=DEFAULTS):
160
+ packages.append(
161
+ ContribPackage(package="bazaar-contrib-node-management~=0.3.0rc1")
162
+ )
163
+ if packages:
164
+ managers: list[ContribManager] = []
165
+
166
+ @asynccontextmanager
167
+ async def observe_manager(ctx: Context):
168
+ managers.append(ctx.accept(CONTRIB_MANAGER))
169
+ yield
170
+
171
+ document = ConfigDocument(
172
+ contribs=(
173
+ *packages,
174
+ ContribPackage(
175
+ enabled=(
176
+ EnabledContrib(entry="commands"),
177
+ EnabledContrib(entry="contrib-manager"),
178
+ )
179
+ ),
180
+ )
181
+ )
182
+ entries, loader = await asyncio.to_thread(
183
+ bootstrap,
184
+ configer="config-memory",
185
+ document=document.model_dump(mode="json"),
186
+ )
187
+ async with (
188
+ run(entries, loader) as hub,
189
+ hub.enable(
190
+ Composition(
191
+ entries=[
192
+ ContribEntry(
193
+ name="bootstrap-manager",
194
+ definition=Contrib(
195
+ accepts=[CONTRIB_MANAGER], lifespan=observe_manager
196
+ ),
197
+ )
198
+ ]
199
+ )
200
+ ),
201
+ ):
202
+ Configuration.check(hub)
203
+ result = await managers[0].bootstrap()
204
+ if result.error:
205
+ raise ConfigFormatError(result.error)
206
+ await asyncio.to_thread(importlib.invalidate_caches)
207
+
208
+ configurations: list[Configuration] = []
209
+ preparers: list[str] = []
210
+ prepared = asyncio.Semaphore(0)
211
+
212
+ @asynccontextmanager
213
+ async def dependencies(ctx: Context):
214
+ configurations.append(ctx.accept(CONFIGURATION))
215
+ yield
216
+
217
+ def initial(document: ConfigDocument) -> Composition:
218
+ composition = build(document)
219
+ preparers.extend(
220
+ entry.name
221
+ for entry in composition.entries
222
+ if CONFIG_PREPARE in entry.definition.listen
223
+ )
224
+ entry = ContribEntry(
225
+ name="node-dependencies",
226
+ definition=Contrib(
227
+ accepts=[CONFIGURATION],
228
+ lifespan=dependencies,
229
+ listen={CONFIG_PREPARED: lambda ctx, _: prepared.release()},
230
+ ),
231
+ )
232
+ return composition.model_copy(
233
+ update={
234
+ "entries": (*composition.entries, entry),
235
+ "roots": (entry.name, *preparers),
236
+ }
237
+ )
238
+
239
+ entries, loader = await asyncio.to_thread(
240
+ bootstrap,
241
+ configer=configer,
242
+ configer_options=configer_options,
243
+ start=initial,
244
+ )
245
+
246
+ async def prepare(hub: ContribHub) -> None:
247
+ Configuration.check(hub)
248
+ await hub.announce(CONFIG_PREPARE, None)
249
+ for _ in preparers:
250
+ await prepared.acquire()
251
+ await configurations[0].select(start)
252
+
253
+ async with run(entries, loader, prepare=prepare) as hub:
254
+ yield hub
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import asynccontextmanager
4
+ lazy import asyncio
5
+ lazy import signal
6
+ lazy import sys
7
+ lazy from collections.abc import Sequence
8
+
9
+ import click
10
+ from bazaar_contrib_config import CONFIGURATION, ConfigDocument, Configuration
11
+ from bazaar_contrib_invoke import (
12
+ COMMANDS,
13
+ RUN,
14
+ CommandCatalog,
15
+ CommandEntry,
16
+ Commands,
17
+ Run,
18
+ contribs,
19
+ table,
20
+ )
21
+ from bazaar_core import Composition, Context, Contrib, ContribEntry
22
+
23
+ lazy from .boot import build, node
24
+
25
+
26
+ async def serve(ctx: Context, configuration: Configuration, run: Run) -> None:
27
+ loop = asyncio.get_running_loop()
28
+ if sys.platform != "win32":
29
+ loop.add_signal_handler(signal.SIGTERM, run.stopped.set)
30
+ try:
31
+ await configuration.activate()
32
+ await asyncio.to_thread(
33
+ click.echo,
34
+ table(contribs(ctx.snapshots), ("Contrib", "State", "Result")),
35
+ )
36
+ await asyncio.to_thread(click.echo, "bcn ready")
37
+ await run.stopped.wait()
38
+ finally:
39
+ if sys.platform != "win32":
40
+ loop.remove_signal_handler(signal.SIGTERM)
41
+
42
+
43
+ @asynccontextmanager
44
+ async def lifespan(ctx: Context):
45
+ commands = ctx.accept(COMMANDS)
46
+ configuration = ctx.accept(CONFIGURATION)
47
+ serving = ctx.accept(RUN)
48
+
49
+ @click.command("run", help=command_entry.help, short_help=command_entry.help)
50
+ def run():
51
+ return serve(ctx, configuration, serving)
52
+
53
+ with commands.register(run):
54
+ yield
55
+
56
+
57
+ command_entry = CommandEntry(
58
+ contrib="run", help="Run the node, serving until it is stopped."
59
+ )
60
+ running = ContribEntry(
61
+ name=command_entry.contrib,
62
+ definition=Contrib(accepts=[COMMANDS, CONFIGURATION, RUN], lifespan=lifespan),
63
+ )
64
+
65
+
66
+ async def dispatch(
67
+ args: Sequence[str],
68
+ *,
69
+ prog_name: str | None,
70
+ configer: str,
71
+ configer_options: tuple[str, ...],
72
+ ) -> None:
73
+ failures: list[click.ClickException | click.exceptions.Exit | click.Abort] = []
74
+ roots: list[str] = []
75
+ selected: list[Commands] = []
76
+
77
+ def start(document: ConfigDocument) -> Composition:
78
+ catalog = CommandCatalog(
79
+ contribs=(
80
+ *(
81
+ entry.entry
82
+ for package in document.contribs
83
+ if package.applies
84
+ for entry in package.enabled
85
+ ),
86
+ ),
87
+ entries={"run": command_entry},
88
+ help=main.help,
89
+ params=main.params,
90
+ )
91
+ composition = build(document)
92
+ try:
93
+ entry = catalog.select(args, prog_name=prog_name)
94
+ if entry is command_entry:
95
+ composition = composition.model_copy(
96
+ update={"entries": (*composition.entries, running)}
97
+ )
98
+ if entry is not None:
99
+ roots.append(entry.contrib)
100
+ except (click.ClickException, click.exceptions.Exit, click.Abort) as error:
101
+ failures.append(error)
102
+ return composition.model_copy(update={"roots": tuple(roots)})
103
+
104
+ @asynccontextmanager
105
+ async def observe(ctx: Context):
106
+ commands = ctx.accept(COMMANDS)
107
+ commands.help = main.help
108
+ commands.params.extend(main.params)
109
+ selected.append(commands)
110
+ yield
111
+
112
+ async with node(
113
+ start=start, configer=configer, configer_options=configer_options
114
+ ) as hub:
115
+ Configuration.check(hub.validate(Composition()))
116
+ if roots:
117
+ async with hub.enable(
118
+ Composition(
119
+ entries=[
120
+ ContribEntry(
121
+ name="command-dispatch",
122
+ definition=Contrib(accepts=[COMMANDS], lifespan=observe),
123
+ )
124
+ ]
125
+ )
126
+ ):
127
+ try:
128
+ await selected[0].dispatch(args, prog_name=prog_name)
129
+ except (
130
+ click.ClickException,
131
+ click.exceptions.Exit,
132
+ click.Abort,
133
+ ) as error:
134
+ failures.append(error)
135
+ if failures:
136
+ raise failures[0]
137
+
138
+
139
+ NODE_OPTIONS = {
140
+ "--configer": "configer",
141
+ "--configer-options": "configer_options",
142
+ "--config": "configer_options",
143
+ }
144
+
145
+
146
+ @click.command(
147
+ add_help_option=False,
148
+ context_settings={
149
+ "allow_extra_args": True,
150
+ "ignore_unknown_options": True,
151
+ "allow_interspersed_args": False,
152
+ },
153
+ )
154
+ @click.version_option(package_name="bazaar-compute")
155
+ @click.option(
156
+ "--configer",
157
+ default="config-filesystem",
158
+ show_default=True,
159
+ help="Configuration contrib to use.",
160
+ )
161
+ @click.option(
162
+ "--configer-options",
163
+ multiple=True,
164
+ metavar="OPTION",
165
+ help="Option passed to the configuration contrib; may be repeated.",
166
+ )
167
+ @click.option(
168
+ "--config",
169
+ "configer_options",
170
+ multiple=True,
171
+ metavar="OPTION",
172
+ help="Legacy alias for --configer-options.",
173
+ )
174
+ @click.pass_context
175
+ def main(ctx: click.Context, configer: str, configer_options: tuple[str, ...]) -> None:
176
+ """Run Bazaar Compute Node."""
177
+ # 0.2 also took node options after the command; those replace earlier ones.
178
+ args: list[str] = []
179
+ after: dict[str, list[str]] = {}
180
+ remaining = iter(ctx.args)
181
+ for arg in remaining:
182
+ name, equals, value = arg.partition("=")
183
+ if name not in NODE_OPTIONS:
184
+ args.append(arg)
185
+ continue
186
+ if not equals:
187
+ value = next(remaining, None)
188
+ if value is None:
189
+ raise click.BadParameter("requires a value", param_hint=name)
190
+ after.setdefault(NODE_OPTIONS[name], []).append(value)
191
+ if "configer" in after:
192
+ configer = after["configer"][-1]
193
+ if "configer_options" in after:
194
+ configer_options = tuple(after["configer_options"])
195
+ try:
196
+ asyncio.run(
197
+ dispatch(
198
+ args,
199
+ prog_name=ctx.info_name,
200
+ configer=configer,
201
+ configer_options=configer_options,
202
+ )
203
+ )
204
+ except click.exceptions.Exit as error:
205
+ ctx.exit(error.exit_code)
206
+ except click.ClickException, click.Abort:
207
+ raise
208
+ except Exception as error:
209
+ pending: list[BaseException] = [error]
210
+ errors: list[str] = []
211
+ while pending:
212
+ error = pending.pop()
213
+ if isinstance(error, BaseExceptionGroup):
214
+ pending.extend(error.exceptions)
215
+ else:
216
+ errors.append(str(error))
217
+ raise click.ClickException("; ".join(errors)) from error
@@ -0,0 +1 @@
1
+