@taptap/cli 2026.11.10 → 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 (43) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +10 -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-fields-and-packages.md +3 -1
  31. package/skills/taptap-asset-library/references/asset-library-ingest.md +2 -2
  32. package/skills/taptap-asset-library/references/asset-library-search.md +15 -0
  33. package/skills/taptap-cli/references/package-type-boundary.md +1 -0
  34. package/skills/taptap-materials/SKILL.md +1 -1
  35. package/skills/taptap-package-management/SKILL.md +1 -1
  36. package/skills/taptap-package-management/references/package-management-diagnostics.md +2 -2
  37. package/taptap-suite/references/taptap-app-edit/references/app-edit-fields-and-packages.md +3 -1
  38. package/taptap-suite/references/taptap-asset-library/references/asset-library-ingest.md +2 -2
  39. package/taptap-suite/references/taptap-asset-library/references/asset-library-search.md +15 -0
  40. package/taptap-suite/references/taptap-cli/references/package-type-boundary.md +1 -0
  41. package/taptap-suite/references/taptap-materials/SKILL.md +1 -1
  42. package/taptap-suite/references/taptap-package-management/SKILL.md +1 -1
  43. package/taptap-suite/references/taptap-package-management/references/package-management-diagnostics.md +2 -2
@@ -0,0 +1,392 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { randomUUID } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import { realpathSync, statSync } from "node:fs";
8
+ import { spawn } from "node:child_process";
9
+ import { setTimeout as delay } from "node:timers/promises";
10
+ import { store, alive, positive, inboxId, defaultWorkspace } from "./store.mjs";
11
+ import { login, loginBinding, assertLoginBinding, tap, nativeCli, servers } from "./tap.mjs";
12
+ import { run } from "./process.mjs";
13
+ import { getAgent } from "./agents/index.mjs";
14
+ import { selectModel, saveModel } from "./models.mjs";
15
+
16
+ const help = `taptap-cli bot — TapTap 机器人长连接
17
+ taptap-cli bot connect --bot 2 选择机器人并登录
18
+ taptap-cli bot connect --bot 2 --reply --agent codex --model 模型ID --workspace . 接收事件并用 Codex 回复
19
+ taptap-cli bot connect --bot 2 --reply --agent cindy --model 模型ID 在 Cindy 可见会话里处理论坛 @
20
+ taptap-cli bot models --agent codex 列出模型,先让用户确认模型 ID
21
+ taptap-cli bot models --agent cindy 列出 Cindy 可用模型
22
+ taptap-cli bot cindy-login 允许 TapTap Bot 连接本机 Cindy
23
+ taptap-cli bot codex-login 授权本机 Codex
24
+ taptap-cli bot list [--profile NAME] 查看当前账号的机器人
25
+ taptap-cli bot status 所有本地实例
26
+ taptap-cli bot events --bot 2 [--limit 10] 最近事件及回复回执
27
+ taptap-cli bot stop --bot 2 停止指定实例
28
+ --bot-name 昵称:为未返回昵称的机器人指定 Codex 项目名称中的昵称。
29
+ 选项:--profile NAME、--env production|rnd、--cli 绝对路径、--personal、
30
+ --cindy-keepalive-minutes 分钟(默认 30)、--replace-epoch N、--foreground、--codex 可执行文件、--model 模型ID、--allow-workspace-write
31
+ 首次 connect --reply 请加 --model 用户确认的模型ID。后续沿用已保存模型。
32
+ 换模型:先 stop --bot ID,再 connect --bot ID --reply --agent 名称 --model 新模型ID。
33
+ 共享机器人签发结果不明时,请先核对绑定,再用 connect --retry-issue 确认重新签发。
34
+ RND 使用与环境匹配的 CLI 构建。--personal 用于论坛个人绑定的续期。
35
+ `;
36
+ async function loadListener() {
37
+ try {
38
+ return (await import("./listener.mjs")).listen;
39
+ } catch (error) {
40
+ if (error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes("'ws'"))
41
+ throw Error("机器人监听需要 ws,请安装包含可选依赖的 TapTap CLI");
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ function config(v, requireBot = true) {
47
+ const bot = v.bot;
48
+ if (requireBot && !positive(bot))
49
+ throw Error("请选择 --bot 正整数");
50
+ const env = v.env || "production",
51
+ profile = v.profile || "default";
52
+ if (
53
+ !Object.hasOwn(servers, env) ||
54
+ !/^[A-Za-z0-9][\w.-]{0,63}$/.test(profile)
55
+ )
56
+ throw Error("环境或 profile 无效");
57
+ if (env === "rnd" && !v.cli && requireBot === false)
58
+ throw Error("RND 登录需要 --cli 对应构建");
59
+ if (v.agent === "cindy" && (v["allow-workspace-write"] || v.codex))
60
+ throw Error("Cindy 论坛会话只开放文字回复");
61
+ const minutes = v["cindy-keepalive-minutes"];
62
+ if (
63
+ minutes !== undefined &&
64
+ (v.agent !== "cindy" ||
65
+ !v.reply ||
66
+ !/^[1-9]\d*$/.test(minutes) ||
67
+ Number(minutes) * 60000 > 2147483647)
68
+ )
69
+ throw Error(
70
+ "--cindy-keepalive-minutes 需要 --reply --agent cindy,并指定有效的正整数分钟数",
71
+ );
72
+ const workspace = v.workspace && realpathSync(v.workspace);
73
+ if (workspace && !statSync(workspace).isDirectory()) throw Error("工作目录无效");
74
+ if (v["allow-workspace-write"] && (!v.reply || !v.workspace))
75
+ throw Error("工作区写入需要 --reply 和 --workspace");
76
+ if (v["replace-epoch"] && !positive(v["replace-epoch"]))
77
+ throw Error("epoch 必须是正整数");
78
+ return {
79
+ env,
80
+ profile,
81
+ bot,
82
+ workspace,
83
+ reply: !!v.reply,
84
+ write: !!v["allow-workspace-write"],
85
+ model: v.model,
86
+ replace: v["replace-epoch"],
87
+ personal: !!v.personal,
88
+ cli: v.cli && realpathSync(v.cli),
89
+ agent: v.reply ? getAgent(v.agent).name : undefined,
90
+ agentOptions:
91
+ v.agent === "cindy"
92
+ ? {
93
+ keepAliveMinutes:
94
+ minutes === undefined ? undefined : Number(minutes),
95
+ discovery:
96
+ v["cindy-discovery"] && realpathSync(v["cindy-discovery"]),
97
+ }
98
+ : v.codex
99
+ ? { executable: realpathSync(v.codex) }
100
+ : undefined,
101
+ };
102
+ }
103
+ const idOf = (c) => [c.env, c.profile, c.bot].join("/");
104
+ const output = (o) => console.log(JSON.stringify(o, null, 2));
105
+ async function* accountBots(config) {
106
+ let app = "0", id = "0";
107
+ const seen = new Set();
108
+ for (;;) {
109
+ const cursor = app + "/" + id;
110
+ if (seen.has(cursor)) throw Error("列表游标重复");
111
+ seen.add(cursor);
112
+ const page = await tap(config, ["community-bot", "list", "--limit", "20",
113
+ "--after-app-id", app, "--after-id", id]);
114
+ for (const { bot_id, game_app_id, nickname } of page.bots)
115
+ yield { bot_id, game_app_id, nickname };
116
+ if (!page.has_more) return;
117
+ app = page.next_after_app_id;
118
+ id = page.next_after_id;
119
+ }
120
+ }
121
+
122
+ async function botNickname(config, saved) {
123
+ try {
124
+ for await (const bot of accountBots(config)) {
125
+ if (bot.bot_id === config.bot) {
126
+ if (bot.nickname?.trim()) return bot.nickname.trim();
127
+ break;
128
+ }
129
+ }
130
+ } catch (error) {
131
+ console.error("读取机器人昵称失败:" + error.message);
132
+ }
133
+ if (saved?.loginBinding === config.loginBinding && saved.nickname) return saved.nickname;
134
+ console.error("未取得机器人昵称,可用 --bot-name 指定 Codex 项目中的机器人名称");
135
+ }
136
+ function activeAgent(row) {
137
+ const config = JSON.parse(row.config);
138
+ return config.reply ? getAgent(config.agent).name : null;
139
+ }
140
+ function runningSummary(row, requestedAgent, requestedModel) {
141
+ if (activeAgent(row) && !JSON.parse(row.config).model)
142
+ throw Error("当前监听尚未确认模型,请先 stop,再让用户确认模型后带 --model 重新 connect");
143
+ if (requestedAgent && activeAgent(row) !== requestedAgent)
144
+ throw Error(
145
+ "请先 stop 当前实例,再用 --reply --agent " + requestedAgent + " 连接",
146
+ );
147
+ if (requestedModel !== undefined && JSON.parse(row.config).model !== requestedModel)
148
+ throw Error("监听器正在使用其他模型,请先 stop 当前实例,再带 --model 重新 connect");
149
+ return summary(row);
150
+ }
151
+ function summary(row) {
152
+ return {
153
+ instance: row.id,
154
+ agent: activeAgent(row),
155
+ model: JSON.parse(row.config).model ?? null,
156
+ status: alive(row.pid)
157
+ ? row.status
158
+ : row.status === "failed"
159
+ ? "failed"
160
+ : "stopped",
161
+ heartbeat: row.beat ? new Date(row.beat).toISOString() : null,
162
+ reason: row.reason,
163
+ binding: row.credential ? JSON.parse(row.credential).binding_id : null,
164
+ };
165
+ }
166
+ export async function main(argv) {
167
+ const [cmd, ...args] = argv;
168
+ if (!cmd || ["--help", "-h", "help"].includes(cmd) || args.includes("--help"))
169
+ return console.log(help);
170
+ // A sidecar credential represents a proxy, not a reusable local account.
171
+ if (Object.entries(process.env).some(([key, value]) =>
172
+ key.toUpperCase() === "TAPTAP_CLI_AUTH_PROXY" && value?.trim()))
173
+ throw Error("机器人需要本机登录的账号,请在 TapTap 授权代理外运行");
174
+ if (cmd === "__run") {
175
+ const listen = await loadListener();
176
+ const db = store();
177
+ try {
178
+ await listen(db, args[0], args[1]);
179
+ } finally {
180
+ db.close();
181
+ }
182
+ return;
183
+ }
184
+ const strings = [
185
+ "bot",
186
+ "bot-name",
187
+ "env",
188
+ "profile",
189
+ "cli",
190
+ "workspace",
191
+ "codex",
192
+ "agent",
193
+ "cindy-discovery",
194
+ "cindy-keepalive-minutes",
195
+ "model",
196
+ "limit",
197
+ "replace-epoch",
198
+ ];
199
+ const flags = [
200
+ "reply",
201
+ "foreground",
202
+ "allow-workspace-write",
203
+ "personal",
204
+ "retry-issue",
205
+ ];
206
+ const { values: v } = parseArgs({
207
+ args,
208
+ options: Object.fromEntries([
209
+ ...strings.map((k) => [k, { type: "string" }]),
210
+ ...flags.map((k) => [k, { type: "boolean" }]),
211
+ ]),
212
+ });
213
+ if (v["bot-name"] !== undefined &&
214
+ (cmd !== "connect" || !v.reply || v.agent === "cindy" || v.workspace || !v["bot-name"].trim()))
215
+ throw Error("--bot-name 仅用于 Codex 的默认项目,请提供机器人昵称");
216
+ if (v["retry-issue"] && (cmd !== "connect" || v.personal || v["replace-epoch"]))
217
+ throw Error("--retry-issue 仅适用于共享机器人的 connect");
218
+ if (v.model !== undefined && (cmd !== "connect" || !v.reply || !v.model.trim()))
219
+ throw Error("--model 需要与 connect --reply 一起使用,请提供用户确认的模型 ID");
220
+ if (cmd === "models") {
221
+ if (!v.agent) throw Error("请使用 models --agent codex 或 models --agent cindy");
222
+ const agent = getAgent(v.agent);
223
+ const options = {
224
+ executable: v.codex && realpathSync(v.codex),
225
+ discovery: v["cindy-discovery"] && realpathSync(v["cindy-discovery"]),
226
+ };
227
+ const workspace = v.workspace ? realpathSync(v.workspace) : process.cwd();
228
+ return output({ agent: agent.name, models: await agent.listModels(options, workspace) });
229
+ }
230
+ if (v.agent !== undefined && (cmd !== "connect" || !v.reply))
231
+ throw Error("--agent 需要与 connect --reply 一起使用");
232
+ if (cmd === "cindy-login")
233
+ return getAgent("cindy").login({ discovery: v["cindy-discovery"] });
234
+ if (cmd === "codex-login") {
235
+ return getAgent("codex").login({ executable: v.codex });
236
+ }
237
+ if (cmd === "list" || cmd === "login") {
238
+ const c = config(v, false);
239
+ await login(c);
240
+ if (cmd === "list") {
241
+ const bots = [];
242
+ for await (const bot of accountBots(c)) bots.push(bot);
243
+ output(bots);
244
+ }
245
+ return;
246
+ }
247
+ const db = store();
248
+ try {
249
+ if (cmd === "status")
250
+ return output(
251
+ db.prepare("SELECT * FROM instances ORDER BY id").all().map(summary),
252
+ );
253
+ const c = config(v),
254
+ id = idOf(c);
255
+ let row = db.prepare("SELECT * FROM instances WHERE id=?").get(id);
256
+ if (cmd === "events") {
257
+ const saved = row && JSON.parse(row.config);
258
+ const limit = Number(v.limit || 10);
259
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
260
+ throw Error("limit 范围 1–100");
261
+ if (!saved?.loginBinding) return output([]);
262
+ await assertLoginBinding(saved);
263
+ return output(
264
+ db
265
+ .prepare(
266
+ "SELECT frame,at,ack,phase,reply,visibleSession FROM events WHERE id=? ORDER BY rowid DESC LIMIT ?",
267
+ )
268
+ .all(inboxId(id, saved), limit)
269
+ .map((r) => {
270
+ const data = JSON.parse(r.frame).data;
271
+ return {
272
+ at: new Date(Number(r.at)).toISOString(),
273
+ event: data.event.eventId,
274
+ source: data.event.sourceId,
275
+ body: data.content?.current?.body,
276
+ ...(r.visibleSession ? { cindySessionId: r.visibleSession } : {}),
277
+ ack: !!r.ack,
278
+ phase: r.phase,
279
+ reply: r.reply && JSON.parse(r.reply),
280
+ };
281
+ }),
282
+ );
283
+ }
284
+ if (cmd === "stop") {
285
+ if (alive(row?.pid)) {
286
+ db.prepare("UPDATE instances SET stop=1 WHERE id=?").run(id);
287
+ for (
288
+ let i = 0;
289
+ i < 240 &&
290
+ alive(
291
+ db.prepare("SELECT pid FROM instances WHERE id=?").get(id)?.pid,
292
+ );
293
+ i++
294
+ )
295
+ await delay(250);
296
+ if (
297
+ alive(db.prepare("SELECT pid FROM instances WHERE id=?").get(id)?.pid)
298
+ )
299
+ throw Error("实例正在停止,请用 status 查看");
300
+ }
301
+ return output({ instance: id, status: "stopped" });
302
+ }
303
+ if (cmd !== "connect") throw Error("未知命令,请运行 taptap-cli bot --help");
304
+ if (alive(row?.pid)) {
305
+ await assertLoginBinding(JSON.parse(row.config));
306
+ return output(runningSummary(row, c.agent, c.model));
307
+ }
308
+ if (c.env === "rnd" && !c.cli) throw Error("RND 需要 --cli 指定 RND 构建");
309
+ const listen = await loadListener();
310
+ await login(c);
311
+ c.loginBinding = await loginBinding(c);
312
+ if (!c.workspace) {
313
+ if (c.agent === "codex") c.nickname = v["bot-name"]?.trim() || await botNickname(c, row && JSON.parse(row.config));
314
+ Object.assign(c, defaultWorkspace(id, c.loginBinding, c));
315
+ }
316
+ if (c.reply) {
317
+ const agent = getAgent(c.agent);
318
+ c.model = selectModel(db, id, c, row && JSON.parse(row.config));
319
+ const models = await agent.listModels(c.agentOptions, c.workspace);
320
+ if (!models.some(model => model.id === c.model))
321
+ throw Error("所选模型不可用:" + c.model + "。请运行 bot models --agent " + agent.name + ",让用户重新确认后使用 --model");
322
+
323
+ if (agent.prepareProject) {
324
+ const projectId = await agent.prepareProject(c.workspace, c.agentOptions);
325
+ c.agentOptions = { ...c.agentOptions, projectId };
326
+ }
327
+ }
328
+ if (c.replace) {
329
+ const check = await run(c.cli || nativeCli(), [
330
+ "community-bot",
331
+ "create-connection",
332
+ "--help",
333
+ ]);
334
+ if (!check.stdout.includes("--replace-epoch"))
335
+ throw Error("此 CLI 不支持个人绑定替换,请用 --cli 指定兼容构建");
336
+ }
337
+ const ticket = randomUUID();
338
+ db.exec("BEGIN IMMEDIATE");
339
+ try {
340
+ row = db.prepare("SELECT * FROM instances WHERE id=?").get(id);
341
+ if (alive(row?.pid)) {
342
+ if (JSON.parse(row.config).loginBinding !== c.loginBinding)
343
+ throw Error("已有不同账号的实例,请先 stop");
344
+ const result = runningSummary(row, c.agent, c.model);
345
+ db.exec("COMMIT");
346
+ return output(result);
347
+ }
348
+ const previous = row && JSON.parse(row.config);
349
+ if (v["retry-issue"] &&
350
+ (!row?.issuing || previous.personal || previous.replace))
351
+ throw Error("--retry-issue 需要存在签发结果待确认的共享连接");
352
+ if (row?.issuing && !c.replace && !v["retry-issue"])
353
+ throw Error("签发结果待确认,请核对绑定:共享连接使用 --retry-issue,个人连接使用 --replace-epoch");
354
+ // Unscoped credentials from earlier releases cannot establish ownership.
355
+ if (previous && previous.loginBinding !== c.loginBinding)
356
+ db.prepare("UPDATE instances SET credential=NULL WHERE id=?").run(id);
357
+ if (v["retry-issue"]) c.retryIssue = true;
358
+ db.prepare(
359
+ `INSERT INTO instances(id,config,status,pid,launch) VALUES(?,?,'starting',?,?) ON CONFLICT(id) DO UPDATE SET
360
+ config=excluded.config,pid=excluded.pid,launch=excluded.launch,status='starting',reason=NULL,stop=0`,
361
+ ).run(id, JSON.stringify(c), process.pid, ticket);
362
+ if (c.reply) saveModel(db, id, c);
363
+ db.exec("COMMIT");
364
+ } catch (e) {
365
+ db.exec("ROLLBACK");
366
+ throw e;
367
+ }
368
+ if (v.foreground) return await listen(db, id, ticket);
369
+ const child = spawn(
370
+ process.execPath,
371
+ [fileURLToPath(new URL("../run.js", import.meta.url)), "bot", "__run", id, ticket],
372
+ { stdio: "ignore", windowsHide: true, detached: true },
373
+ );
374
+ await new Promise((ok, no) => {
375
+ child.once("spawn", ok);
376
+ child.once("error", no);
377
+ });
378
+ child.unref();
379
+ for (let i = 0; i < 240; i++) {
380
+ await delay(250);
381
+ row = db.prepare("SELECT * FROM instances WHERE id=?").get(id);
382
+ if (row.status === "listening") return output(summary(row));
383
+ if (row.stop && row.launch === ticket) throw Error("启动已取消");
384
+ if (row.status === "failed") throw Error(row.reason || "连接失败");
385
+ if (child.exitCode !== null && (row.launch === ticket || !alive(row.pid)))
386
+ throw Error("后台进程已退出");
387
+ }
388
+ throw Error("后台监听器尚未就绪,请运行 bot status 查看状态");
389
+ } finally {
390
+ db.close();
391
+ }
392
+ }
@@ -0,0 +1,10 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ module.exports = async function runBot(args) {
5
+ if (!process.getBuiltinModule?.("node:sqlite")?.DatabaseSync) {
6
+ throw new Error("taptap-cli bot requires built-in SQLite. Use Node.js 22.13+ LTS or a newer LTS.");
7
+ }
8
+ const bot = await import("./cli.mjs");
9
+ return bot.main(args);
10
+ };
@@ -0,0 +1,97 @@
1
+ // Copyright (c) 2026 TapTap
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { positive } from "./store.mjs";
5
+
6
+ export const contextTool = {
7
+ name: "taptap_cli_get_content",
8
+ description: "读取本次 @ 的正文、原帖和从原帖到直接上级的回复链。无需参数。",
9
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
10
+ };
11
+
12
+ export async function forumMessage(ctx, continuing) {
13
+ const { message_body } = await ctx.readContent();
14
+ const parts = ["TapTap 论坛 @ 提问", message_body];
15
+ if (!continuing) {
16
+ const chain = await ctx.readChain();
17
+ if (chain.ancestors.length)
18
+ parts.push("原帖和上级楼层", JSON.stringify(chain.ancestors));
19
+ if (chain.truncated) parts.push("回复链上下文不完整。");
20
+ }
21
+ parts.push(
22
+ "需要查看本次 @ 的原帖和上级楼层时,调用 taptap_cli_get_content,无需参数。",
23
+ );
24
+ return parts.join("\n\n");
25
+ }
26
+
27
+ // Walk only references from this event. ROOT is scoped by the server-side grant.
28
+ export async function loadReplyChain(data, currentItem, query, signal) {
29
+ const e = data.event;
30
+ if (e.sourceType === "BOT_PLATFORM_SOURCE_TOPIC")
31
+ return { ancestors: [], truncated: false };
32
+ if (Array.isArray(data.content?.ancestors) && data.content.ancestors.length)
33
+ return {
34
+ ancestors: data.content.ancestors,
35
+ truncated: !!data.content.truncated,
36
+ };
37
+
38
+ const ancestors = [];
39
+ let truncated = false;
40
+ async function read(kind, target) {
41
+ signal.throwIfAborted();
42
+ try {
43
+ const result = await query({ kind, ...(target ? { target } : {}) });
44
+ return result.item;
45
+ } catch {
46
+ signal.throwIfAborted();
47
+ return null;
48
+ }
49
+ }
50
+ const root = await read("ROOT");
51
+ if (
52
+ typeof root?.content === "string" &&
53
+ (!root.ref || (root.ref.type === "TOPIC" && root.ref.id === e.rootTopicId))
54
+ )
55
+ ancestors.push({ type: "TOPIC", id: e.rootTopicId, body: root.content });
56
+ else truncated = true;
57
+
58
+ const parents = [];
59
+ let target = {
60
+ type: e.sourceType.replace("BOT_PLATFORM_SOURCE_", ""),
61
+ id: e.sourceId,
62
+ };
63
+ let expected = currentItem.parent_ref;
64
+ const seen = new Set([target.type + "/" + target.id]);
65
+ while (target.type === "REPLY") {
66
+ if (expected?.type === "TOPIC") {
67
+ truncated ||= expected.id !== e.rootTopicId;
68
+ break;
69
+ }
70
+ if (parents.length >= 8) {
71
+ truncated = true;
72
+ break;
73
+ }
74
+ const item = await read("PARENT", target);
75
+ const ref = item?.ref ?? expected;
76
+ if (
77
+ !ref ||
78
+ !positive(ref.id) ||
79
+ !["TOPIC", "COMMENT", "REPLY"].includes(ref.type) ||
80
+ (expected && (expected.type !== ref.type || expected.id !== ref.id)) ||
81
+ typeof item?.content !== "string" ||
82
+ seen.has(ref.type + "/" + ref.id)
83
+ ) {
84
+ truncated = true;
85
+ break;
86
+ }
87
+ if (ref.type === "TOPIC") {
88
+ truncated ||= ref.id !== e.rootTopicId;
89
+ break;
90
+ }
91
+ seen.add(ref.type + "/" + ref.id);
92
+ parents.push({ type: ref.type, id: ref.id, body: item.content });
93
+ target = ref;
94
+ expected = item.parent_ref;
95
+ }
96
+ return { ancestors: ancestors.concat(parents.reverse()), truncated };
97
+ }