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