@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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 +132 -194
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/cordis.patch.yml +4 -4
- package/package.json +40 -40
- package/src/assets.js +405 -348
- package/src/catalog.js +999 -605
- package/src/client.js +883 -4
- package/src/config.js +88 -88
- package/src/conversation-readers.js +198 -0
- package/src/conversation-store.js +583 -0
- package/src/export.js +273 -12
- package/src/index.js +282 -136
- package/src/native-transcript.js +217 -0
- package/src/project-archive.js +145 -145
- package/src/projects.js +1837 -980
- package/src/session-import.js +138 -93
- package/src/session-trace.js +121 -0
- package/src/skill-handoff.js +1327 -0
- package/src/skill-package.js +417 -0
- package/src/skill-provider.js +249 -0
- package/src/watch.js +319 -309
- package/web/Geist-OFL.txt +93 -93
- package/web/agent-icons/NOTICE.md +19 -19
- package/web/agent-icons/antigravity.svg +76 -76
- package/web/agent-icons/claude.svg +3 -3
- package/web/agent-icons/dsh.svg +58 -58
- package/web/agent-icons/licenses/copilot.txt +21 -21
- package/web/agent-icons/licenses/dsh.txt +21 -21
- package/web/agent-icons/licenses/gemini.txt +201 -201
- package/web/agent-icons/licenses/opencode.txt +21 -21
- package/web/agent-icons/licenses/qoder-notice.txt +18 -18
- package/web/agent-icons/licenses/qoder.txt +22 -22
- package/web/agent-icons/licenses/qwen.txt +202 -202
- package/web/agent-icons/qoder.svg +4 -4
- package/web/agent-icons/qwen.svg +5 -5
- package/web/agent-icons/workbuddy.svg +29 -29
- package/web/inline-process.css +22 -0
- package/web/markdown.js +225 -0
- package/web/panel.css +168 -151
- package/web/panel.html +82 -43
- package/web/panel.js +1316 -93
- package/web/project-context.js +25 -25
- package/web/reader.css +259 -0
- package/web/vendor/markdown-it-LICENSE.txt +156 -0
- package/web/vendor/markdown-it.mjs +3064 -0
package/src/catalog.js
CHANGED
|
@@ -1,605 +1,999 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process'
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
-
import { realpath, stat } from 'node:fs/promises'
|
|
4
|
-
import path, { win32 } from 'node:path'
|
|
5
|
-
import { promisify } from 'node:util'
|
|
6
|
-
import { listProjectAssets, readAsset } from './assets.js'
|
|
7
|
-
import { dateMillis,
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
} from './
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
function
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
return
|
|
148
|
-
}
|
|
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
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
if (
|
|
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
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
if (
|
|
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
|
-
const
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
const
|
|
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
|
-
}
|
|
469
|
-
if (
|
|
470
|
-
const
|
|
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
|
-
return
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
const
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
}
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
+
import { open, realpath, stat } from 'node:fs/promises'
|
|
4
|
+
import path, { win32 } from 'node:path'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import { authorizeProjectReference, listProjectAssets, readAsset, verifyAssetSource, verifySourceAuthorization } from './assets.js'
|
|
7
|
+
import { dateMillis, probeConversation, readProjectHistory, readSourceEvents, scanProjects } from './projects.js'
|
|
8
|
+
import {
|
|
9
|
+
approveConversation, discardConversation, finishConversation, readConversationSnapshot,
|
|
10
|
+
readHistoryPage, readPendingConversation, rebindConversation, stageConversation,
|
|
11
|
+
} from './conversation-store.js'
|
|
12
|
+
import { createSourceMonitor } from './watch.js'
|
|
13
|
+
import { makeExport } from './export.js'
|
|
14
|
+
import { countTrace, isSessionId, normalizeTrace } from './session-trace.js'
|
|
15
|
+
import { isMarkdownFile, relativeMarkdownLinks } from '../web/markdown.js'
|
|
16
|
+
import {
|
|
17
|
+
ProjectArchiveError, readProjectSelection, readProjectState, writeProjectArchive,
|
|
18
|
+
writeProjectContinuation, writeProjectPin, writeProjectSelection,
|
|
19
|
+
} from './project-archive.js'
|
|
20
|
+
|
|
21
|
+
const run = promisify(execFile)
|
|
22
|
+
const limit = 32_000
|
|
23
|
+
const fallbackScanInterval = 15_000
|
|
24
|
+
const ticketLifetime = 10 * 60_000
|
|
25
|
+
const catalogId = /^[0-9a-f]{24}$/
|
|
26
|
+
const traceBudget = { items: 200, bytes: 48 * 1024, resultBytes: 4 * 1024 }
|
|
27
|
+
|
|
28
|
+
class RequestError extends Error {
|
|
29
|
+
constructor(message, status = 400) {
|
|
30
|
+
super(message)
|
|
31
|
+
this.status = status
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function keyFor(...values) {
|
|
36
|
+
return createHash('sha256').update(JSON.stringify(values)).digest('hex').slice(0, 24)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function pathKey(value, platform = process.platform) {
|
|
40
|
+
const normalized = (platform === 'win32' ? win32 : path).normalize(value)
|
|
41
|
+
return platform === 'win32' ? normalized.toLowerCase() : normalized
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function mergeProjects(entries, platform = process.platform) {
|
|
45
|
+
const byPath = new Map()
|
|
46
|
+
for (const item of entries) {
|
|
47
|
+
if (typeof item.cwd !== 'string' || !(platform === 'win32' ? win32 : path).isAbsolute(item.cwd)) continue
|
|
48
|
+
const key = pathKey(item.cwd, platform)
|
|
49
|
+
if (!byPath.has(key)) byPath.set(key, {
|
|
50
|
+
id: keyFor(key), cwd: item.cwd, name: (platform === 'win32' ? win32 : path).basename(item.cwd) || item.cwd,
|
|
51
|
+
agents: [], projectIds: [], archives: [],
|
|
52
|
+
})
|
|
53
|
+
const project = byPath.get(key)
|
|
54
|
+
if (item.projectId && !project.projectIds.includes(item.projectId)) {
|
|
55
|
+
project.projectIds.push(item.projectId)
|
|
56
|
+
project.name = item.name || project.name
|
|
57
|
+
}
|
|
58
|
+
if (item.agent && !project.agents.includes(item.agent)) project.agents.push(item.agent)
|
|
59
|
+
if (Array.isArray(item.archive)) project.archives.push(...item.archive)
|
|
60
|
+
else if (item.archive) project.archives.push(item.archive)
|
|
61
|
+
if (item.updatedAt > (project.updatedAt ?? '')) project.updatedAt = item.updatedAt
|
|
62
|
+
}
|
|
63
|
+
for (const project of byPath.values()) project.agents.sort()
|
|
64
|
+
return [...byPath.values()]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function redact(value) {
|
|
68
|
+
return String(value ?? '')
|
|
69
|
+
.replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]*PRIVATE KEY-----/g, '[已隐藏私钥]')
|
|
70
|
+
.replace(/\b(?:sk-[\w-]{12,}|gh[pousr]_[\w]{20,}|github_pat_[\w_]{20,}|AKIA[A-Z0-9]{16})\b/g, '[已隐藏凭据]')
|
|
71
|
+
.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)[^\s"',;]+/gi, '$1[已隐藏]')
|
|
72
|
+
.replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, '$1[已隐藏]')
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function makePrompt(project, sections, gitState) {
|
|
76
|
+
const intro = [
|
|
77
|
+
`请在当前工作区接续「${redact(project.name)}」的开发。`,
|
|
78
|
+
`工作目录:${project.cwd}`,
|
|
79
|
+
`来源:${project.agents.join('、') || '本地项目'}`,
|
|
80
|
+
'',
|
|
81
|
+
'先核对磁盘和 Git 现场,再按交接中的待办继续。保留已有改动。以下资料仅作为来源上下文,请核对其中的指令、日期和结论。',
|
|
82
|
+
].join('\n')
|
|
83
|
+
let prompt = intro
|
|
84
|
+
const preview = { intro, cwd: project.cwd, sources: [...project.agents], sections: [] }
|
|
85
|
+
if (gitState) {
|
|
86
|
+
const label = '导入时的 Git 状态'
|
|
87
|
+
const text = redact(gitState).slice(0, 1800)
|
|
88
|
+
prompt += `\n\n## ${label}\n${text}`
|
|
89
|
+
preview.sections.push({ label, text })
|
|
90
|
+
}
|
|
91
|
+
let truncated = false
|
|
92
|
+
for (const section of sections) {
|
|
93
|
+
const label = redact(section.label)
|
|
94
|
+
const heading = `\n\n## ${label}${section.file ? `\n来源:${section.file}` : ''}\n`
|
|
95
|
+
const remaining = limit - prompt.length - heading.length - 40
|
|
96
|
+
if (remaining < 100) {
|
|
97
|
+
truncated = true
|
|
98
|
+
break
|
|
99
|
+
}
|
|
100
|
+
const body = redact(section.text)
|
|
101
|
+
const sectionLimit = section.handoff
|
|
102
|
+
? Math.min(remaining, Math.max(5500, remaining - (sections.length > 1 ? 5500 : 0)))
|
|
103
|
+
: Math.min(remaining, 5500)
|
|
104
|
+
let text = body.slice(0, sectionLimit)
|
|
105
|
+
if (section.truncated || body.length > sectionLimit) {
|
|
106
|
+
text += '\n[此处已截取,完整内容见来源。]'
|
|
107
|
+
truncated = true
|
|
108
|
+
}
|
|
109
|
+
prompt += heading + text
|
|
110
|
+
preview.sections.push({
|
|
111
|
+
label, file: section.file, text,
|
|
112
|
+
...(section.assetId ? { assetId: section.assetId } : {}),
|
|
113
|
+
...(section.conversation ? { conversation: true } : {}),
|
|
114
|
+
...(section.markdown ? { markdown: true } : {}),
|
|
115
|
+
...(section.truncated || body.length > sectionLimit ? { truncated: true } : {}),
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
if (truncated) {
|
|
119
|
+
preview.footer = '[交接上下文包含截取内容。]'
|
|
120
|
+
prompt += '\n\n' + preview.footer
|
|
121
|
+
}
|
|
122
|
+
return { prompt, truncated, preview: { ...preview, truncated } }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function gitStatus(cwd) {
|
|
126
|
+
try {
|
|
127
|
+
const { stdout } = await run('git', [
|
|
128
|
+
'--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', cwd, 'status', '--short',
|
|
129
|
+
'--branch', '--untracked-files=normal', '--ignore-submodules=all',
|
|
130
|
+
], { timeout: 2500, maxBuffer: 128 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })
|
|
131
|
+
return stdout.trim()
|
|
132
|
+
} catch {
|
|
133
|
+
return ''
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function publicProject({ archives, ...project }) {
|
|
138
|
+
return { ...project, sessions: archives.length, hasConversations: archives.some(canReadConversation) }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function canReadConversation(archive) {
|
|
142
|
+
// Antigravity's native CLI index stores prompts, not the assistant replies.
|
|
143
|
+
return archive.kind !== 'antigravity' && typeof archive.file === 'string'
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function conversationId(archive) {
|
|
147
|
+
return keyFor(archive.kind, archive.file, archive.table, archive.id)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function conversationTitle(value, bytes = 200) {
|
|
151
|
+
const normalized = redact(value).replace(/[\s\p{Cc}]+/gu, ' ').trim()
|
|
152
|
+
let title = ''
|
|
153
|
+
let length = 0
|
|
154
|
+
for (const char of normalized) {
|
|
155
|
+
length += Buffer.byteLength(char)
|
|
156
|
+
if (length > bytes) break
|
|
157
|
+
title += char
|
|
158
|
+
}
|
|
159
|
+
return title
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Source trace is shown to the user and stored with the imported session, so
|
|
163
|
+
// it is bounded and redacted exactly once here. Results are shortened before
|
|
164
|
+
// items are dropped so a long build log cannot hide the surrounding calls.
|
|
165
|
+
function limitUtf8(text, bytes) {
|
|
166
|
+
const data = Buffer.from(text, 'utf8')
|
|
167
|
+
if (data.length <= bytes) return text
|
|
168
|
+
while ((data[bytes] & 0xc0) === 0x80) bytes--
|
|
169
|
+
return data.toString('utf8', 0, bytes)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function conversationTrace(trace, messageCount, offset = 0) {
|
|
173
|
+
const items = []
|
|
174
|
+
const seen = new Set()
|
|
175
|
+
let bytes = 2 // JSON array brackets
|
|
176
|
+
let truncated = false
|
|
177
|
+
const indexOf = new Map()
|
|
178
|
+
for (const item of [...trace].reverse()) {
|
|
179
|
+
const index = Number.isInteger(item?.messageIndex) ? item.messageIndex - offset : undefined
|
|
180
|
+
// Records are shown under the question they belong to. One without a
|
|
181
|
+
// retained message, or whose message fell out of the window, cannot be
|
|
182
|
+
// placed anywhere the user can see, so it is dropped.
|
|
183
|
+
if (index === undefined || index < 0 || index >= messageCount) {
|
|
184
|
+
truncated = true
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
const text = redact(item?.text ?? '')
|
|
188
|
+
const bounded = limitUtf8(text, item?.kind === 'tool_result' ? traceBudget.resultBytes : 2000)
|
|
189
|
+
const [entry] = normalizeTrace([{
|
|
190
|
+
...item,
|
|
191
|
+
name: item.name ? redact(item.name) : undefined,
|
|
192
|
+
text: bounded,
|
|
193
|
+
truncated: text !== bounded || item.truncated === true,
|
|
194
|
+
messageIndex: index,
|
|
195
|
+
}])
|
|
196
|
+
if (!entry || seen.has(entry.id)) continue
|
|
197
|
+
const cost = Buffer.byteLength(JSON.stringify(entry)) + (items.length ? 1 : 0)
|
|
198
|
+
if (items.length >= traceBudget.items || bytes + cost > traceBudget.bytes) {
|
|
199
|
+
truncated = true
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
seen.add(entry.id)
|
|
203
|
+
bytes += cost
|
|
204
|
+
truncated ||= entry.truncated === true
|
|
205
|
+
items.unshift(entry)
|
|
206
|
+
indexOf.set(index, [entry.id, ...(indexOf.get(index) ?? [])])
|
|
207
|
+
}
|
|
208
|
+
return { trace: items, indexOf, truncated }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function currentDirectory(cwd) {
|
|
212
|
+
try {
|
|
213
|
+
const canonical = await realpath(cwd)
|
|
214
|
+
if ((await stat(canonical)).isDirectory()) return canonical
|
|
215
|
+
} catch {
|
|
216
|
+
// Historical sources may point to an offline drive or a removed worktree.
|
|
217
|
+
}
|
|
218
|
+
return null
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function conversationDirectory(cwd) {
|
|
222
|
+
if (typeof cwd !== 'string' || cwd.length > 4096 || !path.isAbsolute(cwd) || /[\u0000-\u001f]/u.test(cwd)) return
|
|
223
|
+
const canonical = await currentDirectory(cwd)
|
|
224
|
+
if (!canonical || canonical === path.parse(canonical).root) return
|
|
225
|
+
const info = await stat(canonical, { bigint: true }).catch(() => undefined)
|
|
226
|
+
if (info?.isDirectory()) return { path: canonical, identity: `${info.dev}:${info.ino}` }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function readConversationAttachment(project, archive, item) {
|
|
230
|
+
if (!item.path) return
|
|
231
|
+
const candidate = path.isAbsolute(item.path) ? path.normalize(item.path) : path.resolve(project.cwd, item.path)
|
|
232
|
+
let withinScope = false
|
|
233
|
+
for (const root of [project.cwd, path.join(path.dirname(archive.file), 'attachments')]) {
|
|
234
|
+
if (!root || !path.isAbsolute(root)) continue
|
|
235
|
+
const relative = path.relative(root, candidate)
|
|
236
|
+
if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) continue
|
|
237
|
+
withinScope = true
|
|
238
|
+
const href = relative.split(path.sep).map(encodeURIComponent).join('/')
|
|
239
|
+
const proof = await authorizeProjectReference(root, path.join(root, '.conversation'), href)
|
|
240
|
+
if (!proof.authorization) continue
|
|
241
|
+
const handle = await open(candidate, 'r').catch(() => undefined)
|
|
242
|
+
if (!handle) continue
|
|
243
|
+
try {
|
|
244
|
+
const initial = await handle.stat({ bigint: true })
|
|
245
|
+
const current = await verifySourceAuthorization(proof.authorization)
|
|
246
|
+
if (initial.dev !== current.fileInfo.dev || initial.ino !== current.fileInfo.ino) continue
|
|
247
|
+
if (initial.size > 32n * 1024n * 1024n) return { details: { status: 'attachment-too-large' } }
|
|
248
|
+
const bytes = Buffer.alloc(Number(initial.size))
|
|
249
|
+
let offset = 0
|
|
250
|
+
while (offset < bytes.length) {
|
|
251
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset)
|
|
252
|
+
if (!bytesRead) break
|
|
253
|
+
offset += bytesRead
|
|
254
|
+
}
|
|
255
|
+
const end = await handle.stat({ bigint: true })
|
|
256
|
+
await verifySourceAuthorization(proof.authorization)
|
|
257
|
+
if (offset === bytes.length && end.size === initial.size && end.mtimeNs === initial.mtimeNs && end.ctimeNs === initial.ctimeNs) {
|
|
258
|
+
return { bytes, details: { name: redact(path.basename(candidate)) } }
|
|
259
|
+
}
|
|
260
|
+
} catch { /* Source identity changed during the read. */ }
|
|
261
|
+
finally { await handle.close() }
|
|
262
|
+
}
|
|
263
|
+
return { details: { status: withinScope ? 'attachment-unavailable' : 'outside-project' } }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function sortProjects(a, b) {
|
|
267
|
+
return Number(b.online) - Number(a.online)
|
|
268
|
+
|| (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')
|
|
269
|
+
|| a.name.localeCompare(b.name, 'zh-CN')
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function applyProjectState(projects, { archivedIds, preferences }) {
|
|
273
|
+
const visibleState = []
|
|
274
|
+
for (const project of projects) {
|
|
275
|
+
const preference = preferences.get(project.id)
|
|
276
|
+
project.archived = archivedIds.has(project.id)
|
|
277
|
+
project.pinned = preference?.pinned ?? false
|
|
278
|
+
project.continuedAt = preference?.continuedAt ?? null
|
|
279
|
+
if (project.archived || project.pinned || project.continuedAt !== null) {
|
|
280
|
+
visibleState.push([project.id, project.archived, project.pinned, project.continuedAt])
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return keyFor(visibleState.sort((a, b) => a[0].localeCompare(b[0])))
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function storageFailure(operation, error, subject = '项目归档记录') {
|
|
287
|
+
const sqliteCode = error.errcode & 0xff
|
|
288
|
+
let detail = '请检查 agent-bridge-archive.sqlite 及其所在目录。'
|
|
289
|
+
if (error instanceof ProjectArchiveError) detail = error.message
|
|
290
|
+
else if ([5, 6].includes(sqliteCode)) detail = '归档数据库正忙,请重试。'
|
|
291
|
+
else if ([11, 26].includes(sqliteCode)) detail = '归档文件已损坏或格式无效。'
|
|
292
|
+
else if ([3, 8, 14].includes(sqliteCode) || ['EACCES', 'EPERM', 'EROFS'].includes(error.code)) {
|
|
293
|
+
detail = '请检查归档文件和目录的访问权限。'
|
|
294
|
+
}
|
|
295
|
+
return new RequestError(`无法${operation}${subject}。${detail}`, 503)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function loadProjectState(config) {
|
|
299
|
+
try { return await readProjectState(config) }
|
|
300
|
+
catch (error) { throw storageFailure('读取', error, '项目归档和偏好记录') }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function isCatalogId(id) {
|
|
304
|
+
return typeof id === 'string' && catalogId.test(id)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function requireProject(current, projectId) {
|
|
308
|
+
const project = current.projects.find(item => item.id === projectId)
|
|
309
|
+
if (!project) throw new RequestError('项目目录已刷新,请重新选择项目。', 404)
|
|
310
|
+
return project
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export function createCatalog(loadConfig, { importConversation, skillHandoff, loadSourceRecord } = {}) {
|
|
314
|
+
let snapshot
|
|
315
|
+
let scanning
|
|
316
|
+
let revision = 0
|
|
317
|
+
let epoch = 0
|
|
318
|
+
let disposed = false
|
|
319
|
+
const details = new Map()
|
|
320
|
+
const signatures = new Map()
|
|
321
|
+
const skillDetailRevisions = new Map()
|
|
322
|
+
const tickets = new Map()
|
|
323
|
+
const openReferences = new Map()
|
|
324
|
+
const conversationTickets = new Map()
|
|
325
|
+
const watched = new Map()
|
|
326
|
+
const listeners = new Set()
|
|
327
|
+
const monitor = createSourceMonitor({ onChange() {
|
|
328
|
+
epoch++
|
|
329
|
+
wake()
|
|
330
|
+
} })
|
|
331
|
+
|
|
332
|
+
function wake() {
|
|
333
|
+
for (const listener of listeners) listener()
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function waitForChange(knownRevision) {
|
|
337
|
+
if (knownRevision !== revision || snapshot?.epoch !== epoch || listeners.size >= 32 || disposed) return
|
|
338
|
+
return new Promise(resolve => {
|
|
339
|
+
function done() {
|
|
340
|
+
clearTimeout(timer)
|
|
341
|
+
listeners.delete(done)
|
|
342
|
+
resolve()
|
|
343
|
+
}
|
|
344
|
+
const timer = setTimeout(done, 5_000)
|
|
345
|
+
listeners.add(done)
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function synchronizeProjectState() {
|
|
350
|
+
if (scanning) await scanning
|
|
351
|
+
const current = snapshot
|
|
352
|
+
const state = await loadProjectState(current.config)
|
|
353
|
+
if (scanning || snapshot !== current) return synchronizeProjectState()
|
|
354
|
+
const stateFingerprint = applyProjectState(current.projects, state)
|
|
355
|
+
if (current.stateFingerprint !== stateFingerprint) {
|
|
356
|
+
current.stateFingerprint = stateFingerprint
|
|
357
|
+
revision++
|
|
358
|
+
wake()
|
|
359
|
+
}
|
|
360
|
+
return current
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function scan(refresh = false) {
|
|
364
|
+
if (scanning) return scanning
|
|
365
|
+
if (!refresh && snapshot?.epoch === epoch && Date.now() - snapshot.scannedAt < fallbackScanInterval) {
|
|
366
|
+
return synchronizeProjectState()
|
|
367
|
+
}
|
|
368
|
+
scanning = (async () => {
|
|
369
|
+
const scanEpoch = epoch
|
|
370
|
+
const config = await loadConfig()
|
|
371
|
+
const result = await scanProjects(config)
|
|
372
|
+
const resolved = new Map()
|
|
373
|
+
const aliases = [...new Set(result.projects.map(item => item.cwd))]
|
|
374
|
+
for (let i = 0; i < aliases.length; i += 64) {
|
|
375
|
+
await Promise.all(aliases.slice(i, i + 64).map(async cwd => resolved.set(cwd, await currentDirectory(cwd))))
|
|
376
|
+
}
|
|
377
|
+
const projects = mergeProjects(result.projects.map(item => ({ ...item, cwd: resolved.get(item.cwd) || item.cwd })))
|
|
378
|
+
const online = new Set([...resolved.values()].filter(Boolean).map(value => pathKey(value)))
|
|
379
|
+
for (const project of projects) {
|
|
380
|
+
project.online = online.has(pathKey(project.cwd))
|
|
381
|
+
if (watched.has(project.cwd)) watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds, archives: project.archives })
|
|
382
|
+
}
|
|
383
|
+
projects.sort(sortProjects)
|
|
384
|
+
const fingerprint = keyFor(projects, result.sources)
|
|
385
|
+
const stateFingerprint = applyProjectState(projects, await loadProjectState(config))
|
|
386
|
+
const changed = refresh || snapshot?.epoch !== scanEpoch || snapshot?.fingerprint !== fingerprint
|
|
387
|
+
|| snapshot?.stateFingerprint !== stateFingerprint
|
|
388
|
+
details.clear()
|
|
389
|
+
snapshot = { config, projects, sources: result.sources, scannedAt: Date.now(), fingerprint, stateFingerprint, epoch: scanEpoch, conversationLists: new Map() }
|
|
390
|
+
await monitor.update(config, [...watched.values()])
|
|
391
|
+
if (changed) {
|
|
392
|
+
revision++
|
|
393
|
+
wake()
|
|
394
|
+
}
|
|
395
|
+
return snapshot
|
|
396
|
+
})().finally(() => { scanning = undefined })
|
|
397
|
+
return scanning
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function setProjectArchive(input) {
|
|
401
|
+
if (typeof input.archived !== 'boolean' || !Array.isArray(input.projectIds) || !input.projectIds.length
|
|
402
|
+
|| !input.projectIds.every(isCatalogId)) {
|
|
403
|
+
throw new RequestError('归档请求格式无效,请重新选择项目。')
|
|
404
|
+
}
|
|
405
|
+
const projectIds = [...new Set(input.projectIds)]
|
|
406
|
+
const current = await scan()
|
|
407
|
+
const known = new Set(current.projects.map(project => project.id))
|
|
408
|
+
if (projectIds.some(id => !known.has(id))) throw new RequestError('有项目已不在当前目录中,请刷新后重试。', 404)
|
|
409
|
+
let changedProjectIds
|
|
410
|
+
try { changedProjectIds = await writeProjectArchive(current.config, projectIds, input.archived) }
|
|
411
|
+
catch (error) { throw storageFailure('保存', error) }
|
|
412
|
+
await synchronizeProjectState()
|
|
413
|
+
return { projectIds, changedProjectIds, archived: input.archived, revision }
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function setProjectPin({ projectId, pinned }) {
|
|
417
|
+
if (!isCatalogId(projectId) || typeof pinned !== 'boolean') throw new RequestError('置顶请求格式无效。')
|
|
418
|
+
const current = await scan()
|
|
419
|
+
requireProject(current, projectId)
|
|
420
|
+
try { await writeProjectPin(current.config, projectId, pinned) }
|
|
421
|
+
catch (error) { throw storageFailure('保存', error, '项目置顶') }
|
|
422
|
+
await synchronizeProjectState()
|
|
423
|
+
return { projectId, pinned, revision }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function setProjectSelection({ projectId, assetIds, history }) {
|
|
427
|
+
if (!isCatalogId(projectId) || typeof history !== 'boolean'
|
|
428
|
+
|| !Array.isArray(assetIds) || assetIds.length > 24 || !assetIds.every(isCatalogId)) {
|
|
429
|
+
throw new RequestError('资料选择格式无效,每个项目最多记住 24 项。')
|
|
430
|
+
}
|
|
431
|
+
const current = snapshot ?? await scan()
|
|
432
|
+
requireProject(current, projectId)
|
|
433
|
+
const selection = { assetIds: [...new Set(assetIds)], history }
|
|
434
|
+
try { await writeProjectSelection(current.config, projectId, selection) }
|
|
435
|
+
catch (error) { throw storageFailure('保存', error, '项目资料选择') }
|
|
436
|
+
return { projectId, selection }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function recordProjectContinuation(id) {
|
|
440
|
+
const ticket = getTicket(id)
|
|
441
|
+
if (!ticket.opened) throw new RequestError('请先打开交接草稿,再记录接续。', 409)
|
|
442
|
+
ticket.continuation ??= writeProjectContinuation(ticket.config, ticket.projectId).catch(error => {
|
|
443
|
+
delete ticket.continuation
|
|
444
|
+
throw storageFailure('保存', error, '项目接续记录')
|
|
445
|
+
})
|
|
446
|
+
const continuedAt = await ticket.continuation
|
|
447
|
+
await synchronizeProjectState()
|
|
448
|
+
return { projectId: ticket.projectId, continuedAt, revision }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function detail(id) {
|
|
452
|
+
const current = await scan()
|
|
453
|
+
const { config } = current
|
|
454
|
+
const project = requireProject(current, id)
|
|
455
|
+
if (skillHandoff?.revision) {
|
|
456
|
+
try {
|
|
457
|
+
const skillRevision = await skillHandoff.revision()
|
|
458
|
+
if (skillDetailRevisions.get(id) !== skillRevision) {
|
|
459
|
+
skillDetailRevisions.set(id, skillRevision)
|
|
460
|
+
if (details.has(id)) {
|
|
461
|
+
details.delete(id)
|
|
462
|
+
signatures.delete(id)
|
|
463
|
+
revision++
|
|
464
|
+
wake()
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
} catch { /* The text-only path remains available without a skill service. */ }
|
|
468
|
+
}
|
|
469
|
+
if (details.has(id)) return details.get(id)
|
|
470
|
+
const pending = (async () => {
|
|
471
|
+
if (!watched.has(project.cwd)) {
|
|
472
|
+
if (watched.size >= 4) watched.delete(watched.keys().next().value)
|
|
473
|
+
watched.set(project.cwd, { cwd: project.cwd, projectIds: project.projectIds, archives: project.archives })
|
|
474
|
+
await monitor.update(config, [...watched.values()])
|
|
475
|
+
}
|
|
476
|
+
const [{ memories, skills }, history] = await Promise.all([
|
|
477
|
+
listProjectAssets(project, config),
|
|
478
|
+
readProjectHistory(project, config),
|
|
479
|
+
])
|
|
480
|
+
const used = new Set(history.usedSkills.map(name => name.toLowerCase()))
|
|
481
|
+
const normalize = (item, kind) => ({
|
|
482
|
+
...item, kind, id: keyFor(kind, item.file, item.agent, item.scope),
|
|
483
|
+
used: kind === 'skill' && used.has(item.name.toLowerCase()),
|
|
484
|
+
})
|
|
485
|
+
const normalizedSkills = skills.map(item => normalize(item, 'skill'))
|
|
486
|
+
const inspected = skillHandoff
|
|
487
|
+
? await skillHandoff.inspect(project, normalizedSkills)
|
|
488
|
+
: {
|
|
489
|
+
available: false,
|
|
490
|
+
projectRoot: undefined,
|
|
491
|
+
skills: Object.fromEntries(normalizedSkills.map(item => [item.id, {
|
|
492
|
+
label: '仅可带入说明',
|
|
493
|
+
state: 'handoff',
|
|
494
|
+
action: 'view',
|
|
495
|
+
allowed: false,
|
|
496
|
+
current: false,
|
|
497
|
+
sourceChanged: false,
|
|
498
|
+
reason: '当前 DSH 未提供原生技能服务。',
|
|
499
|
+
}])),
|
|
500
|
+
}
|
|
501
|
+
for (const item of normalizedSkills) {
|
|
502
|
+
if (inspected.skills[item.id]) item.handoff = inspected.skills[item.id]
|
|
503
|
+
}
|
|
504
|
+
const result = {
|
|
505
|
+
project, history, config,
|
|
506
|
+
memories: memories.map(item => normalize(item, 'memory')),
|
|
507
|
+
skills: normalizedSkills,
|
|
508
|
+
skillNativeAvailable: inspected.available,
|
|
509
|
+
skillProjectRoot: inspected.projectRoot,
|
|
510
|
+
managedSkills: inspected.managedSkills ?? [],
|
|
511
|
+
}
|
|
512
|
+
if (current === snapshot) {
|
|
513
|
+
const assets = [...result.memories, ...result.skills].map(item => [publicAsset(item), item.revision])
|
|
514
|
+
const signature = keyFor(assets, result.managedSkills, history)
|
|
515
|
+
if (signatures.has(id) && signatures.get(id) !== signature) {
|
|
516
|
+
revision++
|
|
517
|
+
wake()
|
|
518
|
+
}
|
|
519
|
+
if (!signatures.has(id) && signatures.size >= 24) signatures.delete(signatures.keys().next().value)
|
|
520
|
+
signatures.set(id, signature)
|
|
521
|
+
}
|
|
522
|
+
return result
|
|
523
|
+
})().catch(error => {
|
|
524
|
+
if (details.get(id) === pending) details.delete(id)
|
|
525
|
+
throw error
|
|
526
|
+
})
|
|
527
|
+
if (details.size >= 24) details.delete(details.keys().next().value)
|
|
528
|
+
details.set(id, pending)
|
|
529
|
+
return pending
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function publicAsset({ id, name, agent, scope, detail, file, used, handoff }) {
|
|
533
|
+
return { id, name, agent, scope, detail, file, used, ...(handoff ? { handoff } : {}) }
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function prepare(input) {
|
|
537
|
+
const entry = await detail(input.projectId)
|
|
538
|
+
const current = await currentDirectory(entry.project.cwd)
|
|
539
|
+
const canImport = Boolean(current && pathKey(current) === pathKey(entry.project.cwd))
|
|
540
|
+
if (!Array.isArray(input.assetIds) || input.assetIds.length > 24 || input.assetIds.some(id => typeof id !== 'string')) {
|
|
541
|
+
throw new RequestError('每次交接最多选择 24 项记忆和 Skills。')
|
|
542
|
+
}
|
|
543
|
+
const selected = new Set(input.assetIds)
|
|
544
|
+
const assets = [...entry.memories, ...entry.skills].filter(item => selected.has(item.id))
|
|
545
|
+
if (assets.length !== selected.size) throw new RequestError('所选资料已变化,请刷新项目。', 409)
|
|
546
|
+
if (input.nativeSkillIds !== undefined && (!Array.isArray(input.nativeSkillIds)
|
|
547
|
+
|| input.nativeSkillIds.length > 8
|
|
548
|
+
|| input.nativeSkillIds.some(id => typeof id !== 'string' || !selected.has(id)))) {
|
|
549
|
+
throw new RequestError('已启用技能选择格式无效。')
|
|
550
|
+
}
|
|
551
|
+
const nativeSkillIds = new Set(input.nativeSkillIds ?? [])
|
|
552
|
+
const nativeAssets = assets.filter(item => item.kind === 'skill' && nativeSkillIds.has(item.id))
|
|
553
|
+
if (nativeAssets.length !== nativeSkillIds.size) {
|
|
554
|
+
throw new RequestError('已启用技能必须同时属于本次资料选择。')
|
|
555
|
+
}
|
|
556
|
+
let nativeApprovals = []
|
|
557
|
+
if (nativeAssets.length) {
|
|
558
|
+
if (!skillHandoff?.authorizeTextOmission) {
|
|
559
|
+
throw new RequestError('当前 DSH 无法确认技能的原生登记状态。', 409)
|
|
560
|
+
}
|
|
561
|
+
nativeApprovals = await skillHandoff.authorizeTextOmission(entry.project, nativeAssets)
|
|
562
|
+
}
|
|
563
|
+
const sectionAssets = assets.filter(item => !(item.kind === 'skill' && nativeSkillIds.has(item.id)))
|
|
564
|
+
const sections = await Promise.all(sectionAssets.map(async item => {
|
|
565
|
+
const result = await readAsset(item).catch(() => {
|
|
566
|
+
throw new RequestError(`无法读取「${item.name}」。请刷新后重试。`, 409)
|
|
567
|
+
})
|
|
568
|
+
return {
|
|
569
|
+
label: `${item.kind === 'memory' ? '记忆' : 'Skill'} · ${item.name}(${item.agent})`,
|
|
570
|
+
file: item.file, assetId: item.id, ...result,
|
|
571
|
+
handoff: assets.length === 1 && (item.agent === 'export' || item.detail === '项目交接'),
|
|
572
|
+
}
|
|
573
|
+
}))
|
|
574
|
+
if (nativeAssets.length) {
|
|
575
|
+
const approved = new Map(nativeApprovals.map(item => [item.assetId, item]))
|
|
576
|
+
sections.unshift({
|
|
577
|
+
label: '已启用 Skill',
|
|
578
|
+
text: `${nativeAssets.map(item => {
|
|
579
|
+
const name = item.handoff?.dshName || item.name
|
|
580
|
+
return approved.get(item.id)?.invocation?.modelInvocable === false ? `${name}(仅手动)` : name
|
|
581
|
+
}).join('、')} 已由 DSH 原生技能目录提供;按需调用,不在此重复正文。`,
|
|
582
|
+
})
|
|
583
|
+
}
|
|
584
|
+
let historyTrace
|
|
585
|
+
if (input.history === true) {
|
|
586
|
+
const retained = entry.history.messages.slice(-8)
|
|
587
|
+
const offset = entry.history.messages.length - retained.length
|
|
588
|
+
for (const message of retained) {
|
|
589
|
+
if (message.role !== 'user' && message.role !== 'assistant') continue
|
|
590
|
+
const author = message.role === 'user' ? '用户' : '助手'
|
|
591
|
+
sections.push({
|
|
592
|
+
label: [`近期会话 · ${author}`, message.agent].filter(Boolean).join(' · '),
|
|
593
|
+
text: message.text, conversation: true, markdown: message.role === 'assistant',
|
|
594
|
+
})
|
|
595
|
+
}
|
|
596
|
+
// The draft only carries the last few turns, so the trace is trimmed to
|
|
597
|
+
// the same window and re-indexed before it reaches the export preview.
|
|
598
|
+
historyTrace = conversationTrace(entry.history.trace ?? [], retained.length, offset).trace
|
|
599
|
+
}
|
|
600
|
+
const { prompt, truncated, preview } = makePrompt(entry.project, sections, canImport ? await gitStatus(current) : '')
|
|
601
|
+
for (const section of preview.sections) {
|
|
602
|
+
if (!isMarkdownFile(section.file)) continue
|
|
603
|
+
const asset = sectionAssets.find(item => item.id === section.assetId)
|
|
604
|
+
if (asset) section.references = await markdownReferences(entry, asset, section.text)
|
|
605
|
+
}
|
|
606
|
+
if (historyTrace?.length) preview.trace = historyTrace
|
|
607
|
+
for (const [key, value] of tickets) {
|
|
608
|
+
if (Date.now() - value.created > ticketLifetime) tickets.delete(key)
|
|
609
|
+
}
|
|
610
|
+
if (tickets.size >= 40) tickets.delete(tickets.keys().next().value)
|
|
611
|
+
const ticket = randomUUID()
|
|
612
|
+
tickets.set(ticket, {
|
|
613
|
+
created: Date.now(), path: canImport ? current : null, prompt, truncated, title: entry.project.name,
|
|
614
|
+
projectId: entry.project.id, config: entry.config, preview,
|
|
615
|
+
})
|
|
616
|
+
const skillCandidates = entry.skills.filter(item => selected.has(item.id)).map(item => ({
|
|
617
|
+
assetId: item.id,
|
|
618
|
+
...item.handoff,
|
|
619
|
+
}))
|
|
620
|
+
return { ticket, prompt, truncated, canImport, preview, skillCandidates }
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function getTicket(id) {
|
|
624
|
+
const ticket = tickets.get(id)
|
|
625
|
+
if (!ticket || Date.now() - ticket.created > ticketLifetime) throw new RequestError('预览已过期,请重新生成。', 409)
|
|
626
|
+
return ticket
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async function markdownReferences(entry, asset, text) {
|
|
630
|
+
const hrefs = relativeMarkdownLinks(text).slice(0, 128)
|
|
631
|
+
if (!hrefs.length) return []
|
|
632
|
+
const root = await currentDirectory(entry.project.cwd)
|
|
633
|
+
if (!root || pathKey(root) !== pathKey(entry.project.cwd)) return []
|
|
634
|
+
const references = await Promise.all(hrefs.map(async href => {
|
|
635
|
+
const { path: target, authorization, error, revealOnly } = await authorizeProjectReference(root, asset.file, href)
|
|
636
|
+
if (!authorization) return { href, path: target, error }
|
|
637
|
+
const id = randomUUID()
|
|
638
|
+
if (openReferences.size >= 2048) openReferences.delete(openReferences.keys().next().value)
|
|
639
|
+
openReferences.set(id, { projectId: entry.project.id, asset, authorization, revealOnly, created: Date.now() })
|
|
640
|
+
return { href, path: target, id }
|
|
641
|
+
}))
|
|
642
|
+
return references
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function getOpenReference(id, projectId) {
|
|
646
|
+
const reference = openReferences.get(id)
|
|
647
|
+
if (!reference || reference.projectId !== projectId || Date.now() - reference.created > ticketLifetime) {
|
|
648
|
+
throw new RequestError('文件链接已失效,请重新打开预览。', 409)
|
|
649
|
+
}
|
|
650
|
+
return reference
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function verifyOpenReference(reference, current) {
|
|
654
|
+
if (!current || pathKey(current) !== pathKey(reference.authorization.root)) {
|
|
655
|
+
throw new RequestError('项目目录已移动或不可访问。', 409)
|
|
656
|
+
}
|
|
657
|
+
try {
|
|
658
|
+
await verifyAssetSource(reference.asset)
|
|
659
|
+
const target = await verifySourceAuthorization(reference.authorization)
|
|
660
|
+
return { path: target.file, kind: 'file', name: path.basename(target.file), revealOnly: reference.revealOnly }
|
|
661
|
+
} catch {
|
|
662
|
+
throw new RequestError('链接文件已移动、被替换或不在项目范围内。', 409)
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async function exportPreview(ticket) {
|
|
667
|
+
const current = ticket.path && await currentDirectory(ticket.path)
|
|
668
|
+
if (!current) return ticket.preview
|
|
669
|
+
const sections = await Promise.all(ticket.preview.sections.map(async section => {
|
|
670
|
+
if (!section.references?.length) return section
|
|
671
|
+
const references = await Promise.all(section.references.map(async reference => {
|
|
672
|
+
if (!reference.id) return reference
|
|
673
|
+
try {
|
|
674
|
+
const grant = getOpenReference(reference.id, ticket.projectId)
|
|
675
|
+
const target = await verifyOpenReference(grant, current)
|
|
676
|
+
if (!target.revealOnly) return { ...reference, verifiedFile: target.path }
|
|
677
|
+
} catch { /* A stale reference is exported as text. */ }
|
|
678
|
+
return reference
|
|
679
|
+
}))
|
|
680
|
+
return { ...section, references }
|
|
681
|
+
}))
|
|
682
|
+
return { ...ticket.preview, sections }
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// The panel never supplies a free-form path for opening. It names an asset
|
|
686
|
+
// that is currently listed for the project (or the project directory
|
|
687
|
+
// itself), and the host re-reads the recorded authorization so a replaced
|
|
688
|
+
// file, a junction, or a moved source is refused instead of opened.
|
|
689
|
+
async function resolveOpenPath(input) {
|
|
690
|
+
const entry = await detail(input.projectId)
|
|
691
|
+
if (input.referenceId !== undefined) {
|
|
692
|
+
const reference = getOpenReference(input.referenceId, entry.project.id)
|
|
693
|
+
const current = await currentDirectory(entry.project.cwd)
|
|
694
|
+
return verifyOpenReference(reference, current)
|
|
695
|
+
}
|
|
696
|
+
if (input.directory === true) {
|
|
697
|
+
const current = await currentDirectory(entry.project.cwd)
|
|
698
|
+
if (!current || pathKey(current) !== pathKey(entry.project.cwd)) {
|
|
699
|
+
throw new RequestError('项目目录已移动或不可访问。', 409)
|
|
700
|
+
}
|
|
701
|
+
return { path: current, kind: 'directory', name: entry.project.name }
|
|
702
|
+
}
|
|
703
|
+
if (typeof input.assetId !== 'string' || !isCatalogId(input.assetId)) {
|
|
704
|
+
throw new RequestError('资料标识无效。')
|
|
705
|
+
}
|
|
706
|
+
const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
|
|
707
|
+
if (!item) throw new RequestError('找不到所选资料,请刷新项目。', 404)
|
|
708
|
+
let source
|
|
709
|
+
try {
|
|
710
|
+
source = await verifyAssetSource(item)
|
|
711
|
+
} catch {
|
|
712
|
+
throw new RequestError('资料已移动或内容已变化,请刷新项目后重试。', 409)
|
|
713
|
+
}
|
|
714
|
+
return { path: source.file, kind: 'file', name: item.name }
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
async function readableConversations(project, config) {
|
|
718
|
+
const archives = project.archives
|
|
719
|
+
.filter(canReadConversation)
|
|
720
|
+
.sort((a, b) => dateMillis(b.date) - dateMillis(a.date))
|
|
721
|
+
const unique = new Map()
|
|
722
|
+
for (const archive of archives) {
|
|
723
|
+
const id = conversationId(archive)
|
|
724
|
+
if (!unique.has(id)) unique.set(id, archive)
|
|
725
|
+
}
|
|
726
|
+
const candidates = [...unique]
|
|
727
|
+
const sessions = []
|
|
728
|
+
for (let offset = 0; offset < candidates.length; offset += 8) {
|
|
729
|
+
const batch = await Promise.all(candidates.slice(offset, offset + 8).map(async ([id, archive]) => {
|
|
730
|
+
const probe = await probeConversation(archive, { sourceCwd: project.cwd, config })
|
|
731
|
+
if (probe.state === 'empty') return undefined
|
|
732
|
+
return {
|
|
733
|
+
id, agent: archive.agent ?? archive.kind, date: dateMillis(archive.date),
|
|
734
|
+
title: conversationTitle(archive.title), archivedSource: archive.kind === 'agentsview',
|
|
735
|
+
...(probe.state === 'unknown' ? { unavailable: true, reason: probe.reason } : {}),
|
|
736
|
+
}
|
|
737
|
+
}))
|
|
738
|
+
sessions.push(...batch.filter(Boolean))
|
|
739
|
+
}
|
|
740
|
+
return sessions
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function listConversations(projectId, recent, cursor) {
|
|
744
|
+
const current = await scan()
|
|
745
|
+
const project = requireProject(current, projectId)
|
|
746
|
+
const { conversationLists, config } = current
|
|
747
|
+
if (!conversationLists.has(projectId)) {
|
|
748
|
+
conversationLists.set(projectId, readableConversations(project, config))
|
|
749
|
+
}
|
|
750
|
+
const sessions = await conversationLists.get(projectId)
|
|
751
|
+
const ready = sessions.filter(session => !session.unavailable)
|
|
752
|
+
const unavailable = sessions.filter(session => session.unavailable)
|
|
753
|
+
if (recent) return { sessions: ready.slice(0, 3), total: ready.length,
|
|
754
|
+
...(unavailable.length ? { unavailable: unavailable.slice(0, 20) } : {}) }
|
|
755
|
+
const marker = keyFor(ready.map(({ id }) => id))
|
|
756
|
+
const parsed = typeof cursor === 'string' && /^([0-9a-f]{24}):(\d{1,9})$/.exec(cursor)
|
|
757
|
+
if (cursor && (!parsed || parsed[1] !== marker)) throw new RequestError('会话列表已更新,请从第一页重新打开。', 409)
|
|
758
|
+
const offset = parsed ? Number(parsed[2]) : 0
|
|
759
|
+
const end = offset + 100
|
|
760
|
+
return { sessions: ready.slice(offset, end), ...(end < ready.length ? { nextCursor: `${marker}:${end}` } : {}),
|
|
761
|
+
...(!offset && unavailable.length ? { unavailable: unavailable.slice(0, 100) } : {}) }
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
async function previewConversation({ projectId, sessionId, targetCwd, snapshotId, signal }) {
|
|
765
|
+
if (!isCatalogId(sessionId)) throw new RequestError('会话标识无效。')
|
|
766
|
+
const current = await scan()
|
|
767
|
+
const project = requireProject(current, projectId)
|
|
768
|
+
const { config } = current
|
|
769
|
+
const archive = project.archives.find(item => canReadConversation(item) && conversationId(item) === sessionId)
|
|
770
|
+
const previous = snapshotId && await readConversationSnapshot(config, snapshotId)
|
|
771
|
+
if (snapshotId && (!previous || previous.projectId !== projectId || previous.sourceId !== sessionId || previous.state !== 'preview')) {
|
|
772
|
+
throw new RequestError('会话预览已变化,请重新打开。', 409)
|
|
773
|
+
}
|
|
774
|
+
if (!archive && !previous) throw new RequestError('找不到这条会话,请刷新项目。', 404)
|
|
775
|
+
const target = await conversationDirectory(targetCwd ?? project.cwd)
|
|
776
|
+
if (targetCwd !== undefined && !target) throw new RequestError('目标目录不可访问,请选择本机工作目录。', 409)
|
|
777
|
+
const ready = target && await readPendingConversation(config, projectId, sessionId, target.path)
|
|
778
|
+
const metadata = {
|
|
779
|
+
id: randomUUID(), sessionId: randomUUID(), projectId, sourceId: sessionId,
|
|
780
|
+
sourceCwd: project.cwd, targetCwd: target?.path, targetIdentity: target?.identity,
|
|
781
|
+
title: previous?.title ?? conversationTitle(archive.title, 80),
|
|
782
|
+
}
|
|
783
|
+
const record = ready ?? (previous
|
|
784
|
+
? await rebindConversation(config, previous, metadata)
|
|
785
|
+
: await stageConversation(config, metadata, readSourceEvents(archive, { config, sourceCwd: project.cwd, signal }), redact,
|
|
786
|
+
item => readConversationAttachment(project, archive, item)))
|
|
787
|
+
if (!record) throw new RequestError('会话预览已变化,请重新打开。', 409)
|
|
788
|
+
const messages = record.messages.map(({ role, text, time }) => ({ role, text, time }))
|
|
789
|
+
const { trace, indexOf, truncated: traceTruncated } = conversationTrace(record.trace, messages.length)
|
|
790
|
+
for (let index = 0; index < messages.length; index++) {
|
|
791
|
+
if (indexOf.has(index)) messages[index].traceIds = indexOf.get(index)
|
|
792
|
+
}
|
|
793
|
+
const traceCounts = countTrace(trace)
|
|
794
|
+
const { sourceStats, history } = record
|
|
795
|
+
const title = record.title || conversationTitle(messages[0]?.text, 80) || '迁入的 Agent 会话'
|
|
796
|
+
const canImport = Boolean(target && messages.length && record.targetIdentity === target.identity)
|
|
797
|
+
const skillCandidates = skillHandoff
|
|
798
|
+
&& (!target || pathKey(target.path) === pathKey(project.cwd))
|
|
799
|
+
? await skillHandoff.conversationCandidates(project, record.usedSkills, (await detail(projectId)).skills)
|
|
800
|
+
: []
|
|
801
|
+
return {
|
|
802
|
+
title, messages, ticket: canImport ? record.id : null, canImport, cwd: project.cwd,
|
|
803
|
+
sourceCwd: project.cwd, targetCwd: target?.path, history, resumePending: record.state === 'approved',
|
|
804
|
+
truncated: record.truncated || traceTruncated, skillCandidates, trace, traceCounts, sourceStats,
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
async function commitConversation(ticket) {
|
|
809
|
+
if (!isSessionId(ticket)) throw new RequestError('会话预览已过期,请重新打开。', 409)
|
|
810
|
+
if (conversationTickets.has(ticket)) return conversationTickets.get(ticket)
|
|
811
|
+
const pending = (async () => {
|
|
812
|
+
const config = await loadConfig()
|
|
813
|
+
const record = await readConversationSnapshot(config, ticket)
|
|
814
|
+
if (!record?.targetCwd || !record.messages.length) throw new RequestError('会话预览已过期或不能迁入,请重新打开。', 409)
|
|
815
|
+
if (record.state === 'done') return { sessionId: record.sessionId }
|
|
816
|
+
const target = await conversationDirectory(record.targetCwd)
|
|
817
|
+
if (!target || pathKey(target.path) !== pathKey(record.targetCwd) || target.identity !== record.targetIdentity) {
|
|
818
|
+
throw new RequestError('目标目录已变化,请重新选择目录。', 409)
|
|
819
|
+
}
|
|
820
|
+
if (record.state === 'preview' && !await approveConversation(config, ticket)) {
|
|
821
|
+
throw new RequestError('会话预览已过期或正在迁入,请重新打开。', 409)
|
|
822
|
+
}
|
|
823
|
+
record.config = config
|
|
824
|
+
record.title ||= conversationTitle(record.messages[0].text, 80) || '迁入的 Agent 会话'
|
|
825
|
+
record.trace = conversationTrace(record.trace, record.messages.length).trace
|
|
826
|
+
let result
|
|
827
|
+
try {
|
|
828
|
+
result = await importConversation(record, target.path)
|
|
829
|
+
await finishConversation(config, ticket, record.nativeTimeline)
|
|
830
|
+
} catch (error) {
|
|
831
|
+
if (error.status) throw error
|
|
832
|
+
const message = record.stored ? '会话历史已写入,暂时无法加入工作区。可重试打开。' : '无法将会话写入 DSH。请检查工作区和会话存储后重试。'
|
|
833
|
+
throw new RequestError(message, 503)
|
|
834
|
+
}
|
|
835
|
+
try {
|
|
836
|
+
await writeProjectContinuation(record.config, record.projectId)
|
|
837
|
+
await synchronizeProjectState()
|
|
838
|
+
} catch { /* A saved session remains usable even if the recents index cannot be updated. */ }
|
|
839
|
+
return result
|
|
840
|
+
})().finally(() => conversationTickets.delete(ticket))
|
|
841
|
+
conversationTickets.set(ticket, pending)
|
|
842
|
+
return pending
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
async function exportSession({ conversation, format, includeTrace, sessionId }) {
|
|
846
|
+
if (!conversation || typeof conversation.title !== 'string' || conversation.title.length > 500
|
|
847
|
+
|| typeof conversation.path !== 'string' || conversation.path.length > 4096
|
|
848
|
+
|| !path.isAbsolute(conversation.path) || /[\u0000-\u001f]/u.test(conversation.path)
|
|
849
|
+
|| !Array.isArray(conversation.messages) || conversation.messages.length > 24) {
|
|
850
|
+
throw new RequestError('DSH 会话资料格式无效。')
|
|
851
|
+
}
|
|
852
|
+
const sections = conversation.messages
|
|
853
|
+
.filter(message => (message?.role === 'user' || message?.role === 'assistant')
|
|
854
|
+
&& typeof message.text === 'string' && message.text.trim())
|
|
855
|
+
.map(message => ({ label: message.role === 'user' ? '用户' : 'DSH 助手', text: message.text,
|
|
856
|
+
conversation: true, markdown: message.role === 'assistant' }))
|
|
857
|
+
if (!sections.length) throw new RequestError('这段会话暂无可导出的消息。', 409)
|
|
858
|
+
const title = redact(conversation.title.trim()) || 'DSH 会话'
|
|
859
|
+
const { truncated, preview } = makePrompt({ name: title, cwd: conversation.path, agents: ['DSH'] }, sections, '')
|
|
860
|
+
const saved = includeTrace === true ? await loadSourceRecord?.(sessionId) : undefined
|
|
861
|
+
return makeExport({
|
|
862
|
+
title, origin: 'DSH 会话', format,
|
|
863
|
+
preview: { ...preview, truncated: truncated || conversation.truncated === true, trace: saved?.trace },
|
|
864
|
+
includeTrace: includeTrace === true,
|
|
865
|
+
})
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
return {
|
|
869
|
+
dispose() {
|
|
870
|
+
disposed = true
|
|
871
|
+
wake()
|
|
872
|
+
monitor.dispose()
|
|
873
|
+
tickets.clear()
|
|
874
|
+
openReferences.clear()
|
|
875
|
+
conversationTickets.clear()
|
|
876
|
+
},
|
|
877
|
+
async execute(action, input) {
|
|
878
|
+
if (action === 'catalog') {
|
|
879
|
+
const { projects, sources, scannedAt } = await scan(input.refresh === true)
|
|
880
|
+
return { projects: projects.map(publicProject), sources, scannedAt, revision }
|
|
881
|
+
}
|
|
882
|
+
if (action === 'set-project-archive') return setProjectArchive(input)
|
|
883
|
+
if (action === 'set-project-pin') return setProjectPin(input)
|
|
884
|
+
if (action === 'set-project-selection') return setProjectSelection(input)
|
|
885
|
+
if (action === 'record-project-continuation') return recordProjectContinuation(input.ticket)
|
|
886
|
+
if (action === 'conversation-history' || action === 'discard-conversation-preview') {
|
|
887
|
+
const config = await loadConfig()
|
|
888
|
+
const id = input.snapshotId ?? input.ticket
|
|
889
|
+
if (action === 'discard-conversation-preview') {
|
|
890
|
+
await discardConversation(config, id)
|
|
891
|
+
return {}
|
|
892
|
+
}
|
|
893
|
+
const page = await readHistoryPage(config, id, input.cursor, input.turn)
|
|
894
|
+
if (!page) throw new RequestError('来源历史已过期,请重新打开预览。', 404)
|
|
895
|
+
return page
|
|
896
|
+
}
|
|
897
|
+
if (action === 'preview-skill-activation') {
|
|
898
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
899
|
+
if (!isCatalogId(input.projectId) || !Array.isArray(input.assetIds)
|
|
900
|
+
|| !input.assetIds.length || input.assetIds.length > 8 || !input.assetIds.every(isCatalogId)) {
|
|
901
|
+
throw new RequestError('技能启用请求格式无效。')
|
|
902
|
+
}
|
|
903
|
+
const current = snapshot ?? await scan()
|
|
904
|
+
const project = requireProject(current, input.projectId)
|
|
905
|
+
const entry = await detail(project.id)
|
|
906
|
+
const wanted = new Set(input.assetIds)
|
|
907
|
+
const assets = entry.skills.filter(item => wanted.has(item.id))
|
|
908
|
+
if (assets.length !== wanted.size) throw new RequestError('所选技能已变化,请刷新项目。', 409)
|
|
909
|
+
return await skillHandoff.preview(project, assets)
|
|
910
|
+
}
|
|
911
|
+
if (action === 'apply-skill-activation') {
|
|
912
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
913
|
+
if (typeof input.ticket !== 'string' || input.ticket.length > 128) {
|
|
914
|
+
throw new RequestError('技能预览凭证无效。')
|
|
915
|
+
}
|
|
916
|
+
const result = await skillHandoff.apply(input.ticket)
|
|
917
|
+
details.clear()
|
|
918
|
+
revision++
|
|
919
|
+
wake()
|
|
920
|
+
return { ...result, revision }
|
|
921
|
+
}
|
|
922
|
+
if (action === 'deactivate-skill-activation' || action === 'undo-skill-activation') {
|
|
923
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
924
|
+
if (!isCatalogId(input.projectId) || !isCatalogId(input.activationId)) {
|
|
925
|
+
throw new RequestError('技能启用记录格式无效。')
|
|
926
|
+
}
|
|
927
|
+
const current = snapshot ?? await scan()
|
|
928
|
+
const project = requireProject(current, input.projectId)
|
|
929
|
+
const result = action === 'undo-skill-activation'
|
|
930
|
+
? await skillHandoff.undo(project, input.activationId)
|
|
931
|
+
: await skillHandoff.deactivate(project, input.activationId)
|
|
932
|
+
details.clear()
|
|
933
|
+
revision++
|
|
934
|
+
wake()
|
|
935
|
+
return { ...result, revision }
|
|
936
|
+
}
|
|
937
|
+
if (action === 'list-conversations' || action === 'preview-conversation' || action === 'import-conversation') {
|
|
938
|
+
if (!importConversation) throw new RequestError('当前 DSH 未提供会话迁入服务。', 409)
|
|
939
|
+
if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true, input.cursor)
|
|
940
|
+
if (action === 'preview-conversation') return previewConversation(input)
|
|
941
|
+
return commitConversation(input.ticket)
|
|
942
|
+
}
|
|
943
|
+
if (action === 'changes') {
|
|
944
|
+
const inspect = async () => {
|
|
945
|
+
const current = await scan()
|
|
946
|
+
if (current.projects.some(item => item.id === input.projectId)) await detail(input.projectId)
|
|
947
|
+
}
|
|
948
|
+
await inspect()
|
|
949
|
+
if (input.wait === true && input.revision === revision) {
|
|
950
|
+
await waitForChange(input.revision)
|
|
951
|
+
if (!disposed) await inspect()
|
|
952
|
+
}
|
|
953
|
+
return { revision, changed: input.revision !== revision, scannedAt: snapshot.scannedAt }
|
|
954
|
+
}
|
|
955
|
+
if (action === 'detail') {
|
|
956
|
+
const {
|
|
957
|
+
project, history, memories, skills, config, skillNativeAvailable, skillProjectRoot, managedSkills,
|
|
958
|
+
} = await detail(input.projectId)
|
|
959
|
+
let selection
|
|
960
|
+
try { selection = await readProjectSelection(config, project.id) }
|
|
961
|
+
catch (error) { throw storageFailure('读取', error, '项目资料选择') }
|
|
962
|
+
return {
|
|
963
|
+
project: publicProject(project), memories: memories.map(publicAsset), skills: skills.map(publicAsset),
|
|
964
|
+
usedSkills: history.usedSkills, historyCount: history.messages.length, selection,
|
|
965
|
+
skillNativeAvailable, skillProjectRoot, managedSkills,
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
if (action === 'asset') {
|
|
969
|
+
const entry = await detail(input.projectId)
|
|
970
|
+
const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
|
|
971
|
+
if (!item) throw new RequestError('找不到所选资料。', 404)
|
|
972
|
+
const result = await readAsset(item).catch(() => { throw new RequestError('资料已移动或不可读。', 409) })
|
|
973
|
+
const text = redact(result.text)
|
|
974
|
+
const references = isMarkdownFile(item.file) ? await markdownReferences(entry, item, text) : []
|
|
975
|
+
return { ...result, text, references }
|
|
976
|
+
}
|
|
977
|
+
if (action === 'preview') return prepare(input)
|
|
978
|
+
if (action === 'resolve-open-path') return resolveOpenPath(input)
|
|
979
|
+
if (action === 'export') {
|
|
980
|
+
const ticket = getTicket(input.ticket)
|
|
981
|
+
return makeExport({
|
|
982
|
+
title: redact(ticket.title), origin: '项目交接', format: input.format,
|
|
983
|
+
preview: await exportPreview(ticket), date: new Date(ticket.created),
|
|
984
|
+
includeTrace: input.includeTrace === true,
|
|
985
|
+
})
|
|
986
|
+
}
|
|
987
|
+
if (action === 'export-session') return exportSession(input)
|
|
988
|
+
if (action === 'open') {
|
|
989
|
+
const ticket = getTicket(input.ticket)
|
|
990
|
+
if (!ticket.path) throw new RequestError('原工作目录不可访问。可导出交接。', 409)
|
|
991
|
+
const current = await currentDirectory(ticket.path)
|
|
992
|
+
if (!current || pathKey(current) !== pathKey(ticket.path)) throw new RequestError('原工作目录已变化。', 409)
|
|
993
|
+
ticket.opened = true
|
|
994
|
+
return { path: current, prompt: ticket.prompt }
|
|
995
|
+
}
|
|
996
|
+
throw new RequestError('找不到该操作。', 404)
|
|
997
|
+
},
|
|
998
|
+
}
|
|
999
|
+
}
|