ai-protocol-client 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.
- ai_protocol/__init__.py +7 -0
- ai_protocol/client.py +271 -0
- ai_protocol/conformance.py +90 -0
- ai_protocol/dispatcher.py +79 -0
- ai_protocol/protocol.py +143 -0
- ai_protocol/schemas/error.schema.json +32 -0
- ai_protocol/schemas/manifest.schema.json +127 -0
- ai_protocol/schemas/operation.schema.json +33 -0
- ai_protocol/schemas/policy.schema.json +86 -0
- ai_protocol_client-0.1.0.dist-info/METADATA +215 -0
- ai_protocol_client-0.1.0.dist-info/RECORD +14 -0
- ai_protocol_client-0.1.0.dist-info/WHEEL +5 -0
- ai_protocol_client-0.1.0.dist-info/licenses/LICENSE +202 -0
- ai_protocol_client-0.1.0.dist-info/top_level.txt +1 -0
ai_protocol/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Cooperative agent access: adaptive HTTP client and optional local dispatcher."""
|
|
2
|
+
from .client import AsyncClient, DeadlineExceeded, OperationError, ProtocolError
|
|
3
|
+
from .dispatcher import DispatcherClient
|
|
4
|
+
from .protocol import discover, execute, service_client
|
|
5
|
+
|
|
6
|
+
__all__ = ["AsyncClient", "DeadlineExceeded", "OperationError", "ProtocolError",
|
|
7
|
+
"DispatcherClient", "discover", "execute", "service_client"]
|
ai_protocol/client.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""One adaptive attempt gate and policy refresher per asynchronous client."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import copy
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from contextlib import suppress
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
import jsonschema
|
|
12
|
+
|
|
13
|
+
from .dispatcher import DispatcherClient
|
|
14
|
+
from .protocol import safe_to_retry, validate_operation, validate_origin
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ProtocolError(ValueError):
|
|
18
|
+
"""A discovery or configuration contract was not satisfied."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OperationError(Exception):
|
|
22
|
+
"""An operation failed; attributes contain no credentials or input values."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, code, execution, *, status=None, attempts=0):
|
|
25
|
+
self.code = code if isinstance(code, str) and re.fullmatch(r"[a-z][a-z0-9_]{0,63}", code) else "http_error"
|
|
26
|
+
self.execution = execution
|
|
27
|
+
self.status = status
|
|
28
|
+
self.attempts = attempts
|
|
29
|
+
super().__init__(f"{self.code} (execution={execution}, status={status}, attempts={attempts})")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DeadlineExceeded(OperationError):
|
|
33
|
+
"""The logical task's original deadline expired."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def validate_policy(policy, previous=None):
|
|
37
|
+
"""Validate the adaptive v3 contract and continuity of one gateway identity."""
|
|
38
|
+
if not isinstance(policy, dict):
|
|
39
|
+
raise ProtocolError("Invalid policy object")
|
|
40
|
+
limits = policy.get("limits", {})
|
|
41
|
+
integer = lambda value: type(value) is int
|
|
42
|
+
if (
|
|
43
|
+
policy.get("version") != 3 or not integer(policy.get("version"))
|
|
44
|
+
or not isinstance(policy.get("principal_id"), str) or not policy["principal_id"]
|
|
45
|
+
or policy.get("client_class") not in ("agent", "interactive")
|
|
46
|
+
or not isinstance(limits, dict) or limits.get("scope") != "principal"
|
|
47
|
+
or not integer(limits.get("max_outstanding")) or not 1 <= limits["max_outstanding"] <= 1000
|
|
48
|
+
or not integer(policy.get("policy_revision")) or policy["policy_revision"] < 1
|
|
49
|
+
or not integer(policy.get("refresh_after_ms")) or not 100 <= policy["refresh_after_ms"] <= 60000
|
|
50
|
+
or not integer(policy.get("outstanding")) or policy["outstanding"] < 0
|
|
51
|
+
or not isinstance(policy.get("operations"), list)
|
|
52
|
+
or ("service_id" in policy and (not isinstance(policy["service_id"], str) or not policy["service_id"]))
|
|
53
|
+
):
|
|
54
|
+
raise ProtocolError("Invalid or unsupported adaptive policy")
|
|
55
|
+
names = set()
|
|
56
|
+
for operation in policy["operations"]:
|
|
57
|
+
try:
|
|
58
|
+
validate_operation(operation)
|
|
59
|
+
except (ValueError, jsonschema.SchemaError):
|
|
60
|
+
raise ProtocolError("Invalid operation descriptor") from None
|
|
61
|
+
if operation["name"] in names:
|
|
62
|
+
raise ProtocolError("Duplicate operation name")
|
|
63
|
+
names.add(operation["name"])
|
|
64
|
+
if previous and (
|
|
65
|
+
any(policy.get(key) != previous.get(key) for key in ("principal_id", "client_class", "service_id"))
|
|
66
|
+
or policy["policy_revision"] < previous["policy_revision"]
|
|
67
|
+
or (policy["policy_revision"] == previous["policy_revision"]
|
|
68
|
+
and limits["max_outstanding"] != previous["limits"]["max_outstanding"])
|
|
69
|
+
):
|
|
70
|
+
raise ProtocolError("Policy identity or revision changed inconsistently")
|
|
71
|
+
return copy.deepcopy(policy)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AsyncClient:
|
|
75
|
+
"""An adaptive v3 client. Use `async with` and await all calls before closing.
|
|
76
|
+
|
|
77
|
+
The gate is process-local, not a reservation of server budget. Use a shared
|
|
78
|
+
dispatcher to coordinate separate local processes. Transport loss, cancellation
|
|
79
|
+
and execution timeouts never authorize replay of an unknown outcome.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, origin, token, *, dispatcher_socket=None, transport=None,
|
|
83
|
+
max_response_bytes=16 * 1024 * 1024):
|
|
84
|
+
try:
|
|
85
|
+
origin = validate_origin(origin)
|
|
86
|
+
except ValueError as error:
|
|
87
|
+
raise ProtocolError(str(error)) from None
|
|
88
|
+
if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9._~+/=-]+", token):
|
|
89
|
+
raise ProtocolError("Invalid bearer credential")
|
|
90
|
+
if type(max_response_bytes) is not int or max_response_bytes < 1:
|
|
91
|
+
raise ProtocolError("max_response_bytes must be a positive integer")
|
|
92
|
+
self._origin = origin.rstrip("/")
|
|
93
|
+
self._http = httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"},
|
|
94
|
+
trust_env=False, follow_redirects=False, transport=transport)
|
|
95
|
+
self._dispatcher = DispatcherClient(dispatcher_socket, token) if dispatcher_socket else None
|
|
96
|
+
self._maximum_body = max_response_bytes
|
|
97
|
+
self._condition = asyncio.Condition()
|
|
98
|
+
self._policy = None
|
|
99
|
+
self._active = 0
|
|
100
|
+
self._ready = False
|
|
101
|
+
self._closed = False
|
|
102
|
+
self._refresher = None
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def policy(self):
|
|
106
|
+
"""A detached full discovery snapshot, or None before initial discovery."""
|
|
107
|
+
return copy.deepcopy(self._policy)
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def ready(self):
|
|
111
|
+
"""Whether new attempts may use the last successfully refreshed policy."""
|
|
112
|
+
return self._ready and not self._closed
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def active_attempts(self):
|
|
116
|
+
"""HTTP attempts currently held by this client, excluding dispatcher jobs."""
|
|
117
|
+
return self._active
|
|
118
|
+
|
|
119
|
+
async def __aenter__(self):
|
|
120
|
+
if self._closed or self._refresher is not None:
|
|
121
|
+
raise ProtocolError("Client cannot be reopened or entered twice")
|
|
122
|
+
try:
|
|
123
|
+
await self.refresh()
|
|
124
|
+
except BaseException:
|
|
125
|
+
await self.aclose()
|
|
126
|
+
raise
|
|
127
|
+
self._refresher = asyncio.create_task(self._poll(), name="ai-protocol-policy")
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
async def __aexit__(self, *args):
|
|
131
|
+
await self.aclose()
|
|
132
|
+
|
|
133
|
+
async def _request(self, method, path, *, params=None, maximum=None):
|
|
134
|
+
body = bytearray()
|
|
135
|
+
async with self._http.stream(method, self._origin + path, json=params, timeout=30) as response:
|
|
136
|
+
async for chunk in response.aiter_bytes():
|
|
137
|
+
if len(body) + len(chunk) > (maximum or self._maximum_body):
|
|
138
|
+
raise ProtocolError("Response exceeds the configured size limit")
|
|
139
|
+
body.extend(chunk)
|
|
140
|
+
headers = dict(response.headers)
|
|
141
|
+
headers.pop("content-encoding", None)
|
|
142
|
+
headers.pop("content-length", None)
|
|
143
|
+
return httpx.Response(response.status_code, headers=headers,
|
|
144
|
+
content=bytes(body), request=response.request)
|
|
145
|
+
|
|
146
|
+
async def refresh(self):
|
|
147
|
+
"""Fetch and apply a coherent policy, pausing new work on any failure."""
|
|
148
|
+
async with self._condition:
|
|
149
|
+
if self._closed:
|
|
150
|
+
raise ProtocolError("Client is closed")
|
|
151
|
+
try:
|
|
152
|
+
async with asyncio.timeout(2):
|
|
153
|
+
response = await self._request("GET", "/agent-policy", maximum=1024 * 1024)
|
|
154
|
+
response.raise_for_status()
|
|
155
|
+
policy = response.json()
|
|
156
|
+
async with self._condition:
|
|
157
|
+
validated = validate_policy(policy, self._policy)
|
|
158
|
+
if not self._closed:
|
|
159
|
+
self._policy, self._ready = validated, True
|
|
160
|
+
self._condition.notify_all()
|
|
161
|
+
return self.policy
|
|
162
|
+
except (httpx.HTTPError, ValueError, TimeoutError, asyncio.CancelledError) as error:
|
|
163
|
+
async with self._condition:
|
|
164
|
+
self._ready = False
|
|
165
|
+
self._condition.notify_all()
|
|
166
|
+
if isinstance(error, asyncio.CancelledError):
|
|
167
|
+
raise
|
|
168
|
+
raise ProtocolError("Policy refresh failed") from None
|
|
169
|
+
|
|
170
|
+
async def _poll(self):
|
|
171
|
+
while True:
|
|
172
|
+
delay = self._policy["refresh_after_ms"] / 1000 if self._ready else 1
|
|
173
|
+
await asyncio.sleep(delay)
|
|
174
|
+
with suppress(ProtocolError):
|
|
175
|
+
await self.refresh()
|
|
176
|
+
|
|
177
|
+
async def _acquire(self, name):
|
|
178
|
+
async with self._condition:
|
|
179
|
+
while True:
|
|
180
|
+
if self._closed:
|
|
181
|
+
raise OperationError("client_closed", "not_started")
|
|
182
|
+
if self._ready and (self._dispatcher or self._active < self._policy["limits"]["max_outstanding"]):
|
|
183
|
+
operation = next((op for op in self._policy["operations"] if op["name"] == name), None)
|
|
184
|
+
if operation is None:
|
|
185
|
+
raise OperationError("operation_not_permitted", "not_started")
|
|
186
|
+
if not self._dispatcher:
|
|
187
|
+
self._active += 1
|
|
188
|
+
return copy.deepcopy(operation)
|
|
189
|
+
await self._condition.wait()
|
|
190
|
+
|
|
191
|
+
async def call(self, operation, params, *, timeout=120, deadline_unix_ms=None):
|
|
192
|
+
"""Call a discovered operation by name with one deadline and five attempts.
|
|
193
|
+
|
|
194
|
+
An absolute Unix deadline overrides `timeout`; it is preserved when using
|
|
195
|
+
the dispatcher. A deadline must be no more than one hour in the future.
|
|
196
|
+
"""
|
|
197
|
+
if self._policy is None and self._refresher is None:
|
|
198
|
+
raise ProtocolError("Enter the client with async with before calling operations")
|
|
199
|
+
if deadline_unix_ms is not None and type(deadline_unix_ms) not in (float, int):
|
|
200
|
+
raise ProtocolError("Invalid task deadline")
|
|
201
|
+
duration = timeout if deadline_unix_ms is None else deadline_unix_ms / 1000 - time.time()
|
|
202
|
+
if type(duration) not in (float, int) or not math.isfinite(duration) or duration > 3600:
|
|
203
|
+
raise ProtocolError("Invalid task deadline")
|
|
204
|
+
if duration <= 0:
|
|
205
|
+
raise DeadlineExceeded("task_deadline", "not_started")
|
|
206
|
+
deadline_unix_ms = deadline_unix_ms if deadline_unix_ms is not None else (time.time() + duration) * 1000
|
|
207
|
+
attempts, may_have_executed = 0, False
|
|
208
|
+
try:
|
|
209
|
+
async with asyncio.timeout(duration):
|
|
210
|
+
for number in range(1, 6):
|
|
211
|
+
descriptor = await self._acquire(operation)
|
|
212
|
+
try:
|
|
213
|
+
try:
|
|
214
|
+
jsonschema.Draft202012Validator(descriptor["input_schema"]).validate(params)
|
|
215
|
+
json.dumps(params, allow_nan=False)
|
|
216
|
+
except (TypeError, ValueError, jsonschema.ValidationError, jsonschema.SchemaError):
|
|
217
|
+
raise OperationError("invalid_parameters", "not_started", attempts=attempts) from None
|
|
218
|
+
if self._dispatcher:
|
|
219
|
+
may_have_executed = True
|
|
220
|
+
reply = await self._dispatcher.call(descriptor, params, deadline_unix_ms=deadline_unix_ms)
|
|
221
|
+
if not reply["ok"]:
|
|
222
|
+
raise OperationError(reply["code"], reply["execution"], status=reply.get("status"), attempts=reply.get("attempts"))
|
|
223
|
+
return reply["body"]
|
|
224
|
+
attempts = number
|
|
225
|
+
may_have_executed = True
|
|
226
|
+
try:
|
|
227
|
+
response = await self._request("POST", descriptor["path"], params=params)
|
|
228
|
+
except (httpx.HTTPError, ProtocolError):
|
|
229
|
+
raise OperationError("transport_error", "unknown", attempts=attempts) from None
|
|
230
|
+
finally:
|
|
231
|
+
if not self._dispatcher:
|
|
232
|
+
async with self._condition:
|
|
233
|
+
self._active -= 1
|
|
234
|
+
self._condition.notify_all()
|
|
235
|
+
if response.is_success:
|
|
236
|
+
try:
|
|
237
|
+
return response.json()
|
|
238
|
+
except ValueError:
|
|
239
|
+
raise OperationError("invalid_response", "unknown", attempts=attempts) from None
|
|
240
|
+
try:
|
|
241
|
+
error = response.json().get("error", {})
|
|
242
|
+
except (ValueError, AttributeError):
|
|
243
|
+
error = {}
|
|
244
|
+
known = response.status_code in (400, 401, 403, 404, 405, 413, 415, 422, 429) or (
|
|
245
|
+
response.status_code == 503 and isinstance(error, dict)
|
|
246
|
+
and error.get("code") in ("queue_timeout", "gateway_closed") and error.get("execution") == "not_started")
|
|
247
|
+
may_have_executed = not known
|
|
248
|
+
if not safe_to_retry(response) or number == 5:
|
|
249
|
+
code = error.get("code", "http_error") if isinstance(error, dict) else "http_error"
|
|
250
|
+
if not isinstance(code, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", code):
|
|
251
|
+
code = "http_error"
|
|
252
|
+
raise OperationError(code, "unknown" if may_have_executed else "not_started", status=response.status_code, attempts=attempts)
|
|
253
|
+
raw = response.headers.get("Retry-After", "1").strip()
|
|
254
|
+
seconds = int(raw) if raw.isascii() and raw.isdigit() else 1
|
|
255
|
+
if seconds >= deadline_unix_ms / 1000 - time.time():
|
|
256
|
+
raise DeadlineExceeded("task_deadline", "not_started", attempts=attempts)
|
|
257
|
+
await asyncio.sleep(seconds)
|
|
258
|
+
except TimeoutError:
|
|
259
|
+
raise DeadlineExceeded("task_deadline", "unknown" if may_have_executed else "not_started", attempts=attempts) from None
|
|
260
|
+
|
|
261
|
+
async def aclose(self):
|
|
262
|
+
"""Stop new attempts and the owned refresher; close the HTTP transport."""
|
|
263
|
+
async with self._condition:
|
|
264
|
+
self._closed, self._ready = True, False
|
|
265
|
+
self._condition.notify_all()
|
|
266
|
+
if self._refresher is not None:
|
|
267
|
+
self._refresher.cancel()
|
|
268
|
+
with suppress(asyncio.CancelledError):
|
|
269
|
+
await self._refresher
|
|
270
|
+
self._refresher = None
|
|
271
|
+
await self._http.aclose()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Reusable offline schema validation and opt-in HTTP conformance checks."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from importlib.resources import files
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import jsonschema
|
|
10
|
+
from referencing import Registry, Resource
|
|
11
|
+
|
|
12
|
+
from .client import validate_policy
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@lru_cache(maxsize=1)
|
|
16
|
+
def _contracts():
|
|
17
|
+
schemas = {name: json.loads(files("ai_protocol").joinpath(f"schemas/{name}.schema.json").read_text())
|
|
18
|
+
for name in ("operation", "policy", "error", "manifest")}
|
|
19
|
+
registry = Registry().with_resources((value["$id"], Resource.from_contents(value)) for value in schemas.values())
|
|
20
|
+
return schemas, registry
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def validate_contract(name, document):
|
|
24
|
+
"""Raise ValidationError for a contract violation; never fetch remote schemas."""
|
|
25
|
+
schemas, registry = _contracts()
|
|
26
|
+
jsonschema.Draft202012Validator(schemas[name], registry=registry).validate(document)
|
|
27
|
+
if name == "policy":
|
|
28
|
+
validate_policy(document)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def check_service(origin, token, *, operation=None, params=None):
|
|
32
|
+
"""Check discovery/authentication and optionally execute one read-only call."""
|
|
33
|
+
from .protocol import validate_origin
|
|
34
|
+
import re
|
|
35
|
+
origin = validate_origin(origin)
|
|
36
|
+
if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9._~+/=-]+", token):
|
|
37
|
+
raise ValueError("Invalid bearer credential")
|
|
38
|
+
with httpx.Client(trust_env=False, follow_redirects=False, timeout=5) as http:
|
|
39
|
+
unauthenticated = http.get(origin + "/agent-policy")
|
|
40
|
+
if unauthenticated.status_code != 401:
|
|
41
|
+
raise ValueError("Discovery must reject unauthenticated requests with 401")
|
|
42
|
+
validate_contract("error", unauthenticated.json())
|
|
43
|
+
if unauthenticated.json()["error"]["execution"] != "not_started":
|
|
44
|
+
raise ValueError("Authentication failure cannot start an operation")
|
|
45
|
+
headers = {"Authorization": f"Bearer {token}"}
|
|
46
|
+
response = http.get(origin + "/agent-policy", headers=headers)
|
|
47
|
+
response.raise_for_status()
|
|
48
|
+
if response.headers.get("cache-control") != "no-store":
|
|
49
|
+
raise ValueError("Discovery must be uncacheable")
|
|
50
|
+
policy = response.json()
|
|
51
|
+
validate_contract("policy", policy)
|
|
52
|
+
if operation is not None:
|
|
53
|
+
descriptor = next((op for op in policy["operations"] if op["name"] == operation), None)
|
|
54
|
+
if descriptor is None:
|
|
55
|
+
raise ValueError("Requested operation is absent from discovery")
|
|
56
|
+
jsonschema.Draft202012Validator(descriptor["input_schema"]).validate(params)
|
|
57
|
+
result = http.post(origin + descriptor["path"], headers=headers, json=params)
|
|
58
|
+
result.raise_for_status()
|
|
59
|
+
result.json()
|
|
60
|
+
return {"service_id": policy.get("service_id"), "version": policy["version"], "operations": len(policy["operations"])}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main():
|
|
64
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
65
|
+
parser.add_argument("--manifest", help="Validate a manifest file offline")
|
|
66
|
+
parser.add_argument("--origin", help="Explicit HTTP(S) service origin")
|
|
67
|
+
parser.add_argument("--token-env", default="AGENT_TOKEN_1", help="Name of the token environment variable")
|
|
68
|
+
parser.add_argument("--operation", help="Opt in to one read-only operation call")
|
|
69
|
+
parser.add_argument("--params", help="JSON parameters, required with --operation")
|
|
70
|
+
args = parser.parse_args()
|
|
71
|
+
if bool(args.operation) != (args.params is not None):
|
|
72
|
+
parser.error("--operation and --params must be supplied together")
|
|
73
|
+
try:
|
|
74
|
+
if args.manifest:
|
|
75
|
+
with open(args.manifest) as source:
|
|
76
|
+
validate_contract("manifest", json.load(source))
|
|
77
|
+
if args.origin:
|
|
78
|
+
result = check_service(args.origin, os.environ[args.token_env], operation=args.operation,
|
|
79
|
+
params=json.loads(args.params) if args.params is not None else None)
|
|
80
|
+
print(json.dumps(result))
|
|
81
|
+
if not args.manifest and not args.origin:
|
|
82
|
+
parser.error("Supply --manifest or --origin")
|
|
83
|
+
except (ValueError, KeyError, OSError, httpx.HTTPError, jsonschema.ValidationError):
|
|
84
|
+
# Third-party responses and validation errors can contain submitted secrets.
|
|
85
|
+
parser.exit(1, "Conformance check failed; verify configuration and contract fields.\n")
|
|
86
|
+
print("PASS: requested conformance checks.")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
main()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Local agent connector. Exactly one submission; never replay an unknown outcome."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
|
|
10
|
+
MAX_FRAME = 64 * 1024
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DispatcherClient:
|
|
14
|
+
def __init__(self, socket_path=None, token=None):
|
|
15
|
+
self.socket_path = socket_path or os.environ['DISPATCH_SOCKET']
|
|
16
|
+
self.token = token or os.environ['AGENT_TOKEN_1']
|
|
17
|
+
|
|
18
|
+
async def call(self, operation, params, *, timeout_s=10, deadline_unix_ms=None):
|
|
19
|
+
# Pass an existing absolute deadline if the task arrived before this call.
|
|
20
|
+
deadline = deadline_unix_ms if deadline_unix_ms is not None else (time.time() + timeout_s) * 1000
|
|
21
|
+
remaining = deadline / 1000 - time.time()
|
|
22
|
+
def error(code, execution):
|
|
23
|
+
return dict(ok=False, code=code, execution=execution, attempts=None if execution == 'unknown' else 0, status=None, body=None)
|
|
24
|
+
if not math.isfinite(remaining):
|
|
25
|
+
return error('invalid_dispatch_request', 'not_started')
|
|
26
|
+
if remaining <= 0:
|
|
27
|
+
return error('task_deadline', 'not_started')
|
|
28
|
+
if isinstance(operation, dict):
|
|
29
|
+
from .protocol import validate_operation
|
|
30
|
+
import jsonschema
|
|
31
|
+
try:
|
|
32
|
+
validate_operation(operation)
|
|
33
|
+
jsonschema.Draft202012Validator(operation['input_schema']).validate(params)
|
|
34
|
+
except (ValueError, jsonschema.ValidationError, jsonschema.SchemaError):
|
|
35
|
+
return error('invalid_dispatch_request', 'not_started')
|
|
36
|
+
operation = operation['name']
|
|
37
|
+
if remaining > 3600 or not isinstance(operation, str) or not re.fullmatch(r'[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*', operation):
|
|
38
|
+
return error('invalid_dispatch_request', 'not_started')
|
|
39
|
+
try:
|
|
40
|
+
payload = json.dumps(dict(id=uuid.uuid4().hex, token=self.token, operation=operation,
|
|
41
|
+
params=params, deadline_unix_ms=deadline), allow_nan=False).encode() + b'\n'
|
|
42
|
+
except (TypeError, ValueError):
|
|
43
|
+
return error('invalid_dispatch_request', 'not_started')
|
|
44
|
+
if len(payload) > MAX_FRAME:
|
|
45
|
+
return error('invalid_dispatch_request', 'not_started')
|
|
46
|
+
writer = None
|
|
47
|
+
connected = False
|
|
48
|
+
async def exchange():
|
|
49
|
+
nonlocal writer, connected
|
|
50
|
+
reader, writer = await asyncio.open_unix_connection(self.socket_path, limit=MAX_FRAME)
|
|
51
|
+
connected = True
|
|
52
|
+
writer.write(payload)
|
|
53
|
+
await writer.drain()
|
|
54
|
+
raw = await reader.readline()
|
|
55
|
+
if len(raw) > MAX_FRAME or not raw.endswith(b'\n'):
|
|
56
|
+
raise ValueError('Incomplete dispatcher reply')
|
|
57
|
+
reply = json.loads(raw)
|
|
58
|
+
if not isinstance(reply, dict) or not isinstance(reply.get('ok'), bool) or not isinstance(reply.get('code'), str) or reply.get('execution') not in ('completed', 'not_started', 'unknown'):
|
|
59
|
+
raise ValueError('Invalid dispatcher reply')
|
|
60
|
+
if (reply.get("attempts") is not None and (type(reply["attempts"]) is not int or reply["attempts"] < 0)
|
|
61
|
+
or reply["ok"] and (reply["execution"] != "completed" or "body" not in reply or not (type(reply.get("status")) is int and 200 <= reply["status"] < 300))
|
|
62
|
+
or not reply["ok"] and reply["execution"] == "completed"):
|
|
63
|
+
raise ValueError('Inconsistent dispatcher reply')
|
|
64
|
+
return reply
|
|
65
|
+
remaining = deadline / 1000 - time.time()
|
|
66
|
+
if remaining <= 0:
|
|
67
|
+
return error('task_deadline', 'not_started')
|
|
68
|
+
try:
|
|
69
|
+
return await asyncio.wait_for(exchange(), remaining)
|
|
70
|
+
except (OSError, ValueError, asyncio.TimeoutError):
|
|
71
|
+
return error('dispatcher_response_lost' if connected else 'dispatcher_unavailable',
|
|
72
|
+
'unknown' if connected else 'not_started')
|
|
73
|
+
finally:
|
|
74
|
+
if writer is not None:
|
|
75
|
+
writer.close()
|
|
76
|
+
try:
|
|
77
|
+
await writer.wait_closed()
|
|
78
|
+
except OSError:
|
|
79
|
+
pass
|
ai_protocol/protocol.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Shared v3 discovery, authorization, and bounded retry handling."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import jsonschema
|
|
10
|
+
|
|
11
|
+
BASE_URL = os.environ.get("SERVICE_URL", f"http://127.0.0.1:{os.environ.get('GATEWAY_PORT', '3000')}").rstrip("/")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def validate_origin(origin):
|
|
15
|
+
url = urlsplit(origin)
|
|
16
|
+
if (url.scheme not in ("http", "https") or not url.hostname or url.username is not None
|
|
17
|
+
or url.password is not None or url.path not in ("", "/") or url.query or url.fragment):
|
|
18
|
+
raise ValueError("Service URL must be an HTTP(S) origin without credentials or a path")
|
|
19
|
+
return origin.rstrip("/")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def service_client(token=None):
|
|
23
|
+
token = token or os.environ.get("AGENT_TOKEN_1")
|
|
24
|
+
if not token:
|
|
25
|
+
raise ValueError("Set AGENT_TOKEN_1 before running the client")
|
|
26
|
+
if not re.fullmatch(r"[A-Za-z0-9._~+/=-]+", token):
|
|
27
|
+
raise ValueError("AGENT_TOKEN_1 is not a valid bearer token")
|
|
28
|
+
return httpx.Client(
|
|
29
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
30
|
+
trust_env=False,
|
|
31
|
+
timeout=30,
|
|
32
|
+
follow_redirects=False,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def validate_operation(operation):
|
|
37
|
+
if not isinstance(operation, dict):
|
|
38
|
+
raise ValueError("Invalid operation descriptor")
|
|
39
|
+
if not isinstance(operation.get("name"), str) or not operation["name"]:
|
|
40
|
+
raise ValueError("Invalid operation name")
|
|
41
|
+
if not isinstance(operation.get("description"), str):
|
|
42
|
+
raise ValueError("Invalid operation description")
|
|
43
|
+
if operation.get("method") != "POST":
|
|
44
|
+
raise ValueError("This client currently supports only POST")
|
|
45
|
+
path = operation.get("path")
|
|
46
|
+
if not isinstance(path, str) or not re.fullmatch(
|
|
47
|
+
r"/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*", path
|
|
48
|
+
):
|
|
49
|
+
raise ValueError("Unsupported operation path")
|
|
50
|
+
schema = operation.get("input_schema")
|
|
51
|
+
if not isinstance(schema, dict):
|
|
52
|
+
raise ValueError("Invalid operation schema")
|
|
53
|
+
|
|
54
|
+
# Remote schema references must not cause requests to arbitrary origins.
|
|
55
|
+
def check_references(value):
|
|
56
|
+
if isinstance(value, dict):
|
|
57
|
+
for key, item in value.items():
|
|
58
|
+
if key in ("$ref", "$dynamicRef") and (
|
|
59
|
+
not isinstance(item, str) or not item.startswith("#")
|
|
60
|
+
):
|
|
61
|
+
raise ValueError("External schema references are not supported")
|
|
62
|
+
check_references(item)
|
|
63
|
+
elif isinstance(value, list):
|
|
64
|
+
for item in value:
|
|
65
|
+
check_references(item)
|
|
66
|
+
|
|
67
|
+
check_references(schema)
|
|
68
|
+
jsonschema.Draft202012Validator.check_schema(schema)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def discover(client, *, base_url=None):
|
|
72
|
+
response = client.get((base_url or BASE_URL).rstrip("/") + "/agent-policy")
|
|
73
|
+
response.raise_for_status()
|
|
74
|
+
policy = response.json()
|
|
75
|
+
if (
|
|
76
|
+
not isinstance(policy, dict)
|
|
77
|
+
or type(policy.get("version")) is not int
|
|
78
|
+
or policy["version"] != 3
|
|
79
|
+
):
|
|
80
|
+
raise ValueError("Unsupported protocol version; this client requires v3")
|
|
81
|
+
if not isinstance(policy.get("principal_id"), str) or not policy["principal_id"]:
|
|
82
|
+
raise ValueError("Invalid principal ID")
|
|
83
|
+
if policy.get("client_class") not in ("agent", "interactive"):
|
|
84
|
+
raise ValueError("Invalid client class")
|
|
85
|
+
limits = policy.get("limits")
|
|
86
|
+
if not isinstance(limits, dict) or limits.get("scope") != "principal":
|
|
87
|
+
raise ValueError("Unsupported budget scope")
|
|
88
|
+
maximum = limits.get("max_outstanding")
|
|
89
|
+
if type(maximum) is not int or maximum < 1:
|
|
90
|
+
raise ValueError("Invalid outstanding limit")
|
|
91
|
+
operations = policy.get("operations")
|
|
92
|
+
if not isinstance(operations, list):
|
|
93
|
+
raise ValueError("Invalid operation list")
|
|
94
|
+
names = set()
|
|
95
|
+
for operation in operations:
|
|
96
|
+
validate_operation(operation)
|
|
97
|
+
if operation["name"] in names:
|
|
98
|
+
raise ValueError("Duplicate operation name")
|
|
99
|
+
names.add(operation["name"])
|
|
100
|
+
return operations
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def safe_to_retry(response):
|
|
104
|
+
if response.status_code == 429:
|
|
105
|
+
return True
|
|
106
|
+
if response.status_code != 503:
|
|
107
|
+
return False
|
|
108
|
+
try:
|
|
109
|
+
body = response.json()
|
|
110
|
+
except ValueError:
|
|
111
|
+
return False
|
|
112
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
113
|
+
return (
|
|
114
|
+
isinstance(error, dict)
|
|
115
|
+
and error.get("code") == "queue_timeout"
|
|
116
|
+
and error.get("execution") == "not_started"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def execute(client, operation, params, *, task_timeout=120, base_url=None):
|
|
121
|
+
validate_operation(operation)
|
|
122
|
+
jsonschema.Draft202012Validator(operation["input_schema"]).validate(params)
|
|
123
|
+
deadline = time.monotonic() + task_timeout
|
|
124
|
+
for attempt in range(1, 6):
|
|
125
|
+
remaining = deadline - time.monotonic()
|
|
126
|
+
if remaining <= 0:
|
|
127
|
+
raise TimeoutError("Operation deadline exceeded")
|
|
128
|
+
response = client.request(
|
|
129
|
+
operation["method"], (base_url or BASE_URL).rstrip("/") + operation["path"], json=params,
|
|
130
|
+
timeout=min(30, remaining),
|
|
131
|
+
)
|
|
132
|
+
if time.monotonic() >= deadline:
|
|
133
|
+
raise TimeoutError("Operation deadline exceeded")
|
|
134
|
+
if safe_to_retry(response) and attempt < 5:
|
|
135
|
+
raw = response.headers.get("Retry-After", "1").strip()
|
|
136
|
+
seconds = int(raw) if raw.isascii() and raw.isdigit() else 1
|
|
137
|
+
if seconds >= deadline - time.monotonic():
|
|
138
|
+
raise TimeoutError("Retry-After exceeds the operation deadline")
|
|
139
|
+
print(f"The service asks to wait {seconds} seconds.")
|
|
140
|
+
time.sleep(seconds)
|
|
141
|
+
continue
|
|
142
|
+
response.raise_for_status()
|
|
143
|
+
return response.json()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "urn:ai-protocol:error:3",
|
|
4
|
+
"title": "Protocol v3 gateway error",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"error"
|
|
8
|
+
],
|
|
9
|
+
"properties": {
|
|
10
|
+
"error": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"required": [
|
|
13
|
+
"code",
|
|
14
|
+
"execution"
|
|
15
|
+
],
|
|
16
|
+
"properties": {
|
|
17
|
+
"code": {
|
|
18
|
+
"type": "string",
|
|
19
|
+
"pattern": "^[a-z][a-z0-9_]{0,63}$"
|
|
20
|
+
},
|
|
21
|
+
"execution": {
|
|
22
|
+
"enum": [
|
|
23
|
+
"not_started",
|
|
24
|
+
"unknown"
|
|
25
|
+
]
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"additionalProperties": false
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"additionalProperties": false
|
|
32
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "urn:ai-protocol:manifest:1",
|
|
4
|
+
"title": "Read-only HTTP adapter manifest v1",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"service_id",
|
|
8
|
+
"operations",
|
|
9
|
+
"credentials"
|
|
10
|
+
],
|
|
11
|
+
"additionalProperties": false,
|
|
12
|
+
"properties": {
|
|
13
|
+
"format_version": {
|
|
14
|
+
"const": 1
|
|
15
|
+
},
|
|
16
|
+
"service_id": {
|
|
17
|
+
"type": "string",
|
|
18
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
19
|
+
},
|
|
20
|
+
"operations": {
|
|
21
|
+
"type": "array",
|
|
22
|
+
"minItems": 1,
|
|
23
|
+
"items": {
|
|
24
|
+
"type": "object",
|
|
25
|
+
"required": [
|
|
26
|
+
"name",
|
|
27
|
+
"description",
|
|
28
|
+
"path",
|
|
29
|
+
"upstream_path",
|
|
30
|
+
"parameters"
|
|
31
|
+
],
|
|
32
|
+
"additionalProperties": false,
|
|
33
|
+
"properties": {
|
|
34
|
+
"name": {
|
|
35
|
+
"type": "string",
|
|
36
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
37
|
+
},
|
|
38
|
+
"description": {
|
|
39
|
+
"type": "string"
|
|
40
|
+
},
|
|
41
|
+
"path": {
|
|
42
|
+
"type": "string",
|
|
43
|
+
"pattern": "^/[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$"
|
|
44
|
+
},
|
|
45
|
+
"upstream_path": {
|
|
46
|
+
"type": "string",
|
|
47
|
+
"pattern": "^/[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$"
|
|
48
|
+
},
|
|
49
|
+
"parameters": {
|
|
50
|
+
"type": "object",
|
|
51
|
+
"propertyNames": {
|
|
52
|
+
"type": "string",
|
|
53
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
54
|
+
},
|
|
55
|
+
"additionalProperties": {
|
|
56
|
+
"type": "object",
|
|
57
|
+
"required": [
|
|
58
|
+
"type",
|
|
59
|
+
"upstream"
|
|
60
|
+
],
|
|
61
|
+
"additionalProperties": false,
|
|
62
|
+
"properties": {
|
|
63
|
+
"type": {
|
|
64
|
+
"enum": [
|
|
65
|
+
"string",
|
|
66
|
+
"integer"
|
|
67
|
+
]
|
|
68
|
+
},
|
|
69
|
+
"upstream": {
|
|
70
|
+
"type": "string",
|
|
71
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"credentials": {
|
|
80
|
+
"type": "array",
|
|
81
|
+
"minItems": 1,
|
|
82
|
+
"items": {
|
|
83
|
+
"type": "object",
|
|
84
|
+
"required": [
|
|
85
|
+
"token_env",
|
|
86
|
+
"required",
|
|
87
|
+
"principal_id",
|
|
88
|
+
"client_class",
|
|
89
|
+
"operations",
|
|
90
|
+
"max_outstanding"
|
|
91
|
+
],
|
|
92
|
+
"additionalProperties": false,
|
|
93
|
+
"properties": {
|
|
94
|
+
"token_env": {
|
|
95
|
+
"type": "string",
|
|
96
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
97
|
+
},
|
|
98
|
+
"required": {
|
|
99
|
+
"type": "boolean"
|
|
100
|
+
},
|
|
101
|
+
"principal_id": {
|
|
102
|
+
"type": "string",
|
|
103
|
+
"minLength": 1
|
|
104
|
+
},
|
|
105
|
+
"client_class": {
|
|
106
|
+
"enum": [
|
|
107
|
+
"agent",
|
|
108
|
+
"interactive"
|
|
109
|
+
]
|
|
110
|
+
},
|
|
111
|
+
"operations": {
|
|
112
|
+
"type": "array",
|
|
113
|
+
"items": {
|
|
114
|
+
"type": "string",
|
|
115
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
"max_outstanding": {
|
|
119
|
+
"type": "integer",
|
|
120
|
+
"minimum": 1,
|
|
121
|
+
"maximum": 1000
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "urn:ai-protocol:operation:3",
|
|
4
|
+
"title": "Protocol v3 operation descriptor",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"name",
|
|
8
|
+
"description",
|
|
9
|
+
"method",
|
|
10
|
+
"path",
|
|
11
|
+
"input_schema"
|
|
12
|
+
],
|
|
13
|
+
"properties": {
|
|
14
|
+
"name": {
|
|
15
|
+
"type": "string",
|
|
16
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
17
|
+
},
|
|
18
|
+
"description": {
|
|
19
|
+
"type": "string"
|
|
20
|
+
},
|
|
21
|
+
"method": {
|
|
22
|
+
"const": "POST"
|
|
23
|
+
},
|
|
24
|
+
"path": {
|
|
25
|
+
"type": "string",
|
|
26
|
+
"pattern": "^/[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$"
|
|
27
|
+
},
|
|
28
|
+
"input_schema": {
|
|
29
|
+
"type": "object"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"additionalProperties": true
|
|
33
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "urn:ai-protocol:policy:3",
|
|
4
|
+
"title": "Protocol v3 policy",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"version",
|
|
8
|
+
"principal_id",
|
|
9
|
+
"client_class",
|
|
10
|
+
"policy_revision",
|
|
11
|
+
"refresh_after_ms",
|
|
12
|
+
"outstanding",
|
|
13
|
+
"limits",
|
|
14
|
+
"queue",
|
|
15
|
+
"operations"
|
|
16
|
+
],
|
|
17
|
+
"properties": {
|
|
18
|
+
"version": {
|
|
19
|
+
"const": 3
|
|
20
|
+
},
|
|
21
|
+
"service_id": {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
24
|
+
},
|
|
25
|
+
"principal_id": {
|
|
26
|
+
"type": "string",
|
|
27
|
+
"minLength": 1
|
|
28
|
+
},
|
|
29
|
+
"client_class": {
|
|
30
|
+
"enum": [
|
|
31
|
+
"agent",
|
|
32
|
+
"interactive"
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
"policy_revision": {
|
|
36
|
+
"type": "integer",
|
|
37
|
+
"minimum": 1
|
|
38
|
+
},
|
|
39
|
+
"refresh_after_ms": {
|
|
40
|
+
"type": "integer",
|
|
41
|
+
"minimum": 100,
|
|
42
|
+
"maximum": 60000
|
|
43
|
+
},
|
|
44
|
+
"outstanding": {
|
|
45
|
+
"type": "integer",
|
|
46
|
+
"minimum": 0
|
|
47
|
+
},
|
|
48
|
+
"limits": {
|
|
49
|
+
"type": "object",
|
|
50
|
+
"required": [
|
|
51
|
+
"scope",
|
|
52
|
+
"max_outstanding"
|
|
53
|
+
],
|
|
54
|
+
"properties": {
|
|
55
|
+
"scope": {
|
|
56
|
+
"const": "principal"
|
|
57
|
+
},
|
|
58
|
+
"max_outstanding": {
|
|
59
|
+
"type": "integer",
|
|
60
|
+
"minimum": 1,
|
|
61
|
+
"maximum": 1000
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"queue": {
|
|
66
|
+
"type": "object",
|
|
67
|
+
"required": [
|
|
68
|
+
"max_wait_ms"
|
|
69
|
+
],
|
|
70
|
+
"properties": {
|
|
71
|
+
"max_wait_ms": {
|
|
72
|
+
"type": "integer",
|
|
73
|
+
"minimum": 1,
|
|
74
|
+
"maximum": 3600000
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
"operations": {
|
|
79
|
+
"type": "array",
|
|
80
|
+
"items": {
|
|
81
|
+
"$ref": "urn:ai-protocol:operation:3"
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"additionalProperties": true
|
|
86
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ai-protocol-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Adaptive clients for cooperative agent access to HTTP services
|
|
5
|
+
Author: Nikita Chindin
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/Xenox-developer/ai-protocol
|
|
8
|
+
Project-URL: Issues, https://github.com/Xenox-developer/ai-protocol/issues
|
|
9
|
+
Keywords: agents,http,gateway,scheduling
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: httpx==0.28.1
|
|
14
|
+
Requires-Dist: jsonschema==4.24.0
|
|
15
|
+
Requires-Dist: referencing==0.37.0
|
|
16
|
+
Provides-Extra: llm
|
|
17
|
+
Requires-Dist: openai==1.109.1; extra == "llm"
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# AI Protocol
|
|
23
|
+
|
|
24
|
+
[](https://github.com/Xenox-developer/ai-protocol/actions/workflows/checks.yml)
|
|
25
|
+
[](LICENSE)
|
|
26
|
+
|
|
27
|
+
A Rust framework and Python SDK for cooperative agent access to HTTP services.
|
|
28
|
+
Publish permitted read operations, enforce shared owner budgets, and let clients
|
|
29
|
+
adapt to changing capacity through protocol v3 discovery.
|
|
30
|
+
|
|
31
|
+
**Status:** experimental 0.1.0. The [release page](https://github.com/Xenox-developer/ai-protocol/releases/tag/v0.1.0)
|
|
32
|
+
provides verified archives and the current crates.io/PyPI publication status.
|
|
33
|
+
AI Protocol is a project contract, not a public standard. Supported scope is one in-memory gateway process per
|
|
34
|
+
service, read-only operations, and Linux/macOS for the optional dispatcher.
|
|
35
|
+
|
|
36
|
+
## What it provides
|
|
37
|
+
|
|
38
|
+
- **Embeddable Rust gateway:** typed asynchronous native handlers in Axum, or
|
|
39
|
+
an owner-configured HTTP adapter. Native inputs can contain nested objects,
|
|
40
|
+
arrays, booleans and optional fields; the HTTP mapper supports flat required
|
|
41
|
+
strings/integers mapped from POST JSON to GET query parameters.
|
|
42
|
+
- **Server-enforced access and budgets:** operation grants and one outstanding
|
|
43
|
+
counter per owner/class, shared across tokens, connections and clients.
|
|
44
|
+
- **Bounded scheduling:** queues and execution slots, FIFO within each class,
|
|
45
|
+
interactive/agent selection weights of 3:1 under competition, queue expiry,
|
|
46
|
+
execution deadlines and bounded buffered responses.
|
|
47
|
+
- **Adaptive Python SDK:** full policy refresh, a local attempt gate, typed
|
|
48
|
+
failures, one task deadline and bounded safe retries. OpenAI is optional.
|
|
49
|
+
- **Optional local dispatcher:** coordinate several agent processes through one
|
|
50
|
+
Unix socket per service/owner, without replaying unknown results.
|
|
51
|
+
- **Operational controls:** host authentication callback, separate upstream/admin
|
|
52
|
+
credentials, graceful shutdown, probes, basic metrics and safe JSON logs.
|
|
53
|
+
|
|
54
|
+
## Try it locally
|
|
55
|
+
|
|
56
|
+
Prerequisites: Rust/Cargo **1.98.1** (the pinned and tested minimum), Python
|
|
57
|
+
**3.12+**, and Linux or macOS. Run these commands from the repository root:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
git clone https://github.com/Xenox-developer/ai-protocol.git
|
|
61
|
+
cd ai-protocol
|
|
62
|
+
python3 -m venv .venv
|
|
63
|
+
source .venv/bin/activate
|
|
64
|
+
python -m pip install -e .
|
|
65
|
+
cargo build --locked --bins
|
|
66
|
+
python examples/quickstart.py
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Expected result: a successful catalog call, three independent clients through a
|
|
70
|
+
shared dispatcher, final `outstanding=0`, then cleanup of owned processes and
|
|
71
|
+
temporary credentials. The script uses free loopback ports and local fixture
|
|
72
|
+
data. No paid API or LLM is required. See the [quickstart](docs/QUICKSTART.md) for
|
|
73
|
+
roles, troubleshooting and the manual workflow.
|
|
74
|
+
|
|
75
|
+
For a persistent catalog demo, run `python examples/setup_demo.py` once, start
|
|
76
|
+
`python examples/catalog_service.py` in one terminal, then `source .env.demo`
|
|
77
|
+
and `cargo run --locked --bin ai-protocol` in another. The generated credential
|
|
78
|
+
file is private, ignored by Git, and never overwritten. Give each deployed agent
|
|
79
|
+
only its own credential.
|
|
80
|
+
|
|
81
|
+
## Add a service in Rust
|
|
82
|
+
|
|
83
|
+
For source integration, add this checkout as a path dependency in your application:
|
|
84
|
+
|
|
85
|
+
```toml
|
|
86
|
+
[dependencies]
|
|
87
|
+
ai-protocol = { path = "../ai-protocol" }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Register an `Operation::new` with its name, description, POST path, JSON input
|
|
91
|
+
schema and typed async handler. Create `GatewayConfig::native` with credentials,
|
|
92
|
+
start a `Gateway`, and merge `gateway.router()` at the root of your Axum router.
|
|
93
|
+
The host owns the listener and keeps the gateway alive while serving requests.
|
|
94
|
+
Call `close()` and `shutdown()` as part of bounded server shutdown.
|
|
95
|
+
|
|
96
|
+
A complete runnable integration is [native_service.rs](examples/native_service.rs):
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
export NATIVE_AGENT_TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(24))')"
|
|
100
|
+
cargo run --locked --example native_service
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Native inputs use Serde validation before admission; the service owner keeps the
|
|
104
|
+
published schema consistent with that Rust type and validates extra constraints.
|
|
105
|
+
Handlers must be nonblocking and read-only. For an existing HTTP API, use a
|
|
106
|
+
[service manifest](docs/service-integration.md); the included catalog and support
|
|
107
|
+
services demonstrate the same generic clients without service-specific branches.
|
|
108
|
+
See [Rust integration](docs/rust-library.md) for public interfaces, live host
|
|
109
|
+
authentication, resource bounds, budget updates and lifecycle semantics.
|
|
110
|
+
|
|
111
|
+
## Call it from Python
|
|
112
|
+
|
|
113
|
+
Install with `python -m pip install -e .` from the checkout, or install a verified
|
|
114
|
+
release wheel. The distribution is `ai-protocol-client`; the import is `ai_protocol`.
|
|
115
|
+
Use a separate client per service/credential and share it across concurrent tasks:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
import asyncio
|
|
119
|
+
import os
|
|
120
|
+
from ai_protocol import AsyncClient, OperationError
|
|
121
|
+
|
|
122
|
+
async def main():
|
|
123
|
+
async with AsyncClient(
|
|
124
|
+
os.environ["SERVICE_URL"], os.environ["AGENT_TOKEN_1"]
|
|
125
|
+
) as client:
|
|
126
|
+
print([op["name"] for op in client.policy["operations"]])
|
|
127
|
+
try:
|
|
128
|
+
result = await client.call("find_documents", {"query": "rust"}, timeout=10)
|
|
129
|
+
print(result)
|
|
130
|
+
except OperationError as error:
|
|
131
|
+
print(error.code, error.execution)
|
|
132
|
+
|
|
133
|
+
asyncio.run(main())
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
For the Rust example above, set `SERVICE_URL=http://127.0.0.1:3000` and give the
|
|
137
|
+
client its `NATIVE_AGENT_TOKEN` value as `AGENT_TOKEN_1`. Operation names and
|
|
138
|
+
parameters come from discovery. Policy failures pause new attempts; shrinking a
|
|
139
|
+
limit preserves attempts already running. Only admission 429 and the documented
|
|
140
|
+
pre-execution queue timeout may be retried, at most five attempts under the same
|
|
141
|
+
deadline. Unknown outcomes are terminal. Cancellation propagates to the caller
|
|
142
|
+
and does not prove downstream work stopped.
|
|
143
|
+
|
|
144
|
+
See [Python SDK](docs/python-sdk.md) for deadlines, errors, legacy synchronous
|
|
145
|
+
helpers and the dispatcher connector. `examples/sdk_client.py` provides an
|
|
146
|
+
interactive generic client. An LLM example is available after
|
|
147
|
+
`python -m pip install -e '.[llm]'`; real model calls require your own API access.
|
|
148
|
+
|
|
149
|
+
## How requests flow
|
|
150
|
+
|
|
151
|
+
```mermaid
|
|
152
|
+
flowchart LR
|
|
153
|
+
Agent[Agent / Python SDK] -->|HTTP v3| Gateway[Gateway: auth, owner budget, queues]
|
|
154
|
+
Agents[Several agents] --> Dispatcher[Optional local dispatcher]
|
|
155
|
+
Dispatcher -->|HTTP v3| Gateway
|
|
156
|
+
Gateway --> Slots[Bounded executors]
|
|
157
|
+
Slots --> Native[Native Rust handler]
|
|
158
|
+
Slots --> HTTP[Fixed upstream HTTP API]
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The service owner defines operations, trusted classes, permissions and budgets.
|
|
162
|
+
Agent developers discover/call permitted operations. Owners of several agents
|
|
163
|
+
can add the shared dispatcher; the gateway remains the admission authority.
|
|
164
|
+
|
|
165
|
+
## Configuration and guarantees
|
|
166
|
+
|
|
167
|
+
The executable binds to loopback by default. Configure the listener, executors,
|
|
168
|
+
queues, timeouts, body bounds and credentials using the [configuration and
|
|
169
|
+
operations guide](docs/operations.md). Public HTTPS uses a reverse proxy; that
|
|
170
|
+
guide includes a Caddy recipe, health/readiness routes, private admin metrics,
|
|
171
|
+
logging and shutdown behavior.
|
|
172
|
+
|
|
173
|
+
Budget accounting covers accepted queued and running work in **one process**.
|
|
174
|
+
Reducing a limit does not cancel accepted jobs. The 3:1 rule concerns selection,
|
|
175
|
+
not completion order or latency. Local timeout/drop cannot establish that a
|
|
176
|
+
remote operation did not execute. Errors carry explicit execution certainty;
|
|
177
|
+
there is no exactly-once or durable recovery guarantee.
|
|
178
|
+
|
|
179
|
+
This release does not provide replica coordination, durable queues, writes,
|
|
180
|
+
Windows dispatcher support, automatic API import, a UI, per-owner CPU isolation
|
|
181
|
+
or an independent security audit. See [protocol v3](docs/protocol.md),
|
|
182
|
+
[compatibility and schemas](docs/compatibility.md), and [security](SECURITY.md).
|
|
183
|
+
|
|
184
|
+
## Develop and verify
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
python -m pip install -r requirements.txt
|
|
188
|
+
bash scripts/verify.sh
|
|
189
|
+
# Build verified, unpublished crate/sdist/wheel files into a new local directory:
|
|
190
|
+
python scripts/check_packages.py --output dist/local-release
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
The verification command checks formatting, all Rust targets/tests/docs, Python
|
|
194
|
+
tests, an external Rust application, HTTP demos, documentation links, and isolated
|
|
195
|
+
artifact installation. CI runs it on Ubuntu and macOS. Packaging excludes raw
|
|
196
|
+
benchmark data, virtual environments and local credentials. The wheel is built
|
|
197
|
+
from the source distribution and tested without OpenAI outside the checkout.
|
|
198
|
+
See [contributing](CONTRIBUTING.md), the [release procedure](docs/releasing.md),
|
|
199
|
+
and the [framework verification report](docs/FRAMEWORK_REPORT.md).
|
|
200
|
+
|
|
201
|
+
Historical measurements are reproducible experiments with workload-specific
|
|
202
|
+
limits, not performance promises: [benchmark overview](benchmarks/README.md),
|
|
203
|
+
[second-service report](integration/SECOND_SERVICE_REPORT.md), and the
|
|
204
|
+
[historical catalog runbook](docs/history/README-before-framework.md). New framework
|
|
205
|
+
changes have functional checks; the full historical load series was not rerun.
|
|
206
|
+
The external developer trial remains skipped; no independent usability evidence
|
|
207
|
+
is claimed.
|
|
208
|
+
|
|
209
|
+
## Community and license
|
|
210
|
+
|
|
211
|
+
Use [GitHub issues](https://github.com/Xenox-developer/ai-protocol/issues) for bugs
|
|
212
|
+
and proposals, following [contribution guidance](CONTRIBUTING.md) and the
|
|
213
|
+
[code of conduct](CODE_OF_CONDUCT.md). Report vulnerabilities through the private
|
|
214
|
+
route in [SECURITY.md](SECURITY.md). Changes are recorded in [CHANGELOG.md](CHANGELOG.md).
|
|
215
|
+
Licensed under [Apache-2.0](LICENSE).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
ai_protocol/__init__.py,sha256=5BnsmX0bemLdord1eE3zXFuUigBx1VrLC495hd4WumE,416
|
|
2
|
+
ai_protocol/client.py,sha256=Cz0BC1EgF8HcarU2XWafLLVh3JnBZaGWio4CGUjiTBg,13618
|
|
3
|
+
ai_protocol/conformance.py,sha256=-KsiM4zaQK0lL5U89fJ6N7hnN5v79jJaDyELLIXgeSM,4398
|
|
4
|
+
ai_protocol/dispatcher.py,sha256=Yqsbgp1lEaIkk4iIzR1bwYXzoKMh5k3Tf3EsQDJrDew,4093
|
|
5
|
+
ai_protocol/protocol.py,sha256=mGaBjznJkCTAwGKcJdip_K6yShMUzOm8G63eR77GxhM,5605
|
|
6
|
+
ai_protocol/schemas/error.schema.json,sha256=IeqdmgS4_Dx3FgJaOewaPAbskdgifbW_FVERBqBXfIY,643
|
|
7
|
+
ai_protocol/schemas/manifest.schema.json,sha256=jxjUSgW5oLJHkmglI50-OZO6n2-6kEsXTUHPDDPK41M,3043
|
|
8
|
+
ai_protocol/schemas/operation.schema.json,sha256=-qwvW6mhwe4N1mmPVa0yCD4vDWPU347jT_wCoCeLIW4,651
|
|
9
|
+
ai_protocol/schemas/policy.schema.json,sha256=7WuCRjR12jFIAxMAvVkWFcXLoY1p1Fu7JV4t0o0HytA,1632
|
|
10
|
+
ai_protocol_client-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
ai_protocol_client-0.1.0.dist-info/METADATA,sha256=AI5kL_o9ZlxAm6m6jRcCRMc4Y2SIGgNaNQg95e3ggDo,10158
|
|
12
|
+
ai_protocol_client-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
ai_protocol_client-0.1.0.dist-info/top_level.txt,sha256=HtZVzDkfPfaA1gNOQtWzNMkKxPnMRl5hPezNlXw-5O4,12
|
|
14
|
+
ai_protocol_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ai_protocol
|