dsh-deep-ptc-mode 1.7.2 → 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.
@@ -1,44 +1,332 @@
1
- // Static checks for waiting written into commands or run_code programs. Short literal pauses (readiness
2
- // loops, debounce) stay legal; anything longer, or a delay whose length cannot be read, is reported.
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
- // Longest literal pause in a bash/zsh/PowerShell/cmd command, in seconds; 0 when there is none.
8
- export function shellPauseSeconds(command) {
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 take = seconds => { if (!Number.isNaN(seconds)) longest = Math.max(longest, seconds); };
11
- for (const m of command.matchAll(/(?:^|[\s;&|({`])sleep\s+(infinity|[0-9]*\.?[0-9]+)([smhd]?)(?=$|[\s;&|)}`])/gu))
12
- take(m[1] === 'infinity' ? Infinity : Number(m[1]) * UNIT_SECONDS[m[2]]);
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
- // Read the argument list of the call whose opening parenthesis is at `open`.
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 (quote) {
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 numeric = text => /^[0-9][0-9_]*(?:\.[0-9_]+)?(?:e[0-9]+)?$/iu.test(text) ? Number(text.replaceAll('_', '')) : undefined;
339
+ const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
52
340
 
53
- // A reason when a run_code program sleeps longer than allowed, polls on a timer, or blocks the thread.
54
- export function programPauseIssue(code) {
55
- if (/\bsetInterval\s*\(/u.test(code)) return 'setInterval polling';
56
- if (/\bAtomics\.wait\s*\(/u.test(code)) return 'Atomics.wait';
57
- for (const m of code.matchAll(/\bsetTimeout\s*\(/gu)) {
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 args = callArguments(code, m.index + m[0].length - 1);
60
- if (args === undefined) return 'an unreadable setTimeout call';
61
- const delay = numeric(args[0] ?? '') ?? (args.length >= 2 ? numeric(args[1]) : 0);
62
- if (delay === undefined) return 'a setTimeout delay that is not a numeric literal';
63
- if (delay > MAX_PAUSE_SECONDS * 1000) return `a ${delay} ms setTimeout`;
64
- }
65
- for (const m of code.matchAll(/\b(?:time\.|asyncio\.)?sleep\s*\(/gu)) {
66
- if (!/\b(?:time|asyncio)\.sleep/u.test(m[0]) && !/\bimport\b[^\n]*\bsleep\b/u.test(code)) continue;
67
- const args = callArguments(code, m.index + m[0].length - 1);
68
- const seconds = args?.length ? numeric(args[0]) : undefined;
69
- if (seconds === undefined) return 'a sleep whose duration is not a numeric literal';
70
- if (seconds > MAX_PAUSE_SECONDS) return `a ${seconds} s sleep`;
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
+ }
@@ -28,7 +28,7 @@ export function searchCatalog(definitions, query = '', offset = 0, limit = 6) {
28
28
  nextOffset: start + count < ranked.length ? start + count : null };
29
29
  }
30
30
  export function toolSchema(def) {
31
- return { name: def.name, description: def.description ?? '', parameters: def.parameters, output: def.output.schema };
31
+ return { name: def.name, description: def.description ?? '', parameters: def.parameters, output: def.output?.schema ?? {} };
32
32
  }
33
33
  export function blankState() { return { v: 1, epoch: 0, blocked: [], report: null }; }
34
34
  export function parseState(value) {
@@ -1,23 +1,37 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
- import { installToolCompatibility, officialToolSource } from './tool-policy.mjs';
2
+ import { failOpen, installToolCompatibility, officialToolSource } from './tool-policy.mjs';
3
3
  import { importHost } from './host.mjs';
4
+ import { toolDirectory } from './official-names.mjs';
4
5
  import { DIRECTORY_TOOL, RESET_COMMAND, STATE_EVENT, STATE_KEY, blankState, parseState, foldToolState, searchCatalog, toolSchema } from './tool-catalog.mjs';
5
6
 
6
7
  export const name = 'deep-ptc-tool-compatibility';
7
- export const inject = ['tools', 'systemPrompt', 'commands', 'sessionProjections'];
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'];
8
13
  export const Config = z.object({ enabled: z.boolean().default(true), preferences: z.any().default([]),
9
- compact: z.boolean().default(true), sdkProvider: z.string().default('@deepseek-ai/dsh-tool-executor-ptc'),
14
+ compact: z.boolean().default(true), officialModules: z.any().default([]), sdkProvider: z.string().default('@deepseek-ai/dsh-tool-executor-ptc'),
10
15
  skillProvider: z.string().default('@deepseek-ai/dsh-tool-skill') });
11
16
 
12
- export async function apply(ctx, config) {
17
+ export function apply(ctx, config) {
13
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) {
14
26
  const { appendPluginRecord } = await importHost('@deepseek-ai/dsh-session');
27
+ if (typeof appendPluginRecord !== 'function') throw new Error('the installed session module has no appendPluginRecord');
15
28
  const schema = { parse: parseState };
16
29
  const projection = await ctx.sessionProjections.register({ key: STATE_KEY, stateVersion: 1,
17
30
  stateSchema: schema, init: blankState, apply: foldToolState,
18
31
  wire: { viewSchema: schema, view: state => state, summary: false } });
19
32
  ctx.effect(() => () => projection.dispose());
20
- const state = installToolCompatibility(ctx, { preferences: config.preferences, storage: {
33
+ const directory = toolDirectory(() => ctx.get('loader'), { modules: config.officialModules, base: ctx.baseUrl });
34
+ const state = installToolCompatibility(ctx, { preferences: config.preferences, directory, storage: {
21
35
  read: session => projection.stateOf(session),
22
36
  write: (session, value) => appendPluginRecord(session, STATE_EVENT, value),
23
37
  } });
@@ -38,11 +52,12 @@ export async function apply(ctx, config) {
38
52
  if (args.action === 'search') return state.search(exec.agent, args, exec.toolSet);
39
53
  if (args.action !== 'skills') throw new Error('Unknown directory action');
40
54
  const skills = ctx.get('skills');
41
- const loader = ctx.tools.definitions(exec.agent, exec.toolSet).find(def => officialToolSource(def) === config.skillProvider);
55
+ const loader = ctx.tools.definitions(exec.agent, exec.toolSet).find(def => officialToolSource(def) === config.skillProvider || directory.namesOf(config.skillProvider).has(def.name));
42
56
  if (typeof skills?.list !== 'function' || !loader) return { available: false, results: [], note: 'The official skill loader is unavailable.' };
43
- const { isModelInvocable } = await importHost('@deepseek-ai/dsh-skill');
44
- const directory = ctx.get('workingDirectory');
45
- const lookup = { scope: exec.agent, signal: exec.signal, cwd: directory ? await directory.ensure(exec.agent, exec.signal) : undefined };
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 };
46
61
  const entries = (await skills.list(lookup)).filter(isModelInvocable).map(row => ({ name: row.name, description: row.description ?? '' }));
47
62
  return { available: true, ...searchCatalog(entries, args.query, args.offset, args.limit), loadWith: loader.name,
48
63
  note: 'Load the exact selected name through the official skill tool, then follow its instructions. Reuse instructions already in context.' };
@@ -53,8 +68,7 @@ export async function apply(ctx, config) {
53
68
  const sdkCache = new WeakMap();
54
69
  const same = (left, right) => left?.length === right.length && left.every((def, index) => def === right[index]);
55
70
  try { renderer = await importHost(config.sdkProvider); } catch { ctx.logger.warn('Deep PTC: SDK renderer unavailable; retaining the complete host SDK.'); }
56
- if (renderer?.renderToolsSdk) ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
57
- const assembly = await next();
71
+ const compacted = failOpen(ctx, 'tool catalog', (assembly, context) => {
58
72
  const runtime = ctx.get('ptcRuntime');
59
73
  const render = runtime?.language === 'python' ? renderer.renderToolsSdkPy : runtime?.language === 'typescript' || runtime?.language === 'javascript' ? renderer.renderToolsSdk : undefined;
60
74
  if (!render || !context.scope) return assembly;
@@ -69,4 +83,8 @@ export async function apply(ctx, config) {
69
83
  if (!same(cached.selected, selected)) { cached.selected = selected; cached.text = render(selected.map(toolSchema), runtime.programFormat); }
70
84
  return { ...assembly, sections: assembly.sections.map(section => section.name === 'tools:sdk' && section.text === cached.original ? { ...section, text: cached.text } : section) };
71
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
+ });
72
90
  }