forgexa-cli 1.96.2__tar.gz → 1.96.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/PKG-INFO +1 -1
  2. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/agent_core.py +42 -5
  4. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/component_runtime.py +343 -3
  5. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/daemon.py +42 -5
  6. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/zcode_protocol.py +29 -1
  7. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/PKG-INFO +1 -1
  8. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/pyproject.toml +1 -1
  9. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/README.md +0 -0
  10. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/_build_config.py +0 -0
  11. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/_local_bind.py +0 -0
  12. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/autoupgrade.py +0 -0
  13. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/aws_evidence.py +0 -0
  14. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/aws_logs_evidence.py +0 -0
  15. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/main.py +0 -0
  16. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/observability_contract.py +0 -0
  17. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/observability_evidence.py +0 -0
  18. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/py.typed +0 -0
  19. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli/runtime_evidence.py +0 -0
  20. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/SOURCES.txt +0 -0
  21. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  22. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/entry_points.txt +0 -0
  23. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/requires.txt +0 -0
  24. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/forgexa_cli.egg-info/top_level.txt +0 -0
  25. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/setup.cfg +0 -0
  26. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_auth_and_runtime_commands.py +0 -0
  27. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_autoupgrade.py +0 -0
  28. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_check_command.py +0 -0
  29. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_expiry_warnings_and_revoke.py +0 -0
  30. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_local_bind_commands.py +0 -0
  31. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_publish_script.py +0 -0
  32. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_runtime_credentials.py +0 -0
  33. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_session_credentials.py +0 -0
  34. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_silent_install.py +0 -0
  35. {forgexa_cli-1.96.2 → forgexa_cli-1.96.4}/tests/test_upgrade_observability.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.96.2
3
+ Version: 1.96.4
4
4
  Summary: Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform
5
5
  Author-email: Jason Sun <dev.winds@gmail.com>
6
6
  License-Expression: MIT
@@ -1,2 +1,2 @@
1
1
  """forgexa-cli — Forgexa command-line client."""
2
- __version__ = "1.96.2"
2
+ __version__ = "1.96.4"
@@ -2341,6 +2341,9 @@ class AgentDiscovery:
2341
2341
  if probe_dir is None:
2342
2342
  probe_dir = tempfile.TemporaryDirectory(prefix="forgexa-managed-discovery-")
2343
2343
  env = managed.probe_environment(Path(probe_dir.name), env)
2344
+ execution_lease = component_runtime.current_execution()
2345
+ if managed is not None and managed is execution_lease:
2346
+ await asyncio.to_thread(managed.begin_spawn)
2344
2347
  proc = await asyncio.create_subprocess_exec(
2345
2348
  *parts,
2346
2349
  stdin=asyncio.subprocess.DEVNULL,
@@ -2350,8 +2353,8 @@ class AgentDiscovery:
2350
2353
  cwd=probe_dir.name if managed is not None else None,
2351
2354
  **_agent_process_group_kwargs(),
2352
2355
  )
2353
- if managed is not None and managed is component_runtime.current_execution():
2354
- managed.process_started = True
2356
+ if managed is not None and managed is execution_lease:
2357
+ await asyncio.to_thread(managed.record_process, proc.pid)
2355
2358
  stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=10)
2356
2359
  if proc.returncode != 0:
