echo-t3-bridge 0.1.4 → 0.1.7

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,16 @@ 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. */
8
+ const MAX_BUFFERED_EVENTS = 5_000;
9
+ /** Remembered sequences already sent to the Hub, to drop duplicate replays. */
10
+ const MAX_SENT_SEQUENCES = 20_000;
11
+ const MAX_MISSED_HEARTBEAT_ACKS = 3;
7
12
  /**
8
13
  * Bidirectional reverse bridge daemon:
9
14
  * - Outbound DPoP-authenticated WebSocket to Echo Hub (`wss://wq.stormapex.top/api/t3/device/link`)
10
15
  * - Local WebSocket + HTTP connection to the unmodified official T3 server (`http://127.0.0.1:3773`)
11
- * - Automatic Antigravity `/usage` quota enrichment and model/thought_level normalization.
16
+ * - Automatic model/thought_level normalization and proactive DPoP token renewal.
12
17
  */
13
18
  export class EchoT3Bridge {
14
19
  configPath;
@@ -17,10 +22,17 @@ export class EchoT3Bridge {
17
22
  hubWs = null;
18
23
  stopped = false;
19
24
  heartbeatTimer = null;
25
+ tokenRefreshTimer = null;
20
26
  reconnectTimer = null;
21
27
  backoffMs = 2_000;
22
28
  saveThreadsTimer = null;
23
29
  bypassProxyOnNextAttempt = false;
30
+ /** True once the Hub's welcome arrived on the current link; events flow only then. */
31
+ hubReady = false;
32
+ unackedHeartbeats = 0;
33
+ bufferedEvents = new Map();
34
+ bufferOverflowed = false;
35
+ sentSequences = new Set();
24
36
  constructor(configPath) {
25
37
  this.configPath = configPath;
26
38
  }
@@ -35,7 +47,7 @@ export class EchoT3Bridge {
35
47
  this.sendHubFrame({ type: 'catalog', data: { providers } });
36
48
  },
37
49
  onThreadEvent: (envelope) => {
38
- this.sendHubFrame({ type: 'event', data: envelope });
50
+ this.forwardThreadEvent(envelope);
39
51
  this.scheduleSaveKnownThreads();
40
52
  },
41
53
  onTerminalEvent: (envelope) => {
@@ -73,12 +85,64 @@ export class EchoT3Bridge {
73
85
  void saveConfig(this.config, this.configPath).catch(() => undefined);
74
86
  }, 5_000);
75
87
  }
88
+ /**
89
+ * 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.
93
+ */
94
+ forwardThreadEvent(envelope) {
95
+ 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);
100
+ return;
101
+ }
102
+ if (this.bufferedEvents.has(seq))
103
+ return;
104
+ if (this.bufferedEvents.size >= MAX_BUFFERED_EVENTS) {
105
+ this.bufferOverflowed = true;
106
+ return;
107
+ }
108
+ this.bufferedEvents.set(seq, envelope);
109
+ }
110
+ sendEventNow(envelope) {
111
+ this.sentSequences.add(envelope.sequence);
112
+ if (this.sentSequences.size > MAX_SENT_SEQUENCES) {
113
+ const oldest = this.sentSequences.values().next().value;
114
+ if (oldest !== undefined)
115
+ this.sentSequences.delete(oldest);
116
+ }
117
+ this.sendHubFrame({ type: 'event', data: envelope });
118
+ }
119
+ flushBufferedEvents() {
120
+ 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);
125
+ }
126
+ }
127
+ /** Ask T3 to replay everything after `afterSequence`; duplicates are dropped by sequence. */
128
+ resumeEventsAfter(afterSequence) {
129
+ const after = typeof afterSequence === 'number' ? afterSequence : Number(afterSequence);
130
+ if (!Number.isFinite(after) || after < 0)
131
+ return;
132
+ this.localT3.resubscribeAfter(after);
133
+ }
76
134
  teardownHub() {
135
+ this.hubReady = false;
136
+ this.unackedHeartbeats = 0;
77
137
  this.localT3?.detachAllTerminals();
78
138
  if (this.heartbeatTimer) {
79
139
  clearInterval(this.heartbeatTimer);
80
140
  this.heartbeatTimer = null;
81
141
  }
142
+ if (this.tokenRefreshTimer) {
143
+ clearInterval(this.tokenRefreshTimer);
144
+ this.tokenRefreshTimer = null;
145
+ }
82
146
  const ws = this.hubWs;
83
147
  this.hubWs = null;
84
148
  if (ws) {
@@ -100,10 +164,31 @@ export class EchoT3Bridge {
100
164
  void this.connectHub();
101
165
  }, wait);
102
166
  }
