RRSSM-agent-os 0.1.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.
Files changed (74) hide show
  1. agent_os/__init__.py +62 -0
  2. agent_os/api/__init__.py +5 -0
  3. agent_os/api/app.py +83 -0
  4. agent_os/api/routes.py +449 -0
  5. agent_os/cli.py +47 -0
  6. agent_os/config/__init__.py +0 -0
  7. agent_os/config/settings.py +203 -0
  8. agent_os/ipc/__init__.py +13 -0
  9. agent_os/ipc/channel.py +30 -0
  10. agent_os/ipc/deduplication.py +21 -0
  11. agent_os/ipc/ipc_manager.py +165 -0
  12. agent_os/ipc/message.py +16 -0
  13. agent_os/ipc/queue.py +82 -0
  14. agent_os/kernel/__init__.py +0 -0
  15. agent_os/kernel/agent_process.py +86 -0
  16. agent_os/kernel/process_manager.py +337 -0
  17. agent_os/kernel/process_table.py +114 -0
  18. agent_os/kernel/state_machine.py +191 -0
  19. agent_os/llm/__init__.py +11 -0
  20. agent_os/llm/base.py +21 -0
  21. agent_os/llm/manager.py +22 -0
  22. agent_os/llm/mock.py +55 -0
  23. agent_os/memory/__init__.py +4 -0
  24. agent_os/memory/checkpoint.py +55 -0
  25. agent_os/memory/context_manager.py +172 -0
  26. agent_os/memory/context_page.py +18 -0
  27. agent_os/memory/lru.py +22 -0
  28. agent_os/memory/swap_manager.py +40 -0
  29. agent_os/metrics/__init__.py +4 -0
  30. agent_os/metrics/collector.py +144 -0
  31. agent_os/metrics/events.py +194 -0
  32. agent_os/persistence/__init__.py +21 -0
  33. agent_os/persistence/database.py +32 -0
  34. agent_os/persistence/models.py +103 -0
  35. agent_os/persistence/repository.py +87 -0
  36. agent_os/resources/__init__.py +0 -0
  37. agent_os/resources/manager.py +110 -0
  38. agent_os/resources/quota.py +37 -0
  39. agent_os/resources/usage.py +37 -0
  40. agent_os/runtime/__init__.py +13 -0
  41. agent_os/runtime/cancellation.py +23 -0
  42. agent_os/runtime/event_loop.py +73 -0
  43. agent_os/runtime/executor.py +89 -0
  44. agent_os/runtime/timeout.py +16 -0
  45. agent_os/sandbox/__init__.py +0 -0
  46. agent_os/sandbox/sandbox.py +91 -0
  47. agent_os/scheduler/__init__.py +13 -0
  48. agent_os/scheduler/aging.py +38 -0
  49. agent_os/scheduler/base.py +12 -0
  50. agent_os/scheduler/priority.py +76 -0
  51. agent_os/scheduler/scheduler.py +32 -0
  52. agent_os/scheduler/weighted_fair.py +81 -0
  53. agent_os/sdk/__init__.py +64 -0
  54. agent_os/sdk/agent.py +45 -0
  55. agent_os/sdk/kernel.py +951 -0
  56. agent_os/sdk/registry.py +116 -0
  57. agent_os/sdk/wrapper.py +131 -0
  58. agent_os/security/__init__.py +0 -0
  59. agent_os/security/capability.py +32 -0
  60. agent_os/security/policy.py +19 -0
  61. agent_os/supervisor/__init__.py +12 -0
  62. agent_os/supervisor/failure.py +28 -0
  63. agent_os/supervisor/restart.py +48 -0
  64. agent_os/supervisor/supervisor.py +135 -0
  65. agent_os/synchronization/__init__.py +14 -0
  66. agent_os/synchronization/deadlock.py +73 -0
  67. agent_os/synchronization/lock.py +62 -0
  68. agent_os/synchronization/semaphore.py +52 -0
  69. agent_os/synchronization/sync_manager.py +67 -0
  70. rrssm_agent_os-0.1.0.dist-info/METADATA +258 -0
  71. rrssm_agent_os-0.1.0.dist-info/RECORD +74 -0
  72. rrssm_agent_os-0.1.0.dist-info/WHEEL +5 -0
  73. rrssm_agent_os-0.1.0.dist-info/entry_points.txt +2 -0
  74. rrssm_agent_os-0.1.0.dist-info/top_level.txt +1 -0
