hypercli-sdk 0.10.3__tar.gz → 0.10.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 (77) hide show
  1. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/PKG-INFO +1 -1
  2. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/__init__.py +5 -2
  3. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/acp.py +80 -17
  4. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/agents.py +17 -2
  5. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/sessions.py +35 -0
  6. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/pyproject.toml +1 -1
  7. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_acp.py +290 -4
  8. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_public_surface.py +2 -0
  9. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_sessions.py +41 -1
  10. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/.gitignore +0 -0
  11. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/README.md +0 -0
  12. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/agent.py +0 -0
  13. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/billing.py +0 -0
  14. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/chat_integrations.py +0 -0
  15. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/client.py +0 -0
  16. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/config.py +0 -0
  17. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/files.py +0 -0
  18. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/http.py +0 -0
  19. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/instances.py +0 -0
  20. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/job/__init__.py +0 -0
  21. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/job/base.py +0 -0
  22. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/job/comfyui.py +0 -0
  23. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/job/gradio.py +0 -0
  24. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/jobs.py +0 -0
  25. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/keys.py +0 -0
  26. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/logs.py +0 -0
  27. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/mcp.py +0 -0
  28. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/models.py +0 -0
  29. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/renders.py +0 -0
  30. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/routines.py +0 -0
  31. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/runners.py +0 -0
  32. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/shell.py +0 -0
  33. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/user.py +0 -0
  34. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/voice.py +0 -0
  35. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/voice_stream.py +0 -0
  36. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/voice_transcription.py +0 -0
  37. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/workspaces.py +0 -0
  38. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/hypercli/x402.py +0 -0
  39. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/conftest.py +0 -0
  40. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_agents.py +0 -0
  41. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_auth.py +0 -0
  42. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_billing.py +0 -0
  43. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_instances.py +0 -0
  44. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_jobs_dryrun.py +0 -0
  45. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_keys.py +0 -0
  46. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/integration/test_renders.py +0 -0
  47. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_agent_files_source.py +0 -0
  48. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_agent_lifecycle.py +0 -0
  49. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_agents.py +0 -0
  50. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_apply_params.py +0 -0
  51. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_bootstrap_agents_e2e_user.py +0 -0
  52. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_bootstrap_console_test_key.py +0 -0
  53. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_bootstrap_dev_test_keys.py +0 -0
  54. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_chat_integrations.py +0 -0
  55. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_claw.py +0 -0
  56. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_coding_agents.py +0 -0
  57. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_config.py +0 -0
  58. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_exec_shell_dryrun.py +0 -0
  59. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_file_transport.py +0 -0
  60. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_graph_to_api.py +0 -0
  61. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_http.py +0 -0
  62. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_jobs.py +0 -0
  63. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_keys.py +0 -0
  64. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_models.py +0 -0
  65. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_parity_audit.py +0 -0
  66. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_render_catalog.py +0 -0
  67. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_renders_subscription.py +0 -0
  68. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_repository_integrity.py +0 -0
  69. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_routines.py +0 -0
  70. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_runner_control_url.py +0 -0
  71. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_runner_placement.py +0 -0
  72. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_runners.py +0 -0
  73. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_status.py +0 -0
  74. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_voice.py +0 -0
  75. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_voice_stream.py +0 -0
  76. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_voice_transcription.py +0 -0
  77. {hypercli_sdk-0.10.3 → hypercli_sdk-0.10.5}/tests/test_workspaces.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: hypercli-sdk
3
- Version: 0.10.3
3
+ Version: 0.10.5
4
4
  Summary: Python SDK for HyperCLI - GPU orchestration and HyperAgent API
5
5
  Project-URL: Homepage, https://hypercli.com
6
6
  Project-URL: Documentation, https://docs.hypercli.com
@@ -53,7 +53,7 @@ from .workspaces import (
53
53
  WorkspacesAPI,
54
54
  )
55
55
  from .routines import Routine, RoutinesAPI
56
- from .sessions import SessionPage, SessionRecord
56
+ from .sessions import SessionPage, SessionRecord, SessionSetup
57
57
  from .runners import Runner, RunnerMeta, RunnerUiMeta, RunnersAPI
58
58
  from .x402 import X402Client, X402JobLaunch, X402FlowCreate, FlowCatalogItem
59
59
  from .files import File
@@ -151,19 +151,21 @@ from .acp import (
151
151
  ACPError,
152
152
  ACPPromptResult,
153
153
  ACPRequestError,
154
+ ACPStartupError,
154
155
  ACPTerminalCloseError,
155
156
  ACPUnavailableError,
156
157
  ACP_PROXY_UNKNOWN_SESSION_CLOSE_CODE,
157
158
  AmbiguousDeliveryError,
158
159
  RetryableACPError,
159
160
  )
