ohos-devloop-pc 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1340 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """PC 操作服务(devloop-pc)——把 Windows 上的镜像/设备能力收敛成带鉴权的 HTTP/JSON 服务。
4
+
5
+ 用法(本模块属独立发行版 ohos-devloop-pc;源树脚本直跑等价):
6
+ ohos-devloop-pc serve [--port N] [--token-file PATH]
7
+ ohos-devloop-pc token [--show]
8
+ ohos-devloop-pc tunnel --server <条目> [--port N] [--print]
9
+ ohos-devloop-pc ops [--json]
10
+ ohos-devloop-pc check --server <条目> [--port N] [--remote-token PATH]
11
+ ohos-devloop-pc setup [目录] [--port N] [--token-file PATH] [--require-device]
12
+ ohos-devloop-pc self-check [--port N] [--token-file PATH] [--require-device]
13
+
14
+ 协议(详见 RUNBOOK「部署形态 B」节):
15
+ GET /healthz 免鉴权健康检查;带 service + http_api_version + mcp_tools_version
16
+ GET /v1/ops 操作清单(Bearer 鉴权)
17
+ POST /v1/ops/{op} 执行操作(Bearer 鉴权;body 必须带 Content-Length 且 ≤1MiB)
18
+ GET /v1/jobs/{id} 异步任务状态(id/op/state/rc/started/ended/result/error)
19
+ GET /v1/jobs/{id}/log 异步任务输出尾部(stdout_tail/stderr_tail)
20
+
21
+ 安全边界(threat_model T-261123-01/02):
22
+ - 只 bind 127.0.0.1,不提供 --host(D4 硬约束:无任何非回环监听开关)
23
+ - Bearer token 32 字节 secrets.token_urlsafe;比对用 hmac.compare_digest;401 不回细节
24
+ - 日志只记 method/path/status,绝不打 Authorization 头或请求体;token 文件 0600
25
+ - `token` 子命令默认只打印路径,--show 才打印值(带告警)
26
+
27
+ 坑位:
28
+ - 异步 job 是内存态:服务退出后不可轮询;长任务(apply.run)落 runs/<id>/results.json,
29
+ 可跨重启经 apply.results 续读(RUNBOOK「部署形态 B」长任务与重启语义)。
30
+ - import 期零副作用:不起服务器/不建目录/不读 token(server_agent.py 会 import 本模块
31
+ 取 read_token helper)。
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import hmac
37
+ import json
38
+ import os
39
+ import re
40
+ import secrets
41
+ import shlex
42
+ import socket
43
+ import stat
44
+ import subprocess
45
+ import sys
46
+ import tempfile
47
+ import threading
48
+ import time
49
+ import urllib.error
50
+ import urllib.request
51
+ import uuid
52
+ from datetime import datetime
53
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
54
+ from pathlib import Path
55
+
56
+ # PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
57
+ # 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
58
+ import sys
59
+ from pathlib import Path
60
+
61
+ _PC_DIR = Path(__file__).resolve().parent
62
+ for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
63
+ if _cand not in sys.path:
64
+ sys.path.insert(0, _cand)
65
+ import ohos_devloop_pc # noqa: E402,F401
66
+
67
+ import apply
68
+ import wsroot
69
+
70
+ import check_env
71
+ from ohos_devloop_pc import device_locks # 包导入:避免与 pc/ 目录扁平导入产生双模块实例
72
+ import pc_mcp # 契约版本解析/兼容判定(与客户端握手同一条规则,WARNING-8)
73
+ from ohos_devloop_pc import pc_ops # 包导入:mock/OPS 身份必须与调用方同实例
74
+
75
+ TOKEN_FILE = pc_mcp.TOKEN_FILE
76
+ MAX_BODY = 1 * 1024 * 1024 # 请求体上限 1MiB(T-261123-03 DoS 收敛)
77
+ DEFAULT_PORT = 8765
78
+ REMOTE_TOKEN_RE = re.compile(r"^[A-Za-z0-9._/~-]+$") # 远端 token 路径白名单(注入面收敛)
79
+
80
+
81
+ # --------------------------------------------------------------------------- token
82
+
83
+ def ensure_token(path: Path) -> tuple[str, bool]:
84
+ """生成/读取服务 token(32 字节 url-safe)。返回 (token, 是否新建)。"""
85
+ path = Path(path)
86
+ path.parent.mkdir(parents=True, exist_ok=True)
87
+ if path.is_file():
88
+ tok = path.read_text(encoding="utf-8").strip()
89
+ if tok:
90
+ return tok, False
91
+ tok = secrets.token_urlsafe(32)
92
+ path.write_text(tok, encoding="utf-8", newline="\n")
93
+ try:
94
+ os.chmod(path, 0o600) # best-effort(Windows 无 POSIX 权限语义;服务器侧另有 chmod 600)
95
+ except OSError:
96
+ pass
97
+ return tok, True
98
+
99
+
100
+ def read_token(path: Path) -> str:
101
+ """读 token;缺失/为空抛可执行 OpError(引导 pc serve / pc token)。
102
+
103
+ TOKEN_FILE/read_token 单一来源在服务器 pc_mcp(T-261127-05);此处只把
104
+ pc_mcp.TokenError 转回 pc_ops.OpError,保持既有 CLI 行为与错误文案。
105
+ """
106
+ try:
107
+ return pc_mcp.read_token(path)
108
+ except pc_mcp.TokenError as exc:
109
+ raise pc_ops.OpError(str(exc)) from exc
110
+
111
+
112
+ # --------------------------------------------------------------------------- 参数校验
113
+
114
+ def _validate(op: pc_ops.Op, params: dict) -> dict:
115
+ """required 存在性 + 类型/范围/pattern 校验 + 不接受额外键(T-261123-03 显式 allowlist)。"""
116
+ if not isinstance(params, dict):
117
+ raise pc_ops.OpError(f"{op.name}: 请求体必须是 JSON object")
118
+ unknown = [k for k in params if k not in op.params]
119
+ if unknown:
120
+ raise pc_ops.OpError(f"{op.name}: 未知参数 {unknown}(可用: {'、'.join(sorted(op.params)) or '无'})")
121
+ for key in op.required:
122
+ if key not in params or params[key] is None:
123
+ raise pc_ops.OpError(f"{op.name}: 缺少必填参数 {key!r}")
124
+ for key, schema in op.params.items():
125
+ if key not in params or params[key] is None:
126
+ continue
127
+ v = params[key]
128
+ typ = schema.get("type")
129
+ if typ == "string":
130
+ if not isinstance(v, str):
131
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 必须是 string")
132
+ if "minLength" in schema and len(v) < schema["minLength"]:
133
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 长度过短(≥{schema['minLength']})")
134
+ if "maxLength" in schema and len(v) > schema["maxLength"]:
135
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 长度超限(≤{schema['maxLength']})")
136
+ if "pattern" in schema and not re.match(schema["pattern"], v):
137
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 不匹配 {schema['pattern']!r}")
138
+ elif typ == "integer":
139
+ if isinstance(v, bool) or not isinstance(v, int):
140
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 必须是 integer")
141
+ if "minimum" in schema and v < schema["minimum"]:
142
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 不能小于 {schema['minimum']}")
143
+ if "maximum" in schema and v > schema["maximum"]:
144
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 不能大于 {schema['maximum']}")
145
+ elif typ == "number":
146
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
147
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 必须是 number")
148
+ elif typ == "boolean":
149
+ if not isinstance(v, bool):
150
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 必须是 boolean")
151
+ elif typ == "object":
152
+ if not isinstance(v, dict):
153
+ raise pc_ops.OpError(f"{op.name}: 参数 {key} 必须是 object")
154
+ return params
155
+
156
+
157
+ # --------------------------------------------------------------------------- 异步 job
158
+
159
+ class Job:
160
+ """异步任务记录(内存态;apply.run 另有 runs/<id>/results.json 落盘可跨重启续读)。"""
161
+ __slots__ = ("id", "op", "state", "rc", "stdout_tail", "stderr_tail",
162
+ "started", "ended", "result", "error")
163
+
164
+ def __init__(self, job_id: str, op: str, started: str):
165
+ self.id = job_id
166
+ self.op = op
167
+ self.state = "running"
168
+ self.rc = None
169
+ self.stdout_tail = ""
170
+ self.stderr_tail = ""
171
+ self.started = started
172
+ self.ended = None
173
+ self.result = None
174
+ self.error = None
175
+
176
+
177
+ class JobTable:
178
+ """带锁 job 表:提交用 daemon 线程;同 (op, 规范化参数) 去重(在跑时返回同一 job id);
179
+ finished 超过 32 条丢最旧(T-261123-06:job 表有界)。"""
180
+
181
+ MAX_JOBS = 32
182
+ TAIL_LIMIT = 64 * 1024
183
+
184
+ def __init__(self):
185
+ self._jobs: dict[str, Job] = {}
186
+ self._running: dict[tuple, str] = {}
187
+ self._lock = threading.Lock()
188
+
189
+ def submit(self, op: pc_ops.Op, params: dict) -> str:
190
+ key = (op.name, json.dumps(params, sort_keys=True, ensure_ascii=False))
191
+ with self._lock:
192
+ existing = self._running.get(key)
193
+ if existing and self._jobs.get(existing) is not None \
194
+ and self._jobs[existing].state == "running":
195
+ return existing # 同参在跑去重:直接复用正在跑的 job
196
+ job = Job(f"{op.name.replace('.', '_')}-{uuid.uuid4().hex[:12]}", op.name,
197
+ datetime.now().astimezone().isoformat(timespec="seconds"))
198
+ self._jobs[job.id] = job
199
+ self._running[key] = job.id
200
+ done = [j for j in self._jobs.values() if j.state != "running"]
201
+ if len(done) > self.MAX_JOBS: # 有界:finished 超限丢最旧
202
+ for j in sorted(done, key=lambda x: x.started)[:len(done) - self.MAX_JOBS]:
203
+ self._jobs.pop(j.id, None)
204
+ threading.Thread(target=self._run, args=(job, op, params), daemon=True).start()
205
+ return job.id
206
+
207
+ def _run(self, job: Job, op: pc_ops.Op, params: dict) -> None:
208
+ try:
209
+ job.result = op.handler(params, {"token_configured": True})
210
+ if isinstance(job.result, dict) and isinstance(job.result.get("rc"), int):
211
+ job.rc = job.result["rc"]
212
+ job.state = "done"
213
+ except Exception as e: # handler 异常进 job.error(同步 op 的 500 分支在请求线程)
214
+ job.state = "failed"
215
+ job.error = str(e)
216
+ finally:
217
+ job.ended = datetime.now().astimezone().isoformat(timespec="seconds")
218
+ with self._lock:
219
+ self._running = {k: v for k, v in self._running.items() if v != job.id}
220
+
221
+ def get(self, job_id: str) -> Job | None:
222
+ with self._lock:
223
+ return self._jobs.get(job_id)
224
+
225
+
226
+ # --------------------------------------------------------------------------- HTTP 服务
227
+
228
+ def build_handler(token_file: Path, jobs: JobTable | None = None,
229
+ locks: device_locks.LockStore | None = None):
230
+ """构造 handler 类(token 文件路径/job 表/设备登记存储闭包注入——测试可传临时路径)。
231
+
232
+ 构造时立即 locks.load():服务启动即加载登记;文件损坏 → LockError 冒泡(fail-closed),
233
+ 绝不静默清空登记启动(T-13-01)。
234
+ """
235
+ jobs = jobs or JobTable()
236
+ token_file = Path(token_file)
237
+ locks = locks or device_locks.LockStore()
238
+ locks.load()
239
+
240
+ class Service(BaseHTTPRequestHandler):
241
+ TOKEN_FILE = token_file
242
+ JOBS = jobs
243
+ LOCKS = locks
244
+ server_version = "ohos-devloop-pc/1"
245
+
246
+ def log_message(self, fmt, *args):
247
+ # 记录纪律:只记 method/path/status,绝不打 Authorization 头或请求体(T-261123-02)
248
+ sys.stderr.write(f"[pc_service] {self.address_string()} {fmt % args}\n")
249
+
250
+ def _send(self, code: int, payload: dict) -> None:
251
+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
252
+ self.send_response(code)
253
+ self.send_header("Content-Type", "application/json; charset=utf-8")
254
+ self.send_header("Content-Length", str(len(data)))
255
+ self.end_headers()
256
+ self.wfile.write(data)
257
+
258
+ def _auth(self) -> bool:
259
+ """Bearer 鉴权:hmac.compare_digest 恒定时间比对;失败 401 不解释细节。"""
260
+ header = self.headers.get("Authorization", "")
261
+ prefix = "Bearer "
262
+ if not header.startswith(prefix):
263
+ return False
264
+ supplied = header[len(prefix):].strip()
265
+ try:
266
+ expected = read_token(self.TOKEN_FILE)
267
+ except pc_ops.OpError:
268
+ return False
269
+ return hmac.compare_digest(supplied, expected)
270
+
271
+ def _dispatch(self, op_name: str) -> None:
272
+ op = pc_ops.OPS.get(op_name)
273
+ if op is None:
274
+ self._send(404, {"ok": False, "error": f"未知 op: {op_name}"})
275
+ return
276
+ length = self.headers.get("Content-Length")
277
+ if length is None:
278
+ self._send(400, {"ok": False, "error": "请求必须带 Content-Length"})
279
+ return
280
+ try:
281
+ n = int(length)
282
+ except ValueError:
283
+ self._send(400, {"ok": False, "error": "Content-Length 非法"})
284
+ return
285
+ if n > MAX_BODY:
286
+ self._send(413, {"ok": False, "error": f"请求体超过 {MAX_BODY} 字节上限"})
287
+ return
288
+ try:
289
+ raw = self.rfile.read(n)
290
+ except OSError:
291
+ self._send(400, {"ok": False, "error": "读取请求体失败"})
292
+ return
293
+ try:
294
+ params = json.loads(raw.decode("utf-8"))
295
+ except (UnicodeDecodeError, json.JSONDecodeError):
296
+ self._send(400, {"ok": False, "error": "请求体必须是合法 JSON"})
297
+ return
298
+ try:
299
+ params = _validate(op, params)
300
+ if op.async_job:
301
+ job_id = self.JOBS.submit(op, params)
302
+ self._send(202, {"ok": True, "job_id": job_id, "state": "running"})
303
+ else:
304
+ svc = {"token_configured": self.TOKEN_FILE.is_file(),
305
+ "locks": self.LOCKS,
306
+ "jobs": self.JOBS} # job.wait 长轮询(E2E-18)
307
+ result = op.handler(params, svc)
308
+ self._send(200, {"ok": True, "result": result})
309
+ except pc_ops.OpError as e:
310
+ self._send(400, {"ok": False, "error": str(e)})
311
+ except Exception as e: # 未预期异常 → 500 泛化(详情只写服务端 stderr)
312
+ sys.stderr.write(f"[pc_service] {op_name} 未预期异常: {e!r}\n")
313
+ self._send(500, {"ok": False, "error": "internal error(详情见服务端 stderr)"})
314
+
315
+ def do_GET(self):
316
+ if self.path == "/healthz":
317
+ # 免鉴权分支:必须在 _auth() 之前,绝不读 token、绝不要求 Authorization
318
+ # (healthz 是版本握手的唯一读取面,T-12-01:只回版本与身份,不授予信任)。
319
+ self._send(200, {"ok": True, "service": "ohos-devloop-pc",
320
+ "http_api_version": pc_ops.HTTP_API_VERSION,
321
+ "mcp_tools_version": pc_ops.MCP_TOOLS_VERSION})
322
+ return
323
+ if not self._auth():
324
+ self._send(401, {"ok": False, "error": "unauthorized"})
325
+ return
326
+ if self.path == "/v1/ops":
327
+ # 契约(interface-contract.md 端点表):顶层带 ok/ops/两个版本键/tools——
328
+ # 版本键与 /healthz 同源(四个可读面不变式),tools 即 MCP 工具清单(30 条)。
329
+ self._send(200, {"ok": True, "ops": pc_ops.ops_meta(),
330
+ "http_api_version": pc_ops.HTTP_API_VERSION,
331
+ "mcp_tools_version": pc_ops.MCP_TOOLS_VERSION,
332
+ "tools": pc_ops.tool_manifest()["tools"]})
333
+ return
334
+ m = re.match(r"^/v1/jobs/([A-Za-z0-9._-]+)$", self.path)
335
+ if m:
336
+ job = self.JOBS.get(m.group(1))
337
+ if job is None:
338
+ self._send(404, {"ok": False, "error": f"job 不存在: {m.group(1)}"})
339
+ return
340
+ self._send(200, {"ok": True, "job": {"id": job.id, "op": job.op,
341
+ "state": job.state, "rc": job.rc,
342
+ "started": job.started, "ended": job.ended,
343
+ "result": job.result, "error": job.error}})
344
+ return
345
+ m2 = re.match(r"^/v1/jobs/([A-Za-z0-9._-]+)/log$", self.path)
346
+ if m2:
347
+ job = self.JOBS.get(m2.group(1))
348
+ if job is None:
349
+ self._send(404, {"ok": False, "error": f"job 不存在: {m2.group(1)}"})
350
+ return
351
+ self._send(200, {"ok": True, "log": {"stdout_tail": job.stdout_tail,
352
+ "stderr_tail": job.stderr_tail}})
353
+ return
354
+ self._send(404, {"ok": False, "error": f"未知路径: {self.path}"})
355
+
356
+ def do_POST(self):
357
+ if not self._auth():
358
+ self._send(401, {"ok": False, "error": "unauthorized"})
359
+ return
360
+ m = re.match(r"^/v1/ops/([A-Za-z0-9._-]+)$", self.path)
361
+ if not m:
362
+ self._send(404, {"ok": False, "error": f"未知路径: {self.path}"})
363
+ return
364
+ self._dispatch(m.group(1))
365
+
366
+ return Service
367
+
368
+
369
+ # --------------------------------------------------------------------------- CLI
370
+
371
+ def _port_int(v: str) -> int:
372
+ try:
373
+ n = int(v)
374
+ except ValueError:
375
+ raise pc_ops.OpError(f"端口必须是整数 1..65535: {v!r}")
376
+ if not 1 <= n <= 65535:
377
+ raise pc_ops.OpError(f"端口越界(1..65535): {n}")
378
+ return n
379
+
380
+
381
+ def _ssh(tgt: str, port: str, cmd: str, timeout: int = 60) -> tuple[int, str]:
382
+ rc, out, err = apply.sh(["ssh", "-o", "ConnectTimeout=15", "-p", port, tgt, cmd],
383
+ timeout=timeout)
384
+ return rc, out + (f"\n[stderr] {err}" if err.strip() else "")
385
+
386
+
387
+ def cmd_serve(args) -> int:
388
+ token_file = Path(args.token_file)
389
+ port = 0 if args.port == "0" else _port_int(args.port)
390
+ ensure_token(token_file)
391
+ try:
392
+ handler = build_handler(token_file) # 构造即加载登记:损坏 → LockError(fail-closed)
393
+ except device_locks.LockError as e:
394
+ sys.stderr.write(f"pc 服务启动失败: {e}\n")
395
+ sys.stderr.write("修复: 人工核对 ~/.ohos-devloop/pc_service/device-locks.json,"
396
+ "修复结构或移走该文件后重试(文件不含凭据)。\n")
397
+ return 1
398
+ httpd = ThreadingHTTPServer(("127.0.0.1", port), handler)
399
+ actual = httpd.server_address[1]
400
+ if args.port == "0":
401
+ # 测试/编排用:实际端口与 token 文件路径各一行(供解析),不打印 token 值
402
+ print(f"PORT={actual}", flush=True)
403
+ print(f"TOKEN_FILE={token_file}", flush=True)
404
+ print(f"pc 服务就绪: http://127.0.0.1:{actual}(token 文件: {token_file})", flush=True)
405
+ print("只监听回环地址(127.0.0.1);Ctrl+C 退出", flush=True)
406
+ try:
407
+ httpd.serve_forever()
408
+ except KeyboardInterrupt:
409
+ pass
410
+ return 0
411
+
412
+
413
+ def cmd_token(args) -> int:
414
+ tok, created = ensure_token(Path(args.token_file))
415
+ if args.show:
416
+ print("WARN: 打印 token 值会暴露给能读屏幕/日志的人,仅限临时排障", file=sys.stderr)
417
+ print(tok)
418
+ else:
419
+ print(f"token 文件: {args.token_file}({'新建' if created else '已存在'})")
420
+ print("需要值请运行: ohos-devloop pc token --show")
421
+ return 0
422
+
423
+
424
+ def cmd_tunnel(args) -> int:
425
+ """PC 主动隧道(D4 + E2E-23):反向 HTTP 服务(显式回环绑定,禁 0.0.0.0/GatewayPorts);
426
+ --vnc 时追加模拟器 VNC 正向 `-L 127.0.0.1:<本地>:127.0.0.1:5921`(只回环,供工程师人工观察)。
427
+ --print 只打印不执行。"""
428
+ port = _port_int(args.port)
429
+ inv = pc_ops._inv()
430
+ sname, cfg = pc_ops._pick(inv.get("servers") or {}, args.server, "servers")
431
+ argv = ["ssh", "-N", "-T",
432
+ "-o", "ExitOnForwardFailure=yes",
433
+ "-o", "ServerAliveInterval=30",
434
+ "-o", "ServerAliveCountMax=3",
435
+ "-R", f"127.0.0.1:{port}:127.0.0.1:{port}",
436
+ "-p", str(cfg.get("port", 22)),
437
+ f"{cfg['user']}@{cfg['host']}"]
438
+ vnc_local = None
439
+ if args.vnc is not None:
440
+ vnc_local = args.vnc
441
+ if vnc_local == "auto":
442
+ emus = inv.get("emulators") or {}
443
+ first = next(iter(emus), None)
444
+ if first is not None:
445
+ vnc_local = str((emus[first].get("vnc_local_port") or "").strip() or "15921")
446
+ else:
447
+ vnc_local = "15921"
448
+ vnc_local = _port_int(vnc_local)
449
+ argv = [*argv[:5], "-L", f"127.0.0.1:{vnc_local}:127.0.0.1:5921", *argv[5:]]
450
+ if args.print:
451
+ print(shlex.join(argv))
452
+ return 0
453
+ print(f"反向隧道(仅回环): 服务器 127.0.0.1:{port} → 本机 127.0.0.1:{port}({sname})")
454
+ if vnc_local:
455
+ print(f"VNC 正向(仅回环): 本机 127.0.0.1:{vnc_local} → 服务器模拟器 127.0.0.1:5921"
456
+ "(人工观察用)")
457
+ print("保持前台运行(或自行 nohup);Ctrl+C 退出")
458
+ return subprocess.run(argv).returncode
459
+
460
+
461
+ def cmd_ops(args) -> int:
462
+ if args.json:
463
+ sys.stdout.write(pc_ops.manifest_json())
464
+ else:
465
+ print(f"{'op':<24} {'模式':<6} 说明")
466
+ for o in pc_ops.OPS.values():
467
+ print(f"{o.name:<24} {'async' if o.async_job else 'sync':<6} {o.title}")
468
+ return 0
469
+
470
+
471
+ def versions_compatible(advertised, local) -> bool:
472
+ """契约版本键兼容判定(WARNING-8):与 pc_mcp.compat_error 同一条规则——
473
+ 同 MAJOR 且 MINOR ≥ 本地常量(服务端小版本超前是兼容的,不要求相等)。
474
+
475
+ `pc check` / `pc self-check` 与服务端 MCP 握手判同一条规则:一个前向兼容的
476
+ 1.2 服务能通过握手,就不该被诊断命令误报 FAIL;op 数/工具面仍按 face 精确对账。
477
+ 非法/缺失版本值 fail closed(False)。
478
+ """
479
+ adv = pc_mcp.parse_version(advertised)
480
+ req = pc_mcp.parse_version(local)
481
+ return adv is not None and req is not None and adv[0] == req[0] and adv[1] >= req[1]
482
+
483
+
484
+ def cmd_check(args) -> int:
485
+ """经 ssh 在服务器上顺序执行两次 curl:healthz(免 token)+ /v1/ops(token 来自远端文件,
486
+ `$(cat …)` 展开在服务器侧——token 不进本机命令行/日志)。"""
487
+ port = _port_int(args.port)
488
+ inv = pc_ops._inv()
489
+ sname, cfg = pc_ops._pick(inv.get("servers") or {}, args.server, "servers")
490
+ # 远端路径绝不做本地 expanduser——Windows 下 "~/devloop/pc_token" 会被展开成本机
491
+ # C:\Users\... 并被白名单拒绝;保留 ~ 交由服务器 bash 展开(远端 home 才是正解)。
492
+ remote_token = args.remote_token
493
+ if not REMOTE_TOKEN_RE.fullmatch(remote_token):
494
+ print(f"FAIL: remote-token 路径含非法字符(只允许 [A-Za-z0-9._/~-]): {remote_token!r}")
495
+ return 1
496
+ tgt = f"{cfg['user']}@{cfg['host']}"
497
+ pport = str(cfg.get("port", 22))
498
+ base = f"http://127.0.0.1:{port}"
499
+ ok = True
500
+ rc, out = _ssh(tgt, pport, f"curl -s -o /dev/null -w '%{{http_code}}' {base}/healthz", timeout=30)
501
+ if rc == 0 and out.strip() == "200":
502
+ print("PASS: 健康检查(healthz 免鉴权,隧道+服务在线)")
503
+ else:
504
+ print(f"FAIL: 健康检查(rc={rc} out={out.strip()[:80]!r}——隧道未起或服务未跑?)")
505
+ ok = False
506
+ # 双引号是刻意的:$(cat …) 必须在服务器 bash 里展开;单引号会让 curl 收到字面量。
507
+ cmd = (f"curl -s -w '\\n%{{http_code}}' "
508
+ f'-H "Authorization: Bearer $(cat {remote_token})" {base}/v1/ops')
509
+ rc, out = _ssh(tgt, pport, cmd, timeout=30)
510
+ lines = out.splitlines()
511
+ code = lines[-1].strip() if lines else ""
512
+ if rc == 0 and code == "200" and len(lines) > 1:
513
+ try:
514
+ data = json.loads("\n".join(lines[:-1]))
515
+ except json.JSONDecodeError:
516
+ data = None
517
+ # 契约(CR-01):/v1/ops 顶层必须同时带 ops 清单与两个版本键,缺任一即 fail closed——
518
+ # 只实现部分面的代理会在这里被点名,而不是打出假 PASS。
519
+ ops = (data or {}).get("ops")
520
+ if (data or {}).get("ok") and isinstance(ops, list) \
521
+ and versions_compatible(data.get("http_api_version"),
522
+ pc_ops.HTTP_API_VERSION) \
523
+ and versions_compatible(data.get("mcp_tools_version"),
524
+ pc_ops.MCP_TOOLS_VERSION):
525
+ print(f"PASS: 鉴权工具面({len(ops)} 个 op,版本键 {data.get('http_api_version')}/"
526
+ f"{data.get('mcp_tools_version')} 兼容,同 MAJOR 且 MINOR ≥ 本地)")
527
+ else:
528
+ print("FAIL: /v1/ops 响应非预期(缺 ops 清单或版本键不兼容)")
529
+ ok = False
530
+ else:
531
+ print(f"FAIL: /v1/ops(rc={rc} http={code!r}——token 不符或服务未起)")
532
+ ok = False
533
+ print(f"check 完成: {'PASS' if ok else 'FAIL'}")
534
+ return 0 if ok else 1
535
+
536
+
537
+ # --------------------------------------------------------------------------- self-check
538
+
539
+ PASS = WARN = FAIL = 0
540
+ # 宽泛主体(Windows ACE 判据,大小写不敏感):命中任一即「权限过宽」。
541
+ # 名称匹配只是普通 icacls 文本的兼容面;主判据是下面的 well-known SID/别名——
542
+ # built-in 主体在非英文 Windows 上显示名会本地化(如德语 "Jeder"/"Benutzer"),
543
+ # 只按英文名匹配会 fail-open(WR-04)。
544
+ BROAD_PRINCIPALS = ("builtin\\users", "everyone", "authenticated users")
545
+ # 宽泛主体 SID:Everyone / BUILTIN\Users / Authenticated Users
546
+ BROAD_SIDS = frozenset({"s-1-1-0", "s-1-5-32-545", "s-1-5-11"})
547
+ # SDDL 对 well-known SID 的别名(与 UI 语言无关;icacls /save 输出即此形态)
548
+ SDDL_ALIASES = {"WD": "S-1-1-0", "BU": "S-1-5-32-545", "AU": "S-1-5-11"}
549
+ _SDDL_ACE_RE = re.compile(
550
+ r"\(([A-Za-z]{1,2});([^;()]*);([^;()]*);([^;()]*);([^;()]*);([^)]*)\)")
551
+ # 判定点 item 字面量是外部契约:11-06/11-08 的 verify 分别 grep
552
+ # `^[PASS] 回环监听`、`^[PASS] token 权限`、`^[PASS] hdc + 板卡`——同一判定点
553
+ # 跨 PASS/WARN/FAIL 共用同一 item,不因 tag 改字。
554
+ ITEM_LOOPBACK = "回环监听"
555
+ ITEM_TOKEN_ACL = "token 权限"
556
+ ITEM_AUTH = "鉴权配对"
557
+ ITEM_HDC = "hdc + 板卡"
558
+
559
+
560
+ def report(tag: str, item: str, msg: str = "") -> None:
561
+ """判定输出(与 check_env/server_agent 同形:`[TAG] item — msg`)+ 模块级计数。"""
562
+ global PASS, WARN, FAIL
563
+ suffix = f" — {msg}" if msg else ""
564
+ print(f"[{tag}] {item}{suffix}", flush=True)
565
+ if tag == "PASS":
566
+ PASS += 1
567
+ elif tag == "WARN":
568
+ WARN += 1
569
+ else:
570
+ FAIL += 1
571
+
572
+
573
+ def _write_lines(path: Path, lines: list[str]) -> None:
574
+ with open(path, "w", encoding="utf-8") as f:
575
+ f.write("\n".join(lines) + "\n")
576
+
577
+
578
+ def _step(name: str, status: str, detail: str, started: str) -> dict:
579
+ return {"name": name, "type": "check", "status": status, "detail": detail,
580
+ "started": started,
581
+ "ended": datetime.now().astimezone().isoformat(timespec="seconds")}
582
+
583
+
584
+ def _local_ipv4s() -> list[str]:
585
+ """本机非回环 IPv4 列表(getaddrinfo + UDP connect 默认路由接口),排序后最多 4 个。"""
586
+ ips: set[str] = set()
587
+ try:
588
+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
589
+ ips.add(info[4][0])
590
+ except OSError:
591
+ pass
592
+ try: # 默认路由接口(UDP connect 不发包,纯本机操作)
593
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
594
+ try:
595
+ s.settimeout(0.5)
596
+ s.connect(("8.8.8.8", 80))
597
+ ips.add(s.getsockname()[0])
598
+ finally:
599
+ s.close()
600
+ except OSError:
601
+ pass
602
+ return sorted(ip for ip in ips if not ip.startswith("127."))[:4]
603
+
604
+
605
+ def _healthz(port: int, timeout: float = 1.0) -> dict | None:
606
+ """GET /healthz;能解析 JSON 就返回 dict,任何异常返回 None(调用方校验 service 身份)。"""
607
+ try:
608
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/healthz", timeout=timeout) as r:
609
+ if r.status != 200:
610
+ return None
611
+ return json.loads(r.read().decode("utf-8"))
612
+ except (OSError, ValueError):
613
+ return None
614
+
615
+
616
+ def probe_loopback(port: int, addrs: list[str], timeout: float = 0.6) -> list[str]:
617
+ """对每个非回环地址做连接探测;成功记 CONNECTED,OSError(含超时)记未监听。返回原始证据行。"""
618
+ lines: list[str] = []
619
+ for ip in addrs[:4]:
620
+ try:
621
+ socket.create_connection((ip, port), timeout=timeout).close()
622
+ lines.append(f"{ip}:{port} CONNECTED -> 存在非回环监听")
623
+ except OSError as e:
624
+ lines.append(f"{ip}:{port} {type(e).__name__} -> 未监听")
625
+ return lines
626
+
627
+
628
+ def judge_loopback(healthz_ok: bool, probe_lines: list[str]) -> bool:
629
+ """PASS = healthz 身份正确 且 无任何 CONNECTED 行(超时/拒绝一律视为未监听)。"""
630
+ return bool(healthz_ok) and not any("CONNECTED" in ln for ln in probe_lines)
631
+
632
+
633
+ def _current_user_sid() -> str:
634
+ """当前用户 SID(whoami /user;System32 绝对路径避开 Git Bash 的 whoami)。
635
+
636
+ 取不到返回 "":判定侧按「不可判」处理(FAIL),不退回只凭显示名猜测。
637
+ """
638
+ exe = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "whoami.exe"
639
+ _rc, out = check_env.run([str(exe) if exe.is_file() else "whoami", "/user"], timeout=30)
640
+ found = re.findall(r"S-1-(?:\d+-)+\d+", out)
641
+ return found[-1] if found else ""
642
+
643
+
644
+ def _parse_sddl_acl(sddl: str, self_sid: str) -> list[str]:
645
+ """SDDL DACL → 归一化证据行(SID/别名与 ACE 标志都不随 UI 语言变化)。
646
+
647
+ - 只保留 allow/deny;审计与强制标签不是访问授予。
648
+ - `IO`(inherit-only)标记 effective=no:仅对子对象生效,不算本对象上的授予。
649
+ - `WD`/`BU`/`AU` 是 Everyone/BUILTIN\\Users/Authenticated Users 的语言无关别名。
650
+ - 条件 ACE(`XA`/`XD`/`XU`…,callback ACE)的条件表达式含括号与分号,
651
+ `_SDDL_ACE_RE` 无法可靠拆出 SID:整条证据记 `unjudgeable:` → judge FAIL
652
+ (fail closed;见 IN-R2)。
653
+ """
654
+ lines: list[str] = [f"self-sid={self_sid}"] if self_sid else []
655
+ conditional = False
656
+ for m in _SDDL_ACE_RE.finditer(sddl):
657
+ ace_type, flags, _rights, _obj, _inh, raw_sid = m.groups()
658
+ kind = ace_type.upper()
659
+ if kind.startswith("X"): # XA/XD/XU…:条件(callback)ACE,不按普通 ACE 计数
660
+ conditional = True
661
+ continue
662
+ if kind in ("A", "OA"):
663
+ grant = "allow"
664
+ elif kind in ("D", "OD"):
665
+ grant = "deny"
666
+ else: # AU/OU(审计)、ML(完整性标签)等
667
+ continue
668
+ sid = SDDL_ALIASES.get(raw_sid.strip().upper(), raw_sid.strip())
669
+ flag_tokens = {flags[i:i + 2].upper() for i in range(0, len(flags) - 1, 2)}
670
+ effective = "no" if "IO" in flag_tokens else "yes"
671
+ lines.append(f"ace sid={sid} type={grant} flags={flags or '-'} effective={effective}")
672
+ if conditional:
673
+ lines.append("unjudgeable: DACL 含条件 ACE(XA/XD/XU),条件表达式无法解析")
674
+ return lines
675
+
676
+
677
+ def _probe_token_acl_windows(path: Path) -> list[str]:
678
+ """icacls /save 的 SDDL 取证:SID 级、语言无关、ACE 标志完整。
679
+
680
+ 失败时返回说明行 → judge 视为不可判(FAIL closed),不退回英文显示名匹配。
681
+ """
682
+ try:
683
+ with tempfile.TemporaryDirectory(prefix="devloop-acl-") as td:
684
+ dump = Path(td) / "acl.txt"
685
+ rc, _out = check_env.run(["icacls", str(path), "/save", str(dump)], timeout=30)
686
+ if rc != 0 or not dump.is_file():
687
+ return [f"note: icacls /save 失败(rc={rc}),无法取得 SID 级 ACE 证据"]
688
+ raw = dump.read_bytes()
689
+ except OSError as exc:
690
+ return [f"note: 无法读取 ACL dump({exc})"]
691
+ try:
692
+ text = raw.decode("utf-16")
693
+ except UnicodeDecodeError:
694
+ text = raw.decode("utf-8", errors="replace")
695
+ # /save 的 dump 每行一条:先文件名行,再 SDDL 行(D:...);个别版本同行以空格分隔。
696
+ sddl = ""
697
+ for line in text.splitlines():
698
+ token = line.strip()
699
+ if token.startswith("D:"):
700
+ sddl = token
701
+ break
702
+ if not sddl:
703
+ for line in text.splitlines():
704
+ token = line.strip()
705
+ if " D:" in token:
706
+ sddl = token.rsplit(" ", 1)[-1]
707
+ break
708
+ if not sddl:
709
+ return ["note: ACL dump 中未找到 SDDL"]
710
+ return _parse_sddl_acl(sddl, _current_user_sid())
711
+
712
+
713
+ def probe_token_acl(path: Path) -> list[str]:
714
+ """取 token 权限证据:Windows 走 icacls /save 的 SDDL(SID 级、语言无关);
715
+ POSIX 走 st_mode 单行。"""
716
+ path = Path(path)
717
+ if os.name == "nt":
718
+ return _probe_token_acl_windows(path)
719
+ try:
720
+ mode = stat.S_IMODE(path.stat().st_mode)
721
+ except OSError:
722
+ return []
723
+ return [f"mode={mode:o}"]
724
+
725
+
726
+ def _parse_legacy_acl_line(line: str, path: Path) -> tuple[str, set[str]] | None:
727
+ """普通 icacls 文本的一行 ACE → (主体, 标志集合);非 ACE 行 → None。
728
+
729
+ 首行可能带路径前缀(`C:\\...\\token NT AUTHORITY\\SYSTEM:(I)(F)`):只剥离与
730
+ token 路径匹配的前缀,保留 `NT AUTHORITY\\Authenticated Users` 这类含空格主体。
731
+ """
732
+ text = line.strip()
733
+ low = text.lower()
734
+ for cand in {str(path), str(path).replace("\\", "/"), str(path).replace("/", "\\")}:
735
+ if low.startswith(cand.lower()):
736
+ text = text[len(cand):].strip()
737
+ break
738
+ if ":(" not in text:
739
+ return None
740
+ principal, rest = text.split(":(", 1)
741
+ principal = principal.strip()
742
+ if not principal:
743
+ return None
744
+ tokens = {m.group(1).upper() for m in re.finditer(r"\(([^()]*)\)", "(" + rest)}
745
+ return principal, tokens
746
+
747
+
748
+ def _judge_sddl_evidence(probe_lines: list[str]) -> bool:
749
+ """归一化 SDDL 证据判定:有效 allow ACE 无宽泛 SID,且含当前用户 SID。
750
+
751
+ IN-R2:出现 `unjudgeable:` 行(条件 ACE 无法解析)→ 证据不可判 → False(fail closed)。
752
+ """
753
+ self_sid = ""
754
+ broad = user = False
755
+ for ln in probe_lines:
756
+ if ln.startswith("unjudgeable:"):
757
+ return False # 不可判证据不得产生 PASS
758
+ if ln.startswith("self-sid="):
759
+ self_sid = ln.split("=", 1)[1].strip().lower()
760
+ continue
761
+ if not ln.startswith("ace "):
762
+ continue
763
+ fields = dict(part.split("=", 1) for part in ln.split()[1:] if "=" in part)
764
+ if fields.get("effective") != "yes" or fields.get("type") != "allow":
765
+ continue # DENY / inherit-only 都不是本对象上的授予
766
+ sid = fields.get("sid", "").strip()
767
+ sid = SDDL_ALIASES.get(sid.upper(), sid).lower()
768
+ if sid in BROAD_SIDS:
769
+ broad = True
770
+ elif self_sid and sid == self_sid:
771
+ user = True
772
+ return bool(self_sid) and user and not broad
773
+
774
+
775
+ def judge_token_acl(probe_lines: list[str], path: Path) -> bool:
776
+ """Windows:有效 allow ACE 中无宽泛主体(Everyone / BUILTIN\\Users /
777
+ Authenticated Users,按 SID/别名或显示名)且含当前用户的 allow ACE;
778
+ DENY 与 inherit-only(IO)ACE 不算授予。POSIX:mode 恰为 0o600;
779
+ path 不存在一律 FAIL。"""
780
+ path = Path(path)
781
+ if not path.is_file():
782
+ return False
783
+ if not probe_lines:
784
+ return False
785
+ if os.name == "nt":
786
+ if any(ln.startswith(("ace ", "self-sid=", "unjudgeable:")) for ln in probe_lines):
787
+ return _judge_sddl_evidence(probe_lines)
788
+ # 兼容普通 icacls 文本(旧证据 / 直接调用):SID 与英文显示名双匹配 + 标志感知
789
+ user = (os.environ.get("USERNAME") or "").strip().lower()
790
+ if not user:
791
+ return False
792
+ broad = user_grant = False
793
+ for ln in probe_lines:
794
+ parsed = _parse_legacy_acl_line(ln, path)
795
+ if parsed is None:
796
+ continue
797
+ principal, tokens = parsed
798
+ if "DENY" in tokens or "IO" in tokens:
799
+ continue # 拒绝 / 仅继承 ACE 不是本对象上的授予
800
+ low = principal.lower()
801
+ if low.lstrip("*").strip() in BROAD_SIDS \
802
+ or any(p in low for p in BROAD_PRINCIPALS):
803
+ broad = True
804
+ if low.rsplit("\\", 1)[-1] == user:
805
+ user_grant = True
806
+ return user_grant and not broad
807
+ try:
808
+ mode = int(probe_lines[0].split("=", 1)[1].strip(), 8)
809
+ except (IndexError, ValueError):
810
+ return False
811
+ return mode == 0o600
812
+
813
+
814
+ def probe_hdc(inv: dict) -> tuple[str, list[str]]:
815
+ """hdc 探测:复用 check_env._resolve_hdc(path 只用于探测,不进返回值)与 run()。
816
+ 返回 (source, targets)——source ∈ missing/placeholder/deveco/oh_toolchain/inventory。"""
817
+ hdc, source = check_env._resolve_hdc(inv)
818
+ if source in ("missing", "placeholder"):
819
+ return source, []
820
+ _rc, out = check_env.run([hdc, "list", "targets"])
821
+ targets = [ln.strip() for ln in out.splitlines()
822
+ if ln.strip() and "ERROR" not in ln and "[" not in ln]
823
+ return source, targets
824
+
825
+
826
+ def judge_hdc(source: str, targets: list[str], require_device: bool) -> tuple[bool, str]:
827
+ """hdc 判定:missing → FAIL;placeholder 且无候选 → FAIL;在位无设备 →
828
+ require_device 时 FAIL、否则 WARN((False, "WARN") 由调用侧记 WARN);有设备 → PASS。"""
829
+ if source == "missing":
830
+ return False, "FAIL"
831
+ if source == "placeholder" and not targets:
832
+ return False, "FAIL"
833
+ if targets:
834
+ return True, "PASS"
835
+ return (False, "FAIL") if require_device else (False, "WARN")
836
+
837
+
838
+ def judge_auth(status: int, ops_count: int) -> bool:
839
+ """鉴权配对判定:/v1/ops HTTP 200 且 op 数 == 工具面 op 数(调用侧已做真实 Bearer 调用)。"""
840
+ return status == 200 and ops_count == len(pc_ops.ops_meta())
841
+
842
+
843
+ def run_self_check(port: int, token_file: Path, require_device: bool,
844
+ run_dir: Path | None = None) -> int:
845
+ """三点自检 + 鉴权配对,写 runs/<run-id>/results.json(缺省)或 <run_dir>/self-check.json
846
+ (显式 run_dir,不覆盖该目录 results.json)+ 四份原始输出。
847
+ 无工作区时证据落 ~/.ohos-devloop/pc_service/self-check-<ts>/(0.4 起 PC 不再需要 marker)。
848
+ rc:0=无 FAIL(WARN 允许)、1=有 FAIL、2=无法运行(参数错/token 缺失)。"""
849
+ global PASS, WARN, FAIL
850
+ PASS = WARN = FAIL = 0
851
+ token_file = Path(token_file)
852
+ started = datetime.now().astimezone().isoformat(timespec="seconds")
853
+
854
+ try:
855
+ tok = read_token(token_file)
856
+ except pc_ops.OpError as e: # token 缺失/为空:无法运行,引导 pc serve / pc token
857
+ print(f"ERROR: {e}", file=sys.stderr)
858
+ return 2
859
+
860
+ if run_dir is None:
861
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
862
+ try:
863
+ base = apply.runs_root() / f"self-check-{stamp}"
864
+ except wsroot.WorkspaceRequiredError:
865
+ base = pc_ops._pc_data() / f"self-check-{stamp}"
866
+ print(f"WARN: 无工作区,自检证据落 {base}"
867
+ "(0.4 起 PC 不再需要 ohos-workspace.yaml)", file=sys.stderr)
868
+ else:
869
+ base = Path(run_dir)
870
+ base.mkdir(parents=True, exist_ok=True)
871
+ run_id = base.name
872
+ steps: list[dict] = []
873
+
874
+ # 1) 回环监听:healthz 身份 + 非回环地址连接探测
875
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
876
+ hz = _healthz(port)
877
+ healthz_ok = isinstance(hz, dict) and hz.get("service") == "ohos-devloop-pc"
878
+ addrs = _local_ipv4s()
879
+ loop_lines = [f"healthz: {json.dumps(hz, ensure_ascii=False) if hz else '无响应或非本服务'}"]
880
+ if not addrs:
881
+ loop_lines.append("note: 无可探测非回环地址")
882
+ loop_lines += probe_loopback(port, addrs)
883
+ loop_ok = judge_loopback(healthz_ok, loop_lines)
884
+ loop_lines.append(f"judge: {'PASS' if loop_ok else 'FAIL'}")
885
+ _write_lines(base / "loopback.txt", loop_lines)
886
+ if loop_ok:
887
+ report("PASS", ITEM_LOOPBACK, f"127.0.0.1:{port} 身份匹配;非回环地址 {len(addrs)} 个均未监听")
888
+ loop_status = "pass"
889
+ else:
890
+ report("FAIL", ITEM_LOOPBACK,
891
+ f"127.0.0.1:{port} 身份不匹配或存在非回环监听(见 loopback.txt)")
892
+ loop_status = "fail"
893
+ steps.append(_step("loopback", loop_status,
894
+ f"{'身份匹配' if healthz_ok else '身份不匹配'}; 非回环探测 {len(addrs)} 地址", t0))
895
+
896
+ # 2) token 权限:icacls ACE / POSIX st_mode
897
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
898
+ acl_lines = probe_token_acl(token_file)
899
+ acl_ok = judge_token_acl(acl_lines, token_file)
900
+ acl_evidence = [f"token-file: {token_file}(长度 {token_file.stat().st_size if token_file.is_file() else 0})",
901
+ f"ACE 证据 {len(acl_lines)} 行:"] + acl_lines + [f"judge: {'PASS' if acl_ok else 'FAIL'}"]
902
+ _write_lines(base / "token-acl.txt", acl_evidence)
903
+ if acl_ok:
904
+ report("PASS", ITEM_TOKEN_ACL, f"{token_file.name} 权限受限({len(acl_lines)} 条 ACE,无宽泛主体)")
905
+ acl_status = "pass"
906
+ else:
907
+ report("FAIL", ITEM_TOKEN_ACL, f"{token_file.name} 权限过宽或不可判(见 token-acl.txt)")
908
+ acl_status = "fail"
909
+ steps.append(_step("token-acl", acl_status, f"ACE {len(acl_lines)} 行;judge={acl_ok}", t0))
910
+
911
+ # 3) 鉴权配对:真实 Bearer 调用 /v1/ops,只记状态码、op 数与版本键(CR-01:/v1/ops
912
+ # 顶层带两个版本键,与 /healthz 同源;缺键即按非预期响应计 FAIL,不打出假 PASS)
913
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
914
+ status, op_count, auth_note = 0, 0, ""
915
+ ops_versions = None
916
+ try:
917
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/ops")
918
+ req.add_header("Authorization", f"Bearer {tok}")
919
+ with urllib.request.urlopen(req, timeout=3) as r:
920
+ status = r.status
921
+ data = json.loads(r.read().decode("utf-8"))
922
+ op_count = len(data.get("ops") or [])
923
+ if isinstance(data, dict) and isinstance(data.get("ops"), list):
924
+ ops_versions = (data.get("http_api_version"), data.get("mcp_tools_version"))
925
+ except urllib.error.HTTPError as e:
926
+ status = e.code
927
+ auth_note = type(e).__name__
928
+ except Exception as e: # 连接失败/超时/非 JSON:统一记异常名,绝不打 token
929
+ auth_note = type(e).__name__
930
+ # 版本键按契约兼容规则判(WARNING-8:同 MAJOR 且 MINOR ≥ 本地,不要求相等——
931
+ # 与 pc_mcp 握手同一条规则;op 数/工具面仍由 judge_auth 精确对账)
932
+ auth_ok = judge_auth(status, op_count) and ops_versions is not None and (
933
+ versions_compatible(ops_versions[0], pc_ops.HTTP_API_VERSION)
934
+ and versions_compatible(ops_versions[1], pc_ops.MCP_TOOLS_VERSION))
935
+ auth_lines = [f"GET /v1/ops -> HTTP {status}", f"ops={op_count}",
936
+ f"versions={ops_versions[0] if ops_versions else 'missing'}/"
937
+ f"{ops_versions[1] if ops_versions else 'missing'}",
938
+ "rule: same MAJOR and MINOR >= local",
939
+ *(f"note: {auth_note}" if auth_note else ())]
940
+ auth_lines.append(f"judge: {'PASS' if auth_ok else 'FAIL'}")
941
+ _write_lines(base / "auth.txt", auth_lines)
942
+ if auth_ok:
943
+ report("PASS", ITEM_AUTH, f"/v1/ops HTTP {status},{op_count} 个 op,版本键兼容")
944
+ auth_status = "pass"
945
+ else:
946
+ report("FAIL", ITEM_AUTH,
947
+ f"/v1/ops HTTP {status},op 数 {op_count}/{len(pc_ops.ops_meta())}"
948
+ f",版本键 {ops_versions}(需同 MAJOR 且 MINOR ≥ 本地)"
949
+ "(token 不符、服务未起或契约面缺失?见 auth.txt)")
950
+ auth_status = "fail"
951
+ steps.append(_step("auth", auth_status, f"HTTP {status}, ops {op_count}", t0))
952
+
953
+ # 4) hdc + 板卡:来源解析 + list targets
954
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
955
+ try:
956
+ inv = pc_ops._inv()
957
+ except Exception: # inventory 读不到不阻断自检:按缺失判 FAIL
958
+ inv = {}
959
+ hdc_source, hdc_targets = probe_hdc(inv)
960
+ hdc_ok, hdc_level = judge_hdc(hdc_source, hdc_targets, require_device)
961
+ hdc_lines = [f"source={hdc_source}", f"targets={len(hdc_targets)}",
962
+ *hdc_targets, f"judge: {hdc_level}"]
963
+ _write_lines(base / "hdc.txt", hdc_lines)
964
+ if hdc_ok:
965
+ report("PASS", ITEM_HDC, f"hdc 在位(来源 {hdc_source}),{len(hdc_targets)} 台在线")
966
+ hdc_status = "pass"
967
+ elif hdc_level == "WARN":
968
+ report("WARN", ITEM_HDC, f"hdc 在位(来源 {hdc_source})但无在线设备(--require-device 时升级 FAIL)")
969
+ hdc_status = "warn"
970
+ else:
971
+ report("FAIL", ITEM_HDC, f"hdc 缺失或不可用(来源 {hdc_source},见 hdc.txt)")
972
+ hdc_status = "fail"
973
+ steps.append(_step("hdc", hdc_status, f"source={hdc_source}, targets={len(hdc_targets)}", t0))
974
+
975
+ outcome = "ok" if FAIL == 0 else "fail"
976
+ payload = {
977
+ "job": "pc.self-check", "run_id": run_id, "started": started,
978
+ "tool_version": apply.tool_version(),
979
+ "params": {"port": port, "require_device": require_device},
980
+ "resources": {}, "steps": steps, "outcome": outcome,
981
+ "ended": datetime.now().astimezone().isoformat(timespec="seconds"),
982
+ }
983
+ name = "results.json" if run_dir is None else "self-check.json"
984
+ with open(base / name, "w", encoding="utf-8") as f:
985
+ json.dump(payload, f, ensure_ascii=False, indent=2)
986
+ print(f"self-check 完成: outcome={outcome}(PASS {PASS} / WARN {WARN} / FAIL {FAIL})→ {base}")
987
+ return 0 if outcome == "ok" else 1
988
+
989
+
990
+ def cmd_self_check(args) -> int:
991
+ port = _port_int(args.port)
992
+ return run_self_check(port, Path(args.token_file), args.require_device)
993
+
994
+
995
+ # --------------------------------------------------------------------------- setup
996
+
997
+ def _is_inside(path: Path, root: Path) -> bool:
998
+ """路径包含判定(Windows 大小写不敏感):相等或位于 root 之下。"""
999
+ p, r = os.path.normcase(str(path)), os.path.normcase(str(root))
1000
+ return p == r or p.startswith(r + os.sep)
1001
+
1002
+
1003
+ def _run_init(target: Path, with_skills: bool = False) -> tuple[int, str]:
1004
+ """子进程复用 ws_init.py(绝对路径 + list 参数;禁止内联 init 逻辑或 shell 拼接)。
1005
+
1006
+ 0.4 起 PC 默认不展开 Agent 技能/命令(PC 不跑 Agent runtime):`--with-skills` 例外。
1007
+ """
1008
+ argv = [sys.executable, str(wsroot.PKG / "scripts" / "ws_init.py"), str(target)]
1009
+ if not with_skills:
1010
+ argv.append("--no-skills")
1011
+ rc, out, err = apply.sh(argv)
1012
+ return rc, out + err
1013
+
1014
+
1015
+ def _read_pid() -> int | None:
1016
+ """读 serve.pid(缺失/损坏 → None;复用分支据此打印停止命令)。"""
1017
+ try:
1018
+ return int((pc_ops._pc_data() / "serve.pid").read_text(encoding="utf-8").strip())
1019
+ except (OSError, ValueError):
1020
+ return None
1021
+
1022
+
1023
+ def _stop_command(pid: int) -> str:
1024
+ """平台对应的精确停止命令(仅用于 setup 自己拉起/已验明身份的 pid)。"""
1025
+ return f"taskkill /PID {pid} /F" if os.name == "nt" else f"kill {pid}"
1026
+
1027
+
1028
+ def _process_cmdline(pid: int) -> str | None:
1029
+ """读进程命令行(只用于校验 serve.pid 身份);读不到/无权限/工具缺失 → None。"""
1030
+ if pid is None or pid <= 0:
1031
+ return None
1032
+ if os.name == "nt":
1033
+ script = ("$ErrorActionPreference='Stop';"
1034
+ f"$p=Get-CimInstance Win32_Process -Filter \"ProcessId={pid}\";"
1035
+ "if($p){$p.CommandLine}")
1036
+ argv = ["powershell", "-NoProfile", "-NonInteractive", "-Command", script]
1037
+ else:
1038
+ argv = ["ps", "-p", str(pid), "-o", "args="]
1039
+ try:
1040
+ p = subprocess.run(argv, capture_output=True, text=True, encoding="utf-8",
1041
+ errors="replace", timeout=20)
1042
+ except (OSError, subprocess.SubprocessError):
1043
+ return None
1044
+ if p.returncode != 0:
1045
+ return None
1046
+ return (p.stdout or "").strip() or None
1047
+
1048
+
1049
+ def _verified_stop_command(pid: int | None, port: int) -> str | None:
1050
+ """复用分支的停止命令:仅在 pid 可证明仍是本端口上的 pc_service serve 时返回。
1051
+
1052
+ serve.pid 只由 `_spawn_service` 写入,手工 `pc serve` 既不写也不清;重启后该 PID
1053
+ 可能已被系统复用。直接打印 taskkill 有误杀无关进程的风险(WR-03):命令行必须同时
1054
+ 含 pc_service.py、serve 与 `--port <port>` 三项才认;读不到命令行(无权限/工具缺失)
1055
+ 或任一项不符 → None,调用侧改印手工停止提示,绝不给未经验证的 kill 命令。
1056
+ """
1057
+ if not pid:
1058
+ return None
1059
+ cmdline = _process_cmdline(pid)
1060
+ if not cmdline:
1061
+ return None
1062
+ if "pc_service.py" not in cmdline or "serve" not in cmdline:
1063
+ return None
1064
+ if not any(opt in cmdline for opt in (f"--port {port}", f"--port={port}")):
1065
+ return None
1066
+ return _stop_command(pid)
1067
+
1068
+
1069
+ def _write_json(path: Path, payload: dict) -> None:
1070
+ with open(path, "w", encoding="utf-8") as f:
1071
+ json.dump(payload, f, ensure_ascii=False, indent=2)
1072
+
1073
+
1074
+ def _setup_step(name: str, type_: str, status: str, detail: str, started: str) -> dict:
1075
+ """setup 步记录(apply 同形;type 区分 init/reuse/check,status 只 pass/fail)。"""
1076
+ return {"name": name, "type": type_, "status": status, "detail": detail,
1077
+ "started": started,
1078
+ "ended": datetime.now().astimezone().isoformat(timespec="seconds")}
1079
+
1080
+
1081
+ def _unique_run_dir(runs: Path, base: str) -> Path:
1082
+ """同秒重跑不覆盖既有证据:run 目录碰撞时追加 -2/-3…(幂等运行也要各自留证)。"""
1083
+ cand, n = runs / base, 2
1084
+ while cand.exists():
1085
+ cand = runs / f"{base}-{n}"
1086
+ n += 1
1087
+ return cand
1088
+
1089
+
1090
+ def _setup_results(run_dir: Path, steps: list[dict], outcome: str) -> None:
1091
+ """setup 三步链结果收口(job=pc.setup;自检明细在 run_dir/self-check.json)。"""
1092
+ started = steps[0]["started"] if steps else \
1093
+ datetime.now().astimezone().isoformat(timespec="seconds")
1094
+ payload = {
1095
+ "job": "pc.setup", "run_id": run_dir.name, "started": started,
1096
+ "tool_version": apply.tool_version(),
1097
+ "params": {}, "resources": {}, "steps": steps, "outcome": outcome,
1098
+ "ended": datetime.now().astimezone().isoformat(timespec="seconds"),
1099
+ }
1100
+ _write_json(run_dir / "results.json", payload)
1101
+
1102
+
1103
+ def _spawn_service(port: int, token_file: Path) -> int:
1104
+ """分离子进程再入 `serve`(stdio 全重定向到 serve.log,Pitfall 4);起后轮询身份。"""
1105
+ data_dir = pc_ops._pc_data()
1106
+ data_dir.mkdir(parents=True, exist_ok=True)
1107
+ log_path = data_dir / "serve.log"
1108
+ argv = [sys.executable, str(Path(__file__).resolve().parent / "pc_service.py"),
1109
+ "serve", "--port", str(port), "--token-file", str(token_file)]
1110
+ kw: dict = {}
1111
+ if os.name == "nt":
1112
+ kw["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
1113
+ else:
1114
+ kw["start_new_session"] = True
1115
+ with open(log_path, "ab") as log_fp:
1116
+ proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log_fp,
1117
+ stderr=log_fp, close_fds=True, **kw)
1118
+ (data_dir / "serve.pid").write_text(str(proc.pid), encoding="utf-8", newline="\n")
1119
+ for _ in range(20): # 20 × 0.5s = 10s 上限(T-11-09)
1120
+ hz = _healthz(port)
1121
+ if isinstance(hz, dict) and hz.get("service") == "ohos-devloop-pc":
1122
+ return proc.pid
1123
+ time.sleep(0.5)
1124
+ raise pc_ops.OpError(f"服务未在 10s 内就绪(日志: {log_path})")
1125
+
1126
+
1127
+ def cmd_setup(args) -> int:
1128
+ """空目录一条命令:init(复用 ws_init)→ 拉起/复用 PC 服务 → 复用 self-check。
1129
+
1130
+ rc:0=三步全过(WARN 允许)、1=能运行但某步失败(证据已落盘)、2=无法运行/参数错。
1131
+ 幂等:marker 存在时跳过 init(不传 --force、不重写任何工作区文件);healthz 身份命中
1132
+ 则复用已有服务。不注册任何 OS 常驻项,只写 serve.pid/serve.log 并打印停止命令。
1133
+ """
1134
+ target = ((Path.cwd() / args.dir) if args.dir else Path.cwd()).resolve()
1135
+ port = _port_int(args.port)
1136
+ token_file = Path(args.token_file)
1137
+ if _is_inside(target, wsroot.PKG.resolve()):
1138
+ print("ERROR: 目标目录在工具包内(禁止把用户数据写进 site-packages)", file=sys.stderr)
1139
+ return 2
1140
+
1141
+ started = datetime.now().astimezone().isoformat(timespec="seconds")
1142
+ run_base = f"setup-{datetime.now():%Y%m%d-%H%M%S}"
1143
+ steps: list[dict] = []
1144
+ reused = (target / wsroot.MARKER).is_file()
1145
+
1146
+ if not reused:
1147
+ rc, out = _run_init(target, with_skills=bool(getattr(args, "with_skills", False)))
1148
+ if rc != 0: # init 自身已给出非空/文件目标的可执行提示
1149
+ print(out, file=sys.stderr)
1150
+ return 2
1151
+
1152
+ old_ws = os.environ.get("OHOS_WS")
1153
+ os.environ["OHOS_WS"] = str(target)
1154
+ wsroot.reset_cache() # Pitfall 6:同一进程 init 后必须清缓存
1155
+ pid: int | None = None
1156
+ stop_cmd: str | None = None
1157
+ try:
1158
+ run_dir = _unique_run_dir(target / "runs", run_base)
1159
+ run_dir.mkdir(parents=True, exist_ok=True)
1160
+ if reused:
1161
+ (run_dir / "init.txt").write_text(
1162
+ "工作区已初始化(复用),未重写任何文件\n", encoding="utf-8", newline="\n")
1163
+ steps.append(_setup_step("init", "reuse", "pass",
1164
+ "检测到 ohos-workspace.yaml,跳过 init(未重写任何文件)",
1165
+ started))
1166
+ else:
1167
+ (run_dir / "init.txt").write_text(out, encoding="utf-8", newline="\n")
1168
+ steps.append(_setup_step("init", "init", "pass",
1169
+ f"工作区已初始化: {target}", started))
1170
+
1171
+ # 指南步骤:随包一页纸安装指南送到工作区根 INSTALL.md(已存在即保留用户改动)。
1172
+ # 字节级复制(read_bytes/write_bytes):.gitattributes `* text=auto` + Windows autocrlf
1173
+ # 使模板在工作树可能是 CRLF,文本写会转成 LF,破坏逐字节相等与 md5 对账。
1174
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
1175
+ guide_src = wsroot.PKG / "config" / "templates" / "install-guide.md"
1176
+ guide_dst = target / "INSTALL.md"
1177
+ try:
1178
+ if guide_dst.is_file():
1179
+ guide_detail = f"保留已有(未覆盖): {guide_dst}"
1180
+ guide_status = "pass"
1181
+ else:
1182
+ guide_dst.write_bytes(guide_src.read_bytes())
1183
+ guide_detail = f"已写入: {guide_dst}"
1184
+ guide_status = "pass"
1185
+ except OSError as e: # 指南缺失/不可写不阻断安装主链(不是 rc 语义的一部分)
1186
+ guide_detail = f"指南模板不可用: {e}"
1187
+ guide_status = "fail"
1188
+ print(f"WARN: {guide_detail}", file=sys.stderr)
1189
+ steps.append(_setup_step("guide", "check", guide_status, guide_detail, t0))
1190
+ print(f"指南: {guide_dst}")
1191
+
1192
+ # 第二步:起服务(幂等:先认身份,再决定复用/冲突/spawn)
1193
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
1194
+ try:
1195
+ ensure_token(token_file)
1196
+ hz = _healthz(port)
1197
+ if isinstance(hz, dict) and hz.get("service") == "ohos-devloop-pc":
1198
+ pid = _read_pid()
1199
+ stop_cmd = _verified_stop_command(pid, port) # 未经验证绝不打印 kill 命令
1200
+ _write_json(run_dir / "service.json",
1201
+ {"action": "reuse", "port": port, "pid": pid,
1202
+ "pid_verified": stop_cmd is not None})
1203
+ _write_lines(run_dir / "service.txt",
1204
+ [f"action=reuse", f"port={port}", f"pid={pid}",
1205
+ f"pid_verified={stop_cmd is not None}",
1206
+ f"healthz={json.dumps(hz, ensure_ascii=False)}"])
1207
+ if pid is not None and stop_cmd is None:
1208
+ print(f"WARN: serve.pid 记录的 pid={pid} 无法确认仍是本端口服务,"
1209
+ "不打印停止命令", file=sys.stderr)
1210
+ steps.append(_setup_step("service", "check", "pass",
1211
+ f"复用已有服务 pid={pid}", t0))
1212
+ print(f"复用已有服务 pid={pid}(http://127.0.0.1:{port})")
1213
+ elif hz is not None: # 端口有响应但不是本服务:绝不盲目 spawn 第二个监听者
1214
+ detail = (f"端口 {port} 已被非本服务占用(/healthz 身份不符)"
1215
+ "——用 --port <其他端口> 重试")
1216
+ _write_json(run_dir / "service.json",
1217
+ {"action": "conflict", "port": port, "healthz": hz})
1218
+ _write_lines(run_dir / "service.txt",
1219
+ [f"action=conflict", f"port={port}",
1220
+ f"healthz={json.dumps(hz, ensure_ascii=False)}"])
1221
+ steps.append(_setup_step("service", "check", "fail", detail, t0))
1222
+ _setup_results(run_dir, steps, "fail")
1223
+ print(f"ERROR: {detail}", file=sys.stderr)
1224
+ return 1
1225
+ else:
1226
+ pid = _spawn_service(port, token_file)
1227
+ stop_cmd = _stop_command(pid) # setup 自己拉起:pid 可信
1228
+ _write_json(run_dir / "service.json",
1229
+ {"action": "spawn", "port": port, "pid": pid})
1230
+ _write_lines(run_dir / "service.txt",
1231
+ [f"action=spawn", f"port={port}", f"pid={pid}",
1232
+ f"log={pc_ops._pc_data() / 'serve.log'}"])
1233
+ steps.append(_setup_step("service", "check", "pass",
1234
+ f"已拉起服务 pid={pid}", t0))
1235
+ except (pc_ops.OpError, OSError) as e:
1236
+ detail = str(e)
1237
+ _write_json(run_dir / "service.json", {"action": "fail", "port": port})
1238
+ _write_lines(run_dir / "service.txt",
1239
+ [f"action=fail", f"port={port}", f"error={detail}"])
1240
+ steps.append(_setup_step("service", "check", "fail", detail, t0))
1241
+ _setup_results(run_dir, steps, "fail")
1242
+ print(f"ERROR: {detail}", file=sys.stderr)
1243
+ print(f"提示: 端口 {port} 可能被其他程序占用,可用 --port 换端口重试",
1244
+ file=sys.stderr)
1245
+ return 1
1246
+
1247
+ # 第三步:自检(同一 run 目录;self-check.json 不覆盖 setup 的 results.json)
1248
+ t0 = datetime.now().astimezone().isoformat(timespec="seconds")
1249
+ try:
1250
+ sc_rc = run_self_check(port, token_file, args.require_device, run_dir=run_dir)
1251
+ except Exception as e: # 自检自身异常也必须留证,绝不冒 traceback
1252
+ sc_rc = 1
1253
+ (run_dir / "self-check-error.txt").write_text(repr(e) + "\n", encoding="utf-8")
1254
+ steps.append(_setup_step("self-check", "check",
1255
+ "pass" if sc_rc == 0 else "fail",
1256
+ f"rc={sc_rc}(明细: {run_dir / 'self-check.json'})", t0))
1257
+ outcome = "ok" if sc_rc == 0 else "fail"
1258
+ _setup_results(run_dir, steps, outcome)
1259
+
1260
+ print("")
1261
+ print(f"服务地址: http://127.0.0.1:{port}")
1262
+ print(f"token 文件: {token_file}(值不打印;pc token --show 可查看)")
1263
+ print(f"证据目录: {run_dir}")
1264
+ if stop_cmd is not None:
1265
+ print(f"停止命令: {stop_cmd}")
1266
+ else:
1267
+ print("停止: 当前服务非 setup 拉起或 serve.pid 已失效,请在启动它的终端停止")
1268
+ print(f"setup 完成: outcome={outcome}({run_dir / 'results.json'})")
1269
+ return 0 if outcome == "ok" else 1
1270
+ finally:
1271
+ if old_ws is None:
1272
+ os.environ.pop("OHOS_WS", None)
1273
+ else:
1274
+ os.environ["OHOS_WS"] = old_ws
1275
+ wsroot.reset_cache()
1276
+
1277
+
1278
+ def main(argv: list[str] | None = None) -> int:
1279
+ ap = argparse.ArgumentParser(description="PC 操作服务(devloop-pc)")
1280
+ sub = ap.add_subparsers(dest="cmd", required=True)
1281
+ sp = sub.add_parser("serve", help="起 HTTP 服务(只 bind 127.0.0.1)")
1282
+ sp.add_argument("--port", default=str(DEFAULT_PORT),
1283
+ help="端口(0 = 随机,stdout 打印 PORT=/TOKEN_FILE= 供解析)")
1284
+ sp.add_argument("--token-file", default=str(TOKEN_FILE))
1285
+ sp.set_defaults(func=cmd_serve)
1286
+ sp = sub.add_parser("token", help="生成/查看服务 token")
1287
+ sp.add_argument("--show", action="store_true", help="打印 token 值(带告警)")
1288
+ sp.add_argument("--token-file", default=str(TOKEN_FILE))
1289
+ sp.set_defaults(func=cmd_token)
1290
+ sp = sub.add_parser("tunnel", help="PC 主动隧道(反向 HTTP + 可选模拟器 VNC 正向,仅回环)")
1291
+ sp.add_argument("--server", default="", help="inventory servers 条目名(缺省首条)")
1292
+ sp.add_argument("--port", default=str(DEFAULT_PORT))
1293
+ sp.add_argument("--vnc", nargs="?", const="auto", default=None,
1294
+ help="同时转发模拟器 VNC 到本机(缺省本地端口取 inventory "
1295
+ "emulators.<首条>.vnc_local_port,再缺省 15921;模拟器侧 5921)")
1296
+ sp.add_argument("--print", action="store_true", help="只打印 ssh 命令不执行")
1297
+ sp.set_defaults(func=cmd_tunnel)
1298
+ sp = sub.add_parser("ops", help="打印操作清单 / MCP tool manifest")
1299
+ sp.add_argument("--json", action="store_true", help="输出 tool_manifest JSON")
1300
+ sp.set_defaults(func=cmd_ops)
1301
+ sp = sub.add_parser("check", help="经 SSH 在服务器上验证隧道/服务/token")
1302
+ sp.add_argument("--server", default="", help="inventory servers 条目名(缺省首条)")
1303
+ sp.add_argument("--port", default=str(DEFAULT_PORT))
1304
+ sp.add_argument("--remote-token", default="~/devloop/pc_token")
1305
+ sp.set_defaults(func=cmd_check)
1306
+ sp = sub.add_parser("setup", help="空目录一键:初始化工作区 → 起 PC 服务 → 本地自检")
1307
+ sp.add_argument("dir", nargs="?", default=None, help="目标目录(缺省当前目录)")
1308
+ sp.add_argument("--port", default=str(DEFAULT_PORT))
1309
+ sp.add_argument("--token-file", default=str(TOKEN_FILE))
1310
+ sp.add_argument("--require-device", action="store_true",
1311
+ help="hdc 在位但无在线设备时升级为 FAIL")
1312
+ sp.add_argument("--with-skills", action="store_true",
1313
+ help="同时把五技能/七命令展开到 ~/.agents/(PC 本机也跑 Agent 时用;缺省不展开)")
1314
+ sp.set_defaults(func=cmd_setup)
1315
+ sp = sub.add_parser("self-check", help="工作区内三点自检(回环/token 权限/hdc)并写 runs/ 证据")
1316
+ sp.add_argument("--port", default=str(DEFAULT_PORT))
1317
+ sp.add_argument("--token-file", default=str(TOKEN_FILE))
1318
+ sp.add_argument("--require-device", action="store_true",
1319
+ help="hdc 在位但无在线设备时升级为 FAIL")
1320
+ sp.set_defaults(func=cmd_self_check)
1321
+ args = ap.parse_args(argv)
1322
+ try:
1323
+ return args.func(args)
1324
+ except pc_ops.OpError as e:
1325
+ print(f"ERROR: {e}", file=sys.stderr)
1326
+ return 2
1327
+
1328
+
1329
+ if __name__ == "__main__":
1330
+ try:
1331
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
1332
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
1333
+ except Exception:
1334
+ pass
1335
+ try:
1336
+ rc = main()
1337
+ except wsroot.WorkspaceRequiredError as e: # 安装态无工作区:引导 init,rc==2
1338
+ print(f"ERROR: {e}", file=sys.stderr)
1339
+ rc = 2
1340
+ sys.exit(rc)