dsh-deep-ptc-mode 1.6.0 → 1.7.1

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,7 +1,10 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
2
  import snapshot from './preset.json' with { type: 'json' };
3
- import { availableEnvironments, DEFAULT_FOREGROUND_SECONDS, deriveDeepPtc, normalizeDistribution } from './model.mjs';
4
- import { loadOfficialPreset } from './upstream.mjs';
3
+ import { readFileSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ 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 { importHost, pluginOf, resolveHost } from './host.mjs';
5
8
  import { presetLifecycle } from './lifecycle.mjs';
6
9
 
7
10
  export const name = 'deep-ptc-settings';
@@ -10,6 +13,8 @@ export const Config = z.object({
10
13
  environment: z.union(availableEnvironments(process.platform)).default('auto').volatile(),
11
14
  wslDistribution: z.string().pattern(/^(?!\s*-)[^\u0000-\u001f\u007f]*$/u).default('').volatile(),
12
15
  foregroundSeconds: z.number().step(1).min(5).max(600).default(DEFAULT_FOREGROUND_SECONDS).volatile(),
16
+ toolCompatibility: z.boolean().default(true).volatile(),
17
+ toolPreferences: z.any().default([]).volatile(),
13
18
  hostPlatform: z.const(process.platform).default(process.platform).volatile(),
14
19
  });
15
20
 
@@ -18,15 +23,50 @@ function settingsOf(config) {
18
23
  environment: config.environment.get(),
19
24
  wslDistribution: normalizeDistribution(config.wslDistribution.get()),
20
25
  foregroundSeconds: config.foregroundSeconds.get(),
26
+ toolCompatibility: config.toolCompatibility.get(),
27
+ toolPreferences: config.toolPreferences.get(),
21
28
  };
22
29
  }
23
30
 
31
+ // The shell executors the installed Harness declares in its base deployment, by kind.
32
+ function officialExecutors(ctx) {
33
+ try {
34
+ const url = resolveHost(BASE_DECLARATION_SPECIFIER);
35
+ if (url === undefined) throw new Error(`cannot resolve ${BASE_DECLARATION_SPECIFIER}`);
36
+ const executors = parseOfficialExecutors(readFileSync(fileURLToPath(url), 'utf8'));
37
+ for (const kind of ['bash', 'pwsh']) if (executors[kind] === undefined)
38
+ ctx.logger.warn('Deep PTC: %s declares no %s executor; using the bundled snapshot entry', url, kind);
39
+ return { ...BASE_SNAPSHOT, ...executors };
40
+ } catch (error) {
41
+ ctx.logger.warn('Deep PTC: official executors unavailable (%s); using the bundled snapshot', error.message);
42
+ return BASE_SNAPSHOT;
43
+ }
44
+ }
45
+
46
+ // WSL and Zsh extend the official bash executor class. Probe it before choosing that path so an
47
+ // incompatible Harness falls back to the official shell rows instead of a preset that cannot mount.
48
+ async function canExtend(ctx, executor) {
49
+ try {
50
+ const Base = pluginOf(await importHost(executor.name));
51
+ if (typeof Base === 'function' && typeof Base.decorateResult === 'function'
52
+ && typeof Base.prototype.executeArgv === 'function') return true;
53
+ ctx.logger.warn('Deep PTC: %s no longer exposes the executor API WSL/Zsh extend', executor.name);
54
+ } catch (error) {
55
+ ctx.logger.warn('Deep PTC: cannot load %s (%s)', executor.name, error.message);
56
+ }
57
+ return false;
58
+ }
59
+
24
60
  // Derive Deep PTC from the PTC preset the installed Harness declares, so an
25
61
  // official change is inherited instead of leaving a stale frozen row behind.
26
62
  // The bundled snapshot is only a fallback when the installed declaration
27
63
  // cannot be read or cannot be composed.
