envloop-envhub 2.2.0__tar.gz → 2.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/PKG-INFO +3 -1
  2. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/README.pypi.md +2 -0
  3. envloop_envhub-2.3.1/envhub/proxyhub/__init__.py +1 -0
  4. envloop_envhub-2.3.1/envhub/proxyhub/bundle.py +20 -0
  5. envloop_envhub-2.3.1/envhub/proxyhub/guest.py +627 -0
  6. envloop_envhub-2.3.1/envhub/proxyhub/policy.py +141 -0
  7. envloop_envhub-2.3.1/envhub/proxyhub/services.py +66 -0
  8. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/pyproject.toml +11 -1
  9. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/NOTICE +0 -0
  10. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/__init__.py +0 -0
  11. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/__init__.py +0 -0
  12. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/client/__init__.py +0 -0
  13. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/client/download.py +0 -0
  14. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/client/materialize.py +0 -0
  15. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/client/recipe_package.py +0 -0
  16. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/__init__.py +0 -0
  17. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/ans.proto +0 -0
  18. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/errors.py +0 -0
  19. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/manifests.py +0 -0
  20. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/params.py +0 -0
  21. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/recipe.py +0 -0
  22. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/schemas.py +0 -0
  23. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/tags.py +0 -0
  24. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/ans/proto/uri.py +0 -0
  25. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/checkpoints/__init__.py +0 -0
  26. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/checkpoints/source.py +0 -0
  27. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/jobs/__init__.py +0 -0
  28. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/jobs/types.py +0 -0
  29. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/__init__.py +0 -0
  30. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/__main__.py +0 -0
  31. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/asset_io.py +0 -0
  32. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/bootstrap.py +0 -0
  33. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/contract.py +0 -0
  34. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/controller.py +0 -0
  35. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/declarations.py +0 -0
  36. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/guest.py +0 -0
  37. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/outputs.py +0 -0
  38. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/process.py +0 -0
  39. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/redaction.py +0 -0
  40. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/sdk.py +0 -0
  41. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/envhub/supervisor/tools.py +0 -0
  42. {envloop_envhub-2.2.0 → envloop_envhub-2.3.1}/hatch_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envloop-envhub
3
- Version: 2.2.0
3
+ Version: 2.3.1
4
4
  Summary: Dependency-free ANS protocol and verified downloads
5
5
  License-File: NOTICE
6
6
  Requires-Python: >=3.12
@@ -38,3 +38,5 @@ Source: https://github.com/EnvLoop/EnvHub
38
38
 
39
39
  The source baseline declares no implementation license. This packaging change
40
40
  adds no license grant; excluded content licenses do not apply. See NOTICE.
41
+
42
+ Portable `envhub.proxyhub` supplies the LiteLLM adapter, bounded request policy, private trajectory capture and service launch specifications. Optional service dependencies are prepared separately; importing the default package does not import LiteLLM or an HTTP server.
@@ -29,3 +29,5 @@ Source: https://github.com/EnvLoop/EnvHub
29
29
 
30
30
  The source baseline declares no implementation license. This packaging change
31
31
  adds no license grant; excluded content licenses do not apply. See NOTICE.
