t3-code-qqbot 0.0.0-stage → 1.2.3

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/dist/cli.mjs ADDED
@@ -0,0 +1,2307 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawn } from "node:child_process";
5
+ import { createWriteStream } from "node:fs";
6
+ import { mkdir as mkdir3, readdir, readFile as readFile5, rename as rename2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
7
+ import { homedir as homedir3, tmpdir } from "node:os";
8
+ import { dirname as dirname5, extname, join as join5, resolve as resolve4 } from "node:path";
9
+ import { setTimeout as sleep } from "node:timers/promises";
10
+
11
+ // src/config.ts
12
+ import { realpathSync } from "node:fs";
13
+ import { access, readFile } from "node:fs/promises";
14
+ import path, { dirname, isAbsolute, join, resolve } from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+
17
+ // src/protocol.ts
18
+ import { createHash } from "node:crypto";
19
+ var MAX_ATTACHMENT_BYTES = 12 * 1024 * 1024;
20
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
21
+
22
+ // src/config.ts
23
+ var APP_VERSION = "1.2.3";
24
+ var SELF_UPDATE_EXIT_CODE = 75;
25
+ var DEFAULT_ATTACHMENT_HOSTS = [
26
+ "multimedia.nt.qq.com.cn",
27
+ "multimedia.nt.qq.com",
28
+ "gchat.qpic.cn",
29
+ "c2cpicdw.qpic.cn"
30
+ ];
31
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
32
+ function isMainModule(metaUrl, argv1 = process.argv[1]) {
33
+ if (!argv1) return false;
34
+ const resolved = resolve(argv1);
35
+ if (metaUrl === pathToFileURL(resolved).href) return true;
36
+ try {
37
+ return metaUrl === pathToFileURL(realpathSync(resolved)).href;
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+ function isLoopbackOrigin(origin) {
43
+ try {
44
+ const url = new URL(origin);
45
+ return (url.protocol === "http:" || url.protocol === "https:") && LOOPBACK_HOSTS.has(url.hostname);
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+ function normalizePathForCompare(targetPath, platform = process.platform) {
51
+ const pathImpl = platform === "win32" ? path.win32 : path.posix;
52
+ const normalized = pathImpl.resolve(targetPath);
53
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
54
+ }
55
+ function samePath(a, b, platform = process.platform) {
56
+ return normalizePathForCompare(a, platform) === normalizePathForCompare(b, platform);
57
+ }
58
+ function scopeToHash(scope) {
59
+ const trimmed = scope.trim();
60
+ if (/^sha256:[a-f0-9]{64}$/i.test(trimmed)) {
61
+ return trimmed.slice("sha256:".length).toLowerCase();
62
+ }
63
+ if (!/^(c2c|group):.+$/i.test(trimmed)) {
64
+ throw new Error(
65
+ `Invalid binding scope "${scope}". Expected "c2c:<user_openid>", "group:<group_openid>", or "sha256:<64-hex>".`
66
+ );
67
+ }
68
+ return digest(trimmed);
69
+ }
70
+ function resolveRelative(baseDir, maybeRelative) {
71
+ return isAbsolute(maybeRelative) ? resolve(maybeRelative) : resolve(baseDir, maybeRelative);
72
+ }
73
+ function parseConfig(raw, configPath) {
74
+ const absConfigPath = resolve(configPath);
75
+ const configDir = dirname(absConfigPath);
76
+ if (!raw || typeof raw !== "object") {
77
+ throw new Error("Config must be a JSON object");
78
+ }
79
+ if (!raw.stateDir || typeof raw.stateDir !== "string") {
80
+ throw new Error('Config requires "stateDir"');
81
+ }
82
+ if (!raw.t3?.origin || typeof raw.t3.origin !== "string") {
83
+ throw new Error('Config requires "t3.origin"');
84
+ }
85
+ if (!isLoopbackOrigin(raw.t3.origin)) {
86
+ throw new Error(`Config "t3.origin" must target loopback (127.0.0.1 / localhost / ::1), got: ${raw.t3.origin}`);
87
+ }
88
+ const port = raw.bridge?.port ?? 18773;
89
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
90
+ throw new Error(`Invalid bridge port: ${port}`);
91
+ }
92
+ const host = raw.bridge?.host ?? "127.0.0.1";
93
+ if (!LOOPBACK_HOSTS.has(host)) {
94
+ throw new Error(`Bridge host must be loopback for security, got: ${host}`);
95
+ }
96
+ const maxMessageChars = raw.bridge?.maxMessageChars ?? 1600;
97
+ if (!Number.isInteger(maxMessageChars) || maxMessageChars < 100 || maxMessageChars > 4e3) {
98
+ throw new Error(`Invalid bridge.maxMessageChars (${maxMessageChars}); expected integer between 100 and 4000`);
99
+ }
100
+ const rawBindings = Array.isArray(raw.bindings) ? raw.bindings : [];
101
+ const bindings = rawBindings.map((binding, index) => {
102
+ if (!binding || typeof binding.scope !== "string" || !binding.scope.trim()) {
103
+ throw new Error(`Binding #${index} is missing "scope"`);
104
+ }
105
+ if (typeof binding.workspace !== "string" || !binding.workspace.trim()) {
106
+ throw new Error(`Binding #${index} (${binding.scope}) is missing "workspace"`);
107
+ }
108
+ const threadId = typeof binding.threadId === "string" && binding.threadId.trim() && !binding.threadId.startsWith("REPLACE_WITH_") ? binding.threadId.trim() : void 0;
109
+ return {
110
+ rawScope: binding.scope.trim(),
111
+ scopeHash: scopeToHash(binding.scope),
112
+ workspace: resolveRelative(configDir, binding.workspace.trim()),
113
+ threadId,
114
+ modelSelection: binding.modelSelection
115
+ };
116
+ });
117
+ const bridgeUrl = raw.gateway?.bridgeUrl?.trim() || `http://${host === "::1" ? "[::1]" : host}:${port}/events`;
118
+ return {
119
+ configPath: absConfigPath,
120
+ configDir,
121
+ stateDir: resolveRelative(configDir, raw.stateDir),
122
+ credentialsFile: raw.credentialsFile ? resolveRelative(configDir, raw.credentialsFile) : void 0,
123
+ t3: {
124
+ origin: raw.t3.origin.trim(),
125
+ executable: raw.t3.executable?.trim() || "auto",
126
+ prefix: Array.isArray(raw.t3.prefix) ? raw.t3.prefix.map(String) : [],
127
+ env: raw.t3.env && typeof raw.t3.env === "object" ? { ...raw.t3.env } : {},
128
+ home: raw.t3.home ? resolveRelative(configDir, raw.t3.home) : void 0,
129
+ muteMobileCompletionThreadId: raw.t3.muteMobileCompletionThreadId?.trim() || void 0
130
+ },
131
+ bridge: {
132
+ host,
133
+ port,
134
+ proactiveBackgroundReports: Boolean(raw.bridge?.proactiveBackgroundReports),
135
+ maxMessageChars,
136
+ autoSettleThread: Boolean(raw.bridge?.autoSettleThread),
137
+ enableSlashCommands: raw.bridge?.enableSlashCommands ?? true,
138
+ testStaging: raw.bridge?.testStaging ? resolveRelative(configDir, raw.bridge.testStaging) : void 0
139
+ },
140
+ gateway: {
141
+ bridgeUrl,
142
+ requireMentionInGroup: raw.gateway?.requireMentionInGroup ?? true,
143
+ stripPrefix: raw.gateway?.stripPrefix ?? ""
144
+ },
145
+ attachmentHosts: Array.isArray(raw.attachmentHosts) && raw.attachmentHosts.length > 0 ? raw.attachmentHosts.map((h) => String(h).trim().toLowerCase()).filter(Boolean) : [...DEFAULT_ATTACHMENT_HOSTS],
146
+ bindings
147
+ };
148
+ }
149
+ async function loadConfig(configPath) {
150
+ const rawText = await readFile(configPath, "utf8");
151
+ const parsed = JSON.parse(rawText.replace(/^\uFEFF/, ""));
152
+ return parseConfig(parsed, configPath);
153
+ }
154
+ async function loadCredentials(config, env = process.env, options = {}) {
155
+ const requireBridgeSecret = options.requireBridgeSecret ?? true;
156
+ const envAppId = env.QQ_APP_ID?.trim() || "";
157
+ const envAppSecret = env.QQ_APP_SECRET?.trim() || "";
158
+ const envBridgeSecret = env.QQ_BRIDGE_SECRET?.trim() || "";
159
+ const explicitCredsFile = env.QQ_CREDENTIALS_FILE?.trim();
160
+ const envHasAll = Boolean(envAppId && envAppSecret && (!requireBridgeSecret || envBridgeSecret));
161
+ let fileCreds = {};
162
+ const credentialsPath = explicitCredsFile || (envHasAll ? void 0 : config.credentialsFile);
163
+ if (credentialsPath) {
164
+ try {
165
+ const raw = await readFile(credentialsPath, "utf8");
166
+ fileCreds = JSON.parse(raw.replace(/^\uFEFF/, ""));
167
+ } catch (error) {
168
+ if (error.code === "ENOENT" && !explicitCredsFile && envHasAll) {
169
+ fileCreds = {};
170
+ } else {
171
+ throw error;
172
+ }
173
+ }
174
+ }
175
+ const appId = envAppId || fileCreds.appId?.trim() || "";
176
+ const appSecret = envAppSecret || fileCreds.appSecret?.trim() || "";
177
+ const bridgeSecret = envBridgeSecret || fileCreds.bridgeSecret?.trim() || "";
178
+ if (!appId || !appSecret || requireBridgeSecret && !bridgeSecret) {
179
+ const missing = requireBridgeSecret ? "appId, appSecret, bridgeSecret" : "appId, appSecret";
180
+ throw new Error(
181
+ `Missing QQ Bot credentials (${missing}). Set them in credentials.json or environment variables.`
182
+ );
183
+ }
184
+ if (appId.startsWith("REPLACE_WITH_") || appSecret.startsWith("REPLACE_WITH_") || requireBridgeSecret && bridgeSecret.startsWith("REPLACE_WITH_")) {
185
+ throw new Error("Credentials still contain REPLACE_WITH_* placeholder values. Edit credentials.json first.");
186
+ }
187
+ return { appId, appSecret, bridgeSecret };
188
+ }
189
+
190
+ // src/menu.ts
191
+ import { randomBytes } from "node:crypto";
192
+ import { access as access3, mkdir as mkdir2, readFile as readFile4, rename, writeFile as writeFile2 } from "node:fs/promises";
193
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join4, resolve as resolve3 } from "node:path";
194
+ import { createInterface } from "node:readline/promises";
195
+
196
+ // src/observe.ts
197
+ import { readFile as readFile2 } from "node:fs/promises";
198
+ var McpHttpError = class extends Error {
199
+ status;
200
+ constructor(method, status) {
201
+ super(`T3 MCP ${method} HTTP ${status}`);
202
+ this.status = status;
203
+ }
204
+ };
205
+ var Observer = class {
206
+ state = null;
207
+ connecting;
208
+ id = 0;
209
+ url;
210
+ issue;
211
+ revoke;
212
+ constructor(origin, issue, revoke) {
213
+ this.url = new URL("/mcp", origin).href;
214
+ this.issue = issue;
215
+ this.revoke = revoke;
216
+ }
217
+ async rpcWith(token, sessionId, method, params, notification = false) {
218
+ const response = await fetch(this.url, {
219
+ method: "POST",
220
+ signal: AbortSignal.timeout(15e3),
221
+ headers: {
222
+ Authorization: `Bearer ${token}`,
223
+ "Content-Type": "application/json",
224
+ Accept: "application/json, text/event-stream",
225
+ ...sessionId ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-06-18" } : {}
226
+ },
227
+ body: JSON.stringify({
228
+ jsonrpc: "2.0",
229
+ method,
230
+ params,
231
+ ...!notification ? { id: ++this.id } : {}
232
+ })
233
+ });
234
+ if (!response.ok) {
235
+ await response.body?.cancel().catch(() => {
236
+ });
237
+ throw new McpHttpError(method, response.status);
238
+ }
239
+ const newSessionId = method === "initialize" ? response.headers.get("mcp-session-id") : void 0;
240
+ if (notification) {
241
+ await response.body?.cancel().catch(() => {
242
+ });
243
+ return { newSessionId };
244
+ }
245
+ const contentType = response.headers.get("content-type") ?? "";
246
+ let body;
247
+ if (contentType.includes("text/event-stream")) {
248
+ const text = await response.text();
249
+ const dataLine = text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).filter(Boolean).at(-1);
250
+ if (!dataLine) throw new Error(`T3 MCP ${method} returned empty SSE stream`);
251
+ body = JSON.parse(dataLine);
252
+ } else {
253
+ body = await response.json();
254
+ }
255
+ if (body.error) {
256
+ throw new Error(
257
+ `T3 MCP ${method} error ${body.error.code}${body.error.message ? `: ${body.error.message}` : ""}`
258
+ );
259
+ }
260
+ return { result: body.result, newSessionId };
261
+ }
262
+ async connect(force = false) {
263
+ if (!force && this.state && Date.now() < this.state.renewAt) {
264
+ return this.state;
265
+ }
266
+ if (!this.connecting) {
267
+ const previousAuthId = this.state?.authSessionId;
268
+ this.connecting = (async () => {
269
+ const issued = await this.issue();
270
+ if (!issued.token) throw new Error("T3 MCP session returned no bearer token");
271
+ const init = await this.rpcWith(issued.token, null, "initialize", {
272
+ protocolVersion: "2025-06-18",
273
+ capabilities: {},
274
+ clientInfo: { name: "t3-code-qqbot", version: APP_VERSION }
275
+ });
276
+ if (!init.newSessionId) throw new Error("T3 MCP did not return an mcp-session-id header");
277
+ await this.rpcWith(issued.token, init.newSessionId, "notifications/initialized", void 0, true);
278
+ const next = {
279
+ token: issued.token,
280
+ sessionId: init.newSessionId,
281
+ authSessionId: issued.sessionId,
282
+ renewAt: Date.now() + 50 * 6e4
283
+ };
284
+ this.state = next;
285
+ if (previousAuthId && previousAuthId !== issued.sessionId && this.revoke) {
286
+ void this.revoke(previousAuthId).catch(() => {
287
+ });
288
+ }
289
+ return next;
290
+ })().finally(() => {
291
+ this.connecting = void 0;
292
+ });
293
+ }
294
+ return this.connecting;
295
+ }
296
+ async close() {
297
+ const authId = this.state?.authSessionId;
298
+ this.state = null;
299
+ if (authId && this.revoke) {
300
+ await this.revoke(authId).catch(() => {
301
+ });
302
+ }
303
+ }
304
+ async callWithSession(name, args) {
305
+ let session = await this.connect(false);
306
+ let result;
307
+ try {
308
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
309
+ } catch (error) {
310
+ if (error instanceof McpHttpError && (error.status === 401 || error.status === 404)) {
311
+ if (this.state === session) this.state = null;
312
+ session = await this.connect(true);
313
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
314
+ } else {
315
+ throw error;
316
+ }
317
+ }
318
+ if (result?.isError) {
319
+ const detail = result?.content?.[0]?.text ? `: ${String(result.content[0].text)}` : "";
320
+ throw new Error(`T3 MCP tool rejected (${name})${detail}`);
321
+ }
322
+ if (result?.structuredContent !== void 0) {
323
+ return { data: result.structuredContent, session };
324
+ }
325
+ const text = result?.content?.[0]?.text;
326
+ if (typeof text !== "string") {
327
+ throw new Error(`T3 MCP tool (${name}) returned empty content`);
328
+ }
329
+ return { data: JSON.parse(text), session };
330
+ }
331
+ async call(name, args) {
332
+ const { data } = await this.callWithSession(name, args);
333
+ return data;
334
+ }
335
+ async upload(filePath, name, mimeType) {
336
+ const bytes = await readFile2(filePath);
337
+ const attachment = {
338
+ name,
339
+ mimeType,
340
+ sizeBytes: bytes.length,
341
+ type: /^image\/(png|jpeg|webp|gif)$/.test(mimeType) ? "image" : "file"
342
+ };
343
+ const { data: staged, session } = await this.callWithSession("t3_attachment_prepare_upload", { upload: attachment });
344
+ try {
345
+ const endpoint = new URL(staged.uploadUrl ?? staged.relativeUrl, this.url);
346
+ if (endpoint.origin !== new URL(this.url).origin) {
347
+ throw new Error("Unexpected T3 attachment upload origin");
348
+ }
349
+ const response = await fetch(endpoint, {
350
+ method: "POST",
351
+ signal: AbortSignal.timeout(3e4),
352
+ redirect: "error",
353
+ headers: {
354
+ Authorization: `Bearer ${session.token}`,
355
+ "Content-Type": mimeType
356
+ },
357
+ body: bytes
358
+ });
359
+ if (!response.ok) {
360
+ await response.body?.cancel().catch(() => {
361
+ });
362
+ throw new Error(`T3 native attachment upload HTTP ${response.status}`);
363
+ }
364
+ await response.body?.cancel().catch(() => {
365
+ });
366
+ return { ...attachment, id: staged.attachmentId };
367
+ } catch (error) {
368
+ await this.call("t3_attachment_discard", { attachmentId: staged.attachmentId }).catch(() => {
369
+ });
370
+ throw error;
371
+ }
372
+ }
373
+ async read(threadId, view = "messages", itemId) {
374
+ return this.call("t3_thread_read", {
375
+ threadId,
376
+ view,
377
+ itemId,
378
+ limit: 40,
379
+ runLimit: 50,
380
+ maxCharsPerItem: 2e4
381
+ });
382
+ }
383
+ };
384
+
385
+ // src/qr-login.ts
386
+ import { qrConnect } from "@tencent-connect/qqbot-connector";
387
+ async function runQrBotLogin(options = {}) {
388
+ const controller = new AbortController();
389
+ const timeoutMs = options.timeoutMs ?? 5 * 6e4;
390
+ const timer = setTimeout(() => controller.abort(new Error("\u626B\u7801\u8D85\u65F6\uFF085\u5206\u949F\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u3002")), timeoutMs);
391
+ const onSigint = () => controller.abort(new Error("\u7528\u6237\u5DF2\u53D6\u6D88\u626B\u7801\u3002"));
392
+ process.once("SIGINT", onSigint);
393
+ console.log("\n\u8BF7\u4F7F\u7528\u624B\u673A QQ \u626B\u63CF\u4E0B\u65B9\u4E8C\u7EF4\u7801\u4E00\u952E\u7ED1\u5B9A\u4F60\u7684 QQ \u673A\u5668\u4EBA\uFF08\u6309 Ctrl+C \u53EF\u53D6\u6D88\uFF09\uFF1A\n");
394
+ try {
395
+ const list = await qrConnect({
396
+ signal: controller.signal,
397
+ source: "t3-code-qqbot"
398
+ });
399
+ const picked = list[0];
400
+ if (!picked?.appId || !picked?.appSecret) {
401
+ throw new Error("\u626B\u7801\u5B8C\u6210\u4F46\u672A\u8FD4\u56DE\u6709\u6548\u7684 AppID / AppSecret\u3002");
402
+ }
403
+ return {
404
+ appId: picked.appId,
405
+ appSecret: picked.appSecret,
406
+ ...picked.userOpenid ? { userOpenid: picked.userOpenid } : {}
407
+ };
408
+ } finally {
409
+ clearTimeout(timer);
410
+ process.off("SIGINT", onSigint);
411
+ }
412
+ }
413
+
414
+ // src/service.ts
415
+ import { execFile } from "node:child_process";
416
+ import { mkdir, unlink, writeFile } from "node:fs/promises";
417
+ import { homedir } from "node:os";
418
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
419
+ import { promisify } from "node:util";
420
+ var execFileAsync = promisify(execFile);
421
+ var DEFAULT_LINUX_SERVICE = "t3-code-qqbot";
422
+ var DEFAULT_WINDOWS_TASK = "T3 Code QQBot";
423
+ function sanitizeServiceName(raw, platform) {
424
+ const trimmed = raw.trim();
425
+ if (!trimmed) {
426
+ return platform === "win32" ? DEFAULT_WINDOWS_TASK : DEFAULT_LINUX_SERVICE;
427
+ }
428
+ if (platform === "win32") {
429
+ if (!/^[A-Za-z0-9 _.-]{1,64}$/.test(trimmed)) {
430
+ throw new Error(`Invalid Windows task name "${raw}". Use letters, numbers, spaces, "_", "-", or "." only.`);
431
+ }
432
+ return trimmed;
433
+ }
434
+ if (!/^[a-zA-Z0-9@._-]{1,64}$/.test(trimmed)) {
435
+ throw new Error(`Invalid systemd service name "${raw}". Use letters, numbers, ".", "_", "-", or "@" only.`);
436
+ }
437
+ return trimmed.endsWith(".service") ? trimmed.slice(0, -".service".length) : trimmed;
438
+ }
439
+ function renderSystemdUnit(options) {
440
+ const quote = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
441
+ return [
442
+ "[Unit]",
443
+ `Description=${options.description ?? "T3 Code QQBot Bridge and Official WebSocket Gateway"}`,
444
+ "After=default.target",
445
+ "",
446
+ "[Service]",
447
+ "Type=simple",
448
+ `WorkingDirectory=${options.workingDir}`,
449
+ "Environment=NODE_NO_WARNINGS=1",
450
+ `ExecStart=${quote(options.nodePath)} ${quote(options.cliEntry)} start --config ${quote(options.configPath)}`,
451
+ "Restart=always",
452
+ "RestartSec=5",
453
+ "KillMode=control-group",
454
+ "",
455
+ "[Install]",
456
+ "WantedBy=default.target",
457
+ ""
458
+ ].join("\n");
459
+ }
460
+ function vbsStringLiteral(value) {
461
+ if (/[\r\n]/.test(value)) {
462
+ throw new Error(`Invalid multiline value for Windows launcher: ${JSON.stringify(value)}`);
463
+ }
464
+ return `"${value.replace(/"/g, '""')}"`;
465
+ }
466
+ function renderWindowsLauncherVbs(options) {
467
+ return [
468
+ "Option Explicit",
469
+ "Dim sh, nodePath, cliEntry, configPath, logPath, cmd, exitCode",
470
+ 'Set sh = CreateObject("WScript.Shell")',
471
+ `sh.CurrentDirectory = ${vbsStringLiteral(options.workingDir)}`,
472
+ 'sh.Environment("Process")("NODE_NO_WARNINGS") = "1"',
473
+ `nodePath = ${vbsStringLiteral(options.nodePath)}`,
474
+ `cliEntry = ${vbsStringLiteral(options.cliEntry)}`,
475
+ `configPath = ${vbsStringLiteral(options.configPath)}`,
476
+ `logPath = ${vbsStringLiteral(options.logPath)}`,
477
+ 'cmd = """" & nodePath & """ """ & cliEntry & """ start --supervise --config """ & configPath & """ --log-file """ & logPath & """"',
478
+ "exitCode = sh.Run(cmd, 0, True)",
479
+ "WScript.Quit exitCode",
480
+ ""
481
+ ].join("\r\n");
482
+ }
483
+ function encodeUtf16LeWithBom(content) {
484
+ return Buffer.concat([Buffer.from([255, 254]), Buffer.from(content, "utf16le")]);
485
+ }
486
+ async function runPsEncoded(script) {
487
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
488
+ const psExe = join2(process.env.WINDIR || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
489
+ return execFileAsync(psExe, ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
490
+ windowsHide: true,
491
+ timeout: 3e4,
492
+ maxBuffer: 2e6
493
+ });
494
+ }
495
+ async function probeBridgeHealth(host, port) {
496
+ const url = `http://${host === "::1" ? "[::1]" : host}:${port}/health`;
497
+ try {
498
+ const res = await fetch(url, { signal: AbortSignal.timeout(2e3) });
499
+ const text = await res.text().catch(() => "");
500
+ return `HTTP ${res.status}${text ? ` ${text}` : ""}`;
501
+ } catch {
502
+ return "unreachable";
503
+ }
504
+ }
505
+ async function runWindowsServiceAction(action, options) {
506
+ const psSingle = (value) => `'${value.replace(/'/g, "''")}'`;
507
+ const stopProcessesScript = (targets) => {
508
+ const literals = targets.map((t) => psSingle(t)).join(", ");
509
+ return `
510
+ $targets = @(${literals})
511
+ $skipPids = @($PID, ${process.pid})
512
+ Get-CimInstance Win32_Process -Filter "Name='wscript.exe' OR Name='node.exe' OR Name='powershell.exe'" -ErrorAction SilentlyContinue |
513
+ Where-Object {
514
+ if (-not $_.CommandLine -or ($skipPids -contains $_.ProcessId)) { return $false }
515
+ foreach ($needle in $targets) {
516
+ if ($needle -and $_.CommandLine.IndexOf($needle, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) {
517
+ return $true
518
+ }
519
+ }
520
+ return $false
521
+ } |
522
+ ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
523
+ `;
524
+ };
525
+ if (action === "install") {
526
+ const config = await loadConfig(options.configPath);
527
+ await mkdir(config.stateDir, { recursive: true });
528
+ const launcherPath = join2(config.stateDir, "run-service.vbs");
529
+ const legacyPs1Path = join2(config.stateDir, "run-service.ps1");
530
+ const logPath = join2(config.stateDir, "service.log");
531
+ const launcherContent = renderWindowsLauncherVbs({
532
+ nodePath: process.execPath,
533
+ cliEntry: options.cliEntry,
534
+ configPath: config.configPath,
535
+ workingDir: config.configDir,
536
+ logPath
537
+ });
538
+ await writeFile(launcherPath, encodeUtf16LeWithBom(launcherContent));
539
+ await unlink(legacyPs1Path).catch(() => {
540
+ });
541
+ const wscriptExe = join2(process.env.WINDIR || "C:\\Windows", "System32", "wscript.exe");
542
+ const registerScript = `
543
+ $ErrorActionPreference = 'Stop'
544
+ $taskName = ${psSingle(options.taskName)}
545
+ $existing = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
546
+ if ($existing) {
547
+ Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
548
+ }
549
+ ${stopProcessesScript([config.configPath, launcherPath, legacyPs1Path])}
550
+ $wscriptExe = ${psSingle(wscriptExe)}
551
+ $launcher = ${psSingle(launcherPath)}
552
+ $workDir = ${psSingle(config.configDir)}
553
+ $action = New-ScheduledTaskAction -Execute $wscriptExe -Argument "//B //Nologo \`"$launcher\`"" -WorkingDirectory $workDir
554
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
555
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero)
556
+ Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description 'T3 Code QQBot Bridge & Official WebSocket Gateway' -Force | Out-Null
557
+ Start-ScheduledTask -TaskName $taskName
558
+ Write-Output "INSTALLED_AND_STARTED"
559
+ `;
560
+ await runPsEncoded(registerScript);
561
+ console.log(`Installed & started Windows background service "${options.taskName}" (GUI zero-window wscript launcher).`);
562
+ console.log(` Config: ${config.configPath}`);
563
+ console.log(` Launcher: ${launcherPath}`);
564
+ console.log(` Logs: ${logPath}`);
565
+ console.log(` ${join2(config.stateDir, "bridge.log")}`);
566
+ console.log(` ${join2(config.stateDir, "gateway.log")}`);
567
+ return;
568
+ }
569
+ if (action === "stop" || action === "uninstall") {
570
+ const absConfig = resolve2(options.configPath);
571
+ const config = await loadConfig(absConfig).catch(() => null);
572
+ const stateDir = config?.stateDir ?? join2(dirname2(absConfig), "state");
573
+ const launcherPath = join2(stateDir, "run-service.vbs");
574
+ const legacyPs1Path = join2(stateDir, "run-service.ps1");
575
+ const script = `
576
+ $ErrorActionPreference = 'Stop'
577
+ $taskName = ${psSingle(options.taskName)}
578
+ $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
579
+ if ($task) {
580
+ Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
581
+ ${action === "uninstall" ? "Unregister-ScheduledTask -TaskName $taskName -Confirm:$false" : ""}
582
+ }
583
+ ${stopProcessesScript([absConfig, launcherPath, legacyPs1Path])}
584
+ `;
585
+ await runPsEncoded(script);
586
+ if (action === "uninstall") {
587
+ await unlink(launcherPath).catch(() => {
588
+ });
589
+ await unlink(legacyPs1Path).catch(() => {
590
+ });
591
+ console.log(`Uninstalled Windows background service "${options.taskName}".`);
592
+ } else {
593
+ console.log(`Stopped Windows background service "${options.taskName}".`);
594
+ }
595
+ return;
596
+ }
597
+ if (action === "start") {
598
+ await runPsEncoded(`$ErrorActionPreference='Stop'; Start-ScheduledTask -TaskName ${psSingle(options.taskName)}`);
599
+ console.log(`Started Windows background service "${options.taskName}".`);
600
+ return;
601
+ }
602
+ if (action === "restart") {
603
+ await runWindowsServiceAction("stop", options);
604
+ await runWindowsServiceAction("start", options);
605
+ return;
606
+ }
607
+ if (action === "status") {
608
+ const { stdout } = await runPsEncoded(`
609
+ $task = Get-ScheduledTask -TaskName ${psSingle(options.taskName)} -ErrorAction SilentlyContinue
610
+ if (-not $task) {
611
+ Write-Output "NOT_INSTALLED"
612
+ } else {
613
+ $info = Get-ScheduledTaskInfo -TaskName ${psSingle(options.taskName)}
614
+ Write-Output ("STATE=" + $task.State + ";LAST_RUN=" + $info.LastRunTime + ";LAST_RESULT=" + $info.LastTaskResult)
615
+ }
616
+ `);
617
+ console.log(`Windows Scheduled Task "${options.taskName}": ${stdout.trim()}`);
618
+ const config = await loadConfig(options.configPath).catch(() => null);
619
+ if (config) {
620
+ const health = await probeBridgeHealth(config.bridge.host, config.bridge.port);
621
+ console.log(`Bridge health (http://${config.bridge.host}:${config.bridge.port}/health): ${health}`);
622
+ console.log(`Logs: ${join2(config.stateDir, "service.log")}`);
623
+ }
624
+ }
625
+ }
626
+ async function runLinuxServiceAction(action, options) {
627
+ const unitName = `${options.serviceName}.service`;
628
+ const unitDir = join2(homedir(), ".config", "systemd", "user");
629
+ const unitPath = join2(unitDir, unitName);
630
+ if (action === "install") {
631
+ const config = await loadConfig(options.configPath);
632
+ await mkdir(config.stateDir, { recursive: true });
633
+ await mkdir(unitDir, { recursive: true });
634
+ const unitContent = renderSystemdUnit({
635
+ nodePath: process.execPath,
636
+ cliEntry: options.cliEntry,
637
+ configPath: config.configPath,
638
+ workingDir: config.configDir
639
+ });
640
+ await writeFile(unitPath, unitContent, "utf8");
641
+ await execFileAsync("systemctl", ["--user", "daemon-reload"]);
642
+ await execFileAsync("systemctl", ["--user", "enable", "--now", unitName]);
643
+ console.log(`Installed & started systemd user service "${unitName}".`);
644
+ console.log(` Unit: ${unitPath}`);
645
+ console.log(` Config: ${config.configPath}`);
646
+ console.log(` Logs: journalctl --user -u ${unitName} -f`);
647
+ const user = process.env.USER || "";
648
+ if (user) {
649
+ const linger = await execFileAsync("loginctl", ["show-user", user, "-p", "Linger"]).then((r) => r.stdout.trim()).catch(() => "");
650
+ if (linger && !linger.includes("Linger=yes")) {
651
+ console.log(`
652
+ Tip: To keep the service running after SSH logout, run once:`);
653
+ console.log(` sudo loginctl enable-linger "${user}"`);
654
+ }
655
+ }
656
+ return;
657
+ }
658
+ if (action === "uninstall") {
659
+ await execFileAsync("systemctl", ["--user", "disable", "--now", unitName]).catch(() => {
660
+ });
661
+ await unlink(unitPath).catch(() => {
662
+ });
663
+ await execFileAsync("systemctl", ["--user", "daemon-reload"]).catch(() => {
664
+ });
665
+ console.log(`Uninstalled systemd user service "${unitName}".`);
666
+ return;
667
+ }
668
+ if (action === "start" || action === "stop" || action === "restart") {
669
+ await execFileAsync("systemctl", ["--user", action, unitName]);
670
+ console.log(`Executed "systemctl --user ${action} ${unitName}".`);
671
+ return;
672
+ }
673
+ if (action === "status") {
674
+ const statusOut = await execFileAsync("systemctl", ["--user", "status", "--no-pager", unitName]).then((r) => r.stdout).catch((err) => err.stdout || err.stderr || String(err));
675
+ console.log(statusOut.trim());
676
+ const config = await loadConfig(options.configPath).catch(() => null);
677
+ if (config) {
678
+ const health = await probeBridgeHealth(config.bridge.host, config.bridge.port);
679
+ console.log(`Bridge health (http://${config.bridge.host}:${config.bridge.port}/health): ${health}`);
680
+ }
681
+ }
682
+ }
683
+ async function runServiceCommand(actionRaw, options) {
684
+ const valid = ["install", "uninstall", "status", "start", "stop", "restart"];
685
+ if (!actionRaw || !valid.includes(actionRaw)) {
686
+ throw new Error(`Usage: t3-qqbot service <${valid.join("|")}> [--config <path>] [--name <name>]`);
687
+ }
688
+ const action = actionRaw;
689
+ if (process.platform === "win32") {
690
+ const taskName = sanitizeServiceName(options.name ?? DEFAULT_WINDOWS_TASK, "win32");
691
+ await runWindowsServiceAction(action, {
692
+ taskName,
693
+ cliEntry: options.cliEntry,
694
+ configPath: options.configPath
695
+ });
696
+ return;
697
+ }
698
+ if (process.platform === "linux") {
699
+ const serviceName = sanitizeServiceName(options.name ?? DEFAULT_LINUX_SERVICE, "linux");
700
+ await runLinuxServiceAction(action, {
701
+ serviceName,
702
+ cliEntry: options.cliEntry,
703
+ configPath: options.configPath
704
+ });
705
+ return;
706
+ }
707
+ throw new Error(
708
+ `Automatic service registration currently supports Windows and Linux (detected: ${process.platform}). Run "t3-qqbot start --supervise" under launchd or your process manager.`
709
+ );
710
+ }
711
+
712
+ // src/t3-cli.ts
713
+ import { execFile as execFile2 } from "node:child_process";
714
+ import { access as access2, readFile as readFile3 } from "node:fs/promises";
715
+ import { homedir as homedir2 } from "node:os";
716
+ import { dirname as dirname3, join as join3 } from "node:path";
717
+ var STRIPPED_ENV_KEYS = /* @__PURE__ */ new Set([
718
+ "QQ_BRIDGE_SECRET",
719
+ "QQ_APP_ID",
720
+ "QQ_APP_SECRET",
721
+ "QQ_CREDENTIALS_FILE"
722
+ ]);
723
+ async function fileExists(path2) {
724
+ try {
725
+ await access2(path2);
726
+ return true;
727
+ } catch {
728
+ return false;
729
+ }
730
+ }
731
+ function getEnvCaseInsensitive(env, name) {
732
+ if (env[name] !== void 0) return env[name];
733
+ const target = name.toUpperCase();
734
+ for (const [k, v] of Object.entries(env)) {
735
+ if (k.toUpperCase() === target) return v;
736
+ }
737
+ return void 0;
738
+ }
739
+ function sanitizeChildEnv(baseEnv) {
740
+ const sanitized = {};
741
+ for (const [key, value] of Object.entries(baseEnv)) {
742
+ if (!STRIPPED_ENV_KEYS.has(key.toUpperCase())) {
743
+ sanitized[key] = value;
744
+ }
745
+ }
746
+ return sanitized;
747
+ }
748
+ function parseWindowsT3Cmd(scriptText, options = {}) {
749
+ const callerEnv = options.env ?? {};
750
+ const scriptDir = options.scriptPath ? dirname3(options.scriptPath) : "";
751
+ const env = {};
752
+ const lines = scriptText.split(/\r?\n/);
753
+ for (const line of lines) {
754
+ const trimmed = line.trim();
755
+ if (!trimmed || /^rem\b/i.test(trimmed) || trimmed.startsWith("::")) continue;
756
+ const ifNotDefMatch = /^if\s+not\s+defined\s+([A-Za-z0-9_]+)\s+set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(
757
+ trimmed
758
+ );
759
+ if (ifNotDefMatch) {
760
+ const guardVar = ifNotDefMatch[1];
761
+ const key = ifNotDefMatch[2] ?? ifNotDefMatch[4];
762
+ const val = (ifNotDefMatch[3] ?? ifNotDefMatch[5] ?? "").trim();
763
+ if (!getEnvCaseInsensitive(callerEnv, guardVar) && !val.includes("%ERRORLEVEL%")) {
764
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
765
+ }
766
+ continue;
767
+ }
768
+ const setMatch = /^set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(trimmed);
769
+ if (setMatch) {
770
+ const key = setMatch[1] ?? setMatch[3];
771
+ const val = (setMatch[2] ?? setMatch[4] ?? "").trim();
772
+ if (val.includes("%ERRORLEVEL%") || /^t3_exit$/i.test(key)) continue;
773
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
774
+ }
775
+ }
776
+ for (const line of lines) {
777
+ let trimmed = line.trim();
778
+ if (!trimmed.endsWith("%*")) continue;
779
+ trimmed = trimmed.slice(0, -2).trim();
780
+ trimmed = trimmed.replace(/^if\s+exist\s+(?:"[^"]+"|\S+)\s+/i, "");
781
+ trimmed = trimmed.replace(/^call\s+/i, "");
782
+ if (scriptDir) {
783
+ trimmed = trimmed.replace(/%~dp0/gi, scriptDir + "\\");
784
+ }
785
+ const tokens = [...trimmed.matchAll(/"([^"]+)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
786
+ if (tokens.length >= 1) {
787
+ return {
788
+ executable: tokens[0],
789
+ prefix: tokens.slice(1),
790
+ env
791
+ };
792
+ }
793
+ }
794
+ return null;
795
+ }
796
+ async function resolveT3Command(t3Config, options = {}) {
797
+ const platform = options.platform ?? process.platform;
798
+ const home = options.homeDir ?? homedir2();
799
+ const procEnv = options.env ?? process.env;
800
+ const t3Home = t3Config.home ?? getEnvCaseInsensitive(procEnv, "T3CODE_HOME") ?? join3(home, ".t3");
801
+ const mergeEnv = (detected) => ({
802
+ ...detected,
803
+ ...t3Config.home ? { T3CODE_HOME: t3Config.home } : {},
804
+ ...t3Config.env
805
+ });
806
+ if (t3Config.executable && t3Config.executable !== "auto") {
807
+ if (platform === "win32" && /\.(cmd|bat)$/i.test(t3Config.executable)) {
808
+ const parsed = parseWindowsT3Cmd(await readFile3(t3Config.executable, "utf8"), {
809
+ env: procEnv,
810
+ scriptPath: t3Config.executable
811
+ });
812
+ if (!parsed) {
813
+ throw new Error(`Could not parse Windows T3 launcher script: ${t3Config.executable}`);
814
+ }
815
+ return {
816
+ executable: parsed.executable,
817
+ prefix: [...parsed.prefix, ...t3Config.prefix],
818
+ env: mergeEnv(parsed.env)
819
+ };
820
+ }
821
+ return {
822
+ executable: t3Config.executable,
823
+ prefix: [...t3Config.prefix],
824
+ env: mergeEnv({})
825
+ };
826
+ }
827
+ if (platform === "win32") {
828
+ const candidates = [join3(t3Home, "bin", "t3.cmd"), join3(t3Home, "bin", "t3.exe")];
829
+ for (const candidate of candidates) {
830
+ if (!await fileExists(candidate)) continue;
831
+ if (candidate.endsWith(".cmd")) {
832
+ const parsed = parseWindowsT3Cmd(await readFile3(candidate, "utf8"), {
833
+ env: procEnv,
834
+ scriptPath: candidate
835
+ });
836
+ if (parsed) {
837
+ return {
838
+ executable: parsed.executable,
839
+ prefix: [...parsed.prefix, ...t3Config.prefix],
840
+ env: mergeEnv(parsed.env)
841
+ };
842
+ }
843
+ } else {
844
+ return {
845
+ executable: candidate,
846
+ prefix: [...t3Config.prefix],
847
+ env: mergeEnv({})
848
+ };
849
+ }
850
+ }
851
+ return {
852
+ executable: "t3.exe",
853
+ prefix: [...t3Config.prefix],
854
+ env: mergeEnv({})
855
+ };
856
+ }
857
+ const unixCandidates = [join3(t3Home, "bin", "t3"), join3(home, ".local", "bin", "t3"), "/usr/local/bin/t3"];
858
+ for (const candidate of unixCandidates) {
859
+ if (await fileExists(candidate)) {
860
+ return {
861
+ executable: candidate,
862
+ prefix: [...t3Config.prefix],
863
+ env: mergeEnv({})
864
+ };
865
+ }
866
+ }
867
+ return {
868
+ executable: "t3",
869
+ prefix: [...t3Config.prefix],
870
+ env: mergeEnv({})
871
+ };
872
+ }
873
+ var T3Cli = class {
874
+ resolvedPromise;
875
+ t3Config;
876
+ baseEnv;
877
+ constructor(t3Config, baseEnv = process.env) {
878
+ this.t3Config = t3Config;
879
+ this.baseEnv = sanitizeChildEnv(baseEnv);
880
+ }
881
+ async resolve() {
882
+ this.resolvedPromise ??= resolveT3Command(this.t3Config, { env: this.baseEnv });
883
+ return this.resolvedPromise;
884
+ }
885
+ async runJson(args, input, timeoutMs = 3e4) {
886
+ const cmd = await this.resolve();
887
+ return new Promise((done, fail) => {
888
+ const child = execFile2(
889
+ cmd.executable,
890
+ [...cmd.prefix, ...args, "--json"],
891
+ {
892
+ env: { ...this.baseEnv, ...cmd.env },
893
+ windowsHide: true,
894
+ timeout: timeoutMs,
895
+ maxBuffer: 4e6
896
+ },
897
+ (error, stdout, stderr) => {
898
+ if (error) {
899
+ const detail = stderr?.trim() ? `: ${stderr.trim().slice(0, 300)}` : "";
900
+ return fail(
901
+ new Error(`T3 CLI (${args.slice(0, 2).join(" ")}) failed (${error.code ?? error.signal})${detail}`)
902
+ );
903
+ }
904
+ try {
905
+ done(JSON.parse(stdout));
906
+ } catch (invalid) {
907
+ fail(
908
+ new Error(
909
+ `T3 CLI returned invalid JSON: ${invalid instanceof Error ? invalid.message : String(invalid)}`
910
+ )
911
+ );
912
+ }
913
+ }
914
+ );
915
+ child.stdin?.on("error", () => {
916
+ });
917
+ child.stdin?.end(input, "utf8");
918
+ });
919
+ }
920
+ async issueSession(options) {
921
+ const args = ["auth", "session", "issue"];
922
+ for (const scope of options.scopes) {
923
+ args.push("--scope", scope);
924
+ }
925
+ if (options.subject) {
926
+ args.push("--subject", options.subject);
927
+ }
928
+ args.push("--ttl", options.ttl, "--label", options.label);
929
+ return this.runJson(args);
930
+ }
931
+ async revokeSession(sessionId) {
932
+ const cmd = await this.resolve();
933
+ await new Promise((resolveDone) => {
934
+ const child = execFile2(
935
+ cmd.executable,
936
+ [...cmd.prefix, "auth", "session", "revoke", sessionId],
937
+ {
938
+ env: { ...this.baseEnv, ...cmd.env },
939
+ windowsHide: true,
940
+ timeout: 1e4
941
+ },
942
+ () => resolveDone()
943
+ );
944
+ child.on("error", () => resolveDone());
945
+ });
946
+ }
947
+ async withSession(options, fn) {
948
+ const session = await this.issueSession(options);
949
+ try {
950
+ return await fn(session.token);
951
+ } finally {
952
+ await this.revokeSession(session.sessionId).catch(() => {
953
+ });
954
+ }
955
+ }
956
+ };
957
+
958
+ // src/menu.ts
959
+ function maskSecret(value) {
960
+ if (!value) return "(not set)";
961
+ if (value.startsWith("REPLACE_WITH_")) return "(placeholder)";
962
+ if (value.length <= 6) return "***";
963
+ return `${value.slice(0, 3)}***${value.slice(-3)}`;
964
+ }
965
+ function createDefaultRawConfig() {
966
+ return {
967
+ stateDir: "./state",
968
+ credentialsFile: "./credentials.json",
969
+ t3: {
970
+ origin: "http://127.0.0.1:3773",
971
+ executable: "auto",
972
+ prefix: [],
973
+ env: {}
974
+ },
975
+ bridge: {
976
+ host: "127.0.0.1",
977
+ port: 18773,
978
+ proactiveBackgroundReports: false,
979
+ maxMessageChars: 1600,
980
+ autoSettleThread: false,
981
+ enableSlashCommands: true
982
+ },
983
+ gateway: {
984
+ bridgeUrl: "http://127.0.0.1:18773/events",
985
+ requireMentionInGroup: true,
986
+ stripPrefix: ""
987
+ },
988
+ attachmentHosts: [...DEFAULT_ATTACHMENT_HOSTS],
989
+ bindings: []
990
+ };
991
+ }
992
+ function applyConfigSet(raw, key, value) {
993
+ const next = JSON.parse(JSON.stringify(raw));
994
+ next.t3 ??= { origin: "http://127.0.0.1:3773" };
995
+ next.bridge ??= { port: 18773 };
996
+ next.gateway ??= {};
997
+ const parseBool = (v) => {
998
+ const low = v.trim().toLowerCase();
999
+ if (["true", "1", "yes", "y", "on"].includes(low)) return true;
1000
+ if (["false", "0", "no", "n", "off"].includes(low)) return false;
1001
+ throw new Error(`Invalid boolean "${v}". Use true or false.`);
1002
+ };
1003
+ const parseIntStrict = (v, label) => {
1004
+ const num = Number(v.trim());
1005
+ if (!Number.isInteger(num)) throw new Error(`Invalid integer for ${label}: "${v}"`);
1006
+ return num;
1007
+ };
1008
+ switch (key) {
1009
+ case "stateDir":
1010
+ next.stateDir = value.trim();
1011
+ break;
1012
+ case "credentialsFile":
1013
+ next.credentialsFile = value.trim() || void 0;
1014
+ break;
1015
+ case "t3.origin":
1016
+ next.t3.origin = value.trim();
1017
+ break;
1018
+ case "t3.executable":
1019
+ next.t3.executable = value.trim() || "auto";
1020
+ break;
1021
+ case "t3.home":
1022
+ next.t3.home = value.trim() || void 0;
1023
+ break;
1024
+ case "t3.muteMobileCompletionThreadId":
1025
+ next.t3.muteMobileCompletionThreadId = value.trim() || void 0;
1026
+ break;
1027
+ case "bridge.host":
1028
+ next.bridge.host = value.trim();
1029
+ break;
1030
+ case "bridge.port": {
1031
+ const oldPort = next.bridge.port ?? 18773;
1032
+ const newPort = parseIntStrict(value, "bridge.port");
1033
+ next.bridge.port = newPort;
1034
+ const oldDefault = `http://${next.bridge.host ?? "127.0.0.1"}:${oldPort}/events`;
1035
+ if (!next.gateway.bridgeUrl || next.gateway.bridgeUrl === oldDefault) {
1036
+ next.gateway.bridgeUrl = `http://${next.bridge.host ?? "127.0.0.1"}:${newPort}/events`;
1037
+ }
1038
+ break;
1039
+ }
1040
+ case "bridge.maxMessageChars":
1041
+ next.bridge.maxMessageChars = parseIntStrict(value, "bridge.maxMessageChars");
1042
+ break;
1043
+ case "bridge.proactiveBackgroundReports":
1044
+ next.bridge.proactiveBackgroundReports = parseBool(value);
1045
+ break;
1046
+ case "bridge.autoSettleThread":
1047
+ next.bridge.autoSettleThread = parseBool(value);
1048
+ break;
1049
+ case "bridge.enableSlashCommands":
1050
+ next.bridge.enableSlashCommands = parseBool(value);
1051
+ break;
1052
+ case "gateway.bridgeUrl":
1053
+ next.gateway.bridgeUrl = value.trim();
1054
+ break;
1055
+ case "gateway.requireMentionInGroup":
1056
+ next.gateway.requireMentionInGroup = parseBool(value);
1057
+ break;
1058
+ case "gateway.stripPrefix":
1059
+ next.gateway.stripPrefix = value.trim();
1060
+ break;
1061
+ default:
1062
+ throw new Error(
1063
+ `Unknown config key "${key}". Supported keys: stateDir, credentialsFile, t3.origin, t3.executable, t3.home, t3.muteMobileCompletionThreadId, bridge.host, bridge.port, bridge.maxMessageChars, bridge.proactiveBackgroundReports, bridge.autoSettleThread, bridge.enableSlashCommands, gateway.bridgeUrl, gateway.requireMentionInGroup, gateway.stripPrefix`
1064
+ );
1065
+ }
1066
+ return next;
1067
+ }
1068
+ async function atomicWriteJson(filePath, data, mode) {
1069
+ await mkdir2(dirname4(filePath), { recursive: true });
1070
+ const tmpPath = `${filePath}.next`;
1071
+ await writeFile2(tmpPath, JSON.stringify(data, null, 2) + "\n", mode ? { encoding: "utf8", mode } : "utf8");
1072
+ await rename(tmpPath, filePath);
1073
+ }
1074
+ async function readOrCreateRawConfig(configPath) {
1075
+ try {
1076
+ const raw = await readFile4(configPath, "utf8");
1077
+ return JSON.parse(raw.replace(/^\uFEFF/, ""));
1078
+ } catch (error) {
1079
+ if (error.code === "ENOENT") {
1080
+ const created = createDefaultRawConfig();
1081
+ await atomicWriteJson(configPath, created);
1082
+ console.log(`Created new config file: ${configPath}`);
1083
+ return created;
1084
+ }
1085
+ throw error;
1086
+ }
1087
+ }
1088
+ function resolveCredsPath(configPath, raw) {
1089
+ const rel = raw.credentialsFile || "./credentials.json";
1090
+ return isAbsolute2(rel) ? resolve3(rel) : resolve3(dirname4(resolve3(configPath)), rel);
1091
+ }
1092
+ async function readCredsSafe(credsPath) {
1093
+ try {
1094
+ const raw = await readFile4(credsPath, "utf8");
1095
+ return JSON.parse(raw.replace(/^\uFEFF/, ""));
1096
+ } catch {
1097
+ return {};
1098
+ }
1099
+ }
1100
+ async function saveValidatedConfig(configPath, raw) {
1101
+ parseConfig(raw, configPath);
1102
+ await atomicWriteJson(configPath, raw);
1103
+ }
1104
+ async function fetchT3ProjectsBestEffort(configPath) {
1105
+ try {
1106
+ const cfg = await loadConfig(configPath);
1107
+ const t3Cli = new T3Cli(cfg.t3);
1108
+ const observer = new Observer(
1109
+ cfg.t3.origin,
1110
+ () => t3Cli.issueSession({
1111
+ scopes: ["orchestration:read"],
1112
+ subject: "mcp-client",
1113
+ ttl: "2m",
1114
+ label: "T3 QQBot config menu"
1115
+ }),
1116
+ (id) => t3Cli.revokeSession(id)
1117
+ );
1118
+ try {
1119
+ const { projects } = await observer.call("t3_project_list", { limit: 100 });
1120
+ return projects ?? [];
1121
+ } finally {
1122
+ await observer.close().catch(() => {
1123
+ });
1124
+ }
1125
+ } catch {
1126
+ return [];
1127
+ }
1128
+ }
1129
+ async function runInitWizard(options) {
1130
+ const dir = resolve3(options.dir);
1131
+ await mkdir2(dir, { recursive: true });
1132
+ const configPath = join4(dir, "config.json");
1133
+ const credsPath = join4(dir, "credentials.json");
1134
+ const configExists = await access3(configPath).then(() => true, () => false);
1135
+ const credsExists = await access3(credsPath).then(() => true, () => false);
1136
+ const detected = await resolveT3Command({
1137
+ origin: "http://127.0.0.1:3773",
1138
+ executable: "auto",
1139
+ prefix: [],
1140
+ env: {}
1141
+ });
1142
+ if (options.nonInteractive || !process.stdin.isTTY) {
1143
+ if (!options.force && configExists) {
1144
+ console.log(`Skipped existing ${configPath} (use --force to overwrite)`);
1145
+ } else {
1146
+ await atomicWriteJson(configPath, createDefaultRawConfig());
1147
+ console.log(`Created ${configPath}`);
1148
+ }
1149
+ if (!options.force && credsExists) {
1150
+ console.log(`Skipped existing ${credsPath} (use --force to overwrite)`);
1151
+ } else {
1152
+ await atomicWriteJson(
1153
+ credsPath,
1154
+ {
1155
+ appId: "REPLACE_WITH_QQ_BOT_APP_ID",
1156
+ appSecret: "REPLACE_WITH_QQ_BOT_APP_SECRET",
1157
+ bridgeSecret: randomBytes(32).toString("hex")
1158
+ },
1159
+ 384
1160
+ );
1161
+ console.log(`Created ${credsPath} (generated random 32-byte bridgeSecret)`);
1162
+ }
1163
+ console.log(
1164
+ `Detected T3 CLI: ${detected.executable}${detected.prefix.length ? " " + detected.prefix.join(" ") : ""}`
1165
+ );
1166
+ console.log("\nNext steps:");
1167
+ console.log(` 1. Run "t3-qqbot config --config "${configPath}"" or fill appId/appSecret in "${credsPath}"`);
1168
+ console.log(` 2. Run "t3-qqbot start --config "${configPath}"" and message your QQ Bot to get your "c2c:<openid>"`);
1169
+ console.log(
1170
+ ` 3. Run "t3-qqbot bind --scope c2c:<openid> --workspace "<path>" --install-media-mcp --config "${configPath}""`
1171
+ );
1172
+ console.log(` 4. Run "t3-qqbot service install --config "${configPath}"" to enable background auto-start`);
1173
+ return;
1174
+ }
1175
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1176
+ const ask = async (prompt, fallback = "") => {
1177
+ const suffix = fallback ? ` [${fallback}]` : "";
1178
+ return (await rl.question(`${prompt}${suffix}: `)).trim();
1179
+ };
1180
+ const askYesNo = async (prompt, defaultYes) => {
1181
+ const hint = defaultYes ? "Y/n" : "y/N";
1182
+ const ans = (await rl.question(`${prompt} (${hint}): `)).trim().toLowerCase();
1183
+ if (!ans) return defaultYes;
1184
+ return ["y", "yes", "1", "true"].includes(ans);
1185
+ };
1186
+ try {
1187
+ console.log("\n==================================================");
1188
+ console.log(" T3 Code QQBot \u5B89\u88C5\u521D\u59CB\u5316\u5411\u5BFC");
1189
+ console.log("==================================================");
1190
+ console.log(` \u914D\u7F6E\u76EE\u5F55: ${dir}`);
1191
+ console.log(` \u8FD0\u884C\u5E73\u53F0: ${process.platform}/${process.arch} (Node v${process.versions.node})`);
1192
+ console.log(
1193
+ ` \u63A2\u6D4B T3 CLI: ${detected.executable}${detected.prefix.length ? " " + detected.prefix.join(" ") : ""}`
1194
+ );
1195
+ if (configExists && !options.force) {
1196
+ const overwrite = await askYesNo(`
1197
+ \u68C0\u6D4B\u5230\u5DF2\u5B58\u5728 ${configPath}\uFF0C\u662F\u5426\u91CD\u65B0\u914D\u7F6E\u5E76\u8986\u76D6?`, false);
1198
+ if (!overwrite) {
1199
+ console.log('\u5DF2\u4FDD\u7559\u73B0\u6709\u914D\u7F6E\u3002\u968F\u65F6\u53EF\u8FD0\u884C "t3-qqbot config" \u4FEE\u6539\u5404\u9879\u8BBE\u7F6E\u3002');
1200
+ return;
1201
+ }
1202
+ }
1203
+ const existingCreds = credsExists ? await readCredsSafe(credsPath) : {};
1204
+ let raw = configExists ? await readOrCreateRawConfig(configPath) : createDefaultRawConfig();
1205
+ console.log("\n[1/5] QQ Bot \u51ED\u636E");
1206
+ console.log(" [1] \u624B\u673A QQ \u626B\u7801\u4E00\u952E\u7ED1\u5B9A\uFF08\u81EA\u52A8\u83B7\u53D6 AppID\u3001AppSecret \u4E0E\u4F60\u7684 user_openid\uFF0C\u63A8\u8350\uFF09");
1207
+ console.log(" [2] \u624B\u52A8\u8F93\u5165 AppID / AppSecret\uFF08\u6216\u7559\u7A7A\u7A0D\u540E\u8865\u586B\uFF09");
1208
+ const authMode = await ask(" \u9009\u62E9\u51ED\u636E\u914D\u7F6E\u65B9\u5F0F [1/2]", "1");
1209
+ let appIdVal = existingCreds.appId || "REPLACE_WITH_QQ_BOT_APP_ID";
1210
+ let appSecretVal = existingCreds.appSecret || "REPLACE_WITH_QQ_BOT_APP_SECRET";
1211
+ let qrUserOpenid;
1212
+ if (authMode === "1") {
1213
+ try {
1214
+ const qr = await runQrBotLogin();
1215
+ appIdVal = qr.appId;
1216
+ appSecretVal = qr.appSecret;
1217
+ qrUserOpenid = qr.userOpenid;
1218
+ console.log(` \u626B\u7801\u7ED1\u5B9A\u6210\u529F\uFF01AppID: ${maskSecret(appIdVal)}${qrUserOpenid ? ` \xB7 \u81EA\u52A8\u83B7\u53D6 openid: c2c:${qrUserOpenid}` : ""}`);
1219
+ } catch (error) {
1220
+ console.warn(` \u626B\u7801\u672A\u5B8C\u6210 (${error instanceof Error ? error.message : String(error)})\uFF0C\u56DE\u9000\u5230\u624B\u52A8\u8F93\u5165\uFF1A`);
1221
+ const appIdIn = await ask(" QQ Bot AppID", maskSecret(existingCreds.appId));
1222
+ const appSecretIn = await ask(" QQ Bot AppSecret", maskSecret(existingCreds.appSecret));
1223
+ if (appIdIn) appIdVal = appIdIn;
1224
+ if (appSecretIn) appSecretVal = appSecretIn;
1225
+ }
1226
+ } else {
1227
+ const appIdIn = await ask(" QQ Bot AppID", maskSecret(existingCreds.appId));
1228
+ const appSecretIn = await ask(" QQ Bot AppSecret", maskSecret(existingCreds.appSecret));
1229
+ if (appIdIn) appIdVal = appIdIn;
1230
+ if (appSecretIn) appSecretVal = appSecretIn;
1231
+ }
1232
+ const finalCreds = {
1233
+ appId: appIdVal,
1234
+ appSecret: appSecretVal,
1235
+ bridgeSecret: existingCreds.bridgeSecret && !existingCreds.bridgeSecret.startsWith("REPLACE_WITH_") ? existingCreds.bridgeSecret : randomBytes(32).toString("hex")
1236
+ };
1237
+ const credsReady = !finalCreds.appId.startsWith("REPLACE_WITH_") && !finalCreds.appSecret.startsWith("REPLACE_WITH_");
1238
+ console.log("\n[2/5] T3 Code \u8FDE\u63A5\u4E0E\u672C\u5730\u6865\u63A5\u7AEF\u53E3");
1239
+ const originIn = await ask(" T3 Code \u670D\u52A1\u5730\u5740", raw.t3?.origin ?? "http://127.0.0.1:3773");
1240
+ if (originIn) raw = applyConfigSet(raw, "t3.origin", originIn);
1241
+ const portIn = await ask(" \u672C\u5730\u6865\u63A5\u76D1\u542C\u7AEF\u53E3", String(raw.bridge?.port ?? 18773));
1242
+ if (portIn) raw = applyConfigSet(raw, "bridge.port", portIn);
1243
+ console.log("\n[3/5] \u884C\u4E3A\u4E0E\u4F53\u9A8C\u53EF\u9009\u9879");
1244
+ const enableSlash = await askYesNo(
1245
+ " \u542F\u7528 QQ \u804A\u5929\u5185\u659C\u6760\u6307\u4EE4\u9762\u677F (/help, /model, /think, /new, /rewind, /stop \u7B49)?",
1246
+ raw.bridge?.enableSlashCommands ?? true
1247
+ );
1248
+ raw = applyConfigSet(raw, "bridge.enableSlashCommands", String(enableSlash));
1249
+ const requireMention = await askYesNo(" \u7FA4\u804A\u4E2D\u662F\u5426\u5FC5\u987B @\u673A\u5668\u4EBA \u624D\u54CD\u5E94?", raw.gateway?.requireMentionInGroup ?? true);
1250
+ raw = applyConfigSet(raw, "gateway.requireMentionInGroup", String(requireMention));
1251
+ const autoSettle = await askYesNo(
1252
+ " \u6BCF\u8F6E\u56DE\u590D\u540E\u662F\u5426\u81EA\u52A8\u6536\u8D77 T3 \u4FA7\u8FB9\u680F\u4E2D\u7684 QQ \u4F1A\u8BDD (autoSettleThread)?",
1253
+ raw.bridge?.autoSettleThread ?? false
1254
+ );
1255
+ raw = applyConfigSet(raw, "bridge.autoSettleThread", String(autoSettle));
1256
+ const proactiveBg = await askYesNo(
1257
+ " \u5F02\u6B65\u540E\u53F0\u5B50\u4EFB\u52A1\u662F\u5426\u542F\u7528\u4E3B\u52A8\u6D88\u606F\u6C47\u62A5 (\u9700 QQ \u673A\u5668\u4EBA\u5177\u5907\u4E3B\u52A8\u6D88\u606F\u6743\u9650)?",
1258
+ raw.bridge?.proactiveBackgroundReports ?? false
1259
+ );
1260
+ raw = applyConfigSet(raw, "bridge.proactiveBackgroundReports", String(proactiveBg));
1261
+ const muteThreadIn = await ask(
1262
+ " [\u53EF\u9009\u9AD8\u7EA7\u9879] \u8865\u4E01\u7248 T3 \u9759\u97F3\u624B\u673A\u5B8C\u6210\u63A8\u9001\u7684\u4E3B\u4F1A\u8BDD threadId (\u5B98\u65B9\u7248\u76F4\u63A5\u56DE\u8F66\u8DF3\u8FC7)",
1263
+ raw.t3?.muteMobileCompletionThreadId || ""
1264
+ );
1265
+ if (muteThreadIn) raw = applyConfigSet(raw, "t3.muteMobileCompletionThreadId", muteThreadIn);
1266
+ await saveValidatedConfig(configPath, raw);
1267
+ await atomicWriteJson(credsPath, finalCreds, 384);
1268
+ console.log(`
1269
+ \u5DF2\u4FDD\u5B58\u914D\u7F6E: ${configPath}`);
1270
+ console.log(`\u5DF2\u4FDD\u5B58\u51ED\u636E: ${credsPath}`);
1271
+ console.log("\n[4/5] QQ \u4F1A\u8BDD\u7ED1\u5B9A\uFF08\u53EF\u9009\uFF09");
1272
+ const defaultScope = qrUserOpenid ? `c2c:${qrUserOpenid}` : "";
1273
+ const scopeInput = await ask(
1274
+ defaultScope ? " \u5DF2\u901A\u8FC7\u626B\u7801\u83B7\u53D6\u4F60\u7684\u79C1\u804A scope\uFF08\u76F4\u63A5\u56DE\u8F66\u4F7F\u7528\uFF0C\u586B - \u8DF3\u8FC7\uFF09" : " \u5982\u5DF2\u77E5\u4F60\u7684 QQ scope (\u5982 c2c:OPENID)\uFF0C\u76F4\u63A5\u8F93\u5165\uFF1B\u5C1A\u672A\u83B7\u53D6\u8BF7\u56DE\u8F66\u8DF3\u8FC7",
1275
+ defaultScope
1276
+ );
1277
+ const knownScope = scopeInput === "-" ? "" : scopeInput || defaultScope;
1278
+ if (knownScope) {
1279
+ const projects = await fetchT3ProjectsBestEffort(configPath);
1280
+ let workspace = "";
1281
+ if (projects.length > 0) {
1282
+ console.log(" \u68C0\u6D4B\u5230 T3 Code \u5DF2\u6CE8\u518C\u9879\u76EE:");
1283
+ projects.forEach((p, idx) => console.log(` [${idx + 1}] ${p.title || "(\u672A\u547D\u540D)"} \u2014 ${p.workspaceRoot}`));
1284
+ const pick = await ask(" \u8F93\u5165\u9879\u76EE\u7F16\u53F7\u6216\u5DE5\u4F5C\u533A\u8DEF\u5F84");
1285
+ const num = Number(pick);
1286
+ workspace = Number.isInteger(num) && num >= 1 && num <= projects.length ? projects[num - 1].workspaceRoot : pick;
1287
+ } else {
1288
+ workspace = await ask(" \u8F93\u5165 T3 \u5DF2\u6CE8\u518C\u7684\u9879\u76EE\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84");
1289
+ }
1290
+ if (workspace) {
1291
+ const threadId = await ask(" \u6307\u5B9A\u5DF2\u6709 T3 threadId (\u7559\u7A7A\u5219\u9996\u6B21\u804A\u5929\u81EA\u52A8\u65B0\u5EFA)");
1292
+ const installMcp = await askYesNo(" \u662F\u5426\u540C\u65F6\u914D\u7F6E qqbot_send_media \u5A92\u4F53\u56DE\u4F20 MCP \u5DE5\u5177?", true);
1293
+ if (options.bindAndInstallMcp) {
1294
+ try {
1295
+ await options.bindAndInstallMcp({
1296
+ configPath,
1297
+ scope: knownScope,
1298
+ workspace,
1299
+ threadId: threadId || void 0,
1300
+ installMediaMcp: installMcp
1301
+ });
1302
+ } catch (error) {
1303
+ console.warn(
1304
+ ` \u7ED1\u5B9A\u6821\u9A8C\u672A\u901A\u8FC7 (${error instanceof Error ? error.message : String(error)})\uFF0C\u7A0D\u540E\u53EF\u8FD0\u884C "t3-qqbot bind" \u5B8C\u6210\u7ED1\u5B9A\u3002`
1305
+ );
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1310
+ console.log("\n[5/5] \u5F00\u673A\u81EA\u542F\u52A8\u4E0E\u540E\u53F0\u81EA\u5B88\u62A4");
1311
+ const daemonDesc = process.platform === "win32" ? "Windows \u9690\u85CF\u8BA1\u5212\u4EFB\u52A1 + \u5D29\u6E83\u81EA\u62C9\u8D77" : process.platform === "linux" ? "Linux systemd --user \u5E38\u9A7B\u670D\u52A1" : "\u540E\u53F0\u81EA\u5B88\u62A4\u670D\u52A1";
1312
+ const wantService = await askYesNo(` \u662F\u5426\u7ACB\u5373\u6CE8\u518C\u5F00\u673A\u81EA\u542F\u52A8\u4E0E\u540E\u53F0\u81EA\u5B88\u62A4 (${daemonDesc})?`, credsReady);
1313
+ if (wantService) {
1314
+ if (!credsReady) {
1315
+ console.log(' \u68C0\u6D4B\u5230 AppID / AppSecret \u5C1A\u672A\u586B\u5199\uFF0C\u6682\u7F13\u6CE8\u518C\u81EA\u542F\u52A8\u3002\u586B\u5B8C\u51ED\u636E\u540E\u8FD0\u884C "t3-qqbot service install" \u5373\u53EF\u4E00\u952E\u542F\u7528\u3002');
1316
+ } else {
1317
+ try {
1318
+ await runServiceCommand("install", { cliEntry: options.cliEntry, configPath });
1319
+ } catch (error) {
1320
+ console.error(
1321
+ ` \u81EA\u5B88\u62A4\u6CE8\u518C\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}\u3002\u7A0D\u540E\u53EF\u91CD\u8BD5 "t3-qqbot service install"\u3002`
1322
+ );
1323
+ }
1324
+ }
1325
+ }
1326
+ if (raw.t3?.muteMobileCompletionThreadId) {
1327
+ const tid = raw.t3.muteMobileCompletionThreadId;
1328
+ console.log("\n\u63D0\u793A\uFF1A\u4F60\u8BBE\u7F6E\u4E86\u9759\u97F3\u4E3B\u4F1A\u8BDD ID\uFF0C\u8BF7\u5728\u8865\u4E01\u7248 T3 Code \u542F\u52A8\u73AF\u5883\u4E2D\u6CE8\u5165\uFF1A");
1329
+ console.log(` T3CODE_MUTE_MOBILE_COMPLETION_THREAD_ID=${tid}`);
1330
+ }
1331
+ console.log("\n\u521D\u59CB\u5316\u5B8C\u6210\uFF01\u5E38\u7528\u540E\u7EED\u547D\u4EE4\uFF1A");
1332
+ console.log(` - \u4FEE\u6539\u4EFB\u610F\u914D\u7F6E: t3-qqbot config --config "${configPath}"`);
1333
+ console.log(` - \u5168\u94FE\u8DEF\u4F53\u68C0: t3-qqbot doctor --config "${configPath}"`);
1334
+ console.log(` - \u524D\u53F0\u542F\u52A8\u8C03\u8BD5: t3-qqbot start --config "${configPath}"`);
1335
+ console.log(` - \u540E\u53F0\u5B88\u62A4\u7BA1\u7406: t3-qqbot service status|restart|stop --config "${configPath}"`);
1336
+ } finally {
1337
+ rl.close();
1338
+ }
1339
+ }
1340
+ async function runQrLoginCommand(configPath) {
1341
+ const absPath = resolve3(configPath);
1342
+ const raw = await readOrCreateRawConfig(absPath);
1343
+ const credsPath = resolveCredsPath(absPath, raw);
1344
+ const existing = await readCredsSafe(credsPath);
1345
+ const qr = await runQrBotLogin();
1346
+ const nextCreds = {
1347
+ appId: qr.appId,
1348
+ appSecret: qr.appSecret,
1349
+ bridgeSecret: existing.bridgeSecret && !existing.bridgeSecret.startsWith("REPLACE_WITH_") ? existing.bridgeSecret : randomBytes(32).toString("hex")
1350
+ };
1351
+ await atomicWriteJson(credsPath, nextCreds, 384);
1352
+ if (!raw.credentialsFile) {
1353
+ raw.credentialsFile = "./credentials.json";
1354
+ await saveValidatedConfig(absPath, raw);
1355
+ }
1356
+ console.log(`
1357
+ \u626B\u7801\u767B\u5F55\u6210\u529F\uFF01\u51ED\u636E\u5DF2\u4FDD\u5B58\u81F3 ${credsPath}`);
1358
+ console.log(` AppID: ${maskSecret(qr.appId)}`);
1359
+ if (qr.userOpenid) {
1360
+ console.log(` \u4F60\u7684 QQ \u79C1\u804A scope: c2c:${qr.userOpenid}`);
1361
+ console.log(` \u53EF\u76F4\u63A5\u7ED1\u5B9A: t3-qqbot bind --scope c2c:${qr.userOpenid} --workspace "<T3\u9879\u76EE\u8DEF\u5F84>" --install-media-mcp --config "${absPath}"`);
1362
+ }
1363
+ }
1364
+ async function runConfigShow(configPath) {
1365
+ const absPath = resolve3(configPath);
1366
+ const exists = await access3(absPath).then(() => true, () => false);
1367
+ if (!exists) {
1368
+ throw new Error(`Config file not found: ${absPath}. Run "t3-qqbot init" or "t3-qqbot config" first.`);
1369
+ }
1370
+ const raw = await readOrCreateRawConfig(absPath);
1371
+ const credsPath = resolveCredsPath(absPath, raw);
1372
+ const creds = await readCredsSafe(credsPath);
1373
+ console.log(`Config file: ${absPath}`);
1374
+ console.log(`Credentials file: ${credsPath}`);
1375
+ console.log(` appId: ${maskSecret(creds.appId)}`);
1376
+ console.log(` appSecret: ${maskSecret(creds.appSecret)}`);
1377
+ console.log(` bridgeSecret: ${maskSecret(creds.bridgeSecret)}`);
1378
+ console.log("\nCurrent config.json:");
1379
+ console.log(JSON.stringify(raw, null, 2));
1380
+ }
1381
+ async function runConfigSet(configPath, key, value) {
1382
+ const absPath = resolve3(configPath);
1383
+ const raw = await readOrCreateRawConfig(absPath);
1384
+ const updated = applyConfigSet(raw, key, value);
1385
+ await saveValidatedConfig(absPath, updated);
1386
+ console.log(`Updated "${key}" in ${absPath}`);
1387
+ }
1388
+ async function runConfigMenu(options) {
1389
+ const absPath = resolve3(options.configPath);
1390
+ if (!process.stdin.isTTY) {
1391
+ throw new Error(
1392
+ 'Interactive menu requires a TTY terminal. Use "t3-qqbot config show" or "t3-qqbot config set <key> <value>" in non-interactive shells.'
1393
+ );
1394
+ }
1395
+ let raw = await readOrCreateRawConfig(absPath);
1396
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1397
+ const ask = async (prompt, current) => {
1398
+ const suffix = current !== void 0 ? ` [${current}]` : "";
1399
+ const answer = await rl.question(`${prompt}${suffix}: `);
1400
+ return answer.trim();
1401
+ };
1402
+ try {
1403
+ while (true) {
1404
+ const credsPath = resolveCredsPath(absPath, raw);
1405
+ const creds = await readCredsSafe(credsPath);
1406
+ const credsReady = Boolean(creds.appId && !creds.appId.startsWith("REPLACE_WITH_")) && Boolean(creds.appSecret && !creds.appSecret.startsWith("REPLACE_WITH_")) && Boolean(creds.bridgeSecret && !creds.bridgeSecret.startsWith("REPLACE_WITH_"));
1407
+ console.log("\n==================================================");
1408
+ console.log(" T3 Code QQBot \u914D\u7F6E\u83DC\u5355");
1409
+ console.log("==================================================");
1410
+ console.log(` \u914D\u7F6E\u6587\u4EF6: ${absPath}`);
1411
+ console.log(` QQ \u51ED\u636E: ${credsReady ? "\u5DF2\u914D\u7F6E" : "\u5F85\u586B\u5199"} (AppID: ${maskSecret(creds.appId)})`);
1412
+ console.log(` T3 \u670D\u52A1: ${raw.t3?.origin ?? "http://127.0.0.1:3773"} (CLI: ${raw.t3?.executable || "auto"})`);
1413
+ console.log(` \u6865\u63A5\u7AEF\u53E3: ${raw.bridge?.host ?? "127.0.0.1"}:${raw.bridge?.port ?? 18773} (\u5355\u6BB5\u4E0A\u9650: ${raw.bridge?.maxMessageChars ?? 1600} \u5B57)`);
1414
+ console.log(` \u4F1A\u8BDD\u7ED1\u5B9A: ${(raw.bindings ?? []).length} \u6761`);
1415
+ console.log(` \u4FA7\u8FB9\u680F\u6536\u7EB3: ${raw.bridge?.autoSettleThread ? "\u5F00\u542F (autoSettleThread)" : "\u5173\u95ED"} | \u9759\u97F3\u7EBF\u7A0BID: ${raw.t3?.muteMobileCompletionThreadId || "(\u672A\u8BBE\u7F6E)"}`);
1416
+ console.log("--------------------------------------------------");
1417
+ console.log(" [1] \u914D\u7F6E QQ Bot \u51ED\u636E (AppID / AppSecret / BridgeSecret)");
1418
+ console.log(" [2] \u914D\u7F6E T3 Code \u8FDE\u63A5 (origin / executable / home)");
1419
+ console.log(" [3] \u914D\u7F6E\u6865\u63A5\u4E0E\u7F51\u5173\u53C2\u6570 (\u7AEF\u53E3 / \u5206\u6BB5\u957F\u5EA6 / \u7FA4\u804A@ / \u524D\u7F00)");
1420
+ console.log(" [4] \u7BA1\u7406 QQ \u4F1A\u8BDD\u7ED1\u5B9A (\u65B0\u589E / \u4FEE\u6539 / \u5220\u9664)");
1421
+ console.log(" [5] \u7BA1\u7406\u9644\u4EF6\u57DF\u540D\u767D\u540D\u5355 (attachmentHosts)");
1422
+ console.log(" [6] \u540E\u53F0\u81EA\u5B88\u62A4\u670D\u52A1 (\u5B89\u88C5 / \u72B6\u6001 / \u91CD\u542F / \u505C\u6B62 / \u5378\u8F7D)");
1423
+ console.log(" [7] \u4E3B\u4F1A\u8BDD\u9759\u97F3\u4E0E\u4FA7\u8FB9\u680F\u6536\u7EB3 (\u53EF\u9009)");
1424
+ console.log(" [8] \u8FD0\u884C\u5168\u94FE\u8DEF\u4F53\u68C0 (doctor)");
1425
+ console.log(" [9] \u67E5\u770B\u5B8C\u6574\u914D\u7F6E\u6458\u8981");
1426
+ console.log(" [0] \u9000\u51FA");
1427
+ console.log("--------------------------------------------------");
1428
+ const choice = (await rl.question("\u8BF7\u9009\u62E9\u64CD\u4F5C\u7F16\u53F7 [0-9]: ")).trim();
1429
+ if (choice === "0" || choice.toLowerCase() === "q") {
1430
+ console.log('\u5DF2\u9000\u51FA\u914D\u7F6E\u83DC\u5355\u3002\u4FEE\u6539\u5DF2\u81EA\u52A8\u4FDD\u5B58\uFF1B\u82E5\u540E\u53F0\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u6267\u884C "t3-qqbot service restart" \u4F7F\u65B0\u914D\u7F6E\u751F\u6548\u3002');
1431
+ break;
1432
+ }
1433
+ try {
1434
+ if (choice === "1") {
1435
+ console.log(`
1436
+ --- QQ Bot \u51ED\u636E (${credsPath}) ---`);
1437
+ const mode = await ask("\u65B9\u5F0F: [1] \u624B\u673AQQ\u626B\u7801\u4E00\u952E\u7ED1\u5B9A / [2] \u624B\u52A8\u586B\u5199", "2");
1438
+ let nextAppId = creds.appId || "REPLACE_WITH_QQ_BOT_APP_ID";
1439
+ let nextAppSecret = creds.appSecret || "REPLACE_WITH_QQ_BOT_APP_SECRET";
1440
+ if (mode === "1") {
1441
+ const qr = await runQrBotLogin();
1442
+ nextAppId = qr.appId;
1443
+ nextAppSecret = qr.appSecret;
1444
+ if (qr.userOpenid) {
1445
+ console.log(`\u626B\u7801\u83B7\u53D6\u5230\u4F60\u7684\u79C1\u804A scope: c2c:${qr.userOpenid}`);
1446
+ }
1447
+ } else {
1448
+ console.log("\u76F4\u63A5\u56DE\u8F66\u4FDD\u6301\u539F\u503C\u4E0D\u53D8\u3002");
1449
+ const inputAppId = await ask("AppID", maskSecret(creds.appId));
1450
+ const inputAppSecret = await ask("AppSecret", maskSecret(creds.appSecret));
1451
+ if (inputAppId) nextAppId = inputAppId;
1452
+ if (inputAppSecret) nextAppSecret = inputAppSecret;
1453
+ }
1454
+ const regen = await ask("\u662F\u5426\u91CD\u65B0\u751F\u6210\u968F\u673A bridgeSecret? (y/N)", "N");
1455
+ const nextCreds = {
1456
+ appId: nextAppId,
1457
+ appSecret: nextAppSecret,
1458
+ bridgeSecret: regen.toLowerCase() === "y" || !creds.bridgeSecret || creds.bridgeSecret.startsWith("REPLACE_WITH_") ? randomBytes(32).toString("hex") : creds.bridgeSecret
1459
+ };
1460
+ await atomicWriteJson(credsPath, nextCreds, 384);
1461
+ if (!raw.credentialsFile) {
1462
+ raw.credentialsFile = "./credentials.json";
1463
+ await saveValidatedConfig(absPath, raw);
1464
+ }
1465
+ console.log(`\u5DF2\u4FDD\u5B58\u51ED\u636E\u5230 ${credsPath}`);
1466
+ } else if (choice === "2") {
1467
+ console.log("\n--- T3 Code \u8FDE\u63A5\u914D\u7F6E ---");
1468
+ const origin = await ask("T3 \u670D\u52A1\u5730\u5740 (t3.origin)", raw.t3?.origin ?? "http://127.0.0.1:3773");
1469
+ const executable = await ask("T3 CLI \u8DEF\u5F84 (\u586B auto \u81EA\u52A8\u63A2\u6D4B)", raw.t3?.executable || "auto");
1470
+ const home = await ask("\u81EA\u5B9A\u4E49 T3CODE_HOME (\u7559\u7A7A\u9ED8\u8BA4 ~/.t3, \u586B - \u6E05\u9664)", raw.t3?.home || "");
1471
+ let next = raw;
1472
+ if (origin) next = applyConfigSet(next, "t3.origin", origin);
1473
+ if (executable) next = applyConfigSet(next, "t3.executable", executable);
1474
+ if (home === "-") next = applyConfigSet(next, "t3.home", "");
1475
+ else if (home) next = applyConfigSet(next, "t3.home", home);
1476
+ await saveValidatedConfig(absPath, next);
1477
+ raw = next;
1478
+ console.log("\u5DF2\u4FDD\u5B58 T3 Code \u8FDE\u63A5\u914D\u7F6E\u3002");
1479
+ } else if (choice === "3") {
1480
+ console.log("\n--- \u6865\u63A5\u4E0E\u7F51\u5173\u53C2\u6570 ---");
1481
+ const port = await ask("\u672C\u5730\u6865\u63A5\u7AEF\u53E3 (bridge.port)", String(raw.bridge?.port ?? 18773));
1482
+ const maxChars = await ask("\u5355\u6761\u56DE\u590D\u6700\u5927\u5B57\u6570 (100-4000)", String(raw.bridge?.maxMessageChars ?? 1600));
1483
+ const slashEnabled = await ask(
1484
+ "\u542F\u7528 QQ \u804A\u5929\u5185\u659C\u6760\u6307\u4EE4\u9762\u677F (true/false)",
1485
+ String(raw.bridge?.enableSlashCommands ?? true)
1486
+ );
1487
+ const proactive = await ask(
1488
+ "\u540E\u53F0\u5B50\u4EFB\u52A1\u5141\u8BB8\u4E3B\u52A8\u63A8\u9001 (true/false)",
1489
+ String(raw.bridge?.proactiveBackgroundReports ?? false)
1490
+ );
1491
+ const mention = await ask(
1492
+ "\u7FA4\u804A\u662F\u5426\u5FC5\u987B @\u673A\u5668\u4EBA (true/false)",
1493
+ String(raw.gateway?.requireMentionInGroup ?? true)
1494
+ );
1495
+ const stripPrefix = await ask(
1496
+ "\u53EF\u9009\u5265\u79BB\u6307\u4EE4\u524D\u7F00 (\u5982 /ai\uFF0C\u586B - \u6E05\u9664)",
1497
+ raw.gateway?.stripPrefix || "(\u65E0)"
1498
+ );
1499
+ const bridgeUrl = await ask(
1500
+ "\u7F51\u5173\u8F6C\u53D1\u76EE\u6807\u5730\u5740 (gateway.bridgeUrl)",
1501
+ raw.gateway?.bridgeUrl || `http://${raw.bridge?.host ?? "127.0.0.1"}:${port || raw.bridge?.port || 18773}/events`
1502
+ );
1503
+ let next = raw;
1504
+ if (port) next = applyConfigSet(next, "bridge.port", port);
1505
+ if (maxChars) next = applyConfigSet(next, "bridge.maxMessageChars", maxChars);
1506
+ if (slashEnabled) next = applyConfigSet(next, "bridge.enableSlashCommands", slashEnabled);
1507
+ if (proactive) next = applyConfigSet(next, "bridge.proactiveBackgroundReports", proactive);
1508
+ if (mention) next = applyConfigSet(next, "gateway.requireMentionInGroup", mention);
1509
+ if (stripPrefix === "-") next = applyConfigSet(next, "gateway.stripPrefix", "");
1510
+ else if (stripPrefix && stripPrefix !== "(\u65E0)") next = applyConfigSet(next, "gateway.stripPrefix", stripPrefix);
1511
+ if (bridgeUrl) next = applyConfigSet(next, "gateway.bridgeUrl", bridgeUrl);
1512
+ await saveValidatedConfig(absPath, next);
1513
+ raw = next;
1514
+ console.log("\u5DF2\u4FDD\u5B58\u6865\u63A5\u4E0E\u7F51\u5173\u53C2\u6570\u3002");
1515
+ } else if (choice === "4") {
1516
+ await manageBindingsSubmenu(rl, absPath, raw, (updated) => {
1517
+ raw = updated;
1518
+ });
1519
+ } else if (choice === "5") {
1520
+ const hosts = Array.isArray(raw.attachmentHosts) && raw.attachmentHosts.length > 0 ? [...raw.attachmentHosts] : [...DEFAULT_ATTACHMENT_HOSTS];
1521
+ console.log("\n--- \u9644\u4EF6\u4E0B\u8F7D\u57DF\u540D\u767D\u540D\u5355 ---");
1522
+ hosts.forEach((h, i) => console.log(` ${i + 1}. ${h}`));
1523
+ const action = await ask("\u64CD\u4F5C: [a]\u6DFB\u52A0\u57DF\u540D / [d]\u5220\u9664\u7F16\u53F7 / [r]\u6062\u590D\u9ED8\u8BA4 / \u56DE\u8F66\u8FD4\u56DE");
1524
+ if (action.toLowerCase() === "a") {
1525
+ const domain = await ask("\u8F93\u5165\u8981\u6DFB\u52A0\u7684 HTTPS \u57DF\u540D (\u5982 multimedia.nt.qq.com)");
1526
+ if (domain) {
1527
+ hosts.push(domain.toLowerCase());
1528
+ raw.attachmentHosts = [...new Set(hosts)];
1529
+ await saveValidatedConfig(absPath, raw);
1530
+ console.log("\u5DF2\u6DFB\u52A0\u5E76\u4FDD\u5B58\u3002");
1531
+ }
1532
+ } else if (action.toLowerCase() === "d") {
1533
+ const idx = Number(await ask("\u8F93\u5165\u8981\u5220\u9664\u7684\u7F16\u53F7")) - 1;
1534
+ if (Number.isInteger(idx) && idx >= 0 && idx < hosts.length) {
1535
+ hosts.splice(idx, 1);
1536
+ raw.attachmentHosts = hosts;
1537
+ await saveValidatedConfig(absPath, raw);
1538
+ console.log("\u5DF2\u5220\u9664\u5E76\u4FDD\u5B58\u3002");
1539
+ }
1540
+ } else if (action.toLowerCase() === "r") {
1541
+ raw.attachmentHosts = [...DEFAULT_ATTACHMENT_HOSTS];
1542
+ await saveValidatedConfig(absPath, raw);
1543
+ console.log("\u5DF2\u6062\u590D\u9ED8\u8BA4\u767D\u540D\u5355\u3002");
1544
+ }
1545
+ } else if (choice === "6") {
1546
+ console.log("\n--- \u540E\u53F0\u81EA\u5B88\u62A4\u670D\u52A1\u7BA1\u7406 ---");
1547
+ console.log(" [1] \u5B89\u88C5\u5E76\u7ACB\u5373\u542F\u52A8 (service install)");
1548
+ console.log(" [2] \u67E5\u770B\u8FD0\u884C\u72B6\u6001 (service status)");
1549
+ console.log(" [3] \u91CD\u542F\u670D\u52A1 (service restart)");
1550
+ console.log(" [4] \u505C\u6B62\u670D\u52A1 (service stop)");
1551
+ console.log(" [5] \u5378\u8F7D\u5F00\u673A\u81EA\u542F (service uninstall)");
1552
+ console.log(" [0] \u8FD4\u56DE\u4E0A\u7EA7");
1553
+ const svcChoice = (await rl.question("\u8BF7\u9009\u62E9 [0-5]: ")).trim();
1554
+ const map = {
1555
+ "1": "install",
1556
+ "2": "status",
1557
+ "3": "restart",
1558
+ "4": "stop",
1559
+ "5": "uninstall"
1560
+ };
1561
+ if (map[svcChoice]) {
1562
+ await runServiceCommand(map[svcChoice], {
1563
+ cliEntry: options.cliEntry,
1564
+ configPath: absPath
1565
+ });
1566
+ }
1567
+ } else if (choice === "7") {
1568
+ console.log("\n--- \u4E3B\u4F1A\u8BDD\u9759\u97F3\u4E0E\u4FA7\u8FB9\u680F\u6536\u7EB3\uFF08\u53EF\u9009\uFF09---");
1569
+ console.log("\u8BF4\u660E\uFF1A");
1570
+ console.log(" 1. autoSettleThread\uFF1A\u5B98\u65B9 T3 Code \u76F4\u63A5\u652F\u6301\uFF0C\u6BCF\u8F6E\u56DE\u590D\u540E\u81EA\u52A8\u5C06 QQ \u4F1A\u8BDD\u4ECE\u4FA7\u8FB9\u680F\u6D3B\u8DC3\u5217\u8868\u6536\u8D77\uFF08\u4E0D\u5F71\u54CD\u624B\u673A\u5B8C\u6210\u63A8\u9001\uFF09\u3002");
1571
+ console.log(" 2. muteMobileCompletionThreadId\uFF1A\u4EC5\u5BF9\u652F\u6301 T3CODE_MUTE_MOBILE_COMPLETION_THREAD_ID \u73AF\u5883\u53D8\u91CF\u7684\u81EA\u7F16\u8BD1/\u8865\u4E01\u7248 T3 \u670D\u52A1\u7AEF\u751F\u6548\uFF0C\u5B98\u65B9\u539F\u7248 T3 Code \u76EE\u524D\u65E0\u6CD5\u7531\u5916\u90E8\u63D2\u4EF6\u5C4F\u853D\u624B\u673A\u5B8C\u6210\u63A8\u9001\u3002");
1572
+ const settleAns = await ask(
1573
+ "\u56DE\u590D\u5B8C\u6210\u540E\u81EA\u52A8\u6536\u8D77 T3 \u4FA7\u8FB9\u680F\u4F1A\u8BDD (true/false)",
1574
+ String(raw.bridge?.autoSettleThread ?? false)
1575
+ );
1576
+ const muteAns = await ask(
1577
+ "\u9700\u8981\u9759\u97F3\u624B\u673A\u5B8C\u6210\u63A8\u9001\u7684\u4E3B\u4F1A\u8BDD threadId (\u7559\u7A7A\u4FDD\u6301\uFF0C\u586B - \u6E05\u9664)",
1578
+ raw.t3?.muteMobileCompletionThreadId || ""
1579
+ );
1580
+ let next = raw;
1581
+ if (settleAns) next = applyConfigSet(next, "bridge.autoSettleThread", settleAns);
1582
+ if (muteAns === "-") next = applyConfigSet(next, "t3.muteMobileCompletionThreadId", "");
1583
+ else if (muteAns) next = applyConfigSet(next, "t3.muteMobileCompletionThreadId", muteAns);
1584
+ await saveValidatedConfig(absPath, next);
1585
+ raw = next;
1586
+ console.log("\u5DF2\u4FDD\u5B58\u9759\u97F3\u4E0E\u6536\u7EB3\u9009\u9879\u3002");
1587
+ if (raw.t3?.muteMobileCompletionThreadId) {
1588
+ const tid = raw.t3.muteMobileCompletionThreadId;
1589
+ console.log("\n\u8BF7\u5C06\u4EE5\u4E0B\u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u5230\u4F60\u7684\u81EA\u7F16\u8BD1/\u8865\u4E01\u7248 T3 Code \u670D\u52A1\u7AEF\u542F\u52A8\u73AF\u5883\u4E2D\u5E76\u91CD\u542F T3 Code\uFF1A");
1590
+ console.log(` Linux / systemd: Environment=T3CODE_MUTE_MOBILE_COMPLETION_THREAD_ID=${tid}`);
1591
+ console.log(` Windows PowerShell: $env:T3CODE_MUTE_MOBILE_COMPLETION_THREAD_ID = "${tid}"`);
1592
+ }
1593
+ } else if (choice === "8") {
1594
+ console.log("\n--- \u8FD0\u884C\u5168\u94FE\u8DEF\u4F53\u68C0 ---");
1595
+ await options.runDoctor(absPath);
1596
+ } else if (choice === "9") {
1597
+ console.log("");
1598
+ await runConfigShow(absPath);
1599
+ } else {
1600
+ console.log("\u65E0\u6548\u9009\u9879\uFF0C\u8BF7\u8F93\u5165 0-9\u3002");
1601
+ }
1602
+ } catch (error) {
1603
+ console.error(`
1604
+ \u64CD\u4F5C\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
1605
+ }
1606
+ }
1607
+ } finally {
1608
+ rl.close();
1609
+ }
1610
+ }
1611
+ async function manageBindingsSubmenu(rl, absPath, raw, onSave) {
1612
+ const bindings = Array.isArray(raw.bindings) ? [...raw.bindings] : [];
1613
+ console.log("\n--- QQ \u4F1A\u8BDD\u7ED1\u5B9A\u5217\u8868 ---");
1614
+ if (bindings.length === 0) {
1615
+ console.log(" (\u5F53\u524D\u6682\u65E0\u7ED1\u5B9A)");
1616
+ } else {
1617
+ bindings.forEach((b, i) => {
1618
+ console.log(` [${i + 1}] ${b.scope} -> ${b.workspace} (thread: ${b.threadId || "\u81EA\u52A8\u521B\u5EFA"})`);
1619
+ });
1620
+ }
1621
+ const op = (await rl.question("\u64CD\u4F5C: [a]\u65B0\u589E/\u66F4\u65B0\u7ED1\u5B9A / [d]\u5220\u9664\u7ED1\u5B9A / \u56DE\u8F66\u8FD4\u56DE: ")).trim().toLowerCase();
1622
+ if (op === "d") {
1623
+ const idx = Number((await rl.question("\u8F93\u5165\u8981\u5220\u9664\u7684\u7ED1\u5B9A\u7F16\u53F7: ")).trim()) - 1;
1624
+ if (Number.isInteger(idx) && idx >= 0 && idx < bindings.length) {
1625
+ const removed = bindings.splice(idx, 1)[0];
1626
+ const next2 = { ...raw, bindings };
1627
+ await saveValidatedConfig(absPath, next2);
1628
+ onSave(next2);
1629
+ console.log(`\u5DF2\u5220\u9664\u7ED1\u5B9A: ${removed.scope}`);
1630
+ }
1631
+ return;
1632
+ }
1633
+ if (op !== "a") return;
1634
+ const scope = (await rl.question("\u8F93\u5165 scope (\u4F8B\u5982 c2c:USER_OPENID \u6216 group:GROUP_OPENID): ")).trim();
1635
+ if (!scope) return;
1636
+ const scopeHash = scopeToHash(scope);
1637
+ const projects = await fetchT3ProjectsBestEffort(absPath);
1638
+ let workspace = "";
1639
+ if (projects.length > 0) {
1640
+ console.log("\n\u68C0\u6D4B\u5230\u4EE5\u4E0B T3 Code \u5DF2\u6CE8\u518C\u9879\u76EE:");
1641
+ projects.forEach((p, idx) => console.log(` [${idx + 1}] ${p.title || "(\u672A\u547D\u540D)"} \u2014 ${p.workspaceRoot}`));
1642
+ const pick = (await rl.question("\u8F93\u5165\u9879\u76EE\u7F16\u53F7\uFF0C\u6216\u76F4\u63A5\u8F93\u5165\u5B8C\u6574\u76EE\u5F55\u8DEF\u5F84: ")).trim();
1643
+ const num = Number(pick);
1644
+ if (Number.isInteger(num) && num >= 1 && num <= projects.length) {
1645
+ workspace = projects[num - 1].workspaceRoot;
1646
+ } else {
1647
+ workspace = pick;
1648
+ }
1649
+ } else {
1650
+ workspace = (await rl.question("\u8F93\u5165 T3 \u5DF2\u6CE8\u518C\u7684\u9879\u76EE\u5DE5\u4F5C\u533A\u7EDD\u5BF9\u8DEF\u5F84: ")).trim();
1651
+ }
1652
+ if (!workspace) {
1653
+ console.log("\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u5DF2\u53D6\u6D88\u3002");
1654
+ return;
1655
+ }
1656
+ const threadId = (await rl.question("\u6307\u5B9A\u5DF2\u6709 T3 threadId (\u76F4\u63A5\u56DE\u8F66\u5219\u9996\u6B21\u804A\u5929\u81EA\u52A8\u521B\u5EFA): ")).trim();
1657
+ const entry = {
1658
+ scope,
1659
+ workspace,
1660
+ ...threadId ? { threadId } : {}
1661
+ };
1662
+ const existingIdx = bindings.findIndex((b) => {
1663
+ try {
1664
+ return scopeToHash(b.scope) === scopeHash;
1665
+ } catch {
1666
+ return false;
1667
+ }
1668
+ });
1669
+ if (existingIdx >= 0) bindings[existingIdx] = entry;
1670
+ else bindings.push(entry);
1671
+ const next = { ...raw, bindings };
1672
+ await saveValidatedConfig(absPath, next);
1673
+ onSave(next);
1674
+ console.log(`\u5DF2\u4FDD\u5B58\u7ED1\u5B9A: ${scope} -> ${workspace}`);
1675
+ }
1676
+
1677
+ // src/cli.ts
1678
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["help", "force", "install-media-mcp", "supervise", "yes"]);
1679
+ function parseArgs(argv) {
1680
+ const positional = [];
1681
+ const flags = /* @__PURE__ */ new Map();
1682
+ for (let i = 0; i < argv.length; i++) {
1683
+ const token = argv[i];
1684
+ if (token === "-h") {
1685
+ flags.set("help", true);
1686
+ continue;
1687
+ }
1688
+ if (token === "-y") {
1689
+ flags.set("yes", true);
1690
+ continue;
1691
+ }
1692
+ if (token.startsWith("--")) {
1693
+ const eq = token.indexOf("=");
1694
+ if (eq !== -1) {
1695
+ flags.set(token.slice(2, eq), token.slice(eq + 1));
1696
+ } else {
1697
+ const name = token.slice(2);
1698
+ if (BOOLEAN_FLAGS.has(name)) {
1699
+ flags.set(name, true);
1700
+ } else {
1701
+ const next = argv[i + 1];
1702
+ if (next && !next.startsWith("-")) {
1703
+ flags.set(name, next);
1704
+ i++;
1705
+ } else {
1706
+ flags.set(name, true);
1707
+ }
1708
+ }
1709
+ }
1710
+ } else {
1711
+ positional.push(token);
1712
+ }
1713
+ }
1714
+ return { positional, flags };
1715
+ }
1716
+ function getSiblingEntry(name) {
1717
+ const currentExt = extname(import.meta.filename) === ".mjs" ? ".mjs" : ".ts";
1718
+ return join5(import.meta.dirname, `${name}${currentExt}`);
1719
+ }
1720
+ function printHelp() {
1721
+ console.log(`t3-code-qqbot v${APP_VERSION} \u2014 \u8DE8\u5E73\u53F0\uFF08Windows & Linux\uFF09T3 Code \u5B98\u65B9 QQ \u673A\u5668\u4EBA\u63D2\u4EF6
1722
+
1723
+ \u7528\u6CD5\uFF1A
1724
+ t3-qqbot <\u547D\u4EE4> [\u9009\u9879]
1725
+ node dist/cli.mjs <\u547D\u4EE4> [\u9009\u9879]
1726
+
1727
+ \u5E38\u7528\u547D\u4EE4\uFF1A
1728
+ init [--dir <\u76EE\u5F55>] [--force] [--yes]
1729
+ \u4EA4\u4E92\u5F0F\u5B89\u88C5\u5411\u5BFC\uFF08\u626B\u7801/\u624B\u52A8\u586B\u51ED\u636E\u3001\u53EF\u9009\u9879\u3001\u7ED1\u5B9A\u4E0E\u5F00\u673A\u81EA\u5B88\u62A4\uFF1B--yes \u8DF3\u8FC7\u4EA4\u4E92\uFF09
1730
+ login [--config <\u8DEF\u5F84>] \u7EC8\u7AEF\u626B\u7801\u4E00\u952E\u7ED1\u5B9A QQ \u673A\u5668\u4EBA\uFF08\u81EA\u52A8\u83B7\u53D6 AppID\u3001AppSecret \u4E0E user_openid\uFF09
1731
+ config [show|set <\u952E> <\u503C>] [--config <\u8DEF\u5F84>]
1732
+ \u6253\u5F00\u4EA4\u4E92\u5F0F\u914D\u7F6E\u83DC\u5355\uFF08\u6216\u76F4\u63A5\u67E5\u770B/\u4FEE\u6539\u5355\u9879\u914D\u7F6E\uFF09
1733
+ start [--config <\u8DEF\u5F84>] [--supervise] [--log-file <\u8DEF\u5F84>]
1734
+ \u4E00\u952E\u540C\u65F6\u542F\u52A8\u6865\u63A5\u4E0E QQ \u7F51\u5173\uFF08--supervise \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF1B--log-file \u5C06\u8F93\u51FA\u5E26\u65F6\u95F4\u6233\u5199\u5165\u6587\u4EF6\uFF09
1735
+ service <install|uninstall|status|start|stop|restart> [--config <\u8DEF\u5F84>] [--name <\u540D\u79F0>]
1736
+ \u6CE8\u518C\u4E0E\u7BA1\u7406\u672C\u673A\u540E\u53F0\u81EA\u5B88\u62A4\uFF08Windows \u8BA1\u5212\u4EFB\u52A1 / Linux systemd --user\uFF09
1737
+ bridge [--config <\u8DEF\u5F84>] \u4EC5\u542F\u52A8 T3 \u6865\u63A5 HTTP \u670D\u52A1
1738
+ gateway [--config <\u8DEF\u5F84>] \u4EC5\u542F\u52A8 QQ \u5B98\u65B9 WebSocket \u7F51\u5173
1739
+ bind --scope <c2c:...|group:...> [--workspace <\u76EE\u5F55>] [--thread <\u4F1A\u8BDDID>] [--install-media-mcp] [--config <\u8DEF\u5F84>]
1740
+ \u6821\u9A8C\u5E76\u7ED1\u5B9A QQ \u4F1A\u8BDD\u5230 T3 \u5DE5\u4F5C\u533A\u6216\u6307\u5B9A\u4F1A\u8BDD
1741
+ doctor [--config <\u8DEF\u5F84>] \u6267\u884C 6 \u6B65\u5168\u94FE\u8DEF\u4F53\u68C0\u4E0E\u8FDE\u901A\u6027\u6D4B\u8BD5
1742
+ recover <runId> [--config <\u8DEF\u5F84>] \u5BF9\u5DF2\u4E2D\u65AD\u56DE\u4F20\u7684\u6307\u5B9A T3 runId \u8865\u53D1 QQ \u56DE\u590D
1743
+
1744
+ \u901A\u7528\u9009\u9879\uFF1A
1745
+ --config <\u8DEF\u5F84> \u6307\u5B9A config.json \u8DEF\u5F84\uFF08\u9ED8\u8BA4 ./config.json \u6216 $T3_QQBOT_CONFIG\uFF09
1746
+ --help, -h \u663E\u793A\u672C\u5E2E\u52A9\u4FE1\u606F
1747
+ `);
1748
+ }
1749
+ async function cmdInit(flags) {
1750
+ const dir = resolve4(typeof flags.get("dir") === "string" ? String(flags.get("dir")) : process.cwd());
1751
+ await runInitWizard({
1752
+ dir,
1753
+ force: flags.get("force") === true,
1754
+ nonInteractive: flags.get("yes") === true,
1755
+ cliEntry: import.meta.filename,
1756
+ bindAndInstallMcp: async (args) => {
1757
+ const bindFlags = new Map([
1758
+ ["scope", args.scope],
1759
+ ["workspace", args.workspace],
1760
+ ...args.threadId ? [["thread", args.threadId]] : [],
1761
+ ...args.installMediaMcp ? [["install-media-mcp", true]] : []
1762
+ ]);
1763
+ await cmdBind(args.configPath, bindFlags);
1764
+ }
1765
+ });
1766
+ }
1767
+ async function waitForBridgeOrExit(url, childExitPromise, timeoutMs = 1e4) {
1768
+ let exitedEarly;
1769
+ void childExitPromise.then((info) => {
1770
+ exitedEarly = info;
1771
+ });
1772
+ const deadline = Date.now() + timeoutMs;
1773
+ while (Date.now() < deadline) {
1774
+ if (exitedEarly) return { ready: false, exitedEarly };
1775
+ try {
1776
+ const res = await fetch(url, { signal: AbortSignal.timeout(1500) });
1777
+ await res.body?.cancel().catch(() => {
1778
+ });
1779
+ if (exitedEarly) return { ready: false, exitedEarly };
1780
+ if (res.status === 200 || res.status === 503) return { ready: true };
1781
+ } catch {
1782
+ }
1783
+ await sleep(200);
1784
+ }
1785
+ return { ready: false, exitedEarly };
1786
+ }
1787
+ function formatLocalLogTimestamp(date = /* @__PURE__ */ new Date()) {
1788
+ const pad = (n) => String(n).padStart(2, "0");
1789
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
1790
+ }
1791
+ async function createServiceFileLogger(logFilePath) {
1792
+ const absPath = resolve4(logFilePath);
1793
+ await mkdir3(dirname5(absPath), { recursive: true });
1794
+ const ws = createWriteStream(absPath, { flags: "a", encoding: "utf8" });
1795
+ ws.on("error", () => {
1796
+ });
1797
+ const writeLine = (line) => {
1798
+ if (ws.destroyed || ws.writableEnded) return;
1799
+ ws.write(`[${formatLocalLogTimestamp()}] ${line}
1800
+ `);
1801
+ };
1802
+ const attach = (stream) => {
1803
+ if (!stream) return;
1804
+ stream.setEncoding("utf8");
1805
+ let pending = "";
1806
+ stream.on("data", (chunk) => {
1807
+ pending += chunk;
1808
+ const lines = pending.split(/\r?\n/);
1809
+ pending = lines.pop() ?? "";
1810
+ for (const line of lines) {
1811
+ if (line.length > 0) writeLine(line);
1812
+ }
1813
+ });
1814
+ stream.on("end", () => {
1815
+ if (pending.length > 0) {
1816
+ writeLine(pending);
1817
+ pending = "";
1818
+ }
1819
+ });
1820
+ };
1821
+ const close = () => new Promise((resolveClose) => {
1822
+ if (ws.destroyed || ws.writableEnded) {
1823
+ resolveClose();
1824
+ return;
1825
+ }
1826
+ ws.end(() => resolveClose());
1827
+ });
1828
+ return { writeLine, attach, close };
1829
+ }
1830
+ async function cmdStart(configPath, supervise = false, logFilePath) {
1831
+ const logger = logFilePath ? await createServiceFileLogger(logFilePath) : void 0;
1832
+ const logInfo = (message) => {
1833
+ if (logger) logger.writeLine(message);
1834
+ else console.info(message);
1835
+ };
1836
+ const logError = (message) => {
1837
+ if (logger) logger.writeLine(message);
1838
+ else console.error(message);
1839
+ };
1840
+ if (!supervise) {
1841
+ try {
1842
+ await runStartOnce(configPath, logger);
1843
+ } catch (error) {
1844
+ if (logger) {
1845
+ logError(`Fatal: ${error instanceof Error ? error.message : String(error)}`);
1846
+ }
1847
+ throw error;
1848
+ } finally {
1849
+ await logger?.close();
1850
+ }
1851
+ return;
1852
+ }
1853
+ let stopping = false;
1854
+ const markStop = () => {
1855
+ stopping = true;
1856
+ };
1857
+ process.once("SIGINT", markStop);
1858
+ process.once("SIGTERM", markStop);
1859
+ let consecutiveFailures = 0;
1860
+ try {
1861
+ while (!stopping) {
1862
+ const startedAt = Date.now();
1863
+ try {
1864
+ await runStartOnce(configPath, logger);
1865
+ if (stopping) break;
1866
+ } catch (error) {
1867
+ if (stopping) break;
1868
+ const uptimeMs = Date.now() - startedAt;
1869
+ consecutiveFailures = uptimeMs > 6e4 ? 1 : consecutiveFailures + 1;
1870
+ const backoffMs = Math.min(3e4, 3e3 * Math.pow(2, consecutiveFailures - 1));
1871
+ logError(
1872
+ `Supervisor caught failure (${error instanceof Error ? error.message : String(error)}); restarting in ${backoffMs / 1e3}s...`
1873
+ );
1874
+ await sleep(backoffMs);
1875
+ }
1876
+ }
1877
+ } finally {
1878
+ process.off("SIGINT", markStop);
1879
+ process.off("SIGTERM", markStop);
1880
+ await logger?.close();
1881
+ }
1882
+ }
1883
+ async function runStartOnce(configPath, logger) {
1884
+ const logInfo = (message) => {
1885
+ if (logger) logger.writeLine(message);
1886
+ else console.info(message);
1887
+ };
1888
+ const logError = (message) => {
1889
+ if (logger) logger.writeLine(message);
1890
+ else console.error(message);
1891
+ };
1892
+ const config = await loadConfig(configPath);
1893
+ await loadCredentials(config);
1894
+ const bridgeEntry = getSiblingEntry("bridge");
1895
+ const gatewayEntry = getSiblingEntry("gateway");
1896
+ logInfo(`Starting T3 QQBot bridge (${bridgeEntry})...`);
1897
+ const bridgeChild = spawn(process.execPath, [bridgeEntry, config.configPath], {
1898
+ stdio: logger ? ["ignore", "pipe", "pipe"] : "inherit",
1899
+ env: process.env,
1900
+ windowsHide: true
1901
+ });
1902
+ if (logger) {
1903
+ logger.attach(bridgeChild.stdout);
1904
+ logger.attach(bridgeChild.stderr);
1905
+ }
1906
+ const bridgeExitPromise = new Promise((resolveExit) => {
1907
+ bridgeChild.once("exit", (code, signal) => resolveExit({ code, signal }));
1908
+ });
1909
+ const healthUrl = `http://${config.bridge.host === "::1" ? "[::1]" : config.bridge.host}:${config.bridge.port}/health`;
1910
+ const startup = await waitForBridgeOrExit(healthUrl, bridgeExitPromise, 1e4);
1911
+ if (!startup.ready) {
1912
+ if (bridgeChild.exitCode === null && !bridgeChild.killed) {
1913
+ bridgeChild.kill("SIGTERM");
1914
+ }
1915
+ if (startup.exitedEarly) {
1916
+ throw new Error(
1917
+ `Bridge exited during startup (code=${startup.exitedEarly.code}, signal=${startup.exitedEarly.signal})`
1918
+ );
1919
+ }
1920
+ throw new Error(`Bridge failed to start listening on ${healthUrl}`);
1921
+ }
1922
+ logInfo(`Starting T3 QQBot gateway (${gatewayEntry})...`);
1923
+ const gatewayChild = spawn(process.execPath, [gatewayEntry, config.configPath], {
1924
+ stdio: logger ? ["ignore", "pipe", "pipe"] : "inherit",
1925
+ env: process.env,
1926
+ windowsHide: true
1927
+ });
1928
+ if (logger) {
1929
+ logger.attach(gatewayChild.stdout);
1930
+ logger.attach(gatewayChild.stderr);
1931
+ }
1932
+ const gatewayExitPromise = new Promise((resolveExit) => {
1933
+ gatewayChild.once("exit", (code, signal) => resolveExit({ code, signal }));
1934
+ });
1935
+ let shuttingDown = false;
1936
+ const terminateChildren = (fromSigint) => {
1937
+ if (process.platform === "win32" && fromSigint) {
1938
+ setTimeout(() => {
1939
+ if (bridgeChild.exitCode === null) bridgeChild.kill();
1940
+ if (gatewayChild.exitCode === null) gatewayChild.kill();
1941
+ }, 1e3).unref();
1942
+ } else {
1943
+ if (bridgeChild.exitCode === null) bridgeChild.kill("SIGTERM");
1944
+ if (gatewayChild.exitCode === null) gatewayChild.kill("SIGTERM");
1945
+ }
1946
+ };
1947
+ await new Promise((resolveRun, rejectRun) => {
1948
+ const finish = (error) => {
1949
+ process.off("SIGINT", onSigint);
1950
+ process.off("SIGTERM", onSigterm);
1951
+ if (error) rejectRun(error);
1952
+ else resolveRun();
1953
+ };
1954
+ const shutdownClean = (fromSigint) => {
1955
+ if (shuttingDown) return;
1956
+ shuttingDown = true;
1957
+ terminateChildren(fromSigint);
1958
+ void Promise.race([Promise.all([bridgeExitPromise, gatewayExitPromise]), sleep(2500)]).then(() => finish());
1959
+ };
1960
+ const onSigint = () => shutdownClean(true);
1961
+ const onSigterm = () => shutdownClean(false);
1962
+ process.once("SIGINT", onSigint);
1963
+ process.once("SIGTERM", onSigterm);
1964
+ void bridgeExitPromise.then(({ code, signal }) => {
1965
+ if (shuttingDown) return;
1966
+ shuttingDown = true;
1967
+ if (code === SELF_UPDATE_EXIT_CODE) {
1968
+ logInfo(`Bridge requested graceful self-update restart (code=${code}); restarting immediately...`);
1969
+ terminateChildren(false);
1970
+ void Promise.race([gatewayExitPromise, sleep(2e3)]).then(() => finish());
1971
+ return;
1972
+ }
1973
+ const err = new Error(`Bridge exited unexpectedly (code=${code}, signal=${signal})`);
1974
+ logError(err.message);
1975
+ terminateChildren(false);
1976
+ void Promise.race([gatewayExitPromise, sleep(2e3)]).then(() => finish(err));
1977
+ });
1978
+ void gatewayExitPromise.then(({ code, signal }) => {
1979
+ if (shuttingDown) return;
1980
+ shuttingDown = true;
1981
+ const err = new Error(`Gateway exited unexpectedly (code=${code}, signal=${signal})`);
1982
+ logError(err.message);
1983
+ terminateChildren(false);
1984
+ void Promise.race([bridgeExitPromise, sleep(2e3)]).then(() => finish(err));
1985
+ });
1986
+ });
1987
+ }
1988
+ async function installAntigravityMcp(mcpFile, mcpServerEntry) {
1989
+ const existingRaw = await readFile5(mcpFile, "utf8").catch((err) => {
1990
+ if (err.code === "ENOENT") return "";
1991
+ throw err;
1992
+ });
1993
+ const mcpConfig = existingRaw.trim() ? JSON.parse(existingRaw.replace(/^\uFEFF/, "")) : {};
1994
+ mcpConfig.mcpServers ??= {};
1995
+ await mkdir3(dirname5(mcpFile), { recursive: true });
1996
+ if (existingRaw.trim()) {
1997
+ await writeFile3(`${mcpFile}.pre-t3-qqbot`, existingRaw, { flag: "wx" }).catch((err) => {
1998
+ if (err.code !== "EEXIST") throw err;
1999
+ });
2000
+ }
2001
+ mcpConfig.mcpServers["qqbot-media"] = mcpServerEntry;
2002
+ await writeFile3(`${mcpFile}.next`, JSON.stringify(mcpConfig, null, 2) + "\n", "utf8");
2003
+ await rename2(`${mcpFile}.next`, mcpFile);
2004
+ }
2005
+ async function cmdBind(configPath, flags) {
2006
+ const scope = typeof flags.get("scope") === "string" ? String(flags.get("scope")).trim() : "";
2007
+ const workspaceFlag = typeof flags.get("workspace") === "string" ? String(flags.get("workspace")).trim() : "";
2008
+ const threadId = typeof flags.get("thread") === "string" ? String(flags.get("thread")).trim() : "";
2009
+ const installMediaMcp = flags.get("install-media-mcp") === true;
2010
+ if (!scope) {
2011
+ throw new Error("Missing --scope (example: --scope c2c:<user_openid> or --scope group:<group_openid>)");
2012
+ }
2013
+ if (!threadId && !workspaceFlag) {
2014
+ throw new Error("Provide either --thread <threadId> or --workspace <path>");
2015
+ }
2016
+ const scopeHash = scopeToHash(scope);
2017
+ const config = await loadConfig(configPath);
2018
+ const t3Cli = new T3Cli(config.t3);
2019
+ const observer = new Observer(
2020
+ config.t3.origin,
2021
+ () => t3Cli.issueSession({
2022
+ scopes: ["orchestration:read"],
2023
+ subject: "mcp-client",
2024
+ ttl: "5m",
2025
+ label: "T3 QQBot bind check"
2026
+ }),
2027
+ (sessionId) => t3Cli.revokeSession(sessionId)
2028
+ );
2029
+ let resolvedWorkspace = workspaceFlag ? resolve4(workspaceFlag) : "";
2030
+ let providerInstanceId;
2031
+ try {
2032
+ const { projects } = await observer.call("t3_project_list", { limit: 100 });
2033
+ if (threadId) {
2034
+ const snap = await observer.read(threadId);
2035
+ const project = projects.find((row) => row.id === snap.thread.projectId);
2036
+ if (!project) {
2037
+ throw new Error(`Thread "${threadId}" does not match any registered T3 project`);
2038
+ }
2039
+ if (resolvedWorkspace && !samePath(project.workspaceRoot, resolvedWorkspace)) {
2040
+ throw new Error(`Thread "${threadId}" belongs to "${project.workspaceRoot}", not "${resolvedWorkspace}"`);
2041
+ }
2042
+ resolvedWorkspace = project.workspaceRoot;
2043
+ providerInstanceId = snap.thread.providerInstanceId;
2044
+ } else {
2045
+ const project = projects.find((row) => samePath(row.workspaceRoot, resolvedWorkspace));
2046
+ if (!project) {
2047
+ throw new Error(
2048
+ `Workspace "${resolvedWorkspace}" is not registered in T3 Code. Open/register it in T3 Code first.`
2049
+ );
2050
+ }
2051
+ resolvedWorkspace = project.workspaceRoot;
2052
+ }
2053
+ } finally {
2054
+ await observer.close().catch(() => {
2055
+ });
2056
+ }
2057
+ const rawText = await readFile5(config.configPath, "utf8");
2058
+ const rawJson = JSON.parse(rawText.replace(/^\uFEFF/, ""));
2059
+ rawJson.bindings = Array.isArray(rawJson.bindings) ? rawJson.bindings : [];
2060
+ const nextEntry = {
2061
+ scope,
2062
+ workspace: resolvedWorkspace,
2063
+ ...threadId ? { threadId } : {}
2064
+ };
2065
+ const existingIdx = rawJson.bindings.findIndex((item) => {
2066
+ try {
2067
+ return scopeToHash(item.scope) === scopeHash;
2068
+ } catch {
2069
+ return false;
2070
+ }
2071
+ });
2072
+ if (existingIdx >= 0) {
2073
+ rawJson.bindings[existingIdx] = nextEntry;
2074
+ } else {
2075
+ rawJson.bindings.push(nextEntry);
2076
+ }
2077
+ const tmpConfig = `${config.configPath}.next`;
2078
+ await writeFile3(tmpConfig, JSON.stringify(rawJson, null, 2) + "\n", "utf8");
2079
+ await rename2(tmpConfig, config.configPath);
2080
+ console.log(`Updated binding in ${config.configPath}:`);
2081
+ console.log(` scope: ${scope}`);
2082
+ console.log(` workspace: ${resolvedWorkspace}`);
2083
+ console.log(` threadId: ${threadId || "(auto-create on first message)"}`);
2084
+ const publishEntry = getSiblingEntry("publish");
2085
+ const mcpServerEntry = { command: process.execPath, args: [publishEntry, config.configPath] };
2086
+ const t3Home = config.t3.home || process.env.T3CODE_HOME || join5(homedir3(), ".t3");
2087
+ if (installMediaMcp) {
2088
+ if (providerInstanceId?.startsWith("antigravity")) {
2089
+ const mcpFile = join5(
2090
+ t3Home,
2091
+ "userdata",
2092
+ "providers",
2093
+ "antigravity",
2094
+ digest(providerInstanceId),
2095
+ "config",
2096
+ "mcp_config.json"
2097
+ );
2098
+ await installAntigravityMcp(mcpFile, mcpServerEntry);
2099
+ console.log(`Registered "qqbot-media" MCP server in ${mcpFile}`);
2100
+ } else {
2101
+ const agyRoot = join5(t3Home, "userdata", "providers", "antigravity");
2102
+ const agyDirs = await readdir(agyRoot, { withFileTypes: true }).then((entries) => entries.filter((e) => e.isDirectory()).map((e) => e.name)).catch(() => []);
2103
+ if (!threadId && agyDirs.length === 1) {
2104
+ const mcpFile = join5(agyRoot, agyDirs[0], "config", "mcp_config.json");
2105
+ await installAntigravityMcp(mcpFile, mcpServerEntry);
2106
+ console.log(`Registered "qqbot-media" MCP server in ${mcpFile}`);
2107
+ } else {
2108
+ if (!threadId && agyDirs.length > 1) {
2109
+ console.log(
2110
+ `
2111
+ Detected ${agyDirs.length} Antigravity provider instances under ${agyRoot}. Pass --thread <threadId> with --install-media-mcp to register automatically for that thread's provider, or configure manually:`
2112
+ );
2113
+ } else {
2114
+ console.log('\nRegister the "qqbot-media" MCP server for your provider:');
2115
+ }
2116
+ console.log("\nClaude Code / JSON-based MCP clients:");
2117
+ console.log(JSON.stringify({ mcpServers: { "qqbot-media": mcpServerEntry } }, null, 2));
2118
+ console.log("\nCodex CLI (~/.codex/config.toml):");
2119
+ console.log(`[mcp_servers.qqbot-media]`);
2120
+ console.log(`command = ${JSON.stringify(mcpServerEntry.command)}`);
2121
+ console.log(`args = ${JSON.stringify(mcpServerEntry.args)}`);
2122
+ }
2123
+ }
2124
+ } else {
2125
+ console.log("\nOptional: re-run with --install-media-mcp or add this MCP server so your T3 agent can send files to QQ:");
2126
+ console.log(JSON.stringify({ mcpServers: { "qqbot-media": mcpServerEntry } }, null, 2));
2127
+ }
2128
+ console.log("\nRestart the bridge to activate the updated binding.");
2129
+ }
2130
+ async function cmdDoctor(configPath) {
2131
+ const major = Number(process.versions.node.split(".")[0]);
2132
+ console.log(
2133
+ `[1/6] Node.js: v${process.versions.node} (${process.platform}/${process.arch}) ${major >= 24 ? "OK" : "NEEDS >= 24"}`
2134
+ );
2135
+ if (major < 24) throw new Error("Node.js 24+ is required");
2136
+ const config = await loadConfig(configPath);
2137
+ console.log(`[2/6] Config loaded: ${config.configPath} (${config.bindings.length} binding(s))`);
2138
+ await loadCredentials(config);
2139
+ console.log("[3/6] Credentials loaded: OK (local check only; QQ OpenAPI & IP whitelist verified on gateway connect)");
2140
+ const t3Cli = new T3Cli(config.t3);
2141
+ const resolvedCli = await t3Cli.resolve();
2142
+ console.log(
2143
+ `[4/6] T3 CLI resolved: ${resolvedCli.executable}${resolvedCli.prefix.length ? " " + resolvedCli.prefix.join(" ") : ""}`
2144
+ );
2145
+ const probe = await fetch(config.t3.origin, { signal: AbortSignal.timeout(3e3) }).catch(() => null);
2146
+ if (!probe?.ok) {
2147
+ throw new Error(`T3 Code server is unreachable at ${config.t3.origin}. Start T3 Code first.`);
2148
+ }
2149
+ await probe.body?.cancel();
2150
+ console.log(`[5/6] T3 Code server reachable: ${config.t3.origin}`);
2151
+ const observer = new Observer(
2152
+ config.t3.origin,
2153
+ () => t3Cli.issueSession({
2154
+ scopes: ["orchestration:read", "orchestration:operate"],
2155
+ subject: "mcp-client",
2156
+ ttl: "5m",
2157
+ label: "T3 QQBot doctor"
2158
+ }),
2159
+ (sessionId) => t3Cli.revokeSession(sessionId)
2160
+ );
2161
+ try {
2162
+ if (config.bindings.length === 0) {
2163
+ console.log(" Warning: 0 bindings configured. Run `bind` after capturing your scope from logs.");
2164
+ }
2165
+ for (const binding of config.bindings) {
2166
+ if (binding.threadId) {
2167
+ const snap = await observer.read(binding.threadId);
2168
+ console.log(
2169
+ ` Binding ${binding.rawScope} -> thread ${binding.threadId} (project=${snap.thread.projectId}, items=${snap.thread.itemCount}) OK`
2170
+ );
2171
+ } else {
2172
+ console.log(
2173
+ ` Binding ${binding.rawScope} -> workspace ${binding.workspace} (auto-create thread on first message) OK`
2174
+ );
2175
+ }
2176
+ }
2177
+ const probePng = join5(tmpdir(), `t3-qqbot-doctor-${process.pid}.png`);
2178
+ await writeFile3(
2179
+ probePng,
2180
+ Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/6X+Xo8AAAAASUVORK5CYII=", "base64")
2181
+ );
2182
+ try {
2183
+ const attachment = await observer.upload(probePng, "doctor-check.png", "image/png");
2184
+ await observer.call("t3_attachment_discard", { attachmentId: attachment.id });
2185
+ console.log("[6/6] T3 native attachment upload & discard round-trip: OK");
2186
+ } finally {
2187
+ await unlink2(probePng).catch(() => {
2188
+ });
2189
+ }
2190
+ } finally {
2191
+ await observer.close().catch(() => {
2192
+ });
2193
+ }
2194
+ console.log("\nAll checks passed.");
2195
+ }
2196
+ async function runSibling(entry, args) {
2197
+ const script = getSiblingEntry(entry);
2198
+ let shuttingDown = false;
2199
+ await new Promise((resolveDone, rejectDone) => {
2200
+ const child = spawn(process.execPath, [script, ...args], {
2201
+ stdio: "inherit",
2202
+ env: process.env,
2203
+ windowsHide: true
2204
+ });
2205
+ const forwardSignal = (signal) => {
2206
+ shuttingDown = true;
2207
+ if (process.platform !== "win32" || signal !== "SIGINT") {
2208
+ child.kill(signal);
2209
+ }
2210
+ };
2211
+ process.once("SIGINT", forwardSignal);
2212
+ process.once("SIGTERM", forwardSignal);
2213
+ child.once("error", rejectDone);
2214
+ child.once("exit", (code, signal) => {
2215
+ process.off("SIGINT", forwardSignal);
2216
+ process.off("SIGTERM", forwardSignal);
2217
+ if (code === 0 || shuttingDown && signal) resolveDone();
2218
+ else rejectDone(new Error(`${entry} exited abnormally (code=${code}, signal=${signal})`));
2219
+ });
2220
+ });
2221
+ }
2222
+ async function main() {
2223
+ const { positional, flags } = parseArgs(process.argv.slice(2));
2224
+ const command = positional[0];
2225
+ if (!command || command === "help" || flags.get("help") === true) {
2226
+ printHelp();
2227
+ return;
2228
+ }
2229
+ const configPath = resolve4(
2230
+ typeof flags.get("config") === "string" ? String(flags.get("config")) : process.env.T3_QQBOT_CONFIG || "config.json"
2231
+ );
2232
+ if (command === "init") {
2233
+ await cmdInit(flags);
2234
+ return;
2235
+ }
2236
+ if (command === "login") {
2237
+ await runQrLoginCommand(configPath);
2238
+ return;
2239
+ }
2240
+ if (command === "config" || command === "menu") {
2241
+ const sub = positional[1];
2242
+ if (sub === "show") {
2243
+ await runConfigShow(configPath);
2244
+ return;
2245
+ }
2246
+ if (sub === "set") {
2247
+ const key = positional[2];
2248
+ const value = positional[3];
2249
+ if (!key || value === void 0) {
2250
+ throw new Error("Usage: t3-qqbot config set <key> <value> [--config <path>]");
2251
+ }
2252
+ await runConfigSet(configPath, key, value);
2253
+ return;
2254
+ }
2255
+ await runConfigMenu({
2256
+ configPath,
2257
+ cliEntry: import.meta.filename,
2258
+ runDoctor: cmdDoctor
2259
+ });
2260
+ return;
2261
+ }
2262
+ if (command === "start") {
2263
+ const logFile = typeof flags.get("log-file") === "string" ? String(flags.get("log-file")) : void 0;
2264
+ await cmdStart(configPath, flags.get("supervise") === true, logFile);
2265
+ return;
2266
+ }
2267
+ if (command === "service") {
2268
+ await runServiceCommand(positional[1], {
2269
+ cliEntry: import.meta.filename,
2270
+ configPath,
2271
+ name: typeof flags.get("name") === "string" ? String(flags.get("name")) : void 0
2272
+ });
2273
+ return;
2274
+ }
2275
+ if (command === "bridge") {
2276
+ await runSibling("bridge", [configPath]);
2277
+ return;
2278
+ }
2279
+ if (command === "gateway") {
2280
+ await runSibling("gateway", [configPath]);
2281
+ return;
2282
+ }
2283
+ if (command === "recover") {
2284
+ const runId = positional[1];
2285
+ if (!runId) throw new Error("Usage: recover <runId> [--config <path>]");
2286
+ await runSibling("bridge", [configPath, "--recover", runId]);
2287
+ return;
2288
+ }
2289
+ if (command === "bind") {
2290
+ await cmdBind(configPath, flags);
2291
+ return;
2292
+ }
2293
+ if (command === "doctor") {
2294
+ await cmdDoctor(configPath);
2295
+ return;
2296
+ }
2297
+ throw new Error(`Unknown command "${command}". Run with --help to see available commands.`);
2298
+ }
2299
+ if (isMainModule(import.meta.url)) {
2300
+ main().catch((error) => {
2301
+ console.error("Error:", error instanceof Error ? error.message : String(error));
2302
+ process.exit(1);
2303
+ });
2304
+ }
2305
+ export {
2306
+ parseArgs
2307
+ };