@mealsea/dsh-prompt-enhance 1.0.0 → 1.1.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/CHANGELOG.md +48 -0
- package/README.md +49 -14
- package/client.js +685 -49
- package/docs/AUDIT-1.0.0.md +76 -0
- package/docs/DETAIL.md +95 -3
- package/docs/RELEASE.md +143 -0
- package/docs/dev/awareness-contract.md +1253 -0
- package/docs/dev/context-facts.md +643 -0
- package/docs/images/enhance-panel.png +0 -0
- package/docs/images/icon-180.png +0 -0
- package/docs/images/settings.png +0 -0
- package/docs/prompt-enhance-plugin-dev.md +3 -3
- package/docs/report-2026-12-06-awareness.md +209 -0
- package/icon.svg +1 -1
- package/index.js +796 -6
- package/locale/en.json +1 -1
- package/package.json +4 -4
- package/test/host.mjs +606 -1
- package/test/smoke.mjs +265 -2
package/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Improve prompt — Host 半(单个 ESM 文件、纯 JS、无构建、无第三方依赖)。
|
|
3
3
|
*
|
|
4
4
|
* 为什么需要这一半:
|
|
5
5
|
* Client 半拿不到 LLM —— 客户端 bundle 既没有可用的 Host Remote 命名空间(Remote 是
|
|
@@ -25,6 +25,92 @@ const MAX_OUTPUT = 12000
|
|
|
25
25
|
/** 请求标记:provider 扩展按 purpose 区分一次性调用。 */
|
|
26
26
|
const PURPOSE = 'prompt-enhance'
|
|
27
27
|
|
|
28
|
+
// ---------------------------------------------------------------- 工作区感知常量
|
|
29
|
+
// 设计约束见 docs/dev/awareness-contract.md:只读、双重围栏、预算硬上限、失败不阻断改写。
|
|
30
|
+
// 所有文件访问只走 fs.resolve/contains 与 workspaceFiles.read/list/search,绝不做写操作。
|
|
31
|
+
|
|
32
|
+
const CONTEXT_DEFAULTS = Object.freeze({ maxFiles: 5, maxLinesPerFile: 80, maxTokens: 800 })
|
|
33
|
+
const CONTEXT_LIMITS = Object.freeze({ maxFiles: 8, maxLinesPerFile: 160, maxTokens: 1200 })
|
|
34
|
+
const CONTEXT_MAX_HINTS = 6
|
|
35
|
+
const CONTEXT_MAX_READ_CANDIDATES = 16
|
|
36
|
+
const CONTEXT_MAX_SYMBOLS = 100
|
|
37
|
+
/** 单文件裁剪下限:裁到这么多行仍放不进剩余预算,就跳过该文件换下一个候选。 */
|
|
38
|
+
const MIN_CONTEXT_LINES = 8
|
|
39
|
+
const CONTEXT_TIMEOUT_MS = 2500
|
|
40
|
+
const CONTEXT_ERROR_MAX = 200
|
|
41
|
+
const CONTEXT_EXTENSIONS = new Set([
|
|
42
|
+
'.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md',
|
|
43
|
+
'.css', '.scss', '.html', '.vue', '.svelte',
|
|
44
|
+
'.py', '.go', '.rs', '.java', '.kt', '.rb', '.php', '.cs',
|
|
45
|
+
'.c', '.h', '.cpp', '.hpp', '.sh', '.yml', '.yaml', '.toml',
|
|
46
|
+
])
|
|
47
|
+
const CONTEXT_EXCLUDED_PREFIXES = [
|
|
48
|
+
'.git/', 'node_modules/', 'dist/', 'build/', 'coverage/',
|
|
49
|
+
'.next/', '.cache/', 'vendor/', '.agent-teams/',
|
|
50
|
+
]
|
|
51
|
+
/** 这些错误码只表示「该文件不可读」,不算读取通道失败。 */
|
|
52
|
+
const CONTEXT_SKIP_CODES = new Set([
|
|
53
|
+
'workspace-file/not-text', 'workspace-file/not-regular-file', 'workspace-file/too-large',
|
|
54
|
+
'workspace-file/outside-workspace', 'FS_NOT_TEXT', 'FS_TOO_LARGE',
|
|
55
|
+
])
|
|
56
|
+
|
|
57
|
+
/** 草稿关键词里要丢掉的虚词与泛词。 */
|
|
58
|
+
const HINT_STOPWORDS = new Set([
|
|
59
|
+
'the', 'and', 'for', 'with', 'this', 'that', 'from', 'into', 'when', 'then', 'than', 'have', 'has', 'are', 'was', 'were',
|
|
60
|
+
'will', 'would', 'should', 'could', 'please', 'help', 'make', 'sure', 'code', 'file', 'files', 'function', 'error', 'bug',
|
|
61
|
+
'fix', 'use', 'using', 'need', 'want', 'issue', 'problem', 'test', 'change', 'update', 'add', 'remove', 'about', 'your',
|
|
62
|
+
'you', 'our', 'their', 'there', 'here', 'what', 'why', 'how', 'not', 'but', 'all', 'any', 'can', 'may', 'just', 'like',
|
|
63
|
+
'get', 'set', 'new', 'old', 'good', 'bad', 'more', 'less', 'only', 'also', 'very', 'some', 'such', 'each', 'other',
|
|
64
|
+
'which', 'where', 'while', 'after', 'before', 'between', 'over', 'under', 'again', 'still', 'same', 'different',
|
|
65
|
+
'帮我', '一下', '代码', '这个', '那个', '文件', '函数', '怎么', '可以', '需要', '使用', '问题', '修复', '优化', '修改',
|
|
66
|
+
'增加', '删除', '看看', '这段', '下面', '上面', '然后', '就是', '还是', '已经', '没有', '一个', '我们', '你们', '他们',
|
|
67
|
+
'什么', '为什么', '如何', '这里', '那里', '现在', '之前', '之后', '因为', '所以', '但是', '如果', '或者', '以及', '并且',
|
|
68
|
+
])
|
|
69
|
+
|
|
70
|
+
/** 符号提取规则:每行命中第一条即停止。 */
|
|
71
|
+
const SYMBOL_RULES = [
|
|
72
|
+
{ kind: 'class', re: /^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)/ },
|
|
73
|
+
{ kind: 'function', re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/ },
|
|
74
|
+
{ kind: 'function', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/ },
|
|
75
|
+
{ kind: 'function', re: /^\s*(?:static\s+)?(?:async\s+)?\*?\s*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/ },
|
|
76
|
+
{ kind: 'variable', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/ },
|
|
77
|
+
]
|
|
78
|
+
const SYMBOL_RESERVED = new Set([
|
|
79
|
+
'if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'const', 'let', 'var',
|
|
80
|
+
'new', 'typeof', 'await', 'async', 'class', 'else',
|
|
81
|
+
])
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 内置命令兜底文案:命令注册表不可用时,仍让模型与面板知道用户用的是哪条命令。
|
|
85
|
+
* 未列出的命令沿用契约里的通用文案。
|
|
86
|
+
*/
|
|
87
|
+
const COMMAND_FALLBACKS = {
|
|
88
|
+
goal: {
|
|
89
|
+
zh: '目标模式:围绕一个可持续推进的长期目标工作,直到目标完成。',
|
|
90
|
+
en: 'Goal mode: keep working toward a long-running objective until it is complete.',
|
|
91
|
+
},
|
|
92
|
+
plan: {
|
|
93
|
+
zh: '计划模式:先给出分步计划,再按计划推进,不直接执行不可逆操作。',
|
|
94
|
+
en: 'Plan mode: produce a step-by-step plan before acting, and avoid irreversible actions.',
|
|
95
|
+
},
|
|
96
|
+
'agent-teams': {
|
|
97
|
+
zh: '多智能体协作:把任务拆分给团队成员并行推进,并汇总结果。',
|
|
98
|
+
en: 'Agent teams: split the work across team members in parallel and merge the results.',
|
|
99
|
+
},
|
|
100
|
+
compact: {
|
|
101
|
+
zh: '压缩上下文:把较早的对话折叠为摘要,为后续工作释放上下文空间。',
|
|
102
|
+
en: 'Compact: fold earlier conversation into a summary to free context for later work.',
|
|
103
|
+
},
|
|
104
|
+
feedback: {
|
|
105
|
+
zh: '反馈:记录用户对产品的问题或建议。',
|
|
106
|
+
en: 'Feedback: record the user issue or suggestion about the product.',
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
const COMMAND_FALLBACK_TEXT = {
|
|
110
|
+
zh: '命令说明不可用',
|
|
111
|
+
en: 'Command description unavailable',
|
|
112
|
+
}
|
|
113
|
+
|
|
28
114
|
const SYSTEM = {
|
|
29
115
|
zh: [
|
|
30
116
|
'把 <draft> 改写成一条更清晰、更可执行的请求。',
|
|
@@ -211,12 +297,16 @@ async function collect(stream) {
|
|
|
211
297
|
* 优先走 `prepareCall`(由运行时解析鉴权、默认值,并显式选最低思考档);
|
|
212
298
|
* 老运行时没有该方法时退回裸 `stream`。预算被思考吃光(finish=max-tokens)时翻倍重试一次。
|
|
213
299
|
*/
|
|
214
|
-
async function rewrite(ctx, selection, text, locale, signal) {
|
|
300
|
+
async function rewrite(ctx, selection, text, locale, signal, contextBlock, commandNote) {
|
|
215
301
|
const llm = ctx.get('llm')
|
|
216
302
|
if (!llm) throw Object.assign(new Error('llm service unavailable'), { code: 'no_llm' })
|
|
217
303
|
|
|
218
|
-
|
|
219
|
-
const
|
|
304
|
+
// 命令语义追加在 system 末尾;只读上下文作为独立块放在草稿之前,草稿正文保持原样。
|
|
305
|
+
const system = commandNote ? SYSTEM[locale] + '\n\n' + commandNote : SYSTEM[locale]
|
|
306
|
+
const userText = contextBlock
|
|
307
|
+
? contextBlock + '\n\n<draft>\n' + text + '\n</draft>'
|
|
308
|
+
: text
|
|
309
|
+
const messages = [{ role: 'user', content: [{ type: 'text', text: userText }] }]
|
|
220
310
|
let maxTokens = Math.min(4096, Math.max(512, Math.ceil(text.length * 1.6) + 256))
|
|
221
311
|
|
|
222
312
|
for (let attempt = 0; ; attempt += 1) {
|
|
@@ -270,6 +360,645 @@ function clean(raw) {
|
|
|
270
360
|
return text
|
|
271
361
|
}
|
|
272
362
|
|
|
363
|
+
// ---------------------------------------------------------------- 工作区感知实现
|
|
364
|
+
|
|
365
|
+
/** 唯一 token 估算公式;参数会被 String() 化。 */
|
|
366
|
+
function estimateTokens(text) {
|
|
367
|
+
return Math.ceil(String(text == null ? '' : text).length / 3.5)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* 把整页文本按行前缀裁进剩余 token 预算(行内容不截断,避免切断半行代码)。
|
|
372
|
+
* 返回 null 表示裁到 MIN_CONTEXT_LINES 行仍放不下;调用方应跳过该文件并继续下一个候选。
|
|
373
|
+
* @param {string} text 服务返回的整页文本
|
|
374
|
+
* @param {number} pageLines 服务声明的行数
|
|
375
|
+
* @param {number} startLine 窗口起始行(文件内绝对行号)
|
|
376
|
+
* @param {number} remainingTokens 当前剩余预算
|
|
377
|
+
* @returns {{ text: string, lines: number, tokens: number, endLine: number } | null}
|
|
378
|
+
*/
|
|
379
|
+
function trimContextText(text, pageLines, startLine, remainingTokens) {
|
|
380
|
+
const source = String(text == null ? '' : text)
|
|
381
|
+
const endsWithNewline = source.endsWith('\n')
|
|
382
|
+
const parts = source.split('\n')
|
|
383
|
+
if (endsWithNewline) parts.pop()
|
|
384
|
+
const declared = Number.isFinite(pageLines) ? Math.max(0, Math.floor(pageLines)) : parts.length
|
|
385
|
+
const available = Math.min(parts.length, declared)
|
|
386
|
+
for (let lines = available; lines >= MIN_CONTEXT_LINES; lines -= 1) {
|
|
387
|
+
const candidate = parts.slice(0, lines).join('\n') + (endsWithNewline ? '\n' : '')
|
|
388
|
+
const tokens = estimateTokens(candidate)
|
|
389
|
+
if (tokens <= remainingTokens) {
|
|
390
|
+
return { text: candidate, lines, tokens, endLine: startLine + lines - 1 }
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return null
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function clampInt(value, fallback, min, max) {
|
|
397
|
+
const n = Number(value)
|
|
398
|
+
if (!Number.isFinite(n)) return fallback
|
|
399
|
+
return Math.min(max, Math.max(min, Math.floor(n)))
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** 归一化感知请求:缺省关闭;三个预算都夹到硬上限内。 */
|
|
403
|
+
function normalizeAwarenessRequest(raw) {
|
|
404
|
+
const source = raw && typeof raw === 'object' ? raw : {}
|
|
405
|
+
return {
|
|
406
|
+
enabled: source.enabled === true,
|
|
407
|
+
maxFiles: clampInt(source.maxFiles, CONTEXT_DEFAULTS.maxFiles, 1, CONTEXT_LIMITS.maxFiles),
|
|
408
|
+
maxLinesPerFile: clampInt(source.maxLinesPerFile, CONTEXT_DEFAULTS.maxLinesPerFile, 1, CONTEXT_LIMITS.maxLinesPerFile),
|
|
409
|
+
maxTokens: clampInt(source.maxTokens, CONTEXT_DEFAULTS.maxTokens, 1, CONTEXT_LIMITS.maxTokens),
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** 命令名只接受无斜杠、小写、[a-z0-9][a-z0-9_-]{0,63};其余一律视为未提供。 */
|
|
414
|
+
function normalizeCommandName(raw) {
|
|
415
|
+
if (typeof raw !== 'string') return ''
|
|
416
|
+
const name = raw.trim().replace(/^\/+/, '').toLowerCase()
|
|
417
|
+
return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ? name : ''
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function normalizeSessionId(raw) {
|
|
421
|
+
if (typeof raw !== 'string') return null
|
|
422
|
+
const id = raw.trim()
|
|
423
|
+
return id && id.length <= 256 ? id : null
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function normalizeRelPath(path) {
|
|
427
|
+
return String(path == null ? '' : path).replace(/\\/g, '/').replace(/^\.\//, '')
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function compareText(a, b) {
|
|
431
|
+
const left = String(a)
|
|
432
|
+
const right = String(b)
|
|
433
|
+
return left < right ? -1 : left > right ? 1 : 0
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function isAbortError(err) {
|
|
437
|
+
return Boolean(err && (err.code === 'aborted' || err.name === 'AbortError'))
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 对外回显的预算对象(只含三个上限,不含 enabled)。 */
|
|
441
|
+
function contextBudget(budget) {
|
|
442
|
+
const source = budget && typeof budget === 'object' ? budget : CONTEXT_DEFAULTS
|
|
443
|
+
return {
|
|
444
|
+
maxFiles: clampInt(source.maxFiles, CONTEXT_DEFAULTS.maxFiles, 1, CONTEXT_LIMITS.maxFiles),
|
|
445
|
+
maxLinesPerFile: clampInt(source.maxLinesPerFile, CONTEXT_DEFAULTS.maxLinesPerFile, 1, CONTEXT_LIMITS.maxLinesPerFile),
|
|
446
|
+
maxTokens: clampInt(source.maxTokens, CONTEXT_DEFAULTS.maxTokens, 1, CONTEXT_LIMITS.maxTokens),
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 会话解析失败时的完整 context(字段一个不少)。 */
|
|
451
|
+
function deniedContext(skipped, sessionId, budget) {
|
|
452
|
+
return {
|
|
453
|
+
enabled: false,
|
|
454
|
+
skipped,
|
|
455
|
+
error: {
|
|
456
|
+
code: 'awareness_denied',
|
|
457
|
+
message: skipped === 'no-session' ? 'sessionId required' : 'session workspace not found',
|
|
458
|
+
},
|
|
459
|
+
sessionId: skipped === 'no-session' ? null : sessionId,
|
|
460
|
+
workspaceRoot: null,
|
|
461
|
+
source: 'none',
|
|
462
|
+
skippedFiles: 0,
|
|
463
|
+
truncated: false,
|
|
464
|
+
files: [],
|
|
465
|
+
totalFiles: 0,
|
|
466
|
+
totalLines: 0,
|
|
467
|
+
totalTokens: 0,
|
|
468
|
+
budget: contextBudget(budget),
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** 采集器自身抛错时的兜底 context(不改 HTTP 状态)。 */
|
|
473
|
+
function failedAwarenessContext(sessionId, budget, skipped, message) {
|
|
474
|
+
return {
|
|
475
|
+
enabled: false,
|
|
476
|
+
skipped,
|
|
477
|
+
error: {
|
|
478
|
+
code: 'awareness_failed',
|
|
479
|
+
message: String(message == null ? '' : message).slice(0, CONTEXT_ERROR_MAX) || 'context collection failed',
|
|
480
|
+
},
|
|
481
|
+
sessionId: typeof sessionId === 'string' ? sessionId : null,
|
|
482
|
+
workspaceRoot: null,
|
|
483
|
+
source: 'none',
|
|
484
|
+
skippedFiles: 0,
|
|
485
|
+
truncated: false,
|
|
486
|
+
files: [],
|
|
487
|
+
totalFiles: 0,
|
|
488
|
+
totalLines: 0,
|
|
489
|
+
totalTokens: 0,
|
|
490
|
+
budget: contextBudget(budget),
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* 只解析会话的工作区根:live 会话 header.cwd → 持久化快照 header.cwd。
|
|
496
|
+
* 不读 sessions.list(),不读 workspaceRegistry,不猜 sandboxPolicy 的根。
|
|
497
|
+
*/
|
|
498
|
+
async function resolveWorkspace(ctx, sessionId, signal) {
|
|
499
|
+
if (typeof sessionId !== 'string' || !sessionId.trim()) return { ok: false, skipped: 'no-session' }
|
|
500
|
+
const id = sessionId.trim()
|
|
501
|
+
let live
|
|
502
|
+
try {
|
|
503
|
+
const sessions = ctx.get('sessions')
|
|
504
|
+
live = sessions && typeof sessions.get === 'function' ? sessions.get(id) : undefined
|
|
505
|
+
} catch {
|
|
506
|
+
live = undefined
|
|
507
|
+
}
|
|
508
|
+
const liveCwd = live && live.header && typeof live.header.cwd === 'string' && live.header.cwd.trim()
|
|
509
|
+
? live.header.cwd
|
|
510
|
+
: ''
|
|
511
|
+
if (liveCwd) return { ok: true, sessionId: id, workspaceRoot: liveCwd, source: 'live' }
|
|
512
|
+
if (signal && signal.aborted) return { ok: false, skipped: 'no-workspace' }
|
|
513
|
+
|
|
514
|
+
let persistedCwd = ''
|
|
515
|
+
try {
|
|
516
|
+
const persistence = ctx.get('sessionPersistence')
|
|
517
|
+
const snapshot = persistence && typeof persistence.stat === 'function'
|
|
518
|
+
? await persistence.stat(id, { signal })
|
|
519
|
+
: undefined
|
|
520
|
+
if (snapshot && snapshot.header && typeof snapshot.header.cwd === 'string' && snapshot.header.cwd.trim()) {
|
|
521
|
+
persistedCwd = snapshot.header.cwd
|
|
522
|
+
}
|
|
523
|
+
} catch {
|
|
524
|
+
persistedCwd = ''
|
|
525
|
+
}
|
|
526
|
+
if (persistedCwd) return { ok: true, sessionId: id, workspaceRoot: persistedCwd, source: 'persisted' }
|
|
527
|
+
return { ok: false, skipped: 'no-workspace' }
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* 从草稿里提取最多 6 条搜索提示:先路径、后术语;术语按出现次数/长度/字典序排序。
|
|
532
|
+
* @returns {Array<{ kind: 'path' | 'term', text: string, lower: string }>}
|
|
533
|
+
*/
|
|
534
|
+
function extractContextHints(text) {
|
|
535
|
+
const source = String(text == null ? '' : text)
|
|
536
|
+
const hints = []
|
|
537
|
+
const seen = new Set()
|
|
538
|
+
const push = (kind, value) => {
|
|
539
|
+
if (hints.length >= CONTEXT_MAX_HINTS) return
|
|
540
|
+
const normalized = kind === 'path' ? normalizeRelPath(value) : String(value).toLowerCase()
|
|
541
|
+
if (!normalized) return
|
|
542
|
+
const key = kind + '\0' + normalized.toLowerCase()
|
|
543
|
+
if (seen.has(key)) return
|
|
544
|
+
seen.add(key)
|
|
545
|
+
hints.push({ kind, text: normalized, lower: normalized.toLowerCase() })
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const pathPattern = /[A-Za-z0-9_.@/\\-]+\.[A-Za-z0-9]{1,8}/g
|
|
549
|
+
let match
|
|
550
|
+
while ((match = pathPattern.exec(source)) !== null) {
|
|
551
|
+
if (hints.length >= CONTEXT_MAX_HINTS) break
|
|
552
|
+
const raw = match[0]
|
|
553
|
+
if (raw.length < 3 || raw.length > 240) continue
|
|
554
|
+
if (raw.startsWith('/') || /^[A-Za-z]:[\\/]/.test(raw)) continue
|
|
555
|
+
const dot = raw.lastIndexOf('.')
|
|
556
|
+
const ext = '.' + raw.slice(dot + 1).toLowerCase()
|
|
557
|
+
if (!CONTEXT_EXTENSIONS.has(ext)) continue
|
|
558
|
+
push('path', raw)
|
|
559
|
+
}
|
|
560
|
+
if (hints.length >= CONTEXT_MAX_HINTS) return hints
|
|
561
|
+
|
|
562
|
+
const counts = new Map()
|
|
563
|
+
const addTerm = (raw) => {
|
|
564
|
+
const value = String(raw).toLowerCase()
|
|
565
|
+
if (value.length < 3 || /^[0-9]+$/.test(value) || HINT_STOPWORDS.has(value)) return
|
|
566
|
+
counts.set(value, (counts.get(value) || 0) + 1)
|
|
567
|
+
}
|
|
568
|
+
const asciiPattern = /[A-Za-z_$][A-Za-z0-9_$]{2,}/g
|
|
569
|
+
while ((match = asciiPattern.exec(source)) !== null) addTerm(match[0])
|
|
570
|
+
const cjkPattern = /[\u3400-\u9FFF]{2,8}/g
|
|
571
|
+
while ((match = cjkPattern.exec(source)) !== null) addTerm(match[0])
|
|
572
|
+
|
|
573
|
+
const ranked = [...counts.keys()].sort((a, b) =>
|
|
574
|
+
counts.get(b) - counts.get(a) || b.length - a.length || compareText(a, b))
|
|
575
|
+
for (const term of ranked) {
|
|
576
|
+
push('term', term)
|
|
577
|
+
if (hints.length >= CONTEXT_MAX_HINTS) break
|
|
578
|
+
}
|
|
579
|
+
return hints
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 候选路径必须扩展名允许、不在排除目录、不是压缩产物;越界由预围栏负责。 */
|
|
583
|
+
function contextPathAllowed(rawPath) {
|
|
584
|
+
const rel = normalizeRelPath(rawPath)
|
|
585
|
+
if (!rel) return false
|
|
586
|
+
const lower = rel.toLowerCase()
|
|
587
|
+
for (const prefix of CONTEXT_EXCLUDED_PREFIXES) {
|
|
588
|
+
if (lower.startsWith(prefix)) return false
|
|
589
|
+
}
|
|
590
|
+
const base = lower.slice(lower.lastIndexOf('/') + 1)
|
|
591
|
+
if (base.endsWith('.min.js') || base.endsWith('.min.css')) return false
|
|
592
|
+
const dot = base.lastIndexOf('.')
|
|
593
|
+
if (dot < 0) return false
|
|
594
|
+
return CONTEXT_EXTENSIONS.has(base.slice(dot))
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** 单条 hint 对候选路径的路径分(按契约顺序短路)。 */
|
|
598
|
+
function contextFileScore(hint, relPath) {
|
|
599
|
+
const path = normalizeRelPath(relPath)
|
|
600
|
+
const lowerPath = path.toLowerCase()
|
|
601
|
+
const lower = String(hint && hint.lower != null ? hint.lower : '').toLowerCase()
|
|
602
|
+
if (!lower) return 0
|
|
603
|
+
if (hint.kind === 'path') {
|
|
604
|
+
if (path === hint.text || path.endsWith('/' + hint.text) || path.endsWith(hint.text)) return 150
|
|
605
|
+
}
|
|
606
|
+
const base = lowerPath.slice(lowerPath.lastIndexOf('/') + 1)
|
|
607
|
+
const dot = base.lastIndexOf('.')
|
|
608
|
+
const stem = dot > 0 ? base.slice(0, dot) : base
|
|
609
|
+
if (stem === lower) return 100
|
|
610
|
+
if (stem.includes(lower)) return 60
|
|
611
|
+
if (lowerPath.includes(lower)) return 25
|
|
612
|
+
return 5
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** 非重叠计数;空针返回 0。 */
|
|
616
|
+
function countOccurrences(haystack, needle) {
|
|
617
|
+
const source = String(haystack == null ? '' : haystack)
|
|
618
|
+
const target = String(needle == null ? '' : needle)
|
|
619
|
+
if (!target) return 0
|
|
620
|
+
let count = 0
|
|
621
|
+
let from = 0
|
|
622
|
+
for (;;) {
|
|
623
|
+
const at = source.indexOf(target, from)
|
|
624
|
+
if (at === -1) break
|
|
625
|
+
count += 1
|
|
626
|
+
from = at + target.length
|
|
627
|
+
}
|
|
628
|
+
return count
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* 只读上下文采集:搜索候选 → 双重围栏 → 行窗口读取 → 预算截断 → 符号提取。
|
|
633
|
+
* 契约上永不 throw;失败一律折成带 error 的完整 context。
|
|
634
|
+
* @returns {Promise<{ context: object, symbols: object[], texts: Map<string, string> }>}
|
|
635
|
+
*/
|
|
636
|
+
async function collectContext(ctx, scope, prompt, budget, signal) {
|
|
637
|
+
const sessionId = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
|
638
|
+
const workspaceRoot = scope && typeof scope.workspaceRoot === 'string' ? scope.workspaceRoot : null
|
|
639
|
+
const source = scope && scope.source === 'persisted' ? 'persisted' : 'live'
|
|
640
|
+
const wfScope = { sessionId, workspaceRoot }
|
|
641
|
+
const echoBudget = contextBudget(budget)
|
|
642
|
+
|
|
643
|
+
let searchFailures = 0
|
|
644
|
+
let readFailures = 0
|
|
645
|
+
let skippedFiles = 0
|
|
646
|
+
let truncated = false
|
|
647
|
+
let aborted = false
|
|
648
|
+
|
|
649
|
+
const empty = (flagged) => ({
|
|
650
|
+
context: {
|
|
651
|
+
enabled: false,
|
|
652
|
+
sessionId,
|
|
653
|
+
workspaceRoot,
|
|
654
|
+
source,
|
|
655
|
+
skippedFiles,
|
|
656
|
+
truncated: flagged === true,
|
|
657
|
+
files: [],
|
|
658
|
+
totalFiles: 0,
|
|
659
|
+
totalLines: 0,
|
|
660
|
+
totalTokens: 0,
|
|
661
|
+
budget: echoBudget,
|
|
662
|
+
},
|
|
663
|
+
symbols: [],
|
|
664
|
+
texts: new Map(),
|
|
665
|
+
})
|
|
666
|
+
|
|
667
|
+
const failed = (skipped, message, skippedCount) => ({
|
|
668
|
+
context: {
|
|
669
|
+
enabled: false,
|
|
670
|
+
skipped,
|
|
671
|
+
error: {
|
|
672
|
+
code: 'awareness_failed',
|
|
673
|
+
message: String(message == null ? '' : message).slice(0, CONTEXT_ERROR_MAX) || 'context collection failed',
|
|
674
|
+
},
|
|
675
|
+
sessionId,
|
|
676
|
+
workspaceRoot,
|
|
677
|
+
source,
|
|
678
|
+
skippedFiles: typeof skippedCount === 'number' ? skippedCount : skippedFiles,
|
|
679
|
+
truncated,
|
|
680
|
+
files: [],
|
|
681
|
+
totalFiles: 0,
|
|
682
|
+
totalLines: 0,
|
|
683
|
+
totalTokens: 0,
|
|
684
|
+
budget: echoBudget,
|
|
685
|
+
},
|
|
686
|
+
symbols: [],
|
|
687
|
+
texts: new Map(),
|
|
688
|
+
})
|
|
689
|
+
|
|
690
|
+
try {
|
|
691
|
+
const hints = extractContextHints(prompt)
|
|
692
|
+
if (hints.length === 0) return empty(false)
|
|
693
|
+
|
|
694
|
+
const wf = ctx.get('workspaceFiles')
|
|
695
|
+
if (!wf || typeof wf.read !== 'function') return failed('read-failed', 'workspace files service unavailable')
|
|
696
|
+
|
|
697
|
+
const candidates = new Map()
|
|
698
|
+
const addCandidate = (rawPath) => {
|
|
699
|
+
const rel = normalizeRelPath(rawPath)
|
|
700
|
+
if (!rel || candidates.has(rel) || !contextPathAllowed(rel)) return
|
|
701
|
+
candidates.set(rel, true)
|
|
702
|
+
}
|
|
703
|
+
for (const hint of hints) {
|
|
704
|
+
if (hint.kind === 'path') addCandidate(hint.text)
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
let searchDetail = ''
|
|
708
|
+
let listingTruncated = false
|
|
709
|
+
if (typeof wf.search === 'function') {
|
|
710
|
+
for (const hint of hints) {
|
|
711
|
+
if (signal && signal.aborted) { aborted = true; break }
|
|
712
|
+
try {
|
|
713
|
+
const found = await wf.search(wfScope, {
|
|
714
|
+
query: hint.text,
|
|
715
|
+
excludedPaths: [],
|
|
716
|
+
includeHidden: false,
|
|
717
|
+
respectGitignore: true,
|
|
718
|
+
}, signal)
|
|
719
|
+
const matches = found && Array.isArray(found.matches) ? found.matches : []
|
|
720
|
+
for (const item of matches) {
|
|
721
|
+
if (item && item.type === 'file' && typeof item.path === 'string') addCandidate(item.path)
|
|
722
|
+
}
|
|
723
|
+
} catch (err) {
|
|
724
|
+
if (isAbortError(err) || (signal && signal.aborted)) { aborted = true; break }
|
|
725
|
+
searchFailures += 1
|
|
726
|
+
if (!searchDetail) searchDetail = failureMessage(err)
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
} else if (typeof wf.list === 'function') {
|
|
730
|
+
try {
|
|
731
|
+
const listing = await wf.list(wfScope, '.', signal)
|
|
732
|
+
const entries = listing && Array.isArray(listing.entries) ? listing.entries : []
|
|
733
|
+
for (const entry of entries) {
|
|
734
|
+
if (entry && entry.type === 'file' && typeof entry.name === 'string') addCandidate(entry.name)
|
|
735
|
+
}
|
|
736
|
+
if (listing && listing.truncated === true) listingTruncated = true
|
|
737
|
+
} catch (err) {
|
|
738
|
+
if (isAbortError(err) || (signal && signal.aborted)) aborted = true
|
|
739
|
+
else { searchFailures += 1; searchDetail = failureMessage(err) }
|
|
740
|
+
}
|
|
741
|
+
} else {
|
|
742
|
+
searchFailures += 1
|
|
743
|
+
searchDetail = 'workspace search unavailable'
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
if (aborted) return failed('search-failed', 'context collection aborted' + (searchDetail ? ': ' + searchDetail : ''))
|
|
747
|
+
if (candidates.size === 0) {
|
|
748
|
+
if (searchFailures > 0) return failed('search-failed', searchDetail || 'workspace search failed')
|
|
749
|
+
return empty(false)
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const fsService = ctx.get('fs')
|
|
753
|
+
if (!fsService || typeof fsService.resolve !== 'function' || typeof fsService.contains !== 'function') {
|
|
754
|
+
return failed('read-failed', 'file system service unavailable', candidates.size)
|
|
755
|
+
}
|
|
756
|
+
let root
|
|
757
|
+
try {
|
|
758
|
+
root = await fsService.resolve(workspaceRoot)
|
|
759
|
+
} catch (err) {
|
|
760
|
+
return failed('read-failed', 'workspace root unavailable: ' + failureMessage(err), candidates.size)
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
const ranked = [...candidates.keys()].map((relPath) => {
|
|
764
|
+
let pathScore = 0
|
|
765
|
+
for (const hint of hints) pathScore += contextFileScore(hint, relPath)
|
|
766
|
+
return { path: relPath, pathScore }
|
|
767
|
+
}).sort((a, b) => b.pathScore - a.pathScore || compareText(a.path, b.path))
|
|
768
|
+
.slice(0, Math.min(CONTEXT_MAX_READ_CANDIDATES, budget.maxFiles * 2))
|
|
769
|
+
|
|
770
|
+
// 读取与预算合并成一遍:整页超预算时按行前缀裁剪,裁不动才跳过并继续下一个候选。
|
|
771
|
+
const files = []
|
|
772
|
+
const texts = new Map()
|
|
773
|
+
let totalTokens = 0
|
|
774
|
+
let budgetSkipped = false
|
|
775
|
+
let readDetail = ''
|
|
776
|
+
for (const candidate of ranked) {
|
|
777
|
+
if (signal && signal.aborted) { aborted = true; break }
|
|
778
|
+
// 文件数已满:保留原有 maxFiles 行为,停止读取后续候选。
|
|
779
|
+
if (files.length >= budget.maxFiles) { truncated = true; break }
|
|
780
|
+
const remaining = budget.maxTokens - totalTokens
|
|
781
|
+
if (remaining <= 0) { truncated = true; break }
|
|
782
|
+
|
|
783
|
+
// 预围栏:workspaceFiles.read 服务层不围栏,这里必须先自己挡一次。
|
|
784
|
+
let target
|
|
785
|
+
try {
|
|
786
|
+
target = await fsService.resolve(candidate.path, { cwd: workspaceRoot })
|
|
787
|
+
} catch {
|
|
788
|
+
skippedFiles += 1
|
|
789
|
+
readFailures += 1
|
|
790
|
+
continue
|
|
791
|
+
}
|
|
792
|
+
if (!fsService.contains(root, target)) { skippedFiles += 1; continue }
|
|
793
|
+
|
|
794
|
+
let page
|
|
795
|
+
try {
|
|
796
|
+
page = await wf.read(wfScope, candidate.path, { offset: 1, limit: budget.maxLinesPerFile }, signal)
|
|
797
|
+
} catch (err) {
|
|
798
|
+
if (isAbortError(err) || (signal && signal.aborted)) { aborted = true; break }
|
|
799
|
+
const code = err && typeof err.code === 'string' ? err.code : ''
|
|
800
|
+
skippedFiles += 1
|
|
801
|
+
if (!CONTEXT_SKIP_CODES.has(code)) {
|
|
802
|
+
readFailures += 1
|
|
803
|
+
if (!readDetail) readDetail = failureMessage(err)
|
|
804
|
+
}
|
|
805
|
+
continue
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
if (!page || typeof page.text !== 'string') { skippedFiles += 1; readFailures += 1; continue }
|
|
809
|
+
if (typeof page.absolutePath !== 'string' || !page.absolutePath) { skippedFiles += 1; continue }
|
|
810
|
+
|
|
811
|
+
// 后围栏:用服务返回的 absolutePath 再复核一次,防止符号链接/短名绕过。
|
|
812
|
+
let targetAfter
|
|
813
|
+
try {
|
|
814
|
+
targetAfter = await fsService.resolve(page.absolutePath)
|
|
815
|
+
} catch {
|
|
816
|
+
skippedFiles += 1
|
|
817
|
+
continue
|
|
818
|
+
}
|
|
819
|
+
if (!fsService.contains(root, targetAfter)) { skippedFiles += 1; continue }
|
|
820
|
+
|
|
821
|
+
if (page.lines === 0) continue
|
|
822
|
+
if (!Number.isFinite(page.lines) || page.lines < 0) { skippedFiles += 1; readFailures += 1; continue }
|
|
823
|
+
if (page.text.indexOf('\u0000') !== -1) { skippedFiles += 1; continue }
|
|
824
|
+
|
|
825
|
+
const startLine = Number.isFinite(page.offset) ? page.offset : 1
|
|
826
|
+
let itemText = page.text
|
|
827
|
+
let itemTokens = estimateTokens(itemText)
|
|
828
|
+
let itemLines = page.lines
|
|
829
|
+
if (itemTokens > remaining) {
|
|
830
|
+
const trimmed = trimContextText(itemText, itemLines, startLine, remaining)
|
|
831
|
+
if (!trimmed) {
|
|
832
|
+
// 裁到 MIN_CONTEXT_LINES 行仍放不下:跳过该文件,继续尝试更小的候选。
|
|
833
|
+
skippedFiles += 1
|
|
834
|
+
budgetSkipped = true
|
|
835
|
+
truncated = true
|
|
836
|
+
continue
|
|
837
|
+
}
|
|
838
|
+
itemText = trimmed.text
|
|
839
|
+
itemTokens = trimmed.tokens
|
|
840
|
+
itemLines = trimmed.lines
|
|
841
|
+
truncated = true
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const haystack = page.text.toLowerCase()
|
|
845
|
+
let hits = 0
|
|
846
|
+
for (const hint of hints) hits += Math.min(20, countOccurrences(haystack, hint.lower))
|
|
847
|
+
const contentScore = Math.min(40, hits * 2)
|
|
848
|
+
files.push({
|
|
849
|
+
path: candidate.path,
|
|
850
|
+
absolutePath: page.absolutePath,
|
|
851
|
+
startLine,
|
|
852
|
+
endLine: startLine + itemLines - 1,
|
|
853
|
+
lines: itemLines,
|
|
854
|
+
tokens: itemTokens,
|
|
855
|
+
score: candidate.pathScore + contentScore,
|
|
856
|
+
})
|
|
857
|
+
texts.set(candidate.path, itemText)
|
|
858
|
+
totalTokens += itemTokens
|
|
859
|
+
if (page.eof === false) truncated = true
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
files.sort((a, b) => b.score - a.score || compareText(a.path, b.path))
|
|
863
|
+
if (listingTruncated && files.length > 0) truncated = true
|
|
864
|
+
|
|
865
|
+
const totalLines = files.reduce((sum, file) => sum + file.lines, 0)
|
|
866
|
+
const context = {
|
|
867
|
+
enabled: files.length > 0,
|
|
868
|
+
sessionId,
|
|
869
|
+
workspaceRoot,
|
|
870
|
+
source,
|
|
871
|
+
skippedFiles,
|
|
872
|
+
truncated,
|
|
873
|
+
files,
|
|
874
|
+
totalFiles: files.length,
|
|
875
|
+
totalLines,
|
|
876
|
+
totalTokens,
|
|
877
|
+
budget: echoBudget,
|
|
878
|
+
}
|
|
879
|
+
if (files.length === 0) {
|
|
880
|
+
if (readFailures > 0) {
|
|
881
|
+
context.skipped = 'read-failed'
|
|
882
|
+
context.error = {
|
|
883
|
+
code: 'awareness_failed',
|
|
884
|
+
message: ('read failed' + (readDetail ? ': ' + readDetail : '')).slice(0, CONTEXT_ERROR_MAX),
|
|
885
|
+
}
|
|
886
|
+
} else if (aborted) {
|
|
887
|
+
context.skipped = 'read-failed'
|
|
888
|
+
context.error = { code: 'awareness_failed', message: 'context collection aborted' }
|
|
889
|
+
} else if (searchFailures > 0) {
|
|
890
|
+
context.skipped = 'search-failed'
|
|
891
|
+
context.error = { code: 'awareness_failed', message: (searchDetail || 'workspace search failed').slice(0, CONTEXT_ERROR_MAX) }
|
|
892
|
+
} else if (budgetSkipped) {
|
|
893
|
+
context.skipped = 'budget-exhausted'
|
|
894
|
+
}
|
|
895
|
+
} else if (searchFailures + readFailures > 0 || aborted) {
|
|
896
|
+
context.error = { code: 'awareness_failed', message: 'partial context' }
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
return {
|
|
900
|
+
context,
|
|
901
|
+
symbols: files.length > 0 ? extractSymbols(files, texts) : [],
|
|
902
|
+
texts,
|
|
903
|
+
}
|
|
904
|
+
} catch (err) {
|
|
905
|
+
return failed('read-failed', failureMessage(err))
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** 从已纳入的行窗口里提符号;行号是文件内绝对行号。 */
|
|
910
|
+
function extractSymbols(files, texts) {
|
|
911
|
+
const found = []
|
|
912
|
+
const seen = new Set()
|
|
913
|
+
for (const file of Array.isArray(files) ? files : []) {
|
|
914
|
+
if (!file || typeof file.path !== 'string') continue
|
|
915
|
+
const text = texts && typeof texts.get === 'function' ? texts.get(file.path) : ''
|
|
916
|
+
if (typeof text !== 'string' || !text) continue
|
|
917
|
+
const lines = text.split('\n')
|
|
918
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
919
|
+
const lineText = lines[index]
|
|
920
|
+
for (const rule of SYMBOL_RULES) {
|
|
921
|
+
const match = rule.re.exec(lineText)
|
|
922
|
+
if (!match) continue
|
|
923
|
+
const name = match[1]
|
|
924
|
+
if (!name || SYMBOL_RESERVED.has(name)) break
|
|
925
|
+
const key = file.path + '\0' + name
|
|
926
|
+
if (seen.has(key)) break
|
|
927
|
+
seen.add(key)
|
|
928
|
+
found.push({
|
|
929
|
+
name,
|
|
930
|
+
kind: rule.kind,
|
|
931
|
+
file: file.path,
|
|
932
|
+
line: (Number.isFinite(file.startLine) ? file.startLine : 1) + index,
|
|
933
|
+
})
|
|
934
|
+
break
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
found.sort((a, b) => compareText(a.file, b.file) || a.line - b.line || compareText(a.name, b.name))
|
|
939
|
+
return found.slice(0, CONTEXT_MAX_SYMBOLS)
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/** 把只读上下文拼成模型请求里的块;文件内容绝不进入响应。 */
|
|
943
|
+
function buildContextBlock(context, texts, locale) {
|
|
944
|
+
if (!context || !context.enabled || !Array.isArray(context.files) || context.files.length === 0) return ''
|
|
945
|
+
const header = locale === 'en'
|
|
946
|
+
? 'Read-only context from the current workspace. Use it only to resolve references in the draft; do not modify these files and do not answer or repeat this content.'
|
|
947
|
+
: '以下是当前工作区的只读上下文,仅用于理解草稿中的指代;不要修改这些文件,也不要回答或复述这些内容。'
|
|
948
|
+
const body = context.files.map((file) => {
|
|
949
|
+
const text = String(texts && typeof texts.get === 'function' ? texts.get(file.path) || '' : '').replace(/\n$/, '')
|
|
950
|
+
const path = String(file.path).replace(/"/g, '"')
|
|
951
|
+
return '<file path="' + path + '" lines="' + file.startLine + '-' + file.endLine + '">\n' + text + '\n</file>'
|
|
952
|
+
}).join('\n\n')
|
|
953
|
+
return '<workspace-context>\n' + header + '\n\n' + body + '\n</workspace-context>'
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* 命令描述:优先命令注册表(需要 Agent);取不到就降级。
|
|
958
|
+
* fallback 时用契约规定的通用文案,命令语义由 COMMAND_FALLBACKS 注入 system 提示词。
|
|
959
|
+
*/
|
|
960
|
+
function resolveCommand(ctx, sessionId, commandName, locale) {
|
|
961
|
+
const name = normalizeCommandName(commandName)
|
|
962
|
+
if (!name) return null
|
|
963
|
+
let descriptor = null
|
|
964
|
+
if (typeof sessionId === 'string' && sessionId) {
|
|
965
|
+
try {
|
|
966
|
+
const agents = ctx.get('agents')
|
|
967
|
+
const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
968
|
+
const commands = ctx.get('commands')
|
|
969
|
+
const list = agent && commands && typeof commands.list === 'function' ? commands.list(agent) : null
|
|
970
|
+
if (Array.isArray(list)) {
|
|
971
|
+
descriptor = list.find((item) => item
|
|
972
|
+
&& typeof item.name === 'string'
|
|
973
|
+
&& item.name.toLowerCase() === name
|
|
974
|
+
&& typeof item.description === 'string'
|
|
975
|
+
&& item.description.trim()) || null
|
|
976
|
+
}
|
|
977
|
+
} catch {
|
|
978
|
+
descriptor = null
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
if (descriptor) {
|
|
982
|
+
return { name, description: descriptor.description.trim().slice(0, 300), source: 'registry' }
|
|
983
|
+
}
|
|
984
|
+
return { name, description: COMMAND_FALLBACK_TEXT[locale], source: 'fallback' }
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/** 把命令语义注入 system 提示词;只在请求带有效命令名时生效。 */
|
|
988
|
+
function commandSystemNote(command, locale) {
|
|
989
|
+
const label = '/' + command.name
|
|
990
|
+
const table = command.source === 'fallback' ? COMMAND_FALLBACKS[command.name] : null
|
|
991
|
+
const semantics = table
|
|
992
|
+
? table[locale === 'en' ? 'en' : 'zh']
|
|
993
|
+
: String(command.description == null ? '' : command.description).replace(/\s+/g, ' ').slice(0, 300)
|
|
994
|
+
if (locale === 'en') {
|
|
995
|
+
return 'The draft starts with the ' + label + ' command. Command semantics: ' + semantics
|
|
996
|
+
+ ' Keep the rewrite consistent with this command and do not invent parameters it does not have.'
|
|
997
|
+
}
|
|
998
|
+
return '草稿以 ' + label + ' 命令开头。该命令的语义:' + semantics
|
|
999
|
+
+ ' 改写时请与这个命令的语义保持一致,不要虚构它没有的参数。'
|
|
1000
|
+
}
|
|
1001
|
+
|
|
273
1002
|
/** 模型清单:`GET`,返回默认模型与可选列表;面板据此渲染右上角选择器。 */
|
|
274
1003
|
async function handleModels(ctx, req, res) {
|
|
275
1004
|
if (req.method !== 'GET') {
|
|
@@ -333,6 +1062,16 @@ async function handle(ctx, req, res) {
|
|
|
333
1062
|
return
|
|
334
1063
|
}
|
|
335
1064
|
|
|
1065
|
+
const locale = localeOf(payload.locale)
|
|
1066
|
+
const awareness = normalizeAwarenessRequest(payload.awareness)
|
|
1067
|
+
const sessionId = normalizeSessionId(payload.sessionId)
|
|
1068
|
+
const command = resolveCommand(ctx, sessionId, payload.commandName, locale)
|
|
1069
|
+
const commandNote = command ? commandSystemNote(command, locale) : ''
|
|
1070
|
+
|
|
1071
|
+
let context
|
|
1072
|
+
let symbols = []
|
|
1073
|
+
let contextBlock = ''
|
|
1074
|
+
|
|
336
1075
|
const controller = new AbortController()
|
|
337
1076
|
const onClose = () => {
|
|
338
1077
|
if (!res.writableEnded) controller.abort()
|
|
@@ -341,13 +1080,44 @@ async function handle(ctx, req, res) {
|
|
|
341
1080
|
const timer = setTimeout(() => controller.abort(), CALL_TIMEOUT_MS)
|
|
342
1081
|
|
|
343
1082
|
try {
|
|
344
|
-
|
|
1083
|
+
// 默认关:awareness.enabled=false 时一次 workspaceFiles/fs 调用都不发生。
|
|
1084
|
+
if (awareness.enabled) {
|
|
1085
|
+
const awarenessCtrl = new AbortController()
|
|
1086
|
+
const awarenessTimer = setTimeout(() => awarenessCtrl.abort(), CONTEXT_TIMEOUT_MS)
|
|
1087
|
+
const onOuterAbort = () => awarenessCtrl.abort()
|
|
1088
|
+
controller.signal.addEventListener('abort', onOuterAbort)
|
|
1089
|
+
try {
|
|
1090
|
+
const workspace = await resolveWorkspace(ctx, sessionId, awarenessCtrl.signal)
|
|
1091
|
+
if (workspace.ok) {
|
|
1092
|
+
const collected = await collectContext(ctx, workspace, text, awareness, awarenessCtrl.signal)
|
|
1093
|
+
context = collected.context
|
|
1094
|
+
symbols = collected.symbols
|
|
1095
|
+
contextBlock = buildContextBlock(context, collected.texts, locale)
|
|
1096
|
+
} else {
|
|
1097
|
+
context = deniedContext(workspace.skipped, sessionId, awareness)
|
|
1098
|
+
}
|
|
1099
|
+
} catch (err) {
|
|
1100
|
+
// 采集是增强项:任何异常都折成审计字段,绝不改变本次改写的结果。
|
|
1101
|
+
context = failedAwarenessContext(sessionId, awareness, 'read-failed', failureMessage(err))
|
|
1102
|
+
} finally {
|
|
1103
|
+
clearTimeout(awarenessTimer)
|
|
1104
|
+
controller.signal.removeEventListener('abort', onOuterAbort)
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const raw = await rewrite(ctx, selection, text, locale, controller.signal, contextBlock, commandNote)
|
|
345
1109
|
const output = clean(raw)
|
|
346
1110
|
if (!output) {
|
|
347
1111
|
send(res, 502, { code: 'model', message: 'empty after clean: rawLen=' + String(raw).length })
|
|
348
1112
|
return
|
|
349
1113
|
}
|
|
350
|
-
|
|
1114
|
+
const body = { text: output, notes: [] }
|
|
1115
|
+
if (context) {
|
|
1116
|
+
body.context = context
|
|
1117
|
+
body.symbols = symbols
|
|
1118
|
+
}
|
|
1119
|
+
if (command) body.command = command
|
|
1120
|
+
send(res, 200, body)
|
|
351
1121
|
} catch (err) {
|
|
352
1122
|
// provider 侧和 AbortController 抛的是 AbortError(DOMException,name='AbortError'),
|
|
353
1123
|
// 我们自己的中止用 code='aborted';两者都映射成 499,让客户端知道是"被取消"而非"模型坏了"。
|
|
@@ -396,3 +1166,23 @@ export function apply(ctx) {
|
|
|
396
1166
|
}
|
|
397
1167
|
})
|
|
398
1168
|
}
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* 内部纯函数的测试入口(供 `test/host.mjs` 直接验证,不属于对外 HTTP 契约)。
|
|
1172
|
+
* 只导出纯函数与常量,不暴露 ctx 或任何宿主状态。
|
|
1173
|
+
*/
|
|
1174
|
+
export const __test__ = {
|
|
1175
|
+
estimateTokens,
|
|
1176
|
+
normalizeAwarenessRequest,
|
|
1177
|
+
normalizeCommandName,
|
|
1178
|
+
resolveWorkspace,
|
|
1179
|
+
extractContextHints,
|
|
1180
|
+
contextFileScore,
|
|
1181
|
+
countOccurrences,
|
|
1182
|
+
extractSymbols,
|
|
1183
|
+
buildContextBlock,
|
|
1184
|
+
resolveCommand,
|
|
1185
|
+
collectContext,
|
|
1186
|
+
CONTEXT_DEFAULTS,
|
|
1187
|
+
CONTEXT_LIMITS,
|
|
1188
|
+
}
|