28
- function buildPreset(ctx, config) {
64
+ async function buildPreset(ctx, config) {
29
65
  const settings = settingsOf(config);
66
+ const executors = officialExecutors(ctx);
67
+ const environment = resolveEnvironment(settings.environment);
68
+ if (environment === 'wsl' || environment === 'zsh') settings.mappedExecutor = await canExtend(ctx, executors.bash);
69
+ settings.executors = executors;
30
70
  let upstream = snapshot;
31
71
  let source = 'bundled snapshot';
32
72
  try {
@@ -39,8 +79,8 @@ function buildPreset(ctx, config) {
39
79
  try {
40
80
  const { preset, report } = deriveDeepPtc(upstream, settings);
41
81
  ctx.logger.info(
42
- 'Deep PTC preset derived from %s: %d official rows; persona %s; shell rows [%s]; wrapped [%s]; skipped [%s]',
43
- source, report.upstreamRows, report.persona,
82
+ 'Deep PTC preset derived from %s: %d official rows; persona %s; environment %s; shell rows [%s]; wrapped [%s]; skipped [%s]',
83
+ source, report.upstreamRows, report.persona, report.environment,
44
84
  report.replacedShellRows.join('; ') || '-', report.wrapped.join(', ') || '-', report.skipped.join('; ') || '-',
45
85
  );
46
86
  return preset;
package/lib/jobs-tool.mjs CHANGED
@@ -1,15 +1,21 @@
1
- import { Config, apply as applyJobs, inject } from '@deepseek-ai/dsh-tool-jobs';
1
+ import z from '@deepseek-ai/schemastery';
2
2
  import { adaptContext, registering } from './adapt.mjs';
3
+ import { applyOfficial } from './host.mjs';
3
4
  import { steerableJobs, steerableTool, steeringWatch } from './reachable.mjs';
4
5
 
5
6
  export const name = 'deep-ptc-tool-jobs';
6
- export { Config, inject };
7
+ export const inject = [];
8
+ export const Config = z.object({
9
+ // The official job tool module and its options, as the installed PTC declaration names them.
10
+ upstream: z.string().required(),
11
+ options: z.any(),
12
+ });
7
13
 
8
14
  // The official job tools, with job_output waits ending when the user sends a message.
9
- export function apply(ctx, config) {
15
+ export async function apply(ctx, config) {
10
16
  const watch = steeringWatch(ctx);
11
- applyJobs(adaptContext(ctx, {
17
+ await applyOfficial(ctx, config.upstream, config.options, child => adaptContext(child, {
12
18
  tools: tools => registering(tools, definition => definition.name === 'job_output' ? steerableTool(definition) : definition),
13
19
  jobs: jobs => steerableJobs(jobs, watch),
14
- }), config);
20
+ }));
15
21
  }
package/lib/lifecycle.mjs CHANGED
@@ -6,7 +6,7 @@ export function presetLifecycle(register, getDefinition, onError) {
6
6
  const refresh = () => {
7
7
  queue = queue.then(async () => {
8
8
  if (disposed) return;
9
- const definition = getDefinition(); // Validate before removing the last good definition.
9
+ const definition = await getDefinition(); // Validate before removing the last good definition.
10
10
  await unregister?.();
11
11
  unregister = undefined;
12
12
  if (disposed) return;
package/lib/model.mjs CHANGED
@@ -7,6 +7,8 @@
7
7
  // the official job and question tools. A change on the official side therefore
8
8
  // never leaves a stale module name behind.
9
9
  import snapshot from './preset.json' with { type: 'json' };
10
+ import baseSnapshot from './base-snapshot.json' with { type: 'json' };
11
+ import { normalizePreferences } from './tool-policy.mjs';
10
12
 
11
13
  export const ENVIRONMENTS = ['auto', 'wsl', 'powershell', 'zsh', 'bash'];
12
14
 
@@ -69,40 +71,45 @@ export function normalizeForegroundSeconds(value = DEFAULT_FOREGROUND_SECONDS) {
69
71
  }
70
72
 
71
73
  /**
72
- * Official rows Deep PTC replaces: the shell tools and the executors that back
73
- * them. Matched by id first, then by module name; the traversal is recursive so
74
- * a future official preset may nest them in a group.
74
+ * Lookup hints for the official rows Deep PTC replaces with its execution group. Hints only find
75
+ * rows; the modules Deep PTC loads are always the ones the official rows (or the base declaration)
76
+ * name, so a renamed or replaced official module is followed rather than hard-coded.
75
77
  */
78
+ export const SHELL_TOOLS = {
79
+ bash: { ids: ['tool-bash'], names: ['@deepseek-ai/dsh-tool-bash'] },
80
+ pwsh: { ids: ['tool-pwsh'], names: ['@deepseek-ai/dsh-tool-pwsh'] },
81
+ };
82
+ const SHELL_EXECUTOR_NAMES = [
83
+ '@deepseek-ai/dsh-bash-local',
84
+ '@deepseek-ai/dsh-bash-sandbox',
85
+ '@deepseek-ai/dsh-pwsh-local',
86
+ '@deepseek-ai/dsh-pwsh-sandbox',
87
+ ];
76
88
  export const SHELL_ROWS = {
77
- ids: ['tool-bash', 'tool-pwsh'],
78
- names: [
79
- '@deepseek-ai/dsh-tool-bash',
80
- '@deepseek-ai/dsh-tool-pwsh',
81
- '@deepseek-ai/dsh-bash-local',
82
- '@deepseek-ai/dsh-bash-sandbox',
83
- '@deepseek-ai/dsh-pwsh-sandbox',
84
- ],
89
+ ids: [...SHELL_TOOLS.bash.ids, ...SHELL_TOOLS.pwsh.ids],
90
+ names: [...SHELL_TOOLS.bash.names, ...SHELL_TOOLS.pwsh.names, ...SHELL_EXECUTOR_NAMES],
85
91
  };
86
92
 
87
- /** Official rows Deep PTC keeps but wraps, keyed for diagnostics. */
93
+ /** Lookup hints for the official rows Deep PTC keeps but wraps, keyed by row id. */
88
94
  export const WRAPPED_ROWS = {
89
95
  'tool-jobs': '@deepseek-ai/dsh-tool-jobs',
90
96
  'tool-ask-user': '@deepseek-ai/dsh-tool-ask-user',
91
97
  };
92
98
 
99
+ /** Fallback executor declaration, used only when the installed base declaration cannot be read. */
100
+ export const BASE_SNAPSHOT = baseSnapshot;
101
+
93
102
  const PERSONA_ROW = { ids: ['persona'], names: ['@deepseek-ai/dsh-persona'] };
94
103
  const WRAP_TARGETS = [
95
104
  {
96
105
  key: 'tool-jobs',
97
- upstream: '@deepseek-ai/dsh-tool-jobs',
98
106
  replacement: 'dsh-deep-ptc-mode/jobs-tool',
99
- config: milliseconds => ({ waitTimeoutMs: milliseconds, maxWaitTimeoutMs: milliseconds }),
107
+ options: milliseconds => ({ waitTimeoutMs: milliseconds, maxWaitTimeoutMs: milliseconds }),
100
108
  },
101
109
  {
102
110
  key: 'tool-ask-user',
103
- upstream: '@deepseek-ai/dsh-tool-ask-user',
104
111
  replacement: 'dsh-deep-ptc-mode/ask-user',
105
- config: () => ({ mode: 'timed', timeout: QUESTION_SECONDS }),
112
+ options: () => ({ mode: 'timed', timeout: QUESTION_SECONDS }),
106
113
  },
107
114
  ];
108
115
 
@@ -141,6 +148,13 @@ export function isShellRow(row) {
141
148
  return row.group !== true && (SHELL_ROWS.names.includes(row.name) || SHELL_ROWS.ids.includes(row.id));
142
149
  }
143
150
 
151
+ export function isOfficialCapabilityRow(row) {
152
+ return row.group !== true && !isShellRow(row) && typeof row.name === 'string'
153
+ && row.name.startsWith('@deepseek-ai/')
154
+ && ((row.name.startsWith('@deepseek-ai/dsh-tool-') && !row.name.startsWith('@deepseek-ai/dsh-tool-executor-'))
155
+ || row.name.endsWith('/tools'));
156
+ }
157
+
144
158
  function findRow(rows, { ids = [], names = [] }) {
145
159
  let found;
146
160
  walkRows(rows, row => {
@@ -187,6 +201,7 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
187
201
  const distribution = normalizeDistribution(options.wslDistribution);
188
202
  const foregroundSeconds = normalizeForegroundSeconds(options.foregroundSeconds);
189
203
  const foregroundMs = foregroundSeconds * 1000;
204
+ const toolPreferences = normalizePreferences(options.toolPreferences);
190
205
  const plugins = structuredClone(upstream.plugins);
191
206
  const report = {
192
207
  upstreamId: typeof upstream.id === 'string' ? upstream.id : null,
@@ -208,17 +223,33 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
208
223
  report.persona = 'replaced';
209
224
  }
210
225
 
211
- // Execution environment: remove the official shell rows (wherever the
212
- // official preset nests them) and put the selectable execution group in the
213
- // same place.
214
- const removed = [];
215
- walkRows(plugins, (row, siblings, index) => {
216
- if (isShellRow(row)) removed.push({ row, siblings, index });
217
- });
218
- report.replacedShellRows = removed.map(({ row }) => `${row.id ?? '?'} (${row.name})`);
226
+ // Execution environment: replace the official shell rows (wherever the official preset nests them)
227
+ // with the selectable execution group in the same place. The group runs the official shell tool
228
+ // and executor the installed Harness names; when they cannot be mapped, the official rows stay.
229
+ const kind = environment === 'powershell' ? 'pwsh' : 'bash';
230
+ const executors = { ...BASE_SNAPSHOT, ...(options.executors ?? {}) };
231
+ const tool = findRow(plugins, SHELL_TOOLS[kind]);
232
+ const official = executors[kind];
233
+ const mapped = environment === 'wsl' || environment === 'zsh';
234
+ const unusable = tool === undefined ? `the official PTC preset has no ${kind} tool row`
235
+ : typeof official?.name !== 'string' ? `the installed Harness declares no ${kind} executor`
236
+ : mapped && options.mappedExecutor === false ? `the official bash executor cannot be extended for ${environment}`
237
+ : undefined;
238
+ report.environment = unusable === undefined ? environment : 'official';
219
239
  let anchorSiblings = plugins;
220
240
  let anchorIndex;
221
- if (removed.length > 0) {
241
+ const rows = [];
242
+ if (unusable !== undefined) {
243
+ report.skipped.push(`execution environment ${environment} (${unusable}; official shell rows kept)`);
244
+ const topLevelPersona = plugins.findIndex(row => row && row.group !== true
245
+ && (PERSONA_ROW.names.includes(row.name) || PERSONA_ROW.ids.includes(row.id)));
246
+ anchorIndex = topLevelPersona + 1;
247
+ } else {
248
+ const removed = [];
249
+ walkRows(plugins, (row, siblings, index) => {
250
+ if (isShellRow(row)) removed.push({ row, siblings, index });
251
+ });
252
+ report.replacedShellRows = removed.map(({ row }) => `${row.id ?? '?'} (${row.name})`);
222
253
  anchorSiblings = removed[0].siblings;
223
254
  const bySiblings = new Map();
224
255
  for (const { siblings, index } of removed) {
@@ -229,51 +260,61 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
229
260
  for (const [siblings, indexes] of bySiblings) {
230
261
  for (const index of [...indexes].sort((left, right) => right - left)) siblings.splice(index, 1);
231
262
  }
232
- } else {
233
- report.skipped.push('official shell rows');
234
- const topLevelPersona = plugins.findIndex(row => row && row.group !== true
235
- && (PERSONA_ROW.names.includes(row.name) || PERSONA_ROW.ids.includes(row.id)));
236
- anchorIndex = topLevelPersona + 1;
263
+ // With background jobs available, the executor timeout only decides when a foreground command
264
+ // moves to the background; the official tools run such commands with onExpiry: none.
265
+ const executorOptions = { ...(official.config ?? {}), timeoutMs: foregroundMs, maxTimeoutMs: foregroundMs };
266
+ const executor = mapped
267
+ ? { id: 'executor', name: 'dsh-deep-ptc-mode/executor',
268
+ config: { environment, wslDistribution: distribution, base: official.name, options: executorOptions } }
269
+ : { id: 'executor', name: official.name, config: executorOptions };
270
+ const terminal = {
271
+ id: environment === 'zsh' ? 'tool-zsh' : tool.id ?? `tool-${kind}`,
272
+ name: 'dsh-deep-ptc-mode/terminal',
273
+ config: {
274
+ upstream: tool.name,
275
+ ...tool.config === undefined ? {} : { options: tool.config },
276
+ ...environment === 'zsh' ? { dialect: 'zsh' } : {},
277
+ },
278
+ };
279
+ rows.push({
280
+ id: uniqueRowId(plugins, 'execution'), name: 'cordis:group', group: true, isolate: { shell: true },
281
+ config: [executor, terminal, { id: 'execution-instructions', name: 'dsh-deep-ptc-mode/environment',
282
+ config: { environment, wslDistribution: distribution } }],
283
+ });
237
284
  }
238
-
239
- const executor = {
240
- id: 'executor',
241
- name: environment === 'powershell' ? '@deepseek-ai/dsh-pwsh-sandbox'
242
- : environment === 'bash' ? '@deepseek-ai/dsh-bash-sandbox' : 'dsh-deep-ptc-mode/executor',
243
- config: {
244
- ...(environment === 'wsl' || environment === 'zsh' ? { environment, wslDistribution: distribution } : {}),
245
- timeoutMs: foregroundMs, maxTimeoutMs: foregroundMs,
246
- },
247
- };
248
- const terminal = {
249
- id: environment === 'zsh' ? 'tool-zsh' : environment === 'powershell' ? 'tool-pwsh' : 'tool-bash',
250
- name: 'dsh-deep-ptc-mode/terminal',
251
- config: { tool: environment === 'powershell' ? 'pwsh' : 'bash', ...(environment === 'zsh' ? { dialect: 'zsh' } : {}) },
252
- };
253
- const execution = {
254
- id: uniqueRowId(plugins, 'execution'), name: 'cordis:group', group: true, isolate: { shell: true },
255
- config: [executor, terminal, { id: 'execution-instructions', name: 'dsh-deep-ptc-mode/environment',
256
- config: { environment, wslDistribution: distribution } }],
257
- };
258
- const guard = {
259
- id: uniqueRowId([...plugins, execution], 'reachability'),
285
+ rows.push({
286
+ id: uniqueRowId([...plugins, ...rows], 'reachability'),
260
287
  name: 'dsh-deep-ptc-mode/guard', config: { foregroundSeconds },
261
- };
262
- anchorSiblings.splice(anchorIndex, 0, execution, guard);
288
+ });
289
+ anchorSiblings.splice(anchorIndex, 0, ...rows);
263
290
 
264
- // Wrapped tools: keep the official plugin's own configuration, add the
265
- // Deep PTC wait behaviour on top.
291
+ // Wrapped tools: the wrapper loads the module the official row names, with the official options
292
+ // plus the Deep PTC wait behaviour.
266
293
  for (const target of WRAP_TARGETS) {
267
- const row = findRow(plugins, { ids: [target.key], names: [target.upstream] });
294
+ const row = findRow(plugins, { ids: [target.key], names: [WRAPPED_ROWS[target.key]] });
268
295
  if (row === undefined) {
269
- report.skipped.push(`${target.key} (${target.upstream})`);
296
+ report.skipped.push(`${target.key} (no official row)`);
270
297
  continue;
271
298
  }
299
+ const upstreamName = row.name;
272
300
  row.name = target.replacement;
273
- row.config = { ...(row.config ?? {}), ...target.config(foregroundMs) };
274
- report.wrapped.push(target.key);
301
+ row.config = { upstream: upstreamName, options: { ...(row.config ?? {}), ...target.options(foregroundMs) } };
302
+ report.wrapped.push(`${target.key} (${upstreamName})`);
275
303
  }
276
304
 
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 } };
312
+ });
313
+ plugins.push({
314
+ id: uniqueRowId(plugins, 'tool-compatibility'), name: 'dsh-deep-ptc-mode/tool-compatibility',
315
+ config: { enabled: options.toolCompatibility !== false, preferences: toolPreferences },
316
+ });
317
+
277
318
  const description = `${PRESET_META.description} 当前环境:${environment}${environment === 'wsl' && distribution ? ` (${distribution})` : ''}`;
278
319
  return {
279
320
  preset: {
@@ -0,0 +1,8 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ import { applyOfficial } from './host.mjs';
3
+
4
+ export const name = 'deep-ptc-official-tools';
5
+ export const inject = [];
6
+ export const Config = z.object({ upstream: z.string().required(), options: z.any() });
7
+ // Preserve official schemas, bodies, options and lifecycle; record their provenance for recovery.
8
+ export function apply(ctx, config) { return applyOfficial(ctx, config.upstream, config.options, child => child); }
package/lib/terminal.mjs CHANGED
@@ -1,23 +1,24 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
- import { apply as applyBash } from '@deepseek-ai/dsh-tool-bash';
3
- import { apply as applyPwsh } from '@deepseek-ai/dsh-tool-pwsh';
4
2
  import { adaptContext, registering } from './adapt.mjs';
3
+ import { applyOfficial } from './host.mjs';
5
4
  import { finishPromoted, steerableJobs, steerableTool, steeringWatch } from './reachable.mjs';
6
5
 
7
6
  export const name = 'deep-ptc-terminal';
8
- export const inject = ['tools', 'shell', 'systemPrompt', 'shellEnv', 'workingDirectory'];
7
+ export const inject = [];
9
8
  export const Config = z.object({
10
- tool: z.union(['bash', 'pwsh']).required(),
9
+ // The official shell tool module and its options, as the installed PTC declaration names them.
10
+ upstream: z.string().required(),
11
+ options: z.any(),
11
12
  dialect: z.union(['zsh']),
12
13
  });
13
14
 
14
- // Keep the official execution, jobs and approval implementation. Foreground waits yield to user
15
- // messages; the Zsh dialect only renames the bash tool's public face.
16
- export function apply(ctx, config) {
15
+ // Run the official shell tool with its own execution, jobs and approval implementation. Foreground
16
+ // waits yield to user messages; the Zsh dialect only renames the tool's public face.
17
+ export async function apply(ctx, config) {
17
18
  const watch = steeringWatch(ctx);
18
19
  const zsh = config.dialect === 'zsh';
19
20
  const dialect = text => zsh ? text.replace(/\bbash\b/gu, 'zsh').replace(/\bBash\b/gu, 'Zsh') : text;
20
- const adapted = adaptContext(ctx, {
21
+ await applyOfficial(ctx, config.upstream, config.options, child => adaptContext(child, {
21
22
  tools: tools => registering(tools, definition => steerableTool({
22
23
  ...definition,
23
24
  ...zsh ? { name: definition.name === 'bash' ? 'zsh' : definition.name, description: dialect(definition.description) } : {},
@@ -31,6 +32,5 @@ export function apply(ctx, config) {
31
32
  },
32
33
  }) : prompt,
33
34
  jobs: jobs => steerableJobs(jobs, watch),
34
- });
35
- (config.tool === 'pwsh' ? applyPwsh : applyBash)(adapted, {});
35
+ }));
36
36
  }
@@ -0,0 +1,7 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ import { installToolCompatibility } from './tool-policy.mjs';
3
+
4
+ export const name = 'deep-ptc-tool-compatibility';
5
+ export const inject = ['tools', 'systemPrompt'];
6
+ export const Config = z.object({ enabled: z.boolean().default(true), preferences: z.any().default([]) });
7
+ export function apply(ctx, config) { installToolCompatibility(ctx, config); }
@@ -0,0 +1,141 @@
1
+ // Task-level recovery only: observe outcomes and guide the next model step. Never invoke, rename,
2
+ // translate, hide, or replay a tool. Registrations, schemas and authorization stay with their owners.
3
+ const officialDefinitions = new WeakSet();
4
+ const MAX_FAILURES = 8;
5
+ const MAX_NAMES = 12;
6
+ const validName = name => typeof name === 'string' && /^[\w.:-]{1,128}$/u.test(name);
7
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
8
+
9
+ export function markOfficialTool(definition) {
10
+ officialDefinitions.add(definition);
11
+ return definition;
12
+ }
13
+
14
+ export const compatibilityPolicy = `## Cooperate with tool plugins
15
+
16
+ - Tool selection has two layers. First search the available extension/plugin capabilities for the needed function, including the provider's own discovery/SDK loader when present; prefer a suitable working enhancement. Second, if that layer has no suitable capability or its tool fails, use the inherited official PTC capability as the fallback. Do not repeatedly rediscover or retry the same broken enhancement. Do not assume any plugin is installed or enabled.
17
+ - Use each provider's actual live schema and result contract; tool names, arguments, return values and execution environments are not interchangeable. A preference is a task-level routing choice, not an alias or permission to forward raw arguments between tools.
18
+ - The inherited official PTC tools are the baseline. If an enhancement is missing or fails, automatically continue the task with an available official tool that supports the operation; do not ask for permission merely to change a tool within the already-authorized task. Rebuild the call from that tool's real schema. No equivalent official capability means report the limitation instead of inventing one.
19
+ - A failed call may already have written files, submitted a request, or started a command/job. Before continuing a mutation, inspect its receipts and read back the relevant state; apply only the remaining work. Never replay a command just because its output or renderer failed. A background/promoted job is still running, not a failed call.
20
+ - Permission/approval denials, policy blocks and user cancellation remain authoritative: never switch tools, shells or credentials to evade them. Invalid arguments, missing input files and an ordinary nonzero command exit require diagnosis, not a claim that the provider is broken. Empty searches are valid results. Partial/truncated results require continuation or explicit coverage limits.
21
+ - Keep the selected execution environment and reachability rules. A plugin shell is not automatically the selected WSL/native shell. Use its real job and cancellation contract; prefer explicit background execution for long work. Do not claim Deep PTC's official-tool wait wrapper automatically controls every third-party executor.
22
+ - Keep official fallbacks available in the enhancement plugin's own configuration where supported. If another plugin or host policy hides or removes them, do not bypass its restrictions or call a captured private implementation. Explain the unavailable fallback and the configuration needed to restore it. This compatibility layer adds no tools and cannot repair an unloaded tool executor.`;
23
+
24
+ /** Only structured outcome metadata is interpreted; arbitrary result text is never prompt policy. */
25
+ export function classifyToolOutcome(exec, result) {
26
+ if (exec.signal?.aborted) return { kind: 'cancelled', effect: 'unknown' };
27
+ const value = object(result?.value) ? result.value : undefined;
28
+ if (value?.cancelled === true || ['cancelled', 'aborted'].includes(value?.status)) return { kind: 'cancelled', effect: 'unknown' };
29
+ if (value?.sandbox?.denied === true) return { kind: 'denied', effect: 'unknown' };
30
+ // Host job promotion is success even when the command has not finished yet.
31
+ if (!result?.isError && ['background', 'promoted'].includes(value?.kind)) return undefined;
32
+ if (!result?.isError && value?.kind === 'foreground' && typeof value.exitCode === 'number' && value.exitCode !== 0)
33
+ return { kind: 'command', effect: 'unknown' };
34
+ const status = typeof value?.status === 'string' ? value.status.toLowerCase() : '';
35
+ const failure = object(value?.failure) ? value.failure : undefined;
36
+ const failed = result?.isError === true || ['failed', 'error', 'unavailable', 'partial'].includes(status);
37
+ if (!failed) return undefined;
38
+ const rawCode = result?.error?.code ?? failure?.code;
39
+ const code = typeof rawCode === 'string' && /^[A-Z0-9_:-]{1,96}$/u.test(rawCode) ? rawCode : '';
40
+ const effect = ['none', 'unknown', 'partial', 'completed'].includes(failure?.effectState)
41
+ ? failure.effectState : 'unknown';
42
+ if (/ABORT|CANCEL/u.test(code) || status === 'cancelled') return { kind: 'cancelled', effect };
43
+ if (/DENIED|FORBIDDEN|POLICY|APPROVAL|PERMISSION|EACCES|EPERM|READ_ONLY/u.test(code))
44
+ return { kind: 'denied', effect };
45
+ if (/ARGUMENT|INVALID_ARGS|VALIDATION|ENOENT|NOT_FOUND/u.test(code) && code !== 'UNKNOWN_TOOL')
46
+ return { kind: 'input', effect };
47
+ if (status === 'partial') return { kind: 'partial', effect };
48
+ if (/UNKNOWN_TOOL|UNAVAILABLE|WORKER_MISSING|RUNTIME_MISSING/u.test(code) || status === 'unavailable')
49
+ return { kind: 'unavailable', effect };
50
+ return { kind: 'failure', effect };
51
+ }
52
+
53
+ export function normalizePreferences(preferences = []) {
54
+ if (!Array.isArray(preferences) || preferences.length > 32) throw new Error('toolPreferences must be an array with at most 32 entries');
55
+ const seen = new Set();
56
+ return preferences.map(row => {
57
+ if (!object(row) || !validName(row.preferred) || row.preferred === 'run_code'
58
+ || !Array.isArray(row.fallback) || row.fallback.length === 0 || row.fallback.length > 12
59
+ || row.fallback.some(name => !validName(name) || name === 'run_code' || name === row.preferred)
60
+ || seen.has(row.preferred)) throw new Error('Each tool preference needs a unique preferred tool and 1–12 distinct fallback names (not run_code)');
61
+ if (new Set(row.fallback).size !== row.fallback.length) throw new Error('Duplicate fallback names in toolPreferences');
62
+ seen.add(row.preferred);
63
+ return { preferred: row.preferred, fallback: [...row.fallback] };
64
+ });
65
+ }
66
+
67
+ export function createCompatibilityState(tools, preferences = []) {
68
+ const routes = normalizePreferences(preferences);
69
+ let failures = new WeakMap();
70
+ let dispatched = new WeakSet();
71
+ const definitions = (agent, toolSet) => {
72
+ try { return tools.definitions(agent, toolSet).filter(def => validName(def.name)); }
73
+ catch { return []; } // An unavailable executor/provider must not break prompt assembly.
74
+ };
75
+ return {
76
+ dispatched(exec) { if (object(exec)) dispatched.add(exec); },
77
+ observe(exec, result) {
78
+ if (!object(exec?.agent) || !validName(exec.name) || exec.name === 'run_code') return;
79
+ let outcome = classifyToolOutcome(exec, result);
80
+ // Host guards and approval can deny with only an error message and no machine code. A call
81
+ // that never reached around-dispatch is never treated as a failed provider to route around.
82
+ if (result?.isError && !dispatched.has(exec) && outcome?.kind === 'failure')
83
+ outcome = { kind: 'not-dispatched', effect: 'none' };
84
+ let rows = failures.get(exec.agent);
85
+ if (!outcome) { rows?.delete(exec.name); return; }
86
+ if (!rows) failures.set(exec.agent, rows = new Map());
87
+ rows.delete(exec.name);
88
+ // A new provider definition invalidates evidence about its previous generation.
89
+ let definition;
90
+ try { definition = tools.get(exec.name, exec.agent); } catch { /* absent is evidence too */ }
91
+ rows.set(exec.name, { ...outcome, definition, official: definition !== undefined && officialDefinitions.has(definition) });
92
+ if (rows.size > MAX_FAILURES) rows.delete(rows.keys().next().value);
93
+ },
94
+ text({ scope: agent, toolSet } = {}) {
95
+ if (!object(agent)) return '';
96
+ const live = definitions(agent, toolSet);
97
+ const available = new Map(live.map(def => [def.name, def]));
98
+ const rows = failures.get(agent);
99
+ for (const [name, failure] of rows ?? []) {
100
+ let current;
101
+ try { current = tools.get(name, agent); } catch { /* unavailable */ }
102
+ if (current !== failure.definition) rows.delete(name);
103
+ }
104
+ const unhealthy = name => ['failure', 'unavailable'].includes(rows?.get(name)?.kind);
105
+ const official = live.filter(def => officialDefinitions.has(def)).map(def => def.name).slice(0, MAX_NAMES);
106
+ const enhancements = live.filter(def => !officialDefinitions.has(def) && def.name !== 'run_code' && !unhealthy(def.name)).map(def => def.name).slice(0, MAX_NAMES);
107
+ const lines = [];
108
+ if (enhancements.length) lines.push(`Layer 1: additional capabilities outside the inherited official PTC baseline (bounded list): ${JSON.stringify(enhancements)}. Search their real descriptions and any available provider loader for a matching function first.`);
109
+ for (const route of routes) {
110
+ const fallbacks = route.fallback.filter(name => available.has(name));
111
+ if (available.has(route.preferred) || fallbacks.length) lines.push(
112
+ `Preference: ${JSON.stringify(route.preferred)}${unhealthy(route.preferred) ? ' failed; use a fallback until repaired' : available.has(route.preferred) ? ' available' : ' unavailable'}; candidate fallbacks currently admitted: ${JSON.stringify(fallbacks)}. Check capability and schema; this is not an argument mapping.`);
113
+ }
114
+ for (const [name, failure] of rows ?? []) {
115
+ const label = JSON.stringify(name);
116
+ if (failure.kind === 'denied') lines.push(`${label}: denied. Honor the policy/approval decision; do not route around it.`);
117
+ else if (failure.kind === 'not-dispatched') lines.push(`${label}: not dispatched. Check the original policy/guard/approval or preparation result; do not assume provider failure or switch tools around a denial.`);
118
+ else if (failure.kind === 'cancelled') lines.push(`${label}: cancelled. Do not retry or fall back unless the user authorizes continuing.`);
119
+ else if (failure.kind === 'input') lines.push(`${label}: input/argument failure. Diagnose the call and actual schema before choosing a recovery.`);
120
+ else if (failure.kind === 'command') lines.push(`${label}: foreground command exited unsuccessfully. Diagnose the command and its effects; do not switch shells or treat a nonzero exit alone as provider failure.`);
121
+ else if (failure.kind === 'partial') lines.push(`${label}: partial completion. Preserve completed work and inspect continuation/receipts before completing the remainder.`);
122
+ else if (failure.official) lines.push(`${label}: official fallback failed. Diagnose the actual error and effects; do not loop through the same failed call. Report a precise blocker if no other appropriate admitted capability exists.`);
123
+ else lines.push(`${label}: ${failure.kind}; reported effect state ${failure.effect}. Continue with an equivalent admitted official tool when possible. Inspect state before any mutation/command retry; never copy arguments between schemas.`);
124
+ }
125
+ if (!lines.length) return '';
126
+ lines.push(`Layer 2: visible official baseline tools (bounded list): ${JSON.stringify(official)}. Use an appropriate fallback when layer 1 has no matching working capability. Missing/hidden/step-inactive tools are unavailable; this layer never lifts restrictions.`);
127
+ return lines.join('\n');
128
+ },
129
+ dispose() { failures = new WeakMap(); dispatched = new WeakSet(); },
130
+ };
131
+ }
132
+
133
+ export function installToolCompatibility(ctx, { enabled = true, preferences = [] } = {}) {
134
+ if (!enabled) return;
135
+ const state = createCompatibilityState(ctx.tools, preferences);
136
+ ctx.systemPrompt.section({ name: 'deep-ptc:tool-compatibility', order: 10194, text: compatibilityPolicy });
137
+ ctx.systemPrompt.context({ name: 'deep-ptc:tool-recovery', order: 122, text: context => state.text(context) });
138
+ ctx.on('tools/execute', (exec, next) => { state.dispatched(exec); return next(); });
139
+ ctx.on('tools/result', (exec, result) => state.observe(exec, result));
140
+ ctx.effect(() => () => state.dispose());
141
+ }
package/lib/upstream.mjs CHANGED
@@ -107,6 +107,35 @@ export function parseOfficialPreset(text) {
107
107
  return preset;
108
108
  }
109
109
 
110
+ /** Base deployment declaration that names the shell executors the Harness ships. */
111
+ export const BASE_DECLARATION_SPECIFIER = '@deepseek-ai/dsh-base/cordis.patch.yml';
112
+ const EXECUTOR_ROW_IDS = { bash: 'bash-sandbox', pwsh: 'pwsh-sandbox' };
113
+
114
+ /**
115
+ * Read the official bash and PowerShell executor rows out of the base deployment declaration.
116
+ * @param text - YAML source of `@deepseek-ai/dsh-base/cordis.patch.yml`.
117
+ * @returns `{ bash?, pwsh? }`, each `{ name, config? }` as the declaration states it.
118
+ */
119
+ export function parseOfficialExecutors(text) {
120
+ const document = loadYaml().load(text, { schema: presetSchema() });
121
+ const found = {};
122
+ const visit = rows => {
123
+ if (!Array.isArray(rows)) return;
124
+ for (const row of rows) {
125
+ if (!row || typeof row !== 'object') continue;
126
+ for (const [kind, id] of Object.entries(EXECUTOR_ROW_IDS)) {
127
+ if (row.id !== id || typeof row.name !== 'string' || found[kind] !== undefined) continue;
128
+ const config = row.config && typeof row.config === 'object' && !Array.isArray(row.config) ? row.config : undefined;
129
+ found[kind] = { name: row.name, ...config === undefined ? {} : { config } };
130
+ }
131
+ visit(row.insert);
132
+ if (Array.isArray(row.config)) visit(row.config);
133
+ }
134
+ };
135
+ visit(Array.isArray(document) ? document : []);
136
+ return found;
137
+ }
138
+
110
139
  function tryResolve(specifier) {
111
140
  try {
112
141
  return import.meta.resolve(specifier);