agentmesh-common 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.
@@ -0,0 +1,6 @@
1
+ """Minimal shared configuration and structured errors."""
2
+
3
+ from agentmesh_common.errors import AgentMeshError, ErrorBody, ErrorCode
4
+ from agentmesh_common.settings import Environment, Settings, get_settings
5
+
6
+ __all__ = ["AgentMeshError", "Environment", "ErrorBody", "ErrorCode", "Settings", "get_settings"]
@@ -0,0 +1,88 @@
1
+ """Structured, sanitized error format shared by REST and the relay protocol.
2
+
3
+ Error messages must never contain tool arguments, results, or secrets. Only the
4
+ stable ``code`` is safe to persist as invocation metadata.
5
+ """
6
+
7
+ from enum import StrEnum
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+
13
+ class ErrorCode(StrEnum):
14
+ # Generic
15
+ INTERNAL = "internal_error"
16
+ VALIDATION = "validation_error"
17
+ NOT_FOUND = "not_found"
18
+ RATE_LIMITED = "rate_limited"
19
+ # Auth
20
+ UNAUTHENTICATED = "unauthenticated"
21
+ FORBIDDEN = "forbidden"
22
+ EMAIL_NOT_VERIFIED = "email_not_verified"
23
+ CSRF_FAILED = "csrf_failed"
24
+ # Device authorization (RFC 8628 style)
25
+ AUTHORIZATION_PENDING = "authorization_pending"
26
+ SLOW_DOWN = "slow_down"
27
+ ACCESS_DENIED = "access_denied"
28
+ EXPIRED_TOKEN = "expired_token" # noqa: S105 (error code, not a secret)
29
+ INVALID_GRANT = "invalid_grant"
30
+ # Relay protocol
31
+ UNSUPPORTED_VERSION = "unsupported_relay_version"
32
+ MALFORMED_ENVELOPE = "malformed_envelope"
33
+ PAYLOAD_TOO_LARGE = "payload_too_large"
34
+ STALE_GENERATION = "stale_connection_generation"
35
+ DUPLICATE_CONNECTION = "duplicate_connection"
36
+ # Invocation
37
+ AGENT_OFFLINE = "agent_offline"
38
+ AGENT_BUSY = "agent_busy"
39
+ COORDINATOR_UNAVAILABLE = "coordinator_unavailable"
40
+ TOOL_NOT_FOUND = "tool_not_found"
41
+ IDEMPOTENCY_CONFLICT = "idempotency_conflict"
42
+ DEADLINE_EXCEEDED = "deadline_exceeded"
43
+ TOOL_ERROR = "tool_error"
44
+ MCP_ERROR = "mcp_error"
45
+ FAILED_BEFORE_DISPATCH = "failed_before_dispatch"
46
+ OUTCOME_UNKNOWN = "outcome_unknown"
47
+ CANCELLED = "cancelled"
48
+ HISTORY_UNAVAILABLE = "history_unavailable"
49
+ # The agent's connection can't drive a browser (its manifest doesn't declare it).
50
+ BROWSER_UNSUPPORTED = "browser_unsupported"
51
+ # Sharing (milestone 1.5)
52
+ SHARE_LIMIT_REACHED = "share_limit_reached"
53
+ TOOL_NOT_SHARED = "tool_not_shared"
54
+ # Manifest
55
+ UNSUPPORTED_MANIFEST_VERSION = "unsupported_manifest_version"
56
+ INVALID_MANIFEST = "invalid_manifest"
57
+
58
+
59
+ class ErrorBody(BaseModel):
60
+ """Wire format: ``{"error": {"code": ..., "message": ..., "details": {...}}}``."""
61
+
62
+ code: ErrorCode
63
+ message: str = Field(max_length=500)
64
+ details: dict[str, Any] = Field(default_factory=dict)
65
+
66
+
67
+ class AgentMeshError(Exception):
68
+ """Raise with a stable code and a human-readable, payload-free message."""
69
+
70
+ status_code: int = 400
71
+
72
+ def __init__(
73
+ self,
74
+ code: ErrorCode,
75
+ message: str,
76
+ *,
77
+ status_code: int | None = None,
78
+ details: dict[str, Any] | None = None,
79
+ ) -> None:
80
+ super().__init__(message)
81
+ self.code = code
82
+ self.message = message
83
+ self.details = details or {}
84
+ if status_code is not None:
85
+ self.status_code = status_code
86
+
87
+ def to_body(self) -> ErrorBody:
88
+ return ErrorBody(code=self.code, message=self.message, details=self.details)
@@ -0,0 +1,45 @@
1
+ """Structured logging: one JSON object per line on stdout (or plain text for local dev)."""
2
+
3
+ import json
4
+ import logging
5
+ import sys
6
+ from datetime import UTC, datetime
7
+ from typing import Any
8
+
9
+ # LogRecord attributes that are not user-supplied `extra` fields.
10
+ _STANDARD = set(logging.LogRecord("", 0, "", 0, "", (), None).__dict__) | {"message", "asctime"}
11
+
12
+
13
+ class JsonFormatter(logging.Formatter):
14
+ def format(self, record: logging.LogRecord) -> str:
15
+ entry: dict[str, Any] = {
16
+ "ts": datetime.fromtimestamp(record.created, UTC).isoformat(),
17
+ "level": record.levelname.lower(),
18
+ "logger": record.name,
19
+ "msg": record.getMessage(),
20
+ }
21
+ for key, value in record.__dict__.items():
22
+ if key not in _STANDARD and not key.startswith("_"):
23
+ entry[key] = (
24
+ value if isinstance(value, str | int | float | bool | None) else str(value)
25
+ )
26
+ if record.exc_info:
27
+ entry["exc"] = self.formatException(record.exc_info)
28
+ return json.dumps(entry, separators=(",", ":"))
29
+
30
+
31
+ def configure(fmt: str = "json", level: str = "INFO") -> None:
32
+ handler = logging.StreamHandler(sys.stdout)
33
+ handler.setFormatter(
34
+ JsonFormatter()
35
+ if fmt == "json"
36
+ else logging.Formatter("%(levelname)s %(name)s: %(message)s")
37
+ )
38
+ root = logging.getLogger()
39
+ root.handlers[:] = [handler]
40
+ root.setLevel(level.upper())
41
+ # Uvicorn's own loggers propagate to the root handler (and its redaction filter).
42
+ for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
43
+ lg = logging.getLogger(name)
44
+ lg.handlers[:] = []
45
+ lg.propagate = True
File without changes
@@ -0,0 +1,182 @@
1
+ """Environment-driven configuration (``AGENTMESH_*`` variables)."""
2
+
3
+ import os
4
+ from enum import StrEnum
5
+ from functools import lru_cache
6
+ from typing import Literal
7
+
8
+ from pydantic import Field, SecretStr, model_validator
9
+ from pydantic_settings import BaseSettings, SettingsConfigDict
10
+
11
+
12
+ class Environment(StrEnum):
13
+ DEVELOPMENT = "development"
14
+ TEST = "test"
15
+ STAGING = "staging"
16
+ PRODUCTION = "production"
17
+
18
+
19
+ class Settings(BaseSettings):
20
+ # AGENTMESH_ENV_FILE="" disables .env loading (tests and E2E must not read a
21
+ # developer's local .env).
22
+ model_config = SettingsConfigDict(
23
+ env_prefix="AGENTMESH_",
24
+ env_file=os.environ.get("AGENTMESH_ENV_FILE", ".env") or None,
25
+ extra="ignore",
26
+ )
27
+
28
+ env: Environment = Environment.DEVELOPMENT
29
+ database_url: str = "postgresql+asyncpg://agentmesh:agentmesh@localhost:5432/agentmesh"
30
+ gateway_host: str = "127.0.0.1"
31
+ gateway_port: int = 8000
32
+ # Browser origins allowed for CORS and CSRF origin checks.
33
+ cors_origins: list[str] = Field(default_factory=lambda: ["http://localhost:3000"])
34
+ # Public URL of the web app (used for device verification links).
35
+ public_web_url: str = "http://localhost:3000"
36
+ dev_auth_enabled: bool = False
37
+
38
+ # Self-hosted sign-in: email/password (Argon2) + optional Google (OpenID Connect).
39
+ google_client_id: str | None = None
40
+ google_client_secret: SecretStr | None = None
41
+ password_min_length: int = 10
42
+ email_verify_ttl_seconds: int = 24 * 3600
43
+ password_reset_ttl_seconds: int = 3600
44
+ login_max_failures: int = 5 # per email, within login_failure_window_seconds
45
+ login_failure_window_seconds: int = 15 * 60
46
+ auth_rate_per_minute: int = 20 # per IP, for login/register/reset endpoints
47
+ # Invalid share-key abuse limits (failures per minute) and spike-alert threshold.
48
+ share_auth_fail_per_ip_per_minute: int = 20
49
+ share_auth_fail_global_per_minute: int = 300
50
+ share_auth_alert_per_minute: int = 100
51
+ # IPs/CIDRs of reverse proxies whose X-Forwarded-For is trusted (e.g. ["127.0.0.1"]).
52
+ trusted_proxies: list[str] = Field(default_factory=list)
53
+
54
+ # Outgoing email (verification, password reset). Unset host = dev fallback that
55
+ # logs the link (refused in staging/production).
56
+ smtp_host: str | None = None
57
+ smtp_port: int = 587
58
+ smtp_username: str | None = None
59
+ smtp_password: SecretStr | None = None
60
+ smtp_starttls: bool = True
61
+ email_from: str = "AgentMesh <no-reply@localhost>"
62
+
63
+ # Browser session cookie. None = secure except in development/test.
64
+ session_cookie_secure: bool | None = None
65
+ web_session_ttl_seconds: int = 12 * 3600
66
+
67
+ # CLI device credentials.
68
+ device_code_ttl_seconds: int = 600
69
+ device_poll_interval_seconds: int = 5
70
+ device_access_ttl_seconds: int = 15 * 60
71
+ device_refresh_ttl_seconds: int = 30 * 24 * 3600
72
+
73
+ # Invocations.
74
+ invocation_rate_per_minute: int = 60
75
+ # Opt-in payload history: AES-256-GCM keys as {"key_id": "<base64 32 bytes>"}.
76
+ # Keep them outside the database (env/secret manager); rows record their key_id.
77
+ payload_keys: dict[str, SecretStr] = Field(default_factory=dict)
78
+ payload_active_key: str | None = None
79
+ payload_retention_seconds: int = 7 * 24 * 3600
80
+ # Shared spaces (M3): room history and artifacts are kept this long (D10), and the
81
+ # built-in coordinator runs this local Ollama model (D05).
82
+ room_history_days: int = 90
83
+ coordinator_ollama_url: str = "http://127.0.0.1:11434"
84
+ coordinator_model: str = "qwen3:8b"
85
+ # Task limits (moderate preset, Phase 0): per task, per user, per space, platform-wide.
86
+ task_max_steps: int = 12
87
+ task_max_calls: int = 40
88
+ task_max_minutes: int = 20
89
+ user_max_running_tasks: int = 3
90
+ space_max_running_tasks: int = 2
91
+ platform_max_running_tasks: int = 4
92
+ task_lease_seconds: int = 30
93
+ # Usage units (D05, Phase 3): one per agent/tool call, plus coordinator tokens / 1000.
94
+ # Reserved before work starts; daily caps reset at 00:00 UTC.
95
+ task_max_units: int = 60
96
+ user_daily_units: int = 300
97
+ space_daily_units: int = 600
98
+ platform_daily_units: int = 3000
99
+ task_max_top_up_units: int = 200
100
+ # How long a step waits for a person (ask_human, action approval) or a budget top-up.
101
+ human_wait_seconds: int = 24 * 3600
102
+ # Chat between agents outside tasks: a thread's message cap and idle lifetime, and how
103
+ # long one session holds a claimed message before another session may take it.
104
+ thread_max_messages: int = 20
105
+ thread_idle_seconds: int = 24 * 3600
106
+ inbox_claim_seconds: int = 120
107
+ # Presence and headless runs (a message starting a run while no session is open).
108
+ session_live_seconds: int = 120
109
+ session_busy_seconds: int = 600 # a turn that never reports its end stops counting
110
+ headless_claim_seconds: int = 600
111
+ headless_daily_runs: int = 100
112
+ # Chat between agents needs no grant, up to this many sent messages per agent per hour.
113
+ chat_hourly_messages: int = 10
114
+ # An action request the owner hasn't decided on lapses after this long.
115
+ action_request_hours: int = 24
116
+ # Notifications (Phase 4): reminders for things still waiting on someone.
117
+ notify_first_reminder_seconds: int = 2 * 3600
118
+ notify_reminder_interval_seconds: int = 8 * 3600
119
+ notify_max_reminders: int = 3
120
+ notify_link_days: int = 30
121
+ notify_poll_seconds: int = 15
122
+ notify_worker_enabled: bool = True
123
+ # Metadata-only LangSmith export (D11): off unless an API key is set. Only approved ids,
124
+ # states, counts and durations leave; never prompts, messages, tool data or errors.
125
+ langsmith_api_key: SecretStr | None = None
126
+ langsmith_endpoint: str = "https://api.smith.langchain.com"
127
+ langsmith_project: str = "agentmesh"
128
+ task_runner_enabled: bool = True
129
+ # D09: a step whose agent is offline waits this long (a manager can reassign it).
130
+ step_offline_wait_seconds: int = 900
131
+ # Shared sources (D07): uploaded documents, text extracted at upload.
132
+ source_max_bytes: int = 2 * 1024 * 1024
133
+ source_max_chars: int = 200_000
134
+ # Remote MCP integration: endpoints must be on this host allow-list. https is required
135
+ # except for loopback hosts, which are allowed only outside staging/production.
136
+ integration_allowed_hosts: list[str] = Field(default_factory=lambda: ["127.0.0.1", "localhost"])
137
+ # AES-256 key (base64, 32 bytes) for integration tokens at rest. Without one, dev/test
138
+ # use a per-process key (tokens must be re-entered after a restart) and staging/production
139
+ # refuse to store integration tokens.
140
+ integration_key: SecretStr | None = None
141
+ metadata_retention_seconds: int = 30 * 24 * 3600
142
+ # HMAC key for idempotency digests (no plaintext arguments are retained).
143
+ idempotency_secret: SecretStr | None = None
144
+ maintenance_interval_seconds: int = 600
145
+ log_format: Literal["json", "text"] = "json"
146
+ log_level: str = "INFO"
147
+ # Hold a PostgreSQL advisory lock so a second gateway on the same database refuses
148
+ # to start (live sockets are in-process; see milestone plan §3).
149
+ single_instance_lock: bool = True
150
+ # With history off, how long a finished result stays in memory for late viewers.
151
+ live_result_ttl_seconds: int = 120
152
+
153
+ @property
154
+ def is_deployment(self) -> bool:
155
+ return self.env in (Environment.STAGING, Environment.PRODUCTION)
156
+
157
+ @property
158
+ def cookie_secure(self) -> bool:
159
+ if self.session_cookie_secure is not None:
160
+ return self.session_cookie_secure
161
+ return self.env not in (Environment.DEVELOPMENT, Environment.TEST)
162
+
163
+ @model_validator(mode="after")
164
+ def _deployment_rules(self) -> "Settings":
165
+ if self.dev_auth_enabled and self.is_deployment:
166
+ raise ValueError("developer auth is forbidden in staging/production")
167
+ if self.is_deployment and not self.smtp_host:
168
+ raise ValueError("staging/production require AGENTMESH_SMTP_HOST (verification email)")
169
+ if bool(self.google_client_id) != bool(self.google_client_secret):
170
+ raise ValueError("set both AGENTMESH_GOOGLE_CLIENT_ID and _CLIENT_SECRET, or neither")
171
+ if self.is_deployment and not self.cookie_secure:
172
+ raise ValueError("staging/production require secure session cookies")
173
+ if self.is_deployment and not self.idempotency_secret:
174
+ raise ValueError("staging/production require AGENTMESH_IDEMPOTENCY_SECRET")
175
+ if self.payload_active_key and self.payload_active_key not in self.payload_keys:
176
+ raise ValueError("AGENTMESH_PAYLOAD_ACTIVE_KEY is not in AGENTMESH_PAYLOAD_KEYS")
177
+ return self
178
+
179
+
180
+ @lru_cache
181
+ def get_settings() -> Settings:
182
+ return Settings()
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentmesh-common
3
+ Version: 0.1.0
4
+ Summary: Shared configuration and structured errors for AgentMesh
5
+ Requires-Python: <3.13,>=3.12
6
+ Requires-Dist: pydantic-settings<3,>=2.5
7
+ Requires-Dist: pydantic<3,>=2.9
@@ -0,0 +1,8 @@
1
+ agentmesh_common/__init__.py,sha256=jdv2bB1MhmIdL5jwdofpz_jUh_YDFz9xS0KRvIJjCL0,311
2
+ agentmesh_common/errors.py,sha256=_1OCwUfsjCT5_Pgw3X9HTUuiT1bEGozxO5eWLX5pGlk,3042
3
+ agentmesh_common/logging.py,sha256=1YCt7naAaNnFXCBQ1AnkWjVnUJqIo3GhglByypJil3E,1751
4
+ agentmesh_common/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ agentmesh_common/settings.py,sha256=jKuxpyADBdwtRJZfzKXXumm9Yxdx8pWQli2avkLwOK0,8907
6
+ agentmesh_common-0.1.0.dist-info/METADATA,sha256=er7W1SUW6FBedYBAnPSk2M1zI4zXalxd1KjAcAbNQHw,229
7
+ agentmesh_common-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ agentmesh_common-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any