dsh-deep-ptc-mode 1.7.2 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -2,8 +2,9 @@ import z from '@deepseek-ai/schemastery';
2
2
  import snapshot from './preset.json' with { type: 'json' };
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { normalizePreferences } from './tool-policy.mjs';
5
6
  import { availableEnvironments, BASE_SNAPSHOT, DEFAULT_FOREGROUND_SECONDS, deriveDeepPtc, normalizeDistribution, resolveEnvironment } from './model.mjs';
6
- import { BASE_DECLARATION_SPECIFIER, loadOfficialPreset, parseOfficialExecutors } from './upstream.mjs';
7
+ import { BASE_DECLARATION_SPECIFIER, loadOfficialPreset, loadCurrentPreset, officialPresetUrl, parseOfficialExecutors } from './upstream.mjs';
7
8
  import { importHost, pluginOf, resolveHost } from './host.mjs';
8
9
  import { presetLifecycle } from './lifecycle.mjs';
9
10
 
@@ -19,13 +20,23 @@ export const Config = z.object({
19
20
  hostPlatform: z.const(process.platform).default(process.platform).volatile(),
20
21
  });
21
22
 
22
- function settingsOf(config) {
23
+ // Tool preferences are advice for the model, so a malformed list must not cost the preset.
24
+ function preferencesOf(ctx, config) {
25
+ try {
26
+ return normalizePreferences(config.toolPreferences.get());
27
+ } catch (error) {
28
+ ctx.logger.warn('Deep PTC: ignoring toolPreferences (%s)', error.message);
29
+ return [];
30
+ }
31
+ }
32
+
33
+ function settingsOf(ctx, config) {
23
34
  return {
24
35
  environment: config.environment.get(),
25
36
  wslDistribution: normalizeDistribution(config.wslDistribution.get()),
26
37
  foregroundSeconds: config.foregroundSeconds.get(),
27
38
  toolCompatibility: config.toolCompatibility.get(),
28
- toolPreferences: config.toolPreferences.get(),
39
+ toolPreferences: preferencesOf(ctx, config),
29
40
  compactToolCatalog: config.compactToolCatalog.get(),
30
41
  };
31
42
  }
@@ -63,8 +74,8 @@ async function canExtend(ctx, executor) {
63
74
  // official change is inherited instead of leaving a stale frozen row behind.
64
75
  // The bundled snapshot is only a fallback when the installed declaration
65
76
  // cannot be read or cannot be composed.
66
- async function buildPreset(ctx, config) {
67
- const settings = settingsOf(config);
77
+ async function buildPreset(ctx, config, safeMode) {
78
+ const settings = { ...settingsOf(ctx, config), safeMode };
68
79
  const executors = officialExecutors(ctx);
69
80
  const environment = resolveEnvironment(settings.environment);
70
81
  if (environment === 'wsl' || environment === 'zsh') settings.mappedExecutor = await canExtend(ctx, executors.bash);
@@ -72,7 +83,7 @@ async function buildPreset(ctx, config) {
72
83
  let upstream = snapshot;
73
84
  let source = 'bundled snapshot';
74
85
  try {
75
- const official = loadOfficialPreset();
86
+ const official = await loadCurrentPreset(ctx.agentPresets);
76
87
  upstream = official.preset;
77
88
  source = official.source;
78
89
  } catch (error) {
@@ -94,17 +105,42 @@ async function buildPreset(ctx, config) {
94
105
  }
95
106
 
96
107
  export async function apply(ctx, config) {
108
+ let safeMode = false;
97
109
  const lifecycle = presetLifecycle(
98
110
  definition => ctx.agentPresets.register(definition),
99
- () => buildPreset(ctx, config),
111
+ () => buildPreset(ctx, config, safeMode),
100
112
  error => ctx.logger.error('Deep PTC environment update failed: %s', error.message),
101
113
  );
102
114
  ctx.effect(() => () => lifecycle.dispose());
103
- ctx.on('loader/volatile-update', () => { void lifecycle.refresh().catch(() => {}); });
115
+ // A preset the host refuses to mount would leave its sessions unusable, so fall back to the official
116
+ // composition with the persona. Not awaited: reading the diagnosis waits for the host tree.
117
+ const verify = async () => {
118
+ const row = (await ctx.agentPresets.compositionInventory?.())?.find(candidate => candidate.id === 'deep-ptc');
119
+ if (safeMode || !row?.broken) return;
120
+ ctx.logger.warn('Deep PTC: preset cannot mount (%s); using safe mode', row.broken);
121
+ safeMode = true;
122
+ await lifecycle.refresh();
123
+ };
124
+ const refreshed = () => lifecycle.refresh().then(() => { void verify().catch(() => {}); });
125
+ // Read the installed declarations, not fixture versions. Refresh only when our settings or
126
+ // upstream declaration bytes change. Existing sessions keep their leased preset generation.
127
+ const signature = async () => {
128
+ const read = url => {try{return readFileSync(fileURLToPath(url),'utf8');}catch{return '';}};
129
+ 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));
131
+ };
132
+ let previous=await signature(), detecting=false, active=true;
133
+ const detect = async () => {
134
+ if(detecting||!active)return;detecting=true;
135
+ try {const current=await signature();if(!active||current===previous)return;previous=current;safeMode=false;await refreshed().catch(()=>{});}catch(error){ctx.logger.warn('Deep PTC: upstream detection failed (%s); retaining the active preset',error.message);}finally{detecting=false;}
136
+ };
137
+ ctx.on('loader/volatile-update', detect);
138
+ const upstreamWatch=setInterval(detect,5000);upstreamWatch.unref?.();
139
+ ctx.effect(()=>()=>{active=false;clearInterval(upstreamWatch);});
104
140
  ctx.inject(['settings'], child => {
105
141
  child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
106
142
  });
107
143
  // A failure to publish the preset is reported above; it must not take the
108
144
  // settings service (or the rest of the profile) down with it.
109
- await lifecycle.refresh().catch(() => {});
145
+ await refreshed().catch(() => {});
110
146
  }
package/lib/jobs-tool.mjs CHANGED
@@ -9,6 +9,7 @@ export const Config = z.object({
9
9
  // The official job tool module and its options, as the installed PTC declaration names them.
10
10
  upstream: z.string().required(),
11
11
  options: z.any(),
12
+ overrides: z.any(),
12
13
  });
13
14
 
14
15
  // The official job tools, with job_output waits ending when the user sends a message.
@@ -17,5 +18,5 @@ export async function apply(ctx, config) {
17
18
  await applyOfficial(ctx, config.upstream, config.options, child => adaptContext(child, {
18
19
  tools: tools => registering(tools, definition => definition.name === 'job_output' ? steerableTool(definition) : definition),
19
20
  jobs: jobs => steerableJobs(jobs, watch),
20
- }));
21
+ }), config.overrides);
21
22
  }
package/lib/model.mjs CHANGED
@@ -148,13 +148,6 @@ export function isShellRow(row) {
148
148
  return row.group !== true && (SHELL_ROWS.names.includes(row.name) || SHELL_ROWS.ids.includes(row.id));
149
149
  }
150
150
 
151
- export function isOfficialCapabilityRow(row) {
152
- return row.group !== true && !isShellRow(row) && typeof row.name === 'string'
153
- && !row.name.startsWith('dsh-deep-ptc-mode')
154
- && row.id !== 'persona' && row.name !== '@deepseek-ai/dsh-persona'
155
- && row.id !== 'tool-executor-ptc' && row.name !== '@deepseek-ai/dsh-tool-executor-ptc';
156
- }
157
-
158
151
  function findRow(rows, { ids = [], names = [] }) {
159
152
  let found;
160
153
  walkRows(rows, row => {
@@ -223,6 +216,14 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
223
216
  report.persona = 'replaced';
224
217
  }
225
218
 
219
+ // Safe mode is the official composition plus the persona, for a host where the rest cannot mount.
220
+ if (options.safeMode === true) {
221
+ report.environment = 'official';
222
+ report.skipped.push('safe mode: official composition with the Deep PTC persona');
223
+ return { preset: { ...upstream, id: PRESET_META.id, name: PRESET_META.name, order: PRESET_META.order,
224
+ description: `${PRESET_META.description} 当前为安全模式`, plugins }, report };
225
+ }
226
+
226
227
  // Execution environment: replace the official shell rows (wherever the official preset nests them)
227
228
  // with the selectable execution group in the same place. The group runs the official shell tool
228
229
  // and executor the installed Harness names; when they cannot be mapped, the official rows stay.
@@ -298,22 +299,20 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
298
299
  }
299
300
  const upstreamName = row.name;
300
301
  row.name = target.replacement;
301
- row.config = { upstream: upstreamName, options: { ...(row.config ?? {}), ...target.options(foregroundMs) } };
302
+ row.config = { upstream: upstreamName, ...row.config === undefined ? {} : { options: row.config }, overrides: target.options(foregroundMs) };
302
303
  report.wrapped.push(`${target.key} (${upstreamName})`);
303
304
  }
304
305
 
305
- // Capture provenance without replacing capabilities. New official tools are still loaded from
306
- // the installed declaration; executor selection remains wholly owned by the official PTC row.
307
- walkRows(plugins, row => {
308
- if (!isOfficialCapabilityRow(row)) return;
309
- const upstreamName = row.name;
310
- row.name = 'dsh-deep-ptc-mode/official-tools';
311
- row.config = { upstream: upstreamName, ...row.config === undefined ? {} : { options: row.config } };
306
+ // Official rows stay exactly as declared. Tool discovery learns their tools from these module names.
307
+ const officialModules = [];
308
+ walkRows(upstream.plugins, row => {
309
+ if (row.group === true || typeof row.name !== 'string' || row.disabled === true) return;
310
+ officialModules.push({ name: row.name, ...typeof row.config?.toolName === 'string' ? { toolName: row.config.toolName } : {} });
312
311
  });
313
312
  plugins.push({
314
313
  id: uniqueRowId(plugins, 'tool-compatibility'), name: 'dsh-deep-ptc-mode/tool-compatibility',
315
314
  config: { enabled: options.toolCompatibility !== false, preferences: toolPreferences,
316
- compact: options.compactToolCatalog !== false,
315
+ compact: options.compactToolCatalog !== false, officialModules,
317
316
  sdkProvider: findRow(upstream.plugins, {ids:['tool-executor-ptc'],names:['@deepseek-ai/dsh-tool-executor-ptc']})?.name ?? '@deepseek-ai/dsh-tool-executor-ptc',
318
317
  skillProvider: findRow(upstream.plugins, {ids:['tool-skill'],names:['@deepseek-ai/dsh-tool-skill']})?.name ?? '@deepseek-ai/dsh-tool-skill' },
319
318
  });
@@ -0,0 +1,115 @@
1
+ // Name the tools each composed plugin declares. The host records no owner for a registration, so this
2
+ // reads the installed source of the loader's rows and the preset's official rows. Reading follows every
3
+ // Harness and plugin update without running a module, and a name that cannot be read only stays an
4
+ // unattributed external tool.
5
+ import { readFileSync, statSync } from 'node:fs';
6
+ import { createRequire } from 'node:module';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { resolveHost } from './host.mjs';
9
+
10
+ export const OFFICIAL_SCOPE = '@deepseek-ai/';
11
+ const OWN_PACKAGE = 'dsh-deep-ptc-mode';
12
+ const REFRESH_MS = 1000;
13
+ const DECLARED = /(?:defineTool|tools\.register)\(\{\s*name:\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z_$][\w$]*))/gu;
14
+ const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
15
+
16
+ function identifierValue(source, identifier) {
17
+ const id = escapeRegExp(identifier);
18
+ // `const NAME = "x"`, or a configurable name with its default: `toolName: z.string().default("x")`.
19
+ return new RegExp(`\\b(?:const|let|var)\\s+${id}\\s*=\\s*["']([^"']+)["']`, 'u').exec(source)?.[1]
20
+ ?? new RegExp(`\\b${id}\\b[^\\n;]*?(?:\\.default\\(|\\?\\?\\s*)["']([^"']+)["']`, 'u').exec(source)?.[1];
21
+ }
22
+
23
+ export function toolNamesInSource(source) {
24
+ const names = new Set();
25
+ for (const match of source.matchAll(DECLARED)) {
26
+ const name = match[1] ?? match[2] ?? identifierValue(source, match[3]);
27
+ if (name !== undefined) names.add(name);
28
+ }
29
+ // 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]);
34
+ }
35
+ return names;
36
+ }
37
+
38
+ const sourceCache = new Map();
39
+ function installedSource(moduleName, base) {
40
+ let file;
41
+ if (base !== undefined) {
42
+ try {
43
+ file = createRequire(base).resolve(moduleName);
44
+ } catch {
45
+ // Not installed beside this tree; the runtime's own graph may still hold it.
46
+ }
47
+ }
48
+ if (file === undefined) {
49
+ const url = resolveHost(moduleName);
50
+ if (url !== undefined) file = fileURLToPath(url);
51
+ }
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);}
54
+ return row;
55
+ }
56
+
57
+ /**
58
+ * Attribute tool names to the modules that declare them.
59
+ * @param getLoader - current root loader, whose rows hold the profile's tools.
60
+ * @param modules - the preset's official rows, `{ name, toolName? }`, which the root loader does not list.
61
+ * @param readSource - source reader, replaced in tests.
62
+ * @param base - resolution base for `modules`.
63
+ */
64
+ export function toolDirectory(getLoader, { modules = [], readSource = installedSource, base, refreshMs = REFRESH_MS } = {}) {
65
+ const scanned = new Map();
66
+ const namesIn = (moduleName, rowBase) => {
67
+ const key=moduleName+'\0'+String(rowBase ?? '');
68
+ 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);}
74
+ return cached.names;
75
+ } catch { scanned.delete(key);return new Set(); }
76
+ };
77
+ let view;
78
+ let viewedAt = -Infinity;
79
+ const refresh = () => {
80
+ if (view !== undefined && Date.now() - viewedAt < refreshMs) return view;
81
+ const official = new Set();
82
+ const providers = new Map();
83
+ const add = (name, moduleName, isOfficial) => {
84
+ if (isOfficial) official.add(name);
85
+ if (isOfficial || !providers.has(name)) providers.set(name, moduleName);
86
+ };
87
+ let entries = [];
88
+ try {
89
+ entries = [...getLoader()?.entries?.() ?? []];
90
+ } catch {
91
+ // Attribution is optional; without rows every tool simply stays unattributed.
92
+ }
93
+ for (const entry of entries) {
94
+ const moduleName = entry.options?.name;
95
+ if (entry.disabled || typeof moduleName !== 'string' || moduleName.startsWith('cordis:') || moduleName.startsWith(OWN_PACKAGE)) continue;
96
+ const isOfficial = moduleName.startsWith(OFFICIAL_SCOPE);
97
+ for (const name of namesIn(moduleName, entry.parent?.tree?.ctx?.baseUrl)) add(name, moduleName, isOfficial);
98
+ // Tools named by their row's configuration, such as the subagent tools.
99
+ if (typeof entry.options.config?.toolName === 'string') add(entry.options.config.toolName, moduleName, isOfficial);
100
+ }
101
+ for (const { name: moduleName, toolName } of modules) {
102
+ for (const name of namesIn(moduleName, base)) add(name, moduleName, true);
103
+ if (typeof toolName === 'string') add(toolName, moduleName, true);
104
+ }
105
+ view = { official, providers };
106
+ viewedAt = Date.now();
107
+ return view;
108
+ };
109
+ return {
110
+ isOfficial: name => refresh().official.has(name),
111
+ 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); },
113
+ namesOf: moduleName => namesIn(moduleName, base),
114
+ };
115
+ }
package/lib/rules.mjs CHANGED
@@ -10,12 +10,12 @@ export function reachabilityText(config) {
10
10
 
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
- - Pauses longer than ${MAX_PAUSE_SECONDS} s are refused: sleep or Start-Sleep in foreground commands, and setTimeout, setInterval or sleep inside run_code. Polling one running job more than ${config.maxPollsPerProgram} times in one run_code program is refused.
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
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.`;
15
15
  }
16
16
 
17
17
  // Returns the denial reason for one tool execution, or undefined to allow it.
18
- export function reachabilityGuard(config, jobsOf = () => undefined) {
18
+ export function reachabilityGuard(config, jobsOf = () => undefined, languageOf = () => undefined) {
19
19
  const polls = new Map();
20
20
  const countPoll = (rootCallId, jobId) => {
21
21
  const key = `${rootCallId}\u0000${jobId}`;
@@ -28,13 +28,13 @@ export function reachabilityGuard(config, jobsOf = () => undefined) {
28
28
  return exec => {
29
29
  const args = exec.arguments ?? {};
30
30
  if (SHELL_TOOLS.has(exec.name) && args.run_in_background !== true && typeof args.command === 'string') {
31
- const seconds = shellPauseSeconds(args.command);
31
+ const seconds = shellPauseSeconds(args.command, exec.name === 'pwsh' ? 'powershell' : 'posix');
32
32
  if (seconds > MAX_PAUSE_SECONDS)
33
33
  return `Deep PTC refuses a ${seconds === Infinity ? 'endless' : `${seconds} s`} foreground pause. ${LATER}`;
34
34
  }
35
35
  if (exec.name === 'run_code' && typeof args.code === 'string') {
36
- const issue = programPauseIssue(args.code);
37
- if (issue) return `Deep PTC refuses run_code programs that wait (${issue}; pauses up to ${MAX_PAUSE_SECONDS} s are allowed as numeric literals). ${LATER}`;
36
+ const issue = programPauseIssue(args.code, languageOf());
37
+ if (issue) return `Deep PTC refuses run_code programs that wait (${issue}; pauses up to ${MAX_PAUSE_SECONDS} s are allowed). ${LATER}`;
38
38
  }
39
39
  if (exec.name === 'job_output') {
40
40
  if (args.wait === true && steeringPending(exec.agent))