Draft
[WIP]feat(gateway): shard personal Cron across fixed workers #493
[WIP]feat(gateway): shard personal Cron across fixed workers #493
Draft
yutaoJustinBieber1223Add on 2 days ago
Total: 84 files changed+19705-118
Magent_gateway/app_gateway.py+75-6File content is under review, please try again later
Aagent_gateway/application/cron_preflight.py+102-0File content is under review, please try again later
Magent_gateway/application/inbound.py+27-9File content is under review, please try again later
Aagent_gateway/application/multiprocess.py+171-0File content is under review, please try again later
Magent_gateway/application/tui_acp.py+16-2File content is under review, please try again later
Aagent_gateway/application/worker_cron.py+711-0File content is under review, please try again later
Aagent_gateway/application/worker_cron_commands.py+841-0File content is under review, please try again later
Aagent_gateway/application/worker_cron_ingress.py+119-0File content is under review, please try again later
Aagent_gateway/application/worker_cron_models.py+232-0File content is under review, please try again later
Aagent_gateway/application/worker_data.py+278-0File content is under review, please try again later
Aagent_gateway/application/worker_group.py+208-0File content is under review, please try again later
@@ -0,0 +1,150 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+"""Bound actual Control blocking work, including work outliving its caller."""
3+ 
4+from __future__ import annotations
5+ 
6+import asyncio
7+from collections.abc import Callable
8+from concurrent.futures import Future, ThreadPoolExecutor
9+import math
10+import threading
11+from typing import Any, TypeVar
12+ 
13+from agent_gateway.processes.control_service import ControlServiceBusy, ControlServiceError
14+ 
15+_Result = TypeVar('_Result')
16+ 
17+ 
18+def _consume_result(future: asyncio.Future[Any]) -> None:
19+ """Retrieve abandoned exceptions without logging their possibly secret text."""
20+ if not future.cancelled():
21+ future.exception()
22+ 
23+ 
24+class ControlBlockingWork:
25+ """Same-loop submissions to a private pool with no admission waiting queue.
26+ 
27+ Caller cancellation never returns an occupied slot. Only completion of the
28+ concurrent future does so. Construction starts no threads; the owner must
29+ call ``stop`` before closing its event loop. A timed-out stop leaves actual
30+ work observable through ``pending_count`` and does not claim to kill it.
31+ """
32+ 
33+ def __init__(self, limit: int = 4) -> None:
34+ if type(limit) is not int or limit <= 0:
35+ raise ValueError('limit must be a positive integer')
36+ self._limit = limit
37+ self._executor = ThreadPoolExecutor(max_workers=limit, thread_name_prefix='control-blocking')
38+ self._lock = threading.Lock()
39+ self._pending: set[Future[Any]] = set()
40+ self._count = 0
41+ self._loop: asyncio.AbstractEventLoop | None = None
42+ self._idle = asyncio.Event()
43+ self._idle.set()
44+ self._closed = False
45+ self._stop_task: asyncio.Task[None] | None = None
46+ 
47+ @property
48+ def pending_count(self) -> int:
49+ """Number of actual occupied slots, even after a caller or loop exits."""
50+ with self._lock:
51+ return self._count
52+ 
53+ def _owner_loop(self) -> asyncio.AbstractEventLoop:
54+ try:
55+ loop = asyncio.get_running_loop()
56+ except RuntimeError:
57+ raise ControlServiceError() from None
58+ if self._loop is None:
59+ self._loop = loop
60+ elif self._loop is not loop:
61+ raise ControlServiceError()
62+ return loop
63+ 
64+ def submit(self, fn: Callable[..., _Result], *args: Any) -> Future[_Result]:
65+ """Reserve a real slot synchronously or fail immediately without queuing."""
66+ self._owner_loop()
67+ if self._closed:
68+ raise ControlServiceError()
69+ with self._lock:
70+ if self._count >= self._limit:
71+ raise ControlServiceBusy()
72+ self._count += 1
73+ self._idle.clear()
74+ try:
75+ future = self._executor.submit(fn, *args)
76+ except Exception:
77+ with self._lock:
78+ self._count -= 1
79+ self._notify_completion()
80+ raise ControlServiceError() from None
81+ with self._lock:
82+ self._pending.add(future)
83+ # Register outside the lock: add_done_callback may execute immediately.
84+ future.add_done_callback(self._work_finished)
85+ return future
86+ 
87+ async def run(self, fn: Callable[..., _Result], *args: Any) -> _Result:
88+ """Await a submitted call without cancelling its actual work on timeout."""
89+ future = asyncio.wrap_future(self.submit(fn, *args))
90+ future.add_done_callback(_consume_result)
91+ return await asyncio.shield(future)
92+ 
93+ def _work_finished(self, future: Future[Any]) -> None:
94+ # This can run on a pool thread, including after the owner loop closes.
95+ with self._lock:
96+ self._pending.remove(future)
97+ self._count -= 1
98+ loop = self._loop
99+ if loop is not None:
100+ try:
101+ loop.call_soon_threadsafe(self._notify_completion)
102+ except RuntimeError:
103+ # A closed loop cannot be notified; actual-work tracking is done.
104+ pass
105+ 
106+ def _notify_completion(self) -> None:
107+ if self.pending_count == 0:
108+ self._idle.set()
109+ 
110+ async def _wait_for_work(self, timeout: float) -> None:
111+ try:
112+ async with asyncio.timeout(timeout):
113+ while self.pending_count:
114+ await self._idle.wait()
115+ except TimeoutError:
116+ if self.pending_count:
117+ raise ControlServiceError() from None
118+ 
119+ async def stop(self, timeout: float = 1.0) -> None:
120+ """Reject new calls and finish owned, bounded cleanup despite cancellation.
121+ 
122+ Concurrent stop callers share the current cleanup deadline. After a
123+ timeout a later stop can wait again, but submissions remain closed.
124+ Residual work raises only a fixed error and remains counted until done.
125+ """
126+ if type(timeout) not in {int, float} or not math.isfinite(timeout) or timeout < 0:
127+ raise ValueError('timeout must be a non-negative finite number')
128+ loop = self._owner_loop()
129+ if not self._closed:
130+ self._closed = True
131+ self._executor.shutdown(wait=False, cancel_futures=False)
132+ if self._stop_task is None or self._stop_task.done():
133+ self._stop_task = loop.create_task(self._wait_for_work(float(timeout)))
134+ self._stop_task.add_done_callback(_consume_result)
135+ task = self._stop_task
136+ cancelled = False
137+ while True:
138+ try:
139+ await asyncio.shield(task)
140+ break
141+ except asyncio.CancelledError:
142+ if task.cancelled():
143+ raise
144+ cancelled = True
145+ except ControlServiceError:
146+ if cancelled:
147+ raise asyncio.CancelledError from None
148+ raise
149+ if cancelled:
150+ raise asyncio.CancelledError
Aagent_gateway/auth/control_credentials.py+540-0File content is under review, please try again later
Aagent_gateway/auth/control_model_catalog.py+217-0File content is under review, please try again later
@@ -3,7 +3,35 @@
3from __future__ import annotations3from __future__ import annotations
4 4 
5from dataclasses import dataclass, field5from dataclasses import dataclass, field
6-from typing import Protocol6+from abc import ABC, abstractmethod
7+from typing import TYPE_CHECKING, Protocol
8+ 
9+if TYPE_CHECKING:
10+ from agent_gateway.auth.worker_credential_runtime import WorkerCredentialLease
11+ 
12+ 
13+_CREDENTIAL_ACCESS_ERROR_REASONS = frozenset(
14+ {"unavailable", "invalid", "protocol", "not_enabled"}
15+)
16+ 
17+ 
18+class CredentialAccessError(Exception):
19+ """A remote credential or binding access failure without secret details."""
20+ 
21+ def __init__(self, reason: str = "unavailable") -> None:
22+ if reason not in _CREDENTIAL_ACCESS_ERROR_REASONS:
23+ raise ValueError("Unsupported credential failure reason")
24+ self.reason = reason
25+ super().__init__("Remote credential access failed")
26+ 
27+ 
28+class OwnsResolveDeadline(ABC):
29+ """Bindings that enforce their own typed resolve deadline."""
30+ 
31+ @property
32+ @abstractmethod
33+ def resolve_deadline_s(self) -> float:
34+ """Return the port-owned resolve deadline in seconds."""
7 35 
8 36 
9LOGIN_REFRESH_WAIT_S = 20.037LOGIN_REFRESH_WAIT_S = 20.0
@@ -16,9 +44,42 @@ class ModelCredential:
16 api_base: str44 api_base: str
17 api_key: str = field(repr=False)45 api_key: str = field(repr=False)
18 credential_ref: str46 credential_ref: str
47+ lease: "WorkerCredentialLease | None" = field(default=None, repr=False, compare=False)
19 48 
20- def to_params(self) -> dict[str, str]:49+ def to_params(self) -> "CredentialParams":
21- return {'api_base': self.api_base, 'api_key': self.api_key, 'credential_ref': self.credential_ref}50+ return CredentialParams(
51+ api_base=self.api_base,
52+ api_key=self.api_key,
53+ credential_ref=self.credential_ref,
54+ credential_lease=self.lease,
55+ )
56+ 
57+ 
58+class CredentialParams(dict[str, str]):
59+ """Wire-shaped credential params with a non-serialized request lease."""
60+ 
61+ def __init__(
62+ self,
63+ *,
64+ api_base: str,
65+ api_key: str,
66+ credential_ref: str,
67+ credential_lease: "WorkerCredentialLease | None" = None,
68+ ) -> None:
69+ super().__init__({
70+ 'api_base': api_base,
71+ 'api_key': api_key,
72+ 'credential_ref': credential_ref,
73+ })
74+ self.credential_lease = credential_lease
75+ 
76+ def copy(self) -> "CredentialParams":
77+ return CredentialParams(
78+ api_base=self['api_base'],
79+ api_key=self['api_key'],
80+ credential_ref=self['credential_ref'],
81+ credential_lease=self.credential_lease,
82+ )
22 83 
23 84 
24@dataclass(frozen=True)85@dataclass(frozen=True)
@@ -40,6 +101,16 @@ class CredentialUpdate:
40 return {'credential_ref': self.credential_ref, 'api_key': self.api_key}101 return {'credential_ref': self.credential_ref, 'api_key': self.api_key}
41 102 
42 103 
104+@dataclass(frozen=True)
105+class CredentialRefresh:
106+ """A Control-authorized credential update for one explicit target."""
107+ 
108+ operation_id: str
109+ server_id: str
110+ ref_revision: int
111+ update: CredentialUpdate
112+ 
113+ 
43class CredentialAccess(Protocol):114class CredentialAccess(Protocol):
44 """Only return the credential information needed by this consumer."""115 """Only return the credential information needed by this consumer."""
45 116 
@@ -47,6 +118,10 @@ class CredentialAccess(Protocol):
47 118 
48 async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: ...119 async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: ...
49 120 
121+ async def credential_refresh_for_ref(
122+ self, credential_ref: str, server_id: str
123+ ) -> CredentialRefresh | None: ...
124+ 
50 async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: ...125 async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: ...
51 126 
52 async def model_auth_for_ref(self, credential_ref: str) -> ModelCredential | None: ...127 async def model_auth_for_ref(self, credential_ref: str) -> ModelCredential | None: ...
Aagent_gateway/auth/credential_issuance.py+228-0File content is under review, please try again later
@@ -4,28 +4,93 @@ from __future__ import annotations
4 4 
5import asyncio5import asyncio
6from collections.abc import Callable6from collections.abc import Callable
7+from concurrent.futures import Future
8+from dataclasses import dataclass, replace
7import logging9import logging
8-from typing import TYPE_CHECKING10+from typing import Any, TYPE_CHECKING
9 11 
10from agent_gateway.auth.credential_access import CredentialUpdate, ModelCredential, LOGIN_REFRESH_WAIT_S12from agent_gateway.auth.credential_access import CredentialUpdate, ModelCredential, LOGIN_REFRESH_WAIT_S
11 13 
12if TYPE_CHECKING:14if TYPE_CHECKING:
13 from agent_gateway.auth.service import AuthService15 from agent_gateway.auth.service import AuthService
16+ from agent_gateway.auth.control_blocking_work import ControlBlockingWork
17+ from agent_gateway.auth.session_store import AuthSessionStore
14 18 
15logger = logging.getLogger(__name__)19logger = logging.getLogger(__name__)
16_LOGIN_REFRESH_WAIT_S = LOGIN_REFRESH_WAIT_S20_LOGIN_REFRESH_WAIT_S = LOGIN_REFRESH_WAIT_S
17 21 
18 22 
23+def _consume_refresh_result(future: asyncio.Future) -> None:
24+ """Retrieve late failures without logging credential-bearing exceptions."""
25+ if not future.cancelled():
26+ future.exception()
27+ 
28+ 
29+def _finish_initial(future: asyncio.Future, value: Any) -> None:
30+ if not future.done():
31+ future.set_result(value)
32+ 
33+ 
34+def _fail_initial(future: asyncio.Future, error: BaseException) -> None:
35+ if future.cancelled():
36+ return
37+ if future.done():
38+ _consume_refresh_result(future)
39+ return
40+ future.set_exception(error)
41+ 
42+ 
43+@dataclass(frozen=True)
44+class LocalCredentialSnapshot:
45+ """Immutable identity facts for a synchronous Control commit."""
46+ 
47+ store: AuthSessionStore
48+ session_id: str
49+ user_id: str
50+ created_at: float
51+ credential_ref: str
52+ 
53+ 
54+@dataclass(frozen=True)
55+class LocalCredentialResult:
56+ """A request-scoped credential result and its immutable identity snapshot."""
57+ 
58+ credential: ModelCredential | None
59+ snapshot: LocalCredentialSnapshot | None
60+ model_required: bool
61+ expired: bool = False
62+ model_names: tuple[str, ...] = ()
63+ 
64+ 
65+@dataclass(frozen=True)
66+class _RequestWork:
67+ future: Future
68+ initial: asyncio.Future
69+ 
70+ 
19class LocalCredentialAccess:71class LocalCredentialAccess:
20 """Lazily use the original service; construction has no login side effects."""72 """Lazily use the original service; construction has no login side effects."""
21 73 
22- def __init__(self, auth_service_provider: Callable[[], AuthService]) -> None:74+ def __init__(
75+ self, auth_service_provider: Callable[[], AuthService], *,
76+ blocking_work: ControlBlockingWork | None = None,
77+ ) -> None:
23 self._auth_service_provider = auth_service_provider78 self._auth_service_provider = auth_service_provider
79+ self._blocking_work = blocking_work
80+ self._refreshing: dict[str, _RequestWork] = {}
24 81 
25 async def request_model_auth(self, auth_session: str | None, model_name: str) -> ModelCredential | None:82 async def request_model_auth(self, auth_session: str | None, model_name: str) -> ModelCredential | None:
83+ result = await self.request_model_auth_with_snapshot(auth_session, model_name)
84+ return None if result is None else result.credential
85+ 
86+ async def request_model_auth_with_snapshot(
87+ self, auth_session: str | None, model_name: str,
88+ ) -> LocalCredentialResult | None:
26 from agent_gateway.auth.passthrough import _build_model_auth, _is_login_model, expired_login_session89 from agent_gateway.auth.passthrough import _build_model_auth, _is_login_model, expired_login_session
27 90 
28 model_name = model_name.strip()91 model_name = model_name.strip()
92+ if self._blocking_work is not None:
93+ return await self._bounded_request_model_auth(auth_session, model_name)
29 if not auth_session or not model_name:94 if not auth_session or not model_name:
30 return None95 return None
31 service = self._auth_service_provider()96 service = self._auth_service_provider()
@@ -39,13 +104,150 @@ class LocalCredentialAccess:
39 )104 )
40 except asyncio.TimeoutError:105 except asyncio.TimeoutError:
41 logger.warning('[ModelAuth] Login credential refresh timed out; checking current credentials')106 logger.warning('[ModelAuth] Login credential refresh timed out; checking current credentials')
42- except Exception: # A failed refresh must not prevent the original request.107+ except Exception:
43 logger.debug('[ModelAuth] Login credential refresh failed', exc_info=True)108 logger.debug('[ModelAuth] Login credential refresh failed', exc_info=True)
44 auth = _build_model_auth(model_name, auth_session, service=service)109 auth = _build_model_auth(model_name, auth_session, service=service)
45 if auth is None:110 if auth is None:
46- return None111+ return LocalCredentialResult(None, None, True)
47- return ModelCredential(112+ current = service.resolve_session(auth_session)
48- api_base=auth['api_base'], api_key=auth['api_key'], credential_ref=auth['credential_ref'],113+ if current is None:
114+ return LocalCredentialResult(None, None, True)
115+ snapshot = self._snapshot(service, current)
116+ return LocalCredentialResult(
117+ ModelCredential(
118+ api_base=auth['api_base'],
119+ api_key=auth['api_key'],
120+ credential_ref=auth['credential_ref'],
121+ ),
122+ snapshot,
123+ True,
124+ current.credential.is_expired(),
125+ )
126+ 
127+ async def _bounded_request_model_auth(
128+ self, auth_session: str | None, model_name: str,
129+ ) -> LocalCredentialResult | None:
130+ """Keep account refresh bounded while each request judges its own model."""
131+ from agent_gateway.auth.apig import resolve_apig_config
132+ from agent_gateway.auth.login_credentials import bare_model_name
133+ from agent_gateway.auth.model_catalog import get_models
134+ from agent_gateway.auth.service import REFRESH_AHEAD_S
135+ 
136+ if not auth_session or not model_name:
137+ return LocalCredentialResult(None, None, False)
138+ service = self._auth_service_provider()
139+ work = self._refreshing.get(auth_session)
140+ if work is None or work.future.done():
141+ loop = asyncio.get_running_loop()
142+ initial = loop.create_future()
143+ initial.add_done_callback(_consume_refresh_result)
144+ 
145+ def load_and_refresh():
146+ try:
147+ models = get_models(auth_session, allow_refresh=False, service=service)
148+ model_names = tuple(model.model_name for model in models)
149+ current = service.resolve_session(auth_session)
150+ config = resolve_apig_config(allow_refresh=False)
151+ snapshot = None if current is None else self._snapshot(service, current)
152+ if current is None or config is None:
153+ result = LocalCredentialResult(
154+ None, snapshot, False, False, model_names,
155+ )
156+ else:
157+ result = LocalCredentialResult(
158+ ModelCredential(
159+ api_base=config.invoke_base_url,
160+ api_key=current.credential.id_token,
161+ credential_ref=snapshot.credential_ref,
162+ ),
163+ snapshot,
164+ False,
165+ current.credential.is_expired(),
166+ model_names,
167+ )
168+ loop.call_soon_threadsafe(_finish_initial, initial, result)
169+ if current is None or not current.credential.expires_within(REFRESH_AHEAD_S):
170+ return result
171+ try:
172+ service.try_refresh(current)
173+ except Exception:
174+ logger.debug('[ModelAuth] Control credential refresh failed', exc_info=True)
175+ current = service.resolve_session(auth_session)
176+ config = resolve_apig_config(allow_refresh=False)
177+ if current is None or config is None:
178+ return LocalCredentialResult(
179+ None, result.snapshot, False, True, model_names,
180+ )
181+ snapshot = self._snapshot(service, current)
182+ return LocalCredentialResult(
183+ ModelCredential(
184+ api_base=config.invoke_base_url,
185+ api_key=current.credential.id_token,
186+ credential_ref=snapshot.credential_ref,
187+ ),
188+ snapshot,
189+ False,
190+ current.credential.is_expired(),
191+ model_names,
192+ )
193+ except BaseException as error:
194+ loop.call_soon_threadsafe(_fail_initial, initial, error)
195+ raise
196+ 
197+ future = self._blocking_work.submit(load_and_refresh)
198+ future.add_done_callback(_consume_refresh_result)
199+ work = _RequestWork(future, initial)
200+ self._refreshing[auth_session] = work
201+ 
202+ def clear(completed: Future) -> None:
203+ def remove() -> None:
204+ if self._refreshing.get(auth_session) is work:
205+ self._refreshing.pop(auth_session, None)
206+ try:
207+ loop.call_soon_threadsafe(remove)
208+ except RuntimeError:
209+ pass
210+ 
211+ future.add_done_callback(clear)
212+ 
213+ initial_result: LocalCredentialResult = await asyncio.shield(work.initial)
214+ model_required = (
215+ model_name in initial_result.model_names
216+ or bare_model_name(model_name) in initial_result.model_names
217+ )
218+ if not model_required:
219+ return LocalCredentialResult(
220+ None, initial_result.snapshot, False, initial_result.expired,
221+ initial_result.model_names,
222+ )
223+ if initial_result.credential is None or not initial_result.expired:
224+ return replace(initial_result, model_required=True)
225+ 
226+ waiter = asyncio.wrap_future(work.future)
227+ waiter.add_done_callback(_consume_refresh_result)
228+ try:
229+ async with asyncio.timeout(_LOGIN_REFRESH_WAIT_S):
230+ final_result = await asyncio.shield(waiter)
231+ except asyncio.TimeoutError:
232+ logger.warning('[ModelAuth] Control credential refresh timed out')
233+ return LocalCredentialResult(
234+ None, initial_result.snapshot, True, True, initial_result.model_names,
235+ )
236+ except Exception:
237+ return LocalCredentialResult(
238+ None, initial_result.snapshot, True, True, initial_result.model_names,
239+ )
240+ return replace(final_result, model_required=True)
241+ 
242+ def _snapshot(self, service: AuthService, session: Any) -> LocalCredentialSnapshot:
243+ from agent_gateway.auth.login_credentials import credential_ref_for_user
244+ 
245+ return LocalCredentialSnapshot(
246+ store=service._store,
247+ session_id=session.session_id,
248+ user_id=session.user_id,
249+ created_at=session.created_at,
250+ credential_ref=credential_ref_for_user(session.user_id),
49 )251 )
50 252 
51 async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None:253 async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None:
@@ -64,7 +266,6 @@ class LocalCredentialAccess:
64 api_key=update.get('api_key'), revoked=bool(update.get('revoked', False)),266 api_key=update.get('api_key'), revoked=bool(update.get('revoked', False)),
65 )267 )
66 268 
67- 
68 async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None:269 async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None:
69 from agent_gateway.auth.login_credentials import credential_ref_for_user270 from agent_gateway.auth.login_credentials import credential_ref_for_user
70 from agent_gateway.auth.service import ModelAuthRequired, live_session271 from agent_gateway.auth.service import ModelAuthRequired, live_session
@@ -0,0 +1,267 @@
1+"""Public login-model catalog contracts shared by Control and Worker."""
2+from __future__ import annotations
3+ 
4+import json
5+from dataclasses import dataclass
6+from typing import Literal, Protocol
7+from urllib.parse import urlsplit
8+ 
9+from agent_gateway.processes import control_protocol
10+ 
11+ 
12+CatalogStatus = Literal["ok", "unauthenticated", "too_large", "unavailable"]
13+CatalogErrorReason = Literal[
14+ "too_large", "unavailable", "protocol", "busy", "not_enabled"
15+]
16+ 
17+_CATALOG_STATUSES = frozenset(
18+ {"ok", "unauthenticated", "too_large", "unavailable"}
19+)
20+_CATALOG_ERROR_REASONS = frozenset(
21+ {"too_large", "unavailable", "protocol", "busy", "not_enabled"}
22+)
23+_MAX_AUTH_SESSION_LENGTH = 256
24+_MAX_MODELS = 48
25+_MAX_MODEL_NAME_LENGTH = 256
26+_MAX_DISPLAY_NAME_LENGTH = 256
27+_MAX_DESCRIPTION_LENGTH = 1024
28+_MAX_RESULT_BYTES = 48 * 1024
29+_MAX_API_BASE_LENGTH = 2048
30+ 
31+ 
32+class CatalogError(ValueError):
33+ """A sanitized login-model catalog failure."""
34+ 
35+ def __init__(self, reason: CatalogErrorReason = "unavailable") -> None:
36+ if reason not in _CATALOG_ERROR_REASONS:
37+ raise ValueError("Unsupported login model catalog failure reason")
38+ self.reason = reason
39+ super().__init__("Public login model catalog failed")
40+ 
41+ 
42+@dataclass(frozen=True, slots=True)
43+class PublicLoginModel:
44+ """The immutable, public projection of a login model."""
45+ 
46+ model_name: str
47+ display_name: str
48+ description: str
49+ 
50+ def to_dict(self) -> dict[str, str]:
51+ return {
52+ "model_name": self.model_name,
53+ "display_name": self.display_name,
54+ "description": self.description,
55+ }
56+ 
57+ 
58+@dataclass(frozen=True, slots=True)
59+class CatalogResult:
60+ """An immutable catalog snapshot or fixed business failure status."""
61+ 
62+ status: CatalogStatus
63+ models: tuple[PublicLoginModel, ...]
64+ 
65+ def to_dict(self) -> dict[str, object]:
66+ return {
67+ "status": self.status,
68+ "models": [model.to_dict() for model in self.models],
69+ }
70+ 
71+ 
72+@dataclass(frozen=True, slots=True)
73+class LoginModelSnapshot:
74+ """An immutable public model catalog snapshot with its API base."""
75+ 
76+ status: CatalogStatus
77+ api_base: str
78+ models: tuple[PublicLoginModel, ...]
79+ version: int = 1
80+ 
81+ def to_dict(self) -> dict[str, object]:
82+ return {
83+ "version": self.version,
84+ "status": self.status,
85+ "api_base": self.api_base,
86+ "models": [model.to_dict() for model in self.models],
87+ }
88+ 
89+ 
90+class PublicLoginModelCatalog(Protocol):
91+ """Port for fetching the public login-model catalog."""
92+ 
93+ async def list_models(self, auth_session: str | None) -> CatalogResult:
94+ """Return a snapshot for the selected login session."""
95+ ...
96+ 
97+ 
98+class LoginModelSnapshotPort(Protocol):
99+ """Port for fetching a complete public login-model snapshot."""
100+ 
101+ async def get_snapshot(self, auth_session: str | None) -> LoginModelSnapshot:
102+ """Return model metadata and its public inference API base."""
103+ ...
104+ 
105+ 
106+def validate_auth_session(value: object) -> str | None:
107+ """Validate and normalize a bounded auth-session identifier."""
108+ if value is None:
109+ return None
110+ if type(value) is not str or len(value) > _MAX_AUTH_SESSION_LENGTH:
111+ raise CatalogError("protocol")
112+ normalized = value.strip()
113+ return normalized if normalized else None
114+ 
115+ 
116+def _validate_models(status: CatalogStatus, models_value: object) -> tuple[PublicLoginModel, ...]:
117+ if type(models_value) is not list:
118+ raise CatalogError("protocol")
119+ if status != "ok" and models_value:
120+ raise CatalogError("protocol")
121+ if len(models_value) > _MAX_MODELS:
122+ raise CatalogError("too_large")
123+ 
124+ models: list[PublicLoginModel] = []
125+ for model_value in models_value:
126+ if type(model_value) is not dict or set(model_value) != {
127+ "model_name",
128+ "display_name",
129+ "description",
130+ }:
131+ raise CatalogError("protocol")
132+ 
133+ model_name = model_value["model_name"]
134+ display_name = model_value["display_name"]
135+ description = model_value["description"]
136+ if (
137+ type(model_name) is not str
138+ or type(display_name) is not str
139+ or type(description) is not str
140+ ):
141+ raise CatalogError("protocol")
142+ if (
143+ len(model_name) > _MAX_MODEL_NAME_LENGTH
144+ or len(display_name) > _MAX_DISPLAY_NAME_LENGTH
145+ or len(description) > _MAX_DESCRIPTION_LENGTH
146+ ):
147+ raise CatalogError("too_large")
148+ 
149+ models.append(
150+ PublicLoginModel(
151+ model_name=model_name,
152+ display_name=display_name,
153+ description=description,
154+ )
155+ )
156+ return tuple(models)
157+ 
158+ 
159+def _validate_wire_result(result_dict: dict[str, object]) -> None:
160+ try:
161+ encoded_result = json.dumps(
162+ result_dict,
163+ separators=(",", ":"),
164+ ensure_ascii=False,
165+ allow_nan=False,
166+ ).encode("utf-8")
167+ except UnicodeError:
168+ raise CatalogError("protocol") from None
169+ 
170+ if len(encoded_result) > _MAX_RESULT_BYTES:
171+ raise CatalogError("too_large")
172+ 
173+ try:
174+ control_protocol.encode_message(
175+ {
176+ "protocol_version": 1,
177+ # Budget for the longest UTF-8 group ID accepted by the codec.
178+ "group_id": "\U0010ffff" * 256,
179+ "slot_id": 0,
180+ "generation": 1,
181+ "type": "RESPONSE",
182+ "request_id": "a" * 32,
183+ "status": "OK",
184+ "result": result_dict,
185+ "error_code": None,
186+ }
187+ )
188+ except control_protocol.ControlProtocolError:
189+ raise CatalogError("too_large") from None
190+ 
191+ 
192+def _validate_api_base(value: object) -> str:
193+ if type(value) is not str:
194+ raise CatalogError("protocol")
195+ if len(value) > _MAX_API_BASE_LENGTH:
196+ raise CatalogError("too_large")
197+ if not value:
198+ return value
199+ 
200+ try:
201+ parsed = urlsplit(value)
202+ port = parsed.port
203+ except ValueError:
204+ raise CatalogError("protocol") from None
205+ if (
206+ parsed.scheme not in {"http", "https"}
207+ or not parsed.hostname
208+ or parsed.username is not None
209+ or parsed.password is not None
210+ or parsed.query
211+ or parsed.fragment
212+ or "?" in value
213+ or "#" in value
214+ or (port is not None and not 1 <= port <= 65535)
215+ ):
216+ raise CatalogError("protocol")
217+ return value
218+ 
219+ 
220+def validate_catalog_response(value: object) -> CatalogResult:
221+ """Validate a complete Control catalog response without truncation."""
222+ if type(value) is not dict or set(value) != {"status", "models"}:
223+ raise CatalogError("protocol")
224+ 
225+ status = value["status"]
226+ models_value = value["models"]
227+ if type(status) is not str or status not in _CATALOG_STATUSES:
228+ raise CatalogError("protocol")
229+ models = _validate_models(status, models_value)
230+ 
231+ result = CatalogResult(status=status, models=models)
232+ result_dict = result.to_dict()
233+ _validate_wire_result(result_dict)
234+ return result
235+ 
236+ 
237+def validate_login_model_snapshot(value: object) -> LoginModelSnapshot:
238+ """Validate a complete Control snapshot without truncation or token leakage."""
239+ if type(value) is not dict or set(value) != {
240+ "version",
241+ "status",
242+ "api_base",
243+ "models",
244+ }:
245+ raise CatalogError("protocol")
246+ 
247+ version = value["version"]
248+ if type(version) is not int or version != 1:
249+ raise CatalogError("protocol")
250+ status = value["status"]
251+ if type(status) is not str or status not in _CATALOG_STATUSES:
252+ raise CatalogError("protocol")
253+ api_base = _validate_api_base(value["api_base"])
254+ models = _validate_models(status, value["models"])
255+ if status != "ok" and (api_base or models):
256+ raise CatalogError("protocol")
257+ if models and not api_base:
258+ raise CatalogError("protocol")
259+ 
260+ result = LoginModelSnapshot(
261+ status=status,
262+ api_base=api_base,
263+ models=models,
264+ version=version,
265+ )
266+ _validate_wire_result(result.to_dict())
267+ return result
Aagent_gateway/auth/remote_credential_access.py+383-0File content is under review, please try again later
Aagent_gateway/auth/remote_model_catalog.py+104-0File content is under review, please try again later
Magent_gateway/auth/session_store.py+42-0File content is under review, please try again later
Aagent_gateway/auth/worker_credential_services.py+97-0File content is under review, please try again later
Magent_gateway/channel_manager/channel_manager.py+3-2File content is under review, please try again later
Magent_gateway/channel_manager/tui/tui_channel.py+7-0File content is under review, please try again later
Magent_gateway/channel_manager/web/web_http_auth.py+9-2File content is under review, please try again later
Aagent_gateway/cron/ownership.py+29-0File content is under review, please try again later
Aagent_gateway/cron/preflight.py+87-0File content is under review, please try again later
Magent_gateway/message_handler/message_handler.py+152-19File content is under review, please try again later
Aagent_gateway/processes/pool.py+405-0File content is under review, please try again later
Aagent_gateway/processes/worker.py+264-0File content is under review, please try again later
Magent_gateway/runtime/cron/store.py+142-7File content is under review, please try again later
Magent_gateway/southbound/data/transport.py+7-2File content is under review, please try again later
Magent_gateway/southbound/data/websocket.py+66-26File content is under review, please try again later
Magent_gateway/southbound/orchestration/client.py+7-2File content is under review, please try again later
Atests/integration/gateway/test_controlled_accounts.py+86-0File content is under review, please try again later
Atests/unit_tests/gateway/test_control_model_catalog_network.py+108-0File content is under review, please try again later
Atests/unit_tests/gateway/test_credential_issuance_registry.py+148-0File content is under review, please try again later
Atests/unit_tests/gateway/test_cron_control_commands.py+687-0File content is under review, please try again later
Atests/unit_tests/gateway/test_cron_ownership.py+31-0File content is under review, please try again later
Atests/unit_tests/gateway/test_remote_credential_failure.py+522-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_credential_runtime.py+868-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_commands.py+1239-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_ingress.py+254-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_models.py+291-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_workspace.py+262-0File content is under review, please try again later