forgexa-cli 1.98.1__tar.gz → 1.98.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 (38) hide show
  1. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/PKG-INFO +1 -1
  2. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/__init__.py +1 -1
  3. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/agent_core.py +149 -19
  4. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/component_runtime.py +114 -5
  5. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/daemon.py +62 -18
  6. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/ocr_adapter.py +2 -1
  7. forgexa_cli-1.98.4/forgexa_cli/workspace_storage.py +348 -0
  8. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/PKG-INFO +1 -1
  9. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/SOURCES.txt +3 -1
  10. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/pyproject.toml +1 -1
  11. forgexa_cli-1.98.4/tests/test_workspace_storage.py +289 -0
  12. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/README.md +0 -0
  13. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/_build_config.py +0 -0
  14. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/_local_bind.py +0 -0
  15. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/autoupgrade.py +0 -0
  16. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/aws_evidence.py +0 -0
  17. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/aws_logs_evidence.py +0 -0
  18. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/main.py +0 -0
  19. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/observability_contract.py +0 -0
  20. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/observability_evidence.py +0 -0
  21. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/py.typed +0 -0
  22. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/runtime_evidence.py +0 -0
  23. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli/zcode_protocol.py +0 -0
  24. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/dependency_links.txt +0 -0
  25. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/entry_points.txt +0 -0
  26. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/requires.txt +0 -0
  27. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/forgexa_cli.egg-info/top_level.txt +0 -0
  28. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/setup.cfg +0 -0
  29. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_auth_and_runtime_commands.py +0 -0
  30. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_autoupgrade.py +0 -0
  31. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_check_command.py +0 -0
  32. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_expiry_warnings_and_revoke.py +0 -0
  33. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_local_bind_commands.py +0 -0
  34. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_publish_script.py +0 -0
  35. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_runtime_credentials.py +0 -0
  36. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_session_credentials.py +0 -0
  37. {forgexa_cli-1.98.1 → forgexa_cli-1.98.4}/tests/test_silent_install.py +0 -0
  38. {forgexa_cli-1.98.1 → forgexa_cli-1.98.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.98.1
3
+ Version: 1.98.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.98.1"
2
+ __version__ = "1.98.4"
@@ -777,7 +777,7 @@ def task_failure_domain(
777
777
  if failure_code in {
778
778
  "planned_task_incomplete", "planned_task_baseline_invalid", "approved_plan_baseline_modified",
779
779
  "remediation_scope_violation", "verification_work_item_scope_violation", "uncommitted_workspace_changes",
780
- "forbidden_branch_merge",
780
+ "forbidden_branch_merge", "required_deliverable_missing",
781
781
  }:
782
782
  return "delivery"
783
783
  if failure_code == "implementation_plan_revision_required":
@@ -888,6 +888,7 @@ def implementation_validation_issue_blocks(node_type: str, task_input: dict, cod
888
888
  "qa_policy.source_test_path_invalid",
889
889
  "qa_policy.source_change_inventory_unavailable",
890
890
  "uncommitted_workspace_changes", "forbidden_branch_merge",
891
+ "required_deliverable_missing",
891
892
  }
892
893
 
893
894
 
@@ -2097,6 +2098,12 @@ class AgentDiscovery:
2097
2098
  if additions:
2098
2099
  os.environ["PATH"] = os.pathsep.join(additions) + os.pathsep + current
2099
2100
  logger.debug("Expanded PATH with: %s", ", ".join(additions))
2101
+ for component in (*AgentDiscovery.AGENT_REGISTRY, "forgexa.ocr"):
2102
+ official_base = home / ".forgexa" / "official" / component
2103
+ official_bin = official_base if is_win else official_base / "bin"
2104
+ current = os.environ.get("PATH", "")
2105
+ if official_bin.is_dir() and str(official_bin) not in current.split(os.pathsep):
2106
+ os.environ["PATH"] = os.pathsep.join(filter(None, (current, str(official_bin))))
2100
2107
 
2101
2108
  @staticmethod
2102
2109
  def _wsl_windows_executable(path: str) -> bool:
@@ -2218,7 +2225,11 @@ class AgentDiscovery:
2218
2225
  async def _discover_instance(
2219
2226
  self, agent_id: str, spec: dict, managed: Any = None
2220
2227
  ) -> DiscoveredAgent | None:
2221
- custom_path = os.environ.get(spec.get("env_path_override", ""))
2228
+ selected_path, selected_revision = (
2229
+ await asyncio.to_thread(component_runtime.selected_external_agent_selection, agent_id)
2230
+ if managed is None else (None, None)
2231
+ )
2232
+ custom_path = selected_path or os.environ.get(spec.get("env_path_override", ""))
2222
2233
  cmd = managed.argv_prefix[-1] if managed is not None else custom_path or spec["commands"][0]
2223
2234
  resolved = shutil.which(cmd)
2224
2235
  if resolved:
@@ -2282,7 +2293,7 @@ class AgentDiscovery:
2282
2293
  min_version_ok=min_version_ok,
2283
2294
  version_warning=version_warning,
2284
2295
  installation_id=managed.receipt["installation_id"] if managed is not None else None,
2285
- selection_revision=managed.selection_revision if managed is not None else None,
2296
+ selection_revision=managed.selection_revision if managed is not None else selected_revision,
2286
2297
  )
2287
2298
  logger.info("Discovered agent: %s v%s (%s)", agent_id, version, resolved)
2288
2299
  if managed is not None:
@@ -2709,6 +2720,68 @@ def opencode_error_message(event: dict) -> str | None:
2709
2720
  return None
2710
2721
 
2711
2722
 
2723
+ @dataclass
2724
+ class OpenCodeRunState:
2725
+ """Track native completion independently of bounded stdout tails."""
2726
+
2727
+ session_id: str | None = None
2728
+ message_id: str | None = None
2729
+ messages: set[str] = field(default_factory=set)
2730
+ finish_reason: str | None = None
2731
+ error: str | None = None
2732
+ error_code: str = "agent_error"
2733
+
2734
+ def feed_output(self, output: str) -> None:
2735
+ for line in output.splitlines():
2736
+ try:
2737
+ event = json.loads(line)
2738
+ except json.JSONDecodeError:
2739
+ continue
2740
+ if isinstance(event, dict):
2741
+ self.feed(event)
2742
+
2743
+ def feed(self, event: dict) -> None:
2744
+ kind = event.get("type")
2745
+ if kind == "error":
2746
+ self.error = self.error or opencode_error_message(event) or "OpenCode reported an error"
2747
+ return
2748
+ if kind not in {"step_start", "text", "tool_use", "step_finish"}:
2749
+ return
2750
+ session, part = event.get("sessionID"), event.get("part")
2751
+ if not isinstance(session, str) or not session or not isinstance(part, dict):
2752
+ self.error = "OpenCode event has no session or part"
2753
+ self.error_code = "agent_protocol_error"
2754
+ return
2755
+ if self.session_id is not None and session != self.session_id:
2756
+ return
2757
+ message = part.get("messageID")
2758
+ if not isinstance(message, str) or not message:
2759
+ self.error = "OpenCode event has no message identity"
2760
+ self.error_code = "agent_protocol_error"
2761
+ return
2762
+ self.session_id = session
2763
+ if message != self.message_id:
2764
+ if message in self.messages:
2765
+ return
2766
+ self.messages.add(message)
2767
+ self.message_id, self.finish_reason = message, None
2768
+ if kind == "step_finish":
2769
+ self.finish_reason = part.get("reason")
2770
+
2771
+ def failure(self) -> tuple[str, str] | None:
2772
+ if self.error:
2773
+ return self.error_code, self.error
2774
+ if self.session_id is None:
2775
+ return "agent_protocol_error", "OpenCode did not emit valid JSON events"
2776
+ if self.finish_reason != "stop":
2777
+ return (
2778
+ "agent_incomplete_turn",
2779
+ "OpenCode exited without a final step_finish(reason=stop) for the active turn. "
2780
+ "Pending background-agent work cannot finish after this one-shot invocation exits.",
2781
+ )
2782
+ return None
2783
+
2784
+
2712
2785
  class OpenCodeUsage:
2713
2786
  """Accumulate v2 step totals once per native assistant message."""
2714
2787
 
@@ -3641,6 +3714,34 @@ def build_codex_command(
3641
3714
  return cmd
3642
3715
 
3643
3716
 
3717
+ OPENCODE_WORKER_AGENT = "forgexa-worker"
3718
+ _OPENCODE_WORKER_DENIED_TOOLS = (
3719
+ "task", "subagent", "delegate_task", "call_omo_agent",
3720
+ "background_output", "background_cancel",
3721
+ )
3722
+
3723
+
3724
+ class OpenCodeConfigurationError(RuntimeError):
3725
+ pass
3726
+
3727
+
3728
+ def opencode_worker_prompt(prompt: str) -> str:
3729
+ heading = "## Forgexa One-Shot Worker"
3730
+ if heading in prompt:
3731
+ return prompt
3732
+ return (
3733
+ f"{prompt}\n\n{heading}\n"
3734
+ "Execute the assigned task yourself in this invocation. Do not delegate to subagents "
3735
+ "or launch background-agent work. Skills and ordinary repository tools remain available. "
3736
+ "This is not an interactive orchestration session: returning ends the invocation, and "
3737
+ "no later background completion notifications will arrive. Do not finish with a progress "
3738
+ "update or a promise to continue later. Produce the requested outputs now; when outputs "
3739
+ "are files, write and check those files in the authorized workspace before finishing. "
3740
+ "If a prerequisite genuinely blocks work, report it explicitly and record permitted "
3741
+ "partial results and evidence gaps without claiming unverified completion."
3742
+ )
3743
+
3744
+
3644
3745
  def build_opencode_command(
3645
3746
  binary: str,
3646
3747
  *,
@@ -3651,6 +3752,7 @@ def build_opencode_command(
3651
3752
  prompt: str | None = None,
3652
3753
  profile: OpenCodeProfile = "v1",
3653
3754
  auto_approve: bool = True,
3755
+ single_worker: bool = False,
3654
3756
  ) -> list[str]:
3655
3757
  """OpenCode CLI non-interactive invocation.
3656
3758
 
@@ -3672,6 +3774,8 @@ def build_opencode_command(
3672
3774
  cmd.append("--auto" if profile == "v2" else "--dangerously-skip-permissions")
3673
3775
  if profile == "v1":
3674
3776
  cmd += ["--dir", str(cwd)]
3777
+ if single_worker:
3778
+ cmd += ["--agent", OPENCODE_WORKER_AGENT]
3675
3779
  if session_id:
3676
3780
  cmd += ["--session", session_id]
3677
3781
  if model:
@@ -5084,6 +5188,7 @@ def opencode_base_env(
5084
5188
  env: dict[str, str], *, data_home: str | Path | None = None,
5085
5189
  require_windows_shell: bool = False, profile: OpenCodeProfile = "v1",
5086
5190
  cwd: str | Path | None = None,
5191
+ single_worker: bool = False,
5087
5192
  ) -> dict[str, str]:
5088
5193
  """Isolate each OpenCode run in its own XDG data directory.
5089
5194
 
@@ -5102,6 +5207,31 @@ def opencode_base_env(
5102
5207
  for key in list(env):
5103
5208
  if key.upper().startswith(platform_secrets):
5104
5209
  del env[key]
5210
+ if single_worker:
5211
+ config = _opencode_config_content(env)
5212
+ agents = config.setdefault("agent", {})
5213
+ if not isinstance(agents, dict):
5214
+ raise OpenCodeConfigurationError(
5215
+ "OpenCode worker configuration requires an agent object",
5216
+ )
5217
+ worker = agents.setdefault(OPENCODE_WORKER_AGENT, {})
5218
+ if not isinstance(worker, dict):
5219
+ raise OpenCodeConfigurationError("OpenCode worker configuration must be an object")
5220
+ permissions = worker.get("permission", {})
5221
+ if isinstance(permissions, str):
5222
+ permissions = {"*": permissions}
5223
+ if not isinstance(permissions, dict):
5224
+ raise OpenCodeConfigurationError(
5225
+ "OpenCode worker permissions must be an object or action",
5226
+ )
5227
+ worker.update(
5228
+ mode="primary", hidden=True, disable=False,
5229
+ permission={
5230
+ **permissions,
5231
+ **dict.fromkeys(_OPENCODE_WORKER_DENIED_TOOLS, "deny"),
5232
+ },
5233
+ )
5234
+ env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config, ensure_ascii=False)
5105
5235
  if profile == "v1" and data_home is not None:
5106
5236
  env["XDG_DATA_HOME"] = str(data_home)
5107
5237
  if cwd is not None:
@@ -5112,6 +5242,21 @@ def opencode_base_env(
5112
5242
  return configure_opencode_windows_shell(env, required=require_windows_shell)
5113
5243
 
5114
5244
 
5245
+ def _opencode_config_content(env: dict[str, str]) -> dict[str, Any]:
5246
+ raw_config = env.get("OPENCODE_CONFIG_CONTENT", "").strip()
5247
+ if not raw_config:
5248
+ return {}
5249
+ try:
5250
+ config = json.loads(raw_config)
5251
+ except json.JSONDecodeError as exc:
5252
+ raise OpenCodeConfigurationError(
5253
+ "OpenCode OPENCODE_CONFIG_CONTENT must be a JSON object",
5254
+ ) from exc
5255
+ if not isinstance(config, dict):
5256
+ raise OpenCodeConfigurationError("OpenCode OPENCODE_CONFIG_CONTENT must be a JSON object")
5257
+ return config
5258
+
5259
+
5115
5260
  async def opencode_session_metadata(
5116
5261
  binary: str, session_id: str, *, cwd: str | Path, env: dict[str, str],
5117
5262
  on_process: Callable[[asyncio.subprocess.Process], None] | None = None,
@@ -5211,22 +5356,7 @@ def configure_opencode_windows_shell(
5211
5356
  logger.warning(message)
5212
5357
  return env
5213
5358
 
5214
- raw_config = env.get("OPENCODE_CONFIG_CONTENT", "").strip()
5215
- config: dict[str, Any] = {}
5216
- if raw_config:
5217
- try:
5218
- parsed = json.loads(raw_config)
5219
- except json.JSONDecodeError as exc:
5220
- raise RuntimeError(
5221
- "OPENCODE_CONFIG_CONTENT must be a JSON object to configure "
5222
- "OpenCode's Windows tool shell."
5223
- ) from exc
5224
- if not isinstance(parsed, dict):
5225
- raise RuntimeError(
5226
- "OPENCODE_CONFIG_CONTENT must be a JSON object to configure "
5227
- "OpenCode's Windows tool shell."
5228
- )
5229
- config = parsed
5359
+ config = _opencode_config_content(env)
5230
5360
 
5231
5361
  config["shell"] = shell
5232
5362
  env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config, ensure_ascii=False)
@@ -897,6 +897,40 @@ def runtime_capabilities(
897
897
  }
898
898
 
899
899
 
900
+ def _require_absent_unverified_selection(root: Path, component_id: str) -> None:
901
+ for directory in (root, root / "selections"):
902
+ try:
903
+ metadata = directory.lstat()
904
+ except FileNotFoundError:
905
+ if directory != root:
906
+ return
907
+ raise
908
+ if (
909
+ not stat.S_ISDIR(metadata.st_mode)
910
+ or getattr(metadata, "st_file_attributes", 0) & 0x400
911
+ ):
912
+ raise ComponentRuntimeError("component_storage_invalid")
913
+ try:
914
+ (root / "selections" / f"{component_id}.json").lstat()
915
+ except FileNotFoundError:
916
+ return
917
+ raise ComponentRuntimeError("component_platform_unverified")
918
+
919
+
920
+ def _valid_external_selection_path(path: Any) -> bool:
921
+ if not isinstance(path, str) or not path.startswith("/"):
922
+ return False
923
+ try:
924
+ if len(path.encode("utf-8")) > 4096:
925
+ return False
926
+ except UnicodeEncodeError:
927
+ return False
928
+ return (
929
+ not any(ord(character) < 32 or ord(character) == 127 or character == ":" for character in path)
930
+ and all(part not in {"", ".", ".."} for part in path.split("/")[1:])
931
+ )
932
+
933
+
900
934
  def _acquire_component(
901
935
  component_id: str, root: Path | None = None, override: str | None = None,
902
936
  kind: str = "agent",
@@ -910,11 +944,11 @@ def _acquire_component(
910
944
  if not root.exists():
911
945
  return None
912
946
  if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
913
- raise ComponentRuntimeError("component_platform_unverified")
947
+ _require_absent_unverified_selection(root, component_id)
948
+ return None
914
949
  import fcntl
915
950
 
916
951
  with _ComponentManagerLock(root):
917
- target = _component_target(root)
918
952
  selection = _record(
919
953
  root / "selections" / f"{component_id}.json",
920
954
  {
@@ -925,10 +959,11 @@ def _acquire_component(
925
959
  "installation_id",
926
960
  "enabled",
927
961
  },
928
- optional_fields={"external"},
962
+ optional_fields={"external", "external_path"},
929
963
  )
930
964
  if selection is None:
931
965
  return None
966
+ target = _component_target(root)
932
967
  if (
933
968
  selection["target_id"] != target["target_id"]
934
969
  or selection["component_id"] != component_id
@@ -943,7 +978,9 @@ def _acquire_component(
943
978
  external = selection.get("external")
944
979
  if (external is not None and external is not True) or (
945
980
  external is True and (selection["installation_id"] is not None or kind != "agent")
946
- ):
981
+ ) or ("external_path" in selection and (
982
+ external is not True or not _valid_external_selection_path(selection["external_path"])
983
+ )):
947
984
  raise ComponentRuntimeError("component_selection_invalid")
948
985
  if not selection["enabled"]:
949
986
  raise ComponentRuntimeError("component_disabled")
@@ -1075,6 +1112,73 @@ def acquire_component(
1075
1112
  raise ComponentRuntimeError("component_storage_unavailable") from error
1076
1113
 
1077
1114
 
1115
+ def selected_external_agent_selection(component_id: str, root: Path | None = None) -> tuple[str | None, int | None]:
1116
+ _identifier(component_id)
1117
+ root = default_store_root() if root is None else root
1118
+ if root.is_symlink():
1119
+ raise ComponentRuntimeError("component_storage_invalid")
1120
+ if not root.exists():
1121
+ return None, None
1122
+ try:
1123
+ if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
1124
+ _require_absent_unverified_selection(root, component_id)
1125
+ return None, None
1126
+ with _ComponentManagerLock(root):
1127
+ selection = _record(
1128
+ root / "selections" / f"{component_id}.json",
1129
+ {"schema_version", "target_id", "component_id", "revision", "installation_id", "enabled"},
1130
+ optional_fields={"external", "external_path"},
1131
+ )
1132
+ if selection is None:
1133
+ return None, None
1134
+ target = _component_target(root)
1135
+ if (
1136
+ selection["target_id"] != target["target_id"] or selection["component_id"] != component_id
1137
+ or type(selection["revision"]) is not int or not 0 <= selection["revision"] <= 9_007_199_254_740_991
1138
+ or type(selection["enabled"]) is not bool
1139
+ ):
1140
+ raise ComponentRuntimeError("component_selection_invalid")
1141
+ if not selection["enabled"]:
1142
+ raise ComponentRuntimeError("component_disabled")
1143
+ if selection.get("external") is not True or selection["installation_id"] is not None:
1144
+ raise ComponentRuntimeError("component_selection_changed")
1145
+ path = selection.get("external_path")
1146
+ if path is not None and not _valid_external_selection_path(path):
1147
+ raise ComponentRuntimeError("component_selection_invalid")
1148
+ return path, selection["revision"]
1149
+ except OSError as error:
1150
+ raise ComponentRuntimeError("component_storage_unavailable") from error
1151
+
1152
+
1153
+ def require_unselected_component(component_id: str, root: Path | None = None) -> None:
1154
+ _identifier(component_id)
1155
+ root = default_store_root() if root is None else root
1156
+ if root.is_symlink():
1157
+ raise ComponentRuntimeError("component_storage_invalid")
1158
+ if not root.exists():
1159
+ return
1160
+ if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
1161
+ try:
1162
+ _require_absent_unverified_selection(root, component_id)
1163
+ except OSError as error:
1164
+ raise ComponentRuntimeError("component_storage_unavailable") from error
1165
+ return
1166
+ try:
1167
+ with _ComponentManagerLock(root):
1168
+ selection = _record(
1169
+ root / "selections" / f"{component_id}.json",
1170
+ {
1171
+ "schema_version", "target_id", "component_id", "revision", "installation_id",
1172
+ "enabled",
1173
+ },
1174
+ optional_fields={"external", "external_path"},
1175
+ )
1176
+ if selection is not None:
1177
+ raise ComponentRuntimeError("component_selection_changed")
1178
+ except OSError as error:
1179
+ raise ComponentRuntimeError("component_storage_unavailable") from error
1180
+
1181
+
1078
1182
  def require_external_selection(
1079
1183
  component_id: str, revision: int, root: Path | None = None, *, allow_disabled: bool = False,
1080
1184
  ) -> str | None:
@@ -1153,8 +1257,13 @@ def admit_execution(
1153
1257
  ) -> ManagedComponentLease | None:
1154
1258
  lease = acquire_component(component_id, root=root, override=override)
1155
1259
  if lease is None:
1156
- if installation_id is not None or selection_revision is not None:
1260
+ if installation_id is not None:
1157
1261
  raise ComponentRuntimeError("component_instance_missing")
1262
+ selected_path, selected_revision = selected_external_agent_selection(component_id, root)
1263
+ if selected_revision != selection_revision:
1264
+ raise ComponentRuntimeError("component_selection_changed")
1265
+ if selected_path is not None and os.path.realpath(binary_path) != os.path.realpath(selected_path):
1266
+ raise ComponentRuntimeError("component_instance_changed")
1158
1267
  validate_external_executable(binary_path, root)
1159
1268
  return None
1160
1269
  try:
@@ -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.98.1"
1415
+ DAEMON_VERSION = "1.98.4"
1416
1416
 
1417
1417
 
1418
1418
  def _detect_client_type() -> str:
@@ -7831,6 +7831,7 @@ class ProcessManager:
7831
7831
  usage = agent_core.OpenCodeUsage()
7832
7832
  usage_errors: list[str] = []
7833
7833
  has_native_output = False
7834
+ run_state = agent_core.OpenCodeRunState()
7834
7835
 
7835
7836
  async def collect_output(lines: list[str]) -> None:
7836
7837
  nonlocal has_native_output
@@ -7840,7 +7841,10 @@ class ProcessManager:
7840
7841
  event = json.loads(line)
7841
7842
  except json.JSONDecodeError:
7842
7843
  continue
7843
- if isinstance(event, dict) and event.get("type") == "step_finish":
7844
+ if not isinstance(event, dict):
7845
+ continue
7846
+ run_state.feed(event)
7847
+ if profile == "v2" and event.get("type") == "step_finish":
7844
7848
  try:
7845
7849
  usage.add(event)
7846
7850
  except ValueError as exc:
@@ -7848,7 +7852,7 @@ class ProcessManager:
7848
7852
  if on_chunk:
7849
7853
  await on_chunk(lines)
7850
7854
 
7851
- chunk_handler = collect_output if profile == "v2" else on_chunk
7855
+ chunk_handler = collect_output
7852
7856
  run_options = {"cleanup_process_tree": True} if profile == "v2" else {}
7853
7857
  # Isolate each opencode run in its own data directory to prevent
7854
7858
  # concurrent processes from racing on the shared SQLite WAL file.
@@ -7857,13 +7861,14 @@ class ProcessManager:
7857
7861
  isolated_data_dir = Path(tmp_data_root) / "opencode"
7858
7862
  isolated_data_dir.mkdir()
7859
7863
  prompt_file = Path(tmp_data_root) / "instructions.md"
7860
- prompt_file.write_text(prompt, encoding="utf-8")
7864
+ prompt_file.write_text(agent_core.opencode_worker_prompt(prompt), encoding="utf-8")
7861
7865
  cmd = agent_core.build_opencode_command(
7862
7866
  agent.command,
7863
7867
  cwd=cwd,
7864
7868
  model=model_override,
7865
7869
  prompt_file=prompt_file,
7866
7870
  profile=profile,
7871
+ single_worker=True,
7867
7872
  )
7868
7873
  # Copy auth.json so provider credentials are available.
7869
7874
  auth_src = Path.home() / ".local" / "share" / "opencode" / "auth.json"
@@ -7876,8 +7881,15 @@ class ProcessManager:
7876
7881
  require_windows_shell=True,
7877
7882
  profile=profile,
7878
7883
  cwd=cwd,
7884
+ single_worker=True,
7879
7885
  )
7880
7886
  env.update(TMPDIR=tmp_data_root, BUN_TMPDIR=tmp_data_root)
7887
+ except agent_core.OpenCodeConfigurationError as exc:
7888
+ logger.warning("Invalid OpenCode configuration for task %s: %s", task_id, exc)
7889
+ return TaskResult(
7890
+ status="failed", exit_code=-1, stdout="", stderr="",
7891
+ error=str(exc), failure_code="agent_protocol_error",
7892
+ )
7881
7893
  except RuntimeError as exc:
7882
7894
  return TaskResult(
7883
7895
  status="failed",
@@ -7891,10 +7903,15 @@ class ProcessManager:
7891
7903
  cmd, cwd, timeout, task_id, on_chunk=chunk_handler, env=env,
7892
7904
  **run_options,
7893
7905
  )
7906
+ run_state.feed_output(result.stdout)
7894
7907
  signals = agent_core._extract_output_signals(result.stdout)
7895
- if signals["has_turn_failed"]:
7908
+ if run_state.error or signals["has_turn_failed"]:
7896
7909
  result.status = "failed"
7897
- result.error = "\n".join(signals["error_messages"]) or "OpenCode reported an error"
7910
+ result.error = (
7911
+ run_state.error
7912
+ or "\n".join(signals["error_messages"])
7913
+ or "OpenCode reported an error"
7914
+ )
7898
7915
  output = "\n".join(
7899
7916
  part for part in (
7900
7917
  result.stdout if profile == "v1" else result.error,
@@ -7932,6 +7949,7 @@ class ProcessManager:
7932
7949
  usage = agent_core.OpenCodeUsage()
7933
7950
  usage_errors.clear()
7934
7951
  has_native_output = False
7952
+ run_state = agent_core.OpenCodeRunState()
7935
7953
  retry_env = dict(env)
7936
7954
  retry_env.pop("FACTORY_OPENCODE_MODEL", None)
7937
7955
  cmd = agent_core.build_opencode_command(
@@ -7940,6 +7958,7 @@ class ProcessManager:
7940
7958
  model=retry_model,
7941
7959
  prompt_file=prompt_file,
7942
7960
  profile=profile,
7961
+ single_worker=True,
7943
7962
  )
7944
7963
  result = await self._run_cli(
7945
7964
  cmd, cwd, timeout, task_id, on_chunk=chunk_handler, env=retry_env,
@@ -7949,23 +7968,31 @@ class ProcessManager:
7949
7968
  finally:
7950
7969
  shutil.rmtree(tmp_data_root, ignore_errors=True)
7951
7970
 
7971
+ run_state.feed_output(result.stdout)
7952
7972
  signals = agent_core._extract_output_signals(result.stdout)
7953
- if signals["has_turn_failed"]:
7973
+ if run_state.error or signals["has_turn_failed"]:
7974
+ result.status = "failed"
7975
+ result.error = (
7976
+ run_state.error
7977
+ or "\n".join(signals["error_messages"])
7978
+ or "OpenCode reported an error"
7979
+ )
7980
+ failure = run_state.failure()
7981
+ result.has_verified_completion = failure is None and result.status == "success"
7982
+ if failure and (result.status == "success" or run_state.error):
7954
7983
  result.status = "failed"
7955
- result.error = "\n".join(signals["error_messages"]) or "OpenCode reported an error"
7984
+ result.failure_code, result.error = failure
7985
+ logger.warning("OpenCode execution incomplete for task %s: %s", task_id, result.error)
7956
7986
  try:
7957
7987
  if usage_errors:
7958
7988
  raise ValueError(usage_errors[0])
7959
- if profile == "v2" and result.status == "success" and not (
7960
- has_native_output or agent_core.opencode_v2_has_output(result.stdout)
7961
- ):
7962
- raise ValueError("OpenCode v2 did not emit valid JSON events")
7963
7989
  parsed_metrics = dict(usage.totals) if profile == "v2" and usage.seen else (
7964
7990
  agent_core._parse_agent_jsonl_output(result.stdout, opencode_profile=profile)
7965
7991
  )
7966
7992
  except ValueError as exc:
7967
7993
  logger.warning("OpenCode output protocol failed for task %s: %s", task_id, exc)
7968
7994
  result.status, result.error, result.failure_code = "failed", str(exc), "agent_protocol_error"
7995
+ result.has_verified_completion = False
7969
7996
  return result
7970
7997
  result.metrics.update(parsed_metrics)
7971
7998
  return result
@@ -13936,11 +13963,13 @@ class RuntimeDaemon:
13936
13963
  # 4.1 Recovery: agent exited non-zero but already committed code.
13937
13964
  # Covers two scenarios:
13938
13965
  # A. Process crash (e.g. OpenCode EBADF on exit after successful work):
13939
- # exit_code is a real non-negative/non-(-1) value.
13966
+ # exit_code is positive, not a failed zero-exit completion check.
13940
13967
  # B. Timeout with committed work: agent finished its task and committed
13941
13968
  # before the idle/absolute timeout fired. exit_code=-1 but the commits
13942
13969
  # are real — don't discard them.
13943
- if result.status == "failed":
13970
+ if result.status == "failed" and result.failure_code not in {
13971
+ "agent_incomplete_turn", "agent_protocol_error",
13972
+ }:
13944
13973
  _error_lower = (result.error or "").lower()
13945
13974
  is_timeout_failure = (
13946
13975
  "idle for" in _error_lower
@@ -13949,7 +13978,7 @@ class RuntimeDaemon:
13949
13978
  )
13950
13979
  can_attempt_recovery = (
13951
13980
  is_timeout_failure # timeout: also allow exit_code=-1
13952
- or result.exit_code not in (None, -1) # crash: original guard
13981
+ or result.exit_code not in (None, -1, 0)
13953
13982
  )
13954
13983
  if can_attempt_recovery:
13955
13984
  original_exit_code = result.exit_code
@@ -14159,6 +14188,7 @@ class RuntimeDaemon:
14159
14188
  task.task_id, task.node_type,
14160
14189
  )
14161
14190
  result.status = "failed"
14191
+ result.failure_code = "required_deliverable_missing"
14162
14192
  result.error = (
14163
14193
  f"Agent reported success but did not update required {task.node_type} deliverables "
14164
14194
  f"(agent={agent.agent_id})"
@@ -15314,10 +15344,17 @@ class RuntimeDaemon:
15314
15344
  if doc_dir:
15315
15345
  design_filename = _get_design_output_for_type(req_type, _task_change_scope(input_data))
15316
15346
  design_path = workspace_path / doc_dir / design_filename
15317
- if not design_path.exists():
15318
- issues.append(f"Design document missing: {doc_dir}/{design_filename}")
15347
+ if not design_path.is_file():
15348
+ issues.append(_OutputValidationIssue(
15349
+ "required_deliverable_missing",
15350
+ f"Design document missing: {doc_dir}/{design_filename} "
15351
+ "(expected a regular file)",
15352
+ ))
15319
15353
  elif design_path.stat().st_size == 0:
15320
- issues.append(f"Design document is empty: {doc_dir}/{design_filename}")
15354
+ issues.append(_OutputValidationIssue(
15355
+ "required_deliverable_missing",
15356
+ f"Design document is empty: {doc_dir}/{design_filename}",
15357
+ ))
15321
15358
 
15322
15359
  elif node_type in ("coding", "testing", "fix", "review"):
15323
15360
  # Syntax-check modified Python and JS/TS files
@@ -20904,6 +20941,13 @@ async def main():
20904
20941
 
20905
20942
  def main_sync():
20906
20943
  """Synchronous entry point for CLI: forgexa-daemon"""
20944
+ if sys.argv[1:] == ["--workspace-storage"]:
20945
+ try:
20946
+ from .workspace_storage import main as storage_main
20947
+ except ImportError:
20948
+ from workspace_storage import main as storage_main
20949
+ storage_main()
20950
+ return
20907
20951
  asyncio.run(main())
20908
20952
 
20909
20953
 
@@ -262,8 +262,9 @@ async def run_ocr_delegation(
262
262
  *,
263
263
  external_executable: Path | None = None,
264
264
  expected_external_instance: str | None = None,
265
+ _wsl_guarded: bool = False,
265
266
  ) -> dict[str, Any]:
266
- if os.name != "posix" or os.environ.get("WSL_DISTRO_NAME"):
267
+ if os.name != "posix" or (os.environ.get("WSL_DISTRO_NAME") and not _wsl_guarded):
267
268
  raise OcrAdapterError("ocr_platform_unverified")
268
269
  if (lease is None) == (external_executable is None):
269
270
  raise OcrAdapterError("ocr_instance_unavailable")