2357
2360
  logger.warning(
@@ -4013,9 +4016,14 @@ async def run_minimax(
4013
4016
  max_steps: int = 60, model: str | None = None, session_id: str | None = None,
4014
4017
  on_event: Any = None, on_started: Any = None, on_chunk: Any = None,
4015
4018
  cancel_requested: Any = None,
4019
+ component_lease: Any = None,
4016
4020
  ) -> dict:
4021
+ lease = (
4022
+ component_lease if component_lease is not None else component_runtime.current_execution()
4023
+ )
4017
4024
  state = MiniMaxRunState(expected_session_id=session_id)
4018
4025
  process = None
4026
+ observer = None
4019
4027
  lock = None
4020
4028
  root = None
4021
4029
  temporary = None
@@ -4069,19 +4077,28 @@ async def run_minimax(
4069
4077
  config=root / "config/runtime.json", timeout=remaining,
4070
4078
  max_steps=max_steps, model=model, session_id=session_id)
4071
4079
  command.insert(1, admission["build"]["entry"])
4080
+ command, environment = await asyncio.to_thread(
4081
+ component_runtime.harness_command, lease, "minimax", binary, command,
4082
+ minimax_base_env(root, temporary_root),
4083
+ )
4072
4084
  command = _minimax_sandbox(command, admission, cwd, temporary_root)
4073
4085
  if cancel_requested is not None and cancel_requested():
4074
4086
  return state.finish(-1, cancelled=True)
4075
4087
  _minimax_write_record(active, {"fingerprint": binding_identity, "state": "spawning"})
4088
+ if lease is not None:
4089
+ await asyncio.to_thread(lease.begin_spawn)
4076
4090
  process = await asyncio.create_subprocess_exec(
4077
- *command, cwd=str(cwd), env=minimax_base_env(root, temporary_root),
4091
+ *command, cwd=str(cwd), env=environment,
4078
4092
  stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
4079
4093
  stderr=asyncio.subprocess.PIPE, limit=MINIMAX_MAX_OUTPUT_BYTES,
4080
4094
  **_agent_process_group_kwargs(),
4081
4095
  )
4082
- _minimax_write_record(active, {"pid": process.pid, "fingerprint": binding_identity})
4083
4096
  if on_started is not None:
4084
4097
  on_started(process)
4098
+ if lease is not None:
4099
+ await asyncio.to_thread(lease.record_process, process.pid)
4100
+ observer = asyncio.create_task(component_runtime.observe_owned_process(lease, process))
4101
+ _minimax_write_record(active, {"pid": process.pid, "fingerprint": binding_identity})
4085
4102
 
4086
4103
  async def read_stderr() -> None:
4087
4104
  nonlocal stderr_bytes
@@ -4151,6 +4168,9 @@ async def run_minimax(
4151
4168
  code = "minimax_profile_busy" if "busy" in str(error) else "minimax_startup_failed"
4152
4169
  state.fail(str(error) if isinstance(error, (ValueError, RuntimeError)) else "MiniMax startup or stream I/O failed", code)
4153
4170
  finally:
4171
+ if observer is not None:
4172
+ observer.cancel()
4173
+ await asyncio.gather(observer, return_exceptions=True)
4154
4174
  cleaned = True
4155
4175
  if process is not None:
4156
4176
  _kill_proc(process)
@@ -4869,9 +4889,14 @@ async def run_deepseek_harness(
4869
4889
  on_started: Any = None,
4870
4890
  on_chunk: Any = None,
4871
4891
  cancel_requested: Any = None,
4892
+ component_lease: Any = None,
4872
4893
  ) -> dict:
4873
4894
  """Execute and validate a supervised one-shot process with bounded output."""
4874
4895
  process = None
4896
+ observer = None
4897
+ lease = (
4898
+ component_lease if component_lease is not None else component_runtime.current_execution()
4899
+ )
4875
4900
  state = DeepSeekHarnessRunState(expected_cwd=str(workspace_path))
4876
4901
  raw_lines = []
4877
4902
  raw_bytes = 0
@@ -4881,14 +4906,23 @@ async def run_deepseek_harness(
4881
4906
  try:
4882
4907
  command, env = await asyncio.to_thread(runtime.__enter__)
4883
4908
  entered = True
4909
+ command, env = await asyncio.to_thread(
4910
+ component_runtime.harness_command, lease, "deepseek", binary, command, env,
4911
+ )
4912
+ command = command if lease is not None else _prepare_agent_command(command)
4913
+ if lease is not None:
4914
+ await asyncio.to_thread(lease.begin_spawn)
4884
4915
  process = await asyncio.create_subprocess_exec(
4885
- *_prepare_agent_command(command), cwd=str(workspace_path), env=env,
4916
+ *command, cwd=str(workspace_path), env=env,
4886
4917
  stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
4887
4918
  stderr=asyncio.subprocess.PIPE, limit=DEEPSEEK_HARNESS_MAX_OUTPUT_BYTES,
4888
4919
  **_agent_process_group_kwargs(),
4889
4920
  )
4890
4921
  if on_started is not None:
4891
4922
  on_started(process)
4923
+ if lease is not None:
4924
+ await asyncio.to_thread(lease.record_process, process.pid)
4925
+ observer = asyncio.create_task(component_runtime.observe_owned_process(lease, process))
4892
4926
  if cancel_requested is not None and cancel_requested():
4893
4927
  _kill_proc(process)
4894
4928
 
@@ -4974,6 +5008,9 @@ async def run_deepseek_harness(
4974
5008
  code = "deepseek_harness_profile_busy" if "profile is busy" in message else "deepseek_harness_startup_failed"
4975
5009
  state.fail(message, code)
4976
5010
  finally:
5011
+ if observer is not None:
5012
+ observer.cancel()
5013
+ await asyncio.gather(observer, return_exceptions=True)
4977
5014
  if process is not None and process.returncode is None:
4978
5015
  _kill_proc(process)
4979
5016
  await process.wait()
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import asyncio
3
4
  import hashlib
4
5
  import json
5
6
  import math
@@ -12,6 +13,7 @@ import sys
12
13
  from contextlib import contextmanager
13
14
  from contextvars import ContextVar
14
15
  from pathlib import Path
16
+ from threading import RLock
15
17
  from typing import Any
16
18
 
17
19
  RECORD_LIMIT = 8 * 1024 * 1024
@@ -47,7 +49,7 @@ def _private_directory(path: Path) -> None:
47
49
  raise ComponentRuntimeError("component_storage_invalid")
48
50
 
49
51
 
50
- def _record(path: Path, fields: set[str]) -> dict[str, Any] | None:
52
+ def _record(path: Path, fields: set[str], limit: int = RECORD_LIMIT) -> dict[str, Any] | None:
51
53
  try:
52
54
  descriptor = os.open(
53
55
  path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
@@ -63,8 +65,8 @@ def _record(path: Path, fields: set[str]) -> dict[str, Any] | None:
63
65
  or metadata.st_mode & 0o077
64
66
  ):
65
67
  raise ComponentRuntimeError("component_record_invalid")
66
- data = stream.read(RECORD_LIMIT + 1)
67
- if len(data) > RECORD_LIMIT:
68
+ data = stream.read(limit + 1)
69
+ if len(data) > limit:
68
70
  raise ComponentRuntimeError("component_record_invalid")
69
71
  try:
70
72
  value = json.loads(data)
@@ -128,6 +130,11 @@ class ManagedComponentLease:
128
130
  self.owner_nonce = os.urandom(32).hex()
129
131
  self.process_started = False
130
132
  self.record_path = root / "leases" / f"{self.lease_id}.json"
133
+ self.process_directory = root / "leases" / f"{self.lease_id}.processes"
134
+ self.process_sequence = 0
135
+ self.registered_roots: dict[int, str] = {}
136
+ self.observed_descendants: set[tuple[int, str]] = set()
137
+ self.process_event_lock = RLock()
131
138
  digest = _digest(receipt["installation_id"].removeprefix("install-"))
132
139
  self.directory = root / "versions" / digest
133
140
  entry = receipt["entry_point"]
@@ -144,6 +151,153 @@ class ManagedComponentLease:
144
151
  if entry["kind"] != "native":
145
152
  self.argv_prefix.append(str(self.directory / _relative(entry["script"])))
146
153
 
154
+ def _write_process_event(
155
+ self,
156
+ stage: str,
157
+ process_id: int | None = None,
158
+ expected_identity: str | None = None,
159
+ ) -> dict[str, Any]:
160
+ with self.process_event_lock:
161
+ return self._write_process_event_locked(stage, process_id, expected_identity)
162
+
163
+ def _write_process_event_locked(
164
+ self,
165
+ stage: str,
166
+ process_id: int | None,
167
+ expected_identity: str | None,
168
+ ) -> dict[str, Any]:
169
+ if self.descriptor < 0 or self.process_sequence >= 256:
170
+ raise ComponentRuntimeError("component_usage_unavailable")
171
+ _private_directory(self.root)
172
+ _private_directory(self.root / "leases")
173
+ target = _component_target(self.root)
174
+ if target["target_id"] != self.receipt["target_id"]:
175
+ raise ComponentRuntimeError("component_target_changed")
176
+ record = _record(
177
+ self.record_path,
178
+ {
179
+ "schema_version",
180
+ "target_id",
181
+ "installation_id",
182
+ "lease_id",
183
+ "process_id",
184
+ "owner_nonce",
185
+ },
186
+ )
187
+ if record is None or (
188
+ record["lease_id"] != self.lease_id
189
+ or record["owner_nonce"] != self.owner_nonce
190
+ or record["process_id"] != os.getpid()
191
+ or record["target_id"] != self.receipt["target_id"]
192
+ or record["installation_id"] != self.receipt["installation_id"]
193
+ ):
194
+ raise ComponentRuntimeError("component_usage_changed")
195
+ self.process_directory.mkdir(mode=0o700, exist_ok=True)
196
+ _private_directory(self.process_directory)
197
+ try:
198
+ owner_identity = _process_start_identity(os.getpid())
199
+ except ComponentRuntimeError:
200
+ owner_identity = None
201
+ process_identity = None
202
+ if process_id is not None:
203
+ if type(process_id) is not int or process_id <= 0:
204
+ raise ComponentRuntimeError("component_process_identity_unverified")
205
+ try:
206
+ process_identity = _process_start_identity(process_id)
207
+ except ComponentRuntimeError:
208
+ pass
209
+ if expected_identity is not None and process_identity != expected_identity:
210
+ raise ComponentRuntimeError("component_process_identity_unverified")
211
+ sequence = self.process_sequence + 1
212
+ event = {
213
+ "schema_version": 1,
214
+ "lease_id": self.lease_id,
215
+ "target_id": record["target_id"],
216
+ "installation_id": record["installation_id"],
217
+ "owner_nonce": self.owner_nonce,
218
+ "owner_process_id": os.getpid(),
219
+ "owner_start_identity": owner_identity,
220
+ "sequence": sequence,
221
+ "stage": stage,
222
+ "process_id": process_id,
223
+ "process_start_identity": process_identity,
224
+ }
225
+ contents = json.dumps(event, sort_keys=True, separators=(",", ":")).encode() + b"\n"
226
+ path = self.process_directory / f"{sequence:06d}.json"
227
+ descriptor = os.open(
228
+ path,
229
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
230
+ 0o600,
231
+ )
232
+ with os.fdopen(descriptor, "wb") as stream:
233
+ stream.write(contents)
234
+ stream.flush()
235
+ os.fsync(stream.fileno())
236
+ directory = os.open(self.process_directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
237
+ try:
238
+ os.fsync(directory)
239
+ finally:
240
+ os.close(directory)
241
+ self.process_sequence = sequence
242
+ return event
243
+
244
+ def begin_spawn(self) -> None:
245
+ self.process_started = True
246
+ try:
247
+ self._write_process_event("spawn_pending")
248
+ except OSError as error:
249
+ raise ComponentRuntimeError("component_usage_unavailable") from error
250
+
251
+ def record_process(self, process_id: int) -> None:
252
+ self.process_started = True
253
+ try:
254
+ event = self._write_process_event("spawn_started", process_id)
255
+ if event["process_start_identity"] is not None:
256
+ self.registered_roots[process_id] = event["process_start_identity"]
257
+ except OSError as error:
258
+ raise ComponentRuntimeError("component_usage_unavailable") from error
259
+
260
+ def observe_descendants(self, process_id: int) -> int:
261
+ with self.process_event_lock:
262
+ return self._observe_descendants_locked(process_id)
263
+
264
+ def _observe_descendants_locked(self, process_id: int) -> int:
265
+ identity = self.registered_roots.get(process_id)
266
+ if identity is None or _identity_alive(process_id, identity) is not True:
267
+ raise ComponentRuntimeError("component_process_tree_unverified")
268
+ try:
269
+ import psutil
270
+
271
+ process = psutil.Process(process_id)
272
+ children = process.children(recursive=True)
273
+ except (ImportError, OSError) as error:
274
+ raise ComponentRuntimeError("component_process_tree_unverified") from error
275
+ except psutil.Error as error:
276
+ raise ComponentRuntimeError("component_process_tree_unverified") from error
277
+ if len(children) > 128 or _identity_alive(process_id, identity) is not True:
278
+ raise ComponentRuntimeError("component_process_tree_unverified")
279
+ recorded = 0
280
+ for child in children:
281
+ try:
282
+ created = child.create_time()
283
+ except psutil.NoSuchProcess:
284
+ continue
285
+ except (psutil.Error, OSError) as error:
286
+ raise ComponentRuntimeError("component_process_tree_unverified") from error
287
+ if not math.isfinite(created) or created <= 0:
288
+ raise ComponentRuntimeError("component_process_tree_unverified")
289
+ start_identity = f"process-{child.pid}-{struct.pack('!d', created).hex()}"
290
+ key = (child.pid, start_identity)
291
+ if key in self.observed_descendants:
292
+ continue
293
+ try:
294
+ self._write_process_event("descendant_observed", child.pid, start_identity)
295
+ except OSError as error:
296
+ raise ComponentRuntimeError("component_usage_unavailable") from error
297
+ self.observed_descendants.add(key)
298
+ recorded += 1
299
+ return recorded
300
+
147
301
  def wrap_command(self, command: list[str]) -> list[str]:
148
302
  if not command or command[0] != self.argv_prefix[-1]:
149
303
  raise ComponentRuntimeError("component_instance_changed")
@@ -268,6 +422,9 @@ class ManagedComponentLease:
268
422
  def close(self) -> None:
269
423
  if self.descriptor < 0:
270
424
  return
425
+ if self.process_started:
426
+ self.retain_unknown_usage()
427
+ return
271
428
  import fcntl
272
429
 
273
430
  try:
@@ -401,6 +558,143 @@ def _process_start_identity(process_id: int) -> str:
401
558
  return f"process-{process_id}-{struct.pack('!d', created).hex()}"
402
559
 
403
560
 
561
+ def _identity_alive(process_id: int, identity: str | None) -> bool | None:
562
+ if identity is None:
563
+ return None
564
+ try:
565
+ import psutil
566
+ except ImportError:
567
+ return None
568
+ try:
569
+ created = psutil.Process(process_id).create_time()
570
+ except psutil.NoSuchProcess:
571
+ return False
572
+ except (psutil.Error, OSError):
573
+ return None
574
+ if not math.isfinite(created) or created <= 0:
575
+ return None
576
+ return identity == f"process-{process_id}-{struct.pack('!d', created).hex()}"
577
+
578
+
579
+ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
580
+ _identifier(lease_id)
581
+ root = default_store_root() if root is None else root
582
+ if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
583
+ raise ComponentRuntimeError("component_platform_unverified")
584
+ _private_directory(root)
585
+ _private_directory(root / "leases")
586
+ target = _component_target(root)
587
+ record = _record(
588
+ root / "leases" / f"{lease_id}.json",
589
+ {"schema_version", "target_id", "installation_id", "lease_id", "process_id", "owner_nonce"},
590
+ 16_384,
591
+ )
592
+ if record is None:
593
+ raise ComponentRuntimeError("component_usage_missing")
594
+ if record["lease_id"] != lease_id or record["target_id"] != target["target_id"]:
595
+ raise ComponentRuntimeError("component_usage_changed")
596
+ _identifier(record["installation_id"])
597
+ _digest(record["owner_nonce"])
598
+ if type(record["process_id"]) is not int or record["process_id"] <= 0:
599
+ raise ComponentRuntimeError("component_record_invalid")
600
+ result = {
601
+ "schema_version": 1,
602
+ "target_id": target["target_id"],
603
+ "generation": target["generation"],
604
+ "lease_id": lease_id,
605
+ "installation_id": record["installation_id"],
606
+ "state": "legacy_unknown",
607
+ "descendant_coverage": "observed_only",
608
+ "owner_alive": None,
609
+ "processes": [],
610
+ }
611
+ directory = root / "leases" / f"{lease_id}.processes"
612
+ try:
613
+ _private_directory(directory)
614
+ except FileNotFoundError:
615
+ return result
616
+ paths = []
617
+ for path in directory.iterdir():
618
+ if len(paths) >= 256:
619
+ raise ComponentRuntimeError("component_process_journal_invalid")
620
+ paths.append(path)
621
+ if not paths:
622
+ return result
623
+ events = []
624
+ fields = {
625
+ "schema_version",
626
+ "lease_id",
627
+ "target_id",
628
+ "installation_id",
629
+ "owner_nonce",
630
+ "owner_process_id",
631
+ "owner_start_identity",
632
+ "sequence",
633
+ "stage",
634
+ "process_id",
635
+ "process_start_identity",
636
+ }
637
+ for sequence, path in enumerate(sorted(paths), 1):
638
+ event = _record(path, fields, 16_384)
639
+ if (
640
+ event is None
641
+ or path.name != f"{sequence:06d}.json"
642
+ or (
643
+ type(event["sequence"]) is not int
644
+ or event["sequence"] != sequence
645
+ or event["lease_id"] != lease_id
646
+ or event["target_id"] != record["target_id"]
647
+ or event["installation_id"] != record["installation_id"]
648
+ or event["owner_nonce"] != record["owner_nonce"]
649
+ or type(event["owner_process_id"]) is not int
650
+ or event["owner_process_id"] != record["process_id"]
651
+ or event["stage"] not in {"spawn_pending", "spawn_started", "descendant_observed"}
652
+ )
653
+ ):
654
+ raise ComponentRuntimeError("component_process_journal_invalid")
655
+ owner_identity = event["owner_start_identity"]
656
+ if owner_identity is not None:
657
+ _identifier(owner_identity)
658
+ if events and owner_identity != events[0]["owner_start_identity"]:
659
+ raise ComponentRuntimeError("component_process_journal_invalid")
660
+ if event["stage"] == "spawn_pending":
661
+ if event["process_id"] is not None or event["process_start_identity"] is not None:
662
+ raise ComponentRuntimeError("component_process_journal_invalid")
663
+ else:
664
+ if event["stage"] == "spawn_started" and (
665
+ not events or events[-1]["stage"] != "spawn_pending"
666
+ ):
667
+ raise ComponentRuntimeError("component_process_journal_invalid")
668
+ if event["stage"] == "descendant_observed" and not any(
669
+ value["stage"] == "spawn_started" for value in events
670
+ ):
671
+ raise ComponentRuntimeError("component_process_journal_invalid")
672
+ if type(event["process_id"]) is not int or event["process_id"] <= 0:
673
+ raise ComponentRuntimeError("component_process_journal_invalid")
674
+ identity = event["process_start_identity"]
675
+ if identity is not None:
676
+ _identifier(identity)
677
+ result["processes"].append(
678
+ {
679
+ "process_id": event["process_id"],
680
+ "start_identity": identity,
681
+ "alive": _identity_alive(event["process_id"], identity),
682
+ "role": "descendant" if event["stage"] == "descendant_observed" else "root",
683
+ }
684
+ )
685
+ events.append(event)
686
+ result["owner_alive"] = _identity_alive(record["process_id"], events[0]["owner_start_identity"])
687
+ if result["owner_alive"] is True or any(
688
+ process["alive"] is True for process in result["processes"]
689
+ ):
690
+ result["state"] = "active"
691
+ else:
692
+ result["state"] = (
693
+ "spawn_unknown" if events[-1]["stage"] == "spawn_pending" else "descendants_unknown"
694
+ )
695
+ return result
696
+
697
+
404
698
  def runtime_capabilities(
405
699
  runtime_instance_id: str, root: Path | None = None
406
700
  ) -> dict[str, Any] | None:
@@ -469,6 +763,18 @@ def _acquire_component(
469
763
  if not selection["enabled"]:
470
764
  raise ComponentRuntimeError("component_disabled")
471
765
  installation_id = _identifier(selection["installation_id"])
766
+ maintenance = _record(
767
+ root / "maintenance" / f"{installation_id}.json",
768
+ {"schema_version", "target_id", "installation_id", "operation_id"},
769
+ )
770
+ if maintenance is not None:
771
+ _identifier(maintenance["operation_id"])
772
+ if (
773
+ maintenance["target_id"] != target["target_id"]
774
+ or maintenance["installation_id"] != installation_id
775
+ ):
776
+ raise ComponentRuntimeError("component_record_invalid")
777
+ raise ComponentRuntimeError("component_maintenance_pending")
472
778
  receipt = _record(
473
779
  root / "receipts" / f"{installation_id}.json",
474
780
  {
@@ -620,6 +926,40 @@ def current_execution() -> ManagedComponentLease | None:
620
926
  return _EXECUTION_LEASE.get()
621
927
 
622
928
 
929
+ async def observe_owned_process(lease: ManagedComponentLease, process: Any) -> None:
930
+ stop = asyncio.Event()
931
+ while process.returncode is None:
932
+ try:
933
+ await asyncio.wait_for(
934
+ asyncio.to_thread(lease.observe_descendants, process.pid), timeout=1
935
+ )
936
+ except (asyncio.TimeoutError, OSError, ComponentRuntimeError):
937
+ pass
938
+ try:
939
+ await asyncio.wait_for(stop.wait(), timeout=5)
940
+ except asyncio.TimeoutError:
941
+ continue
942
+
943
+
944
+ def harness_command(
945
+ lease: ManagedComponentLease | None,
946
+ component_id: str,
947
+ binary: str,
948
+ command: list[str],
949
+ environment: dict[str, str],
950
+ ) -> tuple[list[str], dict[str, str]]:
951
+ if lease is None:
952
+ return command, environment
953
+ if lease.receipt["release"]["component_id"] != component_id or binary != lease.argv_prefix[-1]:
954
+ raise ComponentRuntimeError("component_instance_changed")
955
+ lease.verify()
956
+ if command and command[0] == binary:
957
+ command = lease.wrap_command(command)
958
+ elif command[: len(lease.argv_prefix)] != lease.argv_prefix:
959
+ raise ComponentRuntimeError("component_harness_entry_unverified")
960
+ return command, {**environment, "DISABLE_UPDATES": "1", "DISABLE_AUTOUPDATER": "1"}
961
+
962
+
623
963
  def execution_command(command: list[str], environment: dict[str, str] | None):
624
964
  lease = current_execution()
625
965
  if lease is None or not command or command[0] != lease.argv_prefix[-1]:
@@ -142,10 +142,31 @@ async def _create_subprocess_exec(*command, **kwargs):
142
142
  # Desktop stdin is its parent-liveness control pipe, never child input.
143
143
  # Agent callers that need prompt input explicitly pass subprocess.PIPE.
144
144
  kwargs.setdefault("stdin", asyncio.subprocess.DEVNULL)
145
- process = await asyncio.create_subprocess_exec(*command, **kwargs)
146
145
  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
146
+ tracked = (
147
+ lease is not None
148
+ and bool(original_command)
149
+ and original_command[0] == lease.argv_prefix[-1]
150
+ )
151
+ if tracked:
152
+ await asyncio.to_thread(lease.begin_spawn)
153
+ process = await asyncio.create_subprocess_exec(*command, **kwargs)
154
+ if tracked:
155
+ try:
156
+ await asyncio.to_thread(lease.record_process, process.pid)
157
+ except (OSError, component_runtime.ComponentRuntimeError):
158
+ agent_core._kill_proc(process)
159
+ try:
160
+ await asyncio.wait_for(process.wait(), timeout=5)
161
+ except (asyncio.TimeoutError, OSError) as exc:
162
+ raise component_runtime.ComponentRuntimeError(
163
+ "component_process_cleanup_unconfirmed"
164
+ ) from exc
165
+ if process.returncode is None:
166
+ raise component_runtime.ComponentRuntimeError(
167
+ "component_process_cleanup_unconfirmed"
168
+ )
169
+ raise
149
170
  return process
150
171
 
151
172
 
@@ -1391,7 +1412,7 @@ except (ImportError, ModuleNotFoundError):
1391
1412
  # DAEMON_VERSION is the protocol/logic version of the daemon code.
1392
1413
  # Kept in sync with pyproject.toml version via bump-version.sh.
1393
1414
  # CLIENT_TYPE identifies which packaging/distribution this daemon runs in.
1394
- DAEMON_VERSION = "1.96.2"
1415
+ DAEMON_VERSION = "1.96.4"
1395
1416
 
1396
1417
 
1397
1418
  def _detect_client_type() -> str:
@@ -7345,6 +7366,11 @@ class ProcessManager:
7345
7366
  _start_time = time.monotonic()
7346
7367
  # Mutable state shared between nested coroutines (list avoids nonlocal)
7347
7368
  _last_activity_at: list[float] = [time.monotonic()]
7369
+ _last_descendant_observation = 0.0
7370
+ component_lease = component_runtime.current_execution()
7371
+ observes_component = (
7372
+ component_lease is not None and proc.pid in component_lease.registered_roots
7373
+ )
7348
7374
 
7349
7375
  # Write prompt and close stdin so the agent knows input is done.
7350
7376
  if proc.stdin:
@@ -7389,6 +7415,7 @@ class ProcessManager:
7389
7415
  pass
7390
7416
 
7391
7417
  async def _read_stdout():
7418
+ nonlocal _last_descendant_observation
7392
7419
  if not proc.stdout:
7393
7420
  return
7394
7421
  pending_line = ""
@@ -7444,12 +7471,22 @@ class ProcessManager:
7444
7471
  _kill_proc(proc)
7445
7472
  raise _IdleTimeoutError(idle_elapsed)
7446
7473
 
7474
+ if observes_component and now - _last_descendant_observation >= 5:
7475
+ _last_descendant_observation = now
7476
+ try:
7477
+ await asyncio.wait_for(
7478
+ asyncio.to_thread(component_lease.observe_descendants, proc.pid),
7479
+ timeout=min(1.0, max(0.001, timeout - elapsed_abs)),
7480
+ )
7481
+ except (asyncio.TimeoutError, OSError, component_runtime.ComponentRuntimeError):
7482
+ logger.debug("Component descendants remain unverified for task %s", task_id)
7483
+
7447
7484
  # Check interval capped at 30s so the loop stays responsive
7448
7485
  # even when both timeouts are far away.
7449
7486
  check_interval = min(
7450
7487
  idle_timeout - idle_elapsed + 0.5, # until idle fires
7451
7488
  timeout - elapsed_abs + 0.5, # until absolute fires
7452
- 30.0,
7489
+ 5.0 if observes_component else 30.0,
7453
7490
  )
7454
7491
 
7455
7492
  # ── Read available bytes with a bounded wait ───────────────────
@@ -161,6 +161,8 @@ class ZCodeProtocolSession:
161
161
  self._process: asyncio.subprocess.Process | None = None
162
162
  self._reader_task: asyncio.Task[None] | None = None
163
163
  self._stderr_task: asyncio.Task[None] | None = None
164
+ self._observer_task: asyncio.Task[None] | None = None
165
+ self._observer_stop = asyncio.Event()
164
166
  self._pending: dict[str, asyncio.Future[Any]] = {}
165
167
  self._write_lock = asyncio.Lock()
166
168
  self._active_turn: asyncio.Future[_TurnTerminal] | None = None
@@ -195,6 +197,7 @@ class ZCodeProtocolSession:
195
197
  command = self.component_lease.wrap_command(command)
196
198
  process_env = {**(process_env if process_env is not None else os.environ),
197
199
  "DISABLE_UPDATES": "1", "DISABLE_AUTOUPDATER": "1"}
200
+ await asyncio.to_thread(self.component_lease.begin_spawn)
198
201
  self._process = await asyncio.create_subprocess_exec(
199
202
  *command,
200
203
  stdin=asyncio.subprocess.PIPE,
@@ -206,9 +209,30 @@ class ZCodeProtocolSession:
206
209
  **agent_core._agent_process_group_kwargs(),
207
210
  )
208
211
  if self.component_lease is not None:
209
- self.component_lease.process_started = True
212
+ await asyncio.to_thread(self.component_lease.record_process, self._process.pid)
210
213
  self._reader_task = asyncio.create_task(self._read_loop())
211
214
  self._stderr_task = asyncio.create_task(self._read_stderr())
215
+ if self.component_lease is not None:
216
+ self._observer_task = asyncio.create_task(self._observe_process_tree())
217
+
218
+ async def _observe_process_tree(self) -> None:
219
+ while not self._observer_stop.is_set():
220
+ process = self._process
221
+ if process is None or process.returncode is not None or self.component_lease is None:
222
+ return
223
+ try:
224
+ await asyncio.wait_for(
225
+ asyncio.to_thread(self.component_lease.observe_descendants, process.pid),
226
+ timeout=1,
227
+ )
228
+ except (
229
+ asyncio.TimeoutError, OSError, agent_core.component_runtime.ComponentRuntimeError,
230
+ ):
231
+ logger.debug("ZCode component descendants remain unverified")
232
+ try:
233
+ await asyncio.wait_for(self._observer_stop.wait(), timeout=5)
234
+ except asyncio.TimeoutError:
235
+ continue
212
236
 
213
237
  async def create_session(
214
238
  self,
@@ -367,6 +391,10 @@ class ZCodeProtocolSession:
367
391
  if self._closed:
368
392
  return
369
393
  self._closed = True
394
+ self._observer_stop.set()
395
+ if self._observer_task is not None:
396
+ self._observer_task.cancel()
397
+ await asyncio.gather(self._observer_task, return_exceptions=True)
370
398
  if self._active_turn is not None and not self._active_turn.done():
371
399
  self._active_turn.set_exception(ZCodeProtocolError("ZCode Protocol session closed"))
372
400
  self._fail_pending(ZCodeProtocolError("ZCode Protocol session closed"))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: forgexa-cli
3
- Version: 1.96.2
3
+ Version: 1.96.4
4
4
  Summary: Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform
5
5
  Author-email: Jason Sun <dev.winds@gmail.com>
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "forgexa-cli"
3
- version = "1.96.2"
3
+ version = "1.96.4"
4
4
  description = "Forgexa CLI — command-line client and AI agent runtime for the Forgexa platform"
5
5
  requires-python = ">=3.9"
6
6
  license = "MIT"
File without changes
File without changes