forgexa-cli 1.96.3__tar.gz → 1.96.5__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 (36) hide show
  1. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/PKG-INFO +1 -1
  2. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/agent_core.py +37 -3
  4. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/component_runtime.py +142 -13
  5. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/daemon.py +18 -2
  6. forgexa_cli-1.96.5/forgexa_cli/ocr_adapter.py +319 -0
  7. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/zcode_protocol.py +27 -0
  8. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/PKG-INFO +1 -1
  9. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/SOURCES.txt +1 -0
  10. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/pyproject.toml +1 -1
  11. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/README.md +0 -0
  12. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/_build_config.py +0 -0
  13. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/_local_bind.py +0 -0
  14. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/autoupgrade.py +0 -0
  15. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/aws_evidence.py +0 -0
  16. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/aws_logs_evidence.py +0 -0
  17. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/main.py +0 -0
  18. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/observability_contract.py +0 -0
  19. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/observability_evidence.py +0 -0
  20. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/py.typed +0 -0
  21. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli/runtime_evidence.py +0 -0
  22. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  23. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/entry_points.txt +0 -0
  24. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/requires.txt +0 -0
  25. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/forgexa_cli.egg-info/top_level.txt +0 -0
  26. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/setup.cfg +0 -0
  27. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_auth_and_runtime_commands.py +0 -0
  28. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_autoupgrade.py +0 -0
  29. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_check_command.py +0 -0
  30. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_expiry_warnings_and_revoke.py +0 -0
  31. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_local_bind_commands.py +0 -0
  32. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_publish_script.py +0 -0
  33. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_runtime_credentials.py +0 -0
  34. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_session_credentials.py +0 -0
  35. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/tests/test_silent_install.py +0 -0
  36. {forgexa_cli-1.96.3 → forgexa_cli-1.96.5}/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.3
3
+ Version: 1.96.5
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.3"
2
+ __version__ = "1.96.5"
@@ -4016,9 +4016,14 @@ async def run_minimax(
4016
4016
  max_steps: int = 60, model: str | None = None, session_id: str | None = None,
4017
4017
  on_event: Any = None, on_started: Any = None, on_chunk: Any = None,
4018
4018
  cancel_requested: Any = None,
4019
+ component_lease: Any = None,
4019
4020
  ) -> dict:
4021
+ lease = (
4022
+ component_lease if component_lease is not None else component_runtime.current_execution()
4023
+ )
4020
4024
  state = MiniMaxRunState(expected_session_id=session_id)
4021
4025
  process = None
4026
+ observer = None
4022
4027
  lock = None
4023
4028
  root = None
4024
4029
  temporary = None
@@ -4072,19 +4077,28 @@ async def run_minimax(
4072
4077
  config=root / "config/runtime.json", timeout=remaining,
4073
4078
  max_steps=max_steps, model=model, session_id=session_id)
4074
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
+ )
4075
4084
  command = _minimax_sandbox(command, admission, cwd, temporary_root)
4076
4085
  if cancel_requested is not None and cancel_requested():
4077
4086
  return state.finish(-1, cancelled=True)
4078
4087
  _minimax_write_record(active, {"fingerprint": binding_identity, "state": "spawning"})
4088
+ if lease is not None:
4089
+ await asyncio.to_thread(lease.begin_spawn)
4079
4090
  process = await asyncio.create_subprocess_exec(
4080
- *command, cwd=str(cwd), env=minimax_base_env(root, temporary_root),
4091
+ *command, cwd=str(cwd), env=environment,
4081
4092
  stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
4082
4093
  stderr=asyncio.subprocess.PIPE, limit=MINIMAX_MAX_OUTPUT_BYTES,
4083
4094
  **_agent_process_group_kwargs(),
4084
4095
  )
4085
- _minimax_write_record(active, {"pid": process.pid, "fingerprint": binding_identity})
4086
4096
  if on_started is not None:
4087
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})
4088
4102
 
4089
4103
  async def read_stderr() -> None:
4090
4104
  nonlocal stderr_bytes
