@openclaw/qqbot 2026.5.2 → 2026.5.3-beta.2

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 (203) hide show
  1. package/dist/api.js +646 -0
  2. package/dist/approval-cg0SVahb.js +94 -0
  3. package/dist/channel-N6Y_Rcjp.js +551 -0
  4. package/dist/channel-plugin-api.js +2 -0
  5. package/dist/channel.setup-ByCRAe5H.js +25 -0
  6. package/dist/config-D6545NkC.js +94 -0
  7. package/dist/config-schema-DFcjQw73.js +309 -0
  8. package/dist/exec-approvals-COUsM6wZ.js +138 -0
  9. package/dist/gateway-CmSUJKSt.js +6726 -0
  10. package/dist/handler-runtime-Bqm6N0WG.js +120 -0
  11. package/dist/index.js +29 -0
  12. package/dist/narrowing-BoieBTIU.js +25 -0
  13. package/dist/outbound-BJfhwrPg.js +1357 -0
  14. package/dist/request-context-DXtpwWui.js +921 -0
  15. package/dist/resolve-D_06fV6-.js +284 -0
  16. package/dist/runtime-BJAS3eXW.js +18 -0
  17. package/dist/runtime-api.js +2 -0
  18. package/dist/secret-contract-api.js +56 -0
  19. package/dist/sender-p-B14eLG.js +1987 -0
  20. package/dist/setup-entry.js +15 -0
  21. package/dist/setup-plugin-api.js +2 -0
  22. package/dist/string-normalize-Ci6NM5DE.js +98 -0
  23. package/dist/target-parser-Y0prnrXD.js +245 -0
  24. package/package.json +15 -6
  25. package/api.ts +0 -56
  26. package/channel-plugin-api.ts +0 -1
  27. package/index.ts +0 -29
  28. package/runtime-api.ts +0 -9
  29. package/setup-entry.ts +0 -9
  30. package/setup-plugin-api.ts +0 -3
  31. package/src/bridge/approval/capability.ts +0 -237
  32. package/src/bridge/approval/handler-runtime.ts +0 -204
  33. package/src/bridge/bootstrap.ts +0 -135
  34. package/src/bridge/channel-entry.ts +0 -18
  35. package/src/bridge/commands/framework-context-adapter.ts +0 -60
  36. package/src/bridge/commands/framework-registration.ts +0 -47
  37. package/src/bridge/commands/from-parser.test.ts +0 -86
  38. package/src/bridge/commands/from-parser.ts +0 -60
  39. package/src/bridge/commands/result-dispatcher.ts +0 -76
  40. package/src/bridge/config-shared.ts +0 -132
  41. package/src/bridge/config.ts +0 -111
  42. package/src/bridge/gateway.ts +0 -174
  43. package/src/bridge/logger.ts +0 -31
  44. package/src/bridge/narrowing.ts +0 -31
  45. package/src/bridge/plugin-version.test.ts +0 -146
  46. package/src/bridge/plugin-version.ts +0 -102
  47. package/src/bridge/runtime.ts +0 -25
  48. package/src/bridge/sdk-adapter.ts +0 -131
  49. package/src/bridge/setup/finalize.ts +0 -144
  50. package/src/bridge/setup/surface.ts +0 -34
  51. package/src/bridge/tools/channel.ts +0 -58
  52. package/src/bridge/tools/index.ts +0 -15
  53. package/src/bridge/tools/remind.test.ts +0 -124
  54. package/src/bridge/tools/remind.ts +0 -91
  55. package/src/channel.setup.ts +0 -33
  56. package/src/channel.ts +0 -288
  57. package/src/command-auth.test.ts +0 -62
  58. package/src/config-schema.ts +0 -84
  59. package/src/config.test.ts +0 -364
  60. package/src/engine/access/access-control.test.ts +0 -198
  61. package/src/engine/access/access-control.ts +0 -226
  62. package/src/engine/access/index.ts +0 -16
  63. package/src/engine/access/resolve-policy.test.ts +0 -59
  64. package/src/engine/access/resolve-policy.ts +0 -57
  65. package/src/engine/access/sender-match.test.ts +0 -60
  66. package/src/engine/access/sender-match.ts +0 -55
  67. package/src/engine/access/types.ts +0 -53
  68. package/src/engine/adapter/audio.port.ts +0 -27
  69. package/src/engine/adapter/commands.port.ts +0 -22
  70. package/src/engine/adapter/history.port.ts +0 -52
  71. package/src/engine/adapter/index.ts +0 -139
  72. package/src/engine/adapter/mention-gate.port.ts +0 -50
  73. package/src/engine/adapter/types.ts +0 -38
  74. package/src/engine/api/api-client.ts +0 -212
  75. package/src/engine/api/media-chunked.test.ts +0 -336
  76. package/src/engine/api/media-chunked.ts +0 -622
  77. package/src/engine/api/media.ts +0 -218
  78. package/src/engine/api/messages.ts +0 -293
  79. package/src/engine/api/retry.ts +0 -217
  80. package/src/engine/api/routes.ts +0 -95
  81. package/src/engine/api/token.ts +0 -271
  82. package/src/engine/approval/index.test.ts +0 -22
  83. package/src/engine/approval/index.ts +0 -224
  84. package/src/engine/commands/builtin/log-helpers.ts +0 -319
  85. package/src/engine/commands/builtin/register-all.ts +0 -17
  86. package/src/engine/commands/builtin/register-approve.ts +0 -201
  87. package/src/engine/commands/builtin/register-basic.ts +0 -95
  88. package/src/engine/commands/builtin/register-clear-storage.ts +0 -187
  89. package/src/engine/commands/builtin/register-logs.ts +0 -20
  90. package/src/engine/commands/builtin/register-streaming.ts +0 -137
  91. package/src/engine/commands/builtin/state.ts +0 -31
  92. package/src/engine/commands/slash-command-auth.ts +0 -48
  93. package/src/engine/commands/slash-command-handler.ts +0 -146
  94. package/src/engine/commands/slash-commands-impl.test.ts +0 -8
  95. package/src/engine/commands/slash-commands-impl.ts +0 -61
  96. package/src/engine/commands/slash-commands.ts +0 -199
  97. package/src/engine/config/credential-backup.test.ts +0 -88
  98. package/src/engine/config/credential-backup.ts +0 -107
  99. package/src/engine/config/credentials.ts +0 -76
  100. package/src/engine/config/group.test.ts +0 -234
  101. package/src/engine/config/group.ts +0 -299
  102. package/src/engine/config/resolve.test.ts +0 -152
  103. package/src/engine/config/resolve.ts +0 -283
  104. package/src/engine/config/setup-logic.ts +0 -84
  105. package/src/engine/engine-import-boundary.test.ts +0 -73
  106. package/src/engine/gateway/codec.ts +0 -47
  107. package/src/engine/gateway/constants.ts +0 -117
  108. package/src/engine/gateway/event-dispatcher.ts +0 -177
  109. package/src/engine/gateway/gateway-connection.ts +0 -371
  110. package/src/engine/gateway/gateway.ts +0 -291
  111. package/src/engine/gateway/inbound-attachments.test.ts +0 -126
  112. package/src/engine/gateway/inbound-attachments.ts +0 -360
  113. package/src/engine/gateway/inbound-context.ts +0 -195
  114. package/src/engine/gateway/inbound-pipeline.self-echo.test.ts +0 -218
  115. package/src/engine/gateway/inbound-pipeline.ts +0 -235
  116. package/src/engine/gateway/interaction-handler.ts +0 -220
  117. package/src/engine/gateway/message-queue.test.ts +0 -282
  118. package/src/engine/gateway/message-queue.ts +0 -499
  119. package/src/engine/gateway/outbound-dispatch.test.ts +0 -231
  120. package/src/engine/gateway/outbound-dispatch.ts +0 -575
  121. package/src/engine/gateway/reconnect.ts +0 -199
  122. package/src/engine/gateway/stages/access-stage.ts +0 -132
  123. package/src/engine/gateway/stages/assembly-stage.ts +0 -156
  124. package/src/engine/gateway/stages/content-stage.test.ts +0 -77
  125. package/src/engine/gateway/stages/content-stage.ts +0 -77
  126. package/src/engine/gateway/stages/envelope-stage.test.ts +0 -152
  127. package/src/engine/gateway/stages/envelope-stage.ts +0 -144
  128. package/src/engine/gateway/stages/group-gate-stage.ts +0 -292
  129. package/src/engine/gateway/stages/index.ts +0 -18
  130. package/src/engine/gateway/stages/quote-stage.ts +0 -113
  131. package/src/engine/gateway/stages/refidx-stage.ts +0 -62
  132. package/src/engine/gateway/stages/stub-contexts.ts +0 -116
  133. package/src/engine/gateway/types.ts +0 -264
  134. package/src/engine/gateway/typing-keepalive.ts +0 -79
  135. package/src/engine/group/activation.test.ts +0 -114
  136. package/src/engine/group/activation.ts +0 -147
  137. package/src/engine/group/history.test.ts +0 -314
  138. package/src/engine/group/history.ts +0 -321
  139. package/src/engine/group/mention.test.ts +0 -141
  140. package/src/engine/group/mention.ts +0 -197
  141. package/src/engine/group/message-gating.test.ts +0 -188
  142. package/src/engine/group/message-gating.ts +0 -216
  143. package/src/engine/messaging/decode-media-path.ts +0 -82
  144. package/src/engine/messaging/media-source.ts +0 -215
  145. package/src/engine/messaging/media-type-detect.ts +0 -37
  146. package/src/engine/messaging/outbound-audio-port.ts +0 -38
  147. package/src/engine/messaging/outbound-deliver.ts +0 -810
  148. package/src/engine/messaging/outbound-media-send.ts +0 -702
  149. package/src/engine/messaging/outbound-reply.ts +0 -27
  150. package/src/engine/messaging/outbound-result-helpers.ts +0 -54
  151. package/src/engine/messaging/outbound-types.ts +0 -45
  152. package/src/engine/messaging/outbound.ts +0 -485
  153. package/src/engine/messaging/reply-dispatcher.ts +0 -597
  154. package/src/engine/messaging/reply-limiter.ts +0 -164
  155. package/src/engine/messaging/sender.ts +0 -729
  156. package/src/engine/messaging/streaming-c2c.ts +0 -1192
  157. package/src/engine/messaging/streaming-media-send.ts +0 -544
  158. package/src/engine/messaging/target-parser.ts +0 -104
  159. package/src/engine/ref/format-message-ref.ts +0 -142
  160. package/src/engine/ref/format-ref-entry.test.ts +0 -60
  161. package/src/engine/ref/format-ref-entry.ts +0 -27
  162. package/src/engine/ref/store.ts +0 -208
  163. package/src/engine/ref/types.ts +0 -27
  164. package/src/engine/session/known-users.ts +0 -137
  165. package/src/engine/session/session-store.ts +0 -204
  166. package/src/engine/tools/channel-api.ts +0 -244
  167. package/src/engine/tools/remind-logic.test.ts +0 -280
  168. package/src/engine/tools/remind-logic.ts +0 -377
  169. package/src/engine/types.ts +0 -313
  170. package/src/engine/utils/attachment-tags.test.ts +0 -186
  171. package/src/engine/utils/attachment-tags.ts +0 -174
  172. package/src/engine/utils/audio.test.ts +0 -250
  173. package/src/engine/utils/audio.ts +0 -585
  174. package/src/engine/utils/data-paths.ts +0 -38
  175. package/src/engine/utils/diagnostics.ts +0 -109
  176. package/src/engine/utils/file-utils.test.ts +0 -72
  177. package/src/engine/utils/file-utils.ts +0 -225
  178. package/src/engine/utils/format.test.ts +0 -68
  179. package/src/engine/utils/format.ts +0 -70
  180. package/src/engine/utils/image-size.test.ts +0 -158
  181. package/src/engine/utils/image-size.ts +0 -249
  182. package/src/engine/utils/log.test.ts +0 -28
  183. package/src/engine/utils/log.ts +0 -61
  184. package/src/engine/utils/media-tags.test.ts +0 -32
  185. package/src/engine/utils/media-tags.ts +0 -177
  186. package/src/engine/utils/payload.test.ts +0 -68
  187. package/src/engine/utils/payload.ts +0 -145
  188. package/src/engine/utils/platform-storage-laziness.test.ts +0 -63
  189. package/src/engine/utils/platform.test.ts +0 -148
  190. package/src/engine/utils/platform.ts +0 -343
  191. package/src/engine/utils/request-context.ts +0 -60
  192. package/src/engine/utils/string-normalize.ts +0 -91
  193. package/src/engine/utils/stt.test.ts +0 -104
  194. package/src/engine/utils/stt.ts +0 -100
  195. package/src/engine/utils/text-parsing.test.ts +0 -29
  196. package/src/engine/utils/text-parsing.ts +0 -155
  197. package/src/engine/utils/upload-cache.ts +0 -96
  198. package/src/engine/utils/voice-text.ts +0 -15
  199. package/src/exec-approvals.ts +0 -218
  200. package/src/manifest-schema.test.ts +0 -56
  201. package/src/qqbot-test-support.ts +0 -29
  202. package/src/types.ts +0 -210
  203. package/tsconfig.json +0 -16
