@taptap/cli 2026.11.6 → 2026.11.11

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 (59) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/bin/taptap-cli-darwin-amd64 +0 -0
  4. package/bin/taptap-cli-darwin-arm64 +0 -0
  5. package/bin/taptap-cli-linux-amd64 +0 -0
  6. package/bin/taptap-cli-linux-arm64 +0 -0
  7. package/bin/taptap-cli-linux-riscv64 +0 -0
  8. package/bin/taptap-cli-windows-amd64.exe +0 -0
  9. package/bin/taptap-cli-windows-arm64.exe +0 -0
  10. package/checksums.txt +7 -7
  11. package/package.json +7 -3
  12. package/scripts/bot/agent-turn.mjs +136 -0
  13. package/scripts/bot/agents/cindy-client.mjs +127 -0
  14. package/scripts/bot/agents/cindy.mjs +217 -0
  15. package/scripts/bot/agents/codex-project.mjs +63 -0
  16. package/scripts/bot/agents/codex-server.mjs +140 -0
  17. package/scripts/bot/agents/codex-sidebar.mjs +79 -0
  18. package/scripts/bot/agents/codex.mjs +240 -0
  19. package/scripts/bot/agents/index.mjs +20 -0
  20. package/scripts/bot/cli.mjs +392 -0
  21. package/scripts/bot/entry.cjs +10 -0
  22. package/scripts/bot/forum-context.mjs +97 -0
  23. package/scripts/bot/listener.mjs +328 -0
  24. package/scripts/bot/models.mjs +22 -0
  25. package/scripts/bot/process.mjs +47 -0
  26. package/scripts/bot/store.mjs +216 -0
  27. package/scripts/bot/tap.mjs +125 -0
  28. package/scripts/bot/version.mjs +6 -0
  29. package/scripts/run.js +2 -0
  30. package/skills/taptap-app-edit/references/app-edit-field-map.md +1 -1
  31. package/skills/taptap-app-edit/references/app-edit-fields-and-packages.md +5 -3
  32. package/skills/taptap-asset-library/SKILL.md +2 -0
  33. package/skills/taptap-asset-library/references/asset-library-ingest.md +2 -2
  34. package/skills/taptap-asset-library/references/asset-library-search.md +23 -1
  35. package/skills/taptap-cli/SKILL.md +1 -0
  36. package/skills/taptap-cli/references/package-type-boundary.md +1 -0
  37. package/skills/taptap-cli/references/prerequisite-recovery.md +31 -0
  38. package/skills/taptap-identity/SKILL.md +3 -3
  39. package/skills/taptap-identity/references/identity-behavior-rules.md +1 -1
  40. package/skills/taptap-materials/SKILL.md +1 -1
  41. package/skills/taptap-package-management/SKILL.md +1 -1
  42. package/skills/taptap-package-management/references/package-management-diagnostics.md +3 -3
  43. package/skills/taptap-qualification/references/qualification-analysis.md +26 -0
  44. package/skills/taptap-qualification/references/qualification-materials.md +5 -1
  45. package/taptap-suite/SKILL.md +1 -0
  46. package/taptap-suite/references/taptap-app-edit/references/app-edit-field-map.md +1 -1
  47. package/taptap-suite/references/taptap-app-edit/references/app-edit-fields-and-packages.md +5 -3
  48. package/taptap-suite/references/taptap-asset-library/SKILL.md +2 -0
  49. package/taptap-suite/references/taptap-asset-library/references/asset-library-ingest.md +2 -2
  50. package/taptap-suite/references/taptap-asset-library/references/asset-library-search.md +23 -1
  51. package/taptap-suite/references/taptap-cli/references/package-type-boundary.md +1 -0
  52. package/taptap-suite/references/taptap-cli/references/prerequisite-recovery.md +31 -0
  53. package/taptap-suite/references/taptap-identity/SKILL.md +3 -3
  54. package/taptap-suite/references/taptap-identity/references/identity-behavior-rules.md +1 -1
  55. package/taptap-suite/references/taptap-materials/SKILL.md +1 -1
  56. package/taptap-suite/references/taptap-package-management/SKILL.md +1 -1
  57. package/taptap-suite/references/taptap-package-management/references/package-management-diagnostics.md +3 -3
  58. package/taptap-suite/references/taptap-qualification/references/qualification-analysis.md +26 -0
  59. package/taptap-suite/references/taptap-qualification/references/qualification-materials.md +5 -1
