hpilot 0.60.6__py3-none-any.whl

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 (220) hide show
  1. hpilot/__init__.py +24 -0
  2. hpilot/__main__.py +3 -0
  3. hpilot/_constants.py +7 -0
  4. hpilot/_global_config_legacy.py +108 -0
  5. hpilot/adapters/__init__.py +6 -0
  6. hpilot/adapters/_cli_runtime.py +14 -0
  7. hpilot/adapters/_process.py +80 -0
  8. hpilot/adapters/antigravity/__init__.py +3 -0
  9. hpilot/adapters/antigravity/_acp.py +232 -0
  10. hpilot/adapters/antigravity/_acp_config.py +158 -0
  11. hpilot/adapters/antigravity/_acp_process.py +244 -0
  12. hpilot/adapters/antigravity/_handle.py +248 -0
  13. hpilot/adapters/antigravity/_preflight.py +69 -0
  14. hpilot/adapters/antigravity/_timeout.py +37 -0
  15. hpilot/adapters/antigravity/adapter.py +124 -0
  16. hpilot/adapters/antigravity/stream.py +173 -0
  17. hpilot/adapters/base.py +348 -0
  18. hpilot/adapters/claude/__init__.py +3 -0
  19. hpilot/adapters/claude/_handle.py +197 -0
  20. hpilot/adapters/claude/_sdk_wrapper.py +113 -0
  21. hpilot/adapters/claude/adapter.py +439 -0
  22. hpilot/adapters/claude/stream.py +165 -0
  23. hpilot/adapters/codex/__init__.py +3 -0
  24. hpilot/adapters/codex/_app_helpers.py +454 -0
  25. hpilot/adapters/codex/_goal_file.py +80 -0
  26. hpilot/adapters/codex/_goal_protocol.py +228 -0
  27. hpilot/adapters/codex/_handle.py +796 -0
  28. hpilot/adapters/codex/_sdk_wrapper.py +790 -0
  29. hpilot/adapters/codex/_shell_command.py +42 -0
  30. hpilot/adapters/codex/_socket_bridge.py +56 -0
  31. hpilot/adapters/codex/_subagents.py +543 -0
  32. hpilot/adapters/codex/_transport.py +167 -0
  33. hpilot/adapters/codex/adapter.py +112 -0
  34. hpilot/adapters/codex/stream.py +120 -0
  35. hpilot/adapters/cursor/__init__.py +3 -0
  36. hpilot/adapters/cursor/_handle.py +414 -0
  37. hpilot/adapters/cursor/_sdk_wrapper.py +279 -0
  38. hpilot/adapters/cursor/adapter.py +223 -0
  39. hpilot/adapters/cursor/stream.py +488 -0
  40. hpilot/adapters/cursor/tool_mapping.py +101 -0
  41. hpilot/adapters/errors.py +15 -0
  42. hpilot/adapters/mock/__init__.py +3 -0
  43. hpilot/adapters/mock/adapter.py +175 -0
  44. hpilot/adapters/opencode/__init__.py +3 -0
  45. hpilot/adapters/opencode/_diagnostics.py +50 -0
  46. hpilot/adapters/opencode/_model_config.py +296 -0
  47. hpilot/adapters/opencode/_model_selection.py +44 -0
  48. hpilot/adapters/opencode/_native.py +69 -0
  49. hpilot/adapters/opencode/_owned_server.py +86 -0
  50. hpilot/adapters/opencode/_permissions.py +244 -0
  51. hpilot/adapters/opencode/_preflight.py +57 -0
  52. hpilot/adapters/opencode/_probe_process.py +44 -0
  53. hpilot/adapters/opencode/_serve_continuation.py +54 -0
  54. hpilot/adapters/opencode/_serve_handle_base.py +390 -0
  55. hpilot/adapters/opencode/_serve_output.py +89 -0
  56. hpilot/adapters/opencode/_turn.py +146 -0
  57. hpilot/adapters/opencode/_usage.py +124 -0
  58. hpilot/adapters/opencode/_v2_events.py +43 -0
  59. hpilot/adapters/opencode/adapter.py +429 -0
  60. hpilot/adapters/opencode/serve_client.py +608 -0
  61. hpilot/adapters/opencode/serve_transport.py +458 -0
  62. hpilot/adapters/opencode/stream.py +488 -0
  63. hpilot/adapters/opencode/tool_mapping.py +97 -0
  64. hpilot/adapters/registry.py +166 -0
  65. hpilot/adapters/tool_mapping.py +68 -0
  66. hpilot/adapters/types.py +278 -0
  67. hpilot/assets/__init__.py +0 -0
  68. hpilot/assets/init/__init__.py +1 -0
  69. hpilot/assets/init/simple/hpilot.yaml +478 -0
  70. hpilot/assets/init/speckit/hpilot.yaml +352 -0
  71. hpilot/assets/verifier/__init__.py +1 -0
  72. hpilot/assets/verifier/stage-completion-verifier.md +22 -0
  73. hpilot/cli/__init__.py +121 -0
  74. hpilot/cli/_batch_submit.py +263 -0
  75. hpilot/cli/_daemon_cmds.py +169 -0
  76. hpilot/cli/_standalone_cmds.py +130 -0
  77. hpilot/cli/_startup.py +264 -0
  78. hpilot/cli/_usage_cmds.py +69 -0
  79. hpilot/cli/commands.py +565 -0
  80. hpilot/cli/completions.py +216 -0
  81. hpilot/cli/docs.py +136 -0
  82. hpilot/cli/instance.py +121 -0
  83. hpilot/cli/parser.py +373 -0
  84. hpilot/cli/passthrough.py +11 -0
  85. hpilot/cli.py +98 -0
  86. hpilot/client/__init__.py +81 -0
  87. hpilot/client/commands.py +409 -0
  88. hpilot/client/connection.py +130 -0
  89. hpilot/client/rendering.py +118 -0
  90. hpilot/client/streaming.py +368 -0
  91. hpilot/client.py +60 -0
  92. hpilot/config/__init__.py +83 -0
  93. hpilot/config/_parsing.py +331 -0
  94. hpilot/config/_stage_parsing.py +640 -0
  95. hpilot/config/_types.py +247 -0
  96. hpilot/contract_correction.py +74 -0
  97. hpilot/daemon_endpoint.py +134 -0
  98. hpilot/doctor.py +535 -0
  99. hpilot/evaluation/__init__.py +55 -0
  100. hpilot/evaluation/context.py +95 -0
  101. hpilot/evaluation/contracts.py +79 -0
  102. hpilot/evaluation/decision.py +86 -0
  103. hpilot/evaluation/events.py +65 -0
  104. hpilot/evaluation/prompts.py +37 -0
  105. hpilot/evaluation/reply.py +179 -0
  106. hpilot/evaluation/response.py +83 -0
  107. hpilot/evaluation/verifier_client.py +214 -0
  108. hpilot/git_repos.py +274 -0
  109. hpilot/global_config.py +699 -0
  110. hpilot/import_cybervisor.py +179 -0
  111. hpilot/init.py +132 -0
  112. hpilot/jsonc.py +101 -0
  113. hpilot/lifecycle_hooks.py +98 -0
  114. hpilot/log_cleanup.py +98 -0
  115. hpilot/log_paths.py +29 -0
  116. hpilot/logging.py +190 -0
  117. hpilot/mcp/__init__.py +33 -0
  118. hpilot/mcp/config.py +331 -0
  119. hpilot/mcp/dispatcher.py +93 -0
  120. hpilot/mcp/files.py +334 -0
  121. hpilot/mcp/http.py +287 -0
  122. hpilot/mcp/logging.py +206 -0
  123. hpilot/mcp/metadata.py +110 -0
  124. hpilot/mcp/oauth.py +371 -0
  125. hpilot/mcp/server.py +225 -0
  126. hpilot/mcp/service.py +167 -0
  127. hpilot/mcp/workspace.py +113 -0
  128. hpilot/mcp/yieldshell.py +117 -0
  129. hpilot/path_patterns.py +41 -0
  130. hpilot/pipeline/__init__.py +32 -0
  131. hpilot/pipeline/_agent_attempt.py +431 -0
  132. hpilot/pipeline/_attempt_runtime.py +110 -0
  133. hpilot/pipeline/_attempt_start.py +99 -0
  134. hpilot/pipeline/_cleanup.py +113 -0
  135. hpilot/pipeline/_command_attempt.py +250 -0
  136. hpilot/pipeline/_command_stage.py +83 -0
  137. hpilot/pipeline/_completion.py +495 -0
  138. hpilot/pipeline/_continuation.py +106 -0
  139. hpilot/pipeline/_execution.py +488 -0
  140. hpilot/pipeline/_harness_failure.py +78 -0
  141. hpilot/pipeline/_interrupt.py +44 -0
  142. hpilot/pipeline/_pipeline_hooks.py +229 -0
  143. hpilot/pipeline/_resume_reporting.py +38 -0
  144. hpilot/pipeline/_routing.py +131 -0
  145. hpilot/pipeline/_runtime_config.py +173 -0
  146. hpilot/pipeline/_runtime_setup.py +56 -0
  147. hpilot/pipeline/_session_metadata.py +161 -0
  148. hpilot/pipeline/_shell_execution.py +179 -0
  149. hpilot/pipeline/_stage_runtime.py +60 -0
  150. hpilot/pipeline/_startup.py +379 -0
  151. hpilot/pipeline/_usage_scope.py +120 -0
  152. hpilot/pipeline/artifacts.py +256 -0
  153. hpilot/pipeline/contract.py +281 -0
  154. hpilot/pipeline/runner.py +480 -0
  155. hpilot/pipeline.py +27 -0
  156. hpilot/preflight.py +119 -0
  157. hpilot/prompt_sections.py +11 -0
  158. hpilot/read_only_guard.py +304 -0
  159. hpilot/server/__init__.py +78 -0
  160. hpilot/server/_cleanup.py +21 -0
  161. hpilot/server/_daemon_config.py +145 -0
  162. hpilot/server/_path.py +15 -0
  163. hpilot/server/_task_exec.py +625 -0
  164. hpilot/server/daemon.py +684 -0
  165. hpilot/server/handlers.py +456 -0
  166. hpilot/server/socket_lifecycle.py +250 -0
  167. hpilot/server/tasks.py +307 -0
  168. hpilot/server.py +29 -0
  169. hpilot/server_events.py +333 -0
  170. hpilot/server_signals.py +47 -0
  171. hpilot/signals.py +395 -0
  172. hpilot/skills.py +199 -0
  173. hpilot/stream_logging.py +503 -0
  174. hpilot/tool_argument_sanitizer.py +295 -0
  175. hpilot/tool_field_aliases.py +72 -0
  176. hpilot/upgrade.py +86 -0
  177. hpilot/usage/__init__.py +60 -0
  178. hpilot/usage/models.py +151 -0
  179. hpilot/usage/normalize.py +249 -0
  180. hpilot/usage/query.py +289 -0
  181. hpilot/usage/recorder.py +275 -0
  182. hpilot/usage/report.py +150 -0
  183. hpilot/usage/store.py +351 -0
  184. hpilot/usage/timerange.py +140 -0
  185. hpilot/usage_reporting.py +229 -0
  186. hpilot-0.60.6.data/data/share/hpilot/docs/agent-architecture.md +128 -0
  187. hpilot-0.60.6.data/data/share/hpilot/docs/agents/antigravity.md +33 -0
  188. hpilot-0.60.6.data/data/share/hpilot/docs/agents/claude.md +67 -0
  189. hpilot-0.60.6.data/data/share/hpilot/docs/agents/codex.md +229 -0
  190. hpilot-0.60.6.data/data/share/hpilot/docs/agents/cursor.md +131 -0
  191. hpilot-0.60.6.data/data/share/hpilot/docs/agents/opencode.md +113 -0
  192. hpilot-0.60.6.data/data/share/hpilot/docs/batch-submit.md +76 -0
  193. hpilot-0.60.6.data/data/share/hpilot/docs/completions.md +57 -0
  194. hpilot-0.60.6.data/data/share/hpilot/docs/configuration.md +311 -0
  195. hpilot-0.60.6.data/data/share/hpilot/docs/contributing/adding-an-adapter.md +114 -0
  196. hpilot-0.60.6.data/data/share/hpilot/docs/development.md +116 -0
  197. hpilot-0.60.6.data/data/share/hpilot/docs/getting-started.md +248 -0
  198. hpilot-0.60.6.data/data/share/hpilot/docs/index.md +61 -0
  199. hpilot-0.60.6.data/data/share/hpilot/docs/mcp-server.md +296 -0
  200. hpilot-0.60.6.data/data/share/hpilot/docs/native-session-verification.md +28 -0
  201. hpilot-0.60.6.data/data/share/hpilot/docs/opencode-v2-verification.md +60 -0
  202. hpilot-0.60.6.data/data/share/hpilot/docs/pipeline-authoring.md +674 -0
  203. hpilot-0.60.6.data/data/share/hpilot/docs/runtime-internals.md +302 -0
  204. hpilot-0.60.6.data/data/share/hpilot/docs/runtime-user.md +241 -0
  205. hpilot-0.60.6.data/data/share/hpilot/docs/stage-configuration.md +374 -0
  206. hpilot-0.60.6.data/data/share/hpilot/docs/testing-dev.md +106 -0
  207. hpilot-0.60.6.data/data/share/hpilot/docs/testing.md +44 -0
  208. hpilot-0.60.6.data/data/share/hpilot/docs/troubleshooting/daemon.md +118 -0
  209. hpilot-0.60.6.data/data/share/hpilot/docs/troubleshooting/execution.md +259 -0
  210. hpilot-0.60.6.data/data/share/hpilot/docs/troubleshooting/index.md +25 -0
  211. hpilot-0.60.6.data/data/share/hpilot/docs/troubleshooting/installation.md +81 -0
  212. hpilot-0.60.6.data/data/share/hpilot/docs/updating-dev.md +25 -0
  213. hpilot-0.60.6.data/data/share/hpilot/docs/updating.md +104 -0
  214. hpilot-0.60.6.data/data/share/hpilot/docs/usage-metrics.md +127 -0
  215. hpilot-0.60.6.data/data/share/hpilot/docs/websocket-protocol.md +469 -0
  216. hpilot-0.60.6.dist-info/METADATA +393 -0
  217. hpilot-0.60.6.dist-info/RECORD +220 -0
  218. hpilot-0.60.6.dist-info/WHEEL +5 -0
  219. hpilot-0.60.6.dist-info/entry_points.txt +2 -0
  220. hpilot-0.60.6.dist-info/top_level.txt +1 -0