103
- async ensureFreshHubCredentials() {
167
+ async syncHubCredentialsFromDiskIfNewer() {
168
+ const current = this.config.hub;
169
+ if (!current)
170
+ return false;
171
+ try {
172
+ const onDisk = await loadConfig(this.configPath);
173
+ const diskHub = onDisk.hub;
174
+ if (diskHub &&
175
+ diskHub.environmentId === current.environmentId &&
176
+ diskHub.accessToken !== current.accessToken &&
177
+ diskHub.accessTokenExpiresAt > current.accessTokenExpiresAt) {
178
+ this.config.hub = diskHub;
179
+ return true;
180
+ }
181
+ }
182
+ catch {
183
+ // ignore read errors
184
+ }
185
+ return false;
186
+ }
187
+ async ensureFreshHubCredentials(minRemainingMs = 5 * 60_000) {
188
+ await this.syncHubCredentialsFromDiskIfNewer();
104
189
  const creds = this.config.hub;
105
- // Renew if within 5 minutes of expiry.
106
- if (creds.accessTokenExpiresAt - Date.now() < 5 * 60_000) {
190
+ // Renew before expiry so `status` and reconnects always see a valid access token.
191
+ if (creds.accessTokenExpiresAt - Date.now() < minRemainingMs) {
107
192
  console.log('[hub] Access token 即将过期,正在续期…');
108
193
  const renewed = await renewHubToken(creds);
109
194
  this.config.hub = renewed;
@@ -156,6 +241,11 @@ export class EchoT3Bridge {
156
241
  this.teardownHub();
157
242
  if (status === 401 && !retriedAfterRenew) {
158
243
  try {
244
+ const adoptedNewer = await this.syncHubCredentialsFromDiskIfNewer();
245
+ if (adoptedNewer) {
246
+ void this.connectHub(true);
247
+ return;
248
+ }
159
249
  console.log('[hub] 尝试使用 DPoP 密钥刷新 Access Token…');
160
250
  const renewed = await renewHubToken(creds);
161
251
  this.config.hub = renewed;
@@ -177,6 +267,13 @@ export class EchoT3Bridge {
177
267
  this.bypassProxyOnNextAttempt = false;
178
268
  const via = proxyInfo ? ` via proxy ${proxyInfo.proxyUrl}` : '';
179
269
  console.log(`[hub] 已建立公网反向长连接 (${creds.serverUrl}, env=${creds.environmentId}${via})`);
270
+ if (this.tokenRefreshTimer)
271
+ clearInterval(this.tokenRefreshTimer);
272
+ this.tokenRefreshTimer = setInterval(() => {
273
+ void this.ensureFreshHubCredentials(10 * 60_000).catch((err) => {
274
+ console.error(`[hub] 后台续期失败: ${err instanceof Error ? err.message : String(err)}`);
275
+ });
276
+ }, 5 * 60_000);
180
277
  this.sendHubFrame({
181
278
  type: 'hello',
182
279
  data: {
@@ -251,20 +348,50 @@ export class EchoT3Bridge {
251
348
  case 'welcome': {
252
349
  const data = (frame.data ?? {});
253
350
  const interval = Math.max(5_000, Number(data.heartbeatIntervalMs) || 20_000);
351
+ this.unackedHeartbeats = 0;
254
352
  if (this.heartbeatTimer)
255
353
  clearInterval(this.heartbeatTimer);
256
354
  this.heartbeatTimer = setInterval(() => {
355
+ if (this.unackedHeartbeats >= MAX_MISSED_HEARTBEAT_ACKS) {
356
+ console.error(`[hub] 连续 ${MAX_MISSED_HEARTBEAT_ACKS} 个心跳周期未收到 heartbeat_ack,断开并重连…`);
357
+ const ws = this.hubWs;
358
+ this.teardownHub();
359
+ try {
360
+ ws?.terminate();
361
+ }
362
+ catch {
363
+ // ignore
364
+ }
365
+ this.scheduleHubReconnect();
366
+ return;
367
+ }
368
+ this.unackedHeartbeats += 1;
257
369
  this.sendHubFrame({ type: 'heartbeat', id: `hb_${Date.now()}` });
258
370
  }, 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.
373
+ this.hubReady = true;
374
+ this.flushBufferedEvents();
375
+ const cursor = data.lastEventSequence;
376
+ if (typeof cursor === 'number' && cursor > 0) {
377
+ this.bufferOverflowed = false;
378
+ this.resumeEventsAfter(cursor);
379
+ }
259
380
  return;
260
381
  }
261
382
  case 'heartbeat_ack':
262
- case 'events.resume':
383
+ this.unackedHeartbeats = 0;
384
+ return;
385
+ case 'events.resume': {
386
+ const data = (frame.data ?? {});
387
+ this.resumeEventsAfter(data.lastEventSequence ?? data.afterSequence);
263
388
  return;
389
+ }
264
390
  case 'providers.refresh': {
265
391
  try {
266
- const result = await this.localT3.refreshProviders(true);
267
- this.replyHub(frame.type, frame.id, { ok: true, result });
392
+ const providerId = frame.data?.providerId;
393
+ const result = await this.localT3.refreshProviders(true, typeof providerId === 'string' ? providerId : undefined);
394
+ this.replyHub(frame.type, frame.id, { ok: true, result: typeof providerId === 'string' ? { ...result, quotaProviderId: providerId } : result });
268
395
  }
269
396
  catch (err) {
270
397
  this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
@@ -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.4';
6
+ export const APP_VERSION = '0.1.6';
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
@@ -1,10 +1,9 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { probeAntigravityUsage, resolveAgyBinary } from './antigravity-quota.js';
5
4
  import { EchoT3Bridge } from './bridge.js';
6
5
  import { APP_VERSION, clearHubCredentials, DEFAULT_HUB_SERVER, DEFAULT_LOCAL_T3_URL, defaultConfigPath, defaultDeviceLabel, loadConfig, normalizeServerUrl, saveConfig, } from './config.js';
7
- import { fetchHubSelf, pairWithHub, unpairFromHub } from './dpop.js';
6
+ import { fetchHubSelf, pairWithHub, renewHubToken, unpairFromHub } from './dpop.js';
8
7
  import { pairLocalOfficialT3, probeLocalT3Health, resolveLocalT3Binary } from './local-t3.js';
9
8
  import { ensureProcessProxyEnv } from './proxy.js';
10
9
  ensureProcessProxyEnv();
@@ -66,10 +65,10 @@ function printHelp() {
66
65
  (别名: enroll)仅执行公网配对与本机原版 T3 授权,不安装后台服务
67
66
 
68
67
  echo-t3-bridge run
69
- 前台运行反向桥接守护进程(双向断线自动重连 + 实时事件流 + agy 额度增强)
68
+ 前台运行反向桥接守护进程(双向断线自动重连 + 实时事件流)
70
69
 
71
70
  echo-t3-bridge status | doctor
72
- 检查公网连接状态、本机官方原版 T3 服务状态、以及 agy 额度探测状态
71
+ 检查公网连接状态与本机官方原版 T3 服务状态
73
72
 
74
73
  echo-t3-bridge service <install|uninstall|restart>
75
74
  (别名: service:install / service:uninstall)管理后台开机自启服务
@@ -130,33 +129,55 @@ async function doPair(flags, configPath) {
130
129
  await saveConfig(cfg, configPath);
131
130
  console.log(`✓ 凭据已保存到 ${configPath}`);
132
131
  }
132
+ function sleepMs(ms) {
133
+ return new Promise((resolve) => setTimeout(resolve, ms));
134
+ }
133
135
  async function doDoctor(configPath) {
134
- const cfg = await loadConfig(configPath);
136
+ let cfg = await loadConfig(configPath);
135
137
  console.log(`echo-t3-bridge v${APP_VERSION}`);
136
138
  console.log(`配置文件: ${configPath}`);
137
139
  if (!cfg.hub) {
138
140
  console.log('公网 Hub: 未配对(请运行 echo-t3-bridge setup --code <配对码>)');
139
141
  }
140
142
  else {
141
- const self = await fetchHubSelf(cfg.hub).catch(() => ({ ok: false, status: 0 }));
142
- const envName = self.environment?.name || cfg.hub.label;
143
+ let hub = cfg.hub;
144
+ let self = await fetchHubSelf(hub).catch(() => ({ ok: false, status: 0 }));
145
+ // Right after `service install` or after >1h idle WS, the access token may be expired or just rotated by the daemon.
146
+ if (!self.ok && self.status === 401) {
147
+ await sleepMs(1500);
148
+ const reloaded = await loadConfig(configPath);
149
+ if (reloaded.hub && reloaded.hub.accessToken !== hub.accessToken) {
150
+ cfg = reloaded;
151
+ hub = reloaded.hub;
152
+ self = await fetchHubSelf(hub).catch(() => ({ ok: false, status: 0 }));
153
+ }
154
+ else if (reloaded.hub && reloaded.hub.sessionExpiresAt > Date.now()) {
155
+ try {
156
+ const renewed = await renewHubToken(reloaded.hub);
157
+ cfg = { ...reloaded, hub: renewed };
158
+ hub = renewed;
159
+ await saveConfig(cfg, configPath);
160
+ self = await fetchHubSelf(hub).catch(() => ({ ok: false, status: 0 }));
161
+ }
162
+ catch {
163
+ // Keep original 401 status if renewal fails (e.g. unpaired on Hub).
164
+ }
165
+ }
166
+ }
167
+ // Give a freshly restarted background daemon a moment to establish its Hub WebSocket.
168
+ if (self.ok && !self.online) {
169
+ await sleepMs(1500);
170
+ const retry = await fetchHubSelf(hub).catch(() => null);
171
+ if (retry && retry.ok)
172
+ self = retry;
173
+ }
174
+ const envName = self.environment?.name || hub.label;
143
175
  const online = self.online;
144
- console.log(`公网 Hub: ${cfg.hub.serverUrl} | 设备: ${envName} (${cfg.hub.environmentId}) | 凭据: ${self.ok ? '有效' : `异常 (HTTP ${self.status})`} | 在线: ${online ? '● 在线' : '○ 离线'}`);
176
+ console.log(`公网 Hub: ${hub.serverUrl} | 设备: ${envName} (${hub.environmentId}) | 凭据: ${self.ok ? '有效' : `异常 (HTTP ${self.status})`} | 在线: ${online ? '● 在线' : '○ 离线'}`);
145
177
  }
146
178
  const t3Bin = resolveLocalT3Binary(cfg.localT3.t3Binary);
147
179
  const localOk = await probeLocalT3Health(cfg.localT3.baseUrl);
148
180
  console.log(`本机原版 T3: ${cfg.localT3.baseUrl} | 二进制: ${t3Bin} | 服务: ${localOk ? '● 运行中' : '○ 未启动(请运行 t3 up)'} | 本地令牌: ${cfg.localT3.accessToken ? '已授权' : '未授权'}`);
149
- const agyBin = resolveAgyBinary();
150
- const agyUsage = await probeAntigravityUsage(true);
151
- if (agyUsage && agyUsage.windows.length > 0) {
152
- const summary = agyUsage.windows
153
- .map((w) => `${w.label} 剩 ${Math.round(100 - w.usedPercent)}%`)
154
- .join(' | ');
155
- console.log(`Antigravity 额度 (${agyBin}): ✓ ${summary}`);
156
- }
157
- else {
158
- console.log(`Antigravity 额度 (${agyBin}): 未检测到(如未安装 agy 可忽略)`);
159
- }
160
181
  }
161
182
  async function main() {
162
183
  const parsed = parseArgs(process.argv.slice(2));
@@ -177,6 +177,8 @@ export function normalizeDispatchCommand(rawCommand) {
177
177
  }
178
178
  return { ...command, modelSelection: selObj };
179
179
  }
180
+ const PING_INTERVAL_MS = 25_000;
181
+ const PING_SILENCE_LIMIT_MS = 60_000;
180
182
  /**
181
183
  * Persistent client connected to the local unmodified official T3 Code server
182
184
  * via its native `/api/auth/websocket-ticket`, Effect-RPC `/ws`, and HTTP APIs.
@@ -200,6 +202,8 @@ export class LocalT3Client {
200
202
  terminalMetadata = new Map();
201
203
  terminalStreams = new Map();
202
204
  pingTimer = null;
205
+ /** Last time anything (Pong, Chunk, Exit…) arrived from the local T3 socket. */
206
+ lastInboundAt = 0;
203
207
  reconnectTimer = null;
204
208
  backoffMs = 2_000;
205
209
  constructor(config, callbacks, initialThreads = []) {
@@ -332,16 +336,23 @@ export class LocalT3Client {
332
336
  this.backoffMs = 2_000;
333
337
  console.log(`[local-t3] 已连接本机原版 T3 Server (${this.baseUrl})`);
334
338
  this.callbacks.onStatusChange?.(true);
339
+ this.lastInboundAt = Date.now();
335
340
  this.pingTimer = setInterval(() => {
336
- if (ws.readyState === WebSocket.OPEN) {
337
- ws.send(JSON.stringify({ _tag: 'Ping' }));
341
+ if (ws.readyState !== WebSocket.OPEN)
342
+ return;
343
+ if (Date.now() - this.lastInboundAt > PING_SILENCE_LIMIT_MS) {
344
+ console.error('[local-t3] 本机 T3 超过 60 秒无任何回包,断开并重连…');
345
+ ws.terminate();
346
+ return;
338
347
  }
339
- }, 25_000);
348
+ ws.send(JSON.stringify({ _tag: 'Ping' }));
349
+ }, PING_INTERVAL_MS);
340
350
  void this.bootstrapStreams();
341
351
  });
342
352
  ws.on('message', (data) => {
343
353
  if (this.ws !== ws)
344
354
  return;
355
+ this.lastInboundAt = Date.now();
345
356
  this.handleWsMessage(data.toString());
346
357
  });
347
358
  ws.on('close', (code, reason) => {
@@ -475,14 +486,14 @@ export class LocalT3Client {
475
486
  }
476
487
  async bootstrapStreams() {
477
488
  // 1. Subscribe to native server config stream for live providers + cwd updates.
478
- this.startStream('subscribeServerConfig', { usageLimitSources: true, usageLimitsCommand: true }, (item) => {
489
+ this.startStream('subscribeServerConfig', {}, (item) => {
479
490
  void this.handleConfigEvent(item);
480
491
  });
481
492
  // 2. Subscribe to native terminal metadata stream so `terminal.list` is always instant.
482
493
  this.startStream('subscribeTerminalMetadata', {}, (item) => {
483
494
  this.handleTerminalMetadataEvent(item);
484
495
  });
485
- // 3. Proactively refresh providers & Antigravity quota right away.
496
+ // 3. Proactively refresh providers right away (without usage/quota probing on startup).
486
497
  void this.refreshProviders(false).catch(() => undefined);
487
498
  // 4. Re-subscribe any remembered thread streams.
488
499
  for (const [threadId, afterSeq] of this.wantedThreads.entries()) {
@@ -522,16 +533,14 @@ export class LocalT3Client {
522
533
  if (evt.config.cwd)
523
534
  this.defaultCwd = evt.config.cwd;
524
535
  if (Array.isArray(evt.config.providers)) {
525
- const enriched = await enrichProvidersWithQuotas(evt.config.providers, false);
526
- this.lastProviders = enriched;
527
- this.callbacks.onProviders(enriched);
536
+ this.lastProviders = evt.config.providers;
537
+ this.callbacks.onProviders(evt.config.providers);
528
538
  }
529
539
  }
530
540
  else if ((evt.type === 'providerStatuses' || evt.type === 'providerStatusDeltas') &&
531
541
  Array.isArray(evt.payload?.providers)) {
532
- const enriched = await enrichProvidersWithQuotas(evt.payload.providers, false);
533
- this.lastProviders = enriched;
534
- this.callbacks.onProviders(enriched);
542
+ this.lastProviders = evt.payload.providers;
543
+ this.callbacks.onProviders(evt.payload.providers);
535
544
  }
536
545
  }
537
546
  ensureThreadSubscribed(threadId, afterSequence = 0) {
@@ -573,17 +582,48 @@ export class LocalT3Client {
573
582
  this.subscribedThreads.delete(threadId);
574
583
  }
575
584
  }
576
- async refreshProviders(forceQuota = true) {
577
- const raw = (await this.callRpc('server.refreshProviders', { fresh: true, usageLimitsCommand: true }, 30_000));
585
+ /**
586
+ * Re-subscribe every known thread after `afterSequence` so events the Hub
587
+ * missed (while the Hub link was down or its buffer overflowed) are replayed
588
+ * from T3's own log. Replayed events are forwarded verbatim; the caller
589
+ * de-duplicates by sequence.
590
+ */
591
+ resubscribeAfter(afterSequence) {
592
+ if (!Number.isFinite(afterSequence) || afterSequence < 0)
593
+ return;
594
+ for (const threadId of [...this.wantedThreads.keys()]) {
595
+ for (const [reqId, tid] of [...this.streamThreads.entries()]) {
596
+ if (tid === threadId) {
597
+ this.streamThreads.delete(reqId);
598
+ this.interruptStream(reqId);
599
+ }
600
+ }
601
+ this.subscribedThreads.delete(threadId);
602
+ const cur = this.wantedThreads.get(threadId) ?? 0;
603
+ this.wantedThreads.set(threadId, Math.min(cur, afterSequence));
604
+ this.ensureThreadSubscribed(threadId, 0);
605
+ }
606
+ }
607
+ async refreshProviders(includeQuota = false, providerId) {
608
+ if (providerId) {
609
+ const finalList = await enrichProvidersWithQuotas(this.lastProviders, true, providerId);
610
+ this.lastProviders = finalList;
611
+ this.callbacks.onProviders(finalList);
612
+ return { providers: finalList };
613
+ }
614
+ const payload = includeQuota
615
+ ? { fresh: true, refreshModels: true, usageLimitsCommand: true }
616
+ : { fresh: true };
617
+ const raw = (await this.callRpc('server.refreshProviders', payload, 45_000));
578
618
  const list = Array.isArray(raw)
579
619
  ? raw
580
620
  : Array.isArray(raw?.providers)
581
621
  ? raw.providers
582
622
  : this.lastProviders;
583
- const enriched = await enrichProvidersWithQuotas(list, forceQuota);
584
- this.lastProviders = enriched;
585
- this.callbacks.onProviders(enriched);
586
- return { providers: enriched };
623
+ const finalList = includeQuota ? await enrichProvidersWithQuotas(list, true) : list;
624
+ this.lastProviders = finalList;
625
+ this.callbacks.onProviders(finalList);
626
+ return { providers: finalList };
587
627
  }
588
628
  async ensureProject(workspaceRoot) {
589
629
  let targetRoot = (workspaceRoot ?? '').trim();
@@ -375,12 +375,14 @@ async function probeDriverUsage(driver, force = false) {
375
375
  * Enriches all installed/enabled providers reported by the unmodified local T3
376
376
  * server using toc-ocra's proven quota readers (`agy`, `codex`, `claude`, `kiro`).
377
377
  */
378
- export async function enrichProvidersWithQuotas(providers, forceQuota = false) {
378
+ export async function enrichProvidersWithQuotas(providers, forceQuota = false, providerId) {
379
379
  const neededDrivers = new Set();
380
380
  for (const p of providers) {
381
381
  if (!p || typeof p !== 'object')
382
382
  continue;
383
383
  const rec = p;
384
+ if (providerId && String(rec.instanceId ?? '').toLowerCase() !== providerId.toLowerCase())
385
+ continue;
384
386
  if (rec.installed === false)
385
387
  continue;
386
388
  const driver = resolveQuotaDriver(rec);
@@ -393,8 +395,11 @@ export async function enrichProvidersWithQuotas(providers, forceQuota = false) {
393
395
  neededDrivers.add(driver);
394
396
  }
395
397
  }
396
- if (neededDrivers.size === 0)
398
+ if (neededDrivers.size === 0) {
399
+ if (providerId)
400
+ throw new Error('未找到可同步额度的 CLI');
397
401
  return providers;
402
+ }
398
403
  const probed = new Map();
399
404
  await Promise.all([...neededDrivers].map(async (driver) => {
400
405
  const limits = await probeDriverUsage(driver, forceQuota).catch(() => null);
@@ -402,8 +407,11 @@ export async function enrichProvidersWithQuotas(providers, forceQuota = false) {
402
407
  probed.set(driver, limits);
403
408
  }
404
409
  }));
405
- if (probed.size === 0)
410
+ if (probed.size === 0) {
411
+ if (providerId)
412
+ throw new Error('该 CLI 暂时无法读取额度');
406
413
  return providers;
414
+ }
407
415
  return providers.map((p) => {
408
416
  if (!p || typeof p !== 'object')
409
417
  return p;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "echo-t3-bridge",
3
- "version": "0.1.4",
3
+ "version": "0.1.7",
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": {
@@ -127,12 +127,22 @@ function xmlEscape(val) {
127
127
  .replaceAll("'", '&apos;');
128
128
  }
129
129
 
130
- function runCmd(cmd, args, ignoreFailure = false) {
131
- const res = spawnSync(cmd, args, { stdio: 'inherit' });
130
+ function runCmd(cmd, args, options = {}) {
131
+ const ignoreFailure = typeof options === 'boolean' ? options : Boolean(options.ignoreFailure);
132
+ const quiet = typeof options === 'object' && Boolean(options.quiet);
133
+ const res = spawnSync(cmd, args, {
134
+ stdio: quiet ? 'pipe' : 'inherit',
135
+ encoding: quiet ? 'utf8' : undefined,
136
+ });
132
137
  if (!ignoreFailure && res.status !== 0) {
138
+ if (quiet && res.stderr) process.stderr.write(res.stderr);
133
139
  process.exit(res.status ?? 1);
134
140
  }
135
- return res.status ?? 0;
141
+ return {
142
+ status: res.status ?? 0,
143
+ stdout: typeof res.stdout === 'string' ? res.stdout : '',
144
+ stderr: typeof res.stderr === 'string' ? res.stderr : '',
145
+ };
136
146
  }
137
147
 
138
148
  function sleepMs(ms) {
@@ -143,13 +153,13 @@ async function manageLaunchd(mode) {
143
153
  const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
144
154
  const domain = `gui/${process.getuid()}`;
145
155
  if (mode === 'uninstall') {
146
- runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
156
+ runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
147
157
  await unlink(target).catch(() => undefined);
148
158
  console.log(`已移除 macOS 后台服务: ${target}`);
149
159
  return;
150
160
  }
151
161
 
152
- runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
162
+ runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
153
163
  const logDir = join(dataDir, 'logs');
154
164
  await mkdir(dirname(target), { recursive: true });
155
165
  await mkdir(logDir, { recursive: true, mode: 0o700 });
@@ -181,24 +191,31 @@ ${proxyXml ? `${proxyXml}\n` : ''} </dict>
181
191
  </dict></plist>
182
192
  `;
183
193
  await writeFile(target, plist, { mode: 0o600 });
184
- runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], true);
185
- // macOS launchd tears down bootout asynchronously; retry bootstrap briefly before failing.
194
+ runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
195
+ // macOS launchd tears down bootout asynchronously; retry bootstrap quietly before failing.
186
196
  let bootstrapped = false;
197
+ let lastStderr = '';
187
198
  for (let attempt = 1; attempt <= 4; attempt++) {
188
199
  if (attempt > 1) {
189
200
  await sleepMs(700);
190
- runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
201
+ runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
191
202
  await sleepMs(400);
192
203
  }
193
- const status = runCmd('launchctl', ['bootstrap', domain, target], true);
194
- if (status === 0) {
204
+ const res = runCmd('launchctl', ['bootstrap', domain, target], { ignoreFailure: true, quiet: true });
205
+ if (res.status === 0) {
195
206
  bootstrapped = true;
196
207
  break;
197
208
  }
209
+ lastStderr = res.stderr;
198
210
  }
199
211
  if (!bootstrapped) {
200
- const kicked = runCmd('launchctl', ['kickstart', '-k', `${domain}/${LAUNCHD_LABEL}`], true);
201
- if (kicked !== 0) {
212
+ const kicked = runCmd('launchctl', ['kickstart', '-k', `${domain}/${LAUNCHD_LABEL}`], {
213
+ ignoreFailure: true,
214
+ quiet: true,
215
+ });
216
+ if (kicked.status !== 0) {
217
+ if (lastStderr) process.stderr.write(lastStderr);
218
+ if (kicked.stderr) process.stderr.write(kicked.stderr);
202
219
  process.exit(1);
203
220
  }
204
221
  }