160
- __version__ = "0.10.3"
161
+ __version__ = "0.10.5"
161
162
  __all__ = [
162
163
  "CHAT_INTEGRATIONS",
163
164
  "build_chat_integration_config",
164
165
  "HyperCLI",
165
166
  "SessionPage",
166
167
  "SessionRecord",
168
+ "SessionSetup",
167
169
  "configure",
168
170
  "get_api_key",
169
171
  "get_agent_api_key",
@@ -352,6 +354,7 @@ __all__ = [
352
354
  "ACPError",
353
355
  "ACPPromptResult",
354
356
  "ACPRequestError",
357
+ "ACPStartupError",
355
358
  "ACPTerminalCloseError",
356
359
  "ACPUnavailableError",
357
360
  "ACP_PROXY_UNKNOWN_SESSION_CLOSE_CODE",
@@ -21,6 +21,8 @@ from pydantic import ValidationError
21
21
  from websockets.asyncio.client import connect as websocket_connect
22
22
  from websockets.exceptions import WebSocketException
23
23
 
24
+ from .sessions import _parse_session_setup
25
+
24
26
  logger = logging.getLogger("hypercli.acp")
25
27
  ACP_PROTOCOL_VERSION = 1
26
28
  # Transport capacity, not content admission: 25,000,000 decoded image bytes
@@ -82,6 +84,16 @@ class ACPUnavailableError(ACPError):
82
84
  super().__init__(f"{capability} is not available: {detail}")
83
85
 
84
86
 
87
+ class ACPStartupError(ACPError):
88
+ """Product capacity refusal before native startup; not a native JSON-RPC error."""
89
+
90
+ code = "unavailable"
91
+
92
+ def __init__(self, message):
93
+ self.message = message
94
+ super().__init__(f"ACP session startup was refused (unavailable): {message}")
95
+
96
+
85
97
  @dataclass(frozen=True)
86
98
  class ACPPromptResult:
87
99
  """Native terminal prompt result, without a platform receipt dependency."""
@@ -102,18 +114,53 @@ class _Transport:
102
114
  await self.transport.send(message)
103
115
 
104
116
  async def receive(self):
105
- try:
106
- message = await self.transport.receive()
107
- except Exception:
108
- async with self.writing:
109
- self.owner._disconnect()
110
- raise
111
- if message is None:
112
- # The pinned SDK transport owns the socket. Preserve its public
113
- # WebSocket close classification at this one transport boundary.
114
- async with self.writing:
115
- self._observe_close()
116
- return message
117
+ while True:
118
+ try:
119
+ message = await self.transport.receive()
120
+ except Exception:
121
+ async with self.writing:
122
+ self.owner._disconnect()
123
+ raise
124
+ if message is None:
125
+ # The pinned SDK transport owns the socket. Preserve its public
126
+ # WebSocket close classification at this one transport boundary.
127
+ async with self.writing:
128
+ self._observe_close()
129
+ return None
130
+ if isinstance(message, dict) and message.get("type") == "sessionStartupError" \
131
+ and await self._refuse_startup(message):
132
+ # Product capacity refusal consumed here; the JSON-RPC reader
133
+ # keeps reading the still-open connection.
134
+ continue
135
+ return message
136
+
137
+ async def _refuse_startup(self, message):
138
+ """Settle the pending request a product ``sessionStartupError`` refuses.
139
+
140
+ The host reports session-startup capacity refusals as a product frame,
141
+ not a JSON-RPC response, and keeps the connection open; the upstream
142
+ connection would otherwise leave the request pending forever. Returns
143
+ True when the frame is consumed here.
144
+ """
145
+ error = message.get("error")
146
+ request_id = message.get("requestId")
147
+ if (not isinstance(request_id, (str, int)) or isinstance(request_id, bool)
148
+ or not isinstance(error, dict) or error.get("code") != "unavailable"
149
+ or not isinstance(error.get("message"), str)):
150
+ return False
151
+ pending = getattr(self.owner._connection, "_pending", None)
152
+ if isinstance(pending, dict):
153
+ future = pending.pop(request_id, None)
154
+ if future is not None and not future.done():
155
+ future.set_exception(ACPStartupError(error["message"]))
156
+ return True
157
+ # The upstream pending-request seam is absent in this installed version.
158
+ # Fail the connection with the refusal instead of leaving the request
159
+ # pending forever on an open socket.
160
+ logger.warning("ACP sessionStartupError cannot reach the upstream pending map; closing the connection")
161
+ self.owner._disconnect(ACPStartupError(error["message"]))
162
+ await self.close()
163
+ return True
117
164
 
118
165
  async def close(self):
119
166
  await self.transport.close()
@@ -128,7 +175,8 @@ class _Transport:
128
175
 
129
176
  class ACPClient:
130
177
  """One connection using the pinned upstream v1 SDK runtime."""
131
- def __init__(self, transport, *, on_update=None, resolve_default_cwd=None):
178
+ def __init__(self, transport, *, on_update=None, resolve_default_cwd=None,
179
+ resolve_session_setup=None):
132
180
  self._closed = False
133
181
  self._disconnected = False
134
182
  self._transport_error = None
@@ -136,6 +184,7 @@ class ACPClient:
136
184
  self._update_listeners = [on_update] if on_update else []
137
185
  self._request_listeners = {}
138
186
  self._resolve_default_cwd = resolve_default_cwd
187
+ self._resolve_session_setup = resolve_session_setup
139
188
  self._session_setups: dict[str, dict[str, Any]] = {}
140
189
  self._session_config_options: dict[str, list[dict[str, Any]]] = {}
141
190
  self._transport = _Transport(transport, self)
@@ -144,7 +193,7 @@ class ACPClient:
144
193
  @classmethod
145
194
  async def connect(cls, url, *, token=None, open_timeout=DEFAULT_OPEN_TIMEOUT, source=None,
146
195
  client_info=None, client_capabilities=None, on_update=None,
147
- resolve_default_cwd=None):
196
+ resolve_default_cwd=None, resolve_session_setup=None):
148
197
  """Connect with caller-declared capabilities (empty by default).
149
198
 
150
199
  Callers advertising filesystem or terminal support must register the
@@ -161,7 +210,8 @@ class ACPClient:
161
210
  except (TimeoutError, WebSocketException, OSError) as exc:
162
211
  raise RetryableACPError(f"ACP connect failed: {exc}") from exc
163
212
  client = cls(transport, on_update=on_update,
164
- resolve_default_cwd=resolve_default_cwd)
213
+ resolve_default_cwd=resolve_default_cwd,
214
+ resolve_session_setup=resolve_session_setup)
165
215
  try:
166
216
  request = schema.InitializeRequest(protocol_version=ACP_PROTOCOL_VERSION,
167
217
  client_info=schema.Implementation.model_validate(client_info or DEFAULT_CLIENT_INFO),
@@ -318,15 +368,28 @@ class ACPClient:
318
368
  return entry.cwd
319
369
  cursor = page.next_cursor
320
370
  if not cursor:
321
- raise ACPUnavailableError("session/resume", "the original session cwd is unavailable from the standard catalog")
371
+ raise ACPUnavailableError(
372
+ "session/resume",
373
+ f"session {session_id!r} was not found in the available session catalog; "
374
+ "cannot resolve its original cwd. Check the session ID and saved session setup",
375
+ )
322
376
  if cursor in seen:
323
377
  raise ACPUnavailableError("session/list", "catalog repeated a pagination cursor")
324
378
  seen.add(cursor)
325
379
 
326
380
  async def resume_session(self, session_id, *, cwd=_UNSET_CWD, mcp_servers=None):
327
381
  """Resume the exact identity with its original catalog/stored setup."""
328
- cwd = await self._original_session_cwd(session_id) if cwd is _UNSET_CWD else cwd
329
382
  previous = self._session_setups.get(session_id, {})
383
+ if mcp_servers is None and not previous and self._resolve_session_setup is not None:
384
+ recovered = self._resolve_session_setup(session_id)
385
+ if inspect.isawaitable(recovered):
386
+ recovered = await recovered
387
+ if recovered is not None:
388
+ # Typed standard setup parsing; resolver failures must not turn
389
+ # an unknown intended MCP list into an explicit empty override.
390
+ previous = _parse_session_setup(recovered)
391
+ if cwd is _UNSET_CWD:
392
+ cwd = previous["cwd"] if previous else await self._original_session_cwd(session_id)
330
393
  setup = {"cwd": cwd, "mcpServers": deepcopy(mcp_servers if mcp_servers is not None else previous.get("mcpServers", []))}
331
394
  params = {"sessionId": session_id, **setup}
332
395
  result = await self.request("session/resume", params)
@@ -45,7 +45,7 @@ from .config import (
45
45
  _default_agents_ws_url,
46
46
  )
47
47
  from .http import HTTPClient, APIError
48
- from .sessions import SessionPage, SessionRecord
48
+ from .sessions import SessionPage, SessionRecord, SessionSetup
49
49
 
50
50
 
51
51
  AGENTS_API_PREFIX = "/deployments"
@@ -3652,19 +3652,34 @@ class Deployments:
3652
3652
  return self._get(f"{AGENTS_API_PREFIX}/{quote(agent_id, safe='')}/runtime-paths")
3653
3653
 
3654
3654
  async def acp_connect(self, agent_id: str, **options):
3655
- """Connect without caller cwd configuration; resolve only at session/new."""
3655
+ """Connect with authenticated runtime-path and saved-setup resolvers."""
3656
3656
  from .acp import ACPClient
3657
3657
 
3658
3658
  async def default_cwd():
3659
3659
  return (await asyncio.to_thread(self.runtime_paths, agent_id))["cwd"]
3660
3660
 
3661
+ async def session_setup(session_id):
3662
+ return (await asyncio.to_thread(
3663
+ self.get_session_setup, session_id, agent_id=agent_id,
3664
+ )).setup
3665
+
3661
3666
  parts = urlsplit(self.acp_ws_url)
3662
3667
  query = dict(parse_qsl(parts.query, keep_blank_values=True))
3663
3668
  query["agent_id"] = agent_id
3664
3669
  options.setdefault("token", self._api_key)
3665
3670
  options.setdefault("resolve_default_cwd", default_cwd)
3671
+ options.setdefault("resolve_session_setup", session_setup)
3666
3672
  return await ACPClient.connect(urlunsplit(parts._replace(query=urlencode(query))), **options)
3667
3673
 
3674
+ def get_session_setup(self, session_id: str, *, agent_id: str) -> SessionSetup:
3675
+ """Read retained setup for the exact session/agent pair; null means unknown."""
3676
+ result = SessionSetup.from_dict(self._get(
3677
+ f"/sessions/{quote(session_id, safe='')}/setup", params={"agent_id": agent_id},
3678
+ ))
3679
+ if result.session_id != session_id or result.agent_id != agent_id:
3680
+ raise ValueError("Session setup response does not match the requested session/agent")
3681
+ return result
3682
+
3668
3683
  def get_session(self, platform_session_id: str) -> SessionRecord:
3669
3684
  """Read stored metadata by platform session ID, never a runtime/leg ID.
3670
3685
 
@@ -1,8 +1,43 @@
1
1
  """Backend session catalog types. Source is descriptive, forward-open provenance."""
2
2
 
3
+ from copy import deepcopy
3
4
  from dataclasses import dataclass, field
4
5
  from typing import Any
5
6
 
7
+ from acp import schema
8
+
9
+
10
+ def _parse_session_setup(setup: Any) -> dict[str, Any]:
11
+ if not isinstance(setup, dict) or not isinstance(setup.get("mcpServers"), list):
12
+ raise ValueError("Invalid session setup: expected an object with mcpServers")
13
+ parsed = schema.NewSessionRequest.model_validate(setup)
14
+ # Upstream's forward-compatible parser drops invalid list entries. Recovery
15
+ # must preserve the entire intended list or fail, never silently shorten it.
16
+ if len(parsed.mcp_servers) != len(setup["mcpServers"]):
17
+ raise ValueError("Invalid session setup MCP server entry")
18
+ return deepcopy(setup)
19
+
20
+
21
+ @dataclass
22
+ class SessionSetup:
23
+ """Platform-retained standard ACP setup for one session/agent pair."""
24
+
25
+ session_id: str
26
+ agent_id: str
27
+ setup: dict[str, Any] | None
28
+
29
+ @classmethod
30
+ def from_dict(cls, data: dict[str, Any]) -> "SessionSetup":
31
+ if (not isinstance(data, dict)
32
+ or not isinstance(data.get("session_id"), str)
33
+ or not isinstance(data.get("agent_id"), str)
34
+ or "setup" not in data):
35
+ raise ValueError("Invalid session setup response")
36
+ setup = data["setup"]
37
+ if setup is not None:
38
+ setup = _parse_session_setup(setup)
39
+ return cls(data["session_id"], data["agent_id"], setup)
40
+
6
41
 
7
42
  @dataclass
8
43
  class SessionRecord:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "hypercli-sdk"
7
- version = "0.10.3"
7
+ version = "0.10.5"
8
8
  description = "Python SDK for HyperCLI - GPU orchestration and HyperAgent API"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -6,21 +6,40 @@ import asyncio
6
6
  import gc
7
7
  import json
8
8
  from contextlib import asynccontextmanager
9
+ from copy import deepcopy
9
10
 
11
+ import httpx
10
12
  import pytest
11
- from acp.exceptions import RequestError
12
13
  from acp import schema
13
14
  from acp.agent import AgentSideConnection
15
+ from acp.exceptions import RequestError
14
16
  from websockets.asyncio.server import serve
15
17
  from websockets.exceptions import ConnectionClosed
16
18
 
17
19
  from hypercli.acp import (
18
- ACPClient, ACPClosedError, ACPError, ACPRequestError, ACPTerminalCloseError,
19
- AmbiguousDeliveryError, RetryableACPError, ACP_TERMINAL_CLOSE_CODES,
20
+ ACP_TERMINAL_CLOSE_CODES,
21
+ ACPClient,
22
+ ACPClosedError,
23
+ ACPError,
24
+ ACPRequestError,
25
+ ACPStartupError,
26
+ ACPTerminalCloseError,
27
+ ACPUnavailableError,
28
+ AmbiguousDeliveryError,
29
+ RetryableACPError,
20
30
  )
21
31
 
22
32
  pytestmark = pytest.mark.asyncio
23
33
 
34
+ RECOVERED_SETUP = {"cwd": "/saved/project", "mcpServers": [
35
+ {"name": "local", "command": "mcp-tool", "args": ["serve"],
36
+ "env": [{"name": "MODE", "value": "test"}]},
37
+ {"name": "remote", "type": "http", "url": "https://mcp.example.com/api",
38
+ "headers": [{"name": "X-Test", "value": "test"}]},
39
+ {"name": "events", "type": "sse", "url": "https://mcp.example.com/events",
40
+ "headers": []},
41
+ ]}
42
+
24
43
 
25
44
  async def until(predicate):
26
45
  async with asyncio.timeout(5):
@@ -60,10 +79,12 @@ class Peer:
60
79
  self.reject_prompt = False
61
80
  self.reject_resume = False
62
81
  self.hold_initialize = False
82
+ self.hold_new = False
63
83
  self.hold_close = False
64
84
  self.early_close = None
65
85
  self.close_on_upgrade = False
66
86
  self.version = 1
87
+ self.catalog_cwd = "/original/project"
67
88
 
68
89
  async def initialize(self, **kwargs):
69
90
  if self.early_close:
@@ -74,6 +95,8 @@ class Peer:
74
95
  "agentInfo": {"name": "fixture", "version": "1"}, "agentCapabilities": {"sessionCapabilities": {"resume": {}}}})