@@ -4154,6 +4168,9 @@ async def run_minimax(
4154
4168
  code = "minimax_profile_busy" if "busy" in str(error) else "minimax_startup_failed"
4155
4169
  state.fail(str(error) if isinstance(error, (ValueError, RuntimeError)) else "MiniMax startup or stream I/O failed", code)
4156
4170
  finally:
4171
+ if observer is not None:
4172
+ observer.cancel()
4173
+ await asyncio.gather(observer, return_exceptions=True)
4157
4174
  cleaned = True
4158
4175
  if process is not None:
4159
4176
  _kill_proc(process)
@@ -4872,9 +4889,14 @@ async def run_deepseek_harness(
4872
4889
  on_started: Any = None,
4873
4890
  on_chunk: Any = None,
4874
4891
  cancel_requested: Any = None,
4892
+ component_lease: Any = None,
4875
4893
  ) -> dict:
4876
4894
  """Execute and validate a supervised one-shot process with bounded output."""
4877
4895
  process = None
4896
+ observer = None
4897
+ lease = (
4898
+ component_lease if component_lease is not None else component_runtime.current_execution()
4899
+ )
4878
4900
  state = DeepSeekHarnessRunState(expected_cwd=str(workspace_path))
4879
4901
  raw_lines = []
4880
4902
  raw_bytes = 0
@@ -4884,14 +4906,23 @@ async def run_deepseek_harness(
4884
4906
  try:
4885
4907
  command, env = await asyncio.to_thread(runtime.__enter__)
4886
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)
4887
4915
  process = await asyncio.create_subprocess_exec(
4888
- *_prepare_agent_command(command), cwd=str(workspace_path), env=env,
4916
+ *command, cwd=str(workspace_path), env=env,
4889
4917
  stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
4890
4918
  stderr=asyncio.subprocess.PIPE, limit=DEEPSEEK_HARNESS_MAX_OUTPUT_BYTES,
4891
4919
  **_agent_process_group_kwargs(),
4892
4920
  )
4893
4921
  if on_started is not None:
4894
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))
4895
4926
  if cancel_requested is not None and cancel_requested():
4896
4927
  _kill_proc(process)
4897
4928
 
@@ -4977,6 +5008,9 @@ async def run_deepseek_harness(
4977
5008
  code = "deepseek_harness_profile_busy" if "profile is busy" in message else "deepseek_harness_startup_failed"
4978
5009
  state.fail(message, code)
4979
5010
  finally:
5011
+ if observer is not None:
5012
+ observer.cancel()
5013
+ await asyncio.gather(observer, return_exceptions=True)
4980
5014
  if process is not None and process.returncode is None:
4981
5015
  _kill_proc(process)
4982
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
@@ -130,6 +132,9 @@ class ManagedComponentLease:
130
132
  self.record_path = root / "leases" / f"{self.lease_id}.json"
131
133
  self.process_directory = root / "leases" / f"{self.lease_id}.processes"
132
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()
133
138
  digest = _digest(receipt["installation_id"].removeprefix("install-"))
134
139
  self.directory = root / "versions" / digest
135
140
  entry = receipt["entry_point"]
@@ -146,7 +151,21 @@ class ManagedComponentLease:
146
151
  if entry["kind"] != "native":
147
152
  self.argv_prefix.append(str(self.directory / _relative(entry["script"])))
148
153
 
149
- def _write_process_event(self, stage: str, process_id: int | None = None) -> None:
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]:
150
169
  if self.descriptor < 0 or self.process_sequence >= 256:
151
170
  raise ComponentRuntimeError("component_usage_unavailable")
152
171
  _private_directory(self.root)
@@ -187,6 +206,8 @@ class ManagedComponentLease:
187
206
  process_identity = _process_start_identity(process_id)
188
207
  except ComponentRuntimeError:
189
208
  pass
209
+ if expected_identity is not None and process_identity != expected_identity:
210
+ raise ComponentRuntimeError("component_process_identity_unverified")
190
211
  sequence = self.process_sequence + 1
