dsh-deep-ptc-mode 1.7.2 → 1.7.4

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/client.js CHANGED
@@ -10,6 +10,9 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
10
10
  wsl: 'WSL Bash(Windows)', powershell: 'PowerShell(Windows)',
11
11
  zsh: 'Zsh(macOS / Linux)', bash: '原生 Bash(macOS / Linux)',
12
12
  distribution: 'WSL 发行版', distributionHint: '留空使用 Windows 的默认发行版,例如 Ubuntu。',
13
+ shell: 'Shell 版本', shellAuto: '自动(沿用官方查找顺序)',
14
+ shellHint: '只列出本机已发现的常见版本。文件消失后自动回退。WSL 仍只选择发行版。',
15
+ pluginLab: '插件实验台', pluginLabHint: '默认关闭。打开后在内存中检查、定义并经宿主批准后运行插件,不改已发布预设,也不绕过批准。',
13
16
  sessions: '保存后请新建一个“深度PTC模式”会话。已有会话与后台任务保留原环境。',
14
17
  wslHint: 'WSL 暂不支持 Windows 的受限沙箱;受限调用会明确失败,不会自动切换或绕过限制。',
15
18
  save: '保存', saving: '保存中…', saved: '已保存,新会话将使用所选环境。',
@@ -22,6 +25,9 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
22
25
  wsl: 'WSL Bash (Windows)', powershell: 'PowerShell (Windows)',
23
26
  zsh: 'Zsh (macOS / Linux)', bash: 'Native Bash (macOS / Linux)',
24
27
  distribution: 'WSL distribution', distributionHint: 'Leave blank for the Windows default distribution, for example Ubuntu.',
28
+ shell: 'Shell version', shellAuto: 'Automatic (official lookup)',
29
+ shellHint: 'Lists common executables found on this machine. A missing file falls back to automatic. WSL still selects a distribution only.',
30
+ pluginLab: 'Plugin lab', pluginLabHint: 'Off by default. When on, inspect, define and run plugins in memory through host approval. Shipped presets stay unchanged.',
25
31
  sessions: 'After saving, create a new Deep PTC session. Existing sessions and background jobs keep their environment.',
26
32
  wslHint: 'WSL does not support the confined Windows sandbox. Confined calls fail without execution or fallback.',
27
33
  save: 'Save', saving: 'Saving…', saved: 'Saved. New sessions will use this environment.',
@@ -36,6 +42,8 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
36
42
  const state = React.useSyncExternalStore(subscribe, read, read);
37
43
  const [environment, setEnvironment] = React.useState('auto');
38
44
  const [distribution, setDistribution] = React.useState('');
45
+ const [shellExecutable, setShellExecutable] = React.useState('');
46
+ const [pluginLab, setPluginLab] = React.useState(false);
39
47
  const [saving, setSaving] = React.useState(false);
40
48
  const [message, setMessage] = React.useState('');
41
49
  const [failed, setFailed] = React.useState(false);
@@ -45,6 +53,8 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
45
53
  if (!state.value || dirty.current) return;
46
54
  setEnvironment(state.value.environment);
47
55
  setDistribution(state.value.wslDistribution ?? '');
56
+ setShellExecutable(state.value.shellExecutable ?? '');
57
+ setPluginLab(state.value.pluginLab === true);
48
58
  draftRevision.current = state.revision;
49
59
  }, [state.value, state.revision]);
50
60
  if (view === 'summary') return t('summary');
@@ -64,6 +74,8 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
64
74
  const ok = await form.mutate([
65
75
  { op: 'set', path: ['environment'], value: environment },
66
76
  { op: 'set', path: ['wslDistribution'], value: distribution.trim() },
77
+ { op: 'set', path: ['shellExecutable'], value: shellExecutable },
78
+ { op: 'set', path: ['pluginLab'], value: pluginLab },
67
79
  ], draftRevision.current);
68
80
  if (!ok) throw new Error('Configuration was rejected');
69
81
  dirty.current = false;
@@ -71,12 +83,20 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
71
83
  draftRevision.current = latest.revision;
72
84
  setEnvironment(latest.value?.environment ?? environment);
73
85
  setDistribution(latest.value?.wslDistribution ?? distribution.trim());
86
+ setShellExecutable(latest.value?.shellExecutable ?? shellExecutable);
87
+ setPluginLab(latest.value?.pluginLab === true);
74
88
  setMessage(t('saved'));
