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,905 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { basename, join } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import WebSocket from 'ws';
|
|
8
|
+
import { enrichProvidersWithQuotas } from './provider-quotas.js';
|
|
9
|
+
import { DEFAULT_LOCAL_T3_URL, defaultDeviceLabel, } from './config.js';
|
|
10
|
+
import { ACCESS_TOKEN_TYPE, BOOTSTRAP_TOKEN_TYPE, TOKEN_EXCHANGE_GRANT_TYPE, } from './dpop.js';
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
export function resolveLocalT3Binary(override) {
|
|
13
|
+
const candidates = [
|
|
14
|
+
override,
|
|
15
|
+
process.env.T3_BIN,
|
|
16
|
+
join(homedir(), '.t3', 'bin', 't3'),
|
|
17
|
+
join(homedir(), '.local', 'bin', 't3'),
|
|
18
|
+
'/opt/homebrew/bin/t3',
|
|
19
|
+
'/usr/local/bin/t3',
|
|
20
|
+
].filter((v) => Boolean(v));
|
|
21
|
+
for (const candidate of candidates) {
|
|
22
|
+
if (existsSync(candidate))
|
|
23
|
+
return candidate;
|
|
24
|
+
}
|
|
25
|
+
return 't3';
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Runs official unmodified `t3 pair` locally and exchanges the one-time token
|
|
29
|
+
* over 127.0.0.1 for a local Bearer access token.
|
|
30
|
+
*/
|
|
31
|
+
export async function pairLocalOfficialT3(options) {
|
|
32
|
+
const bin = resolveLocalT3Binary(options?.t3Binary);
|
|
33
|
+
let stdout = '';
|
|
34
|
+
let stderr = '';
|
|
35
|
+
try {
|
|
36
|
+
const res = await execFileAsync(bin, ['pair'], {
|
|
37
|
+
timeout: 15_000,
|
|
38
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
39
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
40
|
+
});
|
|
41
|
+
stdout = res.stdout ?? '';
|
|
42
|
+
stderr = res.stderr ?? '';
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
46
|
+
throw new Error(`无法调用本机原版 \`${bin} pair\`。请确认本机已安装官方 T3 Code 且后台服务正在运行(可执行 \`t3 up\` 启动)。原始错误: ${msg}`);
|
|
47
|
+
}
|
|
48
|
+
const combined = `${stdout}\n${stderr}`;
|
|
49
|
+
const tokenMatch = /Token:\s*([A-Z0-9-]{6,64})/i.exec(combined) ?? /#token=([A-Z0-9-]{6,64})/i.exec(combined);
|
|
50
|
+
if (!tokenMatch?.[1]) {
|
|
51
|
+
throw new Error(`本机 \`${bin} pair\` 未返回配对码(请确认原版 T3 服务已启动,例如运行 \`t3 up\` 或打开 T3 桌面端)。输出:\n${combined.slice(0, 400)}`);
|
|
52
|
+
}
|
|
53
|
+
const pairingToken = tokenMatch[1].trim();
|
|
54
|
+
// Always connect to local loopback (127.0.0.1) regardless of LAN IP printed by `t3 pair`.
|
|
55
|
+
let baseUrl = options?.baseUrl?.trim().replace(/\/+$/, '') || '';
|
|
56
|
+
if (!baseUrl) {
|
|
57
|
+
const loopbackMatch = /\((https?:\/\/(?:127\.0\.0\.1|localhost):\d+)\)/i.exec(combined);
|
|
58
|
+
const portMatch = /https?:\/\/[^/\s:]+:(\d+)/i.exec(combined);
|
|
59
|
+
if (loopbackMatch?.[1]) {
|
|
60
|
+
baseUrl = loopbackMatch[1];
|
|
61
|
+
}
|
|
62
|
+
else if (portMatch?.[1]) {
|
|
63
|
+
baseUrl = `http://127.0.0.1:${portMatch[1]}`;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
baseUrl = DEFAULT_LOCAL_T3_URL;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const form = new URLSearchParams({
|
|
70
|
+
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
71
|
+
subject_token: pairingToken,
|
|
72
|
+
subject_token_type: BOOTSTRAP_TOKEN_TYPE,
|
|
73
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
74
|
+
client_label: `Echo T3 Bridge (${defaultDeviceLabel()})`,
|
|
75
|
+
client_device_type: 'desktop',
|
|
76
|
+
});
|
|
77
|
+
const resp = await fetch(`${baseUrl}/oauth/token`, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
80
|
+
body: form.toString(),
|
|
81
|
+
});
|
|
82
|
+
const data = (await resp.json().catch(() => ({})));
|
|
83
|
+
if (!resp.ok || !data.access_token) {
|
|
84
|
+
throw new Error(`本机原版 T3 (${baseUrl}) 令牌换取失败: ${data.error_description || data.message || data.error || `HTTP ${resp.status}`}`);
|
|
85
|
+
}
|
|
86
|
+
return { baseUrl, accessToken: data.access_token };
|
|
87
|
+
}
|
|
88
|
+
/** Check whether local official T3 server is reachable right now. */
|
|
89
|
+
export async function probeLocalT3Health(baseUrl) {
|
|
90
|
+
try {
|
|
91
|
+
const res = await fetch(`${baseUrl.replace(/\/+$/, '')}/`, {
|
|
92
|
+
method: 'GET',
|
|
93
|
+
signal: AbortSignal.timeout(3000),
|
|
94
|
+
});
|
|
95
|
+
return res.status >= 200 && res.status < 500;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function extractRpcError(exit) {
|
|
102
|
+
if (!exit)
|
|
103
|
+
return { tag: 'LocalT3RpcError', message: 'Empty RPC response' };
|
|
104
|
+
for (const entry of exit.cause ?? []) {
|
|
105
|
+
const raw = entry.error ?? entry.defect;
|
|
106
|
+
if (!raw)
|
|
107
|
+
continue;
|
|
108
|
+
if (typeof raw === 'string')
|
|
109
|
+
return { tag: 'LocalT3RpcError', message: raw };
|
|
110
|
+
if (typeof raw === 'object') {
|
|
111
|
+
const rec = raw;
|
|
112
|
+
const tag = typeof rec._tag === 'string' && rec._tag ? rec._tag : 'LocalT3RpcError';
|
|
113
|
+
const message = (typeof rec.message === 'string' && rec.message) ||
|
|
114
|
+
(typeof rec.detail === 'string' && rec.detail) ||
|
|
115
|
+
JSON.stringify(rec);
|
|
116
|
+
const detail = typeof rec.detail === 'string' ? rec.detail : undefined;
|
|
117
|
+
return { tag, message, ...(detail ? { detail } : {}) };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { tag: 'LocalT3RpcError', message: 'Local T3 RPC call failed' };
|
|
121
|
+
}
|
|
122
|
+
const AGY_LEVEL_SUFFIX_RE = /^((?:gemini|claude)-.+)-(low|medium|high|xhigh|max)$/;
|
|
123
|
+
/**
|
|
124
|
+
* Defensive guard: split legacy suffixed Antigravity model IDs like `gemini-3.8-flash-high`
|
|
125
|
+
* into pure `agy acp` 1.5.x model family + separate `thought_level` option before forwarding.
|
|
126
|
+
*/
|
|
127
|
+
export function normalizeDispatchCommand(rawCommand) {
|
|
128
|
+
const command = { ...rawCommand };
|
|
129
|
+
const cmdType = typeof command.type === 'string' ? command.type : '';
|
|
130
|
+
const needsCreatedBy = [
|
|
131
|
+
'thread.create',
|
|
132
|
+
'message.dispatch',
|
|
133
|
+
'thread.fork',
|
|
134
|
+
'thread.merge_back',
|
|
135
|
+
'delegated_task.request',
|
|
136
|
+
];
|
|
137
|
+
if (needsCreatedBy.includes(cmdType)) {
|
|
138
|
+
if (!command.createdBy) {
|
|
139
|
+
command.createdBy = 'user';
|
|
140
|
+
}
|
|
141
|
+
if (!command.creationSource) {
|
|
142
|
+
command.creationSource = 'web';
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const sel = command.modelSelection;
|
|
146
|
+
if (!sel || typeof sel !== 'object' || Array.isArray(sel))
|
|
147
|
+
return command;
|
|
148
|
+
const selObj = { ...sel };
|
|
149
|
+
const instanceId = String(selObj.instanceId ?? selObj.provider ?? '').toLowerCase();
|
|
150
|
+
const isAgy = instanceId === 'antigravity' || instanceId === 'agy' || instanceId.includes('antigravity');
|
|
151
|
+
if (!isAgy || typeof selObj.model !== 'string')
|
|
152
|
+
return command;
|
|
153
|
+
const match = AGY_LEVEL_SUFFIX_RE.exec(selObj.model.trim());
|
|
154
|
+
if (!match)
|
|
155
|
+
return command;
|
|
156
|
+
const [, baseModel, level] = match;
|
|
157
|
+
selObj.model = baseModel;
|
|
158
|
+
const existingOpts = selObj.options;
|
|
159
|
+
if (Array.isArray(existingOpts)) {
|
|
160
|
+
const hasThought = existingOpts.some((item) => item &&
|
|
161
|
+
typeof item === 'object' &&
|
|
162
|
+
(item.id === 'thought_level' ||
|
|
163
|
+
item.id === 'reasoningEffort'));
|
|
164
|
+
if (!hasThought) {
|
|
165
|
+
selObj.options = [...existingOpts, { id: 'thought_level', value: level }];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
else if (existingOpts && typeof existingOpts === 'object') {
|
|
169
|
+
const rec = { ...existingOpts };
|
|
170
|
+
if (!('thought_level' in rec) && !('reasoningEffort' in rec)) {
|
|
171
|
+
rec.thought_level = level;
|
|
172
|
+
}
|
|
173
|
+
selObj.options = rec;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
selObj.options = [{ id: 'thought_level', value: level }];
|
|
177
|
+
}
|
|
178
|
+
return { ...command, modelSelection: selObj };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Persistent client connected to the local unmodified official T3 Code server
|
|
182
|
+
* via its native `/api/auth/websocket-ticket`, Effect-RPC `/ws`, and HTTP APIs.
|
|
183
|
+
*/
|
|
184
|
+
export class LocalT3Client {
|
|
185
|
+
baseUrl;
|
|
186
|
+
accessToken;
|
|
187
|
+
t3Binary;
|
|
188
|
+
callbacks;
|
|
189
|
+
ws = null;
|
|
190
|
+
connected = false;
|
|
191
|
+
stopped = false;
|
|
192
|
+
nextId = 1;
|
|
193
|
+
defaultCwd = '';
|
|
194
|
+
lastProviders = [];
|
|
195
|
+
pending = new Map();
|
|
196
|
+
streams = new Map();
|
|
197
|
+
subscribedThreads = new Set();
|
|
198
|
+
wantedThreads = new Map();
|
|
199
|
+
terminalMetadata = new Map();
|
|
200
|
+
terminalStreams = new Map();
|
|
201
|
+
pingTimer = null;
|
|
202
|
+
reconnectTimer = null;
|
|
203
|
+
backoffMs = 2_000;
|
|
204
|
+
constructor(config, callbacks, initialThreads = []) {
|
|
205
|
+
this.baseUrl = (config.baseUrl || DEFAULT_LOCAL_T3_URL).replace(/\/+$/, '');
|
|
206
|
+
this.accessToken = config.accessToken;
|
|
207
|
+
this.t3Binary = config.t3Binary;
|
|
208
|
+
this.callbacks = callbacks;
|
|
209
|
+
for (const tid of initialThreads) {
|
|
210
|
+
if (tid)
|
|
211
|
+
this.wantedThreads.set(tid, 0);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
isConnected() {
|
|
215
|
+
return this.connected && this.ws?.readyState === WebSocket.OPEN;
|
|
216
|
+
}
|
|
217
|
+
getLastProviders() {
|
|
218
|
+
return this.lastProviders;
|
|
219
|
+
}
|
|
220
|
+
getKnownThreadIds() {
|
|
221
|
+
return [...this.wantedThreads.keys()].slice(-30);
|
|
222
|
+
}
|
|
223
|
+
start() {
|
|
224
|
+
this.stopped = false;
|
|
225
|
+
void this.connectLoop();
|
|
226
|
+
}
|
|
227
|
+
stop() {
|
|
228
|
+
this.stopped = true;
|
|
229
|
+
if (this.reconnectTimer) {
|
|
230
|
+
clearTimeout(this.reconnectTimer);
|
|
231
|
+
this.reconnectTimer = null;
|
|
232
|
+
}
|
|
233
|
+
this.teardownSocket();
|
|
234
|
+
}
|
|
235
|
+
teardownSocket() {
|
|
236
|
+
if (this.pingTimer) {
|
|
237
|
+
clearInterval(this.pingTimer);
|
|
238
|
+
this.pingTimer = null;
|
|
239
|
+
}
|
|
240
|
+
const ws = this.ws;
|
|
241
|
+
this.ws = null;
|
|
242
|
+
const wasConnected = this.connected;
|
|
243
|
+
this.connected = false;
|
|
244
|
+
this.subscribedThreads.clear();
|
|
245
|
+
this.terminalStreams.clear();
|
|
246
|
+
this.terminalMetadata.clear();
|
|
247
|
+
this.streams.clear();
|
|
248
|
+
for (const [, entry] of this.pending) {
|
|
249
|
+
clearTimeout(entry.timer);
|
|
250
|
+
entry.reject({ tag: 'LocalT3Disconnected', message: 'Local T3 connection closed' });
|
|
251
|
+
}
|
|
252
|
+
this.pending.clear();
|
|
253
|
+
if (ws) {
|
|
254
|
+
try {
|
|
255
|
+
ws.close();
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
// ignore
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (wasConnected) {
|
|
262
|
+
this.callbacks.onStatusChange?.(false);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
scheduleReconnect() {
|
|
266
|
+
if (this.stopped)
|
|
267
|
+
return;
|
|
268
|
+
if (this.reconnectTimer)
|
|
269
|
+
return;
|
|
270
|
+
const wait = this.backoffMs;
|
|
271
|
+
this.backoffMs = Math.min(this.backoffMs * 2, 30_000);
|
|
272
|
+
this.reconnectTimer = setTimeout(() => {
|
|
273
|
+
this.reconnectTimer = null;
|
|
274
|
+
void this.connectLoop();
|
|
275
|
+
}, wait);
|
|
276
|
+
}
|
|
277
|
+
async ensureLocalToken(forceRepair = false) {
|
|
278
|
+
if (this.accessToken && !forceRepair)
|
|
279
|
+
return this.accessToken;
|
|
280
|
+
const paired = await pairLocalOfficialT3({
|
|
281
|
+
baseUrl: this.baseUrl,
|
|
282
|
+
t3Binary: this.t3Binary,
|
|
283
|
+
});
|
|
284
|
+
this.baseUrl = paired.baseUrl.replace(/\/+$/, '');
|
|
285
|
+
this.accessToken = paired.accessToken;
|
|
286
|
+
await this.callbacks.onTokenUpdated(this.baseUrl, this.accessToken);
|
|
287
|
+
return this.accessToken;
|
|
288
|
+
}
|
|
289
|
+
async issueWsTicket() {
|
|
290
|
+
let token = await this.ensureLocalToken(false);
|
|
291
|
+
let resp = await fetch(`${this.baseUrl}/api/auth/websocket-ticket`, {
|
|
292
|
+
method: 'POST',
|
|
293
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
294
|
+
signal: AbortSignal.timeout(8_000),
|
|
295
|
+
});
|
|
296
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
297
|
+
console.log('[local-t3] 本地令牌已失效,正在自动重新配对本机原版 T3…');
|
|
298
|
+
token = await this.ensureLocalToken(true);
|
|
299
|
+
resp = await fetch(`${this.baseUrl}/api/auth/websocket-ticket`, {
|
|
300
|
+
method: 'POST',
|
|
301
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
302
|
+
signal: AbortSignal.timeout(8_000),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
if (!resp.ok) {
|
|
306
|
+
const text = await resp.text().catch(() => '');
|
|
307
|
+
throw new Error(`websocket-ticket HTTP ${resp.status}: ${text.slice(0, 200)}`);
|
|
308
|
+
}
|
|
309
|
+
const json = (await resp.json());
|
|
310
|
+
if (!json.ticket)
|
|
311
|
+
throw new Error('Empty websocket ticket from local T3');
|
|
312
|
+
return json.ticket;
|
|
313
|
+
}
|
|
314
|
+
async connectLoop() {
|
|
315
|
+
if (this.stopped)
|
|
316
|
+
return;
|
|
317
|
+
try {
|
|
318
|
+
const ticket = await this.issueWsTicket();
|
|
319
|
+
const wsUrl = new URL(this.baseUrl);
|
|
320
|
+
wsUrl.protocol = wsUrl.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
321
|
+
wsUrl.pathname = '/ws';
|
|
322
|
+
wsUrl.searchParams.set('orchestrationProtocol', '2');
|
|
323
|
+
wsUrl.searchParams.set('wsTicket', ticket);
|
|
324
|
+
const ws = new WebSocket(wsUrl.toString(), { maxPayload: 32 * 1024 * 1024 });
|
|
325
|
+
this.ws = ws;
|
|
326
|
+
ws.on('open', () => {
|
|
327
|
+
if (this.ws !== ws)
|
|
328
|
+
return;
|
|
329
|
+
this.connected = true;
|
|
330
|
+
this.backoffMs = 2_000;
|
|
331
|
+
console.log(`[local-t3] 已连接本机原版 T3 Server (${this.baseUrl})`);
|
|
332
|
+
this.callbacks.onStatusChange?.(true);
|
|
333
|
+
this.pingTimer = setInterval(() => {
|
|
334
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
335
|
+
ws.send(JSON.stringify({ _tag: 'Ping' }));
|
|
336
|
+
}
|
|
337
|
+
}, 25_000);
|
|
338
|
+
void this.bootstrapStreams();
|
|
339
|
+
});
|
|
340
|
+
ws.on('message', (data) => {
|
|
341
|
+
if (this.ws !== ws)
|
|
342
|
+
return;
|
|
343
|
+
this.handleWsMessage(data.toString());
|
|
344
|
+
});
|
|
345
|
+
ws.on('close', (code, reason) => {
|
|
346
|
+
if (this.ws !== ws)
|
|
347
|
+
return;
|
|
348
|
+
console.log(`[local-t3] 连接已断开 (code=${code} ${reason.toString() || ''}),准备重连…`);
|
|
349
|
+
this.teardownSocket();
|
|
350
|
+
this.scheduleReconnect();
|
|
351
|
+
});
|
|
352
|
+
ws.on('error', (err) => {
|
|
353
|
+
if (this.ws !== ws)
|
|
354
|
+
return;
|
|
355
|
+
console.error(`[local-t3] WebSocket 错误: ${err.message}`);
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
catch (err) {
|
|
359
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
360
|
+
console.error(`[local-t3] 连接本机原版 T3 失败: ${msg}`);
|
|
361
|
+
this.scheduleReconnect();
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
handleWsMessage(raw) {
|
|
365
|
+
let msg;
|
|
366
|
+
try {
|
|
367
|
+
msg = JSON.parse(raw);
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (msg._tag === 'Pong')
|
|
373
|
+
return;
|
|
374
|
+
const reqId = msg.requestId !== undefined ? String(msg.requestId) : '';
|
|
375
|
+
if (!reqId)
|
|
376
|
+
return;
|
|
377
|
+
if (msg._tag === 'Chunk') {
|
|
378
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
379
|
+
this.ws.send(JSON.stringify({ _tag: 'Ack', requestId: reqId }));
|
|
380
|
+
}
|
|
381
|
+
const handler = this.streams.get(reqId);
|
|
382
|
+
if (handler && Array.isArray(msg.values)) {
|
|
383
|
+
for (const item of msg.values) {
|
|
384
|
+
handler(item);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (msg._tag === 'Exit') {
|
|
390
|
+
this.streams.delete(reqId);
|
|
391
|
+
const pending = this.pending.get(reqId);
|
|
392
|
+
if (!pending)
|
|
393
|
+
return;
|
|
394
|
+
this.pending.delete(reqId);
|
|
395
|
+
clearTimeout(pending.timer);
|
|
396
|
+
if (msg.exit?._tag === 'Success') {
|
|
397
|
+
pending.resolve(msg.exit.value);
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
pending.reject(extractRpcError(msg.exit));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
nextRequestId() {
|
|
405
|
+
const id = this.nextId++;
|
|
406
|
+
return String(id);
|
|
407
|
+
}
|
|
408
|
+
async callRpc(method, payload, timeoutMs = 55_000) {
|
|
409
|
+
if (!this.isConnected() || !this.ws) {
|
|
410
|
+
throw { tag: 'LocalT3Offline', message: '本机原版 T3 尚未连接,请确认 `t3 up` 或 T3 桌面端正在运行' };
|
|
411
|
+
}
|
|
412
|
+
const id = this.nextRequestId();
|
|
413
|
+
return new Promise((resolve, reject) => {
|
|
414
|
+
const timer = setTimeout(() => {
|
|
415
|
+
this.pending.delete(id);
|
|
416
|
+
reject({ tag: 'LocalT3Timeout', message: `本地 T3 RPC ${method} 超时` });
|
|
417
|
+
}, timeoutMs);
|
|
418
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
419
|
+
try {
|
|
420
|
+
this.ws.send(JSON.stringify({
|
|
421
|
+
_tag: 'Request',
|
|
422
|
+
id,
|
|
423
|
+
tag: method,
|
|
424
|
+
payload,
|
|
425
|
+
headers: [],
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
catch (err) {
|
|
429
|
+
clearTimeout(timer);
|
|
430
|
+
this.pending.delete(id);
|
|
431
|
+
reject({
|
|
432
|
+
tag: 'LocalT3SendError',
|
|
433
|
+
message: err instanceof Error ? err.message : String(err),
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
startStream(method, payload, onItem) {
|
|
439
|
+
if (!this.isConnected() || !this.ws)
|
|
440
|
+
return null;
|
|
441
|
+
const id = this.nextRequestId();
|
|
442
|
+
this.streams.set(id, onItem);
|
|
443
|
+
try {
|
|
444
|
+
this.ws.send(JSON.stringify({
|
|
445
|
+
_tag: 'Request',
|
|
446
|
+
id,
|
|
447
|
+
tag: method,
|
|
448
|
+
payload,
|
|
449
|
+
headers: [],
|
|
450
|
+
}));
|
|
451
|
+
return id;
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
this.streams.delete(id);
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
interruptStream(requestId) {
|
|
459
|
+
this.streams.delete(requestId);
|
|
460
|
+
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
461
|
+
try {
|
|
462
|
+
this.ws.send(JSON.stringify({ _tag: 'Interrupt', requestId }));
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
// ignore
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
async bootstrapStreams() {
|
|
470
|
+
// 1. Subscribe to native server config stream for live providers + cwd updates.
|
|
471
|
+
this.startStream('subscribeServerConfig', { usageLimitSources: true, usageLimitsCommand: true }, (item) => {
|
|
472
|
+
void this.handleConfigEvent(item);
|
|
473
|
+
});
|
|
474
|
+
// 2. Subscribe to native terminal metadata stream so `terminal.list` is always instant.
|
|
475
|
+
this.startStream('subscribeTerminalMetadata', {}, (item) => {
|
|
476
|
+
this.handleTerminalMetadataEvent(item);
|
|
477
|
+
});
|
|
478
|
+
// 3. Proactively refresh providers & Antigravity quota right away.
|
|
479
|
+
void this.refreshProviders(false).catch(() => undefined);
|
|
480
|
+
// 4. Re-subscribe any remembered thread streams.
|
|
481
|
+
for (const [threadId, afterSeq] of this.wantedThreads.entries()) {
|
|
482
|
+
this.ensureThreadSubscribed(threadId, afterSeq);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
handleTerminalMetadataEvent(rawItem) {
|
|
486
|
+
if (!rawItem || typeof rawItem !== 'object')
|
|
487
|
+
return;
|
|
488
|
+
const evt = rawItem;
|
|
489
|
+
if (evt.type === 'snapshot' && Array.isArray(evt.terminals)) {
|
|
490
|
+
this.terminalMetadata.clear();
|
|
491
|
+
for (const term of evt.terminals) {
|
|
492
|
+
const tid = typeof term.threadId === 'string' ? term.threadId : '';
|
|
493
|
+
const termId = typeof term.terminalId === 'string' ? term.terminalId : '';
|
|
494
|
+
if (tid && termId) {
|
|
495
|
+
this.terminalMetadata.set(`${tid}\x00${termId}`, term);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
else if (evt.type === 'upsert' && evt.terminal && typeof evt.terminal === 'object') {
|
|
500
|
+
const tid = typeof evt.terminal.threadId === 'string' ? evt.terminal.threadId : '';
|
|
501
|
+
const termId = typeof evt.terminal.terminalId === 'string' ? evt.terminal.terminalId : '';
|
|
502
|
+
if (tid && termId) {
|
|
503
|
+
this.terminalMetadata.set(`${tid}\x00${termId}`, evt.terminal);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
else if (evt.type === 'remove' && evt.threadId && evt.terminalId) {
|
|
507
|
+
this.terminalMetadata.delete(`${evt.threadId}\x00${evt.terminalId}`);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
async handleConfigEvent(rawItem) {
|
|
511
|
+
if (!rawItem || typeof rawItem !== 'object')
|
|
512
|
+
return;
|
|
513
|
+
const evt = rawItem;
|
|
514
|
+
if (evt.type === 'snapshot' && evt.config) {
|
|
515
|
+
if (evt.config.cwd)
|
|
516
|
+
this.defaultCwd = evt.config.cwd;
|
|
517
|
+
if (Array.isArray(evt.config.providers)) {
|
|
518
|
+
const enriched = await enrichProvidersWithQuotas(evt.config.providers, false);
|
|
519
|
+
this.lastProviders = enriched;
|
|
520
|
+
this.callbacks.onProviders(enriched);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
else if ((evt.type === 'providerStatuses' || evt.type === 'providerStatusDeltas') &&
|
|
524
|
+
Array.isArray(evt.payload?.providers)) {
|
|
525
|
+
const enriched = await enrichProvidersWithQuotas(evt.payload.providers, false);
|
|
526
|
+
this.lastProviders = enriched;
|
|
527
|
+
this.callbacks.onProviders(enriched);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
ensureThreadSubscribed(threadId, afterSequence = 0) {
|
|
531
|
+
if (!threadId)
|
|
532
|
+
return;
|
|
533
|
+
const prev = this.wantedThreads.get(threadId) ?? 0;
|
|
534
|
+
if (afterSequence > prev || !this.wantedThreads.has(threadId)) {
|
|
535
|
+
this.wantedThreads.set(threadId, Math.max(prev, afterSequence));
|
|
536
|
+
}
|
|
537
|
+
if (this.subscribedThreads.has(threadId) || !this.isConnected())
|
|
538
|
+
return;
|
|
539
|
+
this.subscribedThreads.add(threadId);
|
|
540
|
+
const payload = { threadId };
|
|
541
|
+
if (afterSequence > 0)
|
|
542
|
+
payload.afterSequence = afterSequence;
|
|
543
|
+
const reqId = this.startStream('orchestration.subscribeThread', payload, (rawItem) => {
|
|
544
|
+
if (!rawItem || typeof rawItem !== 'object')
|
|
545
|
+
return;
|
|
546
|
+
const env = rawItem;
|
|
547
|
+
if (env.kind !== 'event' || typeof env.sequence !== 'number' || !env.event)
|
|
548
|
+
return;
|
|
549
|
+
const cur = this.wantedThreads.get(threadId) ?? 0;
|
|
550
|
+
if (env.sequence > cur)
|
|
551
|
+
this.wantedThreads.set(threadId, env.sequence);
|
|
552
|
+
this.callbacks.onThreadEvent({ sequence: env.sequence, event: env.event });
|
|
553
|
+
});
|
|
554
|
+
if (!reqId) {
|
|
555
|
+
this.subscribedThreads.delete(threadId);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
async refreshProviders(forceQuota = true) {
|
|
559
|
+
const raw = (await this.callRpc('server.refreshProviders', { fresh: true, usageLimitsCommand: true }, 30_000));
|
|
560
|
+
const list = Array.isArray(raw)
|
|
561
|
+
? raw
|
|
562
|
+
: Array.isArray(raw?.providers)
|
|
563
|
+
? raw.providers
|
|
564
|
+
: this.lastProviders;
|
|
565
|
+
const enriched = await enrichProvidersWithQuotas(list, forceQuota);
|
|
566
|
+
this.lastProviders = enriched;
|
|
567
|
+
this.callbacks.onProviders(enriched);
|
|
568
|
+
return { providers: enriched };
|
|
569
|
+
}
|
|
570
|
+
async ensureProject(workspaceRoot) {
|
|
571
|
+
let targetRoot = (workspaceRoot ?? '').trim();
|
|
572
|
+
if (!targetRoot) {
|
|
573
|
+
if (!this.defaultCwd) {
|
|
574
|
+
try {
|
|
575
|
+
const cfg = (await this.callRpc('server.getConfig', {}, 10_000));
|
|
576
|
+
if (cfg?.cwd)
|
|
577
|
+
this.defaultCwd = cfg.cwd;
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
// ignore
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
targetRoot = this.defaultCwd || homedir();
|
|
584
|
+
}
|
|
585
|
+
const token = await this.ensureLocalToken(false);
|
|
586
|
+
// 1. Check existing projects via native GET /api/projects
|
|
587
|
+
const listResp = await fetch(`${this.baseUrl}/api/projects`, {
|
|
588
|
+
method: 'GET',
|
|
589
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
590
|
+
signal: AbortSignal.timeout(10_000),
|
|
591
|
+
});
|
|
592
|
+
if (listResp.ok) {
|
|
593
|
+
const snapshot = (await listResp.json().catch(() => ({})));
|
|
594
|
+
const cleanedTarget = targetRoot.replace(/\/+$/, '');
|
|
595
|
+
for (const p of snapshot.projects ?? []) {
|
|
596
|
+
if (p.id && p.workspaceRoot && p.workspaceRoot.replace(/\/+$/, '') === cleanedTarget) {
|
|
597
|
+
return { projectId: p.id, workspaceRoot: p.workspaceRoot };
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
// 2. Create project via native POST /api/projects/mutate
|
|
602
|
+
const projectId = crypto.randomUUID();
|
|
603
|
+
const title = basename(targetRoot.replace(/\/+$/, '')) || 'workspace';
|
|
604
|
+
const mutResp = await fetch(`${this.baseUrl}/api/projects/mutate`, {
|
|
605
|
+
method: 'POST',
|
|
606
|
+
headers: {
|
|
607
|
+
Authorization: `Bearer ${token}`,
|
|
608
|
+
'Content-Type': 'application/json',
|
|
609
|
+
},
|
|
610
|
+
body: JSON.stringify({
|
|
611
|
+
type: 'project.create',
|
|
612
|
+
commandId: crypto.randomUUID(),
|
|
613
|
+
projectId,
|
|
614
|
+
title,
|
|
615
|
+
workspaceRoot: targetRoot,
|
|
616
|
+
createWorkspaceRootIfMissing: true,
|
|
617
|
+
}),
|
|
618
|
+
signal: AbortSignal.timeout(15_000),
|
|
619
|
+
});
|
|
620
|
+
const rawText = await mutResp.text();
|
|
621
|
+
if (!mutResp.ok) {
|
|
622
|
+
throw {
|
|
623
|
+
tag: 'ProjectMutationError',
|
|
624
|
+
message: rawText.trim() || `HTTP ${mutResp.status}`,
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
try {
|
|
628
|
+
const created = JSON.parse(rawText);
|
|
629
|
+
return {
|
|
630
|
+
projectId: created.id || projectId,
|
|
631
|
+
workspaceRoot: created.workspaceRoot || targetRoot,
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
return { projectId, workspaceRoot: targetRoot };
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
async dispatchCommand(rawCommand) {
|
|
639
|
+
const command = normalizeDispatchCommand(rawCommand);
|
|
640
|
+
const threadId = typeof command.threadId === 'string' ? command.threadId : '';
|
|
641
|
+
const cmdType = typeof command.type === 'string' ? command.type : '';
|
|
642
|
+
// Persist inline web image attachments (carrying dataUrl) via local T3's assets RPC
|
|
643
|
+
// so multimodal CLIs (Claude / Gemini / Codex) receive real local image attachments.
|
|
644
|
+
if (cmdType === 'message.dispatch' && Array.isArray(command.attachments) && command.attachments.length > 0) {
|
|
645
|
+
const rawAtts = command.attachments;
|
|
646
|
+
const uploadImages = rawAtts.filter((att) => att &&
|
|
647
|
+
typeof att === 'object' &&
|
|
648
|
+
att.type === 'image' &&
|
|
649
|
+
typeof att.dataUrl === 'string' &&
|
|
650
|
+
att.dataUrl.startsWith('data:image/'));
|
|
651
|
+
const alreadyPersisted = rawAtts.filter((att) => att && typeof att === 'object' && typeof att.id === 'string' && typeof att.dataUrl !== 'string');
|
|
652
|
+
if (uploadImages.length > 0 && threadId) {
|
|
653
|
+
const messageId = (typeof command.messageId === 'string' && command.messageId) ||
|
|
654
|
+
(typeof command.commandId === 'string' && command.commandId) ||
|
|
655
|
+
`msg-${Date.now()}`;
|
|
656
|
+
try {
|
|
657
|
+
const persisted = (await this.callRpc('assets.persistChatAttachments', {
|
|
658
|
+
threadId,
|
|
659
|
+
messageId,
|
|
660
|
+
attachments: uploadImages.map((img) => ({
|
|
661
|
+
type: 'image',
|
|
662
|
+
name: typeof img.name === 'string' ? img.name : 'image.png',
|
|
663
|
+
mimeType: typeof img.mimeType === 'string' ? img.mimeType : 'image/png',
|
|
664
|
+
sizeBytes: typeof img.sizeBytes === 'number' ? img.sizeBytes : 0,
|
|
665
|
+
dataUrl: img.dataUrl,
|
|
666
|
+
})),
|
|
667
|
+
}, 20_000));
|
|
668
|
+
command.attachments = [
|
|
669
|
+
...alreadyPersisted,
|
|
670
|
+
...(Array.isArray(persisted?.attachments) ? persisted.attachments : []),
|
|
671
|
+
];
|
|
672
|
+
}
|
|
673
|
+
catch (err) {
|
|
674
|
+
// Graceful fallback: keep already-persisted attachments only so text with file URLs still sends.
|
|
675
|
+
console.warn(`[local-t3] persistChatAttachments failed, falling back to text links: ${err instanceof Error ? err.message : String(err)}`);
|
|
676
|
+
command.attachments = alreadyPersisted;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (threadId && cmdType !== 'thread.create') {
|
|
681
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
682
|
+
}
|
|
683
|
+
const result = await this.callRpc('orchestration.dispatchCommand', command, 55_000);
|
|
684
|
+
if (threadId) {
|
|
685
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
686
|
+
}
|
|
687
|
+
return result;
|
|
688
|
+
}
|
|
689
|
+
async fetchSnapshot(threadId) {
|
|
690
|
+
if (!threadId) {
|
|
691
|
+
throw { tag: 'InvalidSnapshotRequest', message: 'threadId is required' };
|
|
692
|
+
}
|
|
693
|
+
this.ensureThreadSubscribed(threadId, 0);
|
|
694
|
+
const token = await this.ensureLocalToken(false);
|
|
695
|
+
const resp = await fetch(`${this.baseUrl}/api/orchestration/threads/${encodeURIComponent(threadId)}/bounded`, {
|
|
696
|
+
method: 'GET',
|
|
697
|
+
headers: {
|
|
698
|
+
Authorization: `Bearer ${token}`,
|
|
699
|
+
'X-T3-Orchestration-Protocol': '2',
|
|
700
|
+
},
|
|
701
|
+
signal: AbortSignal.timeout(15_000),
|
|
702
|
+
});
|
|
703
|
+
const text = await resp.text();
|
|
704
|
+
if (!resp.ok) {
|
|
705
|
+
throw {
|
|
706
|
+
tag: 'SnapshotError',
|
|
707
|
+
message: text.trim() || `HTTP ${resp.status}`,
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
return JSON.parse(text);
|
|
711
|
+
}
|
|
712
|
+
async resolveDefaultCwd(override) {
|
|
713
|
+
const trimmed = (override ?? '').trim();
|
|
714
|
+
if (trimmed)
|
|
715
|
+
return trimmed;
|
|
716
|
+
if (!this.defaultCwd) {
|
|
717
|
+
try {
|
|
718
|
+
const cfg = (await this.callRpc('server.getConfig', {}, 10_000));
|
|
719
|
+
if (cfg?.cwd)
|
|
720
|
+
this.defaultCwd = cfg.cwd;
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
// ignore
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
return this.defaultCwd || homedir();
|
|
727
|
+
}
|
|
728
|
+
listTerminals(threadId) {
|
|
729
|
+
const prefix = `${threadId}\x00`;
|
|
730
|
+
const list = [];
|
|
731
|
+
for (const [key, term] of this.terminalMetadata.entries()) {
|
|
732
|
+
if (!key.startsWith(prefix))
|
|
733
|
+
continue;
|
|
734
|
+
const status = typeof term.status === 'string' ? term.status : '';
|
|
735
|
+
if (status === 'exited' || status === 'error')
|
|
736
|
+
continue;
|
|
737
|
+
list.push(term);
|
|
738
|
+
}
|
|
739
|
+
list.sort((a, b) => String(a.terminalId ?? '').localeCompare(String(b.terminalId ?? '')));
|
|
740
|
+
return { terminals: list };
|
|
741
|
+
}
|
|
742
|
+
async openTerminal(params) {
|
|
743
|
+
const threadId = (params.threadId ?? '').trim();
|
|
744
|
+
if (!threadId) {
|
|
745
|
+
throw { tag: 'InvalidTerminalRequest', message: 'threadId is required' };
|
|
746
|
+
}
|
|
747
|
+
const terminalId = (params.terminalId ?? '').trim() ||
|
|
748
|
+
`term-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
749
|
+
const cwd = await this.resolveDefaultCwd(params.cwd);
|
|
750
|
+
const payload = { threadId, terminalId, cwd };
|
|
751
|
+
if (typeof params.cols === 'number' && Number.isFinite(params.cols)) {
|
|
752
|
+
payload.cols = Math.min(1000, Math.max(1, Math.floor(params.cols)));
|
|
753
|
+
}
|
|
754
|
+
if (typeof params.rows === 'number' && Number.isFinite(params.rows)) {
|
|
755
|
+
payload.rows = Math.min(500, Math.max(1, Math.floor(params.rows)));
|
|
756
|
+
}
|
|
757
|
+
const snapshot = (await this.callRpc('terminal.open', payload, 20_000));
|
|
758
|
+
if (snapshot && typeof snapshot === 'object') {
|
|
759
|
+
this.terminalMetadata.set(`${threadId}\x00${terminalId}`, {
|
|
760
|
+
threadId,
|
|
761
|
+
terminalId,
|
|
762
|
+
cwd: snapshot.cwd ?? cwd,
|
|
763
|
+
worktreePath: snapshot.worktreePath ?? null,
|
|
764
|
+
status: snapshot.status ?? 'running',
|
|
765
|
+
pid: snapshot.pid ?? null,
|
|
766
|
+
exitCode: snapshot.exitCode ?? null,
|
|
767
|
+
exitSignal: snapshot.exitSignal ?? null,
|
|
768
|
+
hasRunningSubprocess: false,
|
|
769
|
+
label: snapshot.label ?? 'shell',
|
|
770
|
+
updatedAt: snapshot.updatedAt ?? new Date().toISOString(),
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
return snapshot;
|
|
774
|
+
}
|
|
775
|
+
attachTerminal(params) {
|
|
776
|
+
const threadId = (params.threadId ?? '').trim();
|
|
777
|
+
const terminalId = (params.terminalId ?? '').trim();
|
|
778
|
+
if (!threadId || !terminalId) {
|
|
779
|
+
throw { tag: 'InvalidTerminalRequest', message: 'threadId and terminalId are required' };
|
|
780
|
+
}
|
|
781
|
+
if (!this.isConnected()) {
|
|
782
|
+
throw { tag: 'LocalT3Offline', message: '本机原版 T3 尚未连接' };
|
|
783
|
+
}
|
|
784
|
+
const key = `${threadId}\x00${terminalId}`;
|
|
785
|
+
const existingReqId = this.terminalStreams.get(key);
|
|
786
|
+
if (existingReqId) {
|
|
787
|
+
this.interruptStream(existingReqId);
|
|
788
|
+
this.terminalStreams.delete(key);
|
|
789
|
+
}
|
|
790
|
+
const payload = {
|
|
791
|
+
threadId,
|
|
792
|
+
terminalId,
|
|
793
|
+
resume: true,
|
|
794
|
+
maxHistoryBytes: 262_144,
|
|
795
|
+
};
|
|
796
|
+
if (params.cwd?.trim())
|
|
797
|
+
payload.cwd = params.cwd.trim();
|
|
798
|
+
if (typeof params.cols === 'number' && Number.isFinite(params.cols)) {
|
|
799
|
+
payload.cols = Math.min(1000, Math.max(1, Math.floor(params.cols)));
|
|
800
|
+
}
|
|
801
|
+
if (typeof params.rows === 'number' && Number.isFinite(params.rows)) {
|
|
802
|
+
payload.rows = Math.min(500, Math.max(1, Math.floor(params.rows)));
|
|
803
|
+
}
|
|
804
|
+
const reqId = this.startStream('terminal.attach', payload, (rawItem) => {
|
|
805
|
+
if (!rawItem || typeof rawItem !== 'object')
|
|
806
|
+
return;
|
|
807
|
+
const evt = rawItem;
|
|
808
|
+
if (evt.type === 'closed' || evt.type === 'exited') {
|
|
809
|
+
if (evt.type === 'closed') {
|
|
810
|
+
this.terminalMetadata.delete(key);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
this.callbacks.onTerminalEvent?.({ threadId, terminalId, event: rawItem });
|
|
814
|
+
});
|
|
815
|
+
if (!reqId) {
|
|
816
|
+
throw { tag: 'LocalT3SendError', message: '无法订阅本地终端流' };
|
|
817
|
+
}
|
|
818
|
+
this.terminalStreams.set(key, reqId);
|
|
819
|
+
return { ok: true, threadId, terminalId };
|
|
820
|
+
}
|
|
821
|
+
detachTerminal(params) {
|
|
822
|
+
const threadId = (params.threadId ?? '').trim();
|
|
823
|
+
const terminalId = (params.terminalId ?? '').trim();
|
|
824
|
+
const key = `${threadId}\x00${terminalId}`;
|
|
825
|
+
const reqId = this.terminalStreams.get(key);
|
|
826
|
+
if (reqId) {
|
|
827
|
+
this.interruptStream(reqId);
|
|
828
|
+
this.terminalStreams.delete(key);
|
|
829
|
+
}
|
|
830
|
+
return { ok: true };
|
|
831
|
+
}
|
|
832
|
+
detachAllTerminals() {
|
|
833
|
+
for (const [, reqId] of this.terminalStreams.entries()) {
|
|
834
|
+
this.interruptStream(reqId);
|
|
835
|
+
}
|
|
836
|
+
this.terminalStreams.clear();
|
|
837
|
+
}
|
|
838
|
+
async writeTerminal(params) {
|
|
839
|
+
const threadId = (params.threadId ?? '').trim();
|
|
840
|
+
const terminalId = (params.terminalId ?? '').trim();
|
|
841
|
+
const data = typeof params.data === 'string' ? params.data : '';
|
|
842
|
+
if (!threadId || !terminalId) {
|
|
843
|
+
throw { tag: 'InvalidTerminalRequest', message: 'threadId and terminalId are required' };
|
|
844
|
+
}
|
|
845
|
+
if (!data)
|
|
846
|
+
return { ok: true };
|
|
847
|
+
const MAX_CHUNK = 65_536;
|
|
848
|
+
let start = 0;
|
|
849
|
+
while (start < data.length) {
|
|
850
|
+
let end = Math.min(start + MAX_CHUNK, data.length);
|
|
851
|
+
const last = data.charCodeAt(end - 1);
|
|
852
|
+
if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
|
|
853
|
+
end -= 1;
|
|
854
|
+
}
|
|
855
|
+
const chunk = data.slice(start, end);
|
|
856
|
+
if (chunk) {
|
|
857
|
+
await this.callRpc('terminal.write', { threadId, terminalId, data: chunk }, 15_000);
|
|
858
|
+
}
|
|
859
|
+
start = end;
|
|
860
|
+
}
|
|
861
|
+
return { ok: true };
|
|
862
|
+
}
|
|
863
|
+
async resizeTerminal(params) {
|
|
864
|
+
const threadId = (params.threadId ?? '').trim();
|
|
865
|
+
const terminalId = (params.terminalId ?? '').trim();
|
|
866
|
+
if (!threadId || !terminalId) {
|
|
867
|
+
throw { tag: 'InvalidTerminalRequest', message: 'threadId and terminalId are required' };
|
|
868
|
+
}
|
|
869
|
+
const cols = Math.min(1000, Math.max(1, Math.floor(Number(params.cols) || 80)));
|
|
870
|
+
const rows = Math.min(500, Math.max(1, Math.floor(Number(params.rows) || 24)));
|
|
871
|
+
await this.callRpc('terminal.resize', { threadId, terminalId, cols, rows }, 10_000);
|
|
872
|
+
return { ok: true };
|
|
873
|
+
}
|
|
874
|
+
async closeTerminal(params) {
|
|
875
|
+
const threadId = (params.threadId ?? '').trim();
|
|
876
|
+
const terminalId = (params.terminalId ?? '').trim();
|
|
877
|
+
if (!threadId) {
|
|
878
|
+
throw { tag: 'InvalidTerminalRequest', message: 'threadId is required' };
|
|
879
|
+
}
|
|
880
|
+
if (terminalId) {
|
|
881
|
+
const key = `${threadId}\x00${terminalId}`;
|
|
882
|
+
const reqId = this.terminalStreams.get(key);
|
|
883
|
+
if (reqId) {
|
|
884
|
+
this.interruptStream(reqId);
|
|
885
|
+
this.terminalStreams.delete(key);
|
|
886
|
+
}
|
|
887
|
+
this.terminalMetadata.delete(key);
|
|
888
|
+
}
|
|
889
|
+
else {
|
|
890
|
+
const prefix = `${threadId}\x00`;
|
|
891
|
+
for (const [key, reqId] of [...this.terminalStreams.entries()]) {
|
|
892
|
+
if (key.startsWith(prefix)) {
|
|
893
|
+
this.interruptStream(reqId);
|
|
894
|
+
this.terminalStreams.delete(key);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
for (const key of [...this.terminalMetadata.keys()]) {
|
|
898
|
+
if (key.startsWith(prefix))
|
|
899
|
+
this.terminalMetadata.delete(key);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
await this.callRpc('terminal.close', { threadId, ...(terminalId ? { terminalId } : {}) }, 15_000);
|
|
903
|
+
return { ok: true };
|
|
904
|
+
}
|
|
905
|
+
}
|