caura-bus-mcp 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.
- caura_bus_mcp-0.3.0/LICENSE +202 -0
- caura_bus_mcp-0.3.0/NOTICE +7 -0
- caura_bus_mcp-0.3.0/PKG-INFO +15 -0
- caura_bus_mcp-0.3.0/pyproject.toml +29 -0
- caura_bus_mcp-0.3.0/setup.cfg +4 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/__init__.py +5 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/config.py +10 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/delivery.py +299 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/presence.py +229 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/py.typed +0 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp/server.py +527 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/PKG-INFO +15 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/SOURCES.txt +15 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/dependency_links.txt +1 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/entry_points.txt +2 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/requires.txt +2 -0
- caura_bus_mcp-0.3.0/src/caura_bus_mcp.egg-info/top_level.txt +1 -0
|
@@ -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,15 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: caura-bus-mcp
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: MCP server exposing one opcode-based Caura peer tool over stdio
|
|
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
|
+
Requires-Dist: mcp<3,>=2.1.1
|
|
15
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "caura-bus-mcp"
|
|
3
|
+
version = "0.3.0" # x-release-please-version
|
|
4
|
+
description = "MCP server exposing one opcode-based Caura peer tool over stdio"
|
|
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
|
+
"mcp>=2.1.1,<3",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
caura-bus-mcp = "caura_bus_mcp.server:main"
|
|
15
|
+
|
|
16
|
+
[tool.uv.sources]
|
|
17
|
+
caura-bus-core = { workspace = true }
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/caura-ai/caura/tree/main/clients/collaboration"
|
|
21
|
+
Source = "https://github.com/caura-ai/caura"
|
|
22
|
+
Changelog = "https://github.com/caura-ai/caura/blob/main/clients/collaboration/CHANGELOG.md"
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["setuptools>=75"]
|
|
26
|
+
build-backend = "setuptools.build_meta"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Private lease ownership. A tool result never contains a lease token."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import secrets
|
|
6
|
+
from contextlib import suppress
|
|
7
|
+
from datetime import datetime, timedelta
|
|
8
|
+
from time import monotonic
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from caura_bus_core.bus import PlatformError
|
|
12
|
+
from caura_bus_core.consult import PresentedResponses
|
|
13
|
+
from caura_bus_core.protocol import Claim, WaitRequest
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# wait sends no lease length, so Caura grants its request default.
|
|
18
|
+
LEASE_SECONDS = WaitRequest.model_fields["lease_seconds"].default
|
|
19
|
+
|
|
20
|
+
ALREADY_PRESENTED = (
|
|
21
|
+
"This response was already shown in this session (collect or recent). Do not act on it "
|
|
22
|
+
"again; ack this delivery_id."
|
|
23
|
+
)
|
|
24
|
+
UNMATCHED_RESPONSE = (
|
|
25
|
+
"This response does not answer a request sent in this session; it may be a late reply from "
|
|
26
|
+
"an earlier run. Do not report it as the answer to your current question: get answers with "
|
|
27
|
+
"collect(message_id=<your request ID>), then ack this delivery_id."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DeliverySession:
|
|
32
|
+
def __init__(self, bus):
|
|
33
|
+
self.bus = bus
|
|
34
|
+
self.session_id = secrets.token_urlsafe(32)
|
|
35
|
+
self.current: Claim | None = None
|
|
36
|
+
# Monotonic time Caura last reported the current claim's lease_expires_at.
|
|
37
|
+
self.lease_seen: float | None = None
|
|
38
|
+
self.lock = asyncio.Lock()
|
|
39
|
+
self.renewal: asyncio.Task | None = None
|
|
40
|
+
self.reply_keys: set[tuple[str, str]] = set()
|
|
41
|
+
# (delivery_id, idempotency_key) replies sent, even if their result was lost.
|
|
42
|
+
self.reply_attempts: set[tuple[str, str]] = set()
|
|
43
|
+
self.reply_deliveries: dict[str, tuple[str, str, str]] = {}
|
|
44
|
+
# Responses already shown via collect/recent(reply_to) or an earlier wait.
|
|
45
|
+
self.presented = PresentedResponses()
|
|
46
|
+
# Called with a delivery ID once this session finishes it (consultation scopes).
|
|
47
|
+
self.on_finished = lambda _delivery_id: None
|
|
48
|
+
# Notices returned while refreshing a stale claim; the next wait hands them over.
|
|
49
|
+
self.notices: list = []
|
|
50
|
+
# Human decisions whose resume_context the model has already been shown.
|
|
51
|
+
self.surfaced: set[str] = set()
|
|
52
|
+
# Request message IDs this session sent; correlates responses returned by wait.
|
|
53
|
+
self.sent_requests: set[str] = set()
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def public(claim):
|
|
57
|
+
return claim.model_dump(by_alias=True, exclude={"lease_token", "event_cursor"}) if claim else None
|
|
58
|
+
|
|
59
|
+
async def close(self):
|
|
60
|
+
if self.renewal:
|
|
61
|
+
self.renewal.cancel()
|
|
62
|
+
with suppress(asyncio.CancelledError):
|
|
63
|
+
await self.renewal
|
|
64
|
+
# Disconnect is not completion; server lease expiry provides recovery.
|
|
65
|
+
|
|
66
|
+
async def wait(self, timeout=50):
|
|
67
|
+
async with self.lock:
|
|
68
|
+
deadline = monotonic() + timeout
|
|
69
|
+
while True:
|
|
70
|
+
# Notices held from a guard refresh must not wait behind a long poll.
|
|
71
|
+
remaining = 0 if self.notices else max(0.0, deadline - monotonic())
|
|
72
|
+
result = await self.bus.wait_result(self.session_id, remaining)
|
|
73
|
+
claim = await self._adopt(result)
|
|
74
|
+
self.notices.extend(result.get("notices", []))
|
|
75
|
+
if not await self._settle_presented(claim):
|
|
76
|
+
break
|
|
77
|
+
if claim and claim.resume_context:
|
|
78
|
+
self.surfaced.add(str(claim.resume_context.get("intervention_id")))
|
|
79
|
+
notices, self.notices = self.notices, []
|
|
80
|
+
delivery = self.public(claim)
|
|
81
|
+
if claim and claim.envelope.kind == "response":
|
|
82
|
+
delivery["correlation"] = self.correlation(claim.envelope.correlation_id)
|
|
83
|
+
if not self.presented.add(claim.envelope.id):
|
|
84
|
+
# Already in this conversation: show attribution, not the body again,
|
|
85
|
+
# and leave the queued delivery for a normal ACK.
|
|
86
|
+
delivery["envelope"]["body"] = None
|
|
87
|
+
delivery["already_presented"] = True
|
|
88
|
+
delivery["note"] = ALREADY_PRESENTED
|
|
89
|
+
elif not delivery["correlation"]["matches_sent_request"]:
|
|
90
|
+
delivery["note"] = UNMATCHED_RESPONSE
|
|
91
|
+
return {"delivery": delivery, "notices": notices}
|
|
92
|
+
|
|
93
|
+
async def _settle_presented(self, claim):
|
|
94
|
+
"""ACK a claimed response this session already presented, so the inbox drains.
|
|
95
|
+
|
|
96
|
+
collect and recent(reply_to) read responses without a lease, and Caura only
|
|
97
|
+
accepts an ACK from the session holding one, so the queued delivery is settled
|
|
98
|
+
here, when wait claims it. Returns False to hand the claim to the model instead.
|
|
99
|
+
"""
|
|
100
|
+
if not (
|
|
101
|
+
claim
|
|
102
|
+
and claim.state == "leased"
|
|
103
|
+
and claim.lease_token
|
|
104
|
+
and claim.envelope.kind == "response"
|
|
105
|
+
and claim.envelope.id in self.presented
|
|
106
|
+
):
|
|
107
|
+
return False
|
|
108
|
+
try:
|
|
109
|
+
await self.bus.delivery_action(claim.delivery_id, "ack", claim.lease_token)
|
|
110
|
+
except (PlatformError, httpx.TransportError) as exc:
|
|
111
|
+
log.debug("Could not settle an already presented response: %s", exc)
|
|
112
|
+
return False
|
|
113
|
+
self.completed(claim.delivery_id)
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
def correlation(self, reply_to):
|
|
117
|
+
"""Which request a response answers, and whether this session sent that request."""
|
|
118
|
+
return {
|
|
119
|
+
"reply_to": reply_to,
|
|
120
|
+
"correlation_id": reply_to,
|
|
121
|
+
"matches_sent_request": reply_to is not None and reply_to in self.sent_requests,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async def _adopt(self, result):
|
|
125
|
+
claim = Claim.model_validate(result["delivery"]) if result["delivery"] else None
|
|
126
|
+
self._track_lease(claim)
|
|
127
|
+
self.current = claim
|
|
128
|
+
if claim:
|
|
129
|
+
self.reply_deliveries[claim.envelope.id] = (
|
|
130
|
+
claim.delivery_id,
|
|
131
|
+
claim.envelope.from_,
|
|
132
|
+
claim.envelope.thread_id,
|
|
133
|
+
)
|
|
134
|
+
if claim.state == "paused":
|
|
135
|
+
await self._observe_pause(claim)
|
|
136
|
+
elif claim.state == "leased" and (not self.renewal or self.renewal.done()):
|
|
137
|
+
self.renewal = asyncio.create_task(self._renew())
|
|
138
|
+
return claim
|
|
139
|
+
|
|
140
|
+
async def _observe_pause(self, claim):
|
|
141
|
+
token = claim.lease_token
|
|
142
|
+
claim.lease_token = None
|
|
143
|
+
if token:
|
|
144
|
+
result = await self.bus.delivery_action(claim.delivery_id, "caura-stopped", token)
|
|
145
|
+
claim.intervention = result["intervention"]
|
|
146
|
+
|
|
147
|
+
async def guard(self, delivery_id=None, replay=False):
|
|
148
|
+
"""Fence operations on paused or lost work before they reach Caura.
|
|
149
|
+
|
|
150
|
+
``delivery_id`` names the delivery the caller targets. ``replay`` marks an
|
|
151
|
+
idempotent retry of a completion this session already sent, which Caura may
|
|
152
|
+
answer with its stored result even after the delivery left this session.
|
|
153
|
+
"""
|
|
154
|
+
claim = self.current
|
|
155
|
+
if not claim:
|
|
156
|
+
return
|
|
157
|
+
if claim.state == "paused" and not claim.lease_token:
|
|
158
|
+
# A human may have resolved the pause since it was observed. The local
|
|
159
|
+
# copy cannot tell, so ask Caura instead of fencing every later call.
|
|
160
|
+
claim = await self._refresh(claim, delivery_id, replay)
|
|
161
|
+
if claim is None:
|
|
162
|
+
return
|
|
163
|
+
elif claim.lease_token:
|
|
164
|
+
try:
|
|
165
|
+
result = await self.bus.delivery_action(claim.delivery_id, "observe", claim.lease_token)
|
|
166
|
+
except PlatformError as exc:
|
|
167
|
+
if exc.status not in {404, 409} or isinstance(exc.detail, dict):
|
|
168
|
+
raise
|
|
169
|
+
# The lease was lost (expiry, platform rebuild). Reclaim before reusing
|
|
170
|
+
# an in-hand answer; the old token is never retried.
|
|
171
|
+
claim = await self._refresh(claim, delivery_id, replay)
|
|
172
|
+
if claim is None:
|
|
173
|
+
return
|
|
174
|
+
else:
|
|
175
|
+
claim = Claim.model_validate(result["delivery"])
|
|
176
|
+
self._track_lease(claim)
|
|
177
|
+
self.current = claim
|
|
178
|
+
if claim.state == "paused":
|
|
179
|
+
await self._observe_pause(claim)
|
|
180
|
+
raise PlatformError(409, {"state": "paused", "delivery": self.public(claim)})
|
|
181
|
+
if claim.state in {"acked", "cancelled"}:
|
|
182
|
+
self.current = None
|
|
183
|
+
self.on_finished(claim.delivery_id)
|
|
184
|
+
|
|
185
|
+
async def _refresh(self, stale, delivery_id, replay=False):
|
|
186
|
+
"""Re-read a paused or lease-lost claim through this session's authenticated wait.
|
|
187
|
+
|
|
188
|
+
Caura decides: a still-paused delivery stays paused, a resumed or expired one
|
|
189
|
+
is leased to this session with a fresh private token, a rejected, cancelled or
|
|
190
|
+
completed one never returns, and a live lease held by another session is
|
|
191
|
+
never taken over.
|
|
192
|
+
"""
|
|
193
|
+
async with self.lock:
|
|
194
|
+
if self.current is stale:
|
|
195
|
+
result = await self.bus.wait_result(self.session_id, 0)
|
|
196
|
+
self.notices.extend(result.get("notices", []))
|
|
197
|
+
claim = await self._adopt(result)
|
|
198
|
+
else:
|
|
199
|
+
claim = self.current # A concurrent call already refreshed it.
|
|
200
|
+
same = claim is not None and claim.delivery_id == stale.delivery_id
|
|
201
|
+
if delivery_id == stale.delivery_id and not same and not replay:
|
|
202
|
+
raise PlatformError(
|
|
203
|
+
409,
|
|
204
|
+
{
|
|
205
|
+
"state": "unavailable",
|
|
206
|
+
"delivery_id": stale.delivery_id,
|
|
207
|
+
"detail": "Caura no longer offers this delivery to this session (completed, "
|
|
208
|
+
"rejected, cancelled or reassigned). Do not continue or replay its work; "
|
|
209
|
+
"call peer wait.",
|
|
210
|
+
},
|
|
211
|
+
)
|
|
212
|
+
if same and claim.state == "leased" and delivery_id == claim.delivery_id and self._unseen(claim):
|
|
213
|
+
self.surfaced.add(str(claim.resume_context.get("intervention_id")))
|
|
214
|
+
raise PlatformError(
|
|
215
|
+
409,
|
|
216
|
+
{
|
|
217
|
+
"state": "resumed",
|
|
218
|
+
"delivery": self.public(claim),
|
|
219
|
+
"detail": "A human resumed this delivery with instructions. Follow "
|
|
220
|
+
"resume_context.instructions, then retry.",
|
|
221
|
+
},
|
|
222
|
+
)
|
|
223
|
+
return claim
|
|
224
|
+
|
|
225
|
+
def _unseen(self, claim):
|
|
226
|
+
context = claim.resume_context or {}
|
|
227
|
+
if not context or str(context.get("intervention_id")) in self.surfaced:
|
|
228
|
+
return False
|
|
229
|
+
return context.get("action") != "approve" or bool(str(context.get("instructions") or "").strip())
|
|
230
|
+
|
|
231
|
+
def _track_lease(self, claim):
|
|
232
|
+
# A re-read of an unchanged lease (observe, wait on the held claim) reports
|
|
233
|
+
# Caura's older grant time; only a new lease_expires_at restarts the count.
|
|
234
|
+
previous = self.current
|
|
235
|
+
if not (
|
|
236
|
+
previous
|
|
237
|
+
and claim
|
|
238
|
+
and previous.delivery_id == claim.delivery_id
|
|
239
|
+
and previous.lease_expires_at == claim.lease_expires_at
|
|
240
|
+
):
|
|
241
|
+
self.lease_seen = monotonic()
|
|
242
|
+
|
|
243
|
+
def processing_seconds_left(self) -> float | None:
|
|
244
|
+
"""Seconds left before the current claim's processing deadline, on Caura's clock.
|
|
245
|
+
|
|
246
|
+
Both timestamps come from Caura's database clock: lease_expires_at was its "now"
|
|
247
|
+
plus LEASE_SECONDS when it last granted or renewed the lease, so the deadline
|
|
248
|
+
minus that instant is what was left then; a monotonic clock measures time since.
|
|
249
|
+
The local wall clock is never read, so client clock skew cannot move the deadline.
|
|
250
|
+
"""
|
|
251
|
+
claim = self.current
|
|
252
|
+
if (
|
|
253
|
+
not claim
|
|
254
|
+
or not claim.processing_deadline
|
|
255
|
+
or not claim.lease_expires_at
|
|
256
|
+
or self.lease_seen is None
|
|
257
|
+
):
|
|
258
|
+
return None
|
|
259
|
+
try:
|
|
260
|
+
due = datetime.fromisoformat(claim.processing_deadline.replace("Z", "+00:00"))
|
|
261
|
+
expires = datetime.fromisoformat(claim.lease_expires_at.replace("Z", "+00:00"))
|
|
262
|
+
except ValueError:
|
|
263
|
+
return None
|
|
264
|
+
granted = expires - timedelta(seconds=LEASE_SECONDS)
|
|
265
|
+
return (due - granted).total_seconds() - (monotonic() - self.lease_seen)
|
|
266
|
+
|
|
267
|
+
def token(self, delivery_id):
|
|
268
|
+
if self.current and self.current.delivery_id == delivery_id:
|
|
269
|
+
return self.current.lease_token
|
|
270
|
+
return None
|
|
271
|
+
|
|
272
|
+
def completed(self, delivery_id):
|
|
273
|
+
if self.current and self.current.delivery_id == delivery_id:
|
|
274
|
+
self.current = None
|
|
275
|
+
self.on_finished(delivery_id)
|
|
276
|
+
|
|
277
|
+
async def _renew(self):
|
|
278
|
+
while True:
|
|
279
|
+
await asyncio.sleep(2)
|
|
280
|
+
async with self.lock:
|
|
281
|
+
claim = self.current
|
|
282
|
+
if not claim or claim.state != "leased" or not claim.lease_token:
|
|
283
|
+
return
|
|
284
|
+
try:
|
|
285
|
+
result = await self.bus.delivery_action(claim.delivery_id, "renew", claim.lease_token)
|
|
286
|
+
claim.lease_expires_at = result["lease_expires_at"]
|
|
287
|
+
self.lease_seen = monotonic()
|
|
288
|
+
except PlatformError as exc:
|
|
289
|
+
log.debug("Lease renewal stopped or deferred after platform status %s", exc.status)
|
|
290
|
+
if exc.status == 409:
|
|
291
|
+
# Surface pause at the next model call. Background activity is not
|
|
292
|
+
# runtime stoppage and never manufactures that confirmation.
|
|
293
|
+
return
|
|
294
|
+
if exc.status in {401, 403, 404}:
|
|
295
|
+
return
|
|
296
|
+
except httpx.TransportError:
|
|
297
|
+
log.debug("Lease renewal transport failure; retrying within platform fence")
|
|
298
|
+
# The platform fences recovery if a network failure outlasts the lease.
|
|
299
|
+
continue
|