@leiyi-works/dsh-session-tmpdir 0.7.0 → 0.8.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 +190 -187
- package/index.js +2340 -2178
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,2178 +1,2340 @@
|
|
|
1
|
-
import { existsSync, statSync } from 'node:fs'
|
|
2
|
-
import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
3
|
-
import { homedir, tmpdir } from 'node:os'
|
|
4
|
-
import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Per-session task temp folder + orphan cleanup + workspace-root long-term guard.
|
|
8
|
-
*
|
|
9
|
-
* Every session gets `<working directory>/<rootDirName>/<sanitized session title>/`.
|
|
10
|
-
* The folder is created on `session/created` when a title already exists, and on the
|
|
11
|
-
* first `session/title` commit. Later title changes (user rename or a regenerated
|
|
12
|
-
* auto title) rename the folder in place. A marker file inside the folder records the
|
|
13
|
-
* owning session id, so the mapping survives plugin/Host restarts without a state file.
|
|
14
|
-
*
|
|
15
|
-
* Two kinds of writes are governed (v0.5):
|
|
16
|
-
* 1. scratch artifacts (anything under `<rootDirName>/`) — always allowed, never asks;
|
|
17
|
-
* 2. long-term artifacts (everything else inside the workspace) — only allowed under a
|
|
18
|
-
* directory the session has registered through `longterm_approve`, which the model
|
|
19
|
-
* may only call after the user picked a location (a multiple-choice question) or
|
|
20
|
-
* after the task itself named that location. Root-level new files are always denied
|
|
21
|
-
* unless explicitly allow-listed (config `allowRootFiles`).
|
|
22
|
-
* This makes "silently invent a root folder for long-term docs" impossible: the write is
|
|
23
|
-
* refused and the model is told to ask the user first, and to fall back to the temp
|
|
24
|
-
* folder when the user declines.
|
|
25
|
-
*
|
|
26
|
-
* v0.7 closes the write channels that used to bypass the guard:
|
|
27
|
-
* - every call is classified by capability (`toolWritePlan`): `write`/`edit`, shell
|
|
28
|
-
* tools, code-execution tools (`python`, `node`, …), delivery tools (`publish`) and
|
|
29
|
-
* unknown tools that declare path arguments; `present` is display-only;
|
|
30
|
-
* - destinations outside the workspace are classified as well — DSH's own home,
|
|
31
|
-
* caches and the OS temp directory are allowed, anything else is long-term
|
|
32
|
-
* (`outsideAllow` extends that list);
|
|
33
|
-
* - shell parsing is platform aware (drive paths on Windows, `/`-rooted paths on
|
|
34
|
-
* HarmonyOS/POSIX Hosts) and covers POSIX create verbs;
|
|
35
|
-
* - `longterm_approve` may register a directory outside the workspace (never a
|
|
36
|
-
* filesystem root or the home directory itself).
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
* -
|
|
47
|
-
*
|
|
48
|
-
* -
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* -
|
|
54
|
-
*
|
|
55
|
-
* - every
|
|
56
|
-
*
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
const
|
|
78
|
-
/**
|
|
79
|
-
const
|
|
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
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
const
|
|
113
|
-
/**
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
-
const
|
|
185
|
-
const
|
|
186
|
-
const
|
|
187
|
-
const
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
? c.
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
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
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if (
|
|
323
|
-
if (
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
return
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
export function
|
|
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
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
if (
|
|
378
|
-
if (
|
|
379
|
-
if (
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
if (
|
|
391
|
-
if (
|
|
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
|
-
const
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
if (
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
return
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
/**
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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
|
-
|
|
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
|
-
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
/**
|
|
716
|
-
*
|
|
717
|
-
*
|
|
718
|
-
*
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
if (!
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
if (
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
if (
|
|
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
|
-
for (const
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
}
|
|
866
|
-
return
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
/**
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
const
|
|
890
|
-
const {
|
|
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
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
if (
|
|
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
|
-
}
|
|
972
|
-
|
|
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
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
const
|
|
1062
|
-
|
|
1063
|
-
for (const
|
|
1064
|
-
|
|
1065
|
-
try {
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
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
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
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
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
}
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
const
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
)
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
}
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
async function
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
const
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
const
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
if (
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
}
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
}
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
)
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
}
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
}
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
}
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
}
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
return undefined
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
1
|
+
import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { homedir, tmpdir } from 'node:os'
|
|
4
|
+
import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Per-session task temp folder + orphan cleanup + workspace-root long-term guard.
|
|
8
|
+
*
|
|
9
|
+
* Every session gets `<working directory>/<rootDirName>/<sanitized session title>/`.
|
|
10
|
+
* The folder is created on `session/created` when a title already exists, and on the
|
|
11
|
+
* first `session/title` commit. Later title changes (user rename or a regenerated
|
|
12
|
+
* auto title) rename the folder in place. A marker file inside the folder records the
|
|
13
|
+
* owning session id, so the mapping survives plugin/Host restarts without a state file.
|
|
14
|
+
*
|
|
15
|
+
* Two kinds of writes are governed (v0.5):
|
|
16
|
+
* 1. scratch artifacts (anything under `<rootDirName>/`) — always allowed, never asks;
|
|
17
|
+
* 2. long-term artifacts (everything else inside the workspace) — only allowed under a
|
|
18
|
+
* directory the session has registered through `longterm_approve`, which the model
|
|
19
|
+
* may only call after the user picked a location (a multiple-choice question) or
|
|
20
|
+
* after the task itself named that location. Root-level new files are always denied
|
|
21
|
+
* unless explicitly allow-listed (config `allowRootFiles`).
|
|
22
|
+
* This makes "silently invent a root folder for long-term docs" impossible: the write is
|
|
23
|
+
* refused and the model is told to ask the user first, and to fall back to the temp
|
|
24
|
+
* folder when the user declines.
|
|
25
|
+
*
|
|
26
|
+
* v0.7 closes the write channels that used to bypass the guard:
|
|
27
|
+
* - every call is classified by capability (`toolWritePlan`): `write`/`edit`, shell
|
|
28
|
+
* tools, code-execution tools (`python`, `node`, …), delivery tools (`publish`) and
|
|
29
|
+
* unknown tools that declare path arguments; `present` is display-only;
|
|
30
|
+
* - destinations outside the workspace are classified as well — DSH's own home,
|
|
31
|
+
* caches and the OS temp directory are allowed, anything else is long-term
|
|
32
|
+
* (`outsideAllow` extends that list);
|
|
33
|
+
* - shell parsing is platform aware (drive paths on Windows, `/`-rooted paths on
|
|
34
|
+
* HarmonyOS/POSIX Hosts) and covers POSIX create verbs;
|
|
35
|
+
* - `longterm_approve` may register a directory outside the workspace (never a
|
|
36
|
+
* filesystem root or the home directory itself).
|
|
37
|
+
*
|
|
38
|
+
* v0.8 closes the last leak in the cleanup chain: a folder created under
|
|
39
|
+
* `<rootDirName>/` by a plain `write`/shell/code command (instead of `task_tmpdir`)
|
|
40
|
+
* has no marker, so the sweep treated it as "not ours" and never removed it. While
|
|
41
|
+
* allowing such a write the guard now stamps the target folder with the acting
|
|
42
|
+
* session's id — no guessing, because the guard already knows both the target path and
|
|
43
|
+
* the session.
|
|
44
|
+
*
|
|
45
|
+
* Cleanup (default: 7 days after the owning session is deleted):
|
|
46
|
+
* - once a day every registered workspace's `<rootDirName>` is scanned;
|
|
47
|
+
* - a folder whose session still exists (live or persisted) is always kept;
|
|
48
|
+
* - a folder whose session is gone is stamped `orphanedAt` on first sight;
|
|
49
|
+
* - once `orphanedAt` is older than `orphanCleanupDays`, the folder is deleted.
|
|
50
|
+
* Folders without our marker are never touched.
|
|
51
|
+
*
|
|
52
|
+
* Attachment garbage collection (v0.6), same schedule and grace period:
|
|
53
|
+
* - the Host attachment store (`<DSH_HOME>/attachments`) is content-addressed and never
|
|
54
|
+
* garbage collected, so deleting a conversation used to leave its blobs on disk forever;
|
|
55
|
+
* - every tick the ledger `<DSH_HOME>/data/session-tmpdir-attachments.json` records which
|
|
56
|
+
* attachment ids each stored session references (read through `sessionPersistence`, so
|
|
57
|
+
* no log format is assumed); only a changed revision is re-read;
|
|
58
|
+
* - a session that disappears is stamped `orphanedAt`; after `attachmentCleanupDays` the
|
|
59
|
+
* blobs it alone referenced are deleted (any blob still referenced is always kept);
|
|
60
|
+
* - blobs nobody references and older than the grace period are swept as well, which
|
|
61
|
+
* reclaims the historical leftovers of sessions deleted before this feature existed;
|
|
62
|
+
* - every deletion is appended to `session-tmpdir-attachments-gc.jsonl`, and a blob
|
|
63
|
+
* written within the last hour is never touched.
|
|
64
|
+
*/
|
|
65
|
+
|
|
66
|
+
const MARKER_FILE = '.dsh-task.json'
|
|
67
|
+
const DEFAULT_ROOT = '_tmp'
|
|
68
|
+
const DEFAULT_MAX_NAME = 60
|
|
69
|
+
const DEFAULT_ORPHAN_DAYS = 7
|
|
70
|
+
const DEFAULT_CLEANUP_HOURS = 24
|
|
71
|
+
const STARTUP_CLEANUP_DELAY_MS = 60_000
|
|
72
|
+
const FALLBACK_PREFIX = 'session-'
|
|
73
|
+
const DAY_MS = 86_400_000
|
|
74
|
+
|
|
75
|
+
// ── attachment garbage collection (v0.6) ────────────────────────────────────
|
|
76
|
+
/** Ledger file (under `<DSH_HOME>/data/`) recording which attachments each session used. */
|
|
77
|
+
const ATTACHMENT_LEDGER_FILE = 'session-tmpdir-attachments.json'
|
|
78
|
+
/** Append-only audit log of every attachment the collector deleted. */
|
|
79
|
+
const ATTACHMENT_GC_LOG_FILE = 'session-tmpdir-attachments-gc.jsonl'
|
|
80
|
+
const ATTACHMENT_LEDGER_VERSION = 1
|
|
81
|
+
/** `attachmentId` values look like `sha256:<64 lowercase hex>`. */
|
|
82
|
+
const ATTACHMENT_ID_PATTERN = /^sha256:([0-9a-f]{64})$/i
|
|
83
|
+
/** Never delete a blob written this recently — it may belong to a message not yet persisted. */
|
|
84
|
+
const ATTACHMENT_MIN_AGE_MS = 3_600_000
|
|
85
|
+
/** Upper bound on read pages per session, so one corrupt log cannot hang the sweep. */
|
|
86
|
+
const ATTACHMENT_READ_PAGE_LIMIT = 200
|
|
87
|
+
/** Events per read page: keeps peak memory bounded on very long sessions. */
|
|
88
|
+
const ATTACHMENT_READ_PAGE_SIZE = 500
|
|
89
|
+
/** Tool names whose path arguments create or overwrite a file. */
|
|
90
|
+
const WRITE_TOOL_NAMES = new Set(['write', 'edit', 'multi_edit', 'apply_patch', 'str_replace_editor'])
|
|
91
|
+
/** Tool names that run a shell command (their write targets must be parsed from text). */
|
|
92
|
+
const SHELL_TOOL_NAMES = new Set(['pwsh', 'bash', 'sh', 'zsh', 'shell', 'terminal', 'cmd', 'powershell'])
|
|
93
|
+
/** Tool names that execute code in a Host-embedded runtime; their writes are scanned statically. */
|
|
94
|
+
const CODE_TOOL_NAMES = new Set([
|
|
95
|
+
'python',
|
|
96
|
+
'python3',
|
|
97
|
+
'py',
|
|
98
|
+
'node',
|
|
99
|
+
'run_code',
|
|
100
|
+
'execute_code',
|
|
101
|
+
'code_interpreter',
|
|
102
|
+
'ipython',
|
|
103
|
+
'ruby',
|
|
104
|
+
'perl',
|
|
105
|
+
])
|
|
106
|
+
/** Delivery tools: `publish` (HarmonyOS DSHM) copies a file into a delivery folder; `present` only shows it. */
|
|
107
|
+
const PUBLISH_TOOL_NAMES = new Set(['publish', 'present'])
|
|
108
|
+
/** Argument names that can carry a file or directory target. */
|
|
109
|
+
const PATH_ARG_PATTERN =
|
|
110
|
+
/^(?:file_?paths?|paths?|files?|target|targets|target_?path|destination|dest|dst|dest_?path|to|output|output_?path|output_?dir|out|out_?path|dir|directory|directory_?path|folder|save_?path|save|filename|file_?name|location|locations|download_?dir|upload_?dir)$/i
|
|
111
|
+
/** Source-only path arguments (the read side of a copy/publish). */
|
|
112
|
+
const SOURCE_PATH_ARG_PATTERN = /^(?:source|src|from|origin|input|input_?path|source_?path)$/i
|
|
113
|
+
/** Tool name/description words that indicate a write-capable tool. */
|
|
114
|
+
const WRITE_HINT_PATTERN =
|
|
115
|
+
/\b(?:write|writes|writefile|save|create|export|publish|present|download|upload|copy|move|rename|delete|remove|mkdir|install|render|convert|recalculate|generate|produce|dump|store|merge|split|unzip|unpack|extract|replace|patch|append|edit|output)\b/i
|
|
116
|
+
/** Read-only tool names: skipped even when their description mentions a write in a negation. */
|
|
117
|
+
const READ_ONLY_TOOL_PATTERN = /^(?:read|list|get|show|view|check|status|query|search|find|glob|grep|count|stat)(?:[_\-.]|$)/i
|
|
118
|
+
/** The plugin's own tools must always pass their own guard (approval must not self-lock). */
|
|
119
|
+
const SELF_TOOL_NAMES = new Set(['task_tmpdir', 'longterm_approve', 'tmp_cleanup'])
|
|
120
|
+
/** Windows device names that are never files on disk. */
|
|
121
|
+
const WINDOWS_DEVICE_PATTERN = /^(?:nul|con|prn|aux|clock\$|com[0-9]|lpt[0-9])$/i
|
|
122
|
+
/** `scheme://...` tokens are stripped before shell path scanning (a URL contains `s:/`). */
|
|
123
|
+
const URL_PATTERN = /[A-Za-z][A-Za-z0-9+.\-]*:\/\/[^\s'"`]*/g
|
|
124
|
+
/** File names that are scratch artifacts wherever they land. */
|
|
125
|
+
const TEMP_FILE_PATTERNS = [/^_tmp/i, /^tmp_/i, /\.tmp$/i, /\.temp$/i, /\.part$/i, /^~\$/]
|
|
126
|
+
const DEFAULT_ALLOW_ROOT_PATTERNS = ['dsh-*']
|
|
127
|
+
const DEFAULT_ALLOW_ROOT_FILES = ['.dsh-standing-rules.md']
|
|
128
|
+
const DEFAULT_COMMAND_GUARD = 'deny'
|
|
129
|
+
const DEFAULT_PUBLISH_GUARD = 'deny'
|
|
130
|
+
/** Command text that can create a directory/file; used before scanning for paths (v0.7: POSIX verbs). */
|
|
131
|
+
const CREATE_VERB_PATTERN =
|
|
132
|
+
/\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|Invoke-WebRequest|Invoke-RestMethod|curl|wget|robocopy|git\s+clone|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
|
|
133
|
+
/** Redirection source shared by the global form. */
|
|
134
|
+
const REDIRECT_SOURCE =
|
|
135
|
+
'(?:^|[\\s;&|])(?:>>|\\d?>>?)\\s*(?:"([^"]+)"|\'([^\']+)\'|([^\\s;&|]+))'
|
|
136
|
+
/** Every redirection target in a command (v0.7: all of them, not only the first). */
|
|
137
|
+
const REDIRECT_ALL_PATTERN = new RegExp(REDIRECT_SOURCE, 'g')
|
|
138
|
+
/** Windows absolute path tokens inside a command string (not part of a URL). */
|
|
139
|
+
const WIN_ABS_PATH_PATTERN = /(?<![A-Za-z0-9])([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
|
|
140
|
+
/** POSIX absolute path tokens inside a command string (HarmonyOS/POSIX Hosts). */
|
|
141
|
+
const POSIX_ABS_PATH_PATTERN = /(?:^|[\s'"`(=])(\/(?!\/)[^\s'"`,;|&)}\]<>]+)/g
|
|
142
|
+
/** v0.8 claim-on-write: relative `<rootDirName>/<dir>` mentions in a shell command. */
|
|
143
|
+
const TMP_RELATIVE_PATTERN = /(?:^|[\s'"`(=,;|&])(\.{0,2}[\\/]?_tmp[\\/][^\s'"`,;|&)}\]>]+)/g
|
|
144
|
+
/** v0.8: shell verbs that create a directory (so an exact `<root>/<dir>` target is a folder). */
|
|
145
|
+
const CREATE_DIR_HINT_PATTERN =
|
|
146
|
+
/(?:^|[\s;|&(])(?:mkdir|md|ni)\b|\bNew-Item\b[^|;]*(?:-ItemType\s+Directory|\bDirectory\b)|\bgit\s+clone\b|\bCopy-Item\b[^|;]*-Recurse/i
|
|
147
|
+
/** Pseudo paths that are never created on disk. */
|
|
148
|
+
const DEVICE_PATH_PATTERN = /^\/(?:dev\/(?:null|zero|stdin|stdout|stderr|tty|urandom|random|shm)|proc|sys)(?:\/|$)/
|
|
149
|
+
/** `_tmp`-like directory segments that always mean "scratch". */
|
|
150
|
+
const SCRATCH_SEGMENT_NAMES = new Set(['_tmp'])
|
|
151
|
+
/** Write signals inside a code string (Python/JS/Ruby best-effort static scan). */
|
|
152
|
+
const CODE_WRITE_SIGNAL =
|
|
153
|
+
/(?:open\s*\([^()]*,\s*['"][^'"]*[wax+][^'"]*['"]|\.write_text\s*\(|\.write_bytes\s*\(|shutil\.(?:copy|copy2|copyfile|move|copytree|rmtree)|os\.(?:replace|rename|remove|unlink|mkdir|makedirs|rmdir|removedirs|mknod|symlink|link)|json\.dump\s*\(|pickle\.dump\s*\(|\.to_csv\s*\(|\.to_excel\s*\(|\.to_json\s*\(|\.to_pickle\s*\(|\.to_parquet\s*\(|\.savefig\s*\(|\.save\s*\(|imwrite\s*\(|np\.save\w*\s*\(|writeFile(?:Sync)?\s*\(|appendFile(?:Sync)?\s*\(|createWriteStream\s*\(|writeTextFile\s*\(|fs\.(?:copyFile\w*|rename\w*|unlink\w*|mkdir\w*|rm\w*|writeFile\w*|appendFile\w*)|\.mkdir\w*\s*\(|\.rmdir\w*\s*\(|mkdirSync\s*\()/g
|
|
154
|
+
/** String literals that look like file paths inside code (absolute, or relative with a separator/known extension). */
|
|
155
|
+
const CODE_PATH_LITERAL =
|
|
156
|
+
/(['"])((?:\/[^'"\n]{1,400}|[A-Za-z]:[\\/][^'"\n]{1,400}|\.{1,2}[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+\.(?:md|txt|json|jsonl|csv|tsv|xlsx|docx|pptx|pdf|png|jpe?g|gif|webp|mp4|mov|mp3|wav|html?|xml|ya?ml|zip|tar|gz|py|js|ts|mjs|sh)))\1/g
|
|
157
|
+
/** Distance (chars) within which a write signal and a path literal are treated as one statement. */
|
|
158
|
+
const CODE_SIGNAL_WINDOW = 300
|
|
159
|
+
/** v0.7: Windows desktop vs HarmonyOS/POSIX device. */
|
|
160
|
+
const IS_WINDOWS = process.platform === 'win32'
|
|
161
|
+
|
|
162
|
+
export const name = 'session-task-tmpdir'
|
|
163
|
+
|
|
164
|
+
export const inject = ['sessions', 'sessionTitle', 'workingDirectory', 'systemPrompt', 'tools']
|
|
165
|
+
|
|
166
|
+
/** Strip characters that are illegal in Windows/POSIX directory names and bound the length. */
|
|
167
|
+
export function sanitizeTitle(raw, maxLength = DEFAULT_MAX_NAME) {
|
|
168
|
+
let text = String(raw ?? '')
|
|
169
|
+
.normalize('NFC')
|
|
170
|
+
// eslint-disable-next-line no-control-regex
|
|
171
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '-')
|
|
172
|
+
.replace(/\s+/g, ' ')
|
|
173
|
+
.trim()
|
|
174
|
+
// Windows: names may not end with a dot or space
|
|
175
|
+
text = text.replace(/^[.\s]+|[.\s]+$/g, '')
|
|
176
|
+
if (!text) return ''
|
|
177
|
+
if (text.length > maxLength) text = text.slice(0, maxLength).trim()
|
|
178
|
+
text = text.replace(/^[.\s]+|[.\s]+$/g, '')
|
|
179
|
+
return text === '.' || text === '..' ? '' : text
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function readConfig(config) {
|
|
183
|
+
const c = config && typeof config === 'object' ? config : {}
|
|
184
|
+
const rootDirName = typeof c.rootDirName === 'string' && c.rootDirName.trim() ? c.rootDirName.trim() : DEFAULT_ROOT
|
|
185
|
+
const includeSubagents = c.includeSubagents === true
|
|
186
|
+
const maxNameLength = Number.isInteger(c.maxNameLength) && c.maxNameLength > 0 ? c.maxNameLength : DEFAULT_MAX_NAME
|
|
187
|
+
const orphanCleanupDays = Number.isFinite(c.orphanCleanupDays) && c.orphanCleanupDays >= 0 ? c.orphanCleanupDays : DEFAULT_ORPHAN_DAYS
|
|
188
|
+
const cleanupIntervalHours = Number.isFinite(c.cleanupIntervalHours) && c.cleanupIntervalHours >= 1 ? c.cleanupIntervalHours : DEFAULT_CLEANUP_HOURS
|
|
189
|
+
const cleanupDryRun = c.cleanupDryRun === true
|
|
190
|
+
const attachmentCleanup = c.attachmentCleanup !== false
|
|
191
|
+
const attachmentCleanupDays =
|
|
192
|
+
Number.isFinite(c.attachmentCleanupDays) && c.attachmentCleanupDays >= 0 ? c.attachmentCleanupDays : orphanCleanupDays
|
|
193
|
+
const attachmentSweepOrphans = c.attachmentSweepOrphans !== false
|
|
194
|
+
const attachmentsDir =
|
|
195
|
+
typeof c.attachmentsDir === 'string' && c.attachmentsDir.trim() ? c.attachmentsDir.trim() : join(resolveDshHome(), 'attachments')
|
|
196
|
+
const guardWorkspaceRoot = c.guardWorkspaceRoot !== false
|
|
197
|
+
const requireApprovalOutsideTmp = c.requireApprovalOutsideTmp !== false
|
|
198
|
+
const allowRootPatterns = toStringList(c.allowRootPatterns, DEFAULT_ALLOW_ROOT_PATTERNS)
|
|
199
|
+
const allowRootFiles = toStringList(c.allowRootFiles, DEFAULT_ALLOW_ROOT_FILES)
|
|
200
|
+
const commandGuard = ['deny', 'warn', 'off'].includes(c.commandGuard) ? c.commandGuard : DEFAULT_COMMAND_GUARD
|
|
201
|
+
// ── v0.7: write-channel coverage ─────────────────────────────────────────
|
|
202
|
+
/** Guard writes that land outside the workspace (deny | warn | off). */
|
|
203
|
+
const guardOutsideWorkspace = ['deny', 'warn', 'off'].includes(c.guardOutsideWorkspace)
|
|
204
|
+
? c.guardOutsideWorkspace
|
|
205
|
+
: 'deny'
|
|
206
|
+
/** Guard delivery tools (`publish`/`present` with a copy target): deny | warn | off. */
|
|
207
|
+
const publishGuard = ['deny', 'warn', 'off'].includes(c.publishGuard) ? c.publishGuard : DEFAULT_PUBLISH_GUARD
|
|
208
|
+
/** Statically scan code-execution tools (python/node) for file writes. */
|
|
209
|
+
const guardCodeTools = c.guardCodeTools !== false
|
|
210
|
+
/** Also inspect tools the plugin does not know by name, using their schema/description. */
|
|
211
|
+
const guardUnknownTools = c.guardUnknownTools !== false
|
|
212
|
+
/** Extra tool names per channel, appended to the built-in sets. */
|
|
213
|
+
const extraWriteTools = toStringList(c.writeToolNames, [])
|
|
214
|
+
const extraPublishTools = toStringList(c.publishToolNames, [])
|
|
215
|
+
const extraCodeTools = toStringList(c.codeToolNames, [])
|
|
216
|
+
/** Extra absolute directories that may be written outside the workspace (globs). */
|
|
217
|
+
const outsideAllow = toStringList(c.outsideAllow, [])
|
|
218
|
+
/** Base directory used to resolve a relative `publish` target (e.g. HarmonyOS `Download/`). */
|
|
219
|
+
const publishBaseDir = typeof c.publishBaseDir === 'string' && c.publishBaseDir.trim() ? c.publishBaseDir.trim() : undefined
|
|
220
|
+
return {
|
|
221
|
+
rootDirName,
|
|
222
|
+
includeSubagents,
|
|
223
|
+
maxNameLength,
|
|
224
|
+
orphanCleanupDays,
|
|
225
|
+
cleanupIntervalHours,
|
|
226
|
+
cleanupDryRun,
|
|
227
|
+
guardWorkspaceRoot,
|
|
228
|
+
requireApprovalOutsideTmp,
|
|
229
|
+
allowRootPatterns,
|
|
230
|
+
allowRootFiles,
|
|
231
|
+
commandGuard,
|
|
232
|
+
guardOutsideWorkspace,
|
|
233
|
+
publishGuard,
|
|
234
|
+
guardCodeTools,
|
|
235
|
+
guardUnknownTools,
|
|
236
|
+
writeToolNames: [...new Set([...WRITE_TOOL_NAMES, ...extraWriteTools])],
|
|
237
|
+
publishToolNames: [...new Set([...PUBLISH_TOOL_NAMES, ...extraPublishTools])],
|
|
238
|
+
codeToolNames: [...new Set([...CODE_TOOL_NAMES, ...extraCodeTools])],
|
|
239
|
+
shellToolNames: [...SHELL_TOOL_NAMES],
|
|
240
|
+
outsideAllow,
|
|
241
|
+
publishBaseDir,
|
|
242
|
+
attachmentCleanup,
|
|
243
|
+
attachmentCleanupDays,
|
|
244
|
+
attachmentSweepOrphans,
|
|
245
|
+
attachmentsDir,
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Accept a string or an array of strings as a config list, falling back to `fallback`. */
|
|
250
|
+
function toStringList(value, fallback) {
|
|
251
|
+
if (typeof value === 'string' && value.trim()) return [value.trim()]
|
|
252
|
+
if (Array.isArray(value)) {
|
|
253
|
+
const list = value.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
|
|
254
|
+
if (list.length > 0) return list
|
|
255
|
+
}
|
|
256
|
+
return [...fallback]
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Path comparison: case-insensitive on Windows, exact and separator-normalized elsewhere. */
|
|
260
|
+
function samePath(a, b) {
|
|
261
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false
|
|
262
|
+
const normalize = (value) => {
|
|
263
|
+
const text = resolve(value).replace(/[\\/]+$/, '')
|
|
264
|
+
return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
|
|
265
|
+
}
|
|
266
|
+
return normalize(a) === normalize(b)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Reject scratch-file writes that land in the wrong place:
|
|
271
|
+
* temp-looking names directly in the working-directory root, or any file directly
|
|
272
|
+
* under `<cwd>/<rootDirName>/` instead of a session subfolder.
|
|
273
|
+
*
|
|
274
|
+
* @param {string} targetPath the write/edit `file_path` argument (absolute or relative to cwd)
|
|
275
|
+
* @param {string} cwd the session working directory
|
|
276
|
+
* @param {string} [rootDirName] temp root name (default `_tmp`)
|
|
277
|
+
* @returns {string | undefined} denial reason for the tool guard, or undefined to allow
|
|
278
|
+
*/
|
|
279
|
+
export function workspaceRootGuardReason(targetPath, cwd, rootDirName = DEFAULT_ROOT) {
|
|
280
|
+
if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
|
|
281
|
+
if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
|
|
282
|
+
let abs
|
|
283
|
+
try {
|
|
284
|
+
abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
|
|
285
|
+
} catch {
|
|
286
|
+
return undefined
|
|
287
|
+
}
|
|
288
|
+
const name = basename(abs)
|
|
289
|
+
if (!name) return undefined
|
|
290
|
+
if (samePath(dirname(abs), cwd) && TEMP_FILE_PATTERNS.some((pattern) => pattern.test(name))) {
|
|
291
|
+
return (
|
|
292
|
+
`工作区根目录不能放临时文件(${name})。请先调用 task_tmpdir 获取 ` +
|
|
293
|
+
`${rootDirName}/<会话标题>/ 的准确路径,把临时文件写进那个目录。`
|
|
294
|
+
)
|
|
295
|
+
}
|
|
296
|
+
if (samePath(dirname(abs), join(cwd, rootDirName))) {
|
|
297
|
+
return (
|
|
298
|
+
`${rootDirName}/ 根目录不能直接放文件(${name})。请先调用 task_tmpdir,` +
|
|
299
|
+
`把文件写入 ${rootDirName}/<会话标题>/ 子目录。`
|
|
300
|
+
)
|
|
301
|
+
}
|
|
302
|
+
return undefined
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── long-term destination guard (v0.5) ─────────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Normalized path used for comparisons: forward slashes on Windows (case folded),
|
|
309
|
+
* untouched on POSIX where `\` is a legal filename character (v0.7, review M10).
|
|
310
|
+
*/
|
|
311
|
+
function normalizeForCompare(target) {
|
|
312
|
+
const text = resolve(target).replace(/[\\/]+$/, '')
|
|
313
|
+
return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* True when `child` is `parent` or lives inside it (case-insensitive, separator
|
|
318
|
+
* normalized). v0.7: uses `/` on every platform, so the check also works on
|
|
319
|
+
* HarmonyOS/POSIX Hosts where `resolve()` never emits a backslash.
|
|
320
|
+
*/
|
|
321
|
+
export function pathInside(parent, child) {
|
|
322
|
+
if (typeof parent !== 'string' || typeof child !== 'string') return false
|
|
323
|
+
if (!parent.trim() || !child.trim()) return false
|
|
324
|
+
const p = normalizeForCompare(parent)
|
|
325
|
+
const c = normalizeForCompare(child)
|
|
326
|
+
return c === p || c.startsWith(`${p}/`)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** First path segment of `abs` relative to `cwd`, or undefined when not inside `cwd`. */
|
|
330
|
+
export function firstSegmentUnder(cwd, abs) {
|
|
331
|
+
if (typeof cwd !== 'string' || typeof abs !== 'string') return undefined
|
|
332
|
+
const base = resolve(cwd)
|
|
333
|
+
const target = resolve(abs)
|
|
334
|
+
if (!(normalizeForCompare(base) === normalizeForCompare(target) || pathInside(base, target))) return undefined
|
|
335
|
+
if (normalizeForCompare(base) === normalizeForCompare(target)) return ''
|
|
336
|
+
const rest = target.slice(base.replace(/[\\/]+$/, '').length).replace(/^[\\/]+/, '')
|
|
337
|
+
const [first] = rest.split(/[\\/]+/).filter(Boolean)
|
|
338
|
+
return first ?? ''
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Simple case-insensitive glob matcher (`*` and `?` only). */
|
|
342
|
+
export function globMatch(name, patterns) {
|
|
343
|
+
const text = String(name ?? '')
|
|
344
|
+
for (const raw of patterns ?? []) {
|
|
345
|
+
const pattern = String(raw ?? '').trim()
|
|
346
|
+
if (!pattern) continue
|
|
347
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
|
|
348
|
+
try {
|
|
349
|
+
if (new RegExp(`^${escaped}$`, 'i').test(text)) return true
|
|
350
|
+
} catch {
|
|
351
|
+
// an unusable pattern never matches
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return false
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Decide whether a `write`/`edit` target outside the temp root may be written.
|
|
359
|
+
*
|
|
360
|
+
* Rules (v0.5):
|
|
361
|
+
* - under `<cwd>/<rootDirName>/` → allowed (scratch);
|
|
362
|
+
* - under an approved long-term prefix → allowed (session registered it via longterm_approve);
|
|
363
|
+
* - root-level file → allowed only when explicitly allow-listed;
|
|
364
|
+
* - first segment matching allowRootPatterns → allowed (plugin source trees by default);
|
|
365
|
+
* - anything else → denied with the "ask the user first" protocol.
|
|
366
|
+
*
|
|
367
|
+
* @returns {string | undefined} denial reason, or undefined to allow
|
|
368
|
+
*/
|
|
369
|
+
export function longtermGuardReason(targetPath, cwd, options = {}) {
|
|
370
|
+
const {
|
|
371
|
+
rootDirName = DEFAULT_ROOT,
|
|
372
|
+
allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
|
|
373
|
+
allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
|
|
374
|
+
approvedPrefixes = [],
|
|
375
|
+
requireApprovalOutsideTmp = true,
|
|
376
|
+
} = options
|
|
377
|
+
if (!requireApprovalOutsideTmp) return undefined
|
|
378
|
+
if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
|
|
379
|
+
if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
|
|
380
|
+
let abs
|
|
381
|
+
try {
|
|
382
|
+
abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
|
|
383
|
+
} catch {
|
|
384
|
+
return undefined
|
|
385
|
+
}
|
|
386
|
+
const base = resolve(cwd)
|
|
387
|
+
if (!pathInside(base, abs)) return undefined
|
|
388
|
+
const tmpRoot = join(base, rootDirName)
|
|
389
|
+
if (pathInside(tmpRoot, abs)) return undefined
|
|
390
|
+
if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return undefined
|
|
391
|
+
if (samePath(dirname(abs), base)) {
|
|
392
|
+
const name = basename(abs)
|
|
393
|
+
if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) return undefined
|
|
394
|
+
if (globMatch(name, allowRootPatterns)) return undefined
|
|
395
|
+
return (
|
|
396
|
+
`工作区根目录不能新建/修改条目(${name})。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
|
|
397
|
+
`用户同意后用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
|
|
398
|
+
`${rootDirName}/<会话标题>/。`
|
|
399
|
+
)
|
|
400
|
+
}
|
|
401
|
+
const first = firstSegmentUnder(base, abs)
|
|
402
|
+
if (!first) return undefined
|
|
403
|
+
if (globMatch(first, allowRootPatterns)) return undefined
|
|
404
|
+
return (
|
|
405
|
+
`「${first}」不在本次会话已批准的长期落点里。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
|
|
406
|
+
`用户同意后调用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
|
|
407
|
+
`${rootDirName}/<会话标题>/。`
|
|
408
|
+
)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Best-effort guard for shell tools: when a command may create something, scan its
|
|
413
|
+
* literal absolute Windows paths. Any not-yet-existing path inside the workspace that is
|
|
414
|
+
* neither scratch nor approved is denied. Paths that already exist are left alone (they are
|
|
415
|
+
* usually sources for Copy-Item or files being edited) — this keeps false positives low.
|
|
416
|
+
*
|
|
417
|
+
* @returns {string | undefined} denial reason, or undefined to allow
|
|
418
|
+
*/
|
|
419
|
+
export function longtermCommandGuardReason(command, workspaceRoot, options = {}) {
|
|
420
|
+
const {
|
|
421
|
+
rootDirName = DEFAULT_ROOT,
|
|
422
|
+
allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
|
|
423
|
+
allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
|
|
424
|
+
approvedPrefixes = [],
|
|
425
|
+
outsideAllow = [],
|
|
426
|
+
requireApprovalOutsideTmp = true,
|
|
427
|
+
guardOutsideWorkspace = 'deny',
|
|
428
|
+
skipInside = false,
|
|
429
|
+
baseDir,
|
|
430
|
+
pathExists = (target) => existsSync(target),
|
|
431
|
+
platform = process.platform,
|
|
432
|
+
} = options
|
|
433
|
+
if (!requireApprovalOutsideTmp) return undefined
|
|
434
|
+
if (typeof command !== 'string' || command.trim() === '') return undefined
|
|
435
|
+
if (typeof workspaceRoot !== 'string' || workspaceRoot.trim() === '') return undefined
|
|
436
|
+
// v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
|
|
437
|
+
// parsed as one token instead of leaving a second `>` behind. Quoted text such as
|
|
438
|
+
// `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
|
|
439
|
+
const redirectTokens = new Set()
|
|
440
|
+
for (const match of command.matchAll(REDIRECT_ALL_PATTERN)) {
|
|
441
|
+
const token = match[1] ?? match[2] ?? match[3]
|
|
442
|
+
if (!token) continue
|
|
443
|
+
const cleaned = token.replace(/["'`]+$/, '')
|
|
444
|
+
if (!cleaned || /^>+$/.test(cleaned)) continue
|
|
445
|
+
if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
|
|
446
|
+
redirectTokens.add(token)
|
|
447
|
+
}
|
|
448
|
+
const hasRedirect = redirectTokens.size > 0
|
|
449
|
+
if (!hasRedirect && !CREATE_VERB_PATTERN.test(command)) return undefined
|
|
450
|
+
const base = resolve(workspaceRoot)
|
|
451
|
+
const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
|
|
452
|
+
// v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
|
|
453
|
+
// Windows drive-path pattern would otherwise treat as a directory.
|
|
454
|
+
const scanText = command.replace(URL_PATTERN, ' ')
|
|
455
|
+
const pathPattern = platform === 'win32' ? WIN_ABS_PATH_PATTERN : POSIX_ABS_PATH_PATTERN
|
|
456
|
+
const tokens = new Set([...redirectTokens])
|
|
457
|
+
for (const match of scanText.matchAll(pathPattern)) tokens.add(match[1])
|
|
458
|
+
const classifyOptions = {
|
|
459
|
+
rootDirName,
|
|
460
|
+
allowRootPatterns,
|
|
461
|
+
allowRootFiles,
|
|
462
|
+
approvedPrefixes,
|
|
463
|
+
outsideAllow,
|
|
464
|
+
requireApprovalOutsideTmp,
|
|
465
|
+
guardOutsideWorkspace,
|
|
466
|
+
}
|
|
467
|
+
for (const raw of tokens) {
|
|
468
|
+
if (!raw) continue
|
|
469
|
+
const cleaned = String(raw).replace(/["'`]+$/, '')
|
|
470
|
+
let abs
|
|
471
|
+
try {
|
|
472
|
+
const expanded = expandTildePath(cleaned)
|
|
473
|
+
abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
|
|
474
|
+
} catch {
|
|
475
|
+
continue
|
|
476
|
+
}
|
|
477
|
+
if (isDevicePath(abs)) continue
|
|
478
|
+
// v0.8 claim-on-write: report every resolved target so the caller can attribute
|
|
479
|
+
// unmarked `<rootDirName>/<dir>/` folders to the acting session.
|
|
480
|
+
if (typeof options.onTarget === 'function') {
|
|
481
|
+
try {
|
|
482
|
+
options.onTarget(abs)
|
|
483
|
+
} catch {
|
|
484
|
+
// a reporting callback never changes the verdict
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const isRedirectTarget = redirectTokens.has(raw)
|
|
488
|
+
const verdict = classifyWriteTarget(abs, base, classifyOptions)
|
|
489
|
+
if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
|
|
490
|
+
// Existing targets are usually sources of a copy or files being edited; keep the
|
|
491
|
+
// historical low-false-positive behavior — except for redirect targets, which are
|
|
492
|
+
// always written (v0.7 review M6).
|
|
493
|
+
if (!isRedirectTarget && pathExists(abs)) continue
|
|
494
|
+
if (verdict.kind === 'outside') {
|
|
495
|
+
if (guardOutsideWorkspace === 'warn') {
|
|
496
|
+
console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
|
|
497
|
+
continue
|
|
498
|
+
}
|
|
499
|
+
return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
|
|
500
|
+
}
|
|
501
|
+
// inside the workspace but not approved / not scratch
|
|
502
|
+
if (skipInside) continue
|
|
503
|
+
const first = firstSegmentUnder(base, abs)
|
|
504
|
+
if (samePath(dirname(abs), base)) {
|
|
505
|
+
return (
|
|
506
|
+
`命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
|
|
507
|
+
`同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
|
|
508
|
+
)
|
|
509
|
+
}
|
|
510
|
+
return (
|
|
511
|
+
`命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
|
|
512
|
+
`若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
|
|
513
|
+
`临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
|
|
514
|
+
)
|
|
515
|
+
}
|
|
516
|
+
return undefined
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ── v0.7: write-channel resolution (capability based, not a fixed tool list) ──
|
|
520
|
+
|
|
521
|
+
/** Expand a leading `~` to the current user's home directory. */
|
|
522
|
+
function expandTildePath(value) {
|
|
523
|
+
if (typeof value !== 'string' || !value.trim()) return value
|
|
524
|
+
const text = value.trim()
|
|
525
|
+
if (text === '~') return homedir()
|
|
526
|
+
if (text.startsWith('~/') || text.startsWith('~\\')) return join(homedir(), text.slice(2))
|
|
527
|
+
return text
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Forward-slash, lower-cased (on Windows) form used by path globs. */
|
|
531
|
+
function slashedPath(value) {
|
|
532
|
+
const text = String(value).replace(/\\/g, '/').replace(/\/+$/, '')
|
|
533
|
+
return IS_WINDOWS ? text.toLowerCase() : text
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** True for `/dev/null`-style pseudo paths and Windows device names (never on disk). */
|
|
537
|
+
function isDevicePath(abs) {
|
|
538
|
+
if (typeof abs !== 'string') return false
|
|
539
|
+
if (DEVICE_PATH_PATTERN.test(String(abs).replace(/\\/g, '/'))) return true
|
|
540
|
+
if (!IS_WINDOWS) return false
|
|
541
|
+
const name = basename(abs).trim()
|
|
542
|
+
if (/^\$null$/i.test(name)) return true
|
|
543
|
+
return WINDOWS_DEVICE_PATTERN.test(name.replace(/\$\d*$/, ''))
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** True when a path lives under the OS temp directory (`os.tmpdir()`, `/tmp`, `/var/tmp`). */
|
|
547
|
+
export function isSystemTempPath(abs) {
|
|
548
|
+
if (typeof abs !== 'string' || !abs.trim()) return false
|
|
549
|
+
const tempDirs = [tmpdir(), '/tmp', '/var/tmp', '/dev/shm']
|
|
550
|
+
return tempDirs.some((dir) => dir && pathInside(dir, abs))
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** True when any path segment is a scratch root (`_tmp`, configured root name). */
|
|
554
|
+
export function isScratchPath(targetPath, rootDirName = DEFAULT_ROOT) {
|
|
555
|
+
if (typeof targetPath !== 'string' || !targetPath.trim()) return false
|
|
556
|
+
const segments = String(targetPath)
|
|
557
|
+
.replace(/\\/g, '/')
|
|
558
|
+
.split('/')
|
|
559
|
+
.filter(Boolean)
|
|
560
|
+
const names = new Set([...SCRATCH_SEGMENT_NAMES].map((name) => name.toLowerCase()))
|
|
561
|
+
if (typeof rootDirName === 'string' && rootDirName.trim()) names.add(rootDirName.trim().toLowerCase())
|
|
562
|
+
return segments.some((segment) => names.has(segment.toLowerCase()))
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Glob match for absolute path patterns: `*` stays inside one segment, `**` crosses
|
|
567
|
+
* segments. Patterns may start with `~`; a pattern ending in `/**` also matches the
|
|
568
|
+
* directory itself. Used for the `outsideAllow` list.
|
|
569
|
+
*/
|
|
570
|
+
export function pathGlobMatch(targetPath, patterns = []) {
|
|
571
|
+
if (typeof targetPath !== 'string' || !targetPath.trim()) return false
|
|
572
|
+
let target
|
|
573
|
+
try {
|
|
574
|
+
target = slashedPath(resolve(expandTildePath(targetPath)))
|
|
575
|
+
} catch {
|
|
576
|
+
return false
|
|
577
|
+
}
|
|
578
|
+
for (const raw of patterns ?? []) {
|
|
579
|
+
const text = String(raw ?? '').trim()
|
|
580
|
+
if (!text) continue
|
|
581
|
+
let pattern
|
|
582
|
+
try {
|
|
583
|
+
pattern = slashedPath(resolve(expandTildePath(text)))
|
|
584
|
+
} catch {
|
|
585
|
+
continue
|
|
586
|
+
}
|
|
587
|
+
if (target === pattern) return true
|
|
588
|
+
if (pattern.endsWith('/**') && target === pattern.slice(0, -3)) return true
|
|
589
|
+
const regex = pattern
|
|
590
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
591
|
+
.replace(/\*\*/g, '\u0000')
|
|
592
|
+
.replace(/\*/g, '[^/]*')
|
|
593
|
+
.replace(/\?/g, '[^/]')
|
|
594
|
+
.replace(/\u0000\//g, '(?:.*/)?')
|
|
595
|
+
.replace(/\u0000/g, '.*')
|
|
596
|
+
try {
|
|
597
|
+
if (new RegExp(`^${regex}$`).test(target)) return true
|
|
598
|
+
} catch {
|
|
599
|
+
// an unusable pattern never matches
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return false
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Directory + `/**` so `pathGlobMatch` covers everything inside it. */
|
|
606
|
+
function dirGlob(directory) {
|
|
607
|
+
const clean = String(directory ?? '').replace(/[\\/]+$/, '')
|
|
608
|
+
return clean ? `${clean}/**` : clean
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Directories outside the workspace that tools may write without asking: DSH's own
|
|
613
|
+
* home (configuration, credentials, plugin data), caches and the OS temp directory.
|
|
614
|
+
* Everything else outside the workspace is a long-term destination (v0.7).
|
|
615
|
+
*/
|
|
616
|
+
export function defaultOutsideAllow(dshHome) {
|
|
617
|
+
const home = homedir()
|
|
618
|
+
const directories = [
|
|
619
|
+
join(home, '.dsh'),
|
|
620
|
+
join(home, '.cache'),
|
|
621
|
+
join(home, '.npm'),
|
|
622
|
+
join(home, '.config'),
|
|
623
|
+
join(home, '.local', 'share'),
|
|
624
|
+
join(home, '.flova'),
|
|
625
|
+
tmpdir(),
|
|
626
|
+
]
|
|
627
|
+
if (typeof dshHome === 'string' && dshHome.trim()) directories.push(dshHome)
|
|
628
|
+
if (!IS_WINDOWS) directories.push('/tmp', '/var/tmp', '/dev/shm', '/run/user', '/data/local/tmp', '/storage/emulated/0/Android/data')
|
|
629
|
+
return directories.filter(Boolean).map(dirGlob)
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Classify one write target for the long-term guard.
|
|
634
|
+
*
|
|
635
|
+
* @returns {{kind:'allowed'|'inside-longterm'|'outside'|'skip', abs?:string, reason?:string, scratch?:boolean}}
|
|
636
|
+
* `inside-longterm` = inside the workspace but not under `_tmp`/an approved prefix;
|
|
637
|
+
* `outside` = outside the workspace and not in `outsideAllow`.
|
|
638
|
+
*/
|
|
639
|
+
export function classifyWriteTarget(targetPath, cwd, options = {}) {
|
|
640
|
+
const {
|
|
641
|
+
rootDirName = DEFAULT_ROOT,
|
|
642
|
+
allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
|
|
643
|
+
allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
|
|
644
|
+
approvedPrefixes = [],
|
|
645
|
+
outsideAllow = [],
|
|
646
|
+
requireApprovalOutsideTmp = true,
|
|
647
|
+
guardOutsideWorkspace = 'deny',
|
|
648
|
+
baseDir: baseDirOption,
|
|
649
|
+
} = options
|
|
650
|
+
if (!requireApprovalOutsideTmp) return { kind: 'allowed' }
|
|
651
|
+
if (typeof targetPath !== 'string' || !targetPath.trim()) return { kind: 'skip' }
|
|
652
|
+
const base = typeof cwd === 'string' && cwd.trim() ? resolve(cwd) : undefined
|
|
653
|
+
const resolveBase = typeof baseDirOption === 'string' && baseDirOption.trim() ? resolve(baseDirOption) : base
|
|
654
|
+
if (!base && !resolveBase) return { kind: 'skip' }
|
|
655
|
+
let abs
|
|
656
|
+
try {
|
|
657
|
+
const expanded = expandTildePath(targetPath)
|
|
658
|
+
abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase ?? base, expanded)
|
|
659
|
+
} catch {
|
|
660
|
+
return { kind: 'skip' }
|
|
661
|
+
}
|
|
662
|
+
if (isDevicePath(abs)) return { kind: 'allowed', abs }
|
|
663
|
+
// v0.7 (review M8): a `_tmp` segment only counts as scratch inside the workspace or
|
|
664
|
+
// under the OS temp directory — `Desktop/_tmp/x.md` is still a long-term write.
|
|
665
|
+
if (isScratchPath(abs, rootDirName) && ((base && pathInside(base, abs)) || isSystemTempPath(abs))) {
|
|
666
|
+
return { kind: 'allowed', abs, scratch: true }
|
|
667
|
+
}
|
|
668
|
+
if (base && pathInside(base, abs)) {
|
|
669
|
+
const reason = longtermGuardReason(abs, base, {
|
|
670
|
+
rootDirName,
|
|
671
|
+
allowRootPatterns,
|
|
672
|
+
allowRootFiles,
|
|
673
|
+
approvedPrefixes,
|
|
674
|
+
requireApprovalOutsideTmp,
|
|
675
|
+
})
|
|
676
|
+
return reason ? { kind: 'inside-longterm', abs, reason } : { kind: 'allowed', abs }
|
|
677
|
+
}
|
|
678
|
+
if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return { kind: 'allowed', abs }
|
|
679
|
+
if (pathGlobMatch(abs, outsideAllow)) return { kind: 'allowed', abs }
|
|
680
|
+
if (guardOutsideWorkspace === 'off') return { kind: 'allowed', abs }
|
|
681
|
+
return { kind: 'outside', abs }
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Denial reason for a long-term destination outside the workspace. */
|
|
685
|
+
export function outsideWriteDenialReason(abs, options = {}) {
|
|
686
|
+
const { rootDirName = DEFAULT_ROOT, action = '写入' } = options
|
|
687
|
+
return (
|
|
688
|
+
`「${basename(abs)}」在工作区之外(${abs}),属于长期保存位置:${action}前必须先征求用户意见——` +
|
|
689
|
+
`用 ask_user_question 问用户;用户同意后用 longterm_approve 登记该目录再${action};` +
|
|
690
|
+
`用户不同意或属于临时产物 → 用 task_tmpdir 写到 ${rootDirName}/<会话标题>/。`
|
|
691
|
+
)
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** Argument names that name a write destination strongly (bare file names are allowed). */
|
|
695
|
+
const STRONG_TARGET_KEYS = new Set([
|
|
696
|
+
'target',
|
|
697
|
+
'targets',
|
|
698
|
+
'target_path',
|
|
699
|
+
'destination',
|
|
700
|
+
'dest',
|
|
701
|
+
'dst',
|
|
702
|
+
'dest_path',
|
|
703
|
+
'to',
|
|
704
|
+
'output',
|
|
705
|
+
'output_path',
|
|
706
|
+
'output_dir',
|
|
707
|
+
'out',
|
|
708
|
+
'out_path',
|
|
709
|
+
'save_path',
|
|
710
|
+
'filename',
|
|
711
|
+
])
|
|
712
|
+
/** "Looks like a file name" hint used only for strongly-named destination arguments. */
|
|
713
|
+
const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9]{1,8}$/
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* True when a string value looks like a filesystem path. Enum-like values
|
|
717
|
+
* (`this_session`, `@e3`, `#submit`, npm package ids, URLs) are rejected on purpose
|
|
718
|
+
* so business arguments are not mistaken for write targets (v0.7 review M1/S2/S3).
|
|
719
|
+
*/
|
|
720
|
+
export function looksLikePathValue(value) {
|
|
721
|
+
if (typeof value !== 'string') return false
|
|
722
|
+
const text = value.trim()
|
|
723
|
+
if (!text || text.length > 512) return false
|
|
724
|
+
if (/[\r\n]/.test(text)) return false
|
|
725
|
+
URL_PATTERN.lastIndex = 0
|
|
726
|
+
if (URL_PATTERN.test(text)) return false
|
|
727
|
+
if (/^[@#$]/.test(text)) return false
|
|
728
|
+
if (/^@[\w.-]+\//.test(text)) return false
|
|
729
|
+
if (/^[A-Za-z]:/.test(text)) return true
|
|
730
|
+
if (/^~[/\\]/.test(text)) return true
|
|
731
|
+
if (/^\.{1,2}[/\\]/.test(text)) return true
|
|
732
|
+
if (/[\\/]/.test(text)) return true
|
|
733
|
+
return false
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Top-level path targets of a tool call.
|
|
738
|
+
*
|
|
739
|
+
* v0.7 (review M1): only top-level arguments are inspected — nested business objects
|
|
740
|
+
* (`expect[].target`, `args.files`, …) are not filesystem targets — and arguments
|
|
741
|
+
* declared as `enum` in the tool schema are skipped.
|
|
742
|
+
*/
|
|
743
|
+
export function collectPathTargets(args, options = {}) {
|
|
744
|
+
if (!args || typeof args !== 'object') return []
|
|
745
|
+
const { schema } = options
|
|
746
|
+
const enumKeys = new Set()
|
|
747
|
+
const properties = schema?.parameters?.properties
|
|
748
|
+
if (properties && typeof properties === 'object') {
|
|
749
|
+
for (const [key, definition] of Object.entries(properties)) {
|
|
750
|
+
if (definition && typeof definition === 'object' && Array.isArray(definition.enum)) {
|
|
751
|
+
enumKeys.add(key.toLowerCase())
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
const out = []
|
|
756
|
+
const push = (key, value) => {
|
|
757
|
+
if (typeof value !== 'string' || !value.trim()) return
|
|
758
|
+
const text = value.trim()
|
|
759
|
+
if (looksLikePathValue(text)) out.push(text)
|
|
760
|
+
else if (STRONG_TARGET_KEYS.has(key.toLowerCase()) && FILE_EXTENSION_PATTERN.test(text)) out.push(text)
|
|
761
|
+
}
|
|
762
|
+
for (const [key, value] of Object.entries(args)) {
|
|
763
|
+
if (!PATH_ARG_PATTERN.test(key)) continue
|
|
764
|
+
if (enumKeys.has(key.toLowerCase())) continue
|
|
765
|
+
if (typeof value === 'string') push(key, value)
|
|
766
|
+
else if (Array.isArray(value)) {
|
|
767
|
+
for (const item of value) {
|
|
768
|
+
if (typeof item === 'string') push(key, item)
|
|
769
|
+
else if (item && typeof item === 'object' && typeof item.path === 'string') push(key, item.path)
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return out
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Best-effort static guard for code-execution tools (`python`, `node`, …).
|
|
778
|
+
*
|
|
779
|
+
* The tool runs arbitrary code, so this cannot be complete: it pairs write signals
|
|
780
|
+
* (`open(...,'w')`, `shutil.copy`, `Path.write_text`, `fs.writeFileSync`, …) with
|
|
781
|
+
* path literals appearing in the same statement and classifies those literals.
|
|
782
|
+
* Dynamically built paths are intentionally out of scope (documented boundary).
|
|
783
|
+
*/
|
|
784
|
+
export function codeToolGuardReason(code, cwd, options = {}) {
|
|
785
|
+
if (typeof code !== 'string' || !code.trim()) return undefined
|
|
786
|
+
const rootDirName = options.rootDirName ?? DEFAULT_ROOT
|
|
787
|
+
const signals = []
|
|
788
|
+
CODE_WRITE_SIGNAL.lastIndex = 0
|
|
789
|
+
let match
|
|
790
|
+
while ((match = CODE_WRITE_SIGNAL.exec(code)) !== null) signals.push(match.index)
|
|
791
|
+
if (signals.length === 0) return undefined
|
|
792
|
+
const literals = []
|
|
793
|
+
CODE_PATH_LITERAL.lastIndex = 0
|
|
794
|
+
while ((match = CODE_PATH_LITERAL.exec(code)) !== null) {
|
|
795
|
+
if (match[2]) literals.push({ index: match.index, literal: match[2] })
|
|
796
|
+
}
|
|
797
|
+
if (literals.length === 0) return undefined
|
|
798
|
+
// O(S×L) → linear: signals are already ascending, so a single cursor finds the
|
|
799
|
+
// nearest signal at or before `literal index + window` (v0.7 review A11).
|
|
800
|
+
let cursor = 0
|
|
801
|
+
let nearest = Number.NEGATIVE_INFINITY
|
|
802
|
+
for (const entry of literals) {
|
|
803
|
+
while (cursor < signals.length && signals[cursor] <= entry.index + CODE_SIGNAL_WINDOW) {
|
|
804
|
+
nearest = signals[cursor]
|
|
805
|
+
cursor += 1
|
|
806
|
+
}
|
|
807
|
+
if (!Number.isFinite(nearest) || entry.index - nearest > CODE_SIGNAL_WINDOW) continue
|
|
808
|
+
const verdict = classifyWriteTarget(entry.literal, cwd, options)
|
|
809
|
+
if (typeof options.onTarget === 'function' && verdict?.abs) {
|
|
810
|
+
try {
|
|
811
|
+
options.onTarget(verdict.abs)
|
|
812
|
+
} catch {
|
|
813
|
+
// a reporting callback never changes the verdict
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
if (verdict.kind === 'outside') {
|
|
817
|
+
if (options.guardOutsideWorkspace === 'warn') {
|
|
818
|
+
console.info(`[session-task-tmpdir] code guard (warn): ${verdict.abs}`)
|
|
819
|
+
continue
|
|
820
|
+
}
|
|
821
|
+
return `代码执行工具被拦截:${outsideWriteDenialReason(verdict.abs, { rootDirName, action: '写入' })}`
|
|
822
|
+
}
|
|
823
|
+
if (verdict.kind === 'inside-longterm' && !options.skipInside) {
|
|
824
|
+
return `代码执行工具被拦截:${verdict.reason}(代码里的写入目标:${verdict.abs})`
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return undefined
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** Argument names of a delivery tool that name the copy destination. */
|
|
831
|
+
const COPY_TARGET_KEYS = new Set([
|
|
832
|
+
'target',
|
|
833
|
+
'targets',
|
|
834
|
+
'target_path',
|
|
835
|
+
'destination',
|
|
836
|
+
'dest',
|
|
837
|
+
'dst',
|
|
838
|
+
'dest_path',
|
|
839
|
+
'to',
|
|
840
|
+
'output',
|
|
841
|
+
'output_path',
|
|
842
|
+
'output_dir',
|
|
843
|
+
'out',
|
|
844
|
+
'out_path',
|
|
845
|
+
'save_path',
|
|
846
|
+
'dir',
|
|
847
|
+
'directory',
|
|
848
|
+
'filename',
|
|
849
|
+
])
|
|
850
|
+
|
|
851
|
+
/** First path argument of a write/edit-style tool call. */
|
|
852
|
+
export function firstWriteTarget(args) {
|
|
853
|
+
if (!args || typeof args !== 'object') return undefined
|
|
854
|
+
const candidates = [args.file_path, args.file_paths, args.path, args.file, args.files]
|
|
855
|
+
for (const candidate of candidates) {
|
|
856
|
+
if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
|
|
857
|
+
if (Array.isArray(candidate)) {
|
|
858
|
+
for (const item of candidate) {
|
|
859
|
+
if (typeof item === 'string' && item.trim()) return item.trim()
|
|
860
|
+
if (item && typeof item === 'object' && typeof item.path === 'string' && item.path.trim()) {
|
|
861
|
+
return item.path.trim()
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
return undefined
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Copy destinations of a delivery tool (`publish`). Source/read arguments are
|
|
871
|
+
* skipped on purpose: copying *from* a long-term folder is harmless.
|
|
872
|
+
*/
|
|
873
|
+
export function publishWriteTargets(args) {
|
|
874
|
+
if (!args || typeof args !== 'object') return []
|
|
875
|
+
const out = []
|
|
876
|
+
const push = (value) => {
|
|
877
|
+
if (typeof value === 'string' && value.trim()) out.push(value.trim())
|
|
878
|
+
}
|
|
879
|
+
for (const [key, value] of Object.entries(args)) {
|
|
880
|
+
const lower = key.toLowerCase()
|
|
881
|
+
if (SOURCE_PATH_ARG_PATTERN.test(lower)) continue
|
|
882
|
+
if (!COPY_TARGET_KEYS.has(lower)) continue
|
|
883
|
+
if (typeof value === 'string') push(value)
|
|
884
|
+
else if (Array.isArray(value)) value.forEach(push)
|
|
885
|
+
else if (value && typeof value === 'object') {
|
|
886
|
+
for (const nested of Object.values(value)) push(nested)
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const files = Array.isArray(args.files) ? args.files : []
|
|
890
|
+
for (const file of files) {
|
|
891
|
+
if (typeof file === 'string') push(file)
|
|
892
|
+
else if (file && typeof file === 'object') push(file.path ?? file.target)
|
|
893
|
+
}
|
|
894
|
+
return [...new Set(out)]
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** Code text of a code-execution tool call (argument name differs per Host). */
|
|
898
|
+
export function codeTextOf(args) {
|
|
899
|
+
if (!args || typeof args !== 'object') return undefined
|
|
900
|
+
for (const key of ['code', 'script', 'source', 'python', 'ruby', 'js', 'command']) {
|
|
901
|
+
if (typeof args[key] === 'string' && args[key].trim()) return args[key]
|
|
902
|
+
}
|
|
903
|
+
return undefined
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* Decide which guard channel a tool call belongs to.
|
|
908
|
+
*
|
|
909
|
+
* Known write tools keep their dedicated path arguments; `publish` uses its copy
|
|
910
|
+
* target; code tools are scanned statically; anything else that declares a path
|
|
911
|
+
* argument and looks write-capable is inspected as `unknown` (only the two
|
|
912
|
+
* high-risk destinations are denied for that channel).
|
|
913
|
+
*/
|
|
914
|
+
export function toolWritePlan(toolName, args, options = {}) {
|
|
915
|
+
const name = String(toolName ?? '').trim()
|
|
916
|
+
if (!name || !args || typeof args !== 'object') return { channel: 'skip' }
|
|
917
|
+
const lower = name.toLowerCase()
|
|
918
|
+
const {
|
|
919
|
+
writeToolNames = [...WRITE_TOOL_NAMES],
|
|
920
|
+
publishToolNames = [...PUBLISH_TOOL_NAMES],
|
|
921
|
+
codeToolNames = [...CODE_TOOL_NAMES],
|
|
922
|
+
shellToolNames = [...SHELL_TOOL_NAMES],
|
|
923
|
+
guardCodeTools = true,
|
|
924
|
+
guardUnknownTools = true,
|
|
925
|
+
guardPublish = true,
|
|
926
|
+
schema,
|
|
927
|
+
} = options
|
|
928
|
+
// v0.7 (review S1): the plugin's own tools must always pass their own guard —
|
|
929
|
+
// `longterm_approve` is the escape hatch the denial messages point at.
|
|
930
|
+
if (SELF_TOOL_NAMES.has(lower)) return { channel: 'skip' }
|
|
931
|
+
const matches = (list) => (Array.isArray(list) ? list.some((entry) => String(entry).toLowerCase() === lower) : false)
|
|
932
|
+
if (matches(codeToolNames)) return guardCodeTools ? { channel: 'code' } : { channel: 'skip' }
|
|
933
|
+
if (matches(shellToolNames)) return { channel: 'shell' }
|
|
934
|
+
if (matches(publishToolNames)) {
|
|
935
|
+
// `present` only declares files that already exist; it copies nothing.
|
|
936
|
+
if (lower === 'present') return { channel: 'skip' }
|
|
937
|
+
return guardPublish ? { channel: 'publish' } : { channel: 'skip' }
|
|
938
|
+
}
|
|
939
|
+
if (matches(writeToolNames)) return { channel: 'write' }
|
|
940
|
+
if (!guardUnknownTools) return { channel: 'skip' }
|
|
941
|
+
// v0.7 (review S4): a read-only tool stays read-only even when its description
|
|
942
|
+
// mentions writing in a negation ("do not install libraries or create thumbnails").
|
|
943
|
+
if (READ_ONLY_TOOL_PATTERN.test(lower)) return { channel: 'skip' }
|
|
944
|
+
const description = typeof schema?.description === 'string' ? schema.description : ''
|
|
945
|
+
if (!WRITE_HINT_PATTERN.test(`${lower} ${description}`)) return { channel: 'skip' }
|
|
946
|
+
// v0.7 (review M1/S2/S3): only top-level arguments whose values actually look like
|
|
947
|
+
// paths count; enum-like values (`this_session`, `@e3`, `#submit`, package ids) do not.
|
|
948
|
+
const targets = collectPathTargets(args, { schema })
|
|
949
|
+
if (targets.length === 0) return { channel: 'skip' }
|
|
950
|
+
const parameters = schema?.parameters && typeof schema.parameters === 'object' ? schema.parameters : undefined
|
|
951
|
+
const pathParams =
|
|
952
|
+
parameters?.properties && typeof parameters.properties === 'object'
|
|
953
|
+
? Object.keys(parameters.properties).filter((key) => PATH_ARG_PATTERN.test(key))
|
|
954
|
+
: []
|
|
955
|
+
return { channel: 'unknown', pathParams }
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
async function readMarker(dir) {
|
|
959
|
+
try {
|
|
960
|
+
return JSON.parse(await readFile(join(dir, MARKER_FILE), 'utf8'))
|
|
961
|
+
} catch {
|
|
962
|
+
return undefined
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
async function writeMarker(dir, sessionId, title, orphanedAt) {
|
|
967
|
+
const payload = { sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }
|
|
968
|
+
if (Number.isFinite(orphanedAt) && orphanedAt > 0) payload.orphanedAt = orphanedAt
|
|
969
|
+
try {
|
|
970
|
+
await writeFile(join(dir, MARKER_FILE), JSON.stringify(payload, null, 2), 'utf8')
|
|
971
|
+
} catch {
|
|
972
|
+
// marker is best-effort; the folder still works without it
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* v0.8 (claim-on-write): the `<rootDirName>/<dir>/` folders a set of write targets
|
|
978
|
+
* lands in. Used by the guard to stamp a marker on folders the model created with a
|
|
979
|
+
* plain `write`/shell command instead of `task_tmpdir`, so they join the same 7-day
|
|
980
|
+
* orphan cleanup chain. Pure and exported for tests.
|
|
981
|
+
*
|
|
982
|
+
* @param {Iterable<string>} targets raw (possibly relative) write targets
|
|
983
|
+
* @param {string} cwd session working directory
|
|
984
|
+
* @param {string} [rootDirName] temp root name (default `_tmp`)
|
|
985
|
+
* @returns {string[]} absolute directories directly under `<cwd>/<rootDirName>/`
|
|
986
|
+
*/
|
|
987
|
+
export function tmpClaimDirsForTargets(targets, cwd, rootDirName = DEFAULT_ROOT, { allowDirItself = false } = {}) {
|
|
988
|
+
const result = new Set()
|
|
989
|
+
if (typeof cwd !== 'string' || !cwd.trim()) return []
|
|
990
|
+
const root = join(resolve(cwd), rootDirName)
|
|
991
|
+
for (const raw of targets ?? []) {
|
|
992
|
+
if (typeof raw !== 'string' || !raw.trim()) continue
|
|
993
|
+
let abs
|
|
994
|
+
try {
|
|
995
|
+
const expanded = expandTildePath(raw.trim())
|
|
996
|
+
abs = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)
|
|
997
|
+
} catch {
|
|
998
|
+
continue
|
|
999
|
+
}
|
|
1000
|
+
if (isDevicePath(abs)) continue
|
|
1001
|
+
if (!pathInside(root, abs)) continue
|
|
1002
|
+
const child = firstSegmentUnder(root, abs)
|
|
1003
|
+
if (!child) continue
|
|
1004
|
+
const dir = join(root, child)
|
|
1005
|
+
if (normalizeForCompare(dir) !== normalizeForCompare(abs)) {
|
|
1006
|
+
// target lives inside `<root>/<child>/…`
|
|
1007
|
+
result.add(dir)
|
|
1008
|
+
continue
|
|
1009
|
+
}
|
|
1010
|
+
// target is exactly `<root>/<child>`: the write tools target files, so they never
|
|
1011
|
+
// claim the folder itself; a shell command that creates directories (`mkdir`,
|
|
1012
|
+
// `New-Item -ItemType Directory`, `git clone`, …) may, because the target is a
|
|
1013
|
+
// folder and not a file. A command that writes a file (`> _tmp/out`) never creates
|
|
1014
|
+
// the folder, so it must not be claimed here either.
|
|
1015
|
+
if (!allowDirItself) continue
|
|
1016
|
+
try {
|
|
1017
|
+
if (statSync(abs).isFile()) continue
|
|
1018
|
+
} catch {
|
|
1019
|
+
// not created yet — the directory verb tells us the command will create it
|
|
1020
|
+
}
|
|
1021
|
+
if (FILE_EXTENSION_PATTERN.test(child)) continue
|
|
1022
|
+
result.add(dir)
|
|
1023
|
+
}
|
|
1024
|
+
return [...result]
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* v0.8: relative `<rootDirName>/<dir>` mentions a shell command may contain. The shell
|
|
1029
|
+
* guard only scans absolute paths, so `New-Item _tmp/foo` would otherwise stay unowned.
|
|
1030
|
+
* Mentioned paths are treated as relative to the session working directory. Exported
|
|
1031
|
+
* for tests.
|
|
1032
|
+
*/
|
|
1033
|
+
export function relativeTmpTargets(command) {
|
|
1034
|
+
const out = []
|
|
1035
|
+
if (typeof command !== 'string' || !command.trim()) return out
|
|
1036
|
+
const text = command.replace(URL_PATTERN, ' ')
|
|
1037
|
+
for (const match of text.matchAll(TMP_RELATIVE_PATTERN)) {
|
|
1038
|
+
if (match[1]) out.push(match[1])
|
|
1039
|
+
}
|
|
1040
|
+
return out
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/**
|
|
1044
|
+
* v0.8: rough "this shell command creates a directory" test. Only such commands may
|
|
1045
|
+
* claim a target that is exactly `<root>/<dir>` (no deeper path component) before the
|
|
1046
|
+
* folder exists — a file-writing command (`> _tmp/out`, `Set-Content _tmp/notes`) must
|
|
1047
|
+
* never be turned into a folder. Exported for tests.
|
|
1048
|
+
*/
|
|
1049
|
+
export function commandCreatesDirectory(command) {
|
|
1050
|
+
if (typeof command !== 'string' || !command.trim()) return false
|
|
1051
|
+
return CREATE_DIR_HINT_PATTERN.test(command)
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* v0.8: stamp `.dsh-task.json` on unmarked temp folders, synchronously. The guard runs
|
|
1056
|
+
* before the tool executes, so the folder may not exist yet; creating it is harmless
|
|
1057
|
+
* because the write that triggered the claim is about to land inside it anyway.
|
|
1058
|
+
* Existing markers are never overwritten (a folder owned by another session stays its).
|
|
1059
|
+
*/
|
|
1060
|
+
export function claimTmpDirsSync(dirs, sessionId, title, { log = () => {} } = {}) {
|
|
1061
|
+
const claimed = []
|
|
1062
|
+
if (!sessionId) return claimed
|
|
1063
|
+
for (const dir of dirs ?? []) {
|
|
1064
|
+
if (typeof dir !== 'string' || !dir.trim()) continue
|
|
1065
|
+
try {
|
|
1066
|
+
if (existsSync(join(dir, MARKER_FILE))) continue
|
|
1067
|
+
mkdirSync(dir, { recursive: true })
|
|
1068
|
+
writeFileSync(
|
|
1069
|
+
join(dir, MARKER_FILE),
|
|
1070
|
+
JSON.stringify({ sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }, null, 2),
|
|
1071
|
+
'utf8',
|
|
1072
|
+
)
|
|
1073
|
+
claimed.push(dir)
|
|
1074
|
+
log(dir)
|
|
1075
|
+
} catch {
|
|
1076
|
+
// best-effort: a failed claim never blocks the write
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
return claimed
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/**
|
|
1083
|
+
* Delete marker-owned task folders whose owning session has been gone for `orphanDays`.
|
|
1084
|
+
*
|
|
1085
|
+
* @param {object} options
|
|
1086
|
+
* @param {Iterable<string>} options.roots workspace directories to scan
|
|
1087
|
+
* @param {string} [options.rootDirName] temp root name (default `_tmp`)
|
|
1088
|
+
* @param {number} options.orphanDays days after session deletion before removal (0 disables)
|
|
1089
|
+
* @param {boolean} [options.dryRun] report only, write/delete nothing
|
|
1090
|
+
* @param {Iterable<string>} [options.liveSessionIds] currently live sessions (never removed)
|
|
1091
|
+
* @param {Iterable<string>} [options.existingSessionIds] persisted sessions (never removed)
|
|
1092
|
+
* @param {number} [options.now] timestamp override (tests)
|
|
1093
|
+
* @param {(message: string) => void} [options.log] progress logger
|
|
1094
|
+
* @returns {Promise<object>} report
|
|
1095
|
+
*/
|
|
1096
|
+
export async function cleanupOrphanedTempDirs({
|
|
1097
|
+
roots,
|
|
1098
|
+
rootDirName = DEFAULT_ROOT,
|
|
1099
|
+
orphanDays,
|
|
1100
|
+
dryRun = false,
|
|
1101
|
+
liveSessionIds = [],
|
|
1102
|
+
existingSessionIds = [],
|
|
1103
|
+
now = Date.now(),
|
|
1104
|
+
log = () => {},
|
|
1105
|
+
}) {
|
|
1106
|
+
const report = {
|
|
1107
|
+
dryRun,
|
|
1108
|
+
cutoff: now - orphanDays * DAY_MS,
|
|
1109
|
+
roots: [],
|
|
1110
|
+
markedOrphaned: [],
|
|
1111
|
+
deleted: [],
|
|
1112
|
+
kept: { live: 0, alive: 0, unmarked: 0, waiting: 0, error: 0 },
|
|
1113
|
+
}
|
|
1114
|
+
if (!(orphanDays > 0)) return report
|
|
1115
|
+
const live = new Set([...liveSessionIds].map((id) => String(id)))
|
|
1116
|
+
const known = new Set([...existingSessionIds].map((id) => String(id)))
|
|
1117
|
+
for (const id of live) known.add(id)
|
|
1118
|
+
const uniqueRoots = new Set([...roots].filter((root) => typeof root === 'string' && root.trim() !== ''))
|
|
1119
|
+
|
|
1120
|
+
for (const root of uniqueRoots) {
|
|
1121
|
+
const tmpRoot = join(root, rootDirName)
|
|
1122
|
+
let entries
|
|
1123
|
+
try {
|
|
1124
|
+
entries = await readdir(tmpRoot, { withFileTypes: true })
|
|
1125
|
+
} catch {
|
|
1126
|
+
continue
|
|
1127
|
+
}
|
|
1128
|
+
report.roots.push(tmpRoot)
|
|
1129
|
+
for (const entry of entries) {
|
|
1130
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue
|
|
1131
|
+
const dir = join(tmpRoot, entry.name)
|
|
1132
|
+
try {
|
|
1133
|
+
const marker = await readMarker(dir)
|
|
1134
|
+
if (!marker) {
|
|
1135
|
+
report.kept.unmarked += 1
|
|
1136
|
+
continue
|
|
1137
|
+
}
|
|
1138
|
+
const sessionId = String(marker.sessionId ?? '')
|
|
1139
|
+
if (!sessionId) {
|
|
1140
|
+
report.kept.unmarked += 1
|
|
1141
|
+
continue
|
|
1142
|
+
}
|
|
1143
|
+
if (live.has(sessionId)) {
|
|
1144
|
+
report.kept.live += 1
|
|
1145
|
+
continue
|
|
1146
|
+
}
|
|
1147
|
+
if (known.has(sessionId)) {
|
|
1148
|
+
report.kept.alive += 1
|
|
1149
|
+
if (Number(marker.orphanedAt) > 0 && !dryRun) await writeMarker(dir, sessionId, marker.title, undefined)
|
|
1150
|
+
continue
|
|
1151
|
+
}
|
|
1152
|
+
// Owning session no longer exists.
|
|
1153
|
+
const orphanedAt = Number(marker.orphanedAt) || 0
|
|
1154
|
+
if (orphanedAt <= 0) {
|
|
1155
|
+
report.markedOrphaned.push(dir)
|
|
1156
|
+
if (dryRun) {
|
|
1157
|
+
report.kept.waiting += 1
|
|
1158
|
+
log(`[dry-run] would mark orphaned ${dir}`)
|
|
1159
|
+
} else {
|
|
1160
|
+
await writeMarker(dir, sessionId, marker.title, now)
|
|
1161
|
+
log(`marked orphaned ${dir}`)
|
|
1162
|
+
}
|
|
1163
|
+
continue
|
|
1164
|
+
}
|
|
1165
|
+
if (now - orphanedAt < orphanDays * DAY_MS) {
|
|
1166
|
+
report.kept.waiting += 1
|
|
1167
|
+
continue
|
|
1168
|
+
}
|
|
1169
|
+
if (dryRun) {
|
|
1170
|
+
report.deleted.push({ path: dir, dryRun: true })
|
|
1171
|
+
log(`[dry-run] would delete ${dir}`)
|
|
1172
|
+
continue
|
|
1173
|
+
}
|
|
1174
|
+
await rm(dir, { recursive: true, force: true })
|
|
1175
|
+
report.deleted.push({ path: dir })
|
|
1176
|
+
log(`deleted ${dir}`)
|
|
1177
|
+
} catch {
|
|
1178
|
+
report.kept.error += 1
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return report
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/** Resolve the DSH home directory (`DSH_HOME` override, else `~/.dsh`). */
|
|
1186
|
+
export function resolveDshHome() {
|
|
1187
|
+
const fromEnv = process.env.DSH_HOME && process.env.DSH_HOME.trim() ? process.env.DSH_HOME.trim() : ''
|
|
1188
|
+
return fromEnv || join(homedir(), '.dsh')
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/** Best-effort fallback: collect session ids from the persisted session tree. */
|
|
1192
|
+
async function scanPersistedSessionIds() {
|
|
1193
|
+
const ids = new Set()
|
|
1194
|
+
const home = resolveDshHome()
|
|
1195
|
+
const roots = [join(home, 'sessions'), join(home, '_archived-sessions')]
|
|
1196
|
+
const idPattern = /^(?:session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
1197
|
+
for (const root of roots) {
|
|
1198
|
+
let workspaces
|
|
1199
|
+
try {
|
|
1200
|
+
workspaces = await readdir(root, { withFileTypes: true })
|
|
1201
|
+
} catch {
|
|
1202
|
+
continue
|
|
1203
|
+
}
|
|
1204
|
+
for (const workspace of workspaces) {
|
|
1205
|
+
if (!workspace.isDirectory()) continue
|
|
1206
|
+
const workspaceDir = join(root, workspace.name)
|
|
1207
|
+
// Session directories live one level below; also cover a flat layout.
|
|
1208
|
+
if (idPattern.test(workspace.name)) {
|
|
1209
|
+
ids.add(workspace.name.replace(/^session-/, ''))
|
|
1210
|
+
continue
|
|
1211
|
+
}
|
|
1212
|
+
let sessions
|
|
1213
|
+
try {
|
|
1214
|
+
sessions = await readdir(workspaceDir, { withFileTypes: true })
|
|
1215
|
+
} catch {
|
|
1216
|
+
continue
|
|
1217
|
+
}
|
|
1218
|
+
for (const session of sessions) {
|
|
1219
|
+
if (!session.isDirectory()) continue
|
|
1220
|
+
if (idPattern.test(session.name)) ids.add(session.name.replace(/^session-/, ''))
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
return ids
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* Collect `sha256:` attachment ids from an arbitrary session-event payload.
|
|
1229
|
+
*
|
|
1230
|
+
* Attachment references are stored as `{ attachmentId: 'sha256:<hex>', ... }` inside
|
|
1231
|
+
* `image` / `file` content blocks; walking the parsed event keeps this independent of
|
|
1232
|
+
* where a block lives (user message, tool result, spliced inbox, …).
|
|
1233
|
+
*
|
|
1234
|
+
* @param {unknown} value parsed session event (or any nested JSON value)
|
|
1235
|
+
* @param {Set<string>} [out] accumulator of hex hashes
|
|
1236
|
+
* @param {number} [depth] recursion guard
|
|
1237
|
+
* @returns {Set<string>}
|
|
1238
|
+
*/
|
|
1239
|
+
export function collectAttachmentIds(value, out = new Set(), depth = 0) {
|
|
1240
|
+
if (!value || depth > 24) return out
|
|
1241
|
+
if (Array.isArray(value)) {
|
|
1242
|
+
for (const item of value) collectAttachmentIds(item, out, depth + 1)
|
|
1243
|
+
return out
|
|
1244
|
+
}
|
|
1245
|
+
if (typeof value !== 'object') return out
|
|
1246
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1247
|
+
if (key === 'attachmentId' && typeof item === 'string') {
|
|
1248
|
+
const match = ATTACHMENT_ID_PATTERN.exec(item)
|
|
1249
|
+
if (match) out.add(match[1].toLowerCase())
|
|
1250
|
+
continue
|
|
1251
|
+
}
|
|
1252
|
+
collectAttachmentIds(item, out, depth + 1)
|
|
1253
|
+
}
|
|
1254
|
+
return out
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/** Read the attachment ledger; a missing or unreadable file yields an empty ledger. */
|
|
1258
|
+
async function readAttachmentLedger(path) {
|
|
1259
|
+
try {
|
|
1260
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'))
|
|
1261
|
+
if (parsed && typeof parsed === 'object' && parsed.sessions && typeof parsed.sessions === 'object') {
|
|
1262
|
+
return {
|
|
1263
|
+
version: ATTACHMENT_LEDGER_VERSION,
|
|
1264
|
+
sessions: parsed.sessions,
|
|
1265
|
+
lastSweepAt: Number(parsed.lastSweepAt) || 0,
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
} catch {
|
|
1269
|
+
// missing or corrupt ledger: start from scratch
|
|
1270
|
+
}
|
|
1271
|
+
return { version: ATTACHMENT_LEDGER_VERSION, sessions: {}, lastSweepAt: 0 }
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
/** Write the ledger atomically (temp file + rename), best-effort. */
|
|
1275
|
+
async function writeAttachmentLedger(path, ledger) {
|
|
1276
|
+
const temp = `${path}.tmp`
|
|
1277
|
+
try {
|
|
1278
|
+
await mkdir(dirname(path), { recursive: true })
|
|
1279
|
+
await writeFile(temp, JSON.stringify(ledger), 'utf8')
|
|
1280
|
+
await rename(temp, path)
|
|
1281
|
+
} catch {
|
|
1282
|
+
// ledger persistence is an optimization; a failed write only costs a rescan
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* List every stored attachment blob.
|
|
1288
|
+
* @param {string} attachmentsRoot attachment service root (default `<DSH_HOME>/attachments`)
|
|
1289
|
+
* @returns {Promise<Array<{ hash: string, path: string, bytes: number, mtime: number }>>}
|
|
1290
|
+
*/
|
|
1291
|
+
async function listAttachmentBlobs(attachmentsRoot) {
|
|
1292
|
+
const objectsDir = join(attachmentsRoot, 'v1', 'objects')
|
|
1293
|
+
/** @type {Array<{ hash: string, path: string, bytes: number, mtime: number }>} */
|
|
1294
|
+
const blobs = []
|
|
1295
|
+
let buckets
|
|
1296
|
+
try {
|
|
1297
|
+
buckets = await readdir(objectsDir, { withFileTypes: true })
|
|
1298
|
+
} catch {
|
|
1299
|
+
return blobs
|
|
1300
|
+
}
|
|
1301
|
+
for (const bucket of buckets) {
|
|
1302
|
+
if (!bucket.isDirectory()) continue
|
|
1303
|
+
const bucketDir = join(objectsDir, bucket.name)
|
|
1304
|
+
let files
|
|
1305
|
+
try {
|
|
1306
|
+
files = await readdir(bucketDir, { withFileTypes: true })
|
|
1307
|
+
} catch {
|
|
1308
|
+
continue
|
|
1309
|
+
}
|
|
1310
|
+
for (const file of files) {
|
|
1311
|
+
if (!file.isFile() || !/^[0-9a-f]{64}$/i.test(file.name)) continue
|
|
1312
|
+
const full = join(bucketDir, file.name)
|
|
1313
|
+
try {
|
|
1314
|
+
const info = await stat(full)
|
|
1315
|
+
blobs.push({ hash: file.name.toLowerCase(), path: full, bytes: info.size, mtime: info.mtimeMs })
|
|
1316
|
+
} catch {
|
|
1317
|
+
/* raced with a delete */
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
return blobs
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
export function apply(ctx, config) {
|
|
1325
|
+
const {
|
|
1326
|
+
rootDirName,
|
|
1327
|
+
includeSubagents,
|
|
1328
|
+
maxNameLength,
|
|
1329
|
+
orphanCleanupDays,
|
|
1330
|
+
cleanupIntervalHours,
|
|
1331
|
+
cleanupDryRun,
|
|
1332
|
+
guardWorkspaceRoot,
|
|
1333
|
+
requireApprovalOutsideTmp,
|
|
1334
|
+
allowRootPatterns,
|
|
1335
|
+
allowRootFiles,
|
|
1336
|
+
commandGuard,
|
|
1337
|
+
guardOutsideWorkspace,
|
|
1338
|
+
publishGuard,
|
|
1339
|
+
guardCodeTools,
|
|
1340
|
+
guardUnknownTools,
|
|
1341
|
+
writeToolNames,
|
|
1342
|
+
publishToolNames,
|
|
1343
|
+
codeToolNames,
|
|
1344
|
+
shellToolNames,
|
|
1345
|
+
outsideAllow: extraOutsideAllow,
|
|
1346
|
+
publishBaseDir,
|
|
1347
|
+
attachmentCleanup,
|
|
1348
|
+
attachmentCleanupDays,
|
|
1349
|
+
attachmentSweepOrphans,
|
|
1350
|
+
attachmentsDir,
|
|
1351
|
+
} = readConfig(config)
|
|
1352
|
+
/** Directories outside the workspace that never need approval (DSH home, caches, temp). */
|
|
1353
|
+
const outsideAllow = [...defaultOutsideAllow(resolveDshHome()), ...extraOutsideAllow]
|
|
1354
|
+
const queues = new Map()
|
|
1355
|
+
/** sessionId → approved long-term prefixes ({ prefix, reason, basis, approvedAt }[]). */
|
|
1356
|
+
const approvals = new Map()
|
|
1357
|
+
let sessionPersistence
|
|
1358
|
+
let workspaceRegistry
|
|
1359
|
+
try {
|
|
1360
|
+
ctx.inject(['sessionPersistence'], (scoped) => {
|
|
1361
|
+
sessionPersistence = scoped.sessionPersistence
|
|
1362
|
+
})
|
|
1363
|
+
} catch {
|
|
1364
|
+
// fallback: the persisted session tree is scanned directly
|
|
1365
|
+
}
|
|
1366
|
+
try {
|
|
1367
|
+
ctx.inject(['workspaceRegistry'], (scoped) => {
|
|
1368
|
+
workspaceRegistry = scoped.workspaceRegistry
|
|
1369
|
+
})
|
|
1370
|
+
} catch {
|
|
1371
|
+
// workspaceRegistry is optional; live sessions and the default directory still cover roots
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
const cwdOf = (session) => {
|
|
1375
|
+
try {
|
|
1376
|
+
const dir = ctx.workingDirectory.get(session)
|
|
1377
|
+
if (typeof dir === 'string' && dir) return dir
|
|
1378
|
+
} catch {
|
|
1379
|
+
// fall through to the header value
|
|
1380
|
+
}
|
|
1381
|
+
const headerCwd = session?.header?.cwd
|
|
1382
|
+
return typeof headerCwd === 'string' && headerCwd ? headerCwd : undefined
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
const titleOf = (session) => {
|
|
1386
|
+
try {
|
|
1387
|
+
const snapshot = ctx.sessionTitle.get(session)
|
|
1388
|
+
if (snapshot?.title) return snapshot.title
|
|
1389
|
+
} catch {
|
|
1390
|
+
// title provider may be absent or the session may be detached
|
|
1391
|
+
}
|
|
1392
|
+
return undefined
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
const isRelevant = (session) => includeSubagents || session?.header?.origin !== 'subagent'
|
|
1396
|
+
|
|
1397
|
+
/**
|
|
1398
|
+
* The root-entry guard only makes sense when the session is working at a workspace
|
|
1399
|
+
* root. A session `cd`-ed into a subfolder (or a subagent started in a plugin dir)
|
|
1400
|
+
* must not have its project files treated as "new workspace-root entries".
|
|
1401
|
+
*/
|
|
1402
|
+
function isProtectedRoot(cwd) {
|
|
1403
|
+
let workspaces = []
|
|
1404
|
+
try {
|
|
1405
|
+
workspaces = workspaceRegistry?.list() ?? []
|
|
1406
|
+
} catch {
|
|
1407
|
+
workspaces = []
|
|
1408
|
+
}
|
|
1409
|
+
if (workspaces.length > 0) return workspaces.some((workspace) => samePath(workspace?.path, cwd))
|
|
1410
|
+
// Registry not ready: keep the historical strict behavior, default directory still counts.
|
|
1411
|
+
try {
|
|
1412
|
+
const defaultDir = ctx.workingDirectory.defaultDirectory
|
|
1413
|
+
if (typeof defaultDir === 'string' && defaultDir) return samePath(defaultDir, cwd)
|
|
1414
|
+
} catch {
|
|
1415
|
+
// no default directory
|
|
1416
|
+
}
|
|
1417
|
+
return true
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
const baseDir = (cwd) => join(cwd, rootDirName)
|
|
1421
|
+
|
|
1422
|
+
// ── long-term approvals (per live session, in memory) ──────────────────────
|
|
1423
|
+
const sessionKey = (session) => {
|
|
1424
|
+
try {
|
|
1425
|
+
return session?.id ? String(session.id) : ''
|
|
1426
|
+
} catch {
|
|
1427
|
+
return ''
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/**
|
|
1432
|
+
* v0.8 claim-on-write: attribute unmarked `<rootDirName>/<dir>/` folders touched by
|
|
1433
|
+
* this session's writes to the session, so every folder the model creates joins the
|
|
1434
|
+
* 7-day orphan cleanup chain even when it bypassed `task_tmpdir`.
|
|
1435
|
+
*/
|
|
1436
|
+
function claimTmpTargets(targets, session, options = {}) {
|
|
1437
|
+
try {
|
|
1438
|
+
const dirs = tmpClaimDirsForTargets(targets, cwdOf(session), rootDirName, options)
|
|
1439
|
+
if (dirs.length === 0) return
|
|
1440
|
+
claimTmpDirsSync(dirs, sessionKey(session), titleOf(session) ?? '', {
|
|
1441
|
+
log: (dir) => console.info(`[session-task-tmpdir] claimed unmarked temp folder: ${dir}`),
|
|
1442
|
+
})
|
|
1443
|
+
} catch {
|
|
1444
|
+
// claiming is best-effort
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
function approvedPrefixesFor(session) {
|
|
1449
|
+
const id = sessionKey(session)
|
|
1450
|
+
const list = id ? approvals.get(id) : undefined
|
|
1451
|
+
return list ? list.map((entry) => entry.prefix) : []
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
function registerApproval(session, prefix, { reason, basis }) {
|
|
1455
|
+
const id = sessionKey(session)
|
|
1456
|
+
if (!id) throw new Error('longterm_approve: session is unavailable')
|
|
1457
|
+
const list = approvals.get(id) ?? []
|
|
1458
|
+
const normalized = resolve(prefix)
|
|
1459
|
+
if (!list.some((entry) => normalizeForCompare(entry.prefix) === normalizeForCompare(normalized))) {
|
|
1460
|
+
list.push({ prefix: normalized, reason: reason ?? '', basis: basis ?? 'user_confirmed', approvedAt: Date.now() })
|
|
1461
|
+
approvals.set(id, list)
|
|
1462
|
+
console.info(`[session-task-tmpdir] longterm approved ${normalized} (session ${id})`)
|
|
1463
|
+
}
|
|
1464
|
+
return list
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
async function isDir(path) {
|
|
1468
|
+
try {
|
|
1469
|
+
return (await stat(path)).isDirectory()
|
|
1470
|
+
} catch {
|
|
1471
|
+
return false
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
async function findOwnedDir(cwd, sessionId) {
|
|
1476
|
+
const root = baseDir(cwd)
|
|
1477
|
+
let entries
|
|
1478
|
+
try {
|
|
1479
|
+
entries = await readdir(root, { withFileTypes: true })
|
|
1480
|
+
} catch {
|
|
1481
|
+
return undefined
|
|
1482
|
+
}
|
|
1483
|
+
for (const entry of entries) {
|
|
1484
|
+
if (!entry.isDirectory()) continue
|
|
1485
|
+
const dir = join(root, entry.name)
|
|
1486
|
+
const marker = await readMarker(dir)
|
|
1487
|
+
if (marker && String(marker.sessionId) === String(sessionId)) return dir
|
|
1488
|
+
}
|
|
1489
|
+
return undefined
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* Pick a target path for `name`: reuse the folder owned by this session, adopt an
|
|
1494
|
+
* empty unowned folder (removing it first when `removeEmpty` prepares a rename),
|
|
1495
|
+
* otherwise append a numeric suffix.
|
|
1496
|
+
*/
|
|
1497
|
+
async function chooseTarget(root, name, sessionId, { removeEmpty = false } = {}) {
|
|
1498
|
+
let target = join(root, name)
|
|
1499
|
+
let n = 2
|
|
1500
|
+
for (;;) {
|
|
1501
|
+
if (!(await isDir(target))) return target
|
|
1502
|
+
const marker = await readMarker(target)
|
|
1503
|
+
if (marker && sessionId !== undefined && String(marker.sessionId) === String(sessionId)) return target
|
|
1504
|
+
const entries = await readdir(target).catch(() => [])
|
|
1505
|
+
if (!marker && entries.length === 0) {
|
|
1506
|
+
if (!removeEmpty) return target
|
|
1507
|
+
await rm(target, { recursive: true, force: true }).catch(() => {})
|
|
1508
|
+
return target
|
|
1509
|
+
}
|
|
1510
|
+
target = join(root, `${name} (${n++})`)
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
async function createDir(session, sub) {
|
|
1515
|
+
const cwd = cwdOf(session)
|
|
1516
|
+
if (!cwd) throw new Error('session working directory is unavailable')
|
|
1517
|
+
const title = titleOf(session)
|
|
1518
|
+
const name = sanitizeTitle(title, maxNameLength) || `${FALLBACK_PREFIX}${String(session.id).slice(0, 8)}`
|
|
1519
|
+
const root = baseDir(cwd)
|
|
1520
|
+
await mkdir(root, { recursive: true })
|
|
1521
|
+
// Reuse the folder this session already owns (e.g. a `sub` call after the first call)
|
|
1522
|
+
const owned = await findOwnedDir(cwd, session.id)
|
|
1523
|
+
const target = owned ?? (await chooseTarget(root, name, session.id))
|
|
1524
|
+
await mkdir(target, { recursive: true })
|
|
1525
|
+
await writeMarker(target, session.id, title ?? '')
|
|
1526
|
+
const path = sub ? join(target, sanitizeTitle(sub, maxNameLength) || 'sub') : target
|
|
1527
|
+
if (sub) await mkdir(path, { recursive: true })
|
|
1528
|
+
return { path, title: title ?? '' }
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
async function syncDir(session) {
|
|
1532
|
+
const cwd = cwdOf(session)
|
|
1533
|
+
if (!cwd) return
|
|
1534
|
+
const title = titleOf(session)
|
|
1535
|
+
if (!title) return
|
|
1536
|
+
const name = sanitizeTitle(title, maxNameLength)
|
|
1537
|
+
if (!name) return
|
|
1538
|
+
const root = baseDir(cwd)
|
|
1539
|
+
const owned = await findOwnedDir(cwd, session.id)
|
|
1540
|
+
if (!owned) {
|
|
1541
|
+
await createDir(session)
|
|
1542
|
+
return
|
|
1543
|
+
}
|
|
1544
|
+
if (owned === join(root, name)) {
|
|
1545
|
+
await writeMarker(owned, session.id, title)
|
|
1546
|
+
return
|
|
1547
|
+
}
|
|
1548
|
+
const target = await chooseTarget(root, name, session.id, { removeEmpty: true })
|
|
1549
|
+
if (target === owned) return
|
|
1550
|
+
try {
|
|
1551
|
+
await rename(owned, target)
|
|
1552
|
+
} catch (error) {
|
|
1553
|
+
// A locked file can block the rename on Windows; keep the old folder and its marker.
|
|
1554
|
+
console.warn('[session-task-tmpdir] rename failed:', error?.message ?? error)
|
|
1555
|
+
return
|
|
1556
|
+
}
|
|
1557
|
+
await writeMarker(target, session.id, title)
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
function enqueue(session) {
|
|
1561
|
+
const id = String(session.id)
|
|
1562
|
+
const previous = queues.get(id) ?? Promise.resolve()
|
|
1563
|
+
const next = previous
|
|
1564
|
+
.then(() => syncDir(session))
|
|
1565
|
+
.catch((error) => console.warn('[session-task-tmpdir] sync failed:', error?.message ?? error))
|
|
1566
|
+
.finally(() => {
|
|
1567
|
+
if (queues.get(id) === next) queues.delete(id)
|
|
1568
|
+
})
|
|
1569
|
+
queues.set(id, next)
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// Title change (user rename and automatic title regeneration both append session/title).
|
|
1573
|
+
ctx.effect(() =>
|
|
1574
|
+
ctx.on('session/event', (session, event) => {
|
|
1575
|
+
if (event?.type !== 'session/title') return
|
|
1576
|
+
if (!session || !isRelevant(session)) return
|
|
1577
|
+
enqueue(session)
|
|
1578
|
+
}),
|
|
1579
|
+
)
|
|
1580
|
+
|
|
1581
|
+
// A resumed session may already carry a title; materialize the folder on creation.
|
|
1582
|
+
ctx.effect(() =>
|
|
1583
|
+
ctx.on('session/created', (session) => {
|
|
1584
|
+
if (!session || !isRelevant(session)) return
|
|
1585
|
+
enqueue(session)
|
|
1586
|
+
}),
|
|
1587
|
+
)
|
|
1588
|
+
|
|
1589
|
+
// Drop per-session long-term approvals once the session is gone.
|
|
1590
|
+
ctx.effect(() =>
|
|
1591
|
+
ctx.on('session/disposed', (session) => {
|
|
1592
|
+
const id = sessionKey(session)
|
|
1593
|
+
if (id) approvals.delete(id)
|
|
1594
|
+
}),
|
|
1595
|
+
)
|
|
1596
|
+
|
|
1597
|
+
// ── orphan cleanup ─────────────────────────────────────────────────────────
|
|
1598
|
+
let cleaning = false
|
|
1599
|
+
|
|
1600
|
+
async function loadPersistenceSnapshots() {
|
|
1601
|
+
if (sessionPersistence && typeof sessionPersistence.list === 'function') {
|
|
1602
|
+
try {
|
|
1603
|
+
return await sessionPersistence.list()
|
|
1604
|
+
} catch {
|
|
1605
|
+
// fall through to the directory scan
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
return undefined
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
async function collectPersistedSessionIds() {
|
|
1612
|
+
const snapshots = await loadPersistenceSnapshots()
|
|
1613
|
+
if (snapshots) return snapshots.map((snapshot) => String(snapshot?.header?.id ?? '')).filter(Boolean)
|
|
1614
|
+
return [...(await scanPersistedSessionIds())]
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// ── attachment cleanup (v0.6) ───────────────────────────────────────────────
|
|
1618
|
+
// The attachment store is content-addressed and never garbage collected by the Host,
|
|
1619
|
+
// so deleting a conversation leaves its blobs behind forever. Every cleanup tick we
|
|
1620
|
+
// record the attachment ids each *stored* session references (ledger), stamp the
|
|
1621
|
+
// moment a session disappears, and only once that stamp is older than
|
|
1622
|
+
// `attachmentCleanupDays` delete the blobs no surviving session references.
|
|
1623
|
+
const attachmentsRoot = attachmentsDir
|
|
1624
|
+
const attachmentLedgerPath = join(resolveDshHome(), 'data', ATTACHMENT_LEDGER_FILE)
|
|
1625
|
+
const attachmentGcLogPath = join(resolveDshHome(), 'data', ATTACHMENT_GC_LOG_FILE)
|
|
1626
|
+
|
|
1627
|
+
/** Read one stored session through the persistence service and collect its attachment ids. */
|
|
1628
|
+
async function readSessionAttachmentIds(sessionId) {
|
|
1629
|
+
if (!sessionPersistence || typeof sessionPersistence.open !== 'function') return undefined
|
|
1630
|
+
let handle
|
|
1631
|
+
try {
|
|
1632
|
+
handle = await sessionPersistence.open(sessionId, 'read')
|
|
1633
|
+
} catch {
|
|
1634
|
+
return undefined
|
|
1635
|
+
}
|
|
1636
|
+
const ids = new Set()
|
|
1637
|
+
try {
|
|
1638
|
+
let offset = 0
|
|
1639
|
+
for (let page = 0; page < ATTACHMENT_READ_PAGE_LIMIT; page += 1) {
|
|
1640
|
+
const result = await handle.read(offset, ATTACHMENT_READ_PAGE_SIZE)
|
|
1641
|
+
const events = Array.isArray(result?.events) ? result.events : []
|
|
1642
|
+
if (events.length === 0) break
|
|
1643
|
+
for (const event of events) collectAttachmentIds(event, ids)
|
|
1644
|
+
const lastSeq = Number(events[events.length - 1]?.seq)
|
|
1645
|
+
if (!Number.isFinite(lastSeq) || lastSeq < offset) break
|
|
1646
|
+
offset = lastSeq + 1
|
|
1647
|
+
if (events.length < ATTACHMENT_READ_PAGE_SIZE) break
|
|
1648
|
+
}
|
|
1649
|
+
} catch {
|
|
1650
|
+
// torn or unreadable tail: keep whatever was collected so far
|
|
1651
|
+
} finally {
|
|
1652
|
+
try {
|
|
1653
|
+
await handle.close()
|
|
1654
|
+
} catch {
|
|
1655
|
+
/* already closed */
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
return ids
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
/**
|
|
1662
|
+
* Delete attachment blobs whose owning session has been gone for `attachmentCleanupDays`,
|
|
1663
|
+
* plus (optionally) blobs no stored session references and that are at least that old.
|
|
1664
|
+
*/
|
|
1665
|
+
async function runAttachmentCleanup(trigger, { dryRun = cleanupDryRun } = {}) {
|
|
1666
|
+
if (!attachmentCleanup) return { skipped: 'disabled' }
|
|
1667
|
+
const snapshots = await loadPersistenceSnapshots()
|
|
1668
|
+
if (!snapshots) return { skipped: 'sessionPersistence-unavailable' }
|
|
1669
|
+
if (snapshots.length === 0) return { skipped: 'no-stored-sessions' }
|
|
1670
|
+
const now = Date.now()
|
|
1671
|
+
const liveSessionIds = new Set()
|
|
1672
|
+
try {
|
|
1673
|
+
for (const session of ctx.sessions.list()) liveSessionIds.add(String(session.id))
|
|
1674
|
+
} catch {
|
|
1675
|
+
/* sessions unavailable this tick */
|
|
1676
|
+
}
|
|
1677
|
+
const ledger = await readAttachmentLedger(attachmentLedgerPath)
|
|
1678
|
+
const alive = new Set()
|
|
1679
|
+
const referenced = new Set()
|
|
1680
|
+
let rescanned = 0
|
|
1681
|
+
let scannedFailures = 0
|
|
1682
|
+
for (const snapshot of snapshots) {
|
|
1683
|
+
const id = String(snapshot?.header?.id ?? '')
|
|
1684
|
+
if (!id) continue
|
|
1685
|
+
alive.add(id)
|
|
1686
|
+
const revision = String(snapshot?.revision ?? '')
|
|
1687
|
+
const entry = ledger.sessions[id]
|
|
1688
|
+
let hashes
|
|
1689
|
+
if (entry && entry.revision === revision && Array.isArray(entry.hashes)) {
|
|
1690
|
+
hashes = entry.hashes
|
|
1691
|
+
} else {
|
|
1692
|
+
const scanned = await readSessionAttachmentIds(id)
|
|
1693
|
+
if (!scanned) {
|
|
1694
|
+
scannedFailures += 1
|
|
1695
|
+
if (entry && Array.isArray(entry.hashes)) hashes = entry.hashes
|
|
1696
|
+
else continue
|
|
1697
|
+
} else {
|
|
1698
|
+
hashes = [...scanned]
|
|
1699
|
+
ledger.sessions[id] = { revision, hashes, scannedAt: now }
|
|
1700
|
+
rescanned += 1
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
for (const hash of hashes) referenced.add(hash)
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
// ── safety interlocks (portability) ───────────────────────────────────────
|
|
1707
|
+
// The layout and the attachment-id vocabulary are Host-owned. On another platform
|
|
1708
|
+
// (HarmonyOS / mobile / a future store version) either may differ; sweeping then
|
|
1709
|
+
// must fail closed instead of treating "nothing referenced" as "everything stale".
|
|
1710
|
+
const blobs = await listAttachmentBlobs(attachmentsRoot)
|
|
1711
|
+
if (blobs.length === 0) {
|
|
1712
|
+
return { skipped: 'no-attachment-objects', attachmentsRoot }
|
|
1713
|
+
}
|
|
1714
|
+
if (referenced.size === 0) {
|
|
1715
|
+
return {
|
|
1716
|
+
skipped: 'no-attachment-references',
|
|
1717
|
+
objects: blobs.length,
|
|
1718
|
+
storedSessions: alive.size,
|
|
1719
|
+
rescanned,
|
|
1720
|
+
scanFailures: scannedFailures,
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
// Stamp sessions that vanished since the previous tick.
|
|
1725
|
+
let markedOrphaned = 0
|
|
1726
|
+
for (const [id, entry] of Object.entries(ledger.sessions)) {
|
|
1727
|
+
if (alive.has(id) || liveSessionIds.has(id)) continue
|
|
1728
|
+
if (!entry) continue
|
|
1729
|
+
if (!(Number(entry.orphanedAt) > 0)) {
|
|
1730
|
+
entry.orphanedAt = now
|
|
1731
|
+
markedOrphaned += 1
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
const graceDays = attachmentCleanupDays
|
|
1736
|
+
const due = new Map()
|
|
1737
|
+
for (const [id, entry] of Object.entries(ledger.sessions)) {
|
|
1738
|
+
if (!entry || alive.has(id) || liveSessionIds.has(id)) continue
|
|
1739
|
+
const orphanedAt = Number(entry.orphanedAt) || 0
|
|
1740
|
+
if (!(orphanedAt > 0)) continue
|
|
1741
|
+
if (now - orphanedAt < graceDays * DAY_MS) continue
|
|
1742
|
+
due.set(id, entry)
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
const deleted = []
|
|
1746
|
+
let freedBytes = 0
|
|
1747
|
+
let skippedRecent = 0
|
|
1748
|
+
let skippedReferenced = 0
|
|
1749
|
+
const drop = async (hash, reason) => {
|
|
1750
|
+
const blobPath = join(attachmentsRoot, 'v1', 'objects', hash.slice(0, 2), hash)
|
|
1751
|
+
let info
|
|
1752
|
+
try {
|
|
1753
|
+
info = await stat(blobPath)
|
|
1754
|
+
} catch {
|
|
1755
|
+
return false
|
|
1756
|
+
}
|
|
1757
|
+
if (now - info.mtimeMs < ATTACHMENT_MIN_AGE_MS) {
|
|
1758
|
+
skippedRecent += 1
|
|
1759
|
+
return false
|
|
1760
|
+
}
|
|
1761
|
+
if (!dryRun) {
|
|
1762
|
+
try {
|
|
1763
|
+
await rm(blobPath, { force: true })
|
|
1764
|
+
} catch {
|
|
1765
|
+
return false
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
deleted.push({ hash, bytes: info.size, reason })
|
|
1769
|
+
freedBytes += info.size
|
|
1770
|
+
return true
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
for (const entry of due.values()) {
|
|
1774
|
+
for (const hash of entry.hashes ?? []) {
|
|
1775
|
+
if (referenced.has(hash)) {
|
|
1776
|
+
skippedReferenced += 1
|
|
1777
|
+
continue
|
|
1778
|
+
}
|
|
1779
|
+
await drop(hash, 'session-deleted')
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
const known = new Set()
|
|
1784
|
+
for (const entry of Object.values(ledger.sessions)) {
|
|
1785
|
+
for (const hash of entry?.hashes ?? []) known.add(hash)
|
|
1786
|
+
}
|
|
1787
|
+
let sweptOrphans = 0
|
|
1788
|
+
if (attachmentSweepOrphans) {
|
|
1789
|
+
for (const blob of blobs) {
|
|
1790
|
+
if (referenced.has(blob.hash) || known.has(blob.hash)) continue
|
|
1791
|
+
if (now - blob.mtime < graceDays * DAY_MS) continue
|
|
1792
|
+
if (await drop(blob.hash, 'unreferenced')) sweptOrphans += 1
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
if (!dryRun) {
|
|
1797
|
+
for (const id of due.keys()) delete ledger.sessions[id]
|
|
1798
|
+
ledger.lastSweepAt = now
|
|
1799
|
+
await writeAttachmentLedger(attachmentLedgerPath, ledger)
|
|
1800
|
+
if (deleted.length > 0) {
|
|
1801
|
+
try {
|
|
1802
|
+
await appendFile(
|
|
1803
|
+
attachmentGcLogPath,
|
|
1804
|
+
`${JSON.stringify({ at: new Date(now).toISOString(), trigger, deleted })}\n`,
|
|
1805
|
+
'utf8',
|
|
1806
|
+
)
|
|
1807
|
+
} catch {
|
|
1808
|
+
/* audit log is best-effort */
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
const report = {
|
|
1814
|
+
dryRun,
|
|
1815
|
+
storedSessions: alive.size,
|
|
1816
|
+
objects: blobs.length,
|
|
1817
|
+
rescanned,
|
|
1818
|
+
scanFailures: scannedFailures,
|
|
1819
|
+
referencedBlobs: referenced.size,
|
|
1820
|
+
markedOrphaned,
|
|
1821
|
+
dueSessions: due.size,
|
|
1822
|
+
deleted: deleted.length,
|
|
1823
|
+
freedBytes,
|
|
1824
|
+
sweptOrphans,
|
|
1825
|
+
skippedRecent,
|
|
1826
|
+
skippedReferenced,
|
|
1827
|
+
}
|
|
1828
|
+
if (report.deleted > 0 || report.markedOrphaned > 0) {
|
|
1829
|
+
console.info(
|
|
1830
|
+
`[session-task-tmpdir] attachments(${trigger})${dryRun ? ' dry-run' : ''}: ` +
|
|
1831
|
+
`deleted ${report.deleted} (${(freedBytes / 1048576).toFixed(1)} MB), ` +
|
|
1832
|
+
`marked ${report.markedOrphaned}, due sessions ${report.dueSessions}, ` +
|
|
1833
|
+
`referenced ${report.referencedBlobs}, rescanned ${report.rescanned}`,
|
|
1834
|
+
)
|
|
1835
|
+
}
|
|
1836
|
+
return report
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
async function runCleanup(trigger, { dryRun = cleanupDryRun, withAttachments = true } = {}) {
|
|
1840
|
+
if (cleaning || !(orphanCleanupDays > 0)) return undefined
|
|
1841
|
+
cleaning = true
|
|
1842
|
+
try {
|
|
1843
|
+
const roots = new Set()
|
|
1844
|
+
try {
|
|
1845
|
+
const defaultDir = ctx.workingDirectory.defaultDirectory
|
|
1846
|
+
if (typeof defaultDir === 'string' && defaultDir) roots.add(defaultDir)
|
|
1847
|
+
} catch {
|
|
1848
|
+
/* no default directory */
|
|
1849
|
+
}
|
|
1850
|
+
const liveSessionIds = []
|
|
1851
|
+
try {
|
|
1852
|
+
for (const session of ctx.sessions.list()) {
|
|
1853
|
+
liveSessionIds.push(String(session.id))
|
|
1854
|
+
const dir = cwdOf(session)
|
|
1855
|
+
if (dir) roots.add(dir)
|
|
1856
|
+
}
|
|
1857
|
+
} catch {
|
|
1858
|
+
/* sessions unavailable this tick */
|
|
1859
|
+
}
|
|
1860
|
+
try {
|
|
1861
|
+
for (const workspace of workspaceRegistry?.list() ?? []) {
|
|
1862
|
+
if (workspace?.path) roots.add(workspace.path)
|
|
1863
|
+
}
|
|
1864
|
+
} catch {
|
|
1865
|
+
/* registry unavailable this tick */
|
|
1866
|
+
}
|
|
1867
|
+
const existingSessionIds = await collectPersistedSessionIds()
|
|
1868
|
+
const report = await cleanupOrphanedTempDirs({
|
|
1869
|
+
roots,
|
|
1870
|
+
rootDirName,
|
|
1871
|
+
orphanDays: orphanCleanupDays,
|
|
1872
|
+
dryRun,
|
|
1873
|
+
liveSessionIds,
|
|
1874
|
+
existingSessionIds,
|
|
1875
|
+
log: (message) => console.info(`[session-task-tmpdir] ${message}`),
|
|
1876
|
+
})
|
|
1877
|
+
if (
|
|
1878
|
+
report.deleted.length > 0 ||
|
|
1879
|
+
report.markedOrphaned.length > 0 ||
|
|
1880
|
+
report.kept.error > 0
|
|
1881
|
+
) {
|
|
1882
|
+
console.info(
|
|
1883
|
+
`[session-task-tmpdir] cleanup(${trigger})${report.dryRun ? ' dry-run' : ''}: ` +
|
|
1884
|
+
`deleted ${report.deleted.length}, marked ${report.markedOrphaned.length}, ` +
|
|
1885
|
+
`kept live ${report.kept.live} / alive ${report.kept.alive} / waiting ${report.kept.waiting} / ` +
|
|
1886
|
+
`unmarked ${report.kept.unmarked} / errors ${report.kept.error}`,
|
|
1887
|
+
)
|
|
1888
|
+
}
|
|
1889
|
+
// Attachment store sweep (v0.6): same tick, same 7-day semantics.
|
|
1890
|
+
if (withAttachments) {
|
|
1891
|
+
try {
|
|
1892
|
+
report.attachments = await runAttachmentCleanup(trigger, { dryRun })
|
|
1893
|
+
} catch (error) {
|
|
1894
|
+
console.warn('[session-task-tmpdir] attachment cleanup failed:', error?.message ?? error)
|
|
1895
|
+
report.attachments = { error: String(error?.message ?? error) }
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
return report
|
|
1899
|
+
} catch (error) {
|
|
1900
|
+
console.warn('[session-task-tmpdir] cleanup failed:', error?.message ?? error)
|
|
1901
|
+
return undefined
|
|
1902
|
+
} finally {
|
|
1903
|
+
cleaning = false
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
if (orphanCleanupDays > 0) {
|
|
1908
|
+
ctx.effect(() => {
|
|
1909
|
+
const startupTimer = setTimeout(() => {
|
|
1910
|
+
void runCleanup('startup')
|
|
1911
|
+
}, STARTUP_CLEANUP_DELAY_MS)
|
|
1912
|
+
const interval = setInterval(() => {
|
|
1913
|
+
void runCleanup('interval')
|
|
1914
|
+
}, cleanupIntervalHours * 3_600_000)
|
|
1915
|
+
return () => {
|
|
1916
|
+
clearTimeout(startupTimer)
|
|
1917
|
+
clearInterval(interval)
|
|
1918
|
+
}
|
|
1919
|
+
}, 'session-task-tmpdir: cleanup schedule')
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// ── prompt convention + tool ────────────────────────────────────────────────
|
|
1923
|
+
ctx.effect(() =>
|
|
1924
|
+
ctx.systemPrompt.context({
|
|
1925
|
+
name: 'session-task-tmpdir',
|
|
1926
|
+
order: 900,
|
|
1927
|
+
text: [
|
|
1928
|
+
'## Task temp folder (session-task-tmpdir)',
|
|
1929
|
+
'',
|
|
1930
|
+
`This session's task name is its session title. Put every scratch artifact (downloaded files, generated HTML/JSON/CSV, screenshots, debug logs, intermediate data) in \`${rootDirName}/<session title>/\` under the session working directory — never in the working-directory root.`,
|
|
1931
|
+
'Call the `task_tmpdir` tool to obtain the exact current absolute path: it creates the folder and renames it automatically when the session title changes, so always fetch the path again instead of hardcoding it.',
|
|
1932
|
+
'',
|
|
1933
|
+
'### Long-term files need the user’s approval first',
|
|
1934
|
+
'',
|
|
1935
|
+
'A file is "long-term" only when it must survive this session: reusable scripts/configs, cross-session records or backups, finished documents/reports the user will keep, or anything the user asks to keep. Everything else is scratch → `' +
|
|
1936
|
+
rootDirName +
|
|
1937
|
+
'/` and must NOT trigger a question.',
|
|
1938
|
+
`Before writing a long-term file **outside** \`${rootDirName}/\`, you MUST ask the user with \`ask_user_question\` (multiple choice; the free-text answer box lets the user type any other location), for example:`,
|
|
1939
|
+
'- A. 不长期保存',
|
|
1940
|
+
'- B. 工作区根目录保存',
|
|
1941
|
+
`Keep the option labels short exactly like the two above; put the explanation in each option's \`description\` instead (A: 放 ${rootDirName}/<会话标题>/,临时目录,随会话删除后 ${orphanCleanupDays} 天清理;B: 长期保存到会话工作区根目录下). Never stuff the path details into the label.`,
|
|
1942
|
+
'Do not write anything until the user answers.',
|
|
1943
|
+
'Picking B: keep it under the workspace root; pick a clear folder name yourself, call `longterm_approve` on it, then write — no need to ask the user to confirm the folder name (same as how DSH normally names things).',
|
|
1944
|
+
'Any answer other than A/B (e.g. a path the user typed in the free-text box) is a designated location: if it is missing or ambiguous, ask the user to confirm it before calling `longterm_approve` — never guess.',
|
|
1945
|
+
'After the user picks a long-term location (or when the task itself already named that location), call `longterm_approve` with that directory, then write there.',
|
|
1946
|
+
`If the user declines, says temporary, or the content is scratch: call \`task_tmpdir\` and write under \`${rootDirName}/<会话标题>/\`. Never invent a workspace-root folder instead.`,
|
|
1947
|
+
'',
|
|
1948
|
+
`The workspace root is guarded for both tool families: \`write\`/\`edit\` and shell tools (\`pwsh\`/\`bash\`) are denied when they would create something outside \`${rootDirName}/\` that the session has not approved. Allowed without approval: \`${rootDirName}/\`, approved long-term directories, existing plugin-source trees (${allowRootPatterns.join(', ')}), and root files ${allowRootFiles.join(', ') || '(none)'}.`,
|
|
1949
|
+
'',
|
|
1950
|
+
'### What the write guard covers (v0.7)',
|
|
1951
|
+
'',
|
|
1952
|
+
'The rule is enforced at the tool layer, not only in this text. Checked channels:',
|
|
1953
|
+
'- `write` / `edit` path arguments;',
|
|
1954
|
+
'- `publish` delivery copies (`source` → `target`, e.g. HarmonyOS `Download/<package>/`); `present` only displays an existing file and is not a write;',
|
|
1955
|
+
'- shell tools (`pwsh` / `bash`): literal absolute paths in commands that create something;',
|
|
1956
|
+
'- code-execution tools (`python` / `node` / …): write statements paired with path literals (static best-effort; dynamically built paths are not guaranteed);',
|
|
1957
|
+
'- any other tool whose schema declares path arguments: a new workspace-root entry or a destination outside the workspace is denied.',
|
|
1958
|
+
'',
|
|
1959
|
+
`Destinations outside the workspace count as long-term too. Allowed without asking: \`${rootDirName}/\`, already approved directories, DSH's own home, caches and the OS temp directory. When a write is denied, ask the user with \`ask_user_question\` and register the agreed directory with \`longterm_approve\` (it accepts directories outside the workspace as well).`,
|
|
1960
|
+
].join('\n'),
|
|
1961
|
+
}),
|
|
1962
|
+
)
|
|
1963
|
+
|
|
1964
|
+
ctx.effect(() =>
|
|
1965
|
+
ctx.tools.register({
|
|
1966
|
+
name: 'task_tmpdir',
|
|
1967
|
+
description: `Return and create this session's task temp directory (${rootDirName}/<session title>/) in the session working directory. Use it for scratch files instead of cluttering the workspace root. The folder follows session renames.`,
|
|
1968
|
+
parameters: {
|
|
1969
|
+
type: 'object',
|
|
1970
|
+
properties: {
|
|
1971
|
+
sub: { type: 'string', description: 'Optional subdirectory under the task temp directory.' },
|
|
1972
|
+
},
|
|
1973
|
+
additionalProperties: false,
|
|
1974
|
+
},
|
|
1975
|
+
output: {
|
|
1976
|
+
schema: {
|
|
1977
|
+
type: 'object',
|
|
1978
|
+
properties: {
|
|
1979
|
+
path: { type: 'string' },
|
|
1980
|
+
title: { type: 'string' },
|
|
1981
|
+
},
|
|
1982
|
+
required: ['path', 'title'],
|
|
1983
|
+
},
|
|
1984
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.path ?? '') }],
|
|
1985
|
+
},
|
|
1986
|
+
async execute(args, exec) {
|
|
1987
|
+
const agent = exec?.agent
|
|
1988
|
+
const session = agent ? ctx.sessions.get(agent.id) : undefined
|
|
1989
|
+
if (!session) throw new Error('task_tmpdir: no live session for this tool call')
|
|
1990
|
+
const result = await createDir(session, args?.sub)
|
|
1991
|
+
return result
|
|
1992
|
+
},
|
|
1993
|
+
}),
|
|
1994
|
+
)
|
|
1995
|
+
|
|
1996
|
+
// Long-term destination approval. The model may only call this after the user
|
|
1997
|
+
// picked a location (multiple-choice question) or after the task itself named it.
|
|
1998
|
+
ctx.effect(() =>
|
|
1999
|
+
ctx.tools.register({
|
|
2000
|
+
name: 'longterm_approve',
|
|
2001
|
+
description:
|
|
2002
|
+
'登记「本次会话已获用户同意的长期保存落点」。用户明确同意长期保存(或任务里已指定位置)后调用;' +
|
|
2003
|
+
`登记后 write/edit、shell 命令、publish 交付、python 等代码工具才能写该目录(工作区内或工作区外都可以),` +
|
|
2004
|
+
`否则会被拒绝并提示先问用户。临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
|
|
2005
|
+
parameters: {
|
|
2006
|
+
type: 'object',
|
|
2007
|
+
properties: {
|
|
2008
|
+
path: { type: 'string', description: '用户指定/同意的目录绝对路径(传文件路径也行,会自动取所在目录)。' },
|
|
2009
|
+
reason: { type: 'string', description: '为什么属于长期保存(一句话,用于日志)。' },
|
|
2010
|
+
basis: {
|
|
2011
|
+
type: 'string',
|
|
2012
|
+
enum: ['user_confirmed', 'task_designated'],
|
|
2013
|
+
description: 'user_confirmed=用户刚在选择题里同意长期保存;task_designated=用户在任务里明确指定了该位置。',
|
|
2014
|
+
},
|
|
2015
|
+
},
|
|
2016
|
+
required: ['path'],
|
|
2017
|
+
additionalProperties: false,
|
|
2018
|
+
},
|
|
2019
|
+
output: {
|
|
2020
|
+
schema: {
|
|
2021
|
+
type: 'object',
|
|
2022
|
+
properties: {
|
|
2023
|
+
approved: { type: 'boolean' },
|
|
2024
|
+
path: { type: 'string' },
|
|
2025
|
+
basis: { type: 'string' },
|
|
2026
|
+
approvedPrefixes: { type: 'array', items: { type: 'string' } },
|
|
2027
|
+
},
|
|
2028
|
+
required: ['approved', 'path'],
|
|
2029
|
+
},
|
|
2030
|
+
render: (_args, value) => [
|
|
2031
|
+
{ type: 'text', text: `approved: ${String(value?.path ?? '')}` },
|
|
2032
|
+
],
|
|
2033
|
+
},
|
|
2034
|
+
async execute(args, exec) {
|
|
2035
|
+
const agent = exec?.agent
|
|
2036
|
+
const session = agent ? ctx.sessions.get(agent.id) : undefined
|
|
2037
|
+
if (!session) throw new Error('longterm_approve: no live session for this tool call')
|
|
2038
|
+
const cwd = cwdOf(session)
|
|
2039
|
+
if (!cwd) throw new Error('longterm_approve: session working directory is unavailable')
|
|
2040
|
+
const raw = typeof args?.path === 'string' ? args.path.trim() : ''
|
|
2041
|
+
if (!raw) throw new Error('longterm_approve: path 不能为空')
|
|
2042
|
+
const expanded = expandTildePath(raw)
|
|
2043
|
+
const abs = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)
|
|
2044
|
+
const tmpRoot = baseDir(cwd)
|
|
2045
|
+
if (samePath(abs, tmpRoot) || pathInside(tmpRoot, abs)) {
|
|
2046
|
+
throw new Error(`longterm_approve: ${rootDirName}/ 是临时目录,不需要也不允许登记`)
|
|
2047
|
+
}
|
|
2048
|
+
if (isScratchPath(abs, rootDirName)) {
|
|
2049
|
+
throw new Error(`longterm_approve: 路径包含 ${rootDirName}/ 临时目录段,不需要也不允许登记`)
|
|
2050
|
+
}
|
|
2051
|
+
// v0.7 (review A9): registering the workspace root itself would whitelist the
|
|
2052
|
+
// whole workspace, so it is refused like a filesystem root.
|
|
2053
|
+
if (samePath(abs, cwd)) {
|
|
2054
|
+
throw new Error('longterm_approve: 不能登记会话工作区根目录本身,请指定工作区内的具体子目录(或工作区外的目录)')
|
|
2055
|
+
}
|
|
2056
|
+
const insideWorkspace = pathInside(cwd, abs)
|
|
2057
|
+
if (!insideWorkspace) {
|
|
2058
|
+
// v0.7: a destination outside the workspace (e.g. HarmonyOS
|
|
2059
|
+
// `Download/<package>/`) can be registered too, but never a filesystem
|
|
2060
|
+
// root, a whole drive or the user's home directory.
|
|
2061
|
+
const segments = abs.replace(/[\\/]+$/, '').split(/[\\/]+/).filter(Boolean)
|
|
2062
|
+
let fsRoot
|
|
2063
|
+
try {
|
|
2064
|
+
fsRoot = parse(abs).root
|
|
2065
|
+
} catch {
|
|
2066
|
+
fsRoot = undefined
|
|
2067
|
+
}
|
|
2068
|
+
if ((fsRoot && samePath(abs, fsRoot)) || samePath(abs, homedir()) || segments.length < 2) {
|
|
2069
|
+
throw new Error('longterm_approve: 不能登记磁盘根目录、用户主目录或层级过浅的目录,请指定具体文件夹')
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
const basis = args?.basis === 'task_designated' ? 'task_designated' : 'user_confirmed'
|
|
2073
|
+
let directory = abs
|
|
2074
|
+
try {
|
|
2075
|
+
if (existsSync(abs)) {
|
|
2076
|
+
if (!statSync(abs).isDirectory()) directory = dirname(abs)
|
|
2077
|
+
} else if (FILE_EXTENSION_PATTERN.test(basename(abs))) {
|
|
2078
|
+
// v0.7 (review A9): a not-yet-created file path registers its directory,
|
|
2079
|
+
// otherwise the next file in the same folder would still be denied.
|
|
2080
|
+
directory = dirname(abs)
|
|
2081
|
+
}
|
|
2082
|
+
} catch {
|
|
2083
|
+
// keep the passed path
|
|
2084
|
+
}
|
|
2085
|
+
const list = registerApproval(session, directory, { reason: args?.reason, basis })
|
|
2086
|
+
return {
|
|
2087
|
+
approved: true,
|
|
2088
|
+
path: directory,
|
|
2089
|
+
basis,
|
|
2090
|
+
approvedPrefixes: list.map((entry) => entry.prefix),
|
|
2091
|
+
}
|
|
2092
|
+
},
|
|
2093
|
+
}),
|
|
2094
|
+
)
|
|
2095
|
+
|
|
2096
|
+
// Manual cleanup trigger (also handy for verifying the scheduled pass).
|
|
2097
|
+
ctx.effect(() =>
|
|
2098
|
+
ctx.tools.register({
|
|
2099
|
+
name: 'tmp_cleanup', description: `Run the task temp folder cleanup now: marker-owned folders whose owning session has been deleted for more than ${orphanCleanupDays} days are removed, and (v0.6) the attachment store reclaims the blobs of sessions deleted more than ${attachmentCleanupDays} days ago; everything else is reported as kept. Pass dryRun to only report.`,
|
|
2100
|
+
parameters: {
|
|
2101
|
+
type: 'object',
|
|
2102
|
+
properties: {
|
|
2103
|
+
dryRun: { type: 'boolean', description: 'Only report what would be marked or deleted.' },
|
|
2104
|
+
attachments: { type: 'boolean', description: 'Also sweep the attachment store (default true).' },
|
|
2105
|
+
},
|
|
2106
|
+
additionalProperties: false,
|
|
2107
|
+
},
|
|
2108
|
+
output: {
|
|
2109
|
+
schema: {
|
|
2110
|
+
type: 'object',
|
|
2111
|
+
properties: {
|
|
2112
|
+
disabled: { type: 'boolean' },
|
|
2113
|
+
dryRun: { type: 'boolean' },
|
|
2114
|
+
deleted: { type: 'number' },
|
|
2115
|
+
markedOrphaned: { type: 'number' },
|
|
2116
|
+
kept: { type: 'object' },
|
|
2117
|
+
attachments: { type: 'object' },
|
|
2118
|
+
},
|
|
2119
|
+
},
|
|
2120
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
2121
|
+
},
|
|
2122
|
+
async execute(args) {
|
|
2123
|
+
const withAttachments = args?.attachments !== false
|
|
2124
|
+
const report = await runCleanup('manual', { dryRun: args?.dryRun === true, withAttachments })
|
|
2125
|
+
if (!report) return { disabled: true, dryRun: false, deleted: 0, markedOrphaned: 0, kept: {} }
|
|
2126
|
+
const value = {
|
|
2127
|
+
disabled: false,
|
|
2128
|
+
dryRun: report.dryRun,
|
|
2129
|
+
deleted: report.deleted.length,
|
|
2130
|
+
markedOrphaned: report.markedOrphaned.length,
|
|
2131
|
+
kept: report.kept,
|
|
2132
|
+
paths: report.deleted.map((entry) => entry.path),
|
|
2133
|
+
}
|
|
2134
|
+
if (report.attachments) {
|
|
2135
|
+
const a = report.attachments
|
|
2136
|
+
value.attachments = a.skipped || a.error
|
|
2137
|
+
? a
|
|
2138
|
+
: {
|
|
2139
|
+
dryRun: Boolean(a.dryRun),
|
|
2140
|
+
deleted: a.deleted ?? 0,
|
|
2141
|
+
freedMb: Number(((a.freedBytes ?? 0) / 1048576).toFixed(1)),
|
|
2142
|
+
dueSessions: a.dueSessions ?? 0,
|
|
2143
|
+
storedSessions: a.storedSessions ?? 0,
|
|
2144
|
+
objects: a.objects ?? 0,
|
|
2145
|
+
referencedBlobs: a.referencedBlobs ?? 0,
|
|
2146
|
+
markedOrphaned: a.markedOrphaned ?? 0,
|
|
2147
|
+
sweptOrphans: a.sweptOrphans ?? 0,
|
|
2148
|
+
skippedRecent: a.skippedRecent ?? 0,
|
|
2149
|
+
skippedReferenced: a.skippedReferenced ?? 0,
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
return value
|
|
2153
|
+
},
|
|
2154
|
+
}),
|
|
2155
|
+
)
|
|
2156
|
+
|
|
2157
|
+
// ── write guard (v0.5 root rules, v0.7 capability channels) ────────────────
|
|
2158
|
+
// Scratch files keep the v1 rules (temp-named files in the working-directory root
|
|
2159
|
+
// and files directly under `<rootDirName>/` are denied). Long-term artifacts
|
|
2160
|
+
// additionally require a session approval: `write`/`edit`, shell commands,
|
|
2161
|
+
// delivery copies made by `publish`, embedded code runtimes and other tools that
|
|
2162
|
+
// declare path arguments may not create anything outside `<rootDirName>/` (or
|
|
2163
|
+
// outside the workspace) until the model has asked the user and registered the
|
|
2164
|
+
// chosen directory with `longterm_approve`.
|
|
2165
|
+
if (guardWorkspaceRoot || requireApprovalOutsideTmp) {
|
|
2166
|
+
ctx.effect(
|
|
2167
|
+
() =>
|
|
2168
|
+
ctx.tools.guard((execution) => {
|
|
2169
|
+
try {
|
|
2170
|
+
if (!execution) return undefined
|
|
2171
|
+
const toolName = String(execution.name ?? '')
|
|
2172
|
+
const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : undefined
|
|
2173
|
+
if (!args) return undefined
|
|
2174
|
+
const agent = execution.agent
|
|
2175
|
+
if (!agent) return undefined
|
|
2176
|
+
const session = ctx.sessions.get(agent.id)
|
|
2177
|
+
if (!session) return undefined
|
|
2178
|
+
const cwd = cwdOf(session)
|
|
2179
|
+
if (!cwd) return undefined
|
|
2180
|
+
let schema = execution.schema
|
|
2181
|
+
if (!schema || typeof schema !== 'object') {
|
|
2182
|
+
try {
|
|
2183
|
+
schema = ctx.tools.get(toolName, agent)
|
|
2184
|
+
} catch {
|
|
2185
|
+
schema = undefined
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
const plan = toolWritePlan(toolName, args, {
|
|
2189
|
+
writeToolNames,
|
|
2190
|
+
publishToolNames,
|
|
2191
|
+
codeToolNames,
|
|
2192
|
+
shellToolNames,
|
|
2193
|
+
guardCodeTools,
|
|
2194
|
+
guardUnknownTools,
|
|
2195
|
+
guardPublish: publishGuard !== 'off',
|
|
2196
|
+
schema,
|
|
2197
|
+
})
|
|
2198
|
+
if (plan.channel === 'skip') return undefined
|
|
2199
|
+
|
|
2200
|
+
// v0.7 (review M5): only the v1 "workspace-root" rules depend on the session
|
|
2201
|
+
// working directory being a registered workspace root. Destinations outside
|
|
2202
|
+
// the workspace are checked even when the session `cd`-ed into a subfolder.
|
|
2203
|
+
const protectedRoot = isProtectedRoot(cwd)
|
|
2204
|
+
const approvedPrefixes = approvedPrefixesFor(session)
|
|
2205
|
+
const classifyOptions = {
|
|
2206
|
+
rootDirName,
|
|
2207
|
+
allowRootPatterns,
|
|
2208
|
+
allowRootFiles,
|
|
2209
|
+
approvedPrefixes,
|
|
2210
|
+
outsideAllow,
|
|
2211
|
+
requireApprovalOutsideTmp,
|
|
2212
|
+
guardOutsideWorkspace,
|
|
2213
|
+
}
|
|
2214
|
+
const deny = (label, reason) => {
|
|
2215
|
+
console.info(`[session-task-tmpdir] ${label} denied: ${reason}`)
|
|
2216
|
+
return reason
|
|
2217
|
+
}
|
|
2218
|
+
const outsideWarn = (label, abs) => {
|
|
2219
|
+
console.info(`[session-task-tmpdir] ${label} (warn): ${abs}`)
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
// write/edit: scratch rules first (v0.5), then the long-term classification
|
|
2223
|
+
if (plan.channel === 'write') {
|
|
2224
|
+
const targetPath = firstWriteTarget(args)
|
|
2225
|
+
if (!targetPath) return undefined
|
|
2226
|
+
// v0.8 claim-on-write: `<rootDirName>/<dir>/…` is always allowed, so the
|
|
2227
|
+
// claim can run before the long-term checks below.
|
|
2228
|
+
claimTmpTargets([targetPath], session)
|
|
2229
|
+
if (guardWorkspaceRoot && protectedRoot) {
|
|
2230
|
+
const scratchReason = workspaceRootGuardReason(targetPath, cwd, rootDirName)
|
|
2231
|
+
if (scratchReason) return deny(`${toolName} guard`, scratchReason)
|
|
2232
|
+
}
|
|
2233
|
+
const verdict = classifyWriteTarget(targetPath, cwd, classifyOptions)
|
|
2234
|
+
if (verdict.kind === 'inside-longterm') {
|
|
2235
|
+
if (!protectedRoot) return undefined
|
|
2236
|
+
return deny('longterm guard', verdict.reason)
|
|
2237
|
+
}
|
|
2238
|
+
if (verdict.kind === 'outside') {
|
|
2239
|
+
if (guardOutsideWorkspace === 'warn') {
|
|
2240
|
+
outsideWarn('outside guard', verdict.abs)
|
|
2241
|
+
return undefined
|
|
2242
|
+
}
|
|
2243
|
+
if (guardOutsideWorkspace === 'off') return undefined
|
|
2244
|
+
return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
|
|
2245
|
+
}
|
|
2246
|
+
return undefined
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
// publish: the tool copies a finished artifact into a delivery folder
|
|
2250
|
+
if (plan.channel === 'publish') {
|
|
2251
|
+
const publishBase =
|
|
2252
|
+
typeof publishBaseDir === 'string' && publishBaseDir.trim() ? resolve(cwd, publishBaseDir.trim()) : undefined
|
|
2253
|
+
for (const target of publishWriteTargets(args)) {
|
|
2254
|
+
const verdict = classifyWriteTarget(target, cwd, {
|
|
2255
|
+
...classifyOptions,
|
|
2256
|
+
baseDir: publishBase,
|
|
2257
|
+
})
|
|
2258
|
+
if (verdict.kind !== 'inside-longterm' && verdict.kind !== 'outside') continue
|
|
2259
|
+
if (verdict.kind === 'inside-longterm' && !protectedRoot) continue
|
|
2260
|
+
if (publishGuard === 'warn') {
|
|
2261
|
+
outsideWarn('publish guard', verdict.abs)
|
|
2262
|
+
continue
|
|
2263
|
+
}
|
|
2264
|
+
const reason =
|
|
2265
|
+
verdict.kind === 'outside'
|
|
2266
|
+
? outsideWriteDenialReason(verdict.abs, { rootDirName, action: '发布' })
|
|
2267
|
+
: `${verdict.reason}(发布目标:${verdict.abs})`
|
|
2268
|
+
return deny('publish guard', `publish 会把文件复制到长期位置:${reason}`)
|
|
2269
|
+
}
|
|
2270
|
+
claimTmpTargets(publishWriteTargets(args), session)
|
|
2271
|
+
return undefined
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
// code tools (python/node/…): best-effort static scan of write statements
|
|
2275
|
+
if (plan.channel === 'code') {
|
|
2276
|
+
const code = codeTextOf(args)
|
|
2277
|
+
if (!code) return undefined
|
|
2278
|
+
const scanned = []
|
|
2279
|
+
const reason = codeToolGuardReason(code, cwd, {
|
|
2280
|
+
...classifyOptions,
|
|
2281
|
+
guardOutsideWorkspace,
|
|
2282
|
+
skipInside: !protectedRoot,
|
|
2283
|
+
onTarget: (abs) => scanned.push(abs),
|
|
2284
|
+
})
|
|
2285
|
+
if (reason) return deny('code guard', reason)
|
|
2286
|
+
claimTmpTargets(scanned, session)
|
|
2287
|
+
return undefined
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
// shell tools: literal-path scan of commands that create something
|
|
2291
|
+
if (plan.channel === 'shell') {
|
|
2292
|
+
if (commandGuard === 'off') return undefined
|
|
2293
|
+
const command = typeof args.command === 'string' ? args.command : undefined
|
|
2294
|
+
if (!command) return undefined
|
|
2295
|
+
const commandBase =
|
|
2296
|
+
typeof args.workdir === 'string' && args.workdir.trim() ? resolve(cwd, args.workdir) : cwd
|
|
2297
|
+
const scanned = []
|
|
2298
|
+
const reason = longtermCommandGuardReason(command, cwd, {
|
|
2299
|
+
...classifyOptions,
|
|
2300
|
+
baseDir: commandBase,
|
|
2301
|
+
skipInside: !protectedRoot,
|
|
2302
|
+
onTarget: (abs) => scanned.push(abs),
|
|
2303
|
+
})
|
|
2304
|
+
if (reason && commandGuard !== 'warn') return deny('command guard', reason)
|
|
2305
|
+
if (reason) console.info(`[session-task-tmpdir] command guard (warn) ${reason}`)
|
|
2306
|
+
// v0.8: absolute tokens plus relative `<rootDirName>/…` mentions.
|
|
2307
|
+
claimTmpTargets([...scanned, ...relativeTmpTargets(command)], session, {
|
|
2308
|
+
allowDirItself: commandCreatesDirectory(command),
|
|
2309
|
+
})
|
|
2310
|
+
return undefined
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
// unknown but write-capable tools: only the two high-risk destinations
|
|
2314
|
+
if (plan.channel === 'unknown') {
|
|
2315
|
+
for (const target of collectPathTargets(args, { schema })) {
|
|
2316
|
+
const verdict = classifyWriteTarget(target, cwd, classifyOptions)
|
|
2317
|
+
if (verdict.kind === 'outside') {
|
|
2318
|
+
if (guardOutsideWorkspace === 'warn') {
|
|
2319
|
+
outsideWarn('outside guard', verdict.abs)
|
|
2320
|
+
continue
|
|
2321
|
+
}
|
|
2322
|
+
if (guardOutsideWorkspace === 'off') continue
|
|
2323
|
+
return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
|
|
2324
|
+
}
|
|
2325
|
+
if (verdict.kind === 'inside-longterm' && protectedRoot && samePath(dirname(verdict.abs), resolve(cwd))) {
|
|
2326
|
+
return deny('longterm guard', verdict.reason)
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
claimTmpTargets(collectPathTargets(args, { schema }), session)
|
|
2330
|
+
return undefined
|
|
2331
|
+
}
|
|
2332
|
+
return undefined
|
|
2333
|
+
} catch {
|
|
2334
|
+
return undefined
|
|
2335
|
+
}
|
|
2336
|
+
}),
|
|
2337
|
+
'session-task-tmpdir: write guard',
|
|
2338
|
+
)
|
|
2339
|
+
}
|
|
2340
|
+
}
|