compshare-cli 0.5.2__tar.gz → 0.5.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 (70) hide show
  1. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/CHANGELOG.md +15 -0
  2. {compshare_cli-0.5.2/src/compshare_cli.egg-info → compshare_cli-0.5.4}/PKG-INFO +1 -1
  3. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/connector/compshare/connector-meta.json +1 -1
  4. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/connector/compshare/mcp.json +1 -1
  5. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/connector/compshare/skills/compshare/SKILL.md +1 -1
  6. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/skills/compshare-cli/SKILL.md +3 -0
  7. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/__init__.py +1 -1
  8. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/actions.py +0 -1
  9. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/api.py +0 -7
  10. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/instance.py +72 -0
  11. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/i18n.py +7 -8
  12. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/mcp_server.py +1 -0
  13. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/output.py +4 -1
  14. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/sdk.py +46 -15
  15. {compshare_cli-0.5.2 → compshare_cli-0.5.4/src/compshare_cli.egg-info}/PKG-INFO +1 -1
  16. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_cli.py +180 -2
  17. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_config.py +4 -2
  18. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_mcp_server.py +1 -0
  19. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_output.py +13 -0
  20. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_remote_jobs.py +4 -0
  21. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_sdk.py +98 -0
  22. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_ssh.py +5 -1
  23. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_ssh_cache.py +12 -4
  24. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/LICENSE +0 -0
  25. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/MANIFEST.in +0 -0
  26. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/README.md +0 -0
  27. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/RELEASING.md +0 -0
  28. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/connector/compshare/icon.svg +0 -0
  29. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/connector/compshare/token-schema.json +0 -0
  30. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/pyproject.toml +0 -0
  31. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/setup.cfg +0 -0
  32. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/skills/compshare-cli/agents/openai.yaml +0 -0
  33. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/__main__.py +0 -0
  34. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/cli.py +0 -0
  35. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/__init__.py +0 -0
  36. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/bandwidth.py +0 -0
  37. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/common.py +0 -0
  38. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/doctor.py +0 -0
  39. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/feedback.py +0 -0
  40. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/image.py +0 -0
  41. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/minimax.py +0 -0
  42. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/storage.py +0 -0
  43. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/commands/team.py +0 -0
  44. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/config.py +0 -0
  45. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/errors.py +0 -0
  46. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/insights.py +0 -0
  47. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/instance_templates.py +0 -0
  48. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/location.py +0 -0
  49. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/parsing.py +0 -0
  50. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/remote_jobs.py +0 -0
  51. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/runtime.py +0 -0
  52. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/ssh.py +0 -0
  53. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli/ssh_cache.py +0 -0
  54. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli.egg-info/SOURCES.txt +0 -0
  55. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli.egg-info/dependency_links.txt +0 -0
  56. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli.egg-info/entry_points.txt +0 -0
  57. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli.egg-info/requires.txt +0 -0
  58. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/src/compshare_cli.egg-info/top_level.txt +0 -0
  59. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_actions.py +0 -0
  60. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_api.py +0 -0
  61. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_bandwidth.py +0 -0
  62. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_feedback.py +0 -0
  63. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_instance_templates.py +0 -0
  64. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_location.py +0 -0
  65. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_minimax.py +0 -0
  66. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_minimax_media.py +0 -0
  67. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_parsing.py +0 -0
  68. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_release_version.py +0 -0
  69. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_ssh_integration.py +0 -0
  70. {compshare_cli-0.5.2 → compshare_cli-0.5.4}/tests/test_workbuddy_connector.py +0 -0
@@ -2,6 +2,21 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.5.4
6
+
7
+ - 修复 Windows 下 PowerShell 5.1/7 使用 GBK 代码页时中文 JSON 乱码或无法解析的问题,保持 UTF-8
8
+ 输出和原有 JSON 数据结构。
9
+ - 适配 Windows 测试的平台条件,验证 DPAPI 凭证缓存加密,并完成监控、SSH、中文路径传输
10
+ 和持久化远程任务的真实 PowerShell 回归。
11
+ - Windows 经 SSH 会话嵌套调用 OpenSSH 仍可能挂起,独立 PowerShell 实测通过。
12
+
13
+ ## 0.5.3
14
+
15
+ - 恢复 `instance monitor`:自动定位实例地域并按最多 10 台分批查询,终端显示各设备最新
16
+ 使用率和采样时间,JSON 保留 CPU、内存、GPU 与磁盘的完整时间序列;同步开放 MCP 只读调用。
17
+ - 适配监控接口的原生 JSON 数组和数组拼接签名,修复 SDK 展开实例 ID 导致的参数错误,
18
+ 并移除“生产监控接口不可用”的旧提示。
19
+
5
20
  ## 0.5.2
6
21
 
7
22
  - 精简 README 快速开始,移除图片、语音和文件传输示例,以及 SSH 细节和使用统计说明。
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: compshare-cli
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Command-line client for CompShare GPU compute and MiniMax H3
5
5
  Author: CompShare
6
6
  License-Expression: Apache-2.0
@@ -8,7 +8,7 @@
8
8
  "source": "compshare",
9
9
  "type": "mcp",
10
10
  "auth_mode": "token",
11
- "version": "0.5.2",
11
+ "version": "0.5.4",
12
12
  "minWorkbuddyVersion": "5.0.0",