191
212
  event = {
192
213
  "schema_version": 1,
@@ -218,6 +239,7 @@ class ManagedComponentLease:
218
239
  finally:
219
240
  os.close(directory)
220
241
  self.process_sequence = sequence
242
+ return event
221
243
 
222
244
  def begin_spawn(self) -> None:
223
245
  self.process_started = True
@@ -229,10 +251,53 @@ class ManagedComponentLease:
229
251
  def record_process(self, process_id: int) -> None:
230
252
  self.process_started = True
231
253
  try:
232
- self._write_process_event("spawn_started", process_id)
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"]
233
257
  except OSError as error:
234
258
  raise ComponentRuntimeError("component_usage_unavailable") from error
235
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
+
236
301
  def wrap_command(self, command: list[str]) -> list[str]:
237
302
  if not command or command[0] != self.argv_prefix[-1]:
238
303
  raise ComponentRuntimeError("component_instance_changed")
@@ -539,6 +604,7 @@ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
539
604
  "lease_id": lease_id,
540
605
  "installation_id": record["installation_id"],
541
606
  "state": "legacy_unknown",
607
+ "descendant_coverage": "observed_only",
542
608
  "owner_alive": None,
543
609
  "processes": [],
544
610
  }
@@ -582,7 +648,7 @@ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
582
648
  or event["owner_nonce"] != record["owner_nonce"]
583
649
  or type(event["owner_process_id"]) is not int
584
650
  or event["owner_process_id"] != record["process_id"]
585
- or event["stage"] not in {"spawn_pending", "spawn_started"}
651
+ or event["stage"] not in {"spawn_pending", "spawn_started", "descendant_observed"}
586
652
  )
587
653
  ):
588
654
  raise ComponentRuntimeError("component_process_journal_invalid")
@@ -595,7 +661,13 @@ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
595
661
  if event["process_id"] is not None or event["process_start_identity"] is not None:
596
662
  raise ComponentRuntimeError("component_process_journal_invalid")
597
663
  else:
598
- if not events or events[-1]["stage"] != "spawn_pending":
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
+ ):
599
671
  raise ComponentRuntimeError("component_process_journal_invalid")
600
672
  if type(event["process_id"]) is not int or event["process_id"] <= 0:
601
673
  raise ComponentRuntimeError("component_process_journal_invalid")
@@ -607,6 +679,7 @@ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
607
679
  "process_id": event["process_id"],
608
680
  "start_identity": identity,
609
681
  "alive": _identity_alive(event["process_id"], identity),
682
+ "role": "descendant" if event["stage"] == "descendant_observed" else "root",
610
683
  }
611
684
  )
612
685
  events.append(event)
@@ -622,10 +695,7 @@ def inspect_usage(lease_id: str, root: Path | None = None) -> dict[str, Any]:
622
695
  return result
623
696
 
624
697
 
625
- def runtime_capabilities(
626
- runtime_instance_id: str, root: Path | None = None
627
- ) -> dict[str, Any] | None:
628
- _identifier(runtime_instance_id)
698
+ def inspect_target(root: Path | None = None) -> dict[str, Any] | None:
629
699
  root = default_store_root() if root is None else root
630
700
  if root.is_symlink():
631
701
  raise ComponentRuntimeError("component_storage_invalid")
