echo-t3-bridge 0.1.7 → 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 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 dirname3, resolve as resolve3 } from "node:path";
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.6";
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
 
@@ -883,6 +883,7 @@ async function enrichProvidersWithQuotas(providers, forceQuota = false, provider
883
883
  // src/local-t3.ts
884
884
  var execFileAsync3 = promisify3(execFile3);
885
885
  function resolveLocalT3Binary(override) {
886
+ if (process.platform === "win32") return resolveWindowsT3Binary(override);
886
887
  const candidates = [
887
888
  override,
888
889
  process.env.T3_BIN,
@@ -896,6 +897,75 @@ function resolveLocalT3Binary(override) {
896
897
  }
897
898
  return "t3";
898
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
+ }
899
969
  async function pairLocalOfficialT3(options) {
900
970
  const bin = resolveLocalT3Binary(options?.t3Binary);
901
971
  let stdout = "";
@@ -1032,8 +1102,10 @@ function normalizeDispatchCommand(rawCommand) {
1032
1102
  }
1033
1103
  return { ...command, modelSelection: selObj };
1034
1104
  }
1035
- var PING_INTERVAL_MS = 25e3;
1036
- var PING_SILENCE_LIMIT_MS = 6e4;
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;
1037
1109
  var LocalT3Client = class {
1038
1110
  baseUrl;
1039
1111
  accessToken;
@@ -1053,8 +1125,13 @@ var LocalT3Client = class {
1053
1125
  terminalMetadata = /* @__PURE__ */ new Map();
1054
1126
  terminalStreams = /* @__PURE__ */ new Map();
1055
1127
  pingTimer = null;
1056
- /** Last time anything (Pong, Chunk, Exit…) arrived from the local T3 socket. */
1128
+ /** Last time a WebSocket pong or any message arrived from the local T3 socket. */
1057
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();
1058
1135
  reconnectTimer = null;
1059
1136
  backoffMs = 2e3;
1060
1137
  constructor(config, callbacks, initialThreads = []) {
@@ -1098,6 +1175,9 @@ var LocalT3Client = class {
1098
1175
  this.connected = false;
1099
1176
  this.subscribedThreads.clear();
1100
1177
  this.streamThreads.clear();
1178
+ this.interruptedStreams.clear();
1179
+ for (const timer of this.resubscribeTimers.values()) clearTimeout(timer);
1180
+ this.resubscribeTimers.clear();
1101
1181
  this.terminalStreams.clear();
1102
1182
  this.terminalMetadata.clear();
1103
1183
  this.streams.clear();
@@ -1181,15 +1261,25 @@ var LocalT3Client = class {
1181
1261
  this.lastInboundAt = Date.now();
1182
1262
  this.pingTimer = setInterval(() => {
1183
1263
  if (ws.readyState !== WebSocket.OPEN) return;
1184
- if (Date.now() - this.lastInboundAt > PING_SILENCE_LIMIT_MS) {
1185
- console.error("[local-t3] \u672C\u673A T3 \u8D85\u8FC7 60 \u79D2\u65E0\u4EFB\u4F55\u56DE\u5305\uFF0C\u65AD\u5F00\u5E76\u91CD\u8FDE\u2026");
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
+ );
1186
1268
  ws.terminate();
1187
1269
  return;
1188
1270
  }
1189
- ws.send(JSON.stringify({ _tag: "Ping" }));
1271
+ try {
1272
+ ws.ping();
1273
+ ws.send(JSON.stringify({ _tag: "Ping" }));
1274
+ } catch {
1275
+ }
1190
1276
  }, PING_INTERVAL_MS);
1191
1277
  void this.bootstrapStreams();
1192
1278
  });
1279
+ ws.on("pong", () => {
1280
+ if (this.ws !== ws) return;
1281
+ this.lastInboundAt = Date.now();
1282
+ });
1193
1283
  ws.on("message", (data) => {
1194
1284
  if (this.ws !== ws) return;
1195
1285
  this.lastInboundAt = Date.now();
@@ -1239,6 +1329,11 @@ var LocalT3Client = class {
1239
1329
  if (exitedThread) {
1240
1330
  this.streamThreads.delete(reqId);
1241
1331
  this.subscribedThreads.delete(exitedThread);
1332
+ if (!this.interruptedStreams.delete(reqId)) {
1333
+ this.scheduleThreadResubscribe(exitedThread);
1334
+ }
1335
+ } else {
1336
+ this.interruptedStreams.delete(reqId);
1242
1337
  }
1243
1338
  const pending = this.pending.get(reqId);
1244
1339
  if (!pending) return;
@@ -1306,7 +1401,27 @@ var LocalT3Client = class {
1306
1401
  return null;
1307
1402
  }
1308
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
+ }
1309
1423
  interruptStream(requestId) {
1424
+ this.interruptedStreams.add(requestId);
1310
1425
  this.streams.delete(requestId);
1311
1426
  if (this.ws?.readyState === WebSocket.OPEN) {
1312
1427
  try {
@@ -1385,6 +1500,7 @@ var LocalT3Client = class {
1385
1500
  return;
1386
1501
  }
1387
1502
  if (env.kind !== "event" || typeof env.sequence !== "number" || !env.event) return;
1503
+ this.resubscribeAttempts.delete(threadId);
1388
1504
  const cur = this.wantedThreads.get(threadId) ?? 0;
1389
1505
  if (env.sequence > cur) this.wantedThreads.set(threadId, env.sequence);
1390
1506
  this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
@@ -2011,6 +2127,14 @@ function createHubWebSocketAgent(targetUrl) {
2011
2127
  var MAX_BUFFERED_EVENTS = 5e3;
2012
2128
  var MAX_SENT_SEQUENCES = 2e4;
2013
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
+ }
2014
2138
  var EchoT3Bridge = class {
2015
2139
  configPath;
2016
2140
  config;
@@ -2026,9 +2150,17 @@ var EchoT3Bridge = class {
2026
2150
  /** True once the Hub's welcome arrived on the current link; events flow only then. */
2027
2151
  hubReady = false;
2028
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
+ */
2029
2158
  bufferedEvents = /* @__PURE__ */ new Map();
2030
- bufferOverflowed = false;
2159
+ /** Lowest sequence dropped because the buffer was full; replayed from T3 on welcome. */
2160
+ overflowFromSequence = null;
2031
2161
  sentSequences = /* @__PURE__ */ new Set();
2162
+ /** True when the current Hub link acknowledges stored events (welcome.eventAck). */
2163
+ hubAcksEvents = false;
2032
2164
  constructor(configPath) {
2033
2165
  this.configPath = configPath;
2034
2166
  }
@@ -2086,47 +2218,105 @@ var EchoT3Bridge = class {
2086
2218
  }
2087
2219
  /**
2088
2220
  * Forward a T3 event to the Hub verbatim (sequence, occurredAt, driver,
2089
- * providerInstanceId all stay inside `event`). While the Hub link is not
2090
- * ready the event is buffered (bounded) and flushed in sequence order after
2091
- * the welcome frame; overflow is recovered by re-subscribing from T3.
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.
2092
2226
  */
2093
2227
  forwardThreadEvent(envelope) {
2094
2228
  const seq = envelope.sequence;
2095
- if (this.sentSequences.has(seq)) return;
2096
- if (this.hubReady && this.hubWs?.readyState === WebSocket2.OPEN) {
2097
- this.sendEventNow(envelope);
2098
- return;
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
+ }
2099
2239
  }
2100
- if (this.bufferedEvents.has(seq)) return;
2101
- if (this.bufferedEvents.size >= MAX_BUFFERED_EVENTS) {
2102
- this.bufferOverflowed = true;
2103
- return;
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;
2104
2248
  }
2105
- this.bufferedEvents.set(seq, envelope);
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`);
2106
2250
  }
2107
- sendEventNow(envelope) {
2108
- this.sentSequences.add(envelope.sequence);
2251
+ rememberSent(seq) {
2252
+ this.sentSequences.add(seq);
2109
2253
  if (this.sentSequences.size > MAX_SENT_SEQUENCES) {
2110
2254
  const oldest = this.sentSequences.values().next().value;
2111
2255
  if (oldest !== void 0) this.sentSequences.delete(oldest);
2112
2256
  }
2113
- this.sendHubFrame({ type: "event", data: envelope });
2114
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. */
2115
2293
  flushBufferedEvents() {
2116
2294
  const ordered = [...this.bufferedEvents.values()].sort((a, b) => a.sequence - b.sequence);
2117
- this.bufferedEvents.clear();
2118
- for (const envelope of ordered) {
2119
- if (!this.sentSequences.has(envelope.sequence)) this.sendEventNow(envelope);
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
+ );
2120
2299
  }
2300
+ if (!this.hubAcksEvents) this.bufferedEvents.clear();
2301
+ for (const envelope of ordered) this.sendEventNow(envelope);
2121
2302
  }
2122
- /** Ask T3 to replay everything after `afterSequence`; duplicates are dropped by sequence. */
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
+ */
2123
2308
  resumeEventsAfter(afterSequence) {
2124
2309
  const after = typeof afterSequence === "number" ? afterSequence : Number(afterSequence);
2125
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`);
2126
2315
  this.localT3.resubscribeAfter(after);
2127
2316
  }
2128
2317
  teardownHub() {
2129
2318
  this.hubReady = false;
2319
+ this.hubAcksEvents = false;
2130
2320
  this.unackedHeartbeats = 0;
2131
2321
  this.localT3?.detachAllTerminals();
2132
2322
  if (this.heartbeatTimer) {
@@ -2337,17 +2527,28 @@ var EchoT3Bridge = class {
2337
2527
  this.sendHubFrame({ type: "heartbeat", id: `hb_${Date.now()}` });
2338
2528
  }, interval);
2339
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
+ );
2340
2534
  this.flushBufferedEvents();
2341
- const cursor = data.lastEventSequence;
2342
- if (typeof cursor === "number" && cursor > 0) {
2343
- this.bufferOverflowed = false;
2344
- this.resumeEventsAfter(cursor);
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);
2345
2542
  }
2543
+ if (resumeAfter !== null) this.resumeEventsAfter(resumeAfter);
2346
2544
  return;
2347
2545
  }
2348
2546
  case "heartbeat_ack":
2349
2547
  this.unackedHeartbeats = 0;
2350
2548
  return;
2549
+ case "event.ack":
2550
+ this.handleEventAck(frame.data);
2551
+ return;
2351
2552
  case "events.resume": {
2352
2553
  const data = frame.data ?? {};
2353
2554
  this.resumeEventsAfter(data.lastEventSequence ?? data.afterSequence);
@@ -2384,13 +2585,17 @@ var EchoT3Bridge = class {
2384
2585
  return;
2385
2586
  }
2386
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)}` : ""}`;
2387
2590
  try {
2388
- const cmd = frame.data ?? {};
2389
2591
  const result = await this.localT3.dispatchCommand(cmd);
2390
2592
  this.scheduleSaveKnownThreads();
2593
+ console.log(`[hub] command ${label} \u2192 ok`);
2391
2594
  this.replyHub(frame.type, frame.id, { ok: true, result });
2392
2595
  } catch (err) {
2393
- this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
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 });
2394
2599
  }
2395
2600
  return;
2396
2601
  }
@@ -2512,6 +2717,57 @@ var EchoT3Bridge = class {
2512
2717
  }
2513
2718
  };
2514
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
+
2515
2771
  // src/index.ts
2516
2772
  ensureProcessProxyEnv();
2517
2773
  function parseArgs(argv) {
@@ -2587,7 +2843,7 @@ function printHelp() {
2587
2843
  `);
2588
2844
  }
2589
2845
  function runServiceScript(action, configPath) {
2590
- const currentDir = dirname3(fileURLToPath(import.meta.url));
2846
+ const currentDir = dirname5(fileURLToPath(import.meta.url));
2591
2847
  const scriptPath = resolve3(currentDir, "..", "scripts", "service.mjs");
2592
2848
  const res = spawnSync(process.execPath, [scriptPath, action, "--config", configPath], {
2593
2849
  stdio: "inherit"
@@ -2675,6 +2931,10 @@ async function doDoctor(configPath) {
2675
2931
  console.log(
2676
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"}`
2677
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()}`);
2678
2938
  }
2679
2939
  async function main() {
2680
2940
  const parsed = parseArgs(process.argv.slice(2));
@@ -2702,6 +2962,10 @@ async function main() {
2702
2962
  return;
2703
2963
  }
2704
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));
2705
2969
  const bridge = new EchoT3Bridge(configPath);
2706
2970
  const shutdown = () => {
2707
2971
  console.log("[bridge] \u6B63\u5728\u505C\u6B62\u2026");
@@ -4,11 +4,22 @@ import { createDpopProof, renewHubToken } from './dpop.js';
4
4
  import { listDirectories } from './fs-list.js';
5
5
  import { LocalT3Client } from './local-t3.js';
6
6
  import { createHubWebSocketAgent, ensureProcessProxyEnv } from './proxy.js';
7
- /** Max thread events held while the Hub link is down; the rest is re-fetched from T3. */
7
+ /**
8
+ * Max thread events held until the Hub confirms them (ack mode) or while the
9
+ * Hub link is down (legacy mode); the rest is re-fetched from T3's own log.
10
+ */
8
11
  const MAX_BUFFERED_EVENTS = 5_000;
9
- /** Remembered sequences already sent to the Hub, to drop duplicate replays. */
12
+ /** Remembered sequences already sent to the Hub, to drop duplicate live deliveries. */
10
13
  const MAX_SENT_SEQUENCES = 20_000;
11
14
  const MAX_MISSED_HEARTBEAT_ACKS = 3;
15
+ /** Logs run lifecycle events (sequence, runId, status) for layer-by-layer tracing. */
16
+ function logRunEvent(envelope) {
17
+ const event = envelope.event;
18
+ const type = typeof event?.type === 'string' ? event.type : '';
19
+ if (type !== 'run.created' && type !== 'run.updated')
20
+ return;
21
+ console.log(`[event] seq=${envelope.sequence} ${type} thread=${String(event?.threadId ?? '')} runId=${String(event?.payload?.id ?? '')} status=${String(event?.payload?.status ?? '')}`);
22
+ }
12
23
  /**
13
24
  * Bidirectional reverse bridge daemon:
14
25
  * - Outbound DPoP-authenticated WebSocket to Echo Hub (`wss://wq.stormapex.top/api/t3/device/link`)
@@ -30,9 +41,17 @@ export class EchoT3Bridge {
30
41
  /** True once the Hub's welcome arrived on the current link; events flow only then. */
31
42
  hubReady = false;
32
43
  unackedHeartbeats = 0;
44
+ /**
45
+ * Events not yet known to be stored by the Hub. In ack mode an event stays
46
+ * here until the Hub's `event.ack` for its sequence arrives; in legacy mode
47
+ * (older Hub without acks) only while the link is not ready.
48
+ */
33
49
  bufferedEvents = new Map();
34
- bufferOverflowed = false;
50
+ /** Lowest sequence dropped because the buffer was full; replayed from T3 on welcome. */
51
+ overflowFromSequence = null;
35
52
  sentSequences = new Set();
53
+ /** True when the current Hub link acknowledges stored events (welcome.eventAck). */
54
+ hubAcksEvents = false;
36
55
  constructor(configPath) {
37
56
  this.configPath = configPath;
38
57
  }
@@ -87,52 +106,119 @@ export class EchoT3Bridge {
87
106
  }
88
107
  /**
89
108
  * Forward a T3 event to the Hub verbatim (sequence, occurredAt, driver,
90
- * providerInstanceId all stay inside `event`). While the Hub link is not
91
- * ready the event is buffered (bounded) and flushed in sequence order after
92
- * the welcome frame; overflow is recovered by re-subscribing from T3.
109
+ * providerInstanceId all stay inside `event`). An event counts as delivered
110
+ * only once the Hub has it: in ack mode when `event.ack` arrives, in legacy
111
+ * mode when the frame was written to an open socket. Anything else stays
112
+ * buffered (bounded) and is resent in sequence order after the next welcome;
113
+ * overflow is recovered by re-subscribing from T3's own log.
93
114
  */
94
115
  forwardThreadEvent(envelope) {
95
116
  const seq = envelope.sequence;
96
- if (this.sentSequences.has(seq))
97
- return;
98
- if (this.hubReady && this.hubWs?.readyState === WebSocket.OPEN) {
99
- this.sendEventNow(envelope);
117
+ logRunEvent(envelope);
118
+ if (this.sentSequences.has(seq) && !this.bufferedEvents.has(seq))
100
119
  return;
120
+ if (!this.bufferedEvents.has(seq)) {
121
+ if (this.bufferedEvents.size >= MAX_BUFFERED_EVENTS) {
122
+ this.noteOverflow(seq);
123
+ return;
124
+ }
125
+ if (this.hubAcksEvents || !this.isHubReady()) {
126
+ this.bufferedEvents.set(seq, envelope);
127
+ }
101
128
  }
102
- if (this.bufferedEvents.has(seq))
103
- return;
104
- if (this.bufferedEvents.size >= MAX_BUFFERED_EVENTS) {
105
- this.bufferOverflowed = true;
106
- return;
129
+ if (this.isHubReady())
130
+ this.sendEventNow(envelope);
131
+ }
132
+ isHubReady() {
133
+ return this.hubReady && this.hubWs?.readyState === WebSocket.OPEN;
134
+ }
135
+ noteOverflow(seq) {
136
+ if (this.overflowFromSequence === null || seq < this.overflowFromSequence) {
137
+ this.overflowFromSequence = seq;
107
138
  }
108
- this.bufferedEvents.set(seq, envelope);
139
+ console.error(`[hub] 待确认事件超过 ${MAX_BUFFERED_EVENTS} 条,sequence=${seq} 起将在重连后从本机 T3 重新拉取`);
109
140
  }
110
- sendEventNow(envelope) {
111
- this.sentSequences.add(envelope.sequence);
141
+ rememberSent(seq) {
142
+ this.sentSequences.add(seq);
112
143
  if (this.sentSequences.size > MAX_SENT_SEQUENCES) {
113
144
  const oldest = this.sentSequences.values().next().value;
114
145
  if (oldest !== undefined)
115
146
  this.sentSequences.delete(oldest);
116
147
  }
117
- this.sendHubFrame({ type: 'event', data: envelope });
118
148
  }
149
+ sendEventNow(envelope) {
150
+ const ws = this.hubWs;
151
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
152
+ // Keep it for the next link instead of dropping it.
153
+ if (!this.bufferedEvents.has(envelope.sequence))
154
+ this.bufferedEvents.set(envelope.sequence, envelope);
155
+ return;
156
+ }
157
+ const seq = envelope.sequence;
158
+ this.rememberSent(seq);
159
+ ws.send(JSON.stringify({ type: 'event', data: envelope }), (err) => {
160
+ if (!err) {
161
+ // Legacy Hub (no acks): a written frame is all the confirmation there is.
162
+ if (!this.hubAcksEvents)
163
+ this.bufferedEvents.delete(seq);
164
+ return;
165
+ }
166
+ // Never reached the Hub: forget it was sent so the next link resends it.
167
+ this.sentSequences.delete(seq);
168
+ if (!this.bufferedEvents.has(seq) && this.bufferedEvents.size < MAX_BUFFERED_EVENTS) {
169
+ this.bufferedEvents.set(seq, envelope);
170
+ }
171
+ else if (!this.bufferedEvents.has(seq)) {
172
+ this.noteOverflow(seq);
173
+ }
174
+ console.error(`[hub] 事件发送失败,重连后重发: sequence=${seq} ${err.message}`);
175
+ });
176
+ }
177
+ handleEventAck(data) {
178
+ const ack = (data ?? {});
179
+ const seqs = [];
180
+ if (typeof ack.sequence === 'number')
181
+ seqs.push(ack.sequence);
182
+ if (Array.isArray(ack.sequences)) {
183
+ for (const v of ack.sequences)
184
+ if (typeof v === 'number')
185
+ seqs.push(v);
186
+ }
187
+ for (const seq of seqs) {
188
+ this.bufferedEvents.delete(seq);
189
+ this.rememberSent(seq);
190
+ }
191
+ }
192
+ /** Resend everything not yet confirmed, oldest first. */
119
193
  flushBufferedEvents() {
120
194
  const ordered = [...this.bufferedEvents.values()].sort((a, b) => a.sequence - b.sequence);
121
- this.bufferedEvents.clear();
122
- for (const envelope of ordered) {
123
- if (!this.sentSequences.has(envelope.sequence))
124
- this.sendEventNow(envelope);
195
+ if (ordered.length > 0) {
196
+ console.log(`[hub] 重发 ${ordered.length} 条未确认事件 (sequence ${ordered[0].sequence}..${ordered[ordered.length - 1].sequence})`);
125
197
  }
198
+ if (!this.hubAcksEvents)
199
+ this.bufferedEvents.clear();
200
+ for (const envelope of ordered)
201
+ this.sendEventNow(envelope);
126
202
  }
127
- /** Ask T3 to replay everything after `afterSequence`; duplicates are dropped by sequence. */
203
+ /**
204
+ * Ask T3 to replay everything after `afterSequence`. The Hub asked for these,
205
+ * so local "already sent" marks above the cursor are dropped first; the Hub
206
+ * ignores duplicates by (environment_id, sequence).
207
+ */
128
208
  resumeEventsAfter(afterSequence) {
129
209
  const after = typeof afterSequence === 'number' ? afterSequence : Number(afterSequence);
130
210
  if (!Number.isFinite(after) || after < 0)
131
211
  return;
212
+ for (const seq of [...this.sentSequences]) {
213
+ if (seq > after)
214
+ this.sentSequences.delete(seq);
215
+ }
216
+ console.log(`[hub] 从本机 T3 重新拉取 sequence>${after} 的事件`);
132
217
  this.localT3.resubscribeAfter(after);
133
218
  }
134
219
  teardownHub() {
135
220
  this.hubReady = false;
221
+ this.hubAcksEvents = false;
136
222
  this.unackedHeartbeats = 0;
137
223
  this.localT3?.detachAllTerminals();
138
224
  if (this.heartbeatTimer) {
@@ -368,20 +454,31 @@ export class EchoT3Bridge {
368
454
  this.unackedHeartbeats += 1;
369
455
  this.sendHubFrame({ type: 'heartbeat', id: `hb_${Date.now()}` });
370
456
  }, interval);
371
- // Link is ready: flush what was buffered while offline, in order, then
372
- // replay whatever the Hub's cursor says it has not stored yet.
457
+ // Link is ready. Resend what the Hub has not confirmed, in order, then
458
+ // replay whatever the Hub's stored cursor (or a buffer overflow) says
459
+ // it is missing from T3's own log.
373
460
  this.hubReady = true;
461
+ this.hubAcksEvents = data.eventAck === true;
462
+ console.log(`[hub] welcome: cursor=${data.lastEventSequence ?? 'null'} eventAck=${this.hubAcksEvents} pending=${this.bufferedEvents.size}`);
374
463
  this.flushBufferedEvents();
375
- const cursor = data.lastEventSequence;
376
- if (typeof cursor === 'number' && cursor > 0) {
377
- this.bufferOverflowed = false;
378
- this.resumeEventsAfter(cursor);
464
+ const cursor = typeof data.lastEventSequence === 'number' ? data.lastEventSequence : null;
465
+ const overflow = this.overflowFromSequence;
466
+ this.overflowFromSequence = null;
467
+ let resumeAfter = cursor !== null && cursor > 0 ? cursor : null;
468
+ if (overflow !== null) {
469
+ const beforeOverflow = Math.max(0, overflow - 1);
470
+ resumeAfter = resumeAfter === null ? beforeOverflow : Math.min(resumeAfter, beforeOverflow);
379
471
  }
472
+ if (resumeAfter !== null)
473
+ this.resumeEventsAfter(resumeAfter);
380
474
  return;
381
475
  }
382
476
  case 'heartbeat_ack':
383
477
  this.unackedHeartbeats = 0;
384
478
  return;
479
+ case 'event.ack':
480
+ this.handleEventAck(frame.data);
481
+ return;
385
482
  case 'events.resume': {
386
483
  const data = (frame.data ?? {});
387
484
  this.resumeEventsAfter(data.lastEventSequence ?? data.afterSequence);
@@ -421,14 +518,19 @@ export class EchoT3Bridge {
421
518
  return;
422
519
  }
423
520
  case 'command': {
521
+ const cmd = (frame.data ?? {});
522
+ // Only the command type and ids are logged, never message text.
523
+ const label = `type=${String(cmd.type ?? '')}${cmd.threadId ? ` thread=${String(cmd.threadId)}` : ''}${cmd.runId ? ` runId=${String(cmd.runId)}` : ''}`;
424
524
  try {
425
- const cmd = (frame.data ?? {});
426
525
  const result = await this.localT3.dispatchCommand(cmd);
427
526
  this.scheduleSaveKnownThreads();
527
+ console.log(`[hub] command ${label} → ok`);
428
528
  this.replyHub(frame.type, frame.id, { ok: true, result });
429
529
  }
430
530
  catch (err) {
431
- this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
531
+ const rpcError = this.toRpcError(err);
532
+ console.error(`[hub] command ${label} → ${rpcError.tag}: ${rpcError.message}`);
533
+ this.replyHub(frame.type, frame.id, { ok: false, error: rpcError });
432
534
  }
433
535
  return;
434
536
  }
@@ -3,7 +3,7 @@ import { homedir, hostname } from 'node:os';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  export const DEFAULT_HUB_SERVER = 'https://wq.stormapex.top';
5
5
  export const DEFAULT_LOCAL_T3_URL = 'http://127.0.0.1:3773';
6
- export const APP_VERSION = '0.1.6';
6
+ export const APP_VERSION = '0.1.7';
7
7
  export function defaultDataDir() {
8
8
  if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
9
9
  return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
package/dist/tsc/index.js CHANGED
@@ -5,6 +5,7 @@ import { EchoT3Bridge } from './bridge.js';
5
5
  import { APP_VERSION, clearHubCredentials, DEFAULT_HUB_SERVER, DEFAULT_LOCAL_T3_URL, defaultConfigPath, defaultDeviceLabel, loadConfig, normalizeServerUrl, saveConfig, } from './config.js';
6
6
  import { fetchHubSelf, pairWithHub, renewHubToken, unpairFromHub } from './dpop.js';
7
7
  import { pairLocalOfficialT3, probeLocalT3Health, resolveLocalT3Binary } from './local-t3.js';
8
+ import { installRunLogging, removePidFile, serviceLogPath, writePidFile } from './logging.js';
8
9
  import { ensureProcessProxyEnv } from './proxy.js';
9
10
  ensureProcessProxyEnv();
10
11
  function parseArgs(argv) {
@@ -178,6 +179,10 @@ async function doDoctor(configPath) {
178
179
  const t3Bin = resolveLocalT3Binary(cfg.localT3.t3Binary);
179
180
  const localOk = await probeLocalT3Health(cfg.localT3.baseUrl);
180
181
  console.log(`本机原版 T3: ${cfg.localT3.baseUrl} | 二进制: ${t3Bin} | 服务: ${localOk ? '● 运行中' : '○ 未启动(请运行 t3 up)'} | 本地令牌: ${cfg.localT3.accessToken ? '已授权' : '未授权'}`);
182
+ if (cfg.localT3.t3Binary && t3Bin !== cfg.localT3.t3Binary) {
183
+ console.log(` 配置中的 t3 路径 ${cfg.localT3.t3Binary} 已不可用,已自动改用 ${t3Bin}`);
184
+ }
185
+ console.log(`后台服务日志: ${serviceLogPath()}`);
181
186
  }
182
187
  async function main() {
183
188
  const parsed = parseArgs(process.argv.slice(2));
@@ -205,6 +210,10 @@ async function main() {
205
210
  return;
206
211
  }
207
212
  case 'run': {
213
+ installRunLogging();
214
+ console.log(`[bridge] echo-t3-bridge v${APP_VERSION} 启动 (pid=${process.pid}, platform=${process.platform}, config=${configPath})`);
215
+ writePidFile(configPath);
216
+ process.on('exit', () => removePidFile(configPath));
208
217
  const bridge = new EchoT3Bridge(configPath);
209
218
  const shutdown = () => {
210
219
  console.log('[bridge] 正在停止…');
@@ -1,8 +1,8 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import crypto from 'node:crypto';
3
- import { existsSync } from 'node:fs';
3
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
- import { basename, join } from 'node:path';
5
+ import { basename, delimiter, dirname, isAbsolute, join } from 'node:path';
6
6
  import { promisify } from 'node:util';
7
7
  import WebSocket from 'ws';
8
8
  import { enrichProvidersWithQuotas } from './provider-quotas.js';
@@ -10,6 +10,8 @@ import { DEFAULT_LOCAL_T3_URL, defaultDeviceLabel, } from './config.js';
10
10
  import { ACCESS_TOKEN_TYPE, BOOTSTRAP_TOKEN_TYPE, TOKEN_EXCHANGE_GRANT_TYPE, } from './dpop.js';
11
11
  const execFileAsync = promisify(execFile);
12
12
  export function resolveLocalT3Binary(override) {
13
+ if (process.platform === 'win32')
14
+ return resolveWindowsT3Binary(override);
13
15
  const candidates = [
14
16
  override,
15
17
  process.env.T3_BIN,
@@ -24,6 +26,105 @@ export function resolveLocalT3Binary(override) {
24
26
  }
25
27
  return 't3';
26
28
  }
29
+ /**
30
+ * Windows: Node's execFile cannot run the installer's `t3.cmd` shim (EINVAL)
31
+ * and the shim's folder is not on PATH, so the real `t3.exe` is resolved:
32
+ * override / T3_BIN (a .exe, or a .cmd shim that is read) → the exe named in
33
+ * `%USERPROFILE%\.local\bin\t3.cmd` (follows `t3 update`) → the newest
34
+ * `<T3_HOME>\runtime\versions\*\t3.exe` → `t3.exe` on PATH. A configured path
35
+ * that no longer exists is skipped, so an update never strands the bridge.
36
+ */
37
+ function resolveWindowsT3Binary(override) {
38
+ const fromPath = (candidate) => {
39
+ if (!candidate)
40
+ return null;
41
+ const trimmed = candidate.trim().replace(/^"(.*)"$/, '$1');
42
+ if (!trimmed || !existsSync(trimmed))
43
+ return null;
44
+ if (/\.(cmd|bat)$/i.test(trimmed))
45
+ return exeFromCmdShim(trimmed);
46
+ if (/\.exe$/i.test(trimmed))
47
+ return trimmed;
48
+ const withExe = `${trimmed}.exe`;
49
+ return existsSync(withExe) ? withExe : null;
50
+ };
51
+ const t3Home = process.env.T3_HOME?.trim() || join(homedir(), '.t3');
52
+ return (fromPath(override) ??
53
+ fromPath(process.env.T3_BIN) ??
54
+ exeFromCmdShim(join(homedir(), '.local', 'bin', 't3.cmd')) ??
55
+ newestRuntimeExe(t3Home) ??
56
+ (t3Home !== join(homedir(), '.t3') ? newestRuntimeExe(join(homedir(), '.t3')) : null) ??
57
+ exeOnPath('t3.exe') ??
58
+ 't3.exe');
59
+ }
60
+ /** Reads `"<path>\t3.exe" %*` out of the installer's shim. */
61
+ function exeFromCmdShim(cmdPath) {
62
+ try {
63
+ if (!existsSync(cmdPath))
64
+ return null;
65
+ const text = readFileSync(cmdPath, 'utf8');
66
+ const match = /"([^"]+\.exe)"/i.exec(text) ?? /^\s*([^\s"@][^\r\n]*?\.exe)\b/im.exec(text);
67
+ if (!match?.[1])
68
+ return null;
69
+ let exe = match[1].trim();
70
+ exe = exe.replace(/%~dp0\\?/gi, `${dirname(cmdPath)}\\`);
71
+ exe = exe.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (_m, name) => process.env[name] ?? '');
72
+ if (!isAbsolute(exe))
73
+ exe = join(dirname(cmdPath), exe);
74
+ return existsSync(exe) ? exe : null;
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ function compareVersionNames(a, b) {
81
+ const pa = a.replace(/^v/i, '').split(/[.\-+]/);
82
+ const pb = b.replace(/^v/i, '').split(/[.\-+]/);
83
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
84
+ const x = pa[i] ?? '';
85
+ const y = pb[i] ?? '';
86
+ const nx = Number(x);
87
+ const ny = Number(y);
88
+ if (Number.isFinite(nx) && Number.isFinite(ny) && x !== '' && y !== '') {
89
+ if (nx !== ny)
90
+ return nx - ny;
91
+ }
92
+ else if (x !== y) {
93
+ return x < y ? -1 : 1;
94
+ }
95
+ }
96
+ return 0;
97
+ }
98
+ function newestRuntimeExe(t3Home) {
99
+ const versionsDir = join(t3Home, 'runtime', 'versions');
100
+ try {
101
+ const versions = readdirSync(versionsDir).filter((name) => {
102
+ try {
103
+ return statSync(join(versionsDir, name)).isDirectory() && existsSync(join(versionsDir, name, 't3.exe'));
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ });
109
+ if (versions.length === 0)
110
+ return null;
111
+ versions.sort(compareVersionNames);
112
+ return join(versionsDir, versions[versions.length - 1], 't3.exe');
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ }
118
+ function exeOnPath(name) {
119
+ for (const dir of (process.env.PATH ?? process.env.Path ?? '').split(delimiter)) {
120
+ if (!dir)
121
+ continue;
122
+ const candidate = join(dir.replace(/^"(.*)"$/, '$1'), name);
123
+ if (existsSync(candidate))
124
+ return candidate;
125
+ }
126
+ return null;
127
+ }
27
128
  /**
28
129
  * Runs official unmodified `t3 pair` locally and exchanges the one-time token
29
130
  * over 127.0.0.1 for a local Bearer access token.
@@ -177,8 +278,17 @@ export function normalizeDispatchCommand(rawCommand) {
177
278
  }
178
279
  return { ...command, modelSelection: selObj };
179
280
  }
180
- const PING_INTERVAL_MS = 25_000;
181
- const PING_SILENCE_LIMIT_MS = 60_000;
281
+ /**
282
+ * Liveness of the local T3 socket is judged by WebSocket protocol ping/pong
283
+ * (answered by the server's WebSocket layer itself), never by application
284
+ * traffic: an idle thread legitimately sends nothing for minutes.
285
+ */
286
+ const PING_INTERVAL_MS = 20_000;
287
+ /** No pong (or any frame) for this long means the socket is dead. */
288
+ const PONG_TIMEOUT_MS = 50_000;
289
+ /** Delay before re-subscribing a thread stream the server ended on its own. */
290
+ const THREAD_RESUBSCRIBE_DELAY_MS = 2_000;
291
+ const MAX_THREAD_RESUBSCRIBE_ATTEMPTS = 6;
182
292
  /**
183
293
  * Persistent client connected to the local unmodified official T3 Code server
184
294
  * via its native `/api/auth/websocket-ticket`, Effect-RPC `/ws`, and HTTP APIs.
@@ -202,8 +312,13 @@ export class LocalT3Client {
202
312
  terminalMetadata = new Map();
203
313
  terminalStreams = new Map();
204
314
  pingTimer = null;
205
- /** Last time anything (Pong, Chunk, Exit…) arrived from the local T3 socket. */
315
+ /** Last time a WebSocket pong or any message arrived from the local T3 socket. */
206
316
  lastInboundAt = 0;
317
+ /** Thread streams this client ended itself (no automatic re-subscribe). */
318
+ interruptedStreams = new Set();
319
+ resubscribeTimers = new Map();
320
+ /** Consecutive server-ended streams per thread without an event in between. */
321
+ resubscribeAttempts = new Map();
207
322
  reconnectTimer = null;
208
323
  backoffMs = 2_000;
209
324
  constructor(config, callbacks, initialThreads = []) {
@@ -248,6 +363,10 @@ export class LocalT3Client {
248
363
  this.connected = false;
249
364
  this.subscribedThreads.clear();
250
365
  this.streamThreads.clear();
366
+ this.interruptedStreams.clear();
367
+ for (const timer of this.resubscribeTimers.values())
368
+ clearTimeout(timer);
369
+ this.resubscribeTimers.clear();
251
370
  this.terminalStreams.clear();
252
371
  this.terminalMetadata.clear();
253
372
  this.streams.clear();
@@ -340,15 +459,27 @@ export class LocalT3Client {
340
459
  this.pingTimer = setInterval(() => {
341
460
  if (ws.readyState !== WebSocket.OPEN)
342
461
  return;
343
- if (Date.now() - this.lastInboundAt > PING_SILENCE_LIMIT_MS) {
344
- console.error('[local-t3] 本机 T3 超过 60 秒无任何回包,断开并重连…');
462
+ if (Date.now() - this.lastInboundAt > PONG_TIMEOUT_MS) {
463
+ console.error(`[local-t3] 本机 T3 超过 ${Math.round(PONG_TIMEOUT_MS / 1000)} 秒未响应 WebSocket ping,断开并重连…`);
345
464
  ws.terminate();
346
465
  return;
347
466
  }
348
- ws.send(JSON.stringify({ _tag: 'Ping' }));
467
+ try {
468
+ ws.ping();
469
+ // Effect-RPC keep-alive for the server; not used for liveness.
470
+ ws.send(JSON.stringify({ _tag: 'Ping' }));
471
+ }
472
+ catch {
473
+ // The close handler reconnects.
474
+ }
349
475
  }, PING_INTERVAL_MS);
350
476
  void this.bootstrapStreams();
351
477
  });
478
+ ws.on('pong', () => {
479
+ if (this.ws !== ws)
480
+ return;
481
+ this.lastInboundAt = Date.now();
482
+ });
352
483
  ws.on('message', (data) => {
353
484
  if (this.ws !== ws)
354
485
  return;
@@ -405,6 +536,14 @@ export class LocalT3Client {
405
536
  if (exitedThread) {
406
537
  this.streamThreads.delete(reqId);
407
538
  this.subscribedThreads.delete(exitedThread);
539
+ if (!this.interruptedStreams.delete(reqId)) {
540
+ // The server ended the stream: continue it from the last sequence
541
+ // received (events not yet stored by the Hub stay buffered).
542
+ this.scheduleThreadResubscribe(exitedThread);
543
+ }
544
+ }
545
+ else {
546
+ this.interruptedStreams.delete(reqId);
408
547
  }
409
548
  const pending = this.pending.get(reqId);
410
549
  if (!pending)
@@ -473,7 +612,29 @@ export class LocalT3Client {
473
612
  return null;
474
613
  }
475
614
  }
615
+ scheduleThreadResubscribe(threadId) {
616
+ if (this.stopped || this.resubscribeTimers.has(threadId))
617
+ return;
618
+ const attempt = (this.resubscribeAttempts.get(threadId) ?? 0) + 1;
619
+ if (attempt > MAX_THREAD_RESUBSCRIBE_ATTEMPTS) {
620
+ // Ended repeatedly without any event (for example a deleted thread):
621
+ // the next command or snapshot for it subscribes again.
622
+ console.error(`[local-t3] 线程 ${threadId} 订阅连续 ${attempt - 1} 次被结束,暂停自动续订`);
623
+ return;
624
+ }
625
+ this.resubscribeAttempts.set(threadId, attempt);
626
+ const delay = Math.min(THREAD_RESUBSCRIBE_DELAY_MS * 2 ** (attempt - 1), 60_000);
627
+ const timer = setTimeout(() => {
628
+ this.resubscribeTimers.delete(threadId);
629
+ if (!this.isConnected())
630
+ return;
631
+ console.log(`[local-t3] 线程 ${threadId} 订阅被服务端结束,从 sequence ${this.wantedThreads.get(threadId) ?? 0} 之后续订`);
632
+ this.ensureThreadSubscribed(threadId, 0);
633
+ }, delay);
634
+ this.resubscribeTimers.set(threadId, timer);
635
+ }
476
636
  interruptStream(requestId) {
637
+ this.interruptedStreams.add(requestId);
477
638
  this.streams.delete(requestId);
478
639
  if (this.ws?.readyState === WebSocket.OPEN) {
479
640
  try {
@@ -570,6 +731,7 @@ export class LocalT3Client {
570
731
  }
571
732
  if (env.kind !== 'event' || typeof env.sequence !== 'number' || !env.event)
572
733
  return;
734
+ this.resubscribeAttempts.delete(threadId);
573
735
  const cur = this.wantedThreads.get(threadId) ?? 0;
574
736
  if (env.sequence > cur)
575
737
  this.wantedThreads.set(threadId, env.sequence);
@@ -0,0 +1,77 @@
1
+ import { mkdirSync, writeFileSync, unlinkSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { defaultDataDir } from './config.js';
4
+ /**
5
+ * Masks credentials that must never reach a log file: pairing codes, local
6
+ * T3 pairing tokens, Bearer/DPoP access tokens and refresh tokens.
7
+ */
8
+ export function redactSecrets(text) {
9
+ return text
10
+ .replace(/(--code[ =])\S+/gi, '$1***')
11
+ .replace(/(#token=)[^\s&"']+/gi, '$1***')
12
+ .replace(/(\btoken:\s*)[A-Z0-9-]{6,}/gi, '$1***')
13
+ .replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+/=-]{8,}/g, '$1 ***')
14
+ .replace(/("(?:accessToken|refreshToken|access_token|refresh_token|code|pairingCode|token)"\s*:\s*")[^"]*"/gi, '$1***"');
15
+ }
16
+ let installed = false;
17
+ /**
18
+ * For the long-running `run` command: every console line gets an ISO
19
+ * timestamp and secrets redacted, so a redirected background log (Windows
20
+ * bridge.log, launchd/systemd output) can be correlated with T3's own logs.
21
+ */
22
+ export function installRunLogging() {
23
+ if (installed)
24
+ return;
25
+ installed = true;
26
+ const wrap = (fn) => (...args) => {
27
+ const line = args
28
+ .map((a) => (typeof a === 'string' ? a : a instanceof Error ? a.stack ?? a.message : safeJson(a)))
29
+ .join(' ');
30
+ fn(`${new Date().toISOString()} ${redactSecrets(line)}`);
31
+ };
32
+ console.log = wrap(console.log.bind(console));
33
+ console.info = wrap(console.info.bind(console));
34
+ console.warn = wrap(console.warn.bind(console));
35
+ console.error = wrap(console.error.bind(console));
36
+ }
37
+ function safeJson(value) {
38
+ try {
39
+ return JSON.stringify(value);
40
+ }
41
+ catch {
42
+ return String(value);
43
+ }
44
+ }
45
+ /** Where the background service writes its log, per platform. */
46
+ export function serviceLogPath() {
47
+ const dataDir = defaultDataDir();
48
+ if (process.platform === 'win32')
49
+ return join(dataDir, 'bridge.log');
50
+ if (process.platform === 'darwin')
51
+ return join(dataDir, 'logs', 'bridge.stdout.log');
52
+ return 'journalctl --user -u echo-t3-bridge';
53
+ }
54
+ /** PID file of the running `run` process, used by the service script to avoid double instances. */
55
+ export function pidFilePath(configPath) {
56
+ return join(dirname(configPath), 'bridge.pid');
57
+ }
58
+ export function writePidFile(configPath) {
59
+ const path = pidFilePath(configPath);
60
+ try {
61
+ mkdirSync(dirname(path), { recursive: true });
62
+ writeFileSync(path, String(process.pid), 'utf8');
63
+ }
64
+ catch {
65
+ // best effort
66
+ }
67
+ }
68
+ export function removePidFile(configPath) {
69
+ const path = pidFilePath(configPath);
70
+ try {
71
+ if (readFileSync(path, 'utf8').trim() === String(process.pid))
72
+ unlinkSync(path);
73
+ }
74
+ catch {
75
+ // best effort
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "echo-t3-bridge",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Zero-fork bridge connecting an unmodified local T3 Code server to Echo Hub over a reverse WebSocket tunnel.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from 'node:fs';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { chmod, mkdir, unlink, writeFile } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { spawnSync } from 'node:child_process';
7
+ import { spawn, spawnSync } from 'node:child_process';
8
8
 
9
9
  const SERVICE_NAME = 'echo-t3-bridge';
10
10
  const LAUNCHD_LABEL = 'top.stormapex.echo-t3-bridge';
@@ -272,6 +272,12 @@ async function manageWindows(mode) {
272
272
  );
273
273
  const vbsPath = join(startupDir, `${SERVICE_NAME}.vbs`);
274
274
  const cmdPath = join(dataDir, 'run-bridge.cmd');
275
+ const logPath = join(dataDir, 'bridge.log');
276
+
277
+ // Never two bridges for one device: stop whatever runs now (also 0.1.6
278
+ // instances that predate the pid file) before installing, restarting or removing.
279
+ const stopped = stopWindowsBridge();
280
+ if (stopped > 0) console.log(`已停止正在运行的后台进程 (${stopped} 个)`);
275
281
 
276
282
  if (mode === 'uninstall') {
277
283
  await unlink(vbsPath).catch(() => undefined);
@@ -282,11 +288,24 @@ async function manageWindows(mode) {
282
288
 
283
289
  await mkdir(dataDir, { recursive: true });
284
290
  await mkdir(startupDir, { recursive: true });
285
- await writeFile(
286
- cmdPath,
287
- `@echo off\r\nset ECHO_T3_BRIDGE_CONFIG=${configPath}\r\n"${process.execPath}" "${cliEntry}" run\r\n`,
288
- 'utf8'
289
- );
291
+ const proxyLines = collectProxyEnvEntries()
292
+ .map(([k, v]) => `set "${k}=${v}"`)
293
+ .join('\r\n');
294
+ // stdout/stderr are appended to bridge.log (the bridge timestamps each line
295
+ // and redacts credentials); a log over ~5MB is rotated to bridge.log.1 at start.
296
+ const cmd = [
297
+ '@echo off',
298
+ 'chcp 65001 >nul',
299
+ 'setlocal',
300
+ `set "ECHO_T3_BRIDGE_CONFIG=${configPath}"`,
301
+ `set "ECHO_T3_BRIDGE_DATA_DIR=${dataDir}"`,
302
+ `set "LOG=${logPath}"`,
303
+ ...(proxyLines ? [proxyLines] : []),
304
+ 'if exist "%LOG%" for %%F in ("%LOG%") do if %%~zF GTR 5242880 move /Y "%LOG%" "%LOG%.1" >nul',
305
+ `"${process.execPath}" "${cliEntry}" run >> "%LOG%" 2>&1`,
306
+ '',
307
+ ].join('\r\n');
308
+ await writeFile(cmdPath, cmd, 'utf8');
290
309
  await writeFile(
291
310
  vbsPath,
292
311
  `Set WshShell = CreateObject("WScript.Shell")\r\nWshShell.Run """${cmdPath}""", 0, False\r\n`,
@@ -294,5 +313,75 @@ async function manageWindows(mode) {
294
313
  );
295
314
  await chmod(cmdPath, 0o755).catch(() => undefined);
296
315
  console.log(`✓ 已写入 Windows 自启脚本: ${vbsPath}`);
297
- console.log(' 可立即执行 `echo-t3-bridge run` 或双击自启脚本启动服务。');
316
+
317
+ // Start now, hidden, exactly like a logon would.
318
+ const child = spawn('wscript.exe', [vbsPath], { detached: true, stdio: 'ignore', windowsHide: true });
319
+ child.on('error', (err) => console.error(`启动后台进程失败: ${err.message}`));
320
+ child.unref();
321
+ const pid = await waitForPid(8_000);
322
+ if (pid) console.log(`✓ 后台进程已启动 (pid=${pid})`);
323
+ else console.warn('⚠ 未能确认后台进程已启动,请查看日志或手动运行 `echo-t3-bridge run`。');
324
+ console.log(` 日志: ${logPath}`);
325
+ }
326
+
327
+ function pidFile() {
328
+ return join(dirname(configPath), 'bridge.pid');
329
+ }
330
+
331
+ function readPid() {
332
+ try {
333
+ const pid = Number(readFileSync(pidFile(), 'utf8').trim());
334
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+
340
+ function isAlive(pid) {
341
+ try {
342
+ process.kill(pid, 0);
343
+ return true;
344
+ } catch (err) {
345
+ return err?.code === 'EPERM';
346
+ }
347
+ }
348
+
349
+ async function waitForPid(timeoutMs) {
350
+ const deadline = Date.now() + timeoutMs;
351
+ while (Date.now() < deadline) {
352
+ const pid = readPid();
353
+ if (pid && isAlive(pid)) return pid;
354
+ await new Promise((r) => setTimeout(r, 250));
355
+ }
356
+ return null;
357
+ }
358
+
359
+ /** Stops running bridge daemons (pid file, plus any `cli.mjs run` node process). */
360
+ function stopWindowsBridge() {
361
+ const pids = new Set();
362
+ const fromFile = readPid();
363
+ if (fromFile && isAlive(fromFile)) pids.add(fromFile);
364
+ const script = [
365
+ "$ErrorActionPreference='SilentlyContinue'",
366
+ 'Get-CimInstance Win32_Process |',
367
+ "Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -match 'echo-t3-bridge' -and $_.CommandLine -match 'cli[.]mjs.?\\s+run(\\s|$)' } |",
368
+ 'ForEach-Object { $_.ProcessId }',
369
+ ].join(' ');
370
+ const res = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
371
+ encoding: 'utf8',
372
+ timeout: 15_000,
373
+ windowsHide: true,
374
+ });
375
+ for (const line of (res.stdout ?? '').split(/\r?\n/)) {
376
+ const pid = Number(line.trim());
377
+ if (Number.isInteger(pid) && pid > 0) pids.add(pid);
378
+ }
379
+ pids.delete(process.pid);
380
+ pids.delete(process.ppid);
381
+ let count = 0;
382
+ for (const pid of pids) {
383
+ const kill = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { encoding: 'utf8', windowsHide: true });
384
+ if (kill.status === 0) count += 1;
385
+ }
386
+ return count;
298
387
  }