sinapsis-api 1.0.0__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.
- sinapsis_api/__init__.py +1 -0
- sinapsis_api/agent_router.py +482 -0
- sinapsis_api/agent_worker.py +240 -0
- sinapsis_api/api/__init__.py +1 -0
- sinapsis_api/api/healthcheck.py +25 -0
- sinapsis_api/api/main.py +40 -0
- sinapsis_api/api/routes/_common.py +85 -0
- sinapsis_api/api/routes/agents.py +91 -0
- sinapsis_api/api/routes/health.py +18 -0
- sinapsis_api/api/routes/jobs.py +81 -0
- sinapsis_api/client.py +135 -0
- sinapsis_api/constants.py +57 -0
- sinapsis_api/docker_runtime/__init__.py +42 -0
- sinapsis_api/docker_runtime/_file.py +71 -0
- sinapsis_api/docker_runtime/base.py +290 -0
- sinapsis_api/docker_runtime/image.py +83 -0
- sinapsis_api/docker_runtime/runtime.py +143 -0
- sinapsis_api/docker_runtime/services.py +127 -0
- sinapsis_api/env_vars/__init__.py +19 -0
- sinapsis_api/env_vars/env_vars.py +202 -0
- sinapsis_api/journal.py +298 -0
- sinapsis_api/models.py +30 -0
- sinapsis_api/onexth_runtime.py +68 -0
- sinapsis_api/protocol.py +106 -0
- sinapsis_api/telemetry.py +186 -0
- sinapsis_api-1.0.0.dist-info/METADATA +280 -0
- sinapsis_api-1.0.0.dist-info/RECORD +30 -0
- sinapsis_api-1.0.0.dist-info/WHEEL +4 -0
- sinapsis_api-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
- sinapsis_api-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Isolated Sinapsis agent subprocess."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import zmq
|
|
9
|
+
import zmq.asyncio
|
|
10
|
+
from sinapsis.agent import AgentMode
|
|
11
|
+
from sinapsis.logging import sinapsis_logger
|
|
12
|
+
from sinapsis_protocol import (
|
|
13
|
+
EventType,
|
|
14
|
+
SSEEnvelope,
|
|
15
|
+
deserialize_data_container,
|
|
16
|
+
serialize_sse_envelope,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from sinapsis_api.constants import ControlType, JobStatus, WorkerFrame
|
|
20
|
+
from sinapsis_api.env_vars import (
|
|
21
|
+
SINAPSIS_API_WORKER_OUTBOUND_QUEUE_SIZE,
|
|
22
|
+
SINAPSIS_API_ZMQ_RECEIVE_HWM,
|
|
23
|
+
SINAPSIS_API_ZMQ_SEND_HWM,
|
|
24
|
+
)
|
|
25
|
+
from sinapsis_api.protocol import pack_control, unpack_control
|
|
26
|
+
from sinapsis_api.sinapsis_runtime import build_agent, execute_agent
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(slots=True)
|
|
30
|
+
class AgentContext:
|
|
31
|
+
"""Application event boundary exposed to an executing agent job."""
|
|
32
|
+
|
|
33
|
+
agent_id: str
|
|
34
|
+
instance_id: str
|
|
35
|
+
outbound: asyncio.Queue[tuple[bytes, ...]]
|
|
36
|
+
inbound: asyncio.Queue[dict[str, Any]]
|
|
37
|
+
job_id: str | None = None
|
|
38
|
+
|
|
39
|
+
async def send(
|
|
40
|
+
self,
|
|
41
|
+
data: Any = None,
|
|
42
|
+
*,
|
|
43
|
+
event_type: EventType = EventType.DATA,
|
|
44
|
+
agent_status: Any = None,
|
|
45
|
+
errors: tuple[Any, ...] = (),
|
|
46
|
+
request_type: Any = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Serialize one SSEEnvelope at the worker/application boundary."""
|
|
49
|
+
envelope = SSEEnvelope(
|
|
50
|
+
agent_id=self.agent_id,
|
|
51
|
+
agent_status=agent_status,
|
|
52
|
+
data=data,
|
|
53
|
+
errors=errors,
|
|
54
|
+
event_type=event_type,
|
|
55
|
+
request_type=request_type,
|
|
56
|
+
job_id=self.job_id,
|
|
57
|
+
)
|
|
58
|
+
await self.send_envelope(envelope)
|
|
59
|
+
|
|
60
|
+
async def send_envelope(self, envelope: SSEEnvelope) -> None:
|
|
61
|
+
"""Serialize and queue an application envelope exactly once."""
|
|
62
|
+
await self.outbound.put(
|
|
63
|
+
(
|
|
64
|
+
WorkerFrame.EVENT.value,
|
|
65
|
+
(self.job_id or "").encode(),
|
|
66
|
+
serialize_sse_envelope(envelope),
|
|
67
|
+
)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
async def receive(self) -> dict[str, Any]:
|
|
71
|
+
"""Wait for a routed control response such as approval feedback."""
|
|
72
|
+
return await self.inbound.get()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AgentWorker:
|
|
76
|
+
"""Own one Sinapsis Agent inside an isolated OS process."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, endpoint: str, agent_id: str, instance_id: str) -> None:
|
|
79
|
+
self.endpoint = endpoint
|
|
80
|
+
self.agent_id = agent_id
|
|
81
|
+
self.instance_id = instance_id
|
|
82
|
+
self.zmq_context = zmq.asyncio.Context.instance()
|
|
83
|
+
self.socket = self.zmq_context.socket(zmq.DEALER)
|
|
84
|
+
self.socket.setsockopt(zmq.LINGER, 0)
|
|
85
|
+
self.socket.setsockopt(zmq.SNDHWM, SINAPSIS_API_ZMQ_SEND_HWM)
|
|
86
|
+
self.socket.setsockopt(zmq.RCVHWM, SINAPSIS_API_ZMQ_RECEIVE_HWM)
|
|
87
|
+
self.socket.setsockopt(zmq.IDENTITY, f"agent:{agent_id}:{instance_id}".encode())
|
|
88
|
+
self.outbound: asyncio.Queue[tuple[bytes, ...]] = asyncio.Queue(maxsize=SINAPSIS_API_WORKER_OUTBOUND_QUEUE_SIZE)
|
|
89
|
+
self.contexts: dict[str, AgentContext] = {}
|
|
90
|
+
self.tasks: dict[str, asyncio.Task[None]] = {}
|
|
91
|
+
self.production_task: asyncio.Task[None] | None = None
|
|
92
|
+
self.agent: Any | None = None
|
|
93
|
+
self.stopping = False
|
|
94
|
+
|
|
95
|
+
async def run(self) -> None:
|
|
96
|
+
"""Connect to the Router and process commands until stopped."""
|
|
97
|
+
self.socket.connect(self.endpoint)
|
|
98
|
+
await self.socket.send_multipart(
|
|
99
|
+
[
|
|
100
|
+
WorkerFrame.HELLO.value,
|
|
101
|
+
pack_control({"agent_id": self.agent_id, "instance_id": self.instance_id}),
|
|
102
|
+
]
|
|
103
|
+
)
|
|
104
|
+
sender_task = asyncio.create_task(self._sender())
|
|
105
|
+
try:
|
|
106
|
+
while not self.stopping:
|
|
107
|
+
frames = await self.socket.recv_multipart(copy=False)
|
|
108
|
+
if bytes(frames[0]) != WorkerFrame.COMMAND.value:
|
|
109
|
+
continue
|
|
110
|
+
try:
|
|
111
|
+
await self._handle_command(unpack_control(frames[1].buffer))
|
|
112
|
+
except Exception:
|
|
113
|
+
sinapsis_logger.exception("Agent worker failed to handle a command for agent %s.", self.agent_id)
|
|
114
|
+
raise
|
|
115
|
+
except Exception:
|
|
116
|
+
sinapsis_logger.exception("Agent worker failed for agent %s.", self.agent_id)
|
|
117
|
+
raise
|
|
118
|
+
finally:
|
|
119
|
+
for task in tuple(self.tasks.values()):
|
|
120
|
+
task.cancel()
|
|
121
|
+
if self.production_task is not None:
|
|
122
|
+
self.production_task.cancel()
|
|
123
|
+
sender_task.cancel()
|
|
124
|
+
await asyncio.gather(*self.tasks.values(), sender_task, return_exceptions=True)
|
|
125
|
+
if self.production_task is not None:
|
|
126
|
+
await asyncio.gather(self.production_task, return_exceptions=True)
|
|
127
|
+
self.socket.close()
|
|
128
|
+
|
|
129
|
+
async def _handle_command(self, command: dict[str, Any]) -> None:
|
|
130
|
+
command_type = ControlType(command["type"])
|
|
131
|
+
if command_type == ControlType.INIT:
|
|
132
|
+
self.agent = build_agent(command["agent_definition"])
|
|
133
|
+
await self.socket.send_multipart([WorkerFrame.READY.value, pack_control({"agent_id": self.agent_id})])
|
|
134
|
+
if self.agent.agent_attributes.agent_mode == AgentMode.LOOP_FOREVER:
|
|
135
|
+
context = AgentContext(
|
|
136
|
+
agent_id=self.agent_id,
|
|
137
|
+
instance_id=self.instance_id,
|
|
138
|
+
outbound=self.outbound,
|
|
139
|
+
inbound=asyncio.Queue(),
|
|
140
|
+
)
|
|
141
|
+
self.production_task = asyncio.create_task(execute_agent(self.agent, None, context, production=True))
|
|
142
|
+
return
|
|
143
|
+
if command_type == ControlType.STOP:
|
|
144
|
+
self.stopping = True
|
|
145
|
+
return
|
|
146
|
+
if command_type == ControlType.START_JOB:
|
|
147
|
+
await self._start_job(command)
|
|
148
|
+
return
|
|
149
|
+
if command_type == ControlType.CANCEL_JOB:
|
|
150
|
+
task = self.tasks.get(command["job_id"])
|
|
151
|
+
if task is not None:
|
|
152
|
+
task.cancel()
|
|
153
|
+
return
|
|
154
|
+
if command_type == ControlType.APPROVAL_RESPONSE:
|
|
155
|
+
context = self.contexts.get(command["job_id"])
|
|
156
|
+
if context is not None:
|
|
157
|
+
await context.inbound.put(command)
|
|
158
|
+
return
|
|
159
|
+
sinapsis_logger.error("Unsupported worker command: %s.", command_type.value)
|
|
160
|
+
raise ValueError(f"Unsupported worker command: {command_type.value}.")
|
|
161
|
+
|
|
162
|
+
async def _start_job(self, command: dict[str, Any]) -> None:
|
|
163
|
+
if self.agent is None:
|
|
164
|
+
sinapsis_logger.error("Start-job received before agent initialization for %s.", self.agent_id)
|
|
165
|
+
raise RuntimeError("Agent worker is not initialized.")
|
|
166
|
+
job_id = command["job_id"]
|
|
167
|
+
if job_id in self.tasks:
|
|
168
|
+
return
|
|
169
|
+
payload_bytes = command.get("payload")
|
|
170
|
+
payload = deserialize_data_container(payload_bytes) if payload_bytes is not None else None
|
|
171
|
+
context = AgentContext(
|
|
172
|
+
agent_id=self.agent_id,
|
|
173
|
+
instance_id=self.instance_id,
|
|
174
|
+
job_id=job_id,
|
|
175
|
+
outbound=self.outbound,
|
|
176
|
+
inbound=asyncio.Queue(),
|
|
177
|
+
)
|
|
178
|
+
self.contexts[job_id] = context
|
|
179
|
+
self.tasks[job_id] = asyncio.create_task(self._run_job(context, payload))
|
|
180
|
+
|
|
181
|
+
async def _run_job(self, context: AgentContext, payload: Any) -> None:
|
|
182
|
+
try:
|
|
183
|
+
await self._send_job_state(context.job_id, JobStatus.RUNNING)
|
|
184
|
+
|
|
185
|
+
await execute_agent(self.agent, payload, context)
|
|
186
|
+
|
|
187
|
+
# execute_agent() has exhausted the finite execution here.
|
|
188
|
+
# COMPLETED is placed onto the same FIFO outbound queue after all
|
|
189
|
+
# events emitted by context.send().
|
|
190
|
+
await self._send_job_state(context.job_id, JobStatus.COMPLETED)
|
|
191
|
+
|
|
192
|
+
except asyncio.CancelledError:
|
|
193
|
+
await self._send_job_state(context.job_id, JobStatus.CANCELLED)
|
|
194
|
+
raise
|
|
195
|
+
|
|
196
|
+
except Exception as exception:
|
|
197
|
+
sinapsis_logger.exception("Job %s failed in agent %s.", context.job_id, self.agent_id)
|
|
198
|
+
await self._send_job_state(context.job_id, JobStatus.FAILED, str(exception))
|
|
199
|
+
|
|
200
|
+
finally:
|
|
201
|
+
if context.job_id is not None:
|
|
202
|
+
self.contexts.pop(context.job_id, None)
|
|
203
|
+
self.tasks.pop(context.job_id, None)
|
|
204
|
+
|
|
205
|
+
async def _send_job_state(self, job_id: str | None, status: JobStatus, error: str | None = None) -> None:
|
|
206
|
+
if job_id is None:
|
|
207
|
+
return
|
|
208
|
+
await self.outbound.put(
|
|
209
|
+
(
|
|
210
|
+
WorkerFrame.JOB_STATE.value,
|
|
211
|
+
pack_control({"job_id": job_id, "status": status.value, "error": error}),
|
|
212
|
+
)
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
async def _sender(self) -> None:
|
|
216
|
+
while True:
|
|
217
|
+
frames = await self.outbound.get()
|
|
218
|
+
try:
|
|
219
|
+
await self.socket.send_multipart(list(frames), copy=False)
|
|
220
|
+
finally:
|
|
221
|
+
self.outbound.task_done()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def parse_args() -> argparse.Namespace:
|
|
225
|
+
"""Parse subprocess command-line arguments."""
|
|
226
|
+
parser = argparse.ArgumentParser()
|
|
227
|
+
parser.add_argument("--endpoint", required=True)
|
|
228
|
+
parser.add_argument("--agent-id", required=True)
|
|
229
|
+
parser.add_argument("--instance-id", required=True)
|
|
230
|
+
return parser.parse_args()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
async def main() -> None:
|
|
234
|
+
"""Run the agent worker entry point."""
|
|
235
|
+
arguments = parse_args()
|
|
236
|
+
await AgentWorker(arguments.endpoint, arguments.agent_id, arguments.instance_id).run()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
if __name__ == "__main__":
|
|
240
|
+
asyncio.run(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""HTTP API package."""
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from sinapsis.logging import sinapsis_logger
|
|
5
|
+
|
|
6
|
+
from sinapsis_api.constants import ControlType
|
|
7
|
+
|
|
8
|
+
from .routes._common import command, require_success, router_client
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def main() -> None:
|
|
12
|
+
try:
|
|
13
|
+
response = await asyncio.wait_for(router_client.request(command(ControlType.HEALTH)), timeout=5.0)
|
|
14
|
+
|
|
15
|
+
_ = require_success(response)
|
|
16
|
+
|
|
17
|
+
except Exception as exc:
|
|
18
|
+
sinapsis_logger.error(f"Router health check failed: {exc}")
|
|
19
|
+
sys.exit(1)
|
|
20
|
+
sinapsis_logger.debug("Router health check succeeded")
|
|
21
|
+
sys.exit(0)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
asyncio.run(main())
|
sinapsis_api/api/main.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Sinapsis Local API; optional telemetry is isolated from execution."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from contextlib import asynccontextmanager, suppress
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI
|
|
9
|
+
|
|
10
|
+
from sinapsis_api.api.routes.agents import agents_router
|
|
11
|
+
from sinapsis_api.api.routes.health import health_router
|
|
12
|
+
from sinapsis_api.api.routes.jobs import jobs_router
|
|
13
|
+
from sinapsis_api.telemetry import collect_inventory, enabled, publish_pending
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def _telemetry_loop() -> None:
|
|
17
|
+
"""Send queued events and retry once per hour in a dedicated async task."""
|
|
18
|
+
while enabled():
|
|
19
|
+
await asyncio.to_thread(collect_inventory)
|
|
20
|
+
await asyncio.to_thread(publish_pending)
|
|
21
|
+
await asyncio.sleep(3600)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@asynccontextmanager
|
|
25
|
+
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
|
26
|
+
"""Start periodic container telemetry only if its own consent is enabled."""
|
|
27
|
+
task = asyncio.create_task(_telemetry_loop()) if enabled() else None
|
|
28
|
+
try:
|
|
29
|
+
yield
|
|
30
|
+
finally:
|
|
31
|
+
if task:
|
|
32
|
+
task.cancel()
|
|
33
|
+
with suppress(asyncio.CancelledError):
|
|
34
|
+
await task
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
app = FastAPI(title='Sinapsis Local API', lifespan=lifespan)
|
|
38
|
+
app.include_router(health_router)
|
|
39
|
+
app.include_router(agents_router)
|
|
40
|
+
app.include_router(jobs_router)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Shared helpers for stateless FastAPI route handlers."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import uuid
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
|
|
9
|
+
from sinapsis.logging import sinapsis_logger
|
|
10
|
+
|
|
11
|
+
from sinapsis_api.client import RouterClient, SubscriberLaggedError
|
|
12
|
+
from sinapsis_api.constants import ControlType, RouterError
|
|
13
|
+
|
|
14
|
+
router_client = RouterClient()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def command(control_type: ControlType, **values: Any) -> dict[str, Any]:
|
|
18
|
+
"""Create an idempotency-keyed Router control request."""
|
|
19
|
+
return {"type": control_type.value, "command_id": str(uuid.uuid4()), **values}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def require_success(response: dict[str, Any]) -> dict[str, Any]:
|
|
23
|
+
"""Translate Router control errors to HTTP errors."""
|
|
24
|
+
if response.get("ok"):
|
|
25
|
+
sinapsis_logger.debug("Router returned success response ", response)
|
|
26
|
+
return response
|
|
27
|
+
|
|
28
|
+
error = response.get("error")
|
|
29
|
+
|
|
30
|
+
status_code = {
|
|
31
|
+
RouterError.NOT_FOUND.value: 404,
|
|
32
|
+
RouterError.CONFLICT.value: 409,
|
|
33
|
+
RouterError.UNAVAILABLE.value: 503,
|
|
34
|
+
}.get(error, 500)
|
|
35
|
+
|
|
36
|
+
detail = response.get("detail", error)
|
|
37
|
+
|
|
38
|
+
sinapsis_logger.error("Router returned API error %s: %s", error, detail)
|
|
39
|
+
|
|
40
|
+
raise HTTPException(status_code=status_code, detail=detail)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def decode_job_payload(payload: str | None) -> bytes | None:
|
|
44
|
+
"""Decode an HTTP-safe serialized DataContainer without deserializing it."""
|
|
45
|
+
if payload is None:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
return base64.b64decode(payload, validate=True)
|
|
50
|
+
except (ValueError, binascii.Error) as exception:
|
|
51
|
+
sinapsis_logger.error("Invalid base64 job payload: %s", exception)
|
|
52
|
+
raise HTTPException(status_code=422, detail="payload must be valid base64") from exception
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def encode_replay_body(events: tuple[Any, ...]) -> bytes:
|
|
56
|
+
"""Encode bounded events as length-prefixed WebSocket-compatible frames."""
|
|
57
|
+
chunks: list[bytes] = []
|
|
58
|
+
|
|
59
|
+
for event in events:
|
|
60
|
+
frame = event.websocket_frame()
|
|
61
|
+
chunks.extend((len(frame).to_bytes(4, "big"), frame))
|
|
62
|
+
|
|
63
|
+
return b"".join(chunks)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def stream_agent_events(
|
|
67
|
+
websocket: WebSocket, *, agent_id: str, after: int | None = None, job_id: str | None = None
|
|
68
|
+
) -> None:
|
|
69
|
+
"""Stream Router events to an accepted WebSocket."""
|
|
70
|
+
await websocket.accept()
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
async for event in router_client.subscribe(agent_id=agent_id, after=after, job_id=job_id):
|
|
74
|
+
await websocket.send_bytes(event.websocket_frame())
|
|
75
|
+
|
|
76
|
+
except SubscriberLaggedError as exception:
|
|
77
|
+
sinapsis_logger.warning("WebSocket subscriber lagged for agent %s: %s", agent_id, exception.metadata)
|
|
78
|
+
await websocket.close(code=4008, reason="subscriber lagged; reconnect using the last processed cursor")
|
|
79
|
+
|
|
80
|
+
except WebSocketDisconnect:
|
|
81
|
+
sinapsis_logger.info("WebSocket disconnected for agent %s.", agent_id)
|
|
82
|
+
|
|
83
|
+
except Exception as exception:
|
|
84
|
+
sinapsis_logger.exception("WebSocket event stream failed for agent %s. Exc: %s.", agent_id, exception)
|
|
85
|
+
await websocket.close(code=1011, reason="event stream failed")
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Agent API routes."""
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Query, WebSocket
|
|
6
|
+
from fastapi.responses import Response
|
|
7
|
+
from sinapsis.agent import AgentSchema
|
|
8
|
+
from sinapsis_contracts.common.constants import ApiConstants
|
|
9
|
+
from sinapsis_contracts.local_api.models import AgentResponse, AgentsResponse
|
|
10
|
+
from sinapsis_contracts.local_api.paths import API_AGENT_PATHS
|
|
11
|
+
|
|
12
|
+
from sinapsis_api.constants import AgentStatus, ControlType
|
|
13
|
+
from sinapsis_api.env_vars import SINAPSIS_API_EVENT_REPLAY_LIMIT
|
|
14
|
+
|
|
15
|
+
from ._common import (
|
|
16
|
+
command,
|
|
17
|
+
encode_replay_body,
|
|
18
|
+
require_success,
|
|
19
|
+
router_client,
|
|
20
|
+
stream_agent_events,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
agents_router = APIRouter(prefix=API_AGENT_PATHS.base)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@agents_router.post(API_AGENT_PATHS.start, response_model=AgentResponse, status_code=201, tags=["agents"])
|
|
27
|
+
async def start_agent(agent_definition: AgentSchema) -> AgentResponse:
|
|
28
|
+
if not agent_definition.agent.attributes.agent_id:
|
|
29
|
+
agent_definition.agent.attributes.agent_id = str(uuid.uuid4())
|
|
30
|
+
|
|
31
|
+
agent_id = agent_definition.agent.attributes.agent_id
|
|
32
|
+
|
|
33
|
+
response = require_success(
|
|
34
|
+
await router_client.request(
|
|
35
|
+
command(
|
|
36
|
+
ControlType.START_AGENT,
|
|
37
|
+
agent_id=agent_id,
|
|
38
|
+
agent_definition=agent_definition.model_dump(mode="json"),
|
|
39
|
+
)
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
return AgentResponse(agent_id=agent_id, status=AgentStatus.RUNNING.value, stream_id=response["stream_id"])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@agents_router.delete(API_AGENT_PATHS.agent, response_model=AgentResponse, tags=["agents"])
|
|
47
|
+
async def stop_agent(agent_id: str) -> AgentResponse:
|
|
48
|
+
require_success(await router_client.request(command(ControlType.STOP_AGENT, agent_id=agent_id)))
|
|
49
|
+
|
|
50
|
+
return AgentResponse(agent_id=agent_id, status=AgentStatus.STOPPED.value)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@agents_router.get(API_AGENT_PATHS.base, response_model=AgentsResponse, tags=["agents"])
|
|
54
|
+
async def list_agents() -> AgentsResponse:
|
|
55
|
+
response = require_success(await router_client.request(command(ControlType.LIST_AGENTS)))
|
|
56
|
+
|
|
57
|
+
return AgentsResponse(agents=response["agents"], stream_id=response["stream_id"])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@agents_router.get(API_AGENT_PATHS.events, tags=["events"])
|
|
61
|
+
async def replay_agent_events(
|
|
62
|
+
agent_id: str,
|
|
63
|
+
after: int = Query(default=0, ge=0),
|
|
64
|
+
job_id: str | None = None,
|
|
65
|
+
limit: int = Query(default=SINAPSIS_API_EVENT_REPLAY_LIMIT, ge=1, le=SINAPSIS_API_EVENT_REPLAY_LIMIT),
|
|
66
|
+
) -> Response:
|
|
67
|
+
page = await router_client.replay(agent_id=agent_id, after=after, job_id=job_id, limit=limit)
|
|
68
|
+
|
|
69
|
+
metadata = page.metadata
|
|
70
|
+
|
|
71
|
+
headers = {
|
|
72
|
+
ApiConstants.headers.stream_id: str(metadata["stream_id"]),
|
|
73
|
+
ApiConstants.headers.oldest_cursor: str(metadata["oldest_cursor"]),
|
|
74
|
+
ApiConstants.headers.latest_cursor: str(metadata["latest_cursor"]),
|
|
75
|
+
ApiConstants.headers.next_cursor: str(metadata["next_cursor"]),
|
|
76
|
+
ApiConstants.headers.truncated: str(bool(metadata["truncated"])).lower(),
|
|
77
|
+
ApiConstants.headers.has_more: str(bool(metadata["has_more"])).lower(),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return Response(
|
|
81
|
+
content=encode_replay_body(page.events),
|
|
82
|
+
media_type="application/x-sinapsis-events",
|
|
83
|
+
headers=headers,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@agents_router.websocket(API_AGENT_PATHS.events_ws)
|
|
88
|
+
async def agent_event_socket(
|
|
89
|
+
websocket: WebSocket, agent_id: str, after: int | None = None, job_id: str | None = None
|
|
90
|
+
) -> None:
|
|
91
|
+
await stream_agent_events(websocket, agent_id=agent_id, after=after, job_id=job_id)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Health API routes."""
|
|
2
|
+
|
|
3
|
+
from fastapi import APIRouter
|
|
4
|
+
from sinapsis_contracts.common.paths import API_HEALTH_PATHS
|
|
5
|
+
from sinapsis_contracts.local_api.models import HealthResponse
|
|
6
|
+
|
|
7
|
+
from sinapsis_api.constants import ControlType
|
|
8
|
+
|
|
9
|
+
from ._common import command, require_success, router_client
|
|
10
|
+
|
|
11
|
+
health_router = APIRouter()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@health_router.get(API_HEALTH_PATHS.base, response_model=HealthResponse, tags=["health"])
|
|
15
|
+
async def health() -> HealthResponse:
|
|
16
|
+
agent_router_response = await router_client.request(command(ControlType.HEALTH))
|
|
17
|
+
response = require_success(agent_router_response)
|
|
18
|
+
return HealthResponse(status=response["status"], stream_id=response["stream_id"])
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Job API routes."""
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, WebSocket
|
|
6
|
+
from sinapsis_contracts.local_api.models import (
|
|
7
|
+
ApprovalRequest,
|
|
8
|
+
ApprovalResponse,
|
|
9
|
+
JobActionResponse,
|
|
10
|
+
JobResponse,
|
|
11
|
+
StartJobRequest,
|
|
12
|
+
StartJobResponse,
|
|
13
|
+
)
|
|
14
|
+
from sinapsis_contracts.local_api.paths import API_JOB_PATHS
|
|
15
|
+
|
|
16
|
+
from sinapsis_api.constants import ControlType, JobStatus
|
|
17
|
+
|
|
18
|
+
from ._common import (
|
|
19
|
+
command,
|
|
20
|
+
decode_job_payload,
|
|
21
|
+
require_success,
|
|
22
|
+
router_client,
|
|
23
|
+
stream_agent_events,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
jobs_router = APIRouter(prefix=API_JOB_PATHS.base)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@jobs_router.post(API_JOB_PATHS.start, response_model=StartJobResponse, status_code=202, tags=["jobs"])
|
|
30
|
+
async def start_job(body: StartJobRequest) -> StartJobResponse:
|
|
31
|
+
job_id = body.job_id or str(uuid.uuid4())
|
|
32
|
+
|
|
33
|
+
require_success(
|
|
34
|
+
await router_client.request(
|
|
35
|
+
command(
|
|
36
|
+
ControlType.START_JOB,
|
|
37
|
+
job_id=job_id,
|
|
38
|
+
agent_id=body.agent_id,
|
|
39
|
+
payload=decode_job_payload(body.payload),
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
return StartJobResponse(job_id=job_id, agent_id=body.agent_id, status=JobStatus.QUEUED.value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@jobs_router.get(API_JOB_PATHS.job, response_model=JobResponse, tags=["jobs"])
|
|
48
|
+
async def get_job(job_id: str) -> JobResponse:
|
|
49
|
+
response = require_success(await router_client.request(command(ControlType.GET_JOB, job_id=job_id)))
|
|
50
|
+
|
|
51
|
+
return JobResponse.model_validate(response["job"])
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@jobs_router.post(API_JOB_PATHS.cancel, response_model=JobActionResponse, status_code=202, tags=["jobs"])
|
|
55
|
+
async def cancel_job(job_id: str) -> JobActionResponse:
|
|
56
|
+
require_success(await router_client.request(command(ControlType.CANCEL_JOB, job_id=job_id)))
|
|
57
|
+
|
|
58
|
+
return JobActionResponse(job_id=job_id, accepted=True)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@jobs_router.post(API_JOB_PATHS.feedback, response_model=ApprovalResponse, status_code=202, tags=["jobs"])
|
|
62
|
+
async def feedback(job_id: str, body: ApprovalRequest) -> ApprovalResponse:
|
|
63
|
+
require_success(
|
|
64
|
+
await router_client.request(
|
|
65
|
+
command(
|
|
66
|
+
ControlType.APPROVAL_RESPONSE,
|
|
67
|
+
job_id=job_id,
|
|
68
|
+
request_id=body.request_id,
|
|
69
|
+
approved=body.approved,
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return ApprovalResponse(job_id=job_id, request_id=body.request_id, accepted=True)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@jobs_router.websocket(API_JOB_PATHS.events)
|
|
78
|
+
async def job_event_socket(websocket: WebSocket, job_id: str, after: int | None = None) -> None:
|
|
79
|
+
response = require_success(await router_client.request(command(ControlType.GET_JOB, job_id=job_id)))
|
|
80
|
+
|
|
81
|
+
await stream_agent_events(websocket, agent_id=response["job"]["agent_id"], after=after, job_id=job_id)
|