vigilact-protocol 0.4.0a3__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.
vigilact/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Luca Atella
3
+
4
+ """Vigilact experimental protocol and reference implementation."""
5
+
6
+ __version__ = "0.4.0a3"
vigilact/client.py ADDED
@@ -0,0 +1,64 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Luca Atella
3
+
4
+ """Tiny optional Python HTTP client; uses httpx (install the dev extra for demo)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+ from uuid import uuid4
11
+
12
+ import httpx
13
+
14
+
15
+ class VigilactClient:
16
+ """Thin transport client. For production, use TLS and provide a trusted URL."""
17
+
18
+ def __init__(self, base_url: str, principal: str, key: str,
19
+ transport: httpx.BaseTransport | None = None) -> None:
20
+ self.principal = principal
21
+ self._client = httpx.Client(base_url=base_url.rstrip("/"), timeout=10,
22
+ transport=transport,
23
+ headers={"X-Vigilact-Principal": principal,
24
+ "X-Vigilact-Key": key})
25
+
26
+ def __enter__(self) -> "VigilactClient":
27
+ return self
28
+
29
+ def __exit__(self, *_args: object) -> None:
30
+ self._client.close()
31
+
32
+ def _send(self, method: str, path: str, **kwargs: Any) -> dict:
33
+ response = self._client.request(method, path, **kwargs)
34
+ response.raise_for_status()
35
+ return response.json()
36
+
37
+ def propose(self, client_ref: str, subject: str, event_type: str, deadline_at: datetime) -> dict:
38
+ if deadline_at.tzinfo is None:
39
+ raise ValueError("deadline_at must be timezone-aware")
40
+ return self._send("POST", "/v1/contracts", json={
41
+ "client_ref": client_ref, "subject": subject,
42
+ "observation": {"kind": "expected_event", "event_type": event_type,
43
+ "deadline_at": deadline_at.astimezone(timezone.utc).isoformat()}})
44
+
45
+ def event(self, subject: str, event_type: str, *, event_id: str | None = None,
46
+ data: dict[str, Any] | None = None) -> dict:
47
+ return self._send("POST", "/v1/events", json={
48
+ "specversion": "1.0", "id": event_id or str(uuid4()),
49
+ "source": f"urn:vigilact:agent:{self.principal}",
50
+ "type": event_type, "subject": subject, "data": data or {}})
51
+
52
+ def publish_capabilities(self, capabilities: list[dict]) -> dict:
53
+ return self._send("PUT", "/v1/agents/me/capabilities", json={"capabilities": capabilities})
54
+
55
+ def pending_commands(self) -> list[dict]:
56
+ return self._send("GET", "/v1/agents/me/commands")["commands"]
57
+
58
+ def claim_command(self, command_id: str) -> dict:
59
+ return self._send("POST", f"/v1/agents/me/commands/{command_id}/claim")
60
+
61
+ def finish_command(self, command_id: str, success: bool, output: dict | None = None) -> dict:
62
+ return self._send("POST", f"/v1/agents/me/commands/{command_id}/result",
63
+ json={"status": "succeeded" if success else "failed",
64
+ "output": output or {}})
@@ -0,0 +1,81 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Luca Atella
3
+
4
+ """Resource bounds for the experimental HTTP binding.
5
+
6
+ This deliberately limits streamed bodies rather than trusting Content-Length: a
7
+ client is permitted to omit that header when using chunked transfer encoding.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from starlette.responses import JSONResponse
13
+
14
+
15
+ def _too_large():
16
+ return JSONResponse(
17
+ status_code=413,
18
+ media_type="application/problem+json",
19
+ content={
20
+ "type": "about:blank",
21
+ "title": "Payload Too Large",
22
+ "status": 413,
23
+ "detail": "Request body exceeds the configured size limit",
24
+ "error": "payload_too_large",
25
+ },
26
+ )
27
+
28
+
29
+ class RequestBodyLimitMiddleware:
30
+ """Reject oversized HTTP bodies, including bodies of unknown length."""
31
+
32
+ def __init__(self, app, max_bytes: int = 262_144):
33
+ if max_bytes < 1024:
34
+ raise ValueError("max_bytes must be >= 1024")
35
+ self.app = app
36
+ self.max_bytes = max_bytes
37
+
38
+ async def __call__(self, scope, receive, send):
39
+ if scope["type"] != "http":
40
+ await self.app(scope, receive, send)
41
+ return
42
+
43
+ for key, val in scope.get("headers", []):
44
+ if key.lower() == b"content-length":
45
+ try:
46
+ length = int(val)
47
+ except ValueError:
48
+ length = self.max_bytes + 1
49
+ if length > self.max_bytes or length < 0:
50
+ await _too_large()(scope, receive, send)
51
+ return
52
+
53
+ total = 0
54
+ responded = False
55
+
56
+ async def bounded_receive():
57
+ nonlocal total
58
+ message = await receive()
59
+ if message.get("type") == "http.request":
60
+ total += len(message.get("body", b""))
61
+ if total > self.max_bytes:
62
+ raise _LimitExceeded()
63
+ return message
64
+
65
+ async def guarded_send(message):
66
+ nonlocal responded
67
+ if message["type"] == "http.response.start":
68
+ responded = True
69
+ await send(message)
70
+
71
+ try:
72
+ await self.app(scope, bounded_receive, guarded_send)
73
+ except _LimitExceeded:
74
+ if not responded:
75
+ await _too_large()(scope, receive, send)
76
+ # Once HTTP headers are sent, an error cannot safely become 413;
77
+ # the connection is ended rather than silently accepting the body.
78
+
79
+
80
+ class _LimitExceeded(Exception):
81
+ pass
vigilact/models.py ADDED
@@ -0,0 +1,164 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Luca Atella
3
+
4
+ """Transport-neutral shapes for the Vigilact v0.1 experimental profile."""
5
+
6
+ from datetime import datetime, timezone
7
+ import re
8
+ from typing import Any, Literal
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
11
+
12
+
13
+ class StrictModel(BaseModel):
14
+ model_config = ConfigDict(extra="forbid")
15
+
16
+
17
+ _RFC3339 = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$")
18
+
19
+
20
+ def require_timestamp(value: object) -> object:
21
+ """Refuse epoch numbers and non-RFC3339 strings on the public JSON boundary."""
22
+ if isinstance(value, datetime):
23
+ return value # Python SDK may pass a timezone-aware datetime directly.
24
+ if not isinstance(value, str) or not _RFC3339.fullmatch(value):
25
+ raise ValueError("Timestamp must be an RFC 3339 string (at most microsecond precision)")
26
+ return value
27
+
28
+
29
+ def ensure_utc(value: datetime) -> datetime:
30
+ if value.tzinfo is None or value.utcoffset() is None:
31
+ raise ValueError("A timezone-aware RFC 3339 timestamp is required")
32
+ return value.astimezone(timezone.utc)
33
+
34
+
35
+ class ExpectedEvent(StrictModel):
36
+ kind: Literal["expected_event"] = "expected_event"
37
+ event_type: str = Field(min_length=1, max_length=200)
38
+ deadline_at: datetime
39
+
40
+ @field_validator("deadline_at", mode="before")
41
+ @classmethod
42
+ def validate_deadline_format(cls, value: object) -> object:
43
+ return require_timestamp(value)
44
+
45
+ @field_validator("deadline_at")
46
+ @classmethod
47
+ def utc_deadline(cls, value: datetime) -> datetime:
48
+ return ensure_utc(value)
49
+
50
+
51
+ class ContractProposal(StrictModel):
52
+ client_ref: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$")
53
+ subject: str = Field(min_length=1, max_length=255)
54
+ observation: ExpectedEvent
55
+
56
+
57
+ class CloudEvent(StrictModel):
58
+ """Supported CloudEvents JSON subset; other extensions are not implemented."""
59
+
60
+ specversion: Literal["1.0"]
61
+ id: str = Field(min_length=1, max_length=128)
62
+ source: str = Field(min_length=1, max_length=255)
63
+ type: str = Field(min_length=1, max_length=200)
64
+ subject: str = Field(min_length=1, max_length=255)
65
+ time: datetime | None = None
66
+ datacontenttype: Literal["application/json"] = "application/json"
67
+ data: dict[str, Any] = Field(default_factory=dict)
68
+
69
+ @field_validator("time", mode="before")
70
+ @classmethod
71
+ def validate_time_format(cls, value: object) -> object:
72
+ return require_timestamp(value) if value is not None else None
73
+
74
+ @field_validator("time")
75
+ @classmethod
76
+ def utc_time(cls, value: datetime | None) -> datetime | None:
77
+ return ensure_utc(value) if value is not None else None
78
+
79
+
80
+ class Capability(StrictModel):
81
+ name: str = Field(pattern=r"^[a-z][a-z0-9_.-]{0,95}$")
82
+ mode: Literal["query", "command"]
83
+ description: str = Field(default="", max_length=500)
84
+ invocable: bool = False
85
+
86
+ @model_validator(mode="after")
87
+ def safe_mode(self) -> "Capability":
88
+ if self.invocable and self.mode != "command":
89
+ raise ValueError("Only command capabilities can be marked invocable")
90
+ return self
91
+
92
+
93
+ class CapabilityManifest(StrictModel):
94
+ capabilities: list[Capability] = Field(max_length=100)
95
+
96
+ @model_validator(mode="after")
97
+ def no_duplicates(self) -> "CapabilityManifest":
98
+ names = [cap.name for cap in self.capabilities]
99
+ if len(names) != len(set(names)):
100
+ raise ValueError("Capability names must be unique")
101
+ return self
102
+
103
+
104
+ class CommandRequest(StrictModel):
105
+ request_id: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$")
106
+ target_agent: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
107
+ capability: str = Field(pattern=r"^[a-z][a-z0-9_.-]{0,95}$")
108
+ arguments: dict[str, Any] = Field(default_factory=dict)
109
+ ttl_seconds: int = Field(default=300, ge=1, le=86400)
110
+
111
+
112
+ class CommandResult(StrictModel):
113
+ status: Literal["succeeded", "failed"]
114
+ output: dict[str, Any] = Field(default_factory=dict)
115
+
116
+
117
+ class ContractView(StrictModel):
118
+ id: str
119
+ owner: str
120
+ client_ref: str
121
+ subject: str
122
+ observation: ExpectedEvent
123
+ state: Literal["ACTIVE"]
124
+ outcome: Literal["PENDING", "SATISFIED", "NOT_OBSERVED"]
125
+ accepted_at: datetime
126
+ resolved_at: datetime | None
127
+
128
+
129
+ class EventReceipt(StrictModel):
130
+ status: Literal["accepted", "duplicate"]
131
+ satisfied_contracts: list[str]
132
+
133
+
134
+ class CapabilityView(StrictModel):
135
+ agent: str
136
+ capabilities: list[Capability]
137
+
138
+
139
+ class CommandView(StrictModel):
140
+ id: str
141
+ request_id: str
142
+ target_agent: str
143
+ capability: str
144
+ arguments: dict[str, Any]
145
+ status: Literal["PENDING", "CLAIMED", "SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED", "UNKNOWN"]
146
+ result: dict[str, Any] | None
147
+ created_at: datetime
148
+ updated_at: datetime
149
+ expires_at: datetime | None = None
150
+ lease_expires_at: datetime | None = None
151
+
152
+
153
+ class CommandList(StrictModel):
154
+ commands: list[CommandView]
155
+
156
+
157
+ class OutboxEntry(StrictModel):
158
+ seq: int
159
+ event: CloudEvent
160
+
161
+
162
+ class OutboxPage(StrictModel):
163
+ entries: list[OutboxEntry]
164
+ next_cursor: int
vigilact/server.py ADDED
@@ -0,0 +1,239 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Luca Atella
3
+
4
+ """HTTP binding for Vigilact's experimental v0.1 profile."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import hmac
10
+ import json
11
+ import os
12
+ import re
13
+ from contextlib import asynccontextmanager, suppress
14
+ from dataclasses import dataclass
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from typing import Callable
18
+
19
+ from fastapi import Depends, FastAPI, Header, HTTPException, Query
20
+ from fastapi.exceptions import RequestValidationError
21
+ from fastapi.responses import JSONResponse
22
+
23
+ from . import __version__
24
+ from .models import (
25
+ CapabilityManifest,
26
+ CloudEvent,
27
+ CommandRequest,
28
+ CommandResult,
29
+ ContractProposal,
30
+ ContractView,
31
+ EventReceipt,
32
+ CapabilityView,
33
+ CommandView,
34
+ CommandList,
35
+ OutboxPage,
36
+ )
37
+ from .service import ProtocolError, VigilactService
38
+ from .http_limits import RequestBodyLimitMiddleware
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Principal:
43
+ name: str
44
+ role: str
45
+
46
+
47
+ def _credentials_from_env() -> dict[str, dict[str, str]]:
48
+ raw = os.environ.get("VIGILACT_CREDENTIALS_JSON")
49
+ if not raw:
50
+ raise RuntimeError("Set VIGILACT_CREDENTIALS_JSON (no default credentials are provided)")
51
+ parsed = json.loads(raw)
52
+ return parsed
53
+
54
+
55
+ def _validate_credentials(credentials: dict) -> None:
56
+ if not isinstance(credentials, dict) or not credentials:
57
+ raise ValueError("At least one explicit identity is required")
58
+ for name, record in credentials.items():
59
+ if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", name):
60
+ raise ValueError("Principal names must be 1-64 safe ASCII characters")
61
+ if not isinstance(record, dict) or record.get("role") not in ("agent", "operator"):
62
+ raise ValueError("Each identity must have role agent or operator")
63
+ if not isinstance(record.get("key"), str) or len(record["key"]) < 16:
64
+ raise ValueError("Every identity needs an explicit key of at least 16 characters")
65
+
66
+
67
+ def create_app(
68
+ db_path: str | Path | None = None,
69
+ credentials: dict[str, dict[str, str]] | None = None,
70
+ clock: Callable[[], datetime] | None = None,
71
+ sweep_seconds: float | None = None,
72
+ enable_commands: bool | None = None,
73
+ max_request_bytes: int | None = None,
74
+ ) -> FastAPI:
75
+ """Create an instance. For demo/test inject credentials and a deterministic clock."""
76
+ identities = credentials if credentials is not None else _credentials_from_env()
77
+ _validate_credentials(identities)
78
+ service = VigilactService(db_path or os.environ.get("VIGILACT_DB_PATH", "./vigilact.sqlite3"), clock)
79
+ interval = sweep_seconds if sweep_seconds is not None else float(os.environ.get("VIGILACT_SWEEP_SECONDS", "5"))
80
+ if interval < 0:
81
+ raise ValueError("sweep_seconds must not be negative")
82
+ if enable_commands is None:
83
+ enabled_value = os.environ.get("VIGILACT_ENABLE_COMMANDS", "false").lower()
84
+ if enabled_value not in {"true", "false", "1", "0"}:
85
+ raise ValueError("VIGILACT_ENABLE_COMMANDS must be true/false or 1/0")
86
+ enable_commands = enabled_value in {"true", "1"}
87
+ body_limit = (max_request_bytes if max_request_bytes is not None
88
+ else int(os.environ.get("VIGILACT_MAX_REQUEST_BYTES", "262144")))
89
+ if body_limit < 1024:
90
+ raise ValueError("max_request_bytes must be >= 1024")
91
+
92
+ async def sweeper() -> None:
93
+ while True:
94
+ await asyncio.sleep(interval)
95
+ await asyncio.to_thread(service.evaluate_due)
96
+ await asyncio.to_thread(service.reconcile_commands)
97
+
98
+ @asynccontextmanager
99
+ async def lifespan(app: FastAPI):
100
+ # Reconcile persisted due contracts after process restart.
101
+ await asyncio.to_thread(service.evaluate_due)
102
+ await asyncio.to_thread(service.reconcile_commands)
103
+ task = asyncio.create_task(sweeper()) if interval > 0 else None
104
+ try:
105
+ yield
106
+ finally:
107
+ if task is not None:
108
+ task.cancel()
109
+ with suppress(asyncio.CancelledError):
110
+ await task
111
+
112
+ app = FastAPI(title="Vigilact Reference Server", version=__version__, lifespan=lifespan)
113
+ app.add_middleware(RequestBodyLimitMiddleware, max_bytes=body_limit)
114
+ app.state.service = service
115
+
116
+ def problem(status: int, error: str, detail: str, title: str) -> JSONResponse:
117
+ return JSONResponse(
118
+ status_code=status,
119
+ media_type="application/problem+json",
120
+ content={"type": "about:blank", "title": title, "status": status,
121
+ "detail": detail, "error": error},
122
+ )
123
+
124
+ @app.exception_handler(ProtocolError)
125
+ async def protocol_error_handler(request, exc: ProtocolError):
126
+ return problem(exc.status, exc.code, exc.message, "Protocol error")
127
+
128
+ @app.exception_handler(HTTPException)
129
+ async def http_error_handler(request, exc: HTTPException):
130
+ titles = {401: "Unauthorized", 403: "Forbidden", 404: "Not Found"}
131
+ return problem(exc.status_code, "http_error", str(exc.detail),
132
+ titles.get(exc.status_code, "HTTP error"))
133
+
134
+ @app.exception_handler(RequestValidationError)
135
+ async def validation_error_handler(request, exc: RequestValidationError):
136
+ # Do not echo the supplied request body in the error response.
137
+ return problem(422, "validation_error", "Request validation failed", "Validation error")
138
+
139
+ def require_commands() -> None:
140
+ if not enable_commands:
141
+ raise ProtocolError("commands_disabled",
142
+ "Remote command endpoints are disabled on this server", 403)
143
+
144
+ def authenticate(
145
+ x_vigilact_principal: str | None = Header(default=None),
146
+ x_vigilact_key: str | None = Header(default=None),
147
+ ) -> Principal:
148
+ if x_vigilact_principal is None or x_vigilact_key is None:
149
+ raise HTTPException(status_code=401, detail="Missing Vigilact credentials")
150
+ record = identities.get(x_vigilact_principal)
151
+ if record is None or not hmac.compare_digest(record["key"], x_vigilact_key):
152
+ raise HTTPException(status_code=401, detail="Invalid Vigilact credentials")
153
+ return Principal(name=x_vigilact_principal, role=record["role"])
154
+
155
+ def require_agent(identity: Principal = Depends(authenticate)) -> Principal:
156
+ if identity.role != "agent":
157
+ raise HTTPException(status_code=403, detail="Agent identity required")
158
+ return identity
159
+
160
+ def require_operator(identity: Principal = Depends(authenticate)) -> Principal:
161
+ if identity.role != "operator":
162
+ raise HTTPException(status_code=403, detail="Operator identity required")
163
+ return identity
164
+
165
+ @app.get("/healthz", tags=["meta"])
166
+ def healthz():
167
+ return {"status": "ok"}
168
+
169
+ @app.get("/readyz", tags=["meta"])
170
+ def readyz():
171
+ if not service.check_storage():
172
+ return JSONResponse(status_code=503, content={"status": "unavailable"})
173
+ return {"status": "ready"}
174
+
175
+ @app.get("/v1/info", tags=["meta"])
176
+ def info():
177
+ profiles = ["core.expected_event/0.1", "agent.capabilities/0.1"]
178
+ if enable_commands:
179
+ profiles.append("agent.commands/0.1")
180
+ return {"implementation": "vigilact-python-reference", "version": __version__,
181
+ "protocol": "vigilact/0.1-experimental", "profiles": profiles,
182
+ "features": {"remote_commands": enable_commands,
183
+ "max_request_bytes": body_limit},
184
+ "transport": "HTTP/JSON", "events": "CloudEvents 1.0 (restricted JSON subset)"}
185
+
186
+ @app.post("/v1/contracts", status_code=201, response_model=ContractView, tags=["contracts"])
187
+ def propose_contract(proposal: ContractProposal, identity: Principal = Depends(require_agent)):
188
+ return service.create_contract(identity.name, proposal)
189
+
190
+ @app.get("/v1/contracts/{contract_id}", response_model=ContractView, tags=["contracts"])
191
+ def get_contract(contract_id: str, identity: Principal = Depends(authenticate)):
192
+ return service.get_contract(contract_id, identity.name, identity.role == "operator")
193
+
194
+ @app.post("/v1/events", response_model=EventReceipt, tags=["events"])
195
+ def publish_event(event: CloudEvent, identity: Principal = Depends(require_agent)):
196
+ return service.publish_event(identity.name, event)
197
+
198
+ @app.get("/v1/outbox", response_model=OutboxPage, tags=["events"])
199
+ def list_outbox(after: int = Query(0, ge=0), limit: int = Query(100, ge=1, le=500),
200
+ identity: Principal = Depends(require_operator)):
201
+ return service.read_outbox(after, limit)
202
+
203
+ @app.put("/v1/agents/me/capabilities", response_model=CapabilityView, tags=["capabilities"])
204
+ def put_capabilities(body: CapabilityManifest, identity: Principal = Depends(require_agent)):
205
+ return service.put_capabilities(identity.name, body)
206
+
207
+ @app.get("/v1/agents/{agent}/capabilities", response_model=CapabilityView, tags=["capabilities"])
208
+ def get_capabilities(agent: str, identity: Principal = Depends(authenticate)):
209
+ if identity.role != "operator" and identity.name != agent:
210
+ raise HTTPException(status_code=403, detail="Access denied")
211
+ return service.read_capabilities(agent)
212
+
213
+ @app.post("/v1/commands", status_code=201, response_model=CommandView, tags=["commands"])
214
+ def queue_command(body: CommandRequest, identity: Principal = Depends(require_operator)):
215
+ require_commands()
216
+ return service.enqueue_command(identity.name, body)
217
+
218
+ @app.get("/v1/commands/{command_id}", response_model=CommandView, tags=["commands"])
219
+ def get_command(command_id: str, identity: Principal = Depends(require_operator)):
220
+ require_commands()
221
+ return service.get_command(identity.name, command_id)
222
+
223
+ @app.get("/v1/agents/me/commands", response_model=CommandList, tags=["commands"])
224
+ def commands_for_agent(identity: Principal = Depends(require_agent)):
225
+ require_commands()
226
+ return {"commands": service.pending_commands(identity.name)}
227
+
228
+ @app.post("/v1/agents/me/commands/{command_id}/claim", response_model=CommandView, tags=["commands"])
229
+ def claim_command(command_id: str, identity: Principal = Depends(require_agent)):
230
+ require_commands()
231
+ return service.claim_command(identity.name, command_id)
232
+
233
+ @app.post("/v1/agents/me/commands/{command_id}/result", response_model=CommandView, tags=["commands"])
234
+ def resolve_command(command_id: str, result: CommandResult,
235
+ identity: Principal = Depends(require_agent)):
236
+ require_commands()
237
+ return service.resolve_command(identity.name, command_id, result)
238
+
239
+ return app