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.
@@ -0,0 +1,2772 @@
1
+ // src/bridge.ts
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import { appendFileSync } from "node:fs";
4
+ import { mkdir as mkdir3, readFile as readFile5, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
5
+ import { createServer } from "node:http";
6
+ import { basename as basename2, join as join5, resolve as resolve4 } from "node:path";
7
+ import { setTimeout as sleep2 } from "node:timers/promises";
8
+ import { QQBot, StreamInputState, StreamSession } from "@tencent-connect/qqbot-nodejs";
9
+ import { ApiClient, MessageApi } from "@tencent-connect/qqbot-nodejs/protocol";
10
+
11
+ // src/config.ts
12
+ import { realpathSync } from "node:fs";
13
+ import { access, readFile } from "node:fs/promises";
14
+ import path, { dirname, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+
17
+ // src/protocol.ts
18
+ import { createHash } from "node:crypto";
19
+ import { copyFile, mkdir, realpath, stat, writeFile } from "node:fs/promises";
20
+ import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
21
+ var MAX_ATTACHMENT_BYTES = 12 * 1024 * 1024;
22
+ var MAX_ATTACHMENTS_PER_MESSAGE = 10;
23
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
24
+ var digestBuffer = (value) => createHash("sha256").update(value).digest();
25
+ var MIME_MAP = {
26
+ ".png": "image/png",
27
+ ".jpg": "image/jpeg",
28
+ ".jpeg": "image/jpeg",
29
+ ".webp": "image/webp",
30
+ ".gif": "image/gif",
31
+ ".wav": "audio/wav",
32
+ ".mp3": "audio/mpeg",
33
+ ".silk": "audio/silk",
34
+ ".pdf": "application/pdf",
35
+ ".txt": "text/plain",
36
+ ".md": "text/markdown",
37
+ ".json": "application/json",
38
+ ".csv": "text/csv",
39
+ ".zip": "application/zip"
40
+ };
41
+ function mimeFromExtension(filePath) {
42
+ return MIME_MAP[extname(filePath).toLowerCase()] ?? "application/octet-stream";
43
+ }
44
+ function isInsideBase(base, candidate) {
45
+ const rel = relative(base, candidate);
46
+ return Boolean(rel) && rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel);
47
+ }
48
+ async function safeArtifact(root, file) {
49
+ if (!file || typeof file !== "string" || file.includes("\0")) {
50
+ throw new Error("Invalid artifact path");
51
+ }
52
+ if (/^(\\\\|\/\/)/.test(file)) {
53
+ throw new Error("Artifact is outside this workspace directory");
54
+ }
55
+ const base = await realpath(root);
56
+ const lexicalCandidate = resolve(base, file);
57
+ if (/^(\\\\|\/\/)/.test(lexicalCandidate) || !isInsideBase(base, lexicalCandidate)) {
58
+ throw new Error("Artifact is outside this workspace directory");
59
+ }
60
+ const localPath = await realpath(lexicalCandidate);
61
+ if (!isInsideBase(base, localPath)) {
62
+ throw new Error("Artifact is outside this workspace directory");
63
+ }
64
+ const info = await stat(localPath);
65
+ if (!info.isFile() || info.size <= 0 || info.size > MAX_ATTACHMENT_BYTES) {
66
+ throw new Error("Invalid artifact size or type");
67
+ }
68
+ const extension = extname(localPath).toLowerCase();
69
+ const fileType = [".png", ".jpg", ".jpeg"].includes(extension) ? 1 : extension === ".silk" ? 3 : 4;
70
+ return { localPath, fileType, fileName: basename(localPath) };
71
+ }
72
+ function detectExtension(bytes, fallbackName) {
73
+ const header = bytes.subarray(0, 16);
74
+ if (header.length >= 8 && header.subarray(0, 8).toString("hex") === "89504e470d0a1a0a") {
75
+ return "png";
76
+ }
77
+ if (header.length >= 3 && header.subarray(0, 3).toString("hex") === "ffd8ff") {
78
+ return "jpg";
79
+ }
80
+ if (header.length >= 12 && header.toString("ascii", 0, 4) === "RIFF" && header.toString("ascii", 8, 12) === "WAVE") {
81
+ return "wav";
82
+ }
83
+ if (header.length >= 9 && header.subarray(header[0] === 2 ? 1 : 0).toString("ascii").startsWith("#!SILK_V3")) {
84
+ return "silk";
85
+ }
86
+ const suffix = extname(fallbackName).toLowerCase();
87
+ return /^\.[a-z0-9]{1,12}$/.test(suffix) ? suffix.slice(1) : "bin";
88
+ }
89
+ async function saveAttachment(item, directory, index, hosts) {
90
+ if (!item.url) throw new Error("Missing QQ attachment URL");
91
+ const url = new URL(item.url.startsWith("//") ? `https:${item.url}` : item.url);
92
+ if (url.protocol !== "https:" || url.port || url.username || url.password || !hosts.has(url.hostname.toLowerCase())) {
93
+ throw new Error(`Unrecognized QQ attachment origin: ${url.hostname}`);
94
+ }
95
+ const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(2e4) });
96
+ if (!response.ok || !response.body) {
97
+ await response.body?.cancel().catch(() => {
98
+ });
99
+ throw new Error(`QQ attachment HTTP ${response.status}`);
100
+ }
101
+ const chunks = [];
102
+ let size = 0;
103
+ for await (const chunk of response.body) {
104
+ size += chunk.length;
105
+ if (size > MAX_ATTACHMENT_BYTES) {
106
+ await response.body.cancel().catch(() => {
107
+ });
108
+ throw new Error("QQ attachment exceeds 12 MiB limit");
109
+ }
110
+ chunks.push(chunk);
111
+ }
112
+ const bytes = Buffer.concat(chunks);
113
+ const extension = detectExtension(bytes, item.filename ?? url.pathname);
114
+ const path2 = join(directory, `${index}-${digest(bytes).slice(0, 12)}.${extension}`);
115
+ await mkdir(directory, { recursive: true });
116
+ await writeFile(path2, bytes);
117
+ return { path: path2, format: extension };
118
+ }
119
+ async function copyStagedAttachment(root, file, directory, index) {
120
+ const source = await safeArtifact(root, file);
121
+ const path2 = join(directory, `${index}-${basename(source.localPath)}`);
122
+ await mkdir(directory, { recursive: true });
123
+ await copyFile(source.localPath, path2);
124
+ return { path: path2 };
125
+ }
126
+
127
+ // src/config.ts
128
+ var APP_VERSION = "1.2.3";
129
+ var SELF_UPDATE_EXIT_CODE = 75;
130
+ var DEFAULT_ATTACHMENT_HOSTS = [
131
+ "multimedia.nt.qq.com.cn",
132
+ "multimedia.nt.qq.com",
133
+ "gchat.qpic.cn",
134
+ "c2cpicdw.qpic.cn"
135
+ ];
136
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
137
+ function isMainModule(metaUrl, argv1 = process.argv[1]) {
138
+ if (!argv1) return false;
139
+ const resolved = resolve2(argv1);
140
+ if (metaUrl === pathToFileURL(resolved).href) return true;
141
+ try {
142
+ return metaUrl === pathToFileURL(realpathSync(resolved)).href;
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+ function isLoopbackOrigin(origin) {
148
+ try {
149
+ const url = new URL(origin);
150
+ return (url.protocol === "http:" || url.protocol === "https:") && LOOPBACK_HOSTS.has(url.hostname);
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
155
+ function normalizePathForCompare(targetPath, platform = process.platform) {
156
+ const pathImpl = platform === "win32" ? path.win32 : path.posix;
157
+ const normalized = pathImpl.resolve(targetPath);
158
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
159
+ }
160
+ function samePath(a, b, platform = process.platform) {
161
+ return normalizePathForCompare(a, platform) === normalizePathForCompare(b, platform);
162
+ }
163
+ function scopeToHash(scope) {
164
+ const trimmed = scope.trim();
165
+ if (/^sha256:[a-f0-9]{64}$/i.test(trimmed)) {
166
+ return trimmed.slice("sha256:".length).toLowerCase();
167
+ }
168
+ if (!/^(c2c|group):.+$/i.test(trimmed)) {
169
+ throw new Error(
170
+ `Invalid binding scope "${scope}". Expected "c2c:<user_openid>", "group:<group_openid>", or "sha256:<64-hex>".`
171
+ );
172
+ }
173
+ return digest(trimmed);
174
+ }
175
+ function resolveRelative(baseDir, maybeRelative) {
176
+ return isAbsolute2(maybeRelative) ? resolve2(maybeRelative) : resolve2(baseDir, maybeRelative);
177
+ }
178
+ function parseConfig(raw, configPath) {
179
+ const absConfigPath = resolve2(configPath);
180
+ const configDir = dirname(absConfigPath);
181
+ if (!raw || typeof raw !== "object") {
182
+ throw new Error("Config must be a JSON object");
183
+ }
184
+ if (!raw.stateDir || typeof raw.stateDir !== "string") {
185
+ throw new Error('Config requires "stateDir"');
186
+ }
187
+ if (!raw.t3?.origin || typeof raw.t3.origin !== "string") {
188
+ throw new Error('Config requires "t3.origin"');
189
+ }
190
+ if (!isLoopbackOrigin(raw.t3.origin)) {
191
+ throw new Error(`Config "t3.origin" must target loopback (127.0.0.1 / localhost / ::1), got: ${raw.t3.origin}`);
192
+ }
193
+ const port = raw.bridge?.port ?? 18773;
194
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
195
+ throw new Error(`Invalid bridge port: ${port}`);
196
+ }
197
+ const host = raw.bridge?.host ?? "127.0.0.1";
198
+ if (!LOOPBACK_HOSTS.has(host)) {
199
+ throw new Error(`Bridge host must be loopback for security, got: ${host}`);
200
+ }
201
+ const maxMessageChars = raw.bridge?.maxMessageChars ?? 1600;
202
+ if (!Number.isInteger(maxMessageChars) || maxMessageChars < 100 || maxMessageChars > 4e3) {
203
+ throw new Error(`Invalid bridge.maxMessageChars (${maxMessageChars}); expected integer between 100 and 4000`);
204
+ }
205
+ const rawBindings = Array.isArray(raw.bindings) ? raw.bindings : [];
206
+ const bindings = rawBindings.map((binding, index) => {
207
+ if (!binding || typeof binding.scope !== "string" || !binding.scope.trim()) {
208
+ throw new Error(`Binding #${index} is missing "scope"`);
209
+ }
210
+ if (typeof binding.workspace !== "string" || !binding.workspace.trim()) {
211
+ throw new Error(`Binding #${index} (${binding.scope}) is missing "workspace"`);
212
+ }
213
+ const threadId = typeof binding.threadId === "string" && binding.threadId.trim() && !binding.threadId.startsWith("REPLACE_WITH_") ? binding.threadId.trim() : void 0;
214
+ return {
215
+ rawScope: binding.scope.trim(),
216
+ scopeHash: scopeToHash(binding.scope),
217
+ workspace: resolveRelative(configDir, binding.workspace.trim()),
218
+ threadId,
219
+ modelSelection: binding.modelSelection
220
+ };
221
+ });
222
+ const bridgeUrl = raw.gateway?.bridgeUrl?.trim() || `http://${host === "::1" ? "[::1]" : host}:${port}/events`;
223
+ return {
224
+ configPath: absConfigPath,
225
+ configDir,
226
+ stateDir: resolveRelative(configDir, raw.stateDir),
227
+ credentialsFile: raw.credentialsFile ? resolveRelative(configDir, raw.credentialsFile) : void 0,
228
+ t3: {
229
+ origin: raw.t3.origin.trim(),
230
+ executable: raw.t3.executable?.trim() || "auto",
231
+ prefix: Array.isArray(raw.t3.prefix) ? raw.t3.prefix.map(String) : [],
232
+ env: raw.t3.env && typeof raw.t3.env === "object" ? { ...raw.t3.env } : {},
233
+ home: raw.t3.home ? resolveRelative(configDir, raw.t3.home) : void 0,
234
+ muteMobileCompletionThreadId: raw.t3.muteMobileCompletionThreadId?.trim() || void 0
235
+ },
236
+ bridge: {
237
+ host,
238
+ port,
239
+ proactiveBackgroundReports: Boolean(raw.bridge?.proactiveBackgroundReports),
240
+ maxMessageChars,
241
+ autoSettleThread: Boolean(raw.bridge?.autoSettleThread),
242
+ enableSlashCommands: raw.bridge?.enableSlashCommands ?? true,
243
+ testStaging: raw.bridge?.testStaging ? resolveRelative(configDir, raw.bridge.testStaging) : void 0
244
+ },
245
+ gateway: {
246
+ bridgeUrl,
247
+ requireMentionInGroup: raw.gateway?.requireMentionInGroup ?? true,
248
+ stripPrefix: raw.gateway?.stripPrefix ?? ""
249
+ },
250
+ attachmentHosts: Array.isArray(raw.attachmentHosts) && raw.attachmentHosts.length > 0 ? raw.attachmentHosts.map((h) => String(h).trim().toLowerCase()).filter(Boolean) : [...DEFAULT_ATTACHMENT_HOSTS],
251
+ bindings
252
+ };
253
+ }
254
+ async function loadConfig(configPath) {
255
+ const rawText = await readFile(configPath, "utf8");
256
+ const parsed = JSON.parse(rawText.replace(/^\uFEFF/, ""));
257
+ return parseConfig(parsed, configPath);
258
+ }
259
+ async function loadCredentials(config, env = process.env, options = {}) {
260
+ const requireBridgeSecret = options.requireBridgeSecret ?? true;
261
+ const envAppId = env.QQ_APP_ID?.trim() || "";
262
+ const envAppSecret = env.QQ_APP_SECRET?.trim() || "";
263
+ const envBridgeSecret = env.QQ_BRIDGE_SECRET?.trim() || "";
264
+ const explicitCredsFile = env.QQ_CREDENTIALS_FILE?.trim();
265
+ const envHasAll = Boolean(envAppId && envAppSecret && (!requireBridgeSecret || envBridgeSecret));
266
+ let fileCreds = {};
267
+ const credentialsPath = explicitCredsFile || (envHasAll ? void 0 : config.credentialsFile);
268
+ if (credentialsPath) {
269
+ try {
270
+ const raw = await readFile(credentialsPath, "utf8");
271
+ fileCreds = JSON.parse(raw.replace(/^\uFEFF/, ""));
272
+ } catch (error) {
273
+ if (error.code === "ENOENT" && !explicitCredsFile && envHasAll) {
274
+ fileCreds = {};
275
+ } else {
276
+ throw error;
277
+ }
278
+ }
279
+ }
280
+ const appId = envAppId || fileCreds.appId?.trim() || "";
281
+ const appSecret = envAppSecret || fileCreds.appSecret?.trim() || "";
282
+ const bridgeSecret = envBridgeSecret || fileCreds.bridgeSecret?.trim() || "";
283
+ if (!appId || !appSecret || requireBridgeSecret && !bridgeSecret) {
284
+ const missing = requireBridgeSecret ? "appId, appSecret, bridgeSecret" : "appId, appSecret";
285
+ throw new Error(
286
+ `Missing QQ Bot credentials (${missing}). Set them in credentials.json or environment variables.`
287
+ );
288
+ }
289
+ if (appId.startsWith("REPLACE_WITH_") || appSecret.startsWith("REPLACE_WITH_") || requireBridgeSecret && bridgeSecret.startsWith("REPLACE_WITH_")) {
290
+ throw new Error("Credentials still contain REPLACE_WITH_* placeholder values. Edit credentials.json first.");
291
+ }
292
+ return { appId, appSecret, bridgeSecret };
293
+ }
294
+ function findBindingForScope(config, scope) {
295
+ const hash = digest(scope);
296
+ return config.bindings.find((binding) => binding.scopeHash === hash);
297
+ }
298
+
299
+ // src/observe.ts
300
+ import { readFile as readFile2 } from "node:fs/promises";
301
+ var McpHttpError = class extends Error {
302
+ status;
303
+ constructor(method, status) {
304
+ super(`T3 MCP ${method} HTTP ${status}`);
305
+ this.status = status;
306
+ }
307
+ };
308
+ var Observer = class {
309
+ state = null;
310
+ connecting;
311
+ id = 0;
312
+ url;
313
+ issue;
314
+ revoke;
315
+ constructor(origin, issue, revoke) {
316
+ this.url = new URL("/mcp", origin).href;
317
+ this.issue = issue;
318
+ this.revoke = revoke;
319
+ }
320
+ async rpcWith(token, sessionId, method, params, notification = false) {
321
+ const response = await fetch(this.url, {
322
+ method: "POST",
323
+ signal: AbortSignal.timeout(15e3),
324
+ headers: {
325
+ Authorization: `Bearer ${token}`,
326
+ "Content-Type": "application/json",
327
+ Accept: "application/json, text/event-stream",
328
+ ...sessionId ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-06-18" } : {}
329
+ },
330
+ body: JSON.stringify({
331
+ jsonrpc: "2.0",
332
+ method,
333
+ params,
334
+ ...!notification ? { id: ++this.id } : {}
335
+ })
336
+ });
337
+ if (!response.ok) {
338
+ await response.body?.cancel().catch(() => {
339
+ });
340
+ throw new McpHttpError(method, response.status);
341
+ }
342
+ const newSessionId = method === "initialize" ? response.headers.get("mcp-session-id") : void 0;
343
+ if (notification) {
344
+ await response.body?.cancel().catch(() => {
345
+ });
346
+ return { newSessionId };
347
+ }
348
+ const contentType = response.headers.get("content-type") ?? "";
349
+ let body;
350
+ if (contentType.includes("text/event-stream")) {
351
+ const text = await response.text();
352
+ const dataLine = text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).filter(Boolean).at(-1);
353
+ if (!dataLine) throw new Error(`T3 MCP ${method} returned empty SSE stream`);
354
+ body = JSON.parse(dataLine);
355
+ } else {
356
+ body = await response.json();
357
+ }
358
+ if (body.error) {
359
+ throw new Error(
360
+ `T3 MCP ${method} error ${body.error.code}${body.error.message ? `: ${body.error.message}` : ""}`
361
+ );
362
+ }
363
+ return { result: body.result, newSessionId };
364
+ }
365
+ async connect(force = false) {
366
+ if (!force && this.state && Date.now() < this.state.renewAt) {
367
+ return this.state;
368
+ }
369
+ if (!this.connecting) {
370
+ const previousAuthId = this.state?.authSessionId;
371
+ this.connecting = (async () => {
372
+ const issued = await this.issue();
373
+ if (!issued.token) throw new Error("T3 MCP session returned no bearer token");
374
+ const init = await this.rpcWith(issued.token, null, "initialize", {
375
+ protocolVersion: "2025-06-18",
376
+ capabilities: {},
377
+ clientInfo: { name: "t3-code-qqbot", version: APP_VERSION }
378
+ });
379
+ if (!init.newSessionId) throw new Error("T3 MCP did not return an mcp-session-id header");
380
+ await this.rpcWith(issued.token, init.newSessionId, "notifications/initialized", void 0, true);
381
+ const next = {
382
+ token: issued.token,
383
+ sessionId: init.newSessionId,
384
+ authSessionId: issued.sessionId,
385
+ renewAt: Date.now() + 50 * 6e4
386
+ };
387
+ this.state = next;
388
+ if (previousAuthId && previousAuthId !== issued.sessionId && this.revoke) {
389
+ void this.revoke(previousAuthId).catch(() => {
390
+ });
391
+ }
392
+ return next;
393
+ })().finally(() => {
394
+ this.connecting = void 0;
395
+ });
396
+ }
397
+ return this.connecting;
398
+ }
399
+ async close() {
400
+ const authId = this.state?.authSessionId;
401
+ this.state = null;
402
+ if (authId && this.revoke) {
403
+ await this.revoke(authId).catch(() => {
404
+ });
405
+ }
406
+ }
407
+ async callWithSession(name, args) {
408
+ let session = await this.connect(false);
409
+ let result;
410
+ try {
411
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
412
+ } catch (error) {
413
+ if (error instanceof McpHttpError && (error.status === 401 || error.status === 404)) {
414
+ if (this.state === session) this.state = null;
415
+ session = await this.connect(true);
416
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
417
+ } else {
418
+ throw error;
419
+ }
420
+ }
421
+ if (result?.isError) {
422
+ const detail = result?.content?.[0]?.text ? `: ${String(result.content[0].text)}` : "";
423
+ throw new Error(`T3 MCP tool rejected (${name})${detail}`);
424
+ }
425
+ if (result?.structuredContent !== void 0) {
426
+ return { data: result.structuredContent, session };
427
+ }
428
+ const text = result?.content?.[0]?.text;
429
+ if (typeof text !== "string") {
430
+ throw new Error(`T3 MCP tool (${name}) returned empty content`);
431
+ }
432
+ return { data: JSON.parse(text), session };
433
+ }
434
+ async call(name, args) {
435
+ const { data } = await this.callWithSession(name, args);
436
+ return data;
437
+ }
438
+ async upload(filePath, name, mimeType) {
439
+ const bytes = await readFile2(filePath);
440
+ const attachment = {
441
+ name,
442
+ mimeType,
443
+ sizeBytes: bytes.length,
444
+ type: /^image\/(png|jpeg|webp|gif)$/.test(mimeType) ? "image" : "file"
445
+ };
446
+ const { data: staged, session } = await this.callWithSession("t3_attachment_prepare_upload", { upload: attachment });
447
+ try {
448
+ const endpoint = new URL(staged.uploadUrl ?? staged.relativeUrl, this.url);
449
+ if (endpoint.origin !== new URL(this.url).origin) {
450
+ throw new Error("Unexpected T3 attachment upload origin");
451
+ }
452
+ const response = await fetch(endpoint, {
453
+ method: "POST",
454
+ signal: AbortSignal.timeout(3e4),
455
+ redirect: "error",
456
+ headers: {
457
+ Authorization: `Bearer ${session.token}`,
458
+ "Content-Type": mimeType
459
+ },
460
+ body: bytes
461
+ });
462
+ if (!response.ok) {
463
+ await response.body?.cancel().catch(() => {
464
+ });
465
+ throw new Error(`T3 native attachment upload HTTP ${response.status}`);
466
+ }
467
+ await response.body?.cancel().catch(() => {
468
+ });
469
+ return { ...attachment, id: staged.attachmentId };
470
+ } catch (error) {
471
+ await this.call("t3_attachment_discard", { attachmentId: staged.attachmentId }).catch(() => {
472
+ });
473
+ throw error;
474
+ }
475
+ }
476
+ async read(threadId, view = "messages", itemId) {
477
+ return this.call("t3_thread_read", {
478
+ threadId,
479
+ view,
480
+ itemId,
481
+ limit: 40,
482
+ runLimit: 50,
483
+ maxCharsPerItem: 2e4
484
+ });
485
+ }
486
+ };
487
+
488
+ // src/slash-commands.ts
489
+ import { execFile } from "node:child_process";
490
+ import { existsSync } from "node:fs";
491
+ import { cp, mkdir as mkdir2, mkdtemp, readFile as readFile3, rm, unlink, writeFile as writeFile2 } from "node:fs/promises";
492
+ import { tmpdir } from "node:os";
493
+ import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
494
+ import { promisify } from "node:util";
495
+ var execFileAsync = promisify(execFile);
496
+ var SLASH_COMMAND_MAP = {
497
+ "/help": "help",
498
+ "/cmd": "help",
499
+ "/commands": "help",
500
+ "/menu": "help",
501
+ "/?": "help",
502
+ "/status": "status",
503
+ "/info": "status",
504
+ "/new": "new",
505
+ "/reset": "new",
506
+ "/clear": "new",
507
+ "/threads": "threads",
508
+ "/list": "threads",
509
+ "/use": "use",
510
+ "/switch": "use",
511
+ "/compact": "compact",
512
+ "/rewind": "rewind",
513
+ "/undo": "rewind",
514
+ "/\u64A4\u56DE": "rewind",
515
+ "/\u56DE\u6EAF": "rewind",
516
+ "/model": "model",
517
+ "/models": "model",
518
+ "/m": "model",
519
+ "/think": "think",
520
+ "/effort": "think",
521
+ "/t": "think",
522
+ "/provider": "provider",
523
+ "/providers": "provider",
524
+ "/provide": "provider",
525
+ "/p": "provider",
526
+ "/tasks": "tasks",
527
+ "/cancel": "cancel",
528
+ "/stop": "cancel",
529
+ "/update": "update",
530
+ "/upgrade": "update"
531
+ };
532
+ var EFFORT_ALIASES = {
533
+ l: "low",
534
+ lo: "low",
535
+ low: "low",
536
+ min: "low",
537
+ minimal: "low",
538
+ m: "medium",
539
+ med: "medium",
540
+ mid: "medium",
541
+ medium: "medium",
542
+ h: "high",
543
+ hi: "high",
544
+ high: "high",
545
+ xh: "xhigh",
546
+ xhigh: "xhigh",
547
+ "extra-high": "xhigh",
548
+ extra_high: "xhigh",
549
+ max: "max",
550
+ ultra: "ultrathink",
551
+ ultrathink: "ultrathink"
552
+ };
553
+ var MODEL_SHORTHANDS = {
554
+ "4n": ["gemini-4-neon"],
555
+ n4: ["gemini-4-neon"],
556
+ neon: ["gemini-4-neon"],
557
+ "4c": ["gemini-4-carbon", "gemini-4-neon"],
558
+ c4: ["gemini-4-carbon", "gemini-4-neon"],
559
+ carbon: ["gemini-4-carbon"],
560
+ "4a": ["gemini-4-argon"],
561
+ a4: ["gemini-4-argon"],
562
+ argon: ["gemini-4-argon"],
563
+ "4h": ["gemini-4-hydrogen"],
564
+ h4: ["gemini-4-hydrogen"],
565
+ hydrogen: ["gemini-4-hydrogen"],
566
+ "3.8f": ["gemini-3.8-flash"],
567
+ "38f": ["gemini-3.8-flash"],
568
+ "3f": ["gemini-3.8-flash"],
569
+ flash: ["gemini-3.8-flash"],
570
+ orch: ["gemini-pro-orchestrator-neon", "gemini-pro-orchestrator"],
571
+ orchestrator: ["gemini-pro-orchestrator-neon", "gemini-pro-orchestrator"],
572
+ "orch-n": ["gemini-pro-orchestrator-neon"],
573
+ "orch-c": ["gemini-pro-orchestrator"],
574
+ "orch-a": ["gemini-pro-orchestrator-argon"],
575
+ sonnet: ["claude-sonnet-5-5", "claude-sonnet-4-6"],
576
+ cs: ["claude-sonnet-5-5", "claude-sonnet-4-6"],
577
+ opus: ["claude-opus-5-5", "claude-opus-4-6-thinking"],
578
+ co: ["claude-opus-5-5", "claude-opus-4-6-thinking"],
579
+ sol: ["gpt-6.2-sol", "gpt-6.1-sol", "gpt-6-sol"],
580
+ astra: ["gpt-6.2-astra", "gpt-6-astra"],
581
+ terra: ["gpt-6.1-terra"],
582
+ gpt: ["gpt-6.2-sol", "gpt-oss-120b-medium"],
583
+ oss: ["gpt-oss-120b-medium"],
584
+ "120b": ["gpt-oss-120b-medium"]
585
+ };
586
+ var EFFORT_OPTION_KEYS = ["thought_level", "reasoningEffort", "effort"];
587
+ var MAX_REWIND_TURNS = 10;
588
+ function parseSlashCommand(rawText, hasAttachments = false) {
589
+ if (hasAttachments) return null;
590
+ const trimmed = rawText.trim();
591
+ if (!trimmed.startsWith("/")) return null;
592
+ const spaceIdx = trimmed.search(/\s/);
593
+ const head = (spaceIdx >= 0 ? trimmed.slice(0, spaceIdx) : trimmed).toLowerCase();
594
+ const args = spaceIdx >= 0 ? trimmed.slice(spaceIdx + 1).trim() : "";
595
+ const mapped = SLASH_COMMAND_MAP[head];
596
+ if (!mapped) return null;
597
+ return { name: mapped, args };
598
+ }
599
+ function parseThinkingEffort(raw) {
600
+ if (!raw) return null;
601
+ return EFFORT_ALIASES[raw.trim().toLowerCase()] ?? null;
602
+ }
603
+ function parseRewindTurnsArg(rawArg, maxTurns = MAX_REWIND_TURNS) {
604
+ const cleaned = rawArg?.trim() ?? "";
605
+ if (!cleaned) return { turns: 1, restoreFiles: false };
606
+ const tokens = cleaned.split(/\s+/).filter(Boolean);
607
+ let restoreFiles = false;
608
+ const positional = [];
609
+ for (const token of tokens) {
610
+ const low = token.toLowerCase();
611
+ if (low === "--files" || low === "-f" || low === "files" || low === "\u6587\u4EF6") {
612
+ restoreFiles = true;
613
+ } else {
614
+ positional.push(token);
615
+ }
616
+ }
617
+ if (positional.length === 0) return { turns: 1, restoreFiles };
618
+ if (positional.length > 1 || !/^\d+$/.test(positional[0])) {
619
+ return {
620
+ error: `\u65E0\u6548\u7684\u64A4\u56DE\u53C2\u6570 "${cleaned}"\u3002\u8BF7\u4F7F\u7528\u6B63\u6574\u6570\uFF081-${maxTurns}\uFF09\uFF0C\u4F8B\u5982 /rewind\u3001/\u64A4\u56DE 2 \u6216 /rewind 1 --files\u3002`
621
+ };
622
+ }
623
+ const turns = Number.parseInt(positional[0], 10);
624
+ if (!Number.isSafeInteger(turns) || turns < 1 || turns > maxTurns) {
625
+ return {
626
+ error: `\u5355\u6B21\u64A4\u56DE\u8F6E\u6570\u8303\u56F4\u4E3A 1-${maxTurns}\uFF0C\u6536\u5230 ${positional[0]}\u3002\u53D1\u9001 /rewind \u9ED8\u8BA4\u64A4\u56DE\u4E0A\u4E00\u8F6E\u3002`
627
+ };
628
+ }
629
+ return { turns, restoreFiles };
630
+ }
631
+ function formatSlashHelpText() {
632
+ return [
633
+ `T3 Code QQBot \u5FEB\u6377\u6307\u4EE4\u9762\u677F (v${APP_VERSION})`,
634
+ "",
635
+ "\u2022 /model [\u4EE3\u53F7|\u7F16\u53F7|provider/model] \u2014 \u67E5\u770B\u6216\u5207\u6362\u4E3B\u6A21\u578B\uFF08\u522B\u540D /m\uFF09",
636
+ " \u7B80\u5199\uFF1A4n \xB7 4c \xB7 4a \xB7 4h \xB7 3.8f \xB7 sonnet \xB7 opus \xB7 sol \xB7 astra \xB7 orch",
637
+ " \u652F\u6301\u9644\u5E26\u601D\u8003\u5F3A\u5EA6\uFF1A\u5982 /model 4h xhigh\u3001/model 4n-low\u3001/model 1",
638
+ "\u2022 /think [low|medium|high|xhigh|max] \u2014 \u5207\u6362\u601D\u8003/\u63A8\u7406\u5F3A\u5EA6\uFF08\u522B\u540D /t\uFF0C\u652F\u6301 l/m/h/xh\uFF09",
639
+ "\u2022 /provider [\u7F16\u53F7|\u5B9E\u4F8BID] \u2014 \u67E5\u770B\u6216\u5207\u6362 T3 Provider \u8D26\u53F7\u5B9E\u4F8B\uFF08\u522B\u540D /p\uFF09",
640
+ "\u2022 /new [\u6807\u9898] \u2014 \u5728\u5F53\u524D\u9879\u76EE\u5F00\u65B0 T3 \u4F1A\u8BDD\uFF08\u81EA\u52A8\u4FDD\u7559\u6A21\u578B\u4E0E\u5F3A\u5EA6\uFF0C\u522B\u540D /reset\uFF09",
641
+ "\u2022 /threads \u2014 \u5217\u51FA\u5F53\u524D\u9879\u76EE\u6700\u8FD1 10 \u6761 T3 \u4F1A\u8BDD\uFF08\u522B\u540D /list\uFF09",
642
+ "\u2022 /use <\u7F16\u53F7|threadId|main> \u2014 \u5207\u6362\u5230\u6307\u5B9A\u5386\u53F2\u4F1A\u8BDD\u6216\u5207\u56DE\u4E3B\u4F1A\u8BDD\uFF08\u522B\u540D /switch\uFF09",
643
+ "\u2022 /rewind [\u8F6E\u6570] [--files] \u2014 \u8C03\u7528 T3 \u539F\u751F\u68C0\u67E5\u70B9\u539F\u5730\u64A4\u56DE\u6700\u8FD1 1-10 \u8F6E\uFF08\u522B\u540D /undo\u3001/\u64A4\u56DE\uFF1B\u9ED8\u8BA4\u4EC5\u64A4\u56DE\u5BF9\u8BDD\uFF0C\u52A0 --files \u540C\u65F6\u8FD8\u539F\u6587\u4EF6\uFF09",
644
+ "\u2022 /compact [\u4FDD\u7559\u91CD\u70B9] \u2014 \u900F\u4F20\u7ED9\u5F53\u524D T3 \u4F1A\u8BDD\u6267\u884C\u539F\u751F\u4E0A\u4E0B\u6587\u538B\u7F29",
645
+ "\u2022 /status \u2014 \u67E5\u770B\u5F53\u524D\u4F1A\u8BDD ID\u3001Provider\u3001\u6A21\u578B\u6863\u4F4D\u3001\u8FD0\u884C\u72B6\u6001\u4E0E\u540E\u53F0\u4EFB\u52A1\uFF08\u522B\u540D /info\uFF09",
646
+ "\u2022 /tasks & /cancel [taskId|all] \u2014 \u67E5\u770B\u540E\u53F0\u4EFB\u52A1\uFF0C\u6216\u4E2D\u65AD\u5F53\u524D\u8F6E\u6B21/\u53D6\u6D88\u5B50\u4EFB\u52A1\uFF08\u522B\u540D /stop\uFF09",
647
+ "\u2022 /update \u2014 \u68C0\u67E5 GitHub \u6700\u65B0\u7248\u672C\u5E76\u5728\u6E90\u7801\u4ED3\u5E93\u6A21\u5F0F\u4E0B\u81EA\u52A8\u62C9\u53D6\u91CD\u5EFA\u91CD\u542F\uFF08\u522B\u540D /upgrade\uFF09"
648
+ ].join("\n");
649
+ }
650
+ function findEffortOption(model) {
651
+ if (!model?.options?.length) return void 0;
652
+ return model.options.find((opt) => EFFORT_OPTION_KEYS.includes(opt.id));
653
+ }
654
+ function normalizeEffortValueForOption(effort, option) {
655
+ const stringValues = option.values.filter((v) => typeof v === "string");
656
+ if (stringValues.includes(effort)) return effort;
657
+ const fallbacks = {
658
+ low: ["low", "medium"],
659
+ medium: ["medium", "low", "high"],
660
+ high: ["high", "medium"],
661
+ xhigh: ["xhigh", "high", "max"],
662
+ max: ["max", "xhigh", "high"],
663
+ ultrathink: ["ultrathink", "max", "xhigh", "high"]
664
+ };
665
+ for (const candidate of fallbacks[effort]) {
666
+ if (stringValues.includes(candidate)) return candidate;
667
+ }
668
+ return stringValues[0] ?? null;
669
+ }
670
+ function extractCurrentEffort(options) {
671
+ if (!options) return void 0;
672
+ if (Array.isArray(options)) {
673
+ const found = options.find((o) => EFFORT_OPTION_KEYS.includes(o.id));
674
+ return found ? String(found.value) : void 0;
675
+ }
676
+ for (const key of EFFORT_OPTION_KEYS) {
677
+ if (key in options) return String(options[key]);
678
+ }
679
+ return void 0;
680
+ }
681
+ function resolveModelFromInput(rawInput, providers, currentInstanceId) {
682
+ const cleaned = rawInput.trim();
683
+ if (!cleaned) return {};
684
+ const enabledProviders = providers.filter((p) => p.models.length > 0 && p.canRunChildTask !== false);
685
+ const activeProvider = enabledProviders.find((p) => p.providerInstanceId === currentInstanceId) ?? providers.find((p) => p.providerInstanceId === currentInstanceId) ?? enabledProviders[0] ?? providers[0];
686
+ if (/^\d+$/.test(cleaned) && activeProvider) {
687
+ const idx = Number.parseInt(cleaned, 10) - 1;
688
+ if (idx >= 0 && idx < activeProvider.models.length) {
689
+ return { match: { provider: activeProvider, model: activeProvider.models[idx] } };
690
+ }
691
+ }
692
+ const tokens = cleaned.split(/\s+/).filter(Boolean);
693
+ let inferredEffort;
694
+ let modelToken = tokens[0];
695
+ if (tokens.length >= 2) {
696
+ const maybeEffort = parseThinkingEffort(tokens[tokens.length - 1]);
697
+ if (maybeEffort) {
698
+ inferredEffort = maybeEffort;
699
+ modelToken = tokens.slice(0, -1).join(" ");
700
+ }
701
+ }
702
+ let scopedProviders = activeProvider ? [activeProvider, ...enabledProviders.filter((p) => p.providerInstanceId !== activeProvider.providerInstanceId)] : enabledProviders;
703
+ if (modelToken.includes("/")) {
704
+ const [provQuery, restModel] = modelToken.split("/", 2);
705
+ const provLower = provQuery.toLowerCase();
706
+ const matchedProvs = enabledProviders.filter(
707
+ (p) => p.providerInstanceId.toLowerCase() === provLower || p.driverKind.toLowerCase() === provLower || p.displayName && p.displayName.toLowerCase() === provLower
708
+ );
709
+ if (matchedProvs.length > 0 && restModel) {
710
+ scopedProviders = matchedProvs;
711
+ modelToken = restModel;
712
+ }
713
+ }
714
+ const lowerToken = modelToken.toLowerCase();
715
+ if (!inferredEffort) {
716
+ const lastDash = lowerToken.lastIndexOf("-");
717
+ if (lastDash > 0) {
718
+ const left = lowerToken.slice(0, lastDash);
719
+ const right = lowerToken.slice(lastDash + 1);
720
+ const eff = parseThinkingEffort(right);
721
+ if (eff && MODEL_SHORTHANDS[left]) {
722
+ inferredEffort = eff;
723
+ modelToken = left;
724
+ }
725
+ }
726
+ }
727
+ if (!inferredEffort) {
728
+ const compact = /^(4n|4c|4a|4h|3\.8f|38f|3f)(xh|xhigh|low|med|medium|high|max|l|m|h)$/.exec(lowerToken);
729
+ if (compact) {
730
+ inferredEffort = parseThinkingEffort(compact[2]) ?? void 0;
731
+ modelToken = compact[1];
732
+ }
733
+ }
734
+ const normalizedKey = modelToken.toLowerCase();
735
+ for (const prov of scopedProviders) {
736
+ const exact = prov.models.find((m) => m.id.toLowerCase() === normalizedKey);
737
+ if (exact) return { match: { provider: prov, model: exact, inferredEffort } };
738
+ }
739
+ const aliasTargets = MODEL_SHORTHANDS[normalizedKey];
740
+ if (aliasTargets) {
741
+ for (const targetId of aliasTargets) {
742
+ for (const prov of scopedProviders) {
743
+ const hit = prov.models.find((m) => m.id.toLowerCase() === targetId.toLowerCase());
744
+ if (hit) return { match: { provider: prov, model: hit, inferredEffort } };
745
+ }
746
+ }
747
+ }
748
+ const findFuzzy = (provs) => {
749
+ const hits = [];
750
+ for (const prov of provs) {
751
+ for (const m of prov.models) {
752
+ if (m.id.toLowerCase().includes(normalizedKey) || m.label && m.label.toLowerCase().includes(normalizedKey)) {
753
+ hits.push({ provider: prov, model: m });
754
+ }
755
+ }
756
+ }
757
+ return hits;
758
+ };
759
+ if (activeProvider) {
760
+ const localHits = findFuzzy([activeProvider]);
761
+ if (localHits.length === 1) {
762
+ return { match: { ...localHits[0], inferredEffort } };
763
+ }
764
+ if (localHits.length > 1) return { candidates: localHits };
765
+ }
766
+ const allHits = findFuzzy(scopedProviders);
767
+ if (allHits.length === 1) {
768
+ return { match: { ...allHits[0], inferredEffort } };
769
+ }
770
+ if (allHits.length > 1) return { candidates: allHits.slice(0, 10) };
771
+ return {};
772
+ }
773
+ function createSlashCommandHandler(deps) {
774
+ const recentThreadsCache = /* @__PURE__ */ new Map();
775
+ const findProject = async (workspace) => {
776
+ const { projects } = await deps.observer.call("t3_project_list", { limit: 100 });
777
+ const project = projects.find((p) => samePath(p.workspaceRoot, workspace));
778
+ if (!project) {
779
+ throw new Error(`\u5DE5\u4F5C\u533A "${workspace}" \u672A\u5728 T3 Code \u4E2D\u6CE8\u518C\u3002`);
780
+ }
781
+ return project;
782
+ };
783
+ const getCapabilities = (search) => deps.observer.call("orchestrator_capabilities", search ? { search } : {});
784
+ const getThreadConfig = (threadId) => deps.getThreadConfig ? deps.getThreadConfig(threadId) : deps.observer.call("t3_thread_configure", { threadId });
785
+ const setThreadModel = async (threadId, modelSelection) => {
786
+ if (deps.setThreadModel) {
787
+ await deps.setThreadModel(threadId, modelSelection);
788
+ return;
789
+ }
790
+ await deps.observer.call("t3_thread_configure", { threadId, modelSelection });
791
+ };
792
+ const createNewThread = async (input) => {
793
+ if (deps.createThread) {
794
+ let sel = input.modelSelection;
795
+ if (!sel?.model) {
796
+ const caps = await getCapabilities();
797
+ const firstProv = caps.providers.find((p) => p.models.length > 0 && p.canRunChildTask !== false) ?? caps.providers[0];
798
+ const firstModel = firstProv?.models[0]?.id;
799
+ if (!firstProv || !firstModel) throw new Error("T3 Code \u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 Provider \u6A21\u578B\u3002");
800
+ sel = { instanceId: firstProv.providerInstanceId, model: firstModel };
801
+ }
802
+ return deps.createThread({ projectId: input.projectId, title: input.title, modelSelection: sel });
803
+ }
804
+ return deps.observer.call("t3_thread_launch", {
805
+ projectId: input.projectId,
806
+ title: input.title,
807
+ ...input.modelSelection?.model ? { modelSelection: input.modelSelection } : {}
808
+ });
809
+ };
810
+ const stopThread = async (threadId, options = {}) => {
811
+ if (deps.stopThread) {
812
+ await deps.stopThread(threadId, options);
813
+ return;
814
+ }
815
+ await deps.observer.call("t3_thread_interrupt", {
816
+ threadId,
817
+ ...options.reason ? { reason: options.reason } : {}
818
+ });
819
+ };
820
+ return async function handleSlashCommand(cmd, binding, scope) {
821
+ if (cmd.name === "help") {
822
+ await deps.sendReply(formatSlashHelpText());
823
+ return "handled";
824
+ }
825
+ if (cmd.name === "compact") {
826
+ await deps.sendReply("\u6B63\u5728\u538B\u7F29\u5F53\u524D T3 \u4F1A\u8BDD\u4E0A\u4E0B\u6587\uFF0C\u8BF7\u7A0D\u5019\u2026");
827
+ return "passthrough";
828
+ }
829
+ if (cmd.name === "update") {
830
+ await handleSelfUpdate(deps);
831
+ return "handled";
832
+ }
833
+ const threadId = await deps.resolveActiveThread(binding, scope);
834
+ if (cmd.name === "status") {
835
+ const [cfgRes, snap] = await Promise.all([
836
+ getThreadConfig(threadId).catch(() => null),
837
+ deps.observer.read(threadId).catch(() => null)
838
+ ]);
839
+ const sel = cfgRes?.modelSelection;
840
+ const effort = extractCurrentEffort(sel?.options);
841
+ const pendingTasks = snap?.thread.pendingBackgroundTasks?.length ?? 0;
842
+ const isCustom = Boolean(binding.threadId && binding.threadId !== threadId);
843
+ const lines = [
844
+ "T3 Code QQBot \u5F53\u524D\u4F1A\u8BDD\u72B6\u6001",
845
+ `\u2022 \u4F1A\u8BDD ID\uFF1A${threadId}${isCustom ? "\uFF08\u5DF2\u5207\u6362\uFF0C\u53D1 /use main \u53EF\u56DE\u4E3B\u4F1A\u8BDD\uFF09" : ""}`,
846
+ `\u2022 \u5DE5\u4F5C\u533A\uFF1A${binding.workspace}`,
847
+ `\u2022 Provider\uFF1A${sel?.instanceId ?? sel?.provider ?? snap?.thread.providerInstanceId ?? "(\u9ED8\u8BA4)"}`,
848
+ `\u2022 \u5F53\u524D\u6A21\u578B\uFF1A${sel?.model ?? "(\u9ED8\u8BA4)"}${effort ? ` (\u601D\u8003\u5F3A\u5EA6: ${effort})` : ""}`,
849
+ `\u2022 \u8FD0\u884C\u72B6\u6001\uFF1A${snap?.thread.activeRunId ? `\u8FD0\u884C\u4E2D (${snap.thread.activeRunId})` : "\u7A7A\u95F2"}`,
850
+ `\u2022 \u540E\u53F0\u4EFB\u52A1\uFF1A${pendingTasks} \u4E2A`,
851
+ `\u2022 \u4FA7\u8FB9\u680F\u81EA\u52A8\u6536\u7EB3\uFF1A${deps.config.bridge.autoSettleThread ? "\u5F00\u542F" : "\u5173\u95ED"}`
852
+ ];
853
+ await deps.sendReply(lines.join("\n"));
854
+ return "handled";
855
+ }
856
+ if (cmd.name === "provider") {
857
+ const caps = await getCapabilities();
858
+ const enabled = caps.providers.filter((p) => p.models.length > 0 && p.canRunChildTask !== false);
859
+ const cfgRes = await getThreadConfig(threadId).catch(() => null);
860
+ const currentInstance = cfgRes?.modelSelection?.instanceId ?? cfgRes?.modelSelection?.provider;
861
+ if (!cmd.args) {
862
+ const lines = [
863
+ "\u53EF\u7528 T3 Provider \u5B9E\u4F8B",
864
+ `\u5F53\u524D\u5B9E\u4F8B\uFF1A${currentInstance ?? "(\u9ED8\u8BA4)"}`,
865
+ "",
866
+ ...enabled.map((p, idx) => {
867
+ const mark = p.providerInstanceId === currentInstance ? "\u{1F449} " : " ";
868
+ return `${mark}[${idx + 1}] ${p.displayName ?? p.providerInstanceId} (${p.providerInstanceId} \xB7 ${p.models.length} \u4E2A\u6A21\u578B)`;
869
+ }),
870
+ "",
871
+ "\u53D1\u9001 /provider <\u7F16\u53F7\u6216\u5B9E\u4F8BID> \u5207\u6362\uFF08\u4F8B\u5982 /provider 1\uFF09\u3002"
872
+ ];
873
+ await deps.sendReply(lines.join("\n"));
874
+ return "handled";
875
+ }
876
+ const q = cmd.args.trim();
877
+ let picked;
878
+ if (/^\d+$/.test(q)) {
879
+ const idx = Number.parseInt(q, 10) - 1;
880
+ picked = enabled[idx];
881
+ } else {
882
+ const low = q.toLowerCase();
883
+ picked = enabled.find((p) => p.providerInstanceId.toLowerCase() === low) ?? enabled.find((p) => (p.displayName ?? "").toLowerCase() === low) ?? enabled.find(
884
+ (p) => p.providerInstanceId.toLowerCase().includes(low) || (p.displayName ?? "").toLowerCase().includes(low)
885
+ );
886
+ }
887
+ if (!picked) {
888
+ await deps.sendReply(`\u672A\u627E\u5230\u5339\u914D\u7684 Provider "${q}"\uFF0C\u53D1 /provider \u67E5\u770B\u53EF\u7528\u7F16\u53F7\u3002`);
889
+ return "handled";
890
+ }
891
+ const nextModel = picked.models[0]?.id;
892
+ if (!nextModel) {
893
+ await deps.sendReply(`Provider "${picked.providerInstanceId}" \u5F53\u524D\u6CA1\u6709\u53EF\u7528\u6A21\u578B\u3002`);
894
+ return "handled";
895
+ }
896
+ await setThreadModel(threadId, { instanceId: picked.providerInstanceId, model: nextModel });
897
+ await deps.sendReply(
898
+ `\u5DF2\u5207\u6362 Provider \u4E3A\uFF1A${picked.displayName ?? picked.providerInstanceId} (${picked.providerInstanceId})
899
+ \u9ED8\u8BA4\u6A21\u578B\uFF1A${nextModel}`
900
+ );
901
+ return "handled";
902
+ }
903
+ if (cmd.name === "model") {
904
+ const [caps, cfgRes] = await Promise.all([getCapabilities(), getThreadConfig(threadId).catch(() => null)]);
905
+ const currentInstance = cfgRes?.modelSelection?.instanceId ?? cfgRes?.modelSelection?.provider;
906
+ const currentModel = cfgRes?.modelSelection?.model;
907
+ const currentEffort = extractCurrentEffort(cfgRes?.modelSelection?.options);
908
+ const enabled = caps.providers.filter((p) => p.models.length > 0 && p.canRunChildTask !== false);
909
+ const activeProvider = enabled.find((p) => p.providerInstanceId === currentInstance) ?? enabled[0];
910
+ if (!cmd.args) {
911
+ const lines = [
912
+ "\u53EF\u7528\u6A21\u578B\u5217\u8868",
913
+ `\u5F53\u524D Provider\uFF1A${activeProvider?.displayName ?? currentInstance ?? "(\u9ED8\u8BA4)"}`,
914
+ `\u5F53\u524D\u6A21\u578B\uFF1A${currentModel ?? "(\u9ED8\u8BA4)"}${currentEffort ? ` \xB7 \u601D\u8003\u5F3A\u5EA6 ${currentEffort}` : ""}`,
915
+ "",
916
+ ...(activeProvider?.models ?? []).map((m, idx) => {
917
+ const mark = m.id === currentModel ? "\u{1F449} " : " ";
918
+ return `${mark}[${idx + 1}] ${m.label ?? m.id} (${m.id})`;
919
+ }),
920
+ "",
921
+ "\u5FEB\u6377\u5207\u6362\uFF1A/model 1 \xB7 /model 4n \xB7 /model 4h xhigh \xB7 /model 3.8f \xB7 /model sol \xB7 /model provider/model \xB7 /model all"
922
+ ];
923
+ await deps.sendReply(lines.join("\n"));
924
+ return "handled";
925
+ }
926
+ if (cmd.args.trim().toLowerCase() === "all" || cmd.args.trim() === "\u5168\u90E8") {
927
+ const lines = [
928
+ "\u5168\u90E8\u53EF\u7528\u4F9B\u5E94\u5546\u4E0E\u6A21\u578B\u4E00\u89C8",
929
+ `\u5F53\u524D\uFF1A${activeProvider?.displayName ?? currentInstance ?? "(\u9ED8\u8BA4)"} / ${currentModel ?? "(\u9ED8\u8BA4)"}${currentEffort ? ` \xB7 ${currentEffort}` : ""}`,
930
+ "",
931
+ ...enabled.flatMap((p) => [
932
+ `\u25B8 ${p.displayName ?? p.providerInstanceId} (${p.providerInstanceId})`,
933
+ ...p.models.map((m) => {
934
+ const isCur = p.providerInstanceId === currentInstance && m.id === currentModel;
935
+ return `${isCur ? " \u{1F449} " : " "}${m.id}`;
936
+ })
937
+ ]),
938
+ "",
939
+ "\u8DE8\u4F9B\u5E94\u5546\u5207\u6362\u793A\u4F8B\uFF1A/model codex/sol \xB7 /model antigravity_cloudstay/4n"
940
+ ];
941
+ await deps.sendReply(lines.join("\n"));
942
+ return "handled";
943
+ }
944
+ let resolved = resolveModelFromInput(cmd.args, caps.providers, currentInstance);
945
+ if (!resolved.match && !resolved.candidates?.length) {
946
+ const searchTerm = cmd.args.trim().split(/\s+/)[0].split("/").pop() ?? cmd.args.trim();
947
+ const searched = await getCapabilities(searchTerm).catch(() => null);
948
+ if (searched?.providers?.length) {
949
+ resolved = resolveModelFromInput(cmd.args, searched.providers, currentInstance);
950
+ }
951
+ }
952
+ if (resolved.candidates?.length) {
953
+ const lines = [
954
+ `\u627E\u5230\u591A\u4E2A\u5339\u914D\u6A21\u578B\uFF0C\u8BF7\u8F93\u5165\u66F4\u7CBE\u786E\u7684\u7F16\u53F7\u6216\u540D\u79F0\uFF1A`,
955
+ ...resolved.candidates.map((c) => `\u2022 ${c.provider.providerInstanceId}/${c.model.id} (${c.model.label ?? c.model.id})`)
956
+ ];
957
+ await deps.sendReply(lines.join("\n"));
958
+ return "handled";
959
+ }
960
+ if (!resolved.match) {
961
+ await deps.sendReply(`\u672A\u5339\u914D\u5230\u6A21\u578B "${cmd.args}"\u3002\u53D1\u9001 /model \u67E5\u770B\u5F53\u524D\u53EF\u7528\u6A21\u578B\u5217\u8868\uFF0C\u6216\u53D1 /model all \u67E5\u770B\u5168\u90E8\u3002`);
962
+ return "handled";
963
+ }
964
+ const { provider, model, inferredEffort } = resolved.match;
965
+ const effortOpt = findEffortOption(model);
966
+ const desiredEffort = inferredEffort ?? (parseThinkingEffort(currentEffort) ?? void 0);
967
+ let nextOptions;
968
+ let appliedEffort;
969
+ if (effortOpt && desiredEffort) {
970
+ const norm = normalizeEffortValueForOption(desiredEffort, effortOpt);
971
+ if (norm) {
972
+ nextOptions = [{ id: effortOpt.id, value: norm }];
973
+ appliedEffort = norm;
974
+ }
975
+ }
976
+ await setThreadModel(threadId, {
977
+ instanceId: provider.providerInstanceId,
978
+ model: model.id,
979
+ ...nextOptions ? { options: nextOptions } : {}
980
+ });
981
+ await deps.sendReply(
982
+ `\u5DF2\u5207\u6362\u6A21\u578B\uFF1A${model.label ?? model.id} (${model.id})
983
+ Provider\uFF1A${provider.displayName ?? provider.providerInstanceId}${appliedEffort ? `
984
+ \u601D\u8003\u5F3A\u5EA6\uFF1A${appliedEffort}` : ""}`
985
+ );
986
+ return "handled";
987
+ }
988
+ if (cmd.name === "think") {
989
+ const [caps, cfgRes] = await Promise.all([getCapabilities(), getThreadConfig(threadId).catch(() => null)]);
990
+ const currentInstance = cfgRes?.modelSelection?.instanceId ?? cfgRes?.modelSelection?.provider;
991
+ const currentModelId = cfgRes?.modelSelection?.model;
992
+ const currentEffort = extractCurrentEffort(cfgRes?.modelSelection?.options);
993
+ const prov = caps.providers.find((p) => p.providerInstanceId === currentInstance);
994
+ const modelSpec = prov?.models.find((m) => m.id === currentModelId);
995
+ const effortOpt = findEffortOption(modelSpec);
996
+ if (!cmd.args) {
997
+ const allowed = effortOpt ? effortOpt.values.join(" / ") : "low / medium / high / xhigh";
998
+ await deps.sendReply(
999
+ `\u5F53\u524D\u601D\u8003\u5F3A\u5EA6\uFF1A${currentEffort ?? "\u9ED8\u8BA4"}
1000
+ \u5F53\u524D\u6A21\u578B\u652F\u6301\u6863\u4F4D\uFF1A${allowed}
1001
+ \u793A\u4F8B\uFF1A/think low\uFF08\u6216 /t l\uFF09\xB7 /think high \xB7 /think xh`
1002
+ );
1003
+ return "handled";
1004
+ }
1005
+ const parsed = parseThinkingEffort(cmd.args);
1006
+ if (!parsed) {
1007
+ await deps.sendReply(`\u65E0\u6CD5\u8BC6\u522B\u601D\u8003\u5F3A\u5EA6 "${cmd.args}"\u3002\u652F\u6301\uFF1Alow(l) / medium(m) / high(h) / xhigh(xh) / max\u3002`);
1008
+ return "handled";
1009
+ }
1010
+ if (!currentModelId) {
1011
+ await deps.sendReply("\u5F53\u524D\u4F1A\u8BDD\u5C1A\u672A\u7ED1\u5B9A\u5177\u4F53\u6A21\u578B\uFF0C\u8BF7\u5148\u53D1 /model \u9009\u5B9A\u4E00\u4E2A\u6A21\u578B\u3002");
1012
+ return "handled";
1013
+ }
1014
+ const optionId = effortOpt?.id ?? "thought_level";
1015
+ const applied = effortOpt ? normalizeEffortValueForOption(parsed, effortOpt) ?? parsed : parsed;
1016
+ await setThreadModel(threadId, {
1017
+ ...currentInstance ? { instanceId: currentInstance } : {},
1018
+ model: currentModelId,
1019
+ options: [{ id: optionId, value: applied }]
1020
+ });
1021
+ await deps.sendReply(`\u5DF2\u5207\u6362\u601D\u8003\u5F3A\u5EA6\uFF1A${applied}\uFF08\u6A21\u578B\uFF1A${currentModelId}\uFF09`);
1022
+ return "handled";
1023
+ }
1024
+ if (cmd.name === "new") {
1025
+ const [project, cfgRes] = await Promise.all([
1026
+ findProject(binding.workspace),
1027
+ getThreadConfig(threadId).catch(() => null)
1028
+ ]);
1029
+ const title = cmd.args || `QQ ${scope.startsWith("group:") ? "\u7FA4\u804A" : "\u79C1\u804A"} ${(/* @__PURE__ */ new Date()).toISOString().slice(5, 16).replace("T", " ")}`;
1030
+ const inheritedSel = cfgRes?.modelSelection?.model ? {
1031
+ ...cfgRes.modelSelection.instanceId ? { instanceId: cfgRes.modelSelection.instanceId } : {},
1032
+ ...cfgRes.modelSelection.provider && !cfgRes.modelSelection.instanceId ? { instanceId: cfgRes.modelSelection.provider } : {},
1033
+ model: cfgRes.modelSelection.model,
1034
+ ...cfgRes.modelSelection.options ? { options: cfgRes.modelSelection.options } : {}
1035
+ } : void 0;
1036
+ const created = await createNewThread({
1037
+ projectId: project.id,
1038
+ title,
1039
+ modelSelection: inheritedSel
1040
+ });
1041
+ if (!created?.threadId) throw new Error("T3 Code \u672A\u8FD4\u56DE\u65B0\u4F1A\u8BDD threadId");
1042
+ await deps.setActiveThreadOverride(binding, created.threadId);
1043
+ await deps.sendReply(
1044
+ `\u5DF2\u5F00\u542F\u5168\u65B0 T3 \u4F1A\u8BDD\u5E76\u81EA\u52A8\u5207\u6362\uFF1A
1045
+ \u2022 \u65B0\u4F1A\u8BDD ID\uFF1A${created.threadId}
1046
+ \u2022 \u6807\u9898\uFF1A${title}
1047
+ \uFF08\u65E7\u4F1A\u8BDD\u5B8C\u6574\u4FDD\u7559\u5728 T3 \u4E2D\uFF0C\u53D1 /threads \u6216 /use main \u53EF\u968F\u65F6\u5207\u56DE\uFF09`
1048
+ );
1049
+ return "handled";
1050
+ }
1051
+ if (cmd.name === "threads") {
1052
+ const project = await findProject(binding.workspace);
1053
+ const list = await deps.observer.call("t3_thread_list", {
1054
+ projectId: project.id,
1055
+ limit: 10
1056
+ });
1057
+ const rows = (list.threads ?? list.items ?? []).slice(0, 10);
1058
+ recentThreadsCache.set(binding.scopeHash, rows);
1059
+ if (rows.length === 0) {
1060
+ await deps.sendReply("\u5F53\u524D\u9879\u76EE\u4E0B\u6682\u65E0 T3 \u4F1A\u8BDD\u3002\u53D1\u9001 /new \u521B\u5EFA\u65B0\u4F1A\u8BDD\u3002");
1061
+ return "handled";
1062
+ }
1063
+ const lines = [
1064
+ `\u5F53\u524D\u9879\u76EE\u6700\u8FD1 ${rows.length} \u6761 T3 \u4F1A\u8BDD\uFF1A`,
1065
+ "",
1066
+ ...rows.map((row, idx) => {
1067
+ const mark = row.threadId === threadId ? "\u{1F449} " : " ";
1068
+ return `${mark}[${idx + 1}] ${row.title || "(\u65E0\u6807\u9898)"} (${row.status ?? "idle"})
1069
+ ${row.threadId}`;
1070
+ }),
1071
+ "",
1072
+ "\u53D1\u9001 /use <\u7F16\u53F7\u6216threadId> \u5207\u6362\uFF0C\u6216\u53D1 /use main \u5207\u56DE\u914D\u7F6E\u9ED8\u8BA4\u4E3B\u4F1A\u8BDD\u3002"
1073
+ ];
1074
+ await deps.sendReply(lines.join("\n"));
1075
+ return "handled";
1076
+ }
1077
+ if (cmd.name === "use") {
1078
+ const targetArg = cmd.args.trim();
1079
+ if (!targetArg) {
1080
+ await deps.sendReply("\u7528\u6CD5\uFF1A/use <\u7F16\u53F7|threadId|main>\u3002\u5148\u53D1 /threads \u53EF\u67E5\u770B\u7F16\u53F7\u5217\u8868\u3002");
1081
+ return "handled";
1082
+ }
1083
+ if (targetArg.toLowerCase() === "main" || targetArg === "\u4E3B\u4F1A\u8BDD") {
1084
+ if (!binding.threadId) {
1085
+ await deps.sendReply("config.json \u4E2D\u672A\u914D\u7F6E\u56FA\u5B9A\u4E3B\u4F1A\u8BDD threadId\uFF1B\u8BF7\u7528 /threads \u67E5\u770B\u540E\u4EE5 /use <\u7F16\u53F7> \u5207\u6362\u3002");
1086
+ return "handled";
1087
+ }
1088
+ await deps.setActiveThreadOverride(binding, null);
1089
+ await deps.sendReply(`\u5DF2\u5207\u56DE\u914D\u7F6E\u4E3B\u4F1A\u8BDD\uFF1A${binding.threadId}`);
1090
+ return "handled";
1091
+ }
1092
+ let nextThreadId = targetArg;
1093
+ if (/^\d+$/.test(targetArg)) {
1094
+ const cached = recentThreadsCache.get(binding.scopeHash);
1095
+ const idx = Number.parseInt(targetArg, 10) - 1;
1096
+ if (!cached || !cached[idx]) {
1097
+ await deps.sendReply("\u672A\u627E\u5230\u8BE5\u7F16\u53F7\uFF0C\u8BF7\u5148\u53D1\u9001 /threads \u5237\u65B0\u5217\u8868\u540E\u518D\u6267\u884C /use <\u7F16\u53F7>\u3002");
1098
+ return "handled";
1099
+ }
1100
+ nextThreadId = cached[idx].threadId;
1101
+ }
1102
+ const snap = await deps.observer.read(nextThreadId);
1103
+ await deps.setActiveThreadOverride(binding, nextThreadId);
1104
+ await deps.sendReply(
1105
+ `\u5DF2\u5207\u6362\u81F3 T3 \u4F1A\u8BDD\uFF1A${nextThreadId}
1106
+ \u5386\u53F2\u6761\u76EE\u6570\uFF1A${snap.thread.itemCount ?? snap.items.length}`
1107
+ );
1108
+ return "handled";
1109
+ }
1110
+ if (cmd.name === "rewind") {
1111
+ const parsed = parseRewindTurnsArg(cmd.args);
1112
+ if (parsed.error) {
1113
+ await deps.sendReply(parsed.error);
1114
+ return "handled";
1115
+ }
1116
+ const turns = parsed.turns ?? 1;
1117
+ const restoreFiles = parsed.restoreFiles ?? false;
1118
+ const res = await deps.rollbackTurns(threadId, turns, restoreFiles);
1119
+ const modeLabel = res.restoreFiles ? "\u5BF9\u8BDD + \u5DE5\u4F5C\u533A\u6587\u4EF6" : "\u4EC5\u5BF9\u8BDD\u4E0A\u4E0B\u6587\uFF08\u4E0D\u6539\u52A8\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF09";
1120
+ const targetDesc = res.targetOrdinal === 0 ? "\u4F1A\u8BDD\u8D77\u70B9" : `\u7B2C ${res.targetOrdinal} \u8F6E\u7ED3\u675F\u4F4D\u7F6E`;
1121
+ await deps.sendReply(
1122
+ `\u5DF2\u5728\u5F53\u524D T3 \u4F1A\u8BDD\u539F\u5730\u64A4\u56DE\u6700\u8FD1 ${res.rolledBackTurns} \u8F6E\uFF1A
1123
+ \u2022 \u56DE\u6EAF\u4F4D\u7F6E\uFF1A${targetDesc}
1124
+ \u2022 \u64A4\u56DE\u6A21\u5F0F\uFF1A${modeLabel}
1125
+ \u2022 \u5269\u4F59\u6709\u6548\u8F6E\u6B21\uFF1A${res.remainingTurns} \u8F6E`
1126
+ );
1127
+ return "handled";
1128
+ }
1129
+ if (cmd.name === "tasks") {
1130
+ const snap = await deps.observer.read(threadId, "activity");
1131
+ const pendingTasks = snap.thread.pendingBackgroundTasks ?? [];
1132
+ const activeSubagents = snap.items.filter(
1133
+ (item) => item.type === "subagent" && ["pending", "running", "waiting"].includes(item.status)
1134
+ );
1135
+ if (pendingTasks.length === 0 && activeSubagents.length === 0) {
1136
+ await deps.sendReply("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6B63\u5728\u8FD0\u884C\u7684\u540E\u53F0\u4EFB\u52A1\u3002");
1137
+ return "handled";
1138
+ }
1139
+ const lines = ["\u5F53\u524D\u8FD0\u884C\u4E2D\u7684\u540E\u53F0/\u59D4\u6D3E\u4EFB\u52A1\uFF1A", ""];
1140
+ for (const t of pendingTasks) {
1141
+ lines.push(`\u2022 ${t.taskId} (${t.kind})`);
1142
+ }
1143
+ for (const s of activeSubagents) {
1144
+ lines.push(`\u2022 ${s.itemId} \u2014 ${s.title ?? "\u5B50\u4EFB\u52A1"} [${s.status}]`);
1145
+ }
1146
+ lines.push("", "\u53D1 /cancel <taskId> \u6216 /cancel all \u53EF\u53D6\u6D88\uFF0C\u53D1 /stop \u53EF\u4E2D\u65AD\u4E3B\u4F1A\u8BDD\u5F53\u524D\u8F6E\u6B21\u3002");
1147
+ await deps.sendReply(lines.join("\n"));
1148
+ return "handled";
1149
+ }
1150
+ if (cmd.name === "cancel") {
1151
+ const arg = cmd.args.trim();
1152
+ if (!arg) {
1153
+ await stopThread(threadId, {
1154
+ reason: "Stopped by user via QQ /stop command",
1155
+ stopDelegatedTasks: false
1156
+ });
1157
+ await deps.sendReply("\u5DF2\u53D1\u9001\u4E2D\u65AD\u6307\u4EE4\uFF0C\u505C\u6B62\u5F53\u524D T3 \u4F1A\u8BDD\u6B63\u5728\u6267\u884C\u7684\u8F6E\u6B21\u3002");
1158
+ return "handled";
1159
+ }
1160
+ if (arg.toLowerCase() === "all") {
1161
+ await stopThread(threadId, {
1162
+ reason: "Stopped via QQ /cancel all",
1163
+ stopDelegatedTasks: true
1164
+ });
1165
+ await deps.sendReply("\u5DF2\u4E2D\u65AD\u4E3B\u4F1A\u8BDD\u5E76\u505C\u6B62\u5168\u90E8\u5173\u8054\u540E\u53F0\u59D4\u6D3E\u4EFB\u52A1\u3002");
1166
+ return "handled";
1167
+ }
1168
+ await deps.observer.call("task_cancel", {
1169
+ taskId: arg,
1170
+ reason: "Cancelled by user via QQ /cancel command"
1171
+ });
1172
+ await deps.sendReply(`\u5DF2\u53D6\u6D88\u540E\u53F0\u4EFB\u52A1\uFF1A${arg}`);
1173
+ return "handled";
1174
+ }
1175
+ return "passthrough";
1176
+ };
1177
+ }
1178
+ function compareSemver(a, b) {
1179
+ const parse = (v) => v.trim().replace(/^v/i, "").split("-")[0].split(".").map((part) => Number.parseInt(part, 10) || 0);
1180
+ const pa = parse(a);
1181
+ const pb = parse(b);
1182
+ for (let i = 0; i < Math.max(pa.length, pb.length, 3); i++) {
1183
+ const da = pa[i] ?? 0;
1184
+ const db = pb[i] ?? 0;
1185
+ if (da !== db) return da > db ? 1 : -1;
1186
+ }
1187
+ return 0;
1188
+ }
1189
+ function detectInstallMode(pkgRoot) {
1190
+ if (existsSync(join3(pkgRoot, ".git"))) return "git";
1191
+ const normalized = pkgRoot.replace(/\\/g, "/").toLowerCase();
1192
+ if (normalized.includes("/node_modules/t3-code-qqbot")) return "npm-global";
1193
+ return "standalone";
1194
+ }
1195
+ function buildNodeToolEnv() {
1196
+ const env = { ...process.env };
1197
+ const nodeDir = dirname2(process.execPath);
1198
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === "path") ?? "PATH";
1199
+ const existing = env[pathKey] ?? "";
1200
+ const sep2 = process.platform === "win32" ? ";" : ":";
1201
+ env[pathKey] = existing ? `${nodeDir}${sep2}${existing}` : nodeDir;
1202
+ return env;
1203
+ }
1204
+ async function runNpm(args, cwd, timeout = 12e4) {
1205
+ const env = buildNodeToolEnv();
1206
+ if (process.platform === "win32") {
1207
+ const npmCliJs = join3(dirname2(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
1208
+ if (existsSync(npmCliJs)) {
1209
+ return execFileAsync(process.execPath, [npmCliJs, ...args], { cwd, env, windowsHide: true, timeout });
1210
+ }
1211
+ return execFileAsync("npm.cmd", args, { cwd, env, shell: true, windowsHide: true, timeout });
1212
+ }
1213
+ return execFileAsync("npm", args, { cwd, env, windowsHide: true, timeout });
1214
+ }
1215
+ async function handleSelfUpdate(deps, options = {}) {
1216
+ const pkgRoot = options.pkgRoot ?? resolve3(import.meta.dirname, "..");
1217
+ const currentVersion = options.currentVersion ?? APP_VERSION;
1218
+ const mode = detectInstallMode(pkgRoot);
1219
+ if (mode === "git") {
1220
+ await deps.sendReply("\u6B63\u5728\u4ECE GitHub \u62C9\u53D6\u6700\u65B0\u6E90\u7801\u5E76\u68C0\u67E5\u66F4\u65B0\u2026");
1221
+ const env = buildNodeToolEnv();
1222
+ const before = (await execFileAsync("git", ["rev-parse", "--short", "HEAD"], { cwd: pkgRoot, env, windowsHide: true })).stdout.trim();
1223
+ await execFileAsync("git", ["pull", "--ff-only"], { cwd: pkgRoot, env, windowsHide: true, timeout: 6e4 });
1224
+ const after = (await execFileAsync("git", ["rev-parse", "--short", "HEAD"], { cwd: pkgRoot, env, windowsHide: true })).stdout.trim();
1225
+ if (before === after) {
1226
+ await deps.sendReply(`\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u6E90\u7801\u7248\u672C\uFF08v${currentVersion} \xB7 ${after}\uFF09\uFF0C\u65E0\u9700\u66F4\u65B0\u3002`);
1227
+ return;
1228
+ }
1229
+ await runNpm(["install", "--no-audit", "--no-fund"], pkgRoot, 12e4);
1230
+ await runNpm(["run", "build"], pkgRoot, 12e4);
1231
+ await deps.sendReply(`\u6E90\u7801\u66F4\u65B0\u5B8C\u6210\uFF08${before} -> ${after}\uFF09\uFF0C\u6B63\u5728\u70ED\u91CD\u542F\u670D\u52A1\u4EE5\u52A0\u8F7D\u65B0\u7248\u2026`);
1232
+ if (deps.triggerGracefulRestart) {
1233
+ setTimeout(() => deps.triggerGracefulRestart(), 800);
1234
+ }
1235
+ return;
1236
+ }
1237
+ const registryUrl = options.registryUrl ?? "https://registry.npmjs.org/t3-code-qqbot/latest";
1238
+ const res = await fetch(registryUrl, {
1239
+ headers: { Accept: "application/json", "User-Agent": `t3-code-qqbot/${currentVersion}` },
1240
+ signal: AbortSignal.timeout(15e3)
1241
+ });
1242
+ if (!res.ok) {
1243
+ await deps.sendReply(`\u5F53\u524D\u7248\u672C\uFF1Av${currentVersion}\u3002\u68C0\u67E5 npm \u6700\u65B0\u7248\u672C\u5931\u8D25 (HTTP ${res.status})\u3002`);
1244
+ return;
1245
+ }
1246
+ const meta = await res.json();
1247
+ const latestVersion = meta.version?.trim();
1248
+ if (!latestVersion) {
1249
+ await deps.sendReply(`\u5F53\u524D\u7248\u672C\uFF1Av${currentVersion}\u3002npm \u8FD4\u56DE\u7684\u7248\u672C\u4FE1\u606F\u65E0\u6548\u3002`);
1250
+ return;
1251
+ }
1252
+ if (compareSemver(latestVersion, currentVersion) <= 0) {
1253
+ await deps.sendReply(`\u5F53\u524D\u5DF2\u662F npm \u6700\u65B0\u7248\u672C\uFF08v${currentVersion}\uFF09\uFF0C\u65E0\u9700\u66F4\u65B0\u3002`);
1254
+ return;
1255
+ }
1256
+ if (mode === "npm-global") {
1257
+ await deps.sendReply(`\u53D1\u73B0 npm \u65B0\u7248\u672C v${latestVersion}\uFF08\u5F53\u524D v${currentVersion}\uFF09\uFF0C\u6B63\u5728\u901A\u8FC7 npm \u81EA\u52A8\u66F4\u65B0\u2026`);
1258
+ const installArgs = ["install", "-g", `t3-code-qqbot@${latestVersion}`, "--no-audit", "--no-fund"];
1259
+ if (options.npmGlobalPrefix) {
1260
+ installArgs.push("--prefix", options.npmGlobalPrefix);
1261
+ }
1262
+ await runNpm(installArgs, tmpdir(), 18e4);
1263
+ await deps.sendReply(`\u5DF2\u901A\u8FC7 npm \u81EA\u52A8\u66F4\u65B0\u81F3 v${latestVersion}\uFF08\u539F v${currentVersion}\uFF09\uFF0C\u6B63\u5728\u70ED\u91CD\u542F\u670D\u52A1\u4EE5\u52A0\u8F7D\u65B0\u7248\u2026`);
1264
+ if (deps.triggerGracefulRestart) {
1265
+ setTimeout(() => deps.triggerGracefulRestart(), 800);
1266
+ }
1267
+ return;
1268
+ }
1269
+ const tarballUrl = meta.dist?.tarball;
1270
+ if (!tarballUrl || !tarballUrl.startsWith("https://")) {
1271
+ await deps.sendReply(
1272
+ `\u53D1\u73B0 npm \u65B0\u7248\u672C v${latestVersion}\uFF08\u5F53\u524D v${currentVersion}\uFF09\uFF0C\u4F46\u672A\u83B7\u53D6\u5230\u6709\u6548\u7684\u4E0B\u8F7D\u5305\u5730\u5740\uFF0C\u8BF7\u624B\u52A8\u6267\u884C npm i -g t3-code-qqbot@latest\u3002`
1273
+ );
1274
+ return;
1275
+ }
1276
+ await deps.sendReply(`\u53D1\u73B0 npm \u65B0\u7248\u672C v${latestVersion}\uFF08\u5F53\u524D v${currentVersion}\uFF09\uFF0C\u6B63\u5728\u4ECE npm \u62C9\u53D6\u66F4\u65B0\u5305\u2026`);
1277
+ const stageDir = await mkdtemp(join3(tmpdir(), "t3-qqbot-update-"));
1278
+ try {
1279
+ const tgzPath = join3(stageDir, `t3-code-qqbot-${latestVersion}.tgz`);
1280
+ const extractDir = join3(stageDir, "extracted");
1281
+ await mkdir2(extractDir, { recursive: true });
1282
+ const dl = await fetch(tarballUrl, { signal: AbortSignal.timeout(6e4) });
1283
+ if (!dl.ok) throw new Error(`\u4E0B\u8F7D npm \u66F4\u65B0\u5305\u5931\u8D25 (HTTP ${dl.status})`);
1284
+ const bytes = Buffer.from(await dl.arrayBuffer());
1285
+ await writeFile2(tgzPath, bytes);
1286
+ await execFileAsync("tar", ["-xzf", tgzPath, "-C", extractDir], { windowsHide: true, timeout: 6e4 });
1287
+ const unpackedPkgDir = join3(extractDir, "package");
1288
+ if (!existsSync(join3(unpackedPkgDir, "dist", "bridge.mjs")) || !existsSync(join3(unpackedPkgDir, "package.json"))) {
1289
+ throw new Error("\u4E0B\u8F7D\u7684 npm \u5305\u7ED3\u6784\u4E0D\u5B8C\u6574\uFF08\u7F3A\u5C11 dist/bridge.mjs \u6216 package.json\uFF09");
1290
+ }
1291
+ const oldPkgRaw = await readFile3(join3(pkgRoot, "package.json"), "utf8").catch(() => "{}");
1292
+ const newPkgRaw = await readFile3(join3(unpackedPkgDir, "package.json"), "utf8");
1293
+ const oldDeps = JSON.stringify(JSON.parse(oldPkgRaw).dependencies ?? {});
1294
+ const newDeps = JSON.stringify(JSON.parse(newPkgRaw).dependencies ?? {});
1295
+ for (const entry of [
1296
+ "dist",
1297
+ "docs",
1298
+ "scripts",
1299
+ "package.json",
1300
+ "README.md",
1301
+ "LICENSE",
1302
+ "config.example.json",
1303
+ "credentials.example.json"
1304
+ ]) {
1305
+ const src = join3(unpackedPkgDir, entry);
1306
+ if (!existsSync(src)) continue;
1307
+ const dst = join3(pkgRoot, entry);
1308
+ await cp(src, dst, { recursive: true, force: true });
1309
+ }
1310
+ if (oldDeps !== newDeps) {
1311
+ await runNpm(["install", "--omit=dev", "--no-audit", "--no-fund"], pkgRoot, 18e4);
1312
+ }
1313
+ await deps.sendReply(`\u5DF2\u901A\u8FC7 npm \u81EA\u52A8\u66F4\u65B0\u81F3 v${latestVersion}\uFF08\u539F v${currentVersion}\uFF09\uFF0C\u6B63\u5728\u70ED\u91CD\u542F\u670D\u52A1\u4EE5\u52A0\u8F7D\u65B0\u7248\u2026`);
1314
+ if (deps.triggerGracefulRestart) {
1315
+ setTimeout(() => deps.triggerGracefulRestart(), 800);
1316
+ }
1317
+ } finally {
1318
+ await rm(stageDir, { recursive: true, force: true }).catch(() => {
1319
+ });
1320
+ }
1321
+ }
1322
+ async function readActiveThreadOverride(stateDir, scopeHash) {
1323
+ const file = join3(stateDir, "bindings", `${scopeHash}.thread`);
1324
+ const text = await readFile3(file, "utf8").catch((error) => {
1325
+ if (error.code === "ENOENT") return "";
1326
+ throw error;
1327
+ });
1328
+ return text.trim() || void 0;
1329
+ }
1330
+ async function writeActiveThreadOverride(stateDir, scopeHash, threadId) {
1331
+ const dir = join3(stateDir, "bindings");
1332
+ const file = join3(dir, `${scopeHash}.thread`);
1333
+ if (!threadId) {
1334
+ await unlink(file).catch((error) => {
1335
+ if (error.code !== "ENOENT") throw error;
1336
+ });
1337
+ return;
1338
+ }
1339
+ await mkdir2(dir, { recursive: true });
1340
+ await writeFile2(file, threadId + "\n", { mode: 384 });
1341
+ }
1342
+
1343
+ // src/t3-cli.ts
1344
+ import { execFile as execFile2 } from "node:child_process";
1345
+ import { access as access2, readFile as readFile4 } from "node:fs/promises";
1346
+ import { homedir } from "node:os";
1347
+ import { dirname as dirname3, join as join4 } from "node:path";
1348
+ var STRIPPED_ENV_KEYS = /* @__PURE__ */ new Set([
1349
+ "QQ_BRIDGE_SECRET",
1350
+ "QQ_APP_ID",
1351
+ "QQ_APP_SECRET",
1352
+ "QQ_CREDENTIALS_FILE"
1353
+ ]);
1354
+ async function fileExists(path2) {
1355
+ try {
1356
+ await access2(path2);
1357
+ return true;
1358
+ } catch {
1359
+ return false;
1360
+ }
1361
+ }
1362
+ function getEnvCaseInsensitive(env, name) {
1363
+ if (env[name] !== void 0) return env[name];
1364
+ const target = name.toUpperCase();
1365
+ for (const [k, v] of Object.entries(env)) {
1366
+ if (k.toUpperCase() === target) return v;
1367
+ }
1368
+ return void 0;
1369
+ }
1370
+ function sanitizeChildEnv(baseEnv) {
1371
+ const sanitized = {};
1372
+ for (const [key, value] of Object.entries(baseEnv)) {
1373
+ if (!STRIPPED_ENV_KEYS.has(key.toUpperCase())) {
1374
+ sanitized[key] = value;
1375
+ }
1376
+ }
1377
+ return sanitized;
1378
+ }
1379
+ function parseWindowsT3Cmd(scriptText, options = {}) {
1380
+ const callerEnv = options.env ?? {};
1381
+ const scriptDir = options.scriptPath ? dirname3(options.scriptPath) : "";
1382
+ const env = {};
1383
+ const lines = scriptText.split(/\r?\n/);
1384
+ for (const line of lines) {
1385
+ const trimmed = line.trim();
1386
+ if (!trimmed || /^rem\b/i.test(trimmed) || trimmed.startsWith("::")) continue;
1387
+ const ifNotDefMatch = /^if\s+not\s+defined\s+([A-Za-z0-9_]+)\s+set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(
1388
+ trimmed
1389
+ );
1390
+ if (ifNotDefMatch) {
1391
+ const guardVar = ifNotDefMatch[1];
1392
+ const key = ifNotDefMatch[2] ?? ifNotDefMatch[4];
1393
+ const val = (ifNotDefMatch[3] ?? ifNotDefMatch[5] ?? "").trim();
1394
+ if (!getEnvCaseInsensitive(callerEnv, guardVar) && !val.includes("%ERRORLEVEL%")) {
1395
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
1396
+ }
1397
+ continue;
1398
+ }
1399
+ const setMatch = /^set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(trimmed);
1400
+ if (setMatch) {
1401
+ const key = setMatch[1] ?? setMatch[3];
1402
+ const val = (setMatch[2] ?? setMatch[4] ?? "").trim();
1403
+ if (val.includes("%ERRORLEVEL%") || /^t3_exit$/i.test(key)) continue;
1404
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
1405
+ }
1406
+ }
1407
+ for (const line of lines) {
1408
+ let trimmed = line.trim();
1409
+ if (!trimmed.endsWith("%*")) continue;
1410
+ trimmed = trimmed.slice(0, -2).trim();
1411
+ trimmed = trimmed.replace(/^if\s+exist\s+(?:"[^"]+"|\S+)\s+/i, "");
1412
+ trimmed = trimmed.replace(/^call\s+/i, "");
1413
+ if (scriptDir) {
1414
+ trimmed = trimmed.replace(/%~dp0/gi, scriptDir + "\\");
1415
+ }
1416
+ const tokens = [...trimmed.matchAll(/"([^"]+)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
1417
+ if (tokens.length >= 1) {
1418
+ return {
1419
+ executable: tokens[0],
1420
+ prefix: tokens.slice(1),
1421
+ env
1422
+ };
1423
+ }
1424
+ }
1425
+ return null;
1426
+ }
1427
+ async function resolveT3Command(t3Config, options = {}) {
1428
+ const platform = options.platform ?? process.platform;
1429
+ const home = options.homeDir ?? homedir();
1430
+ const procEnv = options.env ?? process.env;
1431
+ const t3Home = t3Config.home ?? getEnvCaseInsensitive(procEnv, "T3CODE_HOME") ?? join4(home, ".t3");
1432
+ const mergeEnv = (detected) => ({
1433
+ ...detected,
1434
+ ...t3Config.home ? { T3CODE_HOME: t3Config.home } : {},
1435
+ ...t3Config.env
1436
+ });
1437
+ if (t3Config.executable && t3Config.executable !== "auto") {
1438
+ if (platform === "win32" && /\.(cmd|bat)$/i.test(t3Config.executable)) {
1439
+ const parsed = parseWindowsT3Cmd(await readFile4(t3Config.executable, "utf8"), {
1440
+ env: procEnv,
1441
+ scriptPath: t3Config.executable
1442
+ });
1443
+ if (!parsed) {
1444
+ throw new Error(`Could not parse Windows T3 launcher script: ${t3Config.executable}`);
1445
+ }
1446
+ return {
1447
+ executable: parsed.executable,
1448
+ prefix: [...parsed.prefix, ...t3Config.prefix],
1449
+ env: mergeEnv(parsed.env)
1450
+ };
1451
+ }
1452
+ return {
1453
+ executable: t3Config.executable,
1454
+ prefix: [...t3Config.prefix],
1455
+ env: mergeEnv({})
1456
+ };
1457
+ }
1458
+ if (platform === "win32") {
1459
+ const candidates = [join4(t3Home, "bin", "t3.cmd"), join4(t3Home, "bin", "t3.exe")];
1460
+ for (const candidate of candidates) {
1461
+ if (!await fileExists(candidate)) continue;
1462
+ if (candidate.endsWith(".cmd")) {
1463
+ const parsed = parseWindowsT3Cmd(await readFile4(candidate, "utf8"), {
1464
+ env: procEnv,
1465
+ scriptPath: candidate
1466
+ });
1467
+ if (parsed) {
1468
+ return {
1469
+ executable: parsed.executable,
1470
+ prefix: [...parsed.prefix, ...t3Config.prefix],
1471
+ env: mergeEnv(parsed.env)
1472
+ };
1473
+ }
1474
+ } else {
1475
+ return {
1476
+ executable: candidate,
1477
+ prefix: [...t3Config.prefix],
1478
+ env: mergeEnv({})
1479
+ };
1480
+ }
1481
+ }
1482
+ return {
1483
+ executable: "t3.exe",
1484
+ prefix: [...t3Config.prefix],
1485
+ env: mergeEnv({})
1486
+ };
1487
+ }
1488
+ const unixCandidates = [join4(t3Home, "bin", "t3"), join4(home, ".local", "bin", "t3"), "/usr/local/bin/t3"];
1489
+ for (const candidate of unixCandidates) {
1490
+ if (await fileExists(candidate)) {
1491
+ return {
1492
+ executable: candidate,
1493
+ prefix: [...t3Config.prefix],
1494
+ env: mergeEnv({})
1495
+ };
1496
+ }
1497
+ }
1498
+ return {
1499
+ executable: "t3",
1500
+ prefix: [...t3Config.prefix],
1501
+ env: mergeEnv({})
1502
+ };
1503
+ }
1504
+ var T3Cli = class {
1505
+ resolvedPromise;
1506
+ t3Config;
1507
+ baseEnv;
1508
+ constructor(t3Config, baseEnv = process.env) {
1509
+ this.t3Config = t3Config;
1510
+ this.baseEnv = sanitizeChildEnv(baseEnv);
1511
+ }
1512
+ async resolve() {
1513
+ this.resolvedPromise ??= resolveT3Command(this.t3Config, { env: this.baseEnv });
1514
+ return this.resolvedPromise;
1515
+ }
1516
+ async runJson(args, input, timeoutMs = 3e4) {
1517
+ const cmd = await this.resolve();
1518
+ return new Promise((done, fail) => {
1519
+ const child = execFile2(
1520
+ cmd.executable,
1521
+ [...cmd.prefix, ...args, "--json"],
1522
+ {
1523
+ env: { ...this.baseEnv, ...cmd.env },
1524
+ windowsHide: true,
1525
+ timeout: timeoutMs,
1526
+ maxBuffer: 4e6
1527
+ },
1528
+ (error, stdout, stderr) => {
1529
+ if (error) {
1530
+ const detail = stderr?.trim() ? `: ${stderr.trim().slice(0, 300)}` : "";
1531
+ return fail(
1532
+ new Error(`T3 CLI (${args.slice(0, 2).join(" ")}) failed (${error.code ?? error.signal})${detail}`)
1533
+ );
1534
+ }
1535
+ try {
1536
+ done(JSON.parse(stdout));
1537
+ } catch (invalid) {
1538
+ fail(
1539
+ new Error(
1540
+ `T3 CLI returned invalid JSON: ${invalid instanceof Error ? invalid.message : String(invalid)}`
1541
+ )
1542
+ );
1543
+ }
1544
+ }
1545
+ );
1546
+ child.stdin?.on("error", () => {
1547
+ });
1548
+ child.stdin?.end(input, "utf8");
1549
+ });
1550
+ }
1551
+ async issueSession(options) {
1552
+ const args = ["auth", "session", "issue"];
1553
+ for (const scope of options.scopes) {
1554
+ args.push("--scope", scope);
1555
+ }
1556
+ if (options.subject) {
1557
+ args.push("--subject", options.subject);
1558
+ }
1559
+ args.push("--ttl", options.ttl, "--label", options.label);
1560
+ return this.runJson(args);
1561
+ }
1562
+ async revokeSession(sessionId) {
1563
+ const cmd = await this.resolve();
1564
+ await new Promise((resolveDone) => {
1565
+ const child = execFile2(
1566
+ cmd.executable,
1567
+ [...cmd.prefix, "auth", "session", "revoke", sessionId],
1568
+ {
1569
+ env: { ...this.baseEnv, ...cmd.env },
1570
+ windowsHide: true,
1571
+ timeout: 1e4
1572
+ },
1573
+ () => resolveDone()
1574
+ );
1575
+ child.on("error", () => resolveDone());
1576
+ });
1577
+ }
1578
+ async withSession(options, fn) {
1579
+ const session = await this.issueSession(options);
1580
+ try {
1581
+ return await fn(session.token);
1582
+ } finally {
1583
+ await this.revokeSession(session.sessionId).catch(() => {
1584
+ });
1585
+ }
1586
+ }
1587
+ };
1588
+
1589
+ // src/t3-ws.ts
1590
+ import { randomUUID } from "node:crypto";
1591
+ import { setTimeout as sleep } from "node:timers/promises";
1592
+ import WebSocket from "ws";
1593
+ var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
1594
+ "completed",
1595
+ "failed",
1596
+ "interrupted",
1597
+ "cancelled",
1598
+ "rolled_back"
1599
+ ]);
1600
+ var ACTIVE_RUN_STATUSES = /* @__PURE__ */ new Set(["queued", "preparing", "starting", "running", "waiting"]);
1601
+ var PENDING_ITEM_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "waiting"]);
1602
+ var DEFAULT_OBSERVE_LIFETIME_MS = 40 * 6e4;
1603
+ var MAX_CONSECUTIVE_WS_FAILURES = 10;
1604
+ function openT3Socket(origin, token) {
1605
+ const url = new URL("/ws?orchestrationProtocol=2", origin);
1606
+ if (url.protocol !== "http:" && url.protocol !== "https:" || !LOOPBACK_HOSTS.has(url.hostname)) {
1607
+ throw new Error(`T3 native WebSocket requires a loopback origin (127.0.0.1 / localhost / ::1), got: ${origin}`);
1608
+ }
1609
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
1610
+ return new WebSocket(url, {
1611
+ headers: { Authorization: `Bearer ${token}` },
1612
+ handshakeTimeout: 5e3
1613
+ });
1614
+ }
1615
+ function sendRpc(socket, tag, payload, id) {
1616
+ return new Promise((resolve5, reject) => {
1617
+ let settled = false;
1618
+ const finish = (error, value) => {
1619
+ if (settled) return;
1620
+ settled = true;
1621
+ clearTimeout(timer);
1622
+ socket.off("message", receive);
1623
+ socket.off("close", closed);
1624
+ socket.off("error", errored);
1625
+ if (error) reject(error);
1626
+ else resolve5(value);
1627
+ };
1628
+ const closed = () => finish(new Error("T3 closed the delivery connection"));
1629
+ const errored = (err) => finish(err);
1630
+ const receive = (frame) => {
1631
+ try {
1632
+ const message = JSON.parse(frame.toString());
1633
+ if (message._tag === "Defect") return finish(new Error("T3 RPC protocol error"));
1634
+ if (message._tag !== "Exit" || String(message.requestId) !== id) return;
1635
+ if (message.exit?._tag === "Success") return finish(void 0, message.exit.value);
1636
+ const causes = Array.isArray(message.exit?.cause) ? message.exit.cause : [];
1637
+ const failure = causes.find(
1638
+ (cause) => cause && typeof cause === "object" && cause._tag === "Fail"
1639
+ );
1640
+ const detail = failure?.error?.message ?? failure?.error?.reason ?? "dispatch rejected";
1641
+ finish(new Error(`T3 ${tag}: ${detail}`));
1642
+ } catch {
1643
+ finish(new Error("T3 returned an invalid RPC response"));
1644
+ }
1645
+ };
1646
+ const timer = setTimeout(() => finish(new Error(`T3 ${tag} timed out`)), 15e3);
1647
+ socket.on("message", receive);
1648
+ socket.once("close", closed);
1649
+ socket.once("error", errored);
1650
+ socket.send(JSON.stringify({ _tag: "Request", id, tag, headers: [], payload }), (error) => {
1651
+ if (error) finish(error);
1652
+ });
1653
+ });
1654
+ }
1655
+ async function dispatchMessage(origin, token, message) {
1656
+ const socket = openT3Socket(origin, token);
1657
+ const ignoreLateError = () => {
1658
+ };
1659
+ socket.on("error", ignoreLateError);
1660
+ try {
1661
+ await new Promise((resolve5, reject) => {
1662
+ const onOpen = () => {
1663
+ socket.off("error", onError);
1664
+ resolve5();
1665
+ };
1666
+ const onError = (err) => {
1667
+ socket.off("open", onOpen);
1668
+ reject(err);
1669
+ };
1670
+ socket.once("open", onOpen);
1671
+ socket.once("error", onError);
1672
+ });
1673
+ const messageId = `qq-message:${message.key}`;
1674
+ const { sequence } = await sendRpc(
1675
+ socket,
1676
+ "orchestration.dispatchCommand",
1677
+ {
1678
+ type: "message.dispatch",
1679
+ commandId: `qq:${message.key}`,
1680
+ threadId: message.threadId,
1681
+ messageId,
1682
+ text: message.text,
1683
+ attachments: message.attachments,
1684
+ createdBy: "user",
1685
+ creationSource: "server",
1686
+ dispatchMode: { type: "queue_after_active" }
1687
+ },
1688
+ "1"
1689
+ );
1690
+ const projection = await sendRpc(
1691
+ socket,
1692
+ "orchestration.getThreadProjection",
1693
+ { threadId: message.threadId },
1694
+ "2"
1695
+ );
1696
+ const runId = projection.runs.find((run) => run.userMessageId === messageId)?.id ?? projection.turnItems.find((item) => item.messageId === messageId)?.runId;
1697
+ if (!runId) {
1698
+ throw new Error("T3 committed the QQ message but returned no matching run");
1699
+ }
1700
+ return { runId, sequence };
1701
+ } finally {
1702
+ socket.close();
1703
+ }
1704
+ }
1705
+ function planCheckpointRollback(projection, turns, restoreFiles = false) {
1706
+ const runs = Array.isArray(projection.runs) ? projection.runs : [];
1707
+ if (runs.some((r) => ACTIVE_RUN_STATUSES.has(r.status))) {
1708
+ return { error: "\u5F53\u524D\u4F1A\u8BDD\u4ECD\u6709\u6B63\u5728\u6267\u884C\u7684\u8F6E\u6B21\uFF0C\u8BF7\u5148\u53D1\u9001 /stop \u4E2D\u65AD\u540E\u518D\u6267\u884C /rewind\u3002" };
1709
+ }
1710
+ const nonRolledBackRuns = runs.filter((r) => r.status !== "rolled_back").sort((a, b) => a.ordinal - b.ordinal);
1711
+ if (nonRolledBackRuns.length === 0) {
1712
+ return { error: "\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u64A4\u56DE\u7684\u5BF9\u8BDD\u8F6E\u6B21\u3002\u82E5\u60F3\u5F00\u65B0\u5BF9\u8BDD\uFF0C\u8BF7\u53D1\u9001 /new\u3002" };
1713
+ }
1714
+ const scopes = Array.isArray(projection.checkpointScopes) ? projection.checkpointScopes : [];
1715
+ const allCheckpoints = Array.isArray(projection.checkpoints) ? projection.checkpoints : [];
1716
+ const activeProviderThreadId = projection.thread?.activeProviderThreadId ?? null;
1717
+ const isEligibleStatus = (status) => restoreFiles ? status === "ready" : status === "ready" || status === "missing";
1718
+ const activeScope = scopes.findLast(
1719
+ (s) => activeProviderThreadId !== null && s.providerThreadId === activeProviderThreadId && s.kind === "root_run"
1720
+ ) ?? scopes.findLast((s) => activeProviderThreadId !== null && s.providerThreadId === activeProviderThreadId) ?? scopes.findLast((s) => allCheckpoints.some((cp2) => cp2.scopeId === s.id && isEligibleStatus(cp2.status))) ?? scopes.at(-1);
1721
+ if (!activeScope) {
1722
+ return { error: "\u5F53\u524D\u4F1A\u8BDD\u5C1A\u672A\u751F\u6210 T3 \u56DE\u6EAF\u68C0\u67E5\u70B9\uFF08checkpoint\uFF09\uFF0C\u6682\u4E0D\u652F\u6301\u539F\u5730\u64A4\u56DE\uFF1B\u8BF7\u53D1\u9001 /new \u5F00\u542F\u65B0\u4F1A\u8BDD\u3002" };
1723
+ }
1724
+ const scopeCheckpoints = allCheckpoints.filter((cp2) => cp2.scopeId === activeScope.id);
1725
+ const eligible = scopeCheckpoints.filter((cp2) => isEligibleStatus(cp2.status));
1726
+ if (eligible.length === 0) {
1727
+ if (restoreFiles && scopeCheckpoints.some((cp2) => cp2.status === "missing")) {
1728
+ return {
1729
+ error: `\u5F53\u524D\u5DE5\u4F5C\u533A\u672A\u751F\u6210\u53EF\u6062\u590D\u7684\u6587\u4EF6\u5FEB\u7167\uFF08\u975E\u72EC\u7ACB worktree \u6216\u975E git \u4ED3\u5E93\uFF09\uFF1B\u8BF7\u6539\u53D1 /rewind ${turns} \u4EC5\u64A4\u56DE\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u3002`
1730
+ };
1731
+ }
1732
+ return { error: "\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u53EF\u7528\u7684\u56DE\u6EAF\u68C0\u67E5\u70B9\uFF0C\u8BF7\u53D1\u9001 /new \u5F00\u542F\u65B0\u4F1A\u8BDD\u3002" };
1733
+ }
1734
+ const baseline = eligible.findLast((cp2) => cp2.ordinalWithinScope === 0 && cp2.appRunOrdinal === null);
1735
+ const runCheckpointsByOrdinal = /* @__PURE__ */ new Map();
1736
+ for (const cp2 of eligible) {
1737
+ if (typeof cp2.appRunOrdinal === "number" && cp2.appRunOrdinal > 0) {
1738
+ runCheckpointsByOrdinal.set(cp2.appRunOrdinal, cp2);
1739
+ }
1740
+ }
1741
+ const runCheckpoints = [...runCheckpointsByOrdinal.values()].sort(
1742
+ (a, b) => (a.appRunOrdinal ?? 0) - (b.appRunOrdinal ?? 0)
1743
+ );
1744
+ const minScopeOrdinal = runCheckpoints[0]?.appRunOrdinal;
1745
+ const scopeRuns = typeof minScopeOrdinal === "number" ? nonRolledBackRuns.filter((r) => r.ordinal >= minScopeOrdinal) : nonRolledBackRuns;
1746
+ const availableTurns = scopeRuns.length;
1747
+ if (availableTurns === 0) {
1748
+ return { error: "\u5F53\u524D\u4F1A\u8BDD\u6682\u65E0\u53EF\u64A4\u56DE\u7684\u5BF9\u8BDD\u8F6E\u6B21\u3002\u82E5\u60F3\u5F00\u65B0\u5BF9\u8BDD\uFF0C\u8BF7\u53D1\u9001 /new\u3002" };
1749
+ }
1750
+ if (turns > availableTurns) {
1751
+ return {
1752
+ error: `\u5F53\u524D\u4F1A\u8BDD\u4EC5\u6709 ${availableTurns} \u8F6E\u53EF\u64A4\u56DE\uFF0C\u65E0\u6CD5\u64A4\u56DE ${turns} \u8F6E\u3002\u53D1\u9001 /rewind ${availableTurns} \u53EF\u64A4\u56DE\u5168\u90E8\uFF0C\u6216\u53D1\u9001 /new \u5F00\u542F\u65B0\u4F1A\u8BDD\u3002`
1753
+ };
1754
+ }
1755
+ let targetCheckpoint;
1756
+ let targetOrdinal = 0;
1757
+ if (turns === availableTurns) {
1758
+ targetCheckpoint = baseline;
1759
+ targetOrdinal = 0;
1760
+ if (!targetCheckpoint) {
1761
+ if (restoreFiles && scopeCheckpoints.some((cp2) => cp2.ordinalWithinScope === 0 && cp2.status === "missing")) {
1762
+ return {
1763
+ error: `\u5F53\u524D\u5DE5\u4F5C\u533A\u7F3A\u5C11\u521D\u59CB\u6587\u4EF6\u5FEB\u7167\uFF0C\u65E0\u6CD5\u5E26 --files \u64A4\u56DE\u5168\u90E8 ${turns} \u8F6E\uFF1B\u8BF7\u6539\u53D1 /rewind ${turns} \u4EC5\u64A4\u56DE\u5BF9\u8BDD\u3002`
1764
+ };
1765
+ }
1766
+ return {
1767
+ error: `\u5F53\u524D\u4F1A\u8BDD\u7F3A\u5C11\u521D\u59CB\u68C0\u67E5\u70B9\uFF0C\u6700\u591A\u652F\u6301\u64A4\u56DE ${Math.max(0, availableTurns - 1)} \u8F6E\uFF1B\u82E5\u60F3\u5B8C\u5168\u6E05\u7A7A\uFF0C\u8BF7\u53D1\u9001 /new\u3002`
1768
+ };
1769
+ }
1770
+ } else {
1771
+ const keepLastRun = scopeRuns[availableTurns - 1 - turns];
1772
+ targetCheckpoint = runCheckpointsByOrdinal.get(keepLastRun.ordinal) ?? runCheckpoints.findLast((cp2) => (cp2.appRunOrdinal ?? 0) <= keepLastRun.ordinal);
1773
+ targetOrdinal = targetCheckpoint?.appRunOrdinal ?? keepLastRun.ordinal;
1774
+ if (!targetCheckpoint) {
1775
+ return {
1776
+ error: `\u672A\u80FD\u627E\u5230\u7B2C ${keepLastRun.ordinal} \u8F6E\u5BF9\u5E94\u7684\u53EF\u7528\u68C0\u67E5\u70B9\uFF0C\u8BF7\u5C1D\u8BD5\u8C03\u6574\u64A4\u56DE\u8F6E\u6570\u6216\u53D1\u9001 /new\u3002`
1777
+ };
1778
+ }
1779
+ }
1780
+ const latestRolledBackRun = scopeRuns[availableTurns - 1];
1781
+ return {
1782
+ plan: {
1783
+ scopeId: targetCheckpoint.scopeId,
1784
+ checkpointId: targetCheckpoint.id,
1785
+ targetOrdinal,
1786
+ rolledBackTurns: turns,
1787
+ remainingTurns: availableTurns - turns,
1788
+ latestRolledBackRunId: latestRolledBackRun.id
1789
+ }
1790
+ };
1791
+ }
1792
+ async function rollbackThreadTurns(origin, token, threadId, options) {
1793
+ const restoreFiles = options.restoreFiles ?? false;
1794
+ const timeoutMs = options.timeoutMs ?? 45e3;
1795
+ const pollIntervalMs = options.pollIntervalMs ?? 250;
1796
+ const socket = openT3Socket(origin, token);
1797
+ const ignoreLateError = () => {
1798
+ };
1799
+ socket.on("error", ignoreLateError);
1800
+ try {
1801
+ await new Promise((resolve5, reject) => {
1802
+ const onOpen = () => {
1803
+ socket.off("error", onError);
1804
+ resolve5();
1805
+ };
1806
+ const onError = (err) => {
1807
+ socket.off("open", onOpen);
1808
+ reject(err);
1809
+ };
1810
+ socket.once("open", onOpen);
1811
+ socket.once("error", onError);
1812
+ });
1813
+ let rpcSeq = 0;
1814
+ const nextId = () => String(++rpcSeq);
1815
+ const initialProjection = await sendRpc(
1816
+ socket,
1817
+ "orchestration.getThreadProjection",
1818
+ { threadId },
1819
+ nextId()
1820
+ );
1821
+ const planned = planCheckpointRollback(initialProjection, options.turns, restoreFiles);
1822
+ if (!planned.plan) {
1823
+ throw new Error(planned.error ?? "\u5F53\u524D\u4F1A\u8BDD\u6682\u4E0D\u652F\u6301\u539F\u5730\u64A4\u56DE\u3002");
1824
+ }
1825
+ const { plan } = planned;
1826
+ const commandId = `qq-rollback:${randomUUID()}`;
1827
+ await sendRpc(
1828
+ socket,
1829
+ "orchestration.dispatchCommand",
1830
+ {
1831
+ type: "checkpoint.rollback",
1832
+ commandId,
1833
+ threadId,
1834
+ scopeId: plan.scopeId,
1835
+ checkpointId: plan.checkpointId,
1836
+ restoreFiles
1837
+ },
1838
+ nextId()
1839
+ );
1840
+ const expectedLastOrdinal = plan.targetOrdinal === 0 ? null : plan.targetOrdinal;
1841
+ const deadline = Date.now() + timeoutMs;
1842
+ while (Date.now() < deadline) {
1843
+ const latest = await sendRpc(
1844
+ socket,
1845
+ "orchestration.getThreadProjection",
1846
+ { threadId },
1847
+ nextId()
1848
+ );
1849
+ if (latest.thread?.rollbackFailure?.requestId === commandId) {
1850
+ throw new Error(latest.thread.rollbackFailure.message || "T3 Code \u64A4\u56DE\u6267\u884C\u5931\u8D25\u3002");
1851
+ }
1852
+ const latestRuns = Array.isArray(latest.runs) ? latest.runs : [];
1853
+ const explicitlyRolledBack = latestRuns.some(
1854
+ (r) => r.id === plan.latestRolledBackRunId && r.status === "rolled_back"
1855
+ );
1856
+ const runRolledBackOrPruned = !latestRuns.some(
1857
+ (r) => r.id === plan.latestRolledBackRunId && r.status !== "rolled_back"
1858
+ );
1859
+ const activePt = latest.providerThreads?.find((pt) => pt.id === latest.thread?.activeProviderThreadId);
1860
+ const providerReachedTarget = activePt !== void 0 && activePt.lastRunOrdinal === expectedLastOrdinal;
1861
+ if (explicitlyRolledBack || runRolledBackOrPruned && providerReachedTarget) {
1862
+ return {
1863
+ threadId,
1864
+ rolledBackTurns: plan.rolledBackTurns,
1865
+ remainingTurns: plan.remainingTurns,
1866
+ targetOrdinal: plan.targetOrdinal,
1867
+ checkpointId: plan.checkpointId,
1868
+ restoreFiles
1869
+ };
1870
+ }
1871
+ await sleep(pollIntervalMs);
1872
+ }
1873
+ throw new Error("\u7B49\u5F85 T3 Code \u5B8C\u6210\u64A4\u56DE\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u53D1\u9001 /status \u786E\u8BA4\u4F1A\u8BDD\u72B6\u6001\u3002");
1874
+ } finally {
1875
+ socket.close();
1876
+ }
1877
+ }
1878
+ async function withT3Socket(origin, token, fn) {
1879
+ const socket = openT3Socket(origin, token);
1880
+ const ignoreLateError = () => {
1881
+ };
1882
+ socket.on("error", ignoreLateError);
1883
+ try {
1884
+ await new Promise((resolve5, reject) => {
1885
+ const onOpen = () => {
1886
+ socket.off("error", onError);
1887
+ resolve5();
1888
+ };
1889
+ const onError = (err) => {
1890
+ socket.off("open", onOpen);
1891
+ reject(err);
1892
+ };
1893
+ socket.once("open", onOpen);
1894
+ socket.once("error", onError);
1895
+ });
1896
+ let seq = 0;
1897
+ const rpc = (tag, payload) => sendRpc(socket, tag, payload, String(++seq));
1898
+ return await fn(rpc);
1899
+ } finally {
1900
+ socket.close();
1901
+ }
1902
+ }
1903
+ async function getThreadState(origin, token, threadId) {
1904
+ return withT3Socket(origin, token, async (rpc) => {
1905
+ const proj = await rpc("orchestration.getThreadProjection", { threadId });
1906
+ const t = proj?.thread ?? {};
1907
+ return {
1908
+ threadId: String(t.id ?? threadId),
1909
+ title: typeof t.title === "string" ? t.title : void 0,
1910
+ projectId: typeof t.projectId === "string" ? t.projectId : void 0,
1911
+ providerInstanceId: typeof t.providerInstanceId === "string" ? t.providerInstanceId : void 0,
1912
+ modelSelection: t.modelSelection && typeof t.modelSelection === "object" ? t.modelSelection : void 0,
1913
+ runtimeMode: typeof t.runtimeMode === "string" ? t.runtimeMode : void 0,
1914
+ interactionMode: typeof t.interactionMode === "string" ? t.interactionMode : void 0
1915
+ };
1916
+ });
1917
+ }
1918
+ async function setThreadModelSelection(origin, token, threadId, modelSelection) {
1919
+ await withT3Socket(origin, token, async (rpc) => {
1920
+ await rpc("orchestration.dispatchCommand", {
1921
+ type: "thread.model-selection.set",
1922
+ commandId: `qq-model:${randomUUID()}`,
1923
+ threadId,
1924
+ modelSelection
1925
+ });
1926
+ });
1927
+ }
1928
+ async function createNativeThread(origin, token, input) {
1929
+ const threadId = input.threadId ?? randomUUID();
1930
+ await withT3Socket(origin, token, async (rpc) => {
1931
+ await rpc("orchestration.dispatchCommand", {
1932
+ type: "thread.create",
1933
+ commandId: `qq-create:${randomUUID()}`,
1934
+ threadId,
1935
+ projectId: input.projectId,
1936
+ title: input.title,
1937
+ modelSelection: input.modelSelection,
1938
+ runtimeMode: input.runtimeMode ?? "full-access",
1939
+ interactionMode: input.interactionMode ?? "default",
1940
+ branch: null,
1941
+ worktreePath: null,
1942
+ createdBy: "user",
1943
+ creationSource: "server"
1944
+ });
1945
+ });
1946
+ return { threadId };
1947
+ }
1948
+ async function stopNativeThread(origin, token, threadId, options = {}) {
1949
+ await withT3Socket(origin, token, async (rpc) => {
1950
+ await rpc("orchestration.dispatchCommand", {
1951
+ type: "thread.stop",
1952
+ commandId: `qq-stop:${randomUUID()}`,
1953
+ threadId,
1954
+ ...options.reason ? { reason: options.reason } : {},
1955
+ ...options.stopDelegatedTasks !== void 0 ? { stopDelegatedTasks: options.stopDelegatedTasks } : {}
1956
+ });
1957
+ });
1958
+ }
1959
+ async function settleNativeThread(origin, token, threadId) {
1960
+ await withT3Socket(origin, token, async (rpc) => {
1961
+ await rpc("orchestration.dispatchCommand", {
1962
+ type: "thread.settle",
1963
+ commandId: `qq-settle:${randomUUID()}`,
1964
+ threadId
1965
+ });
1966
+ });
1967
+ }
1968
+ async function readReply(origin, token, threadId, runId, options = {}) {
1969
+ const deadline = Date.now() + (options.lifetimeMs ?? DEFAULT_OBSERVE_LIFETIME_MS);
1970
+ const textByItem = /* @__PURE__ */ new Map();
1971
+ const pendingSubagents = /* @__PURE__ */ new Set();
1972
+ let cursor = options.afterSequence;
1973
+ let final;
1974
+ const scheduled = /* @__PURE__ */ new Set();
1975
+ let delivery = Promise.resolve();
1976
+ let deliveryError;
1977
+ const queueMessage = (item) => {
1978
+ if (!options.onMessage || !item.text?.trim() || scheduled.has(item.id)) return;
1979
+ scheduled.add(item.id);
1980
+ const message = { id: item.id, text: item.text, updatedAt: item.updatedAt };
1981
+ delivery = delivery.then(() => options.onMessage(message)).catch((error) => {
1982
+ deliveryError ??= error;
1983
+ });
1984
+ };
1985
+ const keepItem = (item) => {
1986
+ if (item.runId !== runId) return;
1987
+ if (item.type === "assistant_message") {
1988
+ textByItem.set(item.id, item);
1989
+ if (item.status === "completed") queueMessage(item);
1990
+ if (!TERMINAL_RUN_STATUSES.has(item.status) && item.text?.trim() && !scheduled.has(item.id)) {
1991
+ options.onUpdate?.({ id: item.id, text: item.text, updatedAt: item.updatedAt });
1992
+ }
1993
+ }
1994
+ if (item.type === "subagent") {
1995
+ if (PENDING_ITEM_STATUSES.has(item.status)) {
1996
+ pendingSubagents.add(item.id);
1997
+ } else if (TERMINAL_RUN_STATUSES.has(item.status)) {
1998
+ pendingSubagents.delete(item.id);
1999
+ }
2000
+ }
2001
+ };
2002
+ const keepRun = (run) => {
2003
+ if (final || run.id !== runId || !TERMINAL_RUN_STATUSES.has(run.status)) return;
2004
+ final = run;
2005
+ options.onTerminal?.(run);
2006
+ };
2007
+ const apply = (item) => {
2008
+ if (item.kind === "snapshot") {
2009
+ const sortedItems = [...item.projection.turnItems].sort((a, b) => a.ordinal - b.ordinal);
2010
+ sortedItems.forEach(keepItem);
2011
+ item.projection.runs.forEach(keepRun);
2012
+ cursor = item.snapshotSequence;
2013
+ } else if (item.kind === "event") {
2014
+ const event = item.event;
2015
+ if (event.type === "turn-item.updated") keepItem(event.payload);
2016
+ if (event.type === "run.updated") keepRun(event.payload);
2017
+ cursor = item.sequence;
2018
+ }
2019
+ };
2020
+ const subscribe = () => new Promise((resolve5, reject) => {
2021
+ if (options.signal?.aborted) {
2022
+ reject(new Error("T3 reply observation aborted"));
2023
+ return;
2024
+ }
2025
+ const socket = openT3Socket(origin, token);
2026
+ const ignoreLateError = () => {
2027
+ };
2028
+ socket.on("error", ignoreLateError);
2029
+ let settled = false;
2030
+ const finish = (error) => {
2031
+ if (settled) return;
2032
+ settled = true;
2033
+ clearTimeout(timer);
2034
+ options.signal?.removeEventListener("abort", onAbort);
2035
+ socket.close();
2036
+ if (error) reject(error);
2037
+ else resolve5();
2038
+ };
2039
+ const onAbort = () => finish(new Error("T3 reply observation aborted"));
2040
+ options.signal?.addEventListener("abort", onAbort, { once: true });
2041
+ const remaining = Math.max(1e3, deadline - Date.now());
2042
+ const timer = setTimeout(() => finish(new Error("T3 reply observation expired")), remaining);
2043
+ socket.once("open", () => {
2044
+ socket.send(
2045
+ JSON.stringify({
2046
+ _tag: "Request",
2047
+ id: "1",
2048
+ tag: "orchestration.subscribeThread",
2049
+ headers: [],
2050
+ payload: {
2051
+ threadId,
2052
+ afterSequence: cursor,
2053
+ acceptBoundedSnapshot: true,
2054
+ requestCompletionMarker: true
2055
+ }
2056
+ })
2057
+ );
2058
+ });
2059
+ socket.on("message", (frame) => {
2060
+ try {
2061
+ const message = JSON.parse(frame.toString());
2062
+ if (message._tag === "Chunk" && String(message.requestId) === "1" && Array.isArray(message.values)) {
2063
+ for (const item of message.values) apply(item);
2064
+ socket.send(JSON.stringify({ _tag: "Ack", requestId: "1" }));
2065
+ if (final) finish();
2066
+ } else if (message._tag === "Exit" || message._tag === "Defect") {
2067
+ finish(new Error("T3 ended the reply subscription"));
2068
+ }
2069
+ } catch (error) {
2070
+ finish(error instanceof Error ? error : new Error("Invalid T3 reply event"));
2071
+ }
2072
+ });
2073
+ socket.on("error", finish);
2074
+ socket.on("close", () => finish(new Error("T3 reply connection closed")));
2075
+ });
2076
+ let failures = 0;
2077
+ try {
2078
+ while (!final) {
2079
+ const previousCursor = cursor;
2080
+ try {
2081
+ await subscribe();
2082
+ } catch (error) {
2083
+ if (options.signal?.aborted) throw error;
2084
+ failures = previousCursor === cursor ? failures + 1 : 1;
2085
+ if (Date.now() >= deadline || failures >= MAX_CONSECUTIVE_WS_FAILURES) throw error;
2086
+ const backoffMs = Math.min(8e3, 250 * Math.pow(2, failures - 1));
2087
+ await sleep(backoffMs, void 0, { signal: options.signal }).catch(() => {
2088
+ });
2089
+ }
2090
+ }
2091
+ } finally {
2092
+ if (final) {
2093
+ const messages2 = [...textByItem.values()].sort((a, b) => a.ordinal - b.ordinal);
2094
+ messages2.forEach(queueMessage);
2095
+ }
2096
+ await delivery;
2097
+ }
2098
+ if (deliveryError) throw deliveryError;
2099
+ if (!final) throw new Error("T3 reply observation ended without terminal run state");
2100
+ const messages = [...textByItem.values()].sort((a, b) => a.ordinal - b.ordinal);
2101
+ return {
2102
+ status: final.status,
2103
+ completedAt: final.completedAt,
2104
+ body: messages.map((item) => item.text ?? "").filter((text) => text.trim()).join("\n\n"),
2105
+ lastBodyAt: messages.reduce((latest, item) => Math.max(latest, Date.parse(item.updatedAt)), 0),
2106
+ backgroundTaskIds: [...pendingSubagents]
2107
+ };
2108
+ }
2109
+
2110
+ // src/bridge.ts
2111
+ var ReplyStreamApi = class extends MessageApi {
2112
+ key;
2113
+ runId;
2114
+ itemId;
2115
+ logTiming;
2116
+ hasLiveBubble = false;
2117
+ constructor(client, tokens, key, runId, itemId, logTiming) {
2118
+ super(client, tokens, { markdownSupport: false });
2119
+ this.key = key;
2120
+ this.runId = runId;
2121
+ this.itemId = itemId;
2122
+ this.logTiming = logTiming;
2123
+ }
2124
+ async sendC2CStreamMessage(...args) {
2125
+ const started = Date.now();
2126
+ const frame = args[2];
2127
+ if (frame.index === 0) this.logTiming("first_frame_send", this.key, this.runId, this.itemId);
2128
+ const response = await super.sendC2CStreamMessage(...args);
2129
+ if (response?.id) {
2130
+ this.hasLiveBubble = true;
2131
+ if (frame.index === 0) {
2132
+ this.logTiming("first_frame_ack", this.key, this.runId, this.itemId, Array.from(frame.content_raw).length);
2133
+ }
2134
+ if (frame.input_state === StreamInputState.DONE) {
2135
+ this.logTiming("final_frame_ack", this.key, this.runId, this.itemId, Array.from(frame.content_raw).length);
2136
+ }
2137
+ }
2138
+ if (frame.input_state === StreamInputState.DONE || frame.index === 0) {
2139
+ console.info(
2140
+ "QQ stream frame confirmed",
2141
+ frame.input_state === StreamInputState.DONE ? "done" : "first",
2142
+ "chars",
2143
+ Array.from(frame.content_raw).length,
2144
+ "ms",
2145
+ Date.now() - started
2146
+ );
2147
+ }
2148
+ return response;
2149
+ }
2150
+ };
2151
+ function startTypingKeepalive(reply, sendTyping, options = {}) {
2152
+ if (reply.scope !== "c2c") return () => {
2153
+ };
2154
+ const durationSec = options.durationSec ?? 60;
2155
+ const intervalMs = options.intervalMs ?? 5e4;
2156
+ let stopped = false;
2157
+ const fire = () => {
2158
+ if (stopped || options.signal?.aborted) return;
2159
+ void sendTyping(reply, durationSec).catch(() => {
2160
+ });
2161
+ };
2162
+ fire();
2163
+ const timer = setInterval(fire, intervalMs);
2164
+ timer.unref?.();
2165
+ const stop = () => {
2166
+ if (stopped) return;
2167
+ stopped = true;
2168
+ clearInterval(timer);
2169
+ options.signal?.removeEventListener("abort", stop);
2170
+ };
2171
+ options.signal?.addEventListener("abort", stop, { once: true });
2172
+ return stop;
2173
+ }
2174
+ async function createBridgeRuntime(config, credentials, options = {}) {
2175
+ const root = resolve4(config.stateDir);
2176
+ await mkdir3(root, { recursive: true });
2177
+ await mkdir3(join5(root, "bindings"), { recursive: true });
2178
+ const originalConsole = {};
2179
+ if (options.attachFileLogger !== false) {
2180
+ const logPath = join5(root, "bridge.log");
2181
+ for (const level of ["info", "warn", "error"]) {
2182
+ const original = console[level].bind(console);
2183
+ originalConsole[level] = console[level];
2184
+ console[level] = (...parts) => {
2185
+ try {
2186
+ appendFileSync(
2187
+ logPath,
2188
+ `${(/* @__PURE__ */ new Date()).toISOString()} [${level.toUpperCase()}] ${parts.map(String).join(" ")}
2189
+ `,
2190
+ { mode: 384 }
2191
+ );
2192
+ } catch {
2193
+ }
2194
+ original(...parts);
2195
+ };
2196
+ }
2197
+ }
2198
+ const shutdownController = new AbortController();
2199
+ const qq = new QQBot({ appId: credentials.appId, appSecret: credentials.appSecret });
2200
+ const streamClient = new ApiClient({ defaultTimeoutMs: 1e4 });
2201
+ const sharedTokenManager = qq.tokenManager;
2202
+ const t3Cli = new T3Cli(config.t3);
2203
+ const observer = new Observer(
2204
+ config.t3.origin,
2205
+ () => t3Cli.issueSession({
2206
+ scopes: ["orchestration:read", "orchestration:operate"],
2207
+ subject: "mcp-client",
2208
+ ttl: "1h",
2209
+ label: "T3 QQBot observer"
2210
+ }),
2211
+ (sessionId) => t3Cli.revokeSession(sessionId)
2212
+ );
2213
+ const expectedAuthDigest = digestBuffer(`Bearer ${credentials.bridgeSecret}`);
2214
+ const threadLocks = /* @__PURE__ */ new Map();
2215
+ const timing = (stage, key, runId, ...details) => console.info("QQ_T3_TIMING", stage, key, runId, Date.now(), ...details);
2216
+ async function resolveThreadForBinding(binding, scope) {
2217
+ const override = await readActiveThreadOverride(root, binding.scopeHash);
2218
+ if (override) return override;
2219
+ if (binding.threadId) return binding.threadId;
2220
+ const existingLock = threadLocks.get(binding.scopeHash);
2221
+ if (existingLock) return existingLock;
2222
+ const promise = (async () => {
2223
+ const persisted = await readActiveThreadOverride(root, binding.scopeHash);
2224
+ if (persisted) return persisted;
2225
+ const { projects } = await observer.call("t3_project_list", { limit: 100 });
2226
+ const project = projects.find((row) => samePath(row.workspaceRoot, binding.workspace));
2227
+ if (!project) {
2228
+ throw new Error(
2229
+ `Workspace "${binding.workspace}" is not registered in T3 Code. Open or add it as a T3 project first.`
2230
+ );
2231
+ }
2232
+ let modelSelection = binding.modelSelection?.model ? {
2233
+ ...binding.modelSelection.provider ? { instanceId: binding.modelSelection.provider } : {},
2234
+ model: binding.modelSelection.model
2235
+ } : void 0;
2236
+ if (!modelSelection) {
2237
+ const caps = await observer.call("orchestrator_capabilities", {});
2238
+ const firstProv = caps.providers.find((p) => p.models.length > 0 && p.canRunChildTask !== false) ?? caps.providers[0];
2239
+ const firstModel = firstProv?.models[0]?.id;
2240
+ if (!firstProv || !firstModel) {
2241
+ throw new Error("T3 Code has no enabled provider model available to auto-create a thread");
2242
+ }
2243
+ modelSelection = { instanceId: firstProv.providerInstanceId, model: firstModel };
2244
+ }
2245
+ const created = await t3Cli.withSession(
2246
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot auto thread" },
2247
+ (token) => createNativeThread(config.t3.origin, token, {
2248
+ projectId: project.id,
2249
+ title: `QQ ${scope.startsWith("group:") ? "Group" : "Chat"} ${binding.scopeHash.slice(0, 8)}`,
2250
+ modelSelection,
2251
+ runtimeMode: "full-access",
2252
+ interactionMode: "default"
2253
+ })
2254
+ );
2255
+ if (!created?.threadId) throw new Error("T3 did not return threadId when auto-creating a thread");
2256
+ await writeActiveThreadOverride(root, binding.scopeHash, created.threadId);
2257
+ console.info("Auto-created T3 thread for scope", `sha256:${binding.scopeHash.slice(0, 12)}`, created.threadId);
2258
+ return created.threadId;
2259
+ })();
2260
+ threadLocks.set(binding.scopeHash, promise);
2261
+ void promise.catch(() => threadLocks.delete(binding.scopeHash));
2262
+ return promise;
2263
+ }
2264
+ async function sendChunkedReply(reply, text) {
2265
+ const chars = Array.from(text);
2266
+ const maxChars = config.bridge.maxMessageChars;
2267
+ for (let offset = 0; offset < chars.length; offset += maxChars) {
2268
+ await qq.sendText(reply, chars.slice(offset, offset + maxChars).join(""));
2269
+ }
2270
+ }
2271
+ const runSlashForReply = (reply) => createSlashCommandHandler({
2272
+ config,
2273
+ observer,
2274
+ stateDir: root,
2275
+ sendReply: (text) => sendChunkedReply(reply, text),
2276
+ resolveActiveThread: (binding, scope) => resolveThreadForBinding(binding, scope),
2277
+ setActiveThreadOverride: async (binding, nextThreadId) => {
2278
+ threadLocks.delete(binding.scopeHash);
2279
+ await writeActiveThreadOverride(root, binding.scopeHash, nextThreadId);
2280
+ },
2281
+ getThreadConfig: (threadId) => t3Cli.withSession(
2282
+ { scopes: ["orchestration:read"], ttl: "2m", label: "T3 QQBot read thread" },
2283
+ (token) => getThreadState(config.t3.origin, token, threadId)
2284
+ ),
2285
+ setThreadModel: (threadId, modelSelection) => t3Cli.withSession(
2286
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot set model" },
2287
+ (token) => setThreadModelSelection(config.t3.origin, token, threadId, modelSelection)
2288
+ ),
2289
+ createThread: (input) => t3Cli.withSession(
2290
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot create thread" },
2291
+ (token) => createNativeThread(config.t3.origin, token, {
2292
+ ...input,
2293
+ runtimeMode: "full-access",
2294
+ interactionMode: "default"
2295
+ })
2296
+ ),
2297
+ stopThread: (threadId, options2) => t3Cli.withSession(
2298
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot stop thread" },
2299
+ (token) => stopNativeThread(config.t3.origin, token, threadId, options2)
2300
+ ),
2301
+ rollbackTurns: (threadId, turns, restoreFiles) => t3Cli.withSession(
2302
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot rollback" },
2303
+ (token) => rollbackThreadTurns(config.t3.origin, token, threadId, { turns, restoreFiles })
2304
+ ),
2305
+ triggerGracefulRestart: () => {
2306
+ console.info("Triggering graceful restart after /update...");
2307
+ if (options.onRestartRequested) {
2308
+ options.onRestartRequested();
2309
+ } else {
2310
+ process.exit(SELF_UPDATE_EXIT_CODE);
2311
+ }
2312
+ }
2313
+ });
2314
+ async function relayBackground(threadId, runId, taskIds, reply) {
2315
+ const settled = await Promise.allSettled(
2316
+ taskIds.map(async (itemId) => {
2317
+ const receipt = join5(root, digest(`bg\0${runId}\0${itemId}`) + ".delivered");
2318
+ const alreadySent = await readFile5(receipt).then(
2319
+ () => true,
2320
+ (error) => error.code === "ENOENT" ? false : Promise.reject(error)
2321
+ );
2322
+ if (alreadySent) return "";
2323
+ for (let attempt = 0; attempt < 720; attempt++) {
2324
+ if (shutdownController.signal.aborted) return "";
2325
+ try {
2326
+ const item = (await observer.read(threadId, "activity", itemId)).items.find((v) => v.itemId === itemId);
2327
+ if (!item || item.type !== "subagent" || item.runId !== runId) return "";
2328
+ if (TERMINAL_RUN_STATUSES.has(item.status)) {
2329
+ const summary = `${item.title ?? "\u540E\u53F0\u4EFB\u52A1"} \xB7 ${item.status}
2330
+ ${item.text?.trim() ?? ""}`.trim();
2331
+ const target = config.bridge.proactiveBackgroundReports ? { scope: reply.scope, targetId: reply.targetId } : reply;
2332
+ const chars = Array.from(summary);
2333
+ const maxChars = config.bridge.maxMessageChars;
2334
+ for (let offset = 0; offset < chars.length; offset += maxChars) {
2335
+ await qq.sendText(target, chars.slice(offset, offset + maxChars).join(""));
2336
+ }
2337
+ await writeFile3(receipt, "1", { mode: 384 });
2338
+ console.info("QQ background report delivered", runId, itemId);
2339
+ return summary;
2340
+ }
2341
+ } catch (error) {
2342
+ console.warn(
2343
+ "QQ background poll retry",
2344
+ runId,
2345
+ itemId,
2346
+ error instanceof Error ? error.message : String(error)
2347
+ );
2348
+ }
2349
+ await sleep2(5e3, void 0, { signal: shutdownController.signal }).catch(() => {
2350
+ });
2351
+ }
2352
+ throw new Error(`T3 background report observation expired (${itemId})`);
2353
+ })
2354
+ );
2355
+ for (const outcome of settled) {
2356
+ if (outcome.status === "rejected") {
2357
+ console.error("QQ background task relay error", runId, outcome.reason?.message ?? String(outcome.reason));
2358
+ }
2359
+ }
2360
+ }
2361
+ async function observeRun(key, reply, threadId, runId, sequence, live = true, emptyCompletedNotice) {
2362
+ const maxChars = config.bridge.maxMessageChars;
2363
+ const streams = /* @__PURE__ */ new Map();
2364
+ const observedItems = /* @__PURE__ */ new Set();
2365
+ const markFirstText = (item) => {
2366
+ if (!live || observedItems.has(item.id)) return;
2367
+ observedItems.add(item.id);
2368
+ timing("first_text", key, runId, item.id, Date.parse(item.updatedAt), Array.from(item.text).length);
2369
+ };
2370
+ const updateStream = (item) => {
2371
+ markFirstText(item);
2372
+ if (reply.scope !== "c2c" || !live) return;
2373
+ let stream = streams.get(item.id);
2374
+ if (!stream) {
2375
+ const api = new ReplyStreamApi(streamClient, sharedTokenManager, key, runId, item.id, timing);
2376
+ const session = new StreamSession(api, {
2377
+ openid: reply.targetId,
2378
+ msgId: reply.msgId,
2379
+ creds: { appId: credentials.appId, clientSecret: credentials.appSecret },
2380
+ logger: {
2381
+ info: () => {
2382
+ },
2383
+ error: () => {
2384
+ const current = streams.get(item.id);
2385
+ if (current && !current.finishing && !current.api.hasLiveBubble) {
2386
+ current.failedBeforeLive = true;
2387
+ current.session.cancel();
2388
+ console.info("QQ streaming unavailable before first frame, falling back to normal text", key, runId);
2389
+ }
2390
+ }
2391
+ }
2392
+ });
2393
+ stream = { session, api, failedBeforeLive: false, finishing: false, lastQueued: "" };
2394
+ streams.set(item.id, stream);
2395
+ }
2396
+ if (!stream.failedBeforeLive) {
2397
+ const clipped = Array.from(item.text).slice(0, maxChars).join("");
2398
+ if (clipped !== stream.lastQueued) {
2399
+ stream.lastQueued = clipped;
2400
+ void stream.session.update(clipped).catch(() => {
2401
+ });
2402
+ }
2403
+ }
2404
+ };
2405
+ const sendMessage = async (item) => {
2406
+ markFirstText(item);
2407
+ if (live) timing("text_completed", key, runId, item.id, Date.parse(item.updatedAt));
2408
+ const chars = Array.from(item.text);
2409
+ const sendStarted = Date.now();
2410
+ let sentCount = 0;
2411
+ const stream = streams.get(item.id);
2412
+ for (let offset = 0; offset < chars.length; offset += maxChars) {
2413
+ const receipt = join5(root, digest(`${runId}\0${item.id}\0${offset}`) + ".delivered");
2414
+ const alreadySent = await readFile5(receipt).then(
2415
+ () => true,
2416
+ (error) => {
2417
+ if (error.code === "ENOENT") return false;
2418
+ throw error;
2419
+ }
2420
+ );
2421
+ if (alreadySent) continue;
2422
+ const content = chars.slice(offset, offset + maxChars).join("");
2423
+ let sent;
2424
+ if (offset === 0 && stream && !stream.failedBeforeLive) {
2425
+ stream.finishing = true;
2426
+ try {
2427
+ if (stream.lastQueued !== content) {
2428
+ stream.lastQueued = content;
2429
+ stream.session.pendingText = content;
2430
+ }
2431
+ sent = await stream.session.complete();
2432
+ } catch {
2433
+ console.info("QQ stream completion failed, falling back to normal text", key, runId);
2434
+ }
2435
+ }
2436
+ sent = sent?.id ? sent : await qq.sendText(reply, content);
2437
+ if (!sent?.id) throw new Error("QQ did not confirm the text reply");
2438
+ await writeFile3(receipt, sent.id, { mode: 384 });
2439
+ sentCount++;
2440
+ }
2441
+ if (sentCount) {
2442
+ console.info(
2443
+ "QQ text delivered",
2444
+ key,
2445
+ runId,
2446
+ "chars",
2447
+ chars.length,
2448
+ "QQ request ms",
2449
+ Date.now() - sendStarted,
2450
+ "last T3 body to QQ ms",
2451
+ Date.now() - Date.parse(item.updatedAt)
2452
+ );
2453
+ }
2454
+ };
2455
+ const result = await t3Cli.withSession(
2456
+ { scopes: ["orchestration:read"], ttl: "45m", label: "T3 QQBot reply" },
2457
+ (token) => readReply(config.t3.origin, token, threadId, runId, {
2458
+ afterSequence: sequence,
2459
+ signal: shutdownController.signal,
2460
+ onMessage: async (item) => {
2461
+ try {
2462
+ await sendMessage(item);
2463
+ } catch (error) {
2464
+ console.error(
2465
+ "QQ reply delivery failed",
2466
+ key,
2467
+ runId,
2468
+ error instanceof Error ? error.message : "unknown error"
2469
+ );
2470
+ throw error;
2471
+ }
2472
+ },
2473
+ onUpdate: updateStream,
2474
+ onTerminal: (run) => {
2475
+ if (live) timing("run_terminal", key, runId, run.status, run.completedAt ?? "-");
2476
+ }
2477
+ })
2478
+ ).finally(() => {
2479
+ for (const stream of streams.values()) stream.session.cancel();
2480
+ });
2481
+ if (!result.body) {
2482
+ console.info("T3 finished without a text reply", key, runId, result.status);
2483
+ if (result.status !== "completed") {
2484
+ const statusText = result.status === "interrupted" ? "\u5DF2\u4E2D\u65AD" : `\u72B6\u6001\uFF1A${result.status}`;
2485
+ await qq.sendText(reply, `T3 Code \u672C\u8F6E\u4EFB\u52A1\u672A\u5B8C\u6210\uFF08${statusText}\uFF09\uFF0C\u8BF7\u5728 T3 Code \u4E2D\u67E5\u770B\u8BE6\u60C5\u3002`).catch(
2486
+ () => {
2487
+ }
2488
+ );
2489
+ } else if (emptyCompletedNotice) {
2490
+ await qq.sendText(reply, emptyCompletedNotice).catch(() => {
2491
+ });
2492
+ }
2493
+ }
2494
+ if (result.status === "completed" && result.backgroundTaskIds.length) {
2495
+ void relayBackground(threadId, runId, result.backgroundTaskIds, reply).catch(
2496
+ (error) => console.error("QQ background report failed", runId, error instanceof Error ? error.message : String(error))
2497
+ );
2498
+ }
2499
+ if (config.bridge.autoSettleThread && result.status === "completed" && !result.backgroundTaskIds.length) {
2500
+ void t3Cli.withSession(
2501
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot settle" },
2502
+ (token) => settleNativeThread(config.t3.origin, token, threadId)
2503
+ ).catch(() => {
2504
+ });
2505
+ }
2506
+ }
2507
+ async function relay(event, target, binding, scope) {
2508
+ const key = digest(`${scope}\0${event.id}`);
2509
+ const reply = {
2510
+ scope: target.kind === "users" ? "c2c" : "group",
2511
+ targetId: target.id,
2512
+ msgId: event.id
2513
+ };
2514
+ const receipt = join5(root, key + ".received");
2515
+ try {
2516
+ await writeFile3(receipt, "", { flag: "wx", mode: 384 });
2517
+ } catch (error) {
2518
+ if (error.code === "EEXIST") return;
2519
+ throw error;
2520
+ }
2521
+ if (!event.content?.trim() && !event.attachments?.length) {
2522
+ await qq.sendText(reply, "\u8BF7\u8F93\u5165\u6D88\u606F\u6B63\u6587\uFF0C\u6216\u9644\u4E0A\u8981\u53D1\u9001\u7684\u6587\u4EF6\u3002");
2523
+ return;
2524
+ }
2525
+ let emptyCompletedNotice;
2526
+ if (config.bridge.enableSlashCommands) {
2527
+ const slash = parseSlashCommand(event.content ?? "", Boolean(event.attachments?.length));
2528
+ if (slash) {
2529
+ try {
2530
+ const outcome = await runSlashForReply(reply)(slash, binding, scope);
2531
+ if (outcome === "handled") {
2532
+ console.info("QQ slash command handled", slash.name, key);
2533
+ return;
2534
+ }
2535
+ if (slash.name === "compact") {
2536
+ emptyCompletedNotice = "\u5F53\u524D T3 \u4F1A\u8BDD\u4E0A\u4E0B\u6587\u538B\u7F29\u5DF2\u5B8C\u6210\u3002";
2537
+ }
2538
+ } catch (error) {
2539
+ const msg = error instanceof Error ? error.message : String(error);
2540
+ console.error("QQ slash command failed", slash.name, msg);
2541
+ await qq.sendText(reply, `\u6307\u4EE4 /${slash.name} \u6267\u884C\u5931\u8D25\uFF1A${msg}`).catch(() => {
2542
+ });
2543
+ return;
2544
+ }
2545
+ }
2546
+ }
2547
+ const rawAttachments = event.attachments ?? [];
2548
+ if (rawAttachments.length > MAX_ATTACHMENTS_PER_MESSAGE) {
2549
+ await unlink2(receipt).catch(() => {
2550
+ });
2551
+ await qq.sendText(reply, `\u5355\u6761\u6D88\u606F\u6700\u591A\u652F\u6301 ${MAX_ATTACHMENTS_PER_MESSAGE} \u4E2A\u9644\u4EF6\uFF0C\u8BF7\u5206\u6279\u53D1\u9001\u3002`).catch(() => {
2552
+ });
2553
+ return;
2554
+ }
2555
+ const stopTyping = startTypingKeepalive(reply, (target2, sec) => qq.sendTyping(target2, sec), {
2556
+ durationSec: 60,
2557
+ intervalMs: 5e4,
2558
+ signal: shutdownController.signal
2559
+ });
2560
+ try {
2561
+ const uploadedAttachments = [];
2562
+ let threadId;
2563
+ let accepted;
2564
+ try {
2565
+ const attachmentDir = join5(binding.workspace, "attachments", key);
2566
+ const allowedHosts = new Set(config.attachmentHosts);
2567
+ const files = [];
2568
+ for (let index = 0; index < rawAttachments.length; index++) {
2569
+ const item = rawAttachments[index];
2570
+ const saved = item.stagedName && config.bridge.testStaging ? await copyStagedAttachment(config.bridge.testStaging, item.stagedName, attachmentDir, index) : await saveAttachment(item, attachmentDir, index, allowedHosts);
2571
+ files.push(saved);
2572
+ }
2573
+ threadId = await resolveThreadForBinding(binding, scope);
2574
+ for (const file of files) {
2575
+ const mime = mimeFromExtension(file.path);
2576
+ uploadedAttachments.push(await observer.upload(file.path, basename2(file.path), mime));
2577
+ }
2578
+ accepted = await t3Cli.withSession(
2579
+ { scopes: ["orchestration:read", "orchestration:operate"], ttl: "2m", label: "T3 QQBot delivery" },
2580
+ (token) => dispatchMessage(config.t3.origin, token, {
2581
+ threadId,
2582
+ key,
2583
+ text: event.content ?? "",
2584
+ attachments: uploadedAttachments
2585
+ })
2586
+ );
2587
+ } catch (error) {
2588
+ await unlink2(receipt).catch(() => {
2589
+ });
2590
+ for (const att of uploadedAttachments) {
2591
+ await observer.call("t3_attachment_discard", { attachmentId: att.id }).catch(() => {
2592
+ });
2593
+ }
2594
+ await qq.sendText(reply, "T3 Code \u6682\u65F6\u65E0\u6CD5\u5904\u7406\u8FD9\u6761\u6D88\u606F\uFF0C\u8BF7\u68C0\u67E5\u672C\u5730 T3 \u670D\u52A1\u4E0E\u65E5\u5FD7\u3002").catch(() => {
2595
+ });
2596
+ throw error;
2597
+ }
2598
+ const record = {
2599
+ key,
2600
+ scope,
2601
+ scopeHash: binding.scopeHash,
2602
+ reply,
2603
+ thread: threadId,
2604
+ runId: accepted.runId,
2605
+ workspace: binding.workspace,
2606
+ sequence: accepted.sequence
2607
+ };
2608
+ await writeFile3(join5(root, digest(accepted.runId) + ".run.json"), JSON.stringify(record), { mode: 384 });
2609
+ timing("dispatch_ack", key, accepted.runId);
2610
+ console.info("T3 accepted", key, threadId, accepted.runId);
2611
+ await observeRun(key, reply, threadId, accepted.runId, accepted.sequence, true, emptyCompletedNotice);
2612
+ } finally {
2613
+ stopTyping();
2614
+ }
2615
+ }
2616
+ const checkHealth = options.checkT3Health ?? (async () => {
2617
+ try {
2618
+ const probe = await fetch(config.t3.origin, { signal: AbortSignal.timeout(2e3) });
2619
+ await probe.body?.cancel();
2620
+ return probe.ok;
2621
+ } catch {
2622
+ return false;
2623
+ }
2624
+ });
2625
+ let server = null;
2626
+ if (options.listen !== false) {
2627
+ const handleRequest = async (req, res) => {
2628
+ if (req.method === "GET" && (req.url === "/health" || req.url === "/ready")) {
2629
+ const t3Running = await checkHealth();
2630
+ const ready = t3Running && (req.url !== "/ready" || config.bindings.length > 0);
2631
+ res.writeHead(ready ? 200 : 503, { "Content-Type": "application/json" });
2632
+ res.end(
2633
+ JSON.stringify({
2634
+ ok: ready,
2635
+ t3Origin: config.t3.origin,
2636
+ bindings: config.bindings.length
2637
+ })
2638
+ );
2639
+ return;
2640
+ }
2641
+ if (req.method !== "POST" || req.url !== "/events") {
2642
+ res.writeHead(404).end();
2643
+ return;
2644
+ }
2645
+ const authHeader = typeof req.headers.authorization === "string" ? req.headers.authorization : "";
2646
+ if (!timingSafeEqual(digestBuffer(authHeader), expectedAuthDigest)) {
2647
+ res.writeHead(401).end();
2648
+ return;
2649
+ }
2650
+ try {
2651
+ let size = 0;
2652
+ const parts = [];
2653
+ for await (const part of req) {
2654
+ const chunk = Buffer.isBuffer(part) ? part : Buffer.from(part);
2655
+ if ((size += chunk.length) > 256e3) {
2656
+ res.writeHead(413).end();
2657
+ return;
2658
+ }
2659
+ parts.push(chunk);
2660
+ }
2661
+ const { t, d } = JSON.parse(Buffer.concat(parts).toString("utf8"));
2662
+ if (t !== "GROUP_AT_MESSAGE_CREATE" && t !== "C2C_MESSAGE_CREATE") {
2663
+ res.writeHead(204).end();
2664
+ return;
2665
+ }
2666
+ const group = t === "GROUP_AT_MESSAGE_CREATE";
2667
+ const id = group ? d?.group_openid : d?.author?.user_openid;
2668
+ if (!id || typeof id !== "string" || !d?.id || typeof d.id !== "string" || d.content !== void 0 && typeof d.content !== "string" || d.attachments !== void 0 && !Array.isArray(d.attachments)) {
2669
+ res.writeHead(400).end();
2670
+ return;
2671
+ }
2672
+ const scope = `${group ? "group" : "c2c"}:${id}`;
2673
+ const binding = findBindingForScope(config, scope);
2674
+ if (!binding) {
2675
+ console.warn(
2676
+ `[unbound] Ignored message from "${scope}" (sha256:${digest(scope)}). Add this scope to "bindings" in ${config.configPath} to enable it.`
2677
+ );
2678
+ res.writeHead(403).end();
2679
+ return;
2680
+ }
2681
+ res.writeHead(202).end();
2682
+ const key = digest(`${scope}\0${d.id}`);
2683
+ timing("bridge_ingress", key, "-");
2684
+ const runner = options.onAccepted ?? relay;
2685
+ void runner(d, { kind: group ? "groups" : "users", id }, binding, scope).catch(
2686
+ (error) => console.error(key, error instanceof Error ? error.message : String(error))
2687
+ );
2688
+ } catch {
2689
+ res.writeHead(400).end();
2690
+ }
2691
+ };
2692
+ server = createServer((req, res) => {
2693
+ void handleRequest(req, res);
2694
+ });
2695
+ await new Promise((resolveListen, rejectListen) => {
2696
+ server.once("error", rejectListen);
2697
+ server.listen(config.bridge.port, config.bridge.host, () => {
2698
+ server.off("error", rejectListen);
2699
+ resolveListen();
2700
+ });
2701
+ });
2702
+ }
2703
+ return {
2704
+ server,
2705
+ observeRun,
2706
+ close: async () => {
2707
+ shutdownController.abort();
2708
+ await observer.close().catch(() => {
2709
+ });
2710
+ if (server) {
2711
+ await new Promise((resolveClose, rejectClose) => {
2712
+ server.close((error) => error ? rejectClose(error) : resolveClose());
2713
+ });
2714
+ }
2715
+ for (const level of ["info", "warn", "error"]) {
2716
+ if (originalConsole[level]) {
2717
+ console[level] = originalConsole[level];
2718
+ }
2719
+ }
2720
+ }
2721
+ };
2722
+ }
2723
+ async function runBridgeCli(argv = process.argv.slice(2)) {
2724
+ const configPath = argv[0] || process.env.T3_QQBOT_CONFIG || resolve4("config.json");
2725
+ const config = await loadConfig(configPath);
2726
+ const credentials = await loadCredentials(config);
2727
+ if (argv[1] === "--recover") {
2728
+ const runId = argv[2];
2729
+ if (!runId) throw new Error("Recovery requires an existing T3 run ID: --recover <runId>");
2730
+ const runtime2 = await createBridgeRuntime(config, credentials, { listen: false });
2731
+ try {
2732
+ const recordPath = join5(config.stateDir, digest(runId) + ".run.json");
2733
+ const record = JSON.parse(await readFile5(recordPath, "utf8"));
2734
+ if (record.runId !== runId) throw new Error("Recovery runId mismatch");
2735
+ await runtime2.observeRun(record.key, record.reply, record.thread, record.runId, record.sequence, false);
2736
+ console.info("Recovery completed for run", runId);
2737
+ } finally {
2738
+ await runtime2.close();
2739
+ }
2740
+ return;
2741
+ }
2742
+ let runtime;
2743
+ runtime = await createBridgeRuntime(config, credentials, {
2744
+ listen: true,
2745
+ onRestartRequested: () => {
2746
+ console.info(`Restarting T3 QQBot bridge after self-update (exit code ${SELF_UPDATE_EXIT_CODE})...`);
2747
+ void runtime.close().finally(() => process.exit(SELF_UPDATE_EXIT_CODE));
2748
+ }
2749
+ });
2750
+ const address = runtime.server?.address();
2751
+ const port = typeof address === "object" && address ? address.port : config.bridge.port;
2752
+ console.info(
2753
+ `T3 QQBot bridge listening on http://${config.bridge.host}:${port} (${config.bindings.length} binding(s))`
2754
+ );
2755
+ const shutdown = () => {
2756
+ console.info("Shutting down T3 QQBot bridge...");
2757
+ void runtime.close().finally(() => process.exit(0));
2758
+ };
2759
+ process.once("SIGINT", shutdown);
2760
+ process.once("SIGTERM", shutdown);
2761
+ }
2762
+ if (isMainModule(import.meta.url)) {
2763
+ runBridgeCli().catch((error) => {
2764
+ console.error(error instanceof Error ? error.message : String(error));
2765
+ process.exit(1);
2766
+ });
2767
+ }
2768
+ export {
2769
+ createBridgeRuntime,
2770
+ runBridgeCli,
2771
+ startTypingKeepalive
2772
+ };