echo-t3-bridge 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,276 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ const execFileAsync = promisify(execFile);
7
+ /** Parse macOS `scutil --proxy` output into standard proxy environment variables (ported from toc_ocra). */
8
+ export async function hydrateProxyEnv(baseEnv = process.env) {
9
+ const next = { ...baseEnv };
10
+ const hasProxy = Boolean(next.https_proxy?.trim() ||
11
+ next.HTTPS_PROXY?.trim() ||
12
+ next.http_proxy?.trim() ||
13
+ next.HTTP_PROXY?.trim() ||
14
+ next.all_proxy?.trim() ||
15
+ next.ALL_PROXY?.trim());
16
+ if (hasProxy || process.platform !== 'darwin')
17
+ return next;
18
+ try {
19
+ const { stdout } = await execFileAsync('scutil', ['--proxy'], { timeout: 2_000 });
20
+ const field = (name) => {
21
+ const m = new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, 'm').exec(stdout);
22
+ return m?.[1]?.trim() || undefined;
23
+ };
24
+ if (field('HTTPEnable') === '1' && field('HTTPProxy') && field('HTTPPort')) {
25
+ const url = `http://${field('HTTPProxy')}:${field('HTTPPort')}`;
26
+ next.http_proxy = url;
27
+ next.HTTP_PROXY = url;
28
+ }
29
+ if (field('HTTPSEnable') === '1' && field('HTTPSProxy') && field('HTTPSPort')) {
30
+ const url = `http://${field('HTTPSProxy')}:${field('HTTPSPort')}`;
31
+ next.https_proxy = url;
32
+ next.HTTPS_PROXY = url;
33
+ }
34
+ if (field('SOCKSEnable') === '1' && field('SOCKSProxy') && field('SOCKSPort')) {
35
+ const url = `socks5://${field('SOCKSProxy')}:${field('SOCKSPort')}`;
36
+ next.all_proxy = url;
37
+ next.ALL_PROXY = url;
38
+ if (!next.http_proxy && !next.https_proxy) {
39
+ next.http_proxy = url;
40
+ next.HTTP_PROXY = url;
41
+ next.https_proxy = url;
42
+ next.HTTPS_PROXY = url;
43
+ }
44
+ }
45
+ }
46
+ catch {
47
+ // ignore
48
+ }
49
+ return next;
50
+ }
51
+ const USAGE_ARGS = ['-p', '/usage', '--output-format', 'json', '--print-timeout', '20s'];
52
+ const USAGE_TIMEOUT_MS = 25_000;
53
+ const MAX_OUTPUT_BYTES = 512 * 1024;
54
+ const CACHE_TTL_MS = 60_000;
55
+ let cachedLimits = null;
56
+ let inflightProbe = null;
57
+ function antigravityUsesApiKeyProvider() {
58
+ try {
59
+ const raw = readFileSync(join(homedir(), '.gemini', 'antigravity-cli', 'settings.json'), 'utf8');
60
+ const parsed = JSON.parse(raw);
61
+ return Boolean(parsed?.modelProvider);
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ function scrubAntigravityEnv(baseEnv = process.env) {
68
+ const next = { ...baseEnv };
69
+ if (!antigravityUsesApiKeyProvider()) {
70
+ for (const key of Object.keys(next)) {
71
+ const normalized = process.platform === 'win32' ? key.toUpperCase() : key;
72
+ if (normalized === 'GEMINI_API_KEY' || normalized === 'GOOGLE_API_KEY') {
73
+ delete next[key];
74
+ }
75
+ }
76
+ }
77
+ next.AGY_CLI_DISABLE_AUTO_UPDATE = 'true';
78
+ return next;
79
+ }
80
+ export function resolveAgyBinary() {
81
+ const candidates = [
82
+ process.env.AGY_BIN,
83
+ join(homedir(), '.local', 'bin', 'agy'),
84
+ '/opt/homebrew/bin/agy',
85
+ '/usr/local/bin/agy',
86
+ ].filter((v) => Boolean(v));
87
+ for (const candidate of candidates) {
88
+ if (existsSync(candidate))
89
+ return candidate;
90
+ }
91
+ return 'agy';
92
+ }
93
+ function validResetIso(raw) {
94
+ if (typeof raw !== 'string' || !raw.trim())
95
+ return undefined;
96
+ const ms = Date.parse(raw);
97
+ // Ignore epoch zero (`1970-01-01T00:00:00Z`) reported for untouched 3p buckets.
98
+ if (!Number.isFinite(ms) || ms <= 86_400_000)
99
+ return undefined;
100
+ return new Date(ms).toISOString();
101
+ }
102
+ export function parseAgyUsageJson(stdout) {
103
+ const checkedAt = new Date().toISOString();
104
+ for (const line of stdout.split(/\r?\n/)) {
105
+ const trimmed = line.trim();
106
+ if (!trimmed.startsWith('{'))
107
+ continue;
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(trimmed);
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
116
+ continue;
117
+ // Guard against older agy treating `/usage` as a billed model turn.
118
+ if (typeof parsed.num_turns === 'number' && parsed.num_turns > 0)
119
+ return null;
120
+ if (typeof parsed.conversation_id === 'string' && parsed.conversation_id.trim())
121
+ return null;
122
+ if (parsed.status !== 'SUCCESS')
123
+ continue;
124
+ const command = parsed.command;
125
+ if (!command || command.name !== 'usage')
126
+ continue;
127
+ const data = command.data;
128
+ if (!data || !Array.isArray(data.groups))
129
+ continue;
130
+ const windows = new Map();
131
+ for (const rawGroup of data.groups) {
132
+ if (!rawGroup || typeof rawGroup !== 'object')
133
+ continue;
134
+ const group = rawGroup;
135
+ const groupName = typeof group.name === 'string' ? group.name.trim() : '';
136
+ if (!Array.isArray(group.buckets))
137
+ continue;
138
+ for (const rawBucket of group.buckets) {
139
+ if (!rawBucket || typeof rawBucket !== 'object')
140
+ continue;
141
+ const bucket = rawBucket;
142
+ if (bucket.disabled === true)
143
+ continue;
144
+ if (typeof bucket.remaining_fraction !== 'number' || !Number.isFinite(bucket.remaining_fraction)) {
145
+ continue;
146
+ }
147
+ const id = typeof bucket.id === 'string' && bucket.id.trim()
148
+ ? bucket.id.trim()
149
+ : `${groupName}-${String(bucket.window ?? 'quota')}`;
150
+ const winRaw = typeof bucket.window === 'string' ? bucket.window.trim() : '';
151
+ const weekly = winRaw === 'weekly';
152
+ const session = winRaw === '5h';
153
+ const family = id.startsWith('gemini-argon-')
154
+ ? groupName || 'Gemini Argon'
155
+ : id.startsWith('gemini-carbon-')
156
+ ? groupName || 'Gemini Carbon'
157
+ : id.startsWith('gemini-') || groupName.toLowerCase().includes('gemini')
158
+ ? 'Gemini'
159
+ : id.startsWith('3p-') || groupName.toLowerCase().includes('claude')
160
+ ? 'Claude / GPT'
161
+ : groupName || id;
162
+ const kind = weekly ? 'weekly' : session ? 'session' : 'other';
163
+ const windowDurationMins = weekly ? 7 * 24 * 60 : session ? 5 * 60 : undefined;
164
+ const usedPercent = (1 - Math.max(0, Math.min(1, bucket.remaining_fraction))) * 100;
165
+ const resetsAt = validResetIso(bucket.reset_time);
166
+ windows.set(id, {
167
+ id,
168
+ label: `${family} · ${weekly ? '每周额度' : session ? '5 小时额度' : (typeof bucket.name === 'string' && bucket.name.trim()) || '额度'}`,
169
+ kind,
170
+ usedPercent,
171
+ ...(resetsAt ? { resetsAt } : {}),
172
+ ...(windowDurationMins !== undefined ? { windowDurationMins } : {}),
173
+ });
174
+ }
175
+ }
176
+ if (windows.size > 0) {
177
+ return {
178
+ checkedAt,
179
+ windows: [...windows.values()],
180
+ };
181
+ }
182
+ }
183
+ return null;
184
+ }
185
+ /**
186
+ * Reads Antigravity quota directly via `agy -p /usage --output-format json`
187
+ * (the exact OCRA-verified mechanism, zero tokens consumed).
188
+ */
189
+ export async function probeAntigravityUsage(force = false) {
190
+ if (!force && cachedLimits && Date.now() - cachedLimits.fetchedAt < CACHE_TTL_MS) {
191
+ return cachedLimits.limits;
192
+ }
193
+ if (inflightProbe)
194
+ return inflightProbe;
195
+ inflightProbe = (async () => {
196
+ const proxyEnv = await hydrateProxyEnv();
197
+ return new Promise((resolve) => {
198
+ let settled = false;
199
+ let stdout = '';
200
+ const done = (val) => {
201
+ if (settled)
202
+ return;
203
+ settled = true;
204
+ clearTimeout(timer);
205
+ if (val) {
206
+ cachedLimits = { fetchedAt: Date.now(), limits: val };
207
+ }
208
+ resolve(val);
209
+ };
210
+ const bin = resolveAgyBinary();
211
+ const child = spawn(bin, [...USAGE_ARGS], {
212
+ env: scrubAntigravityEnv(proxyEnv),
213
+ stdio: ['ignore', 'pipe', 'pipe'],
214
+ windowsHide: true,
215
+ });
216
+ const timer = setTimeout(() => {
217
+ try {
218
+ child.kill('SIGKILL');
219
+ }
220
+ catch {
221
+ // ignore
222
+ }
223
+ done(null);
224
+ }, USAGE_TIMEOUT_MS);
225
+ child.stdout?.on('data', (chunk) => {
226
+ if (stdout.length < MAX_OUTPUT_BYTES) {
227
+ stdout += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
228
+ }
229
+ });
230
+ child.on('error', () => done(null));
231
+ child.on('close', (code) => {
232
+ if (code !== 0) {
233
+ done(null);
234
+ return;
235
+ }
236
+ done(parseAgyUsageJson(stdout));
237
+ });
238
+ });
239
+ })().finally(() => {
240
+ inflightProbe = null;
241
+ });
242
+ return inflightProbe;
243
+ }
244
+ /**
245
+ * Enriches the providers array reported by the unmodified local T3 server with
246
+ * real Antigravity usageLimits probed via `agy -p /usage --output-format json`.
247
+ */
248
+ export async function enrichProvidersWithAgyQuota(providers, forceQuota = false) {
249
+ const hasAgy = providers.some((p) => {
250
+ if (!p || typeof p !== 'object')
251
+ return false;
252
+ const rec = p;
253
+ return rec.driver === 'antigravity' || rec.instanceId === 'antigravity' || rec.instanceId === 'agy';
254
+ });
255
+ if (!hasAgy)
256
+ return providers;
257
+ const agyLimits = await probeAntigravityUsage(forceQuota);
258
+ if (!agyLimits || agyLimits.windows.length === 0)
259
+ return providers;
260
+ return providers.map((p) => {
261
+ if (!p || typeof p !== 'object')
262
+ return p;
263
+ const rec = p;
264
+ const isAgy = rec.driver === 'antigravity' || rec.instanceId === 'antigravity' || rec.instanceId === 'agy';
265
+ if (!isAgy)
266
+ return p;
267
+ const existing = rec.usageLimits;
268
+ if (existing && Array.isArray(existing.windows) && existing.windows.length > 0 && !forceQuota) {
269
+ return p;
270
+ }
271
+ return {
272
+ ...rec,
273
+ usageLimits: agyLimits,
274
+ };
275
+ });
276
+ }
@@ -0,0 +1,413 @@
1
+ import WebSocket from 'ws';
2
+ import { APP_VERSION, loadConfig, saveConfig, } from './config.js';
3
+ import { createDpopProof, renewHubToken } from './dpop.js';
4
+ import { listDirectories } from './fs-list.js';
5
+ import { LocalT3Client } from './local-t3.js';
6
+ /**
7
+ * Bidirectional reverse bridge daemon:
8
+ * - Outbound DPoP-authenticated WebSocket to Echo Hub (`wss://wq.stormapex.top/api/t3/device/link`)
9
+ * - Local WebSocket + HTTP connection to the unmodified official T3 server (`http://127.0.0.1:3773`)
10
+ * - Automatic Antigravity `/usage` quota enrichment and model/thought_level normalization.
11
+ */
12
+ export class EchoT3Bridge {
13
+ configPath;
14
+ config;
15
+ localT3;
16
+ hubWs = null;
17
+ stopped = false;
18
+ heartbeatTimer = null;
19
+ reconnectTimer = null;
20
+ backoffMs = 2_000;
21
+ saveThreadsTimer = null;
22
+ constructor(configPath) {
23
+ this.configPath = configPath;
24
+ }
25
+ async start() {
26
+ this.config = await loadConfig(this.configPath);
27
+ if (!this.config.hub) {
28
+ throw new Error('尚未与公网 Hub 配对。请先在网页端点击「生成配对码」,然后执行:\n echo-t3-bridge setup --code <配对码>');
29
+ }
30
+ this.localT3 = new LocalT3Client(this.config.localT3, {
31
+ onProviders: (providers) => {
32
+ this.sendHubFrame({ type: 'catalog', data: { providers } });
33
+ },
34
+ onThreadEvent: (envelope) => {
35
+ this.sendHubFrame({ type: 'event', data: envelope });
36
+ this.scheduleSaveKnownThreads();
37
+ },
38
+ onTerminalEvent: (envelope) => {
39
+ this.sendHubFrame({ type: 'terminal.event', data: envelope });
40
+ },
41
+ onTokenUpdated: async (baseUrl, accessToken) => {
42
+ this.config.localT3.baseUrl = baseUrl;
43
+ this.config.localT3.accessToken = accessToken;
44
+ await saveConfig(this.config, this.configPath);
45
+ },
46
+ onStatusChange: (connected) => {
47
+ if (connected && this.hubWs?.readyState === WebSocket.OPEN) {
48
+ void this.localT3.refreshProviders(false).catch(() => undefined);
49
+ }
50
+ },
51
+ }, this.config.knownThreadIds ?? []);
52
+ this.localT3.start();
53
+ void this.connectHub();
54
+ }
55
+ stop() {
56
+ this.stopped = true;
57
+ if (this.saveThreadsTimer)
58
+ clearTimeout(this.saveThreadsTimer);
59
+ if (this.reconnectTimer)
60
+ clearTimeout(this.reconnectTimer);
61
+ this.teardownHub();
62
+ this.localT3?.stop();
63
+ }
64
+ scheduleSaveKnownThreads() {
65
+ if (this.saveThreadsTimer)
66
+ return;
67
+ this.saveThreadsTimer = setTimeout(() => {
68
+ this.saveThreadsTimer = null;
69
+ this.config.knownThreadIds = this.localT3.getKnownThreadIds();
70
+ void saveConfig(this.config, this.configPath).catch(() => undefined);
71
+ }, 5_000);
72
+ }
73
+ teardownHub() {
74
+ this.localT3?.detachAllTerminals();
75
+ if (this.heartbeatTimer) {
76
+ clearInterval(this.heartbeatTimer);
77
+ this.heartbeatTimer = null;
78
+ }
79
+ const ws = this.hubWs;
80
+ this.hubWs = null;
81
+ if (ws) {
82
+ try {
83
+ ws.close();
84
+ }
85
+ catch {
86
+ // ignore
87
+ }
88
+ }
89
+ }
90
+ scheduleHubReconnect() {
91
+ if (this.stopped || this.reconnectTimer)
92
+ return;
93
+ const wait = this.backoffMs;
94
+ this.backoffMs = Math.min(this.backoffMs * 2, 30_000);
95
+ this.reconnectTimer = setTimeout(() => {
96
+ this.reconnectTimer = null;
97
+ void this.connectHub();
98
+ }, wait);
99
+ }
100
+ async ensureFreshHubCredentials() {
101
+ const creds = this.config.hub;
102
+ // Renew if within 5 minutes of expiry.
103
+ if (creds.accessTokenExpiresAt - Date.now() < 5 * 60_000) {
104
+ console.log('[hub] Access token 即将过期,正在续期…');
105
+ const renewed = await renewHubToken(creds);
106
+ this.config.hub = renewed;
107
+ await saveConfig(this.config, this.configPath);
108
+ return renewed;
109
+ }
110
+ return creds;
111
+ }
112
+ async connectHub(retriedAfterRenew = false) {
113
+ if (this.stopped)
114
+ return;
115
+ let creds;
116
+ try {
117
+ creds = await this.ensureFreshHubCredentials();
118
+ }
119
+ catch (err) {
120
+ console.error(`[hub] 续期失败: ${err instanceof Error ? err.message : String(err)}`);
121
+ this.scheduleHubReconnect();
122
+ return;
123
+ }
124
+ const linkHttpUrl = `${creds.serverUrl}/api/t3/device/link`;
125
+ const wsUrl = new URL(linkHttpUrl);
126
+ wsUrl.protocol = wsUrl.protocol === 'https:' ? 'wss:' : 'ws:';
127
+ const proof = createDpopProof({
128
+ keyPair: creds.dpop,
129
+ method: 'GET',
130
+ url: linkHttpUrl,
131
+ accessToken: creds.accessToken,
132
+ });
133
+ const ws = new WebSocket(wsUrl.toString(), {
134
+ headers: {
135
+ Authorization: `DPoP ${creds.accessToken}`,
136
+ DPoP: proof,
137
+ },
138
+ maxPayload: 16 * 1024 * 1024,
139
+ });
140
+ this.hubWs = ws;
141
+ ws.on('unexpected-response', async (_req, res) => {
142
+ if (this.hubWs !== ws)
143
+ return;
144
+ const status = res.statusCode ?? 0;
145
+ console.error(`[hub] 握手被拒绝 (HTTP ${status})`);
146
+ this.teardownHub();
147
+ if (status === 401 && !retriedAfterRenew) {
148
+ try {
149
+ console.log('[hub] 尝试使用 DPoP 密钥刷新 Access Token…');
150
+ const renewed = await renewHubToken(creds);
151
+ this.config.hub = renewed;
152
+ await saveConfig(this.config, this.configPath);
153
+ void this.connectHub(true);
154
+ return;
155
+ }
156
+ catch (err) {
157
+ console.error(`[hub] 刷新失败,设备可能已在网页端解绑: ${err instanceof Error ? err.message : String(err)}`);
158
+ }
159
+ }
160
+ this.scheduleHubReconnect();
161
+ });
162
+ ws.on('open', () => {
163
+ if (this.hubWs !== ws)
164
+ return;
165
+ this.backoffMs = 2_000;
166
+ console.log(`[hub] 已建立公网反向长连接 (${creds.serverUrl}, env=${creds.environmentId})`);
167
+ this.sendHubFrame({
168
+ type: 'hello',
169
+ data: {
170
+ platform: process.platform,
171
+ appVersion: `bridge-${APP_VERSION}`,
172
+ },
173
+ });
174
+ const cachedProviders = this.localT3.getLastProviders();
175
+ if (cachedProviders.length > 0) {
176
+ this.sendHubFrame({ type: 'catalog', data: { providers: cachedProviders } });
177
+ }
178
+ else if (this.localT3.isConnected()) {
179
+ void this.localT3.refreshProviders(false).catch(() => undefined);
180
+ }
181
+ });
182
+ ws.on('message', (raw) => {
183
+ if (this.hubWs !== ws)
184
+ return;
185
+ void this.handleHubMessage(raw.toString());
186
+ });
187
+ ws.on('close', (code, reason) => {
188
+ if (this.hubWs !== ws)
189
+ return;
190
+ console.log(`[hub] 长连接关闭 (code=${code} ${reason.toString() || ''}),准备重连…`);
191
+ this.teardownHub();
192
+ this.scheduleHubReconnect();
193
+ });
194
+ ws.on('error', (err) => {
195
+ if (this.hubWs !== ws)
196
+ return;
197
+ console.error(`[hub] WebSocket 错误: ${err.message}`);
198
+ });
199
+ }
200
+ sendHubFrame(frame) {
201
+ if (this.hubWs?.readyState === WebSocket.OPEN) {
202
+ this.hubWs.send(JSON.stringify(frame));
203
+ }
204
+ }
205
+ replyHub(type, id, payload) {
206
+ if (!id)
207
+ return;
208
+ this.sendHubFrame({
209
+ type: `${type}.result`,
210
+ id,
211
+ data: payload,
212
+ });
213
+ }
214
+ toRpcError(err) {
215
+ if (err && typeof err === 'object' && 'tag' in err && 'message' in err) {
216
+ return err;
217
+ }
218
+ return {
219
+ tag: 'BridgeError',
220
+ message: err instanceof Error ? err.message : String(err),
221
+ };
222
+ }
223
+ async handleHubMessage(raw) {
224
+ let frame;
225
+ try {
226
+ frame = JSON.parse(raw);
227
+ }
228
+ catch {
229
+ return;
230
+ }
231
+ switch (frame.type) {
232
+ case 'welcome': {
233
+ const data = (frame.data ?? {});
234
+ const interval = Math.max(5_000, Number(data.heartbeatIntervalMs) || 20_000);
235
+ if (this.heartbeatTimer)
236
+ clearInterval(this.heartbeatTimer);
237
+ this.heartbeatTimer = setInterval(() => {
238
+ this.sendHubFrame({ type: 'heartbeat', id: `hb_${Date.now()}` });
239
+ }, interval);
240
+ return;
241
+ }
242
+ case 'heartbeat_ack':
243
+ case 'events.resume':
244
+ return;
245
+ case 'providers.refresh': {
246
+ try {
247
+ const result = await this.localT3.refreshProviders(true);
248
+ this.replyHub(frame.type, frame.id, { ok: true, result });
249
+ }
250
+ catch (err) {
251
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
252
+ }
253
+ return;
254
+ }
255
+ case 'fs.list': {
256
+ try {
257
+ const req = (frame.data ?? {});
258
+ const listing = await listDirectories(req.path);
259
+ this.replyHub(frame.type, frame.id, { ok: true, result: listing });
260
+ }
261
+ catch (err) {
262
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
263
+ }
264
+ return;
265
+ }
266
+ case 'project.ensure': {
267
+ try {
268
+ const req = (frame.data ?? {});
269
+ const ensured = await this.localT3.ensureProject(req.workspaceRoot);
270
+ this.replyHub(frame.type, frame.id, { ok: true, result: ensured });
271
+ }
272
+ catch (err) {
273
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
274
+ }
275
+ return;
276
+ }
277
+ case 'command': {
278
+ try {
279
+ const cmd = (frame.data ?? {});
280
+ const result = await this.localT3.dispatchCommand(cmd);
281
+ this.scheduleSaveKnownThreads();
282
+ this.replyHub(frame.type, frame.id, { ok: true, result });
283
+ }
284
+ catch (err) {
285
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
286
+ }
287
+ return;
288
+ }
289
+ case 'snapshot': {
290
+ try {
291
+ const req = (frame.data ?? {});
292
+ const snap = await this.localT3.fetchSnapshot(req.threadId ?? '');
293
+ this.scheduleSaveKnownThreads();
294
+ this.replyHub(frame.type, frame.id, { ok: true, result: snap });
295
+ }
296
+ catch (err) {
297
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
298
+ }
299
+ return;
300
+ }
301
+ case 'terminal.list': {
302
+ try {
303
+ const req = (frame.data ?? {});
304
+ const result = this.localT3.listTerminals(req.threadId ?? '');
305
+ this.replyHub(frame.type, frame.id, { ok: true, result });
306
+ }
307
+ catch (err) {
308
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
309
+ }
310
+ return;
311
+ }
312
+ case 'terminal.open': {
313
+ try {
314
+ const req = (frame.data ?? {});
315
+ const result = await this.localT3.openTerminal({
316
+ threadId: req.threadId ?? '',
317
+ terminalId: req.terminalId,
318
+ cwd: req.cwd,
319
+ cols: req.cols,
320
+ rows: req.rows,
321
+ });
322
+ this.replyHub(frame.type, frame.id, { ok: true, result });
323
+ }
324
+ catch (err) {
325
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
326
+ }
327
+ return;
328
+ }
329
+ case 'terminal.attach': {
330
+ try {
331
+ const req = (frame.data ?? {});
332
+ const result = this.localT3.attachTerminal({
333
+ threadId: req.threadId ?? '',
334
+ terminalId: req.terminalId ?? '',
335
+ cwd: req.cwd,
336
+ cols: req.cols,
337
+ rows: req.rows,
338
+ });
339
+ this.replyHub(frame.type, frame.id, { ok: true, result });
340
+ }
341
+ catch (err) {
342
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
343
+ }
344
+ return;
345
+ }
346
+ case 'terminal.detach': {
347
+ try {
348
+ const req = (frame.data ?? {});
349
+ const result = this.localT3.detachTerminal({
350
+ threadId: req.threadId ?? '',
351
+ terminalId: req.terminalId ?? '',
352
+ });
353
+ this.replyHub(frame.type, frame.id, { ok: true, result });
354
+ }
355
+ catch (err) {
356
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
357
+ }
358
+ return;
359
+ }
360
+ case 'terminal.write': {
361
+ try {
362
+ const req = (frame.data ?? {});
363
+ const result = await this.localT3.writeTerminal({
364
+ threadId: req.threadId ?? '',
365
+ terminalId: req.terminalId ?? '',
366
+ data: req.data ?? '',
367
+ });
368
+ this.replyHub(frame.type, frame.id, { ok: true, result });
369
+ }
370
+ catch (err) {
371
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
372
+ }
373
+ return;
374
+ }
375
+ case 'terminal.resize': {
376
+ try {
377
+ const req = (frame.data ?? {});
378
+ const result = await this.localT3.resizeTerminal({
379
+ threadId: req.threadId ?? '',
380
+ terminalId: req.terminalId ?? '',
381
+ cols: Number(req.cols) || 80,
382
+ rows: Number(req.rows) || 24,
383
+ });
384
+ this.replyHub(frame.type, frame.id, { ok: true, result });
385
+ }
386
+ catch (err) {
387
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
388
+ }
389
+ return;
390
+ }
391
+ case 'terminal.close': {
392
+ try {
393
+ const req = (frame.data ?? {});
394
+ const result = await this.localT3.closeTerminal({
395
+ threadId: req.threadId ?? '',
396
+ terminalId: req.terminalId,
397
+ });
398
+ this.replyHub(frame.type, frame.id, { ok: true, result });
399
+ }
400
+ catch (err) {
401
+ this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
402
+ }
403
+ return;
404
+ }
405
+ case 'error': {
406
+ console.error('[hub] 服务端返回错误帧:', JSON.stringify(frame.data));
407
+ return;
408
+ }
409
+ default:
410
+ return;
411
+ }
412
+ }
413
+ }