dsh-deep-ptc-mode 1.7.1 → 1.7.3
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 +91 -63
- package/README.md +180 -174
- package/README.zh.md +195 -193
- package/TEST_REPORT.md +33 -0
- package/lib/ask-user.mjs +2 -1
- package/lib/client.js +46 -0
- package/lib/guard.mjs +2 -1
- package/lib/host.mjs +30 -13
- package/lib/index.mjs +47 -9
- package/lib/jobs-tool.mjs +2 -1
- package/lib/model.mjs +18 -16
- package/lib/official-names.mjs +115 -0
- package/lib/rules.mjs +5 -5
- package/lib/sleep-lint.mjs +391 -41
- package/lib/tool-catalog.mjs +45 -0
- package/lib/tool-compatibility.mjs +87 -4
- package/lib/tool-policy.mjs +193 -87
- package/lib/upstream.mjs +13 -0
- package/package.json +126 -120
- package/lib/official-tools.mjs +0 -8
package/lib/sleep-lint.mjs
CHANGED
|
@@ -1,44 +1,332 @@
|
|
|
1
|
-
// Static checks for waiting written into commands or run_code programs.
|
|
2
|
-
//
|
|
1
|
+
// Static checks for waiting written into commands or run_code programs. Only a real pause counts: text in
|
|
2
|
+
// strings, comments and arguments is not one. A pause whose length cannot be read is allowed, because the
|
|
3
|
+
// runtime still bounds it: foreground commands move to the background and programs have a deadline.
|
|
3
4
|
export const MAX_PAUSE_SECONDS = 5;
|
|
4
5
|
|
|
5
6
|
const UNIT_SECONDS = { '': 1, s: 1, m: 60, h: 3600, d: 86400 };
|
|
7
|
+
const COMMAND_PREFIXES = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time', 'command', 'builtin', 'exec', 'nohup', 'nice', 'sudo', 'env']);
|
|
8
|
+
const HEREDOC = /^<<-?[ \t]*(?:'([^'\n]+)'|"([^"\n]+)"|\\?([^\s;&|<>()'"]+))/u;
|
|
6
9
|
|
|
7
|
-
//
|
|
8
|
-
|
|
10
|
+
// Split shell source into simple commands, each `{ words, background }`. Quoted text stays inside one word,
|
|
11
|
+
// comments and heredoc bodies disappear, and command substitutions become commands of their own.
|
|
12
|
+
function shellCommands(source, dialect) {
|
|
13
|
+
const commands = [];
|
|
14
|
+
const posix = dialect === 'posix';
|
|
15
|
+
let words = [];
|
|
16
|
+
let word;
|
|
17
|
+
let heredocs = [];
|
|
18
|
+
let i = 0;
|
|
19
|
+
const append = text => { word = (word ?? '') + text; };
|
|
20
|
+
const endWord = () => {
|
|
21
|
+
if (word !== undefined) words.push(word);
|
|
22
|
+
word = undefined;
|
|
23
|
+
};
|
|
24
|
+
const endCommand = (background = false) => {
|
|
25
|
+
endWord();
|
|
26
|
+
if (words.length > 0) commands.push({ words, background });
|
|
27
|
+
words = [];
|
|
28
|
+
};
|
|
29
|
+
const closing = (open, close) => {
|
|
30
|
+
let depth = 1;
|
|
31
|
+
let quote;
|
|
32
|
+
for (let at = open; at < source.length; at++) {
|
|
33
|
+
const c = source[at];
|
|
34
|
+
if (quote !== undefined) {
|
|
35
|
+
if (c === '\\' && quote === '"' && posix) at++;
|
|
36
|
+
else if (c === quote) quote = undefined;
|
|
37
|
+
} else if (c === '\\' && posix) at++;
|
|
38
|
+
else if (c === '"' || c === "'") quote = c;
|
|
39
|
+
else if (c === '(' && close === ')') depth++;
|
|
40
|
+
else if (c === close && --depth === 0) return at;
|
|
41
|
+
}
|
|
42
|
+
return source.length;
|
|
43
|
+
};
|
|
44
|
+
const substitute = (start, end) => commands.push(...shellCommands(source.slice(start, end), dialect));
|
|
45
|
+
const doubleQuoted = () => {
|
|
46
|
+
for (i++; i < source.length && source[i] !== '"'; i++) {
|
|
47
|
+
const c = source[i];
|
|
48
|
+
if (c === (posix ? '\\' : '`') && i + 1 < source.length) append(source[++i]);
|
|
49
|
+
else if (c === '$' && source[i + 1] === '(') {
|
|
50
|
+
const end = closing(i + 2, ')');
|
|
51
|
+
substitute(i + 2, end);
|
|
52
|
+
i = end;
|
|
53
|
+
} else if (c === '`' && posix) {
|
|
54
|
+
const end = closing(i + 1, '`');
|
|
55
|
+
substitute(i + 1, end);
|
|
56
|
+
i = end;
|
|
57
|
+
} else append(c);
|
|
58
|
+
}
|
|
59
|
+
i++;
|
|
60
|
+
};
|
|
61
|
+
while (i < source.length) {
|
|
62
|
+
const c = source[i];
|
|
63
|
+
const rest = source.slice(i, i + 2);
|
|
64
|
+
if (c === '\n') {
|
|
65
|
+
endCommand();
|
|
66
|
+
i++;
|
|
67
|
+
for (const terminator of heredocs) {
|
|
68
|
+
while (i < source.length) {
|
|
69
|
+
let end = source.indexOf('\n', i);
|
|
70
|
+
if (end === -1) end = source.length;
|
|
71
|
+
const line = source.slice(i, end);
|
|
72
|
+
i = end + 1;
|
|
73
|
+
if (line.replace(/^\t+/u, '').trimEnd() === terminator) break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
heredocs = [];
|
|
77
|
+
} else if (c === ' ' || c === '\t' || c === '\r') {
|
|
78
|
+
endWord();
|
|
79
|
+
i++;
|
|
80
|
+
} else if (word === undefined && c === '#') {
|
|
81
|
+
while (i < source.length && source[i] !== '\n') i++;
|
|
82
|
+
} else if (!posix && rest === '<#') {
|
|
83
|
+
const end = source.indexOf('#>', i + 2);
|
|
84
|
+
i = end === -1 ? source.length : end + 2;
|
|
85
|
+
} else if (!posix && (rest === "@'" || rest === '@"')) {
|
|
86
|
+
const end = source.indexOf(`\n${rest[1]}@`, i + 2);
|
|
87
|
+
append(source.slice(i + 2, end === -1 ? source.length : end));
|
|
88
|
+
i = end === -1 ? source.length : end + 3;
|
|
89
|
+
} else if (posix && rest === '<<' && source[i + 2] !== '<') {
|
|
90
|
+
const match = HEREDOC.exec(source.slice(i));
|
|
91
|
+
if (match) heredocs.push(match[1] ?? match[2] ?? match[3]);
|
|
92
|
+
i += match?.[0].length ?? 2;
|
|
93
|
+
} else if (c === '\\' && posix) {
|
|
94
|
+
append(source[i + 1] ?? '');
|
|
95
|
+
i += 2;
|
|
96
|
+
} else if (c === '`' && !posix) {
|
|
97
|
+
append(source[i + 1] ?? '');
|
|
98
|
+
i += 2;
|
|
99
|
+
} else if (c === '`') {
|
|
100
|
+
const end = closing(i + 1, '`');
|
|
101
|
+
substitute(i + 1, end);
|
|
102
|
+
i = end + 1;
|
|
103
|
+
} else if (c === "'") {
|
|
104
|
+
let end = source.indexOf("'", i + 1);
|
|
105
|
+
while (!posix && end !== -1 && source[end + 1] === "'") end = source.indexOf("'", end + 2);
|
|
106
|
+
append(source.slice(i + 1, end === -1 ? source.length : end));
|
|
107
|
+
i = end === -1 ? source.length : end + 1;
|
|
108
|
+
} else if (c === '"') {
|
|
109
|
+
append('');
|
|
110
|
+
doubleQuoted();
|
|
111
|
+
} else if (rest === '$(') {
|
|
112
|
+
const end = closing(i + 2, ')');
|
|
113
|
+
substitute(i + 2, end);
|
|
114
|
+
append('');
|
|
115
|
+
i = end + 1;
|
|
116
|
+
} else if (c === '&' && (source[i + 1] === '>' || source[i - 1] === '>' || source[i - 1] === '<')) {
|
|
117
|
+
append(c);
|
|
118
|
+
i++;
|
|
119
|
+
} else if (c === '&' && rest !== '&&' && source[i - 1] !== '&') {
|
|
120
|
+
endCommand(true);
|
|
121
|
+
i++;
|
|
122
|
+
} else if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')') {
|
|
123
|
+
endCommand();
|
|
124
|
+
i++;
|
|
125
|
+
} else if ((c === '{' || c === '}') && word === undefined) {
|
|
126
|
+
endCommand();
|
|
127
|
+
i++;
|
|
128
|
+
} else {
|
|
129
|
+
append(c);
|
|
130
|
+
i++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
endCommand();
|
|
134
|
+
return commands;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// `sleep 2m 30s`, `sleep infinity`, `sleep -s 30`, `Start-Sleep -Milliseconds:500`.
|
|
138
|
+
function sleepSeconds(args) {
|
|
139
|
+
let total = 0;
|
|
140
|
+
for (let index = 0; index < args.length; index++) {
|
|
141
|
+
const flag = /^-(\w+)(?::(.*))?$/u.exec(args[index]);
|
|
142
|
+
if (flag) {
|
|
143
|
+
const name = flag[1].toLowerCase();
|
|
144
|
+
if (!/^(?:s|se|sec|seco|secon|second|seconds|m|mi|mil|mill|milli|millis|millise|milliseco|millisecon|millisecond|milliseconds)$/u.test(name)) return total;
|
|
145
|
+
const value = Number(flag[2] ?? args[++index]);
|
|
146
|
+
if (!Number.isNaN(value)) total += name.startsWith('m') ? value / 1000 : value;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (args[index] === 'infinity') return Infinity;
|
|
150
|
+
const match = /^([0-9]*\.?[0-9]+)([smhd]?)$/u.exec(args[index]);
|
|
151
|
+
if (match) total += Number(match[1]) * UNIT_SECONDS[match[2]];
|
|
152
|
+
}
|
|
153
|
+
return total;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function commandName(word) {
|
|
157
|
+
return word.replace(/^.*[\\/]/u, '').replace(/\.exe$/iu, '').toLowerCase();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The longest pause one simple command starts in the foreground, looking through shells and wrappers.
|
|
161
|
+
function commandPause(words, dialect) {
|
|
162
|
+
let index = 0;
|
|
163
|
+
while (index < words.length) {
|
|
164
|
+
const word = words[index];
|
|
165
|
+
if (/^[A-Za-z_]\w*=/u.test(word) || COMMAND_PREFIXES.has(word) || (index > 0 && word.startsWith('-') && COMMAND_PREFIXES.has(words[index - 1]))) index++;
|
|
166
|
+
else break;
|
|
167
|
+
}
|
|
168
|
+
const name = commandName(words[index] ?? '');
|
|
169
|
+
const args = words.slice(index + 1);
|
|
170
|
+
if (name === 'sleep' || name === 'start-sleep') return sleepSeconds(args);
|
|
171
|
+
if (name === 'timeout' && args[0]?.toLowerCase() === '/t') {
|
|
172
|
+
const seconds = Number(args[1]);
|
|
173
|
+
return Number.isNaN(seconds) ? 0 : seconds < 0 ? Infinity : seconds;
|
|
174
|
+
}
|
|
175
|
+
if (['bash', 'sh', 'zsh', 'dash', 'ksh'].includes(name)) {
|
|
176
|
+
const script = args.findIndex(arg => /^-[a-z]*c$/u.test(arg));
|
|
177
|
+
return script === -1 ? 0 : shellPauseSeconds(args[script + 1] ?? '', 'posix');
|
|
178
|
+
}
|
|
179
|
+
if (name === 'pwsh' || name === 'powershell') {
|
|
180
|
+
const script = args.findIndex(arg => /^-c(?:o(?:m(?:m(?:a(?:n(?:d)?)?)?)?)?)?$/iu.test(arg));
|
|
181
|
+
return script === -1 ? 0 : shellPauseSeconds(args.slice(script + 1).join(' '), 'powershell');
|
|
182
|
+
}
|
|
183
|
+
if (name === 'cmd') {
|
|
184
|
+
const script = args.findIndex(arg => /^\/[ck]$/iu.test(arg));
|
|
185
|
+
return script === -1 ? 0 : shellPauseSeconds(args.slice(script + 1).join(' '), 'powershell');
|
|
186
|
+
}
|
|
187
|
+
if (name === 'wsl') {
|
|
188
|
+
let at = 0;
|
|
189
|
+
while (at < args.length && args[at].startsWith('-')) {
|
|
190
|
+
const flag = args[at].toLowerCase();
|
|
191
|
+
if (flag === '--' || flag === '-e' || flag === '--exec') {
|
|
192
|
+
at++;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
at += ['-d', '--distribution', '-u', '--user', '--cd'].includes(flag) ? 2 : 1;
|
|
196
|
+
}
|
|
197
|
+
return commandPause(args.slice(at), 'posix');
|
|
198
|
+
}
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Longest foreground pause a command starts, in seconds; 0 when there is none.
|
|
204
|
+
* @param command - shell source.
|
|
205
|
+
* @param dialect - `posix` for bash and zsh, `powershell` for PowerShell, whose quoting differs.
|
|
206
|
+
*/
|
|
207
|
+
export function shellPauseSeconds(command, dialect = 'posix') {
|
|
9
208
|
let longest = 0;
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
for (const m of command.matchAll(/\b(?:Start-Sleep|sleep)\s+(?:-(s|seconds|m|milliseconds|duration)\s+)?([0-9]*\.?[0-9]+)/giu)) {
|
|
14
|
-
const flag = (m[1] ?? 's').toLowerCase();
|
|
15
|
-
if (flag === 'duration') continue;
|
|
16
|
-
take(flag.startsWith('m') ? Number(m[2]) / 1000 : Number(m[2]));
|
|
17
|
-
}
|
|
18
|
-
for (const m of command.matchAll(/\btimeout(?:\.exe)?\s+\/t\s+(-?\d+)/giu)) take(Number(m[1]) < 0 ? Infinity : Number(m[1]));
|
|
209
|
+
for (const { words, background } of shellCommands(command, dialect)) {
|
|
210
|
+
if (!background) longest = Math.max(longest, commandPause(words, dialect));
|
|
211
|
+
}
|
|
19
212
|
return longest;
|
|
20
213
|
}
|
|
21
214
|
|
|
22
|
-
|
|
215
|
+
const REGEX_FOLLOWS = /(?:^|[=(,;:!&|?{}[+\-*%<>~^\n]|\b(?:return|typeof|case|in|of|delete|void|throw|new|else|yield|await))\s*$/u;
|
|
216
|
+
|
|
217
|
+
// Blank comments and the text of strings, templates and regular expressions, keeping every offset.
|
|
218
|
+
function maskTypeScript(code) {
|
|
219
|
+
const out = code.split('');
|
|
220
|
+
const blank = (from, to) => {
|
|
221
|
+
for (let at = from; at < to && at < out.length; at++) if (out[at] !== '\n') out[at] = ' ';
|
|
222
|
+
};
|
|
223
|
+
const templates = [];
|
|
224
|
+
let depth = 0;
|
|
225
|
+
let i = 0;
|
|
226
|
+
const template = () => {
|
|
227
|
+
const start = i;
|
|
228
|
+
while (i < code.length) {
|
|
229
|
+
if (code[i] === '\\') i += 2;
|
|
230
|
+
else if (code[i] === '`') {
|
|
231
|
+
blank(start, i);
|
|
232
|
+
i++;
|
|
233
|
+
return;
|
|
234
|
+
} else if (code[i] === '$' && code[i + 1] === '{') {
|
|
235
|
+
blank(start, i + 2);
|
|
236
|
+
i += 2;
|
|
237
|
+
templates.push(depth);
|
|
238
|
+
depth = 0;
|
|
239
|
+
return;
|
|
240
|
+
} else i++;
|
|
241
|
+
}
|
|
242
|
+
blank(start, i);
|
|
243
|
+
};
|
|
244
|
+
while (i < code.length) {
|
|
245
|
+
const c = code[i];
|
|
246
|
+
const next = code[i + 1];
|
|
247
|
+
if (c === '/' && next === '/') {
|
|
248
|
+
const start = i;
|
|
249
|
+
while (i < code.length && code[i] !== '\n') i++;
|
|
250
|
+
blank(start, i);
|
|
251
|
+
} else if (c === '/' && next === '*') {
|
|
252
|
+
const end = code.indexOf('*/', i + 2);
|
|
253
|
+
const stop = end === -1 ? code.length : end + 2;
|
|
254
|
+
blank(i, stop);
|
|
255
|
+
i = stop;
|
|
256
|
+
} else if (c === '"' || c === "'") {
|
|
257
|
+
const start = ++i;
|
|
258
|
+
while (i < code.length && code[i] !== c && code[i] !== '\n') i += code[i] === '\\' ? 2 : 1;
|
|
259
|
+
blank(start, i);
|
|
260
|
+
i++;
|
|
261
|
+
} else if (c === '`') {
|
|
262
|
+
i++;
|
|
263
|
+
template();
|
|
264
|
+
} else if (c === '/' && REGEX_FOLLOWS.test(out.slice(Math.max(0, i - 12), i).join(''))) {
|
|
265
|
+
const start = ++i;
|
|
266
|
+
let inClass = false;
|
|
267
|
+
while (i < code.length && code[i] !== '\n' && (inClass || code[i] !== '/')) {
|
|
268
|
+
if (code[i] === '[') inClass = true;
|
|
269
|
+
else if (code[i] === ']') inClass = false;
|
|
270
|
+
i += code[i] === '\\' ? 2 : 1;
|
|
271
|
+
}
|
|
272
|
+
blank(start, i);
|
|
273
|
+
i++;
|
|
274
|
+
} else if (c === '{') {
|
|
275
|
+
depth++;
|
|
276
|
+
i++;
|
|
277
|
+
} else if (c === '}') {
|
|
278
|
+
if (depth === 0 && templates.length > 0) {
|
|
279
|
+
depth = templates.pop();
|
|
280
|
+
i++;
|
|
281
|
+
template();
|
|
282
|
+
} else {
|
|
283
|
+
depth--;
|
|
284
|
+
i++;
|
|
285
|
+
}
|
|
286
|
+
} else i++;
|
|
287
|
+
}
|
|
288
|
+
return out.join('');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Blank Python comments and string text, keeping every offset.
|
|
292
|
+
function maskPython(code) {
|
|
293
|
+
const out = code.split('');
|
|
294
|
+
const blank = (from, to) => {
|
|
295
|
+
for (let at = from; at < to && at < out.length; at++) if (out[at] !== '\n') out[at] = ' ';
|
|
296
|
+
};
|
|
297
|
+
let i = 0;
|
|
298
|
+
while (i < code.length) {
|
|
299
|
+
const c = code[i];
|
|
300
|
+
if (c === '#') {
|
|
301
|
+
const start = i;
|
|
302
|
+
while (i < code.length && code[i] !== '\n') i++;
|
|
303
|
+
blank(start, i);
|
|
304
|
+
} else if (c === '"' || c === "'") {
|
|
305
|
+
const triple = code.startsWith(c.repeat(3), i);
|
|
306
|
+
const quote = triple ? c.repeat(3) : c;
|
|
307
|
+
const start = i + quote.length;
|
|
308
|
+
i = start;
|
|
309
|
+
while (i < code.length && !code.startsWith(quote, i) && (triple || code[i] !== '\n')) i += code[i] === '\\' ? 2 : 1;
|
|
310
|
+
blank(start, i);
|
|
311
|
+
i += quote.length;
|
|
312
|
+
} else i++;
|
|
313
|
+
}
|
|
314
|
+
return out.join('');
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// The argument list of the call whose opening parenthesis is at `open`, in masked source.
|
|
23
318
|
function callArguments(source, open) {
|
|
24
319
|
const args = [];
|
|
25
320
|
let depth = 0;
|
|
26
321
|
let start = open + 1;
|
|
27
|
-
let quote;
|
|
28
322
|
for (let i = open; i < source.length; i++) {
|
|
29
323
|
const c = source[i];
|
|
30
|
-
if (
|
|
31
|
-
if (c === '\\') i++;
|
|
32
|
-
else if (c === quote) quote = undefined;
|
|
33
|
-
continue;
|
|
34
|
-
}
|
|
35
|
-
if (c === '"' || c === "'" || c === '`') quote = c;
|
|
36
|
-
else if ('([{'.includes(c)) depth++;
|
|
324
|
+
if ('([{'.includes(c)) depth++;
|
|
37
325
|
else if (')]}'.includes(c)) {
|
|
38
326
|
depth--;
|
|
39
327
|
if (depth === 0) {
|
|
40
328
|
args.push(source.slice(start, i).trim());
|
|
41
|
-
return args.filter(arg => arg !== '');
|
|
329
|
+
return { args: args.filter(arg => arg !== ''), end: i };
|
|
42
330
|
}
|
|
43
331
|
} else if (c === ',' && depth === 1) {
|
|
44
332
|
args.push(source.slice(start, i).trim());
|
|
@@ -48,26 +336,88 @@ function callArguments(source, open) {
|
|
|
48
336
|
return undefined;
|
|
49
337
|
}
|
|
50
338
|
|
|
51
|
-
const
|
|
339
|
+
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
52
340
|
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
|
|
57
|
-
for (const
|
|
341
|
+
// The value of a number, a named constant or a product of those; undefined when it cannot be read.
|
|
342
|
+
function constantValue(text, declaration, depth = 0) {
|
|
343
|
+
if (depth > 3 || typeof text !== 'string' || text === '') return undefined;
|
|
344
|
+
let value = 1;
|
|
345
|
+
for (const factor of text.split('*').map(part => part.trim())) {
|
|
346
|
+
let number;
|
|
347
|
+
if (/^[0-9][0-9_]*(?:\.[0-9_]+)?(?:e[0-9]+)?$/iu.test(factor)) number = Number(factor.replaceAll('_', ''));
|
|
348
|
+
else if (/^[A-Za-z_$][\w$]*$/u.test(factor)) number = constantValue(declaration(factor), declaration, depth + 1);
|
|
349
|
+
if (number === undefined) return undefined;
|
|
350
|
+
value *= number;
|
|
351
|
+
}
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const WATCHDOG_CALLBACK = /\b(?:reject|rej|abort|kill|cancel|fail)\b|\bthrow\b/u;
|
|
356
|
+
|
|
357
|
+
function typeScriptPauseIssue(masked) {
|
|
358
|
+
const limitMs = MAX_PAUSE_SECONDS * 1000;
|
|
359
|
+
const declaration = name => new RegExp(`\\b(?:const|let|var)\\s+${escapeRegExp(name)}\\s*(?::[^=\\n]+)?=\\s*([^;,\\n]+)`, 'u').exec(masked)?.[1];
|
|
360
|
+
const value = text => constantValue(text, declaration);
|
|
361
|
+
const promises = [];
|
|
362
|
+
for (const match of masked.matchAll(/\bnew\s+Promise\b(?:<[^(\n]*>)?\s*\(/gu)) {
|
|
363
|
+
const call = callArguments(masked, match.index + match[0].length - 1);
|
|
364
|
+
if (call) promises.push([match.index, call.end]);
|
|
365
|
+
}
|
|
366
|
+
const inPromise = at => promises.some(([from, to]) => at > from && at < to);
|
|
367
|
+
// A helper that hands a parameter to a timer: every literal at its call sites is that timer's delay.
|
|
368
|
+
const helperDelay = (parameter, at) => {
|
|
369
|
+
const helpers = [...masked.matchAll(/\b(?:(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*(?:async\s*)?\(?\s*([A-Za-z_$][\w$]*)[^\n]*?=>|function\s+([A-Za-z_$][\w$]*)\s*(?:<[^(\n]*>)?\(\s*([A-Za-z_$][\w$]*))/gu)];
|
|
370
|
+
const helper = helpers.filter(found => found.index < at && (found[2] ?? found[4]) === parameter).at(-1);
|
|
371
|
+
const name = helper?.[1] ?? helper?.[3];
|
|
372
|
+
if (name === undefined) return undefined;
|
|
373
|
+
let longest;
|
|
374
|
+
for (const call of masked.matchAll(new RegExp(`(?<![\\w$.])${escapeRegExp(name)}\\s*\\(`, 'gu'))) {
|
|
375
|
+
if (call.index === helper.index + helper[0].indexOf(name)) continue;
|
|
376
|
+
const delay = value(callArguments(masked, call.index + call[0].length - 1)?.args[0]);
|
|
377
|
+
if (delay !== undefined) longest = Math.max(longest ?? 0, delay);
|
|
378
|
+
}
|
|
379
|
+
return longest;
|
|
380
|
+
};
|
|
381
|
+
const aliases = [...masked.matchAll(/\bsetTimeout\s*:\s*([A-Za-z_$][\w$]*)/gu)].map(found => found[1]);
|
|
382
|
+
const timers = ['setTimeout', 'setInterval', ...aliases].map(escapeRegExp).join('|');
|
|
383
|
+
for (const match of masked.matchAll(new RegExp(`(?<![\\w$])(${timers})\\s*\\(`, 'gu'))) {
|
|
384
|
+
const call = callArguments(masked, match.index + match[0].length - 1);
|
|
385
|
+
if (call === undefined) continue;
|
|
386
|
+
const [first, second] = call.args;
|
|
58
387
|
// setTimeout(callback, ms) from the global timers, setTimeout(ms, value) from timers/promises.
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const args = callArguments(
|
|
68
|
-
|
|
69
|
-
if (
|
|
70
|
-
|
|
388
|
+
const leading = value(first);
|
|
389
|
+
const promised = leading !== undefined || (call.args.length === 1 && /^[A-Za-z_$][\w$]*$/u.test(first ?? '') && aliases.includes(match[1]));
|
|
390
|
+
if (!promised && !(inPromise(match.index) && !WATCHDOG_CALLBACK.test(first ?? ''))) continue;
|
|
391
|
+
const expression = promised ? first : second;
|
|
392
|
+
const delay = value(expression) ?? (/^[A-Za-z_$][\w$]*$/u.test(expression ?? '') ? helperDelay(expression, match.index) : undefined);
|
|
393
|
+
if (delay !== undefined && delay > limitMs) return `a ${delay} ms ${match[1] === 'setInterval' ? 'setInterval' : 'setTimeout'}`;
|
|
394
|
+
}
|
|
395
|
+
for (const match of masked.matchAll(/\bAtomics\.wait\s*\(/gu)) {
|
|
396
|
+
const args = callArguments(masked, match.index + match[0].length - 1)?.args;
|
|
397
|
+
if (args === undefined) continue;
|
|
398
|
+
if (args.length < 4) return 'Atomics.wait without a timeout';
|
|
399
|
+
const delay = value(args[3]);
|
|
400
|
+
if (delay !== undefined && delay > limitMs) return `a ${delay} ms Atomics.wait`;
|
|
71
401
|
}
|
|
72
402
|
return undefined;
|
|
73
403
|
}
|
|
404
|
+
|
|
405
|
+
function pythonPauseIssue(masked) {
|
|
406
|
+
const declaration = name => new RegExp(`^[ \\t]*${escapeRegExp(name)}\\s*=\\s*([^\\n#]+)`, 'mu').exec(masked)?.[1]?.trim();
|
|
407
|
+
const imported = /^[ \t]*from[ \t]+(?:time|asyncio)[ \t]+import\b[^\n]*\bsleep\b/mu.test(masked);
|
|
408
|
+
for (const match of masked.matchAll(/(?<![\w.])(?:(?:time|asyncio)\.)?sleep\s*\(/gu)) {
|
|
409
|
+
if (!match[0].includes('.') && !imported) continue;
|
|
410
|
+
const seconds = constantValue(callArguments(masked, match.index + match[0].length - 1)?.args[0], declaration);
|
|
411
|
+
if (seconds !== undefined && seconds > MAX_PAUSE_SECONDS) return `a ${seconds} s sleep`;
|
|
412
|
+
}
|
|
413
|
+
return undefined;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* A reason when a run_code program really waits longer than allowed.
|
|
418
|
+
* @param code - program source.
|
|
419
|
+
* @param language - the active PTC runtime's language.
|
|
420
|
+
*/
|
|
421
|
+
export function programPauseIssue(code, language = 'typescript') {
|
|
422
|
+
return language === 'python' ? pythonPauseIssue(maskPython(code)) : typeScriptPauseIssue(maskTypeScript(code));
|
|
423
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Local metadata search only: no model calls, filesystem probing or skill-body reads.
|
|
2
|
+
const indexed = new WeakMap();
|
|
3
|
+
export const DIRECTORY_TOOL = 'deep_ptc_tools';
|
|
4
|
+
export const RESET_COMMAND = 'deep-ptc-reset-tools';
|
|
5
|
+
export const STATE_EVENT = 'plugin:dsh-deep-ptc-mode/tool-state';
|
|
6
|
+
export const STATE_KEY = 'deepPtcTools';
|
|
7
|
+
export function summary(definition) {
|
|
8
|
+
let row = indexed.get(definition);
|
|
9
|
+
if (!row) {
|
|
10
|
+
const name = String(definition.name);
|
|
11
|
+
const description = String(definition.description ?? '').slice(0, 240);
|
|
12
|
+
row = { name, description, text: `${name} ${description}`.toLowerCase() };
|
|
13
|
+
indexed.set(definition, row);
|
|
14
|
+
}
|
|
15
|
+
return row;
|
|
16
|
+
}
|
|
17
|
+
export function searchCatalog(definitions, query = '', offset = 0, limit = 6) {
|
|
18
|
+
const terms = String(query).slice(0, 512).toLowerCase().trim().split(/[\s,,]+/u).filter(Boolean).slice(0, 12);
|
|
19
|
+
const ranked = definitions.map(def => {
|
|
20
|
+
const row = summary(def);
|
|
21
|
+
const score = terms.reduce((sum, word) => sum + (row.name.toLowerCase().includes(word) ? 8 : row.text.includes(word) ? 1 : 0), 0);
|
|
22
|
+
return { row, score };
|
|
23
|
+
}).filter(entry => terms.length === 0 || entry.score > 0)
|
|
24
|
+
.sort((a, b) => b.score - a.score || (a.row.name < b.row.name ? -1 : a.row.name > b.row.name ? 1 : 0));
|
|
25
|
+
const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
|
|
26
|
+
const count = Math.max(1, Math.min(8, Number.isSafeInteger(limit) ? limit : 6));
|
|
27
|
+
return { total: ranked.length, results: ranked.slice(start, start + count).map(({ row }) => ({ name: row.name, description: row.description })),
|
|
28
|
+
nextOffset: start + count < ranked.length ? start + count : null };
|
|
29
|
+
}
|
|
30
|
+
export function toolSchema(def) {
|
|
31
|
+
return { name: def.name, description: def.description ?? '', parameters: def.parameters, output: def.output?.schema ?? {} };
|
|
32
|
+
}
|
|
33
|
+
export function blankState() { return { v: 1, epoch: 0, blocked: [], report: null }; }
|
|
34
|
+
export function parseState(value) {
|
|
35
|
+
if (!value || value.v !== 1 || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !Array.isArray(value.blocked)) throw new Error('Invalid Deep PTC tool state');
|
|
36
|
+
for (const row of value.blocked) if (!row || typeof row.name !== 'string' || row.name.length > 256 || typeof row.provider !== 'string' || typeof row.kind !== 'string') throw new Error('Invalid blocked tool');
|
|
37
|
+
return { v: 1, epoch: value.epoch, blocked: value.blocked.map(row => ({ name: row.name, provider: row.provider, kind: row.kind })), report: value.report ?? null };
|
|
38
|
+
}
|
|
39
|
+
export function foldToolState(state, event) {
|
|
40
|
+
if (event.type === STATE_EVENT && event.ignorable === true) {
|
|
41
|
+
try { return parseState(event.data); } catch { return state; }
|
|
42
|
+
}
|
|
43
|
+
if (event.type === 'turn/end' && state.blocked.length) return { ...state, report: { turn: event.data.turn, tools: state.blocked } };
|
|
44
|
+
return state;
|
|
45
|
+
}
|
|
@@ -1,7 +1,90 @@
|
|
|
1
1
|
import z from '@deepseek-ai/schemastery';
|
|
2
|
-
import { installToolCompatibility } from './tool-policy.mjs';
|
|
2
|
+
import { failOpen, installToolCompatibility, officialToolSource } from './tool-policy.mjs';
|
|
3
|
+
import { importHost } from './host.mjs';
|
|
4
|
+
import { toolDirectory } from './official-names.mjs';
|
|
5
|
+
import { DIRECTORY_TOOL, RESET_COMMAND, STATE_EVENT, STATE_KEY, blankState, parseState, foldToolState, searchCatalog, toolSchema } from './tool-catalog.mjs';
|
|
3
6
|
|
|
4
7
|
export const name = 'deep-ptc-tool-compatibility';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
// Discovery and quarantine are an optional layer: a failed preset row rejects the whole preset mount,
|
|
9
|
+
// and a row waiting on a service is reported as unusable. So this row needs nothing itself and runs the
|
|
10
|
+
// layer in a child fiber; if that fails or never starts, the official PTC tools simply stay as they are.
|
|
11
|
+
export const inject = [];
|
|
12
|
+
const REQUIRED = ['tools', 'systemPrompt', 'commands', 'sessionProjections'];
|
|
13
|
+
export const Config = z.object({ enabled: z.boolean().default(true), preferences: z.any().default([]),
|
|
14
|
+
compact: z.boolean().default(true), officialModules: z.any().default([]), sdkProvider: z.string().default('@deepseek-ai/dsh-tool-executor-ptc'),
|
|
15
|
+
skillProvider: z.string().default('@deepseek-ai/dsh-tool-skill') });
|
|
16
|
+
|
|
17
|
+
export function apply(ctx, config) {
|
|
18
|
+
if (!config.enabled) return;
|
|
19
|
+
const missing = REQUIRED.filter(service => ctx.get(service) === undefined);
|
|
20
|
+
if (missing.length > 0) ctx.logger.info('Deep PTC: tool discovery and quarantine wait for %s', missing.join(', '));
|
|
21
|
+
ctx.plugin({ name: 'deep-ptc-tool-compatibility-layer', inject: REQUIRED, apply: child => install(child, config) }).await()
|
|
22
|
+
.catch(error => ctx.logger.warn('Deep PTC: tool discovery and quarantine are off (%s); official tools are unaffected', error.message));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function install(ctx, config) {
|
|
26
|
+
const { appendPluginRecord } = await importHost('@deepseek-ai/dsh-session');
|
|
27
|
+
if (typeof appendPluginRecord !== 'function') throw new Error('the installed session module has no appendPluginRecord');
|
|
28
|
+
const schema = { parse: parseState };
|
|
29
|
+
const projection = await ctx.sessionProjections.register({ key: STATE_KEY, stateVersion: 1,
|
|
30
|
+
stateSchema: schema, init: blankState, apply: foldToolState,
|
|
31
|
+
wire: { viewSchema: schema, view: state => state, summary: false } });
|
|
32
|
+
ctx.effect(() => () => projection.dispose());
|
|
33
|
+
const directory = toolDirectory(() => ctx.get('loader'), { modules: config.officialModules, base: ctx.baseUrl });
|
|
34
|
+
const state = installToolCompatibility(ctx, { preferences: config.preferences, directory, storage: {
|
|
35
|
+
read: session => projection.stateOf(session),
|
|
36
|
+
write: (session, value) => appendPluginRecord(session, STATE_EVENT, value),
|
|
37
|
+
} });
|
|
38
|
+
ctx.commands.register({ name: RESET_COMMAND, description: '重载所有工具状态 / Reload all tool states',
|
|
39
|
+
handler: ({ agent }) => {
|
|
40
|
+
const count = state.reset(agent);
|
|
41
|
+
return { kind: 'success', text: `已重载本对话全部工具状态,清除 ${count} 个故障标记。正在运行的任务继续执行。 / All tool states reloaded for this conversation; ${count} quarantine marks cleared. Running jobs continue.` };
|
|
42
|
+
} });
|
|
43
|
+
ctx.tools.register({ name: DIRECTORY_TOOL,
|
|
44
|
+
description: 'Find tools or skills by function without loading all schemas. search returns compact tool summaries; load reveals complete schemas for selected tool names; skills returns summaries to load with the official skill tool. Never executes task tools or reads skill bodies.',
|
|
45
|
+
parameters: { type: 'object', additionalProperties: false, properties: {
|
|
46
|
+
action: { type: 'string', enum: ['search', 'load', 'skills'] }, query: { type: 'string' },
|
|
47
|
+
names: { type: 'array', items: { type: 'string' } }, offset: { type: 'integer' }, limit: { type: 'integer' },
|
|
48
|
+
}, required: ['action'] },
|
|
49
|
+
output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
50
|
+
async execute(args, exec) {
|
|
51
|
+
if (args.action === 'load') return state.load(exec.agent, args.names, exec.toolSet);
|
|
52
|
+
if (args.action === 'search') return state.search(exec.agent, args, exec.toolSet);
|
|
53
|
+
if (args.action !== 'skills') throw new Error('Unknown directory action');
|
|
54
|
+
const skills = ctx.get('skills');
|
|
55
|
+
const loader = ctx.tools.definitions(exec.agent, exec.toolSet).find(def => officialToolSource(def) === config.skillProvider || directory.namesOf(config.skillProvider).has(def.name));
|
|
56
|
+
if (typeof skills?.list !== 'function' || !loader) return { available: false, results: [], note: 'The official skill loader is unavailable.' };
|
|
57
|
+
const { isModelInvocable } = await importHost('@deepseek-ai/dsh-skill').catch(() => ({}));
|
|
58
|
+
if (typeof isModelInvocable !== 'function') return { available: false, results: [], note: 'The official skill loader is unavailable.' };
|
|
59
|
+
const workingDirectory = ctx.get('workingDirectory');
|
|
60
|
+
const lookup = { scope: exec.agent, signal: exec.signal, cwd: workingDirectory ? await workingDirectory.ensure(exec.agent, exec.signal) : undefined };
|
|
61
|
+
const entries = (await skills.list(lookup)).filter(isModelInvocable).map(row => ({ name: row.name, description: row.description ?? '' }));
|
|
62
|
+
return { available: true, ...searchCatalog(entries, args.query, args.offset, args.limit), loadWith: loader.name,
|
|
63
|
+
note: 'Load the exact selected name through the official skill tool, then follow its instructions. Reuse instructions already in context.' };
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
// Only reduce the installed official renderer's untouched generated SDK section.
|
|
67
|
+
let renderer;
|
|
68
|
+
const sdkCache = new WeakMap();
|
|
69
|
+
const same = (left, right) => left?.length === right.length && left.every((def, index) => def === right[index]);
|
|
70
|
+
try { renderer = await importHost(config.sdkProvider); } catch { ctx.logger.warn('Deep PTC: SDK renderer unavailable; retaining the complete host SDK.'); }
|
|
71
|
+
const compacted = failOpen(ctx, 'tool catalog', (assembly, context) => {
|
|
72
|
+
const runtime = ctx.get('ptcRuntime');
|
|
73
|
+
const render = runtime?.language === 'python' ? renderer.renderToolsSdkPy : runtime?.language === 'typescript' || runtime?.language === 'javascript' ? renderer.renderToolsSdk : undefined;
|
|
74
|
+
if (!render || !context.scope) return assembly;
|
|
75
|
+
const all = ctx.tools.definitions(context.scope, context.toolSet);
|
|
76
|
+
let cached = sdkCache.get(context.scope);
|
|
77
|
+
if (!cached || cached.render !== render || cached.format !== runtime.programFormat || !same(cached.all, all)) {
|
|
78
|
+
cached = { all, render, format: runtime.programFormat, original: render(all.map(toolSchema), runtime.programFormat) };
|
|
79
|
+
sdkCache.set(context.scope, cached);
|
|
80
|
+
}
|
|
81
|
+
const selected = state.sdkDefinitions(context.scope, context.toolSet, config.compact);
|
|
82
|
+
if (selected.length === all.length) return assembly;
|
|
83
|
+
if (!same(cached.selected, selected)) { cached.selected = selected; cached.text = render(selected.map(toolSchema), runtime.programFormat); }
|
|
84
|
+
return { ...assembly, sections: assembly.sections.map(section => section.name === 'tools:sdk' && section.text === cached.original ? { ...section, text: cached.text } : section) };
|
|
85
|
+
});
|
|
86
|
+
if (renderer?.renderToolsSdk) ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
87
|
+
const assembly = await next();
|
|
88
|
+
return compacted(assembly, context) ?? assembly;
|
|
89
|
+
});
|
|
90
|
+
}
|