@aivin-labs/cli 1.0.68 → 1.0.75
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/bin/lib/remote/agentEvidence.mjs +2 -1
- package/bin/lib/remote/agentPreview.mjs +151 -0
- package/bin/lib/remote/client.mjs +12 -5
- package/bin/lib/remote/codingAgents.mjs +953 -799
- package/bin/lib/remote/desktop/desktopCast.mjs +3 -1
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +23 -4
- package/bin/lib/remote/desktop/desktopCastSource.mjs +2 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +2 -3
- package/bin/lib/remote/localLlm.mjs +626 -576
- package/bin/lib/remote/localLlmLogin.mjs +219 -0
- package/bin/lib/remote/localLlmMembers.mjs +96 -0
- package/bin/lib/remote/mascot/ask.mjs +30 -9
- package/bin/lib/remote/mascot/askHostSource.mjs +22 -8
- package/bin/lib/remote/mascot/emojiSource.mjs +60 -3
- package/bin/lib/remote/mascot/hostSource.mjs +9 -3
- package/bin/lib/remote/mascot/index.mjs +4 -2
- package/bin/lib/remote/mascot/localOpen.mjs +79 -0
- package/bin/lib/remote/mascot/strings.mjs +8 -5
- package/bin/lib/remote/toolHandlers.mjs +26 -2
- package/package.json +1 -1
|
@@ -1,576 +1,626 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import { execFile, spawn } from 'child_process';
|
|
5
|
-
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
|
|
6
|
-
import { DeviceToolError, agentEnv } from './sandbox.mjs';
|
|
7
|
-
import { CLAUDE_ADAPTER, findAgentBinary } from './codingAgents.mjs';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* -
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
*
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
export const
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
if (
|
|
151
|
-
if (
|
|
152
|
-
st.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
export const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
proc.
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
proc.
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
}
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { execFile, spawn } from 'child_process';
|
|
5
|
+
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
|
|
6
|
+
import { DeviceToolError, agentEnv } from './sandbox.mjs';
|
|
7
|
+
import { CLAUDE_ADAPTER, findAgentBinary } from './codingAgents.mjs';
|
|
8
|
+
import { MEMBER_LLM_AGENTS, MEMBER_LLM_DIR, createSignInChecker, memberSpawnArgs } from './localLlmMembers.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Mô hình trên máy cho BE (16/11/2026, bản thử) — BE gọi `llm.complete` như gọi một LLM: chỉ dẫn + lịch sử → chữ trả lời. Chạy bằng agent
|
|
12
|
+
* lập trình người dùng đã đăng nhập sẵn trên máy (gói của chính họ): Claude Code, Codex, Antigravity (`agy`). Không phải agent: không công
|
|
13
|
+
* cụ, không cài đặt / hook / MCP / tệp ngữ cảnh của dự án (thư mục rỗng riêng), không lưu phiên khi agent cho phép.
|
|
14
|
+
*
|
|
15
|
+
* Mỗi agent một ADAPTER, đã kiểm thật trên máy (16/11/2026):
|
|
16
|
+
* - Claude Code 2.1.325: `-p --input-format stream-json` + `--tools ""` (không có công cụ nào), stream từng token.
|
|
17
|
+
* - Codex 0.169: `exec --json --ephemeral --sandbox read-only` + tắt các tính năng công cụ (`--disable code_mode_host`… → công cụ báo lỗi,
|
|
18
|
+
* không đọc được tệp); chỉ trả cả câu một lần ở cuối.
|
|
19
|
+
* - Antigravity `agy` 1.5.9: ACP (`agy acp`). Chế độ print tự chạy lệnh shell / ghi tệp kể cả với `--mode plan` / `--sandbox` / luật
|
|
20
|
+
* `permissions.deny` — ACP thì lệnh phải xin quyền (máy luôn từ chối), nhưng đọc tệp / tìm web không cần xin.
|
|
21
|
+
* Lưới an toàn chung: agent gọi BẤT KỲ công cụ nào → dừng ngay, bỏ câu trả lời, báo `LOCAL_LLM_TOOL_USE` (BE chuyển sang cloud) — chữ có thể
|
|
22
|
+
* mang nội dung tệp trên máy không bao giờ lên BE.
|
|
23
|
+
*
|
|
24
|
+
* Nhanh: giữ sẵn một tiến trình đã khởi động (ACP: đã mở phiên + chọn model) cho mỗi (agent, model, effort); một tiến trình phục vụ ĐÚNG
|
|
25
|
+
* MỘT lời gọi rồi đóng (không dính ngữ cảnh lời gọi trước), một tiến trình mới được giữ sẵn thay chỗ.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
export const LLM_DIR = path.join(REMOTE_CONFIG_DIR, 'llm');
|
|
29
|
+
const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
|
|
30
|
+
export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
31
|
+
const MAX_INPUT_CHARS = 400_000;
|
|
32
|
+
const MAX_OUTPUT_CHARS = 200_000;
|
|
33
|
+
const DEFAULT_TIMEOUT_MS = 180_000;
|
|
34
|
+
const WARM_IDLE_MS = 10 * 60_000;
|
|
35
|
+
const MAX_WARM_KEYS = 4;
|
|
36
|
+
/** Tiến trình giữ sẵn cho MỖI (agent, model, effort): lượt chat gọi song song vài lời gọi cùng loại — một tiến trình thì lời gọi thứ hai khởi động
|
|
37
|
+
* nguội (~1 s). Tổng có trần (`MAX_WARM_PROCS`, mỗi tiến trình Claude Code ~200 MB). Đổi bằng `AIVIN_LLM_WARM_PER_KEY`. */
|
|
38
|
+
const WARM_PER_KEY = Math.min(4, Math.max(1, Number(process.env.AIVIN_LLM_WARM_PER_KEY) || 2));
|
|
39
|
+
const MAX_WARM_PROCS = 6;
|
|
40
|
+
/** Antigravity (ACP): tiến trình phục vụ xong một lời gọi thì mở phiên mới trên CHÍNH nó và quay lại pool — lời gọi sau khỏi khởi động agy
|
|
41
|
+
* (initialize + session/new + set_model, 2–4 s). Mỗi tiến trình vẫn một lời gọi một lúc; đủ số lượt này thì thay tiến trình mới (agy giữ
|
|
42
|
+
* các phiên đã mở trong bộ nhớ). */
|
|
43
|
+
const ACP_MAX_USES = 40;
|
|
44
|
+
/** Mã lỗi riêng: agent định dùng công cụ — câu trả lời bị bỏ. */
|
|
45
|
+
export const TOOL_USE_ERROR = 'LOCAL_LLM_TOOL_USE';
|
|
46
|
+
export const QUOTA_ERROR = 'LOCAL_LLM_QUOTA';
|
|
47
|
+
/** Agent chưa đăng nhập / phiên đăng nhập hết hạn (máy tính tổ chức: thành viên chưa đăng nhập agent của mình). BE chạy cloud. */
|
|
48
|
+
export const NOT_SIGNED_IN_ERROR = 'LOCAL_LLM_NOT_SIGNED_IN';
|
|
49
|
+
const AUTH_ERROR_RE = /please run \/login|not (?:logged|signed) in|invalid api key|oauth token (?:has )?expired|token (?:has )?(?:expired|been revoked)|authentication_error|401 unauthorized|refresh token/i;
|
|
50
|
+
|
|
51
|
+
/** Mã lỗi theo câu báo của agent: chưa đăng nhập / hết hạn mức / lỗi thường (undefined). */
|
|
52
|
+
export function agentErrorCode(message) {
|
|
53
|
+
const text = String(message || '');
|
|
54
|
+
if (AUTH_ERROR_RE.test(text)) return NOT_SIGNED_IN_ERROR;
|
|
55
|
+
if (/limit|quota/i.test(text)) return QUOTA_ERROR;
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
const BASE_SYSTEM = 'You are a language model answering requests from the Aivin server through an API. You have no tools and must not call any. Follow the instructions inside each request exactly; when it asks for JSON, reply with that JSON only, no prose and no code fence.';
|
|
59
|
+
|
|
60
|
+
const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
|
|
61
|
+
const failed = (msg, code = DeviceErrorCode.EXECUTION_FAILED) => new DeviceToolError(code, msg);
|
|
62
|
+
const str = (description) => ({ type: 'string', description });
|
|
63
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Một lời gọi → nội dung tin nhắn gửi agent. Chỉ dẫn hệ thống của BE nằm trong tin nhắn (cờ hệ thống cố định lúc giữ sẵn), lịch sử thành bản
|
|
67
|
+
* ghi hội thoại, schema thành yêu cầu trả JSON. `withBase`: agent không nhận được chỉ dẫn hệ thống riêng (Codex, agy) → đặt lời dặn chung lên đầu.
|
|
68
|
+
*/
|
|
69
|
+
export function renderRequest({ system, messages = [], prompt, json_schema: jsonSchema }, { withBase = false } = {}) {
|
|
70
|
+
const parts = [];
|
|
71
|
+
if (withBase) parts.push(`<rules>\n${BASE_SYSTEM}\n</rules>`);
|
|
72
|
+
if (system) parts.push(`<instructions>\n${system}\n</instructions>`);
|
|
73
|
+
const turns = (Array.isArray(messages) ? messages : []).filter((m) => m && typeof m.content === 'string' && m.content.trim());
|
|
74
|
+
const last = prompt ? null : turns.at(-1)?.role === 'user' ? turns.pop() : null;
|
|
75
|
+
if (turns.length) {
|
|
76
|
+
parts.push(`<conversation>\n${turns.map((m) => `<${m.role === 'assistant' ? 'assistant' : 'user'}>\n${m.content}\n</${m.role === 'assistant' ? 'assistant' : 'user'}>`).join('\n')}\n</conversation>`);
|
|
77
|
+
}
|
|
78
|
+
const ask = prompt || last?.content;
|
|
79
|
+
if (!ask) throw invalid('prompt or a last user message is required');
|
|
80
|
+
parts.push(turns.length || withBase ? `<request>\n${ask}\n</request>` : ask);
|
|
81
|
+
if (jsonSchema) {
|
|
82
|
+
const text = typeof jsonSchema === 'string' ? jsonSchema : JSON.stringify(jsonSchema);
|
|
83
|
+
parts.push(`Reply with one JSON value that matches this JSON Schema, and nothing else:\n${text}`);
|
|
84
|
+
}
|
|
85
|
+
return parts.join('\n\n');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Lấy JSON từ câu trả lời (mô hình có khi vẫn bọc ```json). Không đọc được → null. */
|
|
89
|
+
export function extractJson(text) {
|
|
90
|
+
const t = String(text || '').trim();
|
|
91
|
+
const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(t);
|
|
92
|
+
const body = fenced ? fenced[1] : t;
|
|
93
|
+
try { return JSON.parse(body); } catch { /* thử cắt từ dấu mở đầu tiên */ }
|
|
94
|
+
const start = body.search(/[[{]/);
|
|
95
|
+
const end = Math.max(body.lastIndexOf('}'), body.lastIndexOf(']'));
|
|
96
|
+
if (start < 0 || end <= start) return null;
|
|
97
|
+
try { return JSON.parse(body.slice(start, end + 1)); } catch { return null; }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function onPath(exe, env = process.env) {
|
|
101
|
+
return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Bản mới nhất trong các thư mục kiểu `<root>/<prefix>-<version>-…/<rel>` (extension VS Code). */
|
|
105
|
+
function extensionBins(root, prefix, rel) {
|
|
106
|
+
try {
|
|
107
|
+
return fs.readdirSync(root).filter((d) => d.startsWith(prefix)).sort().reverse().map((d) => path.join(root, d, rel));
|
|
108
|
+
} catch { return []; }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function firstExisting(list) {
|
|
112
|
+
return [...new Set(list)].find((p) => { try { return fs.statSync(p).isFile(); } catch { return false; } }) || null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function versionOf(bin, args = ['--version']) {
|
|
116
|
+
return new Promise((resolve) => {
|
|
117
|
+
execFile(bin, args, { encoding: 'utf8', timeout: 15_000, windowsHide: true }, (err, out) => {
|
|
118
|
+
const m = /(\d+\.\d+\.\d+[\w.-]*)/.exec(String(out || ''));
|
|
119
|
+
resolve(err && !m ? null : m?.[1] || null);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ------------------------------------------------------------------------------------------------------------------------------------------
|
|
125
|
+
// Adapter. `kind`: 'stream' (dòng JSON vào stdin, giữ stdin mở), 'stdin' (ghi đề rồi đóng stdin), 'acp' (Agent Client Protocol, JSON-RPC).
|
|
126
|
+
// `parse(msg, st)` gọi st.delta(text) / st.final(text) / st.done() / st.fail(err) / st.tool(name) / st.meta({ model, usage }).
|
|
127
|
+
// ------------------------------------------------------------------------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
const exe = (name, platform = process.platform) => (platform === 'win32' ? `${name}.exe` : name);
|
|
130
|
+
|
|
131
|
+
export const CLAUDE_LLM = Object.freeze({
|
|
132
|
+
id: 'claude',
|
|
133
|
+
label: 'Claude Code',
|
|
134
|
+
kind: 'stream',
|
|
135
|
+
find: () => findAgentBinary(CLAUDE_ADAPTER),
|
|
136
|
+
args({ model, effort }) {
|
|
137
|
+
const argv = [
|
|
138
|
+
'-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',
|
|
139
|
+
'--tools', '', '--setting-sources', '', '--strict-mcp-config', '--disable-slash-commands', '--no-session-persistence',
|
|
140
|
+
'--system-prompt', BASE_SYSTEM,
|
|
141
|
+
];
|
|
142
|
+
if (model) argv.push('--model', model);
|
|
143
|
+
if (effort) argv.push('--effort', effort);
|
|
144
|
+
return argv;
|
|
145
|
+
},
|
|
146
|
+
encode: (content) => `${JSON.stringify({ type: 'user', message: { role: 'user', content } })}\n`,
|
|
147
|
+
parse(m, st) {
|
|
148
|
+
if (m.type === 'stream_event') {
|
|
149
|
+
const ev = m.event || {};
|
|
150
|
+
if (ev.type === 'message_start') st.meta({ model: ev.message?.model });
|
|
151
|
+
if (ev.type === 'content_block_start' && ev.content_block?.type === 'tool_use') return st.tool(ev.content_block.name);
|
|
152
|
+
if (ev.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && ev.delta.text) st.delta(ev.delta.text);
|
|
153
|
+
if (ev.type === 'message_delta') {
|
|
154
|
+
st.meta({ stop_reason: ev.delta?.stop_reason });
|
|
155
|
+
if (ev.usage) st.meta({ usage: { input_tokens: ev.usage.input_tokens, output_tokens: ev.usage.output_tokens } });
|
|
156
|
+
}
|
|
157
|
+
// Chốt khi mô hình dừng — dòng `result` đến sau một lượt tóm tắt (~0,8 s).
|
|
158
|
+
if (ev.type === 'message_stop') st.done();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (m.type === 'result') {
|
|
162
|
+
if (m.is_error) return st.fail(failed(String(m.result || m.subtype || 'Model error').slice(0, 500), agentErrorCode(m.result)));
|
|
163
|
+
if (typeof m.result === 'string') st.final(m.result);
|
|
164
|
+
st.done();
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
/** Tính năng công cụ của Codex tắt cho chế độ mô hình (chỉ tắt những cái bản đã cài có — cờ lạ làm Codex báo lỗi). */
|
|
170
|
+
const CODEX_TOOL_FEATURES = ['code_mode_host', 'shell_tool', 'unified_exec', 'apps', 'plugins', 'browser_use', 'browser_use_external', 'computer_use', 'in_app_browser', 'skill_search', 'tool_suggest', 'sleep_tool'];
|
|
171
|
+
/** Mục Codex không phải công cụ. */
|
|
172
|
+
const CODEX_TEXT_ITEMS = new Set(['agent_message', 'reasoning', 'error', 'todo_list']);
|
|
173
|
+
|
|
174
|
+
export const CODEX_LLM = Object.freeze({
|
|
175
|
+
id: 'codex',
|
|
176
|
+
label: 'Codex',
|
|
177
|
+
kind: 'stdin',
|
|
178
|
+
find({ env = process.env, home = os.homedir() } = {}) {
|
|
179
|
+
const bin = firstExisting([
|
|
180
|
+
...onPath(exe('codex'), env),
|
|
181
|
+
path.join(home, '.local', 'bin', exe('codex')),
|
|
182
|
+
...extensionBins(path.join(home, '.vscode', 'extensions'), 'openai.chatgpt-', path.join('bin', process.platform === 'win32' ? 'windows-x86_64' : `${process.platform}-${os.arch()}`, exe('codex'))),
|
|
183
|
+
]);
|
|
184
|
+
return bin ? { bin } : null;
|
|
185
|
+
},
|
|
186
|
+
async probe(bin) {
|
|
187
|
+
const out = await new Promise((resolve) => execFile(bin, ['features', 'list'], { encoding: 'utf8', timeout: 20_000, windowsHide: true }, (e, o) => resolve(e ? '' : String(o))));
|
|
188
|
+
const known = new Set(out.split('\n').map((l) => l.trim().split(/\s+/)[0]).filter(Boolean));
|
|
189
|
+
return { disable: CODEX_TOOL_FEATURES.filter((f) => known.has(f)) };
|
|
190
|
+
},
|
|
191
|
+
args({ model, effort, cwd, probe }) {
|
|
192
|
+
const argv = ['exec', '--json', '--ephemeral', '--skip-git-repo-check', '--ignore-rules', '--ignore-user-config', '-s', 'read-only', '-C', cwd, '-c', 'web_search="disabled"'];
|
|
193
|
+
for (const f of probe?.disable || []) argv.push('--disable', f);
|
|
194
|
+
if (model) argv.push('-m', model);
|
|
195
|
+
if (effort) argv.push('-c', `model_reasoning_effort="${effort}"`);
|
|
196
|
+
argv.push('-');
|
|
197
|
+
return argv;
|
|
198
|
+
},
|
|
199
|
+
encode: (content) => content,
|
|
200
|
+
parse(m, st) {
|
|
201
|
+
const item = m.item;
|
|
202
|
+
if ((m.type === 'item.started' || m.type === 'item.completed') && item && !CODEX_TEXT_ITEMS.has(item.type)) return st.tool(item.type);
|
|
203
|
+
// Codex chỉ trả cả câu; có khi nói vài câu "đang làm…" trước — câu CUỐI là câu trả lời.
|
|
204
|
+
if (m.type === 'item.completed' && item?.type === 'agent_message' && typeof item.text === 'string') st.final(item.text);
|
|
205
|
+
if (m.type === 'turn.completed') {
|
|
206
|
+
st.meta({ usage: { input_tokens: m.usage?.input_tokens, output_tokens: m.usage?.output_tokens } });
|
|
207
|
+
st.done();
|
|
208
|
+
}
|
|
209
|
+
if (m.type === 'turn.failed' || m.type === 'error') {
|
|
210
|
+
const msg = String(m.error?.message || m.message || 'Codex error');
|
|
211
|
+
st.fail(failed(msg.slice(0, 500), agentErrorCode(msg)));
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
/** `gemini-3.8-flash` + effort → id model của agy (`gemini-3.8-flash-low`); không có đúng effort → effort gần nhất. */
|
|
217
|
+
export function pickAgyModel(available, model, effort) {
|
|
218
|
+
const ids = (available || []).map((m) => (typeof m === 'string' ? m : m?.modelId)).filter(Boolean);
|
|
219
|
+
if (!ids.length) return null;
|
|
220
|
+
if (model && ids.includes(model)) return model;
|
|
221
|
+
const order = ['low', 'medium', 'high', 'xhigh'];
|
|
222
|
+
const family = model ? ids.filter((id) => id.startsWith(`${model}-`) && order.includes(id.slice(model.length + 1))) : [];
|
|
223
|
+
if (!family.length) return model ? null : ids[0];
|
|
224
|
+
const want = order.indexOf(effort === 'max' ? 'xhigh' : effort || 'medium');
|
|
225
|
+
return family.sort((a, b) => Math.abs(order.indexOf(a.slice(model.length + 1)) - want) - Math.abs(order.indexOf(b.slice(model.length + 1)) - want))[0];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export const ANTIGRAVITY_LLM = Object.freeze({
|
|
229
|
+
id: 'antigravity',
|
|
230
|
+
label: 'Antigravity',
|
|
231
|
+
kind: 'acp',
|
|
232
|
+
find({ env = process.env, home = os.homedir() } = {}) {
|
|
233
|
+
const local = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
|
|
234
|
+
const bin = firstExisting([...onPath(exe('agy'), env), path.join(local, 'agy', 'bin', exe('agy')), path.join(home, '.local', 'bin', exe('agy'))]);
|
|
235
|
+
return bin ? { bin } : null;
|
|
236
|
+
},
|
|
237
|
+
args: () => ['acp', '--disable-telemetry'],
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
export const DEFAULT_LLM_ADAPTERS = Object.freeze([CLAUDE_LLM, CODEX_LLM, ANTIGRAVITY_LLM]);
|
|
241
|
+
|
|
242
|
+
/** Câu báo hết hạn mức agy gửi như một đoạn trả lời bình thường. */
|
|
243
|
+
const AGY_QUOTA_RE = /^\s*⚠?\s*(individual )?quota reached/i;
|
|
244
|
+
|
|
245
|
+
// ------------------------------------------------------------------------------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
export function createLocalLlm({
|
|
248
|
+
adapters = DEFAULT_LLM_ADAPTERS, spawnImpl = spawn, dir = LLM_DIR, now = Date.now, idleMs = WARM_IDLE_MS, version = versionOf,
|
|
249
|
+
warmPerKey = WARM_PER_KEY, maxWarmProcs = MAX_WARM_PROCS,
|
|
250
|
+
// Máy tính tổ chức: lời gọi nào cũng phải mang tài khoản thành viên (`ctx.runAs`) — agent chạy dưới tài khoản đó, không bao giờ bằng root.
|
|
251
|
+
memberMode = false, memberDir = MEMBER_LLM_DIR, signIn: signInOverride,
|
|
252
|
+
} = {}) {
|
|
253
|
+
if (memberMode) adapters = adapters.filter((a) => MEMBER_LLM_AGENTS.includes(a.id));
|
|
254
|
+
const found = new Map();
|
|
255
|
+
const probes = new Map();
|
|
256
|
+
const versions = new Map();
|
|
257
|
+
const binOf = (a) => {
|
|
258
|
+
if (!found.has(a.id)) { try { found.set(a.id, a.find() || null); } catch { found.set(a.id, null); } }
|
|
259
|
+
return found.get(a.id);
|
|
260
|
+
};
|
|
261
|
+
const installed = () => adapters.filter((a) => binOf(a));
|
|
262
|
+
const adapterFor = (id) => {
|
|
263
|
+
const list = installed();
|
|
264
|
+
if (!list.length) throw failed('No coding agent that can serve as a model is installed on this computer', DeviceErrorCode.NOT_FOUND);
|
|
265
|
+
if (!id) return list[0];
|
|
266
|
+
const a = list.find((x) => x.id === id);
|
|
267
|
+
if (!a) throw failed(`${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`, DeviceErrorCode.NOT_FOUND);
|
|
268
|
+
return a;
|
|
269
|
+
};
|
|
270
|
+
const probeOf = (a) => {
|
|
271
|
+
if (!a.probe) return Promise.resolve(null);
|
|
272
|
+
if (!probes.has(a.id)) probes.set(a.id, Promise.resolve(a.probe(binOf(a).bin)).catch(() => null));
|
|
273
|
+
return probes.get(a.id);
|
|
274
|
+
};
|
|
275
|
+
for (const a of installed()) {
|
|
276
|
+
Promise.resolve(binOf(a).version || version(binOf(a).bin)).then((v) => versions.set(a.id, v || null)).catch(() => {});
|
|
277
|
+
}
|
|
278
|
+
const signIn = memberMode ? (signInOverride || createSignInChecker({ binOf, dir: memberDir })) : null;
|
|
279
|
+
/** Tài khoản thành viên của lời gọi; chế độ máy tổ chức mà thiếu → từ chối (không chạy agent bằng root). */
|
|
280
|
+
const accountOf = (ctx) => {
|
|
281
|
+
const account = ctx?.runAs || null;
|
|
282
|
+
if (memberMode && !account) throw invalid('This shared computer runs models only for a member — the call has no member');
|
|
283
|
+
return memberMode ? account : null;
|
|
284
|
+
};
|
|
285
|
+
/** Máy tổ chức: thành viên chưa đăng nhập agent → lỗi ngay, không khởi động agent. */
|
|
286
|
+
async function assertSignedIn(adapter, account) {
|
|
287
|
+
if (!account || !signIn) return;
|
|
288
|
+
if (!(await signIn.status(adapter, account))) {
|
|
289
|
+
throw failed(`${adapter.label} is not signed in for this member on this shared computer — sign in from Aivin first`, NOT_SIGNED_IN_ERROR);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** key → { procs: Promise<proc>[], lastUsed } — các tiến trình đã khởi động, chưa nhận lời gọi nào. */
|
|
294
|
+
const warm = new Map();
|
|
295
|
+
const warmCount = () => [...warm.values()].reduce((n, w) => n + w.procs.length, 0);
|
|
296
|
+
let sweeper = null;
|
|
297
|
+
|
|
298
|
+
// --- Một tiến trình. stream / stdin: chỉ là child. acp: child + phiên đã mở + model đã chọn (`ready`).
|
|
299
|
+
function startProc(adapter, { model, effort, account = null }) {
|
|
300
|
+
if (!account) fs.mkdirSync(dir, { recursive: true });
|
|
301
|
+
const bin = binOf(adapter).bin;
|
|
302
|
+
const proc = { adapter, model, effort, account, child: null, ready: null, rpc: null, exited: false };
|
|
303
|
+
const cwd = account ? memberDir : dir;
|
|
304
|
+
const launch = (argv) => {
|
|
305
|
+
// Thành viên máy tổ chức: chạy dưới tài khoản Linux của họ (HOME riêng → đăng nhập agent của chính họ), có trần số tiến trình.
|
|
306
|
+
const [cmd, args, opts] = account
|
|
307
|
+
? memberSpawnArgs(account, bin, argv, { dir: memberDir })
|
|
308
|
+
: [bin, argv, { cwd: dir, env: agentEnv(process.env), windowsHide: true }];
|
|
309
|
+
const child = spawnImpl(cmd, args, { ...opts, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
310
|
+
child.on('error', () => { proc.exited = true; });
|
|
311
|
+
child.once('exit', () => { proc.exited = true; });
|
|
312
|
+
child.stderr?.on('data', (d) => { proc.stderr = ((proc.stderr || '') + d).slice(-4000); });
|
|
313
|
+
return child;
|
|
314
|
+
};
|
|
315
|
+
if (adapter.kind === 'acp') {
|
|
316
|
+
proc.child = launch(adapter.args());
|
|
317
|
+
proc.rpc = acpClient(proc.child);
|
|
318
|
+
proc.initialized = proc.rpc.call('initialize', { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } });
|
|
319
|
+
proc.initialized.catch(() => {});
|
|
320
|
+
openAcpSession(proc);
|
|
321
|
+
return Promise.resolve(proc);
|
|
322
|
+
}
|
|
323
|
+
return probeOf(adapter).then((probe) => {
|
|
324
|
+
proc.child = launch(adapter.args({ model, effort, cwd, probe }));
|
|
325
|
+
return proc;
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Mở một phiên ACP mới (đã initialize một lần cho cả tiến trình) với đúng model / effort của tiến trình → `proc.ready`. */
|
|
330
|
+
function openAcpSession(proc) {
|
|
331
|
+
const { adapter, model, effort } = proc;
|
|
332
|
+
proc.sessionId = null;
|
|
333
|
+
proc.modelId = null;
|
|
334
|
+
proc.ready = (async () => {
|
|
335
|
+
await proc.initialized;
|
|
336
|
+
const sess = await proc.rpc.call('session/new', { cwd: proc.account ? memberDir : dir, mcpServers: [] });
|
|
337
|
+
const modelId = pickAgyModel(sess?.models?.availableModels, model, effort);
|
|
338
|
+
if (model && !modelId) throw failed(`${adapter.label} has no model "${model}" here`, DeviceErrorCode.NOT_FOUND);
|
|
339
|
+
if (modelId && modelId !== sess?.models?.currentModelId) await proc.rpc.call('session/set_model', { sessionId: sess.sessionId, modelId });
|
|
340
|
+
return { sessionId: sess.sessionId, modelId: modelId || sess?.models?.currentModelId };
|
|
341
|
+
})();
|
|
342
|
+
proc.ready.catch(() => {});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function closeProc(proc) {
|
|
346
|
+
if (!proc) return;
|
|
347
|
+
try { proc.child?.stdin?.end(); } catch { /* đã đóng */ }
|
|
348
|
+
try { proc.child?.kill(); } catch { /* đã thoát */ }
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Máy tổ chức: tiến trình giữ sẵn của thành viên nào chỉ phục vụ thành viên đó (đã đăng nhập bằng tài khoản của họ).
|
|
352
|
+
const keyOf = (adapter, opts) => `${opts.account?.name ? `${opts.account.name}|` : ''}${adapter.id}|${opts.model || ''}|${opts.effort || ''}`;
|
|
353
|
+
|
|
354
|
+
function entryFor(key) {
|
|
355
|
+
let entry = warm.get(key);
|
|
356
|
+
if (!entry) {
|
|
357
|
+
while (warm.size >= MAX_WARM_KEYS) {
|
|
358
|
+
const [oldest] = [...warm.entries()].sort((a, b) => a[1].lastUsed - b[1].lastUsed)[0];
|
|
359
|
+
closeWarm(oldest);
|
|
360
|
+
}
|
|
361
|
+
entry = { procs: [], lastUsed: now() };
|
|
362
|
+
warm.set(key, entry);
|
|
363
|
+
}
|
|
364
|
+
entry.lastUsed = now();
|
|
365
|
+
return entry;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** ACP xong một lời gọi thành công → phiên mới trên chính tiến trình đó, đưa lên đầu pool (nóng hơn tiến trình mới dựng). */
|
|
369
|
+
function recycleAcp(proc) {
|
|
370
|
+
proc.uses = (proc.uses || 0) + 1;
|
|
371
|
+
const entry = entryFor(keyOf(proc.adapter, proc));
|
|
372
|
+
if (proc.exited || proc.uses >= ACP_MAX_USES || entry.procs.length >= warmPerKey || warmCount() >= maxWarmProcs) return closeProc(proc);
|
|
373
|
+
proc.rpc.onNotify = null;
|
|
374
|
+
proc.rpc.onRequest = null;
|
|
375
|
+
openAcpSession(proc);
|
|
376
|
+
entry.procs.unshift(Promise.resolve(proc));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function keepWarm(adapter, opts) {
|
|
380
|
+
const key = keyOf(adapter, opts);
|
|
381
|
+
const entry = entryFor(key);
|
|
382
|
+
// Đủ số cho loại này, tổng còn chỗ thì mới dựng thêm; loại khác ít dùng nhất nhường chỗ khi tổng đầy.
|
|
383
|
+
while (entry.procs.length < warmPerKey) {
|
|
384
|
+
if (warmCount() >= maxWarmProcs) {
|
|
385
|
+
const victim = [...warm.entries()].filter(([k, w]) => k !== key && w.procs.length).sort((a, b) => a[1].lastUsed - b[1].lastUsed)[0];
|
|
386
|
+
if (!victim) break;
|
|
387
|
+
victim[1].procs.pop()?.then(closeProc, () => {});
|
|
388
|
+
}
|
|
389
|
+
const p = startProc(adapter, opts);
|
|
390
|
+
entry.procs.push(p);
|
|
391
|
+
p.catch(() => { const i = entry.procs.indexOf(p); if (i >= 0) entry.procs.splice(i, 1); });
|
|
392
|
+
}
|
|
393
|
+
if (!sweeper) {
|
|
394
|
+
sweeper = setInterval(() => { for (const [k, w] of warm) if (now() - w.lastUsed > idleMs) closeWarm(k); if (!warm.size) { clearInterval(sweeper); sweeper = null; } }, 60_000);
|
|
395
|
+
sweeper.unref?.();
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function closeWarm(key) {
|
|
400
|
+
const w = warm.get(key);
|
|
401
|
+
warm.delete(key);
|
|
402
|
+
for (const p of w?.procs || []) p.then(closeProc, () => {});
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function take(adapter, opts) {
|
|
406
|
+
const key = keyOf(adapter, opts);
|
|
407
|
+
const w = warm.get(key);
|
|
408
|
+
const pending = w?.procs.shift();
|
|
409
|
+
let proc = pending ? await pending.catch(() => null) : null;
|
|
410
|
+
const warmStart = !!proc && !proc.exited;
|
|
411
|
+
if (!warmStart) { closeProc(proc); proc = await startProc(adapter, opts); }
|
|
412
|
+
// ACP: tiến trình này quay lại pool khi xong (recycleAcp) — bù chỗ lúc đó, không dựng thêm ngay (đầy pool thì nó không quay lại được).
|
|
413
|
+
if (adapter.kind !== 'acp') setImmediate(() => keepWarm(adapter, opts));
|
|
414
|
+
return { proc, warmStart };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function validate(args) {
|
|
418
|
+
const adapter = adapterFor(args.agent ? String(args.agent) : '');
|
|
419
|
+
const model = args.model ? String(args.model) : '';
|
|
420
|
+
if (model && !MODEL_RE.test(model)) throw invalid('Bad model name');
|
|
421
|
+
const effort = args.effort ? String(args.effort) : '';
|
|
422
|
+
if (effort && !EFFORTS.includes(effort)) throw invalid(`effort must be one of: ${EFFORTS.join(', ')}`);
|
|
423
|
+
return { adapter, model, effort };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function complete(args = {}, ctx = {}) {
|
|
427
|
+
const { adapter, model, effort } = validate(args);
|
|
428
|
+
const account = accountOf(ctx);
|
|
429
|
+
await assertSignedIn(adapter, account);
|
|
430
|
+
const content = renderRequest(args, { withBase: adapter.kind !== 'stream' });
|
|
431
|
+
if (content.length > MAX_INPUT_CHARS) throw invalid(`Request is too long (${content.length} chars, max ${MAX_INPUT_CHARS})`);
|
|
432
|
+
const startedAt = now();
|
|
433
|
+
const timeoutMs = Math.min(Number(args.timeout_ms) || ctx.timeoutMs || DEFAULT_TIMEOUT_MS, 10 * 60_000);
|
|
434
|
+
if (ctx.signal?.aborted) throw failed('Cancelled', DeviceErrorCode.CANCELLED);
|
|
435
|
+
const { proc, warmStart } = await take(adapter, { model, effort, account });
|
|
436
|
+
|
|
437
|
+
return new Promise((resolve, reject) => {
|
|
438
|
+
let text = '';
|
|
439
|
+
let finalText = null;
|
|
440
|
+
let settled = false;
|
|
441
|
+
let ttft = null;
|
|
442
|
+
const meta = {};
|
|
443
|
+
let onChildError = null;
|
|
444
|
+
let onChildExit = null;
|
|
445
|
+
const finish = (err, value) => {
|
|
446
|
+
if (settled) return;
|
|
447
|
+
settled = true;
|
|
448
|
+
clearTimeout(timer);
|
|
449
|
+
ctx.signal?.removeEventListener?.('abort', onAbort);
|
|
450
|
+
if (onChildError) proc.child.off?.('error', onChildError);
|
|
451
|
+
if (onChildExit) proc.child.off?.('exit', onChildExit);
|
|
452
|
+
// ACP thành công → dùng lại tiến trình (phiên mới); lỗi / huỷ / hết giờ / định dùng công cụ → đóng (phiên có thể đang dở).
|
|
453
|
+
if (!err && adapter.kind === 'acp') recycleAcp(proc); else closeProc(proc);
|
|
454
|
+
if (adapter.kind === 'acp') setImmediate(() => keepWarm(adapter, { model, effort, account }));
|
|
455
|
+
// Agent báo chưa đăng nhập / hết phiên → lần sau hỏi lại trạng thái đăng nhập ngay (không tin kết quả nhớ).
|
|
456
|
+
if (err?.code === NOT_SIGNED_IN_ERROR && account) signIn?.forget(adapter.id, account);
|
|
457
|
+
if (err) reject(err); else resolve(value);
|
|
458
|
+
};
|
|
459
|
+
const st = {
|
|
460
|
+
delta: (t) => {
|
|
461
|
+
if (!t) return;
|
|
462
|
+
if (ttft === null) ttft = now() - startedAt;
|
|
463
|
+
if (text.length < MAX_OUTPUT_CHARS) text += t;
|
|
464
|
+
try { ctx.onOutput?.('stdout', t); } catch { /* chỉ là tiến trình */ }
|
|
465
|
+
},
|
|
466
|
+
final: (t) => { finalText = t; },
|
|
467
|
+
meta: (m) => { for (const [k, v] of Object.entries(m)) if (v !== undefined && v !== null) meta[k] = v; },
|
|
468
|
+
tool: (name) => finish(failed(`${adapter.label} tried to use a tool (${name}) — answer discarded`, TOOL_USE_ERROR)),
|
|
469
|
+
fail: (err) => finish(err),
|
|
470
|
+
done: () => {
|
|
471
|
+
// Agent chỉ trả cả câu (Codex): đẩy một lần lúc xong.
|
|
472
|
+
if (!text && finalText) st.delta(finalText);
|
|
473
|
+
const answer = (text || finalText || '').slice(0, MAX_OUTPUT_CHARS);
|
|
474
|
+
if (adapter.kind === 'acp' && AGY_QUOTA_RE.test(answer)) return finish(failed(answer.trim().slice(0, 300), QUOTA_ERROR));
|
|
475
|
+
const out = { text: answer.replace(/\s+$/, ''), agent: adapter.id, model: meta.model || proc.modelId || model || null, stop_reason: meta.stop_reason || null, usage: meta.usage || {}, ttft_ms: ttft, duration_ms: now() - startedAt, warm_start: warmStart };
|
|
476
|
+
if (args.json_schema) out.json = extractJson(out.text);
|
|
477
|
+
finish(null, out);
|
|
478
|
+
},
|
|
479
|
+
};
|
|
480
|
+
const onAbort = () => { if (proc.rpc && proc.sessionId) proc.rpc.notify('session/cancel', { sessionId: proc.sessionId }); finish(failed('Cancelled', DeviceErrorCode.CANCELLED)); };
|
|
481
|
+
const timer = setTimeout(() => finish(failed(`Model did not finish in ${timeoutMs} ms`, DeviceErrorCode.CALL_TIMEOUT)), timeoutMs);
|
|
482
|
+
ctx.signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
483
|
+
onChildError = (e) => finish(failed(`Could not start ${adapter.label}: ${e.message}`));
|
|
484
|
+
onChildExit = (code) => finish(failed(`${adapter.label} exited (${code}) before answering${proc.stderr ? `: ${proc.stderr.trim().slice(-400)}` : ''}`, agentErrorCode(proc.stderr)));
|
|
485
|
+
proc.child.once('error', onChildError);
|
|
486
|
+
proc.child.once('exit', onChildExit);
|
|
487
|
+
|
|
488
|
+
if (adapter.kind === 'acp') {
|
|
489
|
+
proc.rpc.onNotify = (method, params) => {
|
|
490
|
+
if (method !== 'session/update') return;
|
|
491
|
+
// Tiến trình dùng lại: thông báo trễ của phiên trước không được lẫn vào lời gọi này.
|
|
492
|
+
if (params?.sessionId && proc.sessionId && params.sessionId !== proc.sessionId) return;
|
|
493
|
+
const u = params?.update || {};
|
|
494
|
+
if (u.sessionUpdate === 'agent_message_chunk' && u.content?.type === 'text') st.delta(u.content.text);
|
|
495
|
+
if (u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') st.tool(u.name || u.title || u.kind || 'tool');
|
|
496
|
+
};
|
|
497
|
+
// Agent xin quyền (lệnh, ghi tệp…) → luôn từ chối, và coi như đã định dùng công cụ.
|
|
498
|
+
proc.rpc.onRequest = (method, params) => {
|
|
499
|
+
if (method === 'session/request_permission') {
|
|
500
|
+
const reject = (params?.options || []).find((o) => /reject/.test(String(o.kind)));
|
|
501
|
+
setImmediate(() => st.tool(params?.toolCall?.name || 'permission'));
|
|
502
|
+
return { outcome: reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' } };
|
|
503
|
+
}
|
|
504
|
+
throw Object.assign(new Error('not supported'), { code: -32601 });
|
|
505
|
+
};
|
|
506
|
+
proc.ready.then(async ({ sessionId, modelId }) => {
|
|
507
|
+
proc.sessionId = sessionId;
|
|
508
|
+
proc.modelId = modelId;
|
|
509
|
+
const r = await proc.rpc.call('session/prompt', { sessionId, prompt: [{ type: 'text', text: content }] });
|
|
510
|
+
if (r?.usage) st.meta({ usage: { input_tokens: r.usage.inputTokens, output_tokens: r.usage.outputTokens } });
|
|
511
|
+
st.meta({ stop_reason: r?.stopReason });
|
|
512
|
+
st.done();
|
|
513
|
+
}).catch((e) => finish(e instanceof DeviceToolError ? e : failed(`${adapter.label}: ${e?.message || e}`, agentErrorCode(e?.message))));
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
let buf = '';
|
|
518
|
+
proc.child.stdout.setEncoding('utf8');
|
|
519
|
+
proc.child.stdout.on('data', (d) => {
|
|
520
|
+
buf += d;
|
|
521
|
+
let i;
|
|
522
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
523
|
+
const line = buf.slice(0, i);
|
|
524
|
+
buf = buf.slice(i + 1);
|
|
525
|
+
if (!line.trim()) continue;
|
|
526
|
+
let m;
|
|
527
|
+
try { m = JSON.parse(line); } catch { continue; }
|
|
528
|
+
try { adapter.parse(m, st); } catch (e) { finish(failed(`Bad ${adapter.label} output: ${e.message}`)); }
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
const input = adapter.encode(content);
|
|
532
|
+
proc.child.stdin.write(input);
|
|
533
|
+
if (adapter.kind === 'stdin') proc.child.stdin.end();
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
return {
|
|
538
|
+
available: () => installed().length > 0,
|
|
539
|
+
agents: () => installed().map((a) => ({ id: a.id, label: a.label, ...(versions.get(a.id) ? { version: versions.get(a.id) } : {}) })),
|
|
540
|
+
info: () => ({ agents: installed().map((a) => ({ id: a.id, ...(versions.get(a.id) ? { version: versions.get(a.id) } : {}) })), warm: [...warm.keys()], warm_procs: warmCount() }),
|
|
541
|
+
complete,
|
|
542
|
+
/** BE báo trước agent / model sắp dùng (người dùng vừa chọn máy này) → khởi động sẵn. Máy tổ chức: chỉ khi thành viên đã đăng nhập. */
|
|
543
|
+
prewarm: (args = {}, ctx = {}) => {
|
|
544
|
+
const { adapter, model, effort } = validate(args);
|
|
545
|
+
const account = accountOf(ctx);
|
|
546
|
+
const warmNow = () => {
|
|
547
|
+
keepWarm(adapter, { model, effort, account });
|
|
548
|
+
const own = [...warm.keys()].filter((k) => !account || k.startsWith(`${account.name}|`));
|
|
549
|
+
return { warm: account ? own.map((k) => k.slice(account.name.length + 1)) : own };
|
|
550
|
+
};
|
|
551
|
+
if (!account) return warmNow();
|
|
552
|
+
return signIn.status(adapter, account).then((ok) => (ok ? warmNow() : { warm: [], signed_in: false }));
|
|
553
|
+
},
|
|
554
|
+
memberMode,
|
|
555
|
+
memberDir,
|
|
556
|
+
signIn,
|
|
557
|
+
binOf,
|
|
558
|
+
adapterFor,
|
|
559
|
+
stopAll: () => { for (const k of [...warm.keys()]) closeWarm(k); if (sweeper) { clearInterval(sweeper); sweeper = null; } },
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** JSON-RPC 2.0 theo dòng trên stdin/stdout của tiến trình ACP. */
|
|
564
|
+
export function acpClient(child) {
|
|
565
|
+
let id = 0;
|
|
566
|
+
let buf = '';
|
|
567
|
+
const pending = new Map();
|
|
568
|
+
const client = {
|
|
569
|
+
onNotify: null,
|
|
570
|
+
onRequest: null,
|
|
571
|
+
call(method, params) {
|
|
572
|
+
return new Promise((resolve, reject) => {
|
|
573
|
+
const i = ++id;
|
|
574
|
+
pending.set(i, { resolve, reject });
|
|
575
|
+
try { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: i, method, params })}\n`); } catch (e) { pending.delete(i); reject(e); }
|
|
576
|
+
});
|
|
577
|
+
},
|
|
578
|
+
notify(method, params) {
|
|
579
|
+
try { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params })}\n`); } catch { /* đã đóng */ }
|
|
580
|
+
},
|
|
581
|
+
};
|
|
582
|
+
const reply = (msgId, body) => { try { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: msgId, ...body })}\n`); } catch { /* đã đóng */ } };
|
|
583
|
+
child.stdout.setEncoding?.('utf8');
|
|
584
|
+
child.stdout.on('data', (d) => {
|
|
585
|
+
buf += d;
|
|
586
|
+
let k;
|
|
587
|
+
while ((k = buf.indexOf('\n')) >= 0) {
|
|
588
|
+
const line = buf.slice(0, k);
|
|
589
|
+
buf = buf.slice(k + 1);
|
|
590
|
+
let m;
|
|
591
|
+
try { m = JSON.parse(line); } catch { continue; }
|
|
592
|
+
if (m.id !== undefined && !m.method) {
|
|
593
|
+
const p = pending.get(m.id);
|
|
594
|
+
pending.delete(m.id);
|
|
595
|
+
if (p) m.error ? p.reject(Object.assign(new Error(m.error.message || 'ACP error'), { code: m.error.code })) : p.resolve(m.result);
|
|
596
|
+
} else if (m.method && m.id !== undefined) {
|
|
597
|
+
try { reply(m.id, { result: client.onRequest ? client.onRequest(m.method, m.params) : null }); } catch (e) { reply(m.id, { error: { code: e.code || -32603, message: e.message } }); }
|
|
598
|
+
} else if (m.method) {
|
|
599
|
+
try { client.onNotify?.(m.method, m.params); } catch { /* bỏ qua */ }
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
child.once?.('exit', () => { for (const p of pending.values()) p.reject(new Error('ACP process exited')); pending.clear(); });
|
|
604
|
+
return client;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** Công cụ nội bộ (BE gọi thẳng, không vào danh mục của Planner). */
|
|
608
|
+
export function buildLocalLlmTools(llm) {
|
|
609
|
+
const list = llm.agents().map((a) => `${a.id}${a.version ? ` ${a.version}` : ''}`).join(', ');
|
|
610
|
+
return [
|
|
611
|
+
{ name: 'llm.complete', group: ToolGroup.PROC, read_only: true, internal: true, handler: (a, c, e) => llm.complete(a, { ...c, runAs: e?.runAs }),
|
|
612
|
+
description: `BE-only: answer one LLM request with a coding agent the person is signed in to on this computer, as a plain model — no tools, no files, no project settings. Installed: ${list}. Text streams on stdout; the result has text, json (when json_schema was given), agent, model, usage and timing. Error ${TOOL_USE_ERROR}: the agent tried to use a tool and its answer was discarded.`,
|
|
613
|
+
input_schema: schema({
|
|
614
|
+
agent: str(`which agent: ${llm.agents().map((a) => a.id).join(' | ')} (default the first)`),
|
|
615
|
+
system: str('instructions (system prompt) for this request'), prompt: str('the request; or give messages'),
|
|
616
|
+
messages: { type: 'array', description: 'history: [{role: user|assistant, content}] — the last user message is the request when prompt is empty' },
|
|
617
|
+
json_schema: { type: 'object', description: 'JSON Schema the answer must match' },
|
|
618
|
+
model: str('model of that agent (claude: opus | sonnet | haiku…; codex: gpt-…; antigravity: gemini-…, effort picks the variant)'),
|
|
619
|
+
effort: str(EFFORTS.join(' | ')),
|
|
620
|
+
timeout_ms: { type: 'number', description: 'default 180000, max 600000' },
|
|
621
|
+
}) },
|
|
622
|
+
{ name: 'llm.prewarm', group: ToolGroup.PROC, read_only: true, internal: true, handler: (a, c, e) => llm.prewarm(a, { ...c, runAs: e?.runAs }),
|
|
623
|
+
description: 'BE-only: start a model process ahead of the next llm.complete with this agent / model / effort.',
|
|
624
|
+
input_schema: schema({ agent: str('agent id'), model: str('model'), effort: str('effort') }) },
|
|
625
|
+
];
|
|
626
|
+
}
|