bazaar-contrib-agent-command 0.3.0rc1__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,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,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-contrib-agent-command
3
+ Version: 0.3.0rc1
4
+ Summary: Agent configuration and local conversation-review commands
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: bazaar-core~=0.3.0rc1
8
+ Requires-Dist: bazaar-contrib-agent~=0.3.0rc1
9
+ Requires-Dist: bazaar-contrib-channel~=0.3.0rc1
10
+ Requires-Dist: bazaar-contrib-harness~=0.3.0rc1
11
+ Requires-Dist: bazaar-contrib-config~=0.3.0rc1
12
+ Requires-Dist: bazaar-contrib-invoke~=0.3.0rc1
13
+ Requires-Dist: bazaar-contrib-sidecar~=0.3.0rc1
14
+ Requires-Dist: bazaar-contrib-collaboration~=0.3.0rc1
15
+ Requires-Dist: bazaar-contrib-messages~=0.3.0rc1
16
+ Requires-Dist: click>=8.1.0
17
+ Requires-Dist: jinja2>=3.1.6
18
+ Requires-Dist: pydantic>=2.12.0
19
+ Requires-Python: >=3.15
20
+ Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
21
+ Description-Content-Type: text/markdown
22
+
23
+ # bazaar-contrib-agent-command
24
+
25
+ Manage agents and approve or deny conversations.
26
+
27
+ ```sh
28
+ bcn contrib add agent-command --enable
29
+ ```
30
+
31
+ The corresponding entry in `config.toml`:
32
+
33
+ ```toml
34
+ version = "5"
35
+
36
+ [[contribs]]
37
+ package = "bazaar-contrib-agent-command~=0.3.0rc1"
38
+ [[contribs.enabled]]
39
+ entry = "agent-command"
40
+ ```
41
+
42
+ ```sh
43
+ bcn agent list
44
+ bcn agent add --name Desk --channel CHANNEL_KIND --harness HARNESS_KIND
45
+ bcn agent edit Desk --set agent.idle_timeout=300
46
+ bcn agent remove Desk
47
+ bcn agent review list AGENT_ID
48
+ bcn agent review approve THREAD_ID
49
+ bcn agent review deny THREAD_ID
50
+ ```
@@ -0,0 +1,28 @@
1
+ # bazaar-contrib-agent-command
2
+
3
+ Manage agents and approve or deny conversations.
4
+
5
+ ```sh
6
+ bcn contrib add agent-command --enable
7
+ ```
8
+
9
+ The corresponding entry in `config.toml`:
10
+
11
+ ```toml
12
+ version = "5"
13
+
14
+ [[contribs]]
15
+ package = "bazaar-contrib-agent-command~=0.3.0rc1"
16
+ [[contribs.enabled]]
17
+ entry = "agent-command"
18
+ ```
19
+
20
+ ```sh
21
+ bcn agent list
22
+ bcn agent add --name Desk --channel CHANNEL_KIND --harness HARNESS_KIND
23
+ bcn agent edit Desk --set agent.idle_timeout=300
24
+ bcn agent remove Desk
25
+ bcn agent review list AGENT_ID
26
+ bcn agent review approve THREAD_ID
27
+ bcn agent review deny THREAD_ID
28
+ ```
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "bazaar-contrib-agent-command"
3
+ version = "0.3.0rc1"
4
+ description = "Agent configuration and local conversation-review commands"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.15"
9
+ dependencies = [
10
+ "bazaar-core~=0.3.0rc1",
11
+ "bazaar-contrib-agent~=0.3.0rc1",
12
+ "bazaar-contrib-channel~=0.3.0rc1",
13
+ "bazaar-contrib-harness~=0.3.0rc1",
14
+ "bazaar-contrib-config~=0.3.0rc1",
15
+ "bazaar-contrib-invoke~=0.3.0rc1",
16
+ "bazaar-contrib-sidecar~=0.3.0rc1",
17
+ "bazaar-contrib-collaboration~=0.3.0rc1",
18
+ "bazaar-contrib-messages~=0.3.0rc1",
19
+ "click>=8.1.0",
20
+ "jinja2>=3.1.6",
21
+ "pydantic>=2.12.0",
22
+ ]
23
+
24
+ [project.entry-points."bazaar_compute_node.contribs"]
25
+ agent-command = "bazaar_contrib_agent_command:commands"
26
+
27
+ [project.entry-points."bazaar_compute_node.commands"]
28
+ agent = "bazaar_contrib_agent_command:command_entry"
29
+
30
+ [project.urls]
31
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.13.0,<0.14.0"]
35
+ build-backend = "uv_build"
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "-p no:anyio"
40
+ asyncio_mode = "auto"
41
+ asyncio_default_fixture_loop_scope = "function"
42
+
43
+ [tool.pyright]
44
+ extends = "../../pyrightconfig.json"
45
+ include = [
46
+ "src",
47
+ "tests",
48
+ ]
49
+
50
+ [tool.ruff]
51
+ extend = "../../pyproject.toml"
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "bazaar-contrib-agent-command"
3
+ version = "0.3.0rc1"
4
+ description = "Agent configuration and local conversation-review commands"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.15"
9
+ dependencies = [
10
+ "bazaar-core~=0.3.0rc1",
11
+ "bazaar-contrib-agent~=0.3.0rc1",
12
+ "bazaar-contrib-channel~=0.3.0rc1",
13
+ "bazaar-contrib-harness~=0.3.0rc1",
14
+ "bazaar-contrib-config~=0.3.0rc1",
15
+ "bazaar-contrib-invoke~=0.3.0rc1",
16
+ "bazaar-contrib-sidecar~=0.3.0rc1",
17
+ "bazaar-contrib-collaboration~=0.3.0rc1",
18
+ "bazaar-contrib-messages~=0.3.0rc1",
19
+ "click>=8.1.0",
20
+ "jinja2>=3.1.6",
21
+ "pydantic>=2.12.0",
22
+ ]
23
+
24
+ [project.entry-points."bazaar_compute_node.contribs"]
25
+ agent-command = "bazaar_contrib_agent_command:commands"
26
+
27
+ [project.entry-points."bazaar_compute_node.commands"]
28
+ agent = "bazaar_contrib_agent_command:command_entry"
29
+
30
+ [project.urls]
31
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.13.0,<0.14.0"]
35
+ build-backend = "uv_build"
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "-p no:anyio"
40
+ asyncio_mode = "auto"
41
+ asyncio_default_fixture_loop_scope = "function"
42
+
43
+ [tool.pyright]
44
+ extends = "../../pyrightconfig.json"
45
+ include = ["src", "tests"]
46
+
47
+ [tool.ruff]
48
+ extend = "../../pyproject.toml"
@@ -0,0 +1,80 @@
1
+ """Register independent Agent management commands through the public services."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from contextlib import asynccontextmanager
7
+ from typing import Self
8
+
9
+ from bazaar_contrib_channel import ChannelBuilderConfig
10
+ from bazaar_contrib_config import CONFIGURATION
11
+ from bazaar_contrib_harness import HarnessBuilderConfig
12
+ from bazaar_contrib_invoke import COMMANDS, CommandEntry
13
+ from bazaar_contrib_sidecar import CLIENT
14
+ from bazaar_core import Composition, Context, Contrib, ServiceKey
15
+ from pydantic import BaseModel, ConfigDict, PrivateAttr, ValidationInfo, model_validator
16
+
17
+ from .management import AgentConfiguration, AgentManagement
18
+
19
+ __all__ = [
20
+ "AGENT_CONFIGURATION",
21
+ "AgentConfiguration",
22
+ "AgentManagement",
23
+ "command_entry",
24
+ "commands",
25
+ ]
26
+
27
+
28
+ class Config(BaseModel):
29
+ model_config = ConfigDict(extra="forbid", frozen=True)
30
+ _channels: tuple[str, ...] = PrivateAttr(default=())
31
+ _harnesses: tuple[str, ...] = PrivateAttr(default=())
32
+
33
+ @model_validator(mode="after")
34
+ def declarations(self, info: ValidationInfo) -> Self:
35
+ if isinstance(info.context, Composition):
36
+ channels: list[str] = []
37
+ harnesses: list[str] = []
38
+ for entry in info.context.entries:
39
+ model = entry.definition.config
40
+ if model is not None and issubclass(model, ChannelBuilderConfig):
41
+ channels.append(model.kind)
42
+ elif model is not None and issubclass(model, HarnessBuilderConfig):
43
+ harnesses.append(model.kind)
44
+ self._channels = tuple(channels)
45
+ self._harnesses = tuple(harnesses)
46
+ return self
47
+
48
+
49
+ AGENT_CONFIGURATION = ServiceKey[AgentManagement]("agent.configuration")
50
+ command_entry = CommandEntry(
51
+ contrib="agent-command",
52
+ help="Manage agents",
53
+ )
54
+
55
+
56
+ @asynccontextmanager
57
+ async def lifespan(ctx: Context, config: Config):
58
+ from .cli import create_commands
59
+
60
+ client = ctx.accept(CLIENT)
61
+ timeout = client.timeout
62
+ client.timeout = None
63
+ try:
64
+ service = AgentManagement(
65
+ ctx.accept(CONFIGURATION), client, config._channels, config._harnesses
66
+ )
67
+ ctx.offer(AGENT_CONFIGURATION, service)
68
+ command = await asyncio.to_thread(create_commands, service, client)
69
+ with ctx.accept(COMMANDS).register(command):
70
+ yield
71
+ finally:
72
+ client.timeout = timeout
73
+
74
+
75
+ commands = Contrib(
76
+ config=Config,
77
+ accepts=[CONFIGURATION, COMMANDS, CLIENT],
78
+ offers=[AGENT_CONFIGURATION],
79
+ lifespan=lifespan,
80
+ )
@@ -0,0 +1,341 @@
1
+ """Agent configuration and local admission-review commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import tomllib
7
+ from collections.abc import Awaitable, Callable, Iterable
8
+ from copy import deepcopy
9
+ from typing import TYPE_CHECKING, Any, Literal
10
+
11
+ import click
12
+ from bazaar_contrib_sidecar import Client, Construct, Symbol
13
+ from jinja2 import Environment, PackageLoader, StrictUndefined
14
+ from pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validator
15
+
16
+ if TYPE_CHECKING:
17
+ from .management import AgentManagement
18
+
19
+
20
+ class Option(BaseModel):
21
+ scope: Literal["agent", "channel", "harness"]
22
+ path: str = Field(
23
+ pattern=r"^(?:[0-9]+\.)?[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$"
24
+ )
25
+ value: Any
26
+
27
+ @model_validator(mode="before")
28
+ @classmethod
29
+ def parse(cls, value: Any) -> Any:
30
+ if not isinstance(value, str):
31
+ return value
32
+ try:
33
+ path, raw = value.split("=", 1)
34
+ scope, path = path.split(".", 1)
35
+ except ValueError as error:
36
+ raise ValueError("Use SCOPE.KEY=VALUE") from error
37
+ if scope == "agent" and path == "id":
38
+ raise ValueError("Agent IDs are generated and remain stable")
39
+ if scope != "agent" and path.split(".")[-1] == "kind":
40
+ raise ValueError(f"Use --{scope} to select a provider")
41
+ if scope == "harness" and path.split(".")[-1] == "env":
42
+ name, equals, source = raw.partition("=")
43
+ if not equals or not name or not source:
44
+ raise ValueError("Use harness.env=NAME=SOURCE_NAME")
45
+ parsed = {name: source}
46
+ else:
47
+ try:
48
+ parsed = tomllib.loads(f"value = {raw}")["value"]
49
+ except tomllib.TOMLDecodeError:
50
+ parsed = raw
51
+ return {"scope": scope, "path": path, "value": parsed}
52
+
53
+
54
+ def parameters(
55
+ current: dict[str, Any],
56
+ *,
57
+ name: str | None,
58
+ channel: tuple[str, ...],
59
+ harness: tuple[str, ...],
60
+ options: tuple[str, ...],
61
+ ) -> dict[str, Any]:
62
+ try:
63
+ settings = TypeAdapter(tuple[Option, ...]).validate_python(options)
64
+ except ValidationError as error:
65
+ raise click.BadParameter(str(error), param_hint="--set") from error
66
+ values = deepcopy(current)
67
+ if name is not None:
68
+ values["name"] = name
69
+ for scope, selected in (("channel", channel), ("harness", harness)):
70
+ if selected:
71
+ existing = list(values.get(scope, ()))
72
+ providers = []
73
+ for kind in selected:
74
+ match = next(
75
+ (
76
+ index
77
+ for index, item in enumerate(existing)
78
+ if item["kind"] == kind
79
+ ),
80
+ None,
81
+ )
82
+ providers.append(
83
+ existing.pop(match) if match is not None else {"kind": kind}
84
+ )
85
+ values[scope] = providers
86
+ seen = set()
87
+ for option in settings:
88
+ identity = option.scope, option.path
89
+ if identity in seen and option.path.split(".")[-1] != "env":
90
+ raise click.BadParameter(
91
+ f"duplicate --set option: {option.scope}.{option.path}"
92
+ )
93
+ seen.add(identity)
94
+ names = option.path.split(".")
95
+ target = values
96
+ if option.scope != "agent":
97
+ providers = values.get(option.scope, ())
98
+ position = int(names.pop(0)) if names[0].isdecimal() else 0
99
+ if position >= len(providers):
100
+ raise click.BadParameter(
101
+ f"{option.scope} provider position {position} is not configured"
102
+ )
103
+ target = providers[position]
104
+ for key in names[:-1]:
105
+ target = target.setdefault(key, {})
106
+ key = names[-1]
107
+ if key == "env" and option.scope == "harness":
108
+ target.setdefault(key, {}).update(option.value)
109
+ else:
110
+ target[key] = option.value
111
+ return values
112
+
113
+
114
+ def table(rows: Iterable[tuple[str, ...]], headers: tuple[str, ...]) -> str:
115
+ rows = list(rows)
116
+ widths = [max(map(len, column)) for column in zip(headers, *rows, strict=True)]
117
+ return "\n".join(
118
+ " ".join(
119
+ value.ljust(width) for value, width in zip(row, widths, strict=True)
120
+ ).rstrip()
121
+ for row in (headers, tuple("-" * width for width in widths), *rows)
122
+ )
123
+
124
+
125
+ def create_commands(service: AgentManagement, client: Client) -> click.Group:
126
+ templates = Environment(
127
+ loader=PackageLoader("bazaar_contrib_agent_command", "resources"),
128
+ undefined=StrictUndefined,
129
+ autoescape=False,
130
+ auto_reload=False,
131
+ trim_blocks=True,
132
+ lstrip_blocks=True,
133
+ )
134
+ templates.filters["table"] = table
135
+
136
+ async def execute(
137
+ operation: Awaitable[Any],
138
+ template: str,
139
+ *,
140
+ rows: Callable[[Any], Iterable[tuple[str, ...]]] | None = None,
141
+ err: bool = False,
142
+ **context: object,
143
+ ):
144
+ try:
145
+ result = await operation
146
+ output = await asyncio.to_thread(
147
+ lambda: templates.get_template(template).render(
148
+ result=result, rows=rows(result) if rows else (), **context
149
+ )
150
+ )
151
+ await asyncio.to_thread(click.echo, output.rstrip("\n"), err=err)
152
+ except click.ClickException:
153
+ raise
154
+ except Exception as error:
155
+ raise click.ClickException(str(error)) from error
156
+
157
+ @click.group("agent", help="Manage agents")
158
+ def agent():
159
+ pass
160
+
161
+ @agent.command("list", help="List agents")
162
+ def list_agents():
163
+ return execute(
164
+ service.read(),
165
+ "agents.tpl",
166
+ rows=lambda result: (
167
+ (
168
+ agent.id,
169
+ agent.name,
170
+ ", ".join(provider.kind for provider in agent.channel),
171
+ ", ".join(provider.kind for provider in agent.harness),
172
+ )
173
+ for agent in result.agents
174
+ ),
175
+ )
176
+
177
+ @agent.command("add", help="Add an agent")
178
+ @click.option("--name", required=True, metavar="NAME", help="The name of the agent")
179
+ @click.option(
180
+ "--channel",
181
+ multiple=True,
182
+ required=True,
183
+ type=click.Choice(tuple(service.channels)),
184
+ help="The channel providers to use",
185
+ )
186
+ @click.option(
187
+ "--harness",
188
+ multiple=True,
189
+ required=True,
190
+ type=click.Choice(tuple(service.harnesses)),
191
+ help="The harness providers to use",
192
+ )
193
+ @click.option(
194
+ "--set",
195
+ "options",
196
+ multiple=True,
197
+ metavar="SCOPE.KEY=VALUE",
198
+ help="Override an agent, channel, or harness setting",
199
+ )
200
+ def add(name, channel, harness, options):
201
+ values = parameters(
202
+ {}, name=name, channel=channel, harness=harness, options=options
203
+ )
204
+ return execute(
205
+ service.add(values), "agent_changed.tpl", action="Added", err=True
206
+ )
207
+
208
+ @agent.command("edit", help="Update an agent")
209
+ @click.argument("selector", metavar="AGENT")
210
+ @click.option("--name", metavar="NAME", help="The name of the agent")
211
+ @click.option(
212
+ "--channel",
213
+ multiple=True,
214
+ type=click.Choice(tuple(service.channels)),
215
+ help="The channel providers to use, replacing the current list",
216
+ )
217
+ @click.option(
218
+ "--harness",
219
+ multiple=True,
220
+ type=click.Choice(tuple(service.harnesses)),
221
+ help="The harness providers to use, replacing the current list",
222
+ )
223
+ @click.option(
224
+ "--set",
225
+ "options",
226
+ multiple=True,
227
+ metavar="SCOPE.KEY=VALUE",
228
+ help="Override an agent, channel, or harness setting",
229
+ )
230
+ def edit(selector, name, channel, harness, options):
231
+ async def update():
232
+ snapshot = await service.read()
233
+ current = service.select(snapshot.agents, selector)
234
+ values = parameters(
235
+ current.model_dump(mode="python"),
236
+ name=name,
237
+ channel=channel,
238
+ harness=harness,
239
+ options=options,
240
+ )
241
+ return await service.edit(
242
+ selector, values, expected_revision=snapshot.revision
243
+ )
244
+
245
+ return execute(update(), "agent_changed.tpl", action="Updated", err=True)
246
+
247
+ @agent.command("remove", help="Remove an agent")
248
+ @click.argument("selector", metavar="AGENT")
249
+ def remove(selector):
250
+ return execute(
251
+ service.remove(selector), "agent_changed.tpl", action="Removed", err=True
252
+ )
253
+
254
+ @agent.group("review", help="Review conversations")
255
+ def review():
256
+ pass
257
+
258
+ async def contact_review(
259
+ agent_id: str | None, decision: str | None, thread_id: str | None = None
260
+ ):
261
+ collaboration = await client.context.call(
262
+ "accept", Symbol("bazaar_contrib_collaboration:COLLABORATION")
263
+ )
264
+ if decision is not None:
265
+ snapshot = await service.read()
266
+ messages = await client.context.call(
267
+ "accept", Symbol("bazaar_contrib_messages:MESSAGES")
268
+ )
269
+ thread = Construct("bazaar_contrib_messages:Thread", {"id": thread_id})
270
+ for agent in snapshot.agents:
271
+ storage = await messages.call(
272
+ "storage",
273
+ Construct("bazaar_contrib_messages:Agent", {"id": agent.id}),
274
+ )
275
+ if await storage.call("get_thread", thread) is not None:
276
+ agent_id = agent.id
277
+ break
278
+ else:
279
+ raise ValueError(f"conversation not found: {thread_id}")
280
+ owner = Construct("bazaar_contrib_messages:Agent", {"id": agent_id})
281
+ contacts = await collaboration.call("for_agent", owner)
282
+ if decision is None:
283
+ messages = await contacts.get("messages")
284
+ inbox = await messages.call(
285
+ "check_inbox",
286
+ owner,
287
+ pending_only=False,
288
+ limit=None,
289
+ review=Construct(
290
+ "bazaar_contrib_messages.states:Review", {"value": "pending"}
291
+ ),
292
+ )
293
+ rows = []
294
+ for target in await inbox.get("targets"):
295
+ rows.append(
296
+ {
297
+ key: await target.get(key)
298
+ for key in ("thread_id", "channel", "target", "review")
299
+ }
300
+ )
301
+ return rows
302
+ session = await contacts.call(
303
+ "review_contact",
304
+ Construct("bazaar_contrib_messages:Thread", {"id": thread_id}),
305
+ Construct("bazaar_contrib_messages.states:Review", {"value": decision}),
306
+ )
307
+ return await session.get("review")
308
+
309
+ @review.command("list", help="List pending conversations")
310
+ @click.argument("agent_id")
311
+ def pending(agent_id):
312
+ return execute(
313
+ contact_review(agent_id, None),
314
+ "agent_reviews.tpl",
315
+ rows=lambda result: (
316
+ (target["thread_id"], target["channel"], target["target"])
317
+ for target in result
318
+ ),
319
+ )
320
+
321
+ @review.command("approve", help="Approve a conversation")
322
+ @click.argument("thread_id")
323
+ def approve(thread_id):
324
+ return execute(
325
+ contact_review(None, "approved", thread_id),
326
+ "agent_reviewed.tpl",
327
+ thread_id=thread_id,
328
+ err=True,
329
+ )
330
+
331
+ @review.command("deny", help="Deny a conversation")
332
+ @click.argument("thread_id")
333
+ def deny(thread_id):
334
+ return execute(
335
+ contact_review(None, "denied", thread_id),
336
+ "agent_reviewed.tpl",
337
+ thread_id=thread_id,
338
+ err=True,
339
+ )
340
+
341
+ return agent
@@ -0,0 +1,176 @@
1
+ """Manage Agent configuration through its public model and selected carrier."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from copy import deepcopy
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+ from uuid import uuid7
10
+
11
+ from bazaar_contrib_agent import AgentConfig, Config
12
+ from bazaar_contrib_config import (
13
+ ConfigConflict,
14
+ ConfigDocument,
15
+ Configuration,
16
+ ConfigurationApplication,
17
+ ConfigurationEnvironment,
18
+ )
19
+ from bazaar_contrib_sidecar import Client, Symbol
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class AgentConfiguration:
24
+ agents: tuple[AgentConfig, ...]
25
+ revision: str | None
26
+
27
+
28
+ class AgentManagement:
29
+ """Edit saved Agent entities without acquiring their running instances."""
30
+
31
+ def __init__(
32
+ self,
33
+ configuration: Configuration,
34
+ client: Client,
35
+ channels: tuple[str, ...],
36
+ harnesses: tuple[str, ...],
37
+ ):
38
+ self.configuration = configuration
39
+ self.client = client
40
+ self.channels = channels
41
+ self.harnesses = harnesses
42
+
43
+ async def _read(self) -> tuple[dict[str, Any], Config, str | None]:
44
+ candidate, snapshot = await self.configuration.read()
45
+ document = ConfigDocument.model_validate(candidate.payload)
46
+ entry = next(
47
+ (
48
+ entry
49
+ for package in document.contribs
50
+ if package.applies
51
+ for entry in package.enabled
52
+ if entry.entry == "agent"
53
+ ),
54
+ None,
55
+ )
56
+ if entry is None:
57
+ raise ValueError("The agent contrib is not enabled")
58
+ return (
59
+ deepcopy(candidate.payload),
60
+ Config.model_validate(entry.config),
61
+ snapshot.revision if snapshot is not None else None,
62
+ )
63
+
64
+ async def _save(
65
+ self, payload: dict[str, Any], config: Config, revision: str | None
66
+ ) -> None:
67
+ document = ConfigDocument.model_validate(payload)
68
+ for index, package in enumerate(document.contribs):
69
+ if not package.applies:
70
+ continue
71
+ for position, entry in enumerate(package.enabled):
72
+ if entry.entry == "agent":
73
+ payload["contribs"][index]["enabled"][position]["config"] = (
74
+ config.model_dump(mode="json", exclude_none=True)
75
+ )
76
+ if self.configuration.start is not None:
77
+ try:
78
+ configuration = await self.client.context.call(
79
+ "accept", Symbol("bazaar_contrib_config:CONFIGURATION")
80
+ )
81
+ except FileNotFoundError, ConnectionRefusedError:
82
+ await self.configuration.commit(payload, expected_revision=revision)
83
+ return
84
+ environment = await configuration.get("environment")
85
+ environment = (
86
+ ConfigurationEnvironment.model_validate(
87
+ await environment.call("model_dump", mode="json")
88
+ )
89
+ if environment is not None
90
+ else None
91
+ )
92
+ if (
93
+ environment.model_dump(mode="json") if environment is not None else None
94
+ ) != (
95
+ self.configuration.environment.model_dump(mode="json")
96
+ if self.configuration.environment is not None
97
+ else None
98
+ ):
99
+ raise ValueError(
100
+ "the sidecar belongs to another configuration; "
101
+ "select its configuration or endpoint"
102
+ )
103
+ _, snapshot = await configuration.call("read")
104
+ if (
105
+ await snapshot.get("revision") if snapshot is not None else None
106
+ ) != revision:
107
+ raise ConfigConflict(
108
+ "the sidecar configuration differs from the selected source"
109
+ )
110
+ snapshot = await configuration.call(
111
+ "commit", payload, expected_revision=revision
112
+ )
113
+ result = await configuration.call("apply", snapshot)
114
+ result = ConfigurationApplication.model_validate(
115
+ await result.call("model_dump", mode="json")
116
+ )
117
+ else:
118
+ snapshot = await self.configuration.commit(
119
+ payload, expected_revision=revision
120
+ )
121
+ result = await self.configuration.apply(snapshot)
122
+ if result.error is not None or not result.applied:
123
+ raise ValueError(
124
+ f"configuration saved but not applied: {result.error}"
125
+ if result.error
126
+ else "configuration saved but not applied"
127
+ )
128
+
129
+ async def read(self) -> AgentConfiguration:
130
+ _, config, revision = await self._read()
131
+ return AgentConfiguration(config.agents, revision)
132
+
133
+ @staticmethod
134
+ def select(agents: tuple[AgentConfig, ...], selector: str) -> AgentConfig:
135
+ matches = [agent for agent in agents if selector in (agent.id, agent.name)]
136
+ if not matches:
137
+ raise ValueError(f"Agent not found: {selector}")
138
+ if len(matches) > 1:
139
+ raise ValueError(f"Agent selector is ambiguous: {selector}")
140
+ return matches[0]
141
+
142
+ async def add(self, values: Mapping[str, object]) -> AgentConfig:
143
+ payload, config, revision = await self._read()
144
+ agent = AgentConfig.model_validate({**values, "id": str(uuid7())})
145
+ await self._save(payload, Config(agents=(*config.agents, agent)), revision)
146
+ return agent
147
+
148
+ async def edit(
149
+ self,
150
+ selector: str,
151
+ values: Mapping[str, object],
152
+ *,
153
+ expected_revision: str | None,
154
+ ) -> AgentConfig:
155
+ payload, config, _ = await self._read()
156
+ current = self.select(config.agents, selector)
157
+ agent = AgentConfig.model_validate(
158
+ {**current.model_dump(mode="python"), **values, "id": current.id}
159
+ )
160
+ config = Config(
161
+ agents=tuple(
162
+ agent if item.id == current.id else item for item in config.agents
163
+ )
164
+ )
165
+ await self._save(payload, config, expected_revision)
166
+ return agent
167
+
168
+ async def remove(self, selector: str) -> AgentConfig:
169
+ payload, config, revision = await self._read()
170
+ agent = self.select(config.agents, selector)
171
+ await self._save(
172
+ payload,
173
+ Config(agents=tuple(item for item in config.agents if item.id != agent.id)),
174
+ revision,
175
+ )
176
+ return agent
@@ -0,0 +1,4 @@
1
+ {{ action }} agent `{{ result.name }}` (`{{ result.id }}`)
2
+ {% if action == 'Removed' %}
3
+ Workspace and data preserved
4
+ {% endif %}
@@ -0,0 +1 @@
1
+ {{ result | capitalize }} conversation `{{ thread_id }}`
@@ -0,0 +1,5 @@
1
+ {% if result %}
2
+ {{ rows | table(("Thread", "Channel", "Target")) }}
3
+ {% else %}
4
+ No pending conversations
5
+ {% endif %}
@@ -0,0 +1,5 @@
1
+ {% if result.agents %}
2
+ {{ rows | table(("ID", "Name", "Channels", "Harnesses")) }}
3
+ {% else %}
4
+ No agents
5
+ {% endif %}