field-studio-sdk 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.
- field_studio_sdk/__init__.py +146 -0
- field_studio_sdk/contracts/__init__.py +168 -0
- field_studio_sdk/contracts/identity.py +43 -0
- field_studio_sdk/contracts/resources.py +205 -0
- field_studio_sdk/identity.py +181 -0
- field_studio_sdk/outbox.py +95 -0
- field_studio_sdk/py.typed +0 -0
- field_studio_sdk/workspace.py +213 -0
- field_studio_sdk-0.1.0.dist-info/METADATA +38 -0
- field_studio_sdk-0.1.0.dist-info/RECORD +12 -0
- field_studio_sdk-0.1.0.dist-info/WHEEL +4 -0
- field_studio_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Standalone AI work clients; no business or framework dependencies."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .contracts import CreateTask, PlatformError
|
|
10
|
+
|
|
11
|
+
__all__ = ["PlatformClient", "PlatformError"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _identifier(value: str) -> str:
|
|
15
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]+(?:\.result)?", value):
|
|
16
|
+
raise ValueError("Invalid resource identifier")
|
|
17
|
+
return value
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PlatformClient:
|
|
21
|
+
"""Use a scoped runtime capability without business or UI dependencies."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self, runtime_url: str, *, client: httpx.AsyncClient | None = None
|
|
25
|
+
) -> None:
|
|
26
|
+
parsed = urlsplit(runtime_url)
|
|
27
|
+
if (
|
|
28
|
+
parsed.scheme not in ("http", "https")
|
|
29
|
+
or not parsed.hostname
|
|
30
|
+
or parsed.username
|
|
31
|
+
or parsed.password
|
|
32
|
+
or parsed.query
|
|
33
|
+
or parsed.fragment
|
|
34
|
+
):
|
|
35
|
+
raise ValueError("Invalid runtime URL")
|
|
36
|
+
self.url = runtime_url.rstrip("/")
|
|
37
|
+
self.http = client or httpx.AsyncClient(
|
|
38
|
+
timeout=30, follow_redirects=False, trust_env=False
|
|
39
|
+
)
|
|
40
|
+
self.owned = client is None
|
|
41
|
+
|
|
42
|
+
async def __aenter__(self) -> PlatformClient:
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
async def __aexit__(self, *args: object) -> None:
|
|
46
|
+
if self.owned:
|
|
47
|
+
await self.http.aclose()
|
|
48
|
+
|
|
49
|
+
async def _request(
|
|
50
|
+
self,
|
|
51
|
+
method: str,
|
|
52
|
+
path: str,
|
|
53
|
+
body: dict[str, Any] | None = None,
|
|
54
|
+
key: str | None = None,
|
|
55
|
+
*,
|
|
56
|
+
raw: bool = False,
|
|
57
|
+
) -> Any:
|
|
58
|
+
headers = {}
|
|
59
|
+
if method != "GET":
|
|
60
|
+
if not key or not key.strip() or len(key) > 200:
|
|
61
|
+
raise ValueError("A stable idempotency key is required")
|
|
62
|
+
headers["Idempotency-Key"] = key
|
|
63
|
+
try:
|
|
64
|
+
request = httpx.Request(method, self.url + path, json=body, headers=headers)
|
|
65
|
+
response = await self.http.send(request, auth=None, follow_redirects=False)
|
|
66
|
+
except httpx.HTTPError:
|
|
67
|
+
raise PlatformError(
|
|
68
|
+
"RUNTIME_UNAVAILABLE", "Platform request failed", 503
|
|
69
|
+
) from None
|
|
70
|
+
if not 200 <= response.status_code < 300:
|
|
71
|
+
try:
|
|
72
|
+
error = response.json().get("error", {})
|
|
73
|
+
code = str(error.get("code", "PROTOCOL_ERROR"))
|
|
74
|
+
except ValueError, AttributeError:
|
|
75
|
+
code = "PROTOCOL_ERROR"
|
|
76
|
+
raise PlatformError(
|
|
77
|
+
code, "Platform rejected the request", response.status_code
|
|
78
|
+
)
|
|
79
|
+
if raw:
|
|
80
|
+
return response.content
|
|
81
|
+
try:
|
|
82
|
+
value = response.json()
|
|
83
|
+
if not isinstance(value, dict):
|
|
84
|
+
raise ValueError("Invalid envelope")
|
|
85
|
+
return value
|
|
86
|
+
except ValueError:
|
|
87
|
+
raise PlatformError(
|
|
88
|
+
"PROTOCOL_ERROR", "Invalid platform response", 502
|
|
89
|
+
) from None
|
|
90
|
+
|
|
91
|
+
async def create_task(
|
|
92
|
+
self, body: dict[str, Any], *, idempotency_key: str
|
|
93
|
+
) -> dict[str, Any]:
|
|
94
|
+
"""Create work once per caller-owned intent key."""
|
|
95
|
+
payload = CreateTask.model_validate(body).model_dump()
|
|
96
|
+
return await self._request("POST", "/tasks", payload, idempotency_key)
|
|
97
|
+
|
|
98
|
+
async def get_task(self, task_id: str) -> dict[str, Any]:
|
|
99
|
+
"""Fetch the authoritative state of an owned task."""
|
|
100
|
+
return await self._request("GET", f"/tasks/{_identifier(task_id)}")
|
|
101
|
+
|
|
102
|
+
async def list_tasks(self) -> dict[str, Any]:
|
|
103
|
+
"""List work visible to the runtime session."""
|
|
104
|
+
return await self._request("GET", "/tasks")
|
|
105
|
+
|
|
106
|
+
async def events(
|
|
107
|
+
self, task_id: str, *, after: str = "0", limit: int = 50
|
|
108
|
+
) -> dict[str, Any]:
|
|
109
|
+
"""Continue durable resource events from a previously returned cursor."""
|
|
110
|
+
if not after.isascii() or not after.isdigit() or not 1 <= limit <= 200:
|
|
111
|
+
raise ValueError("Invalid event page")
|
|
112
|
+
return await self._request(
|
|
113
|
+
"GET", f"/tasks/{_identifier(task_id)}/events?after={after}&limit={limit}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
async def cancel(
|
|
117
|
+
self, task_id: str, expected_version: int, *, idempotency_key: str
|
|
118
|
+
) -> dict[str, Any]:
|
|
119
|
+
"""Cancel only the task version the user observed."""
|
|
120
|
+
return await self._request(
|
|
121
|
+
"POST",
|
|
122
|
+
f"/tasks/{_identifier(task_id)}/cancel",
|
|
123
|
+
{"expectedVersion": expected_version},
|
|
124
|
+
idempotency_key,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
async def retry(
|
|
128
|
+
self, task_id: str, expected_version: int, *, idempotency_key: str
|
|
129
|
+
) -> dict[str, Any]:
|
|
130
|
+
"""Request a new attempt; do not automatically replay failed requests."""
|
|
131
|
+
return await self._request(
|
|
132
|
+
"POST",
|
|
133
|
+
f"/tasks/{_identifier(task_id)}/retry",
|
|
134
|
+
{"expectedVersion": expected_version},
|
|
135
|
+
idempotency_key,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
async def artifacts(self, task_id: str) -> dict[str, Any]:
|
|
139
|
+
"""List published result metadata."""
|
|
140
|
+
return await self._request("GET", f"/tasks/{_identifier(task_id)}/artifacts")
|
|
141
|
+
|
|
142
|
+
async def download(self, artifact_id: str) -> bytes:
|
|
143
|
+
"""Download an artifact through the same scoped runtime session."""
|
|
144
|
+
return await self._request(
|
|
145
|
+
"GET", f"/artifacts/{_identifier(artifact_id)}/content", raw=True
|
|
146
|
+
)
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Business-neutral protocol models and bounded JSON validation."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import rfc8785
|
|
9
|
+
from jsonschema import Draft202012Validator
|
|
10
|
+
from jsonschema.exceptions import SchemaError, ValidationError
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Principal:
|
|
16
|
+
"""Server-resolved actor and application scope, never supplied by a model."""
|
|
17
|
+
|
|
18
|
+
actor_id: str
|
|
19
|
+
workspace_id: str
|
|
20
|
+
app_id: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PlatformError(Exception):
|
|
24
|
+
"""Expose a stable protocol error without leaking infrastructure details."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, code: str, message: str, status: int = 400) -> None:
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.code = code
|
|
29
|
+
self.message = message
|
|
30
|
+
self.status = status
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProtocolModel(BaseModel):
|
|
34
|
+
"""Reject unknown fields at the public command boundary."""
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(extra="forbid", strict=True)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DefinitionRef(ProtocolModel):
|
|
40
|
+
"""Pin work to an immutable definition version."""
|
|
41
|
+
|
|
42
|
+
id: str = Field(min_length=1, max_length=100, pattern=r"^[a-zA-Z0-9_-]+$")
|
|
43
|
+
version: int = Field(ge=1, le=2**31 - 1)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DefinitionInput(DefinitionRef):
|
|
47
|
+
"""Describe a read-only task and its registered evidence query."""
|
|
48
|
+
|
|
49
|
+
instructions: str = Field(min_length=1, max_length=16000)
|
|
50
|
+
model: str = Field(min_length=1, max_length=120)
|
|
51
|
+
queryName: str = Field(min_length=1, max_length=100, pattern=r"^[a-zA-Z0-9_.-]+$")
|
|
52
|
+
inputSchema: dict[str, Any]
|
|
53
|
+
outputSchema: dict[str, Any]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CreateTask(ProtocolModel):
|
|
57
|
+
"""Submit work without accepting identity or authorization from the caller."""
|
|
58
|
+
|
|
59
|
+
definitionRef: DefinitionRef
|
|
60
|
+
input: dict[str, Any]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ExpectedVersion(ProtocolModel):
|
|
64
|
+
"""Bind a command to the resource version the caller observed."""
|
|
65
|
+
|
|
66
|
+
expectedVersion: int = Field(ge=1, le=2**53 - 1)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
KEYWORDS = {
|
|
70
|
+
"type",
|
|
71
|
+
"properties",
|
|
72
|
+
"required",
|
|
73
|
+
"additionalProperties",
|
|
74
|
+
"enum",
|
|
75
|
+
"items",
|
|
76
|
+
"minimum",
|
|
77
|
+
"maximum",
|
|
78
|
+
"minLength",
|
|
79
|
+
"maxLength",
|
|
80
|
+
"minItems",
|
|
81
|
+
"maxItems",
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def validate_schema(schema: dict[str, Any]) -> None:
|
|
86
|
+
"""Accept a finite schema subset without references or executable validators."""
|
|
87
|
+
try:
|
|
88
|
+
if len(json.dumps(schema, allow_nan=False).encode()) > 65536:
|
|
89
|
+
raise ValueError("Schema is too large")
|
|
90
|
+
|
|
91
|
+
def visit(node: Any, depth: int = 0) -> None:
|
|
92
|
+
if not isinstance(node, dict) or depth > 12:
|
|
93
|
+
raise ValueError("Schema must be a bounded object")
|
|
94
|
+
if set(node) - KEYWORDS:
|
|
95
|
+
raise ValueError("Unsupported schema keyword")
|
|
96
|
+
if node.get("type") not in {
|
|
97
|
+
"object",
|
|
98
|
+
"array",
|
|
99
|
+
"string",
|
|
100
|
+
"number",
|
|
101
|
+
"integer",
|
|
102
|
+
"boolean",
|
|
103
|
+
"null",
|
|
104
|
+
}:
|
|
105
|
+
raise ValueError("Schema requires a supported type")
|
|
106
|
+
properties = node.get("properties", {})
|
|
107
|
+
if not isinstance(properties, dict) or len(properties) > 100:
|
|
108
|
+
raise ValueError("Invalid properties")
|
|
109
|
+
for child in properties.values():
|
|
110
|
+
visit(child, depth + 1)
|
|
111
|
+
if "items" in node:
|
|
112
|
+
visit(node["items"], depth + 1)
|
|
113
|
+
if node.get("additionalProperties", False) not in (True, False):
|
|
114
|
+
raise ValueError("additionalProperties must be boolean")
|
|
115
|
+
|
|
116
|
+
visit(schema)
|
|
117
|
+
Draft202012Validator.check_schema(schema)
|
|
118
|
+
except (ValueError, TypeError, SchemaError, RecursionError) as exc:
|
|
119
|
+
raise PlatformError(
|
|
120
|
+
"SCHEMA_INVALID", "Invalid or unsupported schema", 422
|
|
121
|
+
) from exc
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def validate_value(schema: dict[str, Any], value: Any) -> None:
|
|
125
|
+
"""Validate a finite JSON value against the registered schema."""
|
|
126
|
+
validate_schema(schema)
|
|
127
|
+
try:
|
|
128
|
+
if len(json.dumps(value, allow_nan=False).encode()) > 262144:
|
|
129
|
+
raise ValueError("Value exceeds protocol limit")
|
|
130
|
+
Draft202012Validator(schema).validate(value)
|
|
131
|
+
except (ValidationError, ValueError, TypeError, RecursionError) as exc:
|
|
132
|
+
raise PlatformError(
|
|
133
|
+
"SCHEMA_INVALID", "Value does not match schema", 422
|
|
134
|
+
) from exc
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def digest(value: Any) -> str:
|
|
138
|
+
"""Hash bounded RFC 8785 JSON; exact decimal values use strings."""
|
|
139
|
+
|
|
140
|
+
def check(item: Any, depth: int = 0) -> None:
|
|
141
|
+
if depth > 32:
|
|
142
|
+
raise ValueError("JSON exceeds nesting limit")
|
|
143
|
+
if item is None or isinstance(item, (str, bool)):
|
|
144
|
+
return
|
|
145
|
+
if type(item) is int and abs(item) <= 2**53 - 1:
|
|
146
|
+
return
|
|
147
|
+
if type(item) is float:
|
|
148
|
+
return
|
|
149
|
+
if isinstance(item, dict) and all(isinstance(key, str) for key in item):
|
|
150
|
+
for child in item.values():
|
|
151
|
+
check(child, depth + 1)
|
|
152
|
+
return
|
|
153
|
+
if isinstance(item, list):
|
|
154
|
+
for child in item:
|
|
155
|
+
check(child, depth + 1)
|
|
156
|
+
return
|
|
157
|
+
raise ValueError("Ambiguous JSON value")
|
|
158
|
+
|
|
159
|
+
try:
|
|
160
|
+
check(value)
|
|
161
|
+
encoded = rfc8785.dumps(value)
|
|
162
|
+
if len(encoded) > 262144:
|
|
163
|
+
raise ValueError("JSON exceeds limit")
|
|
164
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
165
|
+
except (ValueError, TypeError, UnicodeError, RecursionError) as exc:
|
|
166
|
+
raise PlatformError(
|
|
167
|
+
"SCHEMA_INVALID", "Unsupported canonical JSON value", 422
|
|
168
|
+
) from exc
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Public identity response types shared by server and SDK."""
|
|
2
|
+
|
|
3
|
+
from typing import NotRequired, TypedDict
|
|
4
|
+
|
|
5
|
+
ROLE_PERMISSIONS = frozenset(
|
|
6
|
+
{"tasks.run", "tasks.approve", "catalog.manage", "automations.manage"}
|
|
7
|
+
)
|
|
8
|
+
AppScope = dict[str, list[str] | None]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RoleDefinition(TypedDict):
|
|
12
|
+
"""Platform capabilities and application-owned scopes assigned by a role."""
|
|
13
|
+
|
|
14
|
+
id: str
|
|
15
|
+
name: str
|
|
16
|
+
permissions: list[str]
|
|
17
|
+
app_scopes: dict[str, AppScope]
|
|
18
|
+
revision: int
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PublicUser(TypedDict):
|
|
22
|
+
"""Account fields safe to expose to authenticated clients."""
|
|
23
|
+
|
|
24
|
+
id: str
|
|
25
|
+
username: str
|
|
26
|
+
display_name: str
|
|
27
|
+
role: str
|
|
28
|
+
status: str
|
|
29
|
+
workspace_id: str
|
|
30
|
+
must_change_password: int
|
|
31
|
+
created_at: float
|
|
32
|
+
permissions: NotRequired[list[str]]
|
|
33
|
+
app_scopes: NotRequired[dict[str, AppScope]]
|
|
34
|
+
role_revision: NotRequired[int]
|
|
35
|
+
role_assignment_version: NotRequired[int]
|
|
36
|
+
role_name: NotRequired[str]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class UserPage(TypedDict):
|
|
40
|
+
"""A bounded account listing with its total count."""
|
|
41
|
+
|
|
42
|
+
users: list[PublicUser]
|
|
43
|
+
total: int
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Neutral runtime configuration, resource commands and file limits."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal, Self
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class RuntimeSettings:
|
|
15
|
+
"""Server-owned configuration that never points at a business database."""
|
|
16
|
+
|
|
17
|
+
database: Path = Path(".local/data/platform/resources.sqlite")
|
|
18
|
+
model: str = ""
|
|
19
|
+
api_key: str = ""
|
|
20
|
+
base_url: str = "https://api.openai.com/v1"
|
|
21
|
+
sandbox_image: str = "field-studio:sandbox"
|
|
22
|
+
sandbox_url: str = ""
|
|
23
|
+
sandbox_token_file: Path = Path("/run/sandbox-auth/token")
|
|
24
|
+
workspace_id: str = ""
|
|
25
|
+
server_mode: bool = True
|
|
26
|
+
mcp_allowed_urls: tuple[str, ...] = ()
|
|
27
|
+
builtin_mcp_url: str = ""
|
|
28
|
+
codex_bin: str | None = None
|
|
29
|
+
sandbox_network: bool = False
|
|
30
|
+
credential_prefix: str = "FIELD_STUDIO_PLATFORM_WORKSPACE_"
|
|
31
|
+
tls_ca_file: Path | None = None
|
|
32
|
+
tls_cert_file: Path | None = None
|
|
33
|
+
tls_key_file: Path | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SandboxError(RuntimeError):
|
|
37
|
+
"""Safe infrastructure or resource-limit failure from an isolated executor."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate_relative_path(path: str | None, name: str) -> None:
|
|
41
|
+
"""Validate display hierarchy without allowing paths outside the owned input."""
|
|
42
|
+
if path is None:
|
|
43
|
+
return
|
|
44
|
+
if len(path.encode("utf-8")) > 2048 or ":" in path:
|
|
45
|
+
raise ValueError("Invalid relative path")
|
|
46
|
+
for part in path.split("/"):
|
|
47
|
+
validate_name(part)
|
|
48
|
+
if path.split("/")[-1] != name:
|
|
49
|
+
raise ValueError("Path must end with the filename")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Command(BaseModel):
|
|
53
|
+
"""Reject unknown command properties."""
|
|
54
|
+
|
|
55
|
+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SkillBinding(Command):
|
|
59
|
+
"""Bound and unique references to reusable work instructions."""
|
|
60
|
+
|
|
61
|
+
skill_ids: list[str] = Field(default_factory=list, max_length=20)
|
|
62
|
+
mcp_server_ids: list[str] = Field(default_factory=list, max_length=10)
|
|
63
|
+
|
|
64
|
+
@field_validator("skill_ids", "mcp_server_ids")
|
|
65
|
+
@classmethod
|
|
66
|
+
def unique_skills(cls, value: list[str]) -> list[str]:
|
|
67
|
+
"""Reject duplicate skill references."""
|
|
68
|
+
if len(value) != len(set(value)):
|
|
69
|
+
raise ValueError("Skills or MCP service")
|
|
70
|
+
return value
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class MCPDefinition(Command):
|
|
74
|
+
"""Trusted local configuration with environment references for credentials."""
|
|
75
|
+
|
|
76
|
+
name: str = Field(min_length=1, max_length=60)
|
|
77
|
+
transport: Literal["stdio", "http"]
|
|
78
|
+
command: str = Field(default="", max_length=1000)
|
|
79
|
+
args: list[str] = Field(default_factory=list, max_length=50)
|
|
80
|
+
url: str = Field(default="", max_length=2000)
|
|
81
|
+
env: dict[str, str] = Field(default_factory=dict, max_length=50)
|
|
82
|
+
headers: dict[str, str] = Field(default_factory=dict, max_length=30)
|
|
83
|
+
allowed_tools: list[str] = Field(default_factory=list, max_length=100)
|
|
84
|
+
enabled: bool = True
|
|
85
|
+
requires_web_search: bool = False
|
|
86
|
+
|
|
87
|
+
@model_validator(mode="after")
|
|
88
|
+
def validate_connection(self) -> Self:
|
|
89
|
+
"""Reject ambiguous transports and literal credentials."""
|
|
90
|
+
if self.transport == "stdio":
|
|
91
|
+
if not self.command or self.url or self.headers:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"stdio requires a command. Do not set a URL or HTTP Request "
|
|
94
|
+
"headers "
|
|
95
|
+
)
|
|
96
|
+
else:
|
|
97
|
+
parsed = urlsplit(self.url)
|
|
98
|
+
if (
|
|
99
|
+
parsed.scheme not in ("http", "https")
|
|
100
|
+
or not parsed.hostname
|
|
101
|
+
or parsed.username
|
|
102
|
+
or parsed.password
|
|
103
|
+
or parsed.query
|
|
104
|
+
or parsed.fragment
|
|
105
|
+
):
|
|
106
|
+
raise ValueError("Enter an HTTP(S) MCP URL")
|
|
107
|
+
if self.command or self.args or self.env:
|
|
108
|
+
raise ValueError(
|
|
109
|
+
"HTTP connections cannot set a startup command or process "
|
|
110
|
+
"environment variables"
|
|
111
|
+
)
|
|
112
|
+
for key, value in {**self.env, **self.headers}.items():
|
|
113
|
+
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", value):
|
|
114
|
+
raise ValueError(
|
|
115
|
+
"Credential values must reference server environment variables"
|
|
116
|
+
)
|
|
117
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]+", key):
|
|
118
|
+
raise ValueError("Invalid environment variable or header name")
|
|
119
|
+
if len(set(self.allowed_tools)) != len(self.allowed_tools):
|
|
120
|
+
raise ValueError("Tool names must be unique")
|
|
121
|
+
return self
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class SkillImport(Command):
|
|
125
|
+
"""Bounded base64 upload of one ZIP skill package."""
|
|
126
|
+
|
|
127
|
+
filename: str = Field(min_length=1, max_length=255)
|
|
128
|
+
content_base64: str = Field(min_length=1, max_length=28000000)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AgentDefinition(SkillBinding):
|
|
132
|
+
"""User-defined identity and responsibilities for a bounded agent."""
|
|
133
|
+
|
|
134
|
+
name: str = Field(min_length=1, max_length=60)
|
|
135
|
+
role: str = Field(min_length=1, max_length=100)
|
|
136
|
+
description: str = Field(min_length=1, max_length=4000)
|
|
137
|
+
interval_prompt: str = Field(default="", max_length=4000)
|
|
138
|
+
web_search_enabled: bool = Field(default=False, strict=True)
|
|
139
|
+
|
|
140
|
+
@field_validator("interval_prompt")
|
|
141
|
+
@classmethod
|
|
142
|
+
def schedule_prompt(cls, value: str) -> str:
|
|
143
|
+
"""Allow blank for manual-only agents but reject trivial prompts."""
|
|
144
|
+
if value.strip() and len(value.strip()) < 2:
|
|
145
|
+
raise ValueError(
|
|
146
|
+
"A scheduled instruction must contain at least 2 characters. Leave it "
|
|
147
|
+
"blank for manual runs only."
|
|
148
|
+
)
|
|
149
|
+
return value
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class AgentUpdate(SkillBinding):
|
|
153
|
+
"""Editable definition and manual or scheduled operation."""
|
|
154
|
+
|
|
155
|
+
name: str | None = Field(default=None, min_length=1, max_length=60)
|
|
156
|
+
role: str | None = Field(default=None, min_length=1, max_length=100)
|
|
157
|
+
description: str | None = Field(default=None, min_length=1, max_length=4000)
|
|
158
|
+
interval_prompt: str | None = Field(default=None, max_length=4000)
|
|
159
|
+
web_search_enabled: bool | None = Field(default=None, strict=True)
|
|
160
|
+
enabled: bool | None = None
|
|
161
|
+
archived: bool | None = None
|
|
162
|
+
interval_minutes: int | None = Field(default=None, ge=0, le=10080)
|
|
163
|
+
|
|
164
|
+
@field_validator("interval_prompt")
|
|
165
|
+
@classmethod
|
|
166
|
+
def schedule_prompt(cls, value: str | None) -> str | None:
|
|
167
|
+
"""Allow blank for manual-only agents but reject trivial prompts."""
|
|
168
|
+
if value is not None and value.strip() and len(value.strip()) < 2:
|
|
169
|
+
raise ValueError(
|
|
170
|
+
"A scheduled instruction must contain at least 2 characters. Leave it "
|
|
171
|
+
"blank for manual runs only."
|
|
172
|
+
)
|
|
173
|
+
return value
|
|
174
|
+
|
|
175
|
+
@field_validator("interval_minutes")
|
|
176
|
+
@classmethod
|
|
177
|
+
def interval(cls, value: int | None) -> int | None:
|
|
178
|
+
"""Reject intervals too short for bounded model calls."""
|
|
179
|
+
if value is not None and 0 < value < 5:
|
|
180
|
+
raise ValueError(
|
|
181
|
+
"The schedule interval must be at least 5 minutes. 0 is manual only"
|
|
182
|
+
)
|
|
183
|
+
return value
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
FILE_LIMIT = 10 * 1024 * 1024
|
|
187
|
+
TOTAL_LIMIT = 25 * 1024 * 1024
|
|
188
|
+
FILE_COUNT = 5
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def validate_name(name: str) -> str:
|
|
192
|
+
"""Accept a display filename, never a path or HTTP header fragment."""
|
|
193
|
+
if (
|
|
194
|
+
not name.strip()
|
|
195
|
+
or name in (".", "..")
|
|
196
|
+
or "/" in name
|
|
197
|
+
or "\\" in name
|
|
198
|
+
or len(name.encode("utf-8")) > 255
|
|
199
|
+
or any(unicodedata.category(c).startswith("C") for c in name)
|
|
200
|
+
):
|
|
201
|
+
raise ValueError(
|
|
202
|
+
"Invalid file name. Use a name without path separators or control "
|
|
203
|
+
"characters (up to 255 bytes)."
|
|
204
|
+
)
|
|
205
|
+
return name
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Synchronous identity client with no local identity algorithms or database."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import ssl
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, cast
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .contracts import PlatformError
|
|
12
|
+
from .contracts.identity import (
|
|
13
|
+
AppScope,
|
|
14
|
+
PublicUser,
|
|
15
|
+
RoleDefinition,
|
|
16
|
+
UserPage,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class IdentityClient:
|
|
21
|
+
"""Delegate identity operations to an authenticated platform service."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
base_url: str,
|
|
26
|
+
token_file: Path,
|
|
27
|
+
client: httpx.Client | None = None,
|
|
28
|
+
*,
|
|
29
|
+
http_options: dict[str, Any] | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
parsed = urlsplit(base_url)
|
|
32
|
+
if (
|
|
33
|
+
parsed.scheme not in ("http", "https")
|
|
34
|
+
or not parsed.hostname
|
|
35
|
+
or parsed.username
|
|
36
|
+
or parsed.password
|
|
37
|
+
or parsed.query
|
|
38
|
+
or parsed.fragment
|
|
39
|
+
):
|
|
40
|
+
raise ValueError("Invalid identity service URL")
|
|
41
|
+
if parsed.scheme == "http" and parsed.hostname != "localhost":
|
|
42
|
+
try:
|
|
43
|
+
local = ipaddress.ip_address(parsed.hostname).is_loopback
|
|
44
|
+
except ValueError:
|
|
45
|
+
local = False
|
|
46
|
+
if not local:
|
|
47
|
+
raise ValueError("Remote identity services require TLS")
|
|
48
|
+
options = dict(http_options or {})
|
|
49
|
+
if set(options) - {"verify", "cert"}:
|
|
50
|
+
raise ValueError("Only certificate options may override identity transport")
|
|
51
|
+
verify = options.get("verify", True)
|
|
52
|
+
if (
|
|
53
|
+
verify is False
|
|
54
|
+
or isinstance(verify, ssl.SSLContext)
|
|
55
|
+
and (verify.verify_mode != ssl.CERT_REQUIRED or not verify.check_hostname)
|
|
56
|
+
):
|
|
57
|
+
raise ValueError("Identity transport must verify service certificates")
|
|
58
|
+
self.base_url, self.token_file = base_url.rstrip("/"), Path(token_file)
|
|
59
|
+
self.client = client or httpx.Client(
|
|
60
|
+
timeout=20, trust_env=False, follow_redirects=False, **options
|
|
61
|
+
)
|
|
62
|
+
self.owned = client is None
|
|
63
|
+
|
|
64
|
+
def _request(self, method: str, *args: Any, **kwargs: Any) -> Any:
|
|
65
|
+
try:
|
|
66
|
+
token = self.token_file.read_text().strip()
|
|
67
|
+
if not token or len(token) > 4096 or any(char.isspace() for char in token):
|
|
68
|
+
raise ValueError("Invalid workload credential")
|
|
69
|
+
response = self.client.post(
|
|
70
|
+
self.base_url + "/internal/identity/" + method,
|
|
71
|
+
headers={"Authorization": "Bearer " + token},
|
|
72
|
+
json={"args": list(args), "kwargs": kwargs},
|
|
73
|
+
follow_redirects=False,
|
|
74
|
+
)
|
|
75
|
+
except (httpx.HTTPError, OSError, ValueError) as exc:
|
|
76
|
+
raise PlatformError(
|
|
77
|
+
"RUNTIME_UNAVAILABLE", "Identity service unavailable", 503
|
|
78
|
+
) from exc
|
|
79
|
+
if response.is_redirect:
|
|
80
|
+
raise PlatformError(
|
|
81
|
+
"RUNTIME_UNAVAILABLE", "Identity service redirects are refused", 503
|
|
82
|
+
)
|
|
83
|
+
try:
|
|
84
|
+
value = response.json()
|
|
85
|
+
except ValueError as exc:
|
|
86
|
+
raise PlatformError(
|
|
87
|
+
"RUNTIME_UNAVAILABLE", "Invalid identity service response", 503
|
|
88
|
+
) from exc
|
|
89
|
+
if response.is_error:
|
|
90
|
+
detail = (
|
|
91
|
+
value.get("detail", "Identity request rejected")
|
|
92
|
+
if isinstance(value, dict)
|
|
93
|
+
else "Identity request rejected"
|
|
94
|
+
)
|
|
95
|
+
raise PlatformError("IDENTITY_ERROR", str(detail), response.status_code)
|
|
96
|
+
return value
|
|
97
|
+
|
|
98
|
+
def create_user(
|
|
99
|
+
self,
|
|
100
|
+
username: str,
|
|
101
|
+
display_name: str,
|
|
102
|
+
password: str,
|
|
103
|
+
role: str = "member",
|
|
104
|
+
actor: str | None = None,
|
|
105
|
+
) -> PublicUser:
|
|
106
|
+
"""Create a platform account and its server-owned private workspace."""
|
|
107
|
+
return cast(
|
|
108
|
+
PublicUser,
|
|
109
|
+
self._request("create_user", username, display_name, password, role, actor),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def get_user(self, uid: str) -> PublicUser:
|
|
113
|
+
"""Read public account metadata without retrieving password hashes."""
|
|
114
|
+
return cast(PublicUser, self._request("get_user", uid))
|
|
115
|
+
|
|
116
|
+
def users(
|
|
117
|
+
self, offset: int = 0, limit: int = 50, active_only: bool = False
|
|
118
|
+
) -> UserPage:
|
|
119
|
+
"""Read the platform's account page using the original identity contract."""
|
|
120
|
+
return cast(UserPage, self._request("users", offset, limit, active_only))
|
|
121
|
+
|
|
122
|
+
def roles(self, actor: str) -> list[RoleDefinition]:
|
|
123
|
+
return cast(list[RoleDefinition], self._request("roles", actor))
|
|
124
|
+
|
|
125
|
+
def save_role(
|
|
126
|
+
self, name: str, permissions: list[str], actor: str, id: str | None = None
|
|
127
|
+
) -> RoleDefinition:
|
|
128
|
+
return cast(
|
|
129
|
+
RoleDefinition, self._request("save_role", name, permissions, actor, id)
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def set_role_scope(
|
|
133
|
+
self, id: str, app_id: str, scope: AppScope, actor: str
|
|
134
|
+
) -> RoleDefinition:
|
|
135
|
+
return cast(
|
|
136
|
+
RoleDefinition, self._request("set_role_scope", id, app_id, scope, actor)
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def delete_role(self, id: str, actor: str) -> None:
|
|
140
|
+
self._request("delete_role", id, actor)
|
|
141
|
+
|
|
142
|
+
def login(
|
|
143
|
+
self, username: str, password: str, source: str
|
|
144
|
+
) -> tuple[str, str, PublicUser]:
|
|
145
|
+
"""Exchange credentials for a platform session and CSRF token once."""
|
|
146
|
+
value = self._request("login", username, password, source)
|
|
147
|
+
return value[0], value[1], cast(PublicUser, value[2])
|
|
148
|
+
|
|
149
|
+
def session(self, token: str | None) -> tuple[PublicUser, str]:
|
|
150
|
+
"""Validate expiry and current account status on the identity authority."""
|
|
151
|
+
value = self._request("session", token)
|
|
152
|
+
return cast(PublicUser, value[0]), value[1]
|
|
153
|
+
|
|
154
|
+
def logout(self, token: str) -> None:
|
|
155
|
+
"""Revoke a browser session without retrying an uncertain command."""
|
|
156
|
+
self._request("logout", token)
|
|
157
|
+
|
|
158
|
+
def update_user(self, uid: str, changes: dict[str, str], actor: str) -> PublicUser:
|
|
159
|
+
"""Delegate account updates and last-administrator checks to the platform."""
|
|
160
|
+
return cast(PublicUser, self._request("update_user", uid, changes, actor))
|
|
161
|
+
|
|
162
|
+
def change_password(self, uid: str, old_password: str, new_password: str) -> None:
|
|
163
|
+
"""Change a verified password and revoke sessions on the platform."""
|
|
164
|
+
self._request("change_password", uid, old_password, new_password)
|
|
165
|
+
|
|
166
|
+
def reset_token(self, uid: str, actor: str) -> str:
|
|
167
|
+
"""Request a short-lived reset credential from the identity authority."""
|
|
168
|
+
return cast(str, self._request("reset_token", uid, actor))
|
|
169
|
+
|
|
170
|
+
def reset_password(self, token: str, password: str) -> None:
|
|
171
|
+
"""Consume a reset credential without an automatic retry."""
|
|
172
|
+
self._request("reset_password", token, password)
|
|
173
|
+
|
|
174
|
+
def check_health(self) -> None:
|
|
175
|
+
"""Check the remote identity database without exposing SQL access."""
|
|
176
|
+
self._request("check_health")
|
|
177
|
+
|
|
178
|
+
def close(self) -> None:
|
|
179
|
+
"""Close the client's own transport while preserving an injected client."""
|
|
180
|
+
if self.owned:
|
|
181
|
+
self.client.close()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Generic at-least-once delivery of application-owned outbox records."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from contextlib import suppress
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .workspace import WorkspaceClient
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OutboxPublisher:
|
|
15
|
+
"""Deliver fixed event IDs through the SDK without interpreting business facts."""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
client: WorkspaceClient,
|
|
20
|
+
fetch: Callable[[int], list[dict[str, Any]]],
|
|
21
|
+
ack: Callable[[str, Any], None],
|
|
22
|
+
*,
|
|
23
|
+
failed: Callable[[str, str], None] | None = None,
|
|
24
|
+
batch_size: int = 20,
|
|
25
|
+
poll_seconds: float = 1,
|
|
26
|
+
) -> None:
|
|
27
|
+
if not 1 <= batch_size <= 100 or poll_seconds <= 0:
|
|
28
|
+
raise ValueError(
|
|
29
|
+
"Outbox delivery requires bounded batches and a positive interval"
|
|
30
|
+
)
|
|
31
|
+
self.client, self.fetch, self.ack, self.failed = client, fetch, ack, failed
|
|
32
|
+
self.batch_size, self.poll_seconds = batch_size, poll_seconds
|
|
33
|
+
self._job: asyncio.Task[None] | None = None
|
|
34
|
+
self._stop = asyncio.Event()
|
|
35
|
+
self._flushing = asyncio.Lock()
|
|
36
|
+
|
|
37
|
+
async def flush(self) -> int:
|
|
38
|
+
"""Deliver in order and retain the same event ID after uncertain replies."""
|
|
39
|
+
async with self._flushing:
|
|
40
|
+
events = await asyncio.to_thread(self.fetch, self.batch_size)
|
|
41
|
+
delivered = 0
|
|
42
|
+
for event in events:
|
|
43
|
+
if self._stop.is_set():
|
|
44
|
+
break
|
|
45
|
+
event_id = event["eventId"]
|
|
46
|
+
try:
|
|
47
|
+
result = await self.client.request(
|
|
48
|
+
"POST",
|
|
49
|
+
"/events",
|
|
50
|
+
json=event,
|
|
51
|
+
idempotency_key=event_id,
|
|
52
|
+
)
|
|
53
|
+
await asyncio.to_thread(self.ack, event_id, result)
|
|
54
|
+
except asyncio.CancelledError:
|
|
55
|
+
raise
|
|
56
|
+
except Exception:
|
|
57
|
+
if self.failed is not None:
|
|
58
|
+
try:
|
|
59
|
+
await asyncio.to_thread(
|
|
60
|
+
self.failed, event_id, "delivery_unavailable"
|
|
61
|
+
)
|
|
62
|
+
except Exception:
|
|
63
|
+
logger.warning("Outbox failure acknowledgement unavailable")
|
|
64
|
+
return delivered
|
|
65
|
+
delivered += 1
|
|
66
|
+
return delivered
|
|
67
|
+
|
|
68
|
+
def start(self) -> None:
|
|
69
|
+
"""Start one transport worker; duplicate lifecycle opens do not duplicate it."""
|
|
70
|
+
if self._job is not None and not self._job.done():
|
|
71
|
+
return
|
|
72
|
+
self._stop = asyncio.Event()
|
|
73
|
+
self._job = asyncio.create_task(self._run(), name="platform-outbox")
|
|
74
|
+
|
|
75
|
+
async def _run(self) -> None:
|
|
76
|
+
while not self._stop.is_set():
|
|
77
|
+
try:
|
|
78
|
+
delivered = await self.flush()
|
|
79
|
+
if delivered == self.batch_size:
|
|
80
|
+
continue
|
|
81
|
+
except asyncio.CancelledError:
|
|
82
|
+
raise
|
|
83
|
+
except Exception:
|
|
84
|
+
logger.warning("Outbox fetch unavailable; pending records retained")
|
|
85
|
+
with suppress(TimeoutError):
|
|
86
|
+
await asyncio.wait_for(self._stop.wait(), self.poll_seconds)
|
|
87
|
+
|
|
88
|
+
async def close(self) -> None:
|
|
89
|
+
"""Stop transport while retaining pending events and accepted platform work."""
|
|
90
|
+
self._stop.set()
|
|
91
|
+
if self._job is not None:
|
|
92
|
+
self._job.cancel()
|
|
93
|
+
with suppress(asyncio.CancelledError):
|
|
94
|
+
await self._job
|
|
95
|
+
self._job = None
|
|
File without changes
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Workload-authenticated clients for a server-resolved private workspace."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import ssl
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from ipaddress import ip_address
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Protocol, runtime_checkable
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .contracts import PlatformError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@runtime_checkable
|
|
17
|
+
class WorkspaceSettings(Protocol):
|
|
18
|
+
"""Deployment configuration required by the workspace transport."""
|
|
19
|
+
|
|
20
|
+
platform_url: str
|
|
21
|
+
platform_token_file: Path | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _LegacyWorkspaceSettings(Protocol):
|
|
25
|
+
ai_url: str
|
|
26
|
+
ai_token_file: Path | None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RuntimeUnavailable(RuntimeError):
|
|
30
|
+
"""The platform transport or its workload credential is unavailable."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def transport_options(settings: object) -> dict[str, Any]:
|
|
34
|
+
"""Build verified TLS, optionally loading the deployment's client identity."""
|
|
35
|
+
options = getattr(settings, "platform_http_options", None)
|
|
36
|
+
if options is not None:
|
|
37
|
+
if not isinstance(options, dict) or set(options) != {"verify"}:
|
|
38
|
+
raise ValueError("Platform HTTP options must contain a verified SSLContext")
|
|
39
|
+
context = options["verify"]
|
|
40
|
+
else:
|
|
41
|
+
ca = getattr(settings, "platform_ca_file", None)
|
|
42
|
+
cert = getattr(settings, "platform_cert_file", None)
|
|
43
|
+
key = getattr(settings, "platform_key_file", None)
|
|
44
|
+
if bool(cert) != bool(key):
|
|
45
|
+
raise ValueError(
|
|
46
|
+
"Platform client certificate and key must be configured together"
|
|
47
|
+
)
|
|
48
|
+
context = ssl.create_default_context(cafile=str(ca) if ca else None)
|
|
49
|
+
if cert:
|
|
50
|
+
context.load_cert_chain(str(cert), str(key))
|
|
51
|
+
if (
|
|
52
|
+
not isinstance(context, ssl.SSLContext)
|
|
53
|
+
or not context.check_hostname
|
|
54
|
+
or context.verify_mode != ssl.CERT_REQUIRED
|
|
55
|
+
):
|
|
56
|
+
raise ValueError("Platform TLS must verify the peer certificate and hostname")
|
|
57
|
+
return {"verify": context}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class WorkspaceClient:
|
|
61
|
+
"""Use workspace APIs without owning orchestration or business rules."""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
settings: WorkspaceSettings | _LegacyWorkspaceSettings,
|
|
66
|
+
workspace_id: str,
|
|
67
|
+
client: httpx.AsyncClient | None = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", workspace_id):
|
|
70
|
+
raise ValueError("Invalid workspace identifier")
|
|
71
|
+
origin = (
|
|
72
|
+
settings.platform_url
|
|
73
|
+
if isinstance(settings, WorkspaceSettings)
|
|
74
|
+
else settings.ai_url
|
|
75
|
+
)
|
|
76
|
+
parsed = urlsplit(origin)
|
|
77
|
+
if (
|
|
78
|
+
parsed.scheme not in ("http", "https")
|
|
79
|
+
or not parsed.hostname
|
|
80
|
+
or parsed.username
|
|
81
|
+
or parsed.password
|
|
82
|
+
or parsed.query
|
|
83
|
+
or parsed.fragment
|
|
84
|
+
or parsed.path not in ("", "/")
|
|
85
|
+
):
|
|
86
|
+
raise ValueError("Invalid platform origin")
|
|
87
|
+
if parsed.scheme == "http" and parsed.hostname != "localhost":
|
|
88
|
+
try:
|
|
89
|
+
loopback = ip_address(parsed.hostname).is_loopback
|
|
90
|
+
except ValueError:
|
|
91
|
+
loopback = False
|
|
92
|
+
if not loopback:
|
|
93
|
+
raise ValueError("Remote platform connections require verified HTTPS")
|
|
94
|
+
options = transport_options(settings)
|
|
95
|
+
self.settings = settings
|
|
96
|
+
self.workspace_id = workspace_id
|
|
97
|
+
self.prefix = f"/internal/workspaces/{workspace_id}"
|
|
98
|
+
self.origin = origin.rstrip("/")
|
|
99
|
+
self.http = client or httpx.AsyncClient(
|
|
100
|
+
trust_env=False,
|
|
101
|
+
follow_redirects=False,
|
|
102
|
+
timeout=30,
|
|
103
|
+
**options,
|
|
104
|
+
)
|
|
105
|
+
self.owned = client is None
|
|
106
|
+
|
|
107
|
+
async def request(
|
|
108
|
+
self,
|
|
109
|
+
method: str,
|
|
110
|
+
path: str,
|
|
111
|
+
*,
|
|
112
|
+
json: Any = None,
|
|
113
|
+
params: Mapping[str, str | int | float | bool | None] | None = None,
|
|
114
|
+
raw: bool = False,
|
|
115
|
+
timeout: float | None = None,
|
|
116
|
+
content: bytes | None = None,
|
|
117
|
+
idempotency_key: str | None = None,
|
|
118
|
+
) -> Any:
|
|
119
|
+
"""Send scoped JSON or bytes without redirects or inherited credentials."""
|
|
120
|
+
if (
|
|
121
|
+
not path.startswith("/")
|
|
122
|
+
or path.startswith("//")
|
|
123
|
+
or any(char in path for char in ("%", "?", "#", "\\"))
|
|
124
|
+
or any(part in (".", "..") for part in path.split("/"))
|
|
125
|
+
):
|
|
126
|
+
raise ValueError("Invalid workspace API path")
|
|
127
|
+
controls = {"/internal/grants/introspect", "/internal/operations/admit"}
|
|
128
|
+
target = path if path in controls else self.prefix + path
|
|
129
|
+
try:
|
|
130
|
+
token_file = (
|
|
131
|
+
self.settings.platform_token_file
|
|
132
|
+
if isinstance(self.settings, WorkspaceSettings)
|
|
133
|
+
else self.settings.ai_token_file
|
|
134
|
+
)
|
|
135
|
+
token = (
|
|
136
|
+
(token_file or Path(".local/data/ai/service-token")).read_text().strip()
|
|
137
|
+
)
|
|
138
|
+
except OSError as exc:
|
|
139
|
+
raise RuntimeUnavailable(
|
|
140
|
+
"Platform service credentials are unavailable"
|
|
141
|
+
) from exc
|
|
142
|
+
if not token or any(char in token for char in "\r\n"):
|
|
143
|
+
raise RuntimeUnavailable("Platform service credentials are unavailable")
|
|
144
|
+
headers = {"Authorization": "Bearer " + token}
|
|
145
|
+
if idempotency_key is not None:
|
|
146
|
+
if not idempotency_key.strip() or len(idempotency_key) > 200:
|
|
147
|
+
raise ValueError("Invalid idempotency key")
|
|
148
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
149
|
+
request = httpx.Request(
|
|
150
|
+
method,
|
|
151
|
+
self.origin + target,
|
|
152
|
+
params=params,
|
|
153
|
+
headers=headers,
|
|
154
|
+
json=json if content is None else None,
|
|
155
|
+
content=content,
|
|
156
|
+
extensions={
|
|
157
|
+
"timeout": {
|
|
158
|
+
key: timeout if timeout is not None else 30
|
|
159
|
+
for key in ("connect", "read", "write", "pool")
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
)
|
|
163
|
+
try:
|
|
164
|
+
response = await self.http.send(request, auth=None, follow_redirects=False)
|
|
165
|
+
except httpx.HTTPError as exc:
|
|
166
|
+
raise RuntimeUnavailable(
|
|
167
|
+
"Could not connect to the platform service"
|
|
168
|
+
) from exc
|
|
169
|
+
if not 200 <= response.status_code < 300:
|
|
170
|
+
code, message = "PLATFORM_ERROR", "Platform request rejected"
|
|
171
|
+
try:
|
|
172
|
+
body = response.json()
|
|
173
|
+
error = body.get("error", {})
|
|
174
|
+
if isinstance(error, dict):
|
|
175
|
+
code = error.get("code", code)
|
|
176
|
+
message = error.get("message", body.get("detail", message))
|
|
177
|
+
if not isinstance(message, str):
|
|
178
|
+
message = "Platform request rejected"
|
|
179
|
+
except ValueError, AttributeError:
|
|
180
|
+
pass
|
|
181
|
+
raise PlatformError(code, message, response.status_code)
|
|
182
|
+
if raw:
|
|
183
|
+
return response.content
|
|
184
|
+
if not response.content:
|
|
185
|
+
return None
|
|
186
|
+
try:
|
|
187
|
+
return response.json()
|
|
188
|
+
except ValueError as exc:
|
|
189
|
+
raise PlatformError(
|
|
190
|
+
"PROTOCOL_ERROR", "Invalid platform response", 502
|
|
191
|
+
) from exc
|
|
192
|
+
|
|
193
|
+
async def catalog(self) -> dict[str, Any]:
|
|
194
|
+
"""Read platform-owned catalog definitions and availability."""
|
|
195
|
+
return await self.request("GET", "/api/catalog")
|
|
196
|
+
|
|
197
|
+
async def prepare(
|
|
198
|
+
self, agent_id: str, skill_ids: Sequence[str] = ()
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
"""Resolve platform-owned resource bindings for an agent."""
|
|
201
|
+
return await self.request(
|
|
202
|
+
"POST",
|
|
203
|
+
"/api/prepare",
|
|
204
|
+
json={
|
|
205
|
+
"agent_id": agent_id,
|
|
206
|
+
"skill_ids": list(skill_ids),
|
|
207
|
+
},
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
async def close(self) -> None:
|
|
211
|
+
"""Close only the HTTP transport created by this SDK instance."""
|
|
212
|
+
if self.owned:
|
|
213
|
+
await self.http.aclose()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: field-studio-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed clients and data contracts for Field Studio
|
|
5
|
+
Project-URL: Repository, https://github.com/apemost/field-studio
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.14
|
|
9
|
+
Requires-Dist: httpx>=0.28
|
|
10
|
+
Requires-Dist: jsonschema<5,>=4.25
|
|
11
|
+
Requires-Dist: pydantic<3,>=2
|
|
12
|
+
Requires-Dist: rfc8785<1,>=0.1.4
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# Field Studio Python SDK
|
|
16
|
+
|
|
17
|
+
Typed backend clients and data contracts for Field Studio. Requires Python 3.14
|
|
18
|
+
or later.
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pip install field-studio-sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from field_studio_sdk.identity import IdentityClient
|
|
26
|
+
from field_studio_sdk.workspace import WorkspaceClient
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- Use `IdentityClient` to call the platform identity service.
|
|
30
|
+
- Use `WorkspaceClient` to access the workspace resolved by the host's
|
|
31
|
+
authenticated session.
|
|
32
|
+
- Import shared models and errors from `field_studio_sdk.contracts`.
|
|
33
|
+
|
|
34
|
+
Use the SDK version that matches your Field Studio deployment. Configure the
|
|
35
|
+
platform URL and service credentials in the backend. Remote connections require
|
|
36
|
+
verified HTTPS.
|
|
37
|
+
|
|
38
|
+
The SDK is licensed under MIT. The distribution includes the license text.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
field_studio_sdk/__init__.py,sha256=m4o5ewaeFUuG5u7QeA3HdszpHKRRcfJ_hYFcyFBNRpQ,5279
|
|
2
|
+
field_studio_sdk/identity.py,sha256=OnZftrLosIp05W84MLt6-AAK6Kl9VjO3Vo7IWe257oQ,7076
|
|
3
|
+
field_studio_sdk/outbox.py,sha256=OUFADS1-U2hpIQSKhCyxFGx5N7OvcFSVmTCTVXiq_Os,3611
|
|
4
|
+
field_studio_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
field_studio_sdk/workspace.py,sha256=5qoqbImuYDavUkJzIzl3OE6ceo_Vnnd7AUUkdfo0WWE,7857
|
|
6
|
+
field_studio_sdk/contracts/__init__.py,sha256=5V9Z41vKk13VDll3X4hiChlZh6FuBa2AM-L40JQ6z4g,5481
|
|
7
|
+
field_studio_sdk/contracts/identity.py,sha256=gr1C54TINS1nlDLOo4AyrRtFTKwwmFfND0Ji97HVAeo,1065
|
|
8
|
+
field_studio_sdk/contracts/resources.py,sha256=CH5EbLTScsT8pkXD_wtNH2sQlnKaw0-TjZkWRn2C2hk,7684
|
|
9
|
+
field_studio_sdk-0.1.0.dist-info/METADATA,sha256=CbaYJQGS4au9YZ3t3b4dmqLr0-V32H3tUnMArL2nKLs,1178
|
|
10
|
+
field_studio_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
field_studio_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=QrAYl1YAtcwE-sZDvAXB6nz7OPRII7JRDbbxI5mapJ8,1067
|
|
12
|
+
field_studio_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Andrew Lyu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|