75
89
  } catch {
76
90
  draftRevision.current = form.getSnapshot().revision;
77
91
  setFailed(true); setMessage(t('failed'));
78
92
  } finally { setSaving(false); }
79
93
  }
94
+ const effective = environment === 'auto'
95
+ ? (state.value.hostPlatform === 'win32' ? 'powershell' : state.value.hostPlatform === 'darwin' ? 'zsh' : 'bash')
96
+ : environment;
97
+ const choices = (Array.isArray(state.value.shellChoices) ? state.value.shellChoices : [])
98
+ .filter(item => item && item.family === effective && typeof item.id === 'string');
99
+ const showShell = effective !== 'wsl' && choices.length > 0;
80
100
  const control = { width: '100%', padding: '8px 10px', borderRadius: '6px',
81
101
  color: 'inherit', background: 'var(--dsw-alias-bg-base)', border: '1px solid var(--dsw-alias-border-l1)' };
82
102
  return h('form', { onSubmit: save, style: { display: 'grid', gap: '12px', maxWidth: '600px' } },
@@ -90,6 +110,18 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
90
110
  h('input', { id: 'deep-ptc-distribution', value: distribution, disabled, style: control,
91
111
  onChange: event => { changed(); setDistribution(event.target.value); } }),
92
112
  h('p', null, t('distributionHint')), h('p', null, t('wslHint'))) : null,
113
+ showShell ? h(React.Fragment, null,
114
+ h('label', { htmlFor: 'deep-ptc-shell' }, t('shell')),
115
+ h('select', { id: 'deep-ptc-shell', value: shellExecutable, disabled, style: control,
116
+ onChange: event => { changed(); setShellExecutable(event.target.value); } },
117
+ h('option', { value: '' }, t('shellAuto')),
118
+ ...choices.map(item => h('option', { key: item.id, value: item.id }, item.label))),
119
+ h('p', null, t('shellHint'))) : null,
120
+ h('label', { htmlFor: 'deep-ptc-plugin-lab' },
121
+ h('input', { id: 'deep-ptc-plugin-lab', type: 'checkbox', checked: pluginLab, disabled,
122
+ onChange: event => { changed(); setPluginLab(event.target.checked); } }),
123
+ ' ', t('pluginLab')),
124
+ h('p', null, t('pluginLabHint')),
93
125
  h('p', null, t('sessions')),
94
126
  !state.writable ? h('p', { role: 'status' }, t('readOnly')) : null,
95
127
  message ? h('p', { role: failed ? 'alert' : 'status' }, message) : null,
@@ -98,13 +130,17 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
98
130
  }
99
131
 
100
132
  function ToolStateControls({ useProjection, reset, t }) {
101
- const preset = useProjection('agentPreset');
102
- const state = useProjection('deepPtcTools');
103
133
  const [busy, setBusy] = React.useState(false);
104
134
  const [message, setMessage] = React.useState('');
105
135
  const generation = React.useRef(0);
106
136
  React.useEffect(() => { generation.current++; setBusy(false); setMessage(''); return () => { generation.current++; }; }, [reset]);
107
- if (preset !== 'deep-ptc' || !state) return null;
137
+ let preset, state;
138
+ try {
139
+ if (typeof useProjection !== 'function') return null;
140
+ preset = useProjection('agentPreset');
141
+ state = useProjection('deepPtcTools');
142
+ } catch { return null; }
143
+ if (preset !== 'deep-ptc' || !state || typeof state !== 'object') return null;
108
144
  const failed = state?.report?.tools ?? [];
109
145
  async function reload() {
110
146
  const current = generation.current;
@@ -112,10 +148,12 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
112
148
  try {
113
149
  const outcome = await reset();
114
150
  if (current !== generation.current) return;
115
- const result = outcome?.result ?? outcome;
151
+ if (outcome?.ok === false) throw new Error(outcome.error?.message || t('toolResetFailed'));
152
+ const reply = outcome?.ok === true ? outcome.value : outcome;
153
+ const result = reply?.result ?? reply;
116
154
  if (result?.kind !== 'success') throw new Error(result?.text || t('toolResetFailed'));
117
155
  setMessage(t('toolResetDone'));
118
- } catch (error) { if (current === generation.current) setMessage(t('toolResetFailed')); }
156
+ } catch (error) { if (current === generation.current) setMessage(t('toolResetFailed') + ': ' + String(error?.message ?? error).slice(0,220)); }
119
157
  finally { if (current === generation.current) setBusy(false); }
120
158
  }
