rusticai-api 1.4.0__tar.gz → 1.5.1__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.
Files changed (31) hide show
  1. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/PKG-INFO +16 -12
  2. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/pyproject.toml +34 -22
  3. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/catalog/catalog_store.py +1 -1
  4. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/comms_manager.py +16 -4
  5. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/router.py +31 -0
  6. rusticai_api-1.5.1/src/rustic_ai/api_server/guilds/schema.py +45 -0
  7. rusticai_api-1.5.1/src/rustic_ai/api_server/guilds/service.py +210 -0
  8. rusticai_api-1.4.0/src/rustic_ai/api_server/guilds/schema.py +0 -25
  9. rusticai_api-1.4.0/src/rustic_ai/api_server/guilds/service.py +0 -96
  10. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/README.md +0 -0
  11. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/__init__.py +0 -0
  12. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/__init__.py +0 -0
  13. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/boards/__init__.py +0 -0
  14. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/boards/board_store.py +0 -0
  15. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/boards/models.py +0 -0
  16. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/boards/router.py +0 -0
  17. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/boards/schema.py +0 -0
  18. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/addons/router.py +0 -0
  19. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/api_dependency_manager.py +0 -0
  20. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/catalog/__init__.py +0 -0
  21. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/catalog/models.py +0 -0
  22. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/catalog/router.py +0 -0
  23. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/__init__.py +0 -0
  24. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/models.py +0 -0
  25. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/socket.py +0 -0
  26. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/guilds/system_comms_manager.py +0 -0
  27. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/logging/__init__.py +0 -0
  28. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/logging/config.py +0 -0
  29. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/logging/format.py +0 -0
  30. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/main.py +0 -0
  31. {rusticai_api-1.4.0 → rusticai_api-1.5.1}/src/rustic_ai/api_server/main_debug.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rusticai-api
3
- Version: 1.4.0
3
+ Version: 1.5.1
4
4
  Summary: API Server for Rustic AI
5
5
  License-Expression: Apache-2.0
6
6
  Author: Dragonscale Industries Inc.
@@ -9,18 +9,22 @@ Requires-Python: >=3.13,<3.14
9
9
  Classifier: Programming Language :: Python :: 3
10
10
  Classifier: Programming Language :: Python :: 3.13
11
11
  Provides-Extra: test
12
- Requires-Dist: fastapi (>=0.139.2,<0.140.0)
13
- Requires-Dist: griffe (>=2.1.0,<3.0.0)
14
- Requires-Dist: opentelemetry-distro (>=0.65b0,<0.66)
15
- Requires-Dist: psycopg (>=3.3.4,<4.0.0)
12
+ Requires-Dist: fastapi (>=0.165.0,<0.166.0)
13
+ Requires-Dist: griffe (>=2.4.1,<3.0.0)
14
+ Requires-Dist: httpx (>=0.29.0,<0.30.0) ; extra == "test"
15
+ Requires-Dist: opentelemetry-distro (>=0.67b1,<0.68)
16
+ Requires-Dist: psycopg (>=3.3.9,<4.0.0)
16
17
  Requires-Dist: ptvsd (>=4.3.2,<5.0.0)
17
- Requires-Dist: python-json-logger (>=4.1.0,<5.0.0)
18
- Requires-Dist: python-multipart (>=0.0.32,<0.0.33)
19
- Requires-Dist: rusticai-core (>=1.4.0,<1.5.0)
20
- Requires-Dist: rusticai-ray (>=1.4.0,<1.5.0)
21
- Requires-Dist: starlette (>=1.3.1,<2.0.0)
22
- Requires-Dist: uvicorn (>=0.51.0,<0.52.0)
23
- Requires-Dist: websockets (>=16.1.1,<17.0.0)
18
+ Requires-Dist: pytest (>=9.2.0,<10.0.0) ; extra == "test"
19
+ Requires-Dist: pytest-asyncio (>=1.5.0,<2.0.0) ; extra == "test"
20
+ Requires-Dist: python-json-logger (>=4.2.0,<5.0.0)
21
+ Requires-Dist: python-multipart (>=0.0.34,<0.0.35)
22
+ Requires-Dist: rusticai-core (>=1.5.4,<1.6.0)
23
+ Requires-Dist: rusticai-ray (>=1.5.0,<1.6.0)
24
+ Requires-Dist: rusticai-testing (>=1.5.1,<1.6.0) ; extra == "test"
25
+ Requires-Dist: starlette (>=1.10.0,<2.0.0)
26
+ Requires-Dist: uvicorn (>=0.54.0,<0.55.0)
27
+ Requires-Dist: websockets (>=17.4,<18.0)
24
28
  Project-URL: Homepage, https://www.rustic.ai/
