dsh-deep-ptc-mode 1.7.3 → 1.8.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/lib/index.mjs CHANGED
@@ -1,23 +1,58 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
2
  import snapshot from './preset.json' with { type: 'json' };
3
- import { readFileSync } from 'node:fs';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, readFileSync } from 'node:fs';
4
5
  import { fileURLToPath } from 'node:url';
6
+ import { CREATIVE_PRESET_ID } from './creative.mjs';
5
7
  import { normalizePreferences } from './tool-policy.mjs';
6
8
  import { availableEnvironments, BASE_SNAPSHOT, DEFAULT_FOREGROUND_SECONDS, deriveDeepPtc, normalizeDistribution, resolveEnvironment } from './model.mjs';
7
- import { BASE_DECLARATION_SPECIFIER, loadOfficialPreset, loadCurrentPreset, officialPresetUrl, parseOfficialExecutors } from './upstream.mjs';
9
+ import { discoverShells, resolveShellExecutable, shellNote } from './shells.mjs';
10
+ import { BASE_DECLARATION_SPECIFIER, creativePresetUrl, loadCreativePreset, loadCurrentPreset, officialPresetUrl, parseOfficialExecutors } from './upstream.mjs';
8
11
  import { importHost, pluginOf, resolveHost } from './host.mjs';
9
12
  import { presetLifecycle } from './lifecycle.mjs';
13
+ import { installPresetCompat } from './preset-compat.mjs';
14
+
15
+ function whereExecutable(name) {
16
+ try {
17
+ const command = process.platform === 'win32' ? 'where.exe' : 'which';
18
+ const result = spawnSync(command, [name], { encoding: 'utf8', timeout: 2000, windowsHide: true });
19
+ if (result.status !== 0 || typeof result.stdout !== 'string') return [];
20
+ return result.stdout.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
21
+ } catch {
22
+ return [];
23
+ }
24
+ }
25
+
26
+ const discoveredShells = discoverShells({
27
+ platform: process.platform,
28
+ env: process.env,
29
+ exists: existsSync,
30
+ where: whereExecutable,
31
+ });
32
+
33
+ function shellFamily(environment) {
34
+ return environment === 'powershell' || environment === 'bash' || environment === 'zsh' ? environment : '';
35
+ }
10
36
 
11
37
  export const name = 'deep-ptc-settings';
12
38
  export const inject = ['agentPresets'];
13
39
  export const Config = z.object({
14
40
  environment: z.union(availableEnvironments(process.platform)).default('auto').volatile(),
15
41
  wslDistribution: z.string().pattern(/^(?!\s*-)[^\u0000-\u001f\u007f]*$/u).default('').volatile(),
42
+ shellExecutable: z.string().default('').volatile(),
43
+ pluginLab: z.boolean().default(false).volatile(),
44
+ shellChoices: z.array(z.object({
45
+ id: z.string(), label: z.string(), path: z.string(), family: z.string(),
46
+ })).default(discoveredShells).volatile(),
16
47
  foregroundSeconds: z.number().step(1).min(5).max(600).default(DEFAULT_FOREGROUND_SECONDS).volatile(),
17
48
  toolCompatibility: z.boolean().default(true).volatile(),
18
49
  toolPreferences: z.any().default([]).volatile(),
19
50
  compactToolCatalog: z.boolean().default(true).volatile(),
20
51
  hostPlatform: z.const(process.platform).default(process.platform).volatile(),
52
+ // Session-scoped preset identity compatibility (native id first, base fallback).
53
+ presetCompat: z.boolean().default(true).volatile(),
54
+ presetFallback: z.string().default('ptc').volatile(),
55
+ presetSupport: z.any().default({}).volatile(),
21
56
  });
22
57
 
23
58
  // Tool preferences are advice for the model, so a malformed list must not cost the preset.
