dsh-extra-plan 0.0.0-stage → 1.7.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/LICENSE +21 -0
- package/README.md +179 -2
- package/assets/presets/extra-plan/agent.cordis.yml +580 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
- package/assets/presets/extra-plan/preset.yml +2 -0
- package/cordis.patch.yml +7 -0
- package/index.js +1671 -0
- package/lib/agent-runtime.js +172 -0
- package/lib/agent-session.js +65 -0
- package/lib/assembly-presentation.js +267 -0
- package/lib/client-carrier.js +7 -0
- package/lib/client.js +314 -0
- package/lib/extra-plan-gate-tool.js +387 -0
- package/lib/gate-decisions.js +744 -0
- package/lib/gate-words.js +108 -0
- package/lib/live-config.js +293 -0
- package/lib/log-retention.js +132 -0
- package/lib/model-routing.js +648 -0
- package/lib/path-policy.js +464 -0
- package/lib/plan-draft-tool.js +294 -0
- package/lib/planner-budget.js +136 -0
- package/lib/preset-defaults.generated.js +17 -0
- package/lib/preset-settings.js +3 -0
- package/lib/preset-sync.js +809 -0
- package/lib/preset-yaml.js +438 -0
- package/lib/role-contract.js +11 -0
- package/lib/run-code-scanner.js +360 -0
- package/lib/run-code-static.js +621 -0
- package/lib/runtime-diagnostics.js +89 -0
- package/lib/runtime-lifecycle.js +162 -0
- package/lib/runtime-static.js +23 -0
- package/lib/save-contract.js +263 -0
- package/lib/save-persistence.js +223 -0
- package/lib/save-plan-markdown-parser.js +369 -0
- package/lib/save-plan-validation-diagnostics.js +49 -0
- package/lib/save-plan-validation.js +812 -0
- package/lib/save-probe-validation.js +173 -0
- package/lib/save-source-verification.js +195 -0
- package/lib/save-tool-factories.js +270 -0
- package/lib/sdk-text-cache.js +161 -0
- package/lib/settings-contract.js +191 -0
- package/lib/settings.js +369 -0
- package/lib/shell-mutation.js +484 -0
- package/lib/usage-ledger-background.js +214 -0
- package/lib/usage-ledger-worker.js +116 -0
- package/lib/usage-ledger.js +1393 -0
- package/locale/en.json +6 -0
- package/locale/settings/en.json +6 -0
- package/locale/settings/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -4
- package/scripts/generate-runtime-defaults.mjs +796 -0
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
// run_code 静态解析与理由函数:只接收普通参数,不持有宿主/会话运行时状态。
|
|
2
|
+
import { maskCodeLiteralsAndComments, sliceBalancedArgs, collectRunCodeSites, hasDynamicRunCodeAccess } from './run-code-scanner.js'
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
// run_code 静态写模式扫描黑名单(F7',自写正则无依赖):防偶然写;防刻意绕过有限
|
|
6
|
+
// (动态 require/Function 构造/编码拼串不覆盖,见风险 R1)。白名单例外=不在黑名单:
|
|
7
|
+
// node:fs 只读方法族(readFileSync/readdirSync/statSync/existsSync/accessSync/readFile/
|
|
8
|
+
// readdir/stat/access/realpath/lstat 等)天然不命中。
|
|
9
|
+
export const RUNCODE_MUTATION_HINTS = [
|
|
10
|
+
{ id: 'fs-write', re: /\b(?:writeFileSync|appendFileSync|unlinkSync|rmSync|rmdirSync|mkdirSync|renameSync|copyFileSync|truncateSync|chmodSync|chownSync|symlinkSync|linkSync|mkdtempSync|createWriteStream|watch)\s*\(/ },
|
|
11
|
+
{ id: 'fs-promise-write', re: /\b(?:writeFile|appendFile|unlink|rm|rmdir|mkdir|rename|copyFile|truncate|chmod|chown|symlink|link|mkdtemp)\s*\(/ },
|
|
12
|
+
{ id: 'child-process-import', re: /(?:require\s*\(\s*['"](?:child_process|node:child_process)['"]\s*\))|(?:from\s+['"](?:child_process|node:child_process)['"])/ },
|
|
13
|
+
{ id: 'child-process-call', re: /\b(?:execSync|execFileSync|spawnSync|spawn|execFile|fork)\s*\(/ },
|
|
14
|
+
{ id: 'net-http-server', re: /(?:require\s*\(\s*['"](?:net|node:net|http|node:http)['"]\s*\))|(?:from\s+['"](?:net|node:net|http|node:http)['"])|\b(?:createServer|listen)\s*\(/ },
|
|
15
|
+
{ id: 'eval-function', re: /\b(?:eval|Function)\s*\(/ },
|
|
16
|
+
{ id: 'process-binding', re: /\bprocess\s*\.\s*binding\s*\(/ },
|
|
17
|
+
{ id: 'dlopen', re: /\bprocess\s*\.\s*dlopen\s*\(/ },
|
|
18
|
+
{ id: 'node-vm', re: /(?:require\s*\(\s*['"]node:vm['"]\s*\))|(?:from\s+['"]node:vm['"])|\b(?:runInThisContext|runInNewContext|runInContext|compileFunction)\s*\(/ },
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
// run_code 的 code 文本提取(exec.arguments.code 字符串;防御非字符串返回 '')。
|
|
22
|
+
export function runCodeTextOf(exec) {
|
|
23
|
+
const args = exec !== null && exec !== undefined ? exec.arguments : undefined
|
|
24
|
+
const code = args !== null && typeof args === 'object' ? args.code : undefined
|
|
25
|
+
return typeof code === 'string' ? code : ''
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// 静态扫描 code 返回命中的 hint id 列表(去重、按 RUNCODE_MUTATION_HINTS 顺序)。
|
|
29
|
+
export function codeMutationHints(code) {
|
|
30
|
+
const text = typeof code === 'string' ? code : ''
|
|
31
|
+
if (text === '') return []
|
|
32
|
+
const hits = []
|
|
33
|
+
for (const hint of RUNCODE_MUTATION_HINTS) {
|
|
34
|
+
if (hint.re.test(text)) hits.push(hint.id)
|
|
35
|
+
}
|
|
36
|
+
return hits
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 安全的静态参数字面量子集:先保留 JSON.parse 快路径,再用同一无执行解析器
|
|
40
|
+
// 校验重复键、污染键与宽松 JS 对象/数组字面量;失败时由调用方保留原 argsText 走运行时瀑布。
|
|
41
|
+
export function parseStaticLiteral(input) {
|
|
42
|
+
const source = typeof input === 'string' ? input.trim() : ''
|
|
43
|
+
if (source === '') return { ok: false, value: undefined }
|
|
44
|
+
let jsonValue
|
|
45
|
+
let jsonParsed = false
|
|
46
|
+
try {
|
|
47
|
+
jsonValue = JSON.parse(source)
|
|
48
|
+
jsonParsed = true
|
|
49
|
+
} catch (error) { /* 继续解析安全 JS literal 子集 */ }
|
|
50
|
+
|
|
51
|
+
let index = 0
|
|
52
|
+
const fail = () => { throw new Error('not a static literal') }
|
|
53
|
+
const skipWhitespace = () => {
|
|
54
|
+
while (index < source.length && /\s/.test(source[index])) index += 1
|
|
55
|
+
}
|
|
56
|
+
const isIdentifierChar = (ch) => ch !== undefined && /[A-Za-z0-9_$]/.test(ch)
|
|
57
|
+
|
|
58
|
+
const parseString = () => {
|
|
59
|
+
const quote = source[index]
|
|
60
|
+
if (quote !== "'" && quote !== '"') fail()
|
|
61
|
+
index += 1
|
|
62
|
+
let value = ''
|
|
63
|
+
while (index < source.length) {
|
|
64
|
+
const ch = source[index]
|
|
65
|
+
index += 1
|
|
66
|
+
if (ch === quote) return value
|
|
67
|
+
if (ch === '\n' || ch === '\r') fail()
|
|
68
|
+
if (ch !== '\\') {
|
|
69
|
+
value += ch
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
if (index >= source.length) fail()
|
|
73
|
+
const escaped = source[index]
|
|
74
|
+
index += 1
|
|
75
|
+
if (escaped === 'n') value += '\n'
|
|
76
|
+
else if (escaped === 'r') value += '\r'
|
|
77
|
+
else if (escaped === 't') value += '\t'
|
|
78
|
+
else if (escaped === 'b') value += '\b'
|
|
79
|
+
else if (escaped === 'f') value += '\f'
|
|
80
|
+
else if (escaped === 'v') value += '\v'
|
|
81
|
+
else if (escaped === '0') {
|
|
82
|
+
if (/[0-9]/.test(source[index] || '')) fail()
|
|
83
|
+
value += '\0'
|
|
84
|
+
} else if (escaped === 'u') {
|
|
85
|
+
const hex = source.slice(index, index + 4)
|
|
86
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(hex)) fail()
|
|
87
|
+
value += String.fromCharCode(Number.parseInt(hex, 16))
|
|
88
|
+
index += 4
|
|
89
|
+
} else if (escaped === 'x') {
|
|
90
|
+
const hex = source.slice(index, index + 2)
|
|
91
|
+
if (!/^[0-9A-Fa-f]{2}$/.test(hex)) fail()
|
|
92
|
+
value += String.fromCharCode(Number.parseInt(hex, 16))
|
|
93
|
+
index += 2
|
|
94
|
+
} else if (escaped === '\\' || escaped === '/' || escaped === "'" || escaped === '"') value += escaped
|
|
95
|
+
else fail()
|
|
96
|
+
}
|
|
97
|
+
fail()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const parseValue = () => {
|
|
101
|
+
skipWhitespace()
|
|
102
|
+
const ch = source[index]
|
|
103
|
+
if (ch === "'" || ch === '"') return parseString()
|
|
104
|
+
if (ch === '{') {
|
|
105
|
+
index += 1
|
|
106
|
+
const value = {}
|
|
107
|
+
const keys = new Set()
|
|
108
|
+
skipWhitespace()
|
|
109
|
+
if (source[index] === '}') { index += 1; return value }
|
|
110
|
+
while (true) {
|
|
111
|
+
skipWhitespace()
|
|
112
|
+
let key
|
|
113
|
+
if (source[index] === "'" || source[index] === '"') key = parseString()
|
|
114
|
+
else {
|
|
115
|
+
const match = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(source.slice(index))
|
|
116
|
+
if (match === null) fail()
|
|
117
|
+
key = match[0]
|
|
118
|
+
index += key.length
|
|
119
|
+
}
|
|
120
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype' || keys.has(key)) fail()
|
|
121
|
+
keys.add(key)
|
|
122
|
+
skipWhitespace()
|
|
123
|
+
if (source[index] !== ':') fail()
|
|
124
|
+
index += 1
|
|
125
|
+
value[key] = parseValue()
|
|
126
|
+
skipWhitespace()
|
|
127
|
+
if (source[index] === '}') { index += 1; return value }
|
|
128
|
+
if (source[index] !== ',') fail()
|
|
129
|
+
index += 1
|
|
130
|
+
skipWhitespace()
|
|
131
|
+
if (source[index] === '}') { index += 1; return value }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (ch === '[') {
|
|
135
|
+
index += 1
|
|
136
|
+
const value = []
|
|
137
|
+
skipWhitespace()
|
|
138
|
+
if (source[index] === ']') { index += 1; return value }
|
|
139
|
+
while (true) {
|
|
140
|
+
value.push(parseValue())
|
|
141
|
+
skipWhitespace()
|
|
142
|
+
if (source[index] === ']') { index += 1; return value }
|
|
143
|
+
if (source[index] !== ',') fail()
|
|
144
|
+
index += 1
|
|
145
|
+
skipWhitespace()
|
|
146
|
+
if (source[index] === ']') { index += 1; return value }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const [word, value] of [['true', true], ['false', false], ['null', null]]) {
|
|
150
|
+
if (source.startsWith(word, index) && !isIdentifierChar(source[index + word.length])) {
|
|
151
|
+
index += word.length
|
|
152
|
+
return value
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const number = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(source.slice(index))
|
|
156
|
+
if (number !== null) {
|
|
157
|
+
const value = Number(number[0])
|
|
158
|
+
if (!Number.isFinite(value)) fail()
|
|
159
|
+
index += number[0].length
|
|
160
|
+
return value
|
|
161
|
+
}
|
|
162
|
+
fail()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
const parsed = parseValue()
|
|
167
|
+
skipWhitespace()
|
|
168
|
+
if (index !== source.length) fail()
|
|
169
|
+
return { ok: true, value: jsonParsed ? jsonValue : parsed }
|
|
170
|
+
} catch (error) {
|
|
171
|
+
return { ok: false, value: undefined }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function createRunCodeStatic({ askTool, gateTool }) {
|
|
176
|
+
// run_code 拆解、组判定与聚合共用单一纯函数实现;直呼与组成员路径不复制规则,
|
|
177
|
+
// 闭包依赖显式传入,分支顺序与 listener 合同保持一致。
|
|
178
|
+
// 闸门工具 gateTool 与 askTool 同受返回链闸门(askOrGateReturnGateReason)约束:
|
|
179
|
+
// 两者在 run_code 内都只能直接 return await,或变量接收后紧随顶层 return 返回该结果。
|
|
180
|
+
|
|
181
|
+
// 拆解 run_code 的 code 文本为工具组(静态预审用)。返回 { members, dynamic }:
|
|
182
|
+
// members = 去重后的组员数组(按出现顺序;裸写伪成员固定排末尾);
|
|
183
|
+
// dynamic = 是否出现静态不可解析的动态工具访问(tools[var] 等)——不计入组,运行时瀑布兜底。
|
|
184
|
+
// 组员形状:
|
|
185
|
+
// { kind:'tool', name, argsParsed:boolean, args:object|null, argsText:string }(参数不可解析时 argsParsed:false)
|
|
186
|
+
// { kind:'bare-write', name:'write', hints:string[] }(裸写伪工具)
|
|
187
|
+
// 边界与兜底(写入注释,运行时瀑布兜底):动态访问 tools[var]/运行时拼名、参数不可解析、
|
|
188
|
+
// 嵌套 run_code 深度超限、eval/Function 动态代码——静态不可解析时不产生成员 → 组判定放行
|
|
189
|
+
// → 运行时嵌套调用自身进入 tools/pre-execute 瀑布按直呼闸门拦截(文案同源),安全方向。
|
|
190
|
+
function decomposeRunCode(code) {
|
|
191
|
+
const text = typeof code === 'string' ? code : ''
|
|
192
|
+
const members = []
|
|
193
|
+
if (text === '') return { members, dynamic: false }
|
|
194
|
+
const masked = maskCodeLiteralsAndComments(text)
|
|
195
|
+
const occupied = new Array(text.length).fill(false)
|
|
196
|
+
const seen = new Set()
|
|
197
|
+
const addMember = (member) => {
|
|
198
|
+
// 去重键 = name + '\u0001' + (argsParsed ? JSON.stringify(args) : '#raw:' + argsText)。
|
|
199
|
+
// 同名同参重复调用判定恒同,合并去重;同名不同参分别保留。
|
|
200
|
+
const key = member.kind === 'bare-write'
|
|
201
|
+
? 'bare-write\u0001' + member.hints.join('\u0001')
|
|
202
|
+
: member.name + '\u0001' + (member.argsParsed ? JSON.stringify(member.args) : '#raw:' + member.argsText)
|
|
203
|
+
if (seen.has(key)) return
|
|
204
|
+
seen.add(key)
|
|
205
|
+
members.push(member)
|
|
206
|
+
}
|
|
207
|
+
const markRange = (start, end) => {
|
|
208
|
+
for (let k = start; k <= end && k < occupied.length; k += 1) occupied[k] = true
|
|
209
|
+
}
|
|
210
|
+
// 调用点唯一由共享扫描器提取;动态 tools[...] 访问不生成静态成员。
|
|
211
|
+
const sites = collectRunCodeSites(text, masked)
|
|
212
|
+
const dynamic = hasDynamicRunCodeAccess(text, masked, sites)
|
|
213
|
+
for (const site of sites) {
|
|
214
|
+
if (site.name === undefined) continue
|
|
215
|
+
const argsText = site.innerText
|
|
216
|
+
const parsed = parseStaticLiteral(argsText)
|
|
217
|
+
const argsParsed = parsed.ok
|
|
218
|
+
const args = argsParsed ? parsed.value : null
|
|
219
|
+
addMember({ kind: 'tool', name: site.name, argsParsed, args, argsText })
|
|
220
|
+
markRange(site.start, site.calleeEnd)
|
|
221
|
+
}
|
|
222
|
+
// 裸写扫描只看已识别调用点占用区间之外的 masked 文本。
|
|
223
|
+
const restChars = masked.split('')
|
|
224
|
+
for (let k = 0; k < occupied.length; k += 1) { if (occupied[k]) restChars[k] = ' ' }
|
|
225
|
+
const hints = codeMutationHints(restChars.join(''))
|
|
226
|
+
if (hints.length > 0) addMember({ kind: 'bare-write', name: 'write', hints })
|
|
227
|
+
return { members, dynamic }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 多调用容错闸门:tools.* 调用点(未去重、含多行与动态访问;裸写不计)≥2 时,
|
|
231
|
+
// 每点必须有独立 try/catch(try 内恰 1 点、块后紧跟 catch);allSettled/.catch/包装函数不算。
|
|
232
|
+
// 单调用豁免;depth 0 且参数可解析的嵌套 run_code 展平,静态识别失败按未保护拒绝;
|
|
233
|
+
// decomposeRunCode 与 native 直呼路径保持同一合同。
|
|
234
|
+
function runCodeCatchGateReason(code) {
|
|
235
|
+
const text = typeof code === 'string' ? code : ''
|
|
236
|
+
if (text === '') return null
|
|
237
|
+
// 调用点收集:来自 run-code-scanner.js 的 collectRunCodeSites。
|
|
238
|
+
let total = 0
|
|
239
|
+
let protectedCount = 0
|
|
240
|
+
// 单层扫描(嵌套层递归;protection 按层内区间判定,跨层不继承)
|
|
241
|
+
const scanLayer =
|
|
242
|
+
(txt) => {
|
|
243
|
+
const msk = maskCodeLiteralsAndComments(txt)
|
|
244
|
+
const sites = collectRunCodeSites(txt, msk)
|
|
245
|
+
const tlen = txt.length
|
|
246
|
+
// 嵌套展平:depth 0 的 tools.run_code 且参数 JSON.parse 可解析 → 递归扫 args.code、
|
|
247
|
+
// 该调用点不计入本层;参数不可解析的 run_code 调用点按普通调用点计数。
|
|
248
|
+
const layerSites = []
|
|
249
|
+
for (const site of sites) {
|
|
250
|
+
if (site.name === 'run_code' && site.innerText !== '') {
|
|
251
|
+
const parsed = parseStaticLiteral(site.innerText)
|
|
252
|
+
if (parsed.ok && parsed.value !== null && typeof parsed.value === 'object' && typeof parsed.value.code === 'string') {
|
|
253
|
+
scanLayer(parsed.value.code)
|
|
254
|
+
continue
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
layerSites.push(site)
|
|
258
|
+
}
|
|
259
|
+
total += layerSites.length
|
|
260
|
+
const protectedIdx = new Set()
|
|
261
|
+
const within = (site, a, b) => site.start >= a && site.start <= b
|
|
262
|
+
// ① try/catch 保护:masked 上扫 try(前后非 idChar)→ 跳过 ws 须 '{' → 配平取块区间;
|
|
263
|
+
// 块后跳过 ws 须 catch(catch 后一字符非 idChar,兼容 catch(e)/catch{});
|
|
264
|
+
// 该 try 块内恰 1 个调用点 → 该点计入保护;≥2 个 → 均不保护。
|
|
265
|
+
let ti = 0
|
|
266
|
+
while (ti < tlen) {
|
|
267
|
+
const tIdx = msk.indexOf('try', ti)
|
|
268
|
+
if (tIdx === -1) break
|
|
269
|
+
if ((tIdx === 0 || (msk[tIdx - 1] === undefined || !/[A-Za-z0-9_$]/.test(msk[tIdx - 1]))) && (tIdx + 3 >= tlen || (msk[tIdx + 3] === undefined || !/[A-Za-z0-9_$]/.test(msk[tIdx + 3])))) {
|
|
270
|
+
let k = tIdx + 3
|
|
271
|
+
while (k < tlen && /\s/.test(msk[k])) k += 1
|
|
272
|
+
if (msk[k] === '{') {
|
|
273
|
+
// 花括号专用配平('{' 开头、'}' 归零即断;不用 sliceBalancedArgs——它在 ')' 归零才断,
|
|
274
|
+
// 会把 try 块区间错误延伸到 catch 的 '(e)')
|
|
275
|
+
let depthB = 0
|
|
276
|
+
let braceClose = -1
|
|
277
|
+
for (let x = k; x < tlen; x += 1) {
|
|
278
|
+
if (msk[x] === '{') depthB += 1
|
|
279
|
+
else if (msk[x] === '}') { depthB -= 1; if (depthB === 0) { braceClose = x; break } }
|
|
280
|
+
}
|
|
281
|
+
if (braceClose !== -1) {
|
|
282
|
+
let c = braceClose + 1
|
|
283
|
+
while (c < tlen && /\s/.test(msk[c])) c += 1
|
|
284
|
+
if (msk.slice(c, c + 5) === 'catch' && (c + 5 >= tlen || (msk[c + 5] === undefined || !/[A-Za-z0-9_$]/.test(msk[c + 5])))) {
|
|
285
|
+
const hits = []
|
|
286
|
+
for (let s = 0; s < layerSites.length; s += 1) {
|
|
287
|
+
if (within(layerSites[s], k, braceClose)) hits.push(s)
|
|
288
|
+
}
|
|
289
|
+
if (hits.length === 1) protectedIdx.add(hits[0])
|
|
290
|
+
}
|
|
291
|
+
ti = braceClose + 1
|
|
292
|
+
continue
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
ti = tIdx + 3
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
protectedCount += protectedIdx.size
|
|
300
|
+
}
|
|
301
|
+
scanLayer(text)
|
|
302
|
+
if (total < 2) return null
|
|
303
|
+
if (protectedCount === total) return null
|
|
304
|
+
return 'run_code 内 ' + total + ' 个工具调用未全部独立容错:请给每个调用点各写一个独立 try/catch——一次只包 1 个调用、块后紧跟 catch。已保护 ' + protectedCount + ' 个。写法示例:try { await tools.read({ file_path: "x" }) } catch (e) {}'
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ask_user_question / extra_plan_gate 返回链闸门(第一版):只在主会话 run_code 预执行前做保守静态证明。
|
|
308
|
+
// 两个闸门工具同受本闸门约束:允许直接 return await,或单一标识符接收后紧随顶层 return 且按标识符边界实际引用;其余无法证明结果返回用户层的形态拒绝。
|
|
309
|
+
function askOrGateReturnGateReason(code) {
|
|
310
|
+
const text = typeof code === 'string' ? code : ''
|
|
311
|
+
if (text === '') return null
|
|
312
|
+
const masked = maskCodeLiteralsAndComments(text)
|
|
313
|
+
// 拒绝文案按实际命中的工具名填入:同一闸门同时覆盖 ask_user_question 与 extra_plan_gate。
|
|
314
|
+
const reasonFor = (name) => 'run_code 内 ' + name + ' 的结果未正确返回用户层:请直接 return await tools.' + name + '(...),或先用变量接收后在紧随的顶层 return 中返回该结果;不得只调用、只赋值、通过别名或动态访问,或用 .then 与函数包装结果'
|
|
315
|
+
let reason = reasonFor(askTool)
|
|
316
|
+
const isIdChar = (ch) => ch !== undefined && /[A-Za-z0-9_$]/.test(ch)
|
|
317
|
+
const skipWs = (value, start) => {
|
|
318
|
+
let i = start
|
|
319
|
+
while (i < value.length && /\s/.test(value[i])) i += 1
|
|
320
|
+
return i
|
|
321
|
+
}
|
|
322
|
+
const sites = collectRunCodeSites(text, masked)
|
|
323
|
+
const askSites = sites.filter((site) => typeof site.name === 'string' && (site.name === askTool || site.name === gateTool))
|
|
324
|
+
const askStarts = new Set(askSites.map((site) => site.start))
|
|
325
|
+
let invalidReference = sites.some((site) => site.name === undefined)
|
|
326
|
+
|
|
327
|
+
// 任何静态属性引用但非调用、字面量方括号访问、动态方括号访问都不能证明是白名单形态。
|
|
328
|
+
let scan = 0
|
|
329
|
+
while (scan < masked.length) {
|
|
330
|
+
const idx = masked.indexOf('tools', scan)
|
|
331
|
+
if (idx === -1) break
|
|
332
|
+
if ((idx === 0 || !isIdChar(masked[idx - 1]))) {
|
|
333
|
+
let k = skipWs(masked, idx + 5)
|
|
334
|
+
if (masked[k] === '.') {
|
|
335
|
+
k = skipWs(masked, k + 1)
|
|
336
|
+
const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(masked.slice(k))
|
|
337
|
+
if (m !== null && (m[0] === askTool || m[0] === gateTool) && !isIdChar(masked[k + m[0].length])) {
|
|
338
|
+
if (!askStarts.has(idx)) {
|
|
339
|
+
invalidReference = true
|
|
340
|
+
reason = reasonFor(m[0])
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
} else if (masked[k] === '[') {
|
|
344
|
+
const close = masked.indexOf(']', k + 1)
|
|
345
|
+
const q = skipWs(text, k + 1)
|
|
346
|
+
if (text[q] === "'" || text[q] === '"') {
|
|
347
|
+
const quote = text[q]
|
|
348
|
+
let endQuote = q + 1
|
|
349
|
+
while (endQuote < text.length) {
|
|
350
|
+
if (text[endQuote] === '\\') { endQuote += 2; continue }
|
|
351
|
+
if (text[endQuote] === quote) break
|
|
352
|
+
endQuote += 1
|
|
353
|
+
}
|
|
354
|
+
const literal = text.slice(q + 1, endQuote)
|
|
355
|
+
const afterQuote = skipWs(text, endQuote + 1)
|
|
356
|
+
if (close === -1 || afterQuote !== close || literal === askTool || literal === gateTool || literal.includes('\\')) {
|
|
357
|
+
invalidReference = true
|
|
358
|
+
if (literal === askTool || literal === gateTool) reason = reasonFor(literal)
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
invalidReference = true
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
scan = idx + 5
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// 仅为可证明的数据位留例外。取顶层简单语句和静态字面量,不执行代码,
|
|
369
|
+
// 不以整个名字为豁免键;同名调用、成员/别名和无法证明的上下文仍按旧规则。
|
|
370
|
+
const dataOffsets = () => {
|
|
371
|
+
const offsets = new Set()
|
|
372
|
+
const scalars = new Set()
|
|
373
|
+
let start = 0
|
|
374
|
+
const accept = (end) => {
|
|
375
|
+
const raw = text.slice(start, end)
|
|
376
|
+
const visible = masked.slice(start, end)
|
|
377
|
+
if (raw.trim() === '') return
|
|
378
|
+
const binding = /^\s*(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=/u.exec(visible)
|
|
379
|
+
const returned = /^\s*return[ \t]+(?=\S)/u.exec(raw)
|
|
380
|
+
const form = binding ?? returned
|
|
381
|
+
if (form === null) { scalars.clear(); return }
|
|
382
|
+
const initializer = raw.slice(form[0].length)
|
|
383
|
+
const literal = parseStaticLiteral(initializer)
|
|
384
|
+
if (!literal.ok) {
|
|
385
|
+
const name = initializer.trim()
|
|
386
|
+
if (returned !== null && scalars.has(name)) offsets.add(start + form[0].length + initializer.indexOf(name))
|
|
387
|
+
scalars.clear()
|
|
388
|
+
return
|
|
389
|
+
}
|
|
390
|
+
if (binding !== null && (literal.value === null || typeof literal.value !== 'object')) {
|
|
391
|
+
const name = binding[1]
|
|
392
|
+
offsets.add(start + binding[0].lastIndexOf(name))
|
|
393
|
+
scalars.add(name)
|
|
394
|
+
} else if (binding !== null) scalars.delete(binding[1])
|
|
395
|
+
if (literal.value !== null && typeof literal.value === 'object') {
|
|
396
|
+
const valueStart = start + form[0].length
|
|
397
|
+
for (const m of masked.slice(valueStart, end).matchAll(/[{,]\s*([A-Za-z_$][\w$]*)\s*:/gu)) {
|
|
398
|
+
offsets.add(valueStart + m.index + m[0].indexOf(m[1]))
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const stack = []
|
|
403
|
+
const close = { ')': '(', ']': '[', '}': '{' }
|
|
404
|
+
for (let i = 0; i < masked.length; i += 1) {
|
|
405
|
+
const ch = masked[i]
|
|
406
|
+
if (ch === '(' || ch === '[' || ch === '{') stack.push(ch)
|
|
407
|
+
else if (close[ch] !== undefined && stack.pop() !== close[ch]) return new Set()
|
|
408
|
+
if (stack.length !== 0) continue
|
|
409
|
+
if (ch === ';' || (ch === '\n' && /^\s*(?:const|let|return)\b/u.test(masked.slice(i + 1)))) {
|
|
410
|
+
accept(i)
|
|
411
|
+
start = i + 1
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (stack.length === 0) accept(text.length)
|
|
415
|
+
return offsets
|
|
416
|
+
}
|
|
417
|
+
let plainData
|
|
418
|
+
// 裸名或非 tools 的属性在无法证明仅是数据时仍拒绝。
|
|
419
|
+
for (const gatedName of [askTool, gateTool]) {
|
|
420
|
+
if (typeof gatedName !== 'string' || gatedName === '') continue
|
|
421
|
+
scan = 0
|
|
422
|
+
while (scan < masked.length) {
|
|
423
|
+
const idx = masked.indexOf(gatedName, scan)
|
|
424
|
+
if (idx === -1) break
|
|
425
|
+
if ((idx === 0 || !isIdChar(masked[idx - 1])) && !isIdChar(masked[idx + gatedName.length])) {
|
|
426
|
+
let p = idx - 1
|
|
427
|
+
while (p >= 0 && /\s/.test(masked[p])) p -= 1
|
|
428
|
+
let direct = false
|
|
429
|
+
if (masked[p] === '.') {
|
|
430
|
+
p -= 1
|
|
431
|
+
while (p >= 0 && /\s/.test(masked[p])) p -= 1
|
|
432
|
+
const end = p
|
|
433
|
+
while (p >= 0 && isIdChar(masked[p])) p -= 1
|
|
434
|
+
direct = masked.slice(p + 1, end + 1) === 'tools'
|
|
435
|
+
}
|
|
436
|
+
if (!direct && !(plainData ??= dataOffsets()).has(idx)) {
|
|
437
|
+
invalidReference = true
|
|
438
|
+
reason = reasonFor(gatedName)
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
scan = idx + gatedName.length
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (invalidReference) return reason
|
|
445
|
+
if (askSites.length === 0) return null
|
|
446
|
+
|
|
447
|
+
// 仅在三种括号深度都为 0 时才把调用视为顶层语句中的调用。
|
|
448
|
+
const braceDepth = new Array(text.length + 1)
|
|
449
|
+
const parenDepth = new Array(text.length + 1)
|
|
450
|
+
const bracketDepth = new Array(text.length + 1)
|
|
451
|
+
let brace = 0
|
|
452
|
+
let paren = 0
|
|
453
|
+
let bracket = 0
|
|
454
|
+
for (let i = 0; i < masked.length; i += 1) {
|
|
455
|
+
braceDepth[i] = brace
|
|
456
|
+
parenDepth[i] = paren
|
|
457
|
+
bracketDepth[i] = bracket
|
|
458
|
+
if (masked[i] === '{') brace += 1
|
|
459
|
+
else if (masked[i] === '}') brace -= 1
|
|
460
|
+
else if (masked[i] === '(') paren += 1
|
|
461
|
+
else if (masked[i] === ')') paren -= 1
|
|
462
|
+
else if (masked[i] === '[') bracket += 1
|
|
463
|
+
else if (masked[i] === ']') bracket -= 1
|
|
464
|
+
}
|
|
465
|
+
braceDepth[text.length] = brace
|
|
466
|
+
parenDepth[text.length] = paren
|
|
467
|
+
bracketDepth[text.length] = bracket
|
|
468
|
+
const isTopLevel = (pos) => braceDepth[pos] === 0 && parenDepth[pos] === 0 && bracketDepth[pos] === 0
|
|
469
|
+
const candidateStarts = (pos) => {
|
|
470
|
+
const starts = [0]
|
|
471
|
+
for (let i = 0; i < pos; i += 1) {
|
|
472
|
+
if (masked[i] === ';' && isTopLevel(i)) starts.push(i + 1)
|
|
473
|
+
else if (masked[i] === '}' && isTopLevel(i + 1)) starts.push(i + 1)
|
|
474
|
+
}
|
|
475
|
+
return starts
|
|
476
|
+
}
|
|
477
|
+
const tokenAt = (value, pos, token) => value.slice(pos, pos + token.length) === token &&
|
|
478
|
+
(pos === 0 || !isIdChar(value[pos - 1])) && !isIdChar(value[pos + token.length])
|
|
479
|
+
const expressionEnd = (start) => {
|
|
480
|
+
for (let i = start; i < masked.length; i += 1) {
|
|
481
|
+
if (masked[i] === ';' && isTopLevel(i)) return i
|
|
482
|
+
if (masked[i] === '\n' && isTopLevel(i)) {
|
|
483
|
+
let k = skipWs(masked, i + 1)
|
|
484
|
+
if (/^(?:const|let|var|return|console|await|if|for|while|try|throw)\b/.test(masked.slice(k))) return i
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return masked.length
|
|
488
|
+
}
|
|
489
|
+
const references = (expression, name) => {
|
|
490
|
+
let i = 0
|
|
491
|
+
while (i < expression.length) {
|
|
492
|
+
const idx = expression.indexOf(name, i)
|
|
493
|
+
if (idx === -1) return false
|
|
494
|
+
if ((idx === 0 || !isIdChar(expression[idx - 1])) && !isIdChar(expression[idx + name.length])) {
|
|
495
|
+
let p = idx - 1
|
|
496
|
+
while (p >= 0 && /\s/.test(expression[p])) p -= 1
|
|
497
|
+
let n = idx + name.length
|
|
498
|
+
while (n < expression.length && /\s/.test(expression[n])) n += 1
|
|
499
|
+
if (expression[p] !== '.' && expression[n] !== ':') return true
|
|
500
|
+
}
|
|
501
|
+
i = idx + name.length
|
|
502
|
+
}
|
|
503
|
+
return false
|
|
504
|
+
}
|
|
505
|
+
const hasReassignment = (expression, name) => {
|
|
506
|
+
let i = 0
|
|
507
|
+
while (i < expression.length) {
|
|
508
|
+
const idx = expression.indexOf(name, i)
|
|
509
|
+
if (idx === -1) return false
|
|
510
|
+
if ((idx === 0 || !isIdChar(expression[idx - 1])) && !isIdChar(expression[idx + name.length])) {
|
|
511
|
+
let n = idx + name.length
|
|
512
|
+
while (n < expression.length && /\s/.test(expression[n])) n += 1
|
|
513
|
+
if (expression[n] === '=' && expression[n + 1] !== '=' && expression[n + 1] !== '>') return true
|
|
514
|
+
if ((expression[n] === '+' || expression[n] === '-') && expression[n + 1] === '+') return true
|
|
515
|
+
let p = idx - 1
|
|
516
|
+
while (p >= 0 && /\s/.test(expression[p])) p -= 1
|
|
517
|
+
if ((expression[p] === '+' || expression[p] === '-') && expression[p - 1] === expression[p]) return true
|
|
518
|
+
}
|
|
519
|
+
i = idx + name.length
|
|
520
|
+
}
|
|
521
|
+
return false
|
|
522
|
+
}
|
|
523
|
+
const afterCall = (site) => {
|
|
524
|
+
let k = site.end + 1
|
|
525
|
+
while (k < masked.length && /\s/.test(masked[k])) k += 1
|
|
526
|
+
let semicolon = false
|
|
527
|
+
if (masked[k] === ';') {
|
|
528
|
+
semicolon = true
|
|
529
|
+
k += 1
|
|
530
|
+
while (k < masked.length && /\s/.test(masked[k])) k += 1
|
|
531
|
+
}
|
|
532
|
+
return { pos: k, semicolon, gap: text.slice(site.end + 1, k) }
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// 站点形态只认 tools 点号调用,且工具名必须恰为两个闸门工具之一:分组选择式正则 + 两侧词边界,
|
|
536
|
+
// 避免前缀相同的名字(如 extra_plan_gate 与 extra_plan_gate_x)被误配;名字先转义再拼进选择式。
|
|
537
|
+
const escapeRegExpText = (value) => String(value).replace(/[^A-Za-z0-9_$]/g, '\\$&')
|
|
538
|
+
const gatedNames = [askTool, gateTool].filter((name) => typeof name === 'string' && name !== '')
|
|
539
|
+
const gatedCallHeadPattern = new RegExp('^tools\\s*\\.\\s*\\b(?:' + gatedNames.map(escapeRegExpText).join('|') + ')\\b\\s*[(]')
|
|
540
|
+
for (const site of askSites) {
|
|
541
|
+
const callHead = masked.slice(site.start, site.end + 1)
|
|
542
|
+
if (!isTopLevel(site.start) || !gatedCallHeadPattern.test(callHead)) return reasonFor(site.name)
|
|
543
|
+
if (callHead.includes('=>') || /\bfunction\b/.test(callHead)) return reasonFor(site.name)
|
|
544
|
+
let accepted = false
|
|
545
|
+
for (const start of candidateStarts(site.start)) {
|
|
546
|
+
const prefix = masked.slice(start, site.start).trim()
|
|
547
|
+
const direct = /^return[ \t]+await$/.test(prefix)
|
|
548
|
+
const assigned = /^(?:(?:const|let|var)[ \t]+)?([A-Za-z_$][A-Za-z0-9_$]*)[ \t]*=[ \t]*await$/.exec(prefix)
|
|
549
|
+
if (!direct && assigned === null) continue
|
|
550
|
+
const tail = afterCall(site)
|
|
551
|
+
if (direct) {
|
|
552
|
+
const continuation = ['.', '(', '[', '+', '-', '*', '/', '%', '&', '|', '?', ':', ',', '`'].includes(masked[tail.pos])
|
|
553
|
+
if (tail.pos === masked.length || tail.semicolon || ((tail.gap.includes('\n') || tail.gap.includes('\r')) && !continuation)) accepted = true
|
|
554
|
+
continue
|
|
555
|
+
}
|
|
556
|
+
if (!tail.semicolon && !tail.gap.includes('\n') && !tail.gap.includes('\r')) continue
|
|
557
|
+
if (!isTopLevel(tail.pos) || !tokenAt(masked, tail.pos, 'return')) continue
|
|
558
|
+
let exprStart = tail.pos + 6
|
|
559
|
+
const returnGapStart = exprStart
|
|
560
|
+
exprStart = skipWs(masked, exprStart)
|
|
561
|
+
const returnGap = text.slice(returnGapStart, exprStart)
|
|
562
|
+
if (exprStart >= masked.length || returnGap === '' || /[\r\n]/.test(returnGap)) continue
|
|
563
|
+
const end = expressionEnd(exprStart)
|
|
564
|
+
const expression = masked.slice(exprStart, end).trim()
|
|
565
|
+
const name = assigned[1]
|
|
566
|
+
if (expression === '' || !references(expression, name) || hasReassignment(expression, name)) continue
|
|
567
|
+
if (/\bconsole\s*\./.test(expression) || /\.\s*then\b/.test(expression) || expression.includes('=>') || /\bfunction\b/.test(expression)) continue
|
|
568
|
+
accepted = true
|
|
569
|
+
}
|
|
570
|
+
if (!accepted) return reasonFor(site.name)
|
|
571
|
+
}
|
|
572
|
+
return null
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// run_code code 静态调用点计数(单实例子调用上限快路径,planner 专属):run_code 调用点本身不计、
|
|
576
|
+
// 参数 JSON 可解析时递归展开 args.code(镜像 runCodeCatchGateReason 展平口径);其余调用点各计 1。
|
|
577
|
+
function runCodeSiteCount(code) {
|
|
578
|
+
const text = typeof code === 'string' ? code : ''
|
|
579
|
+
if (text === '') return 0
|
|
580
|
+
const masked = maskCodeLiteralsAndComments(text)
|
|
581
|
+
const sites = collectRunCodeSites(text, masked)
|
|
582
|
+
let total = 0
|
|
583
|
+
for (const site of sites) {
|
|
584
|
+
if (site.name === 'run_code' && site.innerText !== '') {
|
|
585
|
+
const parsed = parseStaticLiteral(site.innerText)
|
|
586
|
+
if (parsed.ok && parsed.value !== null && typeof parsed.value === 'object' && typeof parsed.value.code === 'string') {
|
|
587
|
+
total += runCodeSiteCount(parsed.value.code)
|
|
588
|
+
continue
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
total += 1
|
|
592
|
+
}
|
|
593
|
+
return total
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// 子调用语义判定:exec.sub===true(组判定合成成员)或 exec.parent!==undefined(运行时嵌套判定,
|
|
597
|
+
// 与官方 dsh-tools nested 判定同口径)→ true;其余 false(直呼/根 run_code 不算子调用)。
|
|
598
|
+
function isRunCodeSubCall(exec) {
|
|
599
|
+
if (exec === null || typeof exec !== 'object') return false
|
|
600
|
+
if (exec.sub === true) return true
|
|
601
|
+
if (exec.parent !== undefined) return true
|
|
602
|
+
return false
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// 单实例子调用超限文案(供运行时计数器与测试共用)。
|
|
606
|
+
function runCodeDispatchCapText(rid, count, cap) {
|
|
607
|
+
return `run_code 实例(rootCallId ${rid})子调用数 ${count} 超过上限 ${cap}(exploreBudget):请拆分 run_code 或提高 exploreBudget;循环/动态放大同样受限`
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
return {
|
|
611
|
+
maskCodeLiteralsAndComments,
|
|
612
|
+
sliceBalancedArgs,
|
|
613
|
+
decomposeRunCode,
|
|
614
|
+
runCodeCatchGateReason,
|
|
615
|
+
collectRunCodeSites,
|
|
616
|
+
askOrGateReturnGateReason,
|
|
617
|
+
runCodeSiteCount,
|
|
618
|
+
isRunCodeSubCall,
|
|
619
|
+
runCodeDispatchCapText,
|
|
620
|
+
}
|
|
621
|
+
}
|