dsh-plugin-chuhai 0.3.5 → 0.3.6
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/CHANGELOG.md +5 -0
- package/books/ai-global-media/BOOK.md +131 -131
- package/books/ai-global-media/expert/SOURCE.json +43 -41
- package/books/ai-global-media/expert/agents/ilang-wechat-awesome.md +267 -267
- package/books/ai-global-media/expert/skills/remote-dispatch/SKILL.md +101 -101
- package/books/ai-global-media/expert/skills/remote-dispatch/references/gateway-api.md +58 -58
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/dispatch.py +299 -299
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.ps1 +74 -74
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.sh +94 -94
- package/books/ai-global-media/expert/skills/wechat-article/SKILL.md +80 -80
- package/books/ai-global-media/expert/skills/wechat-article/references/algorithm-and-rhythm.md +54 -54
- package/books/ai-global-media/expert/skills/wechat-article/references/compliance.md +68 -68
- package/books/ai-global-media/expert/skills/wechat-article/references/cover-prompt.md +19 -19
- package/books/ai-global-media/expert/skills/wechat-article/references/deai.md +64 -64
- package/books/ai-global-media/expert/skills/wechat-article/references/genes.md +168 -168
- package/books/ai-global-media/expert/skills/wechat-article/references/other-platforms.md +47 -47
- package/books/ai-global-media/expert/skills/wechat-article/references/self-check.md +32 -32
- package/books/ai-global-media/expert/skills/wechat-article/references/structures-and-titles.md +77 -77
- package/books/ai-global-media/expert/skills/wechat-article/references/wechat-format-and-api.md +61 -61
- package/books/ai-global-media/expert/skills/wechat-draft-push/SKILL.md +129 -129
- package/books/ai-global-media/expert/skills/wechat-draft-push/references/api-notes.md +168 -168
- package/books/ai-global-media/expert/skills/wechat-draft-push/references/html-rules.md +62 -62
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/cards.html +75 -75
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/newspic_cards.py +345 -345
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/wechat_draft.py +1023 -1023
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/SKILL.md +125 -92
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/apify-wechat.md +90 -0
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/method.md +49 -49
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/wxrank-api.md +51 -51
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/apify_wechat.py +577 -0
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/hot_sources.py +553 -553
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/sources.json +716 -714
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/wxrank_topics.py +466 -466
- package/books/baowen/BOOK.md +83 -83
- package/package.json +1 -1
|
@@ -1,299 +1,299 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""remote-dispatch: 把一段命令块派给远程机上的 CodeBuddy Code 网关跑,收回结果。只用标准库。
|
|
4
|
-
|
|
5
|
-
配置文件 ~/.dispatch.json(用户自己写,脚本只读):
|
|
6
|
-
{
|
|
7
|
-
"default": "vps",
|
|
8
|
-
"remotes": {
|
|
9
|
-
"vps": {"url": "http://1.2.3.4:8080", "password": "网关口令"}
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
命令:
|
|
14
|
-
python dispatch.py list 列出配置的远程机并探活
|
|
15
|
-
python dispatch.py send --file 块.md [--to vps] [--timeout 900] [--max-wait 3600]
|
|
16
|
-
python dispatch.py send --text "一句话" [--to vps]
|
|
17
|
-
python dispatch.py sessions [--to vps] [--n 5] 远程最近的会话
|
|
18
|
-
python dispatch.py history --session <id> [--to vps]
|
|
19
|
-
python dispatch.py cancel --run <runId> [--to vps]
|
|
20
|
-
|
|
21
|
-
网关的三个硬规矩(实测):请求头带 X-CodeBuddy-Request: 1、Authorization: Bearer 口令、Host: localhost:<端口>;
|
|
22
|
-
正文 UTF-8;结果要在跑的时候挂 /runs/{id}/stream 收,跑完再挂就没了(脚本会自动回退到会话历史)。
|
|
23
|
-
"""
|
|
24
|
-
import socket
|
|
25
|
-
import argparse, datetime, io, json, os, re, sys, time, uuid
|
|
26
|
-
import urllib.request, urllib.error
|
|
27
|
-
from urllib.parse import urlparse
|
|
28
|
-
|
|
29
|
-
try:
|
|
30
|
-
sys.stdout.reconfigure(encoding="utf-8")
|
|
31
|
-
sys.stderr.reconfigure(encoding="utf-8")
|
|
32
|
-
except Exception:
|
|
33
|
-
pass
|
|
34
|
-
|
|
35
|
-
CFG = os.path.expanduser("~/.dispatch.json")
|
|
36
|
-
LOGDIR = os.path.expanduser("~/dispatch-logs")
|
|
37
|
-
VIA_NOTE = "::NOTE{via:remote-dispatch 这段是本机派活技能一次性发来的 没人会回答你的追问 要人决定的按命令里的默认值走 做到能做的最后一步 结果和回执一次给全}"
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
def die(msg, code=1):
|
|
41
|
-
print(msg)
|
|
42
|
-
sys.exit(code)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def load_cfg():
|
|
46
|
-
if not os.path.exists(CFG):
|
|
47
|
-
die("没找到 %s。用户主目录建这个文件,写 default 和 remotes,见本技能 SKILL.md。" % CFG)
|
|
48
|
-
try:
|
|
49
|
-
return json.load(io.open(CFG, encoding="utf-8"))
|
|
50
|
-
except Exception as e:
|
|
51
|
-
die("%s 不是合法 JSON:%s" % (CFG, e))
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def pick(cfg, name):
|
|
55
|
-
remotes = cfg.get("remotes") or {}
|
|
56
|
-
name = name or cfg.get("default") or (next(iter(remotes)) if remotes else None)
|
|
57
|
-
if not name or name not in remotes:
|
|
58
|
-
die("远程机 %r 没配置。配置里有:%s" % (name, ", ".join(remotes) or "空"))
|
|
59
|
-
r = remotes[name]
|
|
60
|
-
url = (r.get("url") or "").rstrip("/")
|
|
61
|
-
pw = r.get("password") or ""
|
|
62
|
-
if not url or not pw:
|
|
63
|
-
die("远程机 %s 缺 url 或 password" % name)
|
|
64
|
-
u = urlparse(url)
|
|
65
|
-
port = u.port or (443 if u.scheme == "https" else 80)
|
|
66
|
-
return name, url, pw, port
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def headers(pw, port, extra=None):
|
|
70
|
-
h = {
|
|
71
|
-
"X-CodeBuddy-Request": "1",
|
|
72
|
-
"Authorization": "Bearer " + pw,
|
|
73
|
-
"Host": "localhost:%d" % port,
|
|
74
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
75
|
-
"Accept": "application/json, text/event-stream",
|
|
76
|
-
}
|
|
77
|
-
if extra:
|
|
78
|
-
h.update(extra)
|
|
79
|
-
return h
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def call(url, pw, port, method="GET", body=None, timeout=30):
|
|
83
|
-
data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
|
|
84
|
-
req = urllib.request.Request(url, data=data, method=method, headers=headers(pw, port))
|
|
85
|
-
try:
|
|
86
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
87
|
-
raw = resp.read().decode("utf-8", "replace")
|
|
88
|
-
except urllib.error.HTTPError as e:
|
|
89
|
-
raw = e.read().decode("utf-8", "replace")
|
|
90
|
-
try:
|
|
91
|
-
return e.code, json.loads(raw)
|
|
92
|
-
except Exception:
|
|
93
|
-
return e.code, {"raw": raw[:500]}
|
|
94
|
-
except Exception as e:
|
|
95
|
-
return 0, {"error": str(e)}
|
|
96
|
-
try:
|
|
97
|
-
return 200, json.loads(raw)
|
|
98
|
-
except Exception:
|
|
99
|
-
return 200, {"raw": raw[:500]}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def mask(s, pw):
|
|
103
|
-
return s.replace(pw, "<口令>") if pw else s
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def cmd_list(args):
|
|
107
|
-
cfg = load_cfg()
|
|
108
|
-
for name in (cfg.get("remotes") or {}):
|
|
109
|
-
_, url, pw, port = pick(cfg, name)
|
|
110
|
-
code, d = call(url + "/api/v1/health", pw, port, timeout=10)
|
|
111
|
-
st = (d.get("data") or {}).get("status") if isinstance(d, dict) else None
|
|
112
|
-
plats = ",".join((d.get("data") or {}).get("platforms", [])) if isinstance(d, dict) and d.get("data") else ""
|
|
113
|
-
print("%-12s %-32s %s %s" % (name, url, "在线 " + plats if st == "ok" else "不通 http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:120], pw)), "(默认)" if name == cfg.get("default") else ""))
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def extract_texts(obj, out):
|
|
117
|
-
"""从任意 JSON 里捞 assistant 的文字(markdown / text / content 字符串)。"""
|
|
118
|
-
if isinstance(obj, dict):
|
|
119
|
-
role = obj.get("role")
|
|
120
|
-
for k in ("markdown", "text"):
|
|
121
|
-
v = obj.get(k)
|
|
122
|
-
if isinstance(v, str) and v.strip() and role != "user":
|
|
123
|
-
out.append(v)
|
|
124
|
-
c = obj.get("content")
|
|
125
|
-
if isinstance(c, str) and c.strip() and role == "assistant":
|
|
126
|
-
out.append(c)
|
|
127
|
-
for v in obj.values():
|
|
128
|
-
extract_texts(v, out)
|
|
129
|
-
elif isinstance(obj, list):
|
|
130
|
-
for v in obj:
|
|
131
|
-
extract_texts(v, out)
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
def read_stream(url, pw, port, run_id, max_wait):
|
|
135
|
-
"""挂 SSE,收 message 事件里的 content.markdown,到 done 为止。返回 (markdowns, status, raw_error)。
|
|
136
|
-
流中途卡住、断掉都不抛栈:返回已收到的部分和 timeout / 流中断 的状态。"""
|
|
137
|
-
req = urllib.request.Request(url + "/api/v1/runs/%s/stream" % run_id, headers=headers(pw, port, {"Accept": "text/event-stream"}))
|
|
138
|
-
mds, status, event = [], None, None
|
|
139
|
-
deadline = time.time() + max_wait
|
|
140
|
-
try:
|
|
141
|
-
resp = urllib.request.urlopen(req, timeout=max_wait)
|
|
142
|
-
except urllib.error.HTTPError as e:
|
|
143
|
-
raw = e.read().decode("utf-8", "replace")
|
|
144
|
-
return mds, status, raw[:300]
|
|
145
|
-
except Exception as e:
|
|
146
|
-
return mds, status, str(e)
|
|
147
|
-
ctype = resp.headers.get("Content-Type", "")
|
|
148
|
-
if "json" in ctype:
|
|
149
|
-
return mds, status, resp.read().decode("utf-8", "replace")[:300]
|
|
150
|
-
buf = []
|
|
151
|
-
try:
|
|
152
|
-
for line in resp:
|
|
153
|
-
if time.time() > deadline:
|
|
154
|
-
return mds, status or "timeout", "超时 %ds" % max_wait
|
|
155
|
-
line = line.decode("utf-8", "replace").rstrip("\r\n")
|
|
156
|
-
if line.startswith("event:"):
|
|
157
|
-
event = line[6:].strip()
|
|
158
|
-
elif line.startswith("data:"):
|
|
159
|
-
buf.append(line[5:].strip())
|
|
160
|
-
elif line == "":
|
|
161
|
-
if buf:
|
|
162
|
-
data = "\n".join(buf); buf = []
|
|
163
|
-
try:
|
|
164
|
-
d = json.loads(data)
|
|
165
|
-
except Exception:
|
|
166
|
-
d = {"raw": data}
|
|
167
|
-
if event == "message":
|
|
168
|
-
status = d.get("status") or status
|
|
169
|
-
md = (d.get("content") or {}).get("markdown") if isinstance(d.get("content"), dict) else None
|
|
170
|
-
if md:
|
|
171
|
-
mds.append(md)
|
|
172
|
-
calls = (d.get("agent") or {}).get("toolCalls") or []
|
|
173
|
-
if calls:
|
|
174
|
-
print(" [远程动了 %d 个工具]" % len(calls), file=sys.stderr)
|
|
175
|
-
elif event == "done":
|
|
176
|
-
return mds, status or "completed", None
|
|
177
|
-
elif event in ("error",):
|
|
178
|
-
return mds, "error", data[:300]
|
|
179
|
-
event = None
|
|
180
|
-
except (TimeoutError, socket.timeout) as e:
|
|
181
|
-
return mds, status or "timeout", "超时 %ds(流卡住:%s)" % (max_wait, e)
|
|
182
|
-
except Exception as e:
|
|
183
|
-
return mds, status or "stream-broken", "流中断 %s: %s" % (type(e).__name__, str(e)[:120])
|
|
184
|
-
return mds, status or "closed", None
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def fallback_history(url, pw, port, text):
|
|
188
|
-
code, d = call(url + "/api/v1/sessions?limit=5", pw, port, timeout=20)
|
|
189
|
-
sess = (d.get("data") or {}).get("sessions") if isinstance(d, dict) else None
|
|
190
|
-
if not sess:
|
|
191
|
-
return None
|
|
192
|
-
head = text.strip()[:20]
|
|
193
|
-
cand = [s for s in sess if str(s.get("name", "")).startswith(head)] or sess[:1]
|
|
194
|
-
sid = cand[0].get("id")
|
|
195
|
-
code, h = call(url + "/api/v1/sessions/%s/history" % sid, pw, port, timeout=30)
|
|
196
|
-
out = []
|
|
197
|
-
extract_texts(h, out)
|
|
198
|
-
return out[-1] if out else None
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
def save_log(name, run_id, text, result, status):
|
|
202
|
-
day = datetime.datetime.now().strftime("%Y-%m-%d")
|
|
203
|
-
d = os.path.join(LOGDIR, day)
|
|
204
|
-
os.makedirs(d, exist_ok=True)
|
|
205
|
-
p = os.path.join(d, "%s-%s-%s.md" % (datetime.datetime.now().strftime("%H%M%S"), name, run_id[:8]))
|
|
206
|
-
with io.open(p, "w", encoding="utf-8") as f:
|
|
207
|
-
f.write("# 派活记录\n\n- 远程机: %s\n- runId: %s\n- 状态: %s\n- 时间: %s\n\n## 发出去的\n\n%s\n\n## 收回来的\n\n%s\n" % (name, run_id, status, datetime.datetime.now().isoformat(timespec="seconds"), text, result or "(空)"))
|
|
208
|
-
return p
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
def cmd_send(args):
|
|
212
|
-
cfg = load_cfg()
|
|
213
|
-
name, url, pw, port = pick(cfg, args.to)
|
|
214
|
-
if args.file:
|
|
215
|
-
text = io.open(args.file, encoding="utf-8").read()
|
|
216
|
-
elif args.text:
|
|
217
|
-
text = args.text
|
|
218
|
-
else:
|
|
219
|
-
die("要 --file 或 --text")
|
|
220
|
-
if not text.strip():
|
|
221
|
-
die("要发的内容是空的")
|
|
222
|
-
orig = text
|
|
223
|
-
if not getattr(args, "raw", False):
|
|
224
|
-
text = VIA_NOTE + "\n\n" + text
|
|
225
|
-
client_id = "dispatch-" + uuid.uuid4().hex[:12]
|
|
226
|
-
body = {
|
|
227
|
-
"id": client_id, "type": "message", "version": "1.0",
|
|
228
|
-
"source": {"platform": "generic", "sender": {"id": "dispatch", "name": "dispatch"},
|
|
229
|
-
"conversation": {"id": client_id, "type": "direct"}},
|
|
230
|
-
"payload": {"text": text},
|
|
231
|
-
"timeoutMs": int(args.timeout) * 1000,
|
|
232
|
-
}
|
|
233
|
-
code, d = call(url + "/api/v1/runs", pw, port, method="POST", body=body, timeout=30)
|
|
234
|
-
run_id = (d.get("data") or {}).get("runId") if isinstance(d, dict) else None
|
|
235
|
-
if not run_id:
|
|
236
|
-
die("派活失败 http %s:%s" % (code, mask(json.dumps(d, ensure_ascii=False)[:400], pw)))
|
|
237
|
-
print("已派给 %s,runId %s,等结果…" % (name, run_id), file=sys.stderr)
|
|
238
|
-
mds, status, err = read_stream(url, pw, port, run_id, int(args.max_wait))
|
|
239
|
-
result = "\n\n".join(m for m in mds if m) if mds else None
|
|
240
|
-
if not result and err and "RUN_NOT_FOUND" in err:
|
|
241
|
-
print(" 跑得太快没挂上流,改从会话历史读…", file=sys.stderr)
|
|
242
|
-
result = fallback_history(url, pw, port, orig) # 用原正文对会话名,不带 ::NOTE 前缀
|
|
243
|
-
status = status or "completed"
|
|
244
|
-
if not result and err:
|
|
245
|
-
status = status or "error"
|
|
246
|
-
result = "(没收到结果) " + mask(err, pw)
|
|
247
|
-
p = save_log(name, run_id, text, result, status)
|
|
248
|
-
print(result or "(空)")
|
|
249
|
-
print("\n[状态 %s · 记录 %s]" % (status, p), file=sys.stderr)
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def cmd_sessions(args):
|
|
253
|
-
cfg = load_cfg()
|
|
254
|
-
name, url, pw, port = pick(cfg, args.to)
|
|
255
|
-
code, d = call(url + "/api/v1/sessions?limit=%d" % int(args.n), pw, port, timeout=20)
|
|
256
|
-
sess = (d.get("data") or {}).get("sessions") if isinstance(d, dict) else None
|
|
257
|
-
if not sess:
|
|
258
|
-
die("没拿到会话:http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:300], pw)))
|
|
259
|
-
for s in sess:
|
|
260
|
-
ts = datetime.datetime.fromtimestamp((s.get("updatedAt") or 0) / 1000).strftime("%m-%d %H:%M")
|
|
261
|
-
print("%s %s %s" % (s.get("id"), ts, str(s.get("name", ""))[:60]))
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
def cmd_history(args):
|
|
265
|
-
cfg = load_cfg()
|
|
266
|
-
name, url, pw, port = pick(cfg, args.to)
|
|
267
|
-
code, h = call(url + "/api/v1/sessions/%s/history" % args.session, pw, port, timeout=30)
|
|
268
|
-
out = []
|
|
269
|
-
extract_texts(h, out)
|
|
270
|
-
if not out:
|
|
271
|
-
print(mask(json.dumps(h, ensure_ascii=False)[:1500], pw))
|
|
272
|
-
else:
|
|
273
|
-
print("\n\n---\n\n".join(out[-int(args.n):]))
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
def cmd_cancel(args):
|
|
277
|
-
cfg = load_cfg()
|
|
278
|
-
name, url, pw, port = pick(cfg, args.to)
|
|
279
|
-
code, d = call(url + "/api/v1/runs/%s/cancel" % args.run, pw, port, method="POST", body={}, timeout=20)
|
|
280
|
-
print("http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:300], pw)))
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
def main():
|
|
284
|
-
ap = argparse.ArgumentParser(description="把命令块派给远程 CodeBuddy 网关跑")
|
|
285
|
-
sub = ap.add_subparsers(dest="cmd")
|
|
286
|
-
sub.add_parser("list")
|
|
287
|
-
p = sub.add_parser("send"); p.add_argument("--to"); p.add_argument("--file"); p.add_argument("--text")
|
|
288
|
-
p.add_argument("--timeout", default=900, help="远程单次执行超时 秒"); p.add_argument("--max-wait", default=3600, help="本地最多等多久 秒"); p.add_argument("--raw", action="store_true", help="不在正文前加 ::NOTE{via:remote-dispatch …} 那一行")
|
|
289
|
-
p = sub.add_parser("sessions"); p.add_argument("--to"); p.add_argument("--n", default=5)
|
|
290
|
-
p = sub.add_parser("history"); p.add_argument("--to"); p.add_argument("--session", required=True); p.add_argument("--n", default=1)
|
|
291
|
-
p = sub.add_parser("cancel"); p.add_argument("--to"); p.add_argument("--run", required=True)
|
|
292
|
-
args = ap.parse_args()
|
|
293
|
-
if not args.cmd:
|
|
294
|
-
ap.print_help(); return
|
|
295
|
-
{"list": cmd_list, "send": cmd_send, "sessions": cmd_sessions, "history": cmd_history, "cancel": cmd_cancel}[args.cmd](args)
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
if __name__ == "__main__":
|
|
299
|
-
main()
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""remote-dispatch: 把一段命令块派给远程机上的 CodeBuddy Code 网关跑,收回结果。只用标准库。
|
|
4
|
+
|
|
5
|
+
配置文件 ~/.dispatch.json(用户自己写,脚本只读):
|
|
6
|
+
{
|
|
7
|
+
"default": "vps",
|
|
8
|
+
"remotes": {
|
|
9
|
+
"vps": {"url": "http://1.2.3.4:8080", "password": "网关口令"}
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
命令:
|
|
14
|
+
python dispatch.py list 列出配置的远程机并探活
|
|
15
|
+
python dispatch.py send --file 块.md [--to vps] [--timeout 900] [--max-wait 3600]
|
|
16
|
+
python dispatch.py send --text "一句话" [--to vps]
|
|
17
|
+
python dispatch.py sessions [--to vps] [--n 5] 远程最近的会话
|
|
18
|
+
python dispatch.py history --session <id> [--to vps]
|
|
19
|
+
python dispatch.py cancel --run <runId> [--to vps]
|
|
20
|
+
|
|
21
|
+
网关的三个硬规矩(实测):请求头带 X-CodeBuddy-Request: 1、Authorization: Bearer 口令、Host: localhost:<端口>;
|
|
22
|
+
正文 UTF-8;结果要在跑的时候挂 /runs/{id}/stream 收,跑完再挂就没了(脚本会自动回退到会话历史)。
|
|
23
|
+
"""
|
|
24
|
+
import socket
|
|
25
|
+
import argparse, datetime, io, json, os, re, sys, time, uuid
|
|
26
|
+
import urllib.request, urllib.error
|
|
27
|
+
from urllib.parse import urlparse
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
31
|
+
sys.stderr.reconfigure(encoding="utf-8")
|
|
32
|
+
except Exception:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
CFG = os.path.expanduser("~/.dispatch.json")
|
|
36
|
+
LOGDIR = os.path.expanduser("~/dispatch-logs")
|
|
37
|
+
VIA_NOTE = "::NOTE{via:remote-dispatch 这段是本机派活技能一次性发来的 没人会回答你的追问 要人决定的按命令里的默认值走 做到能做的最后一步 结果和回执一次给全}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def die(msg, code=1):
|
|
41
|
+
print(msg)
|
|
42
|
+
sys.exit(code)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_cfg():
|
|
46
|
+
if not os.path.exists(CFG):
|
|
47
|
+
die("没找到 %s。用户主目录建这个文件,写 default 和 remotes,见本技能 SKILL.md。" % CFG)
|
|
48
|
+
try:
|
|
49
|
+
return json.load(io.open(CFG, encoding="utf-8"))
|
|
50
|
+
except Exception as e:
|
|
51
|
+
die("%s 不是合法 JSON:%s" % (CFG, e))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def pick(cfg, name):
|
|
55
|
+
remotes = cfg.get("remotes") or {}
|
|
56
|
+
name = name or cfg.get("default") or (next(iter(remotes)) if remotes else None)
|
|
57
|
+
if not name or name not in remotes:
|
|
58
|
+
die("远程机 %r 没配置。配置里有:%s" % (name, ", ".join(remotes) or "空"))
|
|
59
|
+
r = remotes[name]
|
|
60
|
+
url = (r.get("url") or "").rstrip("/")
|
|
61
|
+
pw = r.get("password") or ""
|
|
62
|
+
if not url or not pw:
|
|
63
|
+
die("远程机 %s 缺 url 或 password" % name)
|
|
64
|
+
u = urlparse(url)
|
|
65
|
+
port = u.port or (443 if u.scheme == "https" else 80)
|
|
66
|
+
return name, url, pw, port
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def headers(pw, port, extra=None):
|
|
70
|
+
h = {
|
|
71
|
+
"X-CodeBuddy-Request": "1",
|
|
72
|
+
"Authorization": "Bearer " + pw,
|
|
73
|
+
"Host": "localhost:%d" % port,
|
|
74
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
75
|
+
"Accept": "application/json, text/event-stream",
|
|
76
|
+
}
|
|
77
|
+
if extra:
|
|
78
|
+
h.update(extra)
|
|
79
|
+
return h
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def call(url, pw, port, method="GET", body=None, timeout=30):
|
|
83
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
|
|
84
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers(pw, port))
|
|
85
|
+
try:
|
|
86
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
87
|
+
raw = resp.read().decode("utf-8", "replace")
|
|
88
|
+
except urllib.error.HTTPError as e:
|
|
89
|
+
raw = e.read().decode("utf-8", "replace")
|
|
90
|
+
try:
|
|
91
|
+
return e.code, json.loads(raw)
|
|
92
|
+
except Exception:
|
|
93
|
+
return e.code, {"raw": raw[:500]}
|
|
94
|
+
except Exception as e:
|
|
95
|
+
return 0, {"error": str(e)}
|
|
96
|
+
try:
|
|
97
|
+
return 200, json.loads(raw)
|
|
98
|
+
except Exception:
|
|
99
|
+
return 200, {"raw": raw[:500]}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def mask(s, pw):
|
|
103
|
+
return s.replace(pw, "<口令>") if pw else s
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def cmd_list(args):
|
|
107
|
+
cfg = load_cfg()
|
|
108
|
+
for name in (cfg.get("remotes") or {}):
|
|
109
|
+
_, url, pw, port = pick(cfg, name)
|
|
110
|
+
code, d = call(url + "/api/v1/health", pw, port, timeout=10)
|
|
111
|
+
st = (d.get("data") or {}).get("status") if isinstance(d, dict) else None
|
|
112
|
+
plats = ",".join((d.get("data") or {}).get("platforms", [])) if isinstance(d, dict) and d.get("data") else ""
|
|
113
|
+
print("%-12s %-32s %s %s" % (name, url, "在线 " + plats if st == "ok" else "不通 http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:120], pw)), "(默认)" if name == cfg.get("default") else ""))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def extract_texts(obj, out):
|
|
117
|
+
"""从任意 JSON 里捞 assistant 的文字(markdown / text / content 字符串)。"""
|
|
118
|
+
if isinstance(obj, dict):
|
|
119
|
+
role = obj.get("role")
|
|
120
|
+
for k in ("markdown", "text"):
|
|
121
|
+
v = obj.get(k)
|
|
122
|
+
if isinstance(v, str) and v.strip() and role != "user":
|
|
123
|
+
out.append(v)
|
|
124
|
+
c = obj.get("content")
|
|
125
|
+
if isinstance(c, str) and c.strip() and role == "assistant":
|
|
126
|
+
out.append(c)
|
|
127
|
+
for v in obj.values():
|
|
128
|
+
extract_texts(v, out)
|
|
129
|
+
elif isinstance(obj, list):
|
|
130
|
+
for v in obj:
|
|
131
|
+
extract_texts(v, out)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def read_stream(url, pw, port, run_id, max_wait):
|
|
135
|
+
"""挂 SSE,收 message 事件里的 content.markdown,到 done 为止。返回 (markdowns, status, raw_error)。
|
|
136
|
+
流中途卡住、断掉都不抛栈:返回已收到的部分和 timeout / 流中断 的状态。"""
|
|
137
|
+
req = urllib.request.Request(url + "/api/v1/runs/%s/stream" % run_id, headers=headers(pw, port, {"Accept": "text/event-stream"}))
|
|
138
|
+
mds, status, event = [], None, None
|
|
139
|
+
deadline = time.time() + max_wait
|
|
140
|
+
try:
|
|
141
|
+
resp = urllib.request.urlopen(req, timeout=max_wait)
|
|
142
|
+
except urllib.error.HTTPError as e:
|
|
143
|
+
raw = e.read().decode("utf-8", "replace")
|
|
144
|
+
return mds, status, raw[:300]
|
|
145
|
+
except Exception as e:
|
|
146
|
+
return mds, status, str(e)
|
|
147
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
148
|
+
if "json" in ctype:
|
|
149
|
+
return mds, status, resp.read().decode("utf-8", "replace")[:300]
|
|
150
|
+
buf = []
|
|
151
|
+
try:
|
|
152
|
+
for line in resp:
|
|
153
|
+
if time.time() > deadline:
|
|
154
|
+
return mds, status or "timeout", "超时 %ds" % max_wait
|
|
155
|
+
line = line.decode("utf-8", "replace").rstrip("\r\n")
|
|
156
|
+
if line.startswith("event:"):
|
|
157
|
+
event = line[6:].strip()
|
|
158
|
+
elif line.startswith("data:"):
|
|
159
|
+
buf.append(line[5:].strip())
|
|
160
|
+
elif line == "":
|
|
161
|
+
if buf:
|
|
162
|
+
data = "\n".join(buf); buf = []
|
|
163
|
+
try:
|
|
164
|
+
d = json.loads(data)
|
|
165
|
+
except Exception:
|
|
166
|
+
d = {"raw": data}
|
|
167
|
+
if event == "message":
|
|
168
|
+
status = d.get("status") or status
|
|
169
|
+
md = (d.get("content") or {}).get("markdown") if isinstance(d.get("content"), dict) else None
|
|
170
|
+
if md:
|
|
171
|
+
mds.append(md)
|
|
172
|
+
calls = (d.get("agent") or {}).get("toolCalls") or []
|
|
173
|
+
if calls:
|
|
174
|
+
print(" [远程动了 %d 个工具]" % len(calls), file=sys.stderr)
|
|
175
|
+
elif event == "done":
|
|
176
|
+
return mds, status or "completed", None
|
|
177
|
+
elif event in ("error",):
|
|
178
|
+
return mds, "error", data[:300]
|
|
179
|
+
event = None
|
|
180
|
+
except (TimeoutError, socket.timeout) as e:
|
|
181
|
+
return mds, status or "timeout", "超时 %ds(流卡住:%s)" % (max_wait, e)
|
|
182
|
+
except Exception as e:
|
|
183
|
+
return mds, status or "stream-broken", "流中断 %s: %s" % (type(e).__name__, str(e)[:120])
|
|
184
|
+
return mds, status or "closed", None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def fallback_history(url, pw, port, text):
|
|
188
|
+
code, d = call(url + "/api/v1/sessions?limit=5", pw, port, timeout=20)
|
|
189
|
+
sess = (d.get("data") or {}).get("sessions") if isinstance(d, dict) else None
|
|
190
|
+
if not sess:
|
|
191
|
+
return None
|
|
192
|
+
head = text.strip()[:20]
|
|
193
|
+
cand = [s for s in sess if str(s.get("name", "")).startswith(head)] or sess[:1]
|
|
194
|
+
sid = cand[0].get("id")
|
|
195
|
+
code, h = call(url + "/api/v1/sessions/%s/history" % sid, pw, port, timeout=30)
|
|
196
|
+
out = []
|
|
197
|
+
extract_texts(h, out)
|
|
198
|
+
return out[-1] if out else None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def save_log(name, run_id, text, result, status):
|
|
202
|
+
day = datetime.datetime.now().strftime("%Y-%m-%d")
|
|
203
|
+
d = os.path.join(LOGDIR, day)
|
|
204
|
+
os.makedirs(d, exist_ok=True)
|
|
205
|
+
p = os.path.join(d, "%s-%s-%s.md" % (datetime.datetime.now().strftime("%H%M%S"), name, run_id[:8]))
|
|
206
|
+
with io.open(p, "w", encoding="utf-8") as f:
|
|
207
|
+
f.write("# 派活记录\n\n- 远程机: %s\n- runId: %s\n- 状态: %s\n- 时间: %s\n\n## 发出去的\n\n%s\n\n## 收回来的\n\n%s\n" % (name, run_id, status, datetime.datetime.now().isoformat(timespec="seconds"), text, result or "(空)"))
|
|
208
|
+
return p
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def cmd_send(args):
|
|
212
|
+
cfg = load_cfg()
|
|
213
|
+
name, url, pw, port = pick(cfg, args.to)
|
|
214
|
+
if args.file:
|
|
215
|
+
text = io.open(args.file, encoding="utf-8").read()
|
|
216
|
+
elif args.text:
|
|
217
|
+
text = args.text
|
|
218
|
+
else:
|
|
219
|
+
die("要 --file 或 --text")
|
|
220
|
+
if not text.strip():
|
|
221
|
+
die("要发的内容是空的")
|
|
222
|
+
orig = text
|
|
223
|
+
if not getattr(args, "raw", False):
|
|
224
|
+
text = VIA_NOTE + "\n\n" + text
|
|
225
|
+
client_id = "dispatch-" + uuid.uuid4().hex[:12]
|
|
226
|
+
body = {
|
|
227
|
+
"id": client_id, "type": "message", "version": "1.0",
|
|
228
|
+
"source": {"platform": "generic", "sender": {"id": "dispatch", "name": "dispatch"},
|
|
229
|
+
"conversation": {"id": client_id, "type": "direct"}},
|
|
230
|
+
"payload": {"text": text},
|
|
231
|
+
"timeoutMs": int(args.timeout) * 1000,
|
|
232
|
+
}
|
|
233
|
+
code, d = call(url + "/api/v1/runs", pw, port, method="POST", body=body, timeout=30)
|
|
234
|
+
run_id = (d.get("data") or {}).get("runId") if isinstance(d, dict) else None
|
|
235
|
+
if not run_id:
|
|
236
|
+
die("派活失败 http %s:%s" % (code, mask(json.dumps(d, ensure_ascii=False)[:400], pw)))
|
|
237
|
+
print("已派给 %s,runId %s,等结果…" % (name, run_id), file=sys.stderr)
|
|
238
|
+
mds, status, err = read_stream(url, pw, port, run_id, int(args.max_wait))
|
|
239
|
+
result = "\n\n".join(m for m in mds if m) if mds else None
|
|
240
|
+
if not result and err and "RUN_NOT_FOUND" in err:
|
|
241
|
+
print(" 跑得太快没挂上流,改从会话历史读…", file=sys.stderr)
|
|
242
|
+
result = fallback_history(url, pw, port, orig) # 用原正文对会话名,不带 ::NOTE 前缀
|
|
243
|
+
status = status or "completed"
|
|
244
|
+
if not result and err:
|
|
245
|
+
status = status or "error"
|
|
246
|
+
result = "(没收到结果) " + mask(err, pw)
|
|
247
|
+
p = save_log(name, run_id, text, result, status)
|
|
248
|
+
print(result or "(空)")
|
|
249
|
+
print("\n[状态 %s · 记录 %s]" % (status, p), file=sys.stderr)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def cmd_sessions(args):
|
|
253
|
+
cfg = load_cfg()
|
|
254
|
+
name, url, pw, port = pick(cfg, args.to)
|
|
255
|
+
code, d = call(url + "/api/v1/sessions?limit=%d" % int(args.n), pw, port, timeout=20)
|
|
256
|
+
sess = (d.get("data") or {}).get("sessions") if isinstance(d, dict) else None
|
|
257
|
+
if not sess:
|
|
258
|
+
die("没拿到会话:http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:300], pw)))
|
|
259
|
+
for s in sess:
|
|
260
|
+
ts = datetime.datetime.fromtimestamp((s.get("updatedAt") or 0) / 1000).strftime("%m-%d %H:%M")
|
|
261
|
+
print("%s %s %s" % (s.get("id"), ts, str(s.get("name", ""))[:60]))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cmd_history(args):
|
|
265
|
+
cfg = load_cfg()
|
|
266
|
+
name, url, pw, port = pick(cfg, args.to)
|
|
267
|
+
code, h = call(url + "/api/v1/sessions/%s/history" % args.session, pw, port, timeout=30)
|
|
268
|
+
out = []
|
|
269
|
+
extract_texts(h, out)
|
|
270
|
+
if not out:
|
|
271
|
+
print(mask(json.dumps(h, ensure_ascii=False)[:1500], pw))
|
|
272
|
+
else:
|
|
273
|
+
print("\n\n---\n\n".join(out[-int(args.n):]))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def cmd_cancel(args):
|
|
277
|
+
cfg = load_cfg()
|
|
278
|
+
name, url, pw, port = pick(cfg, args.to)
|
|
279
|
+
code, d = call(url + "/api/v1/runs/%s/cancel" % args.run, pw, port, method="POST", body={}, timeout=20)
|
|
280
|
+
print("http %s %s" % (code, mask(json.dumps(d, ensure_ascii=False)[:300], pw)))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def main():
|
|
284
|
+
ap = argparse.ArgumentParser(description="把命令块派给远程 CodeBuddy 网关跑")
|
|
285
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
286
|
+
sub.add_parser("list")
|
|
287
|
+
p = sub.add_parser("send"); p.add_argument("--to"); p.add_argument("--file"); p.add_argument("--text")
|
|
288
|
+
p.add_argument("--timeout", default=900, help="远程单次执行超时 秒"); p.add_argument("--max-wait", default=3600, help="本地最多等多久 秒"); p.add_argument("--raw", action="store_true", help="不在正文前加 ::NOTE{via:remote-dispatch …} 那一行")
|
|
289
|
+
p = sub.add_parser("sessions"); p.add_argument("--to"); p.add_argument("--n", default=5)
|
|
290
|
+
p = sub.add_parser("history"); p.add_argument("--to"); p.add_argument("--session", required=True); p.add_argument("--n", default=1)
|
|
291
|
+
p = sub.add_parser("cancel"); p.add_argument("--to"); p.add_argument("--run", required=True)
|
|
292
|
+
args = ap.parse_args()
|
|
293
|
+
if not args.cmd:
|
|
294
|
+
ap.print_help(); return
|
|
295
|
+
{"list": cmd_list, "send": cmd_send, "sessions": cmd_sessions, "history": cmd_history, "cancel": cmd_cancel}[args.cmd](args)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
if __name__ == "__main__":
|
|
299
|
+
main()
|