dsh-deep-ptc-mode 1.8.7 → 1.8.8

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.
@@ -11,7 +11,12 @@ export const OFFICIAL_SCOPE = '@deepseek-ai/';
11
11
  const OWN_PACKAGE = 'dsh-deep-ptc-mode';
12
12
  const REFRESH_MS = 1000;
13
13
  const DECLARED = /(?:defineTool|tools\.register)\(\{\s*name:\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z_$][\w$]*))/gu;
14
+ // `tools.register(helper("name", …))` and the `const helper = (name, …) => defineTool({ name: name` it calls.
15
+ const FACTORY_CALL = /tools\.register\(\s*([A-Za-z_$][\w$]*)\(\s*["']([^"']+)["']/gu;
16
+ const IDENTIFIER = String.raw`([A-Za-z_$][\w$]*)`;
14
17
  const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
18
+ const factoryDefinition = helper => new RegExp(
19
+ String.raw`(?:const|let|var)\s+${escapeRegExp(helper)}\s*=\s*\(\s*${IDENTIFIER}[^)]*\)\s*=>\s*defineTool\(\{\s*name:\s*${IDENTIFIER}`, 'u');
15
20
 
16
21
  function identifierValue(source, identifier) {
17
22
  const id = escapeRegExp(identifier);
@@ -27,10 +32,9 @@ export function toolNamesInSource(source) {
27
32
  if (name !== undefined) names.add(name);
28
33
  }
29
34
  // A local factory may pass its first argument directly to defineTool's name.
30
- for(const call of source.matchAll(/tools\.register\(\s*([A-Za-z_$][\w$]*)\(\s*["']([^"']+)["']/gu)){
31
- const helper=escapeRegExp(call[1]);
32
- const factory=new RegExp('(?:const|let|var)\\s+'+helper+'\\s*=\\s*\\(\\s*([A-Za-z_$][\\w$]*)[^)]*\\)\\s*=>\\s*defineTool\\(\\{\\s*name:\\s*([A-Za-z_$][\\w$]*)','u').exec(source);
33
- if(factory && factory[1]===factory[2])names.add(call[2]);
35
+ for (const [, helper, name] of source.matchAll(FACTORY_CALL)) {
36
+ const [, parameter, nameArgument] = factoryDefinition(helper).exec(source) ?? [];
37
+ if (parameter !== undefined && parameter === nameArgument) names.add(name);
34
38
  }
35
39
  return names;
36
40
  }
@@ -49,8 +53,14 @@ function installedSource(moduleName, base) {
49
53
  const url = resolveHost(moduleName);
50
54
  if (url !== undefined) file = fileURLToPath(url);
51
55
  }
52
- const stat=statSync(file); const stamp=`${file}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`;
53
- let row=sourceCache.get(file); if(row?.stamp!==stamp){row={stamp,text:readFileSync(file,'utf8')};sourceCache.set(file,row);}
56
+ if (file === undefined) throw new Error(`cannot resolve ${moduleName}`);
57
+ const stat = statSync(file);
58
+ const stamp = `${file}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`;
59
+ let row = sourceCache.get(file);
60
+ if (row?.stamp !== stamp) {
61
+ row = { stamp, text: readFileSync(file, 'utf8') };
62
+ sourceCache.set(file, row);
63
+ }
54
64
  return row;
55
65
  }
56
66
 
@@ -64,15 +74,21 @@ function installedSource(moduleName, base) {
64
74
  export function toolDirectory(getLoader, { modules = [], readSource = installedSource, base, refreshMs = REFRESH_MS } = {}) {
65
75
  const scanned = new Map();
66
76
  const namesIn = (moduleName, rowBase) => {
67
- const key=moduleName+'\0'+String(rowBase ?? '');
77
+ const key = `${moduleName}\0${rowBase ?? ''}`;
68
78
  try {
69
- const read=readSource(moduleName,rowBase);
70
- const text=typeof read==='string'?read:read.text;
71
- const stamp=typeof read==='string'?read:read.stamp;
72
- let cached=scanned.get(key);
73
- if(!cached || cached.stamp!==stamp){cached={stamp,names:toolNamesInSource(text)};scanned.set(key,cached);}
79
+ // A reader returns `{ stamp, text }`, or plain text that is its own stamp.
80
+ const read = readSource(moduleName, rowBase);
81
+ const { stamp, text } = typeof read === 'string' ? { stamp: read, text: read } : read;
82
+ let cached = scanned.get(key);
83
+ if (cached === undefined || cached.stamp !== stamp) {
84
+ cached = { stamp, names: toolNamesInSource(text) };
85
+ scanned.set(key, cached);
86
+ }
74
87
  return cached.names;
75
- } catch { scanned.delete(key);return new Set(); }
88
+ } catch {
89
+ scanned.delete(key);
90
+ return new Set();
91
+ }
76
92
  };
77
93
  let view;
78
94
  let viewedAt = -Infinity;
@@ -109,7 +125,11 @@ export function toolDirectory(getLoader, { modules = [], readSource = installedS
109
125
  return {
110
126
  isOfficial: name => refresh().official.has(name),
111
127
  providerOf: name => refresh().providers.get(name),
112
- isExternal: name => { const view=refresh(); const provider=view.providers.get(name); return !!provider && !view.official.has(name) && !provider.startsWith(OFFICIAL_SCOPE); },
128
+ isExternal: name => {
129
+ const { official, providers } = refresh();
130
+ const provider = providers.get(name);
131
+ return !!provider && !official.has(name) && !provider.startsWith(OFFICIAL_SCOPE);
132
+ },
113
133
  namesOf: moduleName => namesIn(moduleName, base),
114
134
  };
115
135
  }
@@ -1,19 +1,9 @@
1
1
  // Deep PTC owns a session-scoped preset identity compatibility layer.
2
2
  //
3
- // Two attempts for a session's identity:
4
- // 1. native deep-ptc -- the plugin may pass if it does not limit preset names;
5
- // 2. base ptc -- a plugin that limits preset names to the built-in ids passes here.
6
- //
7
- // Each external plugin is asked once, so the layer is chosen before returning: inspect
8
- // the calling plugin's own package. A package that does not gate on preset ids, or
9
- // that declares deep-ptc, gets the native id. A package that gates on preset ids but
10
- // does not declare deep-ptc gets the base id immediately. The second layer is the one
11
- // that is guaranteed to pass for a plugin whose allowlist includes ptc (dsh-ops maps
12
- // minimal/standard/ptc/cordis). A plugin that excludes ptc can pass neither.
13
- //
14
- // Why not retry at runtime: composedPreset() returns one string and the host gives no
15
- // rejection callback; a plugin whose gate misses simply stays inert. So the two
16
- // attempts are resolved per caller before the value is returned.
3
+ // Third-party callers share two layers. Prefer the real deep-ptc ID. If the caller's
4
+ // preset gate requires a base preset, return its compatibility ID, normally ptc.
5
+ // composedPreset() returns once and cannot observe the caller's check, so choose the
6
+ // layer from the caller's package or configured support before returning the ID.
17
7
  //
18
8
  // Host internals that must keep the exact identity (subagent child headers, scheduled
19
9
  // session creation, the registry itself) are recognised from the immediate frames.
@@ -25,18 +15,29 @@ export const name = 'deep-ptc-preset-compat';
25
15
  export const inject = ['agentPresets'];
26
16
 
27
17
  const PATCH_MARK = Symbol.for('dsh-deep-ptc-mode.preset-compat.patch');
28
- const HOST_CALLERS = /(?:dsh-subagent|dsh-tool-schedule|dsh-agent-preset-registry)/u;
18
+ // Host packages that must see the exact identity, matched as a path segment under the official scope
19
+ // so a third-party package that merely has a similar name is still treated as a plugin.
20
+ const HOST_CALLERS = /[\\/]@deepseek-ai[\\/](?:dsh-subagent|dsh-tool-schedule|dsh-agent-preset-registry)[^\\/]*[\\/]/u;
29
21
  const SELF = 'preset-compat.mjs';
30
22
  const CODE_EXTENSIONS = ['.mjs', '.cjs', '.js', '.mts', '.cts', '.ts'];
31
- const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'docs', 'test', 'tests']);
23
+ // Build output is scanned: a plugin published as dist/ only has its gate nowhere else.
24
+ const SKIP_DIRS = new Set(['node_modules', 'docs', 'test', 'tests', '__tests__', 'examples', 'coverage']);
32
25
  const MAX_FILES = 800;
33
26
  const MAX_FILE_BYTES = 1024 * 1024;
34
27
  const MAX_TOTAL_BYTES = 8 * 1024 * 1024;
28
+ // A cached caller is trusted this long before its package manifest is looked at again.
29
+ const FRESH_MS = 5000;
35
30
 
31
+ // Both caches are stamped with the package manifest's modification time, so a plugin updated in place
32
+ // is probed again, and both are dropped when the layer is disposed.
36
33
  const packageCache = new Map();
37
34
  const callerCache = new Map();
38
35
  const logged = new Set();
39
36
 
37
+ function manifestStamp(root) {
38
+ try { return statSync(join(root, 'package.json')).mtimeMs; } catch { return -1; }
39
+ }
40
+
40
41
  // Diagnostics go to the host logger of the plugin that installed the layer.
41
42
  let sink = () => {};
42
43
  function log(line) {
@@ -99,72 +100,115 @@ export function packageOf(file) {
99
100
  return undefined;
100
101
  }
101
102
 
102
- const GATE_MARKERS = [
103
- 'MODE_PRESET',
104
- "=== 'ptc'", '=== "ptc"', "!== 'ptc'", '!== "ptc"',
105
- "=== 'standard'", '=== "standard"', "=== 'cordis'", '=== "cordis"',
106
- "=== 'minimal'", '=== "minimal"',
107
- "case 'ptc'", 'case "ptc"',
108
- ".includes('ptc')", '.includes("ptc")',
109
- ];
110
-
111
103
  const CREATIVE_PRESET_ID = 'cordis';
104
+ const BASE_PRESET_IDS = ['ptc', 'standard', 'minimal', CREATIVE_PRESET_ID];
112
105
  const KNOWN_PRESET_IDS = ['deep-ptc', CREATIVE_PRESET_ID, 'ptc', 'standard', 'minimal'];
106
+ const QUOTES = ["'", '"', '`'];
107
+ const COMMENT_OR_STRING = /\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`/gu;
108
+ const NAME = String.raw`[A-Za-z_$][\w$]*`;
109
+ const PROPERTY_CHAIN = String.raw`(?:${NAME}\s*(?:\?\.|\.)\s*)*`;
110
+ const PRESET_CALL = String.raw`${PROPERTY_CHAIN}composedPreset\s*(?:\?\.\s*)?\([^()]*\)`;
111
+ const PRESET_ASSIGNMENT = new RegExp(String.raw`\b(?:const|let|var)\s+(${NAME})\s*=\s*${PRESET_CALL}`, 'gu');
112
+ const PRESET_NAME = String.raw`[\w$]*preset(?:id|name)?`;
113
+
114
+ // Keep code and exact preset literals. Other strings stay as empty literals so they cannot form a gate.
115
+ function presetSource(source, ids) {
116
+ return source.replace(COMMENT_OR_STRING, token => {
117
+ if (token[0] === '/') return ' ';
118
+ return ids.has(token.slice(1, -1)) ? token : '""';
119
+ });
120
+ }
121
+
122
+ function quotes(text, id) {
123
+ return QUOTES.some(quote => text.includes(quote + id + quote));
124
+ }
125
+
126
+ const BASE_ID = `(?:${QUOTES.flatMap(quote => BASE_PRESET_IDS.map(id => quote + id + quote)).join('|')})`;
127
+ const LIST_ITEM = String.raw`(?:${NAME}|"[^"]*"|'[^']*'|\x60[^\x60]*\x60)`;
128
+ const BUILTIN_LIST = String.raw`\[\s*(?:${LIST_ITEM}\s*,\s*)*${BASE_ID}\s*(?:,\s*${LIST_ITEM}\s*)*,?\s*\]`;
129
+
130
+ function presetGate(aliases = []) {
131
+ const names = [PRESET_NAME, ...aliases.map(name => name.replaceAll('$', '\\$'))].join('|');
132
+ const namedValue = String.raw`${PROPERTY_CHAIN}(?:${names})(?![\w$]|\s*(?:[.\[(]|\?\.))`;
133
+ const reference = String.raw`(?<![\w$])(?:${PRESET_CALL}|${namedValue})`;
134
+ return new RegExp([
135
+ String.raw`${reference}\s*[!=]==?\s*${BASE_ID}`,
136
+ String.raw`${BASE_ID}\s*[!=]==?\s*${reference}`,
137
+ String.raw`\bswitch\s*\(\s*${reference}\s*\)\s*\{[^{}]*\bcase\s+${BASE_ID}`,
138
+ String.raw`${BUILTIN_LIST}\s*\)?\s*\.\s*(?:includes|has)\(\s*${reference}`,
139
+ String.raw`\b${PROPERTY_CHAIN}[\w$]*preset(?:s|ids|names)?\s*\.\s*(?:includes|has)\(\s*${BASE_ID}`,
140
+ ].join('|'), 'iu');
141
+ }
142
+ const DIRECT_GATE = presetGate();
113
143
 
114
144
  function presetRestricted(text) {
115
- return GATE_MARKERS.some(marker => text.includes(marker));
145
+ if (!/preset/iu.test(text)) return false;
146
+ // The dsh-ops mode table is a known preset allowlist.
147
+ if (/\bMODE_PRESET\s*(?:=|[.\[])/u.test(text) || DIRECT_GATE.test(text)) return true;
148
+ const aliases = [...new Set(Array.from(text.matchAll(PRESET_ASSIGNMENT), match => match[1]))].slice(0, 32);
149
+ return aliases.length > 0 && presetGate(aliases).test(text);
116
150
  }
117
151
 
118
152
  /** Quoted preset ids this code mentions; the base id a restricted plugin accepts. */
119
153
  function acceptedPresetIds(text) {
120
- const found = [];
121
- for (const id of KNOWN_PRESET_IDS) {
122
- if (text.includes("'" + id + "'") || text.includes('"' + id + '"')) found.push(id);
123
- }
124
- return found;
154
+ return KNOWN_PRESET_IDS.filter(id => quotes(text, id));
125
155
  }
126
156
 
127
157
  /**
128
- * Probe one plugin package for the two identity layers. Bounded and cached.
158
+ * Probe one plugin package for the two identity layers. Bounded, and cached until the package's
159
+ * manifest changes.
129
160
  * @param root - package root.
130
161
  * @param nativeId - the native preset id, normally deep-ptc.
162
+ * @param first - a file to read before walking the package, normally the one that asked: it is the
163
+ * likeliest place for the gate and must not be lost to the scan limits in a large package.
131
164
  * @returns declares: the package knows the native id; restricted: the package gates on preset ids.
132
165
  */
133
- export function packageProbe(root, nativeId) {
166
+ export function packageProbe(root, nativeId, first) {
134
167
  const key = root + '|' + nativeId;
135
- if (packageCache.has(key)) return packageCache.get(key);
168
+ const stamp = manifestStamp(root);
169
+ const cached = packageCache.get(key);
170
+ if (cached?.stamp === stamp) return cached.result;
136
171
  let files = 0;
137
172
  let bytes = 0;
138
173
  const result = { declares: false, restricted: false, accepts: [] };
139
174
  const accepts = new Set();
175
+ const presetIds = new Set([...KNOWN_PRESET_IDS, nativeId]);
176
+ const seen = new Set();
177
+ const done = () => result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES;
178
+ const read = file => {
179
+ if (seen.has(file)) return;
180
+ seen.add(file);
181
+ let size = 0;
182
+ try { size = statSync(file).size; } catch { return; }
183
+ if (size <= 0 || size > MAX_FILE_BYTES) return;
184
+ let text;
185
+ try { text = readFileSync(file, 'utf8'); } catch { return; }
186
+ text = presetSource(text, presetIds);
187
+ if (quotes(text, nativeId)) result.declares = true;
188
+ if (presetRestricted(text)) result.restricted = true;
189
+ for (const id of acceptedPresetIds(text)) accepts.add(id);
190
+ files += 1;
191
+ bytes += size;
192
+ };
140
193
  const visit = directory => {
141
- if (result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES) return;
194
+ if (done()) return;
142
195
  let entries;
143
196
  try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return; }
144
197
  for (const entry of entries) {
145
- if (result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES) return;
198
+ if (done()) return;
146
199
  if (entry.name.startsWith('.')) continue;
147
200
  const full = join(directory, entry.name);
148
201
  if (entry.isDirectory()) {
149
202
  if (!SKIP_DIRS.has(entry.name)) visit(full);
150
- continue;
203
+ } else if (entry.isFile() && isCodeFile(entry.name)) {
204
+ read(full);
151
205
  }
152
- if (!entry.isFile() || !isCodeFile(entry.name)) continue;
153
- let size = 0;
154
- try { size = statSync(full).size; } catch { continue; }
155
- if (size <= 0 || size > MAX_FILE_BYTES) continue;
156
- let text;
157
- try { text = readFileSync(full, 'utf8'); } catch { continue; }
158
- if (text.includes(nativeId)) result.declares = true;
159
- if (presetRestricted(text)) result.restricted = true;
160
- for (const id of acceptedPresetIds(text)) accepts.add(id);
161
- files += 1;
162
- bytes += size;
163
206
  }
164
207
  };
208
+ if (typeof first === 'string' && isCodeFile(first)) read(first);
165
209
  visit(root);
166
210
  result.accepts = [...accepts];
167
- packageCache.set(key, result);
211
+ packageCache.set(key, { stamp, result });
168
212
  return result;
169
213
  }
170
214
 
@@ -202,18 +246,24 @@ export function decidePresetId(exact, options = {}, info = {}) {
202
246
 
203
247
  /** Inspect one call: host frame, or the calling plugin package and its declaration. */
204
248
  export function inspectCaller(stack, nativeId) {
205
- const head = String(stack ?? '').split('\n').slice(0, 4).join('\n');
206
- if (HOST_CALLERS.test(head)) return { host: true };
207
249
  const file = callerFile(stack);
208
250
  if (!file) return { host: true };
209
- if (file.includes('app.asar')) return { host: true };
210
- if (callerCache.has(file)) return callerCache.get(file);
251
+ // An official frame further up the stack may have invoked an external plugin.
252
+ if (HOST_CALLERS.test(file) || file.includes('app.asar')) return { host: true };
253
+ const now = Date.now();
254
+ const cached = callerCache.get(file);
255
+ if (cached?.nativeId === nativeId) {
256
+ if (now - cached.checked < FRESH_MS) return cached.info;
257
+ if (manifestStamp(cached.info.packageRoot) === cached.stamp) {
258
+ cached.checked = now;
259
+ return cached.info;
260
+ }
261
+ }
211
262
  const pkg = packageOf(file);
212
263
  if (pkg === undefined) return { host: true };
213
264
  if (pkg.name.startsWith('@deepseek-ai/')) return { host: true };
214
- const probe = packageProbe(pkg.root, nativeId);
215
- const info = { host: false, packageName: pkg.name, packageRoot: pkg.root, declares: probe.declares, restricted: probe.restricted, accepts: probe.accepts };
216
- callerCache.set(file, info);
265
+ const info = { host: false, packageName: pkg.name, packageRoot: pkg.root, ...packageProbe(pkg.root, nativeId, file) };
266
+ callerCache.set(file, { info, nativeId, stamp: manifestStamp(pkg.root), checked: now });
217
267
  return info;
218
268
  }
219
269
 
@@ -222,7 +272,8 @@ function logDecision(info, id) {
222
272
  const key = info.packageName + '|' + id;
223
273
  if (logged.has(key)) return;
224
274
  logged.add(key);
225
- log('decision ' + new Date().toISOString() + ' ' + info.packageName + ' -> ' + id + (info.declares ? ' (declares native)' : info.restricted ? ' (preset restricted -> ' + id + ')' : ' (unrestricted -> native)'));
275
+ const reason = info.declares ? 'declares native' : info.restricted ? 'preset restricted' : 'unrestricted';
276
+ log(`decision ${info.packageName} -> ${id} (${reason})`);
226
277
  }
227
278
 
228
279
  /**
@@ -234,14 +285,18 @@ function logDecision(info, id) {
234
285
  * @returns owner handle; dispose() restores the unpatched method.
235
286
  */
236
287
  export function installPresetCompat(ctx, options) {
237
- if (typeof ctx?.logger?.debug === 'function') sink = line => ctx.logger.debug('Deep PTC preset identity: %s', line);
288
+ const debug = typeof ctx?.logger?.debug === 'function'
289
+ ? line => ctx.logger.debug('Deep PTC preset identity: %s', line)
290
+ : () => {};
238
291
  const registry = ctx?.agentPresets;
239
292
  const current = registry?.composedPreset;
240
293
  if (typeof current !== 'function') {
241
- log('skip ' + new Date().toISOString() + ': agentPresets.composedPreset unavailable');
294
+ try { debug('skip: agentPresets.composedPreset unavailable'); } catch { /* diagnostics only */ }
242
295
  return { active: false, owner: false, dispose() {} };
243
296
  }
244
297
  if (current[PATCH_MARK] === true) return { active: true, owner: false, dispose() {} };
298
+ // Diagnostics follow the owner of the patch, not whichever mount came last.
299
+ sink = debug;
245
300
  const hadOwn = Object.hasOwn(registry, 'composedPreset');
246
301
  const original = current;
247
302
  const patched = function composedPreset(agentCtx) {
@@ -250,17 +305,20 @@ export function installPresetCompat(ctx, options) {
250
305
  if (!now || now.enabled === false) return exact;
251
306
  const nativeIds = Array.isArray(now.nativeIds) && now.nativeIds.length > 0 ? now.nativeIds : ['deep-ptc'];
252
307
  if (typeof exact !== 'string' || !nativeIds.includes(exact)) return exact;
253
- // A failed probe means 'does not declare the native id', so the consumer still
254
- // receives the usable base id instead of losing the plugin surface.
255
- let info = { host: false, declares: false, restricted: true };
256
- try { info = inspectCaller(new Error().stack ?? '', nativeIds[0]); } catch (error) { log('inspect-error ' + error.message); }
308
+ let info;
309
+ try {
310
+ info = inspectCaller(new Error().stack ?? '', exact);
311
+ } catch (error) {
312
+ log('inspect-error ' + error?.message);
313
+ return exact;
314
+ }
257
315
  const id = decidePresetId(exact, now, info);
258
316
  logDecision(info, id);
259
317
  return id;
260
318
  };
261
319
  Object.defineProperty(patched, PATCH_MARK, { value: true });
262
320
  Object.defineProperty(registry, 'composedPreset', { value: patched, configurable: true, writable: true });
263
- log('installed ' + new Date().toISOString());
321
+ log('installed');
264
322
  return {
265
323
  active: true,
266
324
  owner: true,
@@ -268,7 +326,12 @@ export function installPresetCompat(ctx, options) {
268
326
  if (registry.composedPreset !== patched) return;
269
327
  if (hadOwn) Object.defineProperty(registry, 'composedPreset', { value: original, configurable: true, writable: true });
270
328
  else delete registry.composedPreset;
271
- log('disposed ' + new Date().toISOString());
329
+ log('disposed');
330
+ // Nothing learned about callers outlives the layer: the next owner probes afresh.
331
+ packageCache.clear();
332
+ callerCache.clear();
333
+ logged.clear();
334
+ sink = () => {};
272
335
  },
273
336
  };
274
337
  }
package/lib/reachable.mjs CHANGED
@@ -85,8 +85,9 @@ async function steerableWait(jobs, watch, id, timeoutMs, owner, signal) {
85
85
  }
86
86
 
87
87
  // Timed questions become pending as soon as the user writes instead of answering the card. The service
88
- // keeps no public early-expiry hook, so this reaches its wait record and does nothing if the shape differs.
89
- export function steerableQuestions(questions, watch) {
88
+ // keeps no public early-expiry hook, so this reaches its wait record. If an update reshapes that record the
89
+ // question simply waits out its timeout as it does officially, and `reshaped` is told.
90
+ export function steerableQuestions(questions, watch, reshaped = () => {}) {
90
91
  return new Proxy(questions, {
91
92
  get(target, key) {
92
93
  if (key !== 'askTimed') {
@@ -97,8 +98,23 @@ export function steerableQuestions(questions, watch) {
97
98
  const asked = target.askTimed(request, callId, timeoutMs);
98
99
  if (request?.agent === undefined) return asked;
99
100
  const expire = () => {
100
- const wait = target.waits?.get?.(request.agent)?.get?.(callId);
101
- if (typeof wait?.close === 'function' && wait.timeout !== undefined) wait.close(wait.timeout);
101
+ const report = () => {
102
+ try { reshaped(); } catch { /* diagnostics must not interrupt the official wait */ }
103
+ };
104
+ try {
105
+ const waits = target.waits;
106
+ if (typeof waits?.get !== 'function') return report();
107
+ const records = waits.get(request.agent);
108
+ if (records == null) return;
109
+ if (typeof records.get !== 'function') return report();
110
+ // No record means the question was already answered or expired.
111
+ const wait = records.get(callId);
112
+ if (wait == null) return;
113
+ if (typeof wait.close !== 'function' || wait.timeout === undefined) return report();
114
+ wait.close(wait.timeout);
115
+ } catch {
116
+ report();
117
+ }
102
118
  };
103
119
  if (steeringPending(request.agent)) {
104
120
  expire();
package/lib/rules.mjs CHANGED
@@ -11,7 +11,7 @@ export function reachabilityText(config) {
11
11
  - A foreground command still running after ${config.foregroundSeconds} s, or still running when the user sends a message, moves to a background job by itself. A command reported as moved to the background after only a few seconds means a user message is waiting: finish the current step quickly and answer it.
12
12
  - job_output waits end as soon as the user sends a message, and waiting again while that message is unread is refused.
13
13
  - Pauses longer than ${MAX_PAUSE_SECONDS} s are refused: a real sleep or Start-Sleep command in the foreground, and a timer the program awaits in run_code. Text in strings, comments and arguments does not count. Polling one running job more than ${config.maxPollsPerProgram} times in one run_code program is refused.
14
- - ask_user_question waits at most ${config.maxQuestionSeconds} s (timeout is in seconds; -1 is refused). An unanswered question becomes pending, the user can still answer it, and a message the user writes instead ends the wait.`;
14
+ - ask_user_question waits at most ${config.maxQuestionSeconds} s (timeout is in seconds; -1, 0 and negative values are refused). An unanswered question becomes pending, the user can still answer it, and a message the user writes instead ends the wait.`;
15
15
  }
16
16
 
17
17
  // Returns the denial reason for one tool execution, or undefined to allow it.
@@ -44,9 +44,10 @@ export function reachabilityGuard(config, jobsOf = () => undefined, languageOf =
44
44
  if (job?.status === 'running' && countPoll(exec.rootCallId, args.job_id) > config.maxPollsPerProgram)
45
45
  return `Deep PTC refuses polling job ${args.job_id} again inside this run_code program. ${LATER}`;
46
46
  }
47
+ // Only a positive, bounded timeout keeps the turn reachable; -1, 0 and other non-positive values wait forever.
47
48
  if (exec.name === 'ask_user_question' && typeof args.timeout === 'number'
48
- && (args.timeout === -1 || args.timeout > config.maxQuestionSeconds))
49
- return `Deep PTC limits ask_user_question to timeout <= ${config.maxQuestionSeconds} seconds. An unanswered question becomes pending and the user can still answer it later; continue independent work meanwhile.`;
49
+ && !(args.timeout > 0 && args.timeout <= config.maxQuestionSeconds))
50
+ return `Deep PTC limits ask_user_question to 0 < timeout <= ${config.maxQuestionSeconds} seconds. An unanswered question becomes pending and the user can still answer it later; continue independent work meanwhile.`;
50
51
  return undefined;
51
52
  };
52
53
  }
@@ -1,11 +1,23 @@
1
1
  // Static checks for waiting written into commands or run_code programs. Only a real pause counts: text in
2
2
  // strings, comments and arguments is not one. A pause whose length cannot be read is allowed, because the
3
3
  // runtime still bounds it: foreground commands move to the background and programs have a deadline.
4
+ // This is a heuristic reading of the source, not a parser: when in doubt it allows.
4
5
  export const MAX_PAUSE_SECONDS = 5;
5
6
 
6
7
  const UNIT_SECONDS = { '': 1, s: 1, m: 60, h: 3600, d: 86400 };
7
8
  const COMMAND_PREFIXES = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time', 'command', 'builtin', 'exec', 'nohup', 'nice', 'sudo', 'env']);
8
9
  const HEREDOC = /^<<-?[ \t]*(?:'([^'\n]+)'|"([^"\n]+)"|\\?([^\s;&|<>()'"]+))/u;
10
+ // PowerShell cmdlets whose script block runs as a background job.
11
+ const JOB_STARTERS = new Set(['start-job', 'start-threadjob']);
12
+
13
+ function powerShellCommand(words) {
14
+ const first = words[0] ?? '';
15
+ const assignment = /^\$[\w:]+(=.*)?$/u.exec(first);
16
+ if (!assignment) return first;
17
+ const operator = assignment[1] ?? words[1];
18
+ if (!operator?.startsWith('=')) return first;
19
+ return operator.slice(1) || words[assignment[1] === undefined ? 2 : 1] || '';
20
+ }
9
21
 
10
22
  // Split shell source into simple commands, each `{ words, background }`. Quoted text stays inside one word,
11
23
  // comments and heredoc bodies disappear, and command substitutions become commands of their own.
@@ -27,16 +39,30 @@ function shellCommands(source, dialect) {
27
39
  words = [];
28
40
  };
29
41
  const closing = (open, close) => {
42
+ const opener = { ')': '(', '}': '{' }[close];
43
+ const jobBlock = !posix && close === '}';
30
44
  let depth = 1;
31
45
  let quote;
32
46
  for (let at = open; at < source.length; at++) {
33
47
  const c = source[at];
34
48
  if (quote !== undefined) {
35
- if (c === '\\' && quote === '"' && posix) at++;
49
+ if (c === (posix ? '\\' : '`') && quote === '"') at++;
36
50
  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++;
51
+ } else if (c === (posix ? '\\' : '`')) at++;
52
+ else if (jobBlock && c === '<' && source[at + 1] === '#') {
53
+ const end = source.indexOf('#>', at + 2);
54
+ if (end === -1) return source.length;
55
+ at = end + 1;
56
+ } else if (jobBlock && c === '#' && /[\s;({)}|&]/u.test(source[at - 1] ?? '')) {
57
+ const end = source.indexOf('\n', at + 1);
58
+ if (end === -1) return source.length;
59
+ at = end;
60
+ } else if (jobBlock && c === '@' && /^["']\r?\n/u.test(source.slice(at + 1, at + 4))) {
61
+ const end = source.indexOf(`\n${source[at + 1]}@`, at + 2);
62
+ if (end === -1) return source.length;
63
+ at = end + 2;
64
+ } else if (c === '"' || c === "'") quote = c;
65
+ else if (c === opener) depth++;
40
66
  else if (c === close && --depth === 0) return at;
41
67
  }
42
68
  return source.length;
@@ -122,6 +148,13 @@ function shellCommands(source, dialect) {
122
148
  } else if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')') {
123
149
  endCommand();
124
150
  i++;
151
+ } else if (c === '{' && word === undefined && !posix && JOB_STARTERS.has(commandName(powerShellCommand(words)))) {
152
+ // `Start-Job { Start-Sleep 60 }`: the block is the job's body, so nothing in it holds the foreground.
153
+ const end = closing(i + 1, '}');
154
+ if (end === source.length) {
155
+ endCommand();
156
+ i++;
157
+ } else i = end + 1;
125
158
  } else if ((c === '{' || c === '}') && word === undefined) {
126
159
  endCommand();
127
160
  i++;
@@ -1,9 +1,11 @@
1
1
  // Local metadata search only: no model calls, filesystem probing or skill-body reads.
2
- const indexed = new WeakMap();
3
2
  export const DIRECTORY_TOOL = 'deep_ptc_tools';
4
3
  export const RESET_COMMAND = 'deep-ptc-reset-tools';
5
4
  export const STATE_EVENT = 'plugin:dsh-deep-ptc-mode/tool-state';
6
5
  export const STATE_KEY = 'deepPtcTools';
6
+
7
+ const indexed = new WeakMap();
8
+
7
9
  export function summary(definition) {
8
10
  let row = indexed.get(definition);
9
11
  if (!row) {
@@ -14,32 +16,64 @@ export function summary(definition) {
14
16
  }
15
17
  return row;
16
18
  }
19
+
20
+ const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
21
+
17
22
  export function searchCatalog(definitions, query = '', offset = 0, limit = 6) {
18
23
  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));
24
+ // A term in the name outweighs any number of terms in the description.
25
+ const scoreOf = row => terms.reduce(
26
+ (sum, word) => sum + (row.name.toLowerCase().includes(word) ? 8 : row.text.includes(word) ? 1 : 0), 0);
27
+ const ranked = definitions
28
+ .map(definition => {
29
+ const row = summary(definition);
30
+ return { row, score: scoreOf(row) };
31
+ })
32
+ .filter(entry => terms.length === 0 || entry.score > 0)
33
+ .sort((a, b) => b.score - a.score || byName(a.row.name, b.row.name));
25
34
  const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
26
35
  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 };
36
+ return {
37
+ total: ranked.length,
38
+ results: ranked.slice(start, start + count).map(({ row }) => ({ name: row.name, description: row.description })),
39
+ nextOffset: start + count < ranked.length ? start + count : null,
40
+ };
29
41
  }
42
+
30
43
  export function toolSchema(def) {
31
44
  return { name: def.name, description: def.description ?? '', parameters: def.parameters, output: def.output?.schema ?? {} };
32
45
  }
33
- export function blankState() { return { v: 1, epoch: 0, blocked: [], report: null }; }
46
+
47
+ export function blankState() {
48
+ return { v: 1, epoch: 0, blocked: [], report: null };
49
+ }
50
+
51
+ function validBlocked(row) {
52
+ return !!row && typeof row.name === 'string' && row.name.length <= 256
53
+ && typeof row.provider === 'string' && typeof row.kind === 'string';
54
+ }
55
+
34
56
  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 };
57
+ if (!value || value.v !== 1 || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !Array.isArray(value.blocked))
58
+ throw new Error('Invalid Deep PTC tool state');
59
+ if (!value.blocked.every(validBlocked)) throw new Error('Invalid blocked tool');
60
+ return {
61
+ v: 1,
62
+ epoch: value.epoch,
63
+ blocked: value.blocked.map(({ name, provider, kind }) => ({ name, provider, kind })),
64
+ report: value.report ?? null,
65
+ };
38
66
  }
67
+
39
68
  export function foldToolState(state, event) {
40
69
  if (event.type === STATE_EVENT && event.ignorable === true) {
41
- try { return parseState(event.data); } catch { return state; }
70
+ try {
71
+ return parseState(event.data);
72
+ } catch {
73
+ return state;
74
+ }
42
75
  }
43
- if (event.type === 'turn/end' && state.blocked.length) return { ...state, report: { turn: event.data.turn, tools: state.blocked } };
76
+ if (event.type === 'turn/end' && state.blocked.length)
77
+ return { ...state, report: { turn: event.data.turn, tools: state.blocked } };
44
78
  return state;
45
79
  }