caura-bus-adapter-sdk 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 2026 Caura (https://caura.ai)
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,7 @@
1
+ Caura
2
+ Copyright 2026 Caura (https://caura.ai)
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ See the LICENSE file for the full license text.
6
+
7
+ "Caura" is a trademark of Caura.
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: caura-bus-adapter-sdk
3
+ Version: 0.3.0
4
+ Summary: SDK for building caura-bus adapters: connect, subscribe, gate on idle, consume
5
+ Author: Caura, Inc.
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/caura-ai/caura/tree/main/clients/collaboration
8
+ Project-URL: Source, https://github.com/caura-ai/caura
9
+ Project-URL: Changelog, https://github.com/caura-ai/caura/blob/main/clients/collaboration/CHANGELOG.md
10
+ Requires-Python: >=3.12
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: caura-bus-core==0.3.0
14
+ Dynamic: license-file
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "caura-bus-adapter-sdk"
3
+ version = "0.3.0" # x-release-please-version
4
+ description = "SDK for building caura-bus adapters: connect, subscribe, gate on idle, consume"
5
+ requires-python = ">=3.12"
6
+ license = { text = "Apache-2.0" }
7
+ authors = [{ name = "Caura, Inc." }]
8
+ dependencies = [
9
+ "caura-bus-core==0.3.0", # x-release-please-version
10
+ ]
11
+
12
+ [project.scripts]
13
+ caura-bus-adapter-echo = "caura_bus_adapter.echo:main"
14
+
15
+ [tool.uv.sources]
16
+ caura-bus-core = { workspace = true }
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/caura-ai/caura/tree/main/clients/collaboration"
20
+ Source = "https://github.com/caura-ai/caura"
21
+ Changelog = "https://github.com/caura-ai/caura/blob/main/clients/collaboration/CHANGELOG.md"
22
+
23
+ [build-system]
24
+ requires = ["setuptools>=75"]
25
+ build-backend = "setuptools.build_meta"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ """caura_bus_adapter — SDK for building caura-bus adapters."""
2
+
3
+ from .sdk import (
4
+ Adapter,
5
+ NoIdleGate,
6
+ adapter_main,
7
+ checkpoint,
8
+ configure_logging,
9
+ make_arg_parser,
10
+ run_adapter,
11
+ )
12
+
13
+ __all__ = [
14
+ "Adapter",
15
+ "NoIdleGate",
16
+ "adapter_main",
17
+ "configure_logging",
18
+ "checkpoint",
19
+ "make_arg_parser",
20
+ "run_adapter",
21
+ ]
@@ -0,0 +1,61 @@
1
+ """Deterministic demo responder: requests get one idempotent, correlated reply."""
2
+
3
+ from caura_bus_core import Envelope, SendMessage, load_config
4
+
5
+ from .sdk import NoIdleGate, adapter_main, checkpoint, configure_logging, connected_bus, run_adapter
6
+
7
+
8
+ class Responder(NoIdleGate):
9
+ supports_interrupt = True
10
+ capabilities = ["respond", "collaborate"]
11
+
12
+ def __init__(self, bus):
13
+ self.bus = bus
14
+
15
+ async def consume(self, env: Envelope):
16
+ if env.kind == "request":
17
+ # A structured task can ask this fixture to reach a consequential
18
+ # step. Caura evaluates the checkpoint; no action executes while pending.
19
+ import asyncio
20
+ import json
21
+
22
+ try:
23
+ task = json.loads(env.body)
24
+ except ValueError:
25
+ task = {}
26
+ if isinstance(task, dict) and task.get("action_type"):
27
+ await checkpoint(
28
+ checkpoint_key="before-action",
29
+ summary=task.get("summary", "Agent task"),
30
+ proposed_action=task.get("proposed_action", "Complete the requested action"),
31
+ action_type=task["action_type"],
32
+ confidence=task.get("confidence", 1),
33
+ missing_information=task.get("missing_information", []),
34
+ conflicting_results=task.get("conflicting_results", False),
35
+ )
36
+ if isinstance(task, dict) and task.get("work_seconds"):
37
+ await asyncio.sleep(min(float(task["work_seconds"]), 60))
38
+ decision = next((part for part in env.parts if part.get("type") == "caura_human_decision"), None)
39
+ body = f"Caura reply: {env.body}"
40
+ if decision and decision.get("action") == "redirect":
41
+ body = f"Caura redirected task: {decision['instructions']}"
42
+ await self.bus.send(
43
+ SendMessage(
44
+ to=[env.from_],
45
+ body=body,
46
+ kind="response",
47
+ reply_to=env.id,
48
+ ),
49
+ idempotency_key=f"reply:{env.id}",
50
+ )
51
+
52
+
53
+ async def run():
54
+ config = load_config()
55
+ async with connected_bus(config) as bus:
56
+ await run_adapter(config, Responder(bus))
57
+
58
+
59
+ if __name__ == "__main__":
60
+ configure_logging("INFO")
61
+ adapter_main(run())
@@ -0,0 +1,51 @@
1
+ """Echo adapter — the <30-LOC reference implementation.
2
+
3
+ Demonstrates the adapter-sdk surface. Logs every received envelope to
4
+ stdout and otherwise does nothing. Used by ``docker-compose.yml`` as
5
+ the two demo adapters that prove the bus is delivering end-to-end.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+
12
+ from caura_bus_core import Envelope, load_config, require_api_key
13
+
14
+ from .sdk import (
15
+ NoIdleGate,
16
+ adapter_main,
17
+ configure_logging,
18
+ make_arg_parser,
19
+ run_adapter,
20
+ )
21
+
22
+ log = logging.getLogger("caura-bus-adapter-echo")
23
+
24
+
25
+ class EchoAdapter(NoIdleGate):
26
+ supports_interrupt = True
27
+ capabilities = ["receive", "echo"]
28
+
29
+ async def consume(self, env: Envelope) -> None:
30
+ log.info(
31
+ "RECV msg_id=%s kind=%s from=%s thread=%s body=%r",
32
+ env.id,
33
+ env.kind,
34
+ env.from_,
35
+ env.thread_id,
36
+ env.body,
37
+ )
38
+
39
+
40
+ def main() -> None:
41
+ args = make_arg_parser(
42
+ "caura-bus-adapter-echo",
43
+ "Log every envelope addressed to this agent. Demo adapter.",
44
+ ).parse_args()
45
+ configure_logging(args.log_level)
46
+ require_api_key()
47
+ adapter_main(run_adapter(load_config(args.config), EchoAdapter()))
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,361 @@
1
+ """Adapter lifecycle with Caura delivery leases and explicit acknowledgements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import logging
8
+ import os
9
+ import signal
10
+ import time
11
+ import uuid
12
+ from collections.abc import Awaitable, Coroutine
13
+ from contextlib import asynccontextmanager
14
+ from contextvars import ContextVar
15
+ from pathlib import Path
16
+ from typing import Any, Protocol, runtime_checkable
17
+
18
+ import httpx
19
+ from caura_bus_core import (
20
+ CONFIG_ENV_VAR,
21
+ AgentConfig,
22
+ Bus,
23
+ Envelope,
24
+ )
25
+ from caura_bus_core.bus import RESYNC_EVENT, HumanRequired, PlatformError
26
+ from caura_bus_core.collaboration import Checkpoint, Presence
27
+ from caura_bus_core.retry import Backoff, transient_status
28
+
29
+ log = logging.getLogger("caura-bus-adapter")
30
+
31
+
32
+ @runtime_checkable
33
+ class Adapter(Protocol):
34
+ """Structural interface every adapter implements."""
35
+
36
+ async def wait_until_idle(self) -> None: ...
37
+
38
+ async def consume(self, env: Envelope) -> None: ...
39
+
40
+
41
+ class NoIdleGate:
42
+ """Mixin/base for adapters that have nothing to gate on.
43
+
44
+ Override ``consume`` only; ``wait_until_idle`` is a no-op so the
45
+ adapter consumes envelopes as fast as the bus delivers them.
46
+ """
47
+
48
+ async def wait_until_idle(self) -> None:
49
+ return None
50
+
51
+ async def consume(self, env: Envelope) -> None: # pragma: no cover - abstract
52
+ raise NotImplementedError
53
+
54
+
55
+ _active_delivery = ContextVar("caura_active_delivery", default=None)
56
+
57
+
58
+ async def checkpoint(
59
+ *,
60
+ checkpoint_key,
61
+ summary,
62
+ proposed_action,
63
+ action_type="read",
64
+ confidence=1.0,
65
+ missing_information=None,
66
+ conflicting_results=False,
67
+ request_human=False,
68
+ ):
69
+ """Call before a consequential action; Caura may pause execution for a human."""
70
+ active = _active_delivery.get()
71
+ if active is None:
72
+ raise RuntimeError("checkpoint must run inside adapter.consume")
73
+ bus, claim = active
74
+ return await bus.checkpoint(
75
+ Checkpoint(
76
+ delivery_id=claim.delivery_id,
77
+ lease_token=claim.lease_token,
78
+ checkpoint_key=checkpoint_key,
79
+ summary=summary,
80
+ proposed_action=proposed_action,
81
+ action_type=action_type,
82
+ confidence=confidence,
83
+ missing_information=missing_information or [],
84
+ conflicting_results=conflicting_results,
85
+ request_human=request_human,
86
+ )
87
+ )
88
+
89
+
90
+ async def process_delivery(bus, adapter, claim, *, lease_seconds=30):
91
+ """Renew and observe control events while the cooperative runtime executes."""
92
+
93
+ async def renew():
94
+ while True:
95
+ await asyncio.sleep(min(lease_seconds / 3, 2.0))
96
+ await bus.settle(claim, "renew")
97
+
98
+ async def control():
99
+ async for event in bus.events(after=claim.event_cursor):
100
+ if event["event_type"] == RESYNC_EVENT:
101
+ # An interrupt may be among the removed events. The lease is
102
+ # the authority: a paused or lost delivery fails this renewal.
103
+ await bus.settle(claim, "renew")
104
+ elif (
105
+ event["event_type"] == "delivery.interrupt"
106
+ and event["payload"].get("delivery_id") == claim.delivery_id
107
+ ):
108
+ raise HumanRequired(event["payload"])
109
+
110
+ context_token = _active_delivery.set((bus, claim))
111
+ failed = False
112
+ try:
113
+ try:
114
+ async with asyncio.TaskGroup() as group:
115
+ renewal = group.create_task(renew())
116
+ controls = group.create_task(control())
117
+ env = claim.envelope
118
+ # Only Caura's resume_context can carry a human decision; drop
119
+ # any look-alike part that arrived inside peer content.
120
+ parts = [p for p in env.parts if p.get("type") != "caura_human_decision"]
121
+ if claim.resume_context:
122
+ parts.append({"type": "caura_human_decision", **claim.resume_context})
123
+ if parts != env.parts:
124
+ env = env.model_copy(update={"parts": parts})
125
+ await adapter.consume(env)
126
+ renewal.cancel()
127
+ controls.cancel()
128
+ except* HumanRequired:
129
+ failed = True
130
+ log.info("Caura paused delivery %s for human input", claim.delivery_id)
131
+ except* PlatformError as errors:
132
+ if errors.subgroup(
133
+ lambda exc: (
134
+ isinstance(exc, PlatformError) and exc.status != 409 and not transient_status(exc.status)
135
+ )
136
+ ):
137
+ raise
138
+ failed = True
139
+ log.warning("Delivery interrupted by an unavailable API or lost lease")
140
+ except* Exception:
141
+ failed = True
142
+ log.exception("delivery failed id=%s attempt=%s", claim.delivery_id, claim.attempt)
143
+ if failed:
144
+ if getattr(adapter, "supports_interrupt", False):
145
+ try:
146
+ await bus.settle(claim, "paused")
147
+ return
148
+ except (PlatformError, httpx.TransportError):
149
+ log.warning("Pause confirmation failed; attempting safe lease settlement")
150
+ try:
151
+ await bus.settle(claim, "nack")
152
+ except (PlatformError, httpx.TransportError):
153
+ log.warning(
154
+ "delivery remains paused or will recover after lease expiry: %s",
155
+ claim.delivery_id,
156
+ )
157
+ return
158
+ try:
159
+ await bus.settle(claim, "ack")
160
+ except PlatformError as exc:
161
+ # A human can pause between consume returning and the ACK. The
162
+ # runtime is now stopped, so confirm instead of stranding the case.
163
+ if exc.status == 409 and getattr(adapter, "supports_interrupt", False):
164
+ try:
165
+ await bus.settle(claim, "paused")
166
+ return
167
+ except PlatformError:
168
+ log.warning("Pause confirmation rejected after ACK conflict")
169
+ raise
170
+ log.info("consumed msg_id=%s thread=%s", claim.envelope.id, claim.envelope.thread_id)
171
+ finally:
172
+ _active_delivery.reset(context_token)
173
+
174
+
175
+ @asynccontextmanager
176
+ async def connected_bus(config):
177
+ """An upstream restart during startup must not strand the adapter either."""
178
+ bus = Bus(config)
179
+ backoff = Backoff()
180
+ try:
181
+ while True:
182
+ try:
183
+ await bus.connect()
184
+ break
185
+ except (httpx.TransportError, PlatformError) as exc:
186
+ if isinstance(exc, PlatformError) and not transient_status(exc.status):
187
+ raise
188
+ log.warning("Caura connection unavailable; retrying")
189
+ await backoff.sleep()
190
+ yield bus
191
+ finally:
192
+ await bus.close()
193
+
194
+
195
+ class PresencePublisher:
196
+ """Debounce advisory state while keeping one independent liveness loop."""
197
+
198
+ def __init__(self, bus, profile):
199
+ self.bus, self.profile = bus, profile
200
+ self.desired = profile.status
201
+ self.changed_at = time.monotonic()
202
+ self.changed = asyncio.Event()
203
+ self.last_write = float("-inf")
204
+
205
+ def set_status(self, status):
206
+ if status != self.desired:
207
+ self.desired = status
208
+ self.changed_at = time.monotonic()
209
+ self.changed.set()
210
+
211
+ async def publish(self):
212
+ # Includes the final offline announcement. SDK retries of this same
213
+ # advertisement remain bounded by Bus.request's transport policy.
214
+ await asyncio.sleep(max(0, self.last_write + 1 - time.monotonic()))
215
+ self.last_write = time.monotonic()
216
+ await self.bus.advertise(self.profile.model_copy(deep=True))
217
+
218
+ async def run(self):
219
+ heartbeat_at = 0.0
220
+ backoff = Backoff()
221
+ while True:
222
+ self.changed.clear()
223
+ now = time.monotonic()
224
+ transition_at = self.changed_at + 2 if self.desired != self.profile.status else float("inf")
225
+ due = max(self.last_write + 1, min(heartbeat_at, transition_at))
226
+ if now < due:
227
+ try:
228
+ await asyncio.wait_for(self.changed.wait(), due - now)
229
+ except TimeoutError:
230
+ pass
231
+ continue
232
+ if now >= transition_at:
233
+ self.profile.status = self.desired
234
+ try:
235
+ await self.publish()
236
+ except (httpx.TransportError, PlatformError) as exc:
237
+ if isinstance(exc, PlatformError) and not transient_status(exc.status):
238
+ raise
239
+ log.warning("Presence update unavailable; retrying without bypassing Caura")
240
+ await backoff.sleep()
241
+ continue
242
+ backoff.reset()
243
+ heartbeat_at = time.monotonic() + 15
244
+
245
+
246
+ async def run_adapter(config: AgentConfig, adapter: Adapter) -> None:
247
+ """Advertise presence, wake on live events, and execute one leased item at a time."""
248
+ profile = Presence(
249
+ session_id=str(uuid.uuid4()),
250
+ display_name=config.agent.agent_id,
251
+ description=config.agent.description,
252
+ capabilities=getattr(adapter, "capabilities", []),
253
+ supports_interrupt=getattr(adapter, "supports_interrupt", False),
254
+ )
255
+ async with connected_bus(config) as bus:
256
+ wake = asyncio.Event()
257
+ wake.set()
258
+
259
+ publisher = PresencePublisher(bus, profile)
260
+
261
+ async def notifications():
262
+ async for event in bus.events():
263
+ if event["event_type"] in {"message.available", "human.decided", RESYNC_EVENT}:
264
+ wake.set()
265
+
266
+ async def consume():
267
+ backoff = Backoff()
268
+ while True:
269
+ try:
270
+ await adapter.wait_until_idle()
271
+ claim = await bus.claim()
272
+ if claim:
273
+ publisher.set_status("busy")
274
+ try:
275
+ await process_delivery(bus, adapter, claim)
276
+ finally:
277
+ publisher.set_status("ready")
278
+ else:
279
+ # Reconciliation also finds expired leases if an event was lost.
280
+ try:
281
+ await asyncio.wait_for(wake.wait(), timeout=2)
282
+ except TimeoutError:
283
+ log.debug("Inbox event wait timed out; polling durable state")
284
+ wake.clear()
285
+ backoff.reset()
286
+ except (httpx.TransportError, PlatformError) as exc:
287
+ # A lost delivery lease is reconciled by the next claim;
288
+ # authentication and other client errors remain fatal.
289
+ if (
290
+ isinstance(exc, PlatformError)
291
+ and exc.status != 409
292
+ and not transient_status(exc.status)
293
+ ):
294
+ raise
295
+ log.warning("Caura unavailable or lease lost; retrying")
296
+ await backoff.sleep()
297
+
298
+ try:
299
+ async with asyncio.TaskGroup() as tasks:
300
+ tasks.create_task(publisher.run())
301
+ tasks.create_task(notifications())
302
+ tasks.create_task(consume())
303
+ finally:
304
+ profile.status = "offline"
305
+ try:
306
+ await publisher.publish()
307
+ except (httpx.TransportError, PlatformError):
308
+ log.warning("Could not announce shutdown; presence will expire automatically")
309
+
310
+
311
+ def make_arg_parser(prog: str, description: str) -> argparse.ArgumentParser:
312
+ """argparse with the flags every adapter shares."""
313
+ parser = argparse.ArgumentParser(prog=prog, description=description)
314
+ parser.add_argument(
315
+ "--config",
316
+ type=Path,
317
+ default=None,
318
+ help=(f"path to caura-bus.toml (default $ {CONFIG_ENV_VAR} or ./caura-bus.toml)"),
319
+ )
320
+ parser.add_argument(
321
+ "--log-level",
322
+ default=os.environ.get("CAURA_BUS_LOG_LEVEL", "INFO"),
323
+ help="logging level (default INFO; or $CAURA_BUS_LOG_LEVEL)",
324
+ )
325
+ return parser
326
+
327
+
328
+ def configure_logging(level: str) -> None:
329
+ logging.basicConfig(
330
+ level=level.upper(),
331
+ format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
332
+ )
333
+ logging.getLogger("httpx").setLevel(logging.WARNING)
334
+
335
+
336
+ async def _run_with_signals(coro: Coroutine[Any, Any, None]) -> None:
337
+ task = asyncio.create_task(coro)
338
+ loop = asyncio.get_running_loop()
339
+
340
+ def _cancel(*_: object) -> None:
341
+ if not task.done():
342
+ task.cancel()
343
+
344
+ for sig in (signal.SIGINT, signal.SIGTERM):
345
+ try:
346
+ loop.add_signal_handler(sig, _cancel)
347
+ except NotImplementedError:
348
+ # Non-POSIX: SIGINT propagates via KeyboardInterrupt anyway.
349
+ log.debug("Native signal handler unavailable; retaining KeyboardInterrupt fallback")
350
+
351
+ try:
352
+ await task
353
+ except asyncio.CancelledError:
354
+ log.debug("Adapter stopped after cancellation")
355
+
356
+
357
+ def adapter_main(coro: Awaitable[None]) -> None:
358
+ """Run an adapter coroutine with SIGINT/SIGTERM-driven shutdown."""
359
+ if not isinstance(coro, Coroutine):
360
+ raise TypeError("adapter_main expects a coroutine, got " + type(coro).__name__)
361
+ asyncio.run(_run_with_signals(coro))
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: caura-bus-adapter-sdk
3
+ Version: 0.3.0
4
+ Summary: SDK for building caura-bus adapters: connect, subscribe, gate on idle, consume
5
+ Author: Caura, Inc.
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/caura-ai/caura/tree/main/clients/collaboration
8
+ Project-URL: Source, https://github.com/caura-ai/caura
9
+ Project-URL: Changelog, https://github.com/caura-ai/caura/blob/main/clients/collaboration/CHANGELOG.md
10
+ Requires-Python: >=3.12
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: caura-bus-core==0.3.0
14
+ Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ NOTICE
3
+ pyproject.toml
4
+ src/caura_bus_adapter/__init__.py
5
+ src/caura_bus_adapter/demo.py
6
+ src/caura_bus_adapter/echo.py
7
+ src/caura_bus_adapter/py.typed
8
+ src/caura_bus_adapter/sdk.py
9
+ src/caura_bus_adapter_sdk.egg-info/PKG-INFO
10
+ src/caura_bus_adapter_sdk.egg-info/SOURCES.txt
11
+ src/caura_bus_adapter_sdk.egg-info/dependency_links.txt
12
+ src/caura_bus_adapter_sdk.egg-info/entry_points.txt
13
+ src/caura_bus_adapter_sdk.egg-info/requires.txt
14
+ src/caura_bus_adapter_sdk.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ caura-bus-adapter-echo = caura_bus_adapter.echo:main
@@ -0,0 +1 @@
1
+ caura-bus-core==0.3.0