32
+
33
+ Portable `envhub.proxyhub` supplies the LiteLLM adapter, bounded request policy, private trajectory capture and service launch specifications. Optional service dependencies are prepared separately; importing the default package does not import LiteLLM or an HTTP server.
@@ -0,0 +1 @@
1
+ """Portable LiteLLM ProxyHub; optional runtime dependencies are loaded on startup."""
@@ -0,0 +1,20 @@
1
+ """Deterministic, self-contained guest delivery without server implementation imports."""
2
+ import io
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+
7
+ def payload() -> bytes:
8
+ output = io.BytesIO()
9
+ directory = Path(__file__).parent
10
+ files = {'envhub/__init__.py': b'',
11
+ '__main__.py': b'from envhub.proxyhub.guest import main\nimport sys\ntry:\n main()\nexcept Exception:\n print("PROXYHUB_OPERATION_FAILED", file=sys.stderr)\n sys.exit(1)\n'}
12
+ for name in ('__init__.py', 'guest.py', 'policy.py'):
13
+ files['envhub/proxyhub/' + name] = (directory / name).read_bytes()
14
+ with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
15
+ for name, content in sorted(files.items()):
16
+ info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
17
+ info.external_attr = 0o100644 << 16
18
+ info.compress_type = zipfile.ZIP_DEFLATED
19
+ archive.writestr(info, content)
20
+ return output.getvalue()
@@ -0,0 +1,627 @@
1
+ """Minimal sandbox data plane using LiteLLM's native Anthropic and OpenAI adapters.
2
+
3
+ This file is uploaded without importing EnvPlatform or its server credentials.
4
+ """
5
+ import asyncio
6
+ import hmac
7
+ import json
8
+ import os
9
+ import signal
10
+ import sqlite3
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ import uuid
15
+ from collections.abc import AsyncIterator
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from envhub.proxyhub.policy import Evidence, Extension, RetryPolicy
20
+
21
+ if TYPE_CHECKING:
22
+ from fastapi import FastAPI
23
+ from fastapi.requests import Request
24
+
25
+
26
+
27
+ class Spool:
28
+ def __init__(self, path: str | Path) -> None:
29
+ self.path = str(path)
30
+ with sqlite3.connect(self.path) as db:
31
+ db.execute('CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT NOT NULL)')
32
+
33
+ def append(self, event: dict[str, Any]) -> None:
34
+ with sqlite3.connect(self.path, timeout=10) as db:
35
+ if db.execute('SELECT COUNT(*) FROM events').fetchone()[0] >= 10000:
36
+ raise ValueError('PROXYHUB_SPOOL_FULL')
37
+ db.execute('INSERT INTO events(payload) VALUES(?)', (json.dumps(event, allow_nan=False),))
38
+
39
+ def snapshot(self) -> dict[str, Any]:
40
+ with sqlite3.connect(self.path, timeout=10) as db:
41
+ rows = db.execute('SELECT seq,payload FROM events ORDER BY seq LIMIT 1000').fetchall()
42
+ return dict(sequence=rows[-1][0] if rows else 0, events=[json.loads(row[1]) for row in rows])
43
+
44
+ def ack(self, sequence: int) -> None:
45
+ with sqlite3.connect(self.path, timeout=10) as db:
46
+ db.execute('DELETE FROM events WHERE seq<=?', (sequence,))
47
+
48
+
49
+ class StreamUsage:
50
+ def __init__(self) -> None:
51
+ self.buffer = b''
52
+ self.usage: dict[str, Any] = {}
53
+ self.started = self.delta = self.stopped = False
54
+
55
+ def feed(self, chunk: Any) -> None:
56
+ self.buffer += chunk.replace(b'\r\n', b'\n')
57
+ if len(self.buffer) > 4 * 1024 * 1024:
58
+ raise ValueError('PROXYHUB_STREAM_INVALID')
59
+ while b'\n\n' in self.buffer:
60
+ frame, self.buffer = self.buffer.split(b'\n\n', 1)
61
+ data = b'\n'.join(line[5:].lstrip() for line in frame.split(b'\n') if line.startswith(b'data:'))
62
+ if not data:
63
+ continue
64
+ value = json.loads(data)
65
+ if value.get('type') == 'message_start':
66
+ self.usage.update(value.get('message', {}).get('usage') or {})
67
+ self.started = True
68
+ elif value.get('type') == 'message_delta':
69
+ self.usage.update(value.get('usage') or {})
70
+ self.delta = 'output_tokens' in (value.get('usage') or {})
71
+ elif value.get('type') == 'message_stop':
72
+ self.stopped = True
73
+
74
+ @property
75
+ def complete(self) -> bool:
76
+ return self.started and self.delta and self.stopped and not self.buffer.strip()
77
+
78
+
79
+ class ChatStreamUsage:
80
+ """Chat Completions chunks; usage arrives in the final chunk requested by stream_options.
81
+
82
+ ``complete`` means the stream ended normally; ``record`` separately checks the usage counters.
83
+ """
84
+ def __init__(self) -> None:
85
+ self.usage: dict[str, Any] | None = None
86
+ self.finished = False
87
+
88
+ def feed(self, chunk: Any) -> None:
89
+ if chunk.get('usage'):
90
+ self.usage = chunk['usage']
91
+ self.finished = self.finished or any(choice.get('finish_reason') for choice in chunk.get('choices') or ())
92
+
93
+ @property
94
+ def complete(self) -> bool:
95
+ return self.finished
96
+
97
+
98
+ class ResponsesStreamUsage:
99
+ """Responses API events; the terminal event carries the whole response usage."""
100
+ def __init__(self) -> None:
101
+ self.usage: dict[str, Any] | None = None
102
+ self.terminal = False
103
+
104
+ def feed(self, event: dict[str, Any]) -> None:
105
+ if event.get('type') in ('response.completed', 'response.incomplete', 'response.failed'):
106
+ self.terminal = event['type'] != 'response.failed'
107
+ self.usage = (event.get('response') or {}).get('usage')
108
+
109
+ @property
110
+ def complete(self) -> bool:
111
+ return self.terminal
112
+
113
+
114
+ # Exactly the counters the server-side store accepts for each protocol.
115
+ USAGE: dict[str, tuple[tuple[str, ...], tuple[str, ...], dict[str, tuple[str, ...]]]] = {
116
+ 'anthropic': (('input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens',
117
+ 'cache_creation', 'server_tool_use', 'service_tier'), ('input_tokens', 'output_tokens'), {}),
118
+ 'openai': (('prompt_tokens', 'completion_tokens', 'prompt_tokens_details', 'completion_tokens_details'),
119
+ ('prompt_tokens', 'completion_tokens'),
120
+ {'prompt_tokens_details': ('cached_tokens', 'audio_tokens'),
121
+ 'completion_tokens_details': ('reasoning_tokens', 'audio_tokens', 'accepted_prediction_tokens',
122
+ 'rejected_prediction_tokens')}),
123
+ 'openai-responses': (('input_tokens', 'output_tokens', 'input_tokens_details', 'output_tokens_details'),
124
+ ('input_tokens', 'output_tokens'),
125
+ {'input_tokens_details': ('cached_tokens',), 'output_tokens_details': ('reasoning_tokens',)}),
126
+ }
127
+
128
+
129
+ def safe_usage(value: Any, protocol: str = 'anthropic') -> dict[str, Any] | None:
130
+ if hasattr(value, 'model_dump'):
131
+ value = value.model_dump(exclude_none=True)
132
+ if not isinstance(value, dict):
133
+ return None
134
+ keys, required, nested = USAGE[protocol]
135
+ if protocol == 'anthropic':
136
+ return {key: value[key] for key in keys if key in value}
137
+
138
+ def count(item: Any) -> bool:
139
+ return type(item) is int and 0 <= item <= 10**15
140
+ if not all(count(value.get(key)) for key in required):
141
+ return None
142
+ usage = {key: value[key] for key in required}
143
+ for key, allowed in nested.items():
144
+ details = {name: item for name, item in (value.get(key) or {}).items() if name in allowed and count(item)}
145
+ if details:
146
+ usage[key] = details
147
+ inputs, outputs = (usage.get(key, {}) for key in nested)
148
+ # Inconsistent provider counters stay unknown instead of becoming a rejected server event.
149
+ if inputs.get('cached_tokens', 0) > usage[required[0]] or outputs.get('reasoning_tokens', 0) > usage[required[1]]:
150
+ return None
151
+ return usage
152
+
153
+
154
+ # Each protocol's own error frame, so its SDK raises instead of reading a truncated success.
155
+ STREAM_ERROR = {
156
+ 'anthropic': b'event: error\ndata: {"type":"error","error":{"type":"api_error","message":"PROXYHUB_STREAM_INCOMPLETE"}}\n\n',
157
+ 'openai': b'data: {"error":{"type":"api_error","code":"PROXYHUB_STREAM_INCOMPLETE","message":"PROXYHUB_STREAM_INCOMPLETE"}}\n\n',
158
+ 'openai-responses': b'event: error\ndata: {"type":"error","code":"PROXYHUB_STREAM_INCOMPLETE","message":"PROXYHUB_STREAM_INCOMPLETE"}\n\n',
159
+ }
160
+ CHAT_FIELDS = {'model', 'messages', 'stream', 'stream_options', 'temperature', 'top_p', 'n', 'stop', 'max_tokens',
161
+ 'max_completion_tokens', 'presence_penalty', 'frequency_penalty', 'logit_bias', 'logprobs',
162
+ 'top_logprobs', 'user', 'tools', 'tool_choice', 'parallel_tool_calls', 'response_format', 'seed',
163
+ 'reasoning_effort', 'functions', 'function_call', 'service_tier'}
164
+ RESPONSES_FIELDS = {'model', 'input', 'instructions', 'include', 'max_output_tokens', 'max_tool_calls', 'metadata',
165
+ 'parallel_tool_calls', 'previous_response_id', 'reasoning', 'store', 'stream', 'temperature',
166
+ 'text', 'tool_choice', 'tools', 'top_p', 'top_logprobs', 'truncation', 'user', 'service_tier',
167
+ 'prompt_cache_key', 'safety_identifier'}
168
+
169
+
170
+ def selected_usage(usage: Any, paths: Any) -> dict[str, Any] | None:
171
+ """Copy only the provider-declared numeric counters from the raw response."""
172
+ if not isinstance(usage, dict):
173
+ return None
174
+ result: dict[str, Any] = {}
175
+ for path in paths:
176
+ value = usage
177
+ for key in path:
178
+ value = value.get(key) if isinstance(value, dict) else None
179
+ if type(value) is not int or not 0 <= value <= 10**15:
180
+ continue
181
+ target = result
182
+ for key in path[:-1]:
183
+ target = target.setdefault(key, {})
184
+ target[path[-1]] = value
185
+ return result or None
186
+
187
+
188
+ class UpstreamChatError(Exception):
189
+ def __init__(self, status: int) -> None:
190
+ self.status = status if 400 <= status <= 599 else 502
191
+
192
+
193
+ def checked_response(response: Any) -> None:
194
+ if not response.is_success:
195
+ raise UpstreamChatError(response.status_code)
196
+
197
+
198
+ async def raw_chat(base_url: str, api_key: str, timeout: float, body: dict[str, Any]) -> Any:
199
+ """Keep provider fields when relaying OpenAI Chat Completions."""
200
+ import httpx
201
+
202
+ async def chunks() -> AsyncIterator[dict[str, Any]]:
203
+ async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
204
+ async with client.stream('POST', base_url + '/chat/completions', json=body,
205
+ headers={'Authorization': 'Bearer ' + api_key}) as response:
206
+ checked_response(response)
207
+ async for line in response.aiter_lines():
208
+ if line.startswith('data:'):
209
+ data = line[5:].strip()
210
+ if data == '[DONE]':
211
+ return
212
+ value = json.loads(data)
213
+ if not isinstance(value, dict) or 'error' in value:
214
+ raise ValueError('PROXYHUB_STREAM_INCOMPLETE')
215
+ yield value
216
+ raise ValueError('PROXYHUB_STREAM_INCOMPLETE')
217
+
218
+ if body.get('stream'):
219
+ return chunks()
220
+ async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
221
+ response = await client.post(base_url + '/chat/completions', json=body,
222
+ headers={'Authorization': 'Bearer ' + api_key})
223
+ checked_response(response)
224
+ value = response.json()
225
+ if not isinstance(value, dict) or 'error' in value:
226
+ raise ValueError('PROXYHUB_UPSTREAM_FAILED')
227
+ return value
228
+
229
+
230
+ def create_app(config: dict[str, Any], spool: Spool, call: Any, *, provider_chat: Any = raw_chat,
231
+ extensions: tuple[Extension, ...] = ()) -> 'FastAPI':
232
+ """``call`` is one LiteLLM entry point for every protocol, or a mapping by protocol."""
233
+ from fastapi import FastAPI, Request
234
+ from fastapi.responses import JSONResponse, StreamingResponse
235
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
236
+ config = dict(config)
237
+ retry = RetryPolicy.from_config(config.get('retry'))
238
+ evidence = Evidence(spool.path, capture=config.get('capture', False),
239
+ max_bytes=config.get('capture_max_bytes', 32 * 1024**2),
240
+ secrets=tuple(config.get(k, '') for k in ('api_key', 'token', 'control_token')))
241
+ calls = call if isinstance(call, dict) else dict.fromkeys(USAGE, call)
242
+ state = dict(accepting=True, inflight=0, judge=False)
243
+
244
+ def emit(event: dict[str, Any]) -> None:
245
+ evidence.append(event)
246
+ for extension in extensions:
247
+ observer = getattr(extension, 'observe', None)
248
+ if observer is not None:
249
+ observer(evidence.clean(event))
250
+
251
+ def authorized(request: 'Request', *, control: bool = False) -> bool:
252
+ supplied = request.headers.get('x-api-key') or request.headers.get('Authorization', '').removeprefix('Bearer ')
253
+ return hmac.compare_digest(supplied, config.get('control_token', config['token']) if control else config['token'])
254
+
255
+ @app.get('/health')
256
+ async def health(request: Request) -> Any:
257
+ if not authorized(request, control=True):
258
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
259
+ return dict(version=config['version'], accepting=state['accepting'], inflight=state['inflight'])
260
+
261
+ @app.get('/metrics')
262
+ async def metrics(request: Request) -> Any:
263
+ if not authorized(request, control=True):
264
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
265
+ return evidence.metrics()
266
+
267
+ @app.post('/drain')
268
+ async def drain(request: Request) -> Any:
269
+ if not authorized(request, control=True):
270
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
271
+ state['accepting'] = False
272
+ end = time.monotonic() + config.get('flush_timeout', 10)
273
+ while state['inflight'] and time.monotonic() < end:
274
+ await asyncio.sleep(.05)
275
+ return dict(complete=state['inflight'] == 0)
276
+
277
+ @app.post('/activate')
278
+ async def activate(request: Request) -> Any:
279
+ if not authorized(request, control=True):
280
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
281
+ if config.get('provider_usage_paths') or state['accepting'] or state['inflight'] or state['judge']:
282
+ return JSONResponse({'error': 'PROXYHUB_PHASE_DENIED'}, 409)
283
+ try:
284
+ raw = await request.body()
285
+ value = json.loads(raw) if len(raw) <= 16384 else None
286
+ if (not isinstance(value, dict) or set(value) != {'model', 'api_base', 'api_key', 'token'}
287
+ or any(not isinstance(v, str) or not v or len(v) > 4096 for v in value.values())
288
+ or value['token'] in (config['token'], config.get('control_token'))):
289
+ raise ValueError
290
+ except Exception:
291
+ return JSONResponse({'error': 'PROXYHUB_REQUEST_INVALID'}, 422)
292
+ # Body reading yields: another activation may have already won.
293
+ if state['accepting'] or state['inflight'] or state['judge']:
294
+ return JSONResponse({'error': 'PROXYHUB_PHASE_DENIED'}, 409)
295
+ # The platform judge is an Anthropic upstream, whatever the answer protocol was.
296
+ config.update(value, protocol='anthropic')
297
+ state.update(accepting=True, judge=True)
298
+ return dict(accepting=True)
299
+
300
+ def valid(body: Any, protocol: str) -> bool:
301
+ if not isinstance(body, dict) or body.get('model') != config['model'] or type(body.get('stream', False)) is not bool:
302
+ return False
303
+ if protocol == 'anthropic':
304
+ allowed = {'model', 'messages', 'max_tokens', 'stream', 'system', 'temperature', 'top_p', 'top_k',
305
+ 'stop_sequences', 'tools', 'tool_choice', 'thinking', 'metadata', 'output_config', 'service_tier'}
306
+ return (not set(body) - allowed and isinstance(body.get('messages'), list)
307
+ and type(body.get('max_tokens')) is int and 0 < body['max_tokens'] <= 1000000)
308
+ if protocol == 'openai':
309
+ options = body.get('stream_options', {})
310
+ return (bool(config.get('provider_usage_paths') and not config.get('native_litellm') or not set(body) - CHAT_FIELDS)
311
+ and isinstance(body.get('messages'), list)
312
+ and isinstance(options, dict) and not set(options) - {'include_usage'}
313
+ and type(options.get('include_usage', False)) is bool
314
+ and all(type(body.get(key, 1)) is int and 0 < body.get(key, 1) <= 1000000
315
+ for key in ('max_tokens', 'max_completion_tokens', 'n')))
316
+ return (not set(body) - RESPONSES_FIELDS and isinstance(body.get('input'), (str, list))
317
+ and type(body.get('max_output_tokens', 1)) is int and 0 < body.get('max_output_tokens', 1) <= 1000000)
318
+
319
+ def chunk_bytes(chunk: dict[str, Any], protocol: str) -> bytes:
320
+ if protocol == 'anthropic':
321
+ return ('event: ' + chunk['type'] + '\ndata: ' + json.dumps(chunk) + '\n\n').encode()
322
+ if protocol == 'openai-responses':
323
+ return ('event: ' + str(chunk.get('type')) + '\ndata: ' + json.dumps(chunk) + '\n\n').encode()
324
+ return ('data: ' + json.dumps(chunk) + '\n\n').encode()
325
+
326
+ async def relay(request: 'Request', protocol: str) -> Any:
327
+ if not authorized(request):
328
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
329
+ if not state['accepting']:
330
+ return JSONResponse({'error': 'PROXYHUB_DRAINING'}, 503)
331
+ try:
332
+ raw = await request.body()
333
+ if len(raw) > 16 * 1024 * 1024:
334
+ raise ValueError
335
+ body = json.loads(raw)
336
+ if not valid(body, protocol):
337
+ raise ValueError
338
+ body.update(config.get('request_patch', {}))
339
+ for extension in extensions:
340
+ body = extension.request(dict(body))
341
+ if not valid(body, protocol):
342
+ raise ValueError
343
+ except Exception:
344
+ return JSONResponse({'error': 'PROXYHUB_REQUEST_INVALID'}, 422)
345
+ if not authorized(request):
346
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
347
+ if not state['accepting']:
348
+ return JSONResponse({'error': 'PROXYHUB_DRAINING'}, 503)
349
+ # Judge activation switches the active upstream protocol; answer routes stop matching it.
350
+ if config.get('protocol', 'anthropic') != protocol:
351
+ return JSONResponse({'error': 'PROXYHUB_PROTOCOL_DENIED'}, 404)
352
+ request_id = call_id = uuid.uuid4().hex
353
+ attempt = 1
354
+ started = time.monotonic()
355
+ end = started + config['timeout']
356
+ evidence.count('calls')
357
+ evidence.count('attempts')
358
+ emit(dict(event='request', request_id=request_id, attempt=attempt, body=body))
359
+ # Committed before dispatch. Unknown results remain visible as pending.
360
+ provider_paths = config.get('provider_usage_paths') if protocol == 'openai' else None
361
+ intent: dict[str, Any] = dict(event_id=call_id + ':start', call_id=call_id, phase='start')
362
+ if provider_paths:
363
+ intent['started_at'] = time.time_ns() // 1000
364
+ spool.append(intent)
365
+ state['inflight'] += 1
366
+
367
+ def record(usage: Any, complete: bool) -> None:
368
+ usage = selected_usage(usage, provider_paths) if provider_paths else safe_usage(usage, protocol)
369
+ # OpenAI-compatible upstreams may omit usage: the call still succeeded, its cost stays unknown.
370
+ known = complete and (usage is not None or protocol == 'anthropic')
371
+ spool.append(dict(event_id=call_id + ':result', call_id=call_id, phase='result',
372
+ status='succeeded' if complete else 'failed', usage=usage, usage_complete=known))
373
+ emit(dict(event='result', request_id=request_id, attempt=attempt, complete=complete, usage=usage))
374
+
375
+ def terminal(complete: bool) -> None:
376
+ evidence.count('succeeded' if complete else 'failed')
377
+ evidence.count('duration_us', int((time.monotonic() - started) * 1000000))
378
+
379
+ streaming = body.get('stream', False)
380
+ # The final usage chunk is requested from the upstream, and forwarded only if the Agent asked.
381
+ visible_usage = (body.get('stream_options') or {}).get('include_usage') is True
382
+ while True:
383
+ try:
384
+ async with asyncio.timeout(max(.001, end - time.monotonic())):
385
+ arguments = body | dict(api_key=config['api_key'], api_base=config['api_base'],
386
+ custom_llm_provider='anthropic' if protocol == 'anthropic' else 'openai',
387
+ max_retries=0, num_retries=0, timeout=max(.001, end - time.monotonic()))
388
+ if protocol == 'openai' and streaming and (not provider_paths or config.get('provider_stream_options', True)):
389
+ arguments['stream_options'] = dict(include_usage=True)
390
+ extra = {key: request.headers[key] for key in ('anthropic-version', 'anthropic-beta') if key in request.headers}
391
+ if extra and protocol == 'anthropic':
392
+ arguments['extra_headers'] = extra
393
+ if provider_paths and not config.get('native_litellm'):
394
+ if streaming and config['provider_stream_options']:
395
+ body = body | {'stream_options': {'include_usage': True}}
396
+ response = await provider_chat(config['api_base'], config['api_key'], config['timeout'], body)
397
+ else:
398
+ response = await calls[protocol](**arguments)
399
+ break
400
+ except asyncio.CancelledError:
401
+ state['inflight'] -= 1
402
+ record(None, False)
403
+ terminal(False)
404
+ raise
405
+ except Exception as exc:
406
+ try:
407
+ record(None, False)
408
+ except Exception:
409
+ state['inflight'] -= 1
410
+ raise
411
+ delay = retry.delay(exc, attempt=attempt, remaining=end - time.monotonic())
412
+ if delay is None or not state['accepting']:
413
+ state['inflight'] -= 1
414
+ terminal(False)
415
+ status = exc.status if isinstance(exc, UpstreamChatError) else 502
416
+ return JSONResponse({'error': 'PROXYHUB_UPSTREAM_FAILED'}, status)
417
+ try:
418
+ await asyncio.sleep(delay)
419
+ except asyncio.CancelledError:
420
+ state['inflight'] -= 1
421
+ terminal(False)
422
+ raise
423
+ if not state['accepting'] or time.monotonic() >= end:
424
+ state['inflight'] -= 1
425
+ terminal(False)
426
+ return JSONResponse({'error': 'PROXYHUB_DRAINING'}, 503)
427
+ attempt += 1
428
+ call_id = uuid.uuid4().hex
429
+ intent = dict(event_id=call_id + ':start', call_id=call_id, phase='start')
430
+ if provider_paths:
431
+ intent['started_at'] = time.time_ns() // 1000
432
+ try:
433
+ spool.append(intent)
434
+ evidence.count('attempts')
435
+ evidence.count('retries')
436
+ emit(dict(event='request', request_id=request_id, attempt=attempt, body=body))
437
+ except Exception:
438
+ state['inflight'] -= 1
439
+ raise
440
+ if not streaming:
441
+ try:
442
+ value = response.model_dump(exclude_none=True) if hasattr(response, 'model_dump') else response
443
+ emit(dict(event='response', request_id=request_id, attempt=attempt, body=value))
444
+ record(value.get('usage'), True)
445
+ terminal(True)
446
+ return JSONResponse(value)
447
+ finally:
448
+ state['inflight'] -= 1
449
+
450
+ async def stream() -> AsyncIterator[bytes]:
451
+ trackers: dict[str, Any] = dict(anthropic=StreamUsage, openai=ChatStreamUsage)
452
+ usage: Any = trackers.get(protocol, ResponsesStreamUsage)()
453
+ ended = False
454
+ try:
455
+ iterator = aiter(response)
456
+ while True:
457
+ remaining = end - time.monotonic()
458
+ if remaining <= 0:
459
+ raise TimeoutError
460
+ try:
461
+ chunk = await asyncio.wait_for(anext(iterator), timeout=remaining)
462
+ except StopAsyncIteration:
463
+ break
464
+ if hasattr(chunk, 'model_dump'):
465
+ chunk = chunk.model_dump(exclude_none=True)
466
+ emit(dict(event='chunk', request_id=request_id, attempt=attempt, body=chunk))
467
+ if protocol != 'anthropic':
468
+ usage.feed(chunk)
469
+ if protocol == 'openai' and not visible_usage and not chunk.get('choices'):
470
+ continue
471
+ chunk = chunk_bytes(chunk, protocol)
472
+ else:
473
+ if isinstance(chunk, dict):
474
+ chunk = chunk_bytes(chunk, protocol)
475
+ elif isinstance(chunk, str):
476
+ chunk = chunk.encode()
477
+ usage.feed(chunk)
478
+ yield chunk
479
+ ended = usage.complete
480
+ if not ended:
481
+ yield STREAM_ERROR[protocol]
482
+ elif protocol == 'openai':
483
+ yield b'data: [DONE]\n\n'
484
+ except (Exception, asyncio.CancelledError):
485
+ yield STREAM_ERROR[protocol]
486
+ finally:
487
+ close = getattr(response, 'aclose', None)
488
+ closed = True
489
+ try:
490
+ if close is not None:
491
+ await asyncio.wait_for(close(), timeout=1)
492
+ except (Exception, asyncio.CancelledError):
493
+ closed = False
494
+ finally:
495
+ try:
496
+ record(usage.usage or None, ended and usage.complete and closed)
497
+ terminal(ended and usage.complete and closed)
498
+ finally:
499
+ state['inflight'] -= 1
500
+ return StreamingResponse(stream(), media_type='text/event-stream')
501
+
502
+ @app.post('/v1/messages')
503
+ async def messages(request: Request) -> Any:
504
+ return await relay(request, 'anthropic')
505
+
506
+ @app.post('/v1/chat/completions')
507
+ async def chat_completions(request: Request) -> Any:
508
+ return await relay(request, 'openai')
509
+
510
+ @app.post('/v1/responses')
511
+ async def responses(request: Request) -> Any:
512
+ return await relay(request, 'openai-responses')
513
+
514
+ @app.get('/v1/models')
515
+ async def models(request: Request) -> Any:
516
+ if not authorized(request):
517
+ return JSONResponse({'error': 'UNAUTHORIZED'}, 401)
518
+ if config.get('protocol', 'anthropic') == 'anthropic':
519
+ return JSONResponse({'error': 'PROXYHUB_PROTOCOL_DENIED'}, 404)
520
+ return dict(object='list', data=[dict(id=config['model'], object='model', created=0, owned_by='envloop')])
521
+ return app
522
+
523
+
524
+ def control(root: Path, operation: str, *args: str) -> dict[str, Any]:
525
+ from urllib.request import Request, urlopen
526
+ config = json.loads((root / 'config.json').read_text())
527
+ if operation in ('health', 'drain', 'activate'):
528
+ request = Request(f"http://127.0.0.1:{config['port']}/" + operation,
529
+ headers={'Authorization': 'Bearer ' + config.get('control_token', config['token']), 'Content-Type': 'application/json'},
530
+ data=(root / 'phase.json').read_bytes() if operation == 'activate' else None,
531
+ method='GET' if operation == 'health' else 'POST')
532
+ with urlopen(request, timeout=config.get('flush_timeout', 10) + 1) as response:
533
+ return json.load(response)
534
+ if operation == 'evidence':
535
+ return Evidence(root / 'spool.sqlite', capture=True).snapshot()
536
+ if operation == 'snapshot':
537
+ return Spool(root / 'spool.sqlite').snapshot()
538
+ if operation == 'ack':
539
+ Spool(root / 'spool.sqlite').ack(int(args[0]))
540
+ return {}
541
+ if operation == 'stop':
542
+ identity = json.loads((root / 'process.json').read_text())
543
+ if type(identity['pid']) is not int or identity['pid'] <= 1:
544
+ raise ValueError('PROXYHUB_PROCESS_INVALID')
545
+ stat = Path('/proc') / str(identity['pid']) / 'stat'
546
+
547
+ def running() -> bool:
548
+ try:
549
+ fields = stat.read_text().rsplit(')', 1)[1].split()
550
+ return fields[19] == identity['start'] and fields[0] not in ('Z', 'X')
551
+ except FileNotFoundError:
552
+ return False
553
+
554
+ if running():
555
+ os.kill(identity['pid'], signal.SIGTERM)
556
+ end = time.monotonic() + min(5, config.get('flush_timeout', 10))
557
+ while running() and time.monotonic() < end:
558
+ time.sleep(.05)
559
+ if running():
560
+ os.kill(identity['pid'], signal.SIGKILL)
561
+ end = time.monotonic() + 1
562
+ while running() and time.monotonic() < end:
563
+ time.sleep(.05)
564
+ if running():
565
+ raise ValueError('PROXYHUB_STOP_UNCONFIRMED')
566
+ (root / 'config.json').unlink(missing_ok=True)
567
+ (root / 'phase.json').unlink(missing_ok=True)
568
+ return {}
569
+ raise ValueError('PROXYHUB_OPERATION_INVALID')
570
+
571
+
572
+ def main() -> None:
573
+ operation, directory, *args = sys.argv[1:]
574
+ root = Path(directory)
575
+ if operation == 'serve':
576
+ config = json.loads((root / 'config.json').read_text())
577
+ if (not isinstance(config.get('token'), str) or not config['token']
578
+ or not isinstance(config.get('control_token'), str) or not config['control_token']
579
+ or hmac.compare_digest(config['token'], config['control_token'])):
580
+ raise ValueError('PROXYHUB_CONTROL_TOKEN_REQUIRED')
581
+ import importlib.metadata
582
+
583
+ import litellm
584
+ import uvicorn
585
+ config = json.loads((root / 'config.json').read_text())
586
+ if importlib.metadata.version('litellm') != config['version']:
587
+ raise ValueError('PROXYHUB_VERSION_MISMATCH')
588
+ litellm.telemetry = False
589
+ litellm.turn_off_message_logging = True
590
+ litellm.num_retries = 0
591
+ calls = {'anthropic': litellm.anthropic.acreate, 'openai': litellm.acompletion,
592
+ 'openai-responses': litellm.aresponses}
593
+ uvicorn.run(create_app(config, Spool(root / 'spool.sqlite'), calls),
594
+ host='127.0.0.1', port=config['port'], access_log=False, log_level='critical')
595
+ return
596
+ if operation == 'start':
597
+ os.umask(0o077)
598
+ config = json.loads((root / 'config.json').read_text())
599
+ env = {key: value for key, value in os.environ.items() if key in ('PATH', 'LANG', 'LC_ALL')}
600
+ env.update(LITELLM_LOCAL_MODEL_COST_MAP='True', DO_NOT_TRACK='1')
601
+ with open(os.devnull, 'wb') as sink:
602
+ process = subprocess.Popen([sys.executable, sys.argv[0], 'serve', str(root)],
603
+ env=env, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink, start_new_session=True)
604
+ stat = (Path('/proc') / str(process.pid) / 'stat').read_text().rsplit(')', 1)[1].split()[19]
605
+ (root / 'process.json').write_text(json.dumps(dict(pid=process.pid, start=stat)))
606
+ end = time.monotonic() + config['start_timeout']
607
+ while time.monotonic() < end and process.poll() is None:
608
+ try:
609
+ result = control(root, 'health')
610
+ if result['version'] == config['version'] and result['accepting']:
611
+ print(json.dumps(result))
612
+ return
613
+ except Exception:
614
+ pass
615
+ time.sleep(.1)
616
+ process.terminate()
617
+ process.wait(timeout=5)
618
+ raise ValueError('PROXYHUB_NOT_READY')
619
+ print(json.dumps(control(root, operation, *args)))
620
+
621
+
622
+ if __name__ == '__main__':
623
+ try:
624
+ main()
625
+ except Exception:
626
+ print('PROXYHUB_OPERATION_FAILED', file=sys.stderr)
627
+ sys.exit(1)
@@ -0,0 +1,141 @@
1
+ """Bounded request policy and private evidence, independent of platform services."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import math
6
+ import os
7
+ import sqlite3
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from email.utils import parsedate_to_datetime
11
+ from pathlib import Path
12
+ from time import time
13
+ from typing import Any, Protocol
14
+
15
+
16
+ class Extension(Protocol):
17
+ def request(self, body: dict[str, Any]) -> dict[str, Any]: ...
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class RetryPolicy:
22
+ max_attempts: int = 1
23
+ base_delay: float = 0.25
24
+ max_delay: float = 5
25
+ statuses: tuple[int, ...] = (408, 429, 500, 502, 503, 504)
26
+
27
+ @classmethod
28
+ def from_config(cls, value: Any = None) -> RetryPolicy:
29
+ if value is None:
30
+ return cls()
31
+ if not isinstance(value, dict) or set(value) - {'max_attempts', 'base_delay', 'max_delay', 'statuses'}:
32
+ raise ValueError('PROXYHUB_RETRY_INVALID')
33
+ policy = cls(**value)
34
+ if (type(policy.max_attempts) is not int or not 1 <= policy.max_attempts <= 10
35
+ or any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 30
36
+ for v in (policy.base_delay, policy.max_delay))
37
+ or policy.max_delay < policy.base_delay
38
+ or not isinstance(policy.statuses, (tuple, list))
39
+ or any(type(v) is not int or v not in cls.statuses for v in policy.statuses)):
40
+ raise ValueError('PROXYHUB_RETRY_INVALID')
41
+ return policy
42
+
43
+ def delay(self, error: Exception, *, attempt: int, remaining: float) -> float | None:
44
+ status = getattr(error, 'status_code', getattr(error, 'status', None))
45
+ # Unknown outcomes are not silently classified as retryable network errors.
46
+ if attempt >= self.max_attempts or status not in self.statuses:
47
+ return None
48
+ delay = min(self.max_delay, self.base_delay * 2 ** (attempt - 1))
49
+ headers = getattr(getattr(error, 'response', None), 'headers', {})
50
+ value = headers.get('retry-after') if isinstance(headers, Mapping) else None
51
+ if value is not None:
52
+ try:
53
+ requested = float(value)
54
+ except (TypeError, ValueError):
55
+ try:
56
+ requested = parsedate_to_datetime(str(value)).timestamp() - time()
57
+ except (TypeError, ValueError, OverflowError):
58
+ return None
59
+ if not math.isfinite(requested) or requested > self.max_delay:
60
+ return None
61
+ delay = max(delay, requested, 0)
62
+ return delay if delay < remaining else None
63
+
64
+
65
+ SENSITIVE = frozenset({'api_key', 'authorization', 'x-api-key', 'token', 'control_token',
66
+ 'access_token', 'headers', 'extra_headers', 'api_base', 'base_url'})
67
+
68
+
69
+ class Evidence:
70
+ """A bounded private trace and durable low-cardinality counters, separate from usage."""
71
+
72
+ def __init__(self, path: str | Path, *, capture: bool = False, max_bytes: int = 32 * 1024**2,
73
+ secrets: tuple[str, ...] = ()) -> None:
74
+ if type(capture) is not bool or type(max_bytes) is not int or not 1 <= max_bytes <= 64 * 1024**2:
75
+ raise ValueError('PROXYHUB_CAPTURE_INVALID')
76
+ self.path, self.capture, self.max_bytes = str(path), capture, max_bytes
77
+ self.secrets = tuple(value for value in secrets if value)
78
+ with sqlite3.connect(self.path) as db:
79
+ db.execute('CREATE TABLE IF NOT EXISTS trace(seq INTEGER PRIMARY KEY, payload TEXT NOT NULL)')
80
+ db.execute('CREATE TABLE IF NOT EXISTS metrics(name TEXT PRIMARY KEY, value INTEGER NOT NULL)')
81
+ db.execute('CREATE TABLE IF NOT EXISTS evidence_state(id INTEGER PRIMARY KEY CHECK(id=1), complete INTEGER NOT NULL)')
82
+ db.execute('INSERT OR IGNORE INTO evidence_state VALUES(1,1)')
83
+ db.execute('CREATE TABLE IF NOT EXISTS evidence_budget(id INTEGER PRIMARY KEY CHECK(id=1), count INTEGER, bytes INTEGER)')
84
+ db.execute('INSERT OR IGNORE INTO evidence_budget SELECT 1,COUNT(*),COALESCE(SUM(length(CAST(payload AS BLOB))),0) FROM trace')
85
+
86
+ def clean(self, value: Any) -> Any:
87
+ if isinstance(value, dict):
88
+ return {str(k): self.clean(v) for k, v in value.items() if str(k).lower() not in SENSITIVE}
89
+ if isinstance(value, (list, tuple)):
90
+ return [self.clean(item) for item in value]
91
+ if isinstance(value, bytes):
92
+ value = value.decode('utf-8', errors='replace')
93
+ if isinstance(value, str):
94
+ for secret in self.secrets:
95
+ value = value.replace(secret, '[REDACTED]')
96
+ return value
97
+
98
+ def append(self, value: dict[str, Any]) -> None:
99
+ if not self.capture:
100
+ return
101
+ try:
102
+ payload = json.dumps(self.clean(value), ensure_ascii=False, allow_nan=False)
103
+ with sqlite3.connect(self.path, timeout=10) as db:
104
+ db.execute('BEGIN IMMEDIATE')
105
+ count, size = db.execute('SELECT count,bytes FROM evidence_budget WHERE id=1').fetchone()
106
+ complete = db.execute('SELECT complete FROM evidence_state WHERE id=1').fetchone()[0]
107
+ if not complete or count >= 20000 or size + len(payload.encode()) > self.max_bytes:
108
+ db.execute('UPDATE evidence_state SET complete=0 WHERE id=1')
109
+ return
110
+ db.execute('INSERT INTO trace(payload) VALUES(?)', (payload,))
111
+ db.execute('UPDATE evidence_budget SET count=count+1,bytes=bytes+? WHERE id=1', (len(payload.encode()),))
112
+ except Exception:
113
+ self.mark_incomplete()
114
+ raise
115
+
116
+ def mark_incomplete(self) -> None:
117
+ # A separate sticky marker survives temporary SQLite failure. If both writes fail,
118
+ # the error propagates and the collector must fail rather than claim completion.
119
+ marker = Path(self.path + '.incomplete')
120
+ descriptor = os.open(marker, os.O_WRONLY | os.O_CREAT, 0o600)
121
+ os.close(descriptor)
122
+
123
+ def count(self, name: str, value: int = 1) -> None:
124
+ if name not in {'calls', 'attempts', 'retries', 'succeeded', 'failed', 'duration_us'}:
125
+ raise ValueError('PROXYHUB_METRIC_INVALID')
126
+ with sqlite3.connect(self.path, timeout=10) as db:
127
+ db.execute('INSERT INTO metrics VALUES(?,?) ON CONFLICT(name) DO UPDATE SET value=value+excluded.value',
128
+ (name, value))
129
+
130
+ def metrics(self) -> dict[str, int]:
131
+ result = dict.fromkeys(('calls', 'attempts', 'retries', 'succeeded', 'failed', 'duration_us'), 0)
132
+ with sqlite3.connect(self.path, timeout=10) as db:
133
+ result.update(db.execute('SELECT name,value FROM metrics').fetchall())
134
+ return result
135
+
136
+ def snapshot(self) -> dict[str, Any]:
137
+ with sqlite3.connect(self.path, timeout=10) as db:
138
+ complete = bool(db.execute('SELECT complete FROM evidence_state WHERE id=1').fetchone()[0]) and not Path(self.path + '.incomplete').exists()
139
+ events = [json.loads(row[0]) for row in db.execute('SELECT payload FROM trace ORDER BY seq')]
140
+ return {'schema': 'envloop.proxyhub-trajectory/v1', 'complete': complete,
141
+ 'events': events, 'metrics': self.metrics()}
@@ -0,0 +1,66 @@
1
+ """Service launch policy; orchestrators retain resource and sidecar ownership."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from dataclasses import dataclass
6
+ from pathlib import PurePosixPath
7
+ from typing import Any
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class ServicePolicy:
12
+ mode: str = 'process'
13
+ image: str = ''
14
+ port: int = 4000
15
+ network: str = ''
16
+ name: str = ''
17
+
18
+ def __post_init__(self) -> None:
19
+ if self.mode not in {'process', 'docker', 'sidecar'}:
20
+ raise ValueError('PROXYHUB_MODE_UNSUPPORTED')
21
+ if type(self.port) is not int or not 1024 <= self.port <= 65535:
22
+ raise ValueError('PROXYHUB_PORT_INVALID')
23
+ if self.mode != 'process' and not re.fullmatch(r'[A-Za-z0-9./:_-]+@sha256:[0-9a-f]{64}', self.image):
24
+ raise ValueError('PROXYHUB_IMAGE_INVALID')
25
+ if self.mode == 'docker' and (not re.fullmatch(r'container:[A-Za-z0-9][A-Za-z0-9_.-]{0,127}', self.network)
26
+ or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,63}', self.name)):
27
+ raise ValueError('PROXYHUB_DOCKER_OWNER_INVALID')
28
+
29
+ def require(self, capabilities: set[str]) -> None:
30
+ if self.mode not in capabilities:
31
+ raise ValueError('PROXYHUB_MODE_UNSUPPORTED')
32
+
33
+ @staticmethod
34
+ def _paths(python: str, root: str) -> None:
35
+ for value in (python, root):
36
+ if (not re.fullmatch(r'/[A-Za-z0-9_./-]+', value) or str(PurePosixPath(value)) != value
37
+ or '..' in PurePosixPath(value).parts):
38
+ raise ValueError('PROXYHUB_PATH_INVALID')
39
+
40
+ def container(self, python: str, root: str) -> dict[str, Any]:
41
+ self._paths(python, root)
42
+ if self.mode == 'process':
43
+ raise ValueError('PROXYHUB_IMAGE_REQUIRED')
44
+ return {'image': self.image, 'command': [python, root + '/guest.py', 'serve', root],
45
+ 'mounts': [{'source': root, 'target': root, 'read_only': False}],
46
+ 'publish_ports': False, 'readiness': {'path': '/health', 'port': self.port,
47
+ 'authentication': 'control_token'}}
48
+
49
+ def command(self, python: str, root: str, *, operation: str, resource_id: str = '') -> tuple[str, ...]:
50
+ self._paths(python, root)
51
+ if operation not in {'start', 'stop', 'health', 'drain', 'activate', 'snapshot', 'ack', 'evidence'}:
52
+ raise ValueError('PROXYHUB_OPERATION_INVALID')
53
+ if self.mode == 'sidecar':
54
+ raise ValueError('PROXYHUB_SIDECAR_OWNER_REQUIRED')
55
+ if self.mode == 'process':
56
+ return (python, root + '/guest.py', operation, root)
57
+ if operation == 'start':
58
+ return ('docker', 'run', '--detach', '--name', self.name, '--network', self.network,
59
+ '--mount', f'type=bind,source={root},target={root}', '--cap-drop=ALL',
60
+ '--security-opt=no-new-privileges', self.image,
61
+ python, root + '/guest.py', 'serve', root)
62
+ if not re.fullmatch(r'[0-9a-f]{64}', resource_id):
63
+ raise ValueError('PROXYHUB_RESOURCE_ID_REQUIRED')
64
+ if operation == 'stop':
65
+ return ('docker', 'rm', '--force', resource_id)
66
+ return ('docker', 'exec', resource_id, python, root + '/guest.py', operation, root)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "envloop-envhub"
7
- version = "2.2.0"
7
+ version = "2.3.1"
8
8
  description = "Dependency-free ANS protocol and verified downloads"
9
9
  readme = "README.pypi.md"
10
10
  license-files = ["NOTICE"]
@@ -25,6 +25,11 @@ path = "hatch_build.py"
25
25
 
26
26
  [tool.hatch.build.targets.wheel]
27
27
  only-include = [
28
+ "envhub/proxyhub/__init__.py",
29
+ "envhub/proxyhub/guest.py",
30
+ "envhub/proxyhub/policy.py",
31
+ "envhub/proxyhub/services.py",
32
+ "envhub/proxyhub/bundle.py",
28
33
  "envhub/checkpoints/__init__.py",
29
34
  "envhub/checkpoints/source.py",
30
35
  "envhub/__init__.py",
@@ -61,6 +66,11 @@ only-include = [
61
66
 
62
67
  [tool.hatch.build.targets.sdist]
63
68
  only-include = [
69
+ "envhub/proxyhub/__init__.py",
70
+ "envhub/proxyhub/guest.py",
71
+ "envhub/proxyhub/policy.py",
72
+ "envhub/proxyhub/services.py",
73
+ "envhub/proxyhub/bundle.py",
64
74
  "envhub/checkpoints/__init__.py",
65
75
  "envhub/checkpoints/source.py",
66
76
  "envhub/__init__.py",
File without changes