25
29
  Project-URL: Repository, https://github.com/rustic-ai/rustic-ai
26
30
  Project-URL: Rustic AI Core, https://pypi.org/project/rusticai-core/
@@ -1,11 +1,11 @@
1
1
  [build-system]
2
- requires = ["poetry-core"]
2
+ requires = ["poetry-core>=2.5.0,<3.0.0"]
3
3
  build-backend = "poetry.core.masonry.api"
4
4
 
5
5
 
6
6
  [project]
7
7
  name = "rusticai-api"
8
- version = "1.4.0"
8
+ version = "1.5.1"
9
9
  description = "API Server for Rustic AI"
10
10
  authors = [{name = "Dragonscale Industries Inc.", email = "dev@dragonscale.ai"}]
11
11
  license = "Apache-2.0"
@@ -19,19 +19,31 @@ urls = { Homepage = "https://www.rustic.ai/", Repository = "https://github.com/r
19
19
  packages = [{ include = "rustic_ai", from = "src" }]
20
20
 
21
21
  [tool.poetry.dependencies]
22
- rusticai-core = { version = "1.4.0"}
23
- rusticai-ray = { version = "1.4.0"}
24
- fastapi = "^0.139.2"
25
- starlette = "^1.3.1"
26
- uvicorn = "^0.51.0"
22
+ rusticai-core = { version = "1.5.4"}
23
+ rusticai-ray = { version = "1.5.0"}
24
+ fastapi = "^0.165.0"
25
+ starlette = "^1.10.0"
26
+ uvicorn = "^0.54.0"
27
27
  ptvsd = "^4.3.2"
28
- python-multipart = "^0.0.32"
29
- opentelemetry-distro = "^0.65b0"
30
- websockets = "^16.1.1"
31
- griffe = "^2.1.0"
32
- psycopg = "^3.3.4"
33
- python-json-logger = "^4.1.0"
28
+ python-multipart = "^0.0.34"
29
+ opentelemetry-distro = "^0.67b1"
30
+ websockets = "^17.4"
31
+ griffe = "^2.4.1"
32
+ psycopg = "^3.3.9"
33
+ python-json-logger = "^4.2.0"
34
+ rusticai-testing = { optional = true, version = "1.5.1"}
34
35
 
36
+ [tool.poetry.dependencies.pytest]
37
+ version = "^9.2.0"
38
+ optional = true
39
+
40
+ [tool.poetry.dependencies.pytest-asyncio]
41
+ version = "^1.5.0"
42
+ optional = true
43
+
44
+ [tool.poetry.dependencies.httpx]
45
+ version = "^0.29.0"
46
+ optional = true
35
47
  [tool.poetry-monorepo.deps]
36
48
 
37
49
 
@@ -39,15 +51,15 @@ python-json-logger = "^4.1.0"
39
51
  optional = true
40
52
 
41
53
  [tool.poetry.group.dev.dependencies]
42
- pytest = "^9.1.1"
43
- black = { version = "^26.5.1", extras = ["jupyter"] }
44
- flake8 = "^7.3.0"
45
- tox = "^4.57.1"
46
- isort = "^8.0.1"
47
- mypy = "^2.3.0"
48
- pytest-asyncio = "^1.4.0"
49
- httpx = "^0.28.1"
50
- rusticai-testing = { version = "1.4.0"}
54
+ pytest = "^9.2.0"
55
+ black = { version = "^26.10.1", extras = ["jupyter"] }
56
+ flake8 = "^7.5.0"
57
+ tox = "^4.67.16"
58
+ isort = "^9.0.2"
59
+ mypy = "^2.4.1"
60
+ pytest-asyncio = "^1.5.0"
61
+ httpx = "^0.29.0"
62
+ rusticai-testing = { version = "1.5.1"}
51
63
 
52
64
  [tool.poetry.extras]
53
65
  test = ["pytest", "pytest-asyncio", "httpx", "rusticai-testing"]
@@ -205,7 +205,7 @@ class CatalogStore:
205
205
  raise HTTPException(status_code=404, detail=f"Blueprint {blueprint_id} not found")
206
206
 
207
207
  # Ensure orginal organization has access when sharing bp with org exposure
208
- if blueprint.exposure == BlueprintExposure.ORGANIZATION:
208
+ if blueprint.exposure == BlueprintExposure.ORGANIZATION and blueprint.organization_id is not None:
209
209
  session.add(
210
210
  BlueprintSharedWithOrganization(
211
211
  organization_id=blueprint.organization_id, blueprint_id=blueprint_id
@@ -23,7 +23,7 @@ from rustic_ai.core.messaging.core.client import Client
23
23
  from rustic_ai.core.messaging.core.message import AgentTag, Message, ProcessEntry
24
24
  from rustic_ai.core.messaging.core.messaging_interface import MessagingInterface
25
25
  from rustic_ai.core.utils.basic_class_utils import get_qualified_class_name
26
- from rustic_ai.core.utils.gemstone_id import GemstoneGenerator
26
+ from rustic_ai.core.utils.gemstone_id import GemstoneGenerator, GemstoneID
27
27
  from rustic_ai.core.utils.priority import Priority
28
28
 
29
29
 
@@ -293,19 +293,31 @@ class GuildCommunicationManager:
293
293
  return result
294
294
 
295
295
  @staticmethod
296
- def historical_message_sort_key(message: Message) -> tuple[int, int, bool, int, int]:
296
+ def historical_message_sort_key(message: Message) -> tuple[float, int, bool, int, int]:
297
297
  """
298
298
  Prefer chronological ordering, but keep messages from the same interaction in causal order.
299
299
 
300
300
  Different agents can generate IDs in the same millisecond with different machine IDs, which can
301
301
  invert user-message/agent-response pairs if we sort purely by message ID.
302
302
  """
303
+ # Notifications and responses travel on separate subjects. A response can
304
+ # arrive before the user's broadcast notification, so use their shared ingress
305
+ # timestamp and routing depth to preserve the order of each interaction.
306
+ interaction_id = next(
307
+ (
308
+ entry.origin
309
+ for entry in reversed(message.message_history)
310
+ if entry.processor == "unwrap_and_forward_message"
311
+ ),
312
+ None,
313
+ )
314
+ timestamp = GemstoneID.from_int(interaction_id).timestamp if interaction_id is not None else message.timestamp
303
315
  # Any message that explicitly responds to an earlier message should come after
304
316
  # the user-originated entry for that interaction, even if it shares the same root.
305
317
  is_follow_up = message.in_response_to is not None
306
318
  return (
307
- message.timestamp,
308
- message.root_thread_id,
319
+ timestamp,
320
+ interaction_id if interaction_id is not None else message.root_thread_id,
309
321
  is_follow_up,
310
322
  len(message.message_history),
311
323
  message.id,
@@ -17,10 +17,13 @@ from starlette import status
17
17
  from rustic_ai.api_server.api_dependency_manager import ApiDependencyManager
18
18
  from rustic_ai.api_server.guilds.comms_manager import GuildCommunicationManager
19
19
  from rustic_ai.api_server.guilds.schema import (
20
+ GuildActionResponse,
20
21
  GuildSpecResponse,
21
22
  IdInfo,
22
23
  LaunchGuildReq,
23
24
  RelaunchResponse,
25
+ RetryGuildReq,
26
+ StopGuildReq,
24
27
  )
25
28
  from rustic_ai.api_server.guilds.service import GuildService
26
29
  from rustic_ai.core import Agent
@@ -99,6 +102,34 @@ def relaunch_guild(guild_id: str, engine=Depends(Metastore.get_engine)):
99
102
  raise
100
103
 
101
104
 
105
+ @router.post(
106
+ "/guilds/{guild_id}/retry",
107
+ response_model=GuildActionResponse,
108
+ status_code=status.HTTP_202_ACCEPTED,
109
+ operation_id="retryGuildLaunch",
110
+ )
111
+ def retry_guild_launch(guild_id: str, req: RetryGuildReq, engine=Depends(Metastore.get_engine)):
112
+ """
113
+ Relaunches the guild's agents whose launch failed. The outcome arrives in the guild's health reports.
114
+ """
115
+ mode = guild_service.retry_guild(guild_id, engine, req.requested_by, req.agent_ids)
116
+ return GuildActionResponse(mode=mode)
117
+
118
+
119
+ @router.post(
120
+ "/guilds/{guild_id}/stop",
121
+ response_model=GuildActionResponse,
122
+ status_code=status.HTTP_202_ACCEPTED,
123
+ operation_id="stopGuild",
124
+ )
125
+ def stop_guild(guild_id: str, req: StopGuildReq, engine=Depends(Metastore.get_engine)):
126
+ """
127
+ Stops the guild. Works whether or not its manager is running.
128
+ """
129
+ mode = guild_service.stop_guild(guild_id, engine, req.user_id)
130
+ return GuildActionResponse(mode=mode)
131
+
132
+
102
133
  @router.get("/guilds/{guild_id}/{user_id}/messages", operation_id="getHistoricalUserMessages")
103
134
  async def get_historical_user_notifications(
104
135
  guild_id: str,
@@ -0,0 +1,45 @@
1
+ from typing import List, Literal, Optional
2
+
3
+ from pydantic import BaseModel
4
+
5
+ from rustic_ai.core.guild.dsl import GuildSpec
6
+ from rustic_ai.core.guild.metastore.models import GuildStatus
7
+
8
+
9
+ class IdInfo(BaseModel):
10
+ id: str
11
+
12
+
13
+ class LaunchGuildReq(BaseModel):
14
+ spec: GuildSpec
15
+ org_id: str
16
+
17
+
18
+ class GuildSpecResponse(GuildSpec):
19
+ """
20
+ Response for a guild specification that describes its name, description, agents, routes, and status.
21
+ """
22
+
23
+ status: GuildStatus
24
+ last_error: Optional[dict] = None
25
+
26
+
27
+ class RelaunchResponse(BaseModel):
28
+ is_relaunching: bool
29
+
30
+
31
+ class RetryGuildReq(BaseModel):
32
+ """Relaunch agents whose launch failed. With no ``agent_ids``, every failed agent and the user's own proxy."""
33
+
34
+ requested_by: str
35
+ agent_ids: Optional[List[str]] = None
36
+
37
+
38
+ class StopGuildReq(BaseModel):
39
+ user_id: str
40
+
41
+
42
+ class GuildActionResponse(BaseModel):
43
+ """How the request was carried out: sent to the running guild manager, or done directly."""
44
+
45
+ mode: Literal["requested", "relaunched", "stopped"]
@@ -0,0 +1,210 @@
1
+ import logging
2
+ import random
3
+ from typing import List, Optional
4
+
5
+ from fastapi import HTTPException
6
+ from pydantic import BaseModel
7
+ from sqlalchemy import Engine
8
+ from sqlmodel import Session
9
+
10
+ from rustic_ai.api_server.guilds.models import GuildRelaunchModel
11
+ from rustic_ai.api_server.guilds.schema import GuildSpecResponse
12
+ from rustic_ai.core import AgentTag, Message, MessagingInterface, Priority
13
+ from rustic_ai.core.agents.system.launch import PlatformSenders, RetryAgentLaunchRequest
14
+ from rustic_ai.core.agents.system.models import StopGuildRequest
15
+ from rustic_ai.core.agents.utils.user_proxy_agent import UserProxyAgent
16
+ from rustic_ai.core.guild import GuildSpec
17
+ from rustic_ai.core.guild.builders import GuildBuilder, GuildHelper
18
+ from rustic_ai.core.guild.dsl import GuildTopics
19
+ from rustic_ai.core.guild.metastore import GuildModel, GuildStore, Metastore
20
+ from rustic_ai.core.guild.metastore.models import AgentModel, AgentStatus, GuildStatus
21
+ from rustic_ai.core.utils import GemstoneGenerator
22
+ from rustic_ai.core.utils.basic_class_utils import get_qualified_class_name
23
+
24
+
25
+ class GuildService:
26
+
27
+ def create_guild(self, metastore_url: str, guild_spec: GuildSpec, organization_id: str) -> str:
28
+ """
29
+ Creates a new guild and adds it to the database.
30
+
31
+ Args:
32
+ metastore_url (str): The URL of the metastore database.
33
+ guild_spec (GuildSpec): The specification of the guild to create.
34
+ organization_id (str): The ID of the organization that owns this guild.
35
+
36
+ Returns:
37
+ str: The ID of the created guild.
38
+ """
39
+ if guild_spec.get_messaging() is None:
40
+ default_messaging = GuildHelper.get_default_messaging_config()
41
+ guild_spec.set_messaging(**default_messaging)
42
+
43
+ if guild_spec.get_execution_engine() is None:
44
+ guild_spec.set_execution_engine(GuildHelper.get_default_execution_engine())
45
+
46
+ guild_spec.dependency_map = GuildHelper.get_guild_dependency_map(guild_spec)
47
+
48
+ engine = Metastore.get_engine(metastore_url)
49
+ with Session(engine) as session:
50
+ logging.info(f"Creating new guild : [{guild_spec}]")
51
+ guild_model = GuildModel.from_guild_spec(guild_spec, organization_id)
52
+ guild_model.status = GuildStatus.REQUESTED
53
+ session.add(guild_model)
54
+ # Add the agents to the Metastore
55
+ for position, guild_agent in enumerate(guild_spec.agents):
56
+ agent_model = AgentModel.from_agent_spec(guild_spec.id, guild_agent, position=position)
57
+ session.add(agent_model)
58
+ session.commit()
59
+
60
+ guild = GuildBuilder.from_spec(guild_spec).bootstrap(metastore_url, organization_id)
61
+
62
+ return guild.id
63
+
64
+ def get_guild(self, engine: Engine, guild_id: str) -> Optional[GuildSpecResponse]:
65
+ """
66
+ Retrieves a guild and its agents from the database.
67
+
68
+ Args:
69
+ engine (Engine): The database engine.
70
+ guild_id (str): The ID of the guild to retrieve.
71
+
72
+ Returns:
73
+ Optional[GuildSpec]: The guild specification if found, None otherwise.
74
+ """
75
+ guild_store = GuildStore(engine)
76
+ guild_model = guild_store.get_guild(guild_id)
77
+
78
+ guild_spec = guild_model.to_guild_spec() if guild_model else None
79
+
80
+ if guild_spec is None:
81
+ return None
82
+
83
+ return GuildSpecResponse(
84
+ **guild_spec.model_dump(),
85
+ status=GuildStatus(guild_model.status) if guild_model else GuildStatus.UNKNOWN,
86
+ last_error=guild_model.last_error if guild_model else None,
87
+ )
88
+
89
+ def relaunch_guild(self, guild_id: str, engine: Engine) -> bool:
90
+ with Session(engine) as session:
91
+ guild_model = GuildModel.get_by_id(session, guild_id)
92
+ if guild_model is None:
93
+ raise HTTPException(status_code=404, detail="Guild not found")
94
+ else:
95
+ if guild_model.status in [GuildStatus.STOPPED, GuildStatus.STOPPING]:
96
+ raise HTTPException(status_code=400, detail="Guild is already stopped")
97
+ guild_spec = guild_model.to_guild_spec()
98
+ guild = GuildHelper.shallow_guild_from_spec(guild_spec, guild_model.organization_id)
99
+ mgr_agent_id = GuildHelper.get_manager_agent_id(guild.id)
100
+ is_guild_running = guild.is_agent_running(mgr_agent_id)
101
+ if not is_guild_running:
102
+ logging.info(f"Guild {guild.id} is not running. Relaunching it.")
103
+ # A relaunch is a retry of everything: the manager won't relaunch an agent whose
104
+ # recorded failure still stands.
105
+ self._clear_launch_failures(session, guild_model)
106
+ relaunch_entry = GuildRelaunchModel(guild_id=guild_id)
107
+ session.add(relaunch_entry)
108
+ session.commit()
109
+ GuildBuilder.from_spec(guild_spec).bootstrap(Metastore.get_db_url(), guild_model.organization_id)
110
+ return not is_guild_running
111
+
112
+ @staticmethod
113
+ def _clear_launch_failures(
114
+ session: Session,
115
+ guild_model: GuildModel,
116
+ agent_ids: Optional[List[str]] = None,
117
+ requested_by: Optional[str] = None,
118
+ ):
119
+ """Clear recorded launch failures so the manager launches those agents again.
120
+
121
+ With ``requested_by``, other users' proxies keep their failures: one user's retry doesn't
122
+ relaunch another user's agent. ``agent_ids`` empty or None means every agent.
123
+ """
124
+ own_proxy = UserProxyAgent.get_user_agent_id(requested_by) if requested_by is not None else None
125
+ proxy_prefix = UserProxyAgent.get_user_agent_id("")
126
+ if guild_model.last_error is not None:
127
+ guild_model.last_error = None
128
+ if guild_model.status == GuildStatus.ERROR:
129
+ guild_model.status = GuildStatus.PENDING_LAUNCH
130
+ session.add(guild_model)
131
+ for row in guild_model.agents:
132
+ if agent_ids and row.id not in agent_ids:
133
+ continue
134
+ if own_proxy is not None and row.id.startswith(proxy_prefix) and row.id != own_proxy:
135
+ continue
136
+ if row.last_error is not None or row.status == AgentStatus.ERROR:
137
+ row.last_error = None
138
+ if row.status == AgentStatus.ERROR:
139
+ row.status = AgentStatus.PENDING_LAUNCH
140
+ session.add(row)
141
+
142
+ @staticmethod
143
+ def _manager_running(guild_model: GuildModel) -> bool:
144
+ guild = GuildHelper.shallow_guild_from_spec(guild_model.to_guild_spec(), guild_model.organization_id)
145
+ return guild.is_agent_running(GuildHelper.get_manager_agent_id(guild.id))
146
+
147
+ _gemstone = GemstoneGenerator(random.randint(101, 200))
148
+
149
+ @classmethod
150
+ def _publish_to_manager(cls, guild_spec: GuildSpec, payload: BaseModel) -> None:
151
+ """Send a protocol request to the guild's manager as the platform, never as a user."""
152
+ messaging = MessagingInterface(guild_spec.id, GuildHelper.get_messaging_config(guild_spec))
153
+ try:
154
+ messaging.publish(
155
+ None, # type: ignore[arg-type] # the sender client is not used by publish
156
+ Message(
157
+ id_obj=cls._gemstone.get_id(Priority.HIGH),
158
+ topics=GuildTopics.SYSTEM_TOPIC,
159
+ sender=AgentTag(id=PlatformSenders.PLATFORM_API, name=PlatformSenders.PLATFORM_API),
160
+ format=get_qualified_class_name(type(payload)),
161
+ payload=payload.model_dump(mode="json"),
162
+ ),
163
+ )
164
+ finally:
165
+ messaging.shutdown()
166
+
167
+ def retry_guild(
168
+ self, guild_id: str, engine: Engine, requested_by: str, agent_ids: Optional[List[str]] = None
169
+ ) -> str:
170
+ """Retry failed launches: through the running manager, or by relaunching the guild.
171
+
172
+ ``requested_by`` comes from the request: this API has no authentication of its own, so the
173
+ deployment in front of it must vouch for the user. An empty ``agent_ids`` means all of them.
174
+ """
175
+ agent_ids = agent_ids or None
176
+ with Session(engine) as session:
177
+ guild_model = GuildModel.get_by_id(session, guild_id)
178
+ if guild_model is None:
179
+ raise HTTPException(status_code=404, detail="Guild not found")
180
+ if guild_model.status in [GuildStatus.STOPPED, GuildStatus.STOPPING]:
181
+ raise HTTPException(status_code=400, detail="Guild is stopped")
182
+ guild_spec = guild_model.to_guild_spec()
183
+ if self._manager_running(guild_model):
184
+ self._publish_to_manager(
185
+ guild_spec, RetryAgentLaunchRequest(agent_ids=agent_ids, requested_by=requested_by)
186
+ )
187
+ return "requested"
188
+ self._clear_launch_failures(session, guild_model, agent_ids, requested_by)
189
+ session.add(GuildRelaunchModel(guild_id=guild_id))
190
+ session.commit()
191
+ organization_id = guild_model.organization_id
192
+ GuildBuilder.from_spec(guild_spec).bootstrap(Metastore.get_db_url(), organization_id)
193
+ return "relaunched"
194
+
195
+ def stop_guild(self, guild_id: str, engine: Engine, user_id: str) -> str:
196
+ """Stop a guild: through its running manager, or directly when no manager is running."""
197
+ with Session(engine) as session:
198
+ guild_model = GuildModel.get_by_id(session, guild_id)
199
+ if guild_model is None:
200
+ raise HTTPException(status_code=404, detail="Guild not found")
201
+ if self._manager_running(guild_model):
202
+ self._publish_to_manager(
203
+ guild_model.to_guild_spec(), StopGuildRequest(guild_id=guild_id, user_id=user_id)
204
+ )
205
+ return "requested"
206
+ # No manager: nothing in this runtime runs the guild's agents. Record it as stopped.
207
+ guild_model.status = GuildStatus.STOPPED
208
+ session.add(guild_model)
209
+ session.commit()
210
+ return "stopped"
@@ -1,25 +0,0 @@
1
- from pydantic import BaseModel
2
-
3
- from rustic_ai.core.guild.dsl import GuildSpec
4
- from rustic_ai.core.guild.metastore.models import GuildStatus
5
-
6
-
7
- class IdInfo(BaseModel):
8
- id: str
9
-
10
-
11
- class LaunchGuildReq(BaseModel):
12
- spec: GuildSpec
13
- org_id: str
14
-
15
-
16
- class GuildSpecResponse(GuildSpec):
17
- """
18
- Response for a guild specification that describes its name, description, agents, routes, and status.
19
- """
20
-
21
- status: GuildStatus
22
-
23
-
24
- class RelaunchResponse(BaseModel):
25
- is_relaunching: bool
@@ -1,96 +0,0 @@
1
- import logging
2
- from typing import Optional
3
-
4
- from fastapi import HTTPException
5
- from sqlalchemy import Engine
6
- from sqlmodel import Session
7
-
8
- from rustic_ai.api_server.guilds.models import GuildRelaunchModel
9
- from rustic_ai.api_server.guilds.schema import GuildSpecResponse
10
- from rustic_ai.core.guild import GuildSpec
11
- from rustic_ai.core.guild.builders import GuildBuilder, GuildHelper
12
- from rustic_ai.core.guild.metastore import GuildModel, GuildStore, Metastore
13
- from rustic_ai.core.guild.metastore.models import AgentModel, GuildStatus
14
-
15
-
16
- class GuildService:
17
-
18
- def create_guild(self, metastore_url: str, guild_spec: GuildSpec, organization_id: str) -> str:
19
- """
20
- Creates a new guild and adds it to the database.
21
-
22
- Args:
23
- metastore_url (str): The URL of the metastore database.
24
- guild_spec (GuildSpec): The specification of the guild to create.
25
- organization_id (str): The ID of the organization that owns this guild.
26
-
27
- Returns:
28
- str: The ID of the created guild.
29
- """
30
- if guild_spec.get_messaging() is None:
31
- default_messaging = GuildHelper.get_default_messaging_config()
32
- guild_spec.set_messaging(**default_messaging)
33
-
34
- if guild_spec.get_execution_engine() is None:
35
- guild_spec.set_execution_engine(GuildHelper.get_default_execution_engine())
36
-
37
- guild_spec.dependency_map = GuildHelper.get_guild_dependency_map(guild_spec)
38
-
39
- engine = Metastore.get_engine(metastore_url)
40
- with Session(engine) as session:
41
- logging.info(f"Creating new guild : [{guild_spec}]")
42
- guild_model = GuildModel.from_guild_spec(guild_spec, organization_id)
43
- guild_model.status = GuildStatus.REQUESTED
44
- session.add(guild_model)
45
- # Add the agents to the Metastore
46
- for guild_agent in guild_spec.agents:
47
- agent_model = AgentModel.from_agent_spec(guild_spec.id, guild_agent)
48
- session.add(agent_model)
49
- session.commit()
50
-
51
- guild = GuildBuilder.from_spec(guild_spec).bootstrap(metastore_url, organization_id)
52
-
53
- return guild.id
54
-
55
- def get_guild(self, engine: Engine, guild_id: str) -> Optional[GuildSpecResponse]:
56
- """
57
- Retrieves a guild and its agents from the database.
58
-
59
- Args:
60
- engine (Engine): The database engine.
61
- guild_id (str): The ID of the guild to retrieve.
62
-
63
- Returns:
64
- Optional[GuildSpec]: The guild specification if found, None otherwise.
65
- """
66
- guild_store = GuildStore(engine)
67
- guild_model = guild_store.get_guild(guild_id)
68
-
69
- guild_spec = guild_model.to_guild_spec() if guild_model else None
70
-
71
- if guild_spec is None:
72
- return None
73
-
74
- return GuildSpecResponse(
75
- **guild_spec.model_dump(), status=GuildStatus(guild_model.status) if guild_model else GuildStatus.UNKNOWN
76
- )
77
-
78
- def relaunch_guild(self, guild_id: str, engine: Engine) -> bool:
79
- with Session(engine) as session:
80
- guild_model = GuildModel.get_by_id(session, guild_id)
81
- if guild_model is None:
82
- raise HTTPException(status_code=404, detail="Guild not found")
83
- else:
84
- if guild_model.status in [GuildStatus.STOPPED, GuildStatus.STOPPING]:
85
- raise HTTPException(status_code=400, detail="Guild is already stopped")
86
- guild_spec = guild_model.to_guild_spec()
87
- guild = GuildHelper.shallow_guild_from_spec(guild_spec, guild_model.organization_id)
88
- mgr_agent_id = GuildHelper.get_manager_agent_id(guild.id)
89
- is_guild_running = guild.is_agent_running(mgr_agent_id)
90
- if not is_guild_running:
91
- logging.info(f"Guild {guild.id} is not running. Relaunching it.")
92
- relaunch_entry = GuildRelaunchModel(guild_id=guild_id)
93
- session.add(relaunch_entry)
94
- session.commit()
95
- GuildBuilder.from_spec(guild_spec).bootstrap(Metastore.get_db_url(), guild_model.organization_id)
96
- return not is_guild_running
File without changes