vod-devkit 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/QUICKSTART.md +1 -1
  3. package/README.en.md +190 -56
  4. package/README.md +210 -56
  5. package/bin/vod-devkit +502 -460
  6. package/contract/tools.schema.json +114 -7
  7. package/integrations/codeartsdoer/host.json +11 -0
  8. package/integrations/codex/host.json +20 -0
  9. package/integrations/dsh/host.json +15 -0
  10. package/integrations/hermes/host.json +20 -0
  11. package/integrations/opencode/command/vod-doctor.md +10 -0
  12. package/integrations/opencode/host.json +28 -0
  13. package/package.json +13 -10
  14. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  15. package/plugins/vod-devkit/build-info.json +3 -3
  16. package/plugins/vod-devkit/skills/vod-core/SKILL.md +43 -15
  17. package/plugins/vod-devkit/skills/vod-core/references/acceptance-criteria.md +9 -0
  18. package/plugins/vod-devkit/skills/vod-core/references/verification-method.md +29 -0
  19. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +57 -11
  20. package/plugins/vod-devkit/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  21. package/plugins/vod-devkit/skills/vod-feedback-collect/references/verification-method.md +31 -0
  22. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +3 -1
  23. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +22 -1
  24. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  25. package/plugins/vod-devkit/vod_mcp/attribution.py +378 -0
  26. package/plugins/vod-devkit/vod_mcp/config_forms.py +154 -0
  27. package/plugins/vod-devkit/vod_mcp/guardrails.py +25 -0
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/__init__.py +26 -0
  29. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +73 -0
  30. package/plugins/vod-devkit/vod_mcp/host_adapters/codearts.py +57 -0
  31. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +209 -0
  32. package/plugins/vod-devkit/vod_mcp/host_adapters/dsh.py +176 -0
  33. package/plugins/vod-devkit/vod_mcp/host_adapters/generic.py +132 -0
  34. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +76 -0
  35. package/plugins/vod-devkit/vod_mcp/host_adapters/opencode.py +52 -0
  36. package/plugins/vod-devkit/vod_mcp/hosts.py +100 -0
  37. package/plugins/vod-devkit/vod_mcp/packs.py +19 -3
  38. package/plugins/vod-devkit/vod_mcp/payload.py +174 -0
  39. package/plugins/vod-devkit/vod_mcp/remote_app.py +100 -0
  40. package/plugins/vod-devkit/vod_mcp/server.py +43 -16
  41. package/plugins/vod-devkit/vod_mcp/skills_registry.py +124 -0
  42. package/plugins/vod-devkit/vod_mcp/tools.py +455 -55
  43. package/plugins/vod-devkit/vod_mcp/transport_remote.py +289 -0
  44. package/plugins/vod-devkit/vod_mcp/update_check.py +133 -0
  45. package/skills/vod-core/SKILL.md +43 -15
  46. package/skills/vod-core/references/acceptance-criteria.md +9 -0
  47. package/skills/vod-core/references/verification-method.md +29 -0
  48. package/skills/vod-feedback-collect/SKILL.md +57 -11
  49. package/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  50. package/skills/vod-feedback-collect/references/verification-method.md +31 -0
  51. package/skills/vod-problem-classification-rules/SKILL.md +3 -1
  52. package/skills/vod-scoring-rules/SKILL.md +22 -1
  53. package/vod_mcp/__init__.py +1 -1
  54. package/vod_mcp/attribution.py +378 -0
  55. package/vod_mcp/config_forms.py +154 -0
  56. package/vod_mcp/guardrails.py +25 -0
  57. package/vod_mcp/host_adapters/__init__.py +26 -0
  58. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  59. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  60. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-314.pyc +0 -0
  61. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  62. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-314.pyc +0 -0
  63. package/vod_mcp/host_adapters/__pycache__/generic.cpython-314.pyc +0 -0
  64. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  65. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-314.pyc +0 -0
  66. package/vod_mcp/host_adapters/base.py +73 -0
  67. package/vod_mcp/host_adapters/codearts.py +57 -0
  68. package/vod_mcp/host_adapters/codex.py +209 -0
  69. package/vod_mcp/host_adapters/dsh.py +176 -0
  70. package/vod_mcp/host_adapters/generic.py +132 -0
  71. package/vod_mcp/host_adapters/hermes.py +76 -0
  72. package/vod_mcp/host_adapters/opencode.py +52 -0
  73. package/vod_mcp/hosts.py +100 -0
  74. package/vod_mcp/packs.py +19 -3
  75. package/vod_mcp/payload.py +174 -0
  76. package/vod_mcp/remote_app.py +100 -0
  77. package/vod_mcp/server.py +43 -16
  78. package/vod_mcp/skills_registry.py +124 -0
  79. package/vod_mcp/tools.py +455 -55
  80. package/vod_mcp/transport_remote.py +289 -0
  81. package/vod_mcp/update_check.py +133 -0
