echo-t3-bridge 0.1.3 → 0.1.6
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/dist/cli.mjs +415 -259
- package/dist/tsc/bridge.js +132 -6
- package/dist/tsc/config.js +1 -1
- package/dist/tsc/index.js +40 -19
- package/dist/tsc/local-t3.js +51 -17
- package/dist/tsc/proxy.js +7 -1
- package/package.json +1 -1
- package/scripts/service.mjs +47 -6
package/dist/tsc/bridge.js
CHANGED
|
@@ -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
|
|
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.
|
|
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
|
|
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
|
|
106
|
-
if (creds.accessTokenExpiresAt - Date.now() <
|
|
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,16 +348,45 @@ 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
|
-
|
|
383
|
+
this.unackedHeartbeats = 0;
|
|
263
384
|
return;
|
|
385
|
+
case 'events.resume': {
|
|
386
|
+
const data = (frame.data ?? {});
|
|
387
|
+
this.resumeEventsAfter(data.lastEventSequence ?? data.afterSequence);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
264
390
|
case 'providers.refresh': {
|
|
265
391
|
try {
|
|
266
392
|
const result = await this.localT3.refreshProviders(true);
|
package/dist/tsc/config.js
CHANGED
|
@@ -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
|
+
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
|
-
前台运行反向桥接守护进程(双向断线自动重连 +
|
|
68
|
+
前台运行反向桥接守护进程(双向断线自动重连 + 实时事件流)
|
|
70
69
|
|
|
71
70
|
echo-t3-bridge status | doctor
|
|
72
|
-
|
|
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
|
-
|
|
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
|
-
|
|
142
|
-
|
|
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: ${
|
|
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));
|
package/dist/tsc/local-t3.js
CHANGED
|
@@ -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
|
|
337
|
-
|
|
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
|
-
|
|
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', {
|
|
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
|
|
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
|
-
|
|
526
|
-
this.
|
|
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
|
-
|
|
533
|
-
this.
|
|
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,42 @@ export class LocalT3Client {
|
|
|
573
582
|
this.subscribedThreads.delete(threadId);
|
|
574
583
|
}
|
|
575
584
|
}
|
|
576
|
-
|
|
577
|
-
|
|
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) {
|
|
608
|
+
const payload = includeQuota
|
|
609
|
+
? { fresh: true, refreshModels: true, usageLimitsCommand: true }
|
|
610
|
+
: { fresh: true };
|
|
611
|
+
const raw = (await this.callRpc('server.refreshProviders', payload, 45_000));
|
|
578
612
|
const list = Array.isArray(raw)
|
|
579
613
|
? raw
|
|
580
614
|
: Array.isArray(raw?.providers)
|
|
581
615
|
? raw.providers
|
|
582
616
|
: this.lastProviders;
|
|
583
|
-
const
|
|
584
|
-
this.lastProviders =
|
|
585
|
-
this.callbacks.onProviders(
|
|
586
|
-
return { providers:
|
|
617
|
+
const finalList = includeQuota ? await enrichProvidersWithQuotas(list, true) : list;
|
|
618
|
+
this.lastProviders = finalList;
|
|
619
|
+
this.callbacks.onProviders(finalList);
|
|
620
|
+
return { providers: finalList };
|
|
587
621
|
}
|
|
588
622
|
async ensureProject(workspaceRoot) {
|
|
589
623
|
let targetRoot = (workspaceRoot ?? '').trim();
|
package/dist/tsc/proxy.js
CHANGED
|
@@ -277,8 +277,14 @@ export function createHubWebSocketAgent(targetUrl) {
|
|
|
277
277
|
return undefined;
|
|
278
278
|
}
|
|
279
279
|
}
|
|
280
|
+
const agent = new HttpConnectAgent({ keepAlive: false });
|
|
281
|
+
// Node's `https.request` (used by `ws` for `wss://`) validates `agent.protocol === 'https:'`.
|
|
282
|
+
Object.assign(agent, {
|
|
283
|
+
protocol: isSecureTarget ? 'https:' : 'http:',
|
|
284
|
+
defaultPort: isSecureTarget ? 443 : 80,
|
|
285
|
+
});
|
|
280
286
|
return {
|
|
281
|
-
agent
|
|
287
|
+
agent,
|
|
282
288
|
proxyUrl: proxyUrlStr,
|
|
283
289
|
};
|
|
284
290
|
}
|
package/package.json
CHANGED
package/scripts/service.mjs
CHANGED
|
@@ -127,24 +127,39 @@ function xmlEscape(val) {
|
|
|
127
127
|
.replaceAll("'", ''');
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
-
function runCmd(cmd, args,
|
|
131
|
-
const
|
|
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
|
}
|
|
141
|
+
return {
|
|
142
|
+
status: res.status ?? 0,
|
|
143
|
+
stdout: typeof res.stdout === 'string' ? res.stdout : '',
|
|
144
|
+
stderr: typeof res.stderr === 'string' ? res.stderr : '',
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function sleepMs(ms) {
|
|
149
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
135
150
|
}
|
|
136
151
|
|
|
137
152
|
async function manageLaunchd(mode) {
|
|
138
153
|
const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
|
|
139
154
|
const domain = `gui/${process.getuid()}`;
|
|
140
155
|
if (mode === 'uninstall') {
|
|
141
|
-
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
156
|
+
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
|
|
142
157
|
await unlink(target).catch(() => undefined);
|
|
143
158
|
console.log(`已移除 macOS 后台服务: ${target}`);
|
|
144
159
|
return;
|
|
145
160
|
}
|
|
146
161
|
|
|
147
|
-
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
162
|
+
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
|
|
148
163
|
const logDir = join(dataDir, 'logs');
|
|
149
164
|
await mkdir(dirname(target), { recursive: true });
|
|
150
165
|
await mkdir(logDir, { recursive: true, mode: 0o700 });
|
|
@@ -176,8 +191,34 @@ ${proxyXml ? `${proxyXml}\n` : ''} </dict>
|
|
|
176
191
|
</dict></plist>
|
|
177
192
|
`;
|
|
178
193
|
await writeFile(target, plist, { mode: 0o600 });
|
|
179
|
-
runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
180
|
-
|
|
194
|
+
runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
|
|
195
|
+
// macOS launchd tears down bootout asynchronously; retry bootstrap quietly before failing.
|
|
196
|
+
let bootstrapped = false;
|
|
197
|
+
let lastStderr = '';
|
|
198
|
+
for (let attempt = 1; attempt <= 4; attempt++) {
|
|
199
|
+
if (attempt > 1) {
|
|
200
|
+
await sleepMs(700);
|
|
201
|
+
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { ignoreFailure: true, quiet: true });
|
|
202
|
+
await sleepMs(400);
|
|
203
|
+
}
|
|
204
|
+
const res = runCmd('launchctl', ['bootstrap', domain, target], { ignoreFailure: true, quiet: true });
|
|
205
|
+
if (res.status === 0) {
|
|
206
|
+
bootstrapped = true;
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
lastStderr = res.stderr;
|
|
210
|
+
}
|
|
211
|
+
if (!bootstrapped) {
|
|
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);
|
|
219
|
+
process.exit(1);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
181
222
|
console.log(`✓ 已安装并启动 macOS 后台服务: ${LAUNCHD_LABEL}`);
|
|
182
223
|
console.log(` 日志目录: ${logDir}`);
|
|
183
224
|
}
|