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.
@@ -0,0 +1,865 @@
1
+ // src/publish.ts
2
+ import { readFile as readFile4, realpath as realpath2 } from "node:fs/promises";
3
+ import { join as join4, resolve as resolve3 } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import { QQBot } from "@tencent-connect/qqbot-nodejs";
6
+
7
+ // src/config.ts
8
+ import { realpathSync } from "node:fs";
9
+ import { access, readFile } from "node:fs/promises";
10
+ import path, { dirname, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ // src/protocol.ts
14
+ import { createHash } from "node:crypto";
15
+ import { copyFile, mkdir, realpath, stat, writeFile } from "node:fs/promises";
16
+ import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
17
+ var MAX_ATTACHMENT_BYTES = 12 * 1024 * 1024;
18
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
19
+ function isInsideBase(base, candidate) {
20
+ const rel = relative(base, candidate);
21
+ return Boolean(rel) && rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel);
22
+ }
23
+ async function safeArtifact(root, file) {
24
+ if (!file || typeof file !== "string" || file.includes("\0")) {
25
+ throw new Error("Invalid artifact path");
26
+ }
27
+ if (/^(\\\\|\/\/)/.test(file)) {
28
+ throw new Error("Artifact is outside this workspace directory");
29
+ }
30
+ const base = await realpath(root);
31
+ const lexicalCandidate = resolve(base, file);
32
+ if (/^(\\\\|\/\/)/.test(lexicalCandidate) || !isInsideBase(base, lexicalCandidate)) {
33
+ throw new Error("Artifact is outside this workspace directory");
34
+ }
35
+ const localPath = await realpath(lexicalCandidate);
36
+ if (!isInsideBase(base, localPath)) {
37
+ throw new Error("Artifact is outside this workspace directory");
38
+ }
39
+ const info = await stat(localPath);
40
+ if (!info.isFile() || info.size <= 0 || info.size > MAX_ATTACHMENT_BYTES) {
41
+ throw new Error("Invalid artifact size or type");
42
+ }
43
+ const extension = extname(localPath).toLowerCase();
44
+ const fileType = [".png", ".jpg", ".jpeg"].includes(extension) ? 1 : extension === ".silk" ? 3 : 4;
45
+ return { localPath, fileType, fileName: basename(localPath) };
46
+ }
47
+
48
+ // src/config.ts
49
+ var APP_VERSION = "1.2.2";
50
+ var DEFAULT_ATTACHMENT_HOSTS = [
51
+ "multimedia.nt.qq.com.cn",
52
+ "multimedia.nt.qq.com",
53
+ "gchat.qpic.cn",
54
+ "c2cpicdw.qpic.cn"
55
+ ];
56
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
57
+ function isMainModule(metaUrl, argv1 = process.argv[1]) {
58
+ if (!argv1) return false;
59
+ const resolved = resolve2(argv1);
60
+ if (metaUrl === pathToFileURL(resolved).href) return true;
61
+ try {
62
+ return metaUrl === pathToFileURL(realpathSync(resolved)).href;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ function isLoopbackOrigin(origin) {
68
+ try {
69
+ const url = new URL(origin);
70
+ return (url.protocol === "http:" || url.protocol === "https:") && LOOPBACK_HOSTS.has(url.hostname);
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ function normalizePathForCompare(targetPath, platform = process.platform) {
76
+ const pathImpl = platform === "win32" ? path.win32 : path.posix;
77
+ const normalized = pathImpl.resolve(targetPath);
78
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
79
+ }
80
+ function isSameOrInsidePath(candidate, parent, platform = process.platform) {
81
+ const pathImpl = platform === "win32" ? path.win32 : path.posix;
82
+ const normCandidate = normalizePathForCompare(candidate, platform);
83
+ const normParent = normalizePathForCompare(parent, platform);
84
+ if (normCandidate === normParent) return true;
85
+ const rel = pathImpl.relative(normParent, normCandidate);
86
+ return Boolean(rel) && rel !== ".." && !rel.startsWith(".." + pathImpl.sep) && !pathImpl.isAbsolute(rel);
87
+ }
88
+ function scopeToHash(scope) {
89
+ const trimmed = scope.trim();
90
+ if (/^sha256:[a-f0-9]{64}$/i.test(trimmed)) {
91
+ return trimmed.slice("sha256:".length).toLowerCase();
92
+ }
93
+ if (!/^(c2c|group):.+$/i.test(trimmed)) {
94
+ throw new Error(
95
+ `Invalid binding scope "${scope}". Expected "c2c:<user_openid>", "group:<group_openid>", or "sha256:<64-hex>".`
96
+ );
97
+ }
98
+ return digest(trimmed);
99
+ }
100
+ function resolveRelative(baseDir, maybeRelative) {
101
+ return isAbsolute2(maybeRelative) ? resolve2(maybeRelative) : resolve2(baseDir, maybeRelative);
102
+ }
103
+ function parseConfig(raw, configPath) {
104
+ const absConfigPath = resolve2(configPath);
105
+ const configDir = dirname(absConfigPath);
106
+ if (!raw || typeof raw !== "object") {
107
+ throw new Error("Config must be a JSON object");
108
+ }
109
+ if (!raw.stateDir || typeof raw.stateDir !== "string") {
110
+ throw new Error('Config requires "stateDir"');
111
+ }
112
+ if (!raw.t3?.origin || typeof raw.t3.origin !== "string") {
113
+ throw new Error('Config requires "t3.origin"');
114
+ }
115
+ if (!isLoopbackOrigin(raw.t3.origin)) {
116
+ throw new Error(`Config "t3.origin" must target loopback (127.0.0.1 / localhost / ::1), got: ${raw.t3.origin}`);
117
+ }
118
+ const port = raw.bridge?.port ?? 18773;
119
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
120
+ throw new Error(`Invalid bridge port: ${port}`);
121
+ }
122
+ const host = raw.bridge?.host ?? "127.0.0.1";
123
+ if (!LOOPBACK_HOSTS.has(host)) {
124
+ throw new Error(`Bridge host must be loopback for security, got: ${host}`);
125
+ }
126
+ const maxMessageChars = raw.bridge?.maxMessageChars ?? 1600;
127
+ if (!Number.isInteger(maxMessageChars) || maxMessageChars < 100 || maxMessageChars > 4e3) {
128
+ throw new Error(`Invalid bridge.maxMessageChars (${maxMessageChars}); expected integer between 100 and 4000`);
129
+ }
130
+ const rawBindings = Array.isArray(raw.bindings) ? raw.bindings : [];
131
+ const bindings = rawBindings.map((binding, index) => {
132
+ if (!binding || typeof binding.scope !== "string" || !binding.scope.trim()) {
133
+ throw new Error(`Binding #${index} is missing "scope"`);
134
+ }
135
+ if (typeof binding.workspace !== "string" || !binding.workspace.trim()) {
136
+ throw new Error(`Binding #${index} (${binding.scope}) is missing "workspace"`);
137
+ }
138
+ const threadId = typeof binding.threadId === "string" && binding.threadId.trim() && !binding.threadId.startsWith("REPLACE_WITH_") ? binding.threadId.trim() : void 0;
139
+ return {
140
+ rawScope: binding.scope.trim(),
141
+ scopeHash: scopeToHash(binding.scope),
142
+ workspace: resolveRelative(configDir, binding.workspace.trim()),
143
+ threadId,
144
+ modelSelection: binding.modelSelection
145
+ };
146
+ });
147
+ const bridgeUrl = raw.gateway?.bridgeUrl?.trim() || `http://${host === "::1" ? "[::1]" : host}:${port}/events`;
148
+ return {
149
+ configPath: absConfigPath,
150
+ configDir,
151
+ stateDir: resolveRelative(configDir, raw.stateDir),
152
+ credentialsFile: raw.credentialsFile ? resolveRelative(configDir, raw.credentialsFile) : void 0,
153
+ t3: {
154
+ origin: raw.t3.origin.trim(),
155
+ executable: raw.t3.executable?.trim() || "auto",
156
+ prefix: Array.isArray(raw.t3.prefix) ? raw.t3.prefix.map(String) : [],
157
+ env: raw.t3.env && typeof raw.t3.env === "object" ? { ...raw.t3.env } : {},
158
+ home: raw.t3.home ? resolveRelative(configDir, raw.t3.home) : void 0,
159
+ muteMobileCompletionThreadId: raw.t3.muteMobileCompletionThreadId?.trim() || void 0
160
+ },
161
+ bridge: {
162
+ host,
163
+ port,
164
+ proactiveBackgroundReports: Boolean(raw.bridge?.proactiveBackgroundReports),
165
+ maxMessageChars,
166
+ autoSettleThread: Boolean(raw.bridge?.autoSettleThread),
167
+ enableSlashCommands: raw.bridge?.enableSlashCommands ?? true,
168
+ testStaging: raw.bridge?.testStaging ? resolveRelative(configDir, raw.bridge.testStaging) : void 0
169
+ },
170
+ gateway: {
171
+ bridgeUrl,
172
+ requireMentionInGroup: raw.gateway?.requireMentionInGroup ?? true,
173
+ stripPrefix: raw.gateway?.stripPrefix ?? ""
174
+ },
175
+ attachmentHosts: Array.isArray(raw.attachmentHosts) && raw.attachmentHosts.length > 0 ? raw.attachmentHosts.map((h) => String(h).trim().toLowerCase()).filter(Boolean) : [...DEFAULT_ATTACHMENT_HOSTS],
176
+ bindings
177
+ };
178
+ }
179
+ async function loadConfig(configPath) {
180
+ const rawText = await readFile(configPath, "utf8");
181
+ const parsed = JSON.parse(rawText.replace(/^\uFEFF/, ""));
182
+ return parseConfig(parsed, configPath);
183
+ }
184
+ async function loadCredentials(config, env = process.env, options = {}) {
185
+ const requireBridgeSecret = options.requireBridgeSecret ?? true;
186
+ const envAppId = env.QQ_APP_ID?.trim() || "";
187
+ const envAppSecret = env.QQ_APP_SECRET?.trim() || "";
188
+ const envBridgeSecret = env.QQ_BRIDGE_SECRET?.trim() || "";
189
+ const explicitCredsFile = env.QQ_CREDENTIALS_FILE?.trim();
190
+ const envHasAll = Boolean(envAppId && envAppSecret && (!requireBridgeSecret || envBridgeSecret));
191
+ let fileCreds = {};
192
+ const credentialsPath = explicitCredsFile || (envHasAll ? void 0 : config.credentialsFile);
193
+ if (credentialsPath) {
194
+ try {
195
+ const raw = await readFile(credentialsPath, "utf8");
196
+ fileCreds = JSON.parse(raw.replace(/^\uFEFF/, ""));
197
+ } catch (error) {
198
+ if (error.code === "ENOENT" && !explicitCredsFile && envHasAll) {
199
+ fileCreds = {};
200
+ } else {
201
+ throw error;
202
+ }
203
+ }
204
+ }
205
+ const appId = envAppId || fileCreds.appId?.trim() || "";
206
+ const appSecret = envAppSecret || fileCreds.appSecret?.trim() || "";
207
+ const bridgeSecret = envBridgeSecret || fileCreds.bridgeSecret?.trim() || "";
208
+ if (!appId || !appSecret || requireBridgeSecret && !bridgeSecret) {
209
+ const missing = requireBridgeSecret ? "appId, appSecret, bridgeSecret" : "appId, appSecret";
210
+ throw new Error(
211
+ `Missing QQ Bot credentials (${missing}). Set them in credentials.json or environment variables.`
212
+ );
213
+ }
214
+ if (appId.startsWith("REPLACE_WITH_") || appSecret.startsWith("REPLACE_WITH_") || requireBridgeSecret && bridgeSecret.startsWith("REPLACE_WITH_")) {
215
+ throw new Error("Credentials still contain REPLACE_WITH_* placeholder values. Edit credentials.json first.");
216
+ }
217
+ return { appId, appSecret, bridgeSecret };
218
+ }
219
+
220
+ // src/observe.ts
221
+ import { readFile as readFile2 } from "node:fs/promises";
222
+ var McpHttpError = class extends Error {
223
+ status;
224
+ constructor(method, status) {
225
+ super(`T3 MCP ${method} HTTP ${status}`);
226
+ this.status = status;
227
+ }
228
+ };
229
+ var Observer = class {
230
+ state = null;
231
+ connecting;
232
+ id = 0;
233
+ url;
234
+ issue;
235
+ revoke;
236
+ constructor(origin, issue, revoke) {
237
+ this.url = new URL("/mcp", origin).href;
238
+ this.issue = issue;
239
+ this.revoke = revoke;
240
+ }
241
+ async rpcWith(token, sessionId, method, params, notification = false) {
242
+ const response = await fetch(this.url, {
243
+ method: "POST",
244
+ signal: AbortSignal.timeout(15e3),
245
+ headers: {
246
+ Authorization: `Bearer ${token}`,
247
+ "Content-Type": "application/json",
248
+ Accept: "application/json, text/event-stream",
249
+ ...sessionId ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-06-18" } : {}
250
+ },
251
+ body: JSON.stringify({
252
+ jsonrpc: "2.0",
253
+ method,
254
+ params,
255
+ ...!notification ? { id: ++this.id } : {}
256
+ })
257
+ });
258
+ if (!response.ok) {
259
+ await response.body?.cancel().catch(() => {
260
+ });
261
+ throw new McpHttpError(method, response.status);
262
+ }
263
+ const newSessionId = method === "initialize" ? response.headers.get("mcp-session-id") : void 0;
264
+ if (notification) {
265
+ await response.body?.cancel().catch(() => {
266
+ });
267
+ return { newSessionId };
268
+ }
269
+ const contentType = response.headers.get("content-type") ?? "";
270
+ let body;
271
+ if (contentType.includes("text/event-stream")) {
272
+ const text = await response.text();
273
+ const dataLine = text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).filter(Boolean).at(-1);
274
+ if (!dataLine) throw new Error(`T3 MCP ${method} returned empty SSE stream`);
275
+ body = JSON.parse(dataLine);
276
+ } else {
277
+ body = await response.json();
278
+ }
279
+ if (body.error) {
280
+ throw new Error(
281
+ `T3 MCP ${method} error ${body.error.code}${body.error.message ? `: ${body.error.message}` : ""}`
282
+ );
283
+ }
284
+ return { result: body.result, newSessionId };
285
+ }
286
+ async connect(force = false) {
287
+ if (!force && this.state && Date.now() < this.state.renewAt) {
288
+ return this.state;
289
+ }
290
+ if (!this.connecting) {
291
+ const previousAuthId = this.state?.authSessionId;
292
+ this.connecting = (async () => {
293
+ const issued = await this.issue();
294
+ if (!issued.token) throw new Error("T3 MCP session returned no bearer token");
295
+ const init = await this.rpcWith(issued.token, null, "initialize", {
296
+ protocolVersion: "2025-06-18",
297
+ capabilities: {},
298
+ clientInfo: { name: "t3-code-qqbot", version: APP_VERSION }
299
+ });
300
+ if (!init.newSessionId) throw new Error("T3 MCP did not return an mcp-session-id header");
301
+ await this.rpcWith(issued.token, init.newSessionId, "notifications/initialized", void 0, true);
302
+ const next = {
303
+ token: issued.token,
304
+ sessionId: init.newSessionId,
305
+ authSessionId: issued.sessionId,
306
+ renewAt: Date.now() + 50 * 6e4
307
+ };
308
+ this.state = next;
309
+ if (previousAuthId && previousAuthId !== issued.sessionId && this.revoke) {
310
+ void this.revoke(previousAuthId).catch(() => {
311
+ });
312
+ }
313
+ return next;
314
+ })().finally(() => {
315
+ this.connecting = void 0;
316
+ });
317
+ }
318
+ return this.connecting;
319
+ }
320
+ async close() {
321
+ const authId = this.state?.authSessionId;
322
+ this.state = null;
323
+ if (authId && this.revoke) {
324
+ await this.revoke(authId).catch(() => {
325
+ });
326
+ }
327
+ }
328
+ async callWithSession(name, args) {
329
+ let session = await this.connect(false);
330
+ let result;
331
+ try {
332
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
333
+ } catch (error) {
334
+ if (error instanceof McpHttpError && (error.status === 401 || error.status === 404)) {
335
+ if (this.state === session) this.state = null;
336
+ session = await this.connect(true);
337
+ ({ result } = await this.rpcWith(session.token, session.sessionId, "tools/call", { name, arguments: args }));
338
+ } else {
339
+ throw error;
340
+ }
341
+ }
342
+ if (result?.isError) {
343
+ const detail = result?.content?.[0]?.text ? `: ${String(result.content[0].text)}` : "";
344
+ throw new Error(`T3 MCP tool rejected (${name})${detail}`);
345
+ }
346
+ if (result?.structuredContent !== void 0) {
347
+ return { data: result.structuredContent, session };
348
+ }
349
+ const text = result?.content?.[0]?.text;
350
+ if (typeof text !== "string") {
351
+ throw new Error(`T3 MCP tool (${name}) returned empty content`);
352
+ }
353
+ return { data: JSON.parse(text), session };
354
+ }
355
+ async call(name, args) {
356
+ const { data } = await this.callWithSession(name, args);
357
+ return data;
358
+ }
359
+ async upload(filePath, name, mimeType) {
360
+ const bytes = await readFile2(filePath);
361
+ const attachment = {
362
+ name,
363
+ mimeType,
364
+ sizeBytes: bytes.length,
365
+ type: /^image\/(png|jpeg|webp|gif)$/.test(mimeType) ? "image" : "file"
366
+ };
367
+ const { data: staged, session } = await this.callWithSession("t3_attachment_prepare_upload", { upload: attachment });
368
+ try {
369
+ const endpoint = new URL(staged.uploadUrl ?? staged.relativeUrl, this.url);
370
+ if (endpoint.origin !== new URL(this.url).origin) {
371
+ throw new Error("Unexpected T3 attachment upload origin");
372
+ }
373
+ const response = await fetch(endpoint, {
374
+ method: "POST",
375
+ signal: AbortSignal.timeout(3e4),
376
+ redirect: "error",
377
+ headers: {
378
+ Authorization: `Bearer ${session.token}`,
379
+ "Content-Type": mimeType
380
+ },
381
+ body: bytes
382
+ });
383
+ if (!response.ok) {
384
+ await response.body?.cancel().catch(() => {
385
+ });
386
+ throw new Error(`T3 native attachment upload HTTP ${response.status}`);
387
+ }
388
+ await response.body?.cancel().catch(() => {
389
+ });
390
+ return { ...attachment, id: staged.attachmentId };
391
+ } catch (error) {
392
+ await this.call("t3_attachment_discard", { attachmentId: staged.attachmentId }).catch(() => {
393
+ });
394
+ throw error;
395
+ }
396
+ }
397
+ async read(threadId, view = "messages", itemId) {
398
+ return this.call("t3_thread_read", {
399
+ threadId,
400
+ view,
401
+ itemId,
402
+ limit: 40,
403
+ runLimit: 50,
404
+ maxCharsPerItem: 2e4
405
+ });
406
+ }
407
+ };
408
+
409
+ // src/t3-cli.ts
410
+ import { execFile } from "node:child_process";
411
+ import { access as access2, readFile as readFile3 } from "node:fs/promises";
412
+ import { homedir } from "node:os";
413
+ import { dirname as dirname2, join as join3 } from "node:path";
414
+ var STRIPPED_ENV_KEYS = /* @__PURE__ */ new Set([
415
+ "QQ_BRIDGE_SECRET",
416
+ "QQ_APP_ID",
417
+ "QQ_APP_SECRET",
418
+ "QQ_CREDENTIALS_FILE"
419
+ ]);
420
+ async function fileExists(path2) {
421
+ try {
422
+ await access2(path2);
423
+ return true;
424
+ } catch {
425
+ return false;
426
+ }
427
+ }
428
+ function getEnvCaseInsensitive(env, name) {
429
+ if (env[name] !== void 0) return env[name];
430
+ const target = name.toUpperCase();
431
+ for (const [k, v] of Object.entries(env)) {
432
+ if (k.toUpperCase() === target) return v;
433
+ }
434
+ return void 0;
435
+ }
436
+ function sanitizeChildEnv(baseEnv) {
437
+ const sanitized = {};
438
+ for (const [key, value] of Object.entries(baseEnv)) {
439
+ if (!STRIPPED_ENV_KEYS.has(key.toUpperCase())) {
440
+ sanitized[key] = value;
441
+ }
442
+ }
443
+ return sanitized;
444
+ }
445
+ function parseWindowsT3Cmd(scriptText, options = {}) {
446
+ const callerEnv = options.env ?? {};
447
+ const scriptDir = options.scriptPath ? dirname2(options.scriptPath) : "";
448
+ const env = {};
449
+ const lines = scriptText.split(/\r?\n/);
450
+ for (const line of lines) {
451
+ const trimmed = line.trim();
452
+ if (!trimmed || /^rem\b/i.test(trimmed) || trimmed.startsWith("::")) continue;
453
+ const ifNotDefMatch = /^if\s+not\s+defined\s+([A-Za-z0-9_]+)\s+set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(
454
+ trimmed
455
+ );
456
+ if (ifNotDefMatch) {
457
+ const guardVar = ifNotDefMatch[1];
458
+ const key = ifNotDefMatch[2] ?? ifNotDefMatch[4];
459
+ const val = (ifNotDefMatch[3] ?? ifNotDefMatch[5] ?? "").trim();
460
+ if (!getEnvCaseInsensitive(callerEnv, guardVar) && !val.includes("%ERRORLEVEL%")) {
461
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
462
+ }
463
+ continue;
464
+ }
465
+ const setMatch = /^set\s+(?:"([^"=]+)=([^"]*)"|([A-Za-z0-9_]+)=(.*))$/i.exec(trimmed);
466
+ if (setMatch) {
467
+ const key = setMatch[1] ?? setMatch[3];
468
+ const val = (setMatch[2] ?? setMatch[4] ?? "").trim();
469
+ if (val.includes("%ERRORLEVEL%") || /^t3_exit$/i.test(key)) continue;
470
+ env[key] = scriptDir ? val.replace(/%~dp0/gi, scriptDir + "\\") : val;
471
+ }
472
+ }
473
+ for (const line of lines) {
474
+ let trimmed = line.trim();
475
+ if (!trimmed.endsWith("%*")) continue;
476
+ trimmed = trimmed.slice(0, -2).trim();
477
+ trimmed = trimmed.replace(/^if\s+exist\s+(?:"[^"]+"|\S+)\s+/i, "");
478
+ trimmed = trimmed.replace(/^call\s+/i, "");
479
+ if (scriptDir) {
480
+ trimmed = trimmed.replace(/%~dp0/gi, scriptDir + "\\");
481
+ }
482
+ const tokens = [...trimmed.matchAll(/"([^"]+)"|(\S+)/g)].map((match) => match[1] ?? match[2]);
483
+ if (tokens.length >= 1) {
484
+ return {
485
+ executable: tokens[0],
486
+ prefix: tokens.slice(1),
487
+ env
488
+ };
489
+ }
490
+ }
491
+ return null;
492
+ }
493
+ async function resolveT3Command(t3Config, options = {}) {
494
+ const platform = options.platform ?? process.platform;
495
+ const home = options.homeDir ?? homedir();
496
+ const procEnv = options.env ?? process.env;
497
+ const t3Home = t3Config.home ?? getEnvCaseInsensitive(procEnv, "T3CODE_HOME") ?? join3(home, ".t3");
498
+ const mergeEnv = (detected) => ({
499
+ ...detected,
500
+ ...t3Config.home ? { T3CODE_HOME: t3Config.home } : {},
501
+ ...t3Config.env
502
+ });
503
+ if (t3Config.executable && t3Config.executable !== "auto") {
504
+ if (platform === "win32" && /\.(cmd|bat)$/i.test(t3Config.executable)) {
505
+ const parsed = parseWindowsT3Cmd(await readFile3(t3Config.executable, "utf8"), {
506
+ env: procEnv,
507
+ scriptPath: t3Config.executable
508
+ });
509
+ if (!parsed) {
510
+ throw new Error(`Could not parse Windows T3 launcher script: ${t3Config.executable}`);
511
+ }
512
+ return {
513
+ executable: parsed.executable,
514
+ prefix: [...parsed.prefix, ...t3Config.prefix],
515
+ env: mergeEnv(parsed.env)
516
+ };
517
+ }
518
+ return {
519
+ executable: t3Config.executable,
520
+ prefix: [...t3Config.prefix],
521
+ env: mergeEnv({})
522
+ };
523
+ }
524
+ if (platform === "win32") {
525
+ const candidates = [join3(t3Home, "bin", "t3.cmd"), join3(t3Home, "bin", "t3.exe")];
526
+ for (const candidate of candidates) {
527
+ if (!await fileExists(candidate)) continue;
528
+ if (candidate.endsWith(".cmd")) {
529
+ const parsed = parseWindowsT3Cmd(await readFile3(candidate, "utf8"), {
530
+ env: procEnv,
531
+ scriptPath: candidate
532
+ });
533
+ if (parsed) {
534
+ return {
535
+ executable: parsed.executable,
536
+ prefix: [...parsed.prefix, ...t3Config.prefix],
537
+ env: mergeEnv(parsed.env)
538
+ };
539
+ }
540
+ } else {
541
+ return {
542
+ executable: candidate,
543
+ prefix: [...t3Config.prefix],
544
+ env: mergeEnv({})
545
+ };
546
+ }
547
+ }
548
+ return {
549
+ executable: "t3.exe",
550
+ prefix: [...t3Config.prefix],
551
+ env: mergeEnv({})
552
+ };
553
+ }
554
+ const unixCandidates = [join3(t3Home, "bin", "t3"), join3(home, ".local", "bin", "t3"), "/usr/local/bin/t3"];
555
+ for (const candidate of unixCandidates) {
556
+ if (await fileExists(candidate)) {
557
+ return {
558
+ executable: candidate,
559
+ prefix: [...t3Config.prefix],
560
+ env: mergeEnv({})
561
+ };
562
+ }
563
+ }
564
+ return {
565
+ executable: "t3",
566
+ prefix: [...t3Config.prefix],
567
+ env: mergeEnv({})
568
+ };
569
+ }
570
+ var T3Cli = class {
571
+ resolvedPromise;
572
+ t3Config;
573
+ baseEnv;
574
+ constructor(t3Config, baseEnv = process.env) {
575
+ this.t3Config = t3Config;
576
+ this.baseEnv = sanitizeChildEnv(baseEnv);
577
+ }
578
+ async resolve() {
579
+ this.resolvedPromise ??= resolveT3Command(this.t3Config, { env: this.baseEnv });
580
+ return this.resolvedPromise;
581
+ }
582
+ async runJson(args, input, timeoutMs = 3e4) {
583
+ const cmd = await this.resolve();
584
+ return new Promise((done, fail) => {
585
+ const child = execFile(
586
+ cmd.executable,
587
+ [...cmd.prefix, ...args, "--json"],
588
+ {
589
+ env: { ...this.baseEnv, ...cmd.env },
590
+ windowsHide: true,
591
+ timeout: timeoutMs,
592
+ maxBuffer: 4e6
593
+ },
594
+ (error, stdout, stderr) => {
595
+ if (error) {
596
+ const detail = stderr?.trim() ? `: ${stderr.trim().slice(0, 300)}` : "";
597
+ return fail(
598
+ new Error(`T3 CLI (${args.slice(0, 2).join(" ")}) failed (${error.code ?? error.signal})${detail}`)
599
+ );
600
+ }
601
+ try {
602
+ done(JSON.parse(stdout));
603
+ } catch (invalid) {
604
+ fail(
605
+ new Error(
606
+ `T3 CLI returned invalid JSON: ${invalid instanceof Error ? invalid.message : String(invalid)}`
607
+ )
608
+ );
609
+ }
610
+ }
611
+ );
612
+ child.stdin?.on("error", () => {
613
+ });
614
+ child.stdin?.end(input, "utf8");
615
+ });
616
+ }
617
+ async issueSession(options) {
618
+ const args = ["auth", "session", "issue"];
619
+ for (const scope of options.scopes) {
620
+ args.push("--scope", scope);
621
+ }
622
+ if (options.subject) {
623
+ args.push("--subject", options.subject);
624
+ }
625
+ args.push("--ttl", options.ttl, "--label", options.label);
626
+ return this.runJson(args);
627
+ }
628
+ async revokeSession(sessionId) {
629
+ const cmd = await this.resolve();
630
+ await new Promise((resolveDone) => {
631
+ const child = execFile(
632
+ cmd.executable,
633
+ [...cmd.prefix, "auth", "session", "revoke", sessionId],
634
+ {
635
+ env: { ...this.baseEnv, ...cmd.env },
636
+ windowsHide: true,
637
+ timeout: 1e4
638
+ },
639
+ () => resolveDone()
640
+ );
641
+ child.on("error", () => resolveDone());
642
+ });
643
+ }
644
+ async withSession(options, fn) {
645
+ const session = await this.issueSession(options);
646
+ try {
647
+ return await fn(session.token);
648
+ } finally {
649
+ await this.revokeSession(session.sessionId).catch(() => {
650
+ });
651
+ }
652
+ }
653
+ };
654
+
655
+ // src/publish.ts
656
+ var MEDIA_TOOL_DEFINITION = {
657
+ name: "qqbot_send_media",
658
+ description: "Send a local file from the bound QQ workspace back to the active QQ conversation.",
659
+ inputSchema: {
660
+ type: "object",
661
+ required: ["path"],
662
+ additionalProperties: false,
663
+ properties: {
664
+ path: {
665
+ type: "string",
666
+ description: "Local output file path inside the current bound T3 workspace."
667
+ },
668
+ caption: {
669
+ type: "string",
670
+ description: "Optional caption accompanying the file."
671
+ }
672
+ }
673
+ }
674
+ };
675
+ async function resolveBindingThreadId(config, binding) {
676
+ const persisted = await readFile4(join4(config.stateDir, "bindings", `${binding.scopeHash}.thread`), "utf8").catch(
677
+ (error) => {
678
+ if (error.code === "ENOENT") return "";
679
+ throw error;
680
+ }
681
+ );
682
+ if (persisted.trim()) return persisted.trim();
683
+ return binding.threadId;
684
+ }
685
+ function createMediaPublisher(config) {
686
+ const t3Cli = new T3Cli(config.t3);
687
+ const readOnly = new Observer(
688
+ config.t3.origin,
689
+ () => t3Cli.issueSession({
690
+ scopes: ["orchestration:read"],
691
+ subject: "mcp-client",
692
+ ttl: "1h",
693
+ label: "T3 QQBot media tool"
694
+ }),
695
+ (sessionId) => t3Cli.revokeSession(sessionId)
696
+ );
697
+ let cachedBotKey = "";
698
+ let cachedBot = null;
699
+ return async function publishMedia(args) {
700
+ if (!args?.path || typeof args.path !== "string") {
701
+ throw new Error('Missing required "path" argument');
702
+ }
703
+ const cwd = await realpath2(process.cwd());
704
+ const matchingBindings = [];
705
+ for (const binding of config.bindings) {
706
+ const workspace = await realpath2(binding.workspace).catch(() => null);
707
+ if (workspace && isSameOrInsidePath(cwd, workspace)) {
708
+ matchingBindings.push({ binding, workspace });
709
+ }
710
+ }
711
+ if (matchingBindings.length === 0) {
712
+ throw new Error("The QQ media tool can only be used inside a bound QQ workspace");
713
+ }
714
+ matchingBindings.sort((a, b) => b.workspace.length - a.workspace.length);
715
+ const activeMatches = [];
716
+ for (const { binding, workspace } of matchingBindings) {
717
+ const threadId = await resolveBindingThreadId(config, binding);
718
+ if (!threadId) continue;
719
+ let runId;
720
+ try {
721
+ const current = (await readOnly.read(threadId)).thread;
722
+ runId = current.activeRunId;
723
+ } catch {
724
+ continue;
725
+ }
726
+ if (!runId) continue;
727
+ const routePath = join4(config.stateDir, digest(runId) + ".run.json");
728
+ const rawRoute = await readFile4(routePath, "utf8").catch((error) => {
729
+ if (error.code === "ENOENT") return "";
730
+ throw error;
731
+ });
732
+ if (!rawRoute) continue;
733
+ const route = JSON.parse(rawRoute);
734
+ if (route.thread === threadId && route.runId === runId && route.scopeHash === binding.scopeHash) {
735
+ activeMatches.push({ route, workspace });
736
+ }
737
+ }
738
+ if (activeMatches.length === 0) {
739
+ throw new Error("No active QQ turn found for this workspace");
740
+ }
741
+ if (activeMatches.length > 1) {
742
+ throw new Error(
743
+ "Multiple QQ conversations in this workspace are active simultaneously; bind separate workspaces per QQ chat to avoid ambiguity."
744
+ );
745
+ }
746
+ const { route: matchedRoute, workspace: matchedWorkspace } = activeMatches[0];
747
+ const targetPath = resolve3(cwd, args.path);
748
+ const file = await safeArtifact(matchedWorkspace, targetPath);
749
+ const credentials = await loadCredentials(config, process.env, { requireBridgeSecret: false });
750
+ const botKey = `${credentials.appId}\0${credentials.appSecret}`;
751
+ if (!cachedBot || cachedBotKey !== botKey) {
752
+ cachedBot = new QQBot({ appId: credentials.appId, appSecret: credentials.appSecret });
753
+ cachedBotKey = botKey;
754
+ }
755
+ const outcome = await cachedBot.sendMedia({
756
+ ...file,
757
+ target: matchedRoute.reply,
758
+ ...typeof args.caption === "string" ? { content: args.caption } : {}
759
+ });
760
+ if (!outcome.message?.id) {
761
+ throw new Error("QQ did not confirm media delivery");
762
+ }
763
+ return { content: [{ type: "text", text: `File "${file.fileName}" delivered to QQ.` }] };
764
+ };
765
+ }
766
+ async function handleMcpRequest(request, publishFn) {
767
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
768
+ return {
769
+ jsonrpc: "2.0",
770
+ id: null,
771
+ error: { code: -32600, message: "Invalid Request" }
772
+ };
773
+ }
774
+ const req = request;
775
+ if (req.id === void 0) return null;
776
+ const { id, method, params } = req;
777
+ if (method === "initialize") {
778
+ return {
779
+ jsonrpc: "2.0",
780
+ id,
781
+ result: {
782
+ protocolVersion: params?.protocolVersion === "2024-11-05" ? "2024-11-05" : "2025-06-18",
783
+ capabilities: { tools: {} },
784
+ serverInfo: { name: "t3-code-qqbot-media", version: APP_VERSION }
785
+ }
786
+ };
787
+ }
788
+ if (method === "tools/list") {
789
+ return { jsonrpc: "2.0", id, result: { tools: [MEDIA_TOOL_DEFINITION] } };
790
+ }
791
+ if (method === "tools/call") {
792
+ if (params?.name !== MEDIA_TOOL_DEFINITION.name) {
793
+ return {
794
+ jsonrpc: "2.0",
795
+ id,
796
+ error: { code: -32602, message: `Unknown tool: ${String(params?.name ?? "")}` }
797
+ };
798
+ }
799
+ try {
800
+ const result = await publishFn(params?.arguments);
801
+ return { jsonrpc: "2.0", id, result };
802
+ } catch (error) {
803
+ return {
804
+ jsonrpc: "2.0",
805
+ id,
806
+ result: {
807
+ isError: true,
808
+ content: [{ type: "text", text: error instanceof Error ? error.message : "QQ media delivery failed" }]
809
+ }
810
+ };
811
+ }
812
+ }
813
+ if (method === "ping") {
814
+ return { jsonrpc: "2.0", id, result: {} };
815
+ }
816
+ return {
817
+ jsonrpc: "2.0",
818
+ id,
819
+ error: { code: -32601, message: "Method not found" }
820
+ };
821
+ }
822
+ async function runPublishServer(configPath) {
823
+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
824
+ let cachedPublisher = null;
825
+ const getPublisher = async () => {
826
+ if (!cachedPublisher) {
827
+ const config = await loadConfig(configPath);
828
+ cachedPublisher = createMediaPublisher(config);
829
+ }
830
+ return cachedPublisher;
831
+ };
832
+ for await (const rawLine of input) {
833
+ const line = rawLine.replace(/^\uFEFF/, "").trim();
834
+ if (!line) continue;
835
+ let parsed;
836
+ try {
837
+ parsed = JSON.parse(line);
838
+ } catch {
839
+ process.stdout.write(
840
+ JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n"
841
+ );
842
+ continue;
843
+ }
844
+ const response = await handleMcpRequest(parsed, async (args) => {
845
+ const publisher = await getPublisher();
846
+ return publisher(args);
847
+ });
848
+ if (response) {
849
+ process.stdout.write(JSON.stringify(response) + "\n");
850
+ }
851
+ }
852
+ }
853
+ if (isMainModule(import.meta.url)) {
854
+ const configPath = process.argv[2] || process.env.T3_QQBOT_CONFIG || resolve3("config.json");
855
+ runPublishServer(configPath).catch((error) => {
856
+ console.error(error instanceof Error ? error.message : String(error));
857
+ process.exit(1);
858
+ });
859
+ }
860
+ export {
861
+ MEDIA_TOOL_DEFINITION,
862
+ createMediaPublisher,
863
+ handleMcpRequest,
864
+ runPublishServer
865
+ };