echo-t3-bridge 0.1.6 → 0.1.8
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/README.md +7 -0
- package/dist/cli.mjs +321 -43
- package/dist/tsc/bridge.js +137 -34
- package/dist/tsc/config.js +1 -1
- package/dist/tsc/index.js +9 -0
- package/dist/tsc/local-t3.js +177 -9
- package/dist/tsc/logging.js +77 -0
- package/dist/tsc/provider-quotas.js +11 -3
- package/package.json +1 -1
- package/scripts/service.mjs +97 -8
package/README.md
CHANGED
|
@@ -57,4 +57,11 @@ echo-t3-bridge setup --server https://wq.stormapex.top --code <配对码>
|
|
|
57
57
|
| `echo-t3-bridge run` | 前台运行桥接守护进程 |
|
|
58
58
|
| `echo-t3-bridge status` / `doctor` | 检查公网在线态、本机原版 T3 状态与 Antigravity 实时额度 |
|
|
59
59
|
| `echo-t3-bridge service install` / `uninstall` | 安装或卸载开机自启后台服务(macOS launchd / Linux systemd / Windows) |
|
|
60
|
+
| `echo-t3-bridge service restart` | 停止旧进程并重新启动后台服务 |
|
|
60
61
|
| `echo-t3-bridge unpair` | 解绑当前设备 |
|
|
62
|
+
|
|
63
|
+
### Windows 说明
|
|
64
|
+
|
|
65
|
+
- 自动定位官方安装器的 T3:依次尝试 `--t3-bin` / `T3_BIN`、`%USERPROFILE%\.local\bin\t3.cmd` 中记录的 `t3.exe`(`t3 update` 后自动跟随)、`%USERPROFILE%\.t3\runtime\versions\*\t3.exe` 最新版本、PATH 中的 `t3.exe`。配置里记录的路径失效时会自动重新解析。
|
|
66
|
+
- `setup` / `service install` / `service restart` 写入「启动」文件夹脚本后立即在后台启动(先停止已在运行的实例,避免双开);`service uninstall` 停止进程并删除脚本。
|
|
67
|
+
- 后台日志:`%APPDATA%\echo-t3-bridge\bridge.log`(超过约 5MB 启动时轮转为 `bridge.log.1`),每行带时间戳,记录 run 事件的 sequence / runId / status 和命令结果;配对码与令牌会被打码,不会写入日志。`status` 会输出日志路径。
|
package/dist/cli.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
-
import { dirname as
|
|
5
|
+
import { dirname as dirname5, resolve as resolve3 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
|
|
8
8
|
// src/bridge.ts
|
|
@@ -14,7 +14,7 @@ import { homedir, hostname } from "node:os";
|
|
|
14
14
|
import { dirname, join, resolve } from "node:path";
|
|
15
15
|
var DEFAULT_HUB_SERVER = "https://wq.stormapex.top";
|
|
16
16
|
var DEFAULT_LOCAL_T3_URL = "http://127.0.0.1:3773";
|
|
17
|
-
var APP_VERSION = "0.1.
|
|
17
|
+
var APP_VERSION = "0.1.7";
|
|
18
18
|
function defaultDataDir() {
|
|
19
19
|
if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
|
|
20
20
|
return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
|
|
@@ -306,9 +306,9 @@ async function listDirectories(rawPath) {
|
|
|
306
306
|
// src/local-t3.ts
|
|
307
307
|
import { execFile as execFile3 } from "node:child_process";
|
|
308
308
|
import crypto2 from "node:crypto";
|
|
309
|
-
import { existsSync as existsSync3 } from "node:fs";
|
|
309
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, readdirSync, statSync } from "node:fs";
|
|
310
310
|
import { homedir as homedir5 } from "node:os";
|
|
311
|
-
import { basename, join as join5 } from "node:path";
|
|
311
|
+
import { basename, delimiter, dirname as dirname3, isAbsolute, join as join5 } from "node:path";
|
|
312
312
|
import { promisify as promisify3 } from "node:util";
|
|
313
313
|
import WebSocket from "ws";
|
|
314
314
|
|
|
@@ -834,11 +834,12 @@ async function probeDriverUsage(driver, force = false) {
|
|
|
834
834
|
inflightMap.set(driver, task);
|
|
835
835
|
return task;
|
|
836
836
|
}
|
|
837
|
-
async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
837
|
+
async function enrichProvidersWithQuotas(providers, forceQuota = false, providerId) {
|
|
838
838
|
const neededDrivers = /* @__PURE__ */ new Set();
|
|
839
839
|
for (const p of providers) {
|
|
840
840
|
if (!p || typeof p !== "object") continue;
|
|
841
841
|
const rec = p;
|
|
842
|
+
if (providerId && String(rec.instanceId ?? "").toLowerCase() !== providerId.toLowerCase()) continue;
|
|
842
843
|
if (rec.installed === false) continue;
|
|
843
844
|
const driver = resolveQuotaDriver(rec);
|
|
844
845
|
if (!driver) continue;
|
|
@@ -848,7 +849,10 @@ async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
|
848
849
|
neededDrivers.add(driver);
|
|
849
850
|
}
|
|
850
851
|
}
|
|
851
|
-
if (neededDrivers.size === 0)
|
|
852
|
+
if (neededDrivers.size === 0) {
|
|
853
|
+
if (providerId) throw new Error("\u672A\u627E\u5230\u53EF\u540C\u6B65\u989D\u5EA6\u7684 CLI");
|
|
854
|
+
return providers;
|
|
855
|
+
}
|
|
852
856
|
const probed = /* @__PURE__ */ new Map();
|
|
853
857
|
await Promise.all(
|
|
854
858
|
[...neededDrivers].map(async (driver) => {
|
|
@@ -858,7 +862,10 @@ async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
|
858
862
|
}
|
|
859
863
|
})
|
|
860
864
|
);
|
|
861
|
-
if (probed.size === 0)
|
|
865
|
+
if (probed.size === 0) {
|
|
866
|
+
if (providerId) throw new Error("\u8BE5 CLI \u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u989D\u5EA6");
|
|
867
|
+
return providers;
|
|
868
|
+
}
|
|
862
869
|
return providers.map((p) => {
|
|
863
870
|
if (!p || typeof p !== "object") return p;
|
|
864
871
|
const rec = p;
|
|
@@ -876,6 +883,7 @@ async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
|
876
883
|
// src/local-t3.ts
|
|
877
884
|
var execFileAsync3 = promisify3(execFile3);
|
|
878
885
|
function resolveLocalT3Binary(override) {
|
|
886
|
+
if (process.platform === "win32") return resolveWindowsT3Binary(override);
|
|
879
887
|
const candidates = [
|
|
880
888
|
override,
|
|
881
889
|
process.env.T3_BIN,
|
|
@@ -889,6 +897,75 @@ function resolveLocalT3Binary(override) {
|
|
|
889
897
|
}
|
|
890
898
|
return "t3";
|
|
891
899
|
}
|
|
900
|
+
function resolveWindowsT3Binary(override) {
|
|
901
|
+
const fromPath = (candidate) => {
|
|
902
|
+
if (!candidate) return null;
|
|
903
|
+
const trimmed = candidate.trim().replace(/^"(.*)"$/, "$1");
|
|
904
|
+
if (!trimmed || !existsSync3(trimmed)) return null;
|
|
905
|
+
if (/\.(cmd|bat)$/i.test(trimmed)) return exeFromCmdShim(trimmed);
|
|
906
|
+
if (/\.exe$/i.test(trimmed)) return trimmed;
|
|
907
|
+
const withExe = `${trimmed}.exe`;
|
|
908
|
+
return existsSync3(withExe) ? withExe : null;
|
|
909
|
+
};
|
|
910
|
+
const t3Home = process.env.T3_HOME?.trim() || join5(homedir5(), ".t3");
|
|
911
|
+
return fromPath(override) ?? fromPath(process.env.T3_BIN) ?? exeFromCmdShim(join5(homedir5(), ".local", "bin", "t3.cmd")) ?? newestRuntimeExe(t3Home) ?? (t3Home !== join5(homedir5(), ".t3") ? newestRuntimeExe(join5(homedir5(), ".t3")) : null) ?? exeOnPath("t3.exe") ?? "t3.exe";
|
|
912
|
+
}
|
|
913
|
+
function exeFromCmdShim(cmdPath) {
|
|
914
|
+
try {
|
|
915
|
+
if (!existsSync3(cmdPath)) return null;
|
|
916
|
+
const text = readFileSync2(cmdPath, "utf8");
|
|
917
|
+
const match = /"([^"]+\.exe)"/i.exec(text) ?? /^\s*([^\s"@][^\r\n]*?\.exe)\b/im.exec(text);
|
|
918
|
+
if (!match?.[1]) return null;
|
|
919
|
+
let exe = match[1].trim();
|
|
920
|
+
exe = exe.replace(/%~dp0\\?/gi, `${dirname3(cmdPath)}\\`);
|
|
921
|
+
exe = exe.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (_m, name) => process.env[name] ?? "");
|
|
922
|
+
if (!isAbsolute(exe)) exe = join5(dirname3(cmdPath), exe);
|
|
923
|
+
return existsSync3(exe) ? exe : null;
|
|
924
|
+
} catch {
|
|
925
|
+
return null;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
function compareVersionNames(a, b) {
|
|
929
|
+
const pa = a.replace(/^v/i, "").split(/[.\-+]/);
|
|
930
|
+
const pb = b.replace(/^v/i, "").split(/[.\-+]/);
|
|
931
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
932
|
+
const x = pa[i] ?? "";
|
|
933
|
+
const y = pb[i] ?? "";
|
|
934
|
+
const nx = Number(x);
|
|
935
|
+
const ny = Number(y);
|
|
936
|
+
if (Number.isFinite(nx) && Number.isFinite(ny) && x !== "" && y !== "") {
|
|
937
|
+
if (nx !== ny) return nx - ny;
|
|
938
|
+
} else if (x !== y) {
|
|
939
|
+
return x < y ? -1 : 1;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
return 0;
|
|
943
|
+
}
|
|
944
|
+
function newestRuntimeExe(t3Home) {
|
|
945
|
+
const versionsDir = join5(t3Home, "runtime", "versions");
|
|
946
|
+
try {
|
|
947
|
+
const versions = readdirSync(versionsDir).filter((name) => {
|
|
948
|
+
try {
|
|
949
|
+
return statSync(join5(versionsDir, name)).isDirectory() && existsSync3(join5(versionsDir, name, "t3.exe"));
|
|
950
|
+
} catch {
|
|
951
|
+
return false;
|
|
952
|
+
}
|
|
953
|
+
});
|
|
954
|
+
if (versions.length === 0) return null;
|
|
955
|
+
versions.sort(compareVersionNames);
|
|
956
|
+
return join5(versionsDir, versions[versions.length - 1], "t3.exe");
|
|
957
|
+
} catch {
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
function exeOnPath(name) {
|
|
962
|
+
for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(delimiter)) {
|
|
963
|
+
if (!dir) continue;
|
|
964
|
+
const candidate = join5(dir.replace(/^"(.*)"$/, "$1"), name);
|
|
965
|
+
if (existsSync3(candidate)) return candidate;
|
|
966
|
+
}
|
|
967
|
+
return null;
|
|
968
|
+
}
|
|
892
969
|
async function pairLocalOfficialT3(options) {
|
|
893
970
|
const bin = resolveLocalT3Binary(options?.t3Binary);
|
|
894
971
|
let stdout = "";
|
|
@@ -1025,8 +1102,10 @@ function normalizeDispatchCommand(rawCommand) {
|
|
|
1025
1102
|
}
|
|
1026
1103
|
return { ...command, modelSelection: selObj };
|
|
1027
1104
|
}
|
|
1028
|
-
var PING_INTERVAL_MS =
|
|
1029
|
-
var
|
|
1105
|
+
var PING_INTERVAL_MS = 2e4;
|
|
1106
|
+
var PONG_TIMEOUT_MS = 5e4;
|
|
1107
|
+
var THREAD_RESUBSCRIBE_DELAY_MS = 2e3;
|
|
1108
|
+
var MAX_THREAD_RESUBSCRIBE_ATTEMPTS = 6;
|
|
1030
1109
|
var LocalT3Client = class {
|
|
1031
1110
|
baseUrl;
|
|
1032
1111
|
accessToken;
|
|
@@ -1046,8 +1125,13 @@ var LocalT3Client = class {
|
|
|
1046
1125
|
terminalMetadata = /* @__PURE__ */ new Map();
|
|
1047
1126
|
terminalStreams = /* @__PURE__ */ new Map();
|
|
1048
1127
|
pingTimer = null;
|
|
1049
|
-
/** Last time
|
|
1128
|
+
/** Last time a WebSocket pong or any message arrived from the local T3 socket. */
|
|
1050
1129
|
lastInboundAt = 0;
|
|
1130
|
+
/** Thread streams this client ended itself (no automatic re-subscribe). */
|
|
1131
|
+
interruptedStreams = /* @__PURE__ */ new Set();
|
|
1132
|
+
resubscribeTimers = /* @__PURE__ */ new Map();
|
|
1133
|
+
/** Consecutive server-ended streams per thread without an event in between. */
|
|
1134
|
+
resubscribeAttempts = /* @__PURE__ */ new Map();
|
|
1051
1135
|
reconnectTimer = null;
|
|
1052
1136
|
backoffMs = 2e3;
|
|
1053
1137
|
constructor(config, callbacks, initialThreads = []) {
|
|
@@ -1091,6 +1175,9 @@ var LocalT3Client = class {
|
|
|
1091
1175
|
this.connected = false;
|
|
1092
1176
|
this.subscribedThreads.clear();
|
|
1093
1177
|
this.streamThreads.clear();
|
|
1178
|
+
this.interruptedStreams.clear();
|
|
1179
|
+
for (const timer of this.resubscribeTimers.values()) clearTimeout(timer);
|
|
1180
|
+
this.resubscribeTimers.clear();
|
|
1094
1181
|
this.terminalStreams.clear();
|
|
1095
1182
|
this.terminalMetadata.clear();
|
|
1096
1183
|
this.streams.clear();
|
|
@@ -1174,15 +1261,25 @@ var LocalT3Client = class {
|
|
|
1174
1261
|
this.lastInboundAt = Date.now();
|
|
1175
1262
|
this.pingTimer = setInterval(() => {
|
|
1176
1263
|
if (ws.readyState !== WebSocket.OPEN) return;
|
|
1177
|
-
if (Date.now() - this.lastInboundAt >
|
|
1178
|
-
console.error(
|
|
1264
|
+
if (Date.now() - this.lastInboundAt > PONG_TIMEOUT_MS) {
|
|
1265
|
+
console.error(
|
|
1266
|
+
`[local-t3] \u672C\u673A T3 \u8D85\u8FC7 ${Math.round(PONG_TIMEOUT_MS / 1e3)} \u79D2\u672A\u54CD\u5E94 WebSocket ping\uFF0C\u65AD\u5F00\u5E76\u91CD\u8FDE\u2026`
|
|
1267
|
+
);
|
|
1179
1268
|
ws.terminate();
|
|
1180
1269
|
return;
|
|
1181
1270
|
}
|
|
1182
|
-
|
|
1271
|
+
try {
|
|
1272
|
+
ws.ping();
|
|
1273
|
+
ws.send(JSON.stringify({ _tag: "Ping" }));
|
|
1274
|
+
} catch {
|
|
1275
|
+
}
|
|
1183
1276
|
}, PING_INTERVAL_MS);
|
|
1184
1277
|
void this.bootstrapStreams();
|
|
1185
1278
|
});
|
|
1279
|
+
ws.on("pong", () => {
|
|
1280
|
+
if (this.ws !== ws) return;
|
|
1281
|
+
this.lastInboundAt = Date.now();
|
|
1282
|
+
});
|
|
1186
1283
|
ws.on("message", (data) => {
|
|
1187
1284
|
if (this.ws !== ws) return;
|
|
1188
1285
|
this.lastInboundAt = Date.now();
|
|
@@ -1232,6 +1329,11 @@ var LocalT3Client = class {
|
|
|
1232
1329
|
if (exitedThread) {
|
|
1233
1330
|
this.streamThreads.delete(reqId);
|
|
1234
1331
|
this.subscribedThreads.delete(exitedThread);
|
|
1332
|
+
if (!this.interruptedStreams.delete(reqId)) {
|
|
1333
|
+
this.scheduleThreadResubscribe(exitedThread);
|
|
1334
|
+
}
|
|
1335
|
+
} else {
|
|
1336
|
+
this.interruptedStreams.delete(reqId);
|
|
1235
1337
|
}
|
|
1236
1338
|
const pending = this.pending.get(reqId);
|
|
1237
1339
|
if (!pending) return;
|
|
@@ -1299,7 +1401,27 @@ var LocalT3Client = class {
|
|
|
1299
1401
|
return null;
|
|
1300
1402
|
}
|
|
1301
1403
|
}
|
|
1404
|
+
scheduleThreadResubscribe(threadId) {
|
|
1405
|
+
if (this.stopped || this.resubscribeTimers.has(threadId)) return;
|
|
1406
|
+
const attempt = (this.resubscribeAttempts.get(threadId) ?? 0) + 1;
|
|
1407
|
+
if (attempt > MAX_THREAD_RESUBSCRIBE_ATTEMPTS) {
|
|
1408
|
+
console.error(`[local-t3] \u7EBF\u7A0B ${threadId} \u8BA2\u9605\u8FDE\u7EED ${attempt - 1} \u6B21\u88AB\u7ED3\u675F\uFF0C\u6682\u505C\u81EA\u52A8\u7EED\u8BA2`);
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
this.resubscribeAttempts.set(threadId, attempt);
|
|
1412
|
+
const delay = Math.min(THREAD_RESUBSCRIBE_DELAY_MS * 2 ** (attempt - 1), 6e4);
|
|
1413
|
+
const timer = setTimeout(() => {
|
|
1414
|
+
this.resubscribeTimers.delete(threadId);
|
|
1415
|
+
if (!this.isConnected()) return;
|
|
1416
|
+
console.log(
|
|
1417
|
+
`[local-t3] \u7EBF\u7A0B ${threadId} \u8BA2\u9605\u88AB\u670D\u52A1\u7AEF\u7ED3\u675F\uFF0C\u4ECE sequence ${this.wantedThreads.get(threadId) ?? 0} \u4E4B\u540E\u7EED\u8BA2`
|
|
1418
|
+
);
|
|
1419
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
1420
|
+
}, delay);
|
|
1421
|
+
this.resubscribeTimers.set(threadId, timer);
|
|
1422
|
+
}
|
|
1302
1423
|
interruptStream(requestId) {
|
|
1424
|
+
this.interruptedStreams.add(requestId);
|
|
1303
1425
|
this.streams.delete(requestId);
|
|
1304
1426
|
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1305
1427
|
try {
|
|
@@ -1378,6 +1500,7 @@ var LocalT3Client = class {
|
|
|
1378
1500
|
return;
|
|
1379
1501
|
}
|
|
1380
1502
|
if (env.kind !== "event" || typeof env.sequence !== "number" || !env.event) return;
|
|
1503
|
+
this.resubscribeAttempts.delete(threadId);
|
|
1381
1504
|
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
1382
1505
|
if (env.sequence > cur) this.wantedThreads.set(threadId, env.sequence);
|
|
1383
1506
|
this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
|
|
@@ -1409,7 +1532,13 @@ var LocalT3Client = class {
|
|
|
1409
1532
|
this.ensureThreadSubscribed(threadId, 0);
|
|
1410
1533
|
}
|
|
1411
1534
|
}
|
|
1412
|
-
async refreshProviders(includeQuota = false) {
|
|
1535
|
+
async refreshProviders(includeQuota = false, providerId) {
|
|
1536
|
+
if (providerId) {
|
|
1537
|
+
const finalList2 = await enrichProvidersWithQuotas(this.lastProviders, true, providerId);
|
|
1538
|
+
this.lastProviders = finalList2;
|
|
1539
|
+
this.callbacks.onProviders(finalList2);
|
|
1540
|
+
return { providers: finalList2 };
|
|
1541
|
+
}
|
|
1413
1542
|
const payload = includeQuota ? { fresh: true, refreshModels: true, usageLimitsCommand: true } : { fresh: true };
|
|
1414
1543
|
const raw = await this.callRpc("server.refreshProviders", payload, 45e3);
|
|
1415
1544
|
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.providers) ? raw.providers : this.lastProviders;
|
|
@@ -1998,6 +2127,14 @@ function createHubWebSocketAgent(targetUrl) {
|
|
|
1998
2127
|
var MAX_BUFFERED_EVENTS = 5e3;
|
|
1999
2128
|
var MAX_SENT_SEQUENCES = 2e4;
|
|
2000
2129
|
var MAX_MISSED_HEARTBEAT_ACKS = 3;
|
|
2130
|
+
function logRunEvent(envelope) {
|
|
2131
|
+
const event = envelope.event;
|
|
2132
|
+
const type = typeof event?.type === "string" ? event.type : "";
|
|
2133
|
+
if (type !== "run.created" && type !== "run.updated") return;
|
|
2134
|
+
console.log(
|
|
2135
|
+
`[event] seq=${envelope.sequence} ${type} thread=${String(event?.threadId ?? "")} runId=${String(event?.payload?.id ?? "")} status=${String(event?.payload?.status ?? "")}`
|
|
2136
|
+
);
|
|
2137
|
+
}
|
|
2001
2138
|
var EchoT3Bridge = class {
|
|
2002
2139
|
configPath;
|
|
2003
2140
|
config;
|
|
@@ -2013,9 +2150,17 @@ var EchoT3Bridge = class {
|
|
|
2013
2150
|
/** True once the Hub's welcome arrived on the current link; events flow only then. */
|
|
2014
2151
|
hubReady = false;
|
|
2015
2152
|
unackedHeartbeats = 0;
|
|
2153
|
+
/**
|
|
2154
|
+
* Events not yet known to be stored by the Hub. In ack mode an event stays
|
|
2155
|
+
* here until the Hub's `event.ack` for its sequence arrives; in legacy mode
|
|
2156
|
+
* (older Hub without acks) only while the link is not ready.
|
|
2157
|
+
*/
|
|
2016
2158
|
bufferedEvents = /* @__PURE__ */ new Map();
|
|
2017
|
-
|
|
2159
|
+
/** Lowest sequence dropped because the buffer was full; replayed from T3 on welcome. */
|
|
2160
|
+
overflowFromSequence = null;
|
|
2018
2161
|
sentSequences = /* @__PURE__ */ new Set();
|
|
2162
|
+
/** True when the current Hub link acknowledges stored events (welcome.eventAck). */
|
|
2163
|
+
hubAcksEvents = false;
|
|
2019
2164
|
constructor(configPath) {
|
|
2020
2165
|
this.configPath = configPath;
|
|
2021
2166
|
}
|
|
@@ -2073,47 +2218,105 @@ var EchoT3Bridge = class {
|
|
|
2073
2218
|
}
|
|
2074
2219
|
/**
|
|
2075
2220
|
* Forward a T3 event to the Hub verbatim (sequence, occurredAt, driver,
|
|
2076
|
-
* providerInstanceId all stay inside `event`).
|
|
2077
|
-
*
|
|
2078
|
-
* the
|
|
2221
|
+
* providerInstanceId all stay inside `event`). An event counts as delivered
|
|
2222
|
+
* only once the Hub has it: in ack mode when `event.ack` arrives, in legacy
|
|
2223
|
+
* mode when the frame was written to an open socket. Anything else stays
|
|
2224
|
+
* buffered (bounded) and is resent in sequence order after the next welcome;
|
|
2225
|
+
* overflow is recovered by re-subscribing from T3's own log.
|
|
2079
2226
|
*/
|
|
2080
2227
|
forwardThreadEvent(envelope) {
|
|
2081
2228
|
const seq = envelope.sequence;
|
|
2082
|
-
|
|
2083
|
-
if (this.
|
|
2084
|
-
|
|
2085
|
-
|
|
2229
|
+
logRunEvent(envelope);
|
|
2230
|
+
if (this.sentSequences.has(seq) && !this.bufferedEvents.has(seq)) return;
|
|
2231
|
+
if (!this.bufferedEvents.has(seq)) {
|
|
2232
|
+
if (this.bufferedEvents.size >= MAX_BUFFERED_EVENTS) {
|
|
2233
|
+
this.noteOverflow(seq);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (this.hubAcksEvents || !this.isHubReady()) {
|
|
2237
|
+
this.bufferedEvents.set(seq, envelope);
|
|
2238
|
+
}
|
|
2086
2239
|
}
|
|
2087
|
-
if (this.
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2240
|
+
if (this.isHubReady()) this.sendEventNow(envelope);
|
|
2241
|
+
}
|
|
2242
|
+
isHubReady() {
|
|
2243
|
+
return this.hubReady && this.hubWs?.readyState === WebSocket2.OPEN;
|
|
2244
|
+
}
|
|
2245
|
+
noteOverflow(seq) {
|
|
2246
|
+
if (this.overflowFromSequence === null || seq < this.overflowFromSequence) {
|
|
2247
|
+
this.overflowFromSequence = seq;
|
|
2091
2248
|
}
|
|
2092
|
-
|
|
2249
|
+
console.error(`[hub] \u5F85\u786E\u8BA4\u4E8B\u4EF6\u8D85\u8FC7 ${MAX_BUFFERED_EVENTS} \u6761\uFF0Csequence=${seq} \u8D77\u5C06\u5728\u91CD\u8FDE\u540E\u4ECE\u672C\u673A T3 \u91CD\u65B0\u62C9\u53D6`);
|
|
2093
2250
|
}
|
|
2094
|
-
|
|
2095
|
-
this.sentSequences.add(
|
|
2251
|
+
rememberSent(seq) {
|
|
2252
|
+
this.sentSequences.add(seq);
|
|
2096
2253
|
if (this.sentSequences.size > MAX_SENT_SEQUENCES) {
|
|
2097
2254
|
const oldest = this.sentSequences.values().next().value;
|
|
2098
2255
|
if (oldest !== void 0) this.sentSequences.delete(oldest);
|
|
2099
2256
|
}
|
|
2100
|
-
this.sendHubFrame({ type: "event", data: envelope });
|
|
2101
2257
|
}
|
|
2258
|
+
sendEventNow(envelope) {
|
|
2259
|
+
const ws = this.hubWs;
|
|
2260
|
+
if (!ws || ws.readyState !== WebSocket2.OPEN) {
|
|
2261
|
+
if (!this.bufferedEvents.has(envelope.sequence)) this.bufferedEvents.set(envelope.sequence, envelope);
|
|
2262
|
+
return;
|
|
2263
|
+
}
|
|
2264
|
+
const seq = envelope.sequence;
|
|
2265
|
+
this.rememberSent(seq);
|
|
2266
|
+
ws.send(JSON.stringify({ type: "event", data: envelope }), (err) => {
|
|
2267
|
+
if (!err) {
|
|
2268
|
+
if (!this.hubAcksEvents) this.bufferedEvents.delete(seq);
|
|
2269
|
+
return;
|
|
2270
|
+
}
|
|
2271
|
+
this.sentSequences.delete(seq);
|
|
2272
|
+
if (!this.bufferedEvents.has(seq) && this.bufferedEvents.size < MAX_BUFFERED_EVENTS) {
|
|
2273
|
+
this.bufferedEvents.set(seq, envelope);
|
|
2274
|
+
} else if (!this.bufferedEvents.has(seq)) {
|
|
2275
|
+
this.noteOverflow(seq);
|
|
2276
|
+
}
|
|
2277
|
+
console.error(`[hub] \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF0C\u91CD\u8FDE\u540E\u91CD\u53D1: sequence=${seq} ${err.message}`);
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
handleEventAck(data) {
|
|
2281
|
+
const ack = data ?? {};
|
|
2282
|
+
const seqs = [];
|
|
2283
|
+
if (typeof ack.sequence === "number") seqs.push(ack.sequence);
|
|
2284
|
+
if (Array.isArray(ack.sequences)) {
|
|
2285
|
+
for (const v of ack.sequences) if (typeof v === "number") seqs.push(v);
|
|
2286
|
+
}
|
|
2287
|
+
for (const seq of seqs) {
|
|
2288
|
+
this.bufferedEvents.delete(seq);
|
|
2289
|
+
this.rememberSent(seq);
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
/** Resend everything not yet confirmed, oldest first. */
|
|
2102
2293
|
flushBufferedEvents() {
|
|
2103
2294
|
const ordered = [...this.bufferedEvents.values()].sort((a, b) => a.sequence - b.sequence);
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2295
|
+
if (ordered.length > 0) {
|
|
2296
|
+
console.log(
|
|
2297
|
+
`[hub] \u91CD\u53D1 ${ordered.length} \u6761\u672A\u786E\u8BA4\u4E8B\u4EF6 (sequence ${ordered[0].sequence}..${ordered[ordered.length - 1].sequence})`
|
|
2298
|
+
);
|
|
2107
2299
|
}
|
|
2300
|
+
if (!this.hubAcksEvents) this.bufferedEvents.clear();
|
|
2301
|
+
for (const envelope of ordered) this.sendEventNow(envelope);
|
|
2108
2302
|
}
|
|
2109
|
-
/**
|
|
2303
|
+
/**
|
|
2304
|
+
* Ask T3 to replay everything after `afterSequence`. The Hub asked for these,
|
|
2305
|
+
* so local "already sent" marks above the cursor are dropped first; the Hub
|
|
2306
|
+
* ignores duplicates by (environment_id, sequence).
|
|
2307
|
+
*/
|
|
2110
2308
|
resumeEventsAfter(afterSequence) {
|
|
2111
2309
|
const after = typeof afterSequence === "number" ? afterSequence : Number(afterSequence);
|
|
2112
2310
|
if (!Number.isFinite(after) || after < 0) return;
|
|
2311
|
+
for (const seq of [...this.sentSequences]) {
|
|
2312
|
+
if (seq > after) this.sentSequences.delete(seq);
|
|
2313
|
+
}
|
|
2314
|
+
console.log(`[hub] \u4ECE\u672C\u673A T3 \u91CD\u65B0\u62C9\u53D6 sequence>${after} \u7684\u4E8B\u4EF6`);
|
|
2113
2315
|
this.localT3.resubscribeAfter(after);
|
|
2114
2316
|
}
|
|
2115
2317
|
teardownHub() {
|
|
2116
2318
|
this.hubReady = false;
|
|
2319
|
+
this.hubAcksEvents = false;
|
|
2117
2320
|
this.unackedHeartbeats = 0;
|
|
2118
2321
|
this.localT3?.detachAllTerminals();
|
|
2119
2322
|
if (this.heartbeatTimer) {
|
|
@@ -2324,17 +2527,28 @@ var EchoT3Bridge = class {
|
|
|
2324
2527
|
this.sendHubFrame({ type: "heartbeat", id: `hb_${Date.now()}` });
|
|
2325
2528
|
}, interval);
|
|
2326
2529
|
this.hubReady = true;
|
|
2530
|
+
this.hubAcksEvents = data.eventAck === true;
|
|
2531
|
+
console.log(
|
|
2532
|
+
`[hub] welcome: cursor=${data.lastEventSequence ?? "null"} eventAck=${this.hubAcksEvents} pending=${this.bufferedEvents.size}`
|
|
2533
|
+
);
|
|
2327
2534
|
this.flushBufferedEvents();
|
|
2328
|
-
const cursor = data.lastEventSequence;
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2535
|
+
const cursor = typeof data.lastEventSequence === "number" ? data.lastEventSequence : null;
|
|
2536
|
+
const overflow = this.overflowFromSequence;
|
|
2537
|
+
this.overflowFromSequence = null;
|
|
2538
|
+
let resumeAfter = cursor !== null && cursor > 0 ? cursor : null;
|
|
2539
|
+
if (overflow !== null) {
|
|
2540
|
+
const beforeOverflow = Math.max(0, overflow - 1);
|
|
2541
|
+
resumeAfter = resumeAfter === null ? beforeOverflow : Math.min(resumeAfter, beforeOverflow);
|
|
2332
2542
|
}
|
|
2543
|
+
if (resumeAfter !== null) this.resumeEventsAfter(resumeAfter);
|
|
2333
2544
|
return;
|
|
2334
2545
|
}
|
|
2335
2546
|
case "heartbeat_ack":
|
|
2336
2547
|
this.unackedHeartbeats = 0;
|
|
2337
2548
|
return;
|
|
2549
|
+
case "event.ack":
|
|
2550
|
+
this.handleEventAck(frame.data);
|
|
2551
|
+
return;
|
|
2338
2552
|
case "events.resume": {
|
|
2339
2553
|
const data = frame.data ?? {};
|
|
2340
2554
|
this.resumeEventsAfter(data.lastEventSequence ?? data.afterSequence);
|
|
@@ -2342,8 +2556,9 @@ var EchoT3Bridge = class {
|
|
|
2342
2556
|
}
|
|
2343
2557
|
case "providers.refresh": {
|
|
2344
2558
|
try {
|
|
2345
|
-
const
|
|
2346
|
-
this.
|
|
2559
|
+
const providerId = frame.data?.providerId;
|
|
2560
|
+
const result = await this.localT3.refreshProviders(true, typeof providerId === "string" ? providerId : void 0);
|
|
2561
|
+
this.replyHub(frame.type, frame.id, { ok: true, result: typeof providerId === "string" ? { ...result, quotaProviderId: providerId } : result });
|
|
2347
2562
|
} catch (err) {
|
|
2348
2563
|
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2349
2564
|
}
|
|
@@ -2370,13 +2585,17 @@ var EchoT3Bridge = class {
|
|
|
2370
2585
|
return;
|
|
2371
2586
|
}
|
|
2372
2587
|
case "command": {
|
|
2588
|
+
const cmd = frame.data ?? {};
|
|
2589
|
+
const label = `type=${String(cmd.type ?? "")}${cmd.threadId ? ` thread=${String(cmd.threadId)}` : ""}${cmd.runId ? ` runId=${String(cmd.runId)}` : ""}`;
|
|
2373
2590
|
try {
|
|
2374
|
-
const cmd = frame.data ?? {};
|
|
2375
2591
|
const result = await this.localT3.dispatchCommand(cmd);
|
|
2376
2592
|
this.scheduleSaveKnownThreads();
|
|
2593
|
+
console.log(`[hub] command ${label} \u2192 ok`);
|
|
2377
2594
|
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2378
2595
|
} catch (err) {
|
|
2379
|
-
|
|
2596
|
+
const rpcError = this.toRpcError(err);
|
|
2597
|
+
console.error(`[hub] command ${label} \u2192 ${rpcError.tag}: ${rpcError.message}`);
|
|
2598
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: rpcError });
|
|
2380
2599
|
}
|
|
2381
2600
|
return;
|
|
2382
2601
|
}
|
|
@@ -2498,6 +2717,57 @@ var EchoT3Bridge = class {
|
|
|
2498
2717
|
}
|
|
2499
2718
|
};
|
|
2500
2719
|
|
|
2720
|
+
// src/logging.ts
|
|
2721
|
+
import { mkdirSync, writeFileSync, unlinkSync, readFileSync as readFileSync3 } from "node:fs";
|
|
2722
|
+
import { dirname as dirname4, join as join6 } from "node:path";
|
|
2723
|
+
function redactSecrets(text) {
|
|
2724
|
+
return text.replace(/(--code[ =])\S+/gi, "$1***").replace(/(#token=)[^\s&"']+/gi, "$1***").replace(/(\btoken:\s*)[A-Z0-9-]{6,}/gi, "$1***").replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+/=-]{8,}/g, "$1 ***").replace(/("(?:accessToken|refreshToken|access_token|refresh_token|code|pairingCode|token)"\s*:\s*")[^"]*"/gi, '$1***"');
|
|
2725
|
+
}
|
|
2726
|
+
var installed = false;
|
|
2727
|
+
function installRunLogging() {
|
|
2728
|
+
if (installed) return;
|
|
2729
|
+
installed = true;
|
|
2730
|
+
const wrap = (fn) => (...args) => {
|
|
2731
|
+
const line = args.map((a) => typeof a === "string" ? a : a instanceof Error ? a.stack ?? a.message : safeJson(a)).join(" ");
|
|
2732
|
+
fn(`${(/* @__PURE__ */ new Date()).toISOString()} ${redactSecrets(line)}`);
|
|
2733
|
+
};
|
|
2734
|
+
console.log = wrap(console.log.bind(console));
|
|
2735
|
+
console.info = wrap(console.info.bind(console));
|
|
2736
|
+
console.warn = wrap(console.warn.bind(console));
|
|
2737
|
+
console.error = wrap(console.error.bind(console));
|
|
2738
|
+
}
|
|
2739
|
+
function safeJson(value) {
|
|
2740
|
+
try {
|
|
2741
|
+
return JSON.stringify(value);
|
|
2742
|
+
} catch {
|
|
2743
|
+
return String(value);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
function serviceLogPath() {
|
|
2747
|
+
const dataDir = defaultDataDir();
|
|
2748
|
+
if (process.platform === "win32") return join6(dataDir, "bridge.log");
|
|
2749
|
+
if (process.platform === "darwin") return join6(dataDir, "logs", "bridge.stdout.log");
|
|
2750
|
+
return "journalctl --user -u echo-t3-bridge";
|
|
2751
|
+
}
|
|
2752
|
+
function pidFilePath(configPath) {
|
|
2753
|
+
return join6(dirname4(configPath), "bridge.pid");
|
|
2754
|
+
}
|
|
2755
|
+
function writePidFile(configPath) {
|
|
2756
|
+
const path = pidFilePath(configPath);
|
|
2757
|
+
try {
|
|
2758
|
+
mkdirSync(dirname4(path), { recursive: true });
|
|
2759
|
+
writeFileSync(path, String(process.pid), "utf8");
|
|
2760
|
+
} catch {
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
function removePidFile(configPath) {
|
|
2764
|
+
const path = pidFilePath(configPath);
|
|
2765
|
+
try {
|
|
2766
|
+
if (readFileSync3(path, "utf8").trim() === String(process.pid)) unlinkSync(path);
|
|
2767
|
+
} catch {
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
|
|
2501
2771
|
// src/index.ts
|
|
2502
2772
|
ensureProcessProxyEnv();
|
|
2503
2773
|
function parseArgs(argv) {
|
|
@@ -2573,7 +2843,7 @@ function printHelp() {
|
|
|
2573
2843
|
`);
|
|
2574
2844
|
}
|
|
2575
2845
|
function runServiceScript(action, configPath) {
|
|
2576
|
-
const currentDir =
|
|
2846
|
+
const currentDir = dirname5(fileURLToPath(import.meta.url));
|
|
2577
2847
|
const scriptPath = resolve3(currentDir, "..", "scripts", "service.mjs");
|
|
2578
2848
|
const res = spawnSync(process.execPath, [scriptPath, action, "--config", configPath], {
|
|
2579
2849
|
stdio: "inherit"
|
|
@@ -2661,6 +2931,10 @@ async function doDoctor(configPath) {
|
|
|
2661
2931
|
console.log(
|
|
2662
2932
|
`\u672C\u673A\u539F\u7248 T3: ${cfg.localT3.baseUrl} | \u4E8C\u8FDB\u5236: ${t3Bin} | \u670D\u52A1: ${localOk ? "\u25CF \u8FD0\u884C\u4E2D" : "\u25CB \u672A\u542F\u52A8\uFF08\u8BF7\u8FD0\u884C t3 up\uFF09"} | \u672C\u5730\u4EE4\u724C: ${cfg.localT3.accessToken ? "\u5DF2\u6388\u6743" : "\u672A\u6388\u6743"}`
|
|
2663
2933
|
);
|
|
2934
|
+
if (cfg.localT3.t3Binary && t3Bin !== cfg.localT3.t3Binary) {
|
|
2935
|
+
console.log(` \u914D\u7F6E\u4E2D\u7684 t3 \u8DEF\u5F84 ${cfg.localT3.t3Binary} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u5DF2\u81EA\u52A8\u6539\u7528 ${t3Bin}`);
|
|
2936
|
+
}
|
|
2937
|
+
console.log(`\u540E\u53F0\u670D\u52A1\u65E5\u5FD7: ${serviceLogPath()}`);
|
|
2664
2938
|
}
|
|
2665
2939
|
async function main() {
|
|
2666
2940
|
const parsed = parseArgs(process.argv.slice(2));
|
|
@@ -2688,6 +2962,10 @@ async function main() {
|
|
|
2688
2962
|
return;
|
|
2689
2963
|
}
|
|
2690
2964
|
case "run": {
|
|
2965
|
+
installRunLogging();
|
|
2966
|
+
console.log(`[bridge] echo-t3-bridge v${APP_VERSION} \u542F\u52A8 (pid=${process.pid}, platform=${process.platform}, config=${configPath})`);
|
|
2967
|
+
writePidFile(configPath);
|
|
2968
|
+
process.on("exit", () => removePidFile(configPath));
|
|
2691
2969
|
const bridge = new EchoT3Bridge(configPath);
|
|
2692
2970
|
const shutdown = () => {
|
|
2693
2971
|
console.log("[bridge] \u6B63\u5728\u505C\u6B62\u2026");
|