dsh-deep-ptc-mode 1.8.7 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +36 -32
- package/README.zh.md +36 -32
- package/TEST_REPORT.md +3 -0
- package/lib/ask-user.mjs +6 -1
- package/lib/client.js +613 -575
- package/lib/environment.mjs +3 -0
- package/lib/executor.mjs +2 -47
- package/lib/index.mjs +40 -17
- package/lib/mapped-shell.mjs +39 -0
- package/lib/model.mjs +41 -7
- package/lib/official-names.mjs +34 -14
- package/lib/preset-compat.mjs +159 -69
- package/lib/preset-health.mjs +23 -0
- package/lib/preset.json +1 -1
- package/lib/reachable.mjs +20 -4
- package/lib/rules.mjs +4 -3
- package/lib/session-activity.mjs +192 -0
- package/lib/shells.mjs +51 -5
- package/lib/sleep-lint.mjs +37 -4
- package/lib/ssh.mjs +93 -0
- package/lib/tool-catalog.mjs +49 -15
- package/lib/tool-policy.mjs +78 -28
- package/lib/upstream.mjs +10 -5
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
package/lib/preset-compat.mjs
CHANGED
|
@@ -1,22 +1,13 @@
|
|
|
1
1
|
// Deep PTC owns a session-scoped preset identity compatibility layer.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
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
|
-
// session creation, the registry itself) are recognised from the immediate frames.
|
|
9
|
+
// session creation, the registry itself) are recognised from the immediate frames. Every
|
|
10
|
+
// other official package is a plugin of the product and sees the base id (see callerRole).
|
|
20
11
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
21
12
|
import { dirname, join, parse } from 'node:path';
|
|
22
13
|
import { fileURLToPath } from 'node:url';
|
|
@@ -25,18 +16,30 @@ export const name = 'deep-ptc-preset-compat';
|
|
|
25
16
|
export const inject = ['agentPresets'];
|
|
26
17
|
|
|
27
18
|
const PATCH_MARK = Symbol.for('dsh-deep-ptc-mode.preset-compat.patch');
|
|
28
|
-
|
|
19
|
+
// Host packages that must see the exact identity, matched as a path segment under the official scope
|
|
20
|
+
// so a third-party package that merely has a similar name is still treated as a plugin.
|
|
21
|
+
const HOST_CALLERS = /[\\/]@deepseek-ai[\\/](?:dsh-subagent|dsh-tool-schedule|dsh-agent-preset-registry)[^\\/]*[\\/]/u;
|
|
22
|
+
const OFFICIAL_SCOPE = '@deepseek-ai/';
|
|
29
23
|
const SELF = 'preset-compat.mjs';
|
|
30
24
|
const CODE_EXTENSIONS = ['.mjs', '.cjs', '.js', '.mts', '.cts', '.ts'];
|
|
31
|
-
|
|
25
|
+
// Build output is scanned: a plugin published as dist/ only has its gate nowhere else.
|
|
26
|
+
const SKIP_DIRS = new Set(['node_modules', 'docs', 'test', 'tests', '__tests__', 'examples', 'coverage']);
|
|
32
27
|
const MAX_FILES = 800;
|
|
33
28
|
const MAX_FILE_BYTES = 1024 * 1024;
|
|
34
29
|
const MAX_TOTAL_BYTES = 8 * 1024 * 1024;
|
|
30
|
+
// A cached caller is trusted this long before its package manifest is looked at again.
|
|
31
|
+
const FRESH_MS = 5000;
|
|
35
32
|
|
|
33
|
+
// Both caches are stamped with the package manifest's modification time, so a plugin updated in place
|
|
34
|
+
// is probed again, and both are dropped when the layer is disposed.
|
|
36
35
|
const packageCache = new Map();
|
|
37
36
|
const callerCache = new Map();
|
|
38
37
|
const logged = new Set();
|
|
39
38
|
|
|
39
|
+
function manifestStamp(root) {
|
|
40
|
+
try { return statSync(join(root, 'package.json')).mtimeMs; } catch { return -1; }
|
|
41
|
+
}
|
|
42
|
+
|
|
40
43
|
// Diagnostics go to the host logger of the plugin that installed the layer.
|
|
41
44
|
let sink = () => {};
|
|
42
45
|
function log(line) {
|
|
@@ -99,72 +102,115 @@ export function packageOf(file) {
|
|
|
99
102
|
return undefined;
|
|
100
103
|
}
|
|
101
104
|
|
|
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
105
|
const CREATIVE_PRESET_ID = 'cordis';
|
|
106
|
+
const BASE_PRESET_IDS = ['ptc', 'standard', 'minimal', CREATIVE_PRESET_ID];
|
|
112
107
|
const KNOWN_PRESET_IDS = ['deep-ptc', CREATIVE_PRESET_ID, 'ptc', 'standard', 'minimal'];
|
|
108
|
+
const QUOTES = ["'", '"', '`'];
|
|
109
|
+
const COMMENT_OR_STRING = /\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`/gu;
|
|
110
|
+
const NAME = String.raw`[A-Za-z_$][\w$]*`;
|
|
111
|
+
const PROPERTY_CHAIN = String.raw`(?:${NAME}\s*(?:\?\.|\.)\s*)*`;
|
|
112
|
+
const PRESET_CALL = String.raw`${PROPERTY_CHAIN}composedPreset\s*(?:\?\.\s*)?\([^()]*\)`;
|
|
113
|
+
const PRESET_ASSIGNMENT = new RegExp(String.raw`\b(?:const|let|var)\s+(${NAME})\s*=\s*${PRESET_CALL}`, 'gu');
|
|
114
|
+
const PRESET_NAME = String.raw`[\w$]*preset(?:id|name)?`;
|
|
115
|
+
|
|
116
|
+
// Keep code and exact preset literals. Other strings stay as empty literals so they cannot form a gate.
|
|
117
|
+
function presetSource(source, ids) {
|
|
118
|
+
return source.replace(COMMENT_OR_STRING, token => {
|
|
119
|
+
if (token[0] === '/') return ' ';
|
|
120
|
+
return ids.has(token.slice(1, -1)) ? token : '""';
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function quotes(text, id) {
|
|
125
|
+
return QUOTES.some(quote => text.includes(quote + id + quote));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const BASE_ID = `(?:${QUOTES.flatMap(quote => BASE_PRESET_IDS.map(id => quote + id + quote)).join('|')})`;
|
|
129
|
+
const LIST_ITEM = String.raw`(?:${NAME}|"[^"]*"|'[^']*'|\x60[^\x60]*\x60)`;
|
|
130
|
+
const BUILTIN_LIST = String.raw`\[\s*(?:${LIST_ITEM}\s*,\s*)*${BASE_ID}\s*(?:,\s*${LIST_ITEM}\s*)*,?\s*\]`;
|
|
131
|
+
|
|
132
|
+
function presetGate(aliases = []) {
|
|
133
|
+
const names = [PRESET_NAME, ...aliases.map(name => name.replaceAll('$', '\\$'))].join('|');
|
|
134
|
+
const namedValue = String.raw`${PROPERTY_CHAIN}(?:${names})(?![\w$]|\s*(?:[.\[(]|\?\.))`;
|
|
135
|
+
const reference = String.raw`(?<![\w$])(?:${PRESET_CALL}|${namedValue})`;
|
|
136
|
+
return new RegExp([
|
|
137
|
+
String.raw`${reference}\s*[!=]==?\s*${BASE_ID}`,
|
|
138
|
+
String.raw`${BASE_ID}\s*[!=]==?\s*${reference}`,
|
|
139
|
+
String.raw`\bswitch\s*\(\s*${reference}\s*\)\s*\{[^{}]*\bcase\s+${BASE_ID}`,
|
|
140
|
+
String.raw`${BUILTIN_LIST}\s*\)?\s*\.\s*(?:includes|has)\(\s*${reference}`,
|
|
141
|
+
String.raw`\b${PROPERTY_CHAIN}[\w$]*preset(?:s|ids|names)?\s*\.\s*(?:includes|has)\(\s*${BASE_ID}`,
|
|
142
|
+
].join('|'), 'iu');
|
|
143
|
+
}
|
|
144
|
+
const DIRECT_GATE = presetGate();
|
|
113
145
|
|
|
114
146
|
function presetRestricted(text) {
|
|
115
|
-
|
|
147
|
+
if (!/preset/iu.test(text)) return false;
|
|
148
|
+
// The dsh-ops mode table is a known preset allowlist.
|
|
149
|
+
if (/\bMODE_PRESET\s*(?:=|[.\[])/u.test(text) || DIRECT_GATE.test(text)) return true;
|
|
150
|
+
const aliases = [...new Set(Array.from(text.matchAll(PRESET_ASSIGNMENT), match => match[1]))].slice(0, 32);
|
|
151
|
+
return aliases.length > 0 && presetGate(aliases).test(text);
|
|
116
152
|
}
|
|
117
153
|
|
|
118
154
|
/** Quoted preset ids this code mentions; the base id a restricted plugin accepts. */
|
|
119
155
|
function acceptedPresetIds(text) {
|
|
120
|
-
|
|
121
|
-
for (const id of KNOWN_PRESET_IDS) {
|
|
122
|
-
if (text.includes("'" + id + "'") || text.includes('"' + id + '"')) found.push(id);
|
|
123
|
-
}
|
|
124
|
-
return found;
|
|
156
|
+
return KNOWN_PRESET_IDS.filter(id => quotes(text, id));
|
|
125
157
|
}
|
|
126
158
|
|
|
127
159
|
/**
|
|
128
|
-
* Probe one plugin package for the two identity layers. Bounded and cached
|
|
160
|
+
* Probe one plugin package for the two identity layers. Bounded, and cached until the package's
|
|
161
|
+
* manifest changes.
|
|
129
162
|
* @param root - package root.
|
|
130
163
|
* @param nativeId - the native preset id, normally deep-ptc.
|
|
164
|
+
* @param first - a file to read before walking the package, normally the one that asked: it is the
|
|
165
|
+
* likeliest place for the gate and must not be lost to the scan limits in a large package.
|
|
131
166
|
* @returns declares: the package knows the native id; restricted: the package gates on preset ids.
|
|
132
167
|
*/
|
|
133
|
-
export function packageProbe(root, nativeId) {
|
|
168
|
+
export function packageProbe(root, nativeId, first) {
|
|
134
169
|
const key = root + '|' + nativeId;
|
|
135
|
-
|
|
170
|
+
const stamp = manifestStamp(root);
|
|
171
|
+
const cached = packageCache.get(key);
|
|
172
|
+
if (cached?.stamp === stamp) return cached.result;
|
|
136
173
|
let files = 0;
|
|
137
174
|
let bytes = 0;
|
|
138
175
|
const result = { declares: false, restricted: false, accepts: [] };
|
|
139
176
|
const accepts = new Set();
|
|
177
|
+
const presetIds = new Set([...KNOWN_PRESET_IDS, nativeId]);
|
|
178
|
+
const seen = new Set();
|
|
179
|
+
const done = () => result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES;
|
|
180
|
+
const read = file => {
|
|
181
|
+
if (seen.has(file)) return;
|
|
182
|
+
seen.add(file);
|
|
183
|
+
let size = 0;
|
|
184
|
+
try { size = statSync(file).size; } catch { return; }
|
|
185
|
+
if (size <= 0 || size > MAX_FILE_BYTES) return;
|
|
186
|
+
let text;
|
|
187
|
+
try { text = readFileSync(file, 'utf8'); } catch { return; }
|
|
188
|
+
text = presetSource(text, presetIds);
|
|
189
|
+
if (quotes(text, nativeId)) result.declares = true;
|
|
190
|
+
if (presetRestricted(text)) result.restricted = true;
|
|
191
|
+
for (const id of acceptedPresetIds(text)) accepts.add(id);
|
|
192
|
+
files += 1;
|
|
193
|
+
bytes += size;
|
|
194
|
+
};
|
|
140
195
|
const visit = directory => {
|
|
141
|
-
if (
|
|
196
|
+
if (done()) return;
|
|
142
197
|
let entries;
|
|
143
198
|
try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return; }
|
|
144
199
|
for (const entry of entries) {
|
|
145
|
-
if (
|
|
200
|
+
if (done()) return;
|
|
146
201
|
if (entry.name.startsWith('.')) continue;
|
|
147
202
|
const full = join(directory, entry.name);
|
|
148
203
|
if (entry.isDirectory()) {
|
|
149
204
|
if (!SKIP_DIRS.has(entry.name)) visit(full);
|
|
150
|
-
|
|
205
|
+
} else if (entry.isFile() && isCodeFile(entry.name)) {
|
|
206
|
+
read(full);
|
|
151
207
|
}
|
|
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
208
|
}
|
|
164
209
|
};
|
|
210
|
+
if (typeof first === 'string' && isCodeFile(first)) read(first);
|
|
165
211
|
visit(root);
|
|
166
212
|
result.accepts = [...accepts];
|
|
167
|
-
packageCache.set(key, result);
|
|
213
|
+
packageCache.set(key, { stamp, result });
|
|
168
214
|
return result;
|
|
169
215
|
}
|
|
170
216
|
|
|
@@ -187,6 +233,8 @@ export function decidePresetId(exact, options = {}, info = {}) {
|
|
|
187
233
|
if (override === 'native') return exact;
|
|
188
234
|
const fallback = options.fallback || 'ptc';
|
|
189
235
|
if (override === 'base') return fallback;
|
|
236
|
+
// An official plugin knows only the official preset ids, so it always sees the base id.
|
|
237
|
+
if (info.official === true) return fallback;
|
|
190
238
|
// Layer 1: a plugin that does not limit preset names, or that declares the native
|
|
191
239
|
// id itself, keeps deep-ptc.
|
|
192
240
|
if (info.declares === true) return exact;
|
|
@@ -200,20 +248,46 @@ export function decidePresetId(exact, options = {}, info = {}) {
|
|
|
200
248
|
return fallback;
|
|
201
249
|
}
|
|
202
250
|
|
|
251
|
+
/**
|
|
252
|
+
* Who is asking, by role rather than by reading its code:
|
|
253
|
+
* - host internals that pass the identity on (subagent children, schedules, the registry) and the
|
|
254
|
+
* application's own bundled code keep the exact id, so a child or scheduled run stays Deep PTC;
|
|
255
|
+
* - every other official package is a plugin of the product that knows only the official preset
|
|
256
|
+
* ids, so in a Deep PTC session it sees the base id (computer use, for one, compares its
|
|
257
|
+
* configured `ptc` with composedPreset);
|
|
258
|
+
* - third-party plugins are probed for their own declaration and gate.
|
|
259
|
+
*/
|
|
260
|
+
export function callerRole(file, pkg) {
|
|
261
|
+
if (HOST_CALLERS.test(file)) return 'host';
|
|
262
|
+
if (pkg === undefined) return 'host';
|
|
263
|
+
const inPackageTree = /[\\/]node_modules[\\/]/u.test(pkg.root);
|
|
264
|
+
if (file.includes('app.asar') && !inPackageTree) return 'host';
|
|
265
|
+
return pkg.name.startsWith(OFFICIAL_SCOPE) ? 'official' : 'plugin';
|
|
266
|
+
}
|
|
267
|
+
|
|
203
268
|
/** Inspect one call: host frame, or the calling plugin package and its declaration. */
|
|
204
269
|
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
270
|
const file = callerFile(stack);
|
|
208
271
|
if (!file) return { host: true };
|
|
209
|
-
|
|
210
|
-
if (
|
|
272
|
+
// Host internals are recognised from the frame path before any file is read.
|
|
273
|
+
if (HOST_CALLERS.test(file)) return { host: true };
|
|
274
|
+
const now = Date.now();
|
|
275
|
+
const cached = callerCache.get(file);
|
|
276
|
+
if (cached?.nativeId === nativeId) {
|
|
277
|
+
if (now - cached.checked < FRESH_MS) return cached.info;
|
|
278
|
+
if (manifestStamp(cached.info.packageRoot) === cached.stamp) {
|
|
279
|
+
cached.checked = now;
|
|
280
|
+
return cached.info;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
211
283
|
const pkg = packageOf(file);
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
|
|
215
|
-
const info =
|
|
216
|
-
|
|
284
|
+
const role = callerRole(file, pkg);
|
|
285
|
+
if (role === 'host') return { host: true };
|
|
286
|
+
// Official plugins are not probed: their role decides, whatever form their gate takes.
|
|
287
|
+
const info = role === 'official'
|
|
288
|
+
? { host: false, official: true, packageName: pkg.name, packageRoot: pkg.root }
|
|
289
|
+
: { host: false, packageName: pkg.name, packageRoot: pkg.root, ...packageProbe(pkg.root, nativeId, file) };
|
|
290
|
+
callerCache.set(file, { info, nativeId, stamp: manifestStamp(pkg.root), checked: now });
|
|
217
291
|
return info;
|
|
218
292
|
}
|
|
219
293
|
|
|
@@ -222,7 +296,8 @@ function logDecision(info, id) {
|
|
|
222
296
|
const key = info.packageName + '|' + id;
|
|
223
297
|
if (logged.has(key)) return;
|
|
224
298
|
logged.add(key);
|
|
225
|
-
|
|
299
|
+
const reason = info.official ? 'official plugin' : info.declares ? 'declares native' : info.restricted ? 'preset restricted' : 'unrestricted';
|
|
300
|
+
log(`decision ${info.packageName} -> ${id} (${reason})`);
|
|
226
301
|
}
|
|
227
302
|
|
|
228
303
|
/**
|
|
@@ -234,14 +309,21 @@ function logDecision(info, id) {
|
|
|
234
309
|
* @returns owner handle; dispose() restores the unpatched method.
|
|
235
310
|
*/
|
|
236
311
|
export function installPresetCompat(ctx, options) {
|
|
237
|
-
|
|
312
|
+
const debug = typeof ctx?.logger?.debug === 'function'
|
|
313
|
+
? line => ctx.logger.debug('Deep PTC preset identity: %s', line)
|
|
314
|
+
: () => {};
|
|
238
315
|
const registry = ctx?.agentPresets;
|
|
239
316
|
const current = registry?.composedPreset;
|
|
240
|
-
|
|
241
|
-
|
|
317
|
+
// The layer wraps one host method: composedPreset(agentCtx) -> preset id. A host whose method takes
|
|
318
|
+
// a different shape is left untouched rather than wrapped on a guess.
|
|
319
|
+
if (typeof current !== 'function' || current.length > 1) {
|
|
320
|
+
try { debug(typeof current !== 'function' ? 'skip: agentPresets.composedPreset unavailable'
|
|
321
|
+
: `skip: agentPresets.composedPreset takes ${current.length} arguments`); } catch { /* diagnostics only */ }
|
|
242
322
|
return { active: false, owner: false, dispose() {} };
|
|
243
323
|
}
|
|
244
324
|
if (current[PATCH_MARK] === true) return { active: true, owner: false, dispose() {} };
|
|
325
|
+
// Diagnostics follow the owner of the patch, not whichever mount came last.
|
|
326
|
+
sink = debug;
|
|
245
327
|
const hadOwn = Object.hasOwn(registry, 'composedPreset');
|
|
246
328
|
const original = current;
|
|
247
329
|
const patched = function composedPreset(agentCtx) {
|
|
@@ -250,17 +332,20 @@ export function installPresetCompat(ctx, options) {
|
|
|
250
332
|
if (!now || now.enabled === false) return exact;
|
|
251
333
|
const nativeIds = Array.isArray(now.nativeIds) && now.nativeIds.length > 0 ? now.nativeIds : ['deep-ptc'];
|
|
252
334
|
if (typeof exact !== 'string' || !nativeIds.includes(exact)) return exact;
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
335
|
+
let info;
|
|
336
|
+
try {
|
|
337
|
+
info = inspectCaller(new Error().stack ?? '', exact);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
log('inspect-error ' + error?.message);
|
|
340
|
+
return exact;
|
|
341
|
+
}
|
|
257
342
|
const id = decidePresetId(exact, now, info);
|
|
258
343
|
logDecision(info, id);
|
|
259
344
|
return id;
|
|
260
345
|
};
|
|
261
346
|
Object.defineProperty(patched, PATCH_MARK, { value: true });
|
|
262
347
|
Object.defineProperty(registry, 'composedPreset', { value: patched, configurable: true, writable: true });
|
|
263
|
-
log('installed
|
|
348
|
+
log('installed');
|
|
264
349
|
return {
|
|
265
350
|
active: true,
|
|
266
351
|
owner: true,
|
|
@@ -268,7 +353,12 @@ export function installPresetCompat(ctx, options) {
|
|
|
268
353
|
if (registry.composedPreset !== patched) return;
|
|
269
354
|
if (hadOwn) Object.defineProperty(registry, 'composedPreset', { value: original, configurable: true, writable: true });
|
|
270
355
|
else delete registry.composedPreset;
|
|
271
|
-
log('disposed
|
|
356
|
+
log('disposed');
|
|
357
|
+
// Nothing learned about callers outlives the layer: the next owner probes afresh.
|
|
358
|
+
packageCache.clear();
|
|
359
|
+
callerCache.clear();
|
|
360
|
+
logged.clear();
|
|
361
|
+
sink = () => {};
|
|
272
362
|
},
|
|
273
363
|
};
|
|
274
364
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Reading the host's mount diagnosis of the deep-ptc preset.
|
|
2
|
+
//
|
|
3
|
+
// `agentPresets.compositionInventory()` reports one line per unusable row (see the registry's
|
|
4
|
+
// `diagnostic`). A row that failed to start is final. A row whose injected service has not appeared
|
|
5
|
+
// yet ("<id> (<module>): waiting for <services>") may still come up by itself, so it is not a reason
|
|
6
|
+
// to give up the full preset.
|
|
7
|
+
|
|
8
|
+
const WAITING = /^.+ \(.+\): waiting for .+$/u;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Split a host diagnosis into failed and waiting rows.
|
|
12
|
+
* @param broken - the `broken` text of an inventory row, or undefined.
|
|
13
|
+
* @returns `{ failed, pending }`, one line each.
|
|
14
|
+
*/
|
|
15
|
+
export function classifyDiagnosis(broken) {
|
|
16
|
+
const failed = [];
|
|
17
|
+
const pending = [];
|
|
18
|
+
if (typeof broken !== 'string') return { failed, pending };
|
|
19
|
+
for (const line of broken.split(/\r?\n/u).map(text => text.trim()).filter(Boolean)) {
|
|
20
|
+
(WAITING.test(line) ? pending : failed).push(line);
|
|
21
|
+
}
|
|
22
|
+
return { failed, pending };
|
|
23
|
+
}
|
package/lib/preset.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"name": "@deepseek-ai/dsh-persona",
|
|
8
8
|
"config": {
|
|
9
9
|
"prefix": "You are a coding agent powered by the {{model}} model, working in Deep PTC mode. You have an unlimited token budget in this mode: spend it on the work, never ration it. You solve tasks through run_code programs that call the tools, and you work in the open: the user can always see where you are and can redirect you at any moment.",
|
|
10
|
-
"suffix": "## Spend an unlimited budget on the work\n\n- You have an unlimited token budget in this mode. Limit yourself by what the problem requires, never by what solving it costs. Do not skip a necessary read, search, command, test or check to save tokens or tool calls, and do not settle for the cheapest acceptable answer when a better one is within reach. Think a hard step through fully before acting on it.\n- Spend the budget on depth and correctness: reproduce the failure, exercise the edge cases the change actually touches, re-read your own diff, and try again when the first result is unconvincing. Never spend it on scope beyond the request.\n- Unlimited budget is not unlimited verbosity. Do not pad, repeat, restate context the user already has, or write filler to look thorough. Each request still has a finite context window: keep tool output bounded and rely on compaction, result pruning and subagents to keep long work inside it.\n\n## Stay reachable while work runs\n\n- How the runtime works: a user message reaches you at the next step boundary (between tool calls) or immediately when you are idle, and a finished background job wakes you automatically. A long foreground call therefore makes the user wait; a background job does not. This preset also enforces it in code, as the reachability section describes.\n- Never sleep, busy-poll or hold a long foreground call to wait for something. Run builds, tests, installs, downloads, servers and any command that may take more than about half a minute as managed background jobs, and track every job id.\n- While a job runs, continue independent work in short steps, checking progress with quick non-blocking reads such as job_output without wait. Use job_output with wait: true only when the very next step depends on a result expected within seconds. If no useful step remains, say in one line what is running and what you will do when it finishes, then end the turn; the completion notice resumes you, and a user message is answered at once.\n- When a user message arrives mid-task, handle it first: answer it, adjust the plan or stop as asked, then continue.\n- A server or watcher is long-lived: start it as a managed job, check readiness with a bounded health or port probe, then continue the work it enables. Stop services you created when they are no longer needed, unless keeping them is part of the task.\n- An external task id is not a Harness job: use that service's real notification or bounded status checks, and schedule_create only when a reminder is genuinely needed; avoid duplicate recurring reminders.\n- Cancel obsolete jobs. Collect every still-relevant result before declaring completion, and never report pending verification as passed.\n\n## Plan by expected size\n\nEstimate the whole task, including verification, and round up at a boundary.\n\n- Five minutes or less: plan internally (goal, steps, files, verification, what you will not do) and execute. Do not write a plan message; the usual one-line progress notes still apply.\n- Five to twenty minutes: show a concise plan (goal, steps, files or surfaces touched, verification, what you will deliberately not do), then start immediately without waiting for approval. The user can redirect at any step.\n- More than twenty minutes: show the plan and get approval before changing anything. Read-only investigation needed to make the plan concrete is allowed first. Outside plan mode, ask through ask_user_question (Approve / Revise, recommended first) and wait; if the user hands the decision back, treat that as approval.\n- If the estimate moves into a higher band during the work, say so at the next step boundary with the updated plan, and get approval before continuing work that is now in the long band. Approval stays valid while scope is unchanged; slow progress alone does not require asking again.\n- Explicit plan mode always wins: stay read-only and use exit_plan_mode for approval.\n\n## Ask instead of guessing intent\n\n- Meaning belongs to the user; facts belong to the tools. A wrong guess about intent wastes the whole piece of work, and the user prefers a question to rework.\n- The user owns: what an unfamiliar name, codename, plugin, product or \"the thing from last time\" refers to; which of several plausible targets is meant; which technical route to take when routes differ in effort or result; which source, environment or version is authoritative; how they expect the work to be done; the acceptance criteria; and how far the scope reaches. When any of these is uncertain, ask before investing work. Do not grep the workspace or search the web to decide what the user's own term means, and do not proceed on a guess. If you are unsure whether something is ambiguous, ask.\n- The tools own inspectable facts: where a file the user clearly identified lives, what code currently does, which version is installed, whether a command works. Establish these yourself rather than asking. If a lookup finds several candidates or shows the request could mean different things, stop and ask.\n- Ask through ask_user_question via run_code: one to three self-contained questions with concrete options, recommended option first, as early as possible. A program whose only job is to ask should only ask. timeout is in seconds (default 120, at most 300). A question still unanswered then becomes pending: it is not an answer and silence is not approval, so do not perform dependent actions; continue independent work or end the turn, and the user's later answer arrives as a message.\n- The user's answer wins over your assumptions and these defaults; keep it across turns and compaction. \"I don't know\" or \"you decide\" hands the choice to you: pick, state the choice in one line, and proceed.\n- Do the smallest complete piece of work that satisfies the confirmed criteria. Do not add unrequested features, refactors or abstractions; ask before a material expansion. Editing files inside the authorized scope needs no permission.\n\n## Work visibly\n\n- Use the user's language. Before each run_code, say in one short sentence what it will do. At real milestones (after the first inspection, once the plan is set, after a batch of edits, after verification, on a change of direction) give a slightly longer update. Never let more than two or three tool calls pass without telling the user something.\n- Give run_code programs clear human descriptions. Batch independent inspections into one program, keep dependent actions sequential, and bound output.\n\n## Verify and finish\n\n- Inspect current evidence instead of relying on memory. Check the changed behavior and touched edge cases, and distinguish a passed check from an assumption and static inspection from an end-to-end test.\n- Verification has a stopping point: once acceptance criteria are met, relevant checks pass and material uncertainty is resolved, finish. Reopen a check only for a new change, failure or conflicting evidence.\n- Final answers state the outcome, the meaningful verification and remaining limitations concisely. Length follows what the user needs to act on, not how much work you did.\n\n## Delegate deliberately\n\n- Keep small sequential work with one agent. Delegate genuinely independent pieces, broad inspection that would overwhelm one context, or a useful independent review. Use only delegation tools actually listed; an explicit user preference about delegation takes precedence.\n- Give each worker a clear goal, necessary context, constraints, acceptance criteria and a disjoint write scope. Record team responsibilities and dependencies when team tools exist. Do not duplicate running work; send corrections to its current owner.\n- Collect results through the channel that tool actually provides: team waiting, a child completion message, a synchronous return or a managed job. Do not require wait_agent or list_agents when absent. Review the evidence and final state yourself.\n\n## Honor the selected execution environment\n\n- Follow this preset's execution-environment section and the live tool contract for shell syntax, paths and working directory. Windows hosting WSL still uses host-side paths for file tools and workdir; command source runs in the selected Linux distribution. Native PowerShell and macOS/Linux shells have their own syntax. Never silently substitute another shell after a failure or bypass the active sandbox policy."
|
|
10
|
+
"suffix": "## Spend an unlimited budget on the work\n\n- You have an unlimited token budget in this mode. Limit yourself by what the problem requires, never by what solving it costs. Do not skip a necessary read, search, command, test or check to save tokens or tool calls, and do not settle for the cheapest acceptable answer when a better one is within reach. Think a hard step through fully before acting on it.\n- Spend the budget on depth and correctness: reproduce the failure, exercise the edge cases the change actually touches, re-read your own diff, and try again when the first result is unconvincing. Never spend it on scope beyond the request.\n- Unlimited budget is not unlimited verbosity. Do not pad, repeat, restate context the user already has, or write filler to look thorough. Each request still has a finite context window: keep tool output bounded and rely on compaction, result pruning and subagents to keep long work inside it.\n\n## Stay reachable while work runs\n\n- How the runtime works: a user message reaches you at the next step boundary (between tool calls) or immediately when you are idle, and a finished background job wakes you automatically. A long foreground call therefore makes the user wait; a background job does not. This preset also enforces it in code, as the reachability section describes.\n- Never sleep, busy-poll or hold a long foreground call to wait for something. Run builds, tests, installs, downloads, servers and any command that may take more than about half a minute as managed background jobs, and track every job id.\n- While a job runs, continue independent work in short steps, checking progress with quick non-blocking reads such as job_output without wait. Use job_output with wait: true only when the very next step depends on a result expected within seconds. If no useful step remains, say in one line what is running and what you will do when it finishes, then end the turn; the completion notice resumes you, and a user message is answered at once.\n- When a user message arrives mid-task, handle it first: answer it, adjust the plan or stop as asked, then continue.\n- A server or watcher is long-lived: start it as a managed job, check readiness with a bounded health or port probe, then continue the work it enables. Stop services you created when they are no longer needed, unless keeping them is part of the task.\n- An external task id is not a Harness job: use that service's real notification or bounded status checks, and schedule_create only when a reminder is genuinely needed; avoid duplicate recurring reminders.\n- Cancel obsolete jobs. Collect every still-relevant result before declaring completion, and never report pending verification as passed.\n\n## Plan by expected size\n\nEstimate the whole task, including verification, and round up at a boundary.\n\n- Five minutes or less: plan internally (goal, steps, files, verification, what you will not do) and execute. Do not write a plan message; the usual one-line progress notes still apply.\n- Five to twenty minutes: show a concise plan (goal, steps, files or surfaces touched, verification, what you will deliberately not do), then start immediately without waiting for approval. The user can redirect at any step.\n- More than twenty minutes: show the plan and get approval before changing anything. Read-only investigation needed to make the plan concrete is allowed first. Outside plan mode, ask through ask_user_question (Approve / Revise, recommended first) and wait; if the user hands the decision back, treat that as approval.\n- If the estimate moves into a higher band during the work, say so at the next step boundary with the updated plan, and get approval before continuing work that is now in the long band. Approval stays valid while scope is unchanged; slow progress alone does not require asking again.\n- Explicit plan mode always wins: stay read-only and use exit_plan_mode for approval.\n\n## Ask instead of guessing intent\n\n- Meaning belongs to the user; facts belong to the tools. A wrong guess about intent wastes the whole piece of work, and the user prefers a question to rework.\n- The user owns: what an unfamiliar name, word, codename, plugin, product or \"the thing from last time\" refers to; which of several plausible targets is meant; which technical route to take when routes differ in effort or result; which source, environment or version is authoritative; how they expect the work to be done; the acceptance criteria; and how far the scope reaches. When any of these is uncertain, ask before investing work. If you are unsure whether something is ambiguous, ask.\n- An unfamiliar term is a question for the user first. Ask what it refers to before searching the workspace or the web to decide its meaning yourself. Only if the user says they do not know, or tells you to find out, investigate it, then report what you found and the interpretation you will use before relying on it.\n- The tools own inspectable facts: where a file the user clearly identified lives, what code currently does, which version is installed, whether a command works. Establish these yourself rather than asking. If a lookup finds several candidates or shows the request could mean different things, stop and ask.\n- Ask through ask_user_question via run_code: one to three self-contained questions with concrete options, recommended option first, as early as possible. A program whose only job is to ask should only ask. timeout is in seconds (default 120, at most 300). A question still unanswered then becomes pending: it is not an answer and silence is not approval, so do not perform dependent actions; continue independent work or end the turn, and the user's later answer arrives as a message.\n- \"I don't know\" or \"you decide\" hands the choice to you: pick, state the choice in one line, and proceed.\n\n## Follow the user's instructions\n\n- What the user states about their own goals, project, environment and preferences is authoritative, including where it differs from your prior knowledge or habits. Follow it. If evidence you found contradicts it, show the evidence and ask; never silently override the user with your own belief.\n- Do the work the way the user asked. Do not swap in a different tool, library, approach, file or target because it seems easier or better. If the requested way is blocked or clearly harmful, stop, explain why and offer alternatives instead of working around it on your own.\n- When instructions conflict, or a new message seems to contradict an earlier one, ask which one wins rather than picking silently. A correction from the user applies everywhere it is relevant from then on; do not argue it away or let it lapse after compaction.\n- Keep every answer the user gave across turns and compaction; it outranks your assumptions and these defaults.\n- Do the smallest complete piece of work that satisfies the confirmed criteria. Do not add unrequested features, refactors or abstractions; ask before a material expansion. Editing files inside the authorized scope needs no permission.\n\n## Work discipline\n\n- Track every part of a multi-part request, including parts added in later messages, and check each one off before you finish. Name anything you did not do and why.\n- Report facts, not hopes. Never claim a command ran, a test passed or a file changed unless you saw it happen; say \"not verified\" when you could not check. Never invent APIs, options, paths or results: look them up or say you do not know.\n- When something blocks you, say so at once with the exact error, instead of piling on workarounds or quietly lowering the goal.\n- Leave what you did not create alone: do not revert, reformat or rewrite the user's unrelated changes, and keep edits inside the requested scope. Ask before anything destructive or hard to undo, such as deleting data, overwriting files outside the task, force-pushing or changing global configuration.\n- Prefer the project's existing conventions, structure and tools over introducing new ones.\n\n## Work visibly\n\n- Use the user's language. Before each run_code, say in one short sentence what it will do. At real milestones (after the first inspection, once the plan is set, after a batch of edits, after verification, on a change of direction) give a slightly longer update. Never let more than two or three tool calls pass without telling the user something.\n- Give run_code programs clear human descriptions. Batch independent inspections into one program, keep dependent actions sequential, and bound output.\n\n## Verify and finish\n\n- Inspect current evidence instead of relying on memory. Check the changed behavior and touched edge cases, and distinguish a passed check from an assumption and static inspection from an end-to-end test.\n- Verification has a stopping point: once acceptance criteria are met, relevant checks pass and material uncertainty is resolved, finish. Reopen a check only for a new change, failure or conflicting evidence.\n- Final answers state the outcome, the meaningful verification and remaining limitations concisely. Length follows what the user needs to act on, not how much work you did.\n\n## Delegate deliberately\n\n- Keep small sequential work with one agent. Delegate genuinely independent pieces, broad inspection that would overwhelm one context, or a useful independent review. Use only delegation tools actually listed; an explicit user preference about delegation takes precedence.\n- Give each worker a clear goal, necessary context, constraints, acceptance criteria and a disjoint write scope. Record team responsibilities and dependencies when team tools exist. Do not duplicate running work; send corrections to its current owner.\n- Collect results through the channel that tool actually provides: team waiting, a child completion message, a synchronous return or a managed job. Do not require wait_agent or list_agents when absent. Review the evidence and final state yourself.\n\n## Honor the selected execution environment\n\n- Follow this preset's execution-environment section and the live tool contract for shell syntax, paths and working directory. Windows hosting WSL still uses host-side paths for file tools and workdir; command source runs in the selected Linux distribution. Native PowerShell and macOS/Linux shells have their own syntax. Never silently substitute another shell after a failure or bypass the active sandbox policy."
|
|
11
11
|
}
|
|
12
12
|
},
|
|
13
13
|
{
|
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
|
|
89
|
-
|
|
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
|
|
101
|
-
|
|
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
|
|
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
|
|
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
|
}
|