@@ -0,0 +1,328 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import WebSocket from "ws";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { tap, botArgs, servers, assertLoginBinding } from "./tap.mjs";
7
+ import { persist, receipt, acknowledge, positive, claim, vendorOwner, inboxId } from "./store.mjs";
8
+ import { getAgent } from "./agents/index.mjs";
9
+ import { handleTurn } from "./agent-turn.mjs";
10
+
11
+ export function validateCredential(c, config, previous) {
12
+ if (
13
+ !c ||
14
+ c.wss_url !== servers[config.env][1] ||
15
+ c.subprotocol !== "taptap-community-bot.v2" ||
16
+ c.protocol_major !== 2 ||
17
+ c.protocol_minor !== 0 ||
18
+ !/^tpcb_[A-Za-z0-9_-]{43}$/.test(c.credential) ||
19
+ !(positive(c.game_app_id) || (c.game_app_id === "0" && vendorOwner(c.application_client_id))) ||
20
+ ![c.bot_id, c.binding_id, c.epoch, c.expires_at].every(
21
+ positive,
22
+ ) ||
23
+ !c.application_client_id ||
24
+ c.bot_id !== config.bot ||
25
+ (config.app && c.game_app_id !== config.app)
26
+ )
27
+ throw Error("服务器返回的连接信息与所选机器人或环境不一致");
28
+ if (
29
+ previous &&
30
+ (["bot_id", "game_app_id", "binding_id", "application_client_id"].some(
31
+ (k) => c[k] !== previous[k],
32
+ ) ||
33
+ BigInt(c.epoch) < BigInt(previous.epoch))
34
+ )
35
+ throw Error("续期后的绑定身份不一致");
36
+ return c;
37
+ }
38
+ export function checkReady(frame, c) {
39
+ const d = frame.data;
40
+ if (
41
+ frame.type !== "ready" ||
42
+ d?.protocolMajor !== 2 ||
43
+ d.protocolMinor !== 0 ||
44
+ !positive(d.socketEpoch) ||
45
+ !positive(d.credentialExpiresAt) ||
46
+ d.applicationClientId !== c.application_client_id ||
47
+ d.botId !== c.bot_id ||
48
+ d.bindingId !== c.binding_id ||
49
+ d.epoch !== c.epoch
50
+ )
51
+ throw Error("ready 身份校验失败");
52
+ return d.socketEpoch;
53
+ }
54
+ // WSS transport is kept independent from model latency and CLI calls.
55
+ export function session({
56
+ db,
57
+ id,
58
+ c,
59
+ signal,
60
+ onReady,
61
+ onHeartbeat,
62
+ onAck,
63
+ openSocket,
64
+ }) {
65
+ return new Promise((resolve, reject) => {
66
+ const ws = openSocket
67
+ ? openSocket()
68
+ : new WebSocket(c.wss_url, c.subprotocol, {
69
+ headers: { Authorization: "CommunityBot " + c.credential },
70
+ minVersion: "TLSv1.3",
71
+ handshakeTimeout: 12000,
72
+ followRedirects: false,
73
+ maxPayload: 256 * 1024,
74
+ perMessageDeflate: false,
75
+ });
76
+ let epoch,
77
+ pingAt = 0,
78
+ done = false;
79
+ const finish = (err, code) => {
80
+ if (done) return;
81
+ done = true;
82
+ clearTimeout(deadline);
83
+ clearInterval(timer);
84
+ signal.removeEventListener("abort", abort);
85
+ ws.terminate();
86
+ if (err) reject(err);
87
+ else resolve(code);
88
+ };
89
+ const abort = () => finish(null, 1000);
90
+ const deadline = setTimeout(() => finish(null, 1006), 15000);
91
+ const timer = setInterval(() => {
92
+ if (!epoch) return;
93
+ if (pingAt && Date.now() - pingAt > 5000) return finish(null, 1006);
94
+ if (!pingAt && Date.now() - lastPing >= 15000) {
95
+ lastPing = pingAt = Date.now();
96
+ ws.ping();
97
+ }
98
+ }, 1000);
99
+ let lastPing = 0;
100
+ ws.on("error", () => finish(null, 1006));
101
+ ws.on("close", (code) => finish(null, code));
102
+ ws.on("unexpected-response", (_req, res) => {
103
+ res.resume();
104
+ finish(null, res.statusCode);
105
+ });
106
+ ws.on("open", () => {
107
+ if (ws.protocol !== c.subprotocol)
108
+ return finish(Error("WSS 子协议不匹配"));
109
+ ws.send(
110
+ JSON.stringify({
111
+ type: "hello",
112
+ data: {
113
+ protocolMajor: 2,
114
+ protocolMinor: 0,
115
+ bindingId: c.binding_id,
116
+ epoch: c.epoch,
117
+ },
118
+ }),
119
+ );
120
+ });
121
+ ws.on("pong", () => {
122
+ if (pingAt) {
123
+ onHeartbeat(Date.now() - pingAt);
124
+ pingAt = 0;
125
+ }
126
+ });
127
+ function replay() {
128
+ const rows = db
129
+ .prepare("SELECT * FROM events WHERE id=? AND ack=0")
130
+ .all(id);
131
+ for (const row of rows) {
132
+ const ref = receipt(row);
133
+ if (
134
+ ref.data.eventRef.bindingId === c.binding_id &&
135
+ ref.data.eventRef.epoch === c.epoch
136
+ )
137
+ ws.send(JSON.stringify(ref));
138
+ }
139
+ }
140
+ ws.on("message", (raw, binary) => {
141
+ try {
142
+ if (binary) throw Error("收到非文本帧");
143
+ const f = JSON.parse(raw);
144
+ if (!epoch) {
145
+ epoch = checkReady(f, c);
146
+ clearTimeout(deadline);
147
+ onReady();
148
+ replay();
149
+ return;
150
+ }
151
+ if (f.type === "event.deliver")
152
+ ws.send(JSON.stringify(persist(db, id, f, c, epoch)));
153
+ else if (f.type === "receipt.ack") {
154
+ acknowledge(db, id, f.data);
155
+ onAck();
156
+ } else throw Error("未知 WSS 帧类型");
157
+ } catch (e) {
158
+ finish(Error(e instanceof SyntaxError ? "无效 JSON 帧" : e.message));
159
+ }
160
+ });
161
+ signal.addEventListener("abort", abort, { once: true });
162
+ if (signal.aborted) abort();
163
+ });
164
+ }
165
+ async function issue(db, id, config, old) {
166
+ const row = db.prepare("SELECT issuing FROM instances WHERE id=?").get(id);
167
+ if (row.issuing && !config.retryIssue && !config.replace)
168
+ throw Error(
169
+ "上次签发结果待确认,请先核对个人绑定,再使用 --replace-epoch 显式接管",
170
+ );
171
+ await assertLoginBinding(config);
172
+ const args = botArgs(config, "create-connection");
173
+ if (config.replace) args.push("--replace-epoch", config.replace);
174
+ db.prepare("UPDATE instances SET issuing=1 WHERE id=?").run(id);
175
+ let connection;
176
+ try {
177
+ connection = await tap(config, args, {});
178
+ } catch (e) {
179
+ if (e.definite)
180
+ db.prepare("UPDATE instances SET issuing=0 WHERE id=?").run(id);
181
+ throw e;
182
+ }
183
+ await assertLoginBinding(config);
184
+ validateCredential(connection, config, old);
185
+ delete config.retryIssue;
186
+ delete config.replace;
187
+ db.prepare(
188
+ "UPDATE instances SET credential=?,issuing=0,config=? WHERE id=?",
189
+ ).run(JSON.stringify(connection), JSON.stringify(config), id);
190
+ return connection;
191
+ }
192
+ export async function listen(db, id, ticket) {
193
+ claim(db, id, ticket);
194
+ const ctrl = new AbortController();
195
+ const abort = () => ctrl.abort();
196
+ process.on("SIGINT", abort);
197
+ process.on("SIGTERM", abort);
198
+ const stopping = setInterval(() => {
199
+ if (db.prepare("SELECT stop FROM instances WHERE id=?").get(id)?.stop)
200
+ abort();
201
+ }, 300);
202
+ let processing, agent, checkingLogin, loginError;
203
+ const state = (status, reason = null) =>
204
+ db
205
+ .prepare("UPDATE instances SET status=?,reason=? WHERE id=?")
206
+ .run(status, reason, id);
207
+ try {
208
+ const row = db.prepare("SELECT * FROM instances WHERE id=?").get(id);
209
+ const config = JSON.parse(row.config);
210
+ if (!positive(config.bot)) throw Error("监听实例缺少有效的机器人 ID,请使用 connect --bot 正整数");
211
+ const inbox = inboxId(id, config);
212
+ if (config.reply) {
213
+ if (!config.model) throw Error("请让用户确认模型后,带 --model 重新 connect");
214
+ agent = getAgent(config.agent);
215
+ }
216
+ let c = JSON.parse(row.credential),
217
+ tries = 0,
218
+ lastIssued = 0;
219
+ if (row.issuing && !config.retryIssue && !config.replace) throw Error("上次签发结果待确认,请先核对绑定");
220
+ if (c) validateCredential(c, config);
221
+ if (!c || config.replace || config.retryIssue) {
222
+ c = await issue(db, id, config, c);
223
+ lastIssued = Date.now();
224
+ }
225
+ const drain = () => {
226
+ if (processing || !config.reply || ctrl.signal.aborted) return;
227
+ processing = (async () => {
228
+ for (;;) {
229
+ const event = db
230
+ .prepare(
231
+ "SELECT * FROM events WHERE id=? AND ack=1 AND phase='received' ORDER BY rowid LIMIT 1",
232
+ )
233
+ .get(inbox);
234
+ if (!event || ctrl.signal.aborted) break;
235
+ const phase = (value, reply = null) =>
236
+ db
237
+ .prepare("UPDATE events SET phase=?,reply=? WHERE id=? AND key=?")
238
+ .run(value, reply, inbox, event.key);
239
+ const e = JSON.parse(event.frame).data.event;
240
+ if (
241
+ e.bindingId !== c.binding_id ||
242
+ e.epoch !== c.epoch ||
243
+ Number(e.queryExpiresAt) <= Date.now()
244
+ ) {
245
+ phase("expired");
246
+ continue;
247
+ }
248
+ phase("processing");
249
+ try {
250
+ await assertLoginBinding(config);
251
+ await handleTurn(db, inbox, config, event, phase, ctrl.signal);
252
+ } catch (err) {
253
+ const current = db
254
+ .prepare("SELECT phase FROM events WHERE id=? AND key=?")
255
+ .get(inbox, event.key).phase;
256
+ if (current !== "submitted")
257
+ phase(
258
+ ["submitting", "uncertain"].includes(current)
259
+ ? "uncertain"
260
+ : "failed",
261
+ JSON.stringify({ error: err.message.slice(0, 240), code: err.eventErrorCode }),
262
+ );
263
+ }
264
+ }
265
+ })().finally(() => {
266
+ processing = undefined;
267
+ });
268
+ };
269
+ while (!ctrl.signal.aborted) {
270
+ await assertLoginBinding(config);
271
+ state("connecting");
272
+ const code = await session({
273
+ db,
274
+ id: inbox,
275
+ c,
276
+ signal: ctrl.signal,
277
+ onAck: drain,
278
+ onReady: () => {
279
+ state("listening");
280
+ tries = 0;
281
+ drain();
282
+ },
283
+ onHeartbeat: () => {
284
+ db.prepare("UPDATE instances SET beat=? WHERE id=?").run(Date.now(), id);
285
+ checkingLogin ??= assertLoginBinding(config)
286
+ .catch((err) => { loginError = err; abort(); })
287
+ .finally(() => { checkingLogin = undefined; });
288
+ },
289
+ });
290
+ if (ctrl.signal.aborted) break;
291
+ if ([401, 403, 4401, 4403].includes(code)) {
292
+ if (Date.now() - lastIssued < 60000)
293
+ throw Error("续期后仍被拒绝,请检查账号与绑定");
294
+ if (config.personal)
295
+ config.replace = c.epoch;
296
+ c = await issue(db, id, config, c);
297
+ lastIssued = Date.now();
298
+ continue;
299
+ }
300
+ if (
301
+ [409, 4409, 4400, 4406, 1002, 1008].includes(code) ||
302
+ (code >= 300 && code < 500)
303
+ )
304
+ throw Error("连接已停止 (" + code + "),请核对绑定或协议");
305
+ state("reconnecting", String(code));
306
+ await delay(Math.min(30000, 1000 * 2 ** Math.min(tries++, 5)), null, {
307
+ signal: ctrl.signal,
308
+ }).catch(() => {});
309
+ }
310
+ if (loginError) throw loginError;
311
+ state("stopped");
312
+ } catch (e) {
313
+ state("failed", e.message);
314
+ throw e;
315
+ } finally {
316
+ ctrl.abort();
317
+ if (checkingLogin) await checkingLogin;
318
+ if (processing) await processing;
319
+ await agent?.shutdown?.();
320
+ clearInterval(stopping);
321
+ process.off("SIGINT", abort);
322
+ process.off("SIGTERM", abort);
323
+ db.prepare("UPDATE instances SET pid=NULL WHERE id=? AND pid=?").run(
324
+ id,
325
+ process.pid,
326
+ );
327
+ }
328
+ }
@@ -0,0 +1,22 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ export function selectModel(db, instance, config, previous) {
5
+ const saved = db.prepare(
6
+ "SELECT model FROM agent_models WHERE instance=? AND binding=? AND agent=?",
7
+ ).get(instance, config.loginBinding, config.agent)?.model;
8
+ const legacy = previous?.loginBinding === config.loginBinding &&
9
+ previous.agent === config.agent ? previous.model : undefined;
10
+ const model = config.model ?? saved ?? legacy;
11
+ if (typeof model !== "string" || !model.trim())
12
+ throw Error("请运行 bot models --agent " + config.agent +
13
+ ",让用户确认模型后,使用 connect --reply --model 模型ID;确认后会自动保存");
14
+ return model;
15
+ }
16
+
17
+ export function saveModel(db, instance, config) {
18
+ db.prepare(
19
+ "INSERT INTO agent_models(instance,binding,agent,model) VALUES(?,?,?,?) " +
20
+ "ON CONFLICT(instance,binding,agent) DO UPDATE SET model=excluded.model",
21
+ ).run(instance, config.loginBinding, config.agent, config.model);
22
+ }
@@ -0,0 +1,47 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { spawn } from "node:child_process";
5
+
6
+ export function run(
7
+ file,
8
+ args,
9
+ { input = "", timeout = 45000, cwd, env = process.env, signal } = {},
10
+ ) {
11
+ return new Promise((resolve, reject) => {
12
+ const child = spawn(file, args, {
13
+ cwd,
14
+ env,
15
+ signal,
16
+ windowsHide: true,
17
+ stdio: ["pipe", "pipe", "pipe"],
18
+ });
19
+ let stdout = "",
20
+ stderr = "",
21
+ expired = false;
22
+ const timer = setTimeout(() => {
23
+ expired = true;
24
+ child.kill("SIGKILL");
25
+ }, timeout);
26
+ child.stdout.setEncoding("utf8");
27
+ child.stderr.setEncoding("utf8");
28
+ child.stdout.on("data", (x) => {
29
+ stdout += x;
30
+ if (stdout.length > 4e6) child.kill("SIGKILL");
31
+ });
32
+ child.stderr.on("data", (x) => {
33
+ stderr = (stderr + x).slice(-65536);
34
+ });
35
+ child.on("error", (e) => {
36
+ clearTimeout(timer);
37
+ reject(e);
38
+ });
39
+ child.on("close", (code) => {
40
+ clearTimeout(timer);
41
+ if (expired) reject(Error("子进程超时"));
42
+ else resolve({ code, stdout, stderr });
43
+ });
44
+ child.stdin.on("error", () => {});
45
+ child.stdin.end(input);
46
+ });
47
+ }
@@ -0,0 +1,216 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { mkdirSync, chmodSync, openSync, closeSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+
10
+ export const hash = (s) => createHash("sha256").update(s).digest("hex");
11
+ export function directory() {
12
+ const base = process.env.TAPTAP_CLI_CONFIG_DIR || path.join(homedir(), ".taptap-cli");
13
+ if (!path.isAbsolute(base)) throw Error("TAPTAP_CLI_CONFIG_DIR 必须为绝对路径");
14
+ const dir = path.join(base, "bot");
15
+ mkdirSync(dir, { mode: 0o700, recursive: true });
16
+ return dir;
17
+ }
18
+ export function workspacePaths(id, binding, config) {
19
+ const scope = hash(JSON.stringify([id, binding]));
20
+ const legacy = path.join(directory(), "workspaces", scope);
21
+ if (config.agent !== "codex") return { workspace: legacy };
22
+ // The desktop uses the directory name. Keep a single portable path component.
23
+ const nickname = (config.nickname || "").replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_");
24
+ let name = "TapTap 机器人";
25
+ for (const ch of nickname ? " " + nickname : "") {
26
+ if (Buffer.byteLength(name + ch) > 255) break;
27
+ name += ch;
28
+ }
29
+ name = name.replace(/[. ]+$/u, "");
30
+ // Keep account isolation in the parent and the desktop display name in the leaf.
31
+ // Keep the old conversation key so upgrades can resume the same forum thread.
32
+ return { workspace: path.join(directory(), "projects", scope, name), threadWorkspace: legacy };
33
+ }
34
+ export function defaultWorkspace(id, binding, config) {
35
+ const paths = workspacePaths(id, binding, config);
36
+ mkdirSync(paths.workspace, { mode: 0o700, recursive: true });
37
+ return paths;
38
+ }
39
+ export function alive(pid) {
40
+ if (!pid) return false;
41
+ try {
42
+ process.kill(pid, 0);
43
+ return true;
44
+ } catch (e) {
45
+ return e.code === "EPERM";
46
+ }
47
+ }
48
+ export function store(dir = directory()) {
49
+ const file = path.join(dir, "listener.sqlite3");
50
+ if (process.platform !== "win32") {
51
+ closeSync(openSync(file, "a", 0o600));
52
+ chmodSync(file, 0o600);
53
+ }
54
+ const db = new DatabaseSync(file);
55
+ db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
56
+ CREATE TABLE IF NOT EXISTS instances(id TEXT PRIMARY KEY, config TEXT NOT NULL, pid INTEGER, stop INTEGER DEFAULT 0,
57
+ status TEXT DEFAULT 'stopped', beat INTEGER, reason TEXT, credential TEXT, issuing INTEGER DEFAULT 0, launch TEXT);
58
+ CREATE TABLE IF NOT EXISTS agent_models(instance TEXT, binding TEXT, agent TEXT, model TEXT NOT NULL,
59
+ PRIMARY KEY(instance,binding,agent));
60
+ CREATE TABLE IF NOT EXISTS events(id TEXT, key TEXT, digest TEXT, receipt TEXT UNIQUE, at TEXT, frame TEXT, ack INTEGER DEFAULT 0,
61
+ phase TEXT DEFAULT 'received', reply TEXT, PRIMARY KEY(id,key));`);
62
+ if (
63
+ !db
64
+ .prepare("PRAGMA table_info(instances)")
65
+ .all()
66
+ .some((col) => col.name === "launch")
67
+ ) {
68
+ db.exec("ALTER TABLE instances ADD COLUMN launch TEXT");
69
+ }
70
+ if (
71
+ !db
72
+ .prepare("PRAGMA table_info(events)")
73
+ .all()
74
+ .some((c) => c.name === "visibleSession")
75
+ )
76
+ db.exec("ALTER TABLE events ADD COLUMN visibleSession TEXT");
77
+ return db;
78
+ }
79
+ export const inboxId = (id, config) => config.loginBinding ? id + "/" + config.loginBinding : id;
80
+ export function claim(db, id, ticket) {
81
+ db.exec("BEGIN IMMEDIATE");
82
+ try {
83
+ const owner = db
84
+ .prepare("SELECT pid,launch,stop,config FROM instances WHERE id=?")
85
+ .get(id);
86
+ if (!owner || !ticket || owner.launch !== ticket || owner.stop)
87
+ throw Error("实例已经运行或尚未配置");
88
+ db.prepare(
89
+ "UPDATE instances SET pid=?,launch=NULL,stop=0,status='connecting',beat=NULL,reason=NULL WHERE id=?",
90
+ ).run(process.pid, id);
91
+ db.prepare(
92
+ "UPDATE events SET phase=CASE phase WHEN 'submitting' THEN 'uncertain' ELSE 'interrupted' END WHERE id=? AND phase IN ('processing','submitting')",
93
+ ).run(inboxId(id, JSON.parse(owner.config)));
94
+ db.exec("COMMIT");
95
+ } catch (e) {
96
+ db.exec("ROLLBACK");
97
+ throw e;
98
+ }
99
+ }
100
+ export function canonical(v) {
101
+ if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
102
+ if (v && typeof v === "object")
103
+ return (
104
+ "{" +
105
+ Object.keys(v)
106
+ .sort()
107
+ .map((k) => JSON.stringify(k) + ":" + canonical(v[k]))
108
+ .join(",") +
109
+ "}"
110
+ );
111
+ return JSON.stringify(v);
112
+ }
113
+ export const positive = (s) =>
114
+ typeof s === "string" &&
115
+ /^[1-9]\d{0,19}$/.test(s) &&
116
+ BigInt(s) <= 18446744073709551615n;
117
+ // Vendor connections have no home game. The authenticated event identifies the
118
+ // source forum and its developer; keep the other binding and epoch checks exact.
119
+ export function vendorOwner(client) {
120
+ if (typeof client !== "string" || !/^v:[1-9a-z][0-9a-z]{0,12}$/.test(client)) return null;
121
+ let id = 0n;
122
+ for (const digit of client.slice(2)) id = id * 36n + BigInt(parseInt(digit, 36));
123
+ return positive(String(id)) ? String(id) : null;
124
+ }
125
+
126
+ export function matchesEventGame(event, connection) {
127
+ if (!positive(event.gameAppId)) return false;
128
+ if (connection.game_app_id !== "0") return event.gameAppId === connection.game_app_id;
129
+ return positive(event.developerId) && vendorOwner(connection.application_client_id) === event.developerId;
130
+ }
131
+
132
+ export function persist(db, id, frame, connection, socketEpoch) {
133
+ const { event: e, payloadHash, socketEpoch: socket, attempt } = frame.data;
134
+ const fields = {
135
+ botId: "bot_id",
136
+ bindingId: "binding_id",
137
+ epoch: "epoch",
138
+ applicationClientId: "application_client_id",
139
+ };
140
+ if (
141
+ !e ||
142
+ !matchesEventGame(e, connection) ||
143
+ Object.entries(fields).some(([k, v]) => e[k] !== connection[v]) ||
144
+ socket !== socketEpoch ||
145
+ !Number.isInteger(attempt) ||
146
+ attempt < 1 ||
147
+ e.schemaVersion !== "2.0" ||
148
+ e.eventKind !== "BOT_PLATFORM_EVENT_MENTION" ||
149
+ typeof e.eventId !== "string" ||
150
+ !e.eventId ||
151
+ Buffer.byteLength(e.eventId) > 512 ||
152
+ !positive(e.sourceId) ||
153
+ !positive(e.rootTopicId) ||
154
+ !positive(e.actorUserId) ||
155
+ !positive(e.developerId) ||
156
+ !/^BOT_PLATFORM_SOURCE_(TOPIC|COMMENT|REPLY)$/.test(e.sourceType) ||
157
+ !/^[A-Za-z0-9_-]{43}$/.test(e.queryGrantRef) ||
158
+ !positive(e.deliveryDeadline) ||
159
+ !positive(e.queryExpiresAt) ||
160
+ Number(e.deliveryDeadline) <= Date.now() ||
161
+ hash(canonical(e)) !== payloadHash
162
+ )
163
+ throw Error("事件身份、期限或摘要校验失败");
164
+ const key = hash(
165
+ canonical([
166
+ e.applicationClientId,
167
+ e.botId,
168
+ e.bindingId,
169
+ e.epoch,
170
+ e.eventId,
171
+ ]),
172
+ );
173
+ db.prepare(
174
+ "INSERT OR IGNORE INTO events(id,key,digest,receipt,at,frame) VALUES(?,?,?,?,?,?)",
175
+ ).run(
176
+ id,
177
+ key,
178
+ payloadHash,
179
+ randomUUID(),
180
+ String(Date.now()),
181
+ JSON.stringify(frame),
182
+ );
183
+ const row = db
184
+ .prepare("SELECT * FROM events WHERE id=? AND key=?")
185
+ .get(id, key);
186
+ if (row.digest !== payloadHash) throw Error("重复事件摘要不同");
187
+ return receipt(row);
188
+ }
189
+ export function receipt(row) {
190
+ const e = JSON.parse(row.frame).data.event;
191
+ return {
192
+ type: "event.received",
193
+ data: {
194
+ receiptId: row.receipt,
195
+ eventRef: {
196
+ bindingId: e.bindingId,
197
+ epoch: e.epoch,
198
+ eventId: e.eventId,
199
+ payloadHash: row.digest,
200
+ },
201
+ persistedAt: row.at,
202
+ },
203
+ };
204
+ }
205
+ export function acknowledge(db, id, data) {
206
+ const row = db
207
+ .prepare("SELECT * FROM events WHERE id=? AND receipt=?")
208
+ .get(id, data.receiptId);
209
+ if (
210
+ !row ||
211
+ !positive(data.persistedAt) ||
212
+ canonical(data.eventRef) !== canonical(receipt(row).data.eventRef)
213
+ )
214
+ throw Error("收件确认不匹配");
215
+ db.prepare("UPDATE events SET ack=1 WHERE id=? AND key=?").run(id, row.key);
216
+ }