@@ -0,0 +1,289 @@
1
+ """远程面 HTTP 外壳(Streamable HTTP):形态逐项对齐 huaweicloud-devkit。
2
+
3
+ devkit 的契约(mcp-server-remote.ts + test/remote-mcp-server.test.ts 实测),
4
+ 本文件照抄行为,不另发明:
5
+
6
+ POST → Streamable HTTP(官方 SDK,stateless + json_response)
7
+ GET → 405 Allow: POST, OPTIONS("the shell keeps the method filter")
8
+ OPTIONS → 204 + Access-Control-Allow-Origin: *
9
+ 通知(无 id)→ 202
10
+ 坏 JSON → 400 -32700
11
+ 默认 127.0.0.1:9528,--port/--host 可改;无内建鉴权
12
+
13
+ 实现手段的差异(唯一):devkit 用 @modelcontextprotocol/sdk + node:http 直接
14
+ 拿 WebStandard Request;Python SDK 的入口是 ASGI(StreamableHTTPSessionManager
15
+ .handle_request(scope, receive, send)),而本仓不引入 ASGI 服务器,所以这里
16
+ 用一个小的 ASGI 适配层把 stdlib http.server 的请求转成 scope/receive/send。
17
+ 协议处理仍然全部在 SDK 里,与 devkit 同源。
18
+
19
+ 身份:请求头 Authorization: Bearer <key> 逐请求注入(见 tools._REQ_KEY),
20
+ 不落盘、不进 env;插件不代签身份——缺 key 时 submit 结构化拒绝。
21
+ """
22
+ import asyncio
23
+ import json
24
+ import sys
25
+ import threading
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+
28
+ DEFAULT_HOST = "127.0.0.1"
29
+ DEFAULT_PORT = 9528
30
+ MAX_BODY = 4 * 1024 * 1024
31
+ LOOPBACK = ("127.0.0.1", "localhost", "::1")
32
+
33
+
34
+ class RemoteRuntime:
35
+ """持有 asyncio 事件循环 + SDK session manager 的生命周期。"""
36
+
37
+ def __init__(self, host: str, port: int):
38
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
39
+ from vod_mcp.remote_app import build_server
40
+
41
+ self.host, self.port = host, port
42
+ self._loop = asyncio.new_event_loop()
43
+ # stateless + json_response:与 devkit 的 WebStandardStreamableHTTPServerTransport
44
+ # ({sessionIdGenerator: undefined, enableJsonResponse: true}) 等价
45
+ self.manager = StreamableHTTPSessionManager(
46
+ app=build_server(remote=True), json_response=True, stateless=True)
47
+ self._ready = threading.Event()
48
+ self._thread = threading.Thread(target=self._serve_loop, daemon=True)
49
+
50
+ def _serve_loop(self):
51
+ asyncio.set_event_loop(self._loop)
52
+
53
+ async def run():
54
+ async with self.manager.run():
55
+ self._ready.set()
56
+ await asyncio.Event().wait() # 直到进程退出
57
+
58
+ self._loop.run_until_complete(run())
59
+
60
+ def start(self):
61
+ self._thread.start()
62
+ if not self._ready.wait(timeout=15):
63
+ raise RuntimeError("MCP session manager 启动超时")
64
+
65
+ def request(self, scope: dict, body: bytes, sink, timeout: float = 60) -> None:
66
+ """把一次 HTTP 请求投递进事件循环,响应**逐块下沉**给 sink。
67
+
68
+ sink.start(status, headers) / sink.body(bytes) / sink.end()。
69
+ 逐块而不是攒全再写:devkit 的 shell 也是 `for await (chunk of
70
+ response.body) res.write(chunk)`——SSE 这种长响应攒全再写等于把流式
71
+ 语义废掉(客户端一个字节都看不到,直到响应结束)。
72
+ """
73
+ state = {"body_sent": False}
74
+
75
+ async def receive():
76
+ if state["body_sent"]:
77
+ return {"type": "http.disconnect"}
78
+ state["body_sent"] = True
79
+ return {"type": "http.request", "body": body, "more_body": False}
80
+
81
+ async def send(message):
82
+ if message["type"] == "http.response.start":
83
+ headers = [(k.decode() if isinstance(k, bytes) else k,
84
+ v.decode() if isinstance(v, bytes) else v)
85
+ for k, v in message.get("headers", [])]
86
+ sink.start(message["status"], headers)
87
+ elif message["type"] == "http.response.body":
88
+ chunk = message.get("body") or b""
89
+ if chunk:
90
+ sink.body(chunk)
91
+
92
+ async def run():
93
+ try:
94
+ await self.manager.handle_request(scope, receive, send)
95
+ finally:
96
+ sink.end()
97
+
98
+ fut = asyncio.run_coroutine_threadsafe(run(), self._loop)
99
+ try:
100
+ fut.result(timeout=timeout)
101
+ except Exception as e: # 传输层异常:写 stderr 并让外壳答 500/断连
102
+ sys.stderr.write(f"remote transport error: {e}\n")
103
+ raise
104
+
105
+
106
+ def _normalize_headers(handler) -> list:
107
+ """把请求头规范到 SDK 能接的形态——逐条照 devkit 的外壳做法。
108
+
109
+ devkit 在构造 `Request` 前做两件事(mcp-server-remote.ts):
110
+ ① 缺 content-type 或 `text/plain*` → 覆盖成 `application/json`
111
+ (裸 `curl -d` 与 undici 默认体不因此吃 415);
112
+ ② 缺 accept → 补 `application/json, text/event-stream`
113
+ (否则 SDK 的 accept 协商会 406)。
114
+ 这两条不是"宽松",是让最小客户端也能跑通同一份契约。
115
+ """
116
+ headers = []
117
+ ctype = (handler.headers.get("Content-Type") or "").strip()
118
+ if not ctype or ctype.lower().startswith("text/plain"):
119
+ ctype = "application/json"
120
+ seen_ctype = False
121
+ for k, v in handler.headers.items():
122
+ lk = k.lower()
123
+ if lk == "content-type":
124
+ seen_ctype = True
125
+ headers.append((b"content-type", ctype.encode()))
126
+ continue
127
+ headers.append((lk.encode(), str(v).encode()))
128
+ if not seen_ctype:
129
+ headers.append((b"content-type", ctype.encode()))
130
+ if not handler.headers.get("Accept"):
131
+ headers.append((b"accept", b"application/json, text/event-stream"))
132
+ return headers
133
+
134
+
135
+ def _scope(handler, body: bytes) -> dict:
136
+ from urllib.parse import urlsplit
137
+ parts = urlsplit(handler.path)
138
+ return {
139
+ "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
140
+ "method": handler.command, "scheme": "http",
141
+ "path": parts.path or "/", "raw_path": (parts.path or "/").encode(),
142
+ "query_string": (parts.query or "").encode(),
143
+ "headers": _normalize_headers(handler),
144
+ "client": (handler.client_address[0], handler.client_address[1]),
145
+ "server": (handler.server.server_address[0], handler.server.server_address[1]),
146
+ "root_path": "",
147
+ }
148
+
149
+
150
+ class _StreamSink:
151
+ """把 ASGI 的 send 回调落成 HTTP 响应字节流(逐块,不攒全)。
152
+
153
+ 与 devkit 的 `for await (chunk of response.body) res.write(chunk)` 等价:
154
+ - 响应头里有 content-length → 原样写;
155
+ - 没有(SSE 这类流式响应)→ 用 chunked 分帧,客户端能立刻收到字节。
156
+ """
157
+
158
+ def __init__(self, handler):
159
+ self.h = handler
160
+ self.started = False
161
+ self.chunked = False
162
+ self.closed = False
163
+
164
+ def start(self, status, headers):
165
+ h = self.h
166
+ h.send_response_only(status)
167
+ hdrs = [(k, v) for k, v in headers if k.lower() != "transfer-encoding"]
168
+ self.chunked = not any(k.lower() == "content-length" for k, _ in hdrs)
169
+ for k, v in hdrs:
170
+ h.send_header(k, v)
171
+ h._cors()
172
+ if self.chunked:
173
+ h.send_header("Transfer-Encoding", "chunked")
174
+ h.end_headers()
175
+ h.wfile.flush()
176
+ self.started = True
177
+
178
+ def body(self, chunk: bytes):
179
+ if not self.started:
180
+ raise RuntimeError("ASGI body 先于 response.start")
181
+ if self.chunked:
182
+ self.h.wfile.write(f"{len(chunk):X}\r\n".encode() + chunk + b"\r\n")
183
+ else:
184
+ self.h.wfile.write(chunk)
185
+ self.h.wfile.flush()
186
+
187
+ def end(self):
188
+ if not self.started or self.closed:
189
+ return
190
+ self.closed = True
191
+ if self.chunked:
192
+ self.h.wfile.write(b"0\r\n\r\n")
193
+ self.h.wfile.flush()
194
+
195
+
196
+ class _Handler(BaseHTTPRequestHandler):
197
+ protocol_version = "HTTP/1.1"
198
+ server_version = "vod-devkit-mcp"
199
+
200
+ def log_message(self, fmt, *args): # 静默:日志走 /tmp/vod_mcp_server.log
201
+ pass
202
+
203
+ def _cors(self):
204
+ self.send_header("Access-Control-Allow-Origin", "*")
205
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
206
+ self.send_header("Access-Control-Allow-Headers",
207
+ "Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization")
208
+ self.send_header("Access-Control-Expose-Headers",
209
+ "MCP-Protocol-Version, Mcp-Session-Id")
210
+
211
+ def _empty(self, code, extra=None):
212
+ self.send_response(code)
213
+ for k, v in (extra or {}).items():
214
+ self.send_header(k, v)
215
+ self._cors()
216
+ self.send_header("Content-Length", "0")
217
+ self.end_headers()
218
+
219
+ def _json(self, code, payload):
220
+ data = json.dumps(payload, ensure_ascii=False).encode()
221
+ self.send_response(code)
222
+ self.send_header("Content-Type", "application/json")
223
+ self.send_header("Content-Length", str(len(data)))
224
+ self._cors()
225
+ self.end_headers()
226
+ self.wfile.write(data)
227
+
228
+ def do_OPTIONS(self):
229
+ self._empty(204)
230
+
231
+ def do_GET(self):
232
+ # 与 devkit 同契约:GET 不进传输层(SDK 会把它变成 SSE 长连)
233
+ self._empty(405, {"Allow": "POST, OPTIONS"})
234
+
235
+ def do_POST(self):
236
+ length = int(self.headers.get("Content-Length") or 0)
237
+ if length <= 0 or length > MAX_BODY:
238
+ self._json(400, {"jsonrpc": "2.0", "id": None,
239
+ "error": {"code": -32700, "message": "空或超大请求体"}})
240
+ return
241
+ body = self.rfile.read(length)
242
+ try:
243
+ message = json.loads(body.decode("utf-8", "replace"))
244
+ except json.JSONDecodeError:
245
+ self._json(400, {"jsonrpc": "2.0", "id": None,
246
+ "error": {"code": -32700, "message": "Parse error"}})
247
+ return
248
+ # 通知(含 notifications/initialized):不构造 transport,直接 202
249
+ #(devkit 同样的短路,保留 devkit 的 202 契约)
250
+ if isinstance(message, dict) and "id" not in message:
251
+ self._empty(202)
252
+ return
253
+ raw_auth = (self.headers.get("Authorization") or "").strip()
254
+ key = raw_auth[7:].strip() if raw_auth.lower().startswith("bearer ") else ""
255
+
256
+ from vod_mcp import tools
257
+ sink = _StreamSink(self)
258
+ tok_key = tools._REQ_KEY.set(key or None)
259
+ tok_face = tools._SERVER_FACE.set(True)
260
+ try:
261
+ self.server.runtime.request(_scope(self, body), body, sink)
262
+ except Exception as e: # 传输层异常:能答就答 500,已经流出去就断连
263
+ if not sink.started:
264
+ self._json(500, {"jsonrpc": "2.0", "id": None,
265
+ "error": {"code": -32603, "message": str(e)}})
266
+ return
267
+ finally:
268
+ tools._SERVER_FACE.reset(tok_face)
269
+ tools._REQ_KEY.reset(tok_key)
270
+
271
+
272
+ def serve(host: str, port: int) -> int:
273
+ if host not in LOOPBACK:
274
+ print(f"[vod-devkit] 警告:远程 MCP 绑定非回环地址 {host}——本进程无内建鉴权,"
275
+ "不要把它匿名暴露到公网;TLS 与身份校验应由反代承担。", file=sys.stderr)
276
+ runtime = RemoteRuntime(host, port)
277
+ runtime.start()
278
+ httpd = ThreadingHTTPServer((host, port), _Handler)
279
+ httpd.daemon_threads = True
280
+ httpd.runtime = runtime
281
+ real_port = httpd.server_address[1]
282
+ print(f"vod-devkit MCP server (remote) listening on {host}:{real_port}", file=sys.stderr)
283
+ try:
284
+ httpd.serve_forever()
285
+ except KeyboardInterrupt:
286
+ pass
287
+ finally:
288
+ httpd.server_close()
289
+ return 0
@@ -0,0 +1,133 @@
1
+ """版本更新检查(devkit update-check/upgrade 的裁剪版:只提醒,不自升级)。
2
+
3
+ 为什么只提醒:本插件有两种分发形态,preset 形态**禁止自更新**(插件版本随
4
+ agent 发版管理,D-key-guard-3②)。所以升级动作永远是 install/update,工具
5
+ 只负责回答"我这台是不是旧了",绝不下载、不解包、不改盘。
6
+
7
+ 四个约束:
8
+ - 一次会话只打扰一次 + 拒绝后冷却 3 天(devkit 同款);状态落 runtime.json。
9
+ - **skip-version**(devkit update-skip 裁剪版):用户明确说"这个版本不要提醒"时记
10
+ 住该版本号,只压这一个版本——下个版本照常提醒(永久静音的危害大于打扰)。
11
+ - 网络失败静默降级(离线/内网环境必须可用),不阻塞任何采集链。
12
+ - preset 形态完全不发外呼。
13
+ """
14
+ import datetime
15
+ import json
16
+ import urllib.request
17
+
18
+ REGISTRY = "https://registry.npmjs.org/vod-devkit/latest"
19
+ CACHE_TTL_HOURS = 24
20
+ DISMISS_DAYS = 3
21
+
22
+
23
+ def _now():
24
+ return datetime.datetime.now()
25
+
26
+
27
+ def _fetch_latest(timeout=3) -> str | None:
28
+ """查 npm registry 的 latest 版本;任何失败返回 None(永不抛出)。"""
29
+ try:
30
+ req = urllib.request.Request(REGISTRY, headers={"accept": "application/json",
31
+ "user-agent": "vod-devkit"})
32
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
33
+ data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
34
+ v = data.get("version")
35
+ return str(v) if v else None
36
+ except Exception:
37
+ return None
38
+
39
+
40
+ def _version_tuple(v: str) -> tuple:
41
+ """宽松 semver:只比数字段,预发布后缀按 0 处理(0.4.4-rc1 视作 0.4.4)。"""
42
+ core = str(v or "").split("-")[0].split("+")[0]
43
+ out = []
44
+ for part in core.split(".")[:3]:
45
+ try:
46
+ out.append(int(part))
47
+ except ValueError:
48
+ out.append(0)
49
+ while len(out) < 3:
50
+ out.append(0)
51
+ return tuple(out)
52
+
53
+
54
+ def check(params: dict | None = None) -> dict:
55
+ from vod_mcp import __version__, tools
56
+ params = params or {}
57
+ dismiss = bool(params.get("dismiss"))
58
+ skip = bool(params.get("skip"))
59
+ clear_skip = bool(params.get("clearSkip"))
60
+ cfg = tools._runtime_cfg()
61
+ state = cfg.get("update_check") or {}
62
+ now = _now()
63
+
64
+ if tools._distribution() == "preset":
65
+ return {"currentVersion": __version__, "latestVersion": None,
66
+ "updateAvailable": False, "checked": False,
67
+ "note": "本装机为产品分发形态(preset),版本随 agent 发版管理,"
68
+ "不做外呼检查。升级请联系产品提供方。"}
69
+
70
+ if clear_skip:
71
+ tools._save_runtime({"update_check": {k: v for k, v in state.items()
72
+ if k != "skipVersion"}})
73
+ return {"currentVersion": __version__, "latestVersion": state.get("latestVersion"),
74
+ "updateAvailable": False, "checked": False,
75
+ "note": "已清除版本跳过设置,下次检查恢复正常提醒。"}
76
+
77
+ if skip:
78
+ latest_seen = state.get("latestVersion") or _fetch_latest()
79
+ if not latest_seen:
80
+ return {"currentVersion": __version__, "latestVersion": None,
81
+ "updateAvailable": False, "checked": False,
82
+ "note": "版本检查不可达,无法记录跳过版本;不影响采集,稍后重试即可。"}
83
+ tools._save_runtime({"update_check": {**state, "skipVersion": latest_seen}})
84
+ return {"currentVersion": __version__, "latestVersion": latest_seen,
85
+ "updateAvailable": False, "checked": False,
86
+ "note": f"已跳过 v{latest_seen}:只压这一个版本,下个版本仍会提醒"
87
+ f"(clearSkip=true 可撤销)。"}
88
+
89
+ dismissed_until = state.get("dismissedUntil")
90
+ if dismiss:
91
+ until = (now + datetime.timedelta(days=DISMISS_DAYS)).date().isoformat()
92
+ tools._save_runtime({"update_check": {**state, "dismissedUntil": until}})
93
+ return {"currentVersion": __version__, "latestVersion": state.get("latestVersion"),
94
+ "updateAvailable": False, "checked": False,
95
+ "note": f"已记录:{DISMISS_DAYS} 天内不再提醒(至 {until})。"}
96
+
97
+ if dismissed_until and now.date().isoformat() < dismissed_until:
98
+ return {"currentVersion": __version__,
99
+ "latestVersion": state.get("latestVersion"),
100
+ "updateAvailable": False, "checked": False,
101
+ "note": f"用户此前已选择跳过(至 {dismissed_until}),本期不再提醒。"}
102
+
103
+ cached_at = state.get("checkedAt")
104
+ fresh = False
105
+ if cached_at:
106
+ try:
107
+ age = (now - datetime.datetime.fromisoformat(cached_at)).total_seconds()
108
+ fresh = age < CACHE_TTL_HOURS * 3600
109
+ except ValueError:
110
+ fresh = False
111
+ latest = state.get("latestVersion") if fresh else _fetch_latest()
112
+ if latest is None:
113
+ return {"currentVersion": __version__, "latestVersion": None,
114
+ "updateAvailable": False, "checked": False,
115
+ "note": "版本检查不可达(离线/内网正常现象),不影响采集;稍后重试即可。"}
116
+
117
+ if not fresh:
118
+ tools._save_runtime({"update_check": {**state, "checkedAt": now.isoformat(
119
+ timespec="seconds"), "latestVersion": latest}})
120
+ newer = _version_tuple(latest) > _version_tuple(__version__)
121
+ skipped = bool(state.get("skipVersion")) and state["skipVersion"] == latest
122
+ out = {"currentVersion": __version__, "latestVersion": latest,
123
+ "updateAvailable": newer and not skipped, "checked": True,
124
+ "note": ("有新版本可用:重跑 install(幂等原位更新)或 vod-devkit update。"
125
+ "用户不想被打扰时用 dismiss=true 跳过 3 天。") if newer else
126
+ "已是最新版本。"}
127
+ if skipped and newer:
128
+ out["skippedVersion"] = latest
129
+ out["note"] = (f"v{latest} 已被用户跳过(skip-version),本期不提醒;"
130
+ f"clearSkip=true 可恢复。")
131
+ if out["updateAvailable"]:
132
+ out["upgradeCommand"] = "vod-devkit update # 或重跑 install(同一行装命令)"
133
+ return out