121
159
  return h('div', { style: { display: 'grid', gap: '4px', padding: '4px 0', fontSize: '12px' } },
@@ -146,10 +184,22 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
146
184
  name: 'plugins.item', id: 'deep-ptc', order: 41,
147
185
  label: () => t('title'), locale: 'deep-ptc',
148
186
  }, props => h(Card, { ...props, form, t })))));
149
- ctx.inject?.(['remote.commands'], child => child.slots.inject('conversation.composer.dock', () => child.slots.register({
150
- name: 'conversation.composer.dock', id: 'deep-ptc-tool-states', order: 90,
151
- inject: sessionId => ({ reset: () => child.remote.commands.execute(sessionId, '/deep-ptc-reset-tools', []) }),
152
- }, props => h(ToolStateControls, { ...props, t }))));
187
+ try {
188
+ ctx.inject?.(['remote', 'remote.commands'], child => {
189
+ try {
190
+ child.slots.inject('conversation.composer.dock', () => child.slots.register({
191
+ name: 'conversation.composer.dock', id: 'deep-ptc-tool-states', order: 90,
192
+ inject: sessionId => ({
193
+ reset: () => {
194
+ const execute = child.remote?.commands?.execute;
195
+ if (typeof execute !== 'function') return Promise.resolve({ ok: false, error: { message: 'unavailable' } });
196
+ return execute(sessionId, '/deep-ptc-reset-tools', []);
197
+ },
198
+ }),
199
+ }, props => h(ToolStateControls, { ...props, t })));
200
+ } catch { /* a broken dock must not take the composer with it */ }
201
+ });
202
+ } catch { /* the composer stays usable when this slot cannot register */ }
153
203
  }
154
204
  return { apply, inject };
155
205
  } });
