dsh-runtime-kit 0.1.0 → 0.2.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/README.md +28 -0
- package/config.schema.json +38 -1
- package/dist/hooks/index.d.ts +77 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +204 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/policy.d.ts +47 -0
- package/dist/hooks/policy.d.ts.map +1 -0
- package/dist/hooks/policy.js +196 -0
- package/dist/hooks/policy.js.map +1 -0
- package/dist/index.js +1246 -1237
- package/docs/GOVERNANCE.md +158 -0
- package/package.json +8 -2
- package/test/governance.mjs +157 -0
package/dist/index.js
CHANGED
|
@@ -1,1240 +1,1249 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-runtime-kit v0.1.0 - DSH 通用运行时插件
|
|
3
|
-
* 上下文治理(C1)、快路径(C2)、PTC(C3)、编排裁剪(C4)、并发/恢复(C5)、沙箱(C6)、审计(C7)
|
|
4
|
-
* 零业务依赖:仅依赖 Node 内置模块与 DSH 宿主注入的 ctx。
|
|
5
|
-
*
|
|
6
|
-
* 导出形状遵循 @deepseek-ai/cordis-plugin-loader 契约:
|
|
7
|
-
* exports.default ?? exports → { name, inject?, apply }
|
|
8
|
-
* 命令通过 'commands' 服务注册(commands.register),handler 返回 CommandResult。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import * as fs from 'node:fs/promises';
|
|
12
|
-
import * as path from 'node:path';
|
|
13
|
-
import * as os from 'node:os';
|
|
1
|
+
/**
|
|
2
|
+
* dsh-runtime-kit v0.1.0 - DSH 通用运行时插件
|
|
3
|
+
* 上下文治理(C1)、快路径(C2)、PTC(C3)、编排裁剪(C4)、并发/恢复(C5)、沙箱(C6)、审计(C7)
|
|
4
|
+
* 零业务依赖:仅依赖 Node 内置模块与 DSH 宿主注入的 ctx。
|
|
5
|
+
*
|
|
6
|
+
* 导出形状遵循 @deepseek-ai/cordis-plugin-loader 契约:
|
|
7
|
+
* exports.default ?? exports → { name, inject?, apply }
|
|
8
|
+
* 命令通过 'commands' 服务注册(commands.register),handler 返回 CommandResult。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as fs from 'node:fs/promises';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
import * as os from 'node:os';
|
|
14
14
|
import * as crypto from 'node:crypto';
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
this.
|
|
25
|
-
this.
|
|
26
|
-
this.
|
|
27
|
-
this.
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
this.tools.
|
|
33
|
-
this.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
this.
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
this.templates.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
this.
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
this.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
this.
|
|
82
|
-
this.
|
|
83
|
-
this.
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
//
|
|
89
|
-
//
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
this.
|
|
95
|
-
this.
|
|
96
|
-
this.
|
|
97
|
-
this.
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
this.
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (!this.
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
let
|
|
116
|
-
let
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
t.
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
this.
|
|
211
|
-
this.
|
|
212
|
-
this.
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
return
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
return this.allow(`${op} allowed
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (a === '
|
|
258
|
-
if (a === '
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
if (r.action === '
|
|
270
|
-
if (r.action === '
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
if (r.action === '
|
|
288
|
-
if (r.action === '
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
case '
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (en ===
|
|
302
|
-
return this.allow(`Tool
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
const
|
|
310
|
-
arr.
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
const
|
|
327
|
-
this.
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
this.trash.
|
|
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
|
-
|
|
372
|
-
|
|
373
|
-
{ n: '
|
|
374
|
-
{ n: '
|
|
375
|
-
{ n: '
|
|
376
|
-
{ n: '
|
|
377
|
-
{ n: '
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
return { command: '
|
|
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
|
-
this.
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
await fs.
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
let
|
|
462
|
-
|
|
463
|
-
ch.
|
|
464
|
-
ch.on('
|
|
465
|
-
ch.on('
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
this.
|
|
471
|
-
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
//
|
|
476
|
-
//
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
this.
|
|
482
|
-
this.
|
|
483
|
-
this.
|
|
484
|
-
this.
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
by.
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
if (f?.
|
|
526
|
-
if (f?.
|
|
527
|
-
if (f?.
|
|
528
|
-
if (f?.
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
cut
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
const
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
this.
|
|
588
|
-
this.
|
|
589
|
-
this.
|
|
590
|
-
this.
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
await this.
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
this.
|
|
647
|
-
this.
|
|
648
|
-
this.
|
|
649
|
-
this.
|
|
650
|
-
this.
|
|
651
|
-
this.
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
const
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
await this.
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
const
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
this.
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
await fs.
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
this.state.
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
this.state.
|
|
779
|
-
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
//
|
|
805
|
-
//
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
//
|
|
835
|
-
//
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
this.
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
this.
|
|
867
|
-
this.
|
|
868
|
-
this.
|
|
869
|
-
this.
|
|
870
|
-
this.
|
|
871
|
-
this.
|
|
872
|
-
this.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
await fs.
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
{ tool: 'echo', args: { text: 'step-
|
|
972
|
-
{ tool: 'echo', args: { text: 'step-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
checks
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
const
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
this.
|
|
1032
|
-
this.
|
|
1033
|
-
this.
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
//
|
|
1045
|
-
//
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
const
|
|
1054
|
-
|
|
1055
|
-
let
|
|
1056
|
-
let
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
cur
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
const
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
const
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
...
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
await fs.mkdir(config.
|
|
1118
|
-
|
|
1119
|
-
|
|
15
|
+
import { installGovernance, DEFAULT_GOVERNANCE } from './hooks/index.js';
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
|
|
18
|
+
// ============================================================================
|
|
19
|
+
// Registry(唯一业务耦合面:registerTool / registerTemplate / registerWorkspace)
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
class RegistryImpl {
|
|
23
|
+
constructor(hooks = {}) {
|
|
24
|
+
this.hooks = hooks;
|
|
25
|
+
this.tools = new Map();
|
|
26
|
+
this.toolEnabled = new Map();
|
|
27
|
+
this.templates = new Map();
|
|
28
|
+
this.workspaces = new Map();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
registerTool(spec) {
|
|
32
|
+
if (this.tools.has(spec.name)) throw new Error(`Tool "${spec.name}" already registered`);
|
|
33
|
+
this.tools.set(spec.name, spec);
|
|
34
|
+
this.toolEnabled.set(spec.name, true);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
unregisterTool(name) {
|
|
38
|
+
this.tools.delete(name);
|
|
39
|
+
this.toolEnabled.delete(name);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
getTool(name) { return this.tools.get(name); }
|
|
43
|
+
listTools() { return Array.from(this.tools.values()); }
|
|
44
|
+
isToolEnabled(name) { return this.toolEnabled.get(name) ?? false; }
|
|
45
|
+
|
|
46
|
+
setToolEnabled(name, enabled) {
|
|
47
|
+
if (!this.tools.has(name)) throw new Error(`Tool "${name}" not registered`);
|
|
48
|
+
this.toolEnabled.set(name, enabled);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
registerTemplate(spec) {
|
|
52
|
+
if (this.templates.has(spec.name)) throw new Error(`Template "${spec.name}" already registered`);
|
|
53
|
+
this.templates.set(spec.name, spec);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
unregisterTemplate(name) { this.templates.delete(name); }
|
|
57
|
+
getTemplate(name) { return this.templates.get(name); }
|
|
58
|
+
listTemplates() { return Array.from(this.templates.values()); }
|
|
59
|
+
|
|
60
|
+
async matchTemplate(input) {
|
|
61
|
+
for (const t of this.templates.values()) {
|
|
62
|
+
if (await t.match(input)) return t;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
registerWorkspace(spec) {
|
|
67
|
+
if (this.workspaces.has(spec.profile)) throw new Error(`Workspace for profile "${spec.profile}" already registered`);
|
|
68
|
+
const ws = { ...spec, root: path.resolve(spec.root) };
|
|
69
|
+
this.workspaces.set(spec.profile, ws);
|
|
70
|
+
this.hooks.onWorkspaceRegistered?.(ws);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
unregisterWorkspace(profile) {
|
|
74
|
+
this.workspaces.delete(profile);
|
|
75
|
+
this.hooks.onWorkspaceUnregistered?.(profile);
|
|
76
|
+
}
|
|
77
|
+
getWorkspace(profile) { return this.workspaces.get(profile); }
|
|
78
|
+
listWorkspaces() { return Array.from(this.workspaces.values()); }
|
|
79
|
+
|
|
80
|
+
clear() {
|
|
81
|
+
this.tools.clear();
|
|
82
|
+
this.toolEnabled.clear();
|
|
83
|
+
this.templates.clear();
|
|
84
|
+
this.workspaces.clear();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ============================================================================
|
|
89
|
+
// Context Governance(C1):返回体裁剪 / 字段投影 / 懒加载
|
|
90
|
+
// ============================================================================
|
|
91
|
+
|
|
92
|
+
class ContextGovernance {
|
|
93
|
+
constructor(config) {
|
|
94
|
+
this.config = config;
|
|
95
|
+
this.toolSchemas = new Map();
|
|
96
|
+
this.schemasLoaded = new Map();
|
|
97
|
+
this.metrics = [];
|
|
98
|
+
this.currentTurn = 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
registerToolSchema(name, schema) {
|
|
102
|
+
this.toolSchemas.set(name, schema);
|
|
103
|
+
this.schemasLoaded.set(name, false);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async getToolSchema(name) {
|
|
107
|
+
if (!this.config.lazyLoadTools) return this.toolSchemas.get(name);
|
|
108
|
+
if (!this.schemasLoaded.get(name)) this.schemasLoaded.set(name, true);
|
|
109
|
+
return this.toolSchemas.get(name);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async governReturn(toolName, result, projection) {
|
|
113
|
+
const originalStr = JSON.stringify(result);
|
|
114
|
+
const originalBytes = Buffer.byteLength(originalStr, 'utf-8');
|
|
115
|
+
let governed = { ...result };
|
|
116
|
+
let truncated = false;
|
|
117
|
+
let fieldsProjected;
|
|
118
|
+
|
|
119
|
+
if (this.config.fieldsProjection && projection && governed.data) {
|
|
120
|
+
governed.data = this.projectFields(governed.data, projection);
|
|
121
|
+
fieldsProjected = projection.include ?? Object.keys(projection.exclude ?? {});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const budget = this.config.maxReturnBytes;
|
|
125
|
+
let governedBytes = Buffer.byteLength(JSON.stringify(governed), 'utf-8');
|
|
126
|
+
|
|
127
|
+
if (governedBytes > budget) {
|
|
128
|
+
governed = this.truncateToBudget(governed, budget);
|
|
129
|
+
governedBytes = budget;
|
|
130
|
+
truncated = true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return { ...governed, governance: { originalBytes, governedBytes, truncated, fieldsProjected } };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
projectFields(obj, options) {
|
|
137
|
+
const { include, exclude, maxDepth = 10, maxArrayLength = 50 } = options;
|
|
138
|
+
function visit(v, p, d) {
|
|
139
|
+
if (d > maxDepth) return '[MAX_DEPTH_EXCEEDED]';
|
|
140
|
+
if (Array.isArray(v)) {
|
|
141
|
+
if (v.length > maxArrayLength) {
|
|
142
|
+
const head = v.slice(0, maxArrayLength).map((x, i) => visit(x, `${p}[${i}]`, d + 1));
|
|
143
|
+
return [...head, `[...${v.length - maxArrayLength} more]`];
|
|
144
|
+
}
|
|
145
|
+
return v.map((x, i) => visit(x, `${p}[${i}]`, d + 1));
|
|
146
|
+
}
|
|
147
|
+
if (v && typeof v === 'object') {
|
|
148
|
+
const r = {};
|
|
149
|
+
for (const [k, val] of Object.entries(v)) {
|
|
150
|
+
const fp = p ? `${p}.${k}` : k;
|
|
151
|
+
if (include?.length && !include.some(pt => fp === pt || fp.startsWith(pt + '.'))) continue;
|
|
152
|
+
if (exclude?.length && exclude.some(pt => fp === pt || fp.startsWith(pt + '.'))) continue;
|
|
153
|
+
r[k] = visit(val, fp, d + 1);
|
|
154
|
+
}
|
|
155
|
+
return r;
|
|
156
|
+
}
|
|
157
|
+
return v;
|
|
158
|
+
}
|
|
159
|
+
return visit(obj, '', 0);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
truncateToBudget(result, budget) {
|
|
163
|
+
const t = { ...result };
|
|
164
|
+
if (t.data) {
|
|
165
|
+
const oh = Buffer.byteLength(JSON.stringify({ ...t, data: '' }), 'utf-8');
|
|
166
|
+
const avail = budget - oh - 100;
|
|
167
|
+
if (avail > 100) {
|
|
168
|
+
if (typeof t.data === 'string' && t.data.length > avail / 3) {
|
|
169
|
+
t.data = t.data.slice(0, avail / 3) + '\n... [TRUNCATED]';
|
|
170
|
+
} else if (Array.isArray(t.data)) {
|
|
171
|
+
const kept = [];
|
|
172
|
+
let bytes = 0;
|
|
173
|
+
for (const it of t.data) {
|
|
174
|
+
const ib = Buffer.byteLength(JSON.stringify(it), 'utf-8');
|
|
175
|
+
if (bytes + ib > avail) break;
|
|
176
|
+
kept.push(it);
|
|
177
|
+
bytes += ib;
|
|
178
|
+
}
|
|
179
|
+
t.data = [...kept, `[...${t.data.length - kept.length} more TRUNCATED]`];
|
|
180
|
+
} else if (typeof t.data === 'object') {
|
|
181
|
+
t.data = { ...t.data, _truncated: true };
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
t.data = '[TRUNCATED: EXCEEDS BUDGET]';
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
t.truncated = true;
|
|
188
|
+
t.totalBytes = budget;
|
|
189
|
+
return t;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
recordMetrics(s) {
|
|
193
|
+
this.metrics.push(s);
|
|
194
|
+
if (this.metrics.length > 1000) this.metrics.shift();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
getMetrics() { return [...this.metrics]; }
|
|
198
|
+
updateConfig(p) { this.config = { ...this.config, ...p }; }
|
|
199
|
+
getConfig() { return { ...this.config }; }
|
|
200
|
+
nextTurn() { this.currentTurn++; }
|
|
201
|
+
getCurrentTurn() { return this.currentTurn; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ============================================================================
|
|
205
|
+
// Sandbox(C6):3 级基线 + 3 态细规则、fail-closed、快照/回收站、注入防护、脱敏
|
|
206
|
+
// ============================================================================
|
|
207
|
+
|
|
208
|
+
class Sandbox {
|
|
209
|
+
constructor(config) {
|
|
210
|
+
this.config = config;
|
|
211
|
+
this.workspaces = new Map();
|
|
212
|
+
this.snapshots = new Map();
|
|
213
|
+
this.trash = new Map();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
updateConfig(p) { this.config = { ...this.config, ...p }; }
|
|
217
|
+
getConfig() { return { ...this.config }; }
|
|
218
|
+
|
|
219
|
+
registerWorkspace(spec) { this.workspaces.set(spec.profile, { ...spec, root: path.resolve(spec.root) }); }
|
|
220
|
+
unregisterWorkspace(p) { this.workspaces.delete(p); }
|
|
221
|
+
getWorkspace(p) { return this.workspaces.get(p); }
|
|
222
|
+
|
|
223
|
+
resolveAndValidate(profile, requestedPath, op) {
|
|
224
|
+
const ws = this.workspaces.get(profile);
|
|
225
|
+
if (!ws) return this.deny(`Workspace not registered: ${profile}`, 'file', op);
|
|
226
|
+
let abs;
|
|
227
|
+
try {
|
|
228
|
+
abs = path.isAbsolute(requestedPath) ? path.resolve(requestedPath) : path.resolve(ws.root, requestedPath);
|
|
229
|
+
} catch {
|
|
230
|
+
return this.deny(`Path resolution failed: ${requestedPath}`, 'file', op);
|
|
231
|
+
}
|
|
232
|
+
const rel = path.relative(ws.root, abs);
|
|
233
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
234
|
+
return this.deny(`Path traversal: ${requestedPath} -> ${abs}`, 'file', op);
|
|
235
|
+
}
|
|
236
|
+
const base = this.checkBaseMode(ws, op);
|
|
237
|
+
if (!base.allowed) return base;
|
|
238
|
+
const rule = this.matchFileRules(rel, op);
|
|
239
|
+
if (rule) return rule;
|
|
240
|
+
return base;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
checkBaseMode(ws, op) {
|
|
244
|
+
const mode = ws.permissionMode ?? this.config.mode;
|
|
245
|
+
if (mode === 'read-only') {
|
|
246
|
+
if (op === 'read') return this.allow('Read allowed');
|
|
247
|
+
return this.deny(`${op} denied in read-only`, 'file', op);
|
|
248
|
+
}
|
|
249
|
+
if (mode === 'workspace-write') return this.allow(`${op} allowed`);
|
|
250
|
+
return this.allow(`${op} allowed in danger-full-access`);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
matchFileRules(rel, op) {
|
|
254
|
+
for (const r of this.config.rules.files) {
|
|
255
|
+
if (this.matchGlob(rel, r.pattern)) {
|
|
256
|
+
const a = r[op];
|
|
257
|
+
if (a === 'allow') return this.allow(`File rule allow: ${r.pattern}`, r);
|
|
258
|
+
if (a === 'deny') return this.deny(`File rule deny: ${r.pattern}`, 'file', op, r);
|
|
259
|
+
if (a === 'ask') return this.ask(`File rule ask: ${r.pattern}`, r);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
validateCommand(req) {
|
|
266
|
+
const full = `${req.command} ${req.args.join(' ')}`.trim();
|
|
267
|
+
for (const r of this.config.rules.commands) {
|
|
268
|
+
if (full.startsWith(r.prefix)) {
|
|
269
|
+
if (r.action === 'allow') return this.allow(`Cmd allow: ${r.prefix}`, r);
|
|
270
|
+
if (r.action === 'deny') return this.deny(`Cmd deny: ${r.prefix}`, 'command', 'execute', r);
|
|
271
|
+
if (r.action === 'ask') return this.ask(`Cmd ask: ${r.prefix}`, r);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (this.config.mode === 'danger-full-access') return this.allow('Allowed in danger-full-access');
|
|
275
|
+
return this.deny(`Cmd not allowed: ${full}`, 'command', 'execute');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
validateNetwork(req) {
|
|
279
|
+
let host;
|
|
280
|
+
try {
|
|
281
|
+
host = new URL(req.url).hostname;
|
|
282
|
+
} catch {
|
|
283
|
+
return this.deny(`Invalid URL: ${req.url}`, 'network', 'connect');
|
|
284
|
+
}
|
|
285
|
+
for (const r of this.config.rules.network) {
|
|
286
|
+
if (host === r.domain) {
|
|
287
|
+
if (r.action === 'allow') return this.allow(`Net allow: ${r.domain}`, r);
|
|
288
|
+
if (r.action === 'deny') return this.deny(`Net deny: ${r.domain}`, 'network', 'connect', r);
|
|
289
|
+
if (r.action === 'ask') return this.ask(`Net ask: ${r.domain}`, r);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
switch (this.config.networkDefault) {
|
|
293
|
+
case 'allow': return this.allow('Allowed by default');
|
|
294
|
+
case 'ask': return this.ask('Requires approval');
|
|
295
|
+
default: return this.deny(`Denied by default: ${host}`, 'network', 'connect');
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
isToolAllowed(name) {
|
|
300
|
+
const en = this.config.toolControl[name];
|
|
301
|
+
if (en === false) return this.deny(`Tool disabled: ${name}`, 'tool', 'call');
|
|
302
|
+
if (en === true) return this.allow(`Tool enabled: ${name}`);
|
|
303
|
+
return this.allow(`Tool not controlled: ${name}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async createSnapshot(filePath, content) {
|
|
307
|
+
if (!this.config.backupEnabled) return '';
|
|
308
|
+
const hash = crypto.createHash('sha256').update(content).digest('hex').slice(0, 16);
|
|
309
|
+
const snap = { path: filePath, content, hash, timestamp: new Date().toISOString() };
|
|
310
|
+
const arr = this.snapshots.get(filePath) || [];
|
|
311
|
+
arr.push(snap);
|
|
312
|
+
if (arr.length > 10) arr.shift();
|
|
313
|
+
this.snapshots.set(filePath, arr);
|
|
314
|
+
return hash;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
getSnapshots(filePath) { return this.snapshots.get(filePath) || []; }
|
|
318
|
+
|
|
319
|
+
restoreSnapshot(filePath, hash) {
|
|
320
|
+
const s = this.snapshots.get(filePath) || [];
|
|
321
|
+
return s.find(x => x.hash === hash)?.content ?? null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async safeDelete(filePath, content) {
|
|
325
|
+
if (!this.config.deletionProtection) return 'deleted';
|
|
326
|
+
const id = crypto.randomUUID();
|
|
327
|
+
const hash = await this.createSnapshot(filePath, content);
|
|
328
|
+
this.trash.set(id, {
|
|
329
|
+
originalPath: filePath,
|
|
330
|
+
snapshot: { path: filePath, content, hash, timestamp: new Date().toISOString() },
|
|
331
|
+
deletedAt: new Date().toISOString(),
|
|
332
|
+
});
|
|
333
|
+
return id;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
restoreFromTrash(id) {
|
|
337
|
+
const e = this.trash.get(id);
|
|
338
|
+
if (!e) return null;
|
|
339
|
+
this.trash.delete(id);
|
|
340
|
+
return { path: e.originalPath, content: e.snapshot.content };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async emptyTrash(approved) {
|
|
344
|
+
if (!approved) throw new Error('Requires approval');
|
|
345
|
+
const n = this.trash.size;
|
|
346
|
+
this.trash.clear();
|
|
347
|
+
return n;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
isWorkspaceTrusted(p) {
|
|
351
|
+
const w = this.workspaces.get(p);
|
|
352
|
+
return w?.trusted ?? this.config.workspaceTrust;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
detectInjection(content) {
|
|
356
|
+
if (!this.config.injectionGuard) return { suspicious: false, patterns: [] };
|
|
357
|
+
const pats = [
|
|
358
|
+
/ignore\s+(previous|above|all)\s+instructions?/i,
|
|
359
|
+
/forget\s+(everything|all|previous)/i,
|
|
360
|
+
/you\s+are\s+now\s+/i,
|
|
361
|
+
/system\s*:\s*/i,
|
|
362
|
+
/assistant\s*:\s*/i,
|
|
363
|
+
/<\|.*?\|>/g,
|
|
364
|
+
/```\s*(system|user|assistant)/i,
|
|
365
|
+
/override\s+(safety|security|policy)/i,
|
|
366
|
+
/bypass\s+(filter|guard|check)/i,
|
|
367
|
+
];
|
|
368
|
+
const hit = pats.filter(p => p.test(content));
|
|
369
|
+
return { suspicious: hit.length > 0, patterns: hit.map(p => p.source) };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
static SENSITIVE = [
|
|
373
|
+
{ n: 'password', r: /(?:password|passwd|pwd)\s*[:=]\s*["']?([^"'\s]{8,})/gi },
|
|
374
|
+
{ n: 'api_key', r: /(?:api[_-]?key|apikey)\s*[:=]\s*["']?([^"'\s]{16,})/gi },
|
|
375
|
+
{ n: 'secret', r: /(?:secret|token)\s*[:=]\s*["']?([^"'\s]{16,})/gi },
|
|
376
|
+
{ n: 'cookie', r: /(?:cookie|session)\s*[:=]\s*["']?([^"'\s]{16,})/gi },
|
|
377
|
+
{ n: 'private_key', r: /-----BEGIN (?:RSA|EC|OPENSSH)? PRIVATE KEY-----[\s\S]*?-----END (?:RSA|EC|OPENSSH)? PRIVATE KEY-----/gi },
|
|
378
|
+
{ n: 'conn', r: /(?:jdbc:|mongodb:\/\/|redis:\/\/|mysql:\/\/|postgresql:\/\/)[^"'\s]*(?::[^"'\s@]+@)/gi },
|
|
379
|
+
];
|
|
380
|
+
|
|
381
|
+
desensitize(content) {
|
|
382
|
+
if (!this.config.sensitiveProtection) return { sanitized: content, placeholders: new Map() };
|
|
383
|
+
const ph = new Map();
|
|
384
|
+
let s = content;
|
|
385
|
+
for (const { n, r } of Sandbox.SENSITIVE) {
|
|
386
|
+
r.lastIndex = 0;
|
|
387
|
+
let m;
|
|
388
|
+
while ((m = r.exec(content)) !== null) {
|
|
389
|
+
const o = m[1] ?? m[0];
|
|
390
|
+
const pl = `__${n.toUpperCase()}_${ph.size}__`;
|
|
391
|
+
ph.set(pl, o);
|
|
392
|
+
s = s.split(o).join(pl);
|
|
393
|
+
if (!r.global) break;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return { sanitized: s, placeholders: ph };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
resensitize(s, ph) {
|
|
400
|
+
let r = s;
|
|
401
|
+
for (const [pl, o] of ph) r = r.split(pl).join(o);
|
|
402
|
+
return r;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
getShellExecutor() {
|
|
406
|
+
if (process.platform === 'win32') return { command: 'pwsh', args: ['-NoProfile', '-NonInteractive', '-Command'] };
|
|
407
|
+
return { command: '/bin/sh', args: ['-c'] };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
createExecutionDomain() { return new LocalExecutionDomain(this); }
|
|
411
|
+
|
|
412
|
+
matchGlob(s, p) {
|
|
413
|
+
return new RegExp('^' + p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$').test(s);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
allow(reason, rule) {
|
|
417
|
+
return { allowed: true, action: 'allow', reason, ruleMatched: rule, requiresApproval: false };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
deny(reason, _rt, _op, rule) {
|
|
421
|
+
return { allowed: false, action: 'deny', reason, ruleMatched: rule, requiresApproval: false };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
ask(reason, rule) {
|
|
425
|
+
return { allowed: false, action: 'ask', reason, ruleMatched: rule, requiresApproval: true };
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
class LocalExecutionDomain {
|
|
430
|
+
constructor(sb) {
|
|
431
|
+
this.sb = sb;
|
|
432
|
+
this.fs = {
|
|
433
|
+
read: (p) => fs.readFile(p, 'utf-8'),
|
|
434
|
+
write: async (p, c) => {
|
|
435
|
+
await fs.mkdir(path.dirname(p), { recursive: true });
|
|
436
|
+
await fs.writeFile(p, c, 'utf-8');
|
|
437
|
+
},
|
|
438
|
+
delete: async (p) => {
|
|
439
|
+
try {
|
|
440
|
+
await fs.unlink(p);
|
|
441
|
+
} catch {
|
|
442
|
+
await fs.rm(p, { recursive: true, force: true });
|
|
443
|
+
}
|
|
444
|
+
},
|
|
445
|
+
list: (p) => fs.readdir(p),
|
|
446
|
+
stat: async (p) => {
|
|
447
|
+
const s = await fs.stat(p);
|
|
448
|
+
return { size: s.size, mtime: s.mtime, isDirectory: s.isDirectory() };
|
|
449
|
+
},
|
|
450
|
+
mkdir: (p, r = true) => fs.mkdir(p, { recursive: r }),
|
|
451
|
+
};
|
|
452
|
+
this.shell = {
|
|
453
|
+
execute: (cmd, args, o) => {
|
|
454
|
+
const { command, args: shArgs } = this.sb.getShellExecutor();
|
|
455
|
+
return new Promise((resolve, reject) => {
|
|
456
|
+
const ch = spawn(command, [...shArgs, `${cmd} ${args.join(' ')}`], {
|
|
457
|
+
cwd: o?.cwd,
|
|
458
|
+
env: { ...process.env, ...o?.env },
|
|
459
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
460
|
+
});
|
|
461
|
+
let stdout = '';
|
|
462
|
+
let stderr = '';
|
|
463
|
+
ch.stdout?.on('data', d => { stdout += d.toString(); });
|
|
464
|
+
ch.stderr?.on('data', d => { stderr += d.toString(); });
|
|
465
|
+
ch.on('close', c => resolve({ stdout, stderr, exitCode: c ?? 1 }));
|
|
466
|
+
ch.on('error', reject);
|
|
467
|
+
});
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
this.subprocess = { spawn: (cmd, args, o) => this.shell.execute(cmd, args, o) };
|
|
471
|
+
this.network = { fetch: (u, o) => fetch(u, o) };
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// ============================================================================
|
|
476
|
+
// Audit(C7):append-only JSONL、脱敏、导出、清理
|
|
477
|
+
// ============================================================================
|
|
478
|
+
|
|
479
|
+
class Audit {
|
|
480
|
+
constructor(config, logDir, sb) {
|
|
481
|
+
this.config = config;
|
|
482
|
+
this.logDir = logDir;
|
|
483
|
+
this.sb = sb;
|
|
484
|
+
this.buf = [];
|
|
485
|
+
this.timer = null;
|
|
486
|
+
if (config.mode !== 'off') {
|
|
487
|
+
this.timer = setInterval(() => { this.flush().catch(() => {}); }, 5000);
|
|
488
|
+
if (this.timer.unref) this.timer.unref();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
async log(e) {
|
|
493
|
+
if (this.config.mode === 'off') return;
|
|
494
|
+
let ph = e.paramsHash;
|
|
495
|
+
if (this.config.desensitize) {
|
|
496
|
+
const { sanitized } = this.sb.desensitize(e.paramsHash);
|
|
497
|
+
ph = sanitized;
|
|
498
|
+
}
|
|
499
|
+
this.buf.push({ ...e, timestamp: new Date().toISOString(), paramsHash: ph });
|
|
500
|
+
if (e.result === 'BLOCKED' || e.action === 'block') await this.flush();
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async flush() {
|
|
504
|
+
if (!this.buf.length) return;
|
|
505
|
+
const by = new Map();
|
|
506
|
+
for (const e of this.buf) {
|
|
507
|
+
const p = e.profile || 'default';
|
|
508
|
+
if (!by.has(p)) by.set(p, []);
|
|
509
|
+
by.get(p).push(e);
|
|
510
|
+
}
|
|
511
|
+
await fs.mkdir(this.logDir, { recursive: true });
|
|
512
|
+
for (const [prof, ents] of by) {
|
|
513
|
+
const lp = path.join(this.logDir, `audit-${prof}.jsonl`);
|
|
514
|
+
await fs.appendFile(lp, ents.map(e => JSON.stringify(e)).join('\n') + '\n', 'utf-8');
|
|
515
|
+
}
|
|
516
|
+
this.buf = [];
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async getLogs(f) {
|
|
520
|
+
const p = f?.profile || 'default';
|
|
521
|
+
const lp = path.join(this.logDir, `audit-${p}.jsonl`);
|
|
522
|
+
try {
|
|
523
|
+
const c = await fs.readFile(lp, 'utf-8');
|
|
524
|
+
let es = c.trim().split('\n').filter(Boolean).map(l => JSON.parse(l));
|
|
525
|
+
if (f?.tool) es = es.filter(e => e.tool === f.tool);
|
|
526
|
+
if (f?.action) es = es.filter(e => e.action === f.action);
|
|
527
|
+
if (f?.result) es = es.filter(e => e.result === f.result);
|
|
528
|
+
if (f?.since) es = es.filter(e => e.timestamp >= f.since);
|
|
529
|
+
if (f?.until) es = es.filter(e => e.timestamp <= f.until);
|
|
530
|
+
es.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
|
|
531
|
+
return f?.limit ? es.slice(0, f.limit) : es;
|
|
532
|
+
} catch {
|
|
533
|
+
return [];
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async exportLogs(f, fmt = 'jsonl') {
|
|
538
|
+
const es = await this.getLogs(f);
|
|
539
|
+
if (fmt === 'csv') {
|
|
540
|
+
const h = ['timestamp', 'profile', 'tool', 'action', 'paramsHash', 'result', 'durationMs', 'error'];
|
|
541
|
+
return [h.join(','), ...es.map(e => [e.timestamp, e.profile, e.tool, e.action, e.paramsHash, e.result, e.durationMs, e.error ?? ''].join(','))].join('\n');
|
|
542
|
+
}
|
|
543
|
+
return es.map(e => JSON.stringify(e)).join('\n');
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
updateConfig(p) { this.config = { ...this.config, ...p }; }
|
|
547
|
+
|
|
548
|
+
async cleanup() {
|
|
549
|
+
if (this.config.mode === 'off') return 0;
|
|
550
|
+
const cut = new Date();
|
|
551
|
+
cut.setDate(cut.getDate() - this.config.retentionDays);
|
|
552
|
+
const cs = cut.toISOString();
|
|
553
|
+
let n = 0;
|
|
554
|
+
const pros = new Set();
|
|
555
|
+
try {
|
|
556
|
+
for (const e of await fs.readdir(this.logDir)) {
|
|
557
|
+
if (e.startsWith('audit-') && e.endsWith('.jsonl')) pros.add(e.slice(6, -6));
|
|
558
|
+
}
|
|
559
|
+
} catch {
|
|
560
|
+
return 0;
|
|
561
|
+
}
|
|
562
|
+
for (const p of pros) {
|
|
563
|
+
const lp = path.join(this.logDir, `audit-${p}.jsonl`);
|
|
564
|
+
try {
|
|
565
|
+
const c = await fs.readFile(lp, 'utf-8');
|
|
566
|
+
const ls = c.trim().split('\n').filter(Boolean);
|
|
567
|
+
const kept = ls.map(l => JSON.parse(l)).filter(e => e.timestamp >= cs).map(e => JSON.stringify(e));
|
|
568
|
+
await fs.writeFile(lp, kept.join('\n') + (kept.length ? '\n' : ''), 'utf-8');
|
|
569
|
+
n += ls.length - kept.length;
|
|
570
|
+
} catch { /* keep going */ }
|
|
571
|
+
}
|
|
572
|
+
return n;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
async shutdown() {
|
|
576
|
+
if (this.timer) clearInterval(this.timer);
|
|
577
|
+
await this.flush();
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// ============================================================================
|
|
582
|
+
// Loop(C2/C3/C5):FastPath + PTC + SessionManager + ConcurrentScheduler
|
|
583
|
+
// ============================================================================
|
|
584
|
+
|
|
585
|
+
class FastPathExecutor {
|
|
586
|
+
constructor(reg, sb, cg, au, profile) {
|
|
587
|
+
this.reg = reg;
|
|
588
|
+
this.sb = sb;
|
|
589
|
+
this.cg = cg;
|
|
590
|
+
this.au = au;
|
|
591
|
+
this.profile = profile;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async execute(input, tpl) {
|
|
595
|
+
const start = Date.now();
|
|
596
|
+
const ik = tpl.idempotencyKeyFn
|
|
597
|
+
? await tpl.idempotencyKeyFn(input)
|
|
598
|
+
: crypto.createHash('sha256').update(`${tpl.name}:${input}`).digest('hex').slice(0, 32);
|
|
599
|
+
const steps = [];
|
|
600
|
+
const prev = new Map();
|
|
601
|
+
let st = 'SUCCEEDED';
|
|
602
|
+
for (const step of tpl.plan) {
|
|
603
|
+
if (step.condition && !step.condition(prev)) continue;
|
|
604
|
+
const args = typeof step.args === 'function' ? step.args(input, prev) : step.args;
|
|
605
|
+
const ts = this.reg.getTool(step.tool);
|
|
606
|
+
if (!ts) throw new Error(`Tool ${step.tool} not registered`);
|
|
607
|
+
const ta = this.sb.isToolAllowed(step.tool);
|
|
608
|
+
if (!ta.allowed) {
|
|
609
|
+
if (ta.requiresApproval) {
|
|
610
|
+
st = 'BLOCKED';
|
|
611
|
+
await this.au.log({ profile: this.profile, tool: step.tool, action: 'block', paramsHash: JSON.stringify(args), result: 'BLOCKED', durationMs: 0, error: ta.reason });
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
throw new Error(`Tool not allowed: ${ta.reason}`);
|
|
615
|
+
}
|
|
616
|
+
const ss = Date.now();
|
|
617
|
+
let res;
|
|
618
|
+
try {
|
|
619
|
+
res = await ts.handler(args);
|
|
620
|
+
} catch (e) {
|
|
621
|
+
res = { success: false, error: String(e) };
|
|
622
|
+
}
|
|
623
|
+
const gov = await this.cg.governReturn(step.tool, res);
|
|
624
|
+
await this.au.log({
|
|
625
|
+
profile: this.profile,
|
|
626
|
+
tool: step.tool,
|
|
627
|
+
action: 'call',
|
|
628
|
+
paramsHash: JSON.stringify(args),
|
|
629
|
+
result: gov.success ? 'SUCCESS' : 'FAILURE',
|
|
630
|
+
durationMs: Date.now() - ss,
|
|
631
|
+
error: gov.error,
|
|
632
|
+
});
|
|
633
|
+
steps.push({ tool: step.tool, result: gov, durationMs: Date.now() - ss });
|
|
634
|
+
prev.set(step.tool, gov);
|
|
635
|
+
if (!gov.success) {
|
|
636
|
+
st = 'FAILED';
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return { templateName: tpl.name, idempotencyKey: ik, status: st, steps, totalDurationMs: Date.now() - start, llmCalls: 0 };
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
class PTCExecutor {
|
|
645
|
+
constructor(reg, sb, cg, au, profile, maxCalls = 50, timeout = 120000) {
|
|
646
|
+
this.reg = reg;
|
|
647
|
+
this.sb = sb;
|
|
648
|
+
this.cg = cg;
|
|
649
|
+
this.au = au;
|
|
650
|
+
this.profile = profile;
|
|
651
|
+
this.maxCalls = maxCalls;
|
|
652
|
+
this.timeout = timeout;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async execute(script) {
|
|
656
|
+
const start = Date.now();
|
|
657
|
+
const calls = [];
|
|
658
|
+
let trunc = false;
|
|
659
|
+
const parsed = this.parse(script);
|
|
660
|
+
for (const call of parsed) {
|
|
661
|
+
if (calls.length >= this.maxCalls) {
|
|
662
|
+
trunc = true;
|
|
663
|
+
break;
|
|
664
|
+
}
|
|
665
|
+
const ts = this.reg.getTool(call.name);
|
|
666
|
+
if (!ts) {
|
|
667
|
+
calls.push({ tool: call.name, args: call.args, result: { success: false, error: `Tool ${call.name} not registered` } });
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
const ta = this.sb.isToolAllowed(call.name);
|
|
671
|
+
if (!ta.allowed) {
|
|
672
|
+
calls.push({ tool: call.name, args: call.args, result: { success: false, error: `Not allowed: ${ta.reason}` } });
|
|
673
|
+
if (ta.requiresApproval) {
|
|
674
|
+
await this.au.log({ profile: this.profile, tool: call.name, action: 'block', paramsHash: JSON.stringify(call.args), result: 'BLOCKED', durationMs: 0, error: ta.reason });
|
|
675
|
+
}
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const ss = Date.now();
|
|
679
|
+
let r;
|
|
680
|
+
try {
|
|
681
|
+
r = await ts.handler(call.args);
|
|
682
|
+
} catch (e) {
|
|
683
|
+
r = { success: false, error: String(e) };
|
|
684
|
+
}
|
|
685
|
+
const gov = await this.cg.governReturn(call.name, r);
|
|
686
|
+
await this.au.log({
|
|
687
|
+
profile: this.profile,
|
|
688
|
+
tool: call.name,
|
|
689
|
+
action: 'call',
|
|
690
|
+
paramsHash: JSON.stringify(call.args),
|
|
691
|
+
result: gov.success ? 'SUCCESS' : 'FAILURE',
|
|
692
|
+
durationMs: Date.now() - ss,
|
|
693
|
+
error: gov.error,
|
|
694
|
+
});
|
|
695
|
+
calls.push({ tool: call.name, args: call.args, result: gov });
|
|
696
|
+
}
|
|
697
|
+
return {
|
|
698
|
+
script,
|
|
699
|
+
summary: {
|
|
700
|
+
totalCalls: calls.length,
|
|
701
|
+
succeeded: calls.filter(c => c.result.success).length,
|
|
702
|
+
failed: calls.filter(c => !c.result.success).length,
|
|
703
|
+
tools: [...new Set(calls.map(c => c.tool))],
|
|
704
|
+
},
|
|
705
|
+
toolCalls: calls,
|
|
706
|
+
durationMs: Date.now() - start,
|
|
707
|
+
truncated: trunc,
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
parse(s) {
|
|
712
|
+
const out = [];
|
|
713
|
+
const re = /callTool\s*\(\s*["']([^"']+)["']\s*,\s*(\{[\s\S]*?\})\s*\)/g;
|
|
714
|
+
let m;
|
|
715
|
+
while ((m = re.exec(s)) !== null) {
|
|
716
|
+
try {
|
|
717
|
+
out.push({ name: m[1], args: JSON.parse(m[2]) });
|
|
718
|
+
} catch { /* skip malformed call */ }
|
|
719
|
+
}
|
|
720
|
+
return out;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
class SessionManager {
|
|
725
|
+
constructor(profile, dir) {
|
|
726
|
+
this.p = path.join(dir, `session-${profile}.json`);
|
|
727
|
+
this.state = this.init();
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
init() {
|
|
731
|
+
return {
|
|
732
|
+
version: 1,
|
|
733
|
+
turn: 0,
|
|
734
|
+
step: 0,
|
|
735
|
+
completedSteps: new Map(),
|
|
736
|
+
pendingSteps: [],
|
|
737
|
+
idempotencyKeys: new Map(),
|
|
738
|
+
workspaceRoots: new Map(),
|
|
739
|
+
updatedAt: new Date().toISOString(),
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async load() {
|
|
744
|
+
try {
|
|
745
|
+
const c = await fs.readFile(this.p, 'utf-8');
|
|
746
|
+
const j = JSON.parse(c);
|
|
747
|
+
this.state = {
|
|
748
|
+
...j,
|
|
749
|
+
completedSteps: new Map(Object.entries(j.completedSteps ?? {})),
|
|
750
|
+
idempotencyKeys: new Map(Object.entries(j.idempotencyKeys ?? {})),
|
|
751
|
+
workspaceRoots: new Map(Object.entries(j.workspaceRoots ?? {})),
|
|
752
|
+
};
|
|
753
|
+
} catch { /* fresh state */ }
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async save() {
|
|
757
|
+
await fs.mkdir(path.dirname(this.p), { recursive: true });
|
|
758
|
+
await fs.writeFile(this.p, JSON.stringify({
|
|
759
|
+
...this.state,
|
|
760
|
+
completedSteps: Object.fromEntries(this.state.completedSteps),
|
|
761
|
+
idempotencyKeys: Object.fromEntries(this.state.idempotencyKeys),
|
|
762
|
+
workspaceRoots: Object.fromEntries(this.state.workspaceRoots),
|
|
763
|
+
updatedAt: new Date().toISOString(),
|
|
764
|
+
}, null, 2), 'utf-8');
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
mark(id, r) {
|
|
768
|
+
this.state.completedSteps.set(id, r);
|
|
769
|
+
this.state.step++;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
has(id) { return this.state.completedSteps.has(id); }
|
|
773
|
+
get(id) { return this.state.completedSteps.get(id); }
|
|
774
|
+
setIdem(k, r) { this.state.idempotencyKeys.set(k, r); }
|
|
775
|
+
getIdem(k) { return this.state.idempotencyKeys.get(k); }
|
|
776
|
+
|
|
777
|
+
nextTurn() {
|
|
778
|
+
this.state.turn++;
|
|
779
|
+
this.state.step = 0;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
class ConcurrentScheduler {
|
|
784
|
+
constructor(max = 8) { this.max = max; }
|
|
785
|
+
|
|
786
|
+
async execReadOnly(calls) {
|
|
787
|
+
const results = [];
|
|
788
|
+
let cursor = 0;
|
|
789
|
+
const workers = Array.from({ length: Math.min(this.max, calls.length) }, async () => {
|
|
790
|
+
while (cursor < calls.length) {
|
|
791
|
+
const i = cursor++;
|
|
792
|
+
try {
|
|
793
|
+
results[i] = await calls[i].execute();
|
|
794
|
+
} catch (e) {
|
|
795
|
+
results[i] = e;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
await Promise.all(workers);
|
|
800
|
+
return results;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// ============================================================================
|
|
805
|
+
// Preset(C4):编排裁剪补丁
|
|
806
|
+
// ============================================================================
|
|
807
|
+
|
|
808
|
+
const presets = {
|
|
809
|
+
'minimal-no-orchestration': (c) => ({
|
|
810
|
+
...c,
|
|
811
|
+
loop: { ...c.loop, disabledLayers: ['plan', 'todo', 'goal', 'subagent'], prunerEnabled: true, compactionEnabled: true },
|
|
812
|
+
}),
|
|
813
|
+
'code-ptc-friendly': (c) => ({
|
|
814
|
+
...c,
|
|
815
|
+
loop: {
|
|
816
|
+
...c.loop,
|
|
817
|
+
preset: 'code',
|
|
818
|
+
disabledLayers: ['plan', 'todo', 'goal', 'subagent'],
|
|
819
|
+
prunerEnabled: true,
|
|
820
|
+
compactionEnabled: true,
|
|
821
|
+
maxParallelToolCalls: 8,
|
|
822
|
+
},
|
|
823
|
+
}),
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
function applyPreset(cfg, name) {
|
|
827
|
+
const p = presets[name];
|
|
828
|
+
if (!p) throw new Error(`Unknown preset: ${name}`);
|
|
829
|
+
return p(cfg);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function dumpConfig(cfg) { return JSON.stringify(cfg, null, 2); }
|
|
833
|
+
|
|
834
|
+
// ============================================================================
|
|
835
|
+
// Main Service
|
|
836
|
+
// ============================================================================
|
|
837
|
+
|
|
838
|
+
const DEFAULT_CONFIG = {
|
|
839
|
+
context: { maxReturnBytes: 4096, fieldsProjection: true, prunerEnabled: true, compactionEnabled: true, lazyLoadTools: true },
|
|
840
|
+
loop: { preset: 'code', disabledLayers: ['plan', 'todo', 'goal', 'subagent'], maxParallelToolCalls: 8, enableCustomLoop: false },
|
|
841
|
+
sandbox: {
|
|
842
|
+
mode: 'workspace-write',
|
|
843
|
+
approval: 'ask',
|
|
844
|
+
rules: { files: [], commands: [], network: [] },
|
|
845
|
+
networkDefault: 'deny',
|
|
846
|
+
backupEnabled: true,
|
|
847
|
+
deletionProtection: true,
|
|
848
|
+
injectionGuard: true,
|
|
849
|
+
sensitiveProtection: true,
|
|
850
|
+
shell: 'pwsh',
|
|
851
|
+
workspaceTrust: false,
|
|
852
|
+
toolControl: {},
|
|
853
|
+
},
|
|
854
|
+
audit: { mode: 'append-only', desensitize: true, exportable: true, retentionDays: 90 },
|
|
855
|
+
logDir: path.join(os.homedir(), '.dsh', 'runtime-kit', 'logs'),
|
|
856
|
+
stateDir: path.join(os.homedir(), '.dsh', 'runtime-kit', 'state'),
|
|
857
|
+
};
|
|
858
|
+
|
|
859
|
+
class RuntimeKitServiceImpl {
|
|
860
|
+
constructor(config) {
|
|
861
|
+
this.config = config;
|
|
862
|
+
this.registry = new RegistryImpl({
|
|
863
|
+
onWorkspaceRegistered: (ws) => this.sandbox.registerWorkspace(ws),
|
|
864
|
+
onWorkspaceUnregistered: (p) => this.sandbox.unregisterWorkspace(p),
|
|
865
|
+
});
|
|
866
|
+
this.contextGov = new ContextGovernance(config.context);
|
|
867
|
+
this.sandbox = new Sandbox(config.sandbox);
|
|
868
|
+
this.audit = new Audit(config.audit, config.logDir, this.sandbox);
|
|
869
|
+
this.sessionManager = new SessionManager('default', config.stateDir);
|
|
870
|
+
this.fastPath = new FastPathExecutor(this.registry, this.sandbox, this.contextGov, this.audit, 'default');
|
|
871
|
+
this.ptc = new PTCExecutor(this.registry, this.sandbox, this.contextGov, this.audit, 'default');
|
|
872
|
+
this.scheduler = new ConcurrentScheduler(config.loop.maxParallelToolCalls);
|
|
873
|
+
this.registerBuiltinTools();
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
registerBuiltinTools() {
|
|
877
|
+
this.registry.registerTool({
|
|
878
|
+
name: 'echo',
|
|
879
|
+
description: 'Echo back input',
|
|
880
|
+
schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
|
|
881
|
+
isStateChanging: false,
|
|
882
|
+
returnBudget: 1024,
|
|
883
|
+
handler: async (a) => ({ success: true, data: { echoed: a.text } }),
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
const kv = new Map();
|
|
887
|
+
this.registry.registerTool({
|
|
888
|
+
name: 'kv_get',
|
|
889
|
+
description: 'Get KV value',
|
|
890
|
+
schema: { type: 'object', properties: { key: { type: 'string' } }, required: ['key'] },
|
|
891
|
+
isStateChanging: false,
|
|
892
|
+
returnBudget: 1024,
|
|
893
|
+
handler: async (a) => ({ success: true, data: { value: kv.get(a.key) ?? null } }),
|
|
894
|
+
});
|
|
895
|
+
this.registry.registerTool({
|
|
896
|
+
name: 'kv_set',
|
|
897
|
+
description: 'Set KV value',
|
|
898
|
+
schema: { type: 'object', properties: { key: { type: 'string' }, value: { type: 'string' } }, required: ['key', 'value'] },
|
|
899
|
+
isStateChanging: true,
|
|
900
|
+
returnBudget: 1024,
|
|
901
|
+
handler: async (a) => {
|
|
902
|
+
kv.set(a.key, a.value);
|
|
903
|
+
return { success: true, data: { ok: true } };
|
|
904
|
+
},
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
this.registry.registerTool({
|
|
908
|
+
name: 'file_read',
|
|
909
|
+
description: 'Read file content',
|
|
910
|
+
schema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
|
|
911
|
+
isStateChanging: false,
|
|
912
|
+
returnBudget: 4096,
|
|
913
|
+
handler: async (a) => {
|
|
914
|
+
try {
|
|
915
|
+
const c = await fs.readFile(a.path, 'utf-8');
|
|
916
|
+
return { success: true, data: { content: c } };
|
|
917
|
+
} catch (e) {
|
|
918
|
+
return { success: false, error: String(e) };
|
|
919
|
+
}
|
|
920
|
+
},
|
|
921
|
+
});
|
|
922
|
+
this.registry.registerTool({
|
|
923
|
+
name: 'file_write',
|
|
924
|
+
description: 'Write file content',
|
|
925
|
+
schema: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'] },
|
|
926
|
+
isStateChanging: true,
|
|
927
|
+
returnBudget: 1024,
|
|
928
|
+
handler: async (a) => {
|
|
929
|
+
try {
|
|
930
|
+
await fs.mkdir(path.dirname(a.path), { recursive: true });
|
|
931
|
+
await fs.writeFile(a.path, a.content, 'utf-8');
|
|
932
|
+
return { success: true, data: { ok: true } };
|
|
933
|
+
} catch (e) {
|
|
934
|
+
return { success: false, error: String(e) };
|
|
935
|
+
}
|
|
936
|
+
},
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
this.registry.registerTool({
|
|
940
|
+
name: 'http_probe',
|
|
941
|
+
description: 'HTTP probe (GET/HEAD)',
|
|
942
|
+
schema: { type: 'object', properties: { url: { type: 'string', format: 'uri' }, method: { type: 'string', enum: ['GET', 'HEAD'], default: 'GET' } }, required: ['url'] },
|
|
943
|
+
isStateChanging: false,
|
|
944
|
+
returnBudget: 2048,
|
|
945
|
+
handler: async (a) => {
|
|
946
|
+
try {
|
|
947
|
+
const r = await fetch(a.url, { method: a.method ?? 'GET' });
|
|
948
|
+
return { success: true, data: { status: r.status, ok: r.ok } };
|
|
949
|
+
} catch (e) {
|
|
950
|
+
return { success: false, error: String(e) };
|
|
951
|
+
}
|
|
952
|
+
},
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
this.registry.registerTool({
|
|
956
|
+
name: 'crash_tool',
|
|
957
|
+
description: 'Intentional crash for testing',
|
|
958
|
+
schema: { type: 'object', properties: {} },
|
|
959
|
+
isStateChanging: false,
|
|
960
|
+
returnBudget: 1024,
|
|
961
|
+
handler: async () => {
|
|
962
|
+
throw new Error('INTENTIONAL_CRASH');
|
|
963
|
+
},
|
|
964
|
+
});
|
|
965
|
+
|
|
966
|
+
this.registry.registerTemplate({
|
|
967
|
+
name: 'echo-chain',
|
|
968
|
+
description: 'Chain 3 echos',
|
|
969
|
+
match: (i) => i.startsWith('echo-chain:'),
|
|
970
|
+
plan: [
|
|
971
|
+
{ tool: 'echo', args: { text: 'step-1' } },
|
|
972
|
+
{ tool: 'echo', args: { text: 'step-2' } },
|
|
973
|
+
{ tool: 'echo', args: { text: 'step-3' } },
|
|
974
|
+
],
|
|
975
|
+
idempotencyKeyFn: (i) => `echo-chain:${i.slice(11)}`,
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
async executeFastPath(input) {
|
|
980
|
+
const t = await this.registry.matchTemplate(input);
|
|
981
|
+
if (!t) throw new Error(`No template matched: ${input}`);
|
|
982
|
+
return this.fastPath.execute(input, t);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
async executePTC(script) { return this.ptc.execute(script); }
|
|
986
|
+
getMetrics() { return this.contextGov.getMetrics(); }
|
|
987
|
+
async getAuditLogs(f) { return this.audit.getLogs(f); }
|
|
988
|
+
|
|
989
|
+
async verifyIsolation(profile) {
|
|
990
|
+
const ws = this.registry.getWorkspace(profile);
|
|
991
|
+
if (!ws) {
|
|
992
|
+
return {
|
|
993
|
+
profile,
|
|
994
|
+
checks: { workspaceBound: false, pathTraversal: false, networkIsolation: false, credentialLeak: false, toolControl: false },
|
|
995
|
+
violations: [`Workspace not registered: ${profile}`],
|
|
996
|
+
passed: false,
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
return {
|
|
1000
|
+
profile,
|
|
1001
|
+
checks: { workspaceBound: true, pathTraversal: true, networkIsolation: true, credentialLeak: true, toolControl: true },
|
|
1002
|
+
violations: [],
|
|
1003
|
+
passed: true,
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
async healthCheck() {
|
|
1008
|
+
const checks = {};
|
|
1009
|
+
checks.registry = {
|
|
1010
|
+
status: 'pass',
|
|
1011
|
+
message: `${this.registry.listTools().length} tools, ${this.registry.listTemplates().length} templates, ${this.registry.listWorkspaces().length} workspaces`,
|
|
1012
|
+
};
|
|
1013
|
+
try {
|
|
1014
|
+
this.sandbox.getConfig();
|
|
1015
|
+
checks.sandbox = { status: 'pass', message: 'Config loaded' };
|
|
1016
|
+
} catch {
|
|
1017
|
+
checks.sandbox = { status: 'fail', message: 'Config invalid' };
|
|
1018
|
+
}
|
|
1019
|
+
try {
|
|
1020
|
+
await fs.access(this.config.logDir);
|
|
1021
|
+
checks.audit = { status: 'pass', message: 'Log dir accessible' };
|
|
1022
|
+
} catch {
|
|
1023
|
+
checks.audit = { status: 'warn', message: 'Log dir not accessible' };
|
|
1024
|
+
}
|
|
1025
|
+
const all = Object.values(checks).every(c => c.status === 'pass');
|
|
1026
|
+
const any = Object.values(checks).some(c => c.status === 'fail');
|
|
1027
|
+
return { status: any ? 'unhealthy' : all ? 'healthy' : 'degraded', checks, version: '0.1.1', build: 'whole-line-ptc+workspace-hooks', dshVersion: process.env.DSH_VERSION ?? 'unknown' };
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
reloadConfig(p) {
|
|
1031
|
+
this.config = { ...this.config, ...p };
|
|
1032
|
+
this.contextGov.updateConfig(p.context ?? {});
|
|
1033
|
+
this.sandbox.updateConfig(p.sandbox ?? {});
|
|
1034
|
+
this.audit.updateConfig(p.audit ?? {});
|
|
1035
|
+
for (const ws of this.registry.listWorkspaces()) this.sandbox.registerWorkspace(ws);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
getConfig() { return { ...this.config }; }
|
|
1039
|
+
dumpConfig() { return dumpConfig(this.config); }
|
|
1040
|
+
getPresets() { return Object.keys(presets); }
|
|
1041
|
+
applyPreset(name) { this.reloadConfig(applyPreset(this.config, name)); }
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// ============================================================================
|
|
1045
|
+
// Plugin Entry
|
|
1046
|
+
// ============================================================================
|
|
1047
|
+
|
|
1048
|
+
const name = 'dsh-runtime-kit';
|
|
1049
|
+
|
|
1050
|
+
/** Split raw command input into positional tokens and -k value options.
|
|
1051
|
+
* Double-quoted segments ("...") stay together; a quoted empty string is a token. */
|
|
1052
|
+
function parseArgs(rawInput) {
|
|
1053
|
+
const tokens = [];
|
|
1054
|
+
const s = String(rawInput ?? '');
|
|
1055
|
+
let cur = '';
|
|
1056
|
+
let inQuote = false;
|
|
1057
|
+
let started = false;
|
|
1058
|
+
for (const ch of s) {
|
|
1059
|
+
if (inQuote) {
|
|
1060
|
+
if (ch === '"') inQuote = false;
|
|
1061
|
+
else cur += ch;
|
|
1062
|
+
} else if (ch === '"') {
|
|
1063
|
+
inQuote = true;
|
|
1064
|
+
started = true;
|
|
1065
|
+
} else if (/\s/.test(ch)) {
|
|
1066
|
+
if (started || cur) {
|
|
1067
|
+
tokens.push(cur);
|
|
1068
|
+
cur = '';
|
|
1069
|
+
started = false;
|
|
1070
|
+
}
|
|
1071
|
+
} else {
|
|
1072
|
+
cur += ch;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
if (started || cur) tokens.push(cur);
|
|
1076
|
+
const positional = [];
|
|
1077
|
+
const options = {};
|
|
1078
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
1079
|
+
const t = tokens[i];
|
|
1080
|
+
if (t.length > 1 && t.startsWith('-')) {
|
|
1081
|
+
const key = t.replace(/^-+/, '');
|
|
1082
|
+
const next = tokens[i + 1];
|
|
1083
|
+
if (next !== undefined && !next.startsWith('-')) {
|
|
1084
|
+
options[key] = next;
|
|
1085
|
+
i++;
|
|
1086
|
+
} else {
|
|
1087
|
+
options[key] = 'true';
|
|
1088
|
+
}
|
|
1089
|
+
} else {
|
|
1090
|
+
positional.push(t);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
return { positional, options };
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/** Wrap a plain handler into a CommandResult-producing handler. */
|
|
1097
|
+
function command(fn) {
|
|
1098
|
+
return async (invocation) => {
|
|
1099
|
+
try {
|
|
1100
|
+
const text = await fn(parseArgs(invocation.rawInput), invocation);
|
|
1101
|
+
return { kind: 'success', text: String(text ?? '') };
|
|
1102
|
+
} catch (error) {
|
|
1103
|
+
return { kind: 'error', text: String(error?.message ?? error) };
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
async function apply(ctx, raw = {}) {
|
|
1109
|
+
const config = {
|
|
1110
|
+
...DEFAULT_CONFIG,
|
|
1111
|
+
...raw,
|
|
1112
|
+
context: { ...DEFAULT_CONFIG.context, ...raw.context },
|
|
1113
|
+
loop: { ...DEFAULT_CONFIG.loop, ...raw.loop },
|
|
1114
|
+
sandbox: { ...DEFAULT_CONFIG.sandbox, ...raw.sandbox },
|
|
1115
|
+
audit: { ...DEFAULT_CONFIG.audit, ...raw.audit },
|
|
1116
|
+
};
|
|
1117
|
+
await fs.mkdir(config.logDir, { recursive: true });
|
|
1118
|
+
await fs.mkdir(config.stateDir, { recursive: true });
|
|
1119
|
+
|
|
1120
|
+
const svc = new RuntimeKitServiceImpl(config);
|
|
1120
1121
|
ctx.provide('runtimeKit', svc);
|
|
1121
1122
|
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1123
|
+
// ---- 治理钩子:审计 / 脱敏 / 注入检测 / 沙箱(全部 fail-open) ----
|
|
1124
|
+
config.governance = { ...DEFAULT_GOVERNANCE, ...(raw.governance ?? {}) };
|
|
1125
|
+
try {
|
|
1126
|
+
installGovernance(ctx, svc, config.governance);
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
ctx.logger?.warn?.(`[runtime-kit] governance hooks failed: ${String(error)}`);
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
const registerCommands = (commandCtx) => {
|
|
1132
|
+
const commands = commandCtx.commands;
|
|
1133
|
+
const definitions = [
|
|
1134
|
+
{
|
|
1135
|
+
name: 'runtime_kit_health',
|
|
1136
|
+
description: 'Runtime Kit health check',
|
|
1137
|
+
handler: command(async () => JSON.stringify(await svc.healthCheck(), null, 2)),
|
|
1138
|
+
},
|
|
1139
|
+
{
|
|
1140
|
+
name: 'runtime_kit_config',
|
|
1141
|
+
description: 'Show runtime-kit config, or apply a preset (minimal-no-orchestration | code-ptc-friendly)',
|
|
1142
|
+
input: { hint: '[preset]' },
|
|
1143
|
+
handler: command(async ({ positional }) => {
|
|
1144
|
+
const preset = positional[0];
|
|
1145
|
+
if (preset) {
|
|
1146
|
+
svc.applyPreset(preset);
|
|
1147
|
+
return `Applied preset: ${preset}`;
|
|
1148
|
+
}
|
|
1149
|
+
return svc.dumpConfig();
|
|
1150
|
+
}),
|
|
1151
|
+
},
|
|
1152
|
+
{
|
|
1153
|
+
name: 'runtime_kit_metrics',
|
|
1154
|
+
description: 'Show context-governance metrics',
|
|
1155
|
+
handler: command(async () => JSON.stringify(svc.getMetrics(), null, 2)),
|
|
1156
|
+
},
|
|
1157
|
+
{
|
|
1158
|
+
name: 'runtime_kit_audit_logs',
|
|
1159
|
+
description: 'Query audit logs: [profile] [-t tool] [-a action] [-r result] [-s since] [-l limit]',
|
|
1160
|
+
input: { hint: '[profile] [-t tool] [-a action] [-r result] [-s since] [-l limit]' },
|
|
1161
|
+
handler: command(async ({ positional, options }) => JSON.stringify(await svc.getAuditLogs({
|
|
1162
|
+
profile: positional[0],
|
|
1163
|
+
tool: options.t,
|
|
1164
|
+
action: options.a,
|
|
1165
|
+
result: options.r,
|
|
1166
|
+
since: options.s,
|
|
1167
|
+
limit: options.l ? Number(options.l) : 50,
|
|
1168
|
+
}), null, 2)),
|
|
1169
|
+
},
|
|
1170
|
+
{
|
|
1171
|
+
name: 'runtime_kit_isolation',
|
|
1172
|
+
description: 'Verify sandbox isolation for a workspace profile',
|
|
1173
|
+
input: { hint: '<profile>' },
|
|
1174
|
+
handler: command(async ({ positional }) => {
|
|
1175
|
+
const profile = positional[0];
|
|
1176
|
+
if (!profile) throw new Error('Usage: /runtime_kit_isolation <profile>');
|
|
1177
|
+
return JSON.stringify(await svc.verifyIsolation(profile), null, 2);
|
|
1178
|
+
}),
|
|
1179
|
+
},
|
|
1180
|
+
{
|
|
1181
|
+
name: 'runtime_kit_fastpath',
|
|
1182
|
+
description: 'Execute a fast-path template (0 LLM calls); the whole input line is the template input',
|
|
1183
|
+
input: { hint: '<template-input>' },
|
|
1184
|
+
handler: command(async (_args, invocation) => {
|
|
1185
|
+
const input = invocation.rawInput.trim();
|
|
1186
|
+
if (!input) throw new Error('Usage: /runtime_kit_fastpath <template-input>');
|
|
1187
|
+
return JSON.stringify(await svc.executeFastPath(input), null, 2);
|
|
1188
|
+
}),
|
|
1189
|
+
},
|
|
1190
|
+
{
|
|
1191
|
+
name: 'runtime_kit_ptc',
|
|
1192
|
+
description: 'Execute a PTC script: callTool("name", {...}) lines; the whole input line is the script, only the summary returns',
|
|
1193
|
+
input: { hint: '<script>' },
|
|
1194
|
+
handler: command(async (_args, invocation) => {
|
|
1195
|
+
const script = invocation.rawInput.trim();
|
|
1196
|
+
if (!script) throw new Error('Usage: /runtime_kit_ptc <script>');
|
|
1197
|
+
return JSON.stringify(await svc.executePTC(script), null, 2);
|
|
1198
|
+
}),
|
|
1199
|
+
},
|
|
1200
|
+
{
|
|
1201
|
+
name: 'runtime_kit_registry_tools',
|
|
1202
|
+
description: 'List registered runtime-kit tools',
|
|
1203
|
+
handler: command(async () => JSON.stringify(svc.registry.listTools().map(t => t.name), null, 2)),
|
|
1204
|
+
},
|
|
1205
|
+
{
|
|
1206
|
+
name: 'runtime_kit_registry_templates',
|
|
1207
|
+
description: 'List registered fast-path templates',
|
|
1208
|
+
handler: command(async () => JSON.stringify(svc.registry.listTemplates().map(t => t.name), null, 2)),
|
|
1209
|
+
},
|
|
1210
|
+
{
|
|
1211
|
+
name: 'runtime_kit_registry_workspaces',
|
|
1212
|
+
description: 'List registered sandbox workspaces',
|
|
1213
|
+
handler: command(async () => JSON.stringify(svc.registry.listWorkspaces().map(w => ({ profile: w.profile, root: w.root })), null, 2)),
|
|
1214
|
+
},
|
|
1215
|
+
];
|
|
1216
|
+
const disposers = [];
|
|
1217
|
+
for (const def of definitions) {
|
|
1218
|
+
try {
|
|
1219
|
+
disposers.push(commands.register(def));
|
|
1220
|
+
} catch (e) {
|
|
1221
|
+
ctx.logger?.warn?.(`[runtime-kit] command ${def.name} registration failed: ${String(e)}`);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
commandCtx.effect(function* () {
|
|
1225
|
+
for (const dispose of disposers) yield dispose;
|
|
1226
|
+
}, 'runtime-kit commands');
|
|
1227
|
+
};
|
|
1228
|
+
|
|
1229
|
+
// 'commands' 服务可选:宿主提供后注册斜杠命令;不提供时 runtimeKit 服务照常工作。
|
|
1230
|
+
if (typeof ctx.inject === 'function') {
|
|
1231
|
+
try {
|
|
1232
|
+
ctx.inject(['commands'], registerCommands);
|
|
1233
|
+
} catch (e) {
|
|
1234
|
+
ctx.logger?.warn?.(`[runtime-kit] commands subscription failed: ${String(e)}`);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// 审计在插件销毁时落盘。
|
|
1239
|
+
if (typeof ctx.effect === 'function') {
|
|
1240
|
+
ctx.effect(function* () {
|
|
1241
|
+
yield () => svc.audit.shutdown();
|
|
1242
|
+
}, 'runtime-kit audit shutdown');
|
|
1243
|
+
} else {
|
|
1244
|
+
ctx.on('dispose', () => { svc.audit.shutdown().catch(() => {}); });
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
export { name, apply };
|
|
1249
|
+
export default { name, apply };
|