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.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/dist/cli.mjs +2309 -0
- package/dist/tsc/antigravity-quota.js +276 -0
- package/dist/tsc/bridge.js +413 -0
- package/dist/tsc/config.js +77 -0
- package/dist/tsc/dpop.js +196 -0
- package/dist/tsc/fs-list.js +38 -0
- package/dist/tsc/index.js +243 -0
- package/dist/tsc/local-t3.js +905 -0
- package/dist/tsc/provider-quotas.js +422 -0
- package/package.json +44 -4
- package/scripts/service.mjs +192 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,2309 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { dirname as dirname3, resolve as resolve3 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
// src/antigravity-quota.ts
|
|
9
|
+
import { execFile, spawn } from "node:child_process";
|
|
10
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { promisify } from "node:util";
|
|
14
|
+
var execFileAsync = promisify(execFile);
|
|
15
|
+
async function hydrateProxyEnv(baseEnv = process.env) {
|
|
16
|
+
const next = { ...baseEnv };
|
|
17
|
+
const hasProxy = Boolean(
|
|
18
|
+
next.https_proxy?.trim() || next.HTTPS_PROXY?.trim() || next.http_proxy?.trim() || next.HTTP_PROXY?.trim() || next.all_proxy?.trim() || next.ALL_PROXY?.trim()
|
|
19
|
+
);
|
|
20
|
+
if (hasProxy || process.platform !== "darwin") return next;
|
|
21
|
+
try {
|
|
22
|
+
const { stdout } = await execFileAsync("scutil", ["--proxy"], { timeout: 2e3 });
|
|
23
|
+
const field = (name) => {
|
|
24
|
+
const m = new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, "m").exec(stdout);
|
|
25
|
+
return m?.[1]?.trim() || void 0;
|
|
26
|
+
};
|
|
27
|
+
if (field("HTTPEnable") === "1" && field("HTTPProxy") && field("HTTPPort")) {
|
|
28
|
+
const url = `http://${field("HTTPProxy")}:${field("HTTPPort")}`;
|
|
29
|
+
next.http_proxy = url;
|
|
30
|
+
next.HTTP_PROXY = url;
|
|
31
|
+
}
|
|
32
|
+
if (field("HTTPSEnable") === "1" && field("HTTPSProxy") && field("HTTPSPort")) {
|
|
33
|
+
const url = `http://${field("HTTPSProxy")}:${field("HTTPSPort")}`;
|
|
34
|
+
next.https_proxy = url;
|
|
35
|
+
next.HTTPS_PROXY = url;
|
|
36
|
+
}
|
|
37
|
+
if (field("SOCKSEnable") === "1" && field("SOCKSProxy") && field("SOCKSPort")) {
|
|
38
|
+
const url = `socks5://${field("SOCKSProxy")}:${field("SOCKSPort")}`;
|
|
39
|
+
next.all_proxy = url;
|
|
40
|
+
next.ALL_PROXY = url;
|
|
41
|
+
if (!next.http_proxy && !next.https_proxy) {
|
|
42
|
+
next.http_proxy = url;
|
|
43
|
+
next.HTTP_PROXY = url;
|
|
44
|
+
next.https_proxy = url;
|
|
45
|
+
next.HTTPS_PROXY = url;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
} catch {
|
|
49
|
+
}
|
|
50
|
+
return next;
|
|
51
|
+
}
|
|
52
|
+
var USAGE_ARGS = ["-p", "/usage", "--output-format", "json", "--print-timeout", "20s"];
|
|
53
|
+
var USAGE_TIMEOUT_MS = 25e3;
|
|
54
|
+
var MAX_OUTPUT_BYTES = 512 * 1024;
|
|
55
|
+
var CACHE_TTL_MS = 6e4;
|
|
56
|
+
var cachedLimits = null;
|
|
57
|
+
var inflightProbe = null;
|
|
58
|
+
function antigravityUsesApiKeyProvider() {
|
|
59
|
+
try {
|
|
60
|
+
const raw = readFileSync(join(homedir(), ".gemini", "antigravity-cli", "settings.json"), "utf8");
|
|
61
|
+
const parsed = JSON.parse(raw);
|
|
62
|
+
return Boolean(parsed?.modelProvider);
|
|
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
|
+
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)) return candidate;
|
|
89
|
+
}
|
|
90
|
+
return "agy";
|
|
91
|
+
}
|
|
92
|
+
function validResetIso(raw) {
|
|
93
|
+
if (typeof raw !== "string" || !raw.trim()) return void 0;
|
|
94
|
+
const ms = Date.parse(raw);
|
|
95
|
+
if (!Number.isFinite(ms) || ms <= 864e5) return void 0;
|
|
96
|
+
return new Date(ms).toISOString();
|
|
97
|
+
}
|
|
98
|
+
function parseAgyUsageJson(stdout) {
|
|
99
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
100
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
101
|
+
const trimmed = line.trim();
|
|
102
|
+
if (!trimmed.startsWith("{")) continue;
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = JSON.parse(trimmed);
|
|
106
|
+
} catch {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
|
|
110
|
+
if (typeof parsed.num_turns === "number" && parsed.num_turns > 0) return null;
|
|
111
|
+
if (typeof parsed.conversation_id === "string" && parsed.conversation_id.trim()) return null;
|
|
112
|
+
if (parsed.status !== "SUCCESS") continue;
|
|
113
|
+
const command = parsed.command;
|
|
114
|
+
if (!command || command.name !== "usage") continue;
|
|
115
|
+
const data = command.data;
|
|
116
|
+
if (!data || !Array.isArray(data.groups)) continue;
|
|
117
|
+
const windows = /* @__PURE__ */ new Map();
|
|
118
|
+
for (const rawGroup of data.groups) {
|
|
119
|
+
if (!rawGroup || typeof rawGroup !== "object") continue;
|
|
120
|
+
const group = rawGroup;
|
|
121
|
+
const groupName = typeof group.name === "string" ? group.name.trim() : "";
|
|
122
|
+
if (!Array.isArray(group.buckets)) continue;
|
|
123
|
+
for (const rawBucket of group.buckets) {
|
|
124
|
+
if (!rawBucket || typeof rawBucket !== "object") continue;
|
|
125
|
+
const bucket = rawBucket;
|
|
126
|
+
if (bucket.disabled === true) continue;
|
|
127
|
+
if (typeof bucket.remaining_fraction !== "number" || !Number.isFinite(bucket.remaining_fraction)) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const id = typeof bucket.id === "string" && bucket.id.trim() ? bucket.id.trim() : `${groupName}-${String(bucket.window ?? "quota")}`;
|
|
131
|
+
const winRaw = typeof bucket.window === "string" ? bucket.window.trim() : "";
|
|
132
|
+
const weekly = winRaw === "weekly";
|
|
133
|
+
const session = winRaw === "5h";
|
|
134
|
+
const family = id.startsWith("gemini-argon-") ? groupName || "Gemini Argon" : id.startsWith("gemini-carbon-") ? groupName || "Gemini Carbon" : id.startsWith("gemini-") || groupName.toLowerCase().includes("gemini") ? "Gemini" : id.startsWith("3p-") || groupName.toLowerCase().includes("claude") ? "Claude / GPT" : groupName || id;
|
|
135
|
+
const kind = weekly ? "weekly" : session ? "session" : "other";
|
|
136
|
+
const windowDurationMins = weekly ? 7 * 24 * 60 : session ? 5 * 60 : void 0;
|
|
137
|
+
const usedPercent = (1 - Math.max(0, Math.min(1, bucket.remaining_fraction))) * 100;
|
|
138
|
+
const resetsAt = validResetIso(bucket.reset_time);
|
|
139
|
+
windows.set(id, {
|
|
140
|
+
id,
|
|
141
|
+
label: `${family} \xB7 ${weekly ? "\u6BCF\u5468\u989D\u5EA6" : session ? "5 \u5C0F\u65F6\u989D\u5EA6" : typeof bucket.name === "string" && bucket.name.trim() || "\u989D\u5EA6"}`,
|
|
142
|
+
kind,
|
|
143
|
+
usedPercent,
|
|
144
|
+
...resetsAt ? { resetsAt } : {},
|
|
145
|
+
...windowDurationMins !== void 0 ? { windowDurationMins } : {}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (windows.size > 0) {
|
|
150
|
+
return {
|
|
151
|
+
checkedAt,
|
|
152
|
+
windows: [...windows.values()]
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
async function probeAntigravityUsage(force = false) {
|
|
159
|
+
if (!force && cachedLimits && Date.now() - cachedLimits.fetchedAt < CACHE_TTL_MS) {
|
|
160
|
+
return cachedLimits.limits;
|
|
161
|
+
}
|
|
162
|
+
if (inflightProbe) return inflightProbe;
|
|
163
|
+
inflightProbe = (async () => {
|
|
164
|
+
const proxyEnv = await hydrateProxyEnv();
|
|
165
|
+
return new Promise((resolve4) => {
|
|
166
|
+
let settled = false;
|
|
167
|
+
let stdout = "";
|
|
168
|
+
const done = (val) => {
|
|
169
|
+
if (settled) return;
|
|
170
|
+
settled = true;
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
if (val) {
|
|
173
|
+
cachedLimits = { fetchedAt: Date.now(), limits: val };
|
|
174
|
+
}
|
|
175
|
+
resolve4(val);
|
|
176
|
+
};
|
|
177
|
+
const bin = resolveAgyBinary();
|
|
178
|
+
const child = spawn(bin, [...USAGE_ARGS], {
|
|
179
|
+
env: scrubAntigravityEnv(proxyEnv),
|
|
180
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
181
|
+
windowsHide: true
|
|
182
|
+
});
|
|
183
|
+
const timer = setTimeout(() => {
|
|
184
|
+
try {
|
|
185
|
+
child.kill("SIGKILL");
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
done(null);
|
|
189
|
+
}, USAGE_TIMEOUT_MS);
|
|
190
|
+
child.stdout?.on("data", (chunk) => {
|
|
191
|
+
if (stdout.length < MAX_OUTPUT_BYTES) {
|
|
192
|
+
stdout += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
child.on("error", () => done(null));
|
|
196
|
+
child.on("close", (code) => {
|
|
197
|
+
if (code !== 0) {
|
|
198
|
+
done(null);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
done(parseAgyUsageJson(stdout));
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
})().finally(() => {
|
|
205
|
+
inflightProbe = null;
|
|
206
|
+
});
|
|
207
|
+
return inflightProbe;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/bridge.ts
|
|
211
|
+
import WebSocket2 from "ws";
|
|
212
|
+
|
|
213
|
+
// src/config.ts
|
|
214
|
+
import { chmod, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
215
|
+
import { homedir as homedir2, hostname } from "node:os";
|
|
216
|
+
import { dirname, join as join2, resolve } from "node:path";
|
|
217
|
+
var DEFAULT_HUB_SERVER = "https://wq.stormapex.top";
|
|
218
|
+
var DEFAULT_LOCAL_T3_URL = "http://127.0.0.1:3773";
|
|
219
|
+
var APP_VERSION = "0.1.0";
|
|
220
|
+
function defaultDataDir() {
|
|
221
|
+
if (process.env.ECHO_T3_BRIDGE_DATA_DIR?.trim()) {
|
|
222
|
+
return resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR.trim());
|
|
223
|
+
}
|
|
224
|
+
if (process.platform === "darwin") {
|
|
225
|
+
return join2(homedir2(), "Library", "Application Support", "echo-t3-bridge");
|
|
226
|
+
}
|
|
227
|
+
if (process.platform === "win32") {
|
|
228
|
+
return join2(process.env.APPDATA ?? homedir2(), "echo-t3-bridge");
|
|
229
|
+
}
|
|
230
|
+
return join2(process.env.XDG_STATE_HOME ?? join2(homedir2(), ".local", "state"), "echo-t3-bridge");
|
|
231
|
+
}
|
|
232
|
+
function defaultConfigPath() {
|
|
233
|
+
if (process.env.ECHO_T3_BRIDGE_CONFIG?.trim()) {
|
|
234
|
+
return resolve(process.env.ECHO_T3_BRIDGE_CONFIG.trim());
|
|
235
|
+
}
|
|
236
|
+
return join2(defaultDataDir(), "config.json");
|
|
237
|
+
}
|
|
238
|
+
function defaultDeviceLabel() {
|
|
239
|
+
return hostname().replace(/\.local$/i, "") || "T3 Device";
|
|
240
|
+
}
|
|
241
|
+
function normalizeServerUrl(raw) {
|
|
242
|
+
const trimmed = raw.trim().replace(/\/+$/, "");
|
|
243
|
+
if (!trimmed) return DEFAULT_HUB_SERVER;
|
|
244
|
+
if (!/^https?:\/\//i.test(trimmed)) {
|
|
245
|
+
return `https://${trimmed}`;
|
|
246
|
+
}
|
|
247
|
+
return trimmed;
|
|
248
|
+
}
|
|
249
|
+
async function loadConfig(configPath = defaultConfigPath()) {
|
|
250
|
+
try {
|
|
251
|
+
const raw = await readFile(configPath, "utf8");
|
|
252
|
+
const parsed = JSON.parse(raw);
|
|
253
|
+
return {
|
|
254
|
+
version: 1,
|
|
255
|
+
hub: parsed.hub,
|
|
256
|
+
localT3: {
|
|
257
|
+
baseUrl: parsed.localT3?.baseUrl || DEFAULT_LOCAL_T3_URL,
|
|
258
|
+
accessToken: parsed.localT3?.accessToken,
|
|
259
|
+
t3Binary: parsed.localT3?.t3Binary
|
|
260
|
+
},
|
|
261
|
+
knownThreadIds: Array.isArray(parsed.knownThreadIds) ? parsed.knownThreadIds : []
|
|
262
|
+
};
|
|
263
|
+
} catch {
|
|
264
|
+
return {
|
|
265
|
+
version: 1,
|
|
266
|
+
localT3: {
|
|
267
|
+
baseUrl: DEFAULT_LOCAL_T3_URL
|
|
268
|
+
},
|
|
269
|
+
knownThreadIds: []
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function saveConfig(config, configPath = defaultConfigPath()) {
|
|
274
|
+
await mkdir(dirname(configPath), { recursive: true, mode: 448 });
|
|
275
|
+
const tmpPath = `${configPath}.tmp.${process.pid}`;
|
|
276
|
+
await writeFile(tmpPath, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
277
|
+
await chmod(tmpPath, 384).catch(() => void 0);
|
|
278
|
+
const { rename } = await import("node:fs/promises");
|
|
279
|
+
await rename(tmpPath, configPath);
|
|
280
|
+
}
|
|
281
|
+
async function clearHubCredentials(configPath = defaultConfigPath()) {
|
|
282
|
+
const cfg = await loadConfig(configPath);
|
|
283
|
+
delete cfg.hub;
|
|
284
|
+
await saveConfig(cfg, configPath);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// src/dpop.ts
|
|
288
|
+
import crypto from "node:crypto";
|
|
289
|
+
var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
290
|
+
var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
|
|
291
|
+
var BOOTSTRAP_TOKEN_TYPE = "urn:t3:params:oauth:token-type:environment-bootstrap";
|
|
292
|
+
function base64Url(input) {
|
|
293
|
+
const buf = typeof input === "string" ? Buffer.from(input, "utf8") : input;
|
|
294
|
+
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
295
|
+
}
|
|
296
|
+
function sha256Base64Url(value) {
|
|
297
|
+
return base64Url(crypto.createHash("sha256").update(value, "utf8").digest());
|
|
298
|
+
}
|
|
299
|
+
function generateDpopKeyPair() {
|
|
300
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", {
|
|
301
|
+
namedCurve: "P-256"
|
|
302
|
+
});
|
|
303
|
+
const jwk = publicKey.export({ format: "jwk" });
|
|
304
|
+
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
|
305
|
+
return {
|
|
306
|
+
privateKeyPem,
|
|
307
|
+
publicJwk: {
|
|
308
|
+
kty: "EC",
|
|
309
|
+
crv: "P-256",
|
|
310
|
+
x: jwk.x,
|
|
311
|
+
y: jwk.y
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function normalizeHtu(rawUrl) {
|
|
316
|
+
const parsed = new URL(rawUrl);
|
|
317
|
+
if (parsed.protocol === "wss:") parsed.protocol = "https:";
|
|
318
|
+
else if (parsed.protocol === "ws:") parsed.protocol = "http:";
|
|
319
|
+
parsed.search = "";
|
|
320
|
+
parsed.hash = "";
|
|
321
|
+
return parsed.toString();
|
|
322
|
+
}
|
|
323
|
+
function createDpopProof(options) {
|
|
324
|
+
const header = {
|
|
325
|
+
typ: "dpop+jwt",
|
|
326
|
+
alg: "ES256",
|
|
327
|
+
jwk: options.keyPair.publicJwk
|
|
328
|
+
};
|
|
329
|
+
const payload = {
|
|
330
|
+
htm: options.method.toUpperCase(),
|
|
331
|
+
htu: normalizeHtu(options.url),
|
|
332
|
+
jti: crypto.randomUUID(),
|
|
333
|
+
iat: Math.floor(Date.now() / 1e3)
|
|
334
|
+
};
|
|
335
|
+
if (options.accessToken) {
|
|
336
|
+
payload.ath = sha256Base64Url(options.accessToken);
|
|
337
|
+
}
|
|
338
|
+
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
|
|
339
|
+
const privateKey = crypto.createPrivateKey(options.keyPair.privateKeyPem);
|
|
340
|
+
const signature = crypto.sign("sha256", Buffer.from(signingInput, "utf8"), {
|
|
341
|
+
key: privateKey,
|
|
342
|
+
dsaEncoding: "ieee-p1363"
|
|
343
|
+
});
|
|
344
|
+
return `${signingInput}.${base64Url(signature)}`;
|
|
345
|
+
}
|
|
346
|
+
function mapPlatform() {
|
|
347
|
+
if (process.platform === "darwin") return "darwin";
|
|
348
|
+
if (process.platform === "win32") return "win32";
|
|
349
|
+
return "linux";
|
|
350
|
+
}
|
|
351
|
+
async function pairWithHub(options) {
|
|
352
|
+
const serverUrl = options.serverUrl.replace(/\/+$/, "");
|
|
353
|
+
const tokenUrl = `${serverUrl}/api/t3/device/token`;
|
|
354
|
+
const keyPair = generateDpopKeyPair();
|
|
355
|
+
const label = options.label?.trim() || defaultDeviceLabel();
|
|
356
|
+
const proof = createDpopProof({
|
|
357
|
+
keyPair,
|
|
358
|
+
method: "POST",
|
|
359
|
+
url: tokenUrl
|
|
360
|
+
});
|
|
361
|
+
const body = new URLSearchParams({
|
|
362
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
363
|
+
subject_token: options.code.trim(),
|
|
364
|
+
subject_token_type: BOOTSTRAP_TOKEN_TYPE,
|
|
365
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
366
|
+
client_label: label,
|
|
367
|
+
client_device_type: "desktop",
|
|
368
|
+
client_os: mapPlatform(),
|
|
369
|
+
client_app_version: `bridge-${APP_VERSION}`
|
|
370
|
+
});
|
|
371
|
+
const response = await fetch(tokenUrl, {
|
|
372
|
+
method: "POST",
|
|
373
|
+
headers: {
|
|
374
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
375
|
+
DPoP: proof
|
|
376
|
+
},
|
|
377
|
+
body: body.toString()
|
|
378
|
+
});
|
|
379
|
+
const data = await response.json().catch(() => ({}));
|
|
380
|
+
if (!response.ok || !data.access_token || !data.environment_id) {
|
|
381
|
+
const detail = data.error_description || data.error || `HTTP ${response.status}`;
|
|
382
|
+
throw new Error(`Hub \u914D\u5BF9\u5931\u8D25: ${detail}`);
|
|
383
|
+
}
|
|
384
|
+
const now = Date.now();
|
|
385
|
+
return {
|
|
386
|
+
serverUrl,
|
|
387
|
+
environmentId: data.environment_id,
|
|
388
|
+
accessToken: data.access_token,
|
|
389
|
+
accessTokenExpiresAt: now + (Number(data.expires_in) || 3600) * 1e3,
|
|
390
|
+
sessionExpiresAt: (Number(data.session_expires_at) || Math.floor(now / 1e3) + 86400 * 30) * 1e3,
|
|
391
|
+
label,
|
|
392
|
+
dpop: keyPair
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
async function renewHubToken(creds) {
|
|
396
|
+
const tokenUrl = `${creds.serverUrl}/api/t3/device/token`;
|
|
397
|
+
const proof = createDpopProof({
|
|
398
|
+
keyPair: creds.dpop,
|
|
399
|
+
method: "POST",
|
|
400
|
+
url: tokenUrl
|
|
401
|
+
});
|
|
402
|
+
const body = new URLSearchParams({
|
|
403
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
404
|
+
subject_token: creds.accessToken,
|
|
405
|
+
subject_token_type: ACCESS_TOKEN_TYPE,
|
|
406
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
407
|
+
client_label: creds.label,
|
|
408
|
+
client_device_type: "desktop",
|
|
409
|
+
client_os: mapPlatform(),
|
|
410
|
+
client_app_version: `bridge-${APP_VERSION}`
|
|
411
|
+
});
|
|
412
|
+
const response = await fetch(tokenUrl, {
|
|
413
|
+
method: "POST",
|
|
414
|
+
headers: {
|
|
415
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
416
|
+
DPoP: proof
|
|
417
|
+
},
|
|
418
|
+
body: body.toString()
|
|
419
|
+
});
|
|
420
|
+
const data = await response.json().catch(() => ({}));
|
|
421
|
+
if (!response.ok || !data.access_token) {
|
|
422
|
+
const detail = data.error_description || data.error || `HTTP ${response.status}`;
|
|
423
|
+
throw new Error(`Hub Token \u7EED\u671F\u5931\u8D25: ${detail}`);
|
|
424
|
+
}
|
|
425
|
+
const now = Date.now();
|
|
426
|
+
return {
|
|
427
|
+
...creds,
|
|
428
|
+
accessToken: data.access_token,
|
|
429
|
+
accessTokenExpiresAt: now + (Number(data.expires_in) || 3600) * 1e3,
|
|
430
|
+
sessionExpiresAt: data.session_expires_at ? data.session_expires_at * 1e3 : creds.sessionExpiresAt
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
async function unpairFromHub(creds) {
|
|
434
|
+
const url = `${creds.serverUrl}/api/t3/device/environment`;
|
|
435
|
+
const proof = createDpopProof({
|
|
436
|
+
keyPair: creds.dpop,
|
|
437
|
+
method: "DELETE",
|
|
438
|
+
url,
|
|
439
|
+
accessToken: creds.accessToken
|
|
440
|
+
});
|
|
441
|
+
await fetch(url, {
|
|
442
|
+
method: "DELETE",
|
|
443
|
+
headers: {
|
|
444
|
+
Authorization: `DPoP ${creds.accessToken}`,
|
|
445
|
+
DPoP: proof
|
|
446
|
+
}
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
async function fetchHubSelf(creds) {
|
|
450
|
+
const url = `${creds.serverUrl}/api/t3/device/environment`;
|
|
451
|
+
const proof = createDpopProof({
|
|
452
|
+
keyPair: creds.dpop,
|
|
453
|
+
method: "GET",
|
|
454
|
+
url,
|
|
455
|
+
accessToken: creds.accessToken
|
|
456
|
+
});
|
|
457
|
+
const res = await fetch(url, {
|
|
458
|
+
method: "GET",
|
|
459
|
+
headers: {
|
|
460
|
+
Authorization: `DPoP ${creds.accessToken}`,
|
|
461
|
+
DPoP: proof
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
if (!res.ok) return { ok: false, status: res.status };
|
|
465
|
+
const data = await res.json().catch(() => ({}));
|
|
466
|
+
return { ok: true, status: res.status, ...data };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// src/fs-list.ts
|
|
470
|
+
import { readdir, stat } from "node:fs/promises";
|
|
471
|
+
import { homedir as homedir3 } from "node:os";
|
|
472
|
+
import { dirname as dirname2, join as join3, resolve as resolve2 } from "node:path";
|
|
473
|
+
async function listDirectories(rawPath) {
|
|
474
|
+
let target = (rawPath ?? "").trim();
|
|
475
|
+
if (!target || target === "~" || target === "~/") {
|
|
476
|
+
target = homedir3();
|
|
477
|
+
} else if (target.startsWith("~/")) {
|
|
478
|
+
target = join3(homedir3(), target.slice(2));
|
|
479
|
+
}
|
|
480
|
+
const absPath = resolve2(target);
|
|
481
|
+
const names = await readdir(absPath);
|
|
482
|
+
const entries = [];
|
|
483
|
+
await Promise.all(
|
|
484
|
+
names.map(async (name) => {
|
|
485
|
+
const fullPath = join3(absPath, name);
|
|
486
|
+
try {
|
|
487
|
+
const info = await stat(fullPath);
|
|
488
|
+
if (info.isDirectory()) {
|
|
489
|
+
entries.push({
|
|
490
|
+
name,
|
|
491
|
+
path: fullPath,
|
|
492
|
+
hidden: name.startsWith(".")
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
} catch {
|
|
496
|
+
}
|
|
497
|
+
})
|
|
498
|
+
);
|
|
499
|
+
entries.sort((a, b) => Number(a.hidden) - Number(b.hidden) || a.name.localeCompare(b.name));
|
|
500
|
+
const parentDir = dirname2(absPath);
|
|
501
|
+
return {
|
|
502
|
+
path: absPath,
|
|
503
|
+
parent: parentDir !== absPath ? parentDir : null,
|
|
504
|
+
directories: entries
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// src/local-t3.ts
|
|
509
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
510
|
+
import crypto2 from "node:crypto";
|
|
511
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
512
|
+
import { homedir as homedir5 } from "node:os";
|
|
513
|
+
import { basename, join as join5 } from "node:path";
|
|
514
|
+
import { promisify as promisify3 } from "node:util";
|
|
515
|
+
import WebSocket from "ws";
|
|
516
|
+
|
|
517
|
+
// src/provider-quotas.ts
|
|
518
|
+
import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
|
|
519
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
520
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
521
|
+
import { homedir as homedir4, tmpdir } from "node:os";
|
|
522
|
+
import { join as join4 } from "node:path";
|
|
523
|
+
import { createInterface } from "node:readline";
|
|
524
|
+
import { promisify as promisify2, stripVTControlCharacters } from "node:util";
|
|
525
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
526
|
+
var CACHE_TTL_MS2 = 6e4;
|
|
527
|
+
var quotaCache = /* @__PURE__ */ new Map();
|
|
528
|
+
var inflightMap = /* @__PURE__ */ new Map();
|
|
529
|
+
function resolveBinary(name, extraCandidates = []) {
|
|
530
|
+
const candidates = [
|
|
531
|
+
...extraCandidates,
|
|
532
|
+
join4(homedir4(), ".local", "bin", name),
|
|
533
|
+
"/opt/homebrew/bin/" + name,
|
|
534
|
+
"/usr/local/bin/" + name
|
|
535
|
+
].filter(Boolean);
|
|
536
|
+
for (const candidate of candidates) {
|
|
537
|
+
if (existsSync2(candidate)) return candidate;
|
|
538
|
+
}
|
|
539
|
+
return name;
|
|
540
|
+
}
|
|
541
|
+
function epochSecondsToIso(sec) {
|
|
542
|
+
if (!Number.isFinite(sec) || sec <= 86400) return void 0;
|
|
543
|
+
return new Date(sec * 1e3).toISOString();
|
|
544
|
+
}
|
|
545
|
+
function durationKind(durationMins) {
|
|
546
|
+
if (!durationMins || !Number.isFinite(durationMins)) return "other";
|
|
547
|
+
if (durationMins >= 25 * 24 * 60) return "monthly";
|
|
548
|
+
if (durationMins >= 6 * 24 * 60) return "weekly";
|
|
549
|
+
if (durationMins <= 24 * 60) return "session";
|
|
550
|
+
return "other";
|
|
551
|
+
}
|
|
552
|
+
async function probeCodexUsage() {
|
|
553
|
+
const bin = resolveBinary("codex", [
|
|
554
|
+
process.env.CODEX_BIN ?? "",
|
|
555
|
+
"/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex"
|
|
556
|
+
]);
|
|
557
|
+
const env = await hydrateProxyEnv();
|
|
558
|
+
const child = spawn2(bin, ["app-server", "--stdio"], {
|
|
559
|
+
env,
|
|
560
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
561
|
+
windowsHide: true
|
|
562
|
+
});
|
|
563
|
+
let nextId = 0;
|
|
564
|
+
const pending = /* @__PURE__ */ new Map();
|
|
565
|
+
const lines = createInterface({ input: child.stdout });
|
|
566
|
+
const rejectPending = (error) => {
|
|
567
|
+
for (const waiter of pending.values()) waiter.reject(error);
|
|
568
|
+
pending.clear();
|
|
569
|
+
};
|
|
570
|
+
child.once("error", rejectPending);
|
|
571
|
+
child.once("exit", (code) => {
|
|
572
|
+
if (pending.size) rejectPending(new Error(`codex app-server exited (${code ?? "unknown"})`));
|
|
573
|
+
});
|
|
574
|
+
lines.on("line", (line) => {
|
|
575
|
+
let message;
|
|
576
|
+
try {
|
|
577
|
+
message = JSON.parse(line);
|
|
578
|
+
} catch {
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
if (typeof message.id !== "number") return;
|
|
582
|
+
const waiter = pending.get(message.id);
|
|
583
|
+
if (!waiter) return;
|
|
584
|
+
pending.delete(message.id);
|
|
585
|
+
if (message.error) waiter.reject(new Error(message.error.message || "codex rateLimits error"));
|
|
586
|
+
else waiter.resolve(message.result);
|
|
587
|
+
});
|
|
588
|
+
const request = (method, params) => {
|
|
589
|
+
const id = ++nextId;
|
|
590
|
+
return new Promise((resolve4, reject) => {
|
|
591
|
+
const timer = setTimeout(() => {
|
|
592
|
+
pending.delete(id);
|
|
593
|
+
reject(new Error(`codex timeout (${method})`));
|
|
594
|
+
}, 15e3);
|
|
595
|
+
pending.set(id, {
|
|
596
|
+
resolve: (value) => {
|
|
597
|
+
clearTimeout(timer);
|
|
598
|
+
resolve4(value);
|
|
599
|
+
},
|
|
600
|
+
reject: (err) => {
|
|
601
|
+
clearTimeout(timer);
|
|
602
|
+
reject(err);
|
|
603
|
+
}
|
|
604
|
+
});
|
|
605
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, id, params })}
|
|
606
|
+
`, (err) => {
|
|
607
|
+
if (!err) return;
|
|
608
|
+
const waiter = pending.get(id);
|
|
609
|
+
if (waiter) {
|
|
610
|
+
pending.delete(id);
|
|
611
|
+
clearTimeout(timer);
|
|
612
|
+
waiter.reject(err);
|
|
613
|
+
}
|
|
614
|
+
});
|
|
615
|
+
});
|
|
616
|
+
};
|
|
617
|
+
try {
|
|
618
|
+
await request("initialize", {
|
|
619
|
+
clientInfo: { name: "echo-t3-bridge", title: "Echo T3 Bridge", version: "0.1.0" },
|
|
620
|
+
capabilities: { experimentalApi: true }
|
|
621
|
+
});
|
|
622
|
+
child.stdin.write('{"jsonrpc":"2.0","method":"initialized","params":{}}\n');
|
|
623
|
+
const result = await request("account/rateLimits/read", {});
|
|
624
|
+
const buckets = Object.entries(result?.rateLimitsByLimitId ?? {});
|
|
625
|
+
if (!buckets.length && result?.rateLimits) {
|
|
626
|
+
buckets.push([String(result.rateLimits.limitId || "codex"), result.rateLimits]);
|
|
627
|
+
}
|
|
628
|
+
const windows = [];
|
|
629
|
+
for (const [limitId, snapshot] of buckets) {
|
|
630
|
+
for (const key of ["primary", "secondary"]) {
|
|
631
|
+
const win = snapshot[key];
|
|
632
|
+
if (!win) continue;
|
|
633
|
+
const usedRaw = Number(win.usedPercent);
|
|
634
|
+
if (!Number.isFinite(usedRaw) || usedRaw < 0) continue;
|
|
635
|
+
const resetRaw = Number(win.resetsAt);
|
|
636
|
+
const resetsSec = Number.isFinite(resetRaw) && resetRaw > 0 ? Math.floor(resetRaw > 1e10 ? resetRaw / 1e3 : resetRaw) : 0;
|
|
637
|
+
const durationMins = Number(win.windowDurationMins);
|
|
638
|
+
const validDuration = Number.isFinite(durationMins) && durationMins > 0 ? Math.round(durationMins) : void 0;
|
|
639
|
+
const windowLabel = validDuration === 300 ? "5 \u5C0F\u65F6\u989D\u5EA6" : validDuration && validDuration >= 1e4 ? "\u6BCF\u5468\u989D\u5EA6" : validDuration ? `${validDuration} \u5206\u949F\u989D\u5EA6` : key === "primary" ? "\u4E3B\u8981\u989D\u5EA6" : "\u6B21\u8981\u989D\u5EA6";
|
|
640
|
+
const bucketName = typeof snapshot.limitName === "string" && snapshot.limitName.trim() ? snapshot.limitName.trim() : limitId === "codex" ? "" : limitId;
|
|
641
|
+
const resetsAt = epochSecondsToIso(resetsSec);
|
|
642
|
+
windows.push({
|
|
643
|
+
id: `codex:${limitId}:${key}`,
|
|
644
|
+
label: bucketName ? `${bucketName} \xB7 ${windowLabel}` : windowLabel,
|
|
645
|
+
kind: durationKind(validDuration),
|
|
646
|
+
usedPercent: Math.min(100, Math.max(0, usedRaw)),
|
|
647
|
+
...resetsAt ? { resetsAt } : {},
|
|
648
|
+
...validDuration !== void 0 ? { windowDurationMins: validDuration } : {}
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (windows.length === 0) return null;
|
|
653
|
+
return { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), windows };
|
|
654
|
+
} catch {
|
|
655
|
+
return null;
|
|
656
|
+
} finally {
|
|
657
|
+
rejectPending(new Error("closed"));
|
|
658
|
+
lines.close();
|
|
659
|
+
try {
|
|
660
|
+
child.kill("SIGTERM");
|
|
661
|
+
} catch {
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
var CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
666
|
+
var CLAUDE_USAGE_USER_AGENT = "claude-code/2.1.0";
|
|
667
|
+
var CLAUDE_WINDOWS = [
|
|
668
|
+
{ key: "five_hour", label: "5 \u5C0F\u65F6\u989D\u5EA6", mins: 5 * 60, kind: "session" },
|
|
669
|
+
{ key: "seven_day", label: "\u6BCF\u5468\u989D\u5EA6", mins: 7 * 24 * 60, kind: "weekly" },
|
|
670
|
+
{ key: "seven_day_opus", label: "Opus \xB7 \u6BCF\u5468\u989D\u5EA6", mins: 7 * 24 * 60, kind: "weekly" },
|
|
671
|
+
{ key: "seven_day_sonnet", label: "Sonnet \xB7 \u6BCF\u5468\u989D\u5EA6", mins: 7 * 24 * 60, kind: "weekly" }
|
|
672
|
+
];
|
|
673
|
+
function asObj(val) {
|
|
674
|
+
return val && typeof val === "object" && !Array.isArray(val) ? val : {};
|
|
675
|
+
}
|
|
676
|
+
function parseClaudeToken(content, allowRaw) {
|
|
677
|
+
const trimmed = content.trim();
|
|
678
|
+
if (!trimmed) return null;
|
|
679
|
+
try {
|
|
680
|
+
const parsed = asObj(JSON.parse(trimmed));
|
|
681
|
+
const oauth = Object.keys(asObj(parsed.claudeAiOauth)).length ? asObj(parsed.claudeAiOauth) : parsed;
|
|
682
|
+
return typeof oauth.accessToken === "string" && oauth.accessToken.trim() ? oauth.accessToken.trim() : null;
|
|
683
|
+
} catch {
|
|
684
|
+
return allowRaw ? trimmed : null;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
async function readClaudeTokens() {
|
|
688
|
+
const tokens = [];
|
|
689
|
+
const push = (t) => {
|
|
690
|
+
if (t && !tokens.includes(t)) tokens.push(t);
|
|
691
|
+
};
|
|
692
|
+
const fromEnv = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
|
|
693
|
+
if (fromEnv) push(parseClaudeToken(fromEnv, true));
|
|
694
|
+
if (process.platform === "darwin") {
|
|
695
|
+
const { stdout } = await execFileAsync2(
|
|
696
|
+
"security",
|
|
697
|
+
["find-generic-password", "-s", "Claude Code-credentials", "-w"],
|
|
698
|
+
{ timeout: 8e3 }
|
|
699
|
+
).catch(() => ({ stdout: "" }));
|
|
700
|
+
push(parseClaudeToken(String(stdout).trim(), false));
|
|
701
|
+
}
|
|
702
|
+
const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join4(homedir4(), ".claude");
|
|
703
|
+
const fileContent = await readFile2(join4(claudeHome, ".credentials.json"), "utf8").catch(() => "");
|
|
704
|
+
push(parseClaudeToken(fileContent, false));
|
|
705
|
+
return tokens;
|
|
706
|
+
}
|
|
707
|
+
async function probeClaudeUsage() {
|
|
708
|
+
const tokens = await readClaudeTokens();
|
|
709
|
+
for (const token of tokens) {
|
|
710
|
+
try {
|
|
711
|
+
const response = await fetch(CLAUDE_USAGE_URL, {
|
|
712
|
+
headers: {
|
|
713
|
+
authorization: `Bearer ${token}`,
|
|
714
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
715
|
+
"user-agent": CLAUDE_USAGE_USER_AGENT,
|
|
716
|
+
accept: "application/json"
|
|
717
|
+
},
|
|
718
|
+
redirect: "error",
|
|
719
|
+
signal: AbortSignal.timeout(12e3)
|
|
720
|
+
});
|
|
721
|
+
if (!response.ok) continue;
|
|
722
|
+
const body = asObj(await response.json());
|
|
723
|
+
const windows = [];
|
|
724
|
+
for (const spec of CLAUDE_WINDOWS) {
|
|
725
|
+
const raw = body[spec.key];
|
|
726
|
+
if (!raw || typeof raw !== "object") continue;
|
|
727
|
+
const win = asObj(raw);
|
|
728
|
+
const utilization = Number(win.utilization);
|
|
729
|
+
if (win.utilization === null || !Number.isFinite(utilization) || utilization < 0) continue;
|
|
730
|
+
let resetsAt;
|
|
731
|
+
if (typeof win.resets_at === "string" && win.resets_at.trim()) {
|
|
732
|
+
const ms = Date.parse(win.resets_at);
|
|
733
|
+
if (Number.isFinite(ms) && ms > 864e5) resetsAt = new Date(ms).toISOString();
|
|
734
|
+
} else if (typeof win.resets_at === "number" && Number.isFinite(win.resets_at) && win.resets_at > 0) {
|
|
735
|
+
const sec = win.resets_at > 1e10 ? Math.floor(win.resets_at / 1e3) : Math.floor(win.resets_at);
|
|
736
|
+
resetsAt = epochSecondsToIso(sec);
|
|
737
|
+
}
|
|
738
|
+
windows.push({
|
|
739
|
+
id: `claude:${spec.key}`,
|
|
740
|
+
label: spec.label,
|
|
741
|
+
kind: spec.kind,
|
|
742
|
+
usedPercent: Math.min(100, Math.round(utilization * 100) / 100),
|
|
743
|
+
...resetsAt ? { resetsAt } : {},
|
|
744
|
+
windowDurationMins: spec.mins
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
if (windows.length > 0) {
|
|
748
|
+
return { checkedAt: (/* @__PURE__ */ new Date()).toISOString(), windows };
|
|
749
|
+
}
|
|
750
|
+
} catch {
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return null;
|
|
755
|
+
}
|
|
756
|
+
async function probeKiroUsage() {
|
|
757
|
+
const bin = resolveBinary("kiro-cli");
|
|
758
|
+
const env = await hydrateProxyEnv();
|
|
759
|
+
try {
|
|
760
|
+
const { stdout, stderr } = await execFileAsync2(bin, ["chat", "--no-interactive", "/usage"], {
|
|
761
|
+
env,
|
|
762
|
+
cwd: tmpdir(),
|
|
763
|
+
timeout: 2e4,
|
|
764
|
+
maxBuffer: 1024 * 1024,
|
|
765
|
+
windowsHide: true
|
|
766
|
+
});
|
|
767
|
+
const text = stripVTControlCharacters(`${stdout}
|
|
768
|
+
${stderr}`).replace(/\r/g, "");
|
|
769
|
+
const usage = text.match(/^\s*Credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+covered in plan\s*\)/im);
|
|
770
|
+
if (!usage) return null;
|
|
771
|
+
const used = Number(usage[1].replace(/,/g, ""));
|
|
772
|
+
const total = Number(usage[2].replace(/,/g, ""));
|
|
773
|
+
if (!Number.isFinite(used) || !Number.isFinite(total) || total <= 0) return null;
|
|
774
|
+
const usedPercent = Math.min(100, Math.max(0, Math.round(used / total * 1e4) / 100));
|
|
775
|
+
const now = /* @__PURE__ */ new Date();
|
|
776
|
+
const dateMatch = text.match(/resets on\s+(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i)?.[1];
|
|
777
|
+
let resetsAt;
|
|
778
|
+
if (dateMatch) {
|
|
779
|
+
let resetDate = dateMatch.includes("-") ? dateMatch : `${now.getFullYear()}-${dateMatch.replace("/", "-")}`;
|
|
780
|
+
if (!dateMatch.includes("-") && (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) {
|
|
781
|
+
resetDate = `${now.getFullYear() + 1}-${dateMatch.replace("/", "-")}`;
|
|
782
|
+
}
|
|
783
|
+
const ms = (/* @__PURE__ */ new Date(`${resetDate}T00:00:00`)).getTime();
|
|
784
|
+
if (Number.isFinite(ms)) resetsAt = new Date(ms).toISOString();
|
|
785
|
+
}
|
|
786
|
+
const plan = text.match(/Estimated Usage[^\n]*\|\s*(KIRO[^|\n]*)/i)?.[1]?.trim();
|
|
787
|
+
return {
|
|
788
|
+
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
789
|
+
windows: [
|
|
790
|
+
{
|
|
791
|
+
id: "kiro:plan",
|
|
792
|
+
label: plan ? `\u5957\u9910\u79EF\u5206 \xB7 ${plan}` : "\u5957\u9910\u79EF\u5206",
|
|
793
|
+
kind: "monthly",
|
|
794
|
+
usedPercent,
|
|
795
|
+
...resetsAt ? { resetsAt } : {},
|
|
796
|
+
windowDurationMins: 30 * 24 * 60
|
|
797
|
+
}
|
|
798
|
+
]
|
|
799
|
+
};
|
|
800
|
+
} catch {
|
|
801
|
+
return null;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
function resolveQuotaDriver(rec) {
|
|
805
|
+
const driver = String(rec.driver ?? "").toLowerCase();
|
|
806
|
+
const id = String(rec.instanceId ?? "").toLowerCase();
|
|
807
|
+
if (driver === "antigravity" || id === "antigravity" || id === "agy") return "antigravity";
|
|
808
|
+
if (driver === "codex" || id === "codex") return "codex";
|
|
809
|
+
if (driver === "claudeagent" || driver === "claude" || id === "claudeagent" || id === "claude") return "claude";
|
|
810
|
+
if (driver === "kiro" || id === "kiro") return "kiro";
|
|
811
|
+
return null;
|
|
812
|
+
}
|
|
813
|
+
async function probeDriverUsage(driver, force = false) {
|
|
814
|
+
if (driver === "antigravity") {
|
|
815
|
+
return probeAntigravityUsage(force);
|
|
816
|
+
}
|
|
817
|
+
const cached = quotaCache.get(driver);
|
|
818
|
+
if (!force && cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS2) {
|
|
819
|
+
return cached.limits;
|
|
820
|
+
}
|
|
821
|
+
const existing = inflightMap.get(driver);
|
|
822
|
+
if (existing) return existing;
|
|
823
|
+
const task = (async () => {
|
|
824
|
+
const result = driver === "codex" ? await probeCodexUsage() : driver === "claude" ? await probeClaudeUsage() : await probeKiroUsage();
|
|
825
|
+
if (result && result.windows.length > 0) {
|
|
826
|
+
quotaCache.set(driver, { fetchedAt: Date.now(), limits: result });
|
|
827
|
+
}
|
|
828
|
+
return result;
|
|
829
|
+
})().finally(() => {
|
|
830
|
+
inflightMap.delete(driver);
|
|
831
|
+
});
|
|
832
|
+
inflightMap.set(driver, task);
|
|
833
|
+
return task;
|
|
834
|
+
}
|
|
835
|
+
async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
836
|
+
const neededDrivers = /* @__PURE__ */ new Set();
|
|
837
|
+
for (const p of providers) {
|
|
838
|
+
if (!p || typeof p !== "object") continue;
|
|
839
|
+
const rec = p;
|
|
840
|
+
if (rec.installed === false) continue;
|
|
841
|
+
const driver = resolveQuotaDriver(rec);
|
|
842
|
+
if (!driver) continue;
|
|
843
|
+
const existing = rec.usageLimits;
|
|
844
|
+
const hasExisting = Boolean(existing && Array.isArray(existing.windows) && existing.windows.length > 0);
|
|
845
|
+
if (forceQuota || !hasExisting || driver === "antigravity") {
|
|
846
|
+
neededDrivers.add(driver);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
if (neededDrivers.size === 0) return providers;
|
|
850
|
+
const probed = /* @__PURE__ */ new Map();
|
|
851
|
+
await Promise.all(
|
|
852
|
+
[...neededDrivers].map(async (driver) => {
|
|
853
|
+
const limits = await probeDriverUsage(driver, forceQuota).catch(() => null);
|
|
854
|
+
if (limits && limits.windows.length > 0) {
|
|
855
|
+
probed.set(driver, limits);
|
|
856
|
+
}
|
|
857
|
+
})
|
|
858
|
+
);
|
|
859
|
+
if (probed.size === 0) return providers;
|
|
860
|
+
return providers.map((p) => {
|
|
861
|
+
if (!p || typeof p !== "object") return p;
|
|
862
|
+
const rec = p;
|
|
863
|
+
const driver = resolveQuotaDriver(rec);
|
|
864
|
+
if (!driver) return p;
|
|
865
|
+
const limits = probed.get(driver);
|
|
866
|
+
if (!limits) return p;
|
|
867
|
+
return {
|
|
868
|
+
...rec,
|
|
869
|
+
usageLimits: limits
|
|
870
|
+
};
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// src/local-t3.ts
|
|
875
|
+
var execFileAsync3 = promisify3(execFile3);
|
|
876
|
+
function resolveLocalT3Binary(override) {
|
|
877
|
+
const candidates = [
|
|
878
|
+
override,
|
|
879
|
+
process.env.T3_BIN,
|
|
880
|
+
join5(homedir5(), ".t3", "bin", "t3"),
|
|
881
|
+
join5(homedir5(), ".local", "bin", "t3"),
|
|
882
|
+
"/opt/homebrew/bin/t3",
|
|
883
|
+
"/usr/local/bin/t3"
|
|
884
|
+
].filter((v) => Boolean(v));
|
|
885
|
+
for (const candidate of candidates) {
|
|
886
|
+
if (existsSync3(candidate)) return candidate;
|
|
887
|
+
}
|
|
888
|
+
return "t3";
|
|
889
|
+
}
|
|
890
|
+
async function pairLocalOfficialT3(options) {
|
|
891
|
+
const bin = resolveLocalT3Binary(options?.t3Binary);
|
|
892
|
+
let stdout = "";
|
|
893
|
+
let stderr = "";
|
|
894
|
+
try {
|
|
895
|
+
const res = await execFileAsync3(bin, ["pair"], {
|
|
896
|
+
timeout: 15e3,
|
|
897
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
898
|
+
env: { ...process.env, NO_COLOR: "1" }
|
|
899
|
+
});
|
|
900
|
+
stdout = res.stdout ?? "";
|
|
901
|
+
stderr = res.stderr ?? "";
|
|
902
|
+
} catch (err) {
|
|
903
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
904
|
+
throw new Error(
|
|
905
|
+
`\u65E0\u6CD5\u8C03\u7528\u672C\u673A\u539F\u7248 \`${bin} pair\`\u3002\u8BF7\u786E\u8BA4\u672C\u673A\u5DF2\u5B89\u88C5\u5B98\u65B9 T3 Code \u4E14\u540E\u53F0\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF08\u53EF\u6267\u884C \`t3 up\` \u542F\u52A8\uFF09\u3002\u539F\u59CB\u9519\u8BEF: ${msg}`
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
const combined = `${stdout}
|
|
909
|
+
${stderr}`;
|
|
910
|
+
const tokenMatch = /Token:\s*([A-Z0-9-]{6,64})/i.exec(combined) ?? /#token=([A-Z0-9-]{6,64})/i.exec(combined);
|
|
911
|
+
if (!tokenMatch?.[1]) {
|
|
912
|
+
throw new Error(
|
|
913
|
+
`\u672C\u673A \`${bin} pair\` \u672A\u8FD4\u56DE\u914D\u5BF9\u7801\uFF08\u8BF7\u786E\u8BA4\u539F\u7248 T3 \u670D\u52A1\u5DF2\u542F\u52A8\uFF0C\u4F8B\u5982\u8FD0\u884C \`t3 up\` \u6216\u6253\u5F00 T3 \u684C\u9762\u7AEF\uFF09\u3002\u8F93\u51FA:
|
|
914
|
+
${combined.slice(0, 400)}`
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
const pairingToken = tokenMatch[1].trim();
|
|
918
|
+
let baseUrl = options?.baseUrl?.trim().replace(/\/+$/, "") || "";
|
|
919
|
+
if (!baseUrl) {
|
|
920
|
+
const loopbackMatch = /\((https?:\/\/(?:127\.0\.0\.1|localhost):\d+)\)/i.exec(combined);
|
|
921
|
+
const portMatch = /https?:\/\/[^/\s:]+:(\d+)/i.exec(combined);
|
|
922
|
+
if (loopbackMatch?.[1]) {
|
|
923
|
+
baseUrl = loopbackMatch[1];
|
|
924
|
+
} else if (portMatch?.[1]) {
|
|
925
|
+
baseUrl = `http://127.0.0.1:${portMatch[1]}`;
|
|
926
|
+
} else {
|
|
927
|
+
baseUrl = DEFAULT_LOCAL_T3_URL;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
const form = new URLSearchParams({
|
|
931
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
932
|
+
subject_token: pairingToken,
|
|
933
|
+
subject_token_type: BOOTSTRAP_TOKEN_TYPE,
|
|
934
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
935
|
+
client_label: `Echo T3 Bridge (${defaultDeviceLabel()})`,
|
|
936
|
+
client_device_type: "desktop"
|
|
937
|
+
});
|
|
938
|
+
const resp = await fetch(`${baseUrl}/oauth/token`, {
|
|
939
|
+
method: "POST",
|
|
940
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
941
|
+
body: form.toString()
|
|
942
|
+
});
|
|
943
|
+
const data = await resp.json().catch(() => ({}));
|
|
944
|
+
if (!resp.ok || !data.access_token) {
|
|
945
|
+
throw new Error(
|
|
946
|
+
`\u672C\u673A\u539F\u7248 T3 (${baseUrl}) \u4EE4\u724C\u6362\u53D6\u5931\u8D25: ${data.error_description || data.message || data.error || `HTTP ${resp.status}`}`
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
return { baseUrl, accessToken: data.access_token };
|
|
950
|
+
}
|
|
951
|
+
async function probeLocalT3Health(baseUrl) {
|
|
952
|
+
try {
|
|
953
|
+
const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/`, {
|
|
954
|
+
method: "GET",
|
|
955
|
+
signal: AbortSignal.timeout(3e3)
|
|
956
|
+
});
|
|
957
|
+
return res.status >= 200 && res.status < 500;
|
|
958
|
+
} catch {
|
|
959
|
+
return false;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function extractRpcError(exit) {
|
|
963
|
+
if (!exit) return { tag: "LocalT3RpcError", message: "Empty RPC response" };
|
|
964
|
+
for (const entry of exit.cause ?? []) {
|
|
965
|
+
const raw = entry.error ?? entry.defect;
|
|
966
|
+
if (!raw) continue;
|
|
967
|
+
if (typeof raw === "string") return { tag: "LocalT3RpcError", message: raw };
|
|
968
|
+
if (typeof raw === "object") {
|
|
969
|
+
const rec = raw;
|
|
970
|
+
const tag = typeof rec._tag === "string" && rec._tag ? rec._tag : "LocalT3RpcError";
|
|
971
|
+
const message = typeof rec.message === "string" && rec.message || typeof rec.detail === "string" && rec.detail || JSON.stringify(rec);
|
|
972
|
+
const detail = typeof rec.detail === "string" ? rec.detail : void 0;
|
|
973
|
+
return { tag, message, ...detail ? { detail } : {} };
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return { tag: "LocalT3RpcError", message: "Local T3 RPC call failed" };
|
|
977
|
+
}
|
|
978
|
+
var AGY_LEVEL_SUFFIX_RE = /^((?:gemini|claude)-.+)-(low|medium|high|xhigh|max)$/;
|
|
979
|
+
function normalizeDispatchCommand(rawCommand) {
|
|
980
|
+
const command = { ...rawCommand };
|
|
981
|
+
const cmdType = typeof command.type === "string" ? command.type : "";
|
|
982
|
+
const needsCreatedBy = [
|
|
983
|
+
"thread.create",
|
|
984
|
+
"message.dispatch",
|
|
985
|
+
"thread.fork",
|
|
986
|
+
"thread.merge_back",
|
|
987
|
+
"delegated_task.request"
|
|
988
|
+
];
|
|
989
|
+
if (needsCreatedBy.includes(cmdType)) {
|
|
990
|
+
if (!command.createdBy) {
|
|
991
|
+
command.createdBy = "user";
|
|
992
|
+
}
|
|
993
|
+
if (!command.creationSource) {
|
|
994
|
+
command.creationSource = "web";
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const sel = command.modelSelection;
|
|
998
|
+
if (!sel || typeof sel !== "object" || Array.isArray(sel)) return command;
|
|
999
|
+
const selObj = { ...sel };
|
|
1000
|
+
const instanceId = String(selObj.instanceId ?? selObj.provider ?? "").toLowerCase();
|
|
1001
|
+
const isAgy = instanceId === "antigravity" || instanceId === "agy" || instanceId.includes("antigravity");
|
|
1002
|
+
if (!isAgy || typeof selObj.model !== "string") return command;
|
|
1003
|
+
const match = AGY_LEVEL_SUFFIX_RE.exec(selObj.model.trim());
|
|
1004
|
+
if (!match) return command;
|
|
1005
|
+
const [, baseModel, level] = match;
|
|
1006
|
+
selObj.model = baseModel;
|
|
1007
|
+
const existingOpts = selObj.options;
|
|
1008
|
+
if (Array.isArray(existingOpts)) {
|
|
1009
|
+
const hasThought = existingOpts.some(
|
|
1010
|
+
(item) => item && typeof item === "object" && (item.id === "thought_level" || item.id === "reasoningEffort")
|
|
1011
|
+
);
|
|
1012
|
+
if (!hasThought) {
|
|
1013
|
+
selObj.options = [...existingOpts, { id: "thought_level", value: level }];
|
|
1014
|
+
}
|
|
1015
|
+
} else if (existingOpts && typeof existingOpts === "object") {
|
|
1016
|
+
const rec = { ...existingOpts };
|
|
1017
|
+
if (!("thought_level" in rec) && !("reasoningEffort" in rec)) {
|
|
1018
|
+
rec.thought_level = level;
|
|
1019
|
+
}
|
|
1020
|
+
selObj.options = rec;
|
|
1021
|
+
} else {
|
|
1022
|
+
selObj.options = [{ id: "thought_level", value: level }];
|
|
1023
|
+
}
|
|
1024
|
+
return { ...command, modelSelection: selObj };
|
|
1025
|
+
}
|
|
1026
|
+
var LocalT3Client = class {
|
|
1027
|
+
baseUrl;
|
|
1028
|
+
accessToken;
|
|
1029
|
+
t3Binary;
|
|
1030
|
+
callbacks;
|
|
1031
|
+
ws = null;
|
|
1032
|
+
connected = false;
|
|
1033
|
+
stopped = false;
|
|
1034
|
+
nextId = 1;
|
|
1035
|
+
defaultCwd = "";
|
|
1036
|
+
lastProviders = [];
|
|
1037
|
+
pending = /* @__PURE__ */ new Map();
|
|
1038
|
+
streams = /* @__PURE__ */ new Map();
|
|
1039
|
+
subscribedThreads = /* @__PURE__ */ new Set();
|
|
1040
|
+
wantedThreads = /* @__PURE__ */ new Map();
|
|
1041
|
+
terminalMetadata = /* @__PURE__ */ new Map();
|
|
1042
|
+
terminalStreams = /* @__PURE__ */ new Map();
|
|
1043
|
+
pingTimer = null;
|
|
1044
|
+
reconnectTimer = null;
|
|
1045
|
+
backoffMs = 2e3;
|
|
1046
|
+
constructor(config, callbacks, initialThreads = []) {
|
|
1047
|
+
this.baseUrl = (config.baseUrl || DEFAULT_LOCAL_T3_URL).replace(/\/+$/, "");
|
|
1048
|
+
this.accessToken = config.accessToken;
|
|
1049
|
+
this.t3Binary = config.t3Binary;
|
|
1050
|
+
this.callbacks = callbacks;
|
|
1051
|
+
for (const tid of initialThreads) {
|
|
1052
|
+
if (tid) this.wantedThreads.set(tid, 0);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
isConnected() {
|
|
1056
|
+
return this.connected && this.ws?.readyState === WebSocket.OPEN;
|
|
1057
|
+
}
|
|
1058
|
+
getLastProviders() {
|
|
1059
|
+
return this.lastProviders;
|
|
1060
|
+
}
|
|
1061
|
+
getKnownThreadIds() {
|
|
1062
|
+
return [...this.wantedThreads.keys()].slice(-30);
|
|
1063
|
+
}
|
|
1064
|
+
start() {
|
|
1065
|
+
this.stopped = false;
|
|
1066
|
+
void this.connectLoop();
|
|
1067
|
+
}
|
|
1068
|
+
stop() {
|
|
1069
|
+
this.stopped = true;
|
|
1070
|
+
if (this.reconnectTimer) {
|
|
1071
|
+
clearTimeout(this.reconnectTimer);
|
|
1072
|
+
this.reconnectTimer = null;
|
|
1073
|
+
}
|
|
1074
|
+
this.teardownSocket();
|
|
1075
|
+
}
|
|
1076
|
+
teardownSocket() {
|
|
1077
|
+
if (this.pingTimer) {
|
|
1078
|
+
clearInterval(this.pingTimer);
|
|
1079
|
+
this.pingTimer = null;
|
|
1080
|
+
}
|
|
1081
|
+
const ws = this.ws;
|
|
1082
|
+
this.ws = null;
|
|
1083
|
+
const wasConnected = this.connected;
|
|
1084
|
+
this.connected = false;
|
|
1085
|
+
this.subscribedThreads.clear();
|
|
1086
|
+
this.terminalStreams.clear();
|
|
1087
|
+
this.terminalMetadata.clear();
|
|
1088
|
+
this.streams.clear();
|
|
1089
|
+
for (const [, entry] of this.pending) {
|
|
1090
|
+
clearTimeout(entry.timer);
|
|
1091
|
+
entry.reject({ tag: "LocalT3Disconnected", message: "Local T3 connection closed" });
|
|
1092
|
+
}
|
|
1093
|
+
this.pending.clear();
|
|
1094
|
+
if (ws) {
|
|
1095
|
+
try {
|
|
1096
|
+
ws.close();
|
|
1097
|
+
} catch {
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
if (wasConnected) {
|
|
1101
|
+
this.callbacks.onStatusChange?.(false);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
scheduleReconnect() {
|
|
1105
|
+
if (this.stopped) return;
|
|
1106
|
+
if (this.reconnectTimer) return;
|
|
1107
|
+
const wait = this.backoffMs;
|
|
1108
|
+
this.backoffMs = Math.min(this.backoffMs * 2, 3e4);
|
|
1109
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1110
|
+
this.reconnectTimer = null;
|
|
1111
|
+
void this.connectLoop();
|
|
1112
|
+
}, wait);
|
|
1113
|
+
}
|
|
1114
|
+
async ensureLocalToken(forceRepair = false) {
|
|
1115
|
+
if (this.accessToken && !forceRepair) return this.accessToken;
|
|
1116
|
+
const paired = await pairLocalOfficialT3({
|
|
1117
|
+
baseUrl: this.baseUrl,
|
|
1118
|
+
t3Binary: this.t3Binary
|
|
1119
|
+
});
|
|
1120
|
+
this.baseUrl = paired.baseUrl.replace(/\/+$/, "");
|
|
1121
|
+
this.accessToken = paired.accessToken;
|
|
1122
|
+
await this.callbacks.onTokenUpdated(this.baseUrl, this.accessToken);
|
|
1123
|
+
return this.accessToken;
|
|
1124
|
+
}
|
|
1125
|
+
async issueWsTicket() {
|
|
1126
|
+
let token = await this.ensureLocalToken(false);
|
|
1127
|
+
let resp = await fetch(`${this.baseUrl}/api/auth/websocket-ticket`, {
|
|
1128
|
+
method: "POST",
|
|
1129
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1130
|
+
signal: AbortSignal.timeout(8e3)
|
|
1131
|
+
});
|
|
1132
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
1133
|
+
console.log("[local-t3] \u672C\u5730\u4EE4\u724C\u5DF2\u5931\u6548\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u65B0\u914D\u5BF9\u672C\u673A\u539F\u7248 T3\u2026");
|
|
1134
|
+
token = await this.ensureLocalToken(true);
|
|
1135
|
+
resp = await fetch(`${this.baseUrl}/api/auth/websocket-ticket`, {
|
|
1136
|
+
method: "POST",
|
|
1137
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1138
|
+
signal: AbortSignal.timeout(8e3)
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
if (!resp.ok) {
|
|
1142
|
+
const text = await resp.text().catch(() => "");
|
|
1143
|
+
throw new Error(`websocket-ticket HTTP ${resp.status}: ${text.slice(0, 200)}`);
|
|
1144
|
+
}
|
|
1145
|
+
const json = await resp.json();
|
|
1146
|
+
if (!json.ticket) throw new Error("Empty websocket ticket from local T3");
|
|
1147
|
+
return json.ticket;
|
|
1148
|
+
}
|
|
1149
|
+
async connectLoop() {
|
|
1150
|
+
if (this.stopped) return;
|
|
1151
|
+
try {
|
|
1152
|
+
const ticket = await this.issueWsTicket();
|
|
1153
|
+
const wsUrl = new URL(this.baseUrl);
|
|
1154
|
+
wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
|
|
1155
|
+
wsUrl.pathname = "/ws";
|
|
1156
|
+
wsUrl.searchParams.set("orchestrationProtocol", "2");
|
|
1157
|
+
wsUrl.searchParams.set("wsTicket", ticket);
|
|
1158
|
+
const ws = new WebSocket(wsUrl.toString(), { maxPayload: 32 * 1024 * 1024 });
|
|
1159
|
+
this.ws = ws;
|
|
1160
|
+
ws.on("open", () => {
|
|
1161
|
+
if (this.ws !== ws) return;
|
|
1162
|
+
this.connected = true;
|
|
1163
|
+
this.backoffMs = 2e3;
|
|
1164
|
+
console.log(`[local-t3] \u5DF2\u8FDE\u63A5\u672C\u673A\u539F\u7248 T3 Server (${this.baseUrl})`);
|
|
1165
|
+
this.callbacks.onStatusChange?.(true);
|
|
1166
|
+
this.pingTimer = setInterval(() => {
|
|
1167
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
1168
|
+
ws.send(JSON.stringify({ _tag: "Ping" }));
|
|
1169
|
+
}
|
|
1170
|
+
}, 25e3);
|
|
1171
|
+
void this.bootstrapStreams();
|
|
1172
|
+
});
|
|
1173
|
+
ws.on("message", (data) => {
|
|
1174
|
+
if (this.ws !== ws) return;
|
|
1175
|
+
this.handleWsMessage(data.toString());
|
|
1176
|
+
});
|
|
1177
|
+
ws.on("close", (code, reason) => {
|
|
1178
|
+
if (this.ws !== ws) return;
|
|
1179
|
+
console.log(`[local-t3] \u8FDE\u63A5\u5DF2\u65AD\u5F00 (code=${code} ${reason.toString() || ""})\uFF0C\u51C6\u5907\u91CD\u8FDE\u2026`);
|
|
1180
|
+
this.teardownSocket();
|
|
1181
|
+
this.scheduleReconnect();
|
|
1182
|
+
});
|
|
1183
|
+
ws.on("error", (err) => {
|
|
1184
|
+
if (this.ws !== ws) return;
|
|
1185
|
+
console.error(`[local-t3] WebSocket \u9519\u8BEF: ${err.message}`);
|
|
1186
|
+
});
|
|
1187
|
+
} catch (err) {
|
|
1188
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1189
|
+
console.error(`[local-t3] \u8FDE\u63A5\u672C\u673A\u539F\u7248 T3 \u5931\u8D25: ${msg}`);
|
|
1190
|
+
this.scheduleReconnect();
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
handleWsMessage(raw) {
|
|
1194
|
+
let msg;
|
|
1195
|
+
try {
|
|
1196
|
+
msg = JSON.parse(raw);
|
|
1197
|
+
} catch {
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
if (msg._tag === "Pong") return;
|
|
1201
|
+
const reqId = msg.requestId !== void 0 ? String(msg.requestId) : "";
|
|
1202
|
+
if (!reqId) return;
|
|
1203
|
+
if (msg._tag === "Chunk") {
|
|
1204
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1205
|
+
this.ws.send(JSON.stringify({ _tag: "Ack", requestId: reqId }));
|
|
1206
|
+
}
|
|
1207
|
+
const handler = this.streams.get(reqId);
|
|
1208
|
+
if (handler && Array.isArray(msg.values)) {
|
|
1209
|
+
for (const item of msg.values) {
|
|
1210
|
+
handler(item);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
if (msg._tag === "Exit") {
|
|
1216
|
+
this.streams.delete(reqId);
|
|
1217
|
+
const pending = this.pending.get(reqId);
|
|
1218
|
+
if (!pending) return;
|
|
1219
|
+
this.pending.delete(reqId);
|
|
1220
|
+
clearTimeout(pending.timer);
|
|
1221
|
+
if (msg.exit?._tag === "Success") {
|
|
1222
|
+
pending.resolve(msg.exit.value);
|
|
1223
|
+
} else {
|
|
1224
|
+
pending.reject(extractRpcError(msg.exit));
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
nextRequestId() {
|
|
1229
|
+
const id = this.nextId++;
|
|
1230
|
+
return String(id);
|
|
1231
|
+
}
|
|
1232
|
+
async callRpc(method, payload, timeoutMs = 55e3) {
|
|
1233
|
+
if (!this.isConnected() || !this.ws) {
|
|
1234
|
+
throw { tag: "LocalT3Offline", message: "\u672C\u673A\u539F\u7248 T3 \u5C1A\u672A\u8FDE\u63A5\uFF0C\u8BF7\u786E\u8BA4 `t3 up` \u6216 T3 \u684C\u9762\u7AEF\u6B63\u5728\u8FD0\u884C" };
|
|
1235
|
+
}
|
|
1236
|
+
const id = this.nextRequestId();
|
|
1237
|
+
return new Promise((resolve4, reject) => {
|
|
1238
|
+
const timer = setTimeout(() => {
|
|
1239
|
+
this.pending.delete(id);
|
|
1240
|
+
reject({ tag: "LocalT3Timeout", message: `\u672C\u5730 T3 RPC ${method} \u8D85\u65F6` });
|
|
1241
|
+
}, timeoutMs);
|
|
1242
|
+
this.pending.set(id, { resolve: resolve4, reject, timer });
|
|
1243
|
+
try {
|
|
1244
|
+
this.ws.send(
|
|
1245
|
+
JSON.stringify({
|
|
1246
|
+
_tag: "Request",
|
|
1247
|
+
id,
|
|
1248
|
+
tag: method,
|
|
1249
|
+
payload,
|
|
1250
|
+
headers: []
|
|
1251
|
+
})
|
|
1252
|
+
);
|
|
1253
|
+
} catch (err) {
|
|
1254
|
+
clearTimeout(timer);
|
|
1255
|
+
this.pending.delete(id);
|
|
1256
|
+
reject({
|
|
1257
|
+
tag: "LocalT3SendError",
|
|
1258
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
startStream(method, payload, onItem) {
|
|
1264
|
+
if (!this.isConnected() || !this.ws) return null;
|
|
1265
|
+
const id = this.nextRequestId();
|
|
1266
|
+
this.streams.set(id, onItem);
|
|
1267
|
+
try {
|
|
1268
|
+
this.ws.send(
|
|
1269
|
+
JSON.stringify({
|
|
1270
|
+
_tag: "Request",
|
|
1271
|
+
id,
|
|
1272
|
+
tag: method,
|
|
1273
|
+
payload,
|
|
1274
|
+
headers: []
|
|
1275
|
+
})
|
|
1276
|
+
);
|
|
1277
|
+
return id;
|
|
1278
|
+
} catch {
|
|
1279
|
+
this.streams.delete(id);
|
|
1280
|
+
return null;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
interruptStream(requestId) {
|
|
1284
|
+
this.streams.delete(requestId);
|
|
1285
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
1286
|
+
try {
|
|
1287
|
+
this.ws.send(JSON.stringify({ _tag: "Interrupt", requestId }));
|
|
1288
|
+
} catch {
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
async bootstrapStreams() {
|
|
1293
|
+
this.startStream(
|
|
1294
|
+
"subscribeServerConfig",
|
|
1295
|
+
{ usageLimitSources: true, usageLimitsCommand: true },
|
|
1296
|
+
(item) => {
|
|
1297
|
+
void this.handleConfigEvent(item);
|
|
1298
|
+
}
|
|
1299
|
+
);
|
|
1300
|
+
this.startStream("subscribeTerminalMetadata", {}, (item) => {
|
|
1301
|
+
this.handleTerminalMetadataEvent(item);
|
|
1302
|
+
});
|
|
1303
|
+
void this.refreshProviders(false).catch(() => void 0);
|
|
1304
|
+
for (const [threadId, afterSeq] of this.wantedThreads.entries()) {
|
|
1305
|
+
this.ensureThreadSubscribed(threadId, afterSeq);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
handleTerminalMetadataEvent(rawItem) {
|
|
1309
|
+
if (!rawItem || typeof rawItem !== "object") return;
|
|
1310
|
+
const evt = rawItem;
|
|
1311
|
+
if (evt.type === "snapshot" && Array.isArray(evt.terminals)) {
|
|
1312
|
+
this.terminalMetadata.clear();
|
|
1313
|
+
for (const term of evt.terminals) {
|
|
1314
|
+
const tid = typeof term.threadId === "string" ? term.threadId : "";
|
|
1315
|
+
const termId = typeof term.terminalId === "string" ? term.terminalId : "";
|
|
1316
|
+
if (tid && termId) {
|
|
1317
|
+
this.terminalMetadata.set(`${tid}\0${termId}`, term);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
} else if (evt.type === "upsert" && evt.terminal && typeof evt.terminal === "object") {
|
|
1321
|
+
const tid = typeof evt.terminal.threadId === "string" ? evt.terminal.threadId : "";
|
|
1322
|
+
const termId = typeof evt.terminal.terminalId === "string" ? evt.terminal.terminalId : "";
|
|
1323
|
+
if (tid && termId) {
|
|
1324
|
+
this.terminalMetadata.set(`${tid}\0${termId}`, evt.terminal);
|
|
1325
|
+
}
|
|
1326
|
+
} else if (evt.type === "remove" && evt.threadId && evt.terminalId) {
|
|
1327
|
+
this.terminalMetadata.delete(`${evt.threadId}\0${evt.terminalId}`);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async handleConfigEvent(rawItem) {
|
|
1331
|
+
if (!rawItem || typeof rawItem !== "object") return;
|
|
1332
|
+
const evt = rawItem;
|
|
1333
|
+
if (evt.type === "snapshot" && evt.config) {
|
|
1334
|
+
if (evt.config.cwd) this.defaultCwd = evt.config.cwd;
|
|
1335
|
+
if (Array.isArray(evt.config.providers)) {
|
|
1336
|
+
const enriched = await enrichProvidersWithQuotas(evt.config.providers, false);
|
|
1337
|
+
this.lastProviders = enriched;
|
|
1338
|
+
this.callbacks.onProviders(enriched);
|
|
1339
|
+
}
|
|
1340
|
+
} else if ((evt.type === "providerStatuses" || evt.type === "providerStatusDeltas") && Array.isArray(evt.payload?.providers)) {
|
|
1341
|
+
const enriched = await enrichProvidersWithQuotas(evt.payload.providers, false);
|
|
1342
|
+
this.lastProviders = enriched;
|
|
1343
|
+
this.callbacks.onProviders(enriched);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
ensureThreadSubscribed(threadId, afterSequence = 0) {
|
|
1347
|
+
if (!threadId) return;
|
|
1348
|
+
const prev = this.wantedThreads.get(threadId) ?? 0;
|
|
1349
|
+
if (afterSequence > prev || !this.wantedThreads.has(threadId)) {
|
|
1350
|
+
this.wantedThreads.set(threadId, Math.max(prev, afterSequence));
|
|
1351
|
+
}
|
|
1352
|
+
if (this.subscribedThreads.has(threadId) || !this.isConnected()) return;
|
|
1353
|
+
this.subscribedThreads.add(threadId);
|
|
1354
|
+
const payload = { threadId };
|
|
1355
|
+
if (afterSequence > 0) payload.afterSequence = afterSequence;
|
|
1356
|
+
const reqId = this.startStream("orchestration.subscribeThread", payload, (rawItem) => {
|
|
1357
|
+
if (!rawItem || typeof rawItem !== "object") return;
|
|
1358
|
+
const env = rawItem;
|
|
1359
|
+
if (env.kind !== "event" || typeof env.sequence !== "number" || !env.event) return;
|
|
1360
|
+
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
1361
|
+
if (env.sequence > cur) this.wantedThreads.set(threadId, env.sequence);
|
|
1362
|
+
this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
|
|
1363
|
+
});
|
|
1364
|
+
if (!reqId) {
|
|
1365
|
+
this.subscribedThreads.delete(threadId);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
async refreshProviders(forceQuota = true) {
|
|
1369
|
+
const raw = await this.callRpc(
|
|
1370
|
+
"server.refreshProviders",
|
|
1371
|
+
{ fresh: true, usageLimitsCommand: true },
|
|
1372
|
+
3e4
|
|
1373
|
+
);
|
|
1374
|
+
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.providers) ? raw.providers : this.lastProviders;
|
|
1375
|
+
const enriched = await enrichProvidersWithQuotas(list, forceQuota);
|
|
1376
|
+
this.lastProviders = enriched;
|
|
1377
|
+
this.callbacks.onProviders(enriched);
|
|
1378
|
+
return { providers: enriched };
|
|
1379
|
+
}
|
|
1380
|
+
async ensureProject(workspaceRoot) {
|
|
1381
|
+
let targetRoot = (workspaceRoot ?? "").trim();
|
|
1382
|
+
if (!targetRoot) {
|
|
1383
|
+
if (!this.defaultCwd) {
|
|
1384
|
+
try {
|
|
1385
|
+
const cfg = await this.callRpc("server.getConfig", {}, 1e4);
|
|
1386
|
+
if (cfg?.cwd) this.defaultCwd = cfg.cwd;
|
|
1387
|
+
} catch {
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
targetRoot = this.defaultCwd || homedir5();
|
|
1391
|
+
}
|
|
1392
|
+
const token = await this.ensureLocalToken(false);
|
|
1393
|
+
const listResp = await fetch(`${this.baseUrl}/api/projects`, {
|
|
1394
|
+
method: "GET",
|
|
1395
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1396
|
+
signal: AbortSignal.timeout(1e4)
|
|
1397
|
+
});
|
|
1398
|
+
if (listResp.ok) {
|
|
1399
|
+
const snapshot = await listResp.json().catch(() => ({}));
|
|
1400
|
+
const cleanedTarget = targetRoot.replace(/\/+$/, "");
|
|
1401
|
+
for (const p of snapshot.projects ?? []) {
|
|
1402
|
+
if (p.id && p.workspaceRoot && p.workspaceRoot.replace(/\/+$/, "") === cleanedTarget) {
|
|
1403
|
+
return { projectId: p.id, workspaceRoot: p.workspaceRoot };
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
const projectId = crypto2.randomUUID();
|
|
1408
|
+
const title = basename(targetRoot.replace(/\/+$/, "")) || "workspace";
|
|
1409
|
+
const mutResp = await fetch(`${this.baseUrl}/api/projects/mutate`, {
|
|
1410
|
+
method: "POST",
|
|
1411
|
+
headers: {
|
|
1412
|
+
Authorization: `Bearer ${token}`,
|
|
1413
|
+
"Content-Type": "application/json"
|
|
1414
|
+
},
|
|
1415
|
+
body: JSON.stringify({
|
|
1416
|
+
type: "project.create",
|
|
1417
|
+
commandId: crypto2.randomUUID(),
|
|
1418
|
+
projectId,
|
|
1419
|
+
title,
|
|
1420
|
+
workspaceRoot: targetRoot,
|
|
1421
|
+
createWorkspaceRootIfMissing: true
|
|
1422
|
+
}),
|
|
1423
|
+
signal: AbortSignal.timeout(15e3)
|
|
1424
|
+
});
|
|
1425
|
+
const rawText = await mutResp.text();
|
|
1426
|
+
if (!mutResp.ok) {
|
|
1427
|
+
throw {
|
|
1428
|
+
tag: "ProjectMutationError",
|
|
1429
|
+
message: rawText.trim() || `HTTP ${mutResp.status}`
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
try {
|
|
1433
|
+
const created = JSON.parse(rawText);
|
|
1434
|
+
return {
|
|
1435
|
+
projectId: created.id || projectId,
|
|
1436
|
+
workspaceRoot: created.workspaceRoot || targetRoot
|
|
1437
|
+
};
|
|
1438
|
+
} catch {
|
|
1439
|
+
return { projectId, workspaceRoot: targetRoot };
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
async dispatchCommand(rawCommand) {
|
|
1443
|
+
const command = normalizeDispatchCommand(rawCommand);
|
|
1444
|
+
const threadId = typeof command.threadId === "string" ? command.threadId : "";
|
|
1445
|
+
const cmdType = typeof command.type === "string" ? command.type : "";
|
|
1446
|
+
if (cmdType === "message.dispatch" && Array.isArray(command.attachments) && command.attachments.length > 0) {
|
|
1447
|
+
const rawAtts = command.attachments;
|
|
1448
|
+
const uploadImages = rawAtts.filter(
|
|
1449
|
+
(att) => att && typeof att === "object" && att.type === "image" && typeof att.dataUrl === "string" && att.dataUrl.startsWith("data:image/")
|
|
1450
|
+
);
|
|
1451
|
+
const alreadyPersisted = rawAtts.filter(
|
|
1452
|
+
(att) => att && typeof att === "object" && typeof att.id === "string" && typeof att.dataUrl !== "string"
|
|
1453
|
+
);
|
|
1454
|
+
if (uploadImages.length > 0 && threadId) {
|
|
1455
|
+
const messageId = typeof command.messageId === "string" && command.messageId || typeof command.commandId === "string" && command.commandId || `msg-${Date.now()}`;
|
|
1456
|
+
try {
|
|
1457
|
+
const persisted = await this.callRpc(
|
|
1458
|
+
"assets.persistChatAttachments",
|
|
1459
|
+
{
|
|
1460
|
+
threadId,
|
|
1461
|
+
messageId,
|
|
1462
|
+
attachments: uploadImages.map((img) => ({
|
|
1463
|
+
type: "image",
|
|
1464
|
+
name: typeof img.name === "string" ? img.name : "image.png",
|
|
1465
|
+
mimeType: typeof img.mimeType === "string" ? img.mimeType : "image/png",
|
|
1466
|
+
sizeBytes: typeof img.sizeBytes === "number" ? img.sizeBytes : 0,
|
|
1467
|
+
dataUrl: img.dataUrl
|
|
1468
|
+
}))
|
|
1469
|
+
},
|
|
1470
|
+
2e4
|
|
1471
|
+
);
|
|
1472
|
+
command.attachments = [
|
|
1473
|
+
...alreadyPersisted,
|
|
1474
|
+
...Array.isArray(persisted?.attachments) ? persisted.attachments : []
|
|
1475
|
+
];
|
|
1476
|
+
} catch (err) {
|
|
1477
|
+
console.warn(
|
|
1478
|
+
`[local-t3] persistChatAttachments failed, falling back to text links: ${err instanceof Error ? err.message : String(err)}`
|
|
1479
|
+
);
|
|
1480
|
+
command.attachments = alreadyPersisted;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
if (threadId && cmdType !== "thread.create") {
|
|
1485
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
1486
|
+
}
|
|
1487
|
+
const result = await this.callRpc("orchestration.dispatchCommand", command, 55e3);
|
|
1488
|
+
if (threadId) {
|
|
1489
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
1490
|
+
}
|
|
1491
|
+
return result;
|
|
1492
|
+
}
|
|
1493
|
+
async fetchSnapshot(threadId) {
|
|
1494
|
+
if (!threadId) {
|
|
1495
|
+
throw { tag: "InvalidSnapshotRequest", message: "threadId is required" };
|
|
1496
|
+
}
|
|
1497
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
1498
|
+
const token = await this.ensureLocalToken(false);
|
|
1499
|
+
const resp = await fetch(
|
|
1500
|
+
`${this.baseUrl}/api/orchestration/threads/${encodeURIComponent(threadId)}/bounded`,
|
|
1501
|
+
{
|
|
1502
|
+
method: "GET",
|
|
1503
|
+
headers: {
|
|
1504
|
+
Authorization: `Bearer ${token}`,
|
|
1505
|
+
"X-T3-Orchestration-Protocol": "2"
|
|
1506
|
+
},
|
|
1507
|
+
signal: AbortSignal.timeout(15e3)
|
|
1508
|
+
}
|
|
1509
|
+
);
|
|
1510
|
+
const text = await resp.text();
|
|
1511
|
+
if (!resp.ok) {
|
|
1512
|
+
throw {
|
|
1513
|
+
tag: "SnapshotError",
|
|
1514
|
+
message: text.trim() || `HTTP ${resp.status}`
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
return JSON.parse(text);
|
|
1518
|
+
}
|
|
1519
|
+
async resolveDefaultCwd(override) {
|
|
1520
|
+
const trimmed = (override ?? "").trim();
|
|
1521
|
+
if (trimmed) return trimmed;
|
|
1522
|
+
if (!this.defaultCwd) {
|
|
1523
|
+
try {
|
|
1524
|
+
const cfg = await this.callRpc("server.getConfig", {}, 1e4);
|
|
1525
|
+
if (cfg?.cwd) this.defaultCwd = cfg.cwd;
|
|
1526
|
+
} catch {
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
return this.defaultCwd || homedir5();
|
|
1530
|
+
}
|
|
1531
|
+
listTerminals(threadId) {
|
|
1532
|
+
const prefix = `${threadId}\0`;
|
|
1533
|
+
const list = [];
|
|
1534
|
+
for (const [key, term] of this.terminalMetadata.entries()) {
|
|
1535
|
+
if (!key.startsWith(prefix)) continue;
|
|
1536
|
+
const status = typeof term.status === "string" ? term.status : "";
|
|
1537
|
+
if (status === "exited" || status === "error") continue;
|
|
1538
|
+
list.push(term);
|
|
1539
|
+
}
|
|
1540
|
+
list.sort((a, b) => String(a.terminalId ?? "").localeCompare(String(b.terminalId ?? "")));
|
|
1541
|
+
return { terminals: list };
|
|
1542
|
+
}
|
|
1543
|
+
async openTerminal(params) {
|
|
1544
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1545
|
+
if (!threadId) {
|
|
1546
|
+
throw { tag: "InvalidTerminalRequest", message: "threadId is required" };
|
|
1547
|
+
}
|
|
1548
|
+
const terminalId = (params.terminalId ?? "").trim() || `term-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
1549
|
+
const cwd = await this.resolveDefaultCwd(params.cwd);
|
|
1550
|
+
const payload = { threadId, terminalId, cwd };
|
|
1551
|
+
if (typeof params.cols === "number" && Number.isFinite(params.cols)) {
|
|
1552
|
+
payload.cols = Math.min(1e3, Math.max(1, Math.floor(params.cols)));
|
|
1553
|
+
}
|
|
1554
|
+
if (typeof params.rows === "number" && Number.isFinite(params.rows)) {
|
|
1555
|
+
payload.rows = Math.min(500, Math.max(1, Math.floor(params.rows)));
|
|
1556
|
+
}
|
|
1557
|
+
const snapshot = await this.callRpc("terminal.open", payload, 2e4);
|
|
1558
|
+
if (snapshot && typeof snapshot === "object") {
|
|
1559
|
+
this.terminalMetadata.set(`${threadId}\0${terminalId}`, {
|
|
1560
|
+
threadId,
|
|
1561
|
+
terminalId,
|
|
1562
|
+
cwd: snapshot.cwd ?? cwd,
|
|
1563
|
+
worktreePath: snapshot.worktreePath ?? null,
|
|
1564
|
+
status: snapshot.status ?? "running",
|
|
1565
|
+
pid: snapshot.pid ?? null,
|
|
1566
|
+
exitCode: snapshot.exitCode ?? null,
|
|
1567
|
+
exitSignal: snapshot.exitSignal ?? null,
|
|
1568
|
+
hasRunningSubprocess: false,
|
|
1569
|
+
label: snapshot.label ?? "shell",
|
|
1570
|
+
updatedAt: snapshot.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
return snapshot;
|
|
1574
|
+
}
|
|
1575
|
+
attachTerminal(params) {
|
|
1576
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1577
|
+
const terminalId = (params.terminalId ?? "").trim();
|
|
1578
|
+
if (!threadId || !terminalId) {
|
|
1579
|
+
throw { tag: "InvalidTerminalRequest", message: "threadId and terminalId are required" };
|
|
1580
|
+
}
|
|
1581
|
+
if (!this.isConnected()) {
|
|
1582
|
+
throw { tag: "LocalT3Offline", message: "\u672C\u673A\u539F\u7248 T3 \u5C1A\u672A\u8FDE\u63A5" };
|
|
1583
|
+
}
|
|
1584
|
+
const key = `${threadId}\0${terminalId}`;
|
|
1585
|
+
const existingReqId = this.terminalStreams.get(key);
|
|
1586
|
+
if (existingReqId) {
|
|
1587
|
+
this.interruptStream(existingReqId);
|
|
1588
|
+
this.terminalStreams.delete(key);
|
|
1589
|
+
}
|
|
1590
|
+
const payload = {
|
|
1591
|
+
threadId,
|
|
1592
|
+
terminalId,
|
|
1593
|
+
resume: true,
|
|
1594
|
+
maxHistoryBytes: 262144
|
|
1595
|
+
};
|
|
1596
|
+
if (params.cwd?.trim()) payload.cwd = params.cwd.trim();
|
|
1597
|
+
if (typeof params.cols === "number" && Number.isFinite(params.cols)) {
|
|
1598
|
+
payload.cols = Math.min(1e3, Math.max(1, Math.floor(params.cols)));
|
|
1599
|
+
}
|
|
1600
|
+
if (typeof params.rows === "number" && Number.isFinite(params.rows)) {
|
|
1601
|
+
payload.rows = Math.min(500, Math.max(1, Math.floor(params.rows)));
|
|
1602
|
+
}
|
|
1603
|
+
const reqId = this.startStream("terminal.attach", payload, (rawItem) => {
|
|
1604
|
+
if (!rawItem || typeof rawItem !== "object") return;
|
|
1605
|
+
const evt = rawItem;
|
|
1606
|
+
if (evt.type === "closed" || evt.type === "exited") {
|
|
1607
|
+
if (evt.type === "closed") {
|
|
1608
|
+
this.terminalMetadata.delete(key);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
this.callbacks.onTerminalEvent?.({ threadId, terminalId, event: rawItem });
|
|
1612
|
+
});
|
|
1613
|
+
if (!reqId) {
|
|
1614
|
+
throw { tag: "LocalT3SendError", message: "\u65E0\u6CD5\u8BA2\u9605\u672C\u5730\u7EC8\u7AEF\u6D41" };
|
|
1615
|
+
}
|
|
1616
|
+
this.terminalStreams.set(key, reqId);
|
|
1617
|
+
return { ok: true, threadId, terminalId };
|
|
1618
|
+
}
|
|
1619
|
+
detachTerminal(params) {
|
|
1620
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1621
|
+
const terminalId = (params.terminalId ?? "").trim();
|
|
1622
|
+
const key = `${threadId}\0${terminalId}`;
|
|
1623
|
+
const reqId = this.terminalStreams.get(key);
|
|
1624
|
+
if (reqId) {
|
|
1625
|
+
this.interruptStream(reqId);
|
|
1626
|
+
this.terminalStreams.delete(key);
|
|
1627
|
+
}
|
|
1628
|
+
return { ok: true };
|
|
1629
|
+
}
|
|
1630
|
+
detachAllTerminals() {
|
|
1631
|
+
for (const [, reqId] of this.terminalStreams.entries()) {
|
|
1632
|
+
this.interruptStream(reqId);
|
|
1633
|
+
}
|
|
1634
|
+
this.terminalStreams.clear();
|
|
1635
|
+
}
|
|
1636
|
+
async writeTerminal(params) {
|
|
1637
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1638
|
+
const terminalId = (params.terminalId ?? "").trim();
|
|
1639
|
+
const data = typeof params.data === "string" ? params.data : "";
|
|
1640
|
+
if (!threadId || !terminalId) {
|
|
1641
|
+
throw { tag: "InvalidTerminalRequest", message: "threadId and terminalId are required" };
|
|
1642
|
+
}
|
|
1643
|
+
if (!data) return { ok: true };
|
|
1644
|
+
const MAX_CHUNK = 65536;
|
|
1645
|
+
let start = 0;
|
|
1646
|
+
while (start < data.length) {
|
|
1647
|
+
let end = Math.min(start + MAX_CHUNK, data.length);
|
|
1648
|
+
const last = data.charCodeAt(end - 1);
|
|
1649
|
+
if (end < data.length && last >= 55296 && last <= 56319) {
|
|
1650
|
+
end -= 1;
|
|
1651
|
+
}
|
|
1652
|
+
const chunk = data.slice(start, end);
|
|
1653
|
+
if (chunk) {
|
|
1654
|
+
await this.callRpc("terminal.write", { threadId, terminalId, data: chunk }, 15e3);
|
|
1655
|
+
}
|
|
1656
|
+
start = end;
|
|
1657
|
+
}
|
|
1658
|
+
return { ok: true };
|
|
1659
|
+
}
|
|
1660
|
+
async resizeTerminal(params) {
|
|
1661
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1662
|
+
const terminalId = (params.terminalId ?? "").trim();
|
|
1663
|
+
if (!threadId || !terminalId) {
|
|
1664
|
+
throw { tag: "InvalidTerminalRequest", message: "threadId and terminalId are required" };
|
|
1665
|
+
}
|
|
1666
|
+
const cols = Math.min(1e3, Math.max(1, Math.floor(Number(params.cols) || 80)));
|
|
1667
|
+
const rows = Math.min(500, Math.max(1, Math.floor(Number(params.rows) || 24)));
|
|
1668
|
+
await this.callRpc("terminal.resize", { threadId, terminalId, cols, rows }, 1e4);
|
|
1669
|
+
return { ok: true };
|
|
1670
|
+
}
|
|
1671
|
+
async closeTerminal(params) {
|
|
1672
|
+
const threadId = (params.threadId ?? "").trim();
|
|
1673
|
+
const terminalId = (params.terminalId ?? "").trim();
|
|
1674
|
+
if (!threadId) {
|
|
1675
|
+
throw { tag: "InvalidTerminalRequest", message: "threadId is required" };
|
|
1676
|
+
}
|
|
1677
|
+
if (terminalId) {
|
|
1678
|
+
const key = `${threadId}\0${terminalId}`;
|
|
1679
|
+
const reqId = this.terminalStreams.get(key);
|
|
1680
|
+
if (reqId) {
|
|
1681
|
+
this.interruptStream(reqId);
|
|
1682
|
+
this.terminalStreams.delete(key);
|
|
1683
|
+
}
|
|
1684
|
+
this.terminalMetadata.delete(key);
|
|
1685
|
+
} else {
|
|
1686
|
+
const prefix = `${threadId}\0`;
|
|
1687
|
+
for (const [key, reqId] of [...this.terminalStreams.entries()]) {
|
|
1688
|
+
if (key.startsWith(prefix)) {
|
|
1689
|
+
this.interruptStream(reqId);
|
|
1690
|
+
this.terminalStreams.delete(key);
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
for (const key of [...this.terminalMetadata.keys()]) {
|
|
1694
|
+
if (key.startsWith(prefix)) this.terminalMetadata.delete(key);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
await this.callRpc(
|
|
1698
|
+
"terminal.close",
|
|
1699
|
+
{ threadId, ...terminalId ? { terminalId } : {} },
|
|
1700
|
+
15e3
|
|
1701
|
+
);
|
|
1702
|
+
return { ok: true };
|
|
1703
|
+
}
|
|
1704
|
+
};
|
|
1705
|
+
|
|
1706
|
+
// src/bridge.ts
|
|
1707
|
+
var EchoT3Bridge = class {
|
|
1708
|
+
configPath;
|
|
1709
|
+
config;
|
|
1710
|
+
localT3;
|
|
1711
|
+
hubWs = null;
|
|
1712
|
+
stopped = false;
|
|
1713
|
+
heartbeatTimer = null;
|
|
1714
|
+
reconnectTimer = null;
|
|
1715
|
+
backoffMs = 2e3;
|
|
1716
|
+
saveThreadsTimer = null;
|
|
1717
|
+
constructor(configPath) {
|
|
1718
|
+
this.configPath = configPath;
|
|
1719
|
+
}
|
|
1720
|
+
async start() {
|
|
1721
|
+
this.config = await loadConfig(this.configPath);
|
|
1722
|
+
if (!this.config.hub) {
|
|
1723
|
+
throw new Error(
|
|
1724
|
+
"\u5C1A\u672A\u4E0E\u516C\u7F51 Hub \u914D\u5BF9\u3002\u8BF7\u5148\u5728\u7F51\u9875\u7AEF\u70B9\u51FB\u300C\u751F\u6210\u914D\u5BF9\u7801\u300D\uFF0C\u7136\u540E\u6267\u884C:\n echo-t3-bridge setup --code <\u914D\u5BF9\u7801>"
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
1727
|
+
this.localT3 = new LocalT3Client(
|
|
1728
|
+
this.config.localT3,
|
|
1729
|
+
{
|
|
1730
|
+
onProviders: (providers) => {
|
|
1731
|
+
this.sendHubFrame({ type: "catalog", data: { providers } });
|
|
1732
|
+
},
|
|
1733
|
+
onThreadEvent: (envelope) => {
|
|
1734
|
+
this.sendHubFrame({ type: "event", data: envelope });
|
|
1735
|
+
this.scheduleSaveKnownThreads();
|
|
1736
|
+
},
|
|
1737
|
+
onTerminalEvent: (envelope) => {
|
|
1738
|
+
this.sendHubFrame({ type: "terminal.event", data: envelope });
|
|
1739
|
+
},
|
|
1740
|
+
onTokenUpdated: async (baseUrl, accessToken) => {
|
|
1741
|
+
this.config.localT3.baseUrl = baseUrl;
|
|
1742
|
+
this.config.localT3.accessToken = accessToken;
|
|
1743
|
+
await saveConfig(this.config, this.configPath);
|
|
1744
|
+
},
|
|
1745
|
+
onStatusChange: (connected) => {
|
|
1746
|
+
if (connected && this.hubWs?.readyState === WebSocket2.OPEN) {
|
|
1747
|
+
void this.localT3.refreshProviders(false).catch(() => void 0);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
},
|
|
1751
|
+
this.config.knownThreadIds ?? []
|
|
1752
|
+
);
|
|
1753
|
+
this.localT3.start();
|
|
1754
|
+
void this.connectHub();
|
|
1755
|
+
}
|
|
1756
|
+
stop() {
|
|
1757
|
+
this.stopped = true;
|
|
1758
|
+
if (this.saveThreadsTimer) clearTimeout(this.saveThreadsTimer);
|
|
1759
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
1760
|
+
this.teardownHub();
|
|
1761
|
+
this.localT3?.stop();
|
|
1762
|
+
}
|
|
1763
|
+
scheduleSaveKnownThreads() {
|
|
1764
|
+
if (this.saveThreadsTimer) return;
|
|
1765
|
+
this.saveThreadsTimer = setTimeout(() => {
|
|
1766
|
+
this.saveThreadsTimer = null;
|
|
1767
|
+
this.config.knownThreadIds = this.localT3.getKnownThreadIds();
|
|
1768
|
+
void saveConfig(this.config, this.configPath).catch(() => void 0);
|
|
1769
|
+
}, 5e3);
|
|
1770
|
+
}
|
|
1771
|
+
teardownHub() {
|
|
1772
|
+
this.localT3?.detachAllTerminals();
|
|
1773
|
+
if (this.heartbeatTimer) {
|
|
1774
|
+
clearInterval(this.heartbeatTimer);
|
|
1775
|
+
this.heartbeatTimer = null;
|
|
1776
|
+
}
|
|
1777
|
+
const ws = this.hubWs;
|
|
1778
|
+
this.hubWs = null;
|
|
1779
|
+
if (ws) {
|
|
1780
|
+
try {
|
|
1781
|
+
ws.close();
|
|
1782
|
+
} catch {
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
scheduleHubReconnect() {
|
|
1787
|
+
if (this.stopped || this.reconnectTimer) return;
|
|
1788
|
+
const wait = this.backoffMs;
|
|
1789
|
+
this.backoffMs = Math.min(this.backoffMs * 2, 3e4);
|
|
1790
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1791
|
+
this.reconnectTimer = null;
|
|
1792
|
+
void this.connectHub();
|
|
1793
|
+
}, wait);
|
|
1794
|
+
}
|
|
1795
|
+
async ensureFreshHubCredentials() {
|
|
1796
|
+
const creds = this.config.hub;
|
|
1797
|
+
if (creds.accessTokenExpiresAt - Date.now() < 5 * 6e4) {
|
|
1798
|
+
console.log("[hub] Access token \u5373\u5C06\u8FC7\u671F\uFF0C\u6B63\u5728\u7EED\u671F\u2026");
|
|
1799
|
+
const renewed = await renewHubToken(creds);
|
|
1800
|
+
this.config.hub = renewed;
|
|
1801
|
+
await saveConfig(this.config, this.configPath);
|
|
1802
|
+
return renewed;
|
|
1803
|
+
}
|
|
1804
|
+
return creds;
|
|
1805
|
+
}
|
|
1806
|
+
async connectHub(retriedAfterRenew = false) {
|
|
1807
|
+
if (this.stopped) return;
|
|
1808
|
+
let creds;
|
|
1809
|
+
try {
|
|
1810
|
+
creds = await this.ensureFreshHubCredentials();
|
|
1811
|
+
} catch (err) {
|
|
1812
|
+
console.error(`[hub] \u7EED\u671F\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`);
|
|
1813
|
+
this.scheduleHubReconnect();
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
const linkHttpUrl = `${creds.serverUrl}/api/t3/device/link`;
|
|
1817
|
+
const wsUrl = new URL(linkHttpUrl);
|
|
1818
|
+
wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
|
|
1819
|
+
const proof = createDpopProof({
|
|
1820
|
+
keyPair: creds.dpop,
|
|
1821
|
+
method: "GET",
|
|
1822
|
+
url: linkHttpUrl,
|
|
1823
|
+
accessToken: creds.accessToken
|
|
1824
|
+
});
|
|
1825
|
+
const ws = new WebSocket2(wsUrl.toString(), {
|
|
1826
|
+
headers: {
|
|
1827
|
+
Authorization: `DPoP ${creds.accessToken}`,
|
|
1828
|
+
DPoP: proof
|
|
1829
|
+
},
|
|
1830
|
+
maxPayload: 16 * 1024 * 1024
|
|
1831
|
+
});
|
|
1832
|
+
this.hubWs = ws;
|
|
1833
|
+
ws.on("unexpected-response", async (_req, res) => {
|
|
1834
|
+
if (this.hubWs !== ws) return;
|
|
1835
|
+
const status = res.statusCode ?? 0;
|
|
1836
|
+
console.error(`[hub] \u63E1\u624B\u88AB\u62D2\u7EDD (HTTP ${status})`);
|
|
1837
|
+
this.teardownHub();
|
|
1838
|
+
if (status === 401 && !retriedAfterRenew) {
|
|
1839
|
+
try {
|
|
1840
|
+
console.log("[hub] \u5C1D\u8BD5\u4F7F\u7528 DPoP \u5BC6\u94A5\u5237\u65B0 Access Token\u2026");
|
|
1841
|
+
const renewed = await renewHubToken(creds);
|
|
1842
|
+
this.config.hub = renewed;
|
|
1843
|
+
await saveConfig(this.config, this.configPath);
|
|
1844
|
+
void this.connectHub(true);
|
|
1845
|
+
return;
|
|
1846
|
+
} catch (err) {
|
|
1847
|
+
console.error(`[hub] \u5237\u65B0\u5931\u8D25\uFF0C\u8BBE\u5907\u53EF\u80FD\u5DF2\u5728\u7F51\u9875\u7AEF\u89E3\u7ED1: ${err instanceof Error ? err.message : String(err)}`);
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
this.scheduleHubReconnect();
|
|
1851
|
+
});
|
|
1852
|
+
ws.on("open", () => {
|
|
1853
|
+
if (this.hubWs !== ws) return;
|
|
1854
|
+
this.backoffMs = 2e3;
|
|
1855
|
+
console.log(`[hub] \u5DF2\u5EFA\u7ACB\u516C\u7F51\u53CD\u5411\u957F\u8FDE\u63A5 (${creds.serverUrl}, env=${creds.environmentId})`);
|
|
1856
|
+
this.sendHubFrame({
|
|
1857
|
+
type: "hello",
|
|
1858
|
+
data: {
|
|
1859
|
+
platform: process.platform,
|
|
1860
|
+
appVersion: `bridge-${APP_VERSION}`
|
|
1861
|
+
}
|
|
1862
|
+
});
|
|
1863
|
+
const cachedProviders = this.localT3.getLastProviders();
|
|
1864
|
+
if (cachedProviders.length > 0) {
|
|
1865
|
+
this.sendHubFrame({ type: "catalog", data: { providers: cachedProviders } });
|
|
1866
|
+
} else if (this.localT3.isConnected()) {
|
|
1867
|
+
void this.localT3.refreshProviders(false).catch(() => void 0);
|
|
1868
|
+
}
|
|
1869
|
+
});
|
|
1870
|
+
ws.on("message", (raw) => {
|
|
1871
|
+
if (this.hubWs !== ws) return;
|
|
1872
|
+
void this.handleHubMessage(raw.toString());
|
|
1873
|
+
});
|
|
1874
|
+
ws.on("close", (code, reason) => {
|
|
1875
|
+
if (this.hubWs !== ws) return;
|
|
1876
|
+
console.log(`[hub] \u957F\u8FDE\u63A5\u5173\u95ED (code=${code} ${reason.toString() || ""})\uFF0C\u51C6\u5907\u91CD\u8FDE\u2026`);
|
|
1877
|
+
this.teardownHub();
|
|
1878
|
+
this.scheduleHubReconnect();
|
|
1879
|
+
});
|
|
1880
|
+
ws.on("error", (err) => {
|
|
1881
|
+
if (this.hubWs !== ws) return;
|
|
1882
|
+
console.error(`[hub] WebSocket \u9519\u8BEF: ${err.message}`);
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
sendHubFrame(frame) {
|
|
1886
|
+
if (this.hubWs?.readyState === WebSocket2.OPEN) {
|
|
1887
|
+
this.hubWs.send(JSON.stringify(frame));
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
replyHub(type, id, payload) {
|
|
1891
|
+
if (!id) return;
|
|
1892
|
+
this.sendHubFrame({
|
|
1893
|
+
type: `${type}.result`,
|
|
1894
|
+
id,
|
|
1895
|
+
data: payload
|
|
1896
|
+
});
|
|
1897
|
+
}
|
|
1898
|
+
toRpcError(err) {
|
|
1899
|
+
if (err && typeof err === "object" && "tag" in err && "message" in err) {
|
|
1900
|
+
return err;
|
|
1901
|
+
}
|
|
1902
|
+
return {
|
|
1903
|
+
tag: "BridgeError",
|
|
1904
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
async handleHubMessage(raw) {
|
|
1908
|
+
let frame;
|
|
1909
|
+
try {
|
|
1910
|
+
frame = JSON.parse(raw);
|
|
1911
|
+
} catch {
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
switch (frame.type) {
|
|
1915
|
+
case "welcome": {
|
|
1916
|
+
const data = frame.data ?? {};
|
|
1917
|
+
const interval = Math.max(5e3, Number(data.heartbeatIntervalMs) || 2e4);
|
|
1918
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
1919
|
+
this.heartbeatTimer = setInterval(() => {
|
|
1920
|
+
this.sendHubFrame({ type: "heartbeat", id: `hb_${Date.now()}` });
|
|
1921
|
+
}, interval);
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
case "heartbeat_ack":
|
|
1925
|
+
case "events.resume":
|
|
1926
|
+
return;
|
|
1927
|
+
case "providers.refresh": {
|
|
1928
|
+
try {
|
|
1929
|
+
const result = await this.localT3.refreshProviders(true);
|
|
1930
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
1931
|
+
} catch (err) {
|
|
1932
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1933
|
+
}
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
case "fs.list": {
|
|
1937
|
+
try {
|
|
1938
|
+
const req = frame.data ?? {};
|
|
1939
|
+
const listing = await listDirectories(req.path);
|
|
1940
|
+
this.replyHub(frame.type, frame.id, { ok: true, result: listing });
|
|
1941
|
+
} catch (err) {
|
|
1942
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1943
|
+
}
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
case "project.ensure": {
|
|
1947
|
+
try {
|
|
1948
|
+
const req = frame.data ?? {};
|
|
1949
|
+
const ensured = await this.localT3.ensureProject(req.workspaceRoot);
|
|
1950
|
+
this.replyHub(frame.type, frame.id, { ok: true, result: ensured });
|
|
1951
|
+
} catch (err) {
|
|
1952
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1953
|
+
}
|
|
1954
|
+
return;
|
|
1955
|
+
}
|
|
1956
|
+
case "command": {
|
|
1957
|
+
try {
|
|
1958
|
+
const cmd = frame.data ?? {};
|
|
1959
|
+
const result = await this.localT3.dispatchCommand(cmd);
|
|
1960
|
+
this.scheduleSaveKnownThreads();
|
|
1961
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
1962
|
+
} catch (err) {
|
|
1963
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1964
|
+
}
|
|
1965
|
+
return;
|
|
1966
|
+
}
|
|
1967
|
+
case "snapshot": {
|
|
1968
|
+
try {
|
|
1969
|
+
const req = frame.data ?? {};
|
|
1970
|
+
const snap = await this.localT3.fetchSnapshot(req.threadId ?? "");
|
|
1971
|
+
this.scheduleSaveKnownThreads();
|
|
1972
|
+
this.replyHub(frame.type, frame.id, { ok: true, result: snap });
|
|
1973
|
+
} catch (err) {
|
|
1974
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1975
|
+
}
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
case "terminal.list": {
|
|
1979
|
+
try {
|
|
1980
|
+
const req = frame.data ?? {};
|
|
1981
|
+
const result = this.localT3.listTerminals(req.threadId ?? "");
|
|
1982
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
1983
|
+
} catch (err) {
|
|
1984
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
1985
|
+
}
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
case "terminal.open": {
|
|
1989
|
+
try {
|
|
1990
|
+
const req = frame.data ?? {};
|
|
1991
|
+
const result = await this.localT3.openTerminal({
|
|
1992
|
+
threadId: req.threadId ?? "",
|
|
1993
|
+
terminalId: req.terminalId,
|
|
1994
|
+
cwd: req.cwd,
|
|
1995
|
+
cols: req.cols,
|
|
1996
|
+
rows: req.rows
|
|
1997
|
+
});
|
|
1998
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
1999
|
+
} catch (err) {
|
|
2000
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2001
|
+
}
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
case "terminal.attach": {
|
|
2005
|
+
try {
|
|
2006
|
+
const req = frame.data ?? {};
|
|
2007
|
+
const result = this.localT3.attachTerminal({
|
|
2008
|
+
threadId: req.threadId ?? "",
|
|
2009
|
+
terminalId: req.terminalId ?? "",
|
|
2010
|
+
cwd: req.cwd,
|
|
2011
|
+
cols: req.cols,
|
|
2012
|
+
rows: req.rows
|
|
2013
|
+
});
|
|
2014
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2015
|
+
} catch (err) {
|
|
2016
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2017
|
+
}
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
case "terminal.detach": {
|
|
2021
|
+
try {
|
|
2022
|
+
const req = frame.data ?? {};
|
|
2023
|
+
const result = this.localT3.detachTerminal({
|
|
2024
|
+
threadId: req.threadId ?? "",
|
|
2025
|
+
terminalId: req.terminalId ?? ""
|
|
2026
|
+
});
|
|
2027
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2028
|
+
} catch (err) {
|
|
2029
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2030
|
+
}
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
case "terminal.write": {
|
|
2034
|
+
try {
|
|
2035
|
+
const req = frame.data ?? {};
|
|
2036
|
+
const result = await this.localT3.writeTerminal({
|
|
2037
|
+
threadId: req.threadId ?? "",
|
|
2038
|
+
terminalId: req.terminalId ?? "",
|
|
2039
|
+
data: req.data ?? ""
|
|
2040
|
+
});
|
|
2041
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2042
|
+
} catch (err) {
|
|
2043
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2044
|
+
}
|
|
2045
|
+
return;
|
|
2046
|
+
}
|
|
2047
|
+
case "terminal.resize": {
|
|
2048
|
+
try {
|
|
2049
|
+
const req = frame.data ?? {};
|
|
2050
|
+
const result = await this.localT3.resizeTerminal({
|
|
2051
|
+
threadId: req.threadId ?? "",
|
|
2052
|
+
terminalId: req.terminalId ?? "",
|
|
2053
|
+
cols: Number(req.cols) || 80,
|
|
2054
|
+
rows: Number(req.rows) || 24
|
|
2055
|
+
});
|
|
2056
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2057
|
+
} catch (err) {
|
|
2058
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2059
|
+
}
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
2062
|
+
case "terminal.close": {
|
|
2063
|
+
try {
|
|
2064
|
+
const req = frame.data ?? {};
|
|
2065
|
+
const result = await this.localT3.closeTerminal({
|
|
2066
|
+
threadId: req.threadId ?? "",
|
|
2067
|
+
terminalId: req.terminalId
|
|
2068
|
+
});
|
|
2069
|
+
this.replyHub(frame.type, frame.id, { ok: true, result });
|
|
2070
|
+
} catch (err) {
|
|
2071
|
+
this.replyHub(frame.type, frame.id, { ok: false, error: this.toRpcError(err) });
|
|
2072
|
+
}
|
|
2073
|
+
return;
|
|
2074
|
+
}
|
|
2075
|
+
case "error": {
|
|
2076
|
+
console.error("[hub] \u670D\u52A1\u7AEF\u8FD4\u56DE\u9519\u8BEF\u5E27:", JSON.stringify(frame.data));
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
default:
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
};
|
|
2084
|
+
|
|
2085
|
+
// src/index.ts
|
|
2086
|
+
function parseArgs(argv) {
|
|
2087
|
+
const positionals = [];
|
|
2088
|
+
const flags = {};
|
|
2089
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2090
|
+
const arg = argv[i];
|
|
2091
|
+
if (arg.startsWith("--")) {
|
|
2092
|
+
const eq = arg.indexOf("=");
|
|
2093
|
+
if (eq > 0) {
|
|
2094
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
|
|
2095
|
+
} else {
|
|
2096
|
+
const key = arg.slice(2);
|
|
2097
|
+
const next = argv[i + 1];
|
|
2098
|
+
if (next && !next.startsWith("-")) {
|
|
2099
|
+
flags[key] = next;
|
|
2100
|
+
i++;
|
|
2101
|
+
} else {
|
|
2102
|
+
flags[key] = true;
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
} else if (arg === "-v") {
|
|
2106
|
+
flags.version = true;
|
|
2107
|
+
} else if (arg === "-h") {
|
|
2108
|
+
flags.help = true;
|
|
2109
|
+
} else {
|
|
2110
|
+
positionals.push(arg);
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
return {
|
|
2114
|
+
command: positionals[0] ?? "help",
|
|
2115
|
+
subcommand: positionals[1],
|
|
2116
|
+
flags
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
function strFlag(flags, ...names) {
|
|
2120
|
+
for (const name of names) {
|
|
2121
|
+
const val = flags[name];
|
|
2122
|
+
if (typeof val === "string" && val.trim()) return val.trim();
|
|
2123
|
+
}
|
|
2124
|
+
return void 0;
|
|
2125
|
+
}
|
|
2126
|
+
function printHelp() {
|
|
2127
|
+
console.log(`echo-t3-bridge v${APP_VERSION}
|
|
2128
|
+
\u96F6\u4E8C\u5F00\u5B98\u65B9\u539F\u7248 T3 Code \u7684\u516C\u7F51\u53CD\u5411\u6865\u63A5\u5BA2\u6237\u7AEF\uFF08\u4E0E toc-ocra \u540C\u98CE\u683C npm CLI\uFF09
|
|
2129
|
+
|
|
2130
|
+
\u7528\u6CD5:
|
|
2131
|
+
echo-t3-bridge setup --code <\u914D\u5BF9\u7801> [--server ${DEFAULT_HUB_SERVER}] [--label <\u8BBE\u5907\u540D>]
|
|
2132
|
+
\u4E00\u952E\u5B8C\u6210\u516C\u7F51\u914D\u5BF9 + \u5173\u8054\u672C\u673A\u539F\u7248 T3 + \u5B89\u88C5\u5F00\u673A\u81EA\u542F\u540E\u53F0\u670D\u52A1
|
|
2133
|
+
|
|
2134
|
+
echo-t3-bridge pair --code <\u914D\u5BF9\u7801> [--server ${DEFAULT_HUB_SERVER}] [--label <\u8BBE\u5907\u540D>]
|
|
2135
|
+
\uFF08\u522B\u540D: enroll\uFF09\u4EC5\u6267\u884C\u516C\u7F51\u914D\u5BF9\u4E0E\u672C\u673A\u539F\u7248 T3 \u6388\u6743\uFF0C\u4E0D\u5B89\u88C5\u540E\u53F0\u670D\u52A1
|
|
2136
|
+
|
|
2137
|
+
echo-t3-bridge run
|
|
2138
|
+
\u524D\u53F0\u8FD0\u884C\u53CD\u5411\u6865\u63A5\u5B88\u62A4\u8FDB\u7A0B\uFF08\u53CC\u5411\u65AD\u7EBF\u81EA\u52A8\u91CD\u8FDE + \u5B9E\u65F6\u4E8B\u4EF6\u6D41 + agy \u989D\u5EA6\u589E\u5F3A\uFF09
|
|
2139
|
+
|
|
2140
|
+
echo-t3-bridge status | doctor
|
|
2141
|
+
\u68C0\u67E5\u516C\u7F51\u8FDE\u63A5\u72B6\u6001\u3001\u672C\u673A\u5B98\u65B9\u539F\u7248 T3 \u670D\u52A1\u72B6\u6001\u3001\u4EE5\u53CA agy \u989D\u5EA6\u63A2\u6D4B\u72B6\u6001
|
|
2142
|
+
|
|
2143
|
+
echo-t3-bridge service <install|uninstall|restart>
|
|
2144
|
+
\uFF08\u522B\u540D: service:install / service:uninstall\uFF09\u7BA1\u7406\u540E\u53F0\u5F00\u673A\u81EA\u542F\u670D\u52A1
|
|
2145
|
+
|
|
2146
|
+
echo-t3-bridge unpair
|
|
2147
|
+
\u89E3\u9664\u5F53\u524D\u8BBE\u5907\u4E0E\u516C\u7F51 Hub \u7684\u7ED1\u5B9A
|
|
2148
|
+
|
|
2149
|
+
\u9009\u9879:
|
|
2150
|
+
--server <url> \u516C\u7F51 Hub \u5730\u5740\uFF08\u9ED8\u8BA4 ${DEFAULT_HUB_SERVER}\uFF09
|
|
2151
|
+
--code <code> \u5728\u7F51\u9875\u7AEF\u70B9\u51FB\u300C\u751F\u6210\u914D\u5BF9\u7801\u300D\u83B7\u53D6\u7684\u4E00\u6B21\u6027\u914D\u5BF9\u7801
|
|
2152
|
+
--label <name> \u8BBE\u5907\u663E\u793A\u540D\u79F0\uFF08\u9ED8\u8BA4\u53D6\u672C\u673A\u4E3B\u673A\u540D\uFF09
|
|
2153
|
+
--t3-url <url> \u672C\u673A\u5B98\u65B9 T3 \u5730\u5740\uFF08\u9ED8\u8BA4\u81EA\u52A8\u63A2\u6D4B\uFF0C\u56DE\u9000 ${DEFAULT_LOCAL_T3_URL}\uFF09
|
|
2154
|
+
--t3-bin <path> \u6307\u5B9A\u672C\u673A\u5B98\u65B9 t3 \u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84
|
|
2155
|
+
--config <path> \u6307\u5B9A\u914D\u7F6E\u6587\u4EF6\u8DEF\u5F84\uFF08\u9ED8\u8BA4 ${defaultConfigPath()}\uFF09
|
|
2156
|
+
`);
|
|
2157
|
+
}
|
|
2158
|
+
function runServiceScript(action, configPath) {
|
|
2159
|
+
const currentDir = dirname3(fileURLToPath(import.meta.url));
|
|
2160
|
+
const scriptPath = resolve3(currentDir, "..", "scripts", "service.mjs");
|
|
2161
|
+
const res = spawnSync(process.execPath, [scriptPath, action, "--config", configPath], {
|
|
2162
|
+
stdio: "inherit"
|
|
2163
|
+
});
|
|
2164
|
+
if (res.status !== 0) {
|
|
2165
|
+
process.exit(res.status ?? 1);
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
async function doPair(flags, configPath) {
|
|
2169
|
+
const code = strFlag(flags, "code");
|
|
2170
|
+
if (!code) {
|
|
2171
|
+
throw new Error("\u7F3A\u5C11 --code \u53C2\u6570\u3002\u8BF7\u5148\u5728\u7F51\u9875\u7AEF\u70B9\u51FB\u300C\u751F\u6210\u914D\u5BF9\u7801\u300D\u83B7\u53D6\u914D\u5BF9\u7801\u3002");
|
|
2172
|
+
}
|
|
2173
|
+
const serverUrl = normalizeServerUrl(strFlag(flags, "server") ?? DEFAULT_HUB_SERVER);
|
|
2174
|
+
const label = strFlag(flags, "label") ?? defaultDeviceLabel();
|
|
2175
|
+
const t3UrlOverride = strFlag(flags, "t3-url");
|
|
2176
|
+
const t3BinOverride = strFlag(flags, "t3-bin");
|
|
2177
|
+
console.log(`1/2 \u6B63\u5728\u5411\u516C\u7F51 Hub (${serverUrl}) \u914D\u5BF9\u8BBE\u5907\u300C${label}\u300D\u2026`);
|
|
2178
|
+
const hubCreds = await pairWithHub({ serverUrl, code, label });
|
|
2179
|
+
console.log(`\u2713 \u516C\u7F51\u914D\u5BF9\u6210\u529F (environment_id=${hubCreds.environmentId})`);
|
|
2180
|
+
const cfg = await loadConfig(configPath);
|
|
2181
|
+
cfg.hub = hubCreds;
|
|
2182
|
+
if (t3UrlOverride) cfg.localT3.baseUrl = t3UrlOverride.replace(/\/+$/, "");
|
|
2183
|
+
if (t3BinOverride) cfg.localT3.t3Binary = t3BinOverride;
|
|
2184
|
+
console.log("2/2 \u6B63\u5728\u81EA\u52A8\u8FDE\u63A5\u672C\u673A\u5B98\u65B9\u539F\u7248 T3 Server\u2026");
|
|
2185
|
+
try {
|
|
2186
|
+
const localPaired = await pairLocalOfficialT3({
|
|
2187
|
+
baseUrl: t3UrlOverride,
|
|
2188
|
+
t3Binary: cfg.localT3.t3Binary
|
|
2189
|
+
});
|
|
2190
|
+
cfg.localT3.baseUrl = localPaired.baseUrl;
|
|
2191
|
+
cfg.localT3.accessToken = localPaired.accessToken;
|
|
2192
|
+
console.log(`\u2713 \u5DF2\u81EA\u52A8\u6388\u6743\u672C\u673A\u539F\u7248 T3 (${localPaired.baseUrl})`);
|
|
2193
|
+
} catch (err) {
|
|
2194
|
+
console.warn(
|
|
2195
|
+
`\u26A0 \u672C\u673A\u539F\u7248 T3 \u6682\u672A\u8FDE\u901A\uFF08\u7A0D\u540E\u542F\u52A8\u670D\u52A1\u540E\u4F1A\u81EA\u52A8\u91CD\u8BD5\uFF09\uFF1A${err instanceof Error ? err.message : String(err)}`
|
|
2196
|
+
);
|
|
2197
|
+
}
|
|
2198
|
+
await saveConfig(cfg, configPath);
|
|
2199
|
+
console.log(`\u2713 \u51ED\u636E\u5DF2\u4FDD\u5B58\u5230 ${configPath}`);
|
|
2200
|
+
}
|
|
2201
|
+
async function doDoctor(configPath) {
|
|
2202
|
+
const cfg = await loadConfig(configPath);
|
|
2203
|
+
console.log(`echo-t3-bridge v${APP_VERSION}`);
|
|
2204
|
+
console.log(`\u914D\u7F6E\u6587\u4EF6: ${configPath}`);
|
|
2205
|
+
if (!cfg.hub) {
|
|
2206
|
+
console.log("\u516C\u7F51 Hub: \u672A\u914D\u5BF9\uFF08\u8BF7\u8FD0\u884C echo-t3-bridge setup --code <\u914D\u5BF9\u7801>\uFF09");
|
|
2207
|
+
} else {
|
|
2208
|
+
const self = await fetchHubSelf(cfg.hub).catch(() => ({ ok: false, status: 0 }));
|
|
2209
|
+
const envName = self.environment?.name || cfg.hub.label;
|
|
2210
|
+
const online = self.online;
|
|
2211
|
+
console.log(
|
|
2212
|
+
`\u516C\u7F51 Hub: ${cfg.hub.serverUrl} | \u8BBE\u5907: ${envName} (${cfg.hub.environmentId}) | \u51ED\u636E: ${self.ok ? "\u6709\u6548" : `\u5F02\u5E38 (HTTP ${self.status})`} | \u5728\u7EBF: ${online ? "\u25CF \u5728\u7EBF" : "\u25CB \u79BB\u7EBF"}`
|
|
2213
|
+
);
|
|
2214
|
+
}
|
|
2215
|
+
const t3Bin = resolveLocalT3Binary(cfg.localT3.t3Binary);
|
|
2216
|
+
const localOk = await probeLocalT3Health(cfg.localT3.baseUrl);
|
|
2217
|
+
console.log(
|
|
2218
|
+
`\u672C\u673A\u539F\u7248 T3: ${cfg.localT3.baseUrl} | \u4E8C\u8FDB\u5236: ${t3Bin} | \u670D\u52A1: ${localOk ? "\u25CF \u8FD0\u884C\u4E2D" : "\u25CB \u672A\u542F\u52A8\uFF08\u8BF7\u8FD0\u884C t3 up\uFF09"} | \u672C\u5730\u4EE4\u724C: ${cfg.localT3.accessToken ? "\u5DF2\u6388\u6743" : "\u672A\u6388\u6743"}`
|
|
2219
|
+
);
|
|
2220
|
+
const agyBin = resolveAgyBinary();
|
|
2221
|
+
const agyUsage = await probeAntigravityUsage(true);
|
|
2222
|
+
if (agyUsage && agyUsage.windows.length > 0) {
|
|
2223
|
+
const summary = agyUsage.windows.map((w) => `${w.label} \u5269 ${Math.round(100 - w.usedPercent)}%`).join(" | ");
|
|
2224
|
+
console.log(`Antigravity \u989D\u5EA6 (${agyBin}): \u2713 ${summary}`);
|
|
2225
|
+
} else {
|
|
2226
|
+
console.log(`Antigravity \u989D\u5EA6 (${agyBin}): \u672A\u68C0\u6D4B\u5230\uFF08\u5982\u672A\u5B89\u88C5 agy \u53EF\u5FFD\u7565\uFF09`);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
async function main() {
|
|
2230
|
+
const parsed = parseArgs(process.argv.slice(2));
|
|
2231
|
+
const configPath = strFlag(parsed.flags, "config") ?? defaultConfigPath();
|
|
2232
|
+
if (parsed.flags.version || parsed.command === "version") {
|
|
2233
|
+
console.log(APP_VERSION);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (parsed.flags.help || parsed.command === "help") {
|
|
2237
|
+
printHelp();
|
|
2238
|
+
return;
|
|
2239
|
+
}
|
|
2240
|
+
switch (parsed.command) {
|
|
2241
|
+
case "setup": {
|
|
2242
|
+
await doPair(parsed.flags, configPath);
|
|
2243
|
+
console.log("\u6B63\u5728\u5B89\u88C5\u5E76\u542F\u52A8\u540E\u53F0\u5F00\u673A\u81EA\u542F\u670D\u52A1\u2026");
|
|
2244
|
+
runServiceScript("install", configPath);
|
|
2245
|
+
console.log("\u2713 \u5168\u90E8\u5B8C\u6210\uFF01\u8BBE\u5907\u5DF2\u63A5\u5165\u516C\u7F51 Hub\uFF0C\u53EF\u5728\u7F51\u9875\u7AEF\u76F4\u63A5\u4F7F\u7528\u3002");
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
case "pair":
|
|
2249
|
+
case "enroll": {
|
|
2250
|
+
await doPair(parsed.flags, configPath);
|
|
2251
|
+
console.log("\u63D0\u793A\uFF1A\u8FD0\u884C `echo-t3-bridge run` \u524D\u53F0\u542F\u52A8\uFF0C\u6216\u8FD0\u884C `echo-t3-bridge service install` \u5B89\u88C5\u540E\u53F0\u670D\u52A1\u3002");
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2254
|
+
case "run": {
|
|
2255
|
+
const bridge = new EchoT3Bridge(configPath);
|
|
2256
|
+
const shutdown = () => {
|
|
2257
|
+
console.log("[bridge] \u6B63\u5728\u505C\u6B62\u2026");
|
|
2258
|
+
bridge.stop();
|
|
2259
|
+
process.exit(0);
|
|
2260
|
+
};
|
|
2261
|
+
process.on("SIGINT", shutdown);
|
|
2262
|
+
process.on("SIGTERM", shutdown);
|
|
2263
|
+
await bridge.start();
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
case "status":
|
|
2267
|
+
case "doctor": {
|
|
2268
|
+
await doDoctor(configPath);
|
|
2269
|
+
return;
|
|
2270
|
+
}
|
|
2271
|
+
case "service:install": {
|
|
2272
|
+
runServiceScript("install", configPath);
|
|
2273
|
+
return;
|
|
2274
|
+
}
|
|
2275
|
+
case "service:uninstall": {
|
|
2276
|
+
runServiceScript("uninstall", configPath);
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
case "service": {
|
|
2280
|
+
if (parsed.subcommand === "install" || parsed.subcommand === "restart") {
|
|
2281
|
+
runServiceScript("install", configPath);
|
|
2282
|
+
} else if (parsed.subcommand === "uninstall") {
|
|
2283
|
+
runServiceScript("uninstall", configPath);
|
|
2284
|
+
} else if (parsed.subcommand === "status") {
|
|
2285
|
+
await doDoctor(configPath);
|
|
2286
|
+
} else {
|
|
2287
|
+
throw new Error("\u7528\u6CD5: echo-t3-bridge service <install|uninstall|restart|status>");
|
|
2288
|
+
}
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
2291
|
+
case "unpair": {
|
|
2292
|
+
const cfg = await loadConfig(configPath);
|
|
2293
|
+
if (cfg.hub) {
|
|
2294
|
+
await unpairFromHub(cfg.hub).catch(() => void 0);
|
|
2295
|
+
await clearHubCredentials(configPath);
|
|
2296
|
+
console.log("\u2713 \u5DF2\u89E3\u7ED1\u5F53\u524D\u8BBE\u5907\u5E76\u6E05\u7406\u672C\u5730\u516C\u7F51\u51ED\u636E\u3002");
|
|
2297
|
+
} else {
|
|
2298
|
+
console.log("\u5F53\u524D\u672A\u7ED1\u5B9A\u516C\u7F51 Hub\u3002");
|
|
2299
|
+
}
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
default:
|
|
2303
|
+
throw new Error(`\u672A\u77E5\u547D\u4EE4: ${parsed.command}\u3002\u8FD0\u884C \`echo-t3-bridge --help\` \u67E5\u770B\u5E2E\u52A9\u3002`);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
main().catch((err) => {
|
|
2307
|
+
console.error(`\u9519\u8BEF: ${err instanceof Error ? err.message : String(err)}`);
|
|
2308
|
+
process.exit(1);
|
|
2309
|
+
});
|