aixand-suite-python 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aixand/__init__.py +15 -0
- aixand/_agent.py +158 -0
- aixand/_binding.py +182 -0
- aixand/_carrier.py +136 -0
- aixand/_config.py +32 -0
- aixand/_connection.py +295 -0
- aixand/agents.py +226 -0
- aixand/errors.py +34 -0
- aixand/messaging.py +14 -0
- aixand/py.typed +0 -0
- aixand_suite_python-0.1.0a1.dist-info/METADATA +317 -0
- aixand_suite_python-0.1.0a1.dist-info/RECORD +15 -0
- aixand_suite_python-0.1.0a1.dist-info/WHEEL +5 -0
- aixand_suite_python-0.1.0a1.dist-info/licenses/LICENSE +202 -0
- aixand_suite_python-0.1.0a1.dist-info/top_level.txt +1 -0
aixand/_connection.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Optional resource scope, shared by the composable module APIs."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import tempfile
|
|
8
|
+
import uuid
|
|
9
|
+
import weakref
|
|
10
|
+
|
|
11
|
+
import agent_manager
|
|
12
|
+
from agent_manager import Context
|
|
13
|
+
import undercurrent
|
|
14
|
+
|
|
15
|
+
from ._carrier import CarrierResources
|
|
16
|
+
from ._config import CarrierConfig, seconds
|
|
17
|
+
from .errors import ConnectionClosed, ConsumerError, AixandError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Connection:
|
|
21
|
+
def __init__(self, *, runtime=None, runtime_home=None, bridge=None,
|
|
22
|
+
manager_config=None, manager_home=None, carrier=None, state_dir=None,
|
|
23
|
+
stable_for=2.0, timeout=300.0, stop_on_exit=False, labels=None, metadata=None):
|
|
24
|
+
if runtime is not None and (runtime_home is not None or bridge is not None):
|
|
25
|
+
raise ValueError("Supply runtime or runtime_home/bridge, not both")
|
|
26
|
+
self.stable_for = seconds(stable_for, "stable_for", zero=True)
|
|
27
|
+
self.timeout = seconds(timeout, "timeout")
|
|
28
|
+
self.stop_on_exit = stop_on_exit
|
|
29
|
+
self.manager_config, self.manager_home = manager_config, manager_home
|
|
30
|
+
self._context = Context(labels, metadata)
|
|
31
|
+
self._runtime = runtime
|
|
32
|
+
self._owns_runtime = runtime is None
|
|
33
|
+
self._runtime_options = {"home": runtime_home, "bridge": bridge}
|
|
34
|
+
self._managers = {}
|
|
35
|
+
self._agents = {}
|
|
36
|
+
self._owned = set()
|
|
37
|
+
self._loop = None
|
|
38
|
+
self._closed = False
|
|
39
|
+
self._closing = False
|
|
40
|
+
self._opened = False
|
|
41
|
+
self._mutation_lock = asyncio.Lock()
|
|
42
|
+
self._failure_event = asyncio.Event()
|
|
43
|
+
self._failures = []
|
|
44
|
+
self._reported = set()
|
|
45
|
+
self._work = set()
|
|
46
|
+
self._unconfirmed = []
|
|
47
|
+
base = Path(state_dir or Path(os.environ.get("XDG_STATE_HOME", "~/.local/state")) / "aixand")
|
|
48
|
+
self.directory = base.expanduser().resolve() / ("run-" + uuid.uuid4().hex)
|
|
49
|
+
self._carrier = CarrierResources(self, carrier or CarrierConfig())
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def context(self):
|
|
53
|
+
return self._context.as_dict()
|
|
54
|
+
|
|
55
|
+
def with_context(self, *, labels=None, metadata=None, inherit_labels=True, inherit_metadata=True):
|
|
56
|
+
return ConnectionView(self, self._context.resolve(labels=labels, metadata=metadata,
|
|
57
|
+
inherit_labels=inherit_labels, inherit_metadata=inherit_metadata),
|
|
58
|
+
inherit_labels=inherit_labels, inherit_metadata=inherit_metadata)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def closed(self):
|
|
62
|
+
return self._closed
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def agents(self):
|
|
66
|
+
"""Handles owned or attached by this scope (not an alternate API namespace)."""
|
|
67
|
+
return tuple(self._agents.values())
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def errors(self):
|
|
71
|
+
return tuple(self._failures)
|
|
72
|
+
|
|
73
|
+
def _check_loop(self):
|
|
74
|
+
loop = asyncio.get_running_loop()
|
|
75
|
+
if self._loop is None:
|
|
76
|
+
self._loop = weakref.ref(loop)
|
|
77
|
+
elif self._loop() is not loop:
|
|
78
|
+
raise AixandError("A connection cannot be shared across event loops")
|
|
79
|
+
|
|
80
|
+
def check(self):
|
|
81
|
+
self._check_loop()
|
|
82
|
+
if self._closed or self._closing:
|
|
83
|
+
raise ConnectionClosed("Aixand connection is closed")
|
|
84
|
+
if self._failures:
|
|
85
|
+
raise self._failures[0] from self._failures[0].cause
|
|
86
|
+
|
|
87
|
+
async def open(self):
|
|
88
|
+
self.check()
|
|
89
|
+
if not self._opened:
|
|
90
|
+
self.directory.mkdir(parents=True, mode=0o700)
|
|
91
|
+
self._opened = True
|
|
92
|
+
self._save()
|
|
93
|
+
return self
|
|
94
|
+
|
|
95
|
+
async def __aenter__(self):
|
|
96
|
+
return await self.open()
|
|
97
|
+
|
|
98
|
+
async def __aexit__(self, exc_type, exc, tb):
|
|
99
|
+
try:
|
|
100
|
+
await self.close()
|
|
101
|
+
except Exception as error:
|
|
102
|
+
if exc is None:
|
|
103
|
+
raise
|
|
104
|
+
exc.add_note(f"Aixand cleanup also failed: {error}")
|
|
105
|
+
|
|
106
|
+
async def runtime(self):
|
|
107
|
+
await self.open()
|
|
108
|
+
if self._runtime is None:
|
|
109
|
+
self._runtime = undercurrent.Client(**self._runtime_options)
|
|
110
|
+
await self._runtime.connect()
|
|
111
|
+
return self._runtime
|
|
112
|
+
|
|
113
|
+
async def manager(self, provider):
|
|
114
|
+
await self.open()
|
|
115
|
+
if self._runtime is None:
|
|
116
|
+
self._runtime = undercurrent.Client(**self._runtime_options)
|
|
117
|
+
if provider not in self._managers:
|
|
118
|
+
self._managers[provider] = agent_manager.Client(
|
|
119
|
+
provider, runtime=self._runtime, config=self.manager_config, root=self.manager_home,
|
|
120
|
+
**self._context.as_dict())
|
|
121
|
+
return self._managers[provider]
|
|
122
|
+
|
|
123
|
+
def _record_failure(self, binding, cause):
|
|
124
|
+
if binding.address in self._reported:
|
|
125
|
+
return
|
|
126
|
+
self._reported.add(binding.address)
|
|
127
|
+
error = ConsumerError(binding.address, binding.agent.session_id, cause)
|
|
128
|
+
self._failures.append(error)
|
|
129
|
+
self._failure_event.set()
|
|
130
|
+
self._save()
|
|
131
|
+
asyncio.get_running_loop().call_exception_handler({
|
|
132
|
+
"message": str(error), "exception": error, "aixand_connection": self,
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
async def wait_for(self, awaitable, *, timeout=None):
|
|
136
|
+
"""Await work while surfacing managed consumer failures immediately.
|
|
137
|
+
|
|
138
|
+
Cancellation or a consumer failure cancels and joins the supplied work.
|
|
139
|
+
Use this around Carrier waits; failed mutations are never retried.
|
|
140
|
+
"""
|
|
141
|
+
work = asyncio.ensure_future(awaitable)
|
|
142
|
+
self._work.add(work)
|
|
143
|
+
failure = None
|
|
144
|
+
try:
|
|
145
|
+
self.check()
|
|
146
|
+
if timeout is not None:
|
|
147
|
+
seconds(timeout, "timeout")
|
|
148
|
+
failure = asyncio.create_task(self._failure_event.wait())
|
|
149
|
+
async with asyncio.timeout(timeout):
|
|
150
|
+
await asyncio.wait((work, failure), return_when=asyncio.FIRST_COMPLETED)
|
|
151
|
+
self.check()
|
|
152
|
+
return await work
|
|
153
|
+
finally:
|
|
154
|
+
for task in (work, failure):
|
|
155
|
+
if task is not None and not task.done():
|
|
156
|
+
task.cancel()
|
|
157
|
+
await asyncio.gather(*(t for t in (work, failure) if t is not None), return_exceptions=True)
|
|
158
|
+
self._work.discard(work)
|
|
159
|
+
|
|
160
|
+
def _save(self):
|
|
161
|
+
if not self._opened:
|
|
162
|
+
return
|
|
163
|
+
value = {
|
|
164
|
+
"status": "closed" if self._closed else "open",
|
|
165
|
+
"runtime_home": self._runtime.home if self._runtime is not None else None,
|
|
166
|
+
"carrier": {"url": self._carrier.url, "mode": self._carrier.config.mode,
|
|
167
|
+
"database": str(self._carrier.database) if self._carrier.database else None,
|
|
168
|
+
"credentials": {a: str(p) for a, p in self._carrier.credentials.items()}},
|
|
169
|
+
"agents": {key: {**asdict(agent.managed), "address": agent.address,
|
|
170
|
+
"owned": key in self._owned, "uncertain_input": agent._uncertain,
|
|
171
|
+
"pending_acceptance": agent._pending_acceptance,
|
|
172
|
+
"runtime_started_at": agent._runtime_started_at,
|
|
173
|
+
"binding": {"journal": str(agent._binding.path),
|
|
174
|
+
"receipt_address": agent._binding.receipts.address}
|
|
175
|
+
if agent._binding else None,
|
|
176
|
+
"last_receipt": asdict(agent.last_receipt) if agent.last_receipt else None,
|
|
177
|
+
"last_delivery": asdict(agent._last_delivery) if agent._last_delivery else None}
|
|
178
|
+
for key, agent in self._agents.items()},
|
|
179
|
+
"consumer_errors": [str(error) for error in self._failures],
|
|
180
|
+
"unconfirmed_launches": self._unconfirmed,
|
|
181
|
+
}
|
|
182
|
+
fd, temporary = tempfile.mkstemp(dir=self.directory)
|
|
183
|
+
try:
|
|
184
|
+
with os.fdopen(fd, "w") as stream:
|
|
185
|
+
json.dump(value, stream, indent=2)
|
|
186
|
+
stream.write("\n")
|
|
187
|
+
stream.flush()
|
|
188
|
+
os.fsync(stream.fileno())
|
|
189
|
+
os.replace(temporary, self.directory / "run.json")
|
|
190
|
+
finally:
|
|
191
|
+
Path(temporary).unlink(missing_ok=True)
|
|
192
|
+
|
|
193
|
+
async def close(self, *, stop_agents=None):
|
|
194
|
+
"""Detach by default. Optionally stop only agents spawned by this scope."""
|
|
195
|
+
self._check_loop()
|
|
196
|
+
async with self._mutation_lock:
|
|
197
|
+
if self._closed:
|
|
198
|
+
return
|
|
199
|
+
self._closing = True
|
|
200
|
+
errors = []
|
|
201
|
+
try:
|
|
202
|
+
work = [task for task in self._work if task is not asyncio.current_task()]
|
|
203
|
+
for task in work:
|
|
204
|
+
task.cancel()
|
|
205
|
+
await asyncio.gather(*work, return_exceptions=True)
|
|
206
|
+
for agent in self._agents.values():
|
|
207
|
+
if agent._binding is not None:
|
|
208
|
+
try:
|
|
209
|
+
await agent._binding.close()
|
|
210
|
+
except Exception as error:
|
|
211
|
+
errors.append(error)
|
|
212
|
+
should_stop = self.stop_on_exit if stop_agents is None else stop_agents
|
|
213
|
+
if should_stop:
|
|
214
|
+
for key in self._owned:
|
|
215
|
+
agent = self._agents[key]
|
|
216
|
+
if not agent._stopped:
|
|
217
|
+
try:
|
|
218
|
+
await self._runtime.stop(agent.session_id, force=True)
|
|
219
|
+
agent._stopped = True
|
|
220
|
+
except Exception as error:
|
|
221
|
+
errors.append(error)
|
|
222
|
+
for manager in self._managers.values():
|
|
223
|
+
try:
|
|
224
|
+
await manager.close()
|
|
225
|
+
except Exception as error:
|
|
226
|
+
errors.append(error)
|
|
227
|
+
try:
|
|
228
|
+
await self._carrier.close()
|
|
229
|
+
except Exception as error:
|
|
230
|
+
errors.append(error)
|
|
231
|
+
if self._owns_runtime and self._runtime is not None:
|
|
232
|
+
try:
|
|
233
|
+
await self._runtime.close()
|
|
234
|
+
except Exception as error:
|
|
235
|
+
errors.append(error)
|
|
236
|
+
finally:
|
|
237
|
+
self._closed, self._closing = True, False
|
|
238
|
+
self._save()
|
|
239
|
+
if errors:
|
|
240
|
+
raise ExceptionGroup("Aixand cleanup failed", errors)
|
|
241
|
+
if self._failures:
|
|
242
|
+
raise self._failures[0] from self._failures[0].cause
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class ConnectionView(Connection):
|
|
246
|
+
"""Borrow shared state and resource ownership; only launch defaults differ."""
|
|
247
|
+
def __init__(self, parent, context, *, inherit_labels=True, inherit_metadata=True):
|
|
248
|
+
object.__setattr__(self, "_parent", getattr(parent, "_parent", parent))
|
|
249
|
+
object.__setattr__(self, "_context", context)
|
|
250
|
+
object.__setattr__(self, "_view_managers", {})
|
|
251
|
+
object.__setattr__(self, "_inherit_labels", getattr(parent, "_inherit_labels", True) and inherit_labels)
|
|
252
|
+
object.__setattr__(self, "_inherit_metadata", getattr(parent, "_inherit_metadata", True) and inherit_metadata)
|
|
253
|
+
|
|
254
|
+
def __getattr__(self, key):
|
|
255
|
+
return getattr(self._parent, key)
|
|
256
|
+
|
|
257
|
+
def __setattr__(self, key, value):
|
|
258
|
+
setattr(self._parent, key, value)
|
|
259
|
+
|
|
260
|
+
async def manager(self, provider):
|
|
261
|
+
base = await self._parent.manager(provider)
|
|
262
|
+
if provider not in self._view_managers:
|
|
263
|
+
self._view_managers[provider] = base.with_context(**self._context.as_dict(),
|
|
264
|
+
inherit_labels=self._inherit_labels, inherit_metadata=self._inherit_metadata)
|
|
265
|
+
return self._view_managers[provider]
|
|
266
|
+
|
|
267
|
+
async def close(self, *, stop_agents=None):
|
|
268
|
+
# The parent remains responsible for agents, inboxes, and the runtime.
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def connect(**options):
|
|
273
|
+
"""Create an optional scope; use `async with connect(...) as connection`."""
|
|
274
|
+
return Connection(**options)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def resolve(connection=None):
|
|
278
|
+
if connection is None:
|
|
279
|
+
loop = asyncio.get_running_loop()
|
|
280
|
+
connection = getattr(loop, "_aixand_default_connection", None)
|
|
281
|
+
if connection is None or connection.closed:
|
|
282
|
+
connection = Connection()
|
|
283
|
+
loop._aixand_default_connection = connection
|
|
284
|
+
if not isinstance(connection, Connection):
|
|
285
|
+
raise TypeError("connection must be an aixand.Connection")
|
|
286
|
+
connection.check()
|
|
287
|
+
return connection
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def close(*, connection=None, stop_agents=None):
|
|
291
|
+
"""Close the selected scope (or this loop's default); no resources are created."""
|
|
292
|
+
if connection is None:
|
|
293
|
+
connection = getattr(asyncio.get_running_loop(), "_aixand_default_connection", None)
|
|
294
|
+
if connection is not None:
|
|
295
|
+
await connection.close(stop_agents=stop_agents)
|
aixand/agents.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Composable agent operations; no mandatory application object."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import uuid
|
|
6
|
+
|
|
7
|
+
import agent_manager
|
|
8
|
+
from agent_manager.runtime.context import Context, attributes, require_metadata
|
|
9
|
+
import undercurrent
|
|
10
|
+
|
|
11
|
+
from ._agent import Agent
|
|
12
|
+
from ._binding import Binding, PROTOCOL
|
|
13
|
+
from ._carrier import codex_mcp_arguments
|
|
14
|
+
from ._connection import resolve
|
|
15
|
+
from ._config import seconds
|
|
16
|
+
from .errors import AgentSetupError, AixandError, DeliveryUncertain
|
|
17
|
+
|
|
18
|
+
AUTO = object()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def spawn(*, provider="codex", profile="default", cwd=None, args=(), env=None,
|
|
22
|
+
address=None, instructions=None, connection=None, timeout=None,
|
|
23
|
+
detection_profile=None, detection=True, credentials=None,
|
|
24
|
+
receipt_credentials=None, mcp_arguments=None, mcp=None, project=AUTO,
|
|
25
|
+
labels=None, metadata=None, inherit_labels=True, inherit_metadata=True,
|
|
26
|
+
resources=None, application_resources=None, runtime_bindings=None,
|
|
27
|
+
native_config=None):
|
|
28
|
+
"""Launch through Agent Manager and optionally own a Carrier inbox binding.
|
|
29
|
+
|
|
30
|
+
address provisions a fresh identity, configures MCP before launch, confirms
|
|
31
|
+
setup through Carrier, then starts an inbox consumer. Credential files for
|
|
32
|
+
fresh, preprovisioned identities may be supplied instead. They must not be
|
|
33
|
+
shared with another conversation or receiving owner.
|
|
34
|
+
|
|
35
|
+
Codex MCP launch configuration is built in. Other providers can supply a
|
|
36
|
+
synchronous mcp_arguments(url, credentials_path) callback.
|
|
37
|
+
"""
|
|
38
|
+
scope = resolve(connection)
|
|
39
|
+
Context().resolve(labels=labels, metadata=metadata,
|
|
40
|
+
inherit_labels=inherit_labels, inherit_metadata=inherit_metadata)
|
|
41
|
+
if timeout is not None:
|
|
42
|
+
seconds(timeout, "timeout")
|
|
43
|
+
if address is None and any(value is not None for value in (credentials, receipt_credentials, mcp_arguments)):
|
|
44
|
+
raise ValueError("Carrier configuration requires address")
|
|
45
|
+
if instructions is not None and not isinstance(instructions, str):
|
|
46
|
+
raise TypeError("instructions must be a string")
|
|
47
|
+
if isinstance(args, (str, bytes)):
|
|
48
|
+
raise ValueError("args must be a sequence of strings")
|
|
49
|
+
if mcp is not None or project is not AUTO or resources is not None or application_resources is not None or runtime_bindings:
|
|
50
|
+
raise ValueError("Current Agent Manager requires native_config or native CLI arguments for provider configuration")
|
|
51
|
+
args = list(args)
|
|
52
|
+
if not all(isinstance(arg, str) for arg in args):
|
|
53
|
+
raise ValueError("args must be a sequence of strings")
|
|
54
|
+
configure = mcp_arguments or (codex_mcp_arguments if provider == "codex" else None)
|
|
55
|
+
if address is not None and configure is None:
|
|
56
|
+
raise ValueError("This provider needs mcp_arguments(url, credentials_path) for Carrier integration")
|
|
57
|
+
async with scope._mutation_lock:
|
|
58
|
+
await scope.open()
|
|
59
|
+
manager = await scope.manager(provider)
|
|
60
|
+
runtime = await scope.runtime()
|
|
61
|
+
context = Context(**getattr(manager, "context", scope.context)).resolve(
|
|
62
|
+
labels=labels, metadata=metadata, inherit_labels=inherit_labels, inherit_metadata=inherit_metadata)
|
|
63
|
+
attributes({**context.labels, "agent_manager.run_id": "0" * 32,
|
|
64
|
+
"agent_manager.profile": "default"}, "labels", internal=True)
|
|
65
|
+
require_metadata(runtime, context.metadata)
|
|
66
|
+
launch_args = list(args)
|
|
67
|
+
inbox = receipts = None
|
|
68
|
+
if address is not None:
|
|
69
|
+
inbox = await scope._carrier.mailbox(address, credentials=credentials, claim=True)
|
|
70
|
+
if receipt_credentials is None:
|
|
71
|
+
receipt_address = "aixand-receipts/" + uuid.uuid4().hex
|
|
72
|
+
else:
|
|
73
|
+
# The Carrier client will authenticate and verify this identity.
|
|
74
|
+
receipt_address = json.loads(Path(receipt_credentials).expanduser().read_text())["address"]
|
|
75
|
+
receipts = await scope._carrier.mailbox(receipt_address, credentials=receipt_credentials, claim=True)
|
|
76
|
+
extra = configure(scope._carrier.url, scope._carrier.credentials[address])
|
|
77
|
+
if isinstance(extra, (str, bytes)):
|
|
78
|
+
raise ValueError("mcp_arguments must return a sequence of argument strings")
|
|
79
|
+
extra = list(extra)
|
|
80
|
+
if not all(isinstance(arg, str) for arg in extra):
|
|
81
|
+
raise ValueError("mcp_arguments must return a sequence of argument strings")
|
|
82
|
+
launch_args.extend(extra)
|
|
83
|
+
try:
|
|
84
|
+
managed = await manager.spawn(profile=profile, cwd=cwd, args=launch_args, env=env,
|
|
85
|
+
detection_profile=detection_profile, detection=detection,
|
|
86
|
+
timeout=scope.timeout if timeout is None else timeout,
|
|
87
|
+
**({"native_config": native_config} if native_config is not None else {}),
|
|
88
|
+
**({**context.as_dict(), "inherit_labels": False, "inherit_metadata": False}
|
|
89
|
+
if context.labels or context.metadata or not inherit_labels or not inherit_metadata else {}))
|
|
90
|
+
except agent_manager.LaunchError as error:
|
|
91
|
+
scope._unconfirmed.append({"run_id": error.run_id, "provider": provider,
|
|
92
|
+
"address": address, "error": str(error)})
|
|
93
|
+
scope._save()
|
|
94
|
+
raise
|
|
95
|
+
agent = Agent(managed, scope)
|
|
96
|
+
scope._agents[managed.run_id] = agent
|
|
97
|
+
scope._owned.add(managed.run_id)
|
|
98
|
+
scope._save()
|
|
99
|
+
try:
|
|
100
|
+
if inbox is not None:
|
|
101
|
+
agent._binding = Binding(agent, inbox, receipts)
|
|
102
|
+
scope._save()
|
|
103
|
+
setup = (PROTOCOL + "\nYour address is " + address + ".\n"
|
|
104
|
+
+ (instructions or "Wait for a task or incoming peer message.")
|
|
105
|
+
+ "\nThis is setup only. Send the required acceptance receipt, "
|
|
106
|
+
"then end your turn without starting work or sending other messages.")
|
|
107
|
+
receipt = await agent.send(setup, timeout=timeout)
|
|
108
|
+
await agent._binding.accept(receipt.delivery_id, scope.timeout if timeout is None else timeout)
|
|
109
|
+
agent._pending_acceptance = None
|
|
110
|
+
ready = await agent.wait(after=receipt, timeout=timeout)
|
|
111
|
+
agent._runtime_started_at = getattr(ready, "raw", {}).get("started_at_millis")
|
|
112
|
+
scope._save()
|
|
113
|
+
agent._binding.start()
|
|
114
|
+
elif instructions:
|
|
115
|
+
await agent.send(instructions, timeout=timeout)
|
|
116
|
+
return agent
|
|
117
|
+
except asyncio.CancelledError:
|
|
118
|
+
# The known launch is retained in scope.agents and the manifest.
|
|
119
|
+
raise
|
|
120
|
+
except Exception as error:
|
|
121
|
+
raise AgentSetupError(agent, error) from error
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def get(run_id, *, provider="codex", connection=None):
|
|
125
|
+
"""Attach a runtime handle; this does not reconstruct an old Carrier consumer.
|
|
126
|
+
|
|
127
|
+
Within a scope, repeated get calls return the same handle and input lock.
|
|
128
|
+
Across scopes, use restore with the original manifest to recover delivery.
|
|
129
|
+
"""
|
|
130
|
+
scope = resolve(connection)
|
|
131
|
+
async with scope._mutation_lock:
|
|
132
|
+
if run_id in scope._agents:
|
|
133
|
+
agent = scope._agents[run_id]
|
|
134
|
+
if agent.provider != provider:
|
|
135
|
+
raise ValueError("run_id belongs to a different provider")
|
|
136
|
+
return agent
|
|
137
|
+
manager = await scope.manager(provider)
|
|
138
|
+
managed = await manager.get(run_id)
|
|
139
|
+
agent = Agent(managed, scope)
|
|
140
|
+
scope._agents[run_id] = agent
|
|
141
|
+
scope._save()
|
|
142
|
+
return agent
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
async def restore(run_id, *, manifest, connection=None):
|
|
146
|
+
"""Restore delivery to the same live conversation without replaying input.
|
|
147
|
+
|
|
148
|
+
The manifest and journal must come from its original connection. Restoration
|
|
149
|
+
verifies runtime/managed identity, acquires the journal's exclusive lock,
|
|
150
|
+
and refuses ambiguous writes. It never launches or resumes a conversation.
|
|
151
|
+
"""
|
|
152
|
+
scope = resolve(connection)
|
|
153
|
+
path = Path(manifest).expanduser().resolve()
|
|
154
|
+
saved = json.loads(path.read_text())
|
|
155
|
+
row = saved.get("agents", {}).get(run_id)
|
|
156
|
+
if not row or not row.get("address") or not row.get("binding"):
|
|
157
|
+
raise ValueError("Manifest has no recoverable Carrier binding for this run")
|
|
158
|
+
if saved["carrier"]["mode"] != "external" or scope._carrier.config.mode != "external":
|
|
159
|
+
raise ValueError("Restoration requires the persistent external Carrier service")
|
|
160
|
+
if saved["carrier"]["url"].rstrip("/") != scope._carrier.url.rstrip("/"):
|
|
161
|
+
raise ValueError("Carrier service differs from the original binding")
|
|
162
|
+
if row.get("uncertain_input"):
|
|
163
|
+
raise DeliveryUncertain("Original input delivery is uncertain; inspect it before recovery")
|
|
164
|
+
journal = Path(row["binding"]["journal"]).resolve()
|
|
165
|
+
if not journal.is_file():
|
|
166
|
+
raise ValueError("Original delivery journal is missing")
|
|
167
|
+
async with scope._mutation_lock:
|
|
168
|
+
if run_id in scope._agents:
|
|
169
|
+
existing = scope._agents[run_id]
|
|
170
|
+
if existing.consumer_active and existing.address == row["address"]:
|
|
171
|
+
return existing
|
|
172
|
+
raise AixandError("Run already has a handle in this connection; use a fresh recovery scope")
|
|
173
|
+
await scope.open()
|
|
174
|
+
runtime = await scope.runtime()
|
|
175
|
+
if runtime.home != saved["runtime_home"]:
|
|
176
|
+
raise ValueError("Runtime differs from the original binding")
|
|
177
|
+
managed = await (await scope.manager(row["provider"])).get(run_id)
|
|
178
|
+
if any(getattr(managed, key) != row[key] for key in
|
|
179
|
+
("run_id", "provider", "profile", "home", "session_id")):
|
|
180
|
+
raise ValueError("Managed conversation identity has changed")
|
|
181
|
+
snapshot = await runtime.inspect(managed.session_id)
|
|
182
|
+
if snapshot.lifecycle != "running":
|
|
183
|
+
raise AixandError("Only a still-running conversation can be restored")
|
|
184
|
+
if row.get("runtime_started_at") is not None and snapshot.raw.get("started_at_millis") != row["runtime_started_at"]:
|
|
185
|
+
raise AixandError("Original conversation process has changed; recovery was not started")
|
|
186
|
+
credentials = saved["carrier"]["credentials"]
|
|
187
|
+
address, receipt_address = row["address"], row["binding"]["receipt_address"]
|
|
188
|
+
agent = Agent(managed, scope)
|
|
189
|
+
agent._runtime_started_at = row.get("runtime_started_at")
|
|
190
|
+
for key in ("last_receipt", "last_delivery"):
|
|
191
|
+
value = row.get(key)
|
|
192
|
+
if value:
|
|
193
|
+
receipt = undercurrent.InputReceipt(**value)
|
|
194
|
+
if receipt.session_id != managed.session_id:
|
|
195
|
+
raise ValueError("Saved receipt belongs to a different session")
|
|
196
|
+
setattr(agent, "_" + key, receipt)
|
|
197
|
+
inbox = await scope._carrier.mailbox(address, credentials=credentials[address], claim=True)
|
|
198
|
+
receipts = await scope._carrier.mailbox(receipt_address, credentials=credentials[receipt_address], claim=True)
|
|
199
|
+
binding = Binding(agent, inbox, receipts, journal=journal, restore=True)
|
|
200
|
+
try:
|
|
201
|
+
# Check only while holding the journal lock. A submitting write may
|
|
202
|
+
# have reached the terminal; never turn it into a new write.
|
|
203
|
+
if binding.db.execute("SELECT 1 FROM deliveries WHERE state = 'submitting' LIMIT 1").fetchone():
|
|
204
|
+
raise DeliveryUncertain("Journal contains an uncertain terminal write; recovery was not started")
|
|
205
|
+
agent._binding = binding
|
|
206
|
+
agent._pending_acceptance = row.get("pending_acceptance")
|
|
207
|
+
if agent._pending_acceptance:
|
|
208
|
+
await binding.accept(agent._pending_acceptance, scope.timeout)
|
|
209
|
+
agent._pending_acceptance = None
|
|
210
|
+
scope._agents[run_id] = agent
|
|
211
|
+
if row.get("owned"):
|
|
212
|
+
scope._owned.add(run_id)
|
|
213
|
+
scope._save()
|
|
214
|
+
binding.start()
|
|
215
|
+
return agent
|
|
216
|
+
except BaseException:
|
|
217
|
+
await binding.close()
|
|
218
|
+
raise
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
async def profiles(*, provider="codex", connection=None):
|
|
222
|
+
return await (await resolve(connection).manager(provider)).profiles()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
async def budgets(*, provider="codex", auth=None, connection=None):
|
|
226
|
+
return await (await resolve(connection).manager(provider)).budgets(auth)
|
aixand/errors.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Composition failures; underlying SDK errors otherwise retain their original types."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AixandError(Exception):
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# Retained for callers catching the pre-rebrand exception name.
|
|
9
|
+
IntessioError = AixandError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConnectionClosed(AixandError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConsumerError(AixandError):
|
|
17
|
+
def __init__(self, address, session_id, cause):
|
|
18
|
+
self.address, self.session_id, self.cause = address, session_id, cause
|
|
19
|
+
super().__init__(f"Carrier consumer {address!r} for {session_id} failed: {cause}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AcceptanceTimeout(AixandError):
|
|
23
|
+
"""Terminal input was written, but the agent has not confirmed acceptance."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DeliveryUncertain(AixandError):
|
|
27
|
+
"""Input might have been delivered. No input was automatically replayed."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AgentSetupError(AixandError):
|
|
31
|
+
def __init__(self, agent, cause):
|
|
32
|
+
self.agent, self.cause = agent, cause
|
|
33
|
+
super().__init__(f"Agent {agent.run_id} was launched but setup failed: {cause}. "
|
|
34
|
+
"The handle is available as error.agent; stop or inspect it explicitly.")
|
aixand/messaging.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Ordinary application mailboxes return native Carrier SDK clients."""
|
|
2
|
+
from ._connection import resolve
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
async def mailbox(address, *, credentials=None, connection=None):
|
|
6
|
+
"""Provision/open an application inbox, closed with the selected scope.
|
|
7
|
+
|
|
8
|
+
An agent-bound inbox is reserved for its managed consumer. Use a different
|
|
9
|
+
mailbox for application messages, services, or an optional coordinator.
|
|
10
|
+
"""
|
|
11
|
+
scope = resolve(connection)
|
|
12
|
+
async with scope._mutation_lock:
|
|
13
|
+
await scope.open()
|
|
14
|
+
return await scope._carrier.mailbox(address, credentials=credentials)
|
aixand/py.typed
ADDED
|
File without changes
|