75
96
 
76
97
  async def new_session(self, **kwargs):
98
+ if self.hold_new:
99
+ await self.release.wait()
77
100
  return schema.NewSessionResponse(session_id="opaque/runtime:id")
78
101
 
79
102
  async def resume_session(self, session_id, **kwargs):
@@ -84,7 +107,7 @@ class Peer:
84
107
 
85
108
  async def list_sessions(self, **kwargs):
86
109
  return schema.ListSessionsResponse.model_validate({"sessions": [
87
- {"sessionId": "opaque/runtime:id", "cwd": "/original/project"},
110
+ {"sessionId": "opaque/runtime:id", "cwd": self.catalog_cwd},
88
111
  ]})
89
112
 
90
113
  async def close_session(self, **kwargs):
@@ -155,6 +178,140 @@ async def test_v1_handshake_source_and_setup_use_standard_shapes():
155
178
  model.model_validate(frame["params"])
156
179
 
157
180
 
181
+ async def test_platform_factory_recovers_memoryless_setup_through_authenticated_rest(monkeypatch):
182
+ from hypercli import HyperCLI
183
+ from hypercli.agents import Deployments
184
+
185
+ requests = []
186
+ agent_id = "3f6c9a20-1b4d-4e5f-8a7c-2d0e9f1b3a45"
187
+ sid = "opaque/runtime:id"
188
+
189
+ def send(self, request, **kwargs):
190
+ requests.append(request)
191
+ return httpx.Response(200, json={
192
+ "session_id": sid, "agent_id": agent_id, "setup": RECOVERED_SETUP,
193
+ }, request=request)
194
+
195
+ monkeypatch.setattr(httpx.Client, "send", send)
196
+ api = HyperCLI(api_key="caller-key", api_url="https://example.com").deployments
197
+ async with server() as (peer, url):
198
+ monkeypatch.setattr(Deployments, "acp_ws_url", property(lambda self: url))
199
+ async with await api.acp_connect(agent_id) as client:
200
+ await client.resume_session(sid)
201
+ assert len(requests) == 1
202
+ assert str(requests[0].url) == (
203
+ f"https://example.com/agents/sessions/opaque%2Fruntime%3Aid/setup?agent_id={agent_id}"
204
+ )
205
+ assert requests[0].headers["Authorization"] == "Bearer caller-key"
206
+ assert requests[0].method == "GET"
207
+ inbound = [f for direction, f in peer.frames if direction == "in"]
208
+ assert [f["method"] for f in inbound] == ["initialize", "session/resume"]
209
+ assert inbound[-1]["params"] == {"sessionId": sid, **RECOVERED_SETUP}
210
+ schema.ResumeSessionRequest.model_validate(inbound[-1]["params"])
211
+
212
+
213
+ async def test_recovered_setup_is_copied_and_only_cached_after_native_success():
214
+ saved = deepcopy(RECOVERED_SETUP)
215
+ calls = []
216
+
217
+ async def resolve(sid):
218
+ calls.append(sid)
219
+ return saved
220
+
221
+ sid = "opaque/runtime:id"
222
+ async with server() as (peer, url), await ACPClient.connect(url, resolve_session_setup=resolve) as client:
223
+ peer.reject_resume = True
224
+ with pytest.raises(ACPRequestError):
225
+ await client.resume_session(sid)
226
+ assert sid not in client._session_setups
227
+ peer.reject_resume = False
228
+ await client.resume_session(sid)
229
+ saved["mcpServers"][0]["env"][0]["value"] = "changed"
230
+ saved["cwd"] = "/changed"
231
+ await client.resume_session(sid)
232
+ assert calls == [sid, sid]
233
+ frames = [f for direction, f in peer.frames if direction == "in" and f["method"] == "session/resume"]
234
+ assert all(f["params"] == {"sessionId": sid, **RECOVERED_SETUP} for f in frames)
235
+
236
+
237
+ @pytest.mark.parametrize("status,payload", [
238
+ (403, {"detail": "denied"}), (500, {"detail": "unavailable"}),
239
+ (200, {"session_id": "opaque/runtime:id", "agent_id": "agent"}),
240
+ (200, {"session_id": "wrong", "agent_id": "agent", "setup": None}),
241
+ ])
242
+ async def test_factory_recovery_failure_prevents_native_resume(monkeypatch, status, payload):
243
+ from hypercli import HyperCLI
244
+ from hypercli.agents import Deployments
245
+ from hypercli.http import APIError
246
+
247
+ def send(self, request, **kwargs):
248
+ return httpx.Response(status, json=payload, request=request)
249
+
250
+ monkeypatch.setattr(httpx.Client, "send", send)
251
+ api = HyperCLI(api_key="caller-key", api_url="https://example.com").deployments
252
+ async with server() as (peer, url):
253
+ monkeypatch.setattr(Deployments, "acp_ws_url", property(lambda self: url))
254
+ async with await api.acp_connect("agent") as client:
255
+ with pytest.raises(APIError if status >= 400 else ValueError):
256
+ await client.resume_session("opaque/runtime:id")
257
+ assert [f["method"] for direction, f in peer.frames if direction == "in"] == ["initialize"]
258
+
259
+
260
+ @pytest.mark.parametrize("servers", [[], RECOVERED_SETUP["mcpServers"]])
261
+ async def test_explicit_mcp_list_bypasses_recovery(servers):
262
+ def forbidden(sid):
263
+ pytest.fail("an explicit list must bypass platform recovery")
264
+
265
+ async with server() as (peer, url), await ACPClient.connect(url, resolve_session_setup=forbidden) as client:
266
+ await client.resume_session("opaque/runtime:id", mcp_servers=servers)
267
+ await client.resume_session("opaque/runtime:id")
268
+ frames = [f for direction, f in peer.frames if direction == "in" and f["method"] == "session/resume"]
269
+ assert [f["params"]["mcpServers"] for f in frames] == [servers, servers]
270
+
271
+
272
+ @pytest.mark.parametrize("recovered", [{}, {"cwd": "/saved"},
273
+ {"cwd": "/saved", "mcpServers": None}, {"cwd": "/saved", "mcpServers": [42]}, []])
274
+ async def test_malformed_recovery_never_sends_resume(recovered):
275
+ async with server() as (peer, url), await ACPClient.connect(
276
+ url, resolve_session_setup=lambda sid: recovered,
277
+ ) as client:
278
+ with pytest.raises(ValueError):
279
+ await client.resume_session("opaque/runtime:id", cwd="/override")
280
+ assert [f["method"] for direction, f in peer.frames if direction == "in"] == ["initialize"]
281
+
282
+
283
+ @pytest.mark.parametrize("error", [httpx.TimeoutException("timeout"), RuntimeError("denied")])
284
+ async def test_recovery_errors_propagate_before_resume(error):
285
+ async def resolve(sid):
286
+ raise error
287
+
288
+ async with server() as (peer, url), await ACPClient.connect(url, resolve_session_setup=resolve) as client:
289
+ with pytest.raises(type(error)) as caught:
290
+ await client.resume_session("opaque/runtime:id")
291
+ assert caught.value is error
292
+ assert [f["method"] for direction, f in peer.frames if direction == "in"] == ["initialize"]
293
+
294
+
295
+ async def test_unknown_setup_keeps_catalog_fallback_and_explicit_cwd_wins():
296
+ async with server() as (peer, url), await ACPClient.connect(
297
+ url, resolve_session_setup=lambda sid: None,
298
+ ) as client:
299
+ await client.resume_session("opaque/runtime:id")
300
+ frames = [f for direction, f in peer.frames if direction == "in"]
301
+ assert [f["method"] for f in frames] == ["initialize", "session/list", "session/resume"]
302
+ assert frames[-1]["params"] == {
303
+ "sessionId": "opaque/runtime:id", "cwd": peer.catalog_cwd, "mcpServers": [],
304
+ }
305
+ async with server() as (peer, url), await ACPClient.connect(
306
+ url, resolve_session_setup=lambda sid: RECOVERED_SETUP,
307
+ ) as client:
308
+ await client.resume_session("opaque/runtime:id", cwd="/override")
309
+ frames = [f for direction, f in peer.frames if direction == "in"]
310
+ assert frames[-1]["params"] == {
311
+ "sessionId": "opaque/runtime:id", **RECOVERED_SETUP, "cwd": "/override",
312
+ }
313
+
314
+
158
315
  async def test_v2_initialize_answer_is_not_a_supported_execution_profile():
