@cheemsup/dsh-plugin-console 0.1.1 → 0.2.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.
@@ -1,174 +1,198 @@
1
- /**
2
- * 预测首请求里的 `runtime-context` 快照。
3
- *
4
- * 这段快照由 loop 在请求前拼好,来源有两类:
5
- * - **实测**:`assemble()` 直接给出的 contexts(harness:source、app:web-surface 等);
6
- * - **推导**:cwd / sandbox / approval 三段依赖会话状态,没有 Agent 时装配里是空的,
7
- * 但它们恰恰把「权限预设」这个条件变成了模型能看到的文字。
8
- *
9
- * 文案抄自已安装版本 `0.2.2-rc.1`(`dsh-working-directory`、`dsh-sandbox-policy`、
10
- * `dsh-user-approval`)。本地源码 checkout 的文案与已安装版不同,所以以日志为准。
11
- * @module dsh-plugin-console/host/preview-contexts
12
- */
13
-
14
- /** DSH 在快照正文前加的那句前缀。 */
15
- export const RUNTIME_CONTEXT_PREFIX = 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.'
16
-
17
- /** 三段会话依赖上下文的 order,与 `dsh-system-prompt` 的常量表一致。 */
18
- const ORDER = {
19
- WORKING_DIRECTORY: 100,
20
- SANDBOX_POLICY: 110,
21
- APPROVAL_POLICY: 115,
22
- }
23
-
24
- /** 三种 sandbox 模式各自在模型面前的文案。 */
25
- const SANDBOX_TEXT = {
26
- 'read-only': 'Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.',
27
- 'danger-full-access': 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.',
28
- }
29
-
30
- const NEVER_SENTENCE = 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).'
31
- const ASK_SENTENCE = 'Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.'
32
-
33
- /**
34
- * workspace-write 的文案要带上沙箱根目录;没有额外可写目录时不加那一句。
35
- * @param {string} workspaceRoot - 会话工作区路径。
36
- * @returns {string} 模型可见文本。
37
- */
38
- function workspaceWriteText(workspaceRoot) {
39
- return `Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: ${JSON.stringify(workspaceRoot)}. Some platform temporary areas may also be writable.`
40
- }
41
-
42
- /**
43
- * 与 system 段同一套插值规则:只替换能解析的变量,解析不了的保留字面量。
44
- * @param {string} text - 原文。
45
- * @param {object} variables - 变量表。
46
- * @returns {string} 渲染结果。
47
- */
48
- function interpolateText(text, variables) {
49
- return text.replace(/\{\{(\w+)\}\}/g, (whole, key) => {
50
- const value = variables?.[key]
51
- return typeof value === 'string' ? value : whole
52
- })
53
- }
54
-
55
- /**
56
- * 一条 runtime-context 分段。
57
- * @param {object} init - 分段字段。
58
- * @returns {object} 分段。
59
- */
60
- function segment(init) {
61
- return {
62
- name: init.name,
63
- order: init.order,
64
- text: init.text ?? '',
65
- confidence: init.confidence,
66
- ...(init.basis === undefined ? {} : { basis: init.basis }),
67
- ...(init.reason === undefined ? {} : { reason: init.reason }),
68
- }
69
- }
70
-
71
- /**
72
- * 预测整个 runtime-context 快照。
73
- * @param {object} assembly - `previewAssembly()` 的结果。
74
- * @param {object} conditions - `resolveConditions()` 的结果。
75
- * @param {object} [overrides] - 模板对 context 的逐段覆盖(name → 最终文本)。
76
- * @returns {object} `{ text, segments }`。
77
- */
78
- export function previewRuntimeContext(assembly, conditions, overrides) {
79
- const workspacePath = conditions?.workspace?.path
80
- const measured = new Map((assembly?.contexts ?? []).map((context) => [context.name, context]))
81
- const segments = []
82
-
83
- // —— 三段由会话状态决定的部分 ——
84
- if (typeof workspacePath === 'string' && workspacePath.length > 0) {
85
- segments.push(segment({
86
- name: 'working-directory:current',
87
- order: ORDER.WORKING_DIRECTORY,
88
- text: `Current working directory: ${JSON.stringify(workspacePath)}.`,
89
- confidence: 'derived',
90
- basis: ['workspace'],
91
- }))
92
- } else {
93
- // 没有工作区时不编一个路径,也不把这一项当成空段:模型是收不到的。
94
- segments.push(segment({
95
- name: 'working-directory:current',
96
- order: ORDER.WORKING_DIRECTORY,
97
- confidence: 'unknown',
98
- basis: ['workspace'],
99
- reason: 'workspace is not selected',
100
- }))
101
- }
102
-
103
- const sandbox = conditions?.permission?.sandbox
104
- if (typeof sandbox === 'string' && typeof workspacePath === 'string') {
105
- segments.push(segment({
106
- name: 'sandbox:policy',
107
- order: ORDER.SANDBOX_POLICY,
108
- text: sandbox === 'workspace-write' ? workspaceWriteText(workspacePath) : (SANDBOX_TEXT[sandbox] ?? ''),
109
- confidence: 'derived',
110
- basis: ['workspace', 'permission'],
111
- }))
112
- } else {
113
- segments.push(segment({
114
- name: 'sandbox:policy',
115
- order: ORDER.SANDBOX_POLICY,
116
- confidence: 'unknown',
117
- basis: ['permission'],
118
- reason: 'sandbox mode is unknown',
119
- }))
120
- }
121
-
122
- const approval = conditions?.permission?.approval
123
- if (approval === 'ask' || approval === 'never') {
124
- segments.push(segment({
125
- name: 'approval:policy',
126
- order: ORDER.APPROVAL_POLICY,
127
- text: approval === 'never' ? NEVER_SENTENCE : ASK_SENTENCE,
128
- confidence: 'derived',
129
- basis: ['permission'],
130
- }))
131
- } else {
132
- segments.push(segment({
133
- name: 'approval:policy',
134
- order: ORDER.APPROVAL_POLICY,
135
- confidence: 'unknown',
136
- basis: ['permission'],
137
- reason: 'approval policy is unknown',
138
- }))
139
- }
140
-
141
- // —— 装配直接给出的部分 ——
142
- const derivedNames = new Set(['working-directory:current', 'sandbox:policy', 'approval:policy'])
143
- for (const [name, context] of measured) {
144
- if (derivedNames.has(name)) continue
145
- const text = context.interpolate === false ? context.text : interpolateText(context.text, assembly?.variables)
146
- segments.push(segment({
147
- name,
148
- order: typeof context.order === 'number' ? context.order : undefined,
149
- text,
150
- confidence: 'measured',
151
- }))
152
- }
153
-
154
- // 模板覆盖只落在已经存在的段上:名字对不上就保持原样,不凭空造一个 context。
155
- if (overrides !== null && typeof overrides === 'object') {
156
- for (const item of segments) {
157
- const text = overrides[item.name]
158
- if (typeof text !== 'string') continue
159
- item.text = text
160
- item.overridden = true
161
- item.confidence = 'derived'
162
- delete item.reason
163
- item.basis = [...(item.basis ?? []), 'template']
164
- }
165
- }
166
-
167
- // DSH 按 order 排;读不到 order 的放在最后,保持相对顺序(sort 在 V8 上稳定)。
168
- segments.sort((left, right) => (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER))
169
- const body = segments.map((item) => item.text).filter((text) => text.length > 0).join('\n\n')
170
- return {
171
- text: body.length === 0 ? '' : `${RUNTIME_CONTEXT_PREFIX}\n\n${body}`,
172
- segments,
173
- }
174
- }
1
+ /**
2
+ * 预测首请求里的 `runtime-context` 快照。
3
+ *
4
+ * 这段快照由 loop 在请求前拼好,来源有两类:
5
+ * - **实测**:`assemble()` 直接给出的 contexts(harness:source、app:web-surface 等);
6
+ * - **推导**:cwd / sandbox / approval 三段依赖会话状态,没有 Agent 时装配里是空的,
7
+ * 但它们恰恰把「权限预设」这个条件变成了模型能看到的文字。
8
+ *
9
+ * 三段推导文案抄自已安装版本 `0.2.2-rc.5`(`dsh-working-directory`、`dsh-sandbox-policy`、
10
+ * `dsh-user-approval`)。外层包装则来自同一版本的 `dsh-agent-loop`:首份快照把 sections
11
+ * 包进 `<system-reminder>`,只介绍当前会话;只有后续快照才声明替换更早的上下文。
12
+ * 本地源码 checkout 的文案与已安装版不同,所以以日志为准。
13
+ * @module dsh-plugin-console/host/preview-contexts
14
+ */
15
+
16
+ /**
17
+ * 快照的固定包装。预演只模拟新会话的首请求,所以只会用到首份快照的引导语;
18
+ * 后续快照的 `It replaces earlier versions…` 不会出现在这里。
19
+ */
20
+ const SNAPSHOT_OPEN = '<system-reminder>'
21
+ const SNAPSHOT_CLOSE = '</system-reminder>'
22
+ const FIRST_SNAPSHOT_INTRO = 'The following information describes your current session:'
23
+
24
+ /**
25
+ * 把按 order 拼好的分段正文包成模型可见的 runtime-context 快照。
26
+ *
27
+ * 包装抄自 `0.2.2-rc.5` 的 `@deepseek-ai/dsh-agent-loop`(`project()`);早先版本
28
+ * 用的是 `Current runtime context. This snapshot supersedes…` 前缀,不能再拿旧文案
29
+ * 当预测。
30
+ * @param {string} body - 段间以 `\n\n` 连接的正文。
31
+ * @returns {string} 模型可见消息正文;没有正文时返回空串。
32
+ */
33
+ export function wrapRuntimeContext(body) {
34
+ if (body.length === 0) return ''
35
+ // 与 agent-loop 的 project() 一致:正文里若出现闭合标签,必须转义成 `<\/system-reminder>`,
36
+ // 否则一段上下文就能提前把提醒包装关掉。
37
+ const safeBody = body.replace(/<\/system-reminder\s*>/gi, (tag) => `<\\${tag.slice(1)}`)
38
+ return `${SNAPSHOT_OPEN}\n${FIRST_SNAPSHOT_INTRO}\n\n${safeBody}\n${SNAPSHOT_CLOSE}`
39
+ }
40
+
41
+ /** 三段会话依赖上下文的 order,与 `dsh-system-prompt` 的常量表一致。 */
42
+ const ORDER = {
43
+ WORKING_DIRECTORY: 100,
44
+ SANDBOX_POLICY: 110,
45
+ APPROVAL_POLICY: 115,
46
+ }
47
+
48
+ /** 三种 sandbox 模式各自在模型面前的文案。 */
49
+ const SANDBOX_TEXT = {
50
+ 'read-only': 'Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.',
51
+ 'danger-full-access': 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.',
52
+ }
53
+
54
+ const NEVER_SENTENCE = 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).'
55
+ const ASK_SENTENCE = 'Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.'
56
+
57
+ /**
58
+ * workspace-write 的文案要带上沙箱根目录;没有额外可写目录时不加那一句。
59
+ * @param {string} workspaceRoot - 会话工作区路径。
60
+ * @returns {string} 模型可见文本。
61
+ */
62
+ function workspaceWriteText(workspaceRoot) {
63
+ return `Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: ${JSON.stringify(workspaceRoot)}. Some platform temporary areas may also be writable.`
64
+ }
65
+
66
+ /**
67
+ * 与 system 段同一套插值规则:只替换能解析的变量,解析不了的保留字面量。
68
+ * @param {string} text - 原文。
69
+ * @param {object} variables - 变量表。
70
+ * @returns {string} 渲染结果。
71
+ */
72
+ function interpolateText(text, variables) {
73
+ return text.replace(/\{\{(\w+)\}\}/g, (whole, key) => {
74
+ const value = variables?.[key]
75
+ return typeof value === 'string' ? value : whole
76
+ })
77
+ }
78
+
79
+ /**
80
+ * 一条 runtime-context 分段。
81
+ * @param {object} init - 分段字段。
82
+ * @returns {object} 分段。
83
+ */
84
+ function segment(init) {
85
+ return {
86
+ name: init.name,
87
+ order: init.order,
88
+ text: init.text ?? '',
89
+ confidence: init.confidence,
90
+ ...(init.basis === undefined ? {} : { basis: init.basis }),
91
+ ...(init.reason === undefined ? {} : { reason: init.reason }),
92
+ }
93
+ }
94
+
95
+ /**
96
+ * 预测整个 runtime-context 快照。
97
+ * @param {object} assembly - `previewAssembly()` 的结果。
98
+ * @param {object} conditions - `resolveConditions()` 的结果。
99
+ * @param {object} [overrides] - 模板对 context 的逐段覆盖(name → 最终文本)。
100
+ * @returns {object} `{ text, segments }`。
101
+ */
102
+ export function previewRuntimeContext(assembly, conditions, overrides) {
103
+ const workspacePath = conditions?.workspace?.path
104
+ const measured = new Map((assembly?.contexts ?? []).map((context) => [context.name, context]))
105
+ const segments = []
106
+
107
+ // —— 三段由会话状态决定的部分 ——
108
+ if (typeof workspacePath === 'string' && workspacePath.length > 0) {
109
+ segments.push(segment({
110
+ name: 'working-directory:current',
111
+ order: ORDER.WORKING_DIRECTORY,
112
+ text: `Current working directory: ${JSON.stringify(workspacePath)}.`,
113
+ confidence: 'derived',
114
+ basis: ['workspace'],
115
+ }))
116
+ } else {
117
+ // 没有工作区时不编一个路径,也不把这一项当成空段:模型是收不到的。
118
+ segments.push(segment({
119
+ name: 'working-directory:current',
120
+ order: ORDER.WORKING_DIRECTORY,
121
+ confidence: 'unknown',
122
+ basis: ['workspace'],
123
+ reason: 'workspace is not selected',
124
+ }))
125
+ }
126
+
127
+ const sandbox = conditions?.permission?.sandbox
128
+ if (typeof sandbox === 'string' && typeof workspacePath === 'string') {
129
+ segments.push(segment({
130
+ name: 'sandbox:policy',
131
+ order: ORDER.SANDBOX_POLICY,
132
+ text: sandbox === 'workspace-write' ? workspaceWriteText(workspacePath) : (SANDBOX_TEXT[sandbox] ?? ''),
133
+ confidence: 'derived',
134
+ basis: ['workspace', 'permission'],
135
+ }))
136
+ } else {
137
+ segments.push(segment({
138
+ name: 'sandbox:policy',
139
+ order: ORDER.SANDBOX_POLICY,
140
+ confidence: 'unknown',
141
+ basis: ['permission'],
142
+ reason: 'sandbox mode is unknown',
143
+ }))
144
+ }
145
+
146
+ const approval = conditions?.permission?.approval
147
+ if (approval === 'ask' || approval === 'never') {
148
+ segments.push(segment({
149
+ name: 'approval:policy',
150
+ order: ORDER.APPROVAL_POLICY,
151
+ text: approval === 'never' ? NEVER_SENTENCE : ASK_SENTENCE,
152
+ confidence: 'derived',
153
+ basis: ['permission'],
154
+ }))
155
+ } else {
156
+ segments.push(segment({
157
+ name: 'approval:policy',
158
+ order: ORDER.APPROVAL_POLICY,
159
+ confidence: 'unknown',
160
+ basis: ['permission'],
161
+ reason: 'approval policy is unknown',
162
+ }))
163
+ }
164
+
165
+ // —— 装配直接给出的部分 ——
166
+ const derivedNames = new Set(['working-directory:current', 'sandbox:policy', 'approval:policy'])
167
+ for (const [name, context] of measured) {
168
+ if (derivedNames.has(name)) continue
169
+ const text = context.interpolate === false ? context.text : interpolateText(context.text, assembly?.variables)
170
+ segments.push(segment({
171
+ name,
172
+ order: typeof context.order === 'number' ? context.order : undefined,
173
+ text,
174
+ confidence: 'measured',
175
+ }))
176
+ }
177
+
178
+ // 模板覆盖只落在已经存在的段上:名字对不上就保持原样,不凭空造一个 context。
179
+ if (overrides !== null && typeof overrides === 'object') {
180
+ for (const item of segments) {
181
+ const text = overrides[item.name]
182
+ if (typeof text !== 'string') continue
183
+ item.text = text
184
+ item.overridden = true
185
+ item.confidence = 'derived'
186
+ delete item.reason
187
+ item.basis = [...(item.basis ?? []), 'template']
188
+ }
189
+ }
190
+
191
+ // DSH 按 order 排;读不到 order 的放在最后,保持相对顺序(sort 在 V8 上稳定)。
192
+ segments.sort((left, right) => (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER))
193
+ const body = segments.map((item) => item.text).filter((text) => text.length > 0).join('\n\n')
194
+ return {
195
+ text: wrapRuntimeContext(body),
196
+ segments,
197
+ }
198
+ }