bazaar-contrib-collaboration 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,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-contrib-collaboration
3
+ Version: 0.3.0rc1
4
+ Summary: Conversation admission, review and identity association services
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: bazaar-contrib-legacy-node-migrations~=0.3.0rc1
8
+ Requires-Dist: bazaar-core~=0.3.0rc1
9
+ Requires-Dist: bazaar-contrib-schema~=0.3.0rc1
10
+ Requires-Dist: bazaar-contrib-audit~=0.3.0rc1
11
+ Requires-Dist: bazaar-contrib-channel~=0.3.0rc1
12
+ Requires-Dist: bazaar-contrib-messages~=0.3.0rc1
13
+ Requires-Dist: bazaar-contrib-storage~=0.3.0rc1
14
+ Requires-Dist: bazaar-contrib-timer~=0.3.0rc1
15
+ Requires-Dist: pydantic>=2.12.0
16
+ Requires-Python: >=3.15
17
+ Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "bazaar-contrib-collaboration"
3
+ version = "0.3.0rc1"
4
+ description = "Conversation admission, review and identity association services"
5
+ license = "Apache-2.0"
6
+ license-files = ["LICENSE"]
7
+ requires-python = ">=3.15"
8
+ dependencies = [
9
+ "bazaar-contrib-legacy-node-migrations~=0.3.0rc1",
10
+ "bazaar-core~=0.3.0rc1",
11
+ "bazaar-contrib-schema~=0.3.0rc1",
12
+ "bazaar-contrib-audit~=0.3.0rc1",
13
+ "bazaar-contrib-channel~=0.3.0rc1",
14
+ "bazaar-contrib-messages~=0.3.0rc1",
15
+ "bazaar-contrib-storage~=0.3.0rc1",
16
+ "bazaar-contrib-timer~=0.3.0rc1",
17
+ "pydantic>=2.12.0",
18
+ ]
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
22
+
23
+ [project.entry-points."bazaar_compute_node.contribs"]
24
+ collaboration = "bazaar_contrib_collaboration:collaboration"
25
+
26
+ [build-system]
27
+ requires = ["uv_build>=0.13.0,<0.14.0"]
28
+ build-backend = "uv_build"
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
32
+ addopts = "-p no:anyio"
33
+ asyncio_mode = "auto"
34
+ asyncio_default_fixture_loop_scope = "function"
35
+
36
+ [tool.pyright]
37
+ extends = "../../pyrightconfig.json"
38
+ include = [
39
+ "src",
40
+ "tests",
41
+ ]
42
+ extraPaths = [
43
+ "../agent/tests/fixtures/workbench/src",
44
+ "tests/fixtures/gateway/src",
45
+ ]
46
+
47
+ [tool.ruff]
48
+ extend = "../../pyproject.toml"
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "bazaar-contrib-collaboration"
3
+ version = "0.3.0rc1"
4
+ description = "Conversation admission, review and identity association services"
5
+ license = "Apache-2.0"
6
+ license-files = ["LICENSE"]
7
+ requires-python = ">=3.15"
8
+ dependencies = ["bazaar-contrib-legacy-node-migrations~=0.3.0rc1", "bazaar-core~=0.3.0rc1", "bazaar-contrib-schema~=0.3.0rc1", "bazaar-contrib-audit~=0.3.0rc1", "bazaar-contrib-channel~=0.3.0rc1", "bazaar-contrib-messages~=0.3.0rc1", "bazaar-contrib-storage~=0.3.0rc1", "bazaar-contrib-timer~=0.3.0rc1", "pydantic>=2.12.0"]
9
+
10
+ [project.urls]
11
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
12
+
13
+ [project.entry-points."bazaar_compute_node.contribs"]
14
+ collaboration = "bazaar_contrib_collaboration:collaboration"
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.13.0,<0.14.0"]
18
+ build-backend = "uv_build"
19
+
20
+ [tool.pytest.ini_options]
21
+ testpaths = ["tests"]
22
+ addopts = "-p no:anyio"
23
+ asyncio_mode = "auto"
24
+ asyncio_default_fixture_loop_scope = "function"
25
+
26
+ [tool.pyright]
27
+ extends = "../../pyrightconfig.json"
28
+ include = ["src", "tests"]
29
+ extraPaths = ["../agent/tests/fixtures/workbench/src", "tests/fixtures/gateway/src"]
30
+
31
+ [tool.ruff]
32
+ extend = "../../pyproject.toml"
@@ -0,0 +1,106 @@
1
+ """Agent-owned admission, review and inbound conversation association."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator
6
+ from contextlib import asynccontextmanager
7
+
8
+ from bazaar_contrib_audit import AUDIT, Audit
9
+ from bazaar_contrib_channel import Channel, ChannelRetryPolicy, ChannelSender
10
+ from bazaar_contrib_legacy_node_migrations import LEGACY_NODE_MIGRATIONS
11
+ from bazaar_contrib_messages import (
12
+ MESSAGES,
13
+ Agent,
14
+ MessageService,
15
+ ThreadConcurrency,
16
+ )
17
+ from bazaar_contrib_schema import SCHEMA
18
+ from bazaar_contrib_storage import DB, Database
19
+ from bazaar_contrib_timer import TIMER, Timer
20
+ from bazaar_core import Context, Contrib, ServiceKey
21
+
22
+ from .events import CONTACT_REVIEWED, ContactReviewed
23
+ from .review import REVIEW_REPLY
24
+ from .schema import MODULE
25
+ from .service import CollaborationService
26
+ from .store import CollaborationStore
27
+
28
+ __all__ = [
29
+ "COLLABORATION",
30
+ "CONTACT_REVIEWED",
31
+ "REVIEW_REPLY",
32
+ "Collaboration",
33
+ "CollaborationService",
34
+ "CollaborationStore",
35
+ "ContactReviewed",
36
+ "collaboration",
37
+ ]
38
+
39
+
40
+ class Collaboration:
41
+ """Keep each agent's collaboration binding with its message service."""
42
+
43
+ def __init__(
44
+ self, database: Database, audit: Audit, timer: Timer, context: Context
45
+ ):
46
+ self.database = database
47
+ self.audit = audit
48
+ self.timer = timer
49
+ self.context = context
50
+ self._bindings: dict[Agent, CollaborationService] = {}
51
+
52
+ @asynccontextmanager
53
+ async def bind(
54
+ self,
55
+ *,
56
+ messages: MessageService,
57
+ concurrency: ThreadConcurrency,
58
+ channel: Channel,
59
+ provider_timeout: float,
60
+ ) -> AsyncIterator[CollaborationService]:
61
+ owner = messages.storage.owner
62
+ if owner in self._bindings:
63
+ raise ValueError(f"collaboration is already bound for agent: {owner.id}")
64
+ service = CollaborationService(
65
+ messages=messages,
66
+ storage=CollaborationStore(self.database, owner),
67
+ audit=self.audit,
68
+ concurrency=concurrency,
69
+ sender=ChannelSender(
70
+ channel,
71
+ self.timer,
72
+ policy=ChannelRetryPolicy(timeout=provider_timeout),
73
+ ),
74
+ context=self.context,
75
+ )
76
+ self._bindings[owner] = service
77
+ try:
78
+ yield service
79
+ finally:
80
+ del self._bindings[owner]
81
+
82
+ def for_agent(self, owner: Agent) -> CollaborationService:
83
+ service = self._bindings.get(owner)
84
+ if service is None:
85
+ raise ValueError("Agent is not available")
86
+ return service
87
+
88
+
89
+ COLLABORATION = ServiceKey[Collaboration]("collaboration")
90
+
91
+
92
+ @asynccontextmanager
93
+ async def lifespan(ctx: Context):
94
+ async with ctx.accept(SCHEMA).register(MODULE):
95
+ ctx.offer(
96
+ COLLABORATION,
97
+ Collaboration(ctx.accept(DB), ctx.accept(AUDIT), ctx.accept(TIMER), ctx),
98
+ )
99
+ yield
100
+
101
+
102
+ collaboration = Contrib(
103
+ accepts=[SCHEMA, LEGACY_NODE_MIGRATIONS, MESSAGES, DB, AUDIT, TIMER],
104
+ offers=[COLLABORATION],
105
+ lifespan=lifespan,
106
+ )
@@ -0,0 +1,17 @@
1
+ """Business events emitted after a durable admission decision."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from bazaar_contrib_messages import Agent, Thread
6
+ from bazaar_contrib_messages.states import Review
7
+ from bazaar_core import EventKey
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class ContactReviewed:
12
+ agent: Agent
13
+ thread: Thread
14
+ review: Review
15
+
16
+
17
+ CONTACT_REVIEWED = EventKey[ContactReviewed]("collaboration.contact.reviewed")
@@ -0,0 +1,8 @@
1
+ """The setting used to answer a conversation awaiting review."""
2
+
3
+ # the setting that holds what a conversation not yet let in is told, if
4
+ # anything, each time it writes
5
+ REVIEW_REPLY = "review.reply"
6
+
7
+
8
+ __all__ = ["REVIEW_REPLY"]
@@ -0,0 +1,19 @@
1
+ """Own this contrib's tables, schema baseline and append-only migrations."""
2
+
3
+ import bazaar_contrib_storage as s
4
+ from bazaar_contrib_schema import Dependency, Migration, ModuleSchema
5
+
6
+ from . import definitions
7
+
8
+ BASELINE = Migration(
9
+ version=1,
10
+ name="collaboration_schema",
11
+ operations=(s.CreateTable(table=definitions.SETTINGS_V31),),
12
+ )
13
+
14
+ MODULE = ModuleSchema(
15
+ tables=("handoffs", "settings"),
16
+ migrations=(BASELINE,),
17
+ baseline=BASELINE,
18
+ predecessor=Dependency(package="bazaar-contrib-legacy-node-migrations", version=32),
19
+ )
@@ -0,0 +1,14 @@
1
+ """Table and index definitions for this module and its published upgrades."""
2
+
3
+ import bazaar_contrib_storage as s
4
+
5
+ SETTINGS_V31 = s.Table(
6
+ name="settings",
7
+ columns=(
8
+ s.ColumnDefinition(name="agent_id", type="text"),
9
+ s.ColumnDefinition(name="key", type="text"),
10
+ s.ColumnDefinition(name="value", type="text"),
11
+ s.ColumnDefinition(name="updated_at_ms", type="integer"),
12
+ ),
13
+ primary_key=("agent_id", "key"),
14
+ )
@@ -0,0 +1,314 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import fields, replace
5
+ from time import time_ns
6
+ from typing import cast
7
+
8
+ from bazaar_contrib_audit import Audit, AuditContext
9
+ from bazaar_contrib_channel import ChannelSender, ChannelSendRequest, ChannelTarget
10
+ from bazaar_contrib_messages import (
11
+ Actor,
12
+ MessageService,
13
+ MessageSession,
14
+ Thread,
15
+ ThreadConcurrency,
16
+ )
17
+ from bazaar_contrib_messages.correlation import CorrelationContext
18
+ from bazaar_contrib_messages.delivery import from_receipt
19
+ from bazaar_contrib_messages.models import ChannelSession, InboundAttachment, Message
20
+ from bazaar_contrib_messages.operations import RecordInboundResult
21
+ from bazaar_contrib_messages.states import (
22
+ ErrorKind,
23
+ MessageDirection,
24
+ OutboundDeliveryState,
25
+ Review,
26
+ RuntimeEventState,
27
+ )
28
+ from bazaar_core import Context
29
+ from pydantic import JsonValue, TypeAdapter
30
+
31
+ from .events import CONTACT_REVIEWED, ContactReviewed
32
+ from .review import REVIEW_REPLY
33
+ from .store import CollaborationStore
34
+
35
+
36
+ class CollaborationService:
37
+ """Manage admission and review for one agent's conversations."""
38
+
39
+ def __init__(
40
+ self,
41
+ *,
42
+ messages: MessageService,
43
+ storage: CollaborationStore,
44
+ audit: Audit,
45
+ concurrency: ThreadConcurrency,
46
+ sender: ChannelSender,
47
+ context: Context,
48
+ ):
49
+ self.messages = messages
50
+ self.storage = storage
51
+ self._audit = audit
52
+ self._concurrency = concurrency
53
+ self._sender = sender
54
+ self._context = context
55
+
56
+ async def _publish(
57
+ self,
58
+ *,
59
+ event_name: str,
60
+ state: RuntimeEventState,
61
+ correlation: CorrelationContext,
62
+ metadata: Mapping[str, object] | None = None,
63
+ error_kind: ErrorKind | None = None,
64
+ error_message: str | None = None,
65
+ ) -> None:
66
+ # Convert identities only at the shared audit boundary.
67
+ at_ms = time_ns() // 1_000_000
68
+ payload: dict[str, object] = {
69
+ "event_name": event_name,
70
+ "state": state.value,
71
+ "created_at_ms": at_ms,
72
+ "correlation": {
73
+ f"{item.name}_id" if isinstance(value, Actor) else item.name: value.id
74
+ if isinstance(value, Actor)
75
+ else value
76
+ for item in fields(correlation)
77
+ if (value := getattr(correlation, item.name)) is not None
78
+ },
79
+ "metadata": dict(metadata or {}),
80
+ }
81
+ if error_kind is not None:
82
+ payload["error_kind"] = error_kind.value
83
+ if error_message is not None:
84
+ payload["error_message"] = error_message
85
+ await self._audit.publish(
86
+ event_name,
87
+ context=AuditContext(
88
+ agent_id=self.storage.owner.id,
89
+ channel=correlation.channel,
90
+ thread_id=correlation.thread_id,
91
+ message_id=correlation.outbound_message_id,
92
+ session_id=correlation.runtime_session_id,
93
+ turn_id=correlation.turn_id,
94
+ ),
95
+ payload=TypeAdapter(JsonValue).validate_python(payload),
96
+ occurred_at_ms=at_ms,
97
+ )
98
+
99
+ async def review_contact(
100
+ self, thread_id: Thread, decision: Review
101
+ ) -> ChannelSession:
102
+ async def update(storage: MessageSession) -> tuple[ChannelSession, Review]:
103
+ thread = await storage.get_thread(thread_id)
104
+ if thread is None:
105
+ raise ValueError(f"thread is not found: {thread_id.id}")
106
+ session = cast(
107
+ ChannelSession,
108
+ await storage.get_channel_session(thread.channel_session_id),
109
+ )
110
+ previous = session.review
111
+ session = replace(
112
+ session,
113
+ review=decision,
114
+ updated_at_ms=max(session.updated_at_ms, now_ms),
115
+ )
116
+ await storage.save_channel_session(session)
117
+ if previous is Review.PENDING and decision is Review.APPROVED:
118
+ await storage.activate_pending_inbound(thread_id)
119
+ return session, previous
120
+
121
+ async with self._concurrency.for_thread(thread_id):
122
+ now_ms = time_ns() // 1_000_000
123
+ session, previous = await self.messages.storage.write(update)
124
+ target = await self.messages.storage.resolve_inbox_target(
125
+ session.canonical_target
126
+ )
127
+ await self._publish(
128
+ event_name="channel.session.reviewed",
129
+ state=RuntimeEventState.COMPLETED,
130
+ correlation=CorrelationContext(
131
+ node_id=self.storage.owner.id,
132
+ thread_id=thread_id.id,
133
+ channel=session.channel,
134
+ channel_session_id=session.id,
135
+ ),
136
+ metadata={
137
+ "thread_id": thread_id.id,
138
+ "review": decision.value,
139
+ "target": session.canonical_target,
140
+ "target_name": target.display_target,
141
+ },
142
+ )
143
+ if session.review is not previous:
144
+ await self._context.announce(
145
+ CONTACT_REVIEWED,
146
+ ContactReviewed(self.storage.owner, thread_id, session.review),
147
+ )
148
+ return session
149
+
150
+ async def setting(self, key: str) -> str | None:
151
+ return await self.storage.get_setting(key)
152
+
153
+ async def set_setting(self, key: str, value: str) -> None:
154
+ await self.storage.set_setting(key, value, now_ms=time_ns() // 1_000_000)
155
+ # the value is not recorded: it is the operator's words, not a fact
156
+ await self._publish(
157
+ event_name="setting.changed",
158
+ state=RuntimeEventState.COMPLETED,
159
+ correlation=CorrelationContext(
160
+ node_id=self.storage.owner.id,
161
+ ),
162
+ metadata={"key": key},
163
+ )
164
+
165
+ async def record_inbound(
166
+ self,
167
+ message: Message[InboundAttachment],
168
+ ) -> RecordInboundResult | None:
169
+ channel, provider_thread_id, provider_message_id = message.inbound_identity()
170
+ delivery_states = {
171
+ OutboundDeliveryState.QUEUED,
172
+ OutboundDeliveryState.SENT,
173
+ }
174
+ if not message.notifies_runtime:
175
+ existing = await self.messages.storage.find_message(
176
+ channel,
177
+ provider_thread_id,
178
+ provider_message_id,
179
+ direction=MessageDirection.OUTBOUND,
180
+ )
181
+ if existing is not None and existing.delivery_state in delivery_states:
182
+ # Quiet context can refer to a message already in readable history.
183
+ return None
184
+ reference = message.metadata.get("provider_reply_to_message_id")
185
+ if message.reply_to_message_id is None and isinstance(reference, str):
186
+ parent = await self.messages.storage.find_message(
187
+ channel,
188
+ provider_thread_id,
189
+ reference,
190
+ direction=MessageDirection.OUTBOUND,
191
+ )
192
+ if parent is None or parent.delivery_state not in delivery_states:
193
+ parent = await self.messages.storage.find_message(
194
+ channel,
195
+ provider_thread_id,
196
+ reference,
197
+ direction=MessageDirection.INBOUND,
198
+ )
199
+ if parent is not None:
200
+ message = replace(message, reply_to_message_id=parent.message_id)
201
+ recorded = await self.messages.storage.record_inbound(
202
+ message,
203
+ now_ms=time_ns() // 1_000_000,
204
+ opening=(
205
+ Review.APPROVED
206
+ if message.metadata.get("review") == Review.APPROVED.value
207
+ else Review.PENDING
208
+ ),
209
+ )
210
+ message = recorded.message
211
+ if recorded.message_created:
212
+ await self._publish(
213
+ event_name="channel.inbound.persisted",
214
+ state=RuntimeEventState.COMPLETED,
215
+ correlation=CorrelationContext(
216
+ node_id=self.storage.owner.id,
217
+ channel=message.channel,
218
+ channel_session_id=message.channel_session_id,
219
+ thread_id=message.thread_id,
220
+ provider_thread_id=message.provider_thread_id,
221
+ inbound_seq=message.seq,
222
+ ),
223
+ metadata={
224
+ "notifies_runtime": message.notifies_runtime,
225
+ "review": recorded.channel_session.review.value,
226
+ "channel_session_mapping": (
227
+ "created" if recorded.channel_session_created else "reused"
228
+ ),
229
+ "thread_mapping": (
230
+ "created" if recorded.thread_created else "reused"
231
+ ),
232
+ # the sanitizer drops any key called body, and rightly so
233
+ # for provider payloads; the message text goes by its own name
234
+ "text": message.body,
235
+ "target": message.target,
236
+ "target_kind": message.target_kind.value,
237
+ "target_name": (
238
+ None
239
+ if message.target_presentation is None
240
+ else message.target_presentation.display_name
241
+ ),
242
+ "message_type": message.message_type,
243
+ "sender": (
244
+ None
245
+ if message.sender is None
246
+ else {
247
+ "id": message.sender.id,
248
+ "name": message.sender.name,
249
+ "display_name": message.sender.display_name,
250
+ "kind": message.sender_kind.value,
251
+ }
252
+ ),
253
+ "reply_to_message_id": message.reply_to_message_id,
254
+ "attachments": [
255
+ {
256
+ "name": attachment.name,
257
+ "media_type": attachment.media_type,
258
+ "size_bytes": attachment.size_bytes,
259
+ }
260
+ for attachment in message.attachments
261
+ ],
262
+ },
263
+ )
264
+ return recorded
265
+
266
+ async def answer_unreviewed(
267
+ self, message: Message[InboundAttachment], session: ChannelSession
268
+ ) -> None:
269
+ """Say to a conversation not yet let in what the agent is set to say,
270
+ if anything: the one word it gets, every time it writes."""
271
+
272
+ reply = await self.storage.get_setting(REVIEW_REPLY)
273
+ if not reply or message.provider_thread_id is None:
274
+ return
275
+ receipt = await self._sender.send(
276
+ ChannelSendRequest(
277
+ actor_id=message.thread_id,
278
+ body=reply,
279
+ attachments=(),
280
+ target=ChannelTarget(
281
+ kind=message.target_kind.value, thread_id=message.provider_thread_id
282
+ ),
283
+ channel=message.channel,
284
+ channel_identity=message.channel_identity,
285
+ )
286
+ )
287
+ result = from_receipt(receipt)
288
+ await self._publish(
289
+ event_name="channel.review.replied",
290
+ state=(
291
+ RuntimeEventState.COMPLETED
292
+ if result.state
293
+ in (OutboundDeliveryState.SENT, OutboundDeliveryState.QUEUED)
294
+ else RuntimeEventState.FAILED
295
+ ),
296
+ correlation=CorrelationContext(
297
+ node_id=self.storage.owner.id,
298
+ channel=message.channel,
299
+ channel_session_id=session.id,
300
+ thread_id=message.thread_id,
301
+ inbound_seq=message.seq,
302
+ ),
303
+ error_kind=(
304
+ None
305
+ if result.state
306
+ in (OutboundDeliveryState.SENT, OutboundDeliveryState.QUEUED)
307
+ else ErrorKind.PROVIDER_FAILED
308
+ ),
309
+ error_message=result.error_message,
310
+ metadata={
311
+ "review": session.review.value,
312
+ "delivery_state": result.state.value,
313
+ },
314
+ )
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import cast
4
+
5
+ from bazaar_contrib_messages import Agent
6
+ from bazaar_contrib_storage import (
7
+ All,
8
+ Column,
9
+ Compare,
10
+ Conflict,
11
+ Database,
12
+ Insert,
13
+ Select,
14
+ Value,
15
+ )
16
+
17
+
18
+ class CollaborationStore:
19
+ """What an agent is set to do, by key: text an operator can change while
20
+ the agent runs."""
21
+
22
+ def __init__(self, database: Database, owner: Agent):
23
+ self.database = database
24
+ self.owner = owner
25
+
26
+ async def get_setting(self, key: str) -> str | None:
27
+ rows = await self.database.read(
28
+ lambda session: session.select(
29
+ Select(
30
+ table="settings",
31
+ columns={"value": Column(name="value")},
32
+ where=All(
33
+ conditions=(
34
+ Compare(
35
+ left=Column(name="agent_id"),
36
+ operator="=",
37
+ right=Value(value=self.owner.id),
38
+ ),
39
+ Compare(
40
+ left=Column(name="key"),
41
+ operator="=",
42
+ right=Value(value=key),
43
+ ),
44
+ )
45
+ ),
46
+ )
47
+ )
48
+ )
49
+ return None if not rows else cast(str, rows[0]["value"])
50
+
51
+ async def set_setting(self, key: str, value: str, *, now_ms: int) -> None:
52
+ await self.database.write(
53
+ lambda session: session.insert(
54
+ Insert(
55
+ table="settings",
56
+ rows=(
57
+ {
58
+ "agent_id": self.owner.id,
59
+ "key": key,
60
+ "value": value,
61
+ "updated_at_ms": now_ms,
62
+ },
63
+ ),
64
+ conflict=Conflict(
65
+ columns=("agent_id", "key"), update=("value", "updated_at_ms")
66
+ ),
67
+ )
68
+ )
69
+ )