hpilot/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """hpilot package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from pathlib import Path
7
+ import tomllib
8
+
9
+
10
+ def _read_version_from_pyproject() -> str:
11
+ pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
12
+ with pyproject_path.open("rb") as pyproject_file:
13
+ project = tomllib.load(pyproject_file)["project"]
14
+ package_version = project.get("version")
15
+ if not isinstance(package_version, str):
16
+ msg = "project.version must be a string in pyproject.toml"
17
+ raise RuntimeError(msg)
18
+ return package_version
19
+
20
+
21
+ try:
22
+ __version__ = version("hpilot")
23
+ except PackageNotFoundError:
24
+ __version__ = _read_version_from_pyproject()
hpilot/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from hpilot.cli import main
2
+
3
+ raise SystemExit(main())
hpilot/_constants.py ADDED
@@ -0,0 +1,7 @@
1
+ """Shared constants with no internal imports — safe to import from any module."""
2
+
3
+ from typing import Literal
4
+
5
+ DEFAULT_ENDPOINT = "https://api.openai.com/v1"
6
+ DEFAULT_MODEL = "auto"
7
+ AgentToolType = Literal["claude", "mock", "codex", "opencode", "cursor", "antigravity"]
@@ -0,0 +1,108 @@
1
+ """Temporary legacy runtime-config normalization.
2
+
3
+ This is the only module that knows about pre-harness configuration keys. It
4
+ can be deleted in the next breaking release without changing the canonical
5
+ configuration model.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import Any, Callable
12
+
13
+
14
+ def warn_legacy_llm_stage_models(llm_raw: object) -> None:
15
+ """Warn once per load about the ignored ``llm.stage_models`` key."""
16
+ if isinstance(llm_raw, dict) and "stage_models" in llm_raw:
17
+ logging.getLogger("hpilot.global_config").warning(
18
+ "'llm.stage_models' is deprecated and ignored; "
19
+ "move model values into 'stage_overrides'"
20
+ )
21
+
22
+
23
+ def normalize_legacy_runtime_config(
24
+ raw: dict[str, Any],
25
+ *,
26
+ error: Callable[[str], Exception],
27
+ ) -> dict[str, Any]:
28
+ """Return a copy of *raw* using only canonical runtime keys."""
29
+ normalized = dict(raw)
30
+ logger = logging.getLogger("hpilot.global_config")
31
+
32
+ # A legacy key present with a null value (a bare `agent_tool:` line) carries
33
+ # no configuration, so it is treated as absent rather than as the string
34
+ # "None". Otherwise a leftover empty key would both warn and collide with
35
+ # a real value in the other legacy key or in `harness`.
36
+ legacy_globals = [
37
+ name for name in ("agent_tool", "agent") if raw.get(name) is not None
38
+ ]
39
+ for name in legacy_globals:
40
+ logger.warning("'%s' is deprecated; use 'harness'", name)
41
+ if len(legacy_globals) == 2:
42
+ left = str(raw["agent_tool"]).strip().lower()
43
+ right = str(raw["agent"]).strip().lower()
44
+ if left != right:
45
+ raise error("Both 'agent_tool' and 'agent' are configured with different values")
46
+ legacy_name = legacy_globals[0] if legacy_globals else None
47
+ if legacy_name is not None:
48
+ legacy_harness = raw[legacy_name]
49
+ if raw.get("harness") is not None:
50
+ canonical = str(raw["harness"]).strip().lower()
51
+ legacy = str(legacy_harness).strip().lower()
52
+ if canonical != legacy:
53
+ raise error(
54
+ f"Both '{legacy_name}' and 'harness' are configured with different values"
55
+ )
56
+ else:
57
+ normalized["harness"] = legacy_harness
58
+
59
+ stage_overrides_raw = raw.get("stage_overrides")
60
+ if stage_overrides_raw is None:
61
+ stage_overrides: dict[object, object] = {}
62
+ elif isinstance(stage_overrides_raw, dict):
63
+ stage_overrides = {
64
+ key: dict(value) if isinstance(value, dict) else value
65
+ for key, value in stage_overrides_raw.items()
66
+ }
67
+ else:
68
+ # Structural parsing owns the canonical error message.
69
+ stage_overrides = stage_overrides_raw
70
+
71
+ for legacy_key, field_name, noun in (
72
+ ("stage_agents", "harness", "harness"),
73
+ ("stage_models", "model", "model"),
74
+ ):
75
+ legacy_mapping = raw.get(legacy_key)
76
+ if legacy_mapping is None:
77
+ # Absent, or present but empty; either way there is nothing to
78
+ # migrate and nothing worth warning about.
79
+ continue
80
+ replacement = (
81
+ "move harness values into 'stage_overrides'"
82
+ if legacy_key == "stage_agents"
83
+ else "move model values into 'stage_overrides'"
84
+ )
85
+ logger.warning("'%s' is deprecated; %s", legacy_key, replacement)
86
+ if not isinstance(legacy_mapping, dict):
87
+ # Preserve the old structural error because it pinpoints the input.
88
+ raise error(f"{legacy_key} must be a mapping")
89
+ if not isinstance(stage_overrides, dict):
90
+ continue
91
+ for stage, value in legacy_mapping.items():
92
+ existing = stage_overrides.get(stage)
93
+ if isinstance(existing, dict) and field_name in existing:
94
+ raise error(
95
+ f"Stage '{stage}' defines its {noun} in both "
96
+ f"'{legacy_key}' and 'stage_overrides'"
97
+ )
98
+ if existing is None:
99
+ existing = {}
100
+ stage_overrides[stage] = existing
101
+ if isinstance(existing, dict):
102
+ existing[field_name] = value
103
+
104
+ if stage_overrides:
105
+ normalized["stage_overrides"] = stage_overrides
106
+ for key in ("agent_tool", "agent", "stage_agents", "stage_models"):
107
+ normalized.pop(key, None)
108
+ return normalized
@@ -0,0 +1,6 @@
1
+ from hpilot.adapters.registry import (
2
+ get_adapter,
3
+ supported_harness_names,
4
+ )
5
+
6
+ __all__ = ["get_adapter", "supported_harness_names"]
@@ -0,0 +1,14 @@
1
+ """Shared standalone CLI path resolution for SDK-backed adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+
9
+ def resolve_cli_path(binary: str) -> str:
10
+ """Resolve a CLI to an explicit path, with the container path as fallback."""
11
+ discovered = shutil.which(binary)
12
+ if discovered is not None:
13
+ return str(Path(discovered).absolute())
14
+ return f"/usr/local/bin/{binary}"
@@ -0,0 +1,80 @@
1
+ """Shared process-termination helper for subprocess-backed adapters.
2
+
3
+ Provides a single escalation path (graceful wait → SIGTERM → SIGKILL) so
4
+ that each transport's ``close()`` method and each handle's ``wait()`` error
5
+ path don't duplicate the same timeout-and-signal logic.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import signal
12
+ import subprocess
13
+ from collections.abc import Callable
14
+
15
+
16
+ def _signal_process_tree(
17
+ process: subprocess.Popen[str],
18
+ signum: signal.Signals,
19
+ fallback: Callable[[], None],
20
+ ) -> None:
21
+ """Signal a dedicated POSIX process group, or the process elsewhere."""
22
+ if os.name == "posix":
23
+ try:
24
+ if os.getpgid(process.pid) == process.pid:
25
+ os.killpg(process.pid, signum)
26
+ return
27
+ except OSError:
28
+ pass
29
+ fallback()
30
+
31
+
32
+ def terminate_process(
33
+ process: subprocess.Popen[str],
34
+ *,
35
+ graceful_timeout: int = 5,
36
+ term_timeout: int = 2,
37
+ kill_timeout: int = 5,
38
+ ) -> int:
39
+ """Terminate a subprocess with escalating signals.
40
+
41
+ 1. Close stdin if still open (signals the child that input is done).
42
+ 2. Wait up to *graceful_timeout* seconds for the process to exit on its own.
43
+ 3. Send SIGTERM, then wait up to *term_timeout* seconds.
44
+ 4. Send SIGKILL (or ``process.kill()`` on Windows), then wait up to
45
+ *kill_timeout* seconds.
46
+
47
+ Idempotent: if the process already exited, ``process.wait()`` returns
48
+ immediately and no signals are sent.
49
+
50
+ Returns the process exit code (may be negative if killed by a signal).
51
+ """
52
+ # 1. Close stdin to signal EOF.
53
+ try:
54
+ if process.stdin is not None and not process.stdin.closed:
55
+ process.stdin.close()
56
+ except (AttributeError, OSError):
57
+ pass
58
+
59
+ # 2. Graceful wait — process may exit after stdin close.
60
+ try:
61
+ return process.wait(timeout=graceful_timeout)
62
+ except subprocess.TimeoutExpired:
63
+ pass
64
+
65
+ # 3. SIGTERM escalation.
66
+ try:
67
+ _signal_process_tree(process, signal.SIGTERM, process.terminate)
68
+ except OSError:
69
+ pass
70
+ try:
71
+ return process.wait(timeout=term_timeout)
72
+ except subprocess.TimeoutExpired:
73
+ pass
74
+
75
+ # 4. SIGKILL escalation.
76
+ try:
77
+ _signal_process_tree(process, signal.SIGKILL, process.kill)
78
+ except OSError:
79
+ pass
80
+ return process.wait(timeout=kill_timeout)
@@ -0,0 +1,3 @@
1
+ from hpilot.adapters.antigravity.adapter import AntigravityAdapter
2
+
3
+ __all__ = ["AntigravityAdapter"]
@@ -0,0 +1,232 @@
1
+ """Antigravity's ACP v1 client and native session lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import re
7
+ from collections.abc import Callable
8
+ from contextlib import suppress
9
+ from pathlib import Path
10
+ from typing import Any, NoReturn, cast
11
+
12
+ from acp import Client, RequestError
13
+ from acp.connection import StreamDirection, StreamEvent
14
+ from acp.schema import (
15
+ DeclineElicitationResponse,
16
+ DeniedOutcome,
17
+ RequestPermissionResponse,
18
+ TextContentBlock,
19
+ SessionConfigOptionBoolean,
20
+ SessionConfigOptionSelect,
21
+ )
22
+
23
+ from hpilot.adapters.antigravity._acp_config import configure_session
24
+ from hpilot.adapters.antigravity._acp_process import ACPProcess
25
+ from hpilot.adapters.antigravity._preflight import AUTHENTICATION_FAILURE_MESSAGE
26
+ from hpilot.adapters.types import HarnessLaunchRequest
27
+
28
+ UpdateCallback = Callable[[str, dict[str, Any]], None]
29
+
30
+
31
+ class SessionUnavailableError(RuntimeError):
32
+ """The server explicitly reported that the requested session is unavailable."""
33
+
34
+
35
+ def _rpc_failure(exc: RequestError, *, session_id: str | None = None) -> NoReturn:
36
+ if exc.code == -32000:
37
+ raise RuntimeError(AUTHENTICATION_FAILURE_MESSAGE) from exc
38
+ detail = str(exc)
39
+ if isinstance(exc.data, dict):
40
+ reason = exc.data.get("details") or exc.data.get("message")
41
+ if isinstance(reason, str):
42
+ detail += f": {reason}"
43
+ if session_id is not None:
44
+ resource = exc.data.get("uri") if isinstance(exc.data, dict) else None
45
+ missing_id = exc.code == -32002 and resource in (
46
+ session_id,
47
+ f"session://{session_id}",
48
+ )
49
+ noun = r"(?:session|conversation|trajectory)"
50
+ identifier = rf"['\"]?{re.escape(session_id)}['\"]?"
51
+ status = r"(?:not found|does not exist|has expired|is unavailable|unavailable)"
52
+ missing_message = re.fullmatch(
53
+ rf"(?:unknown {noun}(?:[ :]+{identifier})?|"
54
+ rf"{noun}(?:(?: (?:with )?id)? {identifier})? {status}|"
55
+ rf"{noun} {status}: {identifier})",
56
+ detail.strip().rstrip("."),
57
+ re.IGNORECASE,
58
+ )
59
+ if missing_id or missing_message:
60
+ raise SessionUnavailableError(
61
+ f"Antigravity session {session_id!r} is unavailable: {detail}"
62
+ ) from exc
63
+ raise RuntimeError(f"Antigravity ACP error {exc.code}: {detail}") from exc
64
+
65
+
66
+ class _Callbacks:
67
+ """Only these client methods are offered. The agent owns its filesystem and tools."""
68
+
69
+ def __init__(self, on_update: UpdateCallback) -> None:
70
+ self.on_update = on_update
71
+ self.active_session: str | None = None
72
+ self.failure: Exception | None = None
73
+
74
+ def observe(self, event: StreamEvent) -> None:
75
+ # The SDK's wire observer sees updates in receive order before resolving
76
+ # the prompt future. It also preserves provider-specific fields for logs.
77
+ if (
78
+ event.direction != StreamDirection.INCOMING
79
+ or event.message.get("method") != "session/update"
80
+ ):
81
+ return
82
+ params = event.message.get("params")
83
+ if (
84
+ not isinstance(params, dict)
85
+ or self.active_session is None
86
+ or params.get("sessionId") != self.active_session
87
+ ):
88
+ return
89
+ update = params.get("update")
90
+ if isinstance(update, dict):
91
+ try:
92
+ self.on_update(self.active_session, update)
93
+ except Exception as exc:
94
+ # Notifications cannot answer with an error. Fail their turn.
95
+ self.failure = exc
96
+
97
+ async def session_update(self, **kwargs: Any) -> None:
98
+ """The raw notification was already delivered by the wire observer."""
99
+
100
+ async def request_permission(
101
+ self, session_id: str, **kwargs: Any
102
+ ) -> RequestPermissionResponse:
103
+ if self.active_session == session_id:
104
+ self.failure = RuntimeError(
105
+ "Antigravity requested permission despite its unattended permission override."
106
+ )
107
+ return RequestPermissionResponse(outcome=DeniedOutcome())
108
+
109
+ async def create_elicitation(self, **kwargs: Any) -> DeclineElicitationResponse:
110
+ return DeclineElicitationResponse()
111
+
112
+
113
+ async def check_acp(executable: str, cwd: Path) -> None:
114
+ """Negotiate the capabilities used by stages without opening a native session."""
115
+ callbacks = _Callbacks(lambda session_id, update: None)
116
+ transport = ACPProcess(executable, cwd, cast(Client, callbacks))
117
+ try:
118
+ await transport.start()
119
+ finally:
120
+ await transport.close()
121
+
122
+
123
+ class AntigravityACP(ACPProcess):
124
+ """One owned server, one workspace session, and any number of sequential turns."""
125
+
126
+ def __init__(
127
+ self,
128
+ request: HarnessLaunchRequest,
129
+ on_update: UpdateCallback,
130
+ *,
131
+ executable: str = "agy",
132
+ ) -> None:
133
+ self._request = request
134
+ self._callbacks = _Callbacks(on_update)
135
+ # The SDK routes missing optional client handlers to method-not-found.
136
+ super().__init__(
137
+ executable,
138
+ request.effective_workspace_root,
139
+ cast(Client, self._callbacks),
140
+ observer=self._callbacks.observe,
141
+ )
142
+ self.session_id: str | None = None
143
+
144
+ async def open_session(self) -> str:
145
+ cwd = str(self._cwd)
146
+ prior = self._request.retry_session_id
147
+ try:
148
+ if prior is None:
149
+ created = await self.connection.new_session(cwd=cwd, mcp_servers=[])
150
+ if not created.session_id.strip():
151
+ raise RuntimeError("Antigravity did not supply a session ID.")
152
+ self.session_id = created.session_id
153
+ options = created.config_options
154
+ else:
155
+ options = await self._reopen(prior, cwd)
156
+ self.session_id = prior
157
+ except RequestError as exc:
158
+ _rpc_failure(exc, session_id=prior)
159
+ try:
160
+ await configure_session(
161
+ self.connection,
162
+ self.session_id,
163
+ options or [],
164
+ self._request.model,
165
+ self._request.effort,
166
+ )
167
+ except RequestError as exc:
168
+ _rpc_failure(exc)
169
+ return self.session_id
170
+
171
+ async def _reopen(
172
+ self, prior: str, cwd: str
173
+ ) -> list[SessionConfigOptionBoolean | SessionConfigOptionSelect] | None:
174
+ if self._supports_resume:
175
+ try:
176
+ resumed = await self.connection.resume_session(
177
+ session_id=prior, cwd=cwd, mcp_servers=[]
178
+ )
179
+ return resumed.config_options
180
+ except RequestError as exc:
181
+ # agy can require the full history load. Only load can distinguish
182
+ # this recoverable condition from a genuinely missing conversation.
183
+ advisory = f"Failed to read session {prior}; retry, or load it with session/load"
184
+ if not self._supports_load or not (
185
+ exc.code == -32601 or (exc.code == -32603 and str(exc) == advisory)
186
+ ):
187
+ raise
188
+ loaded = await self.connection.load_session(
189
+ session_id=prior, cwd=cwd, mcp_servers=[]
190
+ )
191
+ return loaded.config_options
192
+
193
+ async def prompt(self, text: str) -> dict[str, Any]:
194
+ if self.session_id is None:
195
+ raise RuntimeError("Antigravity ACP has no open session.")
196
+ self._callbacks.active_session = self.session_id
197
+ self._callbacks.failure = None
198
+ try:
199
+ result = await self.connection.prompt(
200
+ session_id=self.session_id, prompt=[TextContentBlock(text=text)]
201
+ )
202
+ except RequestError as exc:
203
+ _rpc_failure(exc)
204
+ finally:
205
+ self._callbacks.active_session = None
206
+ if self._callbacks.failure is not None:
207
+ raise self._callbacks.failure
208
+ return result.model_dump(mode="json", by_alias=True, exclude_none=True)
209
+
210
+ async def cancel(self) -> None:
211
+ self._capture()
212
+ if self._conn is not None and self.session_id is not None:
213
+ with suppress(Exception):
214
+ await asyncio.wait_for(
215
+ self._conn.cancel(session_id=self.session_id), timeout=0.5
216
+ )
217
+
218
+ async def close(self) -> None:
219
+ self._capture()
220
+ try:
221
+ if (
222
+ self._supports_close
223
+ and self.session_id is not None
224
+ and self._conn is not None
225
+ ):
226
+ with suppress(Exception):
227
+ await asyncio.wait_for(
228
+ self._conn.close_session(session_id=self.session_id),
229
+ timeout=0.5,
230
+ )
231
+ finally:
232
+ await super().close()
@@ -0,0 +1,158 @@
1
+ """Apply native session pickers, including the CLI's model-with-effort spelling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Sequence
7
+
8
+ from acp import RequestError
9
+ from acp.client.connection import ClientSideConnection
10
+ from acp.schema import (
11
+ SessionConfigOptionBoolean,
12
+ SessionConfigOptionSelect,
13
+ SessionConfigSelectGroup,
14
+ SessionConfigSelectOption,
15
+ )
16
+
17
+ from hpilot.adapters.errors import HarnessConfigurationError
18
+
19
+ ConfigOption = SessionConfigOptionSelect | SessionConfigOptionBoolean
20
+ _EFFORT_KEYS = ("thought_level", "thinking_level", "effort")
21
+ # CLI --model accepts both a slug (family-xhigh) and its display name (Family (XHigh)).
22
+ _MODEL_VARIANT = re.compile(
23
+ r"^(.+?)(?:-(low|medium|high|xhigh|max)| \((low|medium|high|xhigh|extra|max)\))$",
24
+ re.I,
25
+ )
26
+
27
+
28
+ def _config_error(message: str) -> HarnessConfigurationError:
29
+ return HarnessConfigurationError(message, harness="antigravity")
30
+
31
+
32
+ def _picker(
33
+ options: Sequence[ConfigOption], keys: tuple[str, ...]
34
+ ) -> SessionConfigOptionSelect | None:
35
+ return next(
36
+ (
37
+ option
38
+ for option in options
39
+ if isinstance(option, SessionConfigOptionSelect)
40
+ and (option.category in keys or option.id in keys)
41
+ ),
42
+ None,
43
+ )
44
+
45
+
46
+ def _choices(picker: SessionConfigOptionSelect) -> list[SessionConfigSelectOption]:
47
+ choices: list[SessionConfigSelectOption] = []
48
+ for choice in picker.options:
49
+ choices.extend(
50
+ choice.options if isinstance(choice, SessionConfigSelectGroup) else [choice]
51
+ )
52
+ return choices
53
+
54
+
55
+ def _value(picker: SessionConfigOptionSelect, requested: str) -> str | None:
56
+ choices = _choices(picker)
57
+ if any(c.value == requested for c in choices):
58
+ return requested
59
+ matching = {
60
+ c.value
61
+ for c in choices
62
+ if requested.casefold() in (c.name.casefold(), c.value.casefold())
63
+ }
64
+ if len(matching) > 1:
65
+ raise _config_error(
66
+ f"Antigravity's {picker.name} label {requested!r} matches multiple values."
67
+ )
68
+ return next(iter(matching), None)
69
+
70
+
71
+ def _unavailable(
72
+ picker: SessionConfigOptionSelect, value: str
73
+ ) -> HarnessConfigurationError:
74
+ values = ", ".join(c.value for c in _choices(picker))
75
+ return _config_error(
76
+ f"Antigravity does not advertise {picker.name} {value!r}. Available values: {values}."
77
+ )
78
+
79
+
80
+ def _effort_value(picker: SessionConfigOptionSelect, effort: str) -> str:
81
+ selected = _value(picker, effort)
82
+ if selected is None and effort.casefold() in {"extra", "xhigh"}:
83
+ selected = _value(picker, "extra" if effort.casefold() == "xhigh" else "xhigh")
84
+ if selected is None:
85
+ raise _unavailable(picker, effort)
86
+ return selected
87
+
88
+
89
+ async def _apply(
90
+ conn: ClientSideConnection,
91
+ session_id: str,
92
+ options: Sequence[ConfigOption],
93
+ picker: SessionConfigOptionSelect,
94
+ selected: str,
95
+ ) -> Sequence[ConfigOption]:
96
+ if selected == picker.current_value:
97
+ return options
98
+ try:
99
+ result = await conn.set_config_option(
100
+ config_id=picker.id, session_id=session_id, value=selected
101
+ )
102
+ except RequestError as exc:
103
+ if exc.code == -32602:
104
+ raise _config_error(
105
+ f"Antigravity rejected {picker.name} {selected!r}: {exc}"
106
+ ) from exc
107
+ raise
108
+ active = next(
109
+ (option for option in result.config_options if option.id == picker.id), None
110
+ )
111
+ if active is None or active.current_value != selected:
112
+ raise _config_error(
113
+ f"Antigravity did not apply requested {picker.name} {selected!r}."
114
+ )
115
+ return result.config_options
116
+
117
+
118
+ async def configure_session(
119
+ conn: ClientSideConnection,
120
+ session_id: str,
121
+ options: Sequence[ConfigOption],
122
+ model: str | None,
123
+ effort: str | None,
124
+ ) -> None:
125
+ variant_effort = None
126
+ if model is not None:
127
+ picker = _picker(options, ("model",))
128
+ if picker is None:
129
+ raise _config_error(
130
+ f"Antigravity does not offer a model setting for {model!r}."
131
+ )
132
+ selected = _value(picker, model)
133
+ if selected is None and (variant := _MODEL_VARIANT.fullmatch(model)):
134
+ selected = _value(picker, variant[1])
135
+ if selected is not None:
136
+ variant_effort = (variant[2] or variant[3]).lower()
137
+ effort = effort or variant_effort
138
+ if selected is None and effort is not None:
139
+ # Some catalogs advertise individual variants as their model values.
140
+ selected = _value(picker, f"{model}-{effort}")
141
+ if selected is not None:
142
+ effort = None # The advertised model itself selects this effort.
143
+ if selected is None:
144
+ raise _unavailable(picker, model)
145
+ options = await _apply(conn, session_id, options, picker, selected)
146
+ if effort is not None:
147
+ # Changing a model can replace or remove the thinking-level picker.
148
+ picker = _picker(options, _EFFORT_KEYS)
149
+ if picker is None:
150
+ raise _config_error(
151
+ f"Antigravity does not offer a reasoning effort setting for {effort!r}."
152
+ )
153
+ if variant_effort is not None and variant_effort != effort:
154
+ # An explicit effort can override a valid variant, but an unavailable
155
+ # model slug must still fail even if the override itself is valid.
156
+ _effort_value(picker, variant_effort)
157
+ selected = _effort_value(picker, effort)
158
+ await _apply(conn, session_id, options, picker, selected)