Draft
[WIP]feat(gateway): restore personal workflows in controlled workers #494
[WIP]feat(gateway): restore personal workflows in controlled workers #494
Draft
yutaoJustinBieber1223Add on 2 days ago
Total: 107 files changed+25445-144
@@ -47,12 +47,17 @@ from agent_gateway.startup.bootstrap import (
47 prepare_group_workspace,47 prepare_group_workspace,
48)48)
49 49 
50+# ``--check-cron`` only reports the read-only Cron file preflight. It must not
51+# configure logging, prepare the workspace or apply group environment: none of
52+# those may create or change files before the report is printed.
53+_CHECK_CRON_BOOTSTRAP = "--check-cron" in sys.argv[1:]
50initialize_early_environment(_mark_startup_import_phase)54initialize_early_environment(_mark_startup_import_phase)
51-configure_process_logging(_mark_startup_import_phase)55+if not _CHECK_CRON_BOOTSTRAP:
56+ configure_process_logging(_mark_startup_import_phase)
52 57 
53-# Standalone entrypoints retain workspace preparation; Desktop/app already do58+ # Standalone entrypoints retain workspace preparation; Desktop/app already do
54-# it before spawning us and pass the marker to avoid duplicate disk work.59+ # it before spawning us and pass the marker to avoid duplicate disk work.
55-prepare_group_workspace(_mark_startup_import_phase)60+ prepare_group_workspace(_mark_startup_import_phase)
56 61 
57_mark_startup_import_phase("openjiuwen_and_channel_base_imported")62_mark_startup_import_phase("openjiuwen_and_channel_base_imported")
58 63 
@@ -85,7 +90,8 @@ _mark_startup_import_phase("gateway_core_imports_loaded")
85 90 
86_mark_startup_import_phase("logging_configured")91_mark_startup_import_phase("logging_configured")
87 92 
88-apply_group_environment(_mark_startup_import_phase)93+if not _CHECK_CRON_BOOTSTRAP:
94+ apply_group_environment(_mark_startup_import_phase)
89 95 
90register_edition_req_methods()96register_edition_req_methods()
91 97 
@@ -121,6 +127,23 @@ _XIAOYI_DEFAULT_PUSH_URL = "https://hag.cloud.huawei.com/open-ability-agent/v1/a
121 127 
122 128 
123 129 
130+def _check_cron(args, parser) -> None:
131+ """Report Cron file compatibility without starting the Gateway, then exit."""
132+ from agent_gateway.application.cron_preflight import check_cron_cli
133+ from agent_gateway.application.multiprocess import DEFAULT_WORKERS, MAX_WORKERS
134+ from agent_gateway.common.agentos_runtime import is_agentos_runtime
135+ from agent_gateway.dotenv_early import load_dotenv_runtime
136+ from agent_gateway.enterprise import is_enterprise
137+ 
138+ load_dotenv_runtime(get_env_file(), override=True)
139+ workers = args.workers if args.workers is not None else DEFAULT_WORKERS
140+ if not 1 <= workers <= MAX_WORKERS:
141+ parser.error(f"--workers must be between 1 and {MAX_WORKERS}")
142+ if is_enterprise() or is_agentos_runtime():
143+ parser.error("--check-cron requires a local personal workspace")
144+ raise SystemExit(check_cron_cli(workers))
145+ 
146+ 
124async def _normalize_and_forward_message(msg, channel_manager) -> bool:147async def _normalize_and_forward_message(msg, channel_manager) -> bool:
125 return await MessagePreprocessor(148 return await MessagePreprocessor(
126 _refresh_expired_login_credential, _normalize_gateway_message, _inject_session_work_mode,149 _refresh_expired_login_credential, _normalize_gateway_message, _inject_session_work_mode,
@@ -329,6 +352,15 @@ def main() -> None:
329 metavar="<path>",352 metavar="<path>",
330 help="Load environment from .env file (processed at startup, not used here).",353 help="Load environment from .env file (processed at startup, not used here).",
331 )354 )
355+ parser.add_argument("--mode", choices=("single", "multiprocess"), default="single",
356+ help="Run the single Gateway or opt in to the personal loopback Worker trial.")
357+ parser.add_argument("--workers", type=int, help="Fixed Worker count in multiprocess mode (default: 2).")
358+ parser.add_argument("--enable-accounts", action="store_true",
359+ help="Enable Control-owned account services in the multiprocess trial.")
360+ parser.add_argument("--enable-cron", action="store_true",
361+ help="Enable sharded personal Cron in multiprocess mode.")
362+ parser.add_argument("--check-cron", action="store_true",
363+ help="Print the read-only Cron file preflight and exit.")
332 parser.add_argument(364 parser.add_argument(
333 "--require-adx-router",365 "--require-adx-router",
334 # Accept previously generated service units; validation itself is generic.366 # Accept previously generated service units; validation itself is generic.
@@ -336,6 +368,18 @@ def main() -> None:
336 help=argparse.SUPPRESS,368 help=argparse.SUPPRESS,
337 )369 )
338 args = parser.parse_args()370 args = parser.parse_args()
371+ if args.workers is not None and args.mode != "multiprocess":
372+ parser.error("--workers requires --mode multiprocess")
373+ if args.enable_accounts and args.mode != "multiprocess":
374+ parser.error("--enable-accounts requires --mode multiprocess")
375+ if args.enable_cron and args.mode != "multiprocess":
376+ parser.error("--enable-cron requires --mode multiprocess")
377+ if args.check_cron and (args.mode != "multiprocess" or not args.enable_cron):
378+ parser.error("--check-cron requires --mode multiprocess --enable-cron")
379+ 
380+ if args.check_cron:
381+ _check_cron(args, parser)
382+ return
339 383 
340 # Handle --name: check if bootstrap .env was loaded successfully384 # Handle --name: check if bootstrap .env was loaded successfully
341 # (parse_dotenv_early() already processed it, this is just a fallback check)385 # (parse_dotenv_early() already processed it, this is just a fallback check)
@@ -365,7 +409,9 @@ def main() -> None:
365 or f"ws://{default_host}:{default_port}"409 or f"ws://{default_host}:{default_port}"
366 )410 )
367 web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1")411 web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1")
368- web_port = args.port or int(os.getenv("WEB_PORT", "19000"))412+ web_port = args.port if args.mode == "multiprocess" and args.port is not None else (
413+ args.port or int(os.getenv("WEB_PORT", "19000"))
414+ )
369 web_path = args.web_path or os.getenv("WEB_PATH", "/ws")415 web_path = args.web_path or os.getenv("WEB_PATH", "/ws")
370 # ws permessage-deflate compresses every frame with zlib; on loopback/LAN416 # ws permessage-deflate compresses every frame with zlib; on loopback/LAN
371 # the CPU cost outweighs the bandwidth saving, so it stays off by default.417 # the CPU cost outweighs the bandwidth saving, so it stays off by default.
@@ -377,6 +423,29 @@ def main() -> None:
377 "on",423 "on",
378 )424 )
379 425 
426+ if args.mode == "multiprocess":
427+ from agent_gateway.application.multiprocess import MultiprocessOptions, run_multiprocess
428+ from agent_gateway.startup.lifecycle import gateway_workspace_lock, run_with_shutdown_signals
429+ 
430+ try:
431+ options = MultiprocessOptions.from_cli(
432+ workers=args.workers, web_host=web_host, web_port=web_port,
433+ web_path=web_path, web_ws_deflate=web_ws_deflate,
434+ required_client_type=args.required_client_type, accounts=args.enable_accounts,
435+ cron=args.enable_cron,
436+ )
437+ 
438+ async def run_multiprocess_until_shutdown(shutdown_event: asyncio.Event) -> None:
439+ await run_multiprocess(options, agent_server_url, shutdown_event)
440+ 
441+ install_crash_exit_handler("gateway")
442+ install_async_dump_handler("gateway")
443+ with gateway_workspace_lock(get_user_workspace_dir()):
444+ asyncio.run(run_with_shutdown_signals(run_multiprocess_until_shutdown, shutdown_gateway_telemetry))
445+ except ValueError as error:
446+ parser.error(str(error))
447+ return
448+ 
380 install_crash_exit_handler("gateway")449 install_crash_exit_handler("gateway")
381 install_async_dump_handler("gateway")450 install_async_dump_handler("gateway")
382 451 
@@ -0,0 +1,102 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+ 
3+"""Read-only assembly gate for the explicitly enabled sharded personal Cron."""
4+ 
5+from __future__ import annotations
6+ 
7+from typing import Any
8+ 
9+from agent_gateway.cron.ownership import CronOwnership
10+from agent_gateway.cron.preflight import CronPreflightReport, inspect_cron_store
11+from agent_gateway.cron.store import FileCronJobStore
12+ 
13+ 
14+async def inspect_controlled_cron(
15+ ownership: CronOwnership, *, config: dict[str, Any] | None = None,
16+ store: FileCronJobStore | None = None,
17+ allow_login_credentials: bool = False,
18+ allow_project_jobs: bool = True,
19+) -> CronPreflightReport:
20+ from agent_gateway.common.config import get_config
21+ from agent_gateway.common.cron_settings import load_cron_store_settings
22+ from agent_gateway.enterprise import is_enterprise
23+ 
24+ if is_enterprise():
25+ raise ValueError('sharded Cron requires the personal file backend')
26+ config = get_config() if config is None else config
27+ if not isinstance(config, dict):
28+ raise ValueError('invalid Cron preflight configuration')
29+ gateway = config.get('gateway', {})
30+ if not isinstance(gateway, dict) or not isinstance(gateway.get('cron', {}), dict):
31+ raise ValueError('invalid Cron preflight configuration')
32+ settings = load_cron_store_settings(config)
33+ if settings.backend != 'file':
34+ raise ValueError('sharded Cron requires the personal file backend')
35+ proactive = config.get('proactive_recommendation', {})
36+ if not isinstance(proactive, dict):
37+ raise ValueError('invalid Cron preflight configuration')
38+ enabled = proactive.get('enabled', False)
39+ if type(enabled) is not bool:
40+ raise ValueError('invalid Cron preflight configuration')
41+ backend = store if store is not None else FileCronJobStore(path=settings.file_path)
42+ return await inspect_cron_store(
43+ backend, ownership, proactive_enabled=enabled,
44+ allow_login_credentials=allow_login_credentials, allow_project_jobs=allow_project_jobs,
45+ )
46+ 
47+ 
48+async def preflight_controlled_cron(
49+ ownership: CronOwnership, *, config: dict[str, Any] | None = None,
50+ store: FileCronJobStore | None = None, allow_login_credentials: bool = False,
51+ allow_project_jobs: bool = True,
52+) -> CronPreflightReport:
53+ """Refuse to activate Cron while an enabled record uses an unsupported capability."""
54+ report = await inspect_controlled_cron(
55+ ownership, config=config, store=store, allow_login_credentials=allow_login_credentials,
56+ allow_project_jobs=allow_project_jobs,
57+ )
58+ if not report.ready:
59+ raise ValueError('Cron preflight rejected unsupported enabled capabilities')
60+ return report
61+ 
62+ 
63+async def require_controlled_cron(
64+ ownership: CronOwnership, *, config: dict[str, Any] | None = None,
65+ allow_project_jobs: bool = False,
66+) -> CronPreflightReport:
67+ """Preflight with a message that names only blocking job identifiers and reasons."""
68+ report = await inspect_controlled_cron(
69+ ownership, config=config, allow_project_jobs=allow_project_jobs,
70+ )
71+ if not report.ready:
72+ # ``issues`` carries operational identifiers only: never a task body,
73+ # description or credential reference.
74+ blockers = ", ".join(
75+ f"{issue.job_id or 'config'}: {issue.reason}" for issue in report.issues if issue.blocking
76+ )
77+ raise ValueError(f"Cron preflight rejected unsupported enabled capabilities ({blockers})")
78+ return report
79+ 
80+ 
81+def check_cron_cli(worker_count: int) -> int:
82+ """Inspect a static snapshot without preparing a runtime or touching AS."""
83+ import asyncio
84+ from dataclasses import asdict
85+ import json
86+ 
87+ import yaml
88+ 
89+ from agent_gateway.common.ingress_identity import LocalIdentityPolicy
90+ from agent_gateway.common.worker_affinity import WorkerManifest
91+ 
92+ ownership = CronOwnership(WorkerManifest(tuple(range(worker_count))), LocalIdentityPolicy())
93+ result: dict[str, Any] = {'scope': 'static_file_only', 'agentserver_checked': False}
94+ try:
95+ report = asyncio.run(inspect_controlled_cron(ownership, allow_project_jobs=False))
96+ except (ValueError, OSError, AttributeError, TypeError, yaml.YAMLError):
97+ # YAML/parser and OS errors may carry paths or values; do not echo them.
98+ result.update(ready=False, error='invalid_or_unreadable_cron_configuration_or_snapshot')
99+ else:
100+ result.update(asdict(report), ready=report.ready)
101+ print(json.dumps(result, ensure_ascii=True))
102+ return 0 if result['ready'] else 1
@@ -13,7 +13,7 @@ from typing import AbstractSet, Any, TYPE_CHECKING
13if TYPE_CHECKING:13if TYPE_CHECKING:
14 from agent_gateway.auth.credential_access import CredentialAccess14 from agent_gateway.auth.credential_access import CredentialAccess
15 15 
16-from agent_gateway.auth.credential_access import LOGIN_REFRESH_WAIT_S16+from agent_gateway.auth.credential_access import CredentialAccessError, LOGIN_REFRESH_WAIT_S
17from e2a.message import Message17from e2a.message import Message
18from agent_gateway.channel_manager.web.req_method_routing import (18from agent_gateway.channel_manager.web.req_method_routing import (
19 ROUTE_DENIED,19 ROUTE_DENIED,
@@ -181,8 +181,9 @@ def _inject_session_work_mode(msg: Message) -> None:
181class InboundQueue:181class InboundQueue:
182 """Gateway internal inbound service for forwarding channel messages to MessageHandler."""182 """Gateway internal inbound service for forwarding channel messages to MessageHandler."""
183 183 
184- def __init__(self, inbound_handler):184+ def __init__(self, inbound_handler, *, error_callback=None):
185 self._inbound_handler = inbound_handler185 self._inbound_handler = inbound_handler
186+ self._error_callback = error_callback
186 self._queue: asyncio.Queue = asyncio.Queue()187 self._queue: asyncio.Queue = asyncio.Queue()
187 self._task: asyncio.Task | None = None188 self._task: asyncio.Task | None = None
188 self._running = False189 self._running = False
@@ -218,6 +219,14 @@ class InboundQueue:
218 handled = self._inbound_handler(msg)219 handled = self._inbound_handler(msg)
219 if asyncio.iscoroutine(handled):220 if asyncio.iscoroutine(handled):
220 await handled221 await handled
222+ except CredentialAccessError as error:
223+ if self._error_callback is None:
224+ logger.warning("[App] Gateway credential access failed: id=%s", getattr(msg, "id", None))
225+ else:
226+ try:
227+ await self._error_callback(msg, error)
228+ except Exception:
229+ logger.exception("[App] Gateway credential failure response could not be delivered")
221 except Exception: # noqa: BLE001230 except Exception: # noqa: BLE001
222 logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None))231 logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None))
223 232 
@@ -260,6 +269,8 @@ class MessagePreprocessor:
260 with trace_stage("preprocess.credentials"):269 with trace_stage("preprocess.credentials"):
261 try:270 try:
262 auth = await self.credential_access.request_model_auth(_auth_session_id(msg), model_name)271 auth = await self.credential_access.request_model_auth(_auth_session_id(msg), model_name)
272+ except CredentialAccessError:
273+ raise
263 except Exception: # Login availability must not break request forwarding.274 except Exception: # Login availability must not break request forwarding.
264 logger.debug('[App] Credential lookup failed; forwarding without login credentials', exc_info=True)275 logger.debug('[App] Credential lookup failed; forwarding without login credentials', exc_info=True)
265 auth = None276 auth = None
@@ -269,13 +280,22 @@ class MessagePreprocessor:
269 280 
270 async def forward(self, msg: Any, channel_manager: Any) -> bool:281 async def forward(self, msg: Any, channel_manager: Any) -> bool:
271 normalized = await self._prepare(msg)282 normalized = await self._prepare(msg)
272- method = request_method_name(getattr(msg, "req_method", None))283+ await self._deliver(normalized, msg, channel_manager)
273- if method == "session.create":
274- self.inject_work_mode(normalized)
275- await channel_manager.deliver_to_message_handler(normalized)
276 logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)284 logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
277 return False285 return False
278 286 
287+ async def _deliver(self, normalized: Any, msg: Any, channel_manager: Any) -> None:
288+ accepted = False
289+ try:
290+ if request_method_name(getattr(msg, "req_method", None)) == "session.create":
291+ self.inject_work_mode(normalized)
292+ accepted = await channel_manager.deliver_to_message_handler(normalized) is not False
293+ finally:
294+ if not accepted:
295+ release = getattr(self.credential_access, "release_request", None)
296+ if release is not None:
297+ release(normalized)
298+ 
279 def for_channel(299 def for_channel(
280 self,300 self,
281 channel_manager: Any,301 channel_manager: Any,
@@ -297,9 +317,7 @@ class MessagePreprocessor:
297 if route in (ROUTE_LOCAL, ROUTE_DENIED):317 if route in (ROUTE_LOCAL, ROUTE_DENIED):
298 return False318 return False
299 normalized = await self._prepare(msg)319 normalized = await self._prepare(msg)
300- if method == "session.create":320+ await self._deliver(normalized, msg, channel_manager)
301- self.inject_work_mode(normalized)
302- await channel_manager.deliver_to_message_handler(normalized)
303 logger.debug("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id)321 logger.debug("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id)
304 return route == ROUTE_FORWARD_UNKNOWN or method in no_local_methods322 return route == ROUTE_FORWARD_UNKNOWN or method in no_local_methods
305 323 
@@ -0,0 +1,171 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+"""Opt-in, personal loopback trial using the fixed Worker group."""
3+ 
4+from __future__ import annotations
5+ 
6+import asyncio
7+from dataclasses import dataclass
8+import json
9+import logging
10+import os
11+from pathlib import Path
12+import socket
13+ 
14+from agent_gateway.application.cron_preflight import require_controlled_cron
15+from agent_gateway.application.worker_group import WorkerGroup
16+from agent_gateway.common.agentos_runtime import is_agentos_runtime
17+from agent_gateway.common.ingress_identity import LocalIdentityPolicy
18+from agent_gateway.common.worker_affinity import WorkerManifest
19+from agent_gateway.cron.ownership import CronOwnership
20+from agent_gateway.enterprise import is_enterprise
21+from agent_gateway.processes.capabilities import management_preflight
22+ 
23+DEFAULT_WORKERS = 2
24+MAX_WORKERS = 32
25+logger = logging.getLogger("gateway")
26+ 
27+ 
28+@dataclass(frozen=True)
29+class MultiprocessOptions:
30+ workers: int
31+ web_port: int
32+ protocol_port: int
33+ accounts: bool = False
34+ cron: bool = False
35+ 
36+ @classmethod
37+ def from_cli(cls, *, workers: int | None, web_host: str, web_port: int,
38+ web_path: str, web_ws_deflate: bool,
39+ required_client_type: str | tuple[str, ...] | None,
40+ accounts: bool = False, cron: bool = False) -> MultiprocessOptions:
41+ count = DEFAULT_WORKERS if workers is None else workers
42+ if not 1 <= count <= MAX_WORKERS:
43+ raise ValueError(f"--workers must be between 1 and {MAX_WORKERS}")
44+ if type(accounts) is not bool or type(cron) is not bool:
45+ raise ValueError("--enable-accounts and --enable-cron must be explicit flags")
46+ if is_enterprise() or is_agentos_runtime() or required_client_type is not None:
47+ raise ValueError("multiprocess requires a personal deployment")
48+ if web_host not in {"127.0.0.1", "localhost"} or os.getenv(
49+ "GATEWAY_HOST", "127.0.0.1",
50+ ) not in {"127.0.0.1", "localhost"}:
51+ raise ValueError("multiprocess requires loopback listeners (127.0.0.1)")
52+ if web_path != "/ws" or web_ws_deflate:
53+ raise ValueError("multiprocess requires /ws without WebSocket compression")
54+ if os.getenv("A2A_SERVER_ENABLED", "").strip().lower() in {"1", "true", "yes", "on"}:
55+ raise ValueError("A2A is unavailable in multiprocess mode")
56+ if not management_preflight().supported or not all((
57+ hasattr(socket, "SCM_RIGHTS"), hasattr(socket.socket, "sendmsg"),
58+ hasattr(socket.socket, "recvmsg"),
59+ )):
60+ raise ValueError("multiprocess requires Linux or macOS with fd passing")
61+ protocol_port = int(os.getenv("GATEWAY_PORT", "19001"))
62+ if not 0 <= web_port <= 65535 or not 0 <= protocol_port <= 65535:
63+ raise ValueError("listen ports must be between 0 and 65535")
64+ if web_port == protocol_port != 0:
65+ raise ValueError("Web and TUI/ACP must use distinct ports")
66+ return cls(count, web_port, protocol_port, accounts, cron)
67+ 
68+ 
69+def _channel_enabled(config: object) -> bool:
70+ if not isinstance(config, dict) or not config:
71+ return bool(config)
72+ if "enabled" in config:
73+ return bool(config["enabled"])
74+ if "apps" in config:
75+ return any(_channel_enabled(app) for app in (config["apps"] or ()))
76+ return True
77+ 
78+ 
79+def _has_enabled_cron_jobs(path: Path) -> bool:
80+ # Read the atomic snapshot without invoking the store's lazy migration.
81+ try:
82+ data = json.loads(path.read_text(encoding="utf-8"))
83+ except FileNotFoundError:
84+ return False
85+ except (OSError, ValueError) as error:
86+ raise ValueError("cannot read the Cron job snapshot; use single mode") from error
87+ jobs = data.get("jobs", []) if isinstance(data, dict) else None
88+ if not isinstance(jobs, list) or not all(isinstance(job, dict) for job in jobs):
89+ raise ValueError("invalid Cron job snapshot; use single mode")
90+ return any(job.get("enabled") for job in jobs)
91+ 
92+ 
93+async def validate_workspace(*, cron: bool = False, workers: int = DEFAULT_WORKERS) -> None:
94+ """Refuse a workspace the Worker group cannot serve before any listener opens.
95+ 
96+ Without ``cron`` an enabled Cron record keeps the trial in single mode, as
97+ before. With ``cron`` the record must instead pass the read-only preflight.
98+ Neither path creates, migrates or rewrites the Cron file.
99+ """
100+ from agent_gateway.common.config import get_config
101+ from agent_gateway.common.cron_settings import load_cron_store_settings
102+ 
103+ if type(cron) is not bool:
104+ raise ValueError("cron must be an explicit boolean")
105+ 
106+ config = await asyncio.to_thread(get_config)
107+ gateway = config.get("gateway") or {}
108+ client_type = (gateway.get("agent_client") or {}).get("type") or "websocket"
109+ if client_type != "websocket":
110+ raise ValueError("multiprocess requires the direct WebSocket AgentServer client")
111+ for name, channel in (config.get("channels") or {}).items():
112+ if name == "web":
113+ continue
114+ enabled = (any(_channel_enabled(bot) for bot in channel.values())
115+ if name == "feishu_enterprise" and isinstance(channel, dict)
116+ else _channel_enabled(channel))
117+ if enabled:
118+ raise ValueError("multiprocess requires optional channels to be disabled")
119+ if (config.get("proactive_recommendation") or {}).get("enabled"):
120+ raise ValueError("proactive recommendations are unavailable in multiprocess mode")
121+ settings = load_cron_store_settings(config)
122+ if settings.backend != "file":
123+ raise ValueError("Cron is not supported by this trial; use single mode")
124+ if not cron:
125+ if await asyncio.to_thread(_has_enabled_cron_jobs, settings.file_path):
126+ raise ValueError("Cron is not supported by this trial; use single mode")
127+ return
128+ if type(workers) is not int or not 1 <= workers <= MAX_WORKERS:
129+ raise ValueError(f"--workers must be between 1 and {MAX_WORKERS}")
130+ await require_controlled_cron(
131+ CronOwnership(WorkerManifest(tuple(range(workers))), LocalIdentityPolicy()), config=config,
132+ )
133+ 
134+ 
135+async def run_multiprocess(options: MultiprocessOptions, agent_server_url: str,
136+ shutdown_event: asyncio.Event) -> None:
137+ await validate_workspace(cron=options.cron, workers=options.workers)
138+ if shutdown_event.is_set():
139+ return
140+ auth_service_provider = None
141+ if options.accounts:
142+ from agent_gateway.auth.service import get_auth_service
143+ 
144+ auth_service_provider = get_auth_service
145+ group = WorkerGroup(agent_server_url, workers=options.workers, web_port=options.web_port,
146+ protocol_port=options.protocol_port, auth_service_provider=auth_service_provider,
147+ cron=options.cron)
148+ shutdown = asyncio.create_task(shutdown_event.wait())
149+ startup = asyncio.create_task(group.start())
150+ tasks = [shutdown, startup]
151+ try:
152+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
153+ if startup in done:
154+ await startup
155+ if shutdown.done():
156+ return
157+ logger.info("[App] multiprocess_ready workers=%d web_port=%d protocol_port=%d worker_pids=%s",
158+ options.workers, group.addresses[0][1], group.addresses[1][1],
159+ ",".join(str(process.pid) for process in group.pool.processes))
160+ closed = asyncio.create_task(group.wait())
161+ tasks.append(closed)
162+ done, _ = await asyncio.wait((closed, shutdown), return_when=asyncio.FIRST_COMPLETED)
163+ if closed in done:
164+ await closed
165+ finally:
166+ for task in tasks:
167+ task.cancel()
168+ try:
169+ await asyncio.gather(*tasks, return_exceptions=True)
170+ finally:
171+ await group.stop()
Aagent_gateway/application/personal_settings.py+190-0File content is under review, please try again later
Aagent_gateway/application/personal_tui.py+343-0File content is under review, please try again later
Aagent_gateway/application/personal_web_operations.py+104-0File content is under review, please try again later
@@ -7,8 +7,11 @@ from __future__ import annotations
7from collections.abc import Callable7from collections.abc import Callable
8from dataclasses import dataclass8from dataclasses import dataclass
9import os9import os
10+import time
10from typing import Any11from typing import Any
11 12 
13+from e2a.message import EventType, Message
14+ 
12from agent_gateway.application.inbound import InboundQueue, MessagePreprocessor15from agent_gateway.application.inbound import InboundQueue, MessagePreprocessor
13from agent_gateway.routing.protocol_runtime import ProtocolRuntime, ProtocolRuntimeConfig, RouteConfig16from agent_gateway.routing.protocol_runtime import ProtocolRuntime, ProtocolRuntimeConfig, RouteConfig
14from agent_gateway.routing.route_binding import GatewayRouteBinding17from agent_gateway.routing.route_binding import GatewayRouteBinding
@@ -71,6 +74,8 @@ async def assemble_tui_acp(
71 heartbeat_controller: Any,74 heartbeat_controller: Any,
72 preprocessor: MessagePreprocessor,75 preprocessor: MessagePreprocessor,
73 log_stage: Callable[[str], None],76 log_stage: Callable[[str], None],
77+ personal_tui: bool = False,
78+ web_session_busy: Callable[..., bool] | None = None,
74) -> TuiAcpAssembly:79) -> TuiAcpAssembly:
75 from agent_gateway.channel_manager.web.app_web_handlers import (80 from agent_gateway.channel_manager.web.app_web_handlers import (
76 _FORWARD_REQ_METHODS, _FORWARD_NO_LOCAL_HANDLER_METHODS, _DummyBus,81 _FORWARD_REQ_METHODS, _FORWARD_NO_LOCAL_HANDLER_METHODS, _DummyBus,
@@ -101,10 +106,20 @@ async def assemble_tui_acp(
101 if callable(subscribe_fn):106 if callable(subscribe_fn):
102 subscribe_fn(channel_manager)107 subscribe_fn(channel_manager)
103 108 
109+ async def publish_credential_error(message, error):
110+ acp = message.channel_id == "acp"
111+ payload = {"error": str(error), "code": "CREDENTIAL_SERVICE_FAILED"}
112+ await protocol_runtime.send(Message(
113+ id=message.id, type="event" if acp else "res", channel_id=message.channel_id,
114+ session_id=message.session_id, params={}, timestamp=time.time(), ok=False,
115+ user_id=message.user_id, agent_ref=message.agent_ref, metadata=message.metadata,
116+ event_type=EventType.CHAT_ERROR if acp else None, payload=payload,
117+ ))
118+ 
104 acp_inbound_server = InboundQueue(119 acp_inbound_server = InboundQueue(
105- lambda msg: preprocessor.forward(msg, channel_manager)120+ lambda msg: preprocessor.forward(msg, channel_manager),
121+ error_callback=publish_credential_error,
106 )122 )
107- await acp_inbound_server.start()
108 123 
109 route_bindings = [124 route_bindings = [
110 _build_acp_route_binding(125 _build_acp_route_binding(
@@ -137,6 +152,13 @@ async def assemble_tui_acp(
137 )152 )
138 protocol_runtime = ProtocolRuntime(protocol_runtime_config, _DummyBus())153 protocol_runtime = ProtocolRuntime(protocol_runtime_config, _DummyBus())
139 protocol_runtime.message_handler_ref = message_handler154 protocol_runtime.message_handler_ref = message_handler
155+ if personal_tui:
156+ from agent_gateway.application.personal_tui import PersonalTuiRequests
157+ 
158+ tui_route = protocol_runtime_config.routes["/tui"]
159+ tui_route.unbound_request_handler = PersonalTuiRequests(
160+ protocol_runtime, client, web_session_busy,
161+ ).handle
140 for binding in route_bindings:162 for binding in route_bindings:
141 route_config = protocol_runtime_config.routes[binding.path]163 route_config = protocol_runtime_config.routes[binding.path]
142 # tui 出站已由 TuiChannel 接管(register_channel_with_inbound),164 # tui 出站已由 TuiChannel 接管(register_channel_with_inbound),
@@ -148,5 +170,6 @@ async def assemble_tui_acp(
148 if binding.install is not None:170 if binding.install is not None:
149 binding.install(protocol_runtime)171 binding.install(protocol_runtime)
150 protocol_runtime.on_message(acp_inbound_server.handle_message)172 protocol_runtime.on_message(acp_inbound_server.handle_message)
173+ await acp_inbound_server.start()
151 log_stage("gateway_routes_registered")174 log_stage("gateway_routes_registered")
152 return TuiAcpAssembly(tui_channel, acp_inbound_server, protocol_runtime)175 return TuiAcpAssembly(tui_channel, acp_inbound_server, protocol_runtime)
@@ -21,10 +21,39 @@ from e2a.message import (
21)21)
22from agent_gateway.channel_manager.web.media import normalize_chat_media_attachments22from agent_gateway.channel_manager.web.media import normalize_chat_media_attachments
23from agent_gateway.application.inbound import MessagePreprocessor23from agent_gateway.application.inbound import MessagePreprocessor
24+from agent_gateway.application.personal_web_operations import PERSONAL_WEB_OPERATIONS, protect_personal_web_operation
25+from agent_gateway.application.personal_settings import PERSONAL_SETTINGS_METHODS, protect_settings_handler
24 26 
25logger = logging.getLogger("gateway")27logger = logging.getLogger("gateway")
26 28 
27 29 
30+class _PersonalSettingsRegistration:
31+ """Registration-only proxy used by the account-free personal Worker.
32+ 
33+ Nothing else changes: every attribute is forwarded to the channel and no
34+ global hook is installed. A settings method is registered behind the Web
35+ Origin and parameter gate, and it never takes the generic forwarding path.
36+ """
37+ 
38+ def __init__(self, channel: Any) -> None:
39+ object.__setattr__(self, "_channel", channel)
40+ 
41+ def __getattr__(self, name: str) -> Any:
42+ return getattr(self._channel, name)
43+ 
44+ def __setattr__(self, name: str, value: Any) -> None:
45+ setattr(self._channel, name, value)
46+ 
47+ def register_method(self, method: str, handler: Any, *, local_only: bool = False) -> None:
48+ if method in PERSONAL_SETTINGS_METHODS:
49+ handler = protect_settings_handler(self._channel, method, handler)
50+ local_only = True
51+ elif method in PERSONAL_WEB_OPERATIONS:
52+ handler = protect_personal_web_operation(self._channel, method, handler)
53+ local_only = True
54+ self._channel.register_method(method, handler, local_only=local_only)
55+ 
56+ 
28def assemble_web(57def assemble_web(
29 *,58 *,
30 agent_client: Any,59 agent_client: Any,
@@ -44,6 +73,8 @@ def assemble_web(
44 log_stage: Callable[[str], None],73 log_stage: Callable[[str], None],
45 auth_service_provider: Callable[[], AuthService] | None = None,74 auth_service_provider: Callable[[], AuthService] | None = None,
46 credential_update_sink: CredentialUpdateSink | None = None,75 credential_update_sink: CredentialUpdateSink | None = None,
76+ personal_settings: bool = False,
77+ require_git_activity_snapshot: bool = False,
47) -> tuple[Any, asyncio.Event]:78) -> tuple[Any, asyncio.Event]:
48 from agent_gateway.channel_manager.protocol.web_proxy.web_proxy_listen import register_3rdagent_web_method79 from agent_gateway.channel_manager.protocol.web_proxy.web_proxy_listen import register_3rdagent_web_method
49 from agent_gateway.channel_manager.web.app_web_handlers import (80 from agent_gateway.channel_manager.web.app_web_handlers import (
@@ -61,6 +92,7 @@ def assemble_web(
61 port=web_port,92 port=web_port,
62 path=web_path,93 path=web_path,
63 ws_permessage_deflate=web_ws_deflate,94 ws_permessage_deflate=web_ws_deflate,
95+ require_git_activity_snapshot=require_git_activity_snapshot,
64 )96 )
65 web_channel = WebChannel(97 web_channel = WebChannel(
66 web_config, _DummyBus(), agent_client=client,98 web_config, _DummyBus(), agent_client=client,
@@ -121,7 +153,7 @@ def assemble_web(
121 153 
122 _register_web_handlers(154 _register_web_handlers(
123 WebHandlersBindParams(155 WebHandlersBindParams(
124- channel=web_channel,156+ channel=_PersonalSettingsRegistration(web_channel) if personal_settings else web_channel,
125 agent_client=client,157 agent_client=client,
126 message_handler=message_handler,158 message_handler=message_handler,
127 channel_manager=channel_manager,159 channel_manager=channel_manager,
@@ -130,6 +162,7 @@ def assemble_web(
130 cron_controller=cron_controller,162 cron_controller=cron_controller,
131 heartbeat_controller=heartbeat_controller,163 heartbeat_controller=heartbeat_controller,
132 updater_service=updater_service,164 updater_service=updater_service,
165+ personal_settings=personal_settings,
133 )166 )
134 )167 )
135 168 
@@ -0,0 +1,119 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+ 
3+"""Bind controlled Cron handlers to the original connection business identity."""
4+ 
5+from __future__ import annotations
6+ 
7+import inspect
8+import json
9+from typing import Any
10+ 
11+from agent_gateway.application.worker_cron import requests_real_cron_project
12+ 
13+CRON_PANEL_METHODS = frozenset({
14+ 'cron.job.list', 'cron.job.meta', 'cron.job.get', 'cron.job.create',
15+ 'cron.job.update', 'cron.job.delete', 'cron.job.toggle',
16+ 'cron.job.preview', 'cron.job.run_now',
17+})
18+_CRON_MUTATION_METHODS = frozenset({'cron.job.create', 'cron.job.update'})
19+ 
20+ 
21+def bind_owned_cron_handlers(web_channel: Any, protocol_runtime: Any) -> None:
22+ """Keep legacy handlers, removing their anonymous payload-identity fallback.
23+ 
24+ The controlled personal path has no group or bot identity. The business user
25+ of the connection is the only owner a Cron request may act for: an anonymous
26+ connection cannot claim a payload user, and a non-default project is refused
27+ here, before a handler can ask the AgentServer to bind one. This guard is
28+ applied only when sharded Cron is explicitly assembled, never to single.
29+ """
30+ def bind(handler: Any, *, entry: str, method: str) -> Any:
31+ takes_user = 'user_id' in inspect.signature(handler).parameters
32+ 
33+ async def invoke(ws, req_id, params, session_id, user_id=None):
34+ del user_id
35+ if entry == 'web':
36+ owner = web_channel.connection_user_id(ws)
37+ else:
38+ owner = getattr(ws, '_gateway_user_id', None)
39+ owner = str(owner or '').strip()
40+ 
41+ async def reject(error: str, code: str) -> None:
42+ if entry == 'web':
43+ await web_channel.send_response(ws, req_id, ok=False, error=error, code=code)
44+ return
45+ send_response = getattr(protocol_runtime, 'send_response', None)
46+ if callable(send_response):
47+ await send_response(ws, req_id, ok=False, error=error, code=code)
48+ return
49+ await ws.send(json.dumps({
50+ 'type': 'res', 'id': req_id, 'ok': False,
51+ 'error': error, 'code': code,
52+ }))
53+ 
54+ if not owner or owner == 'default':
55+ await reject('Cron requires a named connection user', 'CRON_IDENTITY_REQUIRED')
56+ return
57+ if params is not None and not isinstance(params, dict):
58+ await reject('params must be object', 'BAD_REQUEST')
59+ return
60+ owned_params = dict(params or {})
61+ owned_params.update(user_id=owner, group_id='', bot_id='')
62+ if method in _CRON_MUTATION_METHODS:
63+ # A private credential-selection parameter is never accepted
64+ # from a client, and no connection session may put it back:
65+ # login models are not enabled for sharded Cron.
66+ owned_params.pop('_auth_session', None)
67+ target = owned_params
68+ if method == 'cron.job.update':
69+ patch = owned_params.get('patch')
70+ if isinstance(patch, dict):
71+ # The handler keeps its own patch-shape validation.
72+ owned_params['patch'] = target = dict(patch)
73+ target.pop('_auth_session', None)
74+ if requests_real_cron_project(target):
75+ await reject(
76+ 'Cron jobs for a non-default project are not enabled',
77+ 'CRON_PROJECT_DISABLED',
78+ )
79+ return
80+ try:
81+ if takes_user:
82+ await handler(ws, req_id, owned_params, session_id, user_id=owner)
83+ else:
84+ await handler(ws, req_id, owned_params, session_id)
85+ except KeyError:
86+ await reject('job not found', 'NOT_FOUND')
87+ except ValueError:
88+ # Validation text is not echoed: it may quote an upstream error.
89+ await reject('Cron request is not supported or invalid', 'BAD_REQUEST')
90+ except RuntimeError:
91+ await reject('Cron is unavailable', 'CRON_UNAVAILABLE')
92+ 
93+ return invoke
94+ 
95+ for method in CRON_PANEL_METHODS:
96+ handler = web_channel._method_handlers.get(method)
97+ if handler is not None:
98+ web_channel.register_method(method, bind(handler, entry='web', method=method))
99+ for route in protocol_runtime.config.routes.values():
100+ tui_channel = getattr(route, 'ws_channel', None)
101+ if tui_channel is not None:
102+ tui_channel.config.cron_owner_filter = True
103+ 
104+ async def register_cron_peer(ws, *, channel=tui_channel):
105+ from agent_gateway.routing.keys import AgentRef, RoutingKey
106+ 
107+ owner = str(getattr(ws, '_gateway_user_id', None) or '').strip()
108+ if not owner or owner == 'default':
109+ return
110+ await channel.register_ws(ws, RoutingKey(
111+ user_id=owner, channel_id='tui', app_id='default',
112+ agent_ref=AgentRef(mode='agent', id='default'), session_id='',
113+ ))
114+ 
115+ tui_channel.on_connect(register_cron_peer)
116+ for method in CRON_PANEL_METHODS:
117+ handler = route.local_handlers.get(method)
118+ if handler is not None:
119+ route.local_handlers[method] = bind(handler, entry='tui', method=method)
@@ -0,0 +1,232 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+ 
3+"""Execution-time Cron model validation against one target AgentServer."""
4+ 
5+from __future__ import annotations
6+ 
7+import asyncio
8+import math
9+import time
10+from typing import Any, Literal
11+import uuid
12+ 
13+from e2a.agent_models import AgentResponse
14+from e2a.gateway_normalize import e2a_from_agent_fields
15+from e2a.message import ReqMethod
16+ 
17+from agent_gateway.auth.model_catalog import LOGIN_MODEL_SOURCE
18+from agent_gateway.common.model_selection import ModelSelection
19+from agent_gateway.common.request_identity import apply_routing_metadata, normalize_routing_identity
20+from agent_gateway.routing.agent_request_timeout import send_agent_request_with_timeout
21+ 
22+CronModelSource = Literal["", "config", "zen"]
23+_SUPPORTED_SOURCES = frozenset({"config", "zen"})
24+ 
25+ 
26+class WorkerCronModelResolver:
27+ """Resolve and revalidate Cron models from the target AgentServer only.
28+ 
29+ The controller validates a model when a job is created or its model fields
30+ are edited. A stored job can outlive that check: its model may be removed,
31+ or a job disabled by single mode may be enabled again. This resolver repeats
32+ the same ``models.list`` based resolution before such a job runs.
33+ 
34+ Login models need an account credential binding that Worker Cron does not
35+ have, so they are refused here; an AgentOS model row is refused as an
36+ unsupported source as well. No model name, selection or credential is
37+ cached between calls, and the local model config is never read.
38+ """
39+ 
40+ def __init__(self, agent_client: Any, *, timeout_seconds: float = 5.0) -> None:
41+ try:
42+ timeout = float(timeout_seconds)
43+ except (TypeError, ValueError) as exc:
44+ raise ValueError("timeout_seconds must be positive and finite") from exc
45+ if not math.isfinite(timeout) or timeout <= 0:
46+ raise ValueError("timeout_seconds must be positive and finite")
47+ self._agent_client = agent_client
48+ self._timeout_seconds = timeout
49+ 
50+ async def __call__(
51+ self,
52+ raw: Any,
53+ *,
54+ model_selection: Any = None,
55+ user_id: str | None = None,
56+ ) -> tuple[str | None, CronModelSource]:
57+ selection = self._normalize_selection(model_selection)
58+ raw_value = raw.strip() if isinstance(raw, str) else ""
59+ payload = await self._request_catalog(user_id)
60+ 
61+ if selection is not None:
62+ model_name, source = self._match(payload, selection["id"])
63+ self._validate_supported_source(source)
64+ return model_name, source
65+ 
66+ if raw_value:
67+ model_name, source = self._match(payload, raw_value)
68+ self._validate_supported_source(source)
69+ return model_name, source
70+ 
71+ # Without an explicit model the AgentServer picks its active default.
72+ # ``is_default`` only marks dropdown visibility, so it cannot tell
73+ # which model would actually run. An unknown active model is refused.
74+ active_source = self._active_source(payload)
75+ if active_source == "login":
76+ raise ValueError("Cron default login model requires explicit model selection")
77+ self._validate_supported_source(active_source)
78+ return None, ""
79+ 
80+ async def validate_job(self, job: Any) -> tuple[str | None, CronModelSource]:
81+ """Fail closed unless every stored model reference still resolves."""
82+ if str(getattr(job, "credential_ref", "") or "").strip():
83+ raise ValueError("Cron login models are not enabled")
84+ return await self(
85+ getattr(job, "model_name", None),
86+ model_selection=getattr(job, "model_selection", None),
87+ user_id=getattr(job, "user_id", None),
88+ )
89+ 
90+ @staticmethod
91+ def _normalize_selection(value: Any) -> dict[str, Any] | None:
92+ if value is None:
93+ return None
94+ selection = ModelSelection.model_validate(value)
95+ if selection.type != "model":
96+ raise ValueError("Scheduled tasks only support a single model")
97+ return selection.model_dump()
98+ 
99+ async def _request_catalog(self, user_id: str | None) -> dict[str, Any]:
100+ """Read the target catalog once, bounded in time.
101+ 
102+ This call site deliberately bypasses the shared unary forward helper:
103+ that helper logs the transport exception text, and a WebSocket close
104+ carries an AgentServer-chosen reason verbatim. The request holds no
105+ credential and the response holds model configuration, so neither the
106+ exception nor its text is logged, chained or returned from here.
107+ """
108+ if self._agent_client is None:
109+ raise ValueError("Cron model catalog unavailable")
110+ identity = normalize_routing_identity(
111+ {"user_id": user_id or "", "group_id": "", "bot_id": ""}
112+ )
113+ envelope = e2a_from_agent_fields(
114+ request_id=f"cron-models-{uuid.uuid4().hex}",
115+ channel_id="web",
116+ session_id=None,
117+ req_method=ReqMethod.MODELS_LIST,
118+ params={},
119+ is_stream=False,
120+ timestamp=time.time(),
121+ user_id=user_id or None,
122+ metadata=apply_routing_metadata(None, identity),
123+ )
124+ failed = False
125+ try:
126+ async with asyncio.timeout(self._timeout_seconds):
127+ response = await send_agent_request_with_timeout(
128+ self._agent_client, envelope, label="models.list",
129+ )
130+ except Exception:
131+ failed = True
132+ # Raised outside ``except`` so the transport exception is not kept as
133+ # implicit context either.
134+ if failed:
135+ raise ValueError("Cron model catalog unavailable")
136+ if (
137+ not isinstance(response, AgentResponse)
138+ or response.request_id != envelope.request_id
139+ or response.channel_id != envelope.channel
140+ ):
141+ raise ValueError("Cron model catalog protocol error")
142+ if not response.ok:
143+ raise ValueError("Cron model catalog unavailable")
144+ self._validate_payload(response.payload)
145+ return response.payload
146+ 
147+ @staticmethod
148+ def _validate_payload(payload: Any) -> None:
149+ if (
150+ type(payload) is not dict
151+ or type(payload.get("models")) is not list
152+ or type(payload.get("active_model")) is not str
153+ or any(type(row) is not dict for row in payload["models"])
154+ ):
155+ raise ValueError("Cron model catalog protocol error")
156+ 
157+ @classmethod
158+ def _match(cls, payload: dict[str, Any], value: str) -> tuple[str | None, str]:
159+ matches: list[tuple[dict[str, Any], str]] = []
160+ for row in payload["models"]:
161+ if not cls._valid_model_row(row):
162+ continue
163+ if value in cls._row_values(row):
164+ matches.append((row, cls._row_source(row)))
165+ # A configured model wins over a same-named free or login entry.
166+ for source in ("config", "zen"):
167+ for row, row_source in matches:
168+ if row_source == source:
169+ return cls._text(row.get("model_name")) or None, source
170+ for row, row_source in matches:
171+ if row_source in {"login", "agentos"}:
172+ return cls._text(row.get("model_name")) or None, row_source
173+ return None, ""
174+ 
175+ @classmethod
176+ def _active_source(cls, payload: dict[str, Any]) -> str:
177+ active_model = cls._text(payload.get("active_model"))
178+ if not active_model:
179+ return ""
180+ for row in payload["models"]:
181+ if not cls._valid_model_row(row):
182+ continue
183+ if active_model in cls._row_values(row):
184+ return cls._row_source(row)
185+ return ""
186+ 
187+ @staticmethod
188+ def _row_source(row: dict[str, Any]) -> str:
189+ if row.get("source") == LOGIN_MODEL_SOURCE:
190+ return "login"
191+ if row.get("is_agentos") is True:
192+ return "agentos"
193+ if row.get("is_free") is True:
194+ return "zen"
195+ return "config"
196+ 
197+ @staticmethod
198+ def _valid_model_row(row: dict[str, Any]) -> bool:
199+ model_name = row.get("model_name")
200+ is_agentos = row.get("is_agentos")
201+ is_free = row.get("is_free")
202+ source = row.get("source")
203+ model_id = row.get("model_id")
204+ alias = row.get("alias")
205+ return (
206+ isinstance(model_name, str)
207+ and bool(model_name.strip())
208+ and (is_agentos is None or isinstance(is_agentos, bool))
209+ and (is_free is None or isinstance(is_free, bool))
210+ and (source is None or isinstance(source, str))
211+ and (model_id is None or isinstance(model_id, str))
212+ and (alias is None or isinstance(alias, str))
213+ )
214+ 
215+ @classmethod
216+ def _row_values(cls, row: dict[str, Any]) -> set[str]:
217+ values = {
218+ cls._text(row.get("model_name")),
219+ cls._text(row.get("alias")),
220+ cls._text(row.get("model_id")),
221+ }
222+ return {value for value in values if value}
223+ 
224+ @staticmethod
225+ def _text(value: Any) -> str:
226+ return value.strip() if isinstance(value, str) else ""
227+ 
228+ def _validate_supported_source(self, source: str) -> None:
229+ if source == "login":
230+ raise ValueError("Cron login models are not enabled")
231+ if source not in _SUPPORTED_SOURCES:
232+ raise ValueError("Unknown cron model")
Aagent_gateway/application/worker_data.py+454-0File content is under review, please try again later
@@ -0,0 +1,208 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+"""Supervise the fixed Worker pool, loopback listeners and optional authorities.
3+ 
4+With ``cron=True`` the group also owns the sharded personal Cron runtime. The
5+parent runs the read-only preflight before any Worker starts, prepares every
6+slot, activates all shards together and only then opens the listeners.
7+"""
8+ 
9+from __future__ import annotations
10+ 
11+import asyncio
12+from collections.abc import Callable
13+import logging
14+import math
15+import socket
16+from urllib.parse import urlsplit
17+ 
18+from agent_gateway.application.cron_preflight import require_controlled_cron
19+from agent_gateway.common.ingress_identity import LocalIdentityPolicy
20+from agent_gateway.common.worker_affinity import FixedUserHash, WorkerManifest
21+from agent_gateway.enterprise import is_enterprise
22+from agent_gateway.processes.pool import WorkerPool
23+from agent_gateway.transport.connection_acceptor import ConnectionAcceptor
24+ 
25+logger = logging.getLogger("gateway")
26+ 
27+ 
28+class WorkerGroup:
29+ """The parent owns admission and supervises one fixed generation."""
30+ 
31+ def __init__(
32+ self, agent_server_url: str, *, workers: int, web_port: int = 19000,
33+ protocol_port: int = 19001, handoff_timeout: float = 2,
34+ auth_service_provider: Callable | None = None,
35+ cron: bool = False,
36+ ) -> None:
37+ url = urlsplit(agent_server_url)
38+ if (is_enterprise() or url.scheme != "ws" or not url.port
39+ or url.netloc != f"127.0.0.1:{url.port}" or url.query or url.fragment):
40+ raise ValueError("the Worker group only supports personal loopback with a single local AgentServer")
41+ if not math.isfinite(handoff_timeout) or handoff_timeout <= 0:
42+ raise ValueError("handoff timeout must be finite and positive")
43+ if type(cron) is not bool:
44+ raise ValueError("cron must be an explicit boolean")
45+ if type(workers) is not int or not 1 <= workers <= 32:
46+ raise ValueError("number of Workers must be between 1 and 32")
47+ self._credential_authority = self._control_web = None
48+ self._cron_ownership = self._cron_commands = None
49+ if cron:
50+ from agent_gateway.cron.control_commands import ControlCronCommands
51+ from agent_gateway.cron.ownership import CronOwnership
52+ 
53+ # Ownership follows the configured slots, never the healthy subset.
54+ self._cron_ownership = CronOwnership(WorkerManifest(tuple(range(workers))), LocalIdentityPolicy())
55+ self._cron_commands = ControlCronCommands(self._cron_ownership, agent_server_url)
56+ control_services = None
57+ if auth_service_provider is not None or self._cron_commands is not None:
58+ from agent_gateway.processes.control_service import ControlServices
59+ 
60+ factories, connects, disconnects = [], [], []
61+ if auth_service_provider is not None:
62+ from agent_gateway.auth.control_credentials import ControlCredentialServices
63+ 
64+ authority = self._credential_authority = ControlCredentialServices(
65+ auth_service_provider, server_id=agent_server_url, enable_public_catalog=True,
66+ )
67+ factories.append(authority.handlers_for)
68+ connects.append(authority.endpoint_connected)
69+ disconnects.append(authority.endpoint_disconnected)
70+ if self._cron_commands is not None:
71+ factories.append(self._cron_commands.handlers_for)
72+ connects.append(self._cron_commands.endpoint_connected)
73+ disconnects.append(self._cron_commands.endpoint_disconnected)
74+ 
75+ def handlers_for(identity):
76+ merged: dict = {}
77+ for factory in factories:
78+ handlers = dict(factory(identity))
79+ reserved = merged.keys() & handlers.keys()
80+ if reserved:
81+ raise ValueError(f"control operations are reserved twice: {sorted(reserved)}")
82+ merged.update(handlers)
83+ return merged
84+ 
85+ def run_all(callbacks):
86+ def invoke(*arguments):
87+ for callback in callbacks:
88+ callback(*arguments)
89+ return invoke
90+ 
91+ control_services = ControlServices(
92+ handlers_factory=handlers_for, on_connect=run_all(connects),
93+ on_disconnect=run_all(disconnects),
94+ )
95+ self.pool = WorkerPool(
96+ agent_server_url, workers, control_services=control_services,
97+ cron_manifest=self._cron_ownership.manifest if self._cron_ownership is not None else None,
98+ account_services=auth_service_provider is not None,
99+ )
100+ self._ports = (web_port, protocol_port)
101+ self._handoff_timeout = handoff_timeout
102+ self._acceptors: list[ConnectionAcceptor] = []
103+ self._monitor: asyncio.Task | None = None
104+ self._started = False
105+ self._close_task: asyncio.Task | None = None
106+ self.addresses: tuple[tuple[str, int], ...] = ()
107+ 
108+ async def start(self) -> None:
109+ if self._close_task is not None or self._started:
110+ raise RuntimeError("Worker group is single-use")
111+ self._started = True
112+ try:
113+ if self._cron_ownership is not None:
114+ # Read-only and parent-side: no Worker is spawned while an
115+ # enabled record still needs a capability this batch lacks.
116+ await require_controlled_cron(self._cron_ownership)
117+ if self._credential_authority is not None:
118+ await self._credential_authority.prepare()
119+ await self._start_control_web()
120+ await self.pool.start()
121+ if self._cron_ownership is not None:
122+ await self.pool.activate_cron()
123+ if self._close_task is not None:
124+ raise RuntimeError("Worker group stopped during startup")
125+ affinity = FixedUserHash(WorkerManifest(self.pool.slots), LocalIdentityPolicy())
126+ addresses = []
127+ for index, port in enumerate(self._ports):
128+ listener = socket.socket()
129+ try:
130+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
131+ listener.bind(("127.0.0.1", port))
132+ listener.listen()
133+ listener.setblocking(False)
134+ addresses.append(listener.getsockname())
135+ self._acceptors.append(ConnectionAcceptor(
136+ listener, protocol_port=index == 1, affinity=affinity, handoff=self.pool.handoff,
137+ handoff_timeout=self._handoff_timeout,
138+ control_http=(self._control_web.adopt if index == 0 and self._control_web is not None else None),
139+ ))
140+ except BaseException:
141+ listener.close()
142+ raise
143+ self.addresses = tuple(addresses)
144+ for acceptor in self._acceptors:
145+ acceptor.start()
146+ self._monitor = asyncio.create_task(self._watch(), name="gateway-watch-worker-group")
147+ if self._cron_ownership is not None:
148+ logger.info("[App] multiprocess_cron_ready workers=%d", len(self.pool.slots))
149+ except BaseException:
150+ await self.stop()
151+ raise
152+ 
153+ async def _start_control_web(self) -> None:
154+ from fastapi import FastAPI
155+ from agent_gateway.channel_manager.web.web_http_auth import register_auth_routes
156+ from agent_gateway.transport.web_protocol_runtime import WebProtocolRuntime
157+ 
158+ authority = self._credential_authority
159+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, redirect_slashes=False)
160+ register_auth_routes(app, auth_service_provider=lambda: authority.prepared_service,
161+ logout_callback=authority.logout)
162+ self._control_web = WebProtocolRuntime(app, ws_per_message_deflate=False, single_request_http=True)
163+ await self._control_web.start()
164+ 
165+ async def _watch(self) -> Exception | None:
166+ waiters = [self.pool.wait, *(acceptor.wait for acceptor in self._acceptors)]
167+ if self._control_web is not None:
168+ waiters.append(self._control_web.wait_closed)
169+ tasks = [asyncio.create_task(wait()) for wait in waiters]
170+ try:
171+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
172+ for task in done:
173+ if not task.cancelled():
174+ task.result()
175+ except Exception as error:
176+ return error
177+ finally:
178+ for task in tasks:
179+ task.cancel()
180+ await asyncio.gather(*tasks, return_exceptions=True)
181+ await self.stop()
182+ return None
183+ 
184+ async def wait(self) -> None:
185+ if self._monitor is None:
186+ raise RuntimeError("Worker group was not started")
187+ error = await asyncio.shield(self._monitor)
188+ if error is not None:
189+ raise error
190+ 
191+ async def stop(self) -> None:
192+ if self._close_task is None:
193+ self._close_task = asyncio.create_task(self._close(), name="gateway-stop-worker-group")
194+ await asyncio.shield(self._close_task)
195+ 
196+ async def _close(self) -> None:
197+ try:
198+ await asyncio.gather(*(acceptor.stop() for acceptor in self._acceptors))
199+ finally:
200+ try:
201+ if self._control_web is not None:
202+ await self._control_web.stop()
203+ finally:
204+ try:
205+ await self.pool.stop()
206+ finally:
207+ if self._credential_authority is not None:
208+ await self._credential_authority.stop()
@@ -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
@@ -0,0 +1,540 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
2+"""Explicit Control-owned credential handlers; not a production account switch."""
3+ 
4+from __future__ import annotations
5+ 
6+import asyncio
7+from collections.abc import Callable, Mapping
8+from concurrent.futures import Future
9+from dataclasses import dataclass
10+from functools import partial
11+import hashlib
12+import hmac
13+import secrets
14+from types import MappingProxyType
15+from typing import Any, TYPE_CHECKING
16+ 
17+from agent_gateway.auth.credential_access import ModelCredential
18+from agent_gateway.auth.control_blocking_work import ControlBlockingWork
19+from agent_gateway.auth.credential_issuance import CredentialIssuanceRegistry, CredentialTarget
20+from agent_gateway.auth.local_credential_access import (
21+ LocalCredentialAccess,
22+ LocalCredentialResult,
23+ LocalCredentialSnapshot,
24+)
25+from agent_gateway.auth.session_login_bindings import LocalSessionLoginBindings
26+from agent_gateway.processes.control_service import ControlServiceBusy, ControlServiceIdentity, Handler
27+ 
28+if TYPE_CHECKING:
29+ from agent_gateway.auth.service import AuthService
30+ from agent_gateway.auth.session_store import AuthSessionStore
31+ 
32+ 
33+def _fields(value: object, names: set[str]) -> dict[str, Any]:
34+ if not isinstance(value, dict) or set(value) != names:
35+ raise ValueError('invalid credential service value')
36+ return value
37+ 
38+ 
39+def _text(value: object, limit: int, *, empty: bool = False) -> str:
40+ if not isinstance(value, str) or len(value) > limit or (not empty and not value.strip()):
41+ raise ValueError('invalid credential service value')
42+ return value
43+ 
44+ 
45+def _ref(value: object) -> str:
46+ from agent_gateway.auth.login_credentials import is_credential_ref
47+ 
48+ result = _text(value, 32)
49+ if not is_credential_ref(result):
50+ raise ValueError('invalid credential service value')
51+ return result
52+ 
53+ 
54+def _credential(value: ModelCredential | None) -> dict[str, Any]:
55+ if value is None:
56+ return {'status': 'invalid'}
57+ return {'status': 'ok', 'credential': {
58+ 'api_base': _text(value.api_base, 2048),
59+ 'api_key': _text(value.api_key, 4096),
60+ 'credential_ref': _ref(value.credential_ref),
61+ }}
62+ 
63+ 
64+@dataclass(frozen=True)
65+class _SessionSnapshot:
66+ """Immutable identity facts captured by a bounded store read."""
67+ 
68+ store: AuthSessionStore
69+ session_id: str
70+ user_id: str
71+ created_at: float
72+ credential_ref: str
73+ epoch: str
74+ 
75+ 
76+@dataclass(frozen=True)
77+class _CredentialRead:
78+ """Immutable credential facts captured by a bounded store read."""
79+ 
80+ id_token: str
81+ expired: bool
82+ 
83+ 
84+@dataclass(frozen=True)
85+class _SessionRead:
86+ """A mutable session object plus the immutable commit identity."""
87+ 
88+ snapshot: _SessionSnapshot
89+ session: Any
90+ credential: _CredentialRead
91+ 
92+ 
93+@dataclass(frozen=True)
94+class _RefreshWork:
95+ """A shared explicit refresh submitted to the real bounded pool."""
96+ 
97+ future: Future
98+ 
99+ 
100+class ControlCredentialServices:
Magent_gateway/channel_manager/web/app_web_handlers.py+66-6File content is under review, please try again later
Magent_gateway/channel_manager/web/web_connect.py+9-2File content is under review, please try again later
Magent_gateway/message_handler/message_handler.py+165-19File content is under review, please try again later
Aagent_gateway/processes/pool.py+406-0File content is under review, please try again later
Magent_gateway/routing/e2a_proxy.py+63-1File content is under review, please try again later
Magent_gateway/routing/protocol_runtime.py+9-0File content is under review, please try again later
Magent_gateway/southbound/data/transport.py+27-6File content is under review, please try again later
Magent_gateway/southbound/data/websocket.py+112-28File content is under review, please try again later
Aagent_gateway/transport/protocol_connection_runtime.py+357-0File content is under review, please try again later
Mdocs/en/reference/cli-and-environment.md+14-0File content is under review, please try again later
Mdocs/zh/reference/cli-and-environment.md+14-0File content is under review, please try again later
Atests/integration/gateway/test_worker_cron_group.py+580-0File content is under review, please try again later
Atests/unit_tests/gateway/test_personal_project_git.py+196-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_commands.py+1287-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_cron_workspace.py+333-0File content is under review, please try again later
Atests/unit_tests/gateway/test_worker_listener_gates.py+87-0File content is under review, please try again later