fmode-artifact-push.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. #!/usr/bin/env python3
  2. """fmode-artifact-push.py — 一步做完 report + enqueueArtifact + drain + 回读校验
  3. 用法:
  4. fmode-artifact-push.py push --files /opt/data/work/a.md [/b.pdf ...] \
  5. [--title T] [--summary S] [--agent-id ID] [--no-drain]
  6. 链路(缺一不可):
  7. ① action=report -> 建 Deliverable 记录,返回 id == deliverableId
  8. ② action=enqueueArtifact -> 入队(deliverableId/agentId/source/filename/index)
  9. ③ action=pendingArtifacts -> 取签名 uploadUrl,PUT 文件,ackArtifact(ok)
  10. ④ curl publicUrl 回读 -> 字节数/md5 必须与本地产物一致才算成功
  11. 退出码: 0 全部拿到 https 且内容一致; 1 任一步失败(详细信息打 stdout)
  12. """
  13. import argparse
  14. import hashlib
  15. import json
  16. import os
  17. import socket
  18. import ssl
  19. import sys
  20. import urllib.error
  21. import urllib.request
  22. BASE = "https://server.fmode.cn/api/functions"
  23. FN = "lfYlgU7SkK"
  24. DEFAULT_AGENT_ID = "agent-node-lj-test"
  25. def _data_home():
  26. return os.environ.get("HERMES_HOME") or "/opt/data"
  27. def _read_cred(key):
  28. """容器 s6 环境文件 → 数据目录 .fmode/ 小写名 → 进程环境。"""
  29. for p in ("/run/s6/container_environment/" + key,
  30. os.path.join(_data_home(), ".fmode", key.lower())):
  31. try:
  32. v = open(p).read().strip()
  33. except Exception:
  34. continue
  35. if v:
  36. return v
  37. return (os.environ.get(key) or "").strip()
  38. def _session_token():
  39. """过门会话(2026-12-04 双 Token):平台入口只认 Parse 会话。"""
  40. t = _read_cred("FMODE_SESSION_TOKEN")
  41. if t:
  42. return t
  43. # 老容器兜底:数据目录里的旧用户配置
  44. for p in (os.path.join(_data_home(), ".fmode/config/user.json"),):
  45. try:
  46. d = json.loads(open(p).read())
  47. except Exception:
  48. continue
  49. for k in ("sessionToken", "session_token", "token"):
  50. if d.get(k):
  51. return d[k]
  52. raise SystemExit("[push] FATAL: 找不到 FMODE_SESSION_TOKEN")
  53. def _access_token():
  54. """身份与有效期判定凭证;老容器没有时返回空 → 云函数走 owner 回落。"""
  55. return _read_cred("FMODE_ACCESS_TOKEN")
  56. TOK = _session_token()
  57. ACCESS = _access_token()
  58. def call(params):
  59. if ACCESS:
  60. params = dict(params or {}, accessToken=ACCESS)
  61. body = json.dumps({"id": FN, "token": TOK, "params": params}).encode()
  62. req = urllib.request.Request(BASE, data=body, headers={
  63. "Content-Type": "application/json",
  64. "X-Parse-Application-Id": "ncloudmaster"})
  65. try:
  66. with urllib.request.urlopen(req, timeout=30) as r:
  67. return json.loads(r.read())
  68. except urllib.error.HTTPError as e:
  69. return {"code": e.code, "error": e.read().decode("utf-8", "replace")[:400]}
  70. except Exception as e:
  71. return {"code": -1, "error": str(e)[:400]}
  72. def md5_bytes(b):
  73. return hashlib.md5(b).hexdigest()
  74. def put_signed_url(url, data, headers, timeout=180):
  75. """PUT to a signed OBS URL, sending the path as RAW UTF-8 bytes.
  76. 中文/非 ASCII 文件名会让你踩到两种 403,都不是权限问题:
  77. - urllib 直接 PUT:'ascii' codec can't encode —— 客户端就地炸
  78. - 先 percent-encode 再 PUT:OBS 返回 403 SignatureDoesNotMatch
  79. —— 服务端签名按 UTF-8 原始字节算,quote 后字节变了
  80. 唯一正确姿势:请求行里写裸 UTF-8 path,query 原样不动,不二次编码。
  81. """
  82. parts = urllib.parse.urlsplit(url)
  83. host = parts.hostname
  84. port = parts.port or (443 if parts.scheme == "https" else 80)
  85. target = (parts.path + ("?" + parts.query if parts.query else "")).encode("utf-8")
  86. lines = [b"PUT " + target + b" HTTP/1.1",
  87. b"Host: " + parts.netloc.encode("utf-8"),
  88. b"Connection: close",
  89. b"Content-Length: %d" % len(data)]
  90. sent_lower = set()
  91. for k, v in headers.items():
  92. sent_lower.add(k.lower())
  93. lines.append(("%s: %s" % (k, v)).encode("utf-8"))
  94. if "content-type" not in sent_lower:
  95. lines.append(b"Content-Type: application/octet-stream")
  96. request = b"\r\n".join(lines) + b"\r\n\r\n" + data
  97. if parts.scheme == "https":
  98. ctx = ssl.create_default_context()
  99. sock = ctx.wrap_socket(socket.create_connection((host, port), timeout=timeout),
  100. server_hostname=host)
  101. else:
  102. sock = socket.create_connection((host, port), timeout=timeout)
  103. try:
  104. sock.sendall(request)
  105. buf = b""
  106. while True:
  107. chunk = sock.recv(65536)
  108. if not chunk:
  109. break
  110. buf += chunk
  111. finally:
  112. sock.close()
  113. head, _, body = buf.partition(b"\r\n\r\n")
  114. status_line = head.split(b"\r\n")[0].decode("latin-1")
  115. code = int(status_line.split()[1]) if len(status_line.split()) > 1 else 0
  116. if code // 100 != 2:
  117. raise RuntimeError("%s %s" % (code, body[:200].decode("utf-8", "replace")))
  118. return code
  119. def fetch_signed_url(url, timeout=120):
  120. """GET a public URL, again using RAW UTF-8 in the request line (中文 key 同理)."""
  121. parts = urllib.parse.urlsplit(url)
  122. host = parts.hostname
  123. port = parts.port or (443 if parts.scheme == "https" else 80)
  124. target = (parts.path + ("?" + parts.query if parts.query else "")).encode("utf-8")
  125. lines = [b"GET " + target + b" HTTP/1.1",
  126. b"Host: " + parts.netloc.encode("utf-8"),
  127. b"Connection: close"]
  128. ctx = ssl.create_default_context()
  129. sock = ctx.wrap_socket(socket.create_connection((host, port), timeout=timeout),
  130. server_hostname=host)
  131. try:
  132. sock.sendall(b"\r\n".join(lines) + b"\r\n\r\n")
  133. raw = b""
  134. while True:
  135. chunk = sock.recv(65536)
  136. if not chunk:
  137. break
  138. raw += chunk
  139. finally:
  140. sock.close()
  141. head, _, body = raw.partition(b"\r\n\r\n")
  142. head_txt = head.decode("latin-1")
  143. first = head_txt.split("\r\n")[0]
  144. code = int(first.split()[1]) if len(first.split()) > 1 else 0
  145. clen = None
  146. for line in head_txt.split("\r\n")[1:]:
  147. if line.lower().startswith("content-length:"):
  148. clen = line.split(":", 1)[1].strip()
  149. if "transfer-encoding: chunked" in head_txt.lower():
  150. body = _dechunk(body)
  151. if code // 100 != 2:
  152. raise RuntimeError("%s %s" % (code, body[:200].decode("utf-8", "replace")))
  153. return code, body, clen
  154. def _dechunk(body):
  155. out = b""
  156. while body:
  157. line, _, rest = body.partition(b"\r\n")
  158. try:
  159. size = int(line.strip().split(b";")[0], 16)
  160. except ValueError:
  161. return out + body
  162. if size == 0:
  163. break
  164. out += rest[:size]
  165. body = rest[size + 2:]
  166. return out
  167. def push(files, agent_id, title, summary, do_drain=True, cleanup=False):
  168. ok_all = True
  169. files = [os.path.abspath(f) for f in files]
  170. for f in files:
  171. if not os.path.isfile(f):
  172. print("[push] FATAL 源文件不存在: %s" % f)
  173. return 1
  174. # ① report —— 🔴 2026-11-14 用户裁决:report 全链路只允许主链路
  175. # (fmode-deliverable-hook.py)执行一次。本函数是 legacy 兜底通道,
  176. # 先查已有 deliverable,命中就复用,绝不新建第二条台账记录。
  177. did = None
  178. for f in files:
  179. try:
  180. hist = call({"action": "list", "agentId": agent_id, "limit": 50})
  181. except Exception:
  182. hist = {}
  183. base = os.path.basename(f)
  184. for old in (hist.get("deliverables") or []):
  185. if not isinstance(old, dict):
  186. continue
  187. for art in (old.get("artifacts") or []):
  188. if not isinstance(art, dict):
  189. continue
  190. if (art.get("name") or "") == base and (art.get("url") or "").startswith("http"):
  191. did = old.get("id")
  192. print("[push] REUSE existing deliverable %s for %s" % (did, f))
  193. break
  194. if did:
  195. break
  196. if did:
  197. break
  198. if did:
  199. print("[push] ① skip report (reuse did=%s)" % did)
  200. else:
  201. rep = call({"action": "report", "agentId": agent_id,
  202. "title": title or os.path.basename(files[0]),
  203. "summary": summary or "",
  204. "artifacts": files})
  205. print("[push] ① report ->", json.dumps(rep, ensure_ascii=False))
  206. did = rep.get("id")
  207. if rep.get("code") != 200 or not did:
  208. print("[push] FATAL report 未返回 deliverableId")
  209. return 1
  210. # ② enqueueArtifact
  211. enq = []
  212. for idx, f in enumerate(files):
  213. r = call({"action": "enqueueArtifact", "deliverableId": did,
  214. "agentId": agent_id, "source": f,
  215. "filename": os.path.basename(f), "index": idx})
  216. print("[push] ② enqueueArtifact[%d] %s -> %s"
  217. % (idx, os.path.basename(f), json.dumps(r, ensure_ascii=False)))
  218. enq.append(r)
  219. if r.get("code") != 200:
  220. ok_all = False
  221. if not do_drain:
  222. return 0 if ok_all else 1
  223. # ③ pendingArtifacts -> PUT -> ackArtifact
  224. pend = call({"action": "pendingArtifacts", "agentId": agent_id})
  225. jobs = (pend.get("jobs") or []) if pend.get("code") == 200 else []
  226. print("[push] ③ pendingArtifacts -> jobs=%d %s" % (len(jobs), "" if jobs else json.dumps(pend, ensure_ascii=False)))
  227. # 只处理本次 report 产生的 job:同一 source 会被多次入队,按 source 匹配会把历史 job 一起重传
  228. mine = [j for j in jobs if j.get("source") in files and j.get("deliverableId") == did]
  229. if not mine:
  230. print("[push] WARN 队列里没有本次文件(可能已被 drain 或入队失败)")
  231. ok_all = False
  232. # 先自己把文件读进内存算 md5,后面回读比对
  233. local = {}
  234. for j in mine:
  235. try:
  236. local[j["source"]] = open(j["source"], "rb").read()
  237. except Exception as e:
  238. print("[push] FATAL 读本地失败 %s: %s" % (j["source"], e))
  239. ok_all = False
  240. for j in mine:
  241. src = j["source"]
  242. data = local.get(src)
  243. if data is None:
  244. continue
  245. try:
  246. put_signed_url(j["uploadUrl"], data, j.get("headers") or {}, timeout=180)
  247. except Exception as e:
  248. msg = str(e)[:200]
  249. call({"action": "ackArtifact", "objectId": j["id"], "ok": False, "error": msg})
  250. print("[push] FAIL PUT %s: %s" % (os.path.basename(src), msg))
  251. ok_all = False
  252. continue
  253. ack = call({"action": "ackArtifact", "objectId": j["id"],
  254. "ok": True, "publicUrl": j["publicUrl"]})
  255. print("[push] ack %s -> %s" % (os.path.basename(src), json.dumps(ack, ensure_ascii=False)))
  256. # ④ public 回读校验
  257. url = j["publicUrl"]
  258. try:
  259. code, got, clen = fetch_signed_url(url, timeout=120)
  260. except Exception as e:
  261. print("[push] VERIFY FAIL 回读异常 %s: %s" % (url, e))
  262. ok_all = False
  263. continue
  264. same = md5_bytes(got) == md5_bytes(data)
  265. print("[push] VERIFY url=%s" % url)
  266. print("[push] http=%s content-length=%s size=%d local=%d"
  267. % (code, clen, len(got), len(data)))
  268. print("[push] md5_remote=%s md5_local=%s identical=%s"
  269. % (md5_bytes(got), md5_bytes(data), "YES" if same else "NO"))
  270. if not same:
  271. ok_all = False
  272. continue
  273. # ⑤ C-2 清理:线上回读 md5 与本地产物一致 → 删除本地源文件(本地只做秒级中转)
  274. if cleanup:
  275. try:
  276. os.remove(src)
  277. print("[push] CLEANUP removed local: %s" % src)
  278. except OSError as e:
  279. print("[push] CLEANUP-FAIL %s: %s" % (src, e))
  280. ok_all = False
  281. print("[push] RESULT", "OK" if ok_all else "PARTIAL/FAIL")
  282. return 0 if ok_all else 1
  283. def main():
  284. # 🔴 2026-11-14 用户裁决:交付只走 fmode-deliverable-hook.py 这一条通道。
  285. # 本脚本的 report/enqueue/PUT/ack 与 hook 第 652-718 行完全重复,
  286. # 两条同时跑会产生两条台账记录(tags=[] 与 tags=["auto-deliverable-hook"])。
  287. # 这里直接退出,避免模型调用后产生重复记录。
  288. # ⚠️ 重要:本模块仍被 fmode-deliverable-hook.py 以 import 方式使用
  289. # (call / put_signed_url / fetch_signed_url / md5_bytes),
  290. # 所以只能拦 CLI 入口,绝不能删函数或让 import 失败。
  291. import sys as _sys
  292. _sys.stderr.write(
  293. "[fmode-artifact-push] DISABLED: 交付统一走 fmode-deliverable-hook.py。"
  294. "本脚本不再上传、不再写台账。\n")
  295. _sys.exit(2)
  296. def _legacy_main():
  297. ap = argparse.ArgumentParser()
  298. sub = ap.add_subparsers(dest="cmd", required=True)
  299. p = sub.add_parser("push")
  300. p.add_argument("--files", nargs="+", required=True)
  301. p.add_argument("--title", default="")
  302. p.add_argument("--summary", default="")
  303. p.add_argument("--agent-id", default=os.environ.get("AGENT_ID") or DEFAULT_AGENT_ID)
  304. p.add_argument("--no-drain", action="store_true")
  305. p.add_argument("--cleanup", action="store_true",
  306. help="回读 md5 校验一致后删除本地源文件(本地只做秒级中转)")
  307. a = ap.parse_args()
  308. if a.cmd == "push":
  309. sys.exit(push(a.files, a.agent_id, a.title, a.summary, not a.no_drain, a.cleanup))
  310. if __name__ == "__main__":
  311. main()