13
13
  "examples_zh": [
14
14
  "查询上海可用的 RTX 4090 GPU 规格、库存和价格",
@@ -7,7 +7,7 @@
7
7
  "--python",
8
8
  "3.11",
9
9
  "--from",
10
- "compshare-cli[mcp]==0.5.2",
10
+ "compshare-cli[mcp]==0.5.4",
11
11
  "compshare-mcp"
12
12
  ],
13
13
  "env": {
@@ -3,7 +3,7 @@ name: compshare
3
3
  description: Manage CompShare GPU cloud resources and MiniMax H3 media tasks through the controlled CompShare MCP bridge.
4
4
  description_zh: 通过受控 CompShare MCP 桥接查询和管理优云智算 GPU 云资源及 MiniMax H3 视频、图片和语音任务。
5
5
  description_en: Manage CompShare GPU cloud resources and MiniMax H3 media tasks through the controlled CompShare MCP bridge.
6
- version: "0.5.2"
6
+ version: "0.5.4"
7
7
  author: "CompShare"
8
8
  ---
9
9
 
@@ -141,6 +141,9 @@ compshare --json instance list --status Running --gpu 4090 --all
141
141
  compshare --json instance show INSTANCE_ID
142
142
  compshare --json instance show INSTANCE_ID --status --spec --billing
143
143
 
144
+ # Query monitoring metrics and time series; locations are resolved automatically
145
+ compshare --json instance monitor INSTANCE_1 INSTANCE_2
146
+
144
147
  # Batch lifecycle operations
145
148
  compshare --json instance start INSTANCE_1 INSTANCE_2 --timeout 600
146
149
  compshare --json instance stop INSTANCE_1 INSTANCE_2 --yes --timeout 600
@@ -1,3 +1,3 @@
1
1
  """CompShare command-line client."""
2
2
 
3
- __version__ = "0.5.2"
3
+ __version__ = "0.5.4"
@@ -113,7 +113,6 @@ UNAVAILABLE_ACTIONS = frozenset(
113
113
  {
114
114
  "AddFavoriteImage",
115
115
  "DescribeFavoriteImages",
116
- "GetCompShareInstanceMonitor",
117
116
  "GetSoftwareURL",
118
117
  "RemoveFavoriteImage",
119
118
  }
@@ -236,13 +236,6 @@ def error_hint(action: str, code: int) -> Optional[str]:
236
236
  hints = {
237
237
  ("DeleteCompshareDisk", 8434): "The disk is still detaching. Wait a moment and retry.",
238
238
  ("AttachUS3", 8433): "Confirm that US3 is enabled for the selected region and account.",
239
- ("GetCompShareInstanceMonitor", 210): (
240
- "This production endpoint currently rejects instance IDs; "
241
- "use the console for monitoring."
242
- ),
243
- ("GetCompShareInstanceMonitor", 230): (
244
- "This production endpoint is currently incompatible; use the console for monitoring."
245
- ),
246
239
  }
247
240
  return tr(hints[(action, code)]) if (action, code) in hints else None
248
241
 
@@ -107,6 +107,15 @@ JOB_COLUMNS = (
107
107
  ("CreatedTime", "CREATED"),
108
108
  )
109
109
 
110
+ MONITOR_METRIC_LABELS = {
111
+ "uhost_cpu_used": "CPU",
112
+ "cloudwatch_memory_usage": "MEMORY",
113
+ "cloudwatch_sys_disk_used_per": "SYSTEM DISK",
114
+ "cloudwatch_data_disk_used_per": "DATA DISKS",
115
+ "cloudwatch_gpu_memory_usage": "VRAM",
116
+ "cloudwatch_gpu_util": "GPU",
117
+ }
118
+
110
119
  INSTANCE_SHOW_SECTION_KEYS = {
111
120
  "ip": ("IPSet",),
112
121
  "softwares": ("Softwares",),
@@ -185,6 +194,27 @@ def _instance_rows(response: Dict[str, Any]) -> Iterable[Dict[str, Any]]:
185
194
  yield row
186
195
 
187
196
 
197
+ def _monitor_rows(response: Dict[str, Any]) -> Iterable[Dict[str, Any]]:
198
+ data = response.get("Data") or {}
199
+ for host in [*(data.get("List") or []), *(data.get("PodList") or [])]:
200
+ for metric in host.get("Metrics") or []:
201
+ metric_key = metric.get("MetricKey") or ""
202
+ for result in metric.get("Results") or [{}]:
203
+ latest = max(
204
+ result.get("Values") or [],
205
+ key=lambda point: point.get("Timestamp") or 0,
206
+ default={},
207
+ )
208
+ tags = result.get("TagMap") or {}
209
+ yield {
210
+ "UHostId": result.get("ResourceId") or host.get("UHostId") or host.get("PodId"),
211
+ "MetricKey": tr(MONITOR_METRIC_LABELS.get(metric_key, metric_key)),
212
+ "Value": latest.get("Value"),
213
+ "Timestamp": latest.get("Timestamp"),
214
+ "Device": tags.get("gpu_bus_id") or tags.get("mount") or tags.get("disk"),
215
+ }
216
+
217
+
188
218
  def _memory_display(value: Any) -> Any:
189
219
  return f"{value // 1024}GiB" if isinstance(value, int) else value
190
220
 
@@ -2186,6 +2216,48 @@ def refund(ctx: typer.Context, instances: List[str] = typer.Argument(...)) -> No
2186
2216
  )
2187
2217
 
2188
2218
 
2219
+ @app.command("monitor", help="Get instance monitoring data.")
2220
+ def monitor(
2221
+ ctx: typer.Context, instances: List[str] = typer.Argument(..., help="Instance IDs.")
2222
+ ) -> None:
2223
+ state = runtime(ctx)
2224
+ requested = list(dict.fromkeys(instances))
2225
+ locations, missing = _locate_instances(state, requested)
2226
+ if missing:
2227
+ raise UsageError(tr("Instance {instance} was not found.", instance=missing[0]))
2228
+ groups: Dict[Tuple[str, str], List[str]] = {}
2229
+ for identifier in requested:
2230
+ region, zone, _ = locations[identifier]
2231
+ groups.setdefault((region, zone), []).append(identifier)
2232
+ response: Dict[str, Any] = {"Data": {"List": [], "PodList": []}}
2233
+ for (region, zone), ids in groups.items():
2234
+ for offset in range(0, len(ids), 10):
2235
+ current = call(
2236
+ state,
2237
+ "GetCompShareInstanceMonitor",
2238
+ {"Region": region, "Zone": zone, "UHostIds": ids[offset : offset + 10]},
2239
+ )
2240
+ data = current.get("Data") or {}
2241
+ for key in ("List", "PodList"):
2242
+ response["Data"][key].extend(data.get(key) or [])
2243
+ rows = list(_monitor_rows(response))
2244
+ renderer = Renderer(state.json_output, state.show_sensitive)
2245
+ if not state.json_output and not rows:
2246
+ renderer.console.print(tr("No monitoring data returned for the selected instances."))
2247
+ return
2248
+ renderer.data(
2249
+ response,
2250
+ rows=rows,
2251
+ columns=(
2252
+ ("UHostId", "INSTANCE"),
2253
+ ("MetricKey", "METRIC"),
2254
+ ("Value", "VALUE (%)"),
2255
+ ("Timestamp", "TIME"),
2256
+ ("Device", "DEVICE"),
2257
+ ),
2258
+ )
2259
+
2260
+
2189
2261
  @app.command("charge", help="Change an instance billing type.")
2190
2262
  def charge(
2191
2263
  ctx: typer.Context,
@@ -359,8 +359,10 @@ ZH_TRANSLATIONS: Dict[str, str] = {
359
359
  "Query current instance pricing.": "查询实例当前计费价格。",
360
360
  "Query instance refund amounts.": "查询实例退款金额。",
361
361
  "Get instance monitoring data.": "获取实例监控数据。",
362
- "Get instance monitoring data (coming soon).": "获取实例监控数据(待上线)。",
363
- "Instance monitoring is coming soon.": "实例监控功能待上线。",
362
+ "Monitoring requires UHostIds to be an array of strings.": (
363
+ "监控请求的 UHostIds 必须为字符串数组。"
364
+ ),
365
+ "No monitoring data returned for the selected instances.": "所选实例暂无监控数据。",
364
366
  "Change an instance billing type.": "变更实例计费方式。",
365
367
  "Check network accelerator status.": "检查网络加速状态。",
366
368
  "List models in the model repository.": "列出模型仓库中的模型。",
@@ -681,6 +683,9 @@ ZH_TRANSLATIONS: Dict[str, str] = {
681
683
  "SOURCE": "来源",
682
684
  "VERSION": "版本",
683
685
  "TAGS": "标签",
686
+ "METRIC": "指标",
687
+ "VALUE (%)": "使用率(%)",
688
+ "TIME": "采样时间",
684
689
  "ACCOUNT ID": "账户 ID",
685
690
  "ACCOUNT": "账户",
686
691
  "DISK ID": "云盘 ID",
@@ -892,12 +897,6 @@ ZH_TRANSLATIONS: Dict[str, str] = {
892
897
  "Confirm that US3 is enabled for the selected region and account.": (
893
898
  "请确认所选地域和账户已开通 US3。"
894
899
  ),
895
- "This production endpoint currently rejects instance IDs; use the console for monitoring.": (
896
- "生产环境的该接口当前会拒绝实例 ID,请暂时在控制台查看监控。"
897
- ),
898
- "This production endpoint is currently incompatible; use the console for monitoring.": (
899
- "生产环境的该接口当前不兼容,请暂时在控制台查看监控。"
900
- ),
901
900
  "This production endpoint currently rejects its action; use instance show or the console.": (
902
901
  "生产环境的该接口当前拒绝请求,请使用 instance show 或控制台。"
903
902
  ),
@@ -23,6 +23,7 @@ _READ_COMMANDS = {
23
23
  ("instance", "families"),
24
24
  ("instance", "list"),
25
25
  ("instance", "show"),
26
+ ("instance", "monitor"),
26
27
  ("instance", "wait"),
27
28
  ("instance", "price"),
28
29
  ("instance", "resize-price"),
@@ -150,7 +150,10 @@ def _project_rows(
150
150
 
151
151
  def _write_json(payload: Dict[str, Any]) -> None:
152
152
  """Write one UTF-8 JSON document independently of the console code page."""
153
- document = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
153
+ # PowerShell can decode native pipes using a legacy Windows console code page.
154
+ document = (
155
+ json.dumps(payload, ensure_ascii=sys.platform == "win32", separators=(",", ":")) + "\n"
156
+ )
154
157
  stream = sys.stdout
155
158
  binary = getattr(stream, "buffer", None)
156
159
  if binary is not None:
@@ -5,9 +5,11 @@ from typing import Any, Dict, Optional, Tuple
5
5
 
6
6
  from ucloud.client import Client
7
7
  from ucloud.core import exc as ucloud_exc
8
- from ucloud.core.transport import SSLOption
8
+ from ucloud.core.transport import Response, SSLOption
9
9
 
10
10
  from compshare_cli.config import Profile
11
+ from compshare_cli.errors import UsageError
12
+ from compshare_cli.i18n import tr
11
13
 
12
14
 
13
15
  class CompShareSDK:
@@ -34,17 +36,40 @@ class CompShareSDK:
34
36
  self._service = Client(config, logger=logger).ucompshare()
35
37
 
36
38
  def invoke(self, action: str, params: Dict[str, Any]) -> Dict[str, Any]:
39
+ if action == "GetCompShareInstanceMonitor":
40
+ return self._json_response(action, self._send_request(action, params))
37
41
  return self._service.invoke(action, dict(params))
38
42
 
39
43
  def download(self, action: str, params: Dict[str, Any]) -> Tuple[bytes, Dict[str, str]]:
40
44
  """Invoke an authenticated action whose success response is a file stream."""
45
+ response = self._send_request(action, params)
46
+ if "json" in str(response.headers.get("Content-Type", "")).lower():
47
+ self._json_response(action, response)
48
+ return response.content, {str(key): str(value) for key, value in response.headers.items()}
49
+
50
+ def _send_request(self, action: str, params: Dict[str, Any]) -> Response:
41
51
  args = dict(params)
42
52
  args["Action"] = action
43
53
  for handler in self._service.middleware.request_handlers:
44
54
  args = handler(args)
55
+ monitoring = action == "GetCompShareInstanceMonitor"
56
+ instance_ids = args.get("UHostIds")
57
+ if monitoring and instance_ids is not None:
58
+ if not isinstance(instance_ids, list) or any(
59
+ not isinstance(identifier, str) for identifier in instance_ids
60
+ ):
61
+ raise UsageError(tr("Monitoring requires UHostIds to be an array of strings."))
62
+ # This endpoint signs native JSON arrays by concatenating their elements.
63
+ args["UHostIds"] = "".join(instance_ids)
45
64
  request = self._service._build_http_request(args)
65
+ if monitoring:
66
+ request.json = dict(request.data)
67
+ if instance_ids is not None:
68
+ request.json["UHostIds"] = list(instance_ids)
69
+ request.data = None
70
+ request.headers["Content-Type"] = "application/json"
46
71
  try:
47
- response = self._service.transport.send(
72
+ return self._service.transport.send(
48
73
  request,
49
74
  ssl_option=SSLOption(
50
75
  self._service.config.ssl_verify,
@@ -60,17 +85,23 @@ class CompShareSDK:
60
85
  handler(error)
61
86
  raise
62
87
 
63
- content_type = str(response.headers.get("Content-Type", "")).lower()
64
- if "json" in content_type:
88
+ def _json_response(self, action: str, response: Response) -> Dict[str, Any]:
89
+ try:
65
90
  data = response.json() or {}
66
- if int(data.get("RetCode", -1)) != 0:
67
- error = ucloud_exc.RetCodeException(
68
- action=action,
69
- code=int(data.get("RetCode", 0)),
70
- message=data.get("Message", ""),
71
- request_uuid=response.request_uuid,
72
- )
73
- for handler in self._service.middleware.exception_handlers:
74
- handler(error)
75
- raise error
76
- return response.content, {str(key): str(value) for key, value in response.headers.items()}
91
+ except Exception as error:
92
+ for handler in self._service.middleware.exception_handlers:
93
+ handler(error)
94
+ raise
95
+ for handler in self._service.middleware.response_handlers:
96
+ data = handler(data, response)
97
+ if int(data.get("RetCode", -1)) != 0:
98
+ error = ucloud_exc.RetCodeException(
99
+ action=action,
100
+ code=int(data.get("RetCode", 0)),
101
+ message=data.get("Message", ""),
102
+ request_uuid=response.request_uuid,
103
+ )
104
+ for handler in self._service.middleware.exception_handlers:
105
+ handler(error)
106
+ raise error
107
+ return data
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: compshare-cli
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Command-line client for CompShare GPU compute and MiniMax H3
5
5
  Author: CompShare
6
6
  License-Expression: Apache-2.0
@@ -1375,7 +1375,7 @@ def test_schedule_extend_requires_an_active_plan(monkeypatch, capsys) -> None:
1375
1375
  assert "schedule set" in _json_error(capsys.readouterr().out)["message"]
1376
1376
 
1377
1377
 
1378
- def test_unavailable_instance_commands_are_not_exposed() -> None:
1378
+ def test_monitor_and_focused_instance_commands_are_exposed() -> None:
1379
1379
  instance_help = runner.invoke(cli.app, ["instance", "--help"])
1380
1380
  software_help = runner.invoke(cli.app, ["instance", "software", "--help"])
1381
1381
  show_help = runner.invoke(cli.app, ["instance", "show", "--help"])
@@ -1383,7 +1383,7 @@ def test_unavailable_instance_commands_are_not_exposed() -> None:
1383
1383
  assert instance_help.exit_code == 0, instance_help.output
1384
1384
  assert software_help.exit_code == 0, software_help.output
1385
1385
  assert show_help.exit_code == 0, show_help.output
1386
- assert "monitor" not in instance_help.stdout
1386
+ assert "monitor" in instance_help.stdout
1387
1387
  assert "url" not in software_help.stdout
1388
1388
  for option in (
1389
1389
  "--ip",
@@ -1398,6 +1398,184 @@ def test_unavailable_instance_commands_are_not_exposed() -> None:
1398
1398
  assert "--connection" not in show_help.stdout
1399
1399
 
1400
1400
 
1401
+ def test_monitor_groups_locations_chunks_requests_and_preserves_series(monkeypatch) -> None:
1402
+ ids = [f"uhost-{index}" for index in range(13)]
1403
+ calls = []
1404
+ hosts = [
1405
+ {
1406
+ "UHostId": identifier,
1407
+ "Region": "cn-wlcb" if index < 11 else "cn-sh2",
1408
+ "Zone": "cn-wlcb-01" if index < 11 else "cn-sh2-02",
1409
+ }
1410
+ for index, identifier in enumerate(ids)
1411
+ ]
1412
+ monkeypatch.setattr(instance, "collect_pages", lambda *args, **kwargs: {"UHostSet": hosts})
1413
+
1414
+ def call(state, action, params):
1415
+ assert action == "GetCompShareInstanceMonitor"
1416
+ calls.append(params)
1417
+ return {
1418
+ "Data": {
1419
+ "List": [
1420
+ {
1421
+ "UHostId": identifier,
1422
+ "Metrics": [
1423
+ {
1424
+ "MetricKey": "uhost_cpu_used",
1425
+ "Results": [
1426
+ {
1427
+ "Values": [
1428
+ {"Timestamp": 100, "Value": 0},
1429
+ {"Timestamp": 99, "Value": 10},
1430
+ ]
1431
+ }
1432
+ ],
1433
+ }
1434
+ ],
1435
+ }
1436
+ for identifier in params["UHostIds"]
1437
+ ],
1438
+ "PodList": None,
1439
+ }
1440
+ }
1441
+
1442
+ monkeypatch.setattr(instance, "call", call)
1443
+ result = runner.invoke(cli.app, ["--json", "instance", "monitor", *ids, ids[0]])
1444
+
1445
+ assert result.exit_code == 0, result.output
1446
+ assert calls == [
1447
+ {"Region": "cn-wlcb", "Zone": "cn-wlcb-01", "UHostIds": ids[:10]},
1448
+ {"Region": "cn-wlcb", "Zone": "cn-wlcb-01", "UHostIds": ids[10:11]},
1449
+ {"Region": "cn-sh2", "Zone": "cn-sh2-02", "UHostIds": ids[11:]},
1450
+ ]
1451
+ data = _json_data(result.stdout)["Data"]
1452
+ assert [host["UHostId"] for host in data["List"]] == ids
1453
+ assert data["PodList"] == []
1454
+ assert data["List"][0]["Metrics"][0]["Results"][0]["Values"] == [
1455
+ {"Timestamp": 100, "Value": 0},
1456
+ {"Timestamp": 99, "Value": 10},
1457
+ ]
1458
+
1459
+
1460
+ def test_monitor_rows_keep_per_device_latest_samples_and_missing_values() -> None:
1461
+ response = {
1462
+ "Data": {
1463
+ "List": [
1464
+ {
1465
+ "UHostId": "uhost-1",
1466
+ "Metrics": [
1467
+ {
1468
+ "MetricKey": "cloudwatch_gpu_util",
1469
+ "Results": [
1470
+ {
1471
+ "TagMap": {"uuid": "long-id", "gpu_bus_id": "01:00.0"},
1472
+ "Values": [
1473
+ {"Timestamp": 200, "Value": 0},
1474
+ {"Timestamp": 100, "Value": 80},
1475
+ ],
1476
+ },
1477
+ {
1478
+ "TagMap": {"gpu_bus_id": "02:00.0"},
1479
+ "Values": [
1480
+ {"Timestamp": 100, "Value": 5},
1481
+ {"Timestamp": 200, "Value": 90},
1482
+ ],
1483
+ },
1484
+ ],
1485
+ },
1486
+ {"MetricKey": "cloudwatch_memory_usage", "Results": None},
1487
+ ],
1488
+ }
1489
+ ],
1490
+ "PodList": [
1491
+ {
1492
+ "PodId": "pod-1",
1493
+ "Metrics": [
1494
+ {
1495
+ "MetricKey": "uhost_cpu_used",
1496
+ "Results": [{"ResourceId": "pod-1", "Values": []}],
1497
+ }
1498
+ ],
1499
+ }
1500
+ ],
1501
+ }
1502
+ }
1503
+ rows = list(instance._monitor_rows(response))
1504
+
1505
+ assert [(row["UHostId"], row["Value"], row["Timestamp"]) for row in rows] == [
1506
+ ("uhost-1", 0, 200),
1507
+ ("uhost-1", 90, 200),
1508
+ ("uhost-1", None, None),
1509
+ ("pod-1", None, None),
1510
+ ]
1511
+ assert rows[0]["Device"] == "01:00.0"
1512
+ assert rows[1]["Device"] == "02:00.0"
1513
+
1514
+
1515
+ def test_monitor_human_output_distinguishes_metrics_and_devices(monkeypatch) -> None:
1516
+ monkeypatch.setattr(
1517
+ instance,
1518
+ "_locate_instances",
1519
+ lambda *args: ({"uhost-1": ("cn-wlcb", "cn-wlcb-01", {})}, []),
1520
+ )
1521
+ data = {
1522
+ "Data": {
1523
+ "List": [
1524
+ {
1525
+ "UHostId": "uhost-1",
1526
+ "Metrics": [
1527
+ {
1528
+ "MetricKey": key,
1529
+ "Results": [
1530
+ {
1531
+ "TagMap": {"gpu_bus_id": "01:00.0"},
1532
+ "Values": [{"Timestamp": 1791444759, "Value": 0}],
1533
+ }
1534
+ ],
1535
+ }
1536
+ for key in instance.MONITOR_METRIC_LABELS
1537
+ ],
1538
+ }
1539
+ ]
1540
+ }
1541
+ }
1542
+ monkeypatch.setattr(instance, "call", lambda *args: data)
1543
+ result = runner.invoke(cli.app, ["instance", "monitor", "uhost-1"])
1544
+
1545
+ assert result.exit_code == 0, result.output
1546
+ for label in ("CPU", "内存", "系统盘", "数据盘", "显存", "GPU", "01:00.0"):
1547
+ assert label in result.stdout
1548
+ assert "cloudwatch_" not in result.stdout
1549
+
1550
+
1551
+ @pytest.mark.parametrize("json_output", [False, True])
1552
+ def test_monitor_handles_empty_data(monkeypatch, json_output) -> None:
1553
+ monkeypatch.setattr(
1554
+ instance,
1555
+ "_locate_instances",
1556
+ lambda *args: ({"uhost-1": ("cn-wlcb", "cn-wlcb-01", {})}, []),
1557
+ )
1558
+ monkeypatch.setattr(instance, "call", lambda *args: {"Data": None})
1559
+ result = runner.invoke(
1560
+ cli.app, [*(["--json"] if json_output else []), "instance", "monitor", "uhost-1"]
1561
+ )
1562
+
1563
+ assert result.exit_code == 0, result.output
1564
+ if json_output:
1565
+ assert _json_data(result.stdout) == {"Data": {"List": [], "PodList": []}}
1566
+ else:
1567
+ assert "暂无监控数据" in result.stdout
1568
+
1569
+
1570
+ def test_monitor_rejects_missing_instances_before_querying(monkeypatch) -> None:
1571
+ monkeypatch.setattr(instance, "_locate_instances", lambda *args: ({}, ["uhost-missing"]))
1572
+ result = runner.invoke(cli.app, ["instance", "monitor", "uhost-missing"])
1573
+
1574
+ assert result.exit_code != 0
1575
+ assert isinstance(result.exception, UsageError)
1576
+ assert "uhost-missing" in str(result.exception)
1577
+
1578
+
1401
1579
  def test_instance_show_json_redacts_private_fields_unless_enabled(monkeypatch) -> None:
1402
1580
  host = {
1403
1581
  "UHostId": "uhost-1",
@@ -1,4 +1,5 @@
1
1
  import json
2
+ import os
2
3
  import stat
3
4
  from pathlib import Path
4
5
 
@@ -21,8 +22,9 @@ def test_profile_round_trip_and_file_permissions(monkeypatch, tmp_path) -> None:
21
22
  expected = Profile("public", "private")
22
23
  store.save_profile("testing", expected)
23
24
 
24
- assert stat.S_IMODE(path.stat().st_mode) == 0o600
25
- assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
25
+ if os.name != "nt":
26
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
27
+ assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
26
28
  assert store.load_profile("testing") == expected
27
29
  saved = json.loads(path.read_text(encoding="utf-8"))["profiles"]["testing"]
28
30
  assert set(saved) == {"public_key", "private_key"}
@@ -18,6 +18,7 @@ from compshare_cli.mcp_server import (
18
18
  "args",
19
19
  [
20
20
  ["instance", "list", "--all"],
21
+ ["instance", "monitor", "uhost-1"],
21
22
  ["team", "billing", "summary", "--team", "1"],
22
23
  ["instance", "create", "--dry-run"],
23
24
  ["instance", "resize", "uhost-1", "--dry-run"],
@@ -53,6 +53,19 @@ def test_json_renderer_writes_utf8_bytes_under_a_gbk_stdout(monkeypatch) -> None
53
53
  }
54
54
 
55
55
 
56
+ def test_windows_json_survives_legacy_powershell_pipe_decoding(monkeypatch) -> None:
57
+ raw = BytesIO()
58
+ monkeypatch.setattr(output.sys, "platform", "win32")
59
+ monkeypatch.setattr(output.sys, "stdout", TextIOWrapper(raw, encoding="gbk"))
60
+
61
+ Renderer(True).data({"value": "中文 😀"})
62
+
63
+ document = raw.getvalue()
64
+ assert document.isascii()
65
+ assert document.count(b"\n") == 1
66
+ assert json.loads(document.decode("gbk"))["data"]["value"] == "中文 😀"
67
+
68
+
56
69
  def test_json_renderer_reports_redacted_field_paths(capsys) -> None:
57
70
  Renderer(True).data({"Password": "secret", "IPSet": [{"IP": "203.0.113.1"}]})
58
71
 
@@ -91,6 +91,7 @@ def test_protocol_parser_and_normalizer() -> None:
91
91
  parse_records("COMPSHARE_JOB_UNSUPPORTED\n")
92
92
 
93
93
 
94
+ @pytest.mark.skipif(os.name == "nt", reason="requires a local POSIX shell")
94
95
  def test_relative_xdg_state_home_falls_back_to_home(tmp_path) -> None:
95
96
  environment = os.environ.copy()
96
97
  environment.update({"HOME": str(tmp_path), "XDG_STATE_HOME": "relative/state"})
@@ -106,6 +107,7 @@ def test_relative_xdg_state_home_falls_back_to_home(tmp_path) -> None:
106
107
  assert (tmp_path / ".local" / "state" / "compshare" / "jobs").is_dir()
107
108
 
108
109
 
110
+ @pytest.mark.skipif(os.name == "nt", reason="requires a local POSIX shell")
109
111
  def test_submit_show_and_read_logs_with_xdg_state_directory(tmp_path) -> None:
110
112
  bin_directory = tmp_path / "bin"
111
113
  bin_directory.mkdir()
@@ -166,6 +168,7 @@ def test_submit_show_and_read_logs_with_xdg_state_directory(tmp_path) -> None:
166
168
  assert [record["JobId"] for record in parse_records(listed.stdout)] == ["job-test"]
167
169
 
168
170
 
171
+ @pytest.mark.skipif(os.name == "nt", reason="requires a local POSIX shell")
169
172
  def test_submit_is_idempotent_for_the_same_job_id(tmp_path) -> None:
170
173
  job_directory = tmp_path / "state" / "compshare" / "jobs" / "job-existing"
171
174
  job_directory.mkdir(parents=True)
@@ -206,6 +209,7 @@ def test_submit_is_idempotent_for_the_same_job_id(tmp_path) -> None:
206
209
  parse_records(cwd_conflict.stdout)
207
210
 
208
211
 
212
+ @pytest.mark.skipif(os.name == "nt", reason="requires a local POSIX shell")
209
213
  def test_prune_removes_only_old_terminal_jobs(tmp_path) -> None:
210
214
  jobs_root = tmp_path / "state" / "compshare" / "jobs"
211
215
  old_job = jobs_root / "job-old"
@@ -1,6 +1,13 @@
1
+ import json
1
2
  import logging
3
+ from hashlib import sha1
4
+
5
+ import pytest
6
+ from ucloud.core import exc as ucloud_exc
7
+ from ucloud.core.transport import Response
2
8
 
3
9
  from compshare_cli.config import Profile
10
+ from compshare_cli.errors import UsageError
4
11
  from compshare_cli.sdk import CompShareSDK
5
12
 
6
13
 
@@ -68,6 +75,97 @@ def test_sdk_invoke_does_not_mutate_the_callers_params(monkeypatch) -> None:
68
75
  assert params == {"Region": "cn-wlcb"}
69
76
 
70
77
 
78
+ @pytest.mark.parametrize("ids", [["uhost-1"], ["uhost-2", "uhost-1"]])
79
+ def test_monitor_sends_native_json_arrays_with_concatenated_signature(monkeypatch, ids) -> None:
80
+ sdk = CompShareSDK(Profile("public", "private"), "cn-wlcb")
81
+ captured = {}
82
+ response = {"RetCode": 0, "Data": {"List": [], "PodList": []}}
83
+
84
+ def send(request, **options):
85
+ captured["request"] = request
86
+ captured["options"] = options
87
+ return Response(
88
+ url=request.url,
89
+ method=request.method,
90
+ content=json.dumps(response).encode(),
91
+ headers={"Content-Type": "application/json"},
92
+ )
93
+
94
+ monkeypatch.setattr(sdk._service.transport, "send", send)
95
+ params = {"Zone": "cn-wlcb-01", "UHostIds": ids}
96
+
97
+ assert sdk.invoke("GetCompShareInstanceMonitor", params) == response
98
+ assert params == {"Zone": "cn-wlcb-01", "UHostIds": ids}
99
+ request = captured["request"]
100
+ signing_text = (
101
+ "ActionGetCompShareInstanceMonitorPublicKeypublicRegioncn-wlcbUHostIds"
102
+ + "".join(ids)
103
+ + "Zonecn-wlcb-01private"
104
+ )
105
+ assert request.json == {
106
+ "Action": "GetCompShareInstanceMonitor",
107
+ "Region": "cn-wlcb",
108
+ "Zone": "cn-wlcb-01",
109
+ "UHostIds": ids,
110
+ "PublicKey": "public",
111
+ "Signature": sha1(signing_text.encode()).hexdigest(),
112
+ }
113
+ assert request.data is None
114
+ assert request.headers["Content-Type"] == "application/json"
115
+ assert captured["options"]["timeout"] == sdk._service.config.timeout
116
+
117
+
118
+ @pytest.mark.parametrize("code", [171, 210, 230])
119
+ def test_monitor_preserves_api_errors_and_request_ids(monkeypatch, code) -> None:
120
+ sdk = CompShareSDK(Profile("public", "private"), "cn-wlcb")
121
+ errors = []
122
+ sdk._service.middleware.exception(errors.append)
123
+ monkeypatch.setattr(
124
+ sdk._service.transport,
125
+ "send",
126
+ lambda *args, **kwargs: Response(
127
+ url="https://api.compshare.cn",
128
+ method="post",
129
+ content=json.dumps({"RetCode": code, "Message": "monitor failure"}).encode(),
130
+ headers={"Content-Type": "application/json", "X-UCLOUD-REQUEST-UUID": "request-1"},
131
+ ),
132
+ )
133
+
134
+ with pytest.raises(ucloud_exc.RetCodeException) as raised:
135
+ sdk.invoke("GetCompShareInstanceMonitor", {"UHostIds": ["uhost-1"]})
136
+
137
+ assert raised.value.action == "GetCompShareInstanceMonitor"
138
+ assert raised.value.code == code
139
+ assert raised.value.request_uuid == "request-1"
140
+ assert errors == [raised.value]
141
+
142
+
143
+ @pytest.mark.parametrize("ids", ["uhost-1", [1]])
144
+ def test_monitor_rejects_invalid_id_arrays(ids) -> None:
145
+ sdk = CompShareSDK(Profile("public", "private"), "cn-wlcb")
146
+
147
+ with pytest.raises(UsageError, match="UHostIds"):
148
+ sdk.invoke("GetCompShareInstanceMonitor", {"UHostIds": ids})
149
+
150
+
151
+ def test_monitor_preserves_transport_failures(monkeypatch) -> None:
152
+ sdk = CompShareSDK(Profile("public", "private"), "cn-wlcb")
153
+ errors = []
154
+ sdk._service.middleware.exception(errors.append)
155
+ failure = TimeoutError("monitor request timed out")
156
+
157
+ def send(*args, **kwargs):
158
+ raise failure
159
+
160
+ monkeypatch.setattr(sdk._service.transport, "send", send)
161
+
162
+ with pytest.raises(TimeoutError) as raised:
163
+ sdk.invoke("GetCompShareInstanceMonitor", {"UHostIds": ["uhost-1"]})
164
+
165
+ assert raised.value is failure
166
+ assert errors == [failure]
167
+
168
+
71
169
  def test_sdk_download_uses_authenticated_service_transport(monkeypatch) -> None:
72
170
  captured = {}
73
171
 
@@ -1,3 +1,4 @@
1
+ import os
1
2
  from pathlib import Path
2
3
  from types import SimpleNamespace
3
4
 
@@ -7,6 +8,7 @@ from compshare_cli import ssh
7
8
  from compshare_cli.errors import CLIError, UsageError
8
9
 
9
10
 
11
+ @pytest.mark.skipif(os.name == "nt", reason="pexpect requires POSIX")
10
12
  def test_connect_with_password_answers_split_prompt_once(monkeypatch) -> None:
11
13
  calls = []
12
14
  sent = []
@@ -68,6 +70,7 @@ def test_connect_with_password_answers_split_prompt_once(monkeypatch) -> None:
68
70
 
69
71
 
70
72
  def test_connect_with_password_requires_an_interactive_terminal(monkeypatch) -> None:
73
+ monkeypatch.setattr(ssh, "_is_windows", lambda: False)
71
74
  monkeypatch.setattr(ssh.sys, "stdin", SimpleNamespace(isatty=lambda: False))
72
75
 
73
76
  try:
@@ -382,7 +385,8 @@ def test_captured_password_authentication_cleans_up_on_failure(monkeypatch, runn
382
385
  password_file = Path(kwargs["env"][ssh._ASKPASS_PASSWORD_FILE_ENV])
383
386
  password_files.append(password_file)
384
387
  assert password_file.read_text() == "temporary-secret"
385
- assert password_file.stat().st_mode & 0o777 == 0o600
388
+ if os.name != "nt":
389
+ assert password_file.stat().st_mode & 0o777 == 0o600
386
390
  raise OSError("test process failure")
387
391
 
388
392
  monkeypatch.setattr(ssh.subprocess, "run", run)
@@ -1,4 +1,5 @@
1
1
  import json
2
+ import os
2
3
  import stat
3
4
 
4
5
  import pytest
@@ -28,9 +29,14 @@ def test_ssh_cache_round_trip_is_profile_scoped_and_permission_restricted(tmp_pa
28
29
  key: value for key, value in _host().items() if key != "Unrelated"
29
30
  }
30
31
  assert cache.get("beta", "uhost-1", ttl=60, now=150) is None
31
- assert stat.S_IMODE(path.stat().st_mode) == 0o600
32
+ if os.name != "nt":
33
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
32
34
  saved = json.loads(path.read_text(encoding="utf-8"))
33
- assert "Unrelated" not in next(iter(saved["entries"].values()))["host"]
35
+ saved_host = next(iter(saved["entries"].values()))["host"]
36
+ assert "Unrelated" not in saved_host
37
+ if os.name == "nt":
38
+ assert saved_host["Password"].startswith("dpapi:")
39
+ assert saved_host["Password"] != _host()["Password"]
34
40
 
35
41
 
36
42
  def test_ssh_cache_expires_and_can_be_deleted(tmp_path) -> None:
@@ -68,8 +74,9 @@ def test_non_utf8_cache_is_ignored(tmp_path) -> None:
68
74
 
69
75
  def test_cache_does_not_change_existing_parent_permissions(tmp_path) -> None:
70
76
  tmp_path.chmod(0o755)
77
+ permissions = stat.S_IMODE(tmp_path.stat().st_mode)
71
78
  SSHCredentialCache(tmp_path / "ssh-cache.json").put("default", "uhost-1", _host())
72
- assert stat.S_IMODE(tmp_path.stat().st_mode) == 0o755
79
+ assert stat.S_IMODE(tmp_path.stat().st_mode) == permissions
73
80
 
74
81
 
75
82
  @pytest.mark.parametrize("field", ["Region", "Zone", "SshLoginCommand", "Password"])
@@ -93,7 +100,8 @@ def test_failed_cache_write_keeps_previous_credentials_and_removes_temporary_fil
93
100
  ) -> None:
94
101
  cache = SSHCredentialCache(tmp_path / "private" / "ssh-cache.json")
95
102
  cache.put("default", "uhost-1", _host("old-password"), now=100)
96
- assert stat.S_IMODE(cache.path.parent.stat().st_mode) == 0o700
103
+ if os.name != "nt":
104
+ assert stat.S_IMODE(cache.path.parent.stat().st_mode) == 0o700
97
105
 
98
106
  def fail(*_):
99
107
  raise OSError("simulated replacement failure")
File without changes
File without changes
File without changes
File without changes