@@ -634,7 +704,16 @@ def runtime_capabilities(
634
704
  if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
635
705
  raise ComponentRuntimeError("component_platform_unverified")
636
706
  with _ComponentManagerLock(root):
637
- target = _component_target(root)
707
+ return _component_target(root)
708
+
709
+
710
+ def runtime_capabilities(
711
+ runtime_instance_id: str, root: Path | None = None
712
+ ) -> dict[str, Any] | None:
713
+ _identifier(runtime_instance_id)
714
+ target = inspect_target(root)
715
+ if target is None:
716
+ return None
638
717
  process_id = os.getpid()
639
718
  return {
640
719
  "schema_version": 1,
@@ -649,9 +728,12 @@ def runtime_capabilities(
649
728
 
650
729
 
651
730
  def _acquire_component(
652
- component_id: str, root: Path | None = None, override: str | None = None
731
+ component_id: str, root: Path | None = None, override: str | None = None,
732
+ kind: str = "agent",
653
733
  ) -> ManagedComponentLease | None:
654
734
  _identifier(component_id)
735
+ if kind not in {"agent", "plugin"}:
736
+ raise ComponentRuntimeError("component_receipt_invalid")
655
737
  root = default_store_root() if root is None else root
656
738
  if root.is_symlink():
657
739
  raise ComponentRuntimeError("component_storage_invalid")
@@ -690,6 +772,18 @@ def _acquire_component(
690
772
  if not selection["enabled"]:
691
773
  raise ComponentRuntimeError("component_disabled")
692
774
  installation_id = _identifier(selection["installation_id"])
775
+ maintenance = _record(
776
+ root / "maintenance" / f"{installation_id}.json",
777
+ {"schema_version", "target_id", "installation_id", "operation_id"},
778
+ )
779
+ if maintenance is not None:
780
+ _identifier(maintenance["operation_id"])
781
+ if (
782
+ maintenance["target_id"] != target["target_id"]
783
+ or maintenance["installation_id"] != installation_id
784
+ ):
785
+ raise ComponentRuntimeError("component_record_invalid")
786
+ raise ComponentRuntimeError("component_maintenance_pending")
693
787
  receipt = _record(
694
788
  root / "receipts" / f"{installation_id}.json",
695
789
  {
@@ -728,7 +822,7 @@ def _acquire_component(
728
822
  if (
729
823
  type(release["schema_version"]) is not int
730
824
  or release["schema_version"] != 1
731
- or release["kind"] != "agent"
825
+ or release["kind"] != kind
732
826
  ):
733
827
  raise ComponentRuntimeError("component_receipt_invalid")
734
828
  for name in ("component_id", "release_id", "protocol_generation"):
@@ -794,10 +888,11 @@ def _acquire_component(
794
888
 
795
889
 
796
890
  def acquire_component(
797
- component_id: str, root: Path | None = None, override: str | None = None
891
+ component_id: str, root: Path | None = None, override: str | None = None,
892
+ kind: str = "agent",
798
893
  ) -> ManagedComponentLease | None:
799
894
  try:
800
- return _acquire_component(component_id, root, override)
895
+ return _acquire_component(component_id, root, override, kind)
801
896
  except OSError as error:
802
897
  raise ComponentRuntimeError("component_storage_unavailable") from error
803
898
 
@@ -841,6 +936,40 @@ def current_execution() -> ManagedComponentLease | None:
841
936
  return _EXECUTION_LEASE.get()
842
937
 
843
938
 
939
+ async def observe_owned_process(lease: ManagedComponentLease, process: Any) -> None:
940
+ stop = asyncio.Event()
941
+ while process.returncode is None:
942
+ try:
943
+ await asyncio.wait_for(
944
+ asyncio.to_thread(lease.observe_descendants, process.pid), timeout=1
945
+ )
946
+ except (asyncio.TimeoutError, OSError, ComponentRuntimeError):
947
+ pass
948
+ try:
949
+ await asyncio.wait_for(stop.wait(), timeout=5)
950
+ except asyncio.TimeoutError:
951
+ continue
952
+
953
+
954
+ def harness_command(
955
+ lease: ManagedComponentLease | None,
956
+ component_id: str,
957
+ binary: str,
958
+ command: list[str],
959
+ environment: dict[str, str],
960
+ ) -> tuple[list[str], dict[str, str]]:
961
+ if lease is None:
962
+ return command, environment
963
+ if lease.receipt["release"]["component_id"] != component_id or binary != lease.argv_prefix[-1]:
964
+ raise ComponentRuntimeError("component_instance_changed")
965
+ lease.verify()
966
+ if command and command[0] == binary:
967
+ command = lease.wrap_command(command)
968
+ elif command[: len(lease.argv_prefix)] != lease.argv_prefix:
969
+ raise ComponentRuntimeError("component_harness_entry_unverified")
970
+ return command, {**environment, "DISABLE_UPDATES": "1", "DISABLE_AUTOUPDATER": "1"}
971
+
972
+
844
973
  def execution_command(command: list[str], environment: dict[str, str] | None):
845
974
  lease = current_execution()
846
975
  if lease is None or not command or command[0] != lease.argv_prefix[-1]:
@@ -1412,7 +1412,7 @@ except (ImportError, ModuleNotFoundError):
1412
1412
  # DAEMON_VERSION is the protocol/logic version of the daemon code.
1413
1413
  # Kept in sync with pyproject.toml version via bump-version.sh.
1414
1414
  # CLIENT_TYPE identifies which packaging/distribution this daemon runs in.
1415
- DAEMON_VERSION = "1.96.3"
1415
+ DAEMON_VERSION = "1.96.5"
1416
1416
 
1417
1417
 
1418
1418
  def _detect_client_type() -> str:
@@ -7366,6 +7366,11 @@ class ProcessManager:
7366
7366
  _start_time = time.monotonic()
7367
7367
  # Mutable state shared between nested coroutines (list avoids nonlocal)
7368
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
+ )
7369
7374
 
7370
7375
  # Write prompt and close stdin so the agent knows input is done.
7371
7376
  if proc.stdin:
@@ -7410,6 +7415,7 @@ class ProcessManager:
7410
7415
  pass
7411
7416
 
7412
7417
  async def _read_stdout():
7418
+ nonlocal _last_descendant_observation
7413
7419
  if not proc.stdout:
7414
7420
  return
7415
7421
  pending_line = ""
@@ -7465,12 +7471,22 @@ class ProcessManager:
7465
7471
  _kill_proc(proc)
7466
7472
  raise _IdleTimeoutError(idle_elapsed)
7467
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
+
7468
7484
  # Check interval capped at 30s so the loop stays responsive
7469
7485
  # even when both timeouts are far away.
7470
7486
  check_interval = min(
7471
7487
  idle_timeout - idle_elapsed + 0.5, # until idle fires
7472
7488
  timeout - elapsed_abs + 0.5, # until absolute fires
7473
- 30.0,
7489
+ 5.0 if observes_component else 30.0,
7474
7490
  )
7475
7491
 
7476
7492
  # ── Read available bytes with a bounded wait ───────────────────
@@ -0,0 +1,319 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import math
6
+ import os
7
+ import re
8
+ import shutil
9
+ import signal
10
+ import tempfile
11
+ from pathlib import Path, PurePosixPath
12
+ from typing import Any
13
+
14
+ if __package__:
15
+ from .component_runtime import ManagedComponentLease, observe_owned_process
16
+ else:
17
+ from component_runtime import ManagedComponentLease, observe_owned_process
18
+
19
+ OCR_COMPONENT_ID = "forgexa.ocr"
20
+ OCR_OUTPUT_LIMIT = 1024 * 1024
21
+ OCR_FILE_LIMIT = 5000
22
+
23
+
24
+ class OcrAdapterError(RuntimeError):
25
+ def __init__(self, code: str) -> None:
26
+ self.code = code
27
+ super().__init__(code)
28
+
29
+
30
+ def _object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
31
+ result: dict[str, Any] = {}
32
+ for key, value in pairs:
33
+ if key in result:
34
+ raise OcrAdapterError("ocr_output_invalid")
35
+ result[key] = value
36
+ return result
37
+
38
+
39
+ def _decode(payload: bytes | str) -> dict[str, Any]:
40
+ if len(payload if isinstance(payload, bytes) else payload.encode()) > OCR_OUTPUT_LIMIT:
41
+ raise OcrAdapterError("ocr_output_limit")
42
+ try:
43
+ value = json.loads(payload, object_pairs_hook=_object)
44
+ except (ValueError, UnicodeError) as exc:
45
+ raise OcrAdapterError("ocr_output_invalid") from exc
46
+ if not isinstance(value, dict) or value.get("schema_version") != "1":
47
+ raise OcrAdapterError("ocr_schema_unsupported")
48
+ return value
49
+
50
+
51
+ def _count(value: Any) -> int:
52
+ if type(value) is not int or value < 0 or value > 9_007_199_254_740_991:
53
+ raise OcrAdapterError("ocr_output_invalid")
54
+ return value
55
+
56
+
57
+ def _text(value: Any, limit: int) -> str:
58
+ if not isinstance(value, str) or len(value) > limit or "\x00" in value:
59
+ raise OcrAdapterError("ocr_output_invalid")
60
+ return value
61
+
62
+
63
+ def _path(value: Any) -> str:
64
+ try:
65
+ value = _text(value, 4096)
66
+ except OcrAdapterError as exc:
67
+ raise OcrAdapterError("ocr_path_invalid") from exc
68
+ path = PurePosixPath(value)
69
+ if not value or path.is_absolute() or "\\" in value or ":" in value:
70
+ raise OcrAdapterError("ocr_path_invalid")
71
+ if any(part in {"", ".", ".."} for part in value.split("/")):
72
+ raise OcrAdapterError("ocr_path_invalid")
73
+ if any(ord(character) < 32 for character in value):
74
+ raise OcrAdapterError("ocr_path_invalid")
75
+ return value
76
+
77
+
78
+ def parse_ocr_preview(payload: bytes | str, repository: Path) -> dict[str, Any]:
79
+ value = _decode(payload)
80
+ if value.get("mode") != "workspace" or any(value.get(key) for key in ("from", "to", "commit")):
81
+ raise OcrAdapterError("ocr_mode_unsupported")
82
+ returned = Path(_text(value.get("repository"), 4096))
83
+ if not returned.is_absolute() or returned.resolve() != repository.resolve():
84
+ raise OcrAdapterError("ocr_repository_changed")
85
+ paths: set[str] = set()
86
+ for key, count_key in (
87
+ ("reviewable_files", "reviewable_count"),
88
+ ("excluded_files", "excluded_count"),
89
+ ):
90
+ files = value.get(key)
91
+ if (
92
+ not isinstance(files, list)
93
+ or len(files) > OCR_FILE_LIMIT
94
+ or len(files) != _count(value.get(count_key))
95
+ ):
96
+ raise OcrAdapterError("ocr_output_invalid")
97
+ for entry in files:
98
+ if not isinstance(entry, dict):
99
+ raise OcrAdapterError("ocr_output_invalid")
100
+ path = _path(entry.get("path"))
101
+ if path in paths:
102
+ raise OcrAdapterError("ocr_output_invalid")
103
+ paths.add(path)
104
+ if not _text(entry.get("status"), 128):
105
+ raise OcrAdapterError("ocr_output_invalid")
106
+ _count(entry.get("insertions"))
107
+ _count(entry.get("deletions"))
108
+ if "exclude_reason" in entry:
109
+ _text(entry["exclude_reason"], 2048)
110
+ if _count(value.get("total_files")) != len(paths) or len(paths) > OCR_FILE_LIMIT:
111
+ raise OcrAdapterError("ocr_output_invalid")
112
+ _count(value.get("total_insertions"))
113
+ _count(value.get("total_deletions"))
114
+ return value
115
+
116
+
117
+ def parse_ocr_rules(payload: bytes | str, requested_paths: list[str]) -> dict[str, Any]:
118
+ requested = {_path(path) for path in requested_paths}
119
+ if not requested or len(requested_paths) != len(requested) or len(requested) > OCR_FILE_LIMIT:
120
+ raise OcrAdapterError("ocr_path_invalid")
121
+ value = _decode(payload)
122
+ groups = value.get("groups")
123
+ if not isinstance(groups, list) or len(groups) > OCR_FILE_LIMIT:
124
+ raise OcrAdapterError("ocr_output_invalid")
125
+ group_ids: set[int] = set()
126
+ covered: set[str] = set()
127
+ for group in groups:
128
+ if not isinstance(group, dict):
129
+ raise OcrAdapterError("ocr_output_invalid")
130
+ group_id = _count(group.get("group_id"))
131
+ if group_id < 1 or group_id in group_ids:
132
+ raise OcrAdapterError("ocr_output_invalid")
133
+ group_ids.add(group_id)
134
+ _text(group.get("source"), 4096)
135
+ _text(group.get("pattern"), 4096)
136
+ _text(group.get("rule"), 64 * 1024)
137
+ files = group.get("files")
138
+ if not isinstance(files, list) or len(files) > OCR_FILE_LIMIT:
139
+ raise OcrAdapterError("ocr_output_invalid")
140
+ for entry in files:
141
+ path = _path(entry)
142
+ if path not in requested:
143
+ raise OcrAdapterError("ocr_rule_scope_invalid")
144
+ covered.add(path)
145
+ if covered != requested:
146
+ raise OcrAdapterError("ocr_rule_scope_invalid")
147
+ return value
148
+
149
+
150
+ async def _read_output(stream: asyncio.StreamReader, limit: int) -> bytes:
151
+ output = bytearray()
152
+ while True:
153
+ chunk = await stream.read(16 * 1024)
154
+ if not chunk:
155
+ return bytes(output)
156
+ output.extend(chunk)
157
+ if len(output) > limit:
158
+ raise OcrAdapterError("ocr_output_limit")
159
+
160
+
161
+ async def _stop_process(process: asyncio.subprocess.Process) -> None:
162
+ if process.returncode is not None:
163
+ return
164
+ try:
165
+ os.killpg(process.pid, signal.SIGTERM)
166
+ await asyncio.wait_for(process.wait(), 1)
167
+ except asyncio.TimeoutError:
168
+ try:
169
+ os.killpg(process.pid, signal.SIGKILL)
170
+ await asyncio.wait_for(process.wait(), 5)
171
+ except (asyncio.TimeoutError, OSError) as exc:
172
+ raise OcrAdapterError("ocr_cleanup_unconfirmed") from exc
173
+ except ProcessLookupError:
174
+ try:
175
+ await asyncio.wait_for(process.wait(), 5)
176
+ except asyncio.TimeoutError as exc:
177
+ raise OcrAdapterError("ocr_cleanup_unconfirmed") from exc
178
+
179
+
180
+ async def _command_output(
181
+ command: list[str],
182
+ directory: Path,
183
+ environment: dict[str, str],
184
+ timeout: float,
185
+ lease: ManagedComponentLease | None = None,
186
+ ) -> bytes:
187
+ process = None
188
+ observer = None
189
+ readers: list[asyncio.Task] = []
190
+ deadline = asyncio.get_running_loop().time() + timeout
191
+ try:
192
+ if lease is not None:
193
+ lease.verify()
194
+ lease.begin_spawn()
195
+ spawn = asyncio.create_task(
196
+ asyncio.create_subprocess_exec(
197
+ *command,
198
+ cwd=str(directory),
199
+ env=environment,
200
+ stdin=asyncio.subprocess.DEVNULL,
201
+ stdout=asyncio.subprocess.PIPE,
202
+ stderr=asyncio.subprocess.PIPE,
203
+ start_new_session=True,
204
+ )
205
+ )
206
+ try:
207
+ process = await asyncio.shield(spawn)
208
+ except asyncio.CancelledError:
209
+ process = await spawn
210
+ raise
211
+ if lease is not None:
212
+ lease.record_process(process.pid)
213
+ observer = asyncio.create_task(observe_owned_process(lease, process))
214
+ readers = [
215
+ asyncio.create_task(_read_output(process.stdout, OCR_OUTPUT_LIMIT)),
216
+ asyncio.create_task(_read_output(process.stderr, 64 * 1024)),
217
+ ]
218
+ output, _stderr = await asyncio.wait_for(
219
+ asyncio.gather(*readers),
220
+ max(0, deadline - asyncio.get_running_loop().time()),
221
+ )
222
+ await asyncio.wait_for(process.wait(), max(0, deadline - asyncio.get_running_loop().time()))
223
+ if process.returncode != 0:
224
+ raise OcrAdapterError("ocr_execution_failed")
225
+ if lease is not None:
226
+ lease.verify()
227
+ return output
228
+ except asyncio.TimeoutError as exc:
229
+ raise OcrAdapterError("ocr_timeout") from exc
230
+ finally:
231
+ if observer is not None:
232
+ observer.cancel()
233
+ await asyncio.gather(observer, return_exceptions=True)
234
+ try:
235
+ if process is not None:
236
+ await _stop_process(process)
237
+ finally:
238
+ for reader in readers:
239
+ reader.cancel()
240
+ if readers:
241
+ await asyncio.gather(*readers, return_exceptions=True)
242
+
243
+
244
+ async def run_ocr_delegation(
245
+ lease: ManagedComponentLease,
246
+ repository: Path,
247
+ action: str,
248
+ paths: list[str] | None = None,
249
+ timeout: float = 30,
250
+ ) -> dict[str, Any]:
251
+ if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
252
+ raise OcrAdapterError("ocr_platform_unverified")
253
+ release = lease.receipt["release"]
254
+ if release["component_id"] != OCR_COMPONENT_ID or release["kind"] != "plugin":
255
+ raise OcrAdapterError("ocr_instance_changed")
256
+ if (
257
+ not isinstance(action, str)
258
+ or action not in {"preview", "rule"}
259
+ or type(timeout) not in {int, float}
260
+ or not math.isfinite(timeout)
261
+ or timeout <= 0
262
+ or timeout > 60
263
+ ):
264
+ raise OcrAdapterError("ocr_request_invalid")
265
+ paths = [] if paths is None else paths
266
+ if (
267
+ not isinstance(paths, list)
268
+ or (action == "preview" and paths)
269
+ or (action == "rule" and not paths)
270
+ or len(paths) > OCR_FILE_LIMIT
271
+ ):
272
+ raise OcrAdapterError("ocr_request_invalid")
273
+ for path in paths:
274
+ _path(path)
275
+ if len(set(paths)) != len(paths):
276
+ raise OcrAdapterError("ocr_path_invalid")
277
+ repository = repository.resolve(strict=True)
278
+ if not repository.is_dir():
279
+ raise OcrAdapterError("ocr_repository_changed")
280
+ for path in paths:
281
+ if not (repository / path).resolve().is_relative_to(repository):
282
+ raise OcrAdapterError("ocr_path_invalid")
283
+ git = shutil.which("git")
284
+ if not git:
285
+ raise OcrAdapterError("ocr_git_unavailable")
286
+ with tempfile.TemporaryDirectory(prefix="forgexa-ocr-delegate-") as temporary:
287
+ directory = Path(temporary)
288
+ environment = lease.probe_environment(directory, baseline={})
289
+ environment.update(
290
+ {
291
+ "PATH": f"{Path(git).parent}{os.pathsep}{environment['PATH']}",
292
+ "GIT_CONFIG_NOSYSTEM": "1",
293
+ "GIT_CONFIG_GLOBAL": os.devnull,
294
+ "GIT_TERMINAL_PROMPT": "0",
295
+ }
296
+ )
297
+ version = await _command_output([git, "--version"], directory, environment, 5)
298
+ match = re.match(rb"git version (\d+)\.(\d+)", version)
299
+ if match is None or tuple(int(part) for part in match.groups()) < (2, 41):
300
+ raise OcrAdapterError("ocr_git_incompatible")
301
+ command = [
302
+ *lease.argv_prefix,
303
+ "delegate",
304
+ action,
305
+ "--format",
306
+ "json",
307
+ "--repo",
308
+ str(repository),
309
+ "--max-git-procs",
310
+ "2",
311
+ ]
312
+ if paths:
313
+ command.extend(["--", *paths])
314
+ output = await _command_output(command, repository, environment, timeout, lease)
315
+ return (
316
+ parse_ocr_preview(output, repository)
317
+ if action == "preview"
318
+ else parse_ocr_rules(output, paths)
319
+ )
@@ -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
@@ -210,6 +212,27 @@ class ZCodeProtocolSession:
210
212
  await asyncio.to_thread(self.component_lease.record_process, self._process.pid)
211
213
  self._reader_task = asyncio.create_task(self._read_loop())
212
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
213
236
 
214
237
  async def create_session(
215
238
  self,
@@ -368,6 +391,10 @@ class ZCodeProtocolSession:
368
391
  if self._closed:
369
392
  return
370
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)
371
398
  if self._active_turn is not None and not self._active_turn.done():
372
399
  self._active_turn.set_exception(ZCodeProtocolError("ZCode Protocol session closed"))
373
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.3
3
+ Version: 1.96.5
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
@@ -12,6 +12,7 @@ forgexa_cli/daemon.py
12
12
  forgexa_cli/main.py
13
13
  forgexa_cli/observability_contract.py
14
14
  forgexa_cli/observability_evidence.py
15
+ forgexa_cli/ocr_adapter.py
15
16
  forgexa_cli/py.typed
16
17
  forgexa_cli/runtime_evidence.py
17
18
  forgexa_cli/zcode_protocol.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "forgexa-cli"
3
- version = "1.96.3"
3
+ version = "1.96.5"
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