@@ -0,0 +1,127 @@
1
+ // Rows the official creative-mode preset adds beyond the preset Deep PTC is
2
+ // derived from. Module names are copied from that declaration. A renamed
3
+ // official package is followed because this file never names one.
4
+ import { join } from 'node:path';
5
+
6
+ /** Shipped preset id, the same kind of lookup key as `ptc`. Not a module name. */
7
+ export const CREATIVE_PRESET_ID = 'cordis';
8
+
9
+ function text(value) {
10
+ return typeof value === 'string' ? value : '';
11
+ }
12
+
13
+ /**
14
+ * Pick the creative preset from a live roster.
15
+ * The published name wins, then the shipped id, then a description that says so.
16
+ * @param {Array<{ id?: string, name?: string, description?: string }>} roster
17
+ */
18
+ export function selectCreativePreset(roster) {
19
+ const rows = Array.isArray(roster) ? roster.filter(row => row && typeof row === 'object') : [];
20
+ return rows.find(row => row.name === '创造模式')
21
+ ?? rows.find(row => row.id === CREATIVE_PRESET_ID)
22
+ ?? rows.find(row => text(row.description).includes('创造'));
23
+ }
24
+
25
+ function isPersona(row) {
26
+ return row?.id === 'persona' || (typeof row?.name === 'string' && row.name.includes('dsh-persona'));
27
+ }
28
+
29
+ function walk(rows, visit) {
30
+ if (!Array.isArray(rows)) return;
31
+ for (const row of rows) {
32
+ if (!row || typeof row !== 'object') continue;
33
+ visit(row);
34
+ if (row.group === true && Array.isArray(row.config)) walk(row.config, visit);
35
+ }
36
+ }
37
+
38
+ function idsOf(rows) {
39
+ const ids = new Set();
40
+ walk(rows, row => { if (typeof row.id === 'string') ids.add(row.id); });
41
+ return ids;
42
+ }
43
+
44
+ function rowById(rows, id) {
45
+ let found;
46
+ walk(rows, row => { if (found === undefined && row.id === id) found = row; });
47
+ return found;
48
+ }
49
+
50
+ function pinDir(entry, root) {
51
+ if (!root || !entry || typeof entry !== 'object' || typeof entry.__jsExpr !== 'string') return entry;
52
+ if (!entry.__jsExpr.includes('baseUrl') || !entry.__jsExpr.includes('skills')) return entry;
53
+ return join(root, 'skills');
54
+ }
55
+
56
+ function pinDirs(dirs, root) {
57
+ return Array.isArray(dirs) ? dirs.map(entry => pinDir(entry, root)) : dirs;
58
+ }
59
+
60
+ function sameDir(left, right) {
61
+ return JSON.stringify(left) === JSON.stringify(right);
62
+ }
63
+
64
+ function withPinnedSkillDirs(row, root) {
65
+ const copy = structuredClone(row);
66
+ const dirs = copy?.config?.customSkillDirs;
67
+ if (Array.isArray(dirs)) copy.config = { ...copy.config, customSkillDirs: pinDirs(dirs, root) };
68
+ return copy;
69
+ }
70
+
71
+ /**
72
+ * Rows to append when the creative preset is enabled.
73
+ * Baseline rows stay as they are: official PTC remains the fallback.
74
+ * @param {object[]} creativePlugins
75
+ * @param {object[]} baselinePlugins
76
+ * @param {{ root?: string }} [options] directory of the creative preset, used to pin skill paths
77
+ */
78
+ export function creativeAdditions(creativePlugins, baselinePlugins, options = {}) {
79
+ const root = typeof options.root === 'string' ? options.root : '';
80
+ const baselineIds = idsOf(baselinePlugins);
81
+ const additions = [];
82
+ const seen = new Set();
83
+
84
+ const uniqueId = preferred => {
85
+ if (!baselineIds.has(preferred) && !seen.has(preferred)) return preferred;
86
+ for (let suffix = 2; ; suffix += 1) {
87
+ const candidate = `${preferred}-${suffix}`;
88
+ if (!baselineIds.has(candidate) && !seen.has(candidate)) return candidate;
89
+ }
90
+ };
91
+
92
+ const push = row => {
93
+ if (!row || seen.has(row.id)) return;
94
+ seen.add(row.id);
95
+ additions.push(row);
96
+ };
97
+
98
+ const consider = row => {
99
+ if (!row || typeof row !== 'object' || isPersona(row)) return;
100
+ if (row.group === true) {
101
+ if (typeof row.id === 'string' && baselineIds.has(row.id)) {
102
+ if (Array.isArray(row.config)) for (const child of row.config) consider(child);
103
+ return;
104
+ }
105
+ push(withPinnedSkillDirs(row, root));
106
+ return;
107
+ }
108
+ if (typeof row.id === 'string' && baselineIds.has(row.id)) {
109
+ const baseline = rowById(baselinePlugins, row.id);
110
+ const creativeDirs = row.config?.customSkillDirs;
111
+ const baselineDirs = baseline?.config?.customSkillDirs ?? [];
112
+ if (!Array.isArray(creativeDirs) || creativeDirs.length === 0) return;
113
+ const pinned = pinDirs(creativeDirs, root);
114
+ const extra = pinned.filter(entry => !baselineDirs.some(existing => sameDir(existing, entry)));
115
+ if (extra.length === 0) return;
116
+ const id = uniqueId(`${row.id}-creative`);
117
+ push({ id, name: row.name, config: { customSkillDirs: extra } });
118
+ return;
119
+ }
120
+ push(withPinnedSkillDirs(row, root));
121
+ };
122
+
123
+ if (Array.isArray(creativePlugins)) {
124
+ for (const row of creativePlugins) consider(row);
125
+ }
126
+ return additions;
127
+ }
@@ -5,10 +5,11 @@ export const inject = ['systemPrompt'];
5
5
  export const Config = z.object({
6
6
  environment: z.union(['wsl', 'powershell', 'zsh', 'bash']).required(),
7
7
  wslDistribution: z.string().default(''),
8
+ shellNote: z.string().default(''),
8
9
  });
9
10
  export function apply(ctx, config) {
10
11
  ctx.systemPrompt.section({
11
12
  name: 'deep-ptc:execution-environment', order: 10190,
12
- text: environmentText(config.environment, config.wslDistribution),
13
+ text: environmentText(config.environment, config.wslDistribution, config.shellNote),
13
14
  });
14
15
  }
package/lib/executor.mjs CHANGED
@@ -5,30 +5,55 @@ import { assertExecutionPolicy, shellArgv } from './model.mjs';
5
5
  export const name = 'deep-ptc-mapped-executor';
6
6
  export const inject = [];
7
7
  export const Config = z.object({
8
- environment: z.union(['wsl', 'zsh']).required(),
8
+ environment: z.union(['wsl', 'zsh', 'bash']).required(),
9
9
  wslDistribution: z.string().default(''),
10
+ shellExecutable: z.string().default(''),
10
11
  // The official bash executor module and its options, as the installed base declaration names them.
11
12
  base: z.string().required(),
12
13
  options: z.any(),
13
14
  });
