sophhub 0.4.8 → 0.4.9

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sophhub",
3
- "version": "0.4.8",
3
+ "version": "0.4.9",
4
4
  "description": "SophHub CLI - Manage and download AI Agent skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "share-skill",
3
+ "version": "1.0.0",
4
+ "types": [
5
+ "builtin"
6
+ ],
7
+ "displayName": "SKILL分享",
8
+ "description": "分享自己的skill给虾友",
9
+ "changelog": [
10
+ {
11
+ "changes": [
12
+ "初次提交"
13
+ ],
14
+ "date": "2026-05-05",
15
+ "version": "1.0.0"
16
+ }
17
+ ],
18
+ "createdAt": "2026-05-05",
19
+ "updatedAt": "2026-05-05"
20
+ }
@@ -0,0 +1,261 @@
1
+ ---
2
+ name: share-skill
3
+ description: 列出当前用户容器中实际安装的 Skill,按 openclaw skills list 返回的 source 字段分组,引导用户选择 Skill、选择虾友后直接发送 web 格式 Skill 分享卡片。Use when the user asks to share or introduce an installed Skill to a Sophclaw friend / 虾友.
4
+ ---
5
+
6
+ # 向虾友介绍 Skill
7
+
8
+ 用于把当前容器里实际安装的某个 Skill 按 web 前端一致的 Skill 分享卡片格式发送给虾友。必须按顺序执行:**选择 Skill → 选择虾友 → 直接发送**。
9
+
10
+ ## Processing Mode
11
+
12
+ **STRICT SERIAL PROCESSING ONLY** — 不并行发送;用户选定 Skill 和虾友后直接发送,不再追加确认步骤。
13
+
14
+ ## Prerequisites
15
+
16
+ - Python 3.10+、uv
17
+ - 本机存在有效 JWT:`/home/node/.openclaw/jwt.json`
18
+ - 能执行 `openclaw skills list --json`;如环境命令名不同,用脚本参数 `--skills-command` 指定
19
+ - 能执行 `openclaw skills info <name> --json`;如环境命令名不同,用脚本参数 `--skill-info-command-template` 指定
20
+ - 虾友接口与 DM 发送接口可访问,默认 API base URL:`https://yagent.sophnet.com/api`
21
+ - **所有脚本调用均使用 `uv run`**,不要直接用 `python`。
22
+
23
+ ## 脚本入口
24
+
25
+ `{baseDir}` 为本 Skill 根目录:
26
+
27
+ ```bash
28
+ uv run {baseDir}/scripts/share_skill_to_friend.py <command> [args...]
29
+ ```
30
+
31
+ 常用命令:
32
+
33
+ ```bash
34
+ uv run {baseDir}/scripts/share_skill_to_friend.py list-skills
35
+ uv run {baseDir}/scripts/share_skill_to_friend.py list-friends
36
+ uv run {baseDir}/scripts/share_skill_to_friend.py send --skill "<skill-name>" --friend-id <id> --friend-name "<name>"
37
+ ```
38
+
39
+ 脚本会优先解析 JSON;如果 OpenClaw 命令输出包含 banner/config warnings,会自动从噪声中提取 JSON;如果实际拿到的是 `openclaw skills list` 的表格输出,也会尽量解析表格中的 Skill 名称、描述、状态和 Source。展示标签直接使用返回的 `source` 字段。
40
+
41
+ ## Step 1:选择 Skill
42
+
43
+ 先执行:
44
+
45
+ ```bash
46
+ uv run {baseDir}/scripts/share_skill_to_friend.py list-skills
47
+ ```
48
+
49
+ 输出 JSON:
50
+
51
+ ```json
52
+ {
53
+ "skills": [
54
+ {
55
+ "index": 1,
56
+ "name": "image-classify",
57
+ "description": "照片分类器。通过人脸识别对照片进行分类、搜索和管理。",
58
+ "tag": "openclaw-workspace",
59
+ "status": "可用"
60
+ }
61
+ ],
62
+ "groups": [
63
+ { "tag": "openclaw-workspace", "collapsedByDefault": false, "count": 1, "skills": [] },
64
+ { "tag": "openclaw-managed", "collapsedByDefault": false, "count": 0, "skills": [] },
65
+ { "tag": "openclaw-bundled", "collapsedByDefault": true, "count": 0, "skills": [] }
66
+ ]
67
+ }
68
+ ```
69
+
70
+ 向用户展示时使用以下格式。若 `description` 不是中文,先改写成自然中文再展示:
71
+
72
+ ```text
73
+ 🧩 **请选择要介绍给虾友的 Skill**
74
+
75
+ 1️⃣ **<name>**
76
+ 📝 功能:<中文 description>
77
+
78
+ 2️⃣ **<name>**
79
+ 📝 功能:<中文 description>
80
+
81
+ ...
82
+
83
+ 📦 **其他内置 skill**(共 <count> 个,已折叠)
84
+ 包含 openclaw-bundled、agents-skills-personal 等来源的 skill
85
+
86
+ 💬 请回复 **序号** 或 **Skill 名称**。
87
+ ```
88
+
89
+ **展示规则:**
90
+
91
+ 1. `openclaw-workspace` 和 `openclaw-managed` 的 skill 直接列出,**不显示分组标题**
92
+ 2. `openclaw-bundled` 和 `agents-skills-personal` 归入"其他内置 skill"分组,默认折叠
93
+ 3. 其它 source 如出现,也归入"其他内置 skill"分组
94
+ 4. 标签(如 `[openclaw-workspace]`)**不显示**,保持界面简洁
95
+ 5. 排序:openclaw-workspace → openclaw-managed → 其他内置 skill
96
+
97
+ ## Step 2:选择虾友
98
+
99
+ 用户选定 Skill 后执行:
100
+
101
+ ```bash
102
+ uv run {baseDir}/scripts/share_skill_to_friend.py list-friends
103
+ ```
104
+
105
+ 输出 JSON:
106
+
107
+ ```json
108
+ {
109
+ "friends": [
110
+ {
111
+ "index": 1,
112
+ "friendId": 23725,
113
+ "displayName": "小李",
114
+ "levelName": "Sophclaw 虾友"
115
+ }
116
+ ]
117
+ }
118
+ ```
119
+
120
+ 只展示非官方客服的虾友,使用以下格式:
121
+
122
+ ```text
123
+ 🦞 **请选择要发送给哪位虾友**
124
+
125
+ 1️⃣ **<displayName>**
126
+ 🌟 <levelIcon> <levelName>
127
+
128
+ 2️⃣ **<displayName>**
129
+ 🌟 <levelIcon> <levelName>
130
+
131
+ 💬 请回复 **序号** 或 **虾友昵称/备注**。
132
+ ```
133
+
134
+ `displayName` 的生成规则:优先使用虾友备注名 `remark`,没有备注时使用昵称 `nickname`,都没有时显示「未命名虾友」。内部保留 `friendId` 供脚本调用,但**不要向用户展示虾友号**。如果昵称重复,只用列表序号区分,并可提示用户按序号选择。
135
+
136
+ ## Step 3:发送(含敏感信息确认)
137
+
138
+ 用户选定虾友后,发送自定义 Skill 前,脚本会先扫描 Skill 目录是否包含私钥、token、`.env`、凭据文件等秘钥相关敏感信息。
139
+
140
+ ### 敏感信息检测
141
+
142
+ 脚本会检测以下敏感信息:
143
+ - 敏感文件名:`.env`、`.env.local`、`credentials.json`、`id_rsa` 等
144
+ - 敏感文件后缀:`.pem`、`.key`、`.p12`、`.pfx` 等
145
+ - 敏感文件名关键词:`token`、`secret`、`password`、`credential`、`private_key` 等
146
+ - 文件内容:私钥块、AWS Access Key、GitHub Token、Slack Token、JWT 等
147
+
148
+ ### 发送流程
149
+
150
+ 首次发送(不带 `--allow-sensitive`):
151
+
152
+ ```bash
153
+ uv run {baseDir}/scripts/share_skill_to_friend.py send \
154
+ --skill "<skill-name>" \
155
+ --friend-id <friendId> \
156
+ --friend-name "<display-name>" \
157
+ --description-zh "<中文功能介绍>"
158
+ ```
159
+
160
+ 如果检测到敏感信息,脚本会返回错误:
161
+
162
+ ```json
163
+ {
164
+ "error": "检测到要分享的 Skill 目录中可能包含秘钥相关敏感信息。\n命中项:\n- resources/bearer_token.txt: 文件名包含敏感关键词: token\n\n如需继续发送,请添加 --allow-sensitive 参数确认。"
165
+ }
166
+ ```
167
+
168
+ **此时 Agent 应向用户展示敏感信息列表,询问是否确认发送:**
169
+
170
+ ```text
171
+ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━
172
+
173
+ 🚨 **安全警告:检测到敏感信息**
174
+
175
+ 该 Skill 包含以下敏感内容,分享后接收方将获得完整访问权限:
176
+
177
+ | 文件路径 | 检测原因 |
178
+ |----------------------------------|------------------------------|
179
+ | `resources/bearer_token.txt` | 文件名包含敏感关键词: token |
180
+ | `scripts/send_email.py` | 疑似秘钥字段赋值 |
181
+
182
+ ⚠️ **风险提示**
183
+ • 接收方将获得这些敏感文件的完整内容
184
+ • 可能导致凭据泄露、API 被滥用等安全风险
185
+ • 建议仅在确认接收方完全可信的情况下发送
186
+
187
+ 💬 请回复 **「确认发送」** 继续发送,或回复 **「取消」** 返回。
188
+
189
+ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━
190
+ ```
191
+
192
+ **注意:** 表格使用标准 Markdown 格式 `| 列1 | 列2 |`,便于阅读和对齐。
193
+
194
+ 用户确认后,使用 `--allow-sensitive` 参数重新发送:
195
+
196
+ ```bash
197
+ uv run {baseDir}/scripts/share_skill_to_friend.py send \
198
+ --skill "<skill-name>" \
199
+ --friend-id <friendId> \
200
+ --friend-name "<display-name>" \
201
+ --description-zh "<中文功能介绍>" \
202
+ --allow-sensitive
203
+ ```
204
+
205
+ ### 发送结果
206
+
207
+ 发送成功后返回:
208
+
209
+ ```json
210
+ {
211
+ "success": true,
212
+ "skill": "operations-dashboard",
213
+ "friend": { "friendId": 34200, "displayName": "黄志举" },
214
+ "messageId": "<message-id>",
215
+ "message": "📝 功能介绍:...\n[claw-skill-share]\n{\"v\":1,...}\n[/claw-skill-share]"
216
+ }
217
+ ```
218
+
219
+ Agent 应向用户提示:
220
+
221
+ ```text
222
+ ✅已发送 `operations-dashboard` skill 给虾友「黄志举」
223
+ ```
224
+
225
+ 如果包含敏感信息,返回结果会额外包含 `sensitiveFindings` 和 `sensitiveWarning` 字段:
226
+
227
+ ```json
228
+ {
229
+ "success": true,
230
+ "skill": "operations-dashboard",
231
+ "friend": { "friendId": 34200, "displayName": "黄志举" },
232
+ "messageId": "<message-id>",
233
+ "sensitiveFindings": [
234
+ { "path": "resources/bearer_token.txt", "reason": "文件名包含敏感关键词: token" }
235
+ ],
236
+ "sensitiveWarning": "已发送包含敏感信息的 Skill,请确认接收方可信"
237
+ }
238
+ ```
239
+
240
+ 如果包含敏感信息,Agent 应在成功提示中提醒用户:
241
+
242
+ ```text
243
+ ✅已发送 `operations-dashboard` skill 给虾友「黄志举」
244
+
245
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
246
+ ⚠️ **安全提醒**
247
+ 该 Skill 已包含敏感文件一并发送给接收方:
248
+ • `resources/bearer_token.txt`
249
+
250
+ 请确认接收方可信,必要时建议轮换相关凭据。
251
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
252
+ ```
253
+
254
+ ## Safety
255
+
256
+ - 发送消息必须使用 web 前端一致的 `[claw-skill-share]` 卡片格式。
257
+ - 用户侧输出不展示内部 JSON、`packageUrl`、本地文件路径、密钥或环境变量值。
258
+ - 分享自定义 Skill 前会扫描敏感信息;命中时必须让用户确认后才可发送。
259
+ - 敏感信息检测到的文件路径和原因可向用户展示,但**不要展示文件内容或密钥值**。
260
+ - 不要替用户猜测虾友;必须让用户从列表中选择,或在用户主动提供时内部使用 `friendId`。
261
+ - 用户侧输出中不要展示虾友号 / `friendId`。
@@ -0,0 +1,1031 @@
1
+ #!/usr/bin/env python3
2
+ """List installed skills, list Sophclaw friends, preview and send a skill intro DM."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import base64
8
+ import hashlib
9
+ import io
10
+ import json
11
+ import os
12
+ import re
13
+ import shlex
14
+ import subprocess
15
+ import sys
16
+ import tarfile
17
+ import time
18
+ import urllib.error
19
+ import urllib.parse
20
+ import urllib.request
21
+ import uuid
22
+ from pathlib import Path, PurePosixPath
23
+ from typing import Any, Dict, Iterable, List, Optional, Pattern, Set, Tuple
24
+
25
+
26
+ DEFAULT_BASE_URL = "https://yagent.sophnet.com/api"
27
+ DEFAULT_TIMEOUT = 30
28
+ JWT_PATH = "/home/node/.openclaw/jwt.json"
29
+ DEFAULT_SKILLS_COMMAND = "openclaw skills list --json"
30
+ DEFAULT_SKILL_INFO_COMMAND_TEMPLATE = "openclaw skills info {skill} --json"
31
+ STORE_SKILLS_PATH = "/open-apis/skill-store/skills"
32
+ MAX_CUSTOM_SKILL_PACK_BYTES = 1024 * 1024
33
+ SKILL_SHARE_OPEN = "[claw-skill-share]"
34
+ SKILL_SHARE_CLOSE = "[/claw-skill-share]"
35
+ MAX_SENSITIVE_SCAN_BYTES = 512 * 1024
36
+ MAX_SENSITIVE_FINDINGS = 20
37
+ SENSITIVE_DIR_NAMES = {
38
+ ".git",
39
+ ".hg",
40
+ ".svn",
41
+ "__pycache__",
42
+ "node_modules",
43
+ ".venv",
44
+ "venv",
45
+ "dist",
46
+ "build",
47
+ }
48
+ SENSITIVE_FILE_NAMES = {
49
+ ".env",
50
+ ".env.local",
51
+ ".env.production",
52
+ ".npmrc",
53
+ ".pypirc",
54
+ "credentials.json",
55
+ "service-account.json",
56
+ "id_rsa",
57
+ "id_dsa",
58
+ "id_ecdsa",
59
+ "id_ed25519",
60
+ }
61
+ # 额外的敏感文件名模式(包含这些关键词的文件名)
62
+ SENSITIVE_FILE_NAME_PATTERNS = (
63
+ "token",
64
+ "secret",
65
+ "password",
66
+ "passwd",
67
+ "credential",
68
+ "private_key",
69
+ "privatekey",
70
+ "access_key",
71
+ "apikey",
72
+ "api_key",
73
+ )
74
+ SENSITIVE_FILE_SUFFIXES = (".pem", ".key", ".p12", ".pfx")
75
+ JsonDict = Dict[str, Any]
76
+ StringDict = Dict[str, str]
77
+
78
+
79
+ SENSITIVE_CONTENT_PATTERNS: Tuple[Tuple[Pattern[str], str], ...] = (
80
+ (
81
+ re.compile(r"-----BEGIN (?:RSA |DSA |EC |OPENSSH |)?PRIVATE KEY-----"),
82
+ "包含私钥块",
83
+ ),
84
+ (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "疑似 AWS Access Key"),
85
+ (re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{30,}\b"), "疑似 GitHub Token"),
86
+ (re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b"), "疑似 Slack Token"),
87
+ (re.compile(r"\bsk-[A-Za-z0-9]{32,}\b"), "疑似 API Key"),
88
+ (
89
+ re.compile(
90
+ r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"
91
+ r"\.[A-Za-z0-9_-]{10,}\b"
92
+ ),
93
+ "疑似 JWT",
94
+ ),
95
+ (
96
+ re.compile(
97
+ r"(?i)\b(?:api[_-]?key|secret(?:[_-]?key)?|access[_-]?token|auth[_-]?token|"
98
+ r"bearer[_-]?token|client[_-]?secret|private[_-]?key|password|passwd|pwd)\b"
99
+ r"\s*[:=]\s*['\"]?[A-Za-z0-9_./+=:@-]{16,}"
100
+ ),
101
+ "疑似秘钥字段赋值",
102
+ ),
103
+ )
104
+
105
+
106
+ class AppError(RuntimeError):
107
+ pass
108
+
109
+
110
+ def configure_stdio() -> None:
111
+ for name in ("stdout", "stderr"):
112
+ stream = getattr(sys, name, None)
113
+ if stream is not None and hasattr(stream, "reconfigure"):
114
+ stream.reconfigure(encoding="utf-8", errors="replace")
115
+
116
+
117
+ def print_json(payload: JsonDict) -> None:
118
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
119
+
120
+
121
+ def normalize_base_url(url: str) -> str:
122
+ value = (url or "").strip().rstrip("/")
123
+ if not value:
124
+ raise AppError("base-url 不能为空")
125
+ if not value.startswith(("http://", "https://")):
126
+ raise AppError("base-url 必须以 http:// 或 https:// 开头")
127
+ return value
128
+
129
+
130
+ def read_bearer_token(jwt_path: str) -> str:
131
+ try:
132
+ with open(jwt_path, "r", encoding="utf-8") as fp:
133
+ data = json.load(fp)
134
+ except OSError as exc:
135
+ raise AppError(f"无法读取 JWT 文件 {jwt_path}: {exc}") from exc
136
+ except json.JSONDecodeError as exc:
137
+ raise AppError(f"JWT 文件不是有效 JSON: {jwt_path}: {exc}") from exc
138
+
139
+ token = data.get("web_jwt") if isinstance(data, dict) else None
140
+ if not isinstance(token, str) or not token.strip():
141
+ raise AppError(f"JWT 文件缺少有效 web_jwt 字段: {jwt_path}")
142
+ token = token.strip()
143
+ if token.lower().startswith("bearer "):
144
+ token = token[7:].strip()
145
+ return token
146
+
147
+
148
+ def jwt_exp_unix(token: str) -> Optional[int]:
149
+ try:
150
+ parts = token.split(".")
151
+ if len(parts) != 3:
152
+ return None
153
+ payload = parts[1] + "=" * (-len(parts[1]) % 4)
154
+ raw = base64.urlsafe_b64decode(payload.encode("ascii"))
155
+ data = json.loads(raw)
156
+ exp = data.get("exp")
157
+ return int(exp) if isinstance(exp, (int, float)) else None
158
+ except Exception:
159
+ return None
160
+
161
+
162
+ def ensure_jwt_valid_for_use(
163
+ token: str,
164
+ jwt_path: str,
165
+ clock_skew_sec: int = 60,
166
+ ) -> None:
167
+ exp = jwt_exp_unix(token)
168
+ if exp is None:
169
+ return
170
+ now = int(time.time())
171
+ if now >= exp + clock_skew_sec:
172
+ raise AppError(f"JWT 已过期,请重新登录后刷新 {jwt_path}")
173
+
174
+
175
+ def make_headers(token: str, content_type: Optional[str] = None) -> StringDict:
176
+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
177
+ if content_type:
178
+ headers["Content-Type"] = content_type
179
+ return headers
180
+
181
+
182
+ def http_error_hint(http_code: int, body: str) -> str:
183
+ if http_code == 401:
184
+ return f"(请检查或刷新 {JWT_PATH} 中的 web_jwt)"
185
+ try:
186
+ data = json.loads(body)
187
+ except json.JSONDecodeError:
188
+ return ""
189
+ msg = str(data.get("message", ""))
190
+ status = data.get("status")
191
+ if status == 20002 or "权限不足" in msg:
192
+ return "(当前账号可能没有权限向该会话发送消息)"
193
+ return ""
194
+
195
+
196
+ def request_json(
197
+ method: str,
198
+ url: str,
199
+ token: Optional[str],
200
+ timeout: int,
201
+ payload: Optional[JsonDict] = None,
202
+ ) -> JsonDict:
203
+ body = None
204
+ headers: StringDict = {"Accept": "application/json"}
205
+ if token:
206
+ headers.update(make_headers(token))
207
+ if payload is not None:
208
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
209
+ headers["Content-Type"] = "application/json"
210
+ req = urllib.request.Request(url=url, data=body, headers=headers, method=method)
211
+ try:
212
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
213
+ raw = resp.read().decode("utf-8", errors="replace")
214
+ except urllib.error.HTTPError as exc:
215
+ err_body = exc.read().decode("utf-8", errors="replace")
216
+ hint = http_error_hint(exc.code, err_body)
217
+ raise AppError(f"HTTP {exc.code} {url}: {err_body}{hint}") from exc
218
+ except urllib.error.URLError as exc:
219
+ raise AppError(f"请求失败 {url}: {exc}") from exc
220
+
221
+ try:
222
+ data = json.loads(raw)
223
+ except json.JSONDecodeError as exc:
224
+ raise AppError(f"接口返回不是有效 JSON: {url}: {exc}\n{raw}") from exc
225
+ if isinstance(data, dict) and data.get("status") not in (None, 0):
226
+ status = data.get("status")
227
+ message = data.get("message")
228
+ raise AppError(f"接口错误: status={status} message={message!r}")
229
+ return data if isinstance(data, dict) else {"result": data}
230
+
231
+
232
+ def unwrap_result(data: JsonDict) -> Any:
233
+ return data.get("result") if "result" in data else data
234
+
235
+
236
+ def extract_json_object(text: str) -> Optional[JsonDict]:
237
+ """Extract the first complete JSON object from noisy CLI output."""
238
+ for start, ch in enumerate(text):
239
+ if ch != "{":
240
+ continue
241
+ depth = 0
242
+ in_string = False
243
+ escaped = False
244
+ for idx in range(start, len(text)):
245
+ c = text[idx]
246
+ if in_string:
247
+ if escaped:
248
+ escaped = False
249
+ elif c == "\\":
250
+ escaped = True
251
+ elif c == '"':
252
+ in_string = False
253
+ continue
254
+ if c == '"':
255
+ in_string = True
256
+ elif c == "{":
257
+ depth += 1
258
+ elif c == "}":
259
+ depth -= 1
260
+ if depth == 0:
261
+ candidate = text[start:idx + 1]
262
+ try:
263
+ data = json.loads(candidate)
264
+ except json.JSONDecodeError:
265
+ break
266
+ return data if isinstance(data, dict) else None
267
+ return None
268
+
269
+
270
+ def strip_ansi(text: str) -> str:
271
+ out: List[str] = []
272
+ i = 0
273
+ while i < len(text):
274
+ if text[i] == "\x1b" and i + 1 < len(text) and text[i + 1] == "[":
275
+ i += 2
276
+ while i < len(text) and not text[i].isalpha():
277
+ i += 1
278
+ i += 1
279
+ continue
280
+ out.append(text[i])
281
+ i += 1
282
+ return "".join(out)
283
+
284
+
285
+ def parse_plain_skills_table(text: str) -> JsonDict:
286
+ """Best-effort parser for `openclaw skills list` table output."""
287
+ skills: List[JsonDict] = []
288
+ current: Optional[JsonDict] = None
289
+ for raw_line in strip_ansi(text).splitlines():
290
+ line = raw_line.rstrip()
291
+ if not line.startswith("│") or line.startswith("│ Status"):
292
+ continue
293
+ parts = [part.strip() for part in line.strip("│").split("│")]
294
+ if len(parts) < 4:
295
+ continue
296
+ status_cell, skill_cell, desc_cell, source_cell = parts[:4]
297
+ border_chars = {"─", "┬", "┴", "┼", " "}
298
+ if set(status_cell + skill_cell + desc_cell + source_cell) <= border_chars:
299
+ continue
300
+ if status_cell or skill_cell or source_cell:
301
+ if skill_cell:
302
+ tokens = skill_cell.split()
303
+ if tokens and not any(ch.isalnum() for ch in tokens[0]):
304
+ tokens = tokens[1:]
305
+ name = " ".join(tokens).strip()
306
+ else:
307
+ name = ""
308
+ if not name:
309
+ continue
310
+ current = {
311
+ "name": name,
312
+ "skillKey": name,
313
+ "description": desc_cell,
314
+ "source": source_cell,
315
+ "eligible": "ready" in status_cell,
316
+ "disabled": "disabled" in status_cell,
317
+ "blockedByAllowlist": "blocked" in status_cell,
318
+ }
319
+ skills.append(current)
320
+ elif current and desc_cell:
321
+ previous_desc = str(current.get("description") or "")
322
+ current["description"] = f"{previous_desc} {desc_cell}".strip()
323
+ if not skills:
324
+ raise AppError("无法从 openclaw skills list 表格输出中解析 Skill")
325
+ return {"skills": skills}
326
+
327
+
328
+ def run_json_command(parts: List[str], timeout: int, label: str) -> JsonDict:
329
+ if not parts:
330
+ raise AppError(f"{label} 命令不能为空")
331
+ try:
332
+ proc = subprocess.run(parts, capture_output=True, text=True, timeout=timeout)
333
+ except FileNotFoundError as exc:
334
+ raise AppError(f"找不到命令: {parts[0]},可用参数指定") from exc
335
+ except subprocess.TimeoutExpired as exc:
336
+ raise AppError(f"{label} 超时: {' '.join(parts)}") from exc
337
+ if proc.returncode != 0:
338
+ detail = (proc.stderr or proc.stdout or "").strip()
339
+ raise AppError(f"{label} 失败: {detail or f'exit {proc.returncode}'}")
340
+ # Some CLI tools output JSON to stderr (e.g., openclaw with config warnings)
341
+ raw_output = proc.stdout or ""
342
+ if not raw_output.strip():
343
+ raw_output = proc.stderr or ""
344
+ try:
345
+ data = json.loads(raw_output)
346
+ except json.JSONDecodeError as exc:
347
+ data = extract_json_object(raw_output)
348
+ if data is None:
349
+ if label == "列出 Skill":
350
+ return parse_plain_skills_table(raw_output)
351
+ raise AppError(f"{label} 输出不是有效 JSON: {exc}\n{raw_output[:1000]}") from exc
352
+ if not isinstance(data, dict):
353
+ raise AppError(f"{label} JSON 根节点应为对象")
354
+ return data
355
+
356
+
357
+ def run_skills_list(command: str, timeout: int) -> JsonDict:
358
+ parts = shlex.split(command)
359
+ return run_json_command(parts, timeout, "列出 Skill")
360
+
361
+
362
+ def run_skill_info(args: argparse.Namespace, skill_name: str) -> JsonDict:
363
+ safe_skill = shlex.quote(skill_name)
364
+ command = args.skill_info_command_template.replace("{skill}", safe_skill)
365
+ return run_json_command(shlex.split(command), args.timeout, "读取 Skill 详情")
366
+
367
+
368
+ def normalize_skill(raw: JsonDict) -> JsonDict:
369
+ name = str(raw.get("name") or raw.get("skillKey") or "").strip()
370
+ skill_key = str(raw.get("skillKey") or name).strip()
371
+ return {
372
+ "name": name,
373
+ "skillKey": skill_key,
374
+ "description": str(raw.get("description") or "").strip(),
375
+ "emoji": raw.get("emoji"),
376
+ "source": str(raw.get("source") or "").strip(),
377
+ "bundled": bool(raw.get("bundled")),
378
+ "baseDir": str(raw.get("baseDir") or "").strip(),
379
+ "filePath": str(raw.get("filePath") or "").strip(),
380
+ "eligible": bool(raw.get("eligible")),
381
+ "disabled": bool(raw.get("disabled")),
382
+ "blockedByAllowlist": bool(raw.get("blockedByAllowlist")),
383
+ "requirements": (
384
+ raw.get("requirements") if isinstance(raw.get("requirements"), dict) else {}
385
+ ),
386
+ "missing": raw.get("missing") if isinstance(raw.get("missing"), dict) else {},
387
+ "homepage": raw.get("homepage"),
388
+ }
389
+
390
+
391
+ def status_label(skill: JsonDict) -> str:
392
+ if skill.get("disabled") or skill.get("blockedByAllowlist"):
393
+ return "已禁用"
394
+ if not skill.get("eligible"):
395
+ return "不可用"
396
+ return "可用"
397
+
398
+
399
+ def fetch_store_catalog(base_url: str, timeout: int) -> Tuple[Set[str], StringDict]:
400
+ ids: Set[str] = set()
401
+ name_to_id: StringDict = {}
402
+ page = 1
403
+ size = 100
404
+ while page <= 20:
405
+ query = urllib.parse.urlencode({"page": page, "size": size})
406
+ url = f"{base_url}{STORE_SKILLS_PATH}?{query}"
407
+ try:
408
+ data = request_json("GET", url, None, timeout)
409
+ except AppError:
410
+ break
411
+ result = unwrap_result(data) or {}
412
+ items = result.get("list") if isinstance(result, dict) else None
413
+ if not isinstance(items, list) or not items:
414
+ break
415
+ for item in items:
416
+ if not isinstance(item, dict):
417
+ continue
418
+ item_id = str(item.get("id") or "").strip().lower()
419
+ item_name = str(item.get("name") or "").strip().lower()
420
+ if item_id:
421
+ ids.add(item_id)
422
+ if item_id and item_name:
423
+ name_to_id[item_name] = item_id
424
+ total = result.get("total") if isinstance(result, dict) else 0
425
+ if len(items) < size or (isinstance(total, int) and page * size >= total):
426
+ break
427
+ page += 1
428
+ return ids, name_to_id
429
+
430
+
431
+ def resolve_store_slug(
432
+ skill: JsonDict,
433
+ store_ids: Set[str],
434
+ store_name_to_id: StringDict,
435
+ ) -> str:
436
+ source = str(skill.get("source") or "")
437
+ key = str(skill.get("skillKey") or "").strip().lower()
438
+ name = str(skill.get("name") or "").strip().lower()
439
+ if source != "openclaw-managed":
440
+ return ""
441
+ if key and key in store_ids:
442
+ return key
443
+ return store_name_to_id.get(name, "")
444
+
445
+
446
+ def classify_tag(
447
+ skill: JsonDict,
448
+ store_ids: Set[str],
449
+ store_name_to_id: StringDict,
450
+ ) -> str:
451
+ source = str(skill.get("source") or "")
452
+ return source or "unknown"
453
+
454
+
455
+ def tag_order(tag: str) -> int:
456
+ return {
457
+ "openclaw-workspace": 0,
458
+ "openclaw-managed": 1,
459
+ "openclaw-bundled": 2,
460
+ }.get(tag, 9)
461
+
462
+
463
+ def load_skills(args: argparse.Namespace) -> List[JsonDict]:
464
+ data = run_skills_list(args.skills_command, args.timeout)
465
+ raw_skills = data.get("skills")
466
+ if not isinstance(raw_skills, list):
467
+ raise AppError("skills list JSON 缺少 skills 数组")
468
+ store_ids, store_name_to_id = fetch_store_catalog(
469
+ normalize_base_url(args.base_url),
470
+ args.timeout,
471
+ )
472
+ out: List[JsonDict] = []
473
+ for raw in raw_skills:
474
+ if not isinstance(raw, dict):
475
+ continue
476
+ skill = normalize_skill(raw)
477
+ if not skill["name"]:
478
+ continue
479
+ skill["storeSlug"] = resolve_store_slug(skill, store_ids, store_name_to_id)
480
+ skill["tag"] = classify_tag(skill, store_ids, store_name_to_id)
481
+ skill["status"] = status_label(skill)
482
+ out.append(skill)
483
+ out.sort(key=lambda s: (tag_order(str(s["tag"])), str(s["name"]).lower()))
484
+ for idx, skill in enumerate(out, start=1):
485
+ skill["index"] = idx
486
+ return out
487
+
488
+
489
+ def build_skill_groups(skills: List[JsonDict]) -> List[JsonDict]:
490
+ groups: List[JsonDict] = []
491
+ tags = sorted(
492
+ {str(skill.get("tag") or "unknown") for skill in skills},
493
+ key=lambda tag: (tag_order(tag), tag),
494
+ )
495
+ for tag in tags:
496
+ items = [skill for skill in skills if skill.get("tag") == tag]
497
+ groups.append({
498
+ "tag": tag,
499
+ "collapsedByDefault": tag == "openclaw-bundled",
500
+ "count": len(items),
501
+ "skills": items,
502
+ })
503
+ return groups
504
+
505
+
506
+ def find_skill(args: argparse.Namespace, selector: str) -> JsonDict:
507
+ skills = load_skills(args)
508
+ raw = str(selector or "").strip()
509
+ if not raw:
510
+ raise AppError("缺少 skill")
511
+ if raw.isdigit():
512
+ idx = int(raw)
513
+ for skill in skills:
514
+ if skill["index"] == idx:
515
+ return skill
516
+ needle = raw.lower()
517
+ matches = [
518
+ s
519
+ for s in skills
520
+ if (
521
+ str(s["name"]).lower() == needle
522
+ or str(s.get("skillKey", "")).lower() == needle
523
+ )
524
+ ]
525
+ if len(matches) == 1:
526
+ return matches[0]
527
+ fuzzy = [
528
+ s
529
+ for s in skills
530
+ if (
531
+ needle in str(s["name"]).lower()
532
+ or needle in str(s.get("skillKey", "")).lower()
533
+ )
534
+ ]
535
+ if len(fuzzy) == 1:
536
+ return fuzzy[0]
537
+ if not matches and not fuzzy:
538
+ raise AppError(f"未找到 Skill: {selector}")
539
+ raise AppError(f"Skill 选择不唯一: {selector}")
540
+
541
+
542
+ def merge_skill_detail(args: argparse.Namespace, skill: JsonDict) -> JsonDict:
543
+ try:
544
+ detail = normalize_skill(run_skill_info(args, str(skill["name"])))
545
+ except AppError:
546
+ return skill
547
+ merged = {**skill}
548
+ for key, value in detail.items():
549
+ if value not in ("", None, {}, []):
550
+ merged[key] = value
551
+ merged["tag"] = skill.get("tag")
552
+ merged["storeSlug"] = skill.get("storeSlug", "")
553
+ merged["status"] = status_label(merged)
554
+ return merged
555
+
556
+
557
+ def load_friends(args: argparse.Namespace) -> List[JsonDict]:
558
+ token = read_bearer_token(args.jwt_path)
559
+ if not args.allow_expired_jwt:
560
+ ensure_jwt_valid_for_use(token, args.jwt_path)
561
+ url = f"{normalize_base_url(args.base_url)}/sys/openclaw/friend/list"
562
+ data = request_json("GET", url, token, args.timeout)
563
+ result = unwrap_result(data) or {}
564
+ friends = result.get("friends") if isinstance(result, dict) else None
565
+ if not isinstance(friends, list):
566
+ raise AppError("虾友列表接口缺少 friends 数组")
567
+
568
+ out: List[JsonDict] = []
569
+ for item in friends:
570
+ if not isinstance(item, dict) or item.get("officialService"):
571
+ continue
572
+ friend_id = item.get("friendId")
573
+ try:
574
+ friend_id_int = int(friend_id)
575
+ except (TypeError, ValueError):
576
+ continue
577
+ display = str(item.get("remark") or item.get("nickname") or "未命名虾友").strip()
578
+ out.append({
579
+ "friendId": friend_id_int,
580
+ "displayName": display,
581
+ "nickname": item.get("nickname"),
582
+ "remark": item.get("remark"),
583
+ "levelName": item.get("levelName"),
584
+ "levelIcon": item.get("levelIcon"),
585
+ })
586
+ out.sort(key=lambda f: str(f["displayName"]))
587
+ for idx, friend in enumerate(out, start=1):
588
+ friend["index"] = idx
589
+ return out
590
+
591
+
592
+ def encode_skill_share_message(payload: JsonDict, prefix: str = "") -> str:
593
+ head = f"{prefix.strip()}\n" if prefix and prefix.strip() else ""
594
+ body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
595
+ return f"{head}{SKILL_SHARE_OPEN}\n{body}\n{SKILL_SHARE_CLOSE}"
596
+
597
+
598
+ def build_intro_prefix(skill: JsonDict, description_zh: str = "") -> str:
599
+ desc = (description_zh or str(skill.get("description") or "")).strip()
600
+ if not desc:
601
+ desc = "这个 Skill 暂未提供详细功能描述。"
602
+ return f"📝 功能介绍:\n{desc}"
603
+
604
+
605
+ def requirements_for_payload(skill: JsonDict) -> Optional[Dict[str, List[str]]]:
606
+ req = skill.get("requirements")
607
+ if not isinstance(req, dict):
608
+ return None
609
+ out: Dict[str, List[str]] = {}
610
+ for source_key, payload_key in (
611
+ ("bins", "bins"),
612
+ ("anyBins", "anyBins"),
613
+ ("env", "env"),
614
+ ):
615
+ values = req.get(source_key)
616
+ if isinstance(values, list) and values:
617
+ out[payload_key] = [str(v) for v in values if str(v).strip()]
618
+ return out or None
619
+
620
+
621
+ def relative_skill_path(base_dir: Path, file_path: Path) -> str:
622
+ try:
623
+ rel_path = file_path.relative_to(base_dir)
624
+ except ValueError:
625
+ return str(file_path)
626
+ return PurePosixPath(rel_path).as_posix()
627
+
628
+
629
+ def sensitive_file_reason(file_name: str) -> str:
630
+ lower = file_name.lower()
631
+ if lower in SENSITIVE_FILE_NAMES:
632
+ return "敏感文件名"
633
+ if lower.endswith(SENSITIVE_FILE_SUFFIXES):
634
+ return "敏感文件后缀"
635
+ # 检查文件名是否包含敏感关键词
636
+ for pattern in SENSITIVE_FILE_NAME_PATTERNS:
637
+ if pattern in lower:
638
+ return f"文件名包含敏感关键词: {pattern}"
639
+ return ""
640
+
641
+
642
+ def looks_binary(data: bytes) -> bool:
643
+ return b"\x00" in data[:1024]
644
+
645
+
646
+ def scan_file_for_sensitive_content(
647
+ base_dir: Path,
648
+ file_path: Path,
649
+ ) -> List[StringDict]:
650
+ findings: List[StringDict] = []
651
+ file_name = file_path.name
652
+ reason = sensitive_file_reason(file_name)
653
+ if reason:
654
+ findings.append({
655
+ "path": relative_skill_path(base_dir, file_path),
656
+ "reason": reason,
657
+ })
658
+
659
+ try:
660
+ with file_path.open("rb") as fp:
661
+ data = fp.read(MAX_SENSITIVE_SCAN_BYTES + 1)
662
+ except OSError:
663
+ return findings
664
+ if looks_binary(data):
665
+ return findings
666
+
667
+ text = data[:MAX_SENSITIVE_SCAN_BYTES].decode("utf-8", errors="replace")
668
+ for pattern, reason in SENSITIVE_CONTENT_PATTERNS:
669
+ if pattern.search(text):
670
+ findings.append({
671
+ "path": relative_skill_path(base_dir, file_path),
672
+ "reason": reason,
673
+ })
674
+ return findings
675
+
676
+
677
+ def skill_base_dir(skill: JsonDict) -> Optional[Path]:
678
+ base_dir = str(skill.get("baseDir") or "").strip()
679
+ if not base_dir:
680
+ return None
681
+ path = Path(base_dir)
682
+ return path if path.is_dir() else None
683
+
684
+
685
+ def iter_packable_skill_files(base_dir: Path) -> Iterable[Tuple[Path, str]]:
686
+ for path in sorted(base_dir.rglob("*")):
687
+ if not path.is_file():
688
+ continue
689
+ rel_path = path.relative_to(base_dir)
690
+ if any(part in SENSITIVE_DIR_NAMES for part in rel_path.parts[:-1]):
691
+ continue
692
+ yield path, PurePosixPath(rel_path).as_posix()
693
+
694
+
695
+ def find_sensitive_skill_content(skill: JsonDict) -> List[StringDict]:
696
+ base_dir = skill_base_dir(skill)
697
+ if base_dir is None:
698
+ return []
699
+
700
+ findings: List[StringDict] = []
701
+ for file_path, _arcname in iter_packable_skill_files(base_dir):
702
+ findings.extend(scan_file_for_sensitive_content(base_dir, file_path))
703
+ if len(findings) >= MAX_SENSITIVE_FINDINGS:
704
+ return findings[:MAX_SENSITIVE_FINDINGS]
705
+ return findings
706
+
707
+
708
+ def ensure_skill_has_no_sensitive_content(
709
+ skill: JsonDict,
710
+ allow_sensitive: bool = False,
711
+ ) -> List[StringDict]:
712
+ """Return sensitive findings, or raise unless the user explicitly allows them."""
713
+ findings = find_sensitive_skill_content(skill)
714
+ if not findings:
715
+ return []
716
+ if allow_sensitive:
717
+ return findings
718
+ lines = [
719
+ "检测到要分享的 Skill 目录中可能包含秘钥相关敏感信息。",
720
+ "命中项:",
721
+ ]
722
+ for item in findings:
723
+ lines.append(f"- {item['path']}: {item['reason']}")
724
+ if len(findings) >= MAX_SENSITIVE_FINDINGS:
725
+ lines.append(f"- 仅展示前 {MAX_SENSITIVE_FINDINGS} 项")
726
+ lines.append("")
727
+ lines.append("如需继续发送,请添加 --allow-sensitive 参数确认。")
728
+ raise AppError("\n".join(lines))
729
+
730
+
731
+ def pack_skill_to_bytes(skill: JsonDict) -> bytes:
732
+ base_dir = skill_base_dir(skill)
733
+ if base_dir is None:
734
+ raise AppError(f"无法定位 Skill 目录,不能按 web custom 格式分享: {skill.get('name')}")
735
+ buf = io.BytesIO()
736
+ with tarfile.open(fileobj=buf, mode="w:gz") as tar:
737
+ for file_path, arcname in iter_packable_skill_files(base_dir):
738
+ tar.add(file_path, arcname=arcname, recursive=False)
739
+ data = buf.getvalue()
740
+ if not data:
741
+ raise AppError("Skill 打包结果为空")
742
+ if len(data) > MAX_CUSTOM_SKILL_PACK_BYTES:
743
+ raise AppError(f"Skill 包 {(len(data) / 1024):.1f} KB 超出 1MB 限制")
744
+ return data
745
+
746
+
747
+ def multipart_file(
748
+ file_name: str,
749
+ file_bytes: bytes,
750
+ content_type: str,
751
+ ) -> Tuple[bytes, str]:
752
+ boundary = f"----oc{uuid.uuid4().hex}"
753
+ b = boundary.encode("ascii")
754
+ parts = [
755
+ b"--" + b + b"\r\n",
756
+ (
757
+ 'Content-Disposition: form-data; '
758
+ f'name="file"; filename="{file_name}"\r\n'
759
+ ).encode("utf-8"),
760
+ f"Content-Type: {content_type}\r\n\r\n".encode("utf-8"),
761
+ file_bytes,
762
+ b"\r\n",
763
+ b"--" + b + b"--\r\n",
764
+ ]
765
+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"
766
+
767
+
768
+ def upload_skill_pack_to_im(
769
+ base_url: str,
770
+ token: str,
771
+ rid: str,
772
+ skill: JsonDict,
773
+ data: bytes,
774
+ timeout: int,
775
+ ) -> str:
776
+ b64 = base64.b64encode(data).decode("ascii")
777
+ wrapped = "\n".join(b64[i:i + 76] for i in range(0, len(b64), 76)).encode("utf-8")
778
+ raw_name = str(skill.get("skillKey") or skill.get("name") or "skill")
779
+ safe_name = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in raw_name)
780
+ body, ctype = multipart_file(f"{safe_name}.txt", wrapped, "text/plain")
781
+ query = urllib.parse.urlencode({"rid": rid})
782
+ url = f"{base_url}/sys/openclaw/im/chat.uploadAsset?{query}"
783
+ req = urllib.request.Request(
784
+ url=url,
785
+ data=body,
786
+ headers=make_headers(token, ctype),
787
+ method="POST",
788
+ )
789
+ try:
790
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
791
+ raw = resp.read().decode("utf-8", errors="replace")
792
+ except urllib.error.HTTPError as exc:
793
+ err_body = exc.read().decode("utf-8", errors="replace")
794
+ hint = http_error_hint(exc.code, err_body)
795
+ raise AppError(f"上传 Skill 包失败: HTTP {exc.code}: {err_body}{hint}") from exc
796
+ try:
797
+ res = json.loads(raw)
798
+ except json.JSONDecodeError as exc:
799
+ raise AppError(f"上传 Skill 包返回不是有效 JSON: {exc}\n{raw}") from exc
800
+ if isinstance(res, dict) and res.get("status") not in (None, 0):
801
+ raise AppError(f"上传 Skill 包失败: {res.get('message')!r}")
802
+ result = unwrap_result(res if isinstance(res, dict) else {}) or {}
803
+ asset = result.get("asset") if isinstance(result, dict) else {}
804
+ url_path = asset.get("urlPath") if isinstance(asset, dict) else None
805
+ if not url_path:
806
+ raise AppError("上传 Skill 包成功但缺少 result.asset.urlPath")
807
+ return str(url_path)
808
+
809
+
810
+ def build_store_payload(skill: JsonDict, note: str) -> JsonDict:
811
+ slug = str(
812
+ skill.get("storeSlug") or skill.get("skillKey") or skill.get("name") or ""
813
+ ).strip()
814
+ if not slug:
815
+ raise AppError("缺少商店 Skill slug")
816
+ payload: JsonDict = {"v": 1, "type": "store", "slug": slug}
817
+ if note.strip():
818
+ payload["note"] = note.strip()
819
+ return payload
820
+
821
+
822
+ def build_custom_payload(
823
+ skill: JsonDict,
824
+ package_url: str,
825
+ size: int,
826
+ sha256: str,
827
+ description_zh: str = "",
828
+ ) -> JsonDict:
829
+ desc = (description_zh or str(skill.get("description") or "")).strip() or None
830
+ payload: JsonDict = {
831
+ "v": 1,
832
+ "type": "custom",
833
+ "name": skill.get("name") or skill.get("skillKey"),
834
+ "skillKey": skill.get("skillKey") or skill.get("name"),
835
+ "description": desc,
836
+ "emoji": skill.get("emoji"),
837
+ "packageUrl": package_url,
838
+ "size": size,
839
+ "sha256": sha256,
840
+ "format": "tgz",
841
+ }
842
+ req = requirements_for_payload(skill)
843
+ if req:
844
+ payload["requires"] = req
845
+ return {k: v for k, v in payload.items() if v is not None}
846
+
847
+
848
+ def build_preview_message(skill: JsonDict, description_zh: str = "") -> str:
849
+ prefix = build_intro_prefix(skill, description_zh)
850
+ if skill.get("storeSlug"):
851
+ return encode_skill_share_message(build_store_payload(skill, prefix), prefix)
852
+ placeholder = {
853
+ "v": 1,
854
+ "type": "custom",
855
+ "name": skill.get("name") or skill.get("skillKey"),
856
+ "skillKey": skill.get("skillKey") or skill.get("name"),
857
+ "description": (
858
+ description_zh or str(skill.get("description") or "")
859
+ ).strip() or None,
860
+ "packageUrl": "<send 时上传生成>",
861
+ "size": 0,
862
+ "format": "tgz",
863
+ }
864
+ payload = {k: v for k, v in placeholder.items() if v is not None}
865
+ return encode_skill_share_message(payload, prefix)
866
+
867
+
868
+ def get_or_create_dm(base_url: str, token: str, friend_id: int, timeout: int) -> str:
869
+ url = f"{base_url}/sys/openclaw/friend/dm"
870
+ data = request_json("POST", url, token, timeout, payload={"friendId": friend_id})
871
+ result = unwrap_result(data) or {}
872
+ channel = result.get("channel") if isinstance(result, dict) else None
873
+ if not isinstance(channel, dict):
874
+ channel = result if isinstance(result, dict) else {}
875
+ rid = channel.get("_id")
876
+ if not rid:
877
+ raise AppError("DM 创建成功但缺少 result.channel._id")
878
+ return str(rid)
879
+
880
+
881
+ def send_message(
882
+ base_url: str,
883
+ token: str,
884
+ rid: str,
885
+ text: str,
886
+ timeout: int,
887
+ ) -> JsonDict:
888
+ url = f"{base_url}/sys/openclaw/im/chat.sendMessage"
889
+ data = request_json("POST", url, token, timeout, payload={"rid": rid, "msg": text})
890
+ result = unwrap_result(data) or {}
891
+ message = result.get("message") if isinstance(result, dict) else None
892
+ return message if isinstance(message, dict) else {}
893
+
894
+
895
+ def add_common_args(parser: argparse.ArgumentParser) -> None:
896
+ parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help="API base URL")
897
+ parser.add_argument(
898
+ "--timeout",
899
+ type=int,
900
+ default=DEFAULT_TIMEOUT,
901
+ help="HTTP timeout seconds",
902
+ )
903
+ parser.add_argument("--jwt-path", default=JWT_PATH, help="JWT file path")
904
+ parser.add_argument(
905
+ "--allow-expired-jwt",
906
+ action="store_true",
907
+ help="Skip local JWT exp check",
908
+ )
909
+ parser.add_argument(
910
+ "--skills-command",
911
+ default=os.environ.get("OPENCLAW_SKILLS_COMMAND", DEFAULT_SKILLS_COMMAND),
912
+ help="Command that prints openclaw skills list JSON",
913
+ )
914
+ parser.add_argument(
915
+ "--skill-info-command-template",
916
+ default=os.environ.get(
917
+ "OPENCLAW_SKILL_INFO_COMMAND_TEMPLATE",
918
+ DEFAULT_SKILL_INFO_COMMAND_TEMPLATE,
919
+ ),
920
+ help="Command template for one skill JSON; use {skill} placeholder",
921
+ )
922
+
923
+
924
+ def build_parser() -> argparse.ArgumentParser:
925
+ parser = argparse.ArgumentParser(description="向虾友发送已安装 Skill 的功能介绍")
926
+ sub = parser.add_subparsers(dest="command", required=True)
927
+
928
+ p = sub.add_parser("list-skills", help="列出当前容器实际可见的 Skill")
929
+ add_common_args(p)
930
+
931
+ p = sub.add_parser("list-friends", help="列出当前账号虾友")
932
+ add_common_args(p)
933
+
934
+ for name in ("preview", "send"):
935
+ p = sub.add_parser(name, help="预览或发送 Skill 功能介绍")
936
+ add_common_args(p)
937
+ p.add_argument("--skill", required=True, help="Skill 名称或 list-skills 返回的序号")
938
+ p.add_argument("--friend-id", type=int, required=True, help="目标虾友 friendId")
939
+ p.add_argument("--friend-name", default="", help="目标虾友展示名")
940
+ p.add_argument("--description-zh", default="", help="可选:由 Agent 改写的中文功能介绍")
941
+ p.add_argument(
942
+ "--allow-sensitive",
943
+ action="store_true",
944
+ help="确认发送包含敏感信息的 Skill",
945
+ )
946
+ return parser
947
+
948
+
949
+ def main(argv: Optional[List[str]] = None) -> int:
950
+ configure_stdio()
951
+ parser = build_parser()
952
+ args = parser.parse_args(argv)
953
+ try:
954
+ if args.timeout <= 0:
955
+ raise AppError("timeout 必须为正整数")
956
+ if args.command == "list-skills":
957
+ skills = load_skills(args)
958
+ print_json({"skills": skills, "groups": build_skill_groups(skills)})
959
+ return 0
960
+ if args.command == "list-friends":
961
+ print_json({"friends": load_friends(args)})
962
+ return 0
963
+
964
+ if args.friend_id <= 0:
965
+ raise AppError("friend-id 必须为正整数")
966
+ skill = merge_skill_detail(args, find_skill(args, args.skill))
967
+ friend_name = (args.friend_name or "未命名虾友").strip()
968
+ sensitive_findings: List[StringDict] = []
969
+ if not skill.get("storeSlug"):
970
+ sensitive_findings = ensure_skill_has_no_sensitive_content(
971
+ skill,
972
+ getattr(args, "allow_sensitive", False),
973
+ )
974
+ if args.command == "preview":
975
+ message = build_preview_message(skill, args.description_zh)
976
+ print_json({
977
+ "skill": skill,
978
+ "friend": {"friendId": args.friend_id, "displayName": friend_name},
979
+ "message": message,
980
+ "sensitiveFindings": sensitive_findings if sensitive_findings else None,
981
+ })
982
+ return 0
983
+
984
+ token = read_bearer_token(args.jwt_path)
985
+ if not args.allow_expired_jwt:
986
+ ensure_jwt_valid_for_use(token, args.jwt_path)
987
+ base_url = normalize_base_url(args.base_url)
988
+ rid = get_or_create_dm(base_url, token, args.friend_id, args.timeout)
989
+ prefix = build_intro_prefix(skill, args.description_zh)
990
+ if skill.get("storeSlug"):
991
+ payload = build_store_payload(skill, prefix)
992
+ message = encode_skill_share_message(payload, prefix)
993
+ else:
994
+ pack = pack_skill_to_bytes(skill)
995
+ package_url = upload_skill_pack_to_im(
996
+ base_url,
997
+ token,
998
+ rid,
999
+ skill,
1000
+ pack,
1001
+ args.timeout,
1002
+ )
1003
+ payload = build_custom_payload(
1004
+ skill,
1005
+ package_url,
1006
+ len(pack),
1007
+ hashlib.sha256(pack).hexdigest(),
1008
+ args.description_zh,
1009
+ )
1010
+ message = encode_skill_share_message(payload, prefix)
1011
+ sent = send_message(base_url, token, rid, message, args.timeout)
1012
+ result = {
1013
+ "success": True,
1014
+ "skill": skill["name"],
1015
+ "friend": {"friendId": args.friend_id, "displayName": friend_name},
1016
+ "rid": rid,
1017
+ "messageId": sent.get("_id"),
1018
+ "message": message,
1019
+ }
1020
+ if sensitive_findings:
1021
+ result["sensitiveFindings"] = sensitive_findings
1022
+ result["sensitiveWarning"] = "已发送包含敏感信息的 Skill,请确认接收方可信"
1023
+ print_json(result)
1024
+ return 0
1025
+ except AppError as exc:
1026
+ print(f"ERROR: {exc}", file=sys.stderr)
1027
+ return 1
1028
+
1029
+
1030
+ if __name__ == "__main__":
1031
+ sys.exit(main())