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.
@@ -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);
@@ -389,8 +486,9 @@ export class EchoT3Bridge {
389
486
  }
390
487
  case 'providers.refresh': {
391
488
  try {
392
- const result = await this.localT3.refreshProviders(true);
393
- this.replyHub(frame.type, frame.id, { ok: true, result });
489
+ const providerId = frame.data?.providerId;
490
+ const result = await this.localT3.refreshProviders(true, typeof providerId === 'string' ? providerId : undefined);
491
+ this.replyHub(frame.type, frame.id, { ok: true, result: typeof providerId === 'string' ? { ...result, quotaProviderId: providerId } : result });
394
492
  }
395
493
  catch (err) {
396
494
  this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
@@ -420,14 +518,19 @@ export class EchoT3Bridge {
420
518
  return;
421
519
  }
422
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)}` : ''}`;
423
524
  try {
424
- const cmd = (frame.data ?? {});
425
525
  const result = await this.localT3.dispatchCommand(cmd);
426
526
  this.scheduleSaveKnownThreads();
527
+ console.log(`[hub] command ${label} → ok`);
427
528
  this.replyHub(frame.type, frame.id, { ok: true, result });
428
529
  }
429
530
  catch (err) {
430
- 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 });
431
534
  }
432
535
  return;
433
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);
@@ -604,7 +766,13 @@ export class LocalT3Client {
604
766
  this.ensureThreadSubscribed(threadId, 0);
605
767
  }
606
768
  }
607
- async refreshProviders(includeQuota = false) {
769
+ async refreshProviders(includeQuota = false, providerId) {
770
+ if (providerId) {
771
+ const finalList = await enrichProvidersWithQuotas(this.lastProviders, true, providerId);
772
+ this.lastProviders = finalList;
773
+ this.callbacks.onProviders(finalList);
774
+ return { providers: finalList };
775
+ }
608
776
  const payload = includeQuota
609
777
  ? { fresh: true, refreshModels: true, usageLimitsCommand: true }
610
778
  : { fresh: true };
@@ -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
+ }