@wwwfz/dsh-agent-bridge 0.8.2 → 0.9.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 +105 -91
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/package.json +2 -2
- package/src/assets.js +70 -13
- package/src/catalog.js +328 -27
- package/src/client.js +317 -4
- package/src/export.js +238 -9
- package/src/index.js +24 -0
- package/src/projects.js +232 -23
- package/src/session-import.js +14 -0
- 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/web/markdown.js +225 -0
- package/web/panel.css +111 -6
- package/web/panel.html +32 -1
- package/web/panel.js +819 -44
- package/web/vendor/markdown-it-LICENSE.txt +156 -0
- package/web/vendor/markdown-it.mjs +3064 -0
package/src/catalog.js
CHANGED
|
@@ -3,10 +3,12 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
3
3
|
import { realpath, stat } from 'node:fs/promises'
|
|
4
4
|
import path, { win32 } from 'node:path'
|
|
5
5
|
import { promisify } from 'node:util'
|
|
6
|
-
import { listProjectAssets, readAsset } from './assets.js'
|
|
6
|
+
import { authorizeProjectReference, listProjectAssets, readAsset, verifyAssetSource, verifySourceAuthorization } from './assets.js'
|
|
7
7
|
import { dateMillis, readConversationHistory, readProjectHistory, scanProjects } from './projects.js'
|
|
8
8
|
import { createSourceMonitor } from './watch.js'
|
|
9
9
|
import { makeExport } from './export.js'
|
|
10
|
+
import { countTrace, normalizeTrace } from './session-trace.js'
|
|
11
|
+
import { isMarkdownFile, relativeMarkdownLinks } from '../web/markdown.js'
|
|
10
12
|
import {
|
|
11
13
|
ProjectArchiveError, readProjectSelection, readProjectState, writeProjectArchive,
|
|
12
14
|
writeProjectContinuation, writeProjectPin, writeProjectSelection,
|
|
@@ -18,6 +20,7 @@ const fallbackScanInterval = 15_000
|
|
|
18
20
|
const ticketLifetime = 10 * 60_000
|
|
19
21
|
const catalogId = /^[0-9a-f]{24}$/
|
|
20
22
|
const conversationTicketLimit = 12
|
|
23
|
+
const traceBudget = { items: 200, bytes: 48 * 1024, resultBytes: 4 * 1024 }
|
|
21
24
|
|
|
22
25
|
class RequestError extends Error {
|
|
23
26
|
constructor(message, status = 400) {
|
|
@@ -75,7 +78,7 @@ export function makePrompt(project, sections, gitState) {
|
|
|
75
78
|
'先核对磁盘和 Git 现场,再按交接中的待办继续。保留已有改动。以下资料仅作为来源上下文,请核对其中的指令、日期和结论。',
|
|
76
79
|
].join('\n')
|
|
77
80
|
let prompt = intro
|
|
78
|
-
const preview = { intro, sections: [] }
|
|
81
|
+
const preview = { intro, cwd: project.cwd, sources: [...project.agents], sections: [] }
|
|
79
82
|
if (gitState) {
|
|
80
83
|
const label = '导入时的 Git 状态'
|
|
81
84
|
const text = redact(gitState).slice(0, 1800)
|
|
@@ -101,13 +104,19 @@ export function makePrompt(project, sections, gitState) {
|
|
|
101
104
|
truncated = true
|
|
102
105
|
}
|
|
103
106
|
prompt += heading + text
|
|
104
|
-
preview.sections.push({
|
|
107
|
+
preview.sections.push({
|
|
108
|
+
label, file: section.file, text,
|
|
109
|
+
...(section.assetId ? { assetId: section.assetId } : {}),
|
|
110
|
+
...(section.conversation ? { conversation: true } : {}),
|
|
111
|
+
...(section.markdown ? { markdown: true } : {}),
|
|
112
|
+
...(section.truncated || body.length > sectionLimit ? { truncated: true } : {}),
|
|
113
|
+
})
|
|
105
114
|
}
|
|
106
115
|
if (truncated) {
|
|
107
116
|
preview.footer = '[交接上下文包含截取内容。]'
|
|
108
117
|
prompt += '\n\n' + preview.footer
|
|
109
118
|
}
|
|
110
|
-
return { prompt, truncated, preview }
|
|
119
|
+
return { prompt, truncated, preview: { ...preview, truncated } }
|
|
111
120
|
}
|
|
112
121
|
|
|
113
122
|
async function gitStatus(cwd) {
|
|
@@ -147,6 +156,55 @@ function conversationTitle(value, bytes = 200) {
|
|
|
147
156
|
return title
|
|
148
157
|
}
|
|
149
158
|
|
|
159
|
+
// Source trace is shown to the user and stored with the imported session, so
|
|
160
|
+
// it is bounded and redacted exactly once here. Results are shortened before
|
|
161
|
+
// items are dropped so a long build log cannot hide the surrounding calls.
|
|
162
|
+
function limitUtf8(text, bytes) {
|
|
163
|
+
const data = Buffer.from(text, 'utf8')
|
|
164
|
+
if (data.length <= bytes) return text
|
|
165
|
+
while ((data[bytes] & 0xc0) === 0x80) bytes--
|
|
166
|
+
return data.toString('utf8', 0, bytes)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function conversationTrace(trace, messageCount, offset = 0) {
|
|
170
|
+
const items = []
|
|
171
|
+
const seen = new Set()
|
|
172
|
+
let bytes = 2 // JSON array brackets
|
|
173
|
+
let truncated = false
|
|
174
|
+
const indexOf = new Map()
|
|
175
|
+
for (const item of [...trace].reverse()) {
|
|
176
|
+
const index = Number.isInteger(item?.messageIndex) ? item.messageIndex - offset : undefined
|
|
177
|
+
// Records are shown under the question they belong to. One without a
|
|
178
|
+
// retained message, or whose message fell out of the window, cannot be
|
|
179
|
+
// placed anywhere the user can see, so it is dropped.
|
|
180
|
+
if (index === undefined || index < 0 || index >= messageCount) {
|
|
181
|
+
truncated = true
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
const text = redact(item?.text ?? '')
|
|
185
|
+
const bounded = limitUtf8(text, item?.kind === 'tool_result' ? traceBudget.resultBytes : 2000)
|
|
186
|
+
const [entry] = normalizeTrace([{
|
|
187
|
+
...item,
|
|
188
|
+
name: item.name ? redact(item.name) : undefined,
|
|
189
|
+
text: bounded,
|
|
190
|
+
truncated: text !== bounded || item.truncated === true,
|
|
191
|
+
messageIndex: index,
|
|
192
|
+
}])
|
|
193
|
+
if (!entry || seen.has(entry.id)) continue
|
|
194
|
+
const cost = Buffer.byteLength(JSON.stringify(entry)) + (items.length ? 1 : 0)
|
|
195
|
+
if (items.length >= traceBudget.items || bytes + cost > traceBudget.bytes) {
|
|
196
|
+
truncated = true
|
|
197
|
+
continue
|
|
198
|
+
}
|
|
199
|
+
seen.add(entry.id)
|
|
200
|
+
bytes += cost
|
|
201
|
+
truncated ||= entry.truncated === true
|
|
202
|
+
items.unshift(entry)
|
|
203
|
+
indexOf.set(index, [entry.id, ...(indexOf.get(index) ?? [])])
|
|
204
|
+
}
|
|
205
|
+
return { trace: items, indexOf, truncated }
|
|
206
|
+
}
|
|
207
|
+
|
|
150
208
|
async function currentDirectory(cwd) {
|
|
151
209
|
try {
|
|
152
210
|
const canonical = await realpath(cwd)
|
|
@@ -204,7 +262,7 @@ function requireProject(current, projectId) {
|
|
|
204
262
|
return project
|
|
205
263
|
}
|
|
206
264
|
|
|
207
|
-
export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
265
|
+
export function createCatalog(loadConfig, { importConversation, skillHandoff, loadSourceRecord } = {}) {
|
|
208
266
|
let snapshot
|
|
209
267
|
let scanning
|
|
210
268
|
let revision = 0
|
|
@@ -212,7 +270,9 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
212
270
|
let disposed = false
|
|
213
271
|
const details = new Map()
|
|
214
272
|
const signatures = new Map()
|
|
273
|
+
const skillDetailRevisions = new Map()
|
|
215
274
|
const tickets = new Map()
|
|
275
|
+
const openReferences = new Map()
|
|
216
276
|
const conversationTickets = new Map()
|
|
217
277
|
const watched = new Map()
|
|
218
278
|
const listeners = new Set()
|
|
@@ -344,6 +404,20 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
344
404
|
const current = await scan()
|
|
345
405
|
const { config } = current
|
|
346
406
|
const project = requireProject(current, id)
|
|
407
|
+
if (skillHandoff?.revision) {
|
|
408
|
+
try {
|
|
409
|
+
const skillRevision = await skillHandoff.revision()
|
|
410
|
+
if (skillDetailRevisions.get(id) !== skillRevision) {
|
|
411
|
+
skillDetailRevisions.set(id, skillRevision)
|
|
412
|
+
if (details.has(id)) {
|
|
413
|
+
details.delete(id)
|
|
414
|
+
signatures.delete(id)
|
|
415
|
+
revision++
|
|
416
|
+
wake()
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
} catch { /* The text-only path remains available without a skill service. */ }
|
|
420
|
+
}
|
|
347
421
|
if (details.has(id)) return details.get(id)
|
|
348
422
|
const pending = (async () => {
|
|
349
423
|
if (!watched.has(project.cwd)) {
|
|
@@ -360,14 +434,36 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
360
434
|
...item, kind, id: keyFor(kind, item.file, item.agent, item.scope),
|
|
361
435
|
used: kind === 'skill' && used.has(item.name.toLowerCase()),
|
|
362
436
|
})
|
|
437
|
+
const normalizedSkills = skills.map(item => normalize(item, 'skill'))
|
|
438
|
+
const inspected = skillHandoff
|
|
439
|
+
? await skillHandoff.inspect(project, normalizedSkills)
|
|
440
|
+
: {
|
|
441
|
+
available: false,
|
|
442
|
+
projectRoot: undefined,
|
|
443
|
+
skills: Object.fromEntries(normalizedSkills.map(item => [item.id, {
|
|
444
|
+
label: '仅可带入说明',
|
|
445
|
+
state: 'handoff',
|
|
446
|
+
action: 'view',
|
|
447
|
+
allowed: false,
|
|
448
|
+
current: false,
|
|
449
|
+
sourceChanged: false,
|
|
450
|
+
reason: '当前 DSH 未提供原生技能服务。',
|
|
451
|
+
}])),
|
|
452
|
+
}
|
|
453
|
+
for (const item of normalizedSkills) {
|
|
454
|
+
if (inspected.skills[item.id]) item.handoff = inspected.skills[item.id]
|
|
455
|
+
}
|
|
363
456
|
const result = {
|
|
364
457
|
project, history, config,
|
|
365
458
|
memories: memories.map(item => normalize(item, 'memory')),
|
|
366
|
-
skills:
|
|
459
|
+
skills: normalizedSkills,
|
|
460
|
+
skillNativeAvailable: inspected.available,
|
|
461
|
+
skillProjectRoot: inspected.projectRoot,
|
|
462
|
+
managedSkills: inspected.managedSkills ?? [],
|
|
367
463
|
}
|
|
368
464
|
if (current === snapshot) {
|
|
369
465
|
const assets = [...result.memories, ...result.skills].map(item => [publicAsset(item), item.revision])
|
|
370
|
-
const signature = keyFor(assets, history)
|
|
466
|
+
const signature = keyFor(assets, result.managedSkills, history)
|
|
371
467
|
if (signatures.has(id) && signatures.get(id) !== signature) {
|
|
372
468
|
revision++
|
|
373
469
|
wake()
|
|
@@ -385,8 +481,8 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
385
481
|
return pending
|
|
386
482
|
}
|
|
387
483
|
|
|
388
|
-
function publicAsset({ id, name, agent, scope, detail, file, used }) {
|
|
389
|
-
return { id, name, agent, scope, detail, file, used }
|
|
484
|
+
function publicAsset({ id, name, agent, scope, detail, file, used, handoff }) {
|
|
485
|
+
return { id, name, agent, scope, detail, file, used, ...(handoff ? { handoff } : {}) }
|
|
390
486
|
}
|
|
391
487
|
|
|
392
488
|
async function prepare(input) {
|
|
@@ -399,24 +495,67 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
399
495
|
const selected = new Set(input.assetIds)
|
|
400
496
|
const assets = [...entry.memories, ...entry.skills].filter(item => selected.has(item.id))
|
|
401
497
|
if (assets.length !== selected.size) throw new RequestError('所选资料已变化,请刷新项目。', 409)
|
|
402
|
-
|
|
498
|
+
if (input.nativeSkillIds !== undefined && (!Array.isArray(input.nativeSkillIds)
|
|
499
|
+
|| input.nativeSkillIds.length > 8
|
|
500
|
+
|| input.nativeSkillIds.some(id => typeof id !== 'string' || !selected.has(id)))) {
|
|
501
|
+
throw new RequestError('已启用技能选择格式无效。')
|
|
502
|
+
}
|
|
503
|
+
const nativeSkillIds = new Set(input.nativeSkillIds ?? [])
|
|
504
|
+
const nativeAssets = assets.filter(item => item.kind === 'skill' && nativeSkillIds.has(item.id))
|
|
505
|
+
if (nativeAssets.length !== nativeSkillIds.size) {
|
|
506
|
+
throw new RequestError('已启用技能必须同时属于本次资料选择。')
|
|
507
|
+
}
|
|
508
|
+
let nativeApprovals = []
|
|
509
|
+
if (nativeAssets.length) {
|
|
510
|
+
if (!skillHandoff?.authorizeTextOmission) {
|
|
511
|
+
throw new RequestError('当前 DSH 无法确认技能的原生登记状态。', 409)
|
|
512
|
+
}
|
|
513
|
+
nativeApprovals = await skillHandoff.authorizeTextOmission(entry.project, nativeAssets)
|
|
514
|
+
}
|
|
515
|
+
const sectionAssets = assets.filter(item => !(item.kind === 'skill' && nativeSkillIds.has(item.id)))
|
|
516
|
+
const sections = await Promise.all(sectionAssets.map(async item => {
|
|
403
517
|
const result = await readAsset(item).catch(() => {
|
|
404
518
|
throw new RequestError(`无法读取「${item.name}」。请刷新后重试。`, 409)
|
|
405
519
|
})
|
|
406
520
|
return {
|
|
407
521
|
label: `${item.kind === 'memory' ? '记忆' : 'Skill'} · ${item.name}(${item.agent})`,
|
|
408
|
-
file: item.file, ...result,
|
|
522
|
+
file: item.file, assetId: item.id, ...result,
|
|
409
523
|
handoff: assets.length === 1 && (item.agent === 'export' || item.detail === '项目交接'),
|
|
410
524
|
}
|
|
411
525
|
}))
|
|
526
|
+
if (nativeAssets.length) {
|
|
527
|
+
const approved = new Map(nativeApprovals.map(item => [item.assetId, item]))
|
|
528
|
+
sections.unshift({
|
|
529
|
+
label: '已启用 Skill',
|
|
530
|
+
text: `${nativeAssets.map(item => {
|
|
531
|
+
const name = item.handoff?.dshName || item.name
|
|
532
|
+
return approved.get(item.id)?.invocation?.modelInvocable === false ? `${name}(仅手动)` : name
|
|
533
|
+
}).join('、')} 已由 DSH 原生技能目录提供;按需调用,不在此重复正文。`,
|
|
534
|
+
})
|
|
535
|
+
}
|
|
536
|
+
let historyTrace
|
|
412
537
|
if (input.history === true) {
|
|
413
|
-
|
|
538
|
+
const retained = entry.history.messages.slice(-8)
|
|
539
|
+
const offset = entry.history.messages.length - retained.length
|
|
540
|
+
for (const message of retained) {
|
|
414
541
|
if (message.role !== 'user' && message.role !== 'assistant') continue
|
|
415
542
|
const author = message.role === 'user' ? '用户' : '助手'
|
|
416
|
-
sections.push({
|
|
543
|
+
sections.push({
|
|
544
|
+
label: [`近期会话 · ${author}`, message.agent].filter(Boolean).join(' · '),
|
|
545
|
+
text: message.text, conversation: true, markdown: message.role === 'assistant',
|
|
546
|
+
})
|
|
417
547
|
}
|
|
548
|
+
// The draft only carries the last few turns, so the trace is trimmed to
|
|
549
|
+
// the same window and re-indexed before it reaches the export preview.
|
|
550
|
+
historyTrace = conversationTrace(entry.history.trace ?? [], retained.length, offset).trace
|
|
418
551
|
}
|
|
419
552
|
const { prompt, truncated, preview } = makePrompt(entry.project, sections, canImport ? await gitStatus(current) : '')
|
|
553
|
+
for (const section of preview.sections) {
|
|
554
|
+
if (!isMarkdownFile(section.file)) continue
|
|
555
|
+
const asset = sectionAssets.find(item => item.id === section.assetId)
|
|
556
|
+
if (asset) section.references = await markdownReferences(entry, asset, section.text)
|
|
557
|
+
}
|
|
558
|
+
if (historyTrace?.length) preview.trace = historyTrace
|
|
420
559
|
for (const [key, value] of tickets) {
|
|
421
560
|
if (Date.now() - value.created > ticketLifetime) tickets.delete(key)
|
|
422
561
|
}
|
|
@@ -424,9 +563,13 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
424
563
|
const ticket = randomUUID()
|
|
425
564
|
tickets.set(ticket, {
|
|
426
565
|
created: Date.now(), path: canImport ? current : null, prompt, truncated, title: entry.project.name,
|
|
427
|
-
projectId: entry.project.id, config: entry.config,
|
|
566
|
+
projectId: entry.project.id, config: entry.config, preview,
|
|
428
567
|
})
|
|
429
|
-
|
|
568
|
+
const skillCandidates = entry.skills.filter(item => selected.has(item.id)).map(item => ({
|
|
569
|
+
assetId: item.id,
|
|
570
|
+
...item.handoff,
|
|
571
|
+
}))
|
|
572
|
+
return { ticket, prompt, truncated, canImport, preview, skillCandidates }
|
|
430
573
|
}
|
|
431
574
|
|
|
432
575
|
function getTicket(id) {
|
|
@@ -435,6 +578,94 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
435
578
|
return ticket
|
|
436
579
|
}
|
|
437
580
|
|
|
581
|
+
async function markdownReferences(entry, asset, text) {
|
|
582
|
+
const hrefs = relativeMarkdownLinks(text).slice(0, 128)
|
|
583
|
+
if (!hrefs.length) return []
|
|
584
|
+
const root = await currentDirectory(entry.project.cwd)
|
|
585
|
+
if (!root || pathKey(root) !== pathKey(entry.project.cwd)) return []
|
|
586
|
+
const references = await Promise.all(hrefs.map(async href => {
|
|
587
|
+
const { path: target, authorization, error, revealOnly } = await authorizeProjectReference(root, asset.file, href)
|
|
588
|
+
if (!authorization) return { href, path: target, error }
|
|
589
|
+
const id = randomUUID()
|
|
590
|
+
if (openReferences.size >= 2048) openReferences.delete(openReferences.keys().next().value)
|
|
591
|
+
openReferences.set(id, { projectId: entry.project.id, asset, authorization, revealOnly, created: Date.now() })
|
|
592
|
+
return { href, path: target, id }
|
|
593
|
+
}))
|
|
594
|
+
return references
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function getOpenReference(id, projectId) {
|
|
598
|
+
const reference = openReferences.get(id)
|
|
599
|
+
if (!reference || reference.projectId !== projectId || Date.now() - reference.created > ticketLifetime) {
|
|
600
|
+
throw new RequestError('文件链接已失效,请重新打开预览。', 409)
|
|
601
|
+
}
|
|
602
|
+
return reference
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async function verifyOpenReference(reference, current) {
|
|
606
|
+
if (!current || pathKey(current) !== pathKey(reference.authorization.root)) {
|
|
607
|
+
throw new RequestError('项目目录已移动或不可访问。', 409)
|
|
608
|
+
}
|
|
609
|
+
try {
|
|
610
|
+
await verifyAssetSource(reference.asset)
|
|
611
|
+
const target = await verifySourceAuthorization(reference.authorization)
|
|
612
|
+
return { path: target.file, kind: 'file', name: path.basename(target.file), revealOnly: reference.revealOnly }
|
|
613
|
+
} catch {
|
|
614
|
+
throw new RequestError('链接文件已移动、被替换或不在项目范围内。', 409)
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async function exportPreview(ticket) {
|
|
619
|
+
const current = ticket.path && await currentDirectory(ticket.path)
|
|
620
|
+
if (!current) return ticket.preview
|
|
621
|
+
const sections = await Promise.all(ticket.preview.sections.map(async section => {
|
|
622
|
+
if (!section.references?.length) return section
|
|
623
|
+
const references = await Promise.all(section.references.map(async reference => {
|
|
624
|
+
if (!reference.id) return reference
|
|
625
|
+
try {
|
|
626
|
+
const grant = getOpenReference(reference.id, ticket.projectId)
|
|
627
|
+
const target = await verifyOpenReference(grant, current)
|
|
628
|
+
if (!target.revealOnly) return { ...reference, verifiedFile: target.path }
|
|
629
|
+
} catch { /* A stale reference is exported as text. */ }
|
|
630
|
+
return reference
|
|
631
|
+
}))
|
|
632
|
+
return { ...section, references }
|
|
633
|
+
}))
|
|
634
|
+
return { ...ticket.preview, sections }
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// The panel never supplies a free-form path for opening. It names an asset
|
|
638
|
+
// that is currently listed for the project (or the project directory
|
|
639
|
+
// itself), and the host re-reads the recorded authorization so a replaced
|
|
640
|
+
// file, a junction, or a moved source is refused instead of opened.
|
|
641
|
+
async function resolveOpenPath(input) {
|
|
642
|
+
const entry = await detail(input.projectId)
|
|
643
|
+
if (input.referenceId !== undefined) {
|
|
644
|
+
const reference = getOpenReference(input.referenceId, entry.project.id)
|
|
645
|
+
const current = await currentDirectory(entry.project.cwd)
|
|
646
|
+
return verifyOpenReference(reference, current)
|
|
647
|
+
}
|
|
648
|
+
if (input.directory === true) {
|
|
649
|
+
const current = await currentDirectory(entry.project.cwd)
|
|
650
|
+
if (!current || pathKey(current) !== pathKey(entry.project.cwd)) {
|
|
651
|
+
throw new RequestError('项目目录已移动或不可访问。', 409)
|
|
652
|
+
}
|
|
653
|
+
return { path: current, kind: 'directory', name: entry.project.name }
|
|
654
|
+
}
|
|
655
|
+
if (typeof input.assetId !== 'string' || !isCatalogId(input.assetId)) {
|
|
656
|
+
throw new RequestError('资料标识无效。')
|
|
657
|
+
}
|
|
658
|
+
const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
|
|
659
|
+
if (!item) throw new RequestError('找不到所选资料,请刷新项目。', 404)
|
|
660
|
+
let source
|
|
661
|
+
try {
|
|
662
|
+
source = await verifyAssetSource(item)
|
|
663
|
+
} catch {
|
|
664
|
+
throw new RequestError('资料已移动或内容已变化,请刷新项目后重试。', 409)
|
|
665
|
+
}
|
|
666
|
+
return { path: source.file, kind: 'file', name: item.name }
|
|
667
|
+
}
|
|
668
|
+
|
|
438
669
|
async function listConversations(projectId, recent) {
|
|
439
670
|
const current = await scan()
|
|
440
671
|
const project = requireProject(current, projectId)
|
|
@@ -468,6 +699,12 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
468
699
|
})
|
|
469
700
|
if (!history.messages.length) throw new RequestError('这条会话没有可迁入的文字问答。', 409)
|
|
470
701
|
const messages = history.messages.map(({ role, text, time }) => ({ role, text: redact(text), time }))
|
|
702
|
+
const { trace, indexOf, truncated: traceTruncated } = conversationTrace(history.trace ?? [], messages.length)
|
|
703
|
+
for (let index = 0; index < messages.length; index++) {
|
|
704
|
+
if (indexOf.has(index)) messages[index].traceIds = indexOf.get(index)
|
|
705
|
+
}
|
|
706
|
+
const traceCounts = countTrace(trace)
|
|
707
|
+
const { sourceStats } = history
|
|
471
708
|
const title = conversationTitle(archive.title || messages[0].text, 80) || '迁入的 Agent 会话'
|
|
472
709
|
const path = await currentDirectory(project.cwd)
|
|
473
710
|
const canImport = Boolean(path && pathKey(path) === pathKey(project.cwd))
|
|
@@ -481,9 +718,16 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
481
718
|
conversationTickets.delete(oldest[0])
|
|
482
719
|
}
|
|
483
720
|
if (canImport) conversationTickets.set(ticket, {
|
|
484
|
-
created: Date.now(), projectId, sessionId: randomUUID(), path, config, messages, title,
|
|
721
|
+
created: Date.now(), projectId, sessionId: randomUUID(), path, config, messages, title, trace, sourceStats,
|
|
485
722
|
})
|
|
486
|
-
|
|
723
|
+
const entry = await detail(projectId)
|
|
724
|
+
const skillCandidates = skillHandoff
|
|
725
|
+
? await skillHandoff.conversationCandidates(project, history.usedSkills, entry.skills)
|
|
726
|
+
: []
|
|
727
|
+
return {
|
|
728
|
+
title, messages, ticket: canImport ? ticket : null, canImport, cwd: project.cwd,
|
|
729
|
+
truncated: history.truncated || traceTruncated, skillCandidates, trace, traceCounts, sourceStats,
|
|
730
|
+
}
|
|
487
731
|
}
|
|
488
732
|
|
|
489
733
|
async function commitConversation(ticket) {
|
|
@@ -516,7 +760,7 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
516
760
|
return record.pending
|
|
517
761
|
}
|
|
518
762
|
|
|
519
|
-
function exportSession(conversation) {
|
|
763
|
+
async function exportSession({ conversation, format, includeTrace, sessionId }) {
|
|
520
764
|
if (!conversation || typeof conversation.title !== 'string' || conversation.title.length > 500
|
|
521
765
|
|| typeof conversation.path !== 'string' || conversation.path.length > 4096
|
|
522
766
|
|| !path.isAbsolute(conversation.path) || /[\u0000-\u001f]/u.test(conversation.path)
|
|
@@ -526,11 +770,17 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
526
770
|
const sections = conversation.messages
|
|
527
771
|
.filter(message => (message?.role === 'user' || message?.role === 'assistant')
|
|
528
772
|
&& typeof message.text === 'string' && message.text.trim())
|
|
529
|
-
.map(message => ({ label: message.role === 'user' ? '用户' : 'DSH 助手', text: message.text
|
|
773
|
+
.map(message => ({ label: message.role === 'user' ? '用户' : 'DSH 助手', text: message.text,
|
|
774
|
+
conversation: true, markdown: message.role === 'assistant' }))
|
|
530
775
|
if (!sections.length) throw new RequestError('这段会话暂无可导出的消息。', 409)
|
|
531
776
|
const title = redact(conversation.title.trim()) || 'DSH 会话'
|
|
532
|
-
const {
|
|
533
|
-
|
|
777
|
+
const { truncated, preview } = makePrompt({ name: title, cwd: conversation.path, agents: ['DSH'] }, sections, '')
|
|
778
|
+
const saved = includeTrace === true ? await loadSourceRecord?.(sessionId) : undefined
|
|
779
|
+
return makeExport({
|
|
780
|
+
title, origin: 'DSH 会话', format,
|
|
781
|
+
preview: { ...preview, truncated: truncated || conversation.truncated === true, trace: saved?.trace },
|
|
782
|
+
includeTrace: includeTrace === true,
|
|
783
|
+
})
|
|
534
784
|
}
|
|
535
785
|
|
|
536
786
|
return {
|
|
@@ -539,6 +789,7 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
539
789
|
wake()
|
|
540
790
|
monitor.dispose()
|
|
541
791
|
tickets.clear()
|
|
792
|
+
openReferences.clear()
|
|
542
793
|
conversationTickets.clear()
|
|
543
794
|
},
|
|
544
795
|
async execute(action, input) {
|
|
@@ -550,6 +801,46 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
550
801
|
if (action === 'set-project-pin') return setProjectPin(input)
|
|
551
802
|
if (action === 'set-project-selection') return setProjectSelection(input)
|
|
552
803
|
if (action === 'record-project-continuation') return recordProjectContinuation(input.ticket)
|
|
804
|
+
if (action === 'preview-skill-activation') {
|
|
805
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
806
|
+
if (!isCatalogId(input.projectId) || !Array.isArray(input.assetIds)
|
|
807
|
+
|| !input.assetIds.length || input.assetIds.length > 8 || !input.assetIds.every(isCatalogId)) {
|
|
808
|
+
throw new RequestError('技能启用请求格式无效。')
|
|
809
|
+
}
|
|
810
|
+
const current = snapshot ?? await scan()
|
|
811
|
+
const project = requireProject(current, input.projectId)
|
|
812
|
+
const entry = await detail(project.id)
|
|
813
|
+
const wanted = new Set(input.assetIds)
|
|
814
|
+
const assets = entry.skills.filter(item => wanted.has(item.id))
|
|
815
|
+
if (assets.length !== wanted.size) throw new RequestError('所选技能已变化,请刷新项目。', 409)
|
|
816
|
+
return await skillHandoff.preview(project, assets)
|
|
817
|
+
}
|
|
818
|
+
if (action === 'apply-skill-activation') {
|
|
819
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
820
|
+
if (typeof input.ticket !== 'string' || input.ticket.length > 128) {
|
|
821
|
+
throw new RequestError('技能预览凭证无效。')
|
|
822
|
+
}
|
|
823
|
+
const result = await skillHandoff.apply(input.ticket)
|
|
824
|
+
details.clear()
|
|
825
|
+
revision++
|
|
826
|
+
wake()
|
|
827
|
+
return { ...result, revision }
|
|
828
|
+
}
|
|
829
|
+
if (action === 'deactivate-skill-activation' || action === 'undo-skill-activation') {
|
|
830
|
+
if (!skillHandoff) throw new RequestError('当前 DSH 未提供原生技能启用服务。', 409)
|
|
831
|
+
if (!isCatalogId(input.projectId) || !isCatalogId(input.activationId)) {
|
|
832
|
+
throw new RequestError('技能启用记录格式无效。')
|
|
833
|
+
}
|
|
834
|
+
const current = snapshot ?? await scan()
|
|
835
|
+
const project = requireProject(current, input.projectId)
|
|
836
|
+
const result = action === 'undo-skill-activation'
|
|
837
|
+
? await skillHandoff.undo(project, input.activationId)
|
|
838
|
+
: await skillHandoff.deactivate(project, input.activationId)
|
|
839
|
+
details.clear()
|
|
840
|
+
revision++
|
|
841
|
+
wake()
|
|
842
|
+
return { ...result, revision }
|
|
843
|
+
}
|
|
553
844
|
if (action === 'list-conversations' || action === 'preview-conversation' || action === 'import-conversation') {
|
|
554
845
|
if (!importConversation) throw new RequestError('当前 DSH 未提供会话迁入服务。', 409)
|
|
555
846
|
if (action === 'list-conversations') return listConversations(input.projectId, input.recent === true)
|
|
@@ -569,28 +860,38 @@ export function createCatalog(loadConfig, { importConversation } = {}) {
|
|
|
569
860
|
return { revision, changed: input.revision !== revision, scannedAt: snapshot.scannedAt }
|
|
570
861
|
}
|
|
571
862
|
if (action === 'detail') {
|
|
572
|
-
const {
|
|
863
|
+
const {
|
|
864
|
+
project, history, memories, skills, config, skillNativeAvailable, skillProjectRoot, managedSkills,
|
|
865
|
+
} = await detail(input.projectId)
|
|
573
866
|
let selection
|
|
574
867
|
try { selection = await readProjectSelection(config, project.id) }
|
|
575
868
|
catch (error) { throw storageFailure('读取', error, '项目资料选择') }
|
|
576
869
|
return {
|
|
577
870
|
project: publicProject(project), memories: memories.map(publicAsset), skills: skills.map(publicAsset),
|
|
578
871
|
usedSkills: history.usedSkills, historyCount: history.messages.length, selection,
|
|
872
|
+
skillNativeAvailable, skillProjectRoot, managedSkills,
|
|
579
873
|
}
|
|
580
874
|
}
|
|
581
875
|
if (action === 'asset') {
|
|
582
|
-
const
|
|
583
|
-
const item = [...memories, ...skills].find(asset => asset.id === input.assetId)
|
|
876
|
+
const entry = await detail(input.projectId)
|
|
877
|
+
const item = [...entry.memories, ...entry.skills].find(asset => asset.id === input.assetId)
|
|
584
878
|
if (!item) throw new RequestError('找不到所选资料。', 404)
|
|
585
879
|
const result = await readAsset(item).catch(() => { throw new RequestError('资料已移动或不可读。', 409) })
|
|
586
|
-
|
|
880
|
+
const text = redact(result.text)
|
|
881
|
+
const references = isMarkdownFile(item.file) ? await markdownReferences(entry, item, text) : []
|
|
882
|
+
return { ...result, text, references }
|
|
587
883
|
}
|
|
588
884
|
if (action === 'preview') return prepare(input)
|
|
885
|
+
if (action === 'resolve-open-path') return resolveOpenPath(input)
|
|
589
886
|
if (action === 'export') {
|
|
590
887
|
const ticket = getTicket(input.ticket)
|
|
591
|
-
return makeExport({
|
|
888
|
+
return makeExport({
|
|
889
|
+
title: redact(ticket.title), origin: '项目交接', format: input.format,
|
|
890
|
+
preview: await exportPreview(ticket), date: new Date(ticket.created),
|
|
891
|
+
includeTrace: input.includeTrace === true,
|
|
892
|
+
})
|
|
592
893
|
}
|
|
593
|
-
if (action === 'export-session') return exportSession(input
|
|
894
|
+
if (action === 'export-session') return exportSession(input)
|
|
594
895
|
if (action === 'open') {
|
|
595
896
|
const ticket = getTicket(input.ticket)
|
|
596
897
|
if (!ticket.path) throw new RequestError('原工作目录不可访问。可导出交接。', 409)
|