159
316
  async with server() as (peer, url):
160
317
  peer.version = 2
@@ -271,6 +428,7 @@ async def test_default_creation_and_tracked_resume_do_not_re_resolve_launch_cwd(
271
428
  async def test_agent_connect_wires_lazy_runtime_default_without_caller_paths(monkeypatch):
272
429
  from types import SimpleNamespace
273
430
  from urllib.parse import parse_qs, urlsplit
431
+
274
432
  from hypercli.agents import Deployments
275
433
 
276
434
  async with server() as (peer, url):
@@ -306,6 +464,33 @@ async def test_fresh_resume_uses_original_catalog_cwd_without_launch_resolution(
306
464
  assert inbound[-1]["params"] == {"sessionId": "opaque/runtime:id", "cwd": "/original/project", "mcpServers": []}
307
465
 
308
466
 
467
+ @pytest.mark.parametrize("session_id", ["resuscitator", "pr-watch", "builder-watch", "missing-session"])
468
+ async def test_unknown_session_reports_catalog_lookup_not_filesystem_failure(session_id):
469
+ async def forbidden_launch_resolution():
470
+ pytest.fail("an unknown binding must not be replaced with the launch cwd")
471
+
472
+ async with server() as (peer, url), await ACPClient.connect(url, resolve_default_cwd=forbidden_launch_resolution) as client:
473
+ with pytest.raises(ACPUnavailableError, match="not found in the available session catalog") as error:
474
+ await client.resume_session(session_id)
475
+ assert session_id in str(error.value)
476
+ assert [f["method"] for direction, f in peer.frames if direction == "in"] == ["initialize", "session/list"]
477
+
478
+
479
+ @pytest.mark.parametrize("cwd", [r"C:\Users\old-runner\project", "/home/alice/project", "/home/node/shared"])
480
+ async def test_old_session_preserves_original_catalog_cwd_and_runtime_refusal(cwd):
481
+ async def forbidden_launch_resolution():
482
+ pytest.fail("resume must preserve the original cwd, including legacy paths")
483
+
484
+ async with server() as (peer, url), await ACPClient.connect(url, resolve_default_cwd=forbidden_launch_resolution) as client:
485
+ peer.catalog_cwd = cwd
486
+ peer.reject_resume = True
487
+ with pytest.raises(ACPRequestError, match="unsupported setup"):
488
+ await client.resume_session("opaque/runtime:id")
489
+ inbound = [f for direction, f in peer.frames if direction == "in"]
490
+ assert [f["method"] for f in inbound] == ["initialize", "session/list", "session/resume"]
491
+ assert inbound[-1]["params"]["cwd"] == cwd
492
+
493
+
309
494
  async def test_foreground_waits_for_terminal_result_and_preserves_media():
310
495
  async with server() as (peer, url), await ACPClient.connect(url, on_update=peer.updates.append) as client:
311
496
  sid = await client.new_session(cwd="/workspace")
@@ -768,3 +953,104 @@ async def test_reader_failure_racing_write_does_not_leak_duplicate_future_error(
768
953
  assert not diagnostics
769
954
  finally:
770
955
  loop.set_exception_handler(previous)
956
+
957
+
958
+ def inbound(peer, method):
959
+ return next(f for d, f in peer.frames if d == "in" and f.get("method") == method)
960
+
961
+
962
+ def inbound_seen(peer, method):
963
+ return any(d == "in" and f.get("method") == method for d, f in peer.frames)
964
+
965
+
966
+ async def test_session_startup_refusal_settles_pending_request_and_keeps_connection_usable():
967
+ """A product sessionStartupError settles only its request; the socket lives on."""
968
+ async with server() as (peer, url), await ACPClient.connect(url) as client:
969
+ peer.hold_new = True
970
+
971
+ async def refuse_startup():
972
+ await until(lambda: inbound_seen(peer, "session/new"))
973
+ request = inbound(peer, "session/new")
974
+ await peer.socket.send(json.dumps({"type": "sessionStartupError", "requestId": request["id"],
975
+ "error": {"code": "unavailable", "message": "All worker slots are occupied"}}))
976
+
977
+ peer.tasks.add(asyncio.create_task(refuse_startup()))
978
+ with pytest.raises(ACPStartupError, match="All worker slots are occupied"):
979
+ async with asyncio.timeout(5):
980
+ await client.new_session(cwd="/workspace")
981
+ # The peer's blocked session/new answer arrives late for a request that
982
+ # already settled; the connection must keep reading past both frames.
983
+ refused_id = inbound(peer, "session/new")["id"]
984
+ peer.release.set()
985
+ await until(lambda: any(d == "out" and f.get("id") == refused_id for d, f in peer.frames))
986
+ async with asyncio.timeout(5):
987
+ assert await client.new_session(cwd="/workspace") == "opaque/runtime:id"
988
+
989
+
990
+ async def test_malformed_or_foreign_startup_frames_do_not_settle_pending_requests():
991
+ """Invalid product shapes are not answered with fabricated request errors."""
992
+ async with server() as (peer, url), await ACPClient.connect(url) as client:
993
+ peer.hold_new = True
994
+
995
+ async def send_startup_frames():
996
+ await until(lambda: inbound_seen(peer, "session/new"))
997
+ request = inbound(peer, "session/new")
998
+ for frame in (
999
+ {"type": "sessionStartupError", "requestId": request["id"],
1000
+ "error": {"code": "busy", "message": "wrong code"}},
1001
+ {"type": "sessionStartupError", "requestId": "foreign-id",
1002
+ "error": {"code": "unavailable", "message": "foreign id"}},
1003
+ {"type": "sessionStartupError", "requestId": True,
1004
+ "error": {"code": "unavailable", "message": "bool id"}},
1005
+ {"type": "unrelatedProductFrame"},
1006
+ ):
1007
+ await peer.socket.send(json.dumps(frame))
1008
+
1009
+ peer.tasks.add(asyncio.create_task(send_startup_frames()))
1010
+ pending = asyncio.create_task(client.new_session(cwd="/workspace"))
1011
+ await asyncio.sleep(0.05)
1012
+ assert not pending.done(), "invalid product frames must not settle the pending request"
1013
+ peer.release.set()
1014
+ assert await asyncio.wait_for(pending, 5) == "opaque/runtime:id"
1015
+
1016
+
1017
+ async def test_session_startup_refusal_without_pending_seam_fails_closed_instead_of_hanging():
1018
+ """Without a dict ``_pending`` seam the refusal still fails the caller, closed."""
1019
+
1020
+ class NonDictPending:
1021
+ # Upstream-shaped request map that defeats the isinstance(dict) seam
1022
+ # while keeping the installed Connection's own bookkeeping working.
1023
+ def __init__(self):
1024
+ self.entries = {}
1025
+
1026
+ def __setitem__(self, request_id, future):
1027
+ self.entries[request_id] = future
1028
+
1029
+ def pop(self, request_id, *default):
1030
+ return self.entries.pop(request_id, *default)
1031
+
1032
+ def values(self):
1033
+ return self.entries.values()
1034
+
1035
+ def clear(self):
1036
+ self.entries.clear()
1037
+
1038
+ async with server() as (peer, url), await ACPClient.connect(url) as client:
1039
+ client._connection._pending = NonDictPending()
1040
+ peer.hold_new = True
1041
+
1042
+ async def refuse_startup():
1043
+ await until(lambda: inbound_seen(peer, "session/new"))
1044
+ request = inbound(peer, "session/new")
1045
+ await peer.socket.send(json.dumps({"type": "sessionStartupError", "requestId": request["id"],
1046
+ "error": {"code": "unavailable", "message": "All worker slots are occupied"}}))
1047
+
1048
+ peer.tasks.add(asyncio.create_task(refuse_startup()))
1049
+ with pytest.raises(ACPStartupError, match="All worker slots are occupied") as refusal:
1050
+ async with asyncio.timeout(5):
1051
+ await client.new_session(cwd="/workspace")
1052
+ # The caller saw the recorded typed error rather than a hang, and the
1053
+ # fallback closed the transport and marked the connection dead.
1054
+ assert refusal.value is client._transport_error
1055
+ assert client._disconnected
1056
+ assert client._transport.transport._ws.close_code is not None
@@ -20,6 +20,7 @@ EXPECTED_PUBLIC_SURFACE = frozenset(
20
20
  "ACPError",
21
21
  "ACPPromptResult",
22
22
  "ACPRequestError",
23
+ "ACPStartupError",
23
24
  "ACPTerminalCloseError",
24
25
  "ACPUnavailableError",
25
26
  "ACP_PROXY_UNKNOWN_SESSION_CLOSE_CODE",
@@ -141,6 +142,7 @@ EXPECTED_PUBLIC_SURFACE = frozenset(
141
142
  "RuntimeLoginSession",
142
143
  "SessionPage",
143
144
  "SessionRecord",
145
+ "SessionSetup",
144
146
  "ShellSession",
145
147
  "User",
146
148
  "UserAPI",
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock
3
3
  import httpx
4
4
  import pytest
5
5
 
6
- from hypercli import HyperCLI, SessionRecord
6
+ from hypercli import HyperCLI, SessionRecord, SessionSetup
7
7
  from hypercli.agents import Deployments
8
8
  from hypercli.http import APIError, HTTPClient
9
9
 
@@ -29,6 +29,46 @@ def test_old_server_missing_source_is_null():
29
29
  assert SessionRecord.from_dict({"id": "old-session"}).source is None
30
30
 
31
31
 
32
+ def test_setup_type_distinguishes_unknown_and_copies_nested_setup():
33
+ payload = {"session_id": "session", "agent_id": "agent", "setup": None}
34
+ assert SessionSetup.from_dict(payload).setup is None
35
+ payload["setup"] = {"cwd": "/project", "mcpServers": [
36
+ {"name": "mcp", "command": "tool", "args": ["serve"], "env": []},
37
+ ]}
38
+ parsed = SessionSetup.from_dict(payload)
39
+ payload["setup"]["mcpServers"][0]["args"].append("changed")
40
+ assert parsed.setup["mcpServers"][0]["args"] == ["serve"]
41
+
42
+
43
+ @pytest.mark.parametrize("payload", [None, {},
44
+ {"session_id": "session", "agent_id": "agent"},
45
+ {"session_id": "session", "agent_id": "agent", "setup": {}},
46
+ {"session_id": "session", "agent_id": "agent", "setup": []},
47
+ {"session_id": "session", "agent_id": "agent", "setup": {"cwd": "/saved", "mcpServers": [42]}},
48
+ {"session_id": "other", "agent_id": "agent", "setup": None},
49
+ {"session_id": "session", "agent_id": "other", "setup": None},
50
+ ])
51
+ def test_setup_helper_rejects_malformed_or_mismatched_response(payload):
52
+ http = MagicMock(spec=HTTPClient)
53
+ http.api_key = "test"
54
+ api = Deployments(http, api_base="https://example.com/agents")
55
+ api._get = MagicMock(return_value=payload)
56
+ with pytest.raises(ValueError):
57
+ api.get_session_setup("session", agent_id="agent")
58
+
59
+
60
+ @pytest.mark.parametrize("status", [401, 403, 404, 422, 500])
61
+ def test_setup_propagates_http_errors(monkeypatch, status):
62
+ def send(self, request, **kwargs):
63
+ return httpx.Response(status, json={"detail": "setup unavailable"}, request=request)
64
+
65
+ monkeypatch.setattr(httpx.Client, "send", send)
66
+ api = HyperCLI(api_key="caller-key", api_url="https://example.com").deployments
67
+ with pytest.raises(APIError) as caught:
68
+ api.get_session_setup("session", agent_id="agent")
69
+ assert caught.value.status_code == status
70
+
71
+
32
72
  @pytest.mark.parametrize("agent_state", ["live", "archived", "deleted", "future-state"])
33
73
  def test_detail_parses_computed_agent_state(agent_state):
34
74
  record = SessionRecord.from_dict({"id": "session", "agentState": agent_state})
File without changes
File without changes