@@ -1,224 +0,0 @@
1
- /**
2
- * Approval helpers — pure functions, zero framework dependencies.
3
- *
4
- * - Build approval message text + inline keyboard
5
- * - Resolve delivery target from session metadata
6
- * - Parse INTERACTION_CREATE button data
7
- */
8
-
9
- import type { ChatScope, InlineKeyboard, KeyboardButton } from "../types.js";
10
-
11
- // ============ Types ============
12
-
13
- export interface ExecApprovalRequest {
14
- id: string;
15
- expiresAtMs: number;
16
- request: {
17
- commandPreview?: string;
18
- command?: string;
19
- cwd?: string;
20
- agentId?: string;
21
- turnSourceAccountId?: string;
22
- sessionKey?: string;
23
- turnSourceTo?: string;
24
- [key: string]: unknown;
25
- };
26
- }
27
-
28
- export interface PluginApprovalRequest {
29
- id: string;
30
- request: {
31
- timeoutMs?: number;
32
- severity?: string;
33
- title: string;
34
- description?: string;
35
- toolName?: string;
36
- pluginId?: string;
37
- agentId?: string;
38
- turnSourceAccountId?: string;
39
- sessionKey?: string;
40
- turnSourceTo?: string;
41
- [key: string]: unknown;
42
- };
43
- }
44
-
45
- type ApprovalDecision = "allow-once" | "allow-always" | "deny";
46
-
47
- interface ApprovalTarget {
48
- type: ChatScope;
49
- id: string;
50
- }
51
-
52
- interface ParsedApprovalAction {
53
- approvalId: string;
54
- decision: ApprovalDecision;
55
- }
56
-
57
- // ============ Text Builders ============
58
-
59
- export function buildExecApprovalText(request: ExecApprovalRequest): string {
60
- const expiresIn = Math.max(0, Math.round((request.expiresAtMs - Date.now()) / 1000));
61
- const lines: string[] = ["\u{1f510} \u547d\u4ee4\u6267\u884c\u5ba1\u6279", ""];
62
- const cmd = request.request.commandPreview ?? request.request.command ?? "";
63
- if (cmd) {
64
- lines.push(`\`\`\`\n${cmd.slice(0, 300)}\n\`\`\``);
65
- }
66
- if (request.request.cwd) {
67
- lines.push(`\u{1f4c1} \u76ee\u5f55: ${request.request.cwd}`);
68
- }
69
- if (request.request.agentId) {
70
- lines.push(`\u{1f916} Agent: ${request.request.agentId}`);
71
- }
72
- lines.push("", `\u23f1\ufe0f \u8d85\u65f6: ${expiresIn} \u79d2`);
73
- return lines.join("\n");
74
- }
75
-
76
- export function buildPluginApprovalText(request: PluginApprovalRequest): string {
77
- const timeoutSec = Math.round((request.request.timeoutMs ?? 120_000) / 1000);
78
- const severityIcon =
79
- request.request.severity === "critical"
80
- ? "\u{1f534}"
81
- : request.request.severity === "info"
82
- ? "\u{1f535}"
83
- : "\u{1f7e1}";
84
-
85
- const lines: string[] = [`${severityIcon} \u5ba1\u6279\u8bf7\u6c42`, ""];
86
- lines.push(`\u{1f4cb} ${request.request.title}`);
87
- if (request.request.description) {
88
- lines.push(`\u{1f4dd} ${request.request.description}`);
89
- }
90
- if (request.request.toolName) {
91
- lines.push(`\u{1f527} \u5de5\u5177: ${request.request.toolName}`);
92
- }
93
- if (request.request.pluginId) {
94
- lines.push(`\u{1f50c} \u63d2\u4ef6: ${request.request.pluginId}`);
95
- }
96
- if (request.request.agentId) {
97
- lines.push(`\u{1f916} Agent: ${request.request.agentId}`);
98
- }
99
- lines.push("", `\u23f1\ufe0f \u8d85\u65f6: ${timeoutSec} \u79d2`);
100
- return lines.join("\n");
101
- }
102
-
103
- // ============ Keyboard Builder ============
104
-
105
- /**
106
- * Build the three-button inline keyboard for approval messages.
107
- *
108
- * type=1 (Callback): click triggers INTERACTION_CREATE, button_data = data field.
109
- * group_id "approval": clicking one button grays out the others (mutual exclusion).
110
- * click_limit=1: each user can only click once.
111
- * permission.type=2: all users can interact.
112
- */
113
- export function buildApprovalKeyboard(
114
- approvalId: string,
115
- allowedDecisions: readonly ApprovalDecision[] = ["allow-once", "allow-always", "deny"],
116
- ): InlineKeyboard {
117
- const makeBtn = (
118
- id: string,
119
- label: string,
120
- visitedLabel: string,
121
- data: string,
122
- style: 0 | 1,
123
- ): KeyboardButton => ({
124
- id,
125
- render_data: { label, visited_label: visitedLabel, style },
126
- action: {
127
- type: 1,
128
- data,
129
- permission: { type: 2 },
130
- click_limit: 1,
131
- },
132
- group_id: "approval",
133
- });
134
-
135
- const buttons: KeyboardButton[] = [];
136
- if (allowedDecisions.includes("allow-once")) {
137
- buttons.push(
138
- makeBtn(
139
- "allow",
140
- "\u2705 \u5141\u8bb8\u4e00\u6b21",
141
- "\u5df2\u5141\u8bb8",
142
- `approve:${approvalId}:allow-once`,
143
- 1,
144
- ),
145
- );
146
- }
147
- if (allowedDecisions.includes("allow-always")) {
148
- buttons.push(
149
- makeBtn(
150
- "always",
151
- "\u2b50 \u59cb\u7ec8\u5141\u8bb8",
152
- "\u5df2\u59cb\u7ec8\u5141\u8bb8",
153
- `approve:${approvalId}:allow-always`,
154
- 1,
155
- ),
156
- );
157
- }
158
- if (allowedDecisions.includes("deny")) {
159
- buttons.push(
160
- makeBtn("deny", "\u274c \u62d2\u7edd", "\u5df2\u62d2\u7edd", `approve:${approvalId}:deny`, 0),
161
- );
162
- }
163
-
164
- return {
165
- content: {
166
- rows: [
167
- {
168
- buttons,
169
- },
170
- ],
171
- },
172
- };
173
- }
174
-
175
- // ============ Target Resolver ============
176
-
177
- /**
178
- * Extract the delivery target from a sessionKey or turnSourceTo string.
179
- *
180
- * Expected formats:
181
- * agent:main:qqbot:direct:OPENID -> { type: "c2c", id: "OPENID" }
182
- * agent:main:qqbot:c2c:OPENID -> { type: "c2c", id: "OPENID" }
183
- * agent:main:qqbot:group:GROUPID -> { type: "group", id: "GROUPID" }
184
- *
185
- * Returns null if neither field matches the expected pattern.
186
- */
187
- export function resolveApprovalTarget(
188
- sessionKey: string | null | undefined,
189
- turnSourceTo: string | null | undefined,
190
- ): ApprovalTarget | null {
191
- const sk = sessionKey ?? turnSourceTo;
192
- if (!sk) {
193
- return null;
194
- }
195
- const m = sk.match(/qqbot:(c2c|direct|group):([A-F0-9]+)/i);
196
- if (!m) {
197
- return null;
198
- }
199
- const type: ChatScope = m[1].toLowerCase() === "group" ? "group" : "c2c";
200
- return { type, id: m[2] };
201
- }
202
-
203
- // ============ Interaction Parser ============
204
-
205
- /**
206
- * Parse the button_data string from an INTERACTION_CREATE event.
207
- *
208
- * Expected format: `approve:<approvalId>:<decision>`
209
- * where approvalId may be prefixed with "exec:" or "plugin:".
210
- *
211
- * Returns null if the data does not match the approval button format.
212
- */
213
- export function parseApprovalButtonData(buttonData: string): ParsedApprovalAction | null {
214
- const m = buttonData.match(
215
- /^approve:((?:(?:exec|plugin):)?[0-9a-f-]+):(allow-once|allow-always|deny)$/i,
216
- );
217
- if (!m) {
218
- return null;
219
- }
220
- return {
221
- approvalId: m[1],
222
- decision: m[2] as ApprovalDecision,
223
- };
224
- }
@@ -1,319 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { getHomeDir, getQQBotDataDir, isWindows } from "../../utils/platform.js";
4
- import type { SlashCommandResult } from "../slash-commands.js";
5
-
6
- /** Read user-configured log file paths from local config files. */
7
- function getConfiguredLogFiles(): string[] {
8
- const homeDir = getHomeDir();
9
- const files: string[] = [];
10
- for (const cli of ["openclaw", "clawdbot", "moltbot"]) {
11
- try {
12
- const cfgPath = path.join(homeDir, `.${cli}`, `${cli}.json`);
13
- if (!fs.existsSync(cfgPath)) {
14
- continue;
15
- }
16
- const cfg = JSON.parse(fs.readFileSync(cfgPath, "utf8"));
17
- const logFile = cfg?.logging?.file;
18
- if (logFile && typeof logFile === "string") {
19
- files.push(path.resolve(logFile));
20
- }
21
- break;
22
- } catch {
23
- // ignore
24
- }
25
- }
26
- return files;
27
- }
28
-
29
- /** Collect directories that may contain runtime logs across common install layouts. */
30
- function collectCandidateLogDirs(): string[] {
31
- const homeDir = getHomeDir();
32
- const dirs = new Set<string>();
33
-
34
- const pushDir = (p?: string) => {
35
- if (!p) {
36
- return;
37
- }
38
- const normalized = path.resolve(p);
39
- dirs.add(normalized);
40
- };
41
-
42
- const pushStateDir = (stateDir?: string) => {
43
- if (!stateDir) {
44
- return;
45
- }
46
- pushDir(stateDir);
47
- pushDir(path.join(stateDir, "logs"));
48
- };
49
-
50
- for (const logFile of getConfiguredLogFiles()) {
51
- pushDir(path.dirname(logFile));
52
- }
53
-
54
- for (const [key, value] of Object.entries(process.env)) {
55
- if (!value) {
56
- continue;
57
- }
58
- if (/STATE_DIR$/i.test(key) && /(OPENCLAW|CLAWDBOT|MOLTBOT)/i.test(key)) {
59
- pushStateDir(value);
60
- }
61
- }
62
-
63
- for (const name of [".openclaw", ".clawdbot", ".moltbot", "openclaw", "clawdbot", "moltbot"]) {
64
- pushDir(path.join(homeDir, name));
65
- pushDir(path.join(homeDir, name, "logs"));
66
- }
67
-
68
- const searchRoots = new Set<string>([homeDir, process.cwd(), path.dirname(process.cwd())]);
69
- if (process.env.APPDATA) {
70
- searchRoots.add(process.env.APPDATA);
71
- }
72
- if (process.env.LOCALAPPDATA) {
73
- searchRoots.add(process.env.LOCALAPPDATA);
74
- }
75
-
76
- for (const root of searchRoots) {
77
- try {
78
- const entries = fs.readdirSync(root, { withFileTypes: true });
79
- for (const entry of entries) {
80
- if (!entry.isDirectory()) {
81
- continue;
82
- }
83
- if (!/(openclaw|clawdbot|moltbot)/i.test(entry.name)) {
84
- continue;
85
- }
86
- const base = path.join(root, entry.name);
87
- pushDir(base);
88
- pushDir(path.join(base, "logs"));
89
- }
90
- } catch {
91
- // Ignore missing or inaccessible directories.
92
- }
93
- }
94
-
95
- if (!isWindows()) {
96
- for (const name of ["openclaw", "clawdbot", "moltbot"]) {
97
- pushDir(path.join("/var/log", name));
98
- }
99
- }
100
-
101
- const tmpRoots = new Set<string>();
102
- if (isWindows()) {
103
- tmpRoots.add("C:\\tmp");
104
- if (process.env.TEMP) {
105
- tmpRoots.add(process.env.TEMP);
106
- }
107
- if (process.env.TMP) {
108
- tmpRoots.add(process.env.TMP);
109
- }
110
- if (process.env.LOCALAPPDATA) {
111
- tmpRoots.add(path.join(process.env.LOCALAPPDATA, "Temp"));
112
- }
113
- } else {
114
- tmpRoots.add("/tmp");
115
- }
116
- for (const tmpRoot of tmpRoots) {
117
- for (const name of ["openclaw", "clawdbot", "moltbot"]) {
118
- pushDir(path.join(tmpRoot, name));
119
- }
120
- }
121
-
122
- return Array.from(dirs);
123
- }
124
-
125
- type LogCandidate = {
126
- filePath: string;
127
- sourceDir: string;
128
- mtimeMs: number;
129
- };
130
-
131
- function collectRecentLogFiles(logDirs: string[]): LogCandidate[] {
132
- const candidates: LogCandidate[] = [];
133
- const dedupe = new Set<string>();
134
-
135
- const pushFile = (filePath: string, sourceDir: string) => {
136
- const normalized = path.resolve(filePath);
137
- if (dedupe.has(normalized)) {
138
- return;
139
- }
140
- try {
141
- const stat = fs.statSync(normalized);
142
- if (!stat.isFile()) {
143
- return;
144
- }
145
- dedupe.add(normalized);
146
- candidates.push({ filePath: normalized, sourceDir, mtimeMs: stat.mtimeMs });
147
- } catch {
148
- // Ignore missing or inaccessible files.
149
- }
150
- };
151
-
152
- for (const logFile of getConfiguredLogFiles()) {
153
- pushFile(logFile, path.dirname(logFile));
154
- }
155
-
156
- for (const dir of logDirs) {
157
- pushFile(path.join(dir, "gateway.log"), dir);
158
- pushFile(path.join(dir, "gateway.err.log"), dir);
159
- pushFile(path.join(dir, "openclaw.log"), dir);
160
- pushFile(path.join(dir, "clawdbot.log"), dir);
161
- pushFile(path.join(dir, "moltbot.log"), dir);
162
-
163
- try {
164
- const entries = fs.readdirSync(dir, { withFileTypes: true });
165
- for (const entry of entries) {
166
- if (!entry.isFile()) {
167
- continue;
168
- }
169
- if (!/\.(log|txt)$/i.test(entry.name)) {
170
- continue;
171
- }
172
- if (!/(gateway|openclaw|clawdbot|moltbot)/i.test(entry.name)) {
173
- continue;
174
- }
175
- pushFile(path.join(dir, entry.name), dir);
176
- }
177
- } catch {
178
- // Ignore missing or inaccessible directories.
179
- }
180
- }
181
-
182
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
183
- return candidates;
184
- }
185
-
186
- /**
187
- * Read the last N lines of a file without loading the entire file into memory.
188
- */
189
- function tailFileLines(
190
- filePath: string,
191
- maxLines: number,
192
- ): { tail: string[]; totalFileLines: number } {
193
- const fd = fs.openSync(filePath, "r");
194
- try {
195
- const stat = fs.fstatSync(fd);
196
- const fileSize = stat.size;
197
- if (fileSize === 0) {
198
- return { tail: [], totalFileLines: 0 };
199
- }
200
-
201
- const CHUNK_SIZE = 64 * 1024;
202
- const chunks: Buffer[] = [];
203
- let bytesRead = 0;
204
- let position = fileSize;
205
- let newlineCount = 0;
206
-
207
- while (position > 0 && newlineCount <= maxLines) {
208
- const readSize = Math.min(CHUNK_SIZE, position);
209
- position -= readSize;
210
- const buf = Buffer.alloc(readSize);
211
- fs.readSync(fd, buf, 0, readSize, position);
212
- chunks.unshift(buf);
213
- bytesRead += readSize;
214
-
215
- for (let i = 0; i < readSize; i++) {
216
- if (buf[i] === 0x0a) {
217
- newlineCount++;
218
- }
219
- }
220
- }
221
-
222
- const tailContent = Buffer.concat(chunks).toString("utf8");
223
- const allLines = tailContent.split("\n");
224
-
225
- const tail = allLines.slice(-maxLines);
226
-
227
- let totalFileLines: number;
228
- if (bytesRead >= fileSize) {
229
- totalFileLines = allLines.length;
230
- } else {
231
- const avgBytesPerLine = bytesRead / Math.max(allLines.length, 1);
232
- totalFileLines = Math.round(fileSize / avgBytesPerLine);
233
- }
234
-
235
- return { tail, totalFileLines };
236
- } finally {
237
- fs.closeSync(fd);
238
- }
239
- }
240
-
241
- /**
242
- * Build the /bot-logs result: collect recent log files, write them to a temp file.
243
- */
244
- export function buildBotLogsResult(): SlashCommandResult {
245
- const logDirs = collectCandidateLogDirs();
246
- const recentFiles = collectRecentLogFiles(logDirs).slice(0, 4);
247
-
248
- if (recentFiles.length === 0) {
249
- const existingDirs = logDirs.filter((d) => {
250
- try {
251
- return fs.existsSync(d);
252
- } catch {
253
- return false;
254
- }
255
- });
256
- const searched =
257
- existingDirs.length > 0
258
- ? existingDirs.map((d) => ` • ${d}`).join("\n")
259
- : logDirs
260
- .slice(0, 6)
261
- .map((d) => ` • ${d}`)
262
- .join("\n") + (logDirs.length > 6 ? `\n …以及另外 ${logDirs.length - 6} 个路径` : "");
263
- return [
264
- `⚠️ 未找到日志文件`,
265
- ``,
266
- `已搜索以下${existingDirs.length > 0 ? "存在的" : ""}路径:`,
267
- searched,
268
- ``,
269
- `💡 如果日志存放在自定义路径,请在配置中添加:`,
270
- ` "logging": { "file": "/path/to/your/logfile.log" }`,
271
- ].join("\n");
272
- }
273
-
274
- const lines: string[] = [];
275
- let totalIncluded = 0;
276
- let totalOriginal = 0;
277
- let truncatedCount = 0;
278
- const MAX_LINES_PER_FILE = 1000;
279
- for (const logFile of recentFiles) {
280
- try {
281
- const { tail, totalFileLines } = tailFileLines(logFile.filePath, MAX_LINES_PER_FILE);
282
- if (tail.length > 0) {
283
- const fileName = path.basename(logFile.filePath);
284
- lines.push(
285
- `\n========== ${fileName} (last ${tail.length} of ${totalFileLines} lines) ==========`,
286
- );
287
- lines.push(`from: ${logFile.sourceDir}`);
288
- lines.push(...tail);
289
- totalIncluded += tail.length;
290
- totalOriginal += totalFileLines;
291
- if (totalFileLines > MAX_LINES_PER_FILE) {
292
- truncatedCount++;
293
- }
294
- }
295
- } catch {
296
- lines.push(`[Failed to read ${path.basename(logFile.filePath)}]`);
297
- }
298
- }
299
-
300
- if (lines.length === 0) {
301
- return `⚠️ 找到了日志文件,但无法读取。请检查文件权限。`;
302
- }
303
-
304
- const tmpDir = getQQBotDataDir("downloads");
305
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
306
- const tmpFile = path.join(tmpDir, `bot-logs-${timestamp}.txt`);
307
- fs.writeFileSync(tmpFile, lines.join("\n"), "utf8");
308
-
309
- const fileCount = recentFiles.length;
310
- const topSources = Array.from(new Set(recentFiles.map((item) => item.sourceDir))).slice(0, 3);
311
- let summaryText = `共 ${fileCount} 个日志文件,包含 ${totalIncluded} 行内容`;
312
- if (truncatedCount > 0) {
313
- summaryText += `(其中 ${truncatedCount} 个文件已截断为最后 ${MAX_LINES_PER_FILE} 行,总计原始 ${totalOriginal} 行)`;
314
- }
315
- return {
316
- text: `📋 ${summaryText}\n📂 来源:${topSources.join(" | ")}`,
317
- filePath: tmpFile,
318
- };
319
- }
@@ -1,17 +0,0 @@
1
- import type { SlashCommandRegistry } from "../slash-commands.js";
2
- import { registerApproveCommands } from "./register-approve.js";
3
- import { registerBasicBotCommands } from "./register-basic.js";
4
- import { registerClearStorageCommands } from "./register-clear-storage.js";
5
- import { registerLogCommands } from "./register-logs.js";
6
- import { registerStreamingCommands } from "./register-streaming.js";
7
-
8
- /**
9
- * Register all built-in slash commands on the shared registry instance.
10
- */
11
- export function registerBuiltinSlashCommands(registry: SlashCommandRegistry): void {
12
- registerBasicBotCommands(registry);
13
- registerLogCommands(registry);
14
- registerClearStorageCommands(registry);
15
- registerStreamingCommands(registry);
16
- registerApproveCommands(registry);
17
- }