14
15
 
16
+ function argvOf(environment, spec, distribution, executable) {
17
+ return shellArgv(environment, spec, distribution, process.platform, executable);
18
+ }
19
+
15
20
  // Extend the official bash executor: its process handles, output retention, cancellation, jobs,
16
21
  // sandbox and Config stay official; only the argv that starts the shell changes.
17
- export function mappedExecutor(Base, environment, distribution = '') {
22
+ export function mappedExecutor(Base, environment, distribution = '', executable = '') {
23
+ const explicit = typeof executable === 'string' && executable !== '';
18
24
  return class MappedShellExecutor extends Base {
19
25
  async execute(spec) {
20
26
  assertExecutionPolicy(environment, spec.sandboxPolicy);
21
27
  if (spec.sandboxPolicy.mode !== 'danger-full-access') return super.execute(spec);
22
- const process = await super.executeArgv(spec, shellArgv(environment, spec, distribution));
28
+ const process = await super.executeArgv(spec, argvOf(environment, spec, distribution, executable));
23
29
  return Base.decorateResult(process, result => ({
24
30
  ...result, sandbox: { mode: spec.sandboxPolicy.mode, denied: false },
25
31
  }));
26
32
  }
27
33
 
34
+ // Current sandboxes enter through run/start. Confined calls use confine, so the chosen
35
+ // binary stays inside the official sandbox. Full access keeps the same denial stamp as before.
36
+ async run(spec) {
37
+ if (!explicit || typeof super.run !== 'function') return super.run?.call(this, spec) ?? this.execute(spec);
38
+ assertExecutionPolicy(environment, spec.sandboxPolicy);
39
+ if (spec.sandboxPolicy?.mode !== 'danger-full-access') return super.run(spec);
40
+ if (typeof super.runArgv !== 'function') return this.execute(spec);
41
+ const result = await super.runArgv(spec, argvOf(environment, spec, distribution, executable));
42
+ return { ...result, sandbox: { mode: spec.sandboxPolicy.mode, denied: false } };
43
+ }
44
+
45
+ start(spec) {
46
+ if (!explicit || typeof super.start !== 'function') return super.start?.call(this, spec);
47
+ assertExecutionPolicy(environment, spec.sandboxPolicy);
48
+ if (spec.sandboxPolicy?.mode !== 'danger-full-access') return super.start(spec);
49
+ if (typeof this.startArgv !== 'function') return super.start(spec);
50
+ return this.startArgv(spec, argvOf(environment, spec, distribution, executable));
51
+ }
52
+
28
53
  confine(command, policy, signal) {
29
54
  assertExecutionPolicy(environment, policy);
30
- return this.ctx.sandbox.confine(shellArgv(environment,
31
- { command, workdir: policy.workspaceRoot }, distribution), policy, signal);
55
+ return this.ctx.sandbox.confine(argvOf(environment,
56
+ { command, workdir: policy.workspaceRoot }, distribution, executable), policy, signal);
32
57
  }
33
58
  };
34
59
  }
@@ -37,5 +62,5 @@ export async function apply(ctx, config) {
37
62
  const Base = pluginOf(await importHost(config.base));
38
63
  if (typeof Base !== 'function' || typeof Base.decorateResult !== 'function' || typeof Base.prototype.executeArgv !== 'function')
39
64
  throw new Error(`${config.base} no longer exposes the executor API Deep PTC extends; choose PowerShell or native Bash`);
40
- ctx.plugin(mappedExecutor(Base, config.environment, config.wslDistribution), config.options);
65
+ ctx.plugin(mappedExecutor(Base, config.environment, config.wslDistribution, config.shellExecutable), config.options);
41
66
  }
package/lib/guard.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
2
  import { reachabilityGuard, reachabilityText } from './rules.mjs';
3
+ import { failOpen } from './tool-policy.mjs';
3
4
 
4
5
  export const name = 'deep-ptc-reachability-guard';
5
6
  export const inject = ['tools', 'systemPrompt'];
@@ -10,6 +11,6 @@ export const Config = z.object({
10
11
  });
11
12
 
12
13
  export function apply(ctx, config) {
13
- ctx.tools.guard(reachabilityGuard(config, () => ctx.get('jobs')));
14
+ ctx.tools.guard(failOpen(ctx, 'reachability guard', reachabilityGuard(config, () => ctx.get('jobs'), () => ctx.get('ptcRuntime')?.language)));
14
15
  ctx.systemPrompt.section({ name: 'deep-ptc:reachability', order: 10195, text: reachabilityText(config) });
15
16
  }
package/lib/host.mjs CHANGED
@@ -48,31 +48,39 @@ export function pluginOf(namespace) {
48
48
  return namespace?.default ?? namespace;
49
49
  }
50
50
 
51
+ async function started(ctx, plugin, options) {
52
+ const fiber = ctx.plugin(plugin, options);
53
+ try { await fiber.await(); return fiber; } catch (error) { await fiber.dispose(); throw error; }
54
+ }
55
+
51
56
  /**
52
57
  * Start the official plugin `upstream` with its own inject list and Config, giving its apply an
53
- * adapted context. A plugin of another shape is started unadapted, so the official behaviour stays.
58
+ * adapted context and Deep PTC's `overrides` on top of its official options. If that fails, or the plugin
59
+ * has another shape, it runs as the official row would: an official tool keeps working without the
60
+ * Deep PTC behaviour, and only a failure of the official plugin itself reaches the preset.
54
61
  */
55
- export async function applyOfficial(ctx, upstream, options, adapt) {
62
+ export async function applyOfficial(ctx, upstream, options, adapt, overrides) {
56
63
  const plugin = pluginOf(await importHost(upstream));
57
64
  const tagged = child => adapt(adaptContext(child, {
58
65
  tools: tools => registering(tools, definition => markOfficialTool(definition, upstream)),
59
66
  }));
67
+ const merged = overrides === undefined ? options : { ...options, ...overrides };
68
+ let adapted;
60
69
  if (typeof plugin === 'function') {
61
- if (/^\s*class\b/u.test(Function.prototype.toString.call(plugin))) {
62
- class TaggedOfficial extends plugin { constructor(child, ...args) { super(tagged(child), ...args); } }
63
- return ctx.plugin(TaggedOfficial, options);
64
- }
65
- return ctx.plugin({ ...plugin, name: plugin.name || upstream, apply: (child, config) => plugin(tagged(child), config) }, options);
70
+ adapted = /^\s*class\b/u.test(Function.prototype.toString.call(plugin))
71
+ ? class TaggedOfficial extends plugin { constructor(child, ...args) { super(tagged(child), ...args); } }
72
+ : { ...plugin, name: plugin.name || upstream, apply: (child, config) => plugin(tagged(child), config) };
73
+ } else if (typeof plugin?.apply === 'function') {
74
+ adapted = { ...plugin, name: plugin.name ?? upstream, apply: (child, config) => plugin.apply(tagged(child), config) };
66
75
  }
67
- if (typeof plugin?.apply !== 'function') {
68
- ctx.logger.warn('Deep PTC: %s is not an apply-style plugin; loading it without Deep PTC wait handling', upstream);
69
- return ctx.plugin(plugin, options);
76
+ if (adapted === undefined) {
77
+ ctx.logger.warn('Deep PTC: %s has an unknown plugin shape; running it without Deep PTC behaviour', upstream);
78
+ return started(ctx, plugin, options);
79
+ }
80
+ try {
81
+ return await started(ctx, adapted, merged);
82
+ } catch (error) {
83
+ ctx.logger.warn('Deep PTC: %s failed with Deep PTC behaviour (%s); running it as declared', upstream, error?.message);
84
+ return started(ctx, plugin, options);
70
85
  }
71
- return ctx.plugin({
72
- ...plugin,
73
- name: plugin.name ?? upstream,
74
- ...plugin.inject === undefined ? {} : { inject: plugin.inject },
75
- ...plugin.Config === undefined ? {} : { Config: plugin.Config },
76
- apply: (child, config) => plugin.apply(tagged(child), config),
77
- }, options);
78
86
  }
package/lib/index.mjs CHANGED
@@ -1,17 +1,48 @@
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';
7
+ import { normalizePreferences } from './tool-policy.mjs';
5
8
  import { availableEnvironments, BASE_SNAPSHOT, DEFAULT_FOREGROUND_SECONDS, deriveDeepPtc, normalizeDistribution, resolveEnvironment } from './model.mjs';
6
- import { BASE_DECLARATION_SPECIFIER, loadOfficialPreset, 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';
7
11
  import { importHost, pluginOf, resolveHost } from './host.mjs';
8
12
  import { presetLifecycle } from './lifecycle.mjs';
9
13
 
14
+ function whereExecutable(name) {
15
+ try {
16
+ const command = process.platform === 'win32' ? 'where.exe' : 'which';
17
+ const result = spawnSync(command, [name], { encoding: 'utf8', timeout: 2000, windowsHide: true });
18
+ if (result.status !== 0 || typeof result.stdout !== 'string') return [];
19
+ return result.stdout.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
20
+ } catch {
21
+ return [];
22
+ }
23
+ }
24
+
25
+ const discoveredShells = discoverShells({
26
+ platform: process.platform,
27
+ env: process.env,
28
+ exists: existsSync,
29
+ where: whereExecutable,
30
+ });
31
+
32
+ function shellFamily(environment) {
33
+ return environment === 'powershell' || environment === 'bash' || environment === 'zsh' ? environment : '';
34
+ }
35
+
10
36
  export const name = 'deep-ptc-settings';
11
37
  export const inject = ['agentPresets'];
12
38
  export const Config = z.object({
13
39
  environment: z.union(availableEnvironments(process.platform)).default('auto').volatile(),
14
40
  wslDistribution: z.string().pattern(/^(?!\s*-)[^\u0000-\u001f\u007f]*$/u).default('').volatile(),
41
+ shellExecutable: z.string().default('').volatile(),
42
+ pluginLab: z.boolean().default(false).volatile(),
43
+ shellChoices: z.array(z.object({
44
+ id: z.string(), label: z.string(), path: z.string(), family: z.string(),
45
+ })).default(discoveredShells).volatile(),
15
46
  foregroundSeconds: z.number().step(1).min(5).max(600).default(DEFAULT_FOREGROUND_SECONDS).volatile(),
16
47
  toolCompatibility: z.boolean().default(true).volatile(),
17
48
  toolPreferences: z.any().default([]).volatile(),
@@ -19,13 +50,25 @@ export const Config = z.object({
19
50
  hostPlatform: z.const(process.platform).default(process.platform).volatile(),
20
51
  });
21
52
 
22
- function settingsOf(config) {
53
+ // Tool preferences are advice for the model, so a malformed list must not cost the preset.
54
+ function preferencesOf(ctx, config) {
55
+ try {
56
+ return normalizePreferences(config.toolPreferences.get());
57
+ } catch (error) {
58
+ ctx.logger.warn('Deep PTC: ignoring toolPreferences (%s)', error.message);
59
+ return [];
60
+ }
61
+ }
62
+
63
+ function settingsOf(ctx, config) {
23
64
  return {
24
65
  environment: config.environment.get(),
25
66
  wslDistribution: normalizeDistribution(config.wslDistribution.get()),
67
+ shellExecutable: config.shellExecutable.get(),
68
+ pluginLab: config.pluginLab.get() === true,
26
69
  foregroundSeconds: config.foregroundSeconds.get(),
27
70
  toolCompatibility: config.toolCompatibility.get(),
28
- toolPreferences: config.toolPreferences.get(),
71
+ toolPreferences: preferencesOf(ctx, config),
29
72
  compactToolCatalog: config.compactToolCatalog.get(),
30
73
  };
31
74
  }
@@ -63,16 +106,41 @@ async function canExtend(ctx, executor) {
63
106
  // official change is inherited instead of leaving a stale frozen row behind.
64
107
  // The bundled snapshot is only a fallback when the installed declaration
65
108
  // cannot be read or cannot be composed.
66
- async function buildPreset(ctx, config) {
67
- const settings = settingsOf(config);
109
+ async function buildPreset(ctx, config, safeMode) {
110
+ const settings = { ...settingsOf(ctx, config), safeMode };
68
111
  const executors = officialExecutors(ctx);
69
112
  const environment = resolveEnvironment(settings.environment);
70
- if (environment === 'wsl' || environment === 'zsh') settings.mappedExecutor = await canExtend(ctx, executors.bash);
113
+ const family = shellFamily(environment);
114
+ if (family) {
115
+ const requested = typeof settings.shellExecutable === 'string' ? settings.shellExecutable : '';
116
+ const resolved = resolveShellExecutable(requested, { family, discovered: discoveredShells, exists: existsSync });
117
+ if (requested && requested !== 'auto' && !resolved) {
118
+ ctx.logger.warn('Deep PTC: selected shell %s is not available; using the automatic executable', requested);
119
+ }
120
+ settings.shellExecutable = resolved;
121
+ const note = shellNote({ family, executable: resolved });
122
+ if (note) settings.shellNote = note;
123
+ } else {
124
+ settings.shellExecutable = '';
125
+ }
126
+ if (environment === 'wsl' || environment === 'zsh' || (environment === 'bash' && settings.shellExecutable)) {
127
+ settings.mappedExecutor = await canExtend(ctx, executors.bash);
128
+ }
129
+ if (settings.pluginLab && !safeMode) {
130
+ try {
131
+ const creative = await loadCreativePreset(ctx.agentPresets);
132
+ settings.creativePlugins = creative.plugins;
133
+ settings.creativeRoot = creative.root;
134
+ ctx.logger.info('Deep PTC: plugin lab reading %s', creative.source);
135
+ } catch (error) {
136
+ ctx.logger.warn('Deep PTC: creative preset unavailable (%s); plugin lab keeps the PTC tools', error.message);
137
+ }
138
+ }
71
139
  settings.executors = executors;
72
140
  let upstream = snapshot;
73
141
  let source = 'bundled snapshot';
74
142
  try {
75
- const official = loadOfficialPreset();
143
+ const official = await loadCurrentPreset(ctx.agentPresets);
76
144
  upstream = official.preset;
77
145
  source = official.source;
78
146
  } catch (error) {
@@ -94,17 +162,43 @@ async function buildPreset(ctx, config) {
94
162
  }
95
163
 
96
164
  export async function apply(ctx, config) {
165
+ let safeMode = false;
97
166
  const lifecycle = presetLifecycle(
98
167
  definition => ctx.agentPresets.register(definition),
99
- () => buildPreset(ctx, config),
168
+ () => buildPreset(ctx, config, safeMode),
100
169
  error => ctx.logger.error('Deep PTC environment update failed: %s', error.message),
101
170
  );
102
171
  ctx.effect(() => () => lifecycle.dispose());
103
- ctx.on('loader/volatile-update', () => { void lifecycle.refresh().catch(() => {}); });
172
+ // A preset the host refuses to mount would leave its sessions unusable, so fall back to the official
173
+ // composition with the persona. Not awaited: reading the diagnosis waits for the host tree.
174
+ const verify = async () => {
175
+ const row = (await ctx.agentPresets.compositionInventory?.())?.find(candidate => candidate.id === 'deep-ptc');
176
+ if (safeMode || !row?.broken) return;
177
+ ctx.logger.warn('Deep PTC: preset cannot mount (%s); using safe mode', row.broken);
178
+ safeMode = true;
179
+ await lifecycle.refresh();
180
+ };
181
+ const refreshed = () => lifecycle.refresh().then(() => { void verify().catch(() => {}); });
182
+ // Read the installed declarations, not fixture versions. Refresh only when our settings or
183
+ // upstream declaration bytes change. Existing sessions keep their leased preset generation.
184
+ const signature = async () => {
185
+ const read = url => {try{return readFileSync(fileURLToPath(url),'utf8');}catch{return '';}};
186
+ let runtime='';try{runtime=JSON.stringify(await ctx.agentPresets.readDocument?.('ptc'));}catch{}
187
+ let creative='';try{creative=JSON.stringify(await ctx.agentPresets.readDocument?.(CREATIVE_PRESET_ID));}catch{}
188
+ return JSON.stringify(settingsOf(ctx,config))+'\0'+runtime+'\0'+creative+'\0'+read(officialPresetUrl())+'\0'+read(resolveHost(BASE_DECLARATION_SPECIFIER))+'\0'+read(creativePresetUrl());
189
+ };
190
+ let previous=await signature(), detecting=false, active=true;
191
+ const detect = async () => {
192
+ if(detecting||!active)return;detecting=true;
193
+ 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;}
194
+ };
195
+ ctx.on('loader/volatile-update', detect);
196
+ const upstreamWatch=setInterval(detect,5000);upstreamWatch.unref?.();
197
+ ctx.effect(()=>()=>{active=false;clearInterval(upstreamWatch);});
104
198
  ctx.inject(['settings'], child => {
105
199
  child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
106
200
  });
107
201
  // A failure to publish the preset is reported above; it must not take the
108
202
  // settings service (or the rest of the profile) down with it.
109
- await lifecycle.refresh().catch(() => {});
203
+ await refreshed().catch(() => {});
110
204
  }
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/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
+ }