@cheemsup/dsh-plugin-console 0.0.0-stage → 0.1.1

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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/cordis.patch.yml +5 -0
  4. package/lib/client.activity.js +222 -0
  5. package/lib/client.apply.js +171 -0
  6. package/lib/client.changes.js +206 -0
  7. package/lib/client.cleanup.js +270 -0
  8. package/lib/client.control.js +242 -0
  9. package/lib/client.dialog.js +77 -0
  10. package/lib/client.draft.js +280 -0
  11. package/lib/client.editor-messages.js +421 -0
  12. package/lib/client.editor-store.js +266 -0
  13. package/lib/client.editor.js +433 -0
  14. package/lib/client.effects.js +115 -0
  15. package/lib/client.influence.js +361 -0
  16. package/lib/client.js +216 -0
  17. package/lib/client.page.js +584 -0
  18. package/lib/client.plugin-filters.js +62 -0
  19. package/lib/client.plugins.js +504 -0
  20. package/lib/client.preview-messages.js +495 -0
  21. package/lib/client.preview-raw.js +132 -0
  22. package/lib/client.preview-store.js +128 -0
  23. package/lib/client.preview-tools.js +194 -0
  24. package/lib/client.preview.js +447 -0
  25. package/lib/client.schema.js +327 -0
  26. package/lib/client.search.js +408 -0
  27. package/lib/client.session-detail.js +503 -0
  28. package/lib/client.sessions.js +495 -0
  29. package/lib/client.shared.js +559 -0
  30. package/lib/client.store.js +452 -0
  31. package/lib/client.styles.js +524 -0
  32. package/lib/client.template-card.js +240 -0
  33. package/lib/client.tools.js +366 -0
  34. package/lib/client.workspace-picker.js +204 -0
  35. package/lib/host/activity.js +252 -0
  36. package/lib/host/assembly-preview.js +244 -0
  37. package/lib/host/attribution.js +307 -0
  38. package/lib/host/catalog.js +133 -0
  39. package/lib/host/categorize.js +40 -0
  40. package/lib/host/constants.js +66 -0
  41. package/lib/host/control.js +159 -0
  42. package/lib/host/entries.js +289 -0
  43. package/lib/host/fiber.js +86 -0
  44. package/lib/host/fs.js +99 -0
  45. package/lib/host/health.js +178 -0
  46. package/lib/host/http.js +65 -0
  47. package/lib/host/impact.js +132 -0
  48. package/lib/host/layers.js +132 -0
  49. package/lib/host/masks.js +145 -0
  50. package/lib/host/modes.js +96 -0
  51. package/lib/host/names.js +44 -0
  52. package/lib/host/patch-scan.js +103 -0
  53. package/lib/host/preview-conditions.js +281 -0
  54. package/lib/host/preview-contexts.js +174 -0
  55. package/lib/host/preview-envelope.js +31 -0
  56. package/lib/host/preview-instructions.js +450 -0
  57. package/lib/host/preview-messages.js +284 -0
  58. package/lib/host/preview-modules.js +233 -0
  59. package/lib/host/preview-skills.js +200 -0
  60. package/lib/host/prompt.js +213 -0
  61. package/lib/host/recipe-overlay.js +209 -0
  62. package/lib/host/request-preview.js +114 -0
  63. package/lib/host/routes/activation.js +96 -0
  64. package/lib/host/routes/activity.js +22 -0
  65. package/lib/host/routes/apply.js +93 -0
  66. package/lib/host/routes/cleanup.js +62 -0
  67. package/lib/host/routes/control.js +22 -0
  68. package/lib/host/routes/impact.js +19 -0
  69. package/lib/host/routes/operations.js +22 -0
  70. package/lib/host/routes/preview.js +58 -0
  71. package/lib/host/routes/session-influence.js +23 -0
  72. package/lib/host/routes/snapshot.js +21 -0
  73. package/lib/host/routes/template.js +54 -0
  74. package/lib/host/routes/templates.js +28 -0
  75. package/lib/host/scope-impact.js +125 -0
  76. package/lib/host/session-events.js +39 -0
  77. package/lib/host/session-influence.js +475 -0
  78. package/lib/host/sessions.js +293 -0
  79. package/lib/host/snapshot.js +218 -0
  80. package/lib/host/source-scan.js +225 -0
  81. package/lib/host/templates/cleanup.js +219 -0
  82. package/lib/host/templates/inheritance.js +144 -0
  83. package/lib/host/templates/materialize.js +317 -0
  84. package/lib/host/templates/message-overlay.js +184 -0
  85. package/lib/host/templates/repository.js +323 -0
  86. package/lib/host/templates/store.js +131 -0
  87. package/lib/host/tool-set.js +150 -0
  88. package/lib/host/tools.js +129 -0
  89. package/lib/index.js +103 -0
  90. package/package.json +111 -4
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 会话贡献掩码:把一个插件的工具贡献从**一个会话**里隐藏。
3
+ *
4
+ * 掩码只动工具 deny 名单,不卸载插件、不停服务、不移除事件监听,也不改模板
5
+ * 的提示词覆盖。它和模板共存的方式是「编译成一份 plan 再物化」:
6
+ * base = 会话自己的 manifest recipe(模板关闭时为 null)
7
+ * mask = 所有掩码记录里的工具名并集
8
+ * plan = mergeRecipes(base, mask)
9
+ * 这样同一个 agent scope 只会被物化一次,不会出现同名注册冲突。
10
+ *
11
+ * 掩码记录会持久化;resume / 子 Agent 创建时由 `installMaskInheritance` 重放。
12
+ * @module dsh-plugin-console/host/masks
13
+ */
14
+
15
+ import { applyRecipeToSession, clearRecipeForSession } from './templates/materialize.js'
16
+ import { deleteMask, getManifest, masksForSession, putMask } from './templates/repository.js'
17
+ import { ensureTemplateStore, templateTable } from './templates/store.js'
18
+
19
+ /**
20
+ * 合并模板 recipe 与掩码 recipe。
21
+ *
22
+ * 只合并工具 deny;提示词覆盖保留模板自己的(掩码目前不碰提示词段)。
23
+ * @param {object | null} base - 模板 recipe。
24
+ * @param {object | null} mask - 掩码 recipe。
25
+ * @returns {object} 合并后的 recipe。
26
+ */
27
+ export function mergeRecipes(base, mask) {
28
+ const left = base ?? {}
29
+ const right = mask ?? {}
30
+ const disabled = [...new Set([...(left.tools?.disabled ?? []), ...(right.tools?.disabled ?? [])])]
31
+ return {
32
+ ...left,
33
+ prompt: { ...(left.prompt ?? {}), ...(right.prompt ?? {}) },
34
+ tools: { ...(left.tools ?? {}), ...(right.tools ?? {}), disabled },
35
+ }
36
+ }
37
+
38
+ /** 一个会话的全部掩码编译成 recipe;没有掩码时 null。 */
39
+ export function buildMaskRecipe(state, sessionId) {
40
+ const masks = masksForSession(state, sessionId)
41
+ if (masks.length === 0) return null
42
+ const tools = [...new Set(masks.flatMap((mask) => Array.isArray(mask.tools) ? mask.tools : []))]
43
+ return tools.length > 0 ? { tools: { disabled: tools } } : null
44
+ }
45
+
46
+ /** 会话的模板 recipe;没有 manifest 或模板显式关闭时为 null。 */
47
+ export function baseRecipeForSession(state, sessionId) {
48
+ const manifest = getManifest(state, sessionId)
49
+ if (manifest === undefined) return null
50
+ const activation = templateTable(state, 'activations').get(sessionId)
51
+ if (activation !== undefined && activation.enabled !== true) return null
52
+ return manifest.recipe ?? null
53
+ }
54
+
55
+ /** 取会话的模式:header 优先,注册表兜底。 */
56
+ function presetOf(ctx, agent) {
57
+ const header = agent?.session?.header
58
+ if (typeof header?.agentPreset === 'string') return header.agentPreset
59
+ try {
60
+ return ctx.get('agentPresets')?.presetForSession?.(agent?.session) ?? undefined
61
+ } catch {
62
+ return undefined
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 按「模板 + 掩码」重新物化一个会话。
68
+ *
69
+ * 没有活 agent 时不物化,只返回 recorded;resume 时会由监听器重放。
70
+ * @param {object} ctx - host 插件上下文。
71
+ * @param {object} state - 模板存储状态。
72
+ * @param {string} sessionId - 会话 id。
73
+ * @returns {Promise<object>} 物化结果。
74
+ */
75
+ export async function reapplySessionPlan(ctx, state, sessionId) {
76
+ await ensureTemplateStore(ctx, state)
77
+ const base = baseRecipeForSession(state, sessionId)
78
+ const mask = buildMaskRecipe(state, sessionId)
79
+ if (base === null && mask === null) {
80
+ const cleared = await clearRecipeForSession(sessionId)
81
+ return { applied: false, live: true, cleared, reason: '没有提示词模板也没有掩码' }
82
+ }
83
+
84
+ const agent = ctx.get('agents')?.get?.(sessionId)
85
+ if (agent === undefined) {
86
+ return { applied: false, live: false, recorded: true, reason: '会话未激活;掩码已记录,resume 时按它重放' }
87
+ }
88
+
89
+ const result = await applyRecipeToSession(ctx, sessionId, mergeRecipes(base, mask), presetOf(ctx, agent))
90
+ return {
91
+ ...result,
92
+ live: true,
93
+ maskTools: mask?.tools?.disabled ?? [],
94
+ baseApplied: base !== null,
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 记录一条掩码并立即重放 plan。
100
+ * @param {object} ctx - host 插件上下文。
101
+ * @param {object} state - 模板存储状态。
102
+ * @param {{sessionId: string, rowId: string, tools: string[]}} input - 目标。
103
+ * @returns {Promise<object>} 记录与物化结果。
104
+ */
105
+ export async function addMask(ctx, state, input) {
106
+ await ensureTemplateStore(ctx, state)
107
+ const record = await putMask(state, input.sessionId, input.rowId, input.tools)
108
+ return { record, result: await reapplySessionPlan(ctx, state, input.sessionId) }
109
+ }
110
+
111
+ /**
112
+ * 删除一条掩码并重放剩余 plan。
113
+ * @param {object} ctx - host 插件上下文。
114
+ * @param {object} state - 模板存储状态。
115
+ * @param {{sessionId: string, rowId: string}} input - 目标。
116
+ * @returns {Promise<object>} 删除与物化结果。
117
+ */
118
+ export async function removeMask(ctx, state, input) {
119
+ await ensureTemplateStore(ctx, state)
120
+ await deleteMask(state, input.sessionId, input.rowId)
121
+ return { result: await reapplySessionPlan(ctx, state, input.sessionId) }
122
+ }
123
+
124
+ /**
125
+ * 在 agent 创建时重放掩码。
126
+ *
127
+ * 必须排在模板继承之后:模板先把 base 物化,掩码再把它和 mask 合并重物化。
128
+ * 没有掩码时什么都不做,避免每次 resume 都重复注册。
129
+ * @param {object} ctx - host 插件上下文。
130
+ * @param {object} state - 模板存储状态。
131
+ * @returns {void}
132
+ */
133
+ export function installMaskInheritance(ctx, state) {
134
+ ctx.on('agent/created', async ({ agent }) => {
135
+ const sessionId = typeof agent?.id === 'string' ? agent.id : agent?.session?.id
136
+ if (typeof sessionId !== 'string') return
137
+ try {
138
+ await ensureTemplateStore(ctx, state)
139
+ if (masksForSession(state, sessionId).length === 0) return
140
+ await reapplySessionPlan(ctx, state, sessionId)
141
+ } catch (error) {
142
+ ctx.logger?.warn?.('plugin-console: 掩码重放失败:' + (error instanceof Error ? error.message : String(error)))
143
+ }
144
+ })
145
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * 模式(Agent 预设)的两份事实:声明组合与运行时实测组合。
3
+ *
4
+ * 模式不是全局 Loader 的一部分,它挂在每个 Agent 自己的隔离 scope 里,所以必须
5
+ * 单独读:`compositionInventory()` 给声明值,`inspectCompositions(agent.ctx)` 给
6
+ * 此刻真正挂载的结果。两者的差额来自禁用行、条件行与仍在等依赖的条目。
7
+ * @module dsh-plugin-console/host/modes
8
+ */
9
+
10
+ import { FIBER_PHASE } from './constants.js'
11
+ import { readScopeTools } from './tools.js'
12
+
13
+ /**
14
+ * 读取 Agent 预设(模式)的当前组合。
15
+ *
16
+ * 每个 preset 自带一串子插件行,这是「模式」这一层贡献的插件;
17
+ * 和 base/profile 的条目合并后才是会话最终得到的插件集合。
18
+ * @param {object} ctx - host 插件上下文。
19
+ * @param {Map<string, Array<object>>} rowsByModule - 模块名 → 全局行摘要。
20
+ * @returns {Promise<Array<object>>} 预设列表;无 roster 时为空数组。
21
+ */
22
+ export async function readModes(ctx, rowsByModule) {
23
+ const presets = ctx.get('agentPresets')
24
+ if (presets === void 0 || typeof presets.compositionInventory !== 'function') return []
25
+ let inventory
26
+ try {
27
+ inventory = await presets.compositionInventory()
28
+ } catch {
29
+ return []
30
+ }
31
+ // `order` 只出现在 preset 的元数据列表里,compositionInventory 不带它。
32
+ // 它不是插件排序,而是模式自己的选择器顺序;读不到就不编造。
33
+ const orderById = new Map()
34
+ try {
35
+ const listed = typeof presets.list === 'function' ? await presets.list() : []
36
+ for (const row of Array.isArray(listed) ? listed : []) {
37
+ if (typeof row?.id === 'string' && typeof row.order === 'number') orderById.set(row.id, row.order)
38
+ }
39
+ } catch {
40
+ // 元数据列表读不到不影响组合本身
41
+ }
42
+ return inventory.map((mode) => ({
43
+ id: mode.id,
44
+ name: typeof mode.name === 'string' ? mode.name : undefined,
45
+ description: typeof mode.description === 'string' ? mode.description : undefined,
46
+ order: orderById.get(mode.id),
47
+ isDefault: Boolean(mode.isDefault),
48
+ broken: typeof mode.broken === 'string' ? mode.broken : undefined,
49
+ rows: (mode.rows ?? []).map((row) => ({
50
+ entryId: typeof row.entryId === 'string' ? row.entryId : null,
51
+ moduleName: row.moduleName,
52
+ // 读 preset 行引用的全局条目:会话追溯链的中间一环
53
+ globalRows: rowsByModule?.get(row.moduleName) ?? [],
54
+ enabled: row.enabled === 'conditional' ? null : row.enabled !== false,
55
+ conditional: row.enabled === 'conditional',
56
+ condition: typeof row.condition === 'string' ? row.condition : undefined,
57
+ phase: row.fiberState === undefined ? null : (FIBER_PHASE[row.fiberState] ?? null),
58
+ })),
59
+ })).sort((left, right) => (left.order ?? Infinity) - (right.order ?? Infinity) || left.id.localeCompare(right.id))
60
+ }
61
+
62
+ /**
63
+ * 读取一个活会话此刻**真正在运行**的模式组合。
64
+ *
65
+ * `inspectCompositions(agentCtx)` 只返回 `state === ACTIVE` 且未被禁用的条目。
66
+ * 因此它给的是实测值而不是声明值;冷会话没有 fiber,取不到,返回 undefined。
67
+ * @param {object} ctx - host 插件上下文。
68
+ * @param {object} agent - 活跃 Agent(`agents.get(sessionId)`)。
69
+ * @returns {{preset: string, modules: Array<string>, leakedServices: string[], tools?: string[]} | undefined} 运行时组合。
70
+ */
71
+ export function readRuntimeComposition(ctx, agent) {
72
+ const presets = ctx.get('agentPresets')
73
+ if (presets === undefined || typeof presets.inspectCompositions !== 'function') return undefined
74
+ const agentCtx = agent?.ctx
75
+ if (agentCtx === undefined) return undefined
76
+ let compositions
77
+ try {
78
+ compositions = presets.inspectCompositions(agentCtx)
79
+ } catch {
80
+ return undefined
81
+ }
82
+ const composition = compositions?.[0]
83
+ if (composition === undefined) return undefined
84
+ const view = readScopeTools(ctx, agentCtx)
85
+ return {
86
+ preset: composition.id,
87
+ modules: (composition.modules ?? [])
88
+ .map((module) => module?.moduleName)
89
+ .filter((name) => typeof name === 'string'),
90
+ leakedServices: (composition.leakedServices ?? []).filter((name) => typeof name === 'string'),
91
+ /** 读 agent scope 此刻可用的工具:已算完全局层与 scope 层的遮蔽。 */
92
+ tools: view?.visible,
93
+ /** restrict 之前的已知集;与 visible 的差集才是「被 restrict 过滤」。 */
94
+ knownNames: view?.knownNames,
95
+ }
96
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 名字归一与来源层判定。
3
+ *
4
+ * 这三个函数处理的是「一行的身份从哪来」这类问题:包名怎么从模块标识里取、
5
+ * 没有组合包认领的行该算哪一层、哪些行只是 Loader 的结构行。
6
+ * @module dsh-plugin-console/host/names
7
+ */
8
+
9
+ /**
10
+ * 从包名得到「裸包名」:`@scope/name` 或 `name`,丢弃子路径导出。
11
+ * @param {string} specifier - Loader 行的模块标识。
12
+ * @returns {string | undefined} 裸包名;不是包标识时 undefined。
13
+ */
14
+ export function barePackageName(specifier) {
15
+ if (typeof specifier !== 'string' || specifier.startsWith('.') || specifier.startsWith('cordis:')) return undefined
16
+ const parts = specifier.split('/')
17
+ if (specifier.startsWith('@')) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : undefined
18
+ return parts[0]
19
+ }
20
+
21
+ /**
22
+ * 没有 bundle 认领的行,按来源判层。
23
+ *
24
+ * - `cordis:*` 是 Loader 结构行(include 根、group),不属于任何组合包;
25
+ * - 深度 0 且无 bundle 认领的行,是插件在运行时用 `ctx.plugin()` 直接挂上的
26
+ * 子 fiber(例如目录选择器的原生实现),也不来自任何 patch;
27
+ * - 其余未认领的行只可能是 profile 或 home 补丁自己插入的。
28
+ * @param {string} moduleName - 行的模块标识。
29
+ * @param {number} depth - 条目在 id 路径上的深度;顶层根行的深度是 0。
30
+ * @returns {string} 层标识。
31
+ */
32
+ export function fallbackLayer(moduleName, depth) {
33
+ if (typeof moduleName === 'string' && moduleName.startsWith('cordis:')) return 'cordis'
34
+ return depth === 0 ? 'runtime' : 'profile'
35
+ }
36
+
37
+ /**
38
+ * 结构行(cordis:include、cordis:group)不是插件,不计入任何统计。
39
+ * @param {object} entry - 已采集的条目。
40
+ * @returns {boolean} 是否结构行。
41
+ */
42
+ export function isStructuralEntry(entry) {
43
+ return typeof entry.moduleName === 'string' && entry.moduleName.startsWith('cordis:')
44
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * profile / home 的 `cordis.patch.yml` 扫描。
3
+ *
4
+ * 完整的 YAML 解析在这里没有收益:patch 的语义只有两种(`insert` 与按
5
+ * `id` 覆盖),而界面需要回答的是「这一行被谁、改了哪些顶层键」。所以
6
+ * 这里只按缩进识别块式 patch,并记下每个 id 的顶层键名;流式 insert
7
+ * 与嵌套 group 不求全——漏报只影响键的展示,不影响覆盖关系本身。
8
+ * @module dsh-plugin-console/host/patch-scan
9
+ */
10
+
11
+ /**
12
+ * 扫描一个 patch 文件,分别给出插入行与覆盖行。
13
+ *
14
+ * 识别的缩进形状(DSH 组合文件实际使用的块式写法):
15
+ * - insert: ← 顶层,进入插入模式
16
+ * - id: added ← 插入行,缩进 > 0
17
+ * name: pkg ← 该行的顶层键
18
+ * - id: existing ← 顶层,覆盖行
19
+ * config: ← 该行的顶层键(嵌套内容不展开)
20
+ *
21
+ * 同一个 id 在一个文件里出现多次时,键取并集,行号取首次出现的位置。
22
+ * @param {string} text - patch 文件内容。
23
+ * @returns {{inserted: Map<string, {keys: string[], line: number}>, overridden: Map<string, {keys: string[], line: number}>}}
24
+ * 插入行与覆盖行;值是该行声明的顶层键与起始行号。
25
+ */
26
+ export function scanPatchRows(text) {
27
+ const inserted = new Map()
28
+ const overridden = new Map()
29
+ let inserting = false
30
+ /** @type {{entry: {keys: string[], line: number}, keyIndent: number} | null} */
31
+ let current = null
32
+ let lineNo = 0
33
+
34
+ /** 同一个 id 重复出现时复用同一条记录,键去重后合并。 */
35
+ const record = (rows, id, line) => {
36
+ let entry = rows.get(id)
37
+ if (entry === undefined) {
38
+ entry = { keys: [], line }
39
+ rows.set(id, entry)
40
+ }
41
+ return entry
42
+ }
43
+
44
+ for (const rawLine of text.split(/\r?\n/)) {
45
+ lineNo++
46
+ // 注释只在行尾截断;引号内的 # 目前不会出现在 id 或键名上。
47
+ const line = rawLine.replace(/#.*$/, '')
48
+ if (!line.trim()) continue
49
+ const indent = line.length - line.trimStart().length
50
+ const body = line.trim()
51
+
52
+ // 顶层的每个新条目都会结束上一个 id 的作用域。
53
+ if (indent === 0) {
54
+ current = null
55
+ inserting = false
56
+ if (/^-\s*insert\s*:/.test(body)) {
57
+ inserting = true
58
+ continue
59
+ }
60
+ const idLine = body.match(/^-\s*id\s*:\s*(.+)$/)
61
+ if (idLine === null) continue
62
+ const id = cleanId(idLine[1])
63
+ if (!id) continue
64
+ current = { entry: record(overridden, id, lineNo), keyIndent: 2 }
65
+ continue
66
+ }
67
+
68
+ const idLine = body.match(/^-\s*id\s*:\s*(.+)$/)
69
+ if (idLine !== null) {
70
+ const id = cleanId(idLine[1])
71
+ current = inserting && id ? { entry: record(inserted, id, lineNo), keyIndent: indent + 2 } : null
72
+ continue
73
+ }
74
+
75
+ if (current === null) continue
76
+ // 缩进回退说明这个行条目结束;顶层键只认它自己那一层。
77
+ if (indent < current.keyIndent) {
78
+ current = null
79
+ continue
80
+ }
81
+ if (indent !== current.keyIndent) continue
82
+ const keyLine = body.match(/^([A-Za-z_][\w-]*)\s*:/)
83
+ if (keyLine === null || keyLine[1] === 'id') continue
84
+ if (!current.entry.keys.includes(keyLine[1])) current.entry.keys.push(keyLine[1])
85
+ }
86
+
87
+ return { inserted, overridden }
88
+ }
89
+
90
+ /**
91
+ * 只要 id 集合的兼容入口。
92
+ * @param {string} text - patch 文件内容。
93
+ * @returns {{inserted: Set<string>, overridden: Set<string>}} 两种 id 集合。
94
+ */
95
+ export function scanPatchIds(text) {
96
+ const { inserted, overridden } = scanPatchRows(text)
97
+ return { inserted: new Set(inserted.keys()), overridden: new Set(overridden.keys()) }
98
+ }
99
+
100
+ /** 去掉 id 两端的引号,其余字符原样保留。 */
101
+ function cleanId(raw) {
102
+ return raw.trim().replace(/^['"]|['"]$/g, '')
103
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * 预演条件:把「在哪个工作区、用哪套权限、什么模型、什么时区」解析成可展示的值。
3
+ *
4
+ * 为什么这些要单独成文件:首请求里有一半内容不是 `assemble()` 产出的,而是
5
+ * loop 与 pre-step 监听器按会话状态注入的(cwd、sandbox、approval、skill 目录、
6
+ * 时间快照)。那些东西在「只选一个模式」的预演里根本没有输入,页面只能显示
7
+ * 空——把一个条件缺失说成「模型没收到」,结论正好相反。所以条件必须先被显式解析,
8
+ * 解析不出来就标未知并写原因,不留空。
9
+ *
10
+ * 所有采集都降级:任何一段读不到只影响它自己,绝不抛错——除了 `assemble()` 本身。
11
+ * @module dsh-plugin-console/host/preview-conditions
12
+ */
13
+
14
+ import { isAbsolute, resolve } from 'node:path'
15
+ import { isDirectory } from './fs.js'
16
+
17
+ /** 路径比较在 Windows 上大小写不敏感;这是比较口径,不是路径改写。 */
18
+ const WINDOWS = process.platform === 'win32'
19
+
20
+ /** 模型信息查询的上限:适配器可能访问网络,预演不该被它拖住。 */
21
+ const MODEL_INFO_TIMEOUT_MS = 2000
22
+
23
+ /** 客户端时区的合理长度上限;超长说明不是 IANA 时区名。 */
24
+ const MAX_TIME_ZONE_LENGTH = 64
25
+
26
+ /** 列举可用的 permissionPresets 选项时要保留的字段。 */
27
+ function presetOption(option) {
28
+ return {
29
+ value: String(option?.value ?? ''),
30
+ name: typeof option?.name === 'string' ? option.name : String(option?.value ?? ''),
31
+ ...(typeof option?.description === 'string' ? { description: option.description } : {}),
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 归一化路径用于**比较**:统一分隔符、去掉尾部分隔符,Windows 上折成小写。
37
+ * 不改写任何展示路径——注册表里的 `path` 才是权威写法。
38
+ * @param {unknown} value - 待比较的路径。
39
+ * @returns {string} 比较键。
40
+ */
41
+ function pathKey(value) {
42
+ const text = String(value ?? '').replace(/[\\/]+/g, '/').replace(/\/+$/, '')
43
+ return WINDOWS ? text.toLowerCase() : text
44
+ }
45
+
46
+ /**
47
+ * 解析工作区条件。
48
+ *
49
+ * 已注册的工作区优先用注册表记录(id / title 是权威值);未注册但真实存在的绝对路径
50
+ * 按「自定义目录」预演——预演需要看任意目录的 AGENTS.md 与 skill 目录,不能只限注册表。
51
+ * 自定义目录只用于推导:它没有工作区 id,不会被拿去建会话。
52
+ * @param {object} ctx - host 插件上下文。
53
+ * @param {string | undefined} requested - 客户端选择的工作区路径。
54
+ * @param {string[]} warnings - 收集警告。
55
+ * @returns {Promise<object | null>} `{ id, path, title, source }`;无法解析时为 null。
56
+ */
57
+ async function readWorkspace(ctx, requested, warnings) {
58
+ let list = []
59
+ try {
60
+ list = ctx.get('workspaceRegistry')?.list?.() ?? []
61
+ } catch (error) {
62
+ warnings.push(`工作区注册表不可用:${error instanceof Error ? error.message : String(error)}`)
63
+ }
64
+ if (typeof requested !== 'string' || requested.trim().length === 0) {
65
+ warnings.push('未选择工作区:skill 目录、workspace 指令与 cwd / sandbox / approval 文本都无法预测')
66
+ return null
67
+ }
68
+ const requestedText = requested.trim()
69
+ const found = list.find((workspace) => pathKey(workspace?.path) === pathKey(requestedText))
70
+ if (found !== undefined) {
71
+ return {
72
+ id: found.id ?? null,
73
+ path: found.path,
74
+ title: found.title ?? found.path,
75
+ source: 'registered',
76
+ }
77
+ }
78
+ // 注册表里没有:只有真实存在的绝对路径才能当目录读。
79
+ if (!isAbsolute(requestedText)) {
80
+ warnings.push(`工作区路径「${requestedText}」不是绝对路径:无法定位目录`)
81
+ return null
82
+ }
83
+ const resolved = resolve(requestedText)
84
+ if (!(await isDirectory(resolved))) {
85
+ warnings.push(`工作区路径「${resolved}」不存在或不是目录`)
86
+ return null
87
+ }
88
+ warnings.push(`工作区「${resolved}」未注册:按自定义目录预演,仅影响推导,不用于建会话`)
89
+ return { id: null, path: resolved, title: resolved, source: 'custom' }
90
+ }
91
+
92
+ /**
93
+ * 组合默认的 sandbox / approval。
94
+ *
95
+ * 新建会话在 `permissionPresets` 缺席时会直接读到这两个值,所以它们是「没有预设时
96
+ * 真实会生效的东西」,而不是猜测。
97
+ * @param {object} ctx - host 插件上下文。
98
+ * @returns {{ sandbox: string | null, approval: string }} 组合默认值。
99
+ */
100
+ function compositionPermission(ctx) {
101
+ let sandbox = null
102
+ let approval = 'ask'
103
+ try {
104
+ const mode = ctx.get('shell')?.sandboxMode
105
+ if (typeof mode === 'string') sandbox = mode
106
+ } catch {
107
+ // shell 不可用就留空,由调用方标未知
108
+ }
109
+ try {
110
+ const policy = ctx.get('approval')?.config?.policy
111
+ if (typeof policy === 'string') approval = policy
112
+ } catch {
113
+ // approval 不可用就用 DSH 自己的缺省
114
+ }
115
+ return { sandbox, approval }
116
+ }
117
+
118
+ /**
119
+ * 解析权限预设:预设名 → `{ sandbox, approval }` 的映射由 `permissionPresets.resolve()`
120
+ * 给出,不需要去偷读 Loader 行的私有配置。
121
+ * @param {object} ctx - host 插件上下文。
122
+ * @param {string | undefined} requested - 客户端选择的预设名。
123
+ * @param {string[]} warnings - 收集警告。
124
+ * @returns {object} `{ preset, sandbox, approval, source, options }`。
125
+ */
126
+ function readPermission(ctx, requested, warnings) {
127
+ const fallback = compositionPermission(ctx)
128
+ let service
129
+ let catalog = null
130
+ try {
131
+ service = ctx.get('permissionPresets')
132
+ catalog = service?.catalog?.() ?? null
133
+ } catch (error) {
134
+ warnings.push(`权限预设目录不可用:${error instanceof Error ? error.message : String(error)}`)
135
+ }
136
+ if (catalog === null || catalog === undefined) {
137
+ warnings.push('权限预设服务不可用:sandbox 与 approval 退回组合默认值')
138
+ return { preset: null, ...fallback, source: 'composition', options: [] }
139
+ }
140
+
141
+ const options = (catalog.options ?? []).map(presetOption)
142
+ const names = new Set(options.map((option) => option.value))
143
+ const fallbackName = typeof catalog.defaultPreset === 'string' ? catalog.defaultPreset : null
144
+ let preset = fallbackName
145
+ let source = 'default'
146
+ if (typeof requested === 'string' && requested.length > 0) {
147
+ if (names.has(requested)) {
148
+ preset = requested
149
+ source = 'selected'
150
+ } else {
151
+ warnings.push(`未知的权限预设「${requested}」:改用部署默认值「${fallbackName ?? '无'}」`)
152
+ }
153
+ }
154
+
155
+ let spec = null
156
+ try {
157
+ spec = service.resolve(preset)
158
+ } catch {
159
+ // `custom` 不是可切换目标,`resolve()` 对它必然抛错:它本身就等于「不匹配任何预设」,
160
+ // 所以直接退回组合默认值,那正是当前会话真实生效的 sandbox / approval。
161
+ spec = null
162
+ }
163
+ if (spec === null) {
164
+ return { preset, ...fallback, source: 'composition', options }
165
+ }
166
+ return {
167
+ preset,
168
+ sandbox: typeof spec.sandbox === 'string' ? spec.sandbox : fallback.sandbox,
169
+ approval: typeof spec.approval === 'string' ? spec.approval : fallback.approval,
170
+ source,
171
+ options,
172
+ }
173
+ }
174
+
175
+ /**
176
+ * 解析默认模型。没有它,`{{model}}` / `{{provider}}` 只能保留字面量。
177
+ * @param {object} ctx - host 插件上下文。
178
+ * @param {string[]} warnings - 收集警告。
179
+ * @returns {object | null} `{ provider, model, reasoningEffort?, source }`。
180
+ */
181
+ function readModel(ctx, warnings) {
182
+ try {
183
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
184
+ if (typeof selection?.provider === 'string' && typeof selection?.model === 'string') {
185
+ return {
186
+ provider: selection.provider,
187
+ model: selection.model,
188
+ ...(typeof selection.reasoningEffort === 'string' ? { reasoningEffort: selection.reasoningEffort } : {}),
189
+ source: 'default',
190
+ }
191
+ }
192
+ } catch (error) {
193
+ warnings.push(`默认模型不可用:${error instanceof Error ? error.message : String(error)}`)
194
+ return null
195
+ }
196
+ warnings.push('默认模型不可用:provider、model 与上下文窗口都标为未知')
197
+ return null
198
+ }
199
+
200
+ /**
201
+ * 解析上下文窗口。
202
+ *
203
+ * 适配器可能真的去问远端,所以既传 AbortSignal 又自己设一道超时——只依赖 signal 的话,
204
+ * 不理会信号的适配器会让整次预演挂住。
205
+ * @param {object} ctx - host 插件上下文。
206
+ * @param {object | null} model - 已解析的模型。
207
+ * @param {string[]} warnings - 收集警告。
208
+ * @returns {Promise<number | null>} 窗口大小(token)。
209
+ */
210
+ async function readContextWindow(ctx, model, warnings) {
211
+ if (model === null) return null
212
+ const llm = ctx.get('llm')
213
+ if (typeof llm?.resolveModelInfo !== 'function') {
214
+ warnings.push('llm 服务不可用:上下文窗口未知')
215
+ return null
216
+ }
217
+ let timer
218
+ try {
219
+ const expired = new Promise((resolve) => {
220
+ timer = setTimeout(() => resolve(null), MODEL_INFO_TIMEOUT_MS)
221
+ })
222
+ const info = await Promise.race([
223
+ llm.resolveModelInfo(model.provider, model.model, AbortSignal.timeout(MODEL_INFO_TIMEOUT_MS)),
224
+ expired,
225
+ ])
226
+ const window = info?.context?.contextWindow
227
+ return typeof window === 'number' && window > 0 ? window : null
228
+ } catch (error) {
229
+ warnings.push(`模型信息查询失败:上下文窗口未知(${error instanceof Error ? error.message : String(error)})`)
230
+ return null
231
+ } finally {
232
+ clearTimeout(timer)
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 解析客户端时区:模型看到的 time-context 用的就是这个时区。
238
+ * @param {unknown} requested - 客户端上报的 IANA 时区名。
239
+ * @param {string[]} warnings - 收集警告。
240
+ * @returns {{ clientTimeZone: string, clientTimeZoneSource: 'client' | 'server' }} 时区与来源。
241
+ */
242
+ function readTimeZone(requested, warnings) {
243
+ if (typeof requested === 'string' && requested.length > 0 && requested.length <= MAX_TIME_ZONE_LENGTH) {
244
+ return { clientTimeZone: requested, clientTimeZoneSource: 'client' }
245
+ }
246
+ let fallback = 'UTC'
247
+ try {
248
+ fallback = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
249
+ } catch {
250
+ // 拿不到就用 UTC,不编一个时区出来
251
+ }
252
+ warnings.push('客户端时区缺失:退回服务端时区')
253
+ return { clientTimeZone: fallback, clientTimeZoneSource: 'server' }
254
+ }
255
+
256
+ /**
257
+ * 解析一次首请求预演的全部条件。
258
+ * @param {object} ctx - host 插件上下文。
259
+ * @param {object} options - 客户端上报的条件。
260
+ * @param {string} [options.workspacePath] - 工作区路径:已注册路径,或任意绝对目录。
261
+ * @param {string} [options.permissionPreset] - 权限预设名。
262
+ * @param {string} [options.clientTimeZone] - 客户端 IANA 时区。
263
+ * @returns {Promise<object>} 条件 + 警告。
264
+ */
265
+ export async function resolveConditions(ctx, options = {}) {
266
+ const warnings = []
267
+ const workspace = await readWorkspace(ctx, options.workspacePath, warnings)
268
+ const permission = readPermission(ctx, options.permissionPreset, warnings)
269
+ const model = readModel(ctx, warnings)
270
+ const contextWindow = await readContextWindow(ctx, model, warnings)
271
+ const zone = readTimeZone(options.clientTimeZone, warnings)
272
+ return {
273
+ workspace,
274
+ permission,
275
+ model,
276
+ contextWindow,
277
+ clientTimeZone: zone.clientTimeZone,
278
+ clientTimeZoneSource: zone.clientTimeZoneSource,
279
+ warnings,
280
+ }
281
+ }