agent_os/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """
2
+ Agent-OS — Top-level public API
3
+
4
+ When users write `import agent_os`, they get both:
5
+ - The SDK decorator API: register, Kernel, AutoWrapper
6
+ - The OS types: ProcessState, StepStatus, AgentStepResult, WaitReason
7
+
8
+ Usage:
9
+ import agent_os
10
+
11
+ @agent_os.register(priority=7, name="MyAgent")
12
+ class MyAgent:
13
+ async def run(self) -> str:
14
+ return "done"
15
+
16
+ async def main():
17
+ kernel = agent_os.Kernel()
18
+ await kernel.boot()
19
+ await kernel.spawn_registered()
20
+ await kernel.run()
21
+
22
+ asyncio.run(main())
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from agent_os.sdk.registry import (
27
+ register,
28
+ get_registry,
29
+ clear_registry,
30
+ registered_count,
31
+ AgentRegistration,
32
+ )
33
+ from agent_os.sdk.wrapper import AutoWrapper
34
+ from agent_os.sdk.kernel import Kernel, KernelNotBootedError
35
+ from agent_os.sdk.agent import Agent, AgentContext
36
+
37
+ # Core OS types — always available
38
+ from agent_os.kernel.state_machine import (
39
+ AgentStepResult,
40
+ StepStatus,
41
+ WaitReason,
42
+ ProcessState,
43
+ )
44
+
45
+ __all__ = [
46
+ # SDK
47
+ "register",
48
+ "get_registry",
49
+ "clear_registry",
50
+ "registered_count",
51
+ "AgentRegistration",
52
+ "AutoWrapper",
53
+ "Kernel",
54
+ "KernelNotBootedError",
55
+ "Agent",
56
+ "AgentContext",
57
+ # OS types
58
+ "AgentStepResult",
59
+ "StepStatus",
60
+ "WaitReason",
61
+ "ProcessState",
62
+ ]
@@ -0,0 +1,5 @@
1
+ """Agent-OS API package."""
2
+ from .app import app, create_app
3
+ from .routes import router, set_kernel_state
4
+
5
+ __all__ = ["app", "create_app", "router", "set_kernel_state"]
agent_os/api/app.py ADDED
@@ -0,0 +1,83 @@
1
+ """
2
+ Agent-OS API Application (FastAPI)
3
+
4
+ Provides the REST API server for Agent-OS.
5
+ Initializes the kernel AND persistence layer on startup.
6
+ """
7
+ import asyncio
8
+ from contextlib import asynccontextmanager
9
+
10
+ from fastapi import FastAPI
11
+ from fastapi.responses import RedirectResponse
12
+
13
+ from agent_os.config.settings import Settings
14
+ from agent_os.api.routes import router, set_demo_components, use_kernel
15
+
16
+ # Persistence (optional — gracefully disabled if sqlalchemy not installed)
17
+ _db_manager = None
18
+ try:
19
+ from agent_os.persistence.database import DatabaseManager
20
+ _HAS_PERSISTENCE = True
21
+ except ImportError:
22
+ _HAS_PERSISTENCE = False
23
+
24
+
25
+ @asynccontextmanager
26
+ async def lifespan(app: FastAPI):
27
+ """Boot the Agent-OS kernel + persistence layer when the server starts."""
28
+ from agent_os.sdk.kernel import Kernel
29
+
30
+ settings = Settings()
31
+ kernel = Kernel(settings) # the real Agent-OS kernel: scheduler, supervisor, sync, ...
32
+ await kernel.boot()
33
+
34
+ # ── Phase 7: Boot persistence layer ───────────────────────────────────
35
+ global _db_manager
36
+ if _HAS_PERSISTENCE:
37
+ try:
38
+ _db_manager = DatabaseManager(settings.persistence.database_url)
39
+ await _db_manager.initialize()
40
+ print(f"[Agent-OS] Persistence layer online: {settings.persistence.database_url}")
41
+ except Exception as e:
42
+ print(f"[Agent-OS] Persistence unavailable (continuing without it): {e}")
43
+ _db_manager = None
44
+ else:
45
+ print("[Agent-OS] Persistence disabled (sqlalchemy/aiosqlite not installed)")
46
+
47
+ use_kernel(kernel) # REST cancel/pause/resume go through the kernel
48
+ set_demo_components(
49
+ supervisor=kernel.supervisor,
50
+ ipc_manager=kernel.ipc,
51
+ event_manager=kernel.events,
52
+ process_manager=kernel.pm,
53
+ )
54
+ print("[Agent-OS] Kernel booted successfully.")
55
+ yield
56
+
57
+ # ── Shutdown ───────────────────────────────────────────────────────────
58
+ if _db_manager:
59
+ await _db_manager.close()
60
+ await kernel.shutdown()
61
+ print("[Agent-OS] Kernel shutting down.")
62
+
63
+
64
+ def create_app() -> FastAPI:
65
+ app = FastAPI(
66
+ title="Agent-OS API",
67
+ description=(
68
+ "REST API for Agent-OS: treating LLM agents as first-class OS processes. "
69
+ "Provides scheduling, IPC, memory, supervisor, and deadlock detection."
70
+ ),
71
+ version="0.1.0",
72
+ lifespan=lifespan,
73
+ )
74
+ app.include_router(router)
75
+
76
+ @app.get("/", include_in_schema=False)
77
+ async def root():
78
+ return RedirectResponse(url="/docs")
79
+
80
+ return app
81
+
82
+
83
+ app = create_app()
agent_os/api/routes.py ADDED
@@ -0,0 +1,449 @@
1
+ """
2
+ Agent-OS API Routes
3
+
4
+ All REST endpoints for managing processes, IPC, events, health, and demo.
5
+ """
6
+ import asyncio
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any, Optional
10
+
11
+ from fastapi import APIRouter, HTTPException, Query, BackgroundTasks
12
+ from pydantic import BaseModel
13
+
14
+ from agent_os.kernel.state_machine import StepStatus, AgentStepResult, ProcessState
15
+ from agent_os.sdk.agent import AgentContext
16
+
17
+ router = APIRouter()
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Kernel state holder — populated by app.py lifespan
22
+ # ---------------------------------------------------------------------------
23
+
24
+ class KernelState:
25
+ def __init__(self):
26
+ self.process_manager = None
27
+ self.event_manager = None
28
+ self.metrics_collector = None
29
+ self.ipc_manager = None
30
+ self.kernel = None # sdk.Kernel driving these subsystems (if any)
31
+ # Demo components
32
+ self.supervisor = None
33
+ self.demo_running = False
34
+ self.demo_status = "idle" # idle | running | done | error
35
+ self.demo_report = None
36
+
37
+
38
+ _ks = KernelState()
39
+
40
+
41
+ def set_kernel_state(process_manager, event_manager, metrics_collector, ipc_manager, kernel=None):
42
+ _ks.process_manager = process_manager
43
+ _ks.event_manager = event_manager
44
+ _ks.metrics_collector = metrics_collector
45
+ _ks.ipc_manager = ipc_manager
46
+ _ks.kernel = kernel
47
+
48
+
49
+ def use_kernel(kernel) -> None:
50
+ """Point every endpoint at a booted sdk.Kernel (processes, events, IPC, operator actions)."""
51
+ set_kernel_state(kernel.pm, kernel.events, kernel.metrics, kernel.ipc, kernel=kernel)
52
+
53
+
54
+ def set_demo_components(supervisor, ipc_manager, event_manager, process_manager):
55
+ _ks.supervisor = supervisor
56
+
57
+
58
+ def set_demo_runner(fn):
59
+ """Allow external apps (e.g. the showcase) to override the demo pipeline function."""
60
+ global _run_demo_pipeline
61
+ _run_demo_pipeline = fn
62
+
63
+
64
+ def _get_pm():
65
+ if not _ks.process_manager:
66
+ raise HTTPException(status_code=503, detail="Kernel not initialized.")
67
+ return _ks.process_manager
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Request / Response models
72
+ # ---------------------------------------------------------------------------
73
+
74
+ class ProcessCreateReq(BaseModel):
75
+ name: Optional[str] = "api-agent"
76
+ priority: int = 5
77
+
78
+ class MessageSendReq(BaseModel):
79
+ payload: Any
80
+ message_type: str = "DATA"
81
+
82
+ class IPCSendReq(BaseModel):
83
+ sender_pid: int
84
+ receiver_pid: int
85
+ payload: Any
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # NoOp agent for API-spawned processes
90
+ # ---------------------------------------------------------------------------
91
+
92
+ class NoOpAgent:
93
+ """A placeholder agent created via the API."""
94
+ async def step(self, context: AgentContext) -> AgentStepResult:
95
+ return AgentStepResult(status=StepStatus.COMPLETED, output="NoOp agent completed.")
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # Process serializer
100
+ # ---------------------------------------------------------------------------
101
+
102
+ def _serialize_process(p) -> dict:
103
+ return {
104
+ "process_id": p.process_id,
105
+ "name": p.name,
106
+ "state": p.state.value,
107
+ "priority": p.priority,
108
+ "weight": p.weight,
109
+ "restart_count": p.restart_count,
110
+ "restart_policy": p.restart_policy,
111
+ "waiting_for": p.waiting_for.value if p.waiting_for else None,
112
+ "creation_time": p.creation_time,
113
+ "resource_usage": {
114
+ "steps": p.resource_usage.steps,
115
+ "total_tokens": p.resource_usage.total_tokens,
116
+ "llm_calls": p.resource_usage.llm_calls,
117
+ "tool_calls": p.resource_usage.tool_calls,
118
+ "input_tokens": p.resource_usage.input_tokens,
119
+ "output_tokens":p.resource_usage.output_tokens,
120
+ },
121
+ "resource_limits": {
122
+ "step_limit": p.resource_limits.step_limit,
123
+ "token_limit": p.resource_limits.token_limit,
124
+ },
125
+ }
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Process endpoints
130
+ # ---------------------------------------------------------------------------
131
+
132
+ @router.get("/processes", tags=["Processes"])
133
+ async def list_processes():
134
+ pm = _get_pm()
135
+ return [_serialize_process(p) for p in await pm.list()]
136
+
137
+
138
+ @router.post("/processes", tags=["Processes"])
139
+ async def create_process(req: ProcessCreateReq):
140
+ pm = _get_pm()
141
+ proc = await pm.spawn(NoOpAgent(), name=req.name, priority=req.priority)
142
+ return _serialize_process(proc)
143
+
144
+
145
+ @router.get("/processes/{pid}", tags=["Processes"])
146
+ async def get_process(pid: int):
147
+ pm = _get_pm()
148
+ try:
149
+ p = await pm.get(pid)
150
+ return _serialize_process(p)
151
+ except Exception:
152
+ raise HTTPException(status_code=404, detail=f"Process {pid} not found")
153
+
154
+
155
+ @router.post("/processes/{pid}/cancel", tags=["Processes"])
156
+ async def cancel_process(pid: int):
157
+ pm = _get_pm()
158
+ try:
159
+ if _ks.kernel is not None:
160
+ # Kernel path: reclaim locks/memory, CANCELLED → TERMINATED, orphan policy.
161
+ await _ks.kernel.cancel(pid)
162
+ else:
163
+ await pm.cancel(pid)
164
+ await pm.terminate(pid)
165
+ return {"status": "cancelled", "process_id": pid, "state": (await pm.get(pid)).state.value}
166
+ except Exception as e:
167
+ raise HTTPException(status_code=400, detail=str(e))
168
+
169
+
170
+ @router.post("/processes/{pid}/terminate", tags=["Processes"])
171
+ async def terminate_process(pid: int):
172
+ pm = _get_pm()
173
+ try:
174
+ if _ks.kernel is not None:
175
+ await _ks.kernel.cancel(pid)
176
+ else:
177
+ await pm.terminate(pid)
178
+ return {"status": "terminated", "process_id": pid}
179
+ except Exception as e:
180
+ raise HTTPException(status_code=400, detail=str(e))
181
+
182
+
183
+ @router.post("/processes/{pid}/pause", tags=["Processes"])
184
+ async def pause_process(pid: int):
185
+ pm = _get_pm()
186
+ try:
187
+ if _ks.kernel is not None:
188
+ await _ks.kernel.pause(pid)
189
+ else:
190
+ await pm.pause(pid)
191
+ state = (await pm.get(pid)).state.value
192
+ if state not in ("WAITING", "BLOCKED"):
193
+ raise HTTPException(status_code=409, detail=f"Process {pid} is {state}; it cannot be paused")
194
+ return {"status": "paused", "process_id": pid, "state": state}
195
+ except HTTPException:
196
+ raise
197
+ except Exception as e:
198
+ raise HTTPException(status_code=400, detail=str(e))
199
+
200
+
201
+ @router.post("/processes/{pid}/resume", tags=["Processes"])
202
+ async def resume_process(pid: int):
203
+ pm = _get_pm()
204
+ try:
205
+ if _ks.kernel is not None:
206
+ await _ks.kernel.resume(pid)
207
+ else:
208
+ await pm.resume(pid)
209
+ return {"status": "resumed", "process_id": pid, "state": (await pm.get(pid)).state.value}
210
+ except Exception as e:
211
+ raise HTTPException(status_code=400, detail=str(e))
212
+
213
+
214
+ # ---------------------------------------------------------------------------
215
+ # IPC endpoints
216
+ # ---------------------------------------------------------------------------
217
+
218
+ @router.post("/processes/{pid}/messages", tags=["IPC"])
219
+ async def send_message_to_pid(pid: int, req: MessageSendReq):
220
+ if not _ks.ipc_manager:
221
+ raise HTTPException(status_code=503, detail="IPC Manager not configured")
222
+ try:
223
+ msg = await _ks.ipc_manager.send(
224
+ sender_pid=0,
225
+ receiver_pid=pid,
226
+ payload=req.payload,
227
+ )
228
+ return {"status": "sent", "message_id": msg.message_id}
229
+ except Exception as e:
230
+ raise HTTPException(status_code=400, detail=str(e))
231
+
232
+
233
+ @router.get("/processes/{pid}/messages", tags=["IPC"])
234
+ async def get_messages(pid: int):
235
+ if not _ks.ipc_manager:
236
+ raise HTTPException(status_code=503, detail="IPC Manager not configured")
237
+ msg = await _ks.ipc_manager.receive(pid)
238
+ if not msg:
239
+ return {"message": None}
240
+ return {
241
+ "message_id": msg.message_id,
242
+ "sender_pid": msg.sender_pid,
243
+ "receiver_pid": msg.receiver_pid,
244
+ "payload": msg.payload,
245
+ "delivery_status":msg.delivery_status,
246
+ }
247
+
248
+
249
+ @router.post("/ipc/send", tags=["IPC"])
250
+ async def ipc_send(req: IPCSendReq):
251
+ """Send a message between any two PIDs."""
252
+ if not _ks.ipc_manager:
253
+ raise HTTPException(status_code=503, detail="IPC Manager not configured")
254
+ try:
255
+ msg = await _ks.ipc_manager.send(
256
+ sender_pid=req.sender_pid,
257
+ receiver_pid=req.receiver_pid,
258
+ payload=req.payload,
259
+ )
260
+ return {"status": "sent", "message_id": msg.message_id}
261
+ except Exception as e:
262
+ raise HTTPException(status_code=400, detail=str(e))
263
+
264
+
265
+ @router.get("/ipc/receive/{pid}", tags=["IPC"])
266
+ async def ipc_receive(pid: int):
267
+ """Peek at the next queued message for a PID."""
268
+ if not _ks.ipc_manager:
269
+ raise HTTPException(status_code=503, detail="IPC Manager not configured")
270
+ msg = await _ks.ipc_manager.receive(pid)
271
+ if not msg:
272
+ return {"message": None}
273
+ return {
274
+ "message_id": msg.message_id,
275
+ "sender_pid": msg.sender_pid,
276
+ "receiver_pid": msg.receiver_pid,
277
+ "payload": msg.payload,
278
+ "delivery_status":msg.delivery_status,
279
+ }
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # Events & Metrics
284
+ # ---------------------------------------------------------------------------
285
+
286
+ @router.get("/events", tags=["Observability"])
287
+ async def get_events(
288
+ event_type: Optional[str] = None,
289
+ process_id: Optional[int] = None,
290
+ limit: int = Query(200, ge=1, le=1000),
291
+ ):
292
+ if not _ks.event_manager:
293
+ raise HTTPException(status_code=503, detail="Event manager not configured")
294
+ # Filter BEFORE applying the limit, otherwise rare events (deadlocks, locks)
295
+ # fall outside the window of the most recent N events and are never returned.
296
+ # event_type accepts a comma-separated list, e.g. DEADLOCK_DETECTED,LOCK_ACQUIRED
297
+ events = await _ks.event_manager.get_history(process_id=process_id)
298
+ if event_type:
299
+ wanted = {t.strip() for t in event_type.split(",") if t.strip()}
300
+ events = [e for e in events if e.event_type.value in wanted]
301
+ events = events[-limit:]
302
+ return [
303
+ {
304
+ "event_id": e.event_id,
305
+ "event_type": e.event_type.value,
306
+ "process_id": e.process_id,
307
+ "timestamp": e.timestamp,
308
+ "metadata": e.metadata,
309
+ }
310
+ for e in events
311
+ ]
312
+
313
+
314
+ @router.get("/metrics", tags=["Observability"])
315
+ async def get_metrics():
316
+ pm = _ks.process_manager
317
+ if not pm:
318
+ return {}
319
+ procs = await pm.list()
320
+ total_tokens = sum(p.resource_usage.total_tokens for p in procs)
321
+ total_steps = sum(p.resource_usage.steps for p in procs)
322
+ total_llm = sum(p.resource_usage.llm_calls for p in procs)
323
+ by_state = {}
324
+ for p in procs:
325
+ by_state[p.state.value] = by_state.get(p.state.value, 0) + 1
326
+ events = await _ks.event_manager.get_history(limit=1000) if _ks.event_manager else []
327
+ return {
328
+ "total_processes": len(procs),
329
+ "total_tokens": total_tokens,
330
+ "total_steps": total_steps,
331
+ "total_llm_calls": total_llm,
332
+ "total_events": len(events),
333
+ "by_state": by_state,
334
+ "demo_status": _ks.demo_status,
335
+ }
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # Health
340
+ # ---------------------------------------------------------------------------
341
+
342
+ @router.get("/health", tags=["System"])
343
+ async def health_check():
344
+ pm = _ks.process_manager
345
+ if not pm:
346
+ return {"status": "booting", "process_count": 0, "demo_status": "idle"}
347
+ procs = await pm.list()
348
+ return {
349
+ "status": "healthy",
350
+ "process_count": len(procs),
351
+ "demo_status": _ks.demo_status,
352
+ }
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # Demo endpoint — runs the full Research Intelligence Pipeline
357
+ # inside the live server kernel so the UI sees everything in real time
358
+ # ---------------------------------------------------------------------------
359
+
360
+ async def _run_demo_pipeline():
361
+ """Background task: run the Orbital Research Lab (showcase_full/) on the live server.
362
+
363
+ Nine missions, each on its own native agent_os.Kernel, ~110 agents and 62
364
+ scenarios. The routes follow the run live; the scorecard is at GET /demo/report.
365
+ """
366
+ _ks.demo_status = "running"
367
+ _ks.demo_report = {"status": "running", "current_mission": "booting"}
368
+ try:
369
+ _ROOT = Path(__file__).resolve().parents[3]
370
+ _SHOWCASE = _ROOT / "showcase_full"
371
+ if str(_SHOWCASE) not in sys.path:
372
+ sys.path.insert(0, str(_SHOWCASE))
373
+ from live import run_live
374
+
375
+ def publish(report):
376
+ _ks.demo_report = report
377
+
378
+ report = await run_live(_ks, pace=0.02, publish=publish)
379
+ _ks.demo_status = "done" if report["counts"]["FAIL"] == 0 else "error"
380
+ except Exception as e:
381
+ _ks.demo_status = "error"
382
+ _ks.demo_report = {"status": "error", "error": repr(e)}
383
+ print(f"[Agent-OS Demo] Error: {e!r}")
384
+ raise
385
+
386
+
387
+ @router.get("/demo/report", tags=["Demo"])
388
+ async def demo_report():
389
+ """Scorecard of the running / last demo: per-scenario outcome and evidence."""
390
+ return _ks.demo_report or {"status": "idle"}
391
+
392
+
393
+ @router.post("/demo/run", tags=["Demo"])
394
+ async def run_demo(background_tasks: BackgroundTasks):
395
+ """
396
+ Trigger the Orbital Research Lab demo (showcase_full/: 9 missions, 62 scenarios).
397
+ Runs in the background — poll /processes and /events to see live data.
398
+ """
399
+ if _ks.demo_status == "running":
400
+ return {"status": "already_running", "message": "Demo is already in progress"}
401
+
402
+ _ks.demo_status = "running"
403
+ background_tasks.add_task(_run_demo_pipeline)
404
+ return {
405
+ "status": "started",
406
+ "message": "Demo pipeline started. Poll /processes and /events to see live data.",
407
+ }
408
+
409
+
410
+ @router.get("/demo/status", tags=["Demo"])
411
+ async def demo_status():
412
+ """Check whether a demo pipeline is running."""
413
+ pm = _ks.process_manager
414
+ procs = await pm.list() if pm else []
415
+ return {
416
+ "demo_status": _ks.demo_status,
417
+ "process_count": len(procs),
418
+ }
419
+
420
+
421
+ @router.post("/demo/reset", tags=["Demo"])
422
+ async def reset_demo():
423
+ """Clear all processes and event history so the demo can be re-run."""
424
+ if _ks.demo_status == "running":
425
+ raise HTTPException(status_code=409, detail="Demo is still running. Wait for it to finish.")
426
+
427
+ pm = _ks.process_manager
428
+ em = _ks.event_manager
429
+
430
+ if pm:
431
+ procs = await pm.list()
432
+ for p in procs:
433
+ try:
434
+ if p.state not in (ProcessState.TERMINATED,):
435
+ await pm.terminate(p.process_id)
436
+ except Exception:
437
+ pass
438
+ for p in procs:
439
+ try:
440
+ await pm.remove(p.process_id)
441
+ except Exception:
442
+ pass
443
+
444
+ if em:
445
+ await em.clear_history()
446
+
447
+ _ks.demo_status = "idle"
448
+ _ks.demo_report = None
449
+ return {"status": "reset", "message": "All processes cleared. Ready to run demo again."}
agent_os/cli.py ADDED
@@ -0,0 +1,47 @@
1
+ """Agent-OS CLI Entry Point."""
2
+ from __future__ import annotations
3
+ import sys
4
+ import argparse
5
+
6
+
7
+ def main() -> None:
8
+ parser = argparse.ArgumentParser(
9
+ prog="agent-os",
10
+ description="Agent-OS — Operating System for LLM Agents",
11
+ )
12
+ sub = parser.add_subparsers(dest="command")
13
+
14
+ # server
15
+ srv = sub.add_parser("server", help="Start the Agent-OS REST API server")
16
+ srv.add_argument("--host", default="0.0.0.0", help="Bind host (default: 0.0.0.0)")
17
+ srv.add_argument("--port", type=int, default=8000, help="Bind port (default: 8000)")
18
+ srv.add_argument("--reload", action="store_true", help="Enable auto-reload for development")
19
+
20
+ # version
21
+ sub.add_parser("version", help="Print Agent-OS version")
22
+
23
+ args = parser.parse_args()
24
+
25
+ if args.command == "server":
26
+ try:
27
+ import uvicorn
28
+ from agent_os.api.app import app
29
+ uvicorn.run(
30
+ "agent_os.api.app:app",
31
+ host=args.host,
32
+ port=args.port,
33
+ reload=args.reload,
34
+ )
35
+ except ImportError:
36
+ print("uvicorn not found. Install with: pip install uvicorn[standard]")
37
+ sys.exit(1)
38
+
39
+ elif args.command == "version":
40
+ print("agent-os 0.1.0")
41
+
42
+ else:
43
+ parser.print_help()
44
+
45
+
46
+ if __name__ == "__main__":
47
+ main()
File without changes