@@ -34,6 +69,8 @@ function settingsOf(ctx, config) {
34
69
  return {
35
70
  environment: config.environment.get(),
36
71
  wslDistribution: normalizeDistribution(config.wslDistribution.get()),
72
+ shellExecutable: config.shellExecutable.get(),
73
+ pluginLab: config.pluginLab.get() === true,
37
74
  foregroundSeconds: config.foregroundSeconds.get(),
38
75
  toolCompatibility: config.toolCompatibility.get(),
39
76
  toolPreferences: preferencesOf(ctx, config),
@@ -78,7 +115,32 @@ async function buildPreset(ctx, config, safeMode) {
78
115
  const settings = { ...settingsOf(ctx, config), safeMode };
79
116
  const executors = officialExecutors(ctx);
80
117
  const environment = resolveEnvironment(settings.environment);
81
- if (environment === 'wsl' || environment === 'zsh') settings.mappedExecutor = await canExtend(ctx, executors.bash);
118
+ const family = shellFamily(environment);
119
+ if (family) {
120
+ const requested = typeof settings.shellExecutable === 'string' ? settings.shellExecutable : '';
121
+ const resolved = resolveShellExecutable(requested, { family, discovered: discoveredShells, exists: existsSync });
122
+ if (requested && requested !== 'auto' && !resolved) {
123
+ ctx.logger.warn('Deep PTC: selected shell %s is not available; using the automatic executable', requested);
124
+ }
125
+ settings.shellExecutable = resolved;
126
+ const note = shellNote({ family, executable: resolved });
127
+ if (note) settings.shellNote = note;
128
+ } else {
129
+ settings.shellExecutable = '';
130
+ }
131
+ if (environment === 'wsl' || environment === 'zsh' || (environment === 'bash' && settings.shellExecutable)) {
132
+ settings.mappedExecutor = await canExtend(ctx, executors.bash);
133
+ }
134
+ if (settings.pluginLab && !safeMode) {
135
+ try {
136
+ const creative = await loadCreativePreset(ctx.agentPresets);
137
+ settings.creativePlugins = creative.plugins;
138
+ settings.creativeRoot = creative.root;
139
+ ctx.logger.info('Deep PTC: plugin lab reading %s', creative.source);
140
+ } catch (error) {
141
+ ctx.logger.warn('Deep PTC: creative preset unavailable (%s); plugin lab keeps the PTC tools', error.message);
142
+ }
143
+ }
82
144
  settings.executors = executors;
83
145
  let upstream = snapshot;
84
146
  let source = 'bundled snapshot';
@@ -112,6 +174,18 @@ export async function apply(ctx, config) {
112
174
  error => ctx.logger.error('Deep PTC environment update failed: %s', error.message),
113
175
  );
114
176
  ctx.effect(() => () => lifecycle.dispose());
177
+ // Session-scoped preset identity: report the native deep-ptc id first; an external
178
+ // consumer that does not declare support for it gets the base preset id instead.
179
+ const compat = installPresetCompat(ctx, () => {
180
+ if (config.presetCompat.get() === false) return { enabled: false };
181
+ let support = {};
182
+ try {
183
+ const raw = config.presetSupport.get();
184
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) support = raw;
185
+ } catch { /* keep the empty override list */ }
186
+ return { enabled: true, nativeIds: ['deep-ptc'], fallback: config.presetFallback.get() || 'ptc', support };
187
+ });
188
+ ctx.effect(() => () => compat.dispose(), 'Deep PTC: session-scoped preset identity');
115
189
  // A preset the host refuses to mount would leave its sessions unusable, so fall back to the official
116
190
  // composition with the persona. Not awaited: reading the diagnosis waits for the host tree.
117
191
  const verify = async () => {
@@ -127,7 +201,8 @@ export async function apply(ctx, config) {
127
201
  const signature = async () => {
128
202
  const read = url => {try{return readFileSync(fileURLToPath(url),'utf8');}catch{return '';}};
129
203
  let runtime='';try{runtime=JSON.stringify(await ctx.agentPresets.readDocument?.('ptc'));}catch{}
130
- return JSON.stringify(settingsOf(ctx,config))+'\0'+runtime+'\0'+read(officialPresetUrl())+'\0'+read(resolveHost(BASE_DECLARATION_SPECIFIER));
204
+ let creative='';try{creative=JSON.stringify(await ctx.agentPresets.readDocument?.(CREATIVE_PRESET_ID));}catch{}
205
+ return JSON.stringify(settingsOf(ctx,config))+'\0'+runtime+'\0'+creative+'\0'+read(officialPresetUrl())+'\0'+read(resolveHost(BASE_DECLARATION_SPECIFIER))+'\0'+read(creativePresetUrl());
131
206
  };
132
207
  let previous=await signature(), detecting=false, active=true;
133
208
  const detect = async () => {
package/lib/jobs-tool.mjs CHANGED
File without changes
package/lib/lab.mjs ADDED
@@ -0,0 +1,13 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+
3
+ export const name = 'deep-ptc-plugin-lab';
4
+ export const inject = ['systemPrompt'];
5
+ export const Config = z.object({});
6
+
7
+ const text = `Plugin lab is on for this Deep PTC session.
8
+ Inspect the live composition, define a syntax-checked package, then run it only through the host approval. Packages stay in memory for this process. They do not write the repository, shipped presets, the desktop composition, or this plugin's source.
9
+ Do not bypass or weaken approval. If a lab tool is missing or fails, continue with the official PTC tools.`;
10
+
11
+ export function apply(ctx) {
12
+ ctx.systemPrompt.section({ name: 'deep-ptc:plugin-lab', order: 10192, text });
13
+ }
package/lib/lifecycle.mjs CHANGED
File without changes
package/lib/model.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  // never leaves a stale module name behind.
9
9
  import snapshot from './preset.json' with { type: 'json' };
10
10
  import baseSnapshot from './base-snapshot.json' with { type: 'json' };
11
+ import { creativeAdditions } from './creative.mjs';
11
12
  import { normalizePreferences } from './tool-policy.mjs';
12
13
 
13
14
  export const ENVIRONMENTS = ['auto', 'wsl', 'powershell', 'zsh', 'bash'];
@@ -34,14 +35,16 @@ export function normalizeDistribution(value = '') {
34
35
  return distribution;
35
36
  }
36
37
 
37
- export function shellArgv(environment, spec, distribution = '', platform = process.platform) {
38
+ export function shellArgv(environment, spec, distribution = '', platform = process.platform, executable = '') {
38
39
  if (environment === 'wsl') {
39
40
  if (platform !== 'win32') throw new Error('WSL requires a Windows host');
40
41
  const distro = normalizeDistribution(distribution);
41
42
  return ['wsl.exe', ...(distro ? ['--distribution', distro] : []),
42
43
  '--cd', spec.workdir, '--exec', 'bash', '-lc', spec.command];
43
44
  }
44
- if (environment === 'zsh') return [platform === 'darwin' ? '/bin/zsh' : 'zsh', '-lc', spec.command];
45
+ const binary = typeof executable === 'string' ? executable : '';
46
+ if (environment === 'zsh') return [binary || (platform === 'darwin' ? '/bin/zsh' : 'zsh'), '-lc', spec.command];
47
+ if (environment === 'bash' && binary) return [binary, '-c', spec.command];
45
48
  throw new Error(`No mapped executor for ${environment}`);
46
49
  }
47
50
 
@@ -51,7 +54,7 @@ export function assertExecutionPolicy(environment, policy) {
51
54
  }
52
55
  }
53
56
 
54
- export function environmentText(environment, distribution = '') {
57
+ export function environmentText(environment, distribution = '', note = '') {
55
58
  const descriptions = {
56
59
  wsl: `Execution environment: WSL Bash${distribution ? ` (${distribution})` : ' (Windows default distribution)'}. The bash tool runs POSIX source via wsl.exe and bash -lc. File tools and the tool workdir use Windows host paths; Linux paths belong inside command source. WSL is available only in danger-full-access; a confined call fails without execution. Never silently fall back to PowerShell or another distribution.`,
57
60
  powershell: 'Execution environment: native Windows PowerShell. Use the pwsh tool and PowerShell syntax, native Windows paths and $env:NAME. This selection takes precedence over older workspace guidance that assumed WSL. The configured sandbox and approval policy still apply.',
@@ -59,7 +62,7 @@ export function environmentText(environment, distribution = '') {
59
62
  bash: 'Execution environment: native Bash on macOS/Linux. Use the bash tool with Bash/POSIX command source and native host paths. This is not WSL. The configured sandbox and approval policy still apply.',
60
63
  };
61
64
  if (!descriptions[environment]) throw new Error(`Unknown environment ${environment}`);
62
- return descriptions[environment];
65
+ return typeof note === 'string' && note !== '' ? `${descriptions[environment]}\n${note}` : descriptions[environment];
63
66
  }
64
67
 
65
68
  export const DEFAULT_FOREGROUND_SECONDS = 30;
@@ -148,6 +151,17 @@ export function isShellRow(row) {
148
151
  return row.group !== true && (SHELL_ROWS.names.includes(row.name) || SHELL_ROWS.ids.includes(row.id));
149
152
  }
150
153
 
154
+ // The desktop already mounts this host service. Copying it into the session would start a second one.
155
+ function isHostRunner(row) {
156
+ return row?.id === 'dynamicCordisRunner'
157
+ || (typeof row?.name === 'string' && row.name.includes('cordis-host-runner'));
158
+ }
159
+
160
+ function chosenExecutable(environment, value) {
161
+ if (environment !== 'powershell' && environment !== 'bash' && environment !== 'zsh') return '';
162
+ return typeof value === 'string' ? value.trim() : '';
163
+ }
164
+
151
165
  function findRow(rows, { ids = [], names = [] }) {
152
166
  let found;
153
167
  walkRows(rows, row => {
@@ -231,7 +245,8 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
231
245
  const executors = { ...BASE_SNAPSHOT, ...(options.executors ?? {}) };
232
246
  const tool = findRow(plugins, SHELL_TOOLS[kind]);
233
247
  const official = executors[kind];
234
- const mapped = environment === 'wsl' || environment === 'zsh';
248
+ const shellPath = chosenExecutable(environment, options.shellExecutable);
249
+ const mapped = environment === 'wsl' || environment === 'zsh' || (environment === 'bash' && shellPath !== '');
235
250
  const unusable = tool === undefined ? `the official PTC preset has no ${kind} tool row`
236
251
  : typeof official?.name !== 'string' ? `the installed Harness declares no ${kind} executor`
237
252
  : mapped && options.mappedExecutor === false ? `the official bash executor cannot be extended for ${environment}`
@@ -264,9 +279,11 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
264
279
  // With background jobs available, the executor timeout only decides when a foreground command
265
280
  // moves to the background; the official tools run such commands with onExpiry: none.
266
281
  const executorOptions = { ...(official.config ?? {}), timeoutMs: foregroundMs, maxTimeoutMs: foregroundMs };
282
+ if (environment === 'powershell' && shellPath) executorOptions.pwshPath = shellPath;
267
283
  const executor = mapped
268
284
  ? { id: 'executor', name: 'dsh-deep-ptc-mode/executor',
269
- config: { environment, wslDistribution: distribution, base: official.name, options: executorOptions } }
285
+ config: { environment, wslDistribution: distribution, base: official.name, options: executorOptions,
286
+ ...shellPath ? { shellExecutable: shellPath } : {} } }
270
287
  : { id: 'executor', name: official.name, config: executorOptions };
271
288
  const terminal = {
272
289
  id: environment === 'zsh' ? 'tool-zsh' : tool.id ?? `tool-${kind}`,
@@ -280,7 +297,8 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
280
297
  rows.push({
281
298
  id: uniqueRowId(plugins, 'execution'), name: 'cordis:group', group: true, isolate: { shell: true },
282
299
  config: [executor, terminal, { id: 'execution-instructions', name: 'dsh-deep-ptc-mode/environment',
283
- config: { environment, wslDistribution: distribution } }],
300
+ config: { environment, wslDistribution: distribution,
301
+ ...typeof options.shellNote === 'string' && options.shellNote !== '' ? { shellNote: options.shellNote } : {} } }],
284
302
  });
285
303
  }
286
304
  rows.push({
@@ -317,6 +335,15 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
317
335
  skillProvider: findRow(upstream.plugins, {ids:['tool-skill'],names:['@deepseek-ai/dsh-tool-skill']})?.name ?? '@deepseek-ai/dsh-tool-skill' },
318
336
  });
319
337
 
338
+ if (options.pluginLab === true) {
339
+ const additions = creativeAdditions(options.creativePlugins, plugins, {
340
+ root: typeof options.creativeRoot === 'string' ? options.creativeRoot : '',
341
+ }).filter(row => !isHostRunner(row));
342
+ plugins.push(...additions);
343
+ plugins.push({ id: uniqueRowId(plugins, 'plugin-lab'), name: 'dsh-deep-ptc-mode/lab' });
344
+ report.pluginLab = additions.map(row => `${row.id} (${row.name})`);
345
+ }
346
+
320
347
  const description = `${PRESET_META.description} 当前环境:${environment}${environment === 'wsl' && distribution ? ` (${distribution})` : ''}`;
321
348
  return {
322
349
  preset: {
File without changes
@@ -0,0 +1,283 @@
1
+ // Deep PTC owns a session-scoped preset identity compatibility layer.
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.
17
+ //
18
+ // Host internals that must keep the exact identity (subagent child headers, scheduled
19
+ // session creation, the registry itself) are recognised from the immediate frames.
20
+ import { appendFileSync, readFileSync, readdirSync, statSync } from 'node:fs';
21
+ import { dirname, join, parse } from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+
24
+ export const name = 'deep-ptc-preset-compat';
25
+ export const inject = ['agentPresets'];
26
+
27
+ 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;
29
+ const SELF = 'preset-compat.mjs';
30
+ const CODE_EXTENSIONS = ['.mjs', '.cjs', '.js', '.mts', '.cts', '.ts'];
31
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'docs', 'test', 'tests']);
32
+ const MAX_FILES = 800;
33
+ const MAX_FILE_BYTES = 1024 * 1024;
34
+ const MAX_TOTAL_BYTES = 8 * 1024 * 1024;
35
+ const LOG = 'C:/Users/13987/.dsh/tmp/deep-ptc-preset-compat.log';
36
+
37
+ const packageCache = new Map();
38
+ const callerCache = new Map();
39
+ const logged = new Set();
40
+
41
+ function log(line) {
42
+ try { appendFileSync(LOG, line + '\n'); } catch { /* diagnostics only */ }
43
+ }
44
+
45
+ function fileOf(value) {
46
+ try {
47
+ const file = value.startsWith('file:') ? fileURLToPath(value) : value;
48
+ // fileURLToPath yields /C:/... under a POSIX runtime and C:\... on Windows.
49
+ return /^\/[A-Za-z]:[\\/]/u.test(file) ? file.slice(1) : file;
50
+ } catch { return ''; }
51
+ }
52
+
53
+ function isCodeFile(name) {
54
+ return CODE_EXTENSIONS.some(extension => name.endsWith(extension));
55
+ }
56
+
57
+ function isNumber(text) {
58
+ return text.length > 0 && Number.isFinite(Number(text)) && /^[0-9]+$/u.test(text);
59
+ }
60
+
61
+ /** First stack frame outside this module, as an absolute file path. */
62
+ export function callerFile(stack) {
63
+ for (const raw of String(stack ?? '').split('\n').slice(1)) {
64
+ if (raw.includes(SELF)) continue;
65
+ // Cordis service proxies insert one infrastructure frame (Object.apply in the
66
+ // host's cordis package) between this wrapper and the real caller. Skip it so
67
+ // the caller's own package, not the proxy, decides the layer.
68
+ if (raw.includes('@deepseek-ai/cordis/')) continue;
69
+ let text = raw.trim();
70
+ if (text.startsWith('at ')) text = text.slice(3).trim();
71
+ if (text.startsWith('async ')) text = text.slice(6).trim();
72
+ const open = text.lastIndexOf('(');
73
+ if (open !== -1 && text.endsWith(')')) text = text.slice(open + 1, -1);
74
+ const parts = text.split(':');
75
+ if (parts.length < 3) continue;
76
+ const col = parts.pop();
77
+ const line = parts.pop();
78
+ if (!isNumber(line) || !isNumber(col)) continue;
79
+ const file = fileOf(parts.join(':'));
80
+ if (file) return file;
81
+ }
82
+ return '';
83
+ }
84
+
85
+ /** Nearest ancestor package.json carrying a name. */
86
+ export function packageOf(file) {
87
+ let dir = dirname(file);
88
+ const { root } = parse(dir);
89
+ for (let depth = 0; depth < 12 && dir && dir !== root; depth++) {
90
+ try {
91
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
92
+ if (manifest && typeof manifest.name === 'string') return { root: dir, name: manifest.name };
93
+ } catch { /* keep walking */ }
94
+ const parent = dirname(dir);
95
+ if (parent === dir) break;
96
+ dir = parent;
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ const GATE_MARKERS = [
102
+ 'MODE_PRESET',
103
+ "=== 'ptc'", '=== "ptc"', "!== 'ptc'", '!== "ptc"',
104
+ "=== 'standard'", '=== "standard"', "=== 'cordis'", '=== "cordis"',
105
+ "=== 'minimal'", '=== "minimal"',
106
+ "case 'ptc'", 'case "ptc"',
107
+ ".includes('ptc')", '.includes("ptc")',
108
+ ];
109
+
110
+ const CREATIVE_PRESET_ID = 'cordis';
111
+ const KNOWN_PRESET_IDS = ['deep-ptc', CREATIVE_PRESET_ID, 'ptc', 'standard', 'minimal'];
112
+
113
+ function presetRestricted(text) {
114
+ return GATE_MARKERS.some(marker => text.includes(marker));
115
+ }
116
+
117
+ /** Quoted preset ids this code mentions; the base id a restricted plugin accepts. */
118
+ function acceptedPresetIds(text) {
119
+ const found = [];
120
+ for (const id of KNOWN_PRESET_IDS) {
121
+ if (text.includes("'" + id + "'") || text.includes('"' + id + '"')) found.push(id);
122
+ }
123
+ return found;
124
+ }
125
+
126
+ /**
127
+ * Probe one plugin package for the two identity layers. Bounded and cached.
128
+ * @param root - package root.
129
+ * @param nativeId - the native preset id, normally deep-ptc.
130
+ * @returns declares: the package knows the native id; restricted: the package gates on preset ids.
131
+ */
132
+ export function packageProbe(root, nativeId) {
133
+ const key = root + '|' + nativeId;
134
+ if (packageCache.has(key)) return packageCache.get(key);
135
+ let files = 0;
136
+ let bytes = 0;
137
+ const result = { declares: false, restricted: false, accepts: [] };
138
+ const accepts = new Set();
139
+ const visit = directory => {
140
+ if (result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES) return;
141
+ let entries;
142
+ try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return; }
143
+ for (const entry of entries) {
144
+ if (result.declares || files >= MAX_FILES || bytes >= MAX_TOTAL_BYTES) return;
145
+ if (entry.name.startsWith('.')) continue;
146
+ const full = join(directory, entry.name);
147
+ if (entry.isDirectory()) {
148
+ if (!SKIP_DIRS.has(entry.name)) visit(full);
149
+ continue;
150
+ }
151
+ if (!entry.isFile() || !isCodeFile(entry.name)) continue;
152
+ let size = 0;
153
+ try { size = statSync(full).size; } catch { continue; }
154
+ if (size <= 0 || size > MAX_FILE_BYTES) continue;
155
+ let text;
156
+ try { text = readFileSync(full, 'utf8'); } catch { continue; }
157
+ if (text.includes(nativeId)) result.declares = true;
158
+ if (presetRestricted(text)) result.restricted = true;
159
+ for (const id of acceptedPresetIds(text)) accepts.add(id);
160
+ files += 1;
161
+ bytes += size;
162
+ }
163
+ };
164
+ visit(root);
165
+ result.accepts = [...accepts];
166
+ packageCache.set(key, result);
167
+ return result;
168
+ }
169
+
170
+ /**
171
+ * Resolve the identity one external consumer should see.
172
+ * @param exact - the live composed preset id.
173
+ * @param options - enabled, nativeIds, fallback, creativeFallback and support overrides.
174
+ * @param info - host flag, package name and declaration probe result.
175
+ * @returns the id to report.
176
+ */
177
+ export function decidePresetId(exact, options = {}, info = {}) {
178
+ const nativeIds = Array.isArray(options.nativeIds) && options.nativeIds.length > 0
179
+ ? options.nativeIds : ['deep-ptc'];
180
+ if (typeof exact !== 'string' || !nativeIds.includes(exact)) return exact;
181
+ if (options.enabled === false) return exact;
182
+ if (info.host === true) return exact;
183
+ const support = options.support && typeof options.support === 'object' && !Array.isArray(options.support)
184
+ ? options.support : {};
185
+ const override = info.packageName === undefined ? undefined : support[info.packageName];
186
+ if (override === 'native') return exact;
187
+ const fallback = options.fallback || 'ptc';
188
+ if (override === 'base') return fallback;
189
+ // Layer 1: a plugin that does not limit preset names, or that declares the native
190
+ // id itself, keeps deep-ptc.
191
+ if (info.declares === true) return exact;
192
+ if (info.restricted !== true) return exact;
193
+ // Layer 2: a plugin that limits preset names gets a base id. ptc is the normal
194
+ // base; a creative-mode row mounted by the plugin lab may accept only cordis,
195
+ // so use the id its own code actually mentions.
196
+ const accepts = Array.isArray(info.accepts) ? info.accepts : [];
197
+ if (accepts.includes(fallback)) return fallback;
198
+ if (accepts.includes(CREATIVE_PRESET_ID)) return CREATIVE_PRESET_ID;
199
+ return fallback;
200
+ }
201
+
202
+ /** Inspect one call: host frame, or the calling plugin package and its declaration. */
203
+ export function inspectCaller(stack, nativeId) {
204
+ const head = String(stack ?? '').split('\n').slice(0, 4).join('\n');
205
+ if (HOST_CALLERS.test(head)) return { host: true };
206
+ const file = callerFile(stack);
207
+ if (!file) return { host: true };
208
+ if (file.includes('app.asar')) return { host: true };
209
+ if (callerCache.has(file)) return callerCache.get(file);
210
+ const pkg = packageOf(file);
211
+ if (pkg === undefined) return { host: true };
212
+ if (pkg.name.startsWith('@deepseek-ai/')) return { host: true };
213
+ const probe = packageProbe(pkg.root, nativeId);
214
+ const info = { host: false, packageName: pkg.name, packageRoot: pkg.root, declares: probe.declares, restricted: probe.restricted, accepts: probe.accepts };
215
+ callerCache.set(file, info);
216
+ return info;
217
+ }
218
+
219
+ function logDecision(info, id) {
220
+ if (!info || typeof info.packageName !== 'string') return;
221
+ const key = info.packageName + '|' + id;
222
+ if (logged.has(key)) return;
223
+ logged.add(key);
224
+ log('decision ' + new Date().toISOString() + ' ' + info.packageName + ' -> ' + id + (info.declares ? ' (declares native)' : info.restricted ? ' (preset restricted -> ' + id + ')' : ' (unrestricted -> native)'));
225
+ }
226
+
227
+ /**
228
+ * Install the identity layer on the live registry. Idempotent: a second mount
229
+ * (plugin startup plus an explicit compatibility row) keeps the first owner and
230
+ * becomes a no-op.
231
+ * @param ctx - plugin context carrying agentPresets.
232
+ * @param options - options object or a getter returning one.
233
+ * @returns owner handle; dispose() restores the unpatched method.
234
+ */
235
+ export function installPresetCompat(ctx, options) {
236
+ const registry = ctx?.agentPresets;
237
+ const current = registry?.composedPreset;
238
+ if (typeof current !== 'function') {
239
+ log('skip ' + new Date().toISOString() + ': agentPresets.composedPreset unavailable');
240
+ return { active: false, owner: false, dispose() {} };
241
+ }
242
+ if (current[PATCH_MARK] === true) return { active: true, owner: false, dispose() {} };
243
+ const hadOwn = Object.hasOwn(registry, 'composedPreset');
244
+ const original = current;
245
+ const patched = function composedPreset(agentCtx) {
246
+ const exact = original.call(registry, agentCtx);
247
+ const now = typeof options === 'function' ? options() : options;
248
+ if (!now || now.enabled === false) return exact;
249
+ const nativeIds = Array.isArray(now.nativeIds) && now.nativeIds.length > 0 ? now.nativeIds : ['deep-ptc'];
250
+ if (typeof exact !== 'string' || !nativeIds.includes(exact)) return exact;
251
+ // A failed probe means 'does not declare the native id', so the consumer still
252
+ // receives the usable base id instead of losing the plugin surface.
253
+ let info = { host: false, declares: false, restricted: true };
254
+ try { info = inspectCaller(new Error().stack ?? '', nativeIds[0]); } catch (error) { log('inspect-error ' + error.message); }
255
+ const id = decidePresetId(exact, now, info);
256
+ logDecision(info, id);
257
+ return id;
258
+ };
259
+ Object.defineProperty(patched, PATCH_MARK, { value: true });
260
+ Object.defineProperty(registry, 'composedPreset', { value: patched, configurable: true, writable: true });
261
+ log('installed ' + new Date().toISOString());
262
+ return {
263
+ active: true,
264
+ owner: true,
265
+ dispose() {
266
+ if (registry.composedPreset !== patched) return;
267
+ if (hadOwn) Object.defineProperty(registry, 'composedPreset', { value: original, configurable: true, writable: true });
268
+ else delete registry.composedPreset;
269
+ log('disposed ' + new Date().toISOString());
270
+ },
271
+ };
272
+ }
273
+
274
+ // Compatibility row entry: mount the same layer explicitly (idempotent).
275
+ export function apply(ctx, config) {
276
+ const compat = installPresetCompat(ctx, {
277
+ enabled: true,
278
+ nativeIds: ['deep-ptc'],
279
+ fallback: config?.fallback ?? 'ptc',
280
+ support: config?.support && typeof config.support === 'object' ? config.support : {},
281
+ });
282
+ ctx.effect(() => () => compat.dispose(), 'Deep PTC: preset identity compatibility');
283
+ }
package/lib/preset.json CHANGED
File without changes
package/lib/reachable.mjs CHANGED
File without changes
@@ -0,0 +1,27 @@
1
+ // Which external tools stay in the initial PTC SDK and are never quarantined.
2
+ // Any plugin can opt in with `resident: true`. Screen-control tools are recognised
3
+ // from their own definition or provider string, not from a pinned package list.
4
+
5
+ const SCREEN_NAMES = new Set(['intent', 'collect', 'tap_xy']);
6
+ const PROVIDER_MARK = /dsh-go|screen-control|computer-use|phone-control/iu;
7
+
8
+ function presentationOf(definition) {
9
+ const presentation = definition.presentationMeta ?? definition.presentation;
10
+ return presentation && typeof presentation === 'object' ? presentation : undefined;
11
+ }
12
+
13
+ /**
14
+ * @param {object | null | undefined} definition live tool definition
15
+ * @param {string} [provider] module or plugin that declared it
16
+ * @returns {boolean}
17
+ */
18
+ export function staysResident(definition, provider = '') {
19
+ if (!definition || typeof definition !== 'object') return false;
20
+ if (definition.resident === true || definition.deepPtc?.resident === true) return true;
21
+ const presentation = presentationOf(definition);
22
+ if (presentation && Object.prototype.hasOwnProperty.call(presentation, 'dsh-go/view')) return true;
23
+ const name = typeof definition.name === 'string' ? definition.name : '';
24
+ if (SCREEN_NAMES.has(name) || name.startsWith('screen_')) return true;
25
+ const owner = `${provider}\n${typeof definition.deepPtc?.provider === 'string' ? definition.deepPtc.provider : ''}`;
26
+ return PROVIDER_MARK.test(owner);
27
+ }
package/lib/rules.mjs CHANGED
File without changes