forgexa-cli 1.95.2__tar.gz → 1.96.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/PKG-INFO +1 -1
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/__init__.py +1 -1
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/agent_core.py +129 -50
- forgexa_cli-1.96.1/forgexa_cli/component_runtime.py +634 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/daemon.py +71 -5
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/observability_contract.py +8 -8
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/zcode_protocol.py +20 -1
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/PKG-INFO +1 -1
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/SOURCES.txt +1 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/pyproject.toml +1 -1
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/README.md +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/_build_config.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/_local_bind.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/autoupgrade.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/aws_evidence.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/aws_logs_evidence.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/main.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/observability_evidence.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/py.typed +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli/runtime_evidence.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/dependency_links.txt +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/entry_points.txt +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/requires.txt +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/forgexa_cli.egg-info/top_level.txt +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/setup.cfg +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_auth_and_runtime_commands.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_autoupgrade.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_check_command.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_expiry_warnings_and_revoke.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_local_bind_commands.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_publish_script.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_runtime_credentials.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_session_credentials.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_silent_install.py +0 -0
- {forgexa_cli-1.95.2 → forgexa_cli-1.96.1}/tests/test_upgrade_observability.py +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"""forgexa-cli — Forgexa command-line client."""
|
|
2
|
-
__version__ = "1.
|
|
2
|
+
__version__ = "1.96.1"
|
|
@@ -60,6 +60,17 @@ from fnmatch import fnmatchcase
|
|
|
60
60
|
from pathlib import Path, PurePosixPath
|
|
61
61
|
from typing import Any, Awaitable, Callable, Literal
|
|
62
62
|
|
|
63
|
+
# The import shim covers the backend package layout (app.component_runtime),
|
|
64
|
+
# the CLI package layout (forgexa_cli.component_runtime) and the flat mirror
|
|
65
|
+
# layout (component_runtime next to daemon.py in the desktop app's resources).
|
|
66
|
+
try:
|
|
67
|
+
from app import component_runtime
|
|
68
|
+
except ImportError:
|
|
69
|
+
try:
|
|
70
|
+
from . import component_runtime # type: ignore[no-redef] # CLI package layout
|
|
71
|
+
except ImportError:
|
|
72
|
+
import component_runtime # type: ignore[no-redef] # flat script layout
|
|
73
|
+
|
|
63
74
|
# fcntl is Unix-only; on Windows we use msvcrt instead (see acquire_file_lock)
|
|
64
75
|
try:
|
|
65
76
|
import fcntl
|
|
@@ -1283,6 +1294,8 @@ class DiscoveredAgent:
|
|
|
1283
1294
|
compatibility_level: str
|
|
1284
1295
|
min_version_ok: bool = True
|
|
1285
1296
|
version_warning: str = ""
|
|
1297
|
+
installation_id: str | None = None
|
|
1298
|
+
selection_revision: int | None = None
|
|
1286
1299
|
|
|
1287
1300
|
|
|
1288
1301
|
def _prepare_agent_command(
|
|
@@ -2180,61 +2193,106 @@ class AgentDiscovery:
|
|
|
2180
2193
|
async def discover(self) -> list[DiscoveredAgent]:
|
|
2181
2194
|
self._expand_path()
|
|
2182
2195
|
# Probe bwrap support once at discovery time and log a clear warning
|
|
2183
|
-
# if it is broken.
|
|
2196
|
+
# if it is broken. This surfaces the error early rather than mid-task.
|
|
2184
2197
|
await self._probe_bwrap_support()
|
|
2185
2198
|
available = []
|
|
2186
2199
|
for agent_id, spec in self.AGENT_REGISTRY.items():
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
if
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
if
|
|
2202
|
-
|
|
2203
|
-
# not properly installed (e.g. copilot prompts to install).
|
|
2204
|
-
logger.warning(
|
|
2205
|
-
"Agent %s found at %s but version check failed — skipping. "
|
|
2206
|
-
"Likely an uninitialized first-run stub (e.g. GitHub Copilot CLI "
|
|
2207
|
-
"prompts \"Install GitHub Copilot CLI? [y/N]\"): run it once in a "
|
|
2208
|
-
"terminal, complete the setup/login, then restart the daemon.",
|
|
2209
|
-
agent_id, resolved,
|
|
2210
|
-
)
|
|
2211
|
-
continue
|
|
2212
|
-
min_version_ok, version_warning = _check_agent_min_version(agent_id, version, spec)
|
|
2213
|
-
verification_issue = await asyncio.to_thread(_agent_discovery_verification_issue, agent_id, resolved)
|
|
2214
|
-
if agent_id == "opencode" and min_version_ok:
|
|
2215
|
-
verification_issue = opencode_platform_issue(opencode_cli_profile(version))
|
|
2216
|
-
if verification_issue:
|
|
2217
|
-
min_version_ok = False
|
|
2218
|
-
version_warning = verification_issue
|
|
2219
|
-
if not min_version_ok:
|
|
2220
|
-
logger.warning(
|
|
2221
|
-
"Agent %s found at %s (v%s) but below minimum version: %s",
|
|
2222
|
-
agent_id, resolved, version, version_warning,
|
|
2223
|
-
)
|
|
2224
|
-
available.append(DiscoveredAgent(
|
|
2225
|
-
agent_id=agent_id,
|
|
2226
|
-
command=resolved,
|
|
2227
|
-
version=version,
|
|
2228
|
-
invoke_modes=spec["invoke_modes"],
|
|
2229
|
-
compatibility_level=spec["compatibility_level"],
|
|
2230
|
-
min_version_ok=min_version_ok,
|
|
2231
|
-
version_warning=version_warning,
|
|
2232
|
-
))
|
|
2233
|
-
logger.info("Discovered agent: %s v%s (%s)", agent_id, version, resolved)
|
|
2200
|
+
managed = None
|
|
2201
|
+
try:
|
|
2202
|
+
managed = await asyncio.to_thread(
|
|
2203
|
+
component_runtime.acquire_component,
|
|
2204
|
+
agent_id,
|
|
2205
|
+
None,
|
|
2206
|
+
os.environ.get(spec.get("env_path_override", "")),
|
|
2207
|
+
)
|
|
2208
|
+
discovered = await self._discover_instance(agent_id, spec, managed)
|
|
2209
|
+
if discovered is not None:
|
|
2210
|
+
available.append(discovered)
|
|
2211
|
+
except component_runtime.ComponentRuntimeError as error:
|
|
2212
|
+
logger.warning("Managed agent %s is unavailable: %s", agent_id, error.code)
|
|
2213
|
+
finally:
|
|
2214
|
+
if managed is not None:
|
|
2215
|
+
await asyncio.to_thread(managed.close)
|
|
2234
2216
|
return available
|
|
2235
2217
|
|
|
2218
|
+
async def _discover_instance(
|
|
2219
|
+
self, agent_id: str, spec: dict, managed: Any = None
|
|
2220
|
+
) -> DiscoveredAgent | None:
|
|
2221
|
+
custom_path = os.environ.get(spec.get("env_path_override", ""))
|
|
2222
|
+
cmd = managed.argv_prefix[-1] if managed is not None else custom_path or spec["commands"][0]
|
|
2223
|
+
resolved = shutil.which(cmd)
|
|
2224
|
+
if resolved:
|
|
2225
|
+
issue = await asyncio.to_thread(self._wsl_execution_issue, resolved)
|
|
2226
|
+
if issue:
|
|
2227
|
+
logger.warning(
|
|
2228
|
+
"Agent %s has an unavailable Linux-side WSL toolchain; skipping", agent_id
|
|
2229
|
+
)
|
|
2230
|
+
return None
|
|
2231
|
+
version = (
|
|
2232
|
+
await self._get_version(spec["detect"], resolved)
|
|
2233
|
+
if managed is None
|
|
2234
|
+
else await self._get_version(spec["detect"], resolved, managed)
|
|
2235
|
+
)
|
|
2236
|
+
if version is None and "detect_alt" in spec:
|
|
2237
|
+
# Primary detect command failed; try the alternative.
|
|
2238
|
+
# Example: new GitHub Copilot CLI 1.0.x uses `copilot version`
|
|
2239
|
+
# as a subcommand while older releases used `copilot --version`.
|
|
2240
|
+
version = (
|
|
2241
|
+
await self._get_version(spec["detect_alt"], resolved)
|
|
2242
|
+
if managed is None
|
|
2243
|
+
else await self._get_version(spec["detect_alt"], resolved, managed)
|
|
2244
|
+
)
|
|
2245
|
+
if version is None:
|
|
2246
|
+
# Binary found but version check failed — it is a stub or
|
|
2247
|
+
# not properly installed (e.g. copilot prompts to install).
|
|
2248
|
+
logger.warning(
|
|
2249
|
+
"Agent %s found at %s but version check failed — skipping. "
|
|
2250
|
+
"Likely an uninitialized first-run stub (e.g. GitHub Copilot CLI "
|
|
2251
|
+
'prompts "Install GitHub Copilot CLI? [y/N]"): run it once in a '
|
|
2252
|
+
"terminal, complete the setup/login, then restart the daemon.",
|
|
2253
|
+
agent_id,
|
|
2254
|
+
resolved,
|
|
2255
|
+
)
|
|
2256
|
+
return None
|
|
2257
|
+
min_version_ok, version_warning = _check_agent_min_version(agent_id, version, spec)
|
|
2258
|
+
verification_issue = await asyncio.to_thread(
|
|
2259
|
+
_agent_discovery_verification_issue, agent_id, resolved
|
|
2260
|
+
)
|
|
2261
|
+
if agent_id == "opencode" and min_version_ok:
|
|
2262
|
+
verification_issue = opencode_platform_issue(opencode_cli_profile(version))
|
|
2263
|
+
if verification_issue:
|
|
2264
|
+
min_version_ok = False
|
|
2265
|
+
version_warning = verification_issue
|
|
2266
|
+
if not min_version_ok:
|
|
2267
|
+
logger.warning(
|
|
2268
|
+
"Agent %s found at %s (v%s) but below minimum version: %s",
|
|
2269
|
+
agent_id,
|
|
2270
|
+
resolved,
|
|
2271
|
+
version,
|
|
2272
|
+
version_warning,
|
|
2273
|
+
)
|
|
2274
|
+
discovered = DiscoveredAgent(
|
|
2275
|
+
agent_id=agent_id,
|
|
2276
|
+
command=resolved,
|
|
2277
|
+
version=version,
|
|
2278
|
+
invoke_modes=spec["invoke_modes"],
|
|
2279
|
+
compatibility_level=spec["compatibility_level"],
|
|
2280
|
+
min_version_ok=min_version_ok,
|
|
2281
|
+
version_warning=version_warning,
|
|
2282
|
+
installation_id=managed.receipt["installation_id"] if managed is not None else None,
|
|
2283
|
+
selection_revision=managed.selection_revision if managed is not None else None,
|
|
2284
|
+
)
|
|
2285
|
+
logger.info("Discovered agent: %s v%s (%s)", agent_id, version, resolved)
|
|
2286
|
+
if managed is not None:
|
|
2287
|
+
await asyncio.to_thread(managed.verify)
|
|
2288
|
+
return discovered
|
|
2289
|
+
return None
|
|
2290
|
+
|
|
2236
2291
|
async def _get_version(
|
|
2237
|
-
self,
|
|
2292
|
+
self,
|
|
2293
|
+
detect_cmd: str,
|
|
2294
|
+
executable: str | None = None,
|
|
2295
|
+
managed: Any = None,
|
|
2238
2296
|
) -> str | None:
|
|
2239
2297
|
"""Run <detect_cmd> and return the first line of output as a version string.
|
|
2240
2298
|
|
|
@@ -2244,9 +2302,19 @@ class AgentDiscovery:
|
|
|
2244
2302
|
"binary found but not functional".
|
|
2245
2303
|
"""
|
|
2246
2304
|
import re
|
|
2305
|
+
|
|
2247
2306
|
probe_dir = None
|
|
2248
2307
|
proc = None
|
|
2249
2308
|
try:
|
|
2309
|
+
active_component = component_runtime.current_execution()
|
|
2310
|
+
if (
|
|
2311
|
+
managed is None
|
|
2312
|
+
and active_component is not None
|
|
2313
|
+
and executable == active_component.argv_prefix[-1]
|
|
2314
|
+
):
|
|
2315
|
+
managed = active_component
|
|
2316
|
+
if managed is not None:
|
|
2317
|
+
await asyncio.to_thread(managed.verify)
|
|
2250
2318
|
parts = detect_cmd.split()
|
|
2251
2319
|
if executable:
|
|
2252
2320
|
parts[0] = executable
|
|
@@ -2254,6 +2322,8 @@ class AgentDiscovery:
|
|
|
2254
2322
|
resolved = shutil.which(parts[0])
|
|
2255
2323
|
if resolved:
|
|
2256
2324
|
parts[0] = resolved
|
|
2325
|
+
if managed is not None:
|
|
2326
|
+
parts = managed.wrap_command(parts)
|
|
2257
2327
|
parts = _prepare_agent_command(parts, preserve_argv=False)
|
|
2258
2328
|
env = None
|
|
2259
2329
|
if detect_cmd == "dsh --version":
|
|
@@ -2262,17 +2332,26 @@ class AgentDiscovery:
|
|
|
2262
2332
|
probe_dir = tempfile.TemporaryDirectory(prefix="forgexa-minimax-probe-")
|
|
2263
2333
|
env = minimax_base_env(Path(probe_dir.name), Path(probe_dir.name))
|
|
2264
2334
|
if detect_cmd in ("opencode --version", "mimo --version"):
|
|
2265
|
-
probe_dir = tempfile.TemporaryDirectory(
|
|
2335
|
+
probe_dir = tempfile.TemporaryDirectory(
|
|
2336
|
+
prefix=f"forgexa-{detect_cmd.split()[0]}-probe-"
|
|
2337
|
+
)
|
|
2266
2338
|
env = os.environ.copy()
|
|
2267
2339
|
env.update(TMPDIR=probe_dir.name, BUN_TMPDIR=probe_dir.name)
|
|
2340
|
+
if managed is not None:
|
|
2341
|
+
if probe_dir is None:
|
|
2342
|
+
probe_dir = tempfile.TemporaryDirectory(prefix="forgexa-managed-discovery-")
|
|
2343
|
+
env = managed.probe_environment(Path(probe_dir.name), env)
|
|
2268
2344
|
proc = await asyncio.create_subprocess_exec(
|
|
2269
2345
|
*parts,
|
|
2270
2346
|
stdin=asyncio.subprocess.DEVNULL,
|
|
2271
2347
|
stdout=asyncio.subprocess.PIPE,
|
|
2272
2348
|
stderr=asyncio.subprocess.PIPE,
|
|
2273
2349
|
env=env,
|
|
2350
|
+
cwd=probe_dir.name if managed is not None else None,
|
|
2274
2351
|
**_agent_process_group_kwargs(),
|
|
2275
2352
|
)
|
|
2353
|
+
if managed is not None and managed is component_runtime.current_execution():
|
|
2354
|
+
managed.process_started = True
|
|
2276
2355
|
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=10)
|
|
2277
2356
|
if proc.returncode != 0:
|
|
2278
2357
|
logger.warning(
|
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import stat
|
|
10
|
+
import struct
|
|
11
|
+
import sys
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from contextvars import ContextVar
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
RECORD_LIMIT = 8 * 1024 * 1024
|
|
18
|
+
IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
19
|
+
DIGEST = re.compile(r"^[0-9a-f]{64}$")
|
|
20
|
+
_EXECUTION_LEASE: ContextVar[ManagedComponentLease | None] = ContextVar(
|
|
21
|
+
"forgexa_component_execution_lease",
|
|
22
|
+
default=None,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ComponentRuntimeError(RuntimeError):
|
|
27
|
+
def __init__(self, code: str) -> None:
|
|
28
|
+
self.code = code
|
|
29
|
+
super().__init__(code)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _identifier(value: Any) -> str:
|
|
33
|
+
if not isinstance(value, str) or not IDENTIFIER.fullmatch(value) or ".." in value:
|
|
34
|
+
raise ComponentRuntimeError("component_record_invalid")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _private_directory(path: Path) -> None:
|
|
39
|
+
if os.name != "posix":
|
|
40
|
+
raise ComponentRuntimeError("component_platform_unverified")
|
|
41
|
+
metadata = path.lstat()
|
|
42
|
+
if (
|
|
43
|
+
not stat.S_ISDIR(metadata.st_mode)
|
|
44
|
+
or metadata.st_uid != os.getuid()
|
|
45
|
+
or metadata.st_mode & 0o077
|
|
46
|
+
):
|
|
47
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _record(path: Path, fields: set[str]) -> dict[str, Any] | None:
|
|
51
|
+
try:
|
|
52
|
+
descriptor = os.open(
|
|
53
|
+
path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
54
|
+
)
|
|
55
|
+
except FileNotFoundError:
|
|
56
|
+
return None
|
|
57
|
+
with os.fdopen(descriptor, "rb") as stream:
|
|
58
|
+
metadata = os.fstat(stream.fileno())
|
|
59
|
+
if (
|
|
60
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
61
|
+
or metadata.st_uid != os.getuid()
|
|
62
|
+
or metadata.st_nlink != 1
|
|
63
|
+
or metadata.st_mode & 0o077
|
|
64
|
+
):
|
|
65
|
+
raise ComponentRuntimeError("component_record_invalid")
|
|
66
|
+
data = stream.read(RECORD_LIMIT + 1)
|
|
67
|
+
if len(data) > RECORD_LIMIT:
|
|
68
|
+
raise ComponentRuntimeError("component_record_invalid")
|
|
69
|
+
try:
|
|
70
|
+
value = json.loads(data)
|
|
71
|
+
except (ValueError, UnicodeError) as error:
|
|
72
|
+
raise ComponentRuntimeError("component_record_invalid") from error
|
|
73
|
+
if not isinstance(value, dict) or set(value) != fields:
|
|
74
|
+
raise ComponentRuntimeError("component_schema_unsupported")
|
|
75
|
+
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
|
|
76
|
+
raise ComponentRuntimeError("component_schema_unsupported")
|
|
77
|
+
return value
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _relative(value: Any) -> str:
|
|
81
|
+
if (
|
|
82
|
+
not isinstance(value, str)
|
|
83
|
+
or not value
|
|
84
|
+
or len(value) > 4096
|
|
85
|
+
or any(character in value for character in '\\:*?<>"|')
|
|
86
|
+
):
|
|
87
|
+
raise ComponentRuntimeError("component_path_invalid")
|
|
88
|
+
for segment in value.split("/"):
|
|
89
|
+
if (
|
|
90
|
+
segment in ("", ".", "..")
|
|
91
|
+
or segment.endswith((".", " "))
|
|
92
|
+
or any(ord(character) < 32 for character in segment)
|
|
93
|
+
):
|
|
94
|
+
raise ComponentRuntimeError("component_path_invalid")
|
|
95
|
+
stem = segment.split(".", 1)[0].upper()
|
|
96
|
+
if stem in {"CON", "PRN", "AUX", "NUL", "CLOCK$"} or re.fullmatch(
|
|
97
|
+
r"(?:COM|LPT)[1-9]", stem
|
|
98
|
+
):
|
|
99
|
+
raise ComponentRuntimeError("component_path_invalid")
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _digest(value: Any) -> str:
|
|
104
|
+
if not isinstance(value, str) or not DIGEST.fullmatch(value):
|
|
105
|
+
raise ComponentRuntimeError("component_record_invalid")
|
|
106
|
+
return value
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def default_store_root(env: dict[str, str] | None = None) -> Path:
|
|
110
|
+
environment = os.environ if env is None else env
|
|
111
|
+
root = Path(
|
|
112
|
+
environment.get("FORGEXA_COMPONENT_STORE") or Path.home() / ".forgexa" / "components"
|
|
113
|
+
)
|
|
114
|
+
if not root.is_absolute():
|
|
115
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
116
|
+
return root
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class ManagedComponentLease:
|
|
120
|
+
def __init__(
|
|
121
|
+
self, root: Path, receipt: dict[str, Any], selection_revision: int, descriptor: int
|
|
122
|
+
) -> None:
|
|
123
|
+
self.root = root
|
|
124
|
+
self.receipt = receipt
|
|
125
|
+
self.selection_revision = selection_revision
|
|
126
|
+
self.descriptor = descriptor
|
|
127
|
+
self.lease_id = os.urandom(32).hex()
|
|
128
|
+
self.owner_nonce = os.urandom(32).hex()
|
|
129
|
+
self.process_started = False
|
|
130
|
+
self.record_path = root / "leases" / f"{self.lease_id}.json"
|
|
131
|
+
digest = _digest(receipt["installation_id"].removeprefix("install-"))
|
|
132
|
+
self.directory = root / "versions" / digest
|
|
133
|
+
entry = receipt["entry_point"]
|
|
134
|
+
if not isinstance(entry, dict) or entry.get("kind") not in {"native", "node", "python"}:
|
|
135
|
+
raise ComponentRuntimeError("component_entry_invalid")
|
|
136
|
+
expected_fields = (
|
|
137
|
+
{"kind", "executable"}
|
|
138
|
+
if entry["kind"] == "native"
|
|
139
|
+
else {"kind", "executable", "script"}
|
|
140
|
+
)
|
|
141
|
+
if set(entry) != expected_fields:
|
|
142
|
+
raise ComponentRuntimeError("component_entry_invalid")
|
|
143
|
+
self.argv_prefix = [str(self.directory / _relative(entry["executable"]))]
|
|
144
|
+
if entry["kind"] != "native":
|
|
145
|
+
self.argv_prefix.append(str(self.directory / _relative(entry["script"])))
|
|
146
|
+
|
|
147
|
+
def wrap_command(self, command: list[str]) -> list[str]:
|
|
148
|
+
if not command or command[0] != self.argv_prefix[-1]:
|
|
149
|
+
raise ComponentRuntimeError("component_instance_changed")
|
|
150
|
+
return [*self.argv_prefix, *command[1:]]
|
|
151
|
+
|
|
152
|
+
def probe_environment(
|
|
153
|
+
self, directory: Path, baseline: dict[str, str] | None = None
|
|
154
|
+
) -> dict[str, str]:
|
|
155
|
+
source = os.environ if baseline is None else baseline
|
|
156
|
+
environment = {
|
|
157
|
+
name: source[name]
|
|
158
|
+
for name in (
|
|
159
|
+
"SystemRoot",
|
|
160
|
+
"WINDIR",
|
|
161
|
+
"SSL_CERT_FILE",
|
|
162
|
+
"SSL_CERT_DIR",
|
|
163
|
+
"HTTPS_PROXY",
|
|
164
|
+
"HTTP_PROXY",
|
|
165
|
+
"ALL_PROXY",
|
|
166
|
+
"NO_PROXY",
|
|
167
|
+
"LANG",
|
|
168
|
+
"LC_ALL",
|
|
169
|
+
)
|
|
170
|
+
if name in source
|
|
171
|
+
}
|
|
172
|
+
environment.update(
|
|
173
|
+
{
|
|
174
|
+
"PATH": f"{Path(self.argv_prefix[0]).parent}{os.pathsep}{os.defpath}",
|
|
175
|
+
"HOME": str(directory),
|
|
176
|
+
"TMPDIR": str(directory),
|
|
177
|
+
"BUN_TMPDIR": str(directory),
|
|
178
|
+
"DISABLE_UPDATES": "1",
|
|
179
|
+
"DISABLE_AUTOUPDATER": "1",
|
|
180
|
+
}
|
|
181
|
+
)
|
|
182
|
+
return environment
|
|
183
|
+
|
|
184
|
+
def verify(self) -> None:
|
|
185
|
+
_private_directory(self.directory)
|
|
186
|
+
files = self.receipt["files"]
|
|
187
|
+
if not isinstance(files, list) or not 0 < len(files) <= 20_000:
|
|
188
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
189
|
+
serialized = json.dumps(
|
|
190
|
+
files, sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
|
191
|
+
).encode()
|
|
192
|
+
if hashlib.sha256(serialized).hexdigest() != _digest(self.receipt["content_digest"]):
|
|
193
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
194
|
+
expected: dict[str, dict[str, Any]] = {}
|
|
195
|
+
previous = ""
|
|
196
|
+
folded: set[str] = set()
|
|
197
|
+
for member in files:
|
|
198
|
+
if not isinstance(member, dict) or set(member) != {
|
|
199
|
+
"path",
|
|
200
|
+
"sha256",
|
|
201
|
+
"length",
|
|
202
|
+
"executable",
|
|
203
|
+
}:
|
|
204
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
205
|
+
relative = _relative(member["path"])
|
|
206
|
+
if (
|
|
207
|
+
relative <= previous
|
|
208
|
+
or relative.lower() in folded
|
|
209
|
+
or type(member["length"]) is not int
|
|
210
|
+
or member["length"] < 0
|
|
211
|
+
or type(member["executable"]) is not bool
|
|
212
|
+
):
|
|
213
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
214
|
+
previous = relative
|
|
215
|
+
folded.add(relative.lower())
|
|
216
|
+
expected[relative] = member
|
|
217
|
+
if sum(member["length"] for member in files) != self.receipt["release"]["expanded_length"]:
|
|
218
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
219
|
+
actual: set[str] = set()
|
|
220
|
+
for parent, directories, names in os.walk(self.directory, followlinks=False):
|
|
221
|
+
for name in directories:
|
|
222
|
+
directory = Path(parent) / name
|
|
223
|
+
_private_directory(directory)
|
|
224
|
+
relative = directory.relative_to(self.directory).as_posix()
|
|
225
|
+
if not any(path.startswith(f"{relative}/") for path in expected):
|
|
226
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
227
|
+
for name in names:
|
|
228
|
+
path = Path(parent) / name
|
|
229
|
+
relative = path.relative_to(self.directory).as_posix()
|
|
230
|
+
member = expected.get(relative)
|
|
231
|
+
if member is None:
|
|
232
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
233
|
+
descriptor = os.open(
|
|
234
|
+
path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
235
|
+
)
|
|
236
|
+
with os.fdopen(descriptor, "rb") as stream:
|
|
237
|
+
metadata = os.fstat(stream.fileno())
|
|
238
|
+
if (
|
|
239
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
240
|
+
or metadata.st_nlink != 1
|
|
241
|
+
or metadata.st_uid != os.getuid()
|
|
242
|
+
or stat.S_IMODE(metadata.st_mode)
|
|
243
|
+
!= (0o700 if member["executable"] else 0o600)
|
|
244
|
+
or metadata.st_size != member["length"]
|
|
245
|
+
):
|
|
246
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
247
|
+
digest = hashlib.sha256()
|
|
248
|
+
total = 0
|
|
249
|
+
while chunk := stream.read(65_536):
|
|
250
|
+
total += len(chunk)
|
|
251
|
+
if total > member["length"]:
|
|
252
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
253
|
+
digest.update(chunk)
|
|
254
|
+
if digest.hexdigest() != _digest(member["sha256"]):
|
|
255
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
256
|
+
actual.add(relative)
|
|
257
|
+
if actual != set(expected):
|
|
258
|
+
raise ComponentRuntimeError("component_inventory_invalid")
|
|
259
|
+
executable = Path(self.argv_prefix[0]).relative_to(self.directory).as_posix()
|
|
260
|
+
if executable not in expected or not expected[executable]["executable"]:
|
|
261
|
+
raise ComponentRuntimeError("component_entry_invalid")
|
|
262
|
+
if (
|
|
263
|
+
len(self.argv_prefix) == 2
|
|
264
|
+
and Path(self.argv_prefix[1]).relative_to(self.directory).as_posix() not in expected
|
|
265
|
+
):
|
|
266
|
+
raise ComponentRuntimeError("component_entry_invalid")
|
|
267
|
+
|
|
268
|
+
def close(self) -> None:
|
|
269
|
+
if self.descriptor < 0:
|
|
270
|
+
return
|
|
271
|
+
import fcntl
|
|
272
|
+
|
|
273
|
+
try:
|
|
274
|
+
with _ComponentManagerLock(self.root):
|
|
275
|
+
record = _record(
|
|
276
|
+
self.record_path,
|
|
277
|
+
{
|
|
278
|
+
"schema_version",
|
|
279
|
+
"target_id",
|
|
280
|
+
"installation_id",
|
|
281
|
+
"lease_id",
|
|
282
|
+
"process_id",
|
|
283
|
+
"owner_nonce",
|
|
284
|
+
},
|
|
285
|
+
)
|
|
286
|
+
if (
|
|
287
|
+
record is not None
|
|
288
|
+
and record["process_id"] == os.getpid()
|
|
289
|
+
and record["lease_id"] == self.lease_id
|
|
290
|
+
and record["owner_nonce"] == self.owner_nonce
|
|
291
|
+
):
|
|
292
|
+
self.record_path.unlink()
|
|
293
|
+
finally:
|
|
294
|
+
fcntl.flock(self.descriptor, fcntl.LOCK_UN)
|
|
295
|
+
os.close(self.descriptor)
|
|
296
|
+
self.descriptor = -1
|
|
297
|
+
|
|
298
|
+
def retain_unknown_usage(self) -> None:
|
|
299
|
+
if self.descriptor < 0:
|
|
300
|
+
return
|
|
301
|
+
import fcntl
|
|
302
|
+
|
|
303
|
+
fcntl.flock(self.descriptor, fcntl.LOCK_UN)
|
|
304
|
+
os.close(self.descriptor)
|
|
305
|
+
self.descriptor = -1
|
|
306
|
+
|
|
307
|
+
def __enter__(self) -> ManagedComponentLease:
|
|
308
|
+
return self
|
|
309
|
+
|
|
310
|
+
def __exit__(self, *_arguments: Any) -> None:
|
|
311
|
+
self.close()
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class _ComponentManagerLock:
|
|
315
|
+
def __init__(self, root: Path) -> None:
|
|
316
|
+
self.root = root
|
|
317
|
+
self.descriptor = -1
|
|
318
|
+
|
|
319
|
+
def __enter__(self) -> None:
|
|
320
|
+
import fcntl
|
|
321
|
+
|
|
322
|
+
_private_directory(self.root)
|
|
323
|
+
self.descriptor = os.open(
|
|
324
|
+
self.root / ".manager.lock",
|
|
325
|
+
os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0),
|
|
326
|
+
)
|
|
327
|
+
try:
|
|
328
|
+
metadata = os.fstat(self.descriptor)
|
|
329
|
+
if (
|
|
330
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
331
|
+
or metadata.st_uid != os.getuid()
|
|
332
|
+
or metadata.st_nlink != 1
|
|
333
|
+
or metadata.st_mode & 0o077
|
|
334
|
+
):
|
|
335
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
336
|
+
fcntl.flock(self.descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
337
|
+
except (OSError, ComponentRuntimeError) as error:
|
|
338
|
+
os.close(self.descriptor)
|
|
339
|
+
self.descriptor = -1
|
|
340
|
+
if isinstance(error, ComponentRuntimeError):
|
|
341
|
+
raise
|
|
342
|
+
raise ComponentRuntimeError("component_manager_busy") from error
|
|
343
|
+
|
|
344
|
+
def __exit__(self, *_arguments: Any) -> None:
|
|
345
|
+
import fcntl
|
|
346
|
+
|
|
347
|
+
fcntl.flock(self.descriptor, fcntl.LOCK_UN)
|
|
348
|
+
os.close(self.descriptor)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _component_target(root: Path) -> dict[str, Any]:
|
|
352
|
+
target = _record(
|
|
353
|
+
root / "target.json",
|
|
354
|
+
{
|
|
355
|
+
"schema_version",
|
|
356
|
+
"target_id",
|
|
357
|
+
"kind",
|
|
358
|
+
"os",
|
|
359
|
+
"arch",
|
|
360
|
+
"os_user_id",
|
|
361
|
+
"store_id",
|
|
362
|
+
"generation",
|
|
363
|
+
},
|
|
364
|
+
)
|
|
365
|
+
if target is None:
|
|
366
|
+
raise ComponentRuntimeError("component_target_invalid")
|
|
367
|
+
metadata = root.stat()
|
|
368
|
+
identity = f"{root.resolve()}\n{os.getuid()}\n{metadata.st_dev}\n{metadata.st_ino}"
|
|
369
|
+
target_os = (
|
|
370
|
+
"macos"
|
|
371
|
+
if sys.platform == "darwin"
|
|
372
|
+
else "linux"
|
|
373
|
+
if sys.platform == "linux"
|
|
374
|
+
else "unsupported"
|
|
375
|
+
)
|
|
376
|
+
target_arch = "aarch64" if platform.machine().lower() in {"arm64", "aarch64"} else "x86_64"
|
|
377
|
+
_identifier(target["target_id"])
|
|
378
|
+
_identifier(target["generation"])
|
|
379
|
+
if (
|
|
380
|
+
target["kind"] != "native"
|
|
381
|
+
or target["os"] != target_os
|
|
382
|
+
or target["arch"] != target_arch
|
|
383
|
+
or target["os_user_id"] != str(os.getuid())
|
|
384
|
+
or target["store_id"] != hashlib.sha256(identity.encode()).hexdigest()
|
|
385
|
+
):
|
|
386
|
+
raise ComponentRuntimeError("component_target_changed")
|
|
387
|
+
return target
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _process_start_identity(process_id: int) -> str:
|
|
391
|
+
try:
|
|
392
|
+
import psutil
|
|
393
|
+
except ImportError as error:
|
|
394
|
+
raise ComponentRuntimeError("component_process_identity_unverified") from error
|
|
395
|
+
try:
|
|
396
|
+
created = psutil.Process(process_id).create_time()
|
|
397
|
+
except (psutil.Error, OSError) as error:
|
|
398
|
+
raise ComponentRuntimeError("component_process_identity_unverified") from error
|
|
399
|
+
if not math.isfinite(created) or created <= 0:
|
|
400
|
+
raise ComponentRuntimeError("component_process_identity_unverified")
|
|
401
|
+
return f"process-{process_id}-{struct.pack('!d', created).hex()}"
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def runtime_capabilities(
|
|
405
|
+
runtime_instance_id: str, root: Path | None = None
|
|
406
|
+
) -> dict[str, Any] | None:
|
|
407
|
+
_identifier(runtime_instance_id)
|
|
408
|
+
root = default_store_root() if root is None else root
|
|
409
|
+
if root.is_symlink():
|
|
410
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
411
|
+
if not root.exists():
|
|
412
|
+
return None
|
|
413
|
+
if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
|
|
414
|
+
raise ComponentRuntimeError("component_platform_unverified")
|
|
415
|
+
with _ComponentManagerLock(root):
|
|
416
|
+
target = _component_target(root)
|
|
417
|
+
process_id = os.getpid()
|
|
418
|
+
return {
|
|
419
|
+
"schema_version": 1,
|
|
420
|
+
"target": target,
|
|
421
|
+
"runtime_instance_id": runtime_instance_id,
|
|
422
|
+
"process_id": process_id,
|
|
423
|
+
"process_start_identity": _process_start_identity(process_id),
|
|
424
|
+
"managed_instance_resolution": True,
|
|
425
|
+
"version_usage_leases": True,
|
|
426
|
+
"usage_recovery": False,
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _acquire_component(
|
|
431
|
+
component_id: str, root: Path | None = None, override: str | None = None
|
|
432
|
+
) -> ManagedComponentLease | None:
|
|
433
|
+
_identifier(component_id)
|
|
434
|
+
root = default_store_root() if root is None else root
|
|
435
|
+
if root.is_symlink():
|
|
436
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
437
|
+
if not root.exists():
|
|
438
|
+
return None
|
|
439
|
+
if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
|
|
440
|
+
raise ComponentRuntimeError("component_platform_unverified")
|
|
441
|
+
import fcntl
|
|
442
|
+
|
|
443
|
+
with _ComponentManagerLock(root):
|
|
444
|
+
target = _component_target(root)
|
|
445
|
+
selection = _record(
|
|
446
|
+
root / "selections" / f"{component_id}.json",
|
|
447
|
+
{
|
|
448
|
+
"schema_version",
|
|
449
|
+
"target_id",
|
|
450
|
+
"component_id",
|
|
451
|
+
"revision",
|
|
452
|
+
"installation_id",
|
|
453
|
+
"enabled",
|
|
454
|
+
},
|
|
455
|
+
)
|
|
456
|
+
if selection is None:
|
|
457
|
+
return None
|
|
458
|
+
if (
|
|
459
|
+
selection["target_id"] != target["target_id"]
|
|
460
|
+
or selection["component_id"] != component_id
|
|
461
|
+
or type(selection["enabled"]) is not bool
|
|
462
|
+
):
|
|
463
|
+
raise ComponentRuntimeError("component_selection_invalid")
|
|
464
|
+
if (
|
|
465
|
+
type(selection["revision"]) is not int
|
|
466
|
+
or not 0 <= selection["revision"] <= 9_007_199_254_740_991
|
|
467
|
+
):
|
|
468
|
+
raise ComponentRuntimeError("component_selection_invalid")
|
|
469
|
+
if not selection["enabled"]:
|
|
470
|
+
raise ComponentRuntimeError("component_disabled")
|
|
471
|
+
installation_id = _identifier(selection["installation_id"])
|
|
472
|
+
receipt = _record(
|
|
473
|
+
root / "receipts" / f"{installation_id}.json",
|
|
474
|
+
{
|
|
475
|
+
"schema_version",
|
|
476
|
+
"installation_id",
|
|
477
|
+
"target_id",
|
|
478
|
+
"release",
|
|
479
|
+
"content_digest",
|
|
480
|
+
"entry_point",
|
|
481
|
+
"files",
|
|
482
|
+
"created_by_operation_id",
|
|
483
|
+
},
|
|
484
|
+
)
|
|
485
|
+
if (
|
|
486
|
+
receipt is None
|
|
487
|
+
or receipt["installation_id"] != installation_id
|
|
488
|
+
or receipt["target_id"] != target["target_id"]
|
|
489
|
+
or not isinstance(receipt["release"], dict)
|
|
490
|
+
or receipt["release"].get("component_id") != component_id
|
|
491
|
+
):
|
|
492
|
+
raise ComponentRuntimeError("component_receipt_invalid")
|
|
493
|
+
release = receipt["release"]
|
|
494
|
+
if not isinstance(release, dict) or set(release) != {
|
|
495
|
+
"schema_version",
|
|
496
|
+
"component_id",
|
|
497
|
+
"kind",
|
|
498
|
+
"release_id",
|
|
499
|
+
"version",
|
|
500
|
+
"protocol_generation",
|
|
501
|
+
"artifact_target",
|
|
502
|
+
"artifact_sha256",
|
|
503
|
+
"artifact_length",
|
|
504
|
+
"expanded_length",
|
|
505
|
+
}:
|
|
506
|
+
raise ComponentRuntimeError("component_receipt_invalid")
|
|
507
|
+
if (
|
|
508
|
+
type(release["schema_version"]) is not int
|
|
509
|
+
or release["schema_version"] != 1
|
|
510
|
+
or release["kind"] != "agent"
|
|
511
|
+
):
|
|
512
|
+
raise ComponentRuntimeError("component_receipt_invalid")
|
|
513
|
+
for name in ("component_id", "release_id", "protocol_generation"):
|
|
514
|
+
_identifier(release[name])
|
|
515
|
+
_identifier(receipt["created_by_operation_id"])
|
|
516
|
+
_relative(release["artifact_target"])
|
|
517
|
+
_digest(release["artifact_sha256"])
|
|
518
|
+
if (
|
|
519
|
+
not isinstance(release["version"], str)
|
|
520
|
+
or not release["version"]
|
|
521
|
+
or any(ord(character) < 32 for character in release["version"])
|
|
522
|
+
):
|
|
523
|
+
raise ComponentRuntimeError("component_receipt_invalid")
|
|
524
|
+
if any(
|
|
525
|
+
type(release[name]) is not int or not 0 < release[name] <= 4 * 1024 * 1024 * 1024
|
|
526
|
+
for name in ("artifact_length", "expanded_length")
|
|
527
|
+
):
|
|
528
|
+
raise ComponentRuntimeError("component_receipt_invalid")
|
|
529
|
+
_private_directory(root / "leases")
|
|
530
|
+
descriptor = os.open(
|
|
531
|
+
root / "leases" / f"{installation_id}.lock",
|
|
532
|
+
os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0),
|
|
533
|
+
0o600,
|
|
534
|
+
)
|
|
535
|
+
try:
|
|
536
|
+
metadata = os.fstat(descriptor)
|
|
537
|
+
if (
|
|
538
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
539
|
+
or metadata.st_uid != os.getuid()
|
|
540
|
+
or metadata.st_nlink != 1
|
|
541
|
+
or metadata.st_mode & 0o077
|
|
542
|
+
):
|
|
543
|
+
raise ComponentRuntimeError("component_storage_invalid")
|
|
544
|
+
fcntl.flock(descriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
545
|
+
lease = ManagedComponentLease(root, receipt, selection["revision"], descriptor)
|
|
546
|
+
if override and os.path.realpath(override) != os.path.realpath(lease.argv_prefix[-1]):
|
|
547
|
+
raise ComponentRuntimeError("component_path_override_conflict")
|
|
548
|
+
record = {
|
|
549
|
+
"schema_version": 1,
|
|
550
|
+
"target_id": target["target_id"],
|
|
551
|
+
"installation_id": installation_id,
|
|
552
|
+
"lease_id": lease.lease_id,
|
|
553
|
+
"process_id": os.getpid(),
|
|
554
|
+
"owner_nonce": lease.owner_nonce,
|
|
555
|
+
}
|
|
556
|
+
with os.fdopen(
|
|
557
|
+
os.open(lease.record_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb"
|
|
558
|
+
) as stream:
|
|
559
|
+
stream.write(
|
|
560
|
+
json.dumps(record, sort_keys=True, separators=(",", ":")).encode() + b"\n"
|
|
561
|
+
)
|
|
562
|
+
stream.flush()
|
|
563
|
+
os.fsync(stream.fileno())
|
|
564
|
+
except Exception:
|
|
565
|
+
os.close(descriptor)
|
|
566
|
+
raise
|
|
567
|
+
try:
|
|
568
|
+
lease.verify()
|
|
569
|
+
except Exception:
|
|
570
|
+
lease.close()
|
|
571
|
+
raise
|
|
572
|
+
return lease
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def acquire_component(
|
|
576
|
+
component_id: str, root: Path | None = None, override: str | None = None
|
|
577
|
+
) -> ManagedComponentLease | None:
|
|
578
|
+
try:
|
|
579
|
+
return _acquire_component(component_id, root, override)
|
|
580
|
+
except OSError as error:
|
|
581
|
+
raise ComponentRuntimeError("component_storage_unavailable") from error
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def admit_execution(
|
|
585
|
+
component_id: str,
|
|
586
|
+
binary_path: str,
|
|
587
|
+
installation_id: str | None = None,
|
|
588
|
+
selection_revision: int | None = None,
|
|
589
|
+
root: Path | None = None,
|
|
590
|
+
override: str | None = None,
|
|
591
|
+
) -> ManagedComponentLease | None:
|
|
592
|
+
lease = acquire_component(component_id, root=root, override=override)
|
|
593
|
+
if lease is None:
|
|
594
|
+
if installation_id is not None or selection_revision is not None:
|
|
595
|
+
raise ComponentRuntimeError("component_instance_missing")
|
|
596
|
+
return None
|
|
597
|
+
try:
|
|
598
|
+
if binary_path != lease.argv_prefix[-1]:
|
|
599
|
+
raise ComponentRuntimeError("component_instance_changed")
|
|
600
|
+
if installation_id is not None and installation_id != lease.receipt["installation_id"]:
|
|
601
|
+
raise ComponentRuntimeError("component_instance_changed")
|
|
602
|
+
if selection_revision is not None and selection_revision != lease.selection_revision:
|
|
603
|
+
raise ComponentRuntimeError("component_selection_changed")
|
|
604
|
+
return lease
|
|
605
|
+
except Exception:
|
|
606
|
+
lease.close()
|
|
607
|
+
raise
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
@contextmanager
|
|
611
|
+
def execution_scope(lease: ManagedComponentLease | None):
|
|
612
|
+
token = _EXECUTION_LEASE.set(lease)
|
|
613
|
+
try:
|
|
614
|
+
yield
|
|
615
|
+
finally:
|
|
616
|
+
_EXECUTION_LEASE.reset(token)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def current_execution() -> ManagedComponentLease | None:
|
|
620
|
+
return _EXECUTION_LEASE.get()
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def execution_command(command: list[str], environment: dict[str, str] | None):
|
|
624
|
+
lease = current_execution()
|
|
625
|
+
if lease is None or not command or command[0] != lease.argv_prefix[-1]:
|
|
626
|
+
return command, environment
|
|
627
|
+
lease.verify()
|
|
628
|
+
command = lease.wrap_command(command)
|
|
629
|
+
environment = {
|
|
630
|
+
**(os.environ if environment is None else environment),
|
|
631
|
+
"DISABLE_UPDATES": "1",
|
|
632
|
+
"DISABLE_AUTOUPDATER": "1",
|
|
633
|
+
}
|
|
634
|
+
return command, environment
|
|
@@ -108,6 +108,7 @@ except ImportError:
|
|
|
108
108
|
# of truth lives in agent_core.
|
|
109
109
|
DiscoveredAgent = agent_core.DiscoveredAgent
|
|
110
110
|
AgentDiscovery = agent_core.AgentDiscovery
|
|
111
|
+
component_runtime = agent_core.component_runtime
|
|
111
112
|
_prepare_agent_command = agent_core._prepare_agent_command
|
|
112
113
|
_windows_agent_needs_task_file_redirect = agent_core._windows_agent_needs_task_file_redirect
|
|
113
114
|
_redirect_prompt_through_task_file = agent_core._redirect_prompt_through_task_file
|
|
@@ -131,12 +132,21 @@ _MANAGED_WSL_POLICY = getattr(_wsl_policy_module, "ACTIVE_POLICY", None)
|
|
|
131
132
|
|
|
132
133
|
|
|
133
134
|
async def _create_subprocess_exec(*command, **kwargs):
|
|
135
|
+
original_command = command
|
|
136
|
+
prepared, environment = component_runtime.execution_command(list(command), kwargs.get("env"))
|
|
137
|
+
if environment is not kwargs.get("env"):
|
|
138
|
+
kwargs["env"] = environment
|
|
139
|
+
command = prepared
|
|
134
140
|
if _MANAGED_WSL_POLICY is not None:
|
|
135
141
|
return await _MANAGED_WSL_POLICY.spawn(*command, **kwargs)
|
|
136
142
|
# Desktop stdin is its parent-liveness control pipe, never child input.
|
|
137
143
|
# Agent callers that need prompt input explicitly pass subprocess.PIPE.
|
|
138
144
|
kwargs.setdefault("stdin", asyncio.subprocess.DEVNULL)
|
|
139
|
-
|
|
145
|
+
process = await asyncio.create_subprocess_exec(*command, **kwargs)
|
|
146
|
+
lease = component_runtime.current_execution()
|
|
147
|
+
if lease is not None and original_command and original_command[0] == lease.argv_prefix[-1]:
|
|
148
|
+
lease.process_started = True
|
|
149
|
+
return process
|
|
140
150
|
|
|
141
151
|
|
|
142
152
|
def _materialize_performance_evidence(workspace_path, input_context):
|
|
@@ -1381,7 +1391,7 @@ except (ImportError, ModuleNotFoundError):
|
|
|
1381
1391
|
# DAEMON_VERSION is the protocol/logic version of the daemon code.
|
|
1382
1392
|
# Kept in sync with pyproject.toml version via bump-version.sh.
|
|
1383
1393
|
# CLIENT_TYPE identifies which packaging/distribution this daemon runs in.
|
|
1384
|
-
DAEMON_VERSION = "1.
|
|
1394
|
+
DAEMON_VERSION = "1.96.1"
|
|
1385
1395
|
|
|
1386
1396
|
|
|
1387
1397
|
def _detect_client_type() -> str:
|
|
@@ -6911,6 +6921,35 @@ class ProcessManager:
|
|
|
6911
6921
|
workspace_path: Path,
|
|
6912
6922
|
on_progress: Any = None,
|
|
6913
6923
|
on_chunk: Any = None,
|
|
6924
|
+
) -> TaskResult:
|
|
6925
|
+
existing = component_runtime.current_execution()
|
|
6926
|
+
lease = existing
|
|
6927
|
+
owned = False
|
|
6928
|
+
try:
|
|
6929
|
+
if lease is None or lease.receipt["release"]["component_id"] != agent.agent_id:
|
|
6930
|
+
lease = await asyncio.to_thread(
|
|
6931
|
+
component_runtime.admit_execution, agent.agent_id, agent.command,
|
|
6932
|
+
getattr(agent, "installation_id", None), getattr(agent, "selection_revision", None),
|
|
6933
|
+
None, os.environ.get(AgentDiscovery.AGENT_REGISTRY.get(agent.agent_id, {}).get("env_path_override", "")),
|
|
6934
|
+
)
|
|
6935
|
+
owned = lease is not None
|
|
6936
|
+
elif lease.argv_prefix[-1] != agent.command:
|
|
6937
|
+
raise component_runtime.ComponentRuntimeError("component_instance_changed")
|
|
6938
|
+
with component_runtime.execution_scope(lease):
|
|
6939
|
+
return await self._run_admitted_agent(agent, task, workspace_path, on_progress, on_chunk)
|
|
6940
|
+
except component_runtime.ComponentRuntimeError as exc:
|
|
6941
|
+
return TaskResult(status="failed", exit_code=-1, stdout="", stderr="", error=exc.code,
|
|
6942
|
+
failure_code=exc.code, execution_attempt_id=task.execution_attempt_id)
|
|
6943
|
+
finally:
|
|
6944
|
+
if owned and lease is not None:
|
|
6945
|
+
if lease.process_started:
|
|
6946
|
+
lease.retain_unknown_usage()
|
|
6947
|
+
else:
|
|
6948
|
+
await asyncio.to_thread(lease.close)
|
|
6949
|
+
|
|
6950
|
+
async def _run_admitted_agent(
|
|
6951
|
+
self, agent: DiscoveredAgent, task: TaskInfo, workspace_path: Path,
|
|
6952
|
+
on_progress: Any = None, on_chunk: Any = None,
|
|
6914
6953
|
) -> TaskResult:
|
|
6915
6954
|
"""Execute an agent CLI and collect results."""
|
|
6916
6955
|
if isinstance(getattr(task, "input_data", None), dict) and task.input_data.get("requires_capture_images") and agent.agent_id != "claude":
|
|
@@ -8278,6 +8317,7 @@ class ProcessManager:
|
|
|
8278
8317
|
env=await asyncio.to_thread(agent_core.zcode_base_env, os.environ.copy()),
|
|
8279
8318
|
on_event=on_event,
|
|
8280
8319
|
permission_handler=agent_core.zcode_permission_response,
|
|
8320
|
+
component_lease=component_runtime.current_execution(),
|
|
8281
8321
|
)
|
|
8282
8322
|
await client.start()
|
|
8283
8323
|
if client.process is not None:
|
|
@@ -8350,9 +8390,11 @@ class ProcessManager:
|
|
|
8350
8390
|
finally:
|
|
8351
8391
|
self.active_zcode_sessions.pop(task_id, None)
|
|
8352
8392
|
self.active_processes.pop(task_id, None)
|
|
8353
|
-
|
|
8354
|
-
|
|
8355
|
-
|
|
8393
|
+
try:
|
|
8394
|
+
if client is not None:
|
|
8395
|
+
await client.close()
|
|
8396
|
+
finally:
|
|
8397
|
+
agent_core.release_file_lock(profile_lock)
|
|
8356
8398
|
|
|
8357
8399
|
async def _run_gemini(
|
|
8358
8400
|
self, agent: DiscoveredAgent, prompt: str, cwd: Path, timeout: int, task_id: str,
|
|
@@ -13271,6 +13313,30 @@ class RuntimeDaemon:
|
|
|
13271
13313
|
result.lines_removed = git_info.get("lines_removed", 0)
|
|
13272
13314
|
|
|
13273
13315
|
async def _execute_task(self, task: TaskInfo, conn: ServerConnection):
|
|
13316
|
+
agent = self._select_agent(task.agent_type, task.fallback_chain)
|
|
13317
|
+
lease = None
|
|
13318
|
+
try:
|
|
13319
|
+
if agent is not None:
|
|
13320
|
+
lease = await asyncio.to_thread(
|
|
13321
|
+
component_runtime.admit_execution, agent.agent_id, agent.command,
|
|
13322
|
+
getattr(agent, "installation_id", None), getattr(agent, "selection_revision", None),
|
|
13323
|
+
None, os.environ.get(AgentDiscovery.AGENT_REGISTRY.get(agent.agent_id, {}).get("env_path_override", "")),
|
|
13324
|
+
)
|
|
13325
|
+
with component_runtime.execution_scope(lease):
|
|
13326
|
+
return await self._execute_admitted_task(task, conn)
|
|
13327
|
+
except component_runtime.ComponentRuntimeError as exc:
|
|
13328
|
+
await conn.reporter.report_complete(task.task_id, TaskResult(
|
|
13329
|
+
status="failed", exit_code=-1, stdout="", stderr="", error=exc.code,
|
|
13330
|
+
failure_code=exc.code, execution_attempt_id=task.execution_attempt_id,
|
|
13331
|
+
))
|
|
13332
|
+
finally:
|
|
13333
|
+
if lease is not None:
|
|
13334
|
+
if lease.process_started:
|
|
13335
|
+
lease.retain_unknown_usage()
|
|
13336
|
+
else:
|
|
13337
|
+
await asyncio.to_thread(lease.close)
|
|
13338
|
+
|
|
13339
|
+
async def _execute_admitted_task(self, task: TaskInfo, conn: ServerConnection):
|
|
13274
13340
|
"""Execute a single task, reporting to the originating server connection."""
|
|
13275
13341
|
reporter = conn.reporter
|
|
13276
13342
|
# Forgexa IDE local-bind (Phase 0): several cloud-worktree-only steps
|
|
@@ -62,7 +62,7 @@ class ObservabilitySelection(ObservabilityModel):
|
|
|
62
62
|
@model_validator(mode='after')
|
|
63
63
|
def validate_arguments(self) -> ObservabilitySelection:
|
|
64
64
|
arguments = {'percentile': 'percentile', 'rate_interval_seconds': 'rate', 'threshold': 'apdex'}
|
|
65
|
-
for name, aggregate in arguments.items():
|
|
65
|
+
for (name, aggregate) in arguments.items():
|
|
66
66
|
required = self.aggregate == aggregate
|
|
67
67
|
if required != (getattr(self, name) is not None):
|
|
68
68
|
raise ValueError('Aggregate arguments do not match the selected function')
|
|
@@ -127,7 +127,7 @@ class ObservabilityQuery(ObservabilityModel):
|
|
|
127
127
|
pending = [(value, 1)] if value is not None else []
|
|
128
128
|
count = 0
|
|
129
129
|
while pending:
|
|
130
|
-
node, depth = pending.pop()
|
|
130
|
+
(node, depth) = pending.pop()
|
|
131
131
|
count += 1
|
|
132
132
|
if depth > 8 or count > 100:
|
|
133
133
|
raise ValueError('Filter tree exceeds its depth or node limit')
|
|
@@ -396,7 +396,7 @@ class ObservabilitySeries(ObservabilityModel):
|
|
|
396
396
|
raise ValueError('observability_percentile_required')
|
|
397
397
|
for bucket in self.buckets:
|
|
398
398
|
validate_unit_values(bucket.native_value, bucket.value, self.native_unit, self.display_unit)
|
|
399
|
-
for previous, current in zip(self.buckets, self.buckets[1:]):
|
|
399
|
+
for (previous, current) in zip(self.buckets, self.buckets[1:]):
|
|
400
400
|
if previous.end_time > current.start_time:
|
|
401
401
|
raise ValueError('observability_time_buckets_overlap')
|
|
402
402
|
return self
|
|
@@ -432,7 +432,7 @@ class ObservabilityHistory(ObservabilityModel):
|
|
|
432
432
|
raise ValueError('observability_history_empty')
|
|
433
433
|
if len(self.native_values) != len(self.values) or (self.statistic == 'percentile') != (self.percentile is not None):
|
|
434
434
|
raise ValueError('observability_history_semantics_invalid')
|
|
435
|
-
for native_value, value in _strict_zip(self.native_values, self.values):
|
|
435
|
+
for (native_value, value) in _strict_zip(self.native_values, self.values):
|
|
436
436
|
validate_unit_values(native_value, value, self.native_unit, self.display_unit)
|
|
437
437
|
validate_unit_values(self.latest_native_value, self.latest_value, self.native_unit, self.display_unit)
|
|
438
438
|
return self
|
|
@@ -616,7 +616,7 @@ class ObservabilitySnapshotPayload(ObservabilityModel):
|
|
|
616
616
|
column = column_map[item.field_id]
|
|
617
617
|
if column.statistic != item.statistic or column.percentile != item.percentile:
|
|
618
618
|
raise ValueError('observability_statistic_mismatch')
|
|
619
|
-
for field_id, value in item.dimensions.items():
|
|
619
|
+
for (field_id, value) in item.dimensions.items():
|
|
620
620
|
if field_id not in column_map:
|
|
621
621
|
raise ValueError('observability_projection_not_declared')
|
|
622
622
|
validate_redacted_value(value, column_map[field_id].redaction)
|
|
@@ -642,7 +642,7 @@ class ObservabilitySnapshotPayload(ObservabilityModel):
|
|
|
642
642
|
else:
|
|
643
643
|
if item.kind == 'span' and any((column.redaction != 'none' for column in self.columns)):
|
|
644
644
|
raise ValueError('observability_redacted_representation_required')
|
|
645
|
-
for field_id, value in item.values.items():
|
|
645
|
+
for (field_id, value) in item.values.items():
|
|
646
646
|
if field_id not in column_map:
|
|
647
647
|
raise ValueError('observability_projection_not_declared')
|
|
648
648
|
mode = column_map[field_id].redaction
|
|
@@ -871,7 +871,7 @@ class TransactionComponent(ObservabilityModel):
|
|
|
871
871
|
if any((set(value) - bindings.keys() for value in values)):
|
|
872
872
|
raise ValueError('Transaction values require declared field bindings')
|
|
873
873
|
for value in values:
|
|
874
|
-
for column_ref, cell in value.items():
|
|
874
|
+
for (column_ref, cell) in value.items():
|
|
875
875
|
definition = bindings[column_ref]
|
|
876
876
|
validate_redacted_value(cell, definition.redaction)
|
|
877
877
|
if cell is not None and (not (definition.value_type == 'number' and type(cell) in {int, float} or (definition.value_type == 'integer' and type(cell) is int) or (definition.value_type == 'boolean' and type(cell) is bool) or (definition.value_type in {'string', 'timestamp'} and isinstance(cell, str)))):
|
|
@@ -989,7 +989,7 @@ def canonical_bytes(value: object) -> bytes:
|
|
|
989
989
|
|
|
990
990
|
def _unique_object(pairs):
|
|
991
991
|
result = {}
|
|
992
|
-
for key, value in pairs:
|
|
992
|
+
for (key, value) in pairs:
|
|
993
993
|
if key in result:
|
|
994
994
|
raise ValueError('observability_invalid_json')
|
|
995
995
|
result[key] = value
|
|
@@ -11,6 +11,7 @@ import asyncio
|
|
|
11
11
|
import inspect
|
|
12
12
|
import json
|
|
13
13
|
import logging
|
|
14
|
+
import os
|
|
14
15
|
import re
|
|
15
16
|
import uuid
|
|
16
17
|
from collections import deque
|
|
@@ -147,12 +148,14 @@ class ZCodeProtocolSession:
|
|
|
147
148
|
env: dict[str, str] | None = None,
|
|
148
149
|
on_event: EventHandler | None = None,
|
|
149
150
|
permission_handler: PermissionHandler | None = None,
|
|
151
|
+
component_lease: agent_core.component_runtime.ManagedComponentLease | None = None,
|
|
150
152
|
) -> None:
|
|
151
153
|
self.command = list(command)
|
|
152
154
|
self.cwd = str(cwd)
|
|
153
155
|
self.env = dict(env) if env is not None else None
|
|
154
156
|
self.on_event = on_event
|
|
155
157
|
self.permission_handler = permission_handler
|
|
158
|
+
self.component_lease = component_lease
|
|
156
159
|
self.session_id: str | None = None
|
|
157
160
|
self.protocol_version: int | None = None
|
|
158
161
|
self._process: asyncio.subprocess.Process | None = None
|
|
@@ -182,8 +185,18 @@ class ZCodeProtocolSession:
|
|
|
182
185
|
if self._process is not None:
|
|
183
186
|
raise ZCodeProtocolError("ZCode Protocol process is already running")
|
|
184
187
|
process_env = self.env
|
|
188
|
+
command = self.command
|
|
189
|
+
if self.component_lease is not None:
|
|
190
|
+
if self.component_lease.receipt["release"]["component_id"] != "zcode":
|
|
191
|
+
raise agent_core.component_runtime.ComponentRuntimeError(
|
|
192
|
+
"component_instance_changed"
|
|
193
|
+
)
|
|
194
|
+
await asyncio.to_thread(self.component_lease.verify)
|
|
195
|
+
command = self.component_lease.wrap_command(command)
|
|
196
|
+
process_env = {**(process_env if process_env is not None else os.environ),
|
|
197
|
+
"DISABLE_UPDATES": "1", "DISABLE_AUTOUPDATER": "1"}
|
|
185
198
|
self._process = await asyncio.create_subprocess_exec(
|
|
186
|
-
*
|
|
199
|
+
*command,
|
|
187
200
|
stdin=asyncio.subprocess.PIPE,
|
|
188
201
|
stdout=asyncio.subprocess.PIPE,
|
|
189
202
|
stderr=asyncio.subprocess.PIPE,
|
|
@@ -192,6 +205,8 @@ class ZCodeProtocolSession:
|
|
|
192
205
|
limit=1_048_576,
|
|
193
206
|
**agent_core._agent_process_group_kwargs(),
|
|
194
207
|
)
|
|
208
|
+
if self.component_lease is not None:
|
|
209
|
+
self.component_lease.process_started = True
|
|
195
210
|
self._reader_task = asyncio.create_task(self._read_loop())
|
|
196
211
|
self._stderr_task = asyncio.create_task(self._read_stderr())
|
|
197
212
|
|
|
@@ -365,6 +380,10 @@ class ZCodeProtocolSession:
|
|
|
365
380
|
for task in (self._reader_task, self._stderr_task):
|
|
366
381
|
if task is not None and not task.done():
|
|
367
382
|
task.cancel()
|
|
383
|
+
if self.component_lease is not None and process is not None and process.returncode is None:
|
|
384
|
+
raise agent_core.component_runtime.ComponentRuntimeError(
|
|
385
|
+
"component_process_cleanup_unconfirmed"
|
|
386
|
+
)
|
|
368
387
|
self._process = None
|
|
369
388
|
|
|
370
389
|
async def _request(self, method: str, params: dict[str, Any], timeout: float = 30.0) -> Any:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|