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
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir, tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { promisify, stripVTControlCharacters } from 'node:util';
|
|
8
|
+
import { hydrateProxyEnv, probeAntigravityUsage, } from './antigravity-quota.js';
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
const CACHE_TTL_MS = 60_000;
|
|
11
|
+
const quotaCache = new Map();
|
|
12
|
+
const inflightMap = new Map();
|
|
13
|
+
function resolveBinary(name, extraCandidates = []) {
|
|
14
|
+
const candidates = [
|
|
15
|
+
...extraCandidates,
|
|
16
|
+
join(homedir(), '.local', 'bin', name),
|
|
17
|
+
'/opt/homebrew/bin/' + name,
|
|
18
|
+
'/usr/local/bin/' + name,
|
|
19
|
+
].filter(Boolean);
|
|
20
|
+
for (const candidate of candidates) {
|
|
21
|
+
if (existsSync(candidate))
|
|
22
|
+
return candidate;
|
|
23
|
+
}
|
|
24
|
+
return name;
|
|
25
|
+
}
|
|
26
|
+
function epochSecondsToIso(sec) {
|
|
27
|
+
if (!Number.isFinite(sec) || sec <= 86_400)
|
|
28
|
+
return undefined;
|
|
29
|
+
return new Date(sec * 1000).toISOString();
|
|
30
|
+
}
|
|
31
|
+
function durationKind(durationMins) {
|
|
32
|
+
if (!durationMins || !Number.isFinite(durationMins))
|
|
33
|
+
return 'other';
|
|
34
|
+
if (durationMins >= 25 * 24 * 60)
|
|
35
|
+
return 'monthly';
|
|
36
|
+
if (durationMins >= 6 * 24 * 60)
|
|
37
|
+
return 'weekly';
|
|
38
|
+
if (durationMins <= 24 * 60)
|
|
39
|
+
return 'session';
|
|
40
|
+
return 'other';
|
|
41
|
+
}
|
|
42
|
+
export async function probeCodexUsage() {
|
|
43
|
+
const bin = resolveBinary('codex', [
|
|
44
|
+
process.env.CODEX_BIN ?? '',
|
|
45
|
+
'/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex',
|
|
46
|
+
]);
|
|
47
|
+
const env = await hydrateProxyEnv();
|
|
48
|
+
const child = spawn(bin, ['app-server', '--stdio'], {
|
|
49
|
+
env,
|
|
50
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
51
|
+
windowsHide: true,
|
|
52
|
+
});
|
|
53
|
+
let nextId = 0;
|
|
54
|
+
const pending = new Map();
|
|
55
|
+
const lines = createInterface({ input: child.stdout });
|
|
56
|
+
const rejectPending = (error) => {
|
|
57
|
+
for (const waiter of pending.values())
|
|
58
|
+
waiter.reject(error);
|
|
59
|
+
pending.clear();
|
|
60
|
+
};
|
|
61
|
+
child.once('error', rejectPending);
|
|
62
|
+
child.once('exit', (code) => {
|
|
63
|
+
if (pending.size)
|
|
64
|
+
rejectPending(new Error(`codex app-server exited (${code ?? 'unknown'})`));
|
|
65
|
+
});
|
|
66
|
+
lines.on('line', (line) => {
|
|
67
|
+
let message;
|
|
68
|
+
try {
|
|
69
|
+
message = JSON.parse(line);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (typeof message.id !== 'number')
|
|
75
|
+
return;
|
|
76
|
+
const waiter = pending.get(message.id);
|
|
77
|
+
if (!waiter)
|
|
78
|
+
return;
|
|
79
|
+
pending.delete(message.id);
|
|
80
|
+
if (message.error)
|
|
81
|
+
waiter.reject(new Error(message.error.message || 'codex rateLimits error'));
|
|
82
|
+
else
|
|
83
|
+
waiter.resolve(message.result);
|
|
84
|
+
});
|
|
85
|
+
const request = (method, params) => {
|
|
86
|
+
const id = ++nextId;
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const timer = setTimeout(() => {
|
|
89
|
+
pending.delete(id);
|
|
90
|
+
reject(new Error(`codex timeout (${method})`));
|
|
91
|
+
}, 15_000);
|
|
92
|
+
pending.set(id, {
|
|
93
|
+
resolve: (value) => {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
resolve(value);
|
|
96
|
+
},
|
|
97
|
+
reject: (err) => {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
reject(err);
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, id, params })}\n`, (err) => {
|
|
103
|
+
if (!err)
|
|
104
|
+
return;
|
|
105
|
+
const waiter = pending.get(id);
|
|
106
|
+
if (waiter) {
|
|
107
|
+
pending.delete(id);
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
waiter.reject(err);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
await request('initialize', {
|
|
116
|
+
clientInfo: { name: 'echo-t3-bridge', title: 'Echo T3 Bridge', version: '0.1.0' },
|
|
117
|
+
capabilities: { experimentalApi: true },
|
|
118
|
+
});
|
|
119
|
+
child.stdin.write('{"jsonrpc":"2.0","method":"initialized","params":{}}\n');
|
|
120
|
+
const result = (await request('account/rateLimits/read', {}));
|
|
121
|
+
const buckets = Object.entries(result?.rateLimitsByLimitId ?? {});
|
|
122
|
+
if (!buckets.length && result?.rateLimits) {
|
|
123
|
+
buckets.push([String(result.rateLimits.limitId || 'codex'), result.rateLimits]);
|
|
124
|
+
}
|
|
125
|
+
const windows = [];
|
|
126
|
+
for (const [limitId, snapshot] of buckets) {
|
|
127
|
+
for (const key of ['primary', 'secondary']) {
|
|
128
|
+
const win = snapshot[key];
|
|
129
|
+
if (!win)
|
|
130
|
+
continue;
|
|
131
|
+
const usedRaw = Number(win.usedPercent);
|
|
132
|
+
if (!Number.isFinite(usedRaw) || usedRaw < 0)
|
|
133
|
+
continue;
|
|
134
|
+
const resetRaw = Number(win.resetsAt);
|
|
135
|
+
const resetsSec = Number.isFinite(resetRaw) && resetRaw > 0
|
|
136
|
+
? Math.floor(resetRaw > 10_000_000_000 ? resetRaw / 1000 : resetRaw)
|
|
137
|
+
: 0;
|
|
138
|
+
const durationMins = Number(win.windowDurationMins);
|
|
139
|
+
const validDuration = Number.isFinite(durationMins) && durationMins > 0 ? Math.round(durationMins) : undefined;
|
|
140
|
+
const windowLabel = validDuration === 300
|
|
141
|
+
? '5 小时额度'
|
|
142
|
+
: validDuration && validDuration >= 10_000
|
|
143
|
+
? '每周额度'
|
|
144
|
+
: validDuration
|
|
145
|
+
? `${validDuration} 分钟额度`
|
|
146
|
+
: key === 'primary'
|
|
147
|
+
? '主要额度'
|
|
148
|
+
: '次要额度';
|
|
149
|
+
const bucketName = typeof snapshot.limitName === 'string' && snapshot.limitName.trim()
|
|
150
|
+
? snapshot.limitName.trim()
|
|
151
|
+
: limitId === 'codex'
|
|
152
|
+
? ''
|
|
153
|
+
: limitId;
|
|
154
|
+
const resetsAt = epochSecondsToIso(resetsSec);
|
|
155
|
+
windows.push({
|
|
156
|
+
id: `codex:${limitId}:${key}`,
|
|
157
|
+
label: bucketName ? `${bucketName} · ${windowLabel}` : windowLabel,
|
|
158
|
+
kind: durationKind(validDuration),
|
|
159
|
+
usedPercent: Math.min(100, Math.max(0, usedRaw)),
|
|
160
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
161
|
+
...(validDuration !== undefined ? { windowDurationMins: validDuration } : {}),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (windows.length === 0)
|
|
166
|
+
return null;
|
|
167
|
+
return { checkedAt: new Date().toISOString(), windows };
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
rejectPending(new Error('closed'));
|
|
174
|
+
lines.close();
|
|
175
|
+
try {
|
|
176
|
+
child.kill('SIGTERM');
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// ignore
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// ---- 2. Claude Code quota (ported 1:1 from toc_ocra/src/providers/claude-quota.ts) ----
|
|
184
|
+
const CLAUDE_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
|
|
185
|
+
const CLAUDE_USAGE_USER_AGENT = 'claude-code/2.1.0';
|
|
186
|
+
const CLAUDE_WINDOWS = [
|
|
187
|
+
{ key: 'five_hour', label: '5 小时额度', mins: 5 * 60, kind: 'session' },
|
|
188
|
+
{ key: 'seven_day', label: '每周额度', mins: 7 * 24 * 60, kind: 'weekly' },
|
|
189
|
+
{ key: 'seven_day_opus', label: 'Opus · 每周额度', mins: 7 * 24 * 60, kind: 'weekly' },
|
|
190
|
+
{ key: 'seven_day_sonnet', label: 'Sonnet · 每周额度', mins: 7 * 24 * 60, kind: 'weekly' },
|
|
191
|
+
];
|
|
192
|
+
function asObj(val) {
|
|
193
|
+
return val && typeof val === 'object' && !Array.isArray(val) ? val : {};
|
|
194
|
+
}
|
|
195
|
+
function parseClaudeToken(content, allowRaw) {
|
|
196
|
+
const trimmed = content.trim();
|
|
197
|
+
if (!trimmed)
|
|
198
|
+
return null;
|
|
199
|
+
try {
|
|
200
|
+
const parsed = asObj(JSON.parse(trimmed));
|
|
201
|
+
const oauth = Object.keys(asObj(parsed.claudeAiOauth)).length ? asObj(parsed.claudeAiOauth) : parsed;
|
|
202
|
+
return typeof oauth.accessToken === 'string' && oauth.accessToken.trim() ? oauth.accessToken.trim() : null;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return allowRaw ? trimmed : null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async function readClaudeTokens() {
|
|
209
|
+
const tokens = [];
|
|
210
|
+
const push = (t) => {
|
|
211
|
+
if (t && !tokens.includes(t))
|
|
212
|
+
tokens.push(t);
|
|
213
|
+
};
|
|
214
|
+
const fromEnv = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
|
|
215
|
+
if (fromEnv)
|
|
216
|
+
push(parseClaudeToken(fromEnv, true));
|
|
217
|
+
if (process.platform === 'darwin') {
|
|
218
|
+
const { stdout } = await execFileAsync('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], { timeout: 8_000 }).catch(() => ({ stdout: '' }));
|
|
219
|
+
push(parseClaudeToken(String(stdout).trim(), false));
|
|
220
|
+
}
|
|
221
|
+
const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude');
|
|
222
|
+
const fileContent = await readFile(join(claudeHome, '.credentials.json'), 'utf8').catch(() => '');
|
|
223
|
+
push(parseClaudeToken(fileContent, false));
|
|
224
|
+
return tokens;
|
|
225
|
+
}
|
|
226
|
+
export async function probeClaudeUsage() {
|
|
227
|
+
const tokens = await readClaudeTokens();
|
|
228
|
+
for (const token of tokens) {
|
|
229
|
+
try {
|
|
230
|
+
const response = await fetch(CLAUDE_USAGE_URL, {
|
|
231
|
+
headers: {
|
|
232
|
+
authorization: `Bearer ${token}`,
|
|
233
|
+
'anthropic-beta': 'oauth-2025-04-20',
|
|
234
|
+
'user-agent': CLAUDE_USAGE_USER_AGENT,
|
|
235
|
+
accept: 'application/json',
|
|
236
|
+
},
|
|
237
|
+
redirect: 'error',
|
|
238
|
+
signal: AbortSignal.timeout(12_000),
|
|
239
|
+
});
|
|
240
|
+
if (!response.ok)
|
|
241
|
+
continue;
|
|
242
|
+
const body = asObj(await response.json());
|
|
243
|
+
const windows = [];
|
|
244
|
+
for (const spec of CLAUDE_WINDOWS) {
|
|
245
|
+
const raw = body[spec.key];
|
|
246
|
+
if (!raw || typeof raw !== 'object')
|
|
247
|
+
continue;
|
|
248
|
+
const win = asObj(raw);
|
|
249
|
+
const utilization = Number(win.utilization);
|
|
250
|
+
if (win.utilization === null || !Number.isFinite(utilization) || utilization < 0)
|
|
251
|
+
continue;
|
|
252
|
+
let resetsAt;
|
|
253
|
+
if (typeof win.resets_at === 'string' && win.resets_at.trim()) {
|
|
254
|
+
const ms = Date.parse(win.resets_at);
|
|
255
|
+
if (Number.isFinite(ms) && ms > 86_400_000)
|
|
256
|
+
resetsAt = new Date(ms).toISOString();
|
|
257
|
+
}
|
|
258
|
+
else if (typeof win.resets_at === 'number' && Number.isFinite(win.resets_at) && win.resets_at > 0) {
|
|
259
|
+
const sec = win.resets_at > 10_000_000_000 ? Math.floor(win.resets_at / 1000) : Math.floor(win.resets_at);
|
|
260
|
+
resetsAt = epochSecondsToIso(sec);
|
|
261
|
+
}
|
|
262
|
+
windows.push({
|
|
263
|
+
id: `claude:${spec.key}`,
|
|
264
|
+
label: spec.label,
|
|
265
|
+
kind: spec.kind,
|
|
266
|
+
usedPercent: Math.min(100, Math.round(utilization * 100) / 100),
|
|
267
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
268
|
+
windowDurationMins: spec.mins,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
if (windows.length > 0) {
|
|
272
|
+
return { checkedAt: new Date().toISOString(), windows };
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
// ---- 3. Kiro quota (ported 1:1 from toc_ocra/src/providers/kiro-quota.ts) ----
|
|
282
|
+
export async function probeKiroUsage() {
|
|
283
|
+
const bin = resolveBinary('kiro-cli');
|
|
284
|
+
const env = await hydrateProxyEnv();
|
|
285
|
+
try {
|
|
286
|
+
const { stdout, stderr } = await execFileAsync(bin, ['chat', '--no-interactive', '/usage'], {
|
|
287
|
+
env,
|
|
288
|
+
cwd: tmpdir(),
|
|
289
|
+
timeout: 20_000,
|
|
290
|
+
maxBuffer: 1024 * 1024,
|
|
291
|
+
windowsHide: true,
|
|
292
|
+
});
|
|
293
|
+
const text = stripVTControlCharacters(`${stdout}\n${stderr}`).replace(/\r/g, '');
|
|
294
|
+
const usage = text.match(/^\s*Credits\s*\(\s*([\d,.]+)\s+of\s+([\d,.]+)\s+covered in plan\s*\)/im);
|
|
295
|
+
if (!usage)
|
|
296
|
+
return null;
|
|
297
|
+
const used = Number(usage[1].replace(/,/g, ''));
|
|
298
|
+
const total = Number(usage[2].replace(/,/g, ''));
|
|
299
|
+
if (!Number.isFinite(used) || !Number.isFinite(total) || total <= 0)
|
|
300
|
+
return null;
|
|
301
|
+
const usedPercent = Math.min(100, Math.max(0, Math.round((used / total) * 10000) / 100));
|
|
302
|
+
const now = new Date();
|
|
303
|
+
const dateMatch = text.match(/resets on\s+(\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i)?.[1];
|
|
304
|
+
let resetsAt;
|
|
305
|
+
if (dateMatch) {
|
|
306
|
+
let resetDate = dateMatch.includes('-') ? dateMatch : `${now.getFullYear()}-${dateMatch.replace('/', '-')}`;
|
|
307
|
+
if (!dateMatch.includes('-') &&
|
|
308
|
+
new Date(`${resetDate}T00:00:00`).getTime() < new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) {
|
|
309
|
+
resetDate = `${now.getFullYear() + 1}-${dateMatch.replace('/', '-')}`;
|
|
310
|
+
}
|
|
311
|
+
const ms = new Date(`${resetDate}T00:00:00`).getTime();
|
|
312
|
+
if (Number.isFinite(ms))
|
|
313
|
+
resetsAt = new Date(ms).toISOString();
|
|
314
|
+
}
|
|
315
|
+
const plan = text.match(/Estimated Usage[^\n]*\|\s*(KIRO[^|\n]*)/i)?.[1]?.trim();
|
|
316
|
+
return {
|
|
317
|
+
checkedAt: new Date().toISOString(),
|
|
318
|
+
windows: [
|
|
319
|
+
{
|
|
320
|
+
id: 'kiro:plan',
|
|
321
|
+
label: plan ? `套餐积分 · ${plan}` : '套餐积分',
|
|
322
|
+
kind: 'monthly',
|
|
323
|
+
usedPercent,
|
|
324
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
325
|
+
windowDurationMins: 30 * 24 * 60,
|
|
326
|
+
},
|
|
327
|
+
],
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function resolveQuotaDriver(rec) {
|
|
335
|
+
const driver = String(rec.driver ?? '').toLowerCase();
|
|
336
|
+
const id = String(rec.instanceId ?? '').toLowerCase();
|
|
337
|
+
if (driver === 'antigravity' || id === 'antigravity' || id === 'agy')
|
|
338
|
+
return 'antigravity';
|
|
339
|
+
if (driver === 'codex' || id === 'codex')
|
|
340
|
+
return 'codex';
|
|
341
|
+
if (driver === 'claudeagent' || driver === 'claude' || id === 'claudeagent' || id === 'claude')
|
|
342
|
+
return 'claude';
|
|
343
|
+
if (driver === 'kiro' || id === 'kiro')
|
|
344
|
+
return 'kiro';
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
async function probeDriverUsage(driver, force = false) {
|
|
348
|
+
if (driver === 'antigravity') {
|
|
349
|
+
return probeAntigravityUsage(force);
|
|
350
|
+
}
|
|
351
|
+
const cached = quotaCache.get(driver);
|
|
352
|
+
if (!force && cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
|
|
353
|
+
return cached.limits;
|
|
354
|
+
}
|
|
355
|
+
const existing = inflightMap.get(driver);
|
|
356
|
+
if (existing)
|
|
357
|
+
return existing;
|
|
358
|
+
const task = (async () => {
|
|
359
|
+
const result = driver === 'codex'
|
|
360
|
+
? await probeCodexUsage()
|
|
361
|
+
: driver === 'claude'
|
|
362
|
+
? await probeClaudeUsage()
|
|
363
|
+
: await probeKiroUsage();
|
|
364
|
+
if (result && result.windows.length > 0) {
|
|
365
|
+
quotaCache.set(driver, { fetchedAt: Date.now(), limits: result });
|
|
366
|
+
}
|
|
367
|
+
return result;
|
|
368
|
+
})().finally(() => {
|
|
369
|
+
inflightMap.delete(driver);
|
|
370
|
+
});
|
|
371
|
+
inflightMap.set(driver, task);
|
|
372
|
+
return task;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Enriches all installed/enabled providers reported by the unmodified local T3
|
|
376
|
+
* server using toc-ocra's proven quota readers (`agy`, `codex`, `claude`, `kiro`).
|
|
377
|
+
*/
|
|
378
|
+
export async function enrichProvidersWithQuotas(providers, forceQuota = false) {
|
|
379
|
+
const neededDrivers = new Set();
|
|
380
|
+
for (const p of providers) {
|
|
381
|
+
if (!p || typeof p !== 'object')
|
|
382
|
+
continue;
|
|
383
|
+
const rec = p;
|
|
384
|
+
if (rec.installed === false)
|
|
385
|
+
continue;
|
|
386
|
+
const driver = resolveQuotaDriver(rec);
|
|
387
|
+
if (!driver)
|
|
388
|
+
continue;
|
|
389
|
+
const existing = rec.usageLimits;
|
|
390
|
+
const hasExisting = Boolean(existing && Array.isArray(existing.windows) && existing.windows.length > 0);
|
|
391
|
+
// Always probe Antigravity (local T3 lacks its `/usage` reader) and any provider missing windows or force-refreshed.
|
|
392
|
+
if (forceQuota || !hasExisting || driver === 'antigravity') {
|
|
393
|
+
neededDrivers.add(driver);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (neededDrivers.size === 0)
|
|
397
|
+
return providers;
|
|
398
|
+
const probed = new Map();
|
|
399
|
+
await Promise.all([...neededDrivers].map(async (driver) => {
|
|
400
|
+
const limits = await probeDriverUsage(driver, forceQuota).catch(() => null);
|
|
401
|
+
if (limits && limits.windows.length > 0) {
|
|
402
|
+
probed.set(driver, limits);
|
|
403
|
+
}
|
|
404
|
+
}));
|
|
405
|
+
if (probed.size === 0)
|
|
406
|
+
return providers;
|
|
407
|
+
return providers.map((p) => {
|
|
408
|
+
if (!p || typeof p !== 'object')
|
|
409
|
+
return p;
|
|
410
|
+
const rec = p;
|
|
411
|
+
const driver = resolveQuotaDriver(rec);
|
|
412
|
+
if (!driver)
|
|
413
|
+
return p;
|
|
414
|
+
const limits = probed.get(driver);
|
|
415
|
+
if (!limits)
|
|
416
|
+
return p;
|
|
417
|
+
return {
|
|
418
|
+
...rec,
|
|
419
|
+
usageLimits: limits,
|
|
420
|
+
};
|
|
421
|
+
});
|
|
422
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "echo-t3-bridge",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zero-fork bridge connecting an unmodified local T3 Code server to Echo Hub over a reverse WebSocket tunnel.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"echo-t3-bridge": "dist/cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist/",
|
|
11
|
+
"scripts/service.mjs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.json && node scripts/build-cli.mjs",
|
|
17
|
+
"typecheck": "tsc --noEmit",
|
|
18
|
+
"dev": "tsx src/index.ts",
|
|
19
|
+
"start": "node dist/cli.mjs run",
|
|
20
|
+
"service:install": "node scripts/service.mjs install",
|
|
21
|
+
"service:uninstall": "node scripts/service.mjs uninstall",
|
|
22
|
+
"publish:latest": "bash ./publish-latest.sh"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"ws": "^8.18.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^22.15.0",
|
|
32
|
+
"@types/ws": "^8.18.0",
|
|
33
|
+
"esbuild": "^0.25.0",
|
|
34
|
+
"tsx": "^4.20.0",
|
|
35
|
+
"typescript": "^5.8.0"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"echo",
|
|
39
|
+
"t3",
|
|
40
|
+
"t3code",
|
|
41
|
+
"bridge",
|
|
42
|
+
"cli",
|
|
43
|
+
"agent"
|
|
44
|
+
],
|
|
45
|
+
"license": "MIT"
|
|
46
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { chmod, mkdir, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
|
|
9
|
+
const SERVICE_NAME = 'echo-t3-bridge';
|
|
10
|
+
const LAUNCHD_LABEL = 'top.stormapex.echo-t3-bridge';
|
|
11
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
12
|
+
const cliEntry = join(root, 'dist', 'cli.mjs');
|
|
13
|
+
const action = process.argv[2];
|
|
14
|
+
const dataDir = resolve(process.env.ECHO_T3_BRIDGE_DATA_DIR ?? defaultDataDir());
|
|
15
|
+
const configPath = resolve(
|
|
16
|
+
readOption('--config') ?? process.env.ECHO_T3_BRIDGE_CONFIG ?? join(dataDir, 'config.json')
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
if (action !== 'install' && action !== 'uninstall') {
|
|
20
|
+
console.error('用法: node scripts/service.mjs <install|uninstall> [--config <path>]');
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
if (action === 'install' && !existsSync(cliEntry)) {
|
|
24
|
+
console.error('缺少构建产物 dist/cli.mjs,请先运行 npm run build。');
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (process.platform === 'darwin') await manageLaunchd(action);
|
|
29
|
+
else if (process.platform === 'linux') await manageSystemd(action);
|
|
30
|
+
else if (process.platform === 'win32') await manageWindows(action);
|
|
31
|
+
else {
|
|
32
|
+
console.error(`暂不支持自动安装后台服务的系统: ${process.platform},请手动运行 echo-t3-bridge run`);
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function readOption(name) {
|
|
37
|
+
const index = process.argv.indexOf(name);
|
|
38
|
+
return index >= 0 ? process.argv[index + 1] : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function defaultDataDir() {
|
|
42
|
+
if (process.platform === 'darwin') return join(homedir(), 'Library', 'Application Support', SERVICE_NAME);
|
|
43
|
+
if (process.platform === 'win32') return join(process.env.APPDATA ?? homedir(), SERVICE_NAME);
|
|
44
|
+
return join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), SERVICE_NAME);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function buildServicePath() {
|
|
48
|
+
const home = homedir();
|
|
49
|
+
const extras = [
|
|
50
|
+
dirname(process.execPath),
|
|
51
|
+
join(home, '.t3', 'bin'),
|
|
52
|
+
join(home, '.local', 'bin'),
|
|
53
|
+
'/opt/homebrew/bin',
|
|
54
|
+
'/usr/local/bin',
|
|
55
|
+
'/usr/bin',
|
|
56
|
+
'/bin',
|
|
57
|
+
];
|
|
58
|
+
const current = (process.env.PATH ?? '').split(':').filter(Boolean);
|
|
59
|
+
return [...new Set([...extras, ...current])].join(':');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function xmlEscape(val) {
|
|
63
|
+
return String(val)
|
|
64
|
+
.replaceAll('&', '&')
|
|
65
|
+
.replaceAll('<', '<')
|
|
66
|
+
.replaceAll('>', '>')
|
|
67
|
+
.replaceAll('"', '"')
|
|
68
|
+
.replaceAll("'", ''');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function runCmd(cmd, args, ignoreFailure = false) {
|
|
72
|
+
const res = spawnSync(cmd, args, { stdio: 'inherit' });
|
|
73
|
+
if (!ignoreFailure && res.status !== 0) {
|
|
74
|
+
process.exit(res.status ?? 1);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function manageLaunchd(mode) {
|
|
79
|
+
const target = join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
|
|
80
|
+
const domain = `gui/${process.getuid()}`;
|
|
81
|
+
if (mode === 'uninstall') {
|
|
82
|
+
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
83
|
+
await unlink(target).catch(() => undefined);
|
|
84
|
+
console.log(`已移除 macOS 后台服务: ${target}`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
runCmd('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
89
|
+
const logDir = join(dataDir, 'logs');
|
|
90
|
+
await mkdir(dirname(target), { recursive: true });
|
|
91
|
+
await mkdir(logDir, { recursive: true, mode: 0o700 });
|
|
92
|
+
|
|
93
|
+
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
94
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
95
|
+
<plist version="1.0"><dict>
|
|
96
|
+
<key>Label</key><string>${LAUNCHD_LABEL}</string>
|
|
97
|
+
<key>ProgramArguments</key><array>
|
|
98
|
+
<string>${xmlEscape(process.execPath)}</string>
|
|
99
|
+
<string>${xmlEscape(cliEntry)}</string>
|
|
100
|
+
<string>run</string>
|
|
101
|
+
</array>
|
|
102
|
+
<key>EnvironmentVariables</key><dict>
|
|
103
|
+
<key>ECHO_T3_BRIDGE_CONFIG</key><string>${xmlEscape(configPath)}</string>
|
|
104
|
+
<key>ECHO_T3_BRIDGE_DATA_DIR</key><string>${xmlEscape(dataDir)}</string>
|
|
105
|
+
<key>HOME</key><string>${xmlEscape(homedir())}</string>
|
|
106
|
+
<key>SHELL</key><string>${xmlEscape(process.env.SHELL ?? '/bin/zsh')}</string>
|
|
107
|
+
<key>PATH</key><string>${xmlEscape(buildServicePath())}</string>
|
|
108
|
+
</dict>
|
|
109
|
+
<key>RunAtLoad</key><true/>
|
|
110
|
+
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
111
|
+
<key>ThrottleInterval</key><integer>5</integer>
|
|
112
|
+
<key>StandardOutPath</key><string>${xmlEscape(join(logDir, 'bridge.stdout.log'))}</string>
|
|
113
|
+
<key>StandardErrorPath</key><string>${xmlEscape(join(logDir, 'bridge.stderr.log'))}</string>
|
|
114
|
+
</dict></plist>
|
|
115
|
+
`;
|
|
116
|
+
await writeFile(target, plist, { mode: 0o600 });
|
|
117
|
+
runCmd('launchctl', ['enable', `${domain}/${LAUNCHD_LABEL}`], true);
|
|
118
|
+
runCmd('launchctl', ['bootstrap', domain, target]);
|
|
119
|
+
console.log(`✓ 已安装并启动 macOS 后台服务: ${LAUNCHD_LABEL}`);
|
|
120
|
+
console.log(` 日志目录: ${logDir}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function manageSystemd(mode) {
|
|
124
|
+
const target = join(homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`);
|
|
125
|
+
if (mode === 'uninstall') {
|
|
126
|
+
runCmd('systemctl', ['--user', 'disable', '--now', SERVICE_NAME], true);
|
|
127
|
+
await unlink(target).catch(() => undefined);
|
|
128
|
+
runCmd('systemctl', ['--user', 'daemon-reload'], true);
|
|
129
|
+
console.log(`已移除 systemd 服务: ${target}`);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
runCmd('systemctl', ['--user', 'stop', SERVICE_NAME], true);
|
|
134
|
+
await mkdir(dirname(target), { recursive: true });
|
|
135
|
+
const unit = `[Unit]
|
|
136
|
+
Description=Echo T3 Bridge (zero-fork local T3 to Echo Hub reverse tunnel)
|
|
137
|
+
After=network-online.target
|
|
138
|
+
Wants=network-online.target
|
|
139
|
+
|
|
140
|
+
[Service]
|
|
141
|
+
Type=simple
|
|
142
|
+
Environment="ECHO_T3_BRIDGE_CONFIG=${configPath}"
|
|
143
|
+
Environment="ECHO_T3_BRIDGE_DATA_DIR=${dataDir}"
|
|
144
|
+
Environment="PATH=${buildServicePath()}"
|
|
145
|
+
ExecStart="${process.execPath}" "${cliEntry}" run
|
|
146
|
+
Restart=always
|
|
147
|
+
RestartSec=3
|
|
148
|
+
|
|
149
|
+
[Install]
|
|
150
|
+
WantedBy=default.target
|
|
151
|
+
`;
|
|
152
|
+
await writeFile(target, unit, { mode: 0o644 });
|
|
153
|
+
runCmd('systemctl', ['--user', 'daemon-reload']);
|
|
154
|
+
runCmd('systemctl', ['--user', 'enable', '--now', SERVICE_NAME]);
|
|
155
|
+
console.log(`✓ 已安装并启动 systemd 用户服务: ${SERVICE_NAME}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function manageWindows(mode) {
|
|
159
|
+
const startupDir = join(
|
|
160
|
+
process.env.APPDATA ?? homedir(),
|
|
161
|
+
'Microsoft',
|
|
162
|
+
'Windows',
|
|
163
|
+
'Start Menu',
|
|
164
|
+
'Programs',
|
|
165
|
+
'Startup'
|
|
166
|
+
);
|
|
167
|
+
const vbsPath = join(startupDir, `${SERVICE_NAME}.vbs`);
|
|
168
|
+
const cmdPath = join(dataDir, 'run-bridge.cmd');
|
|
169
|
+
|
|
170
|
+
if (mode === 'uninstall') {
|
|
171
|
+
await unlink(vbsPath).catch(() => undefined);
|
|
172
|
+
await unlink(cmdPath).catch(() => undefined);
|
|
173
|
+
console.log(`已移除 Windows 开机自启脚本: ${vbsPath}`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
await mkdir(dataDir, { recursive: true });
|
|
178
|
+
await mkdir(startupDir, { recursive: true });
|
|
179
|
+
await writeFile(
|
|
180
|
+
cmdPath,
|
|
181
|
+
`@echo off\r\nset ECHO_T3_BRIDGE_CONFIG=${configPath}\r\n"${process.execPath}" "${cliEntry}" run\r\n`,
|
|
182
|
+
'utf8'
|
|
183
|
+
);
|
|
184
|
+
await writeFile(
|
|
185
|
+
vbsPath,
|
|
186
|
+
`Set WshShell = CreateObject("WScript.Shell")\r\nWshShell.Run """${cmdPath}""", 0, False\r\n`,
|
|
187
|
+
'utf8'
|
|
188
|
+
);
|
|
189
|
+
await chmod(cmdPath, 0o755).catch(() => undefined);
|
|
190
|
+
console.log(`✓ 已写入 Windows 自启脚本: ${vbsPath}`);
|
|
191
|
+
console.log(' 可立即执行 `echo-t3-bridge run` 或双击自启脚本启动服务。');
|
|
192
|
+
}
|