dsh-deep-ptc-mode 1.7.1 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.7.2 — 2026-11-05
4
+
5
+ - Add local tool/skill discovery and complete-schema loading with bounded pages, byte budgets and recent selections. Reuse the installed official PTC SDK renderer, reducing only its untouched generated section. Skill discovery reads metadata and invocation controls; the official loader owns skill bodies.
6
+ - Quarantine failed external tools in durable conversation state. Block subsequent calls until the user resets; no automatic probing, retries or root-cause analysis. Capture provenance/reset generation before dispatch; keep cancellation, permission decisions and normal pagination intact.
7
+ - Add a bilingual Reload all tool states button below the composer and a user-only host command. Preserve running jobs. Project failed tool/provider lists at turn completion and request concise final-task reporting.
8
+ - Identify baseline registrations from the inherited composition rather than package naming patterns; support class-style official plugins while retaining their metadata.
9
+ - Preserve the original execution, reachability, question, planning and shell policies. Add regression coverage for quarantine persistence, reset races, SDK disclosure, skill metadata and UI actions.
10
+
3
11
  ## 1.7.1 — 2026-11-05
4
12
 
5
13
  - Publish the plugin-cooperation release with bilingual README introductions and package/repository descriptions: external capabilities first, multiple providers working together, and the current official PTC composition as fallback, following the “everything is a plugin” composition model. Preserve the original interruptible background-work behavior and document integration boundaries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Deep PTC mode
2
2
 
3
- [中文](README.zh.md) · MIT · **1.7.1**
3
+ [中文](README.zh.md) · MIT · **1.7.2**
4
4
 
5
5
  **Let plugins cooperate. Keep current official PTC tools as the fallback. Stay interruptible while work runs.**
6
6
 
@@ -23,28 +23,28 @@ An extension must publish into the `deep-ptc` scope and support the installed ho
23
23
 
24
24
  The official fallback retains the 1.6.1 derivation mechanism: each preset load or rebuild reads the PTC declaration from the currently installed Harness and follows its module names and configuration. The bundled snapshot is used only if loading, parsing or derivation fails, with a warning. Reload after an official upgrade and use a new preset revision; existing sessions are not forcibly switched. DSH support starts at `>=0.2.2-rc.1` with no upper bound; future host APIs still require verification.
25
25
 
26
- ## Two-layer tool compatibility (1.7.0)
26
+ ## 1.7.2: lightweight, on-demand tool orchestration
27
27
 
28
- Deep PTC adds no task tools. First search the available extension/plugin capabilities for the required function, using the provider's own discovery or SDK loader when needed, and prefer a suitable enhancement. If no enhancement fits or a provider fails, continue through an admitted inherited official PTC tool.
28
+ One tool/skill directory, `deep_ptc_tools`, coordinates discovery. Task operations still belong to external providers and the current official PTC tools.
29
29
 
30
- The runtime tracks official registration provenance and final outcomes, then supplies bounded per-agent recovery guidance on the next model step. The model rebuilds the call from the fallback's actual schema; no alias, argument translation, output conversion or silent replay is performed. Check receipts and read back state before continuing partially completed writes or commands. Empty searches and active background/promoted jobs are not provider failures. Denials, cancellation and guard decisions stay authoritative.
30
+ - **Search summaries, then load definitions.** Local metadata search prefers external tools, then returns official candidates when no extension matches. Pages default to six entries (maximum eight); disclose up to six complete schemas within a 16 KB budget per load. Official tools stay available; up to twelve recent extension selections enter the host-generated PTC SDK on demand.
31
+ - **One actual failure quarantines the tool for this conversation.** Subsequent execution is blocked in code and state persists with the session. Agent recreation, conversation restore and provider reload do not lift quarantine. Capture provenance and reset generation before dispatch; late pre-reset results cannot contaminate the new state. Empty results, normal pagination, denial, cancellation, invalid arguments and ordinary nonzero command exits are not automatically treated as broken plugins.
32
+ - **Finish the task; do not diagnose failed providers.** Move promptly to a working equivalent or official fallback. No probing, retrying or root-cause investigation. Read back only the task state necessary to avoid duplicate effects after a potentially partial mutation.
33
+ - **Brief completion reporting.** The model lists failed tools and declared provider names at completion. The runtime also projects an expandable compatibility notice after a turn ends. Unknown ownership is reported as unknown, never inferred from a tool name.
34
+ - **Reload from below the composer.** “Reload all tool states” clears quarantine and on-demand selections for the current conversation without a model call or stopping running jobs. The user slash command `/deep-ptc-reset-tools` provides the same action.
35
+ - **Two-stage skill use.** Search the host's resolved, model-invocable skill metadata, then load the exact name with the official `skill` tool and follow its full instructions. Reuse instructions already in context. Discovery never reads skill bodies.
31
36
 
32
- This layer does not replace the tool executor, lift another plugin's restrictions, or call captured private bodies. Foreground caps, steering, managed jobs and completion wakeups, timed questions, planning, persona and the selected shell remain unchanged. Third-party executors retain their own background/cancellation contracts; the official-tool wait wrapper cannot automatically control them.
33
-
34
- Providers must already publish tools into the `deep-ptc` scope and should retain official fallbacks through their own configuration. This does not install OPS or bypass its host-version and custom-preset integration requirements. Hidden/removed capabilities and an unavailable whole executor cannot be recovered by overriding authorization.
35
-
36
- Enabled by default. Optional settings under the existing `deep-ptc-settings` row:
37
-
38
- ```yaml
39
- toolCompatibility: true
40
- toolPreferences:
41
- - preferred: ops_grep
42
- fallback: [grep]
37
+ ```js
38
+ // Inside the official run_code tool; discovery itself never executes a found task tool.
39
+ const matches = await tools.deep_ptc_tools({ action: 'search', query: 'search files' });
40
+ const loaded = await tools.deep_ptc_tools({ action: 'load', names: ['actual_tool_name'] });
41
+ const skills = await tools.deep_ptc_tools({ action: 'skills', query: 'build test' });
42
+ // Next use each actual tool schema, or the official skill loader for a selected skill.
43
43
  ```
44
44
 
45
- Names must match the installed provider's real catalog. Preferences guide choices between existing capabilities, not dispatch mappings. Settings apply to new preset revisions; existing sessions retain their original revision.
45
+ Set `compactToolCatalog: false` under `deep-ptc-settings` to retain the full host SDK while keeping quarantine and reset. `toolCompatibility: false` disables the entire new layer. Optional `toolPreferences` still guide choices between existing tools.
46
46
 
47
- `node --test` covers recovery distinctions, scope isolation, reloads, live admission and unchanged execution configuration. `scripts/check-compatibility.cjs` exercises the real DSH pipeline and official web tools with an offline web-service double. The reachability integration runs with compatibility enabled. These checks do not constitute an online-model or actual-OPS end-to-end evaluation.
47
+ Compaction only changes an untouched SDK section generated by the installed official renderer. Provider-owned/custom SDKs keep their own loaders. Extensions must support the host and publish into `deep-ptc`; this layer does not override hidden tools, authorization or an unloaded whole executor. Actual OPS/online-model end-to-end integration has not been performed.
48
48
 
49
49
  ## Overview
50
50
 
@@ -120,10 +120,10 @@ A prompt changes the model's working tendency, not the real token limit or billi
120
120
  Requires Node `>=24` and DSH `>=0.2.2-rc.1`. Windows desktop rc.5 was used for real WSL/PowerShell command checks. macOS/Zsh configuration, argv and tool mounting were checked; native macOS execution has not been verified on this Windows host.
121
121
 
122
122
  ```js
123
- plugin_manager({ action: "install_bundle", target: "dsh-deep-ptc-mode@1.7.1" })
123
+ plugin_manager({ action: "install_bundle", target: "dsh-deep-ptc-mode@1.7.2" })
124
124
  // Or from a local checkout or archive:
125
125
  plugin_manager({ action: "install_bundle", target: "C:\\path\\to\\dsh-deep-ptc-mode" })
126
- // Or target: "C:\\path\\to\\dsh-deep-ptc-mode-1.7.1.tgz"
126
+ // Or target: "C:\\path\\to\\dsh-deep-ptc-mode-1.7.2.tgz"
127
127
  ```
128
128
 
129
129
  Repository locator: `github:lishize20040802-rgb/dsh-deep-ptc-mode`. It installs content actually published there; a local upgrade does not publish to GitHub or npm.
package/README.zh.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 深度 PTC 模式
2
2
 
3
- [English](README.md) · MIT · 当前版本:**1.7.1**
3
+ [English](README.md) · MIT · 当前版本:**1.7.2**
4
4
 
5
5
  **让插件协作,让当前官方 PTC 工具兜底,让任务始终可沟通。**
6
6
 
@@ -23,32 +23,28 @@
23
23
 
24
24
  官方兜底沿用 1.6.1 的动态派生机制:每次加载或重建预设时读取当前安装版本的官方 PTC 声明,工具模块和配置跟随该声明;仅在声明无法读取、解析或派生时使用随包快照并记录日志。官方升级后需重载并创建使用新版预设的会话,既有会话不被强制切换。最低支持 DSH `>=0.2.2-rc.1`,不设上限;更高版本仍需验证宿主接口。
25
25
 
26
- ## 两层工具兼容(1.7.0)
26
+ ## 1.7.2:轻量、按需、可恢复的工具调用层
27
27
 
28
- Deep PTC 自身不提供新的任务工具。工具选择分两层:**先在当前可用的外部插件能力中寻找同功能工具并调用;没有合适能力或工具故障时,自动用继承的官方 PTC 工具继续任务。** 可选工具的发现/SDK 加载仍使用相应插件自己的接口。
28
+ 本版增加一个工具与 Skill 的目录入口 `deep_ptc_tools`,具体任务继续交给外部插件和当前官方 PTC 工具完成。
29
29
 
30
- 运行时记录真实工具注册的来源,并观察宿主的最终调用结果;下一模型步骤获得当前可调用的两层能力和故障恢复指引。回退由模型按官方工具的真实参数重新组织调用,不把第三方参数、返回值或失败调用原样重放。空搜索、后台/转后台成功不触发故障回退;权限拒绝、用户取消和守卫拦截不会被当成换工具绕过的理由。写入、批处理或命令可能已部分完成时,必须先读回状态,再完成剩余工作。
30
+ - **先搜摘要,再加载定义。** 本地元数据检索优先返回外部工具,未找到匹配项时返回官方候选。默认每页 6 项,最多 8 项;完整 schema 每次最多加载 6 个、总预算 16 KB。普通官方工具继续可用,额外工具按需进入宿主生成的 PTC SDK,最多保留 12 个近期选择。
31
+ - **一次真实故障,本对话禁用。** 由程序拦截后续调用,故障记录随对话保存;切换 agent、恢复对话或重载插件不会自动解除。调用开始时捕获来源和状态代次,用户重载前的迟到结果不会污染新状态。普通空结果、分页续读、权限拒绝、取消、参数错误和命令非零退出不会被直接判为插件损坏。
32
+ - **任务优先,不查坏工具。** 确认工具故障后尽快改用其他可用同类工具或官方工具,不探测、不重试、不查根因。仅在写入或命令可能已部分完成时核查必要的任务状态,避免重复操作。
33
+ - **完成时简报。** 模型结束任务时简短列出失败工具与已声明的插件来源;程序同时在回合结束后生成可展开的“工具适配提醒”。来源不明就列工具名,不猜插件身份或故障原因。
34
+ - **输入框下方一键重载。** “重载所有工具状态”仅清除当前对话的故障标记与按需加载选择;不调用模型,也不停止正在运行的任务。另有用户命令 `/deep-ptc-reset-tools`。
35
+ - **Skill 两阶段调用。** 目录只查询宿主已解析的技能元数据和调用权限;选中后使用官方 `skill` 工具加载正文并遵守完整指令,复用上下文中已有指令。检索不读取 Skill 正文。
31
36
 
32
- 兼容层不替换工具执行器,不调用工具私有实现,不解除其他插件的隐藏/权限限制,也不改变后台执行、30 秒前台上限、插话让出等待、job 完成通知、限时提问、计划规则或所选 Shell。第三方执行器需遵守它自己的后台与取消契约,不能声称现有官方工具包装会自动控制它。
33
-
34
- 无需安装 OPS 才能启用此机制,也不写死某个插件。外部插件须先在 `deep-ptc` 的作用域里发布工具,且应在其自己的配置中保留官方兜底工具;OPS 的宿主版本范围与显式预设接入仍需该插件自身适配。若原工具被隐藏/删除,兼容层会如实说明不可用,不绕过宿主限制。
35
-
36
- 默认启用;可以在现有 `deep-ptc-settings` 配置中关闭,或指定可选的优先关系。优先关系只是选择提示,不是工具别名或参数映射:
37
-
38
- ```yaml
39
- - id: deep-ptc-settings
40
- config:
41
- toolCompatibility: true
42
- toolPreferences:
43
- - preferred: ops_grep
44
- fallback: [grep]
45
- - preferred: ops_read_files
46
- fallback: [read]
37
+ ```js
38
+ // 在官方 run_code 中使用;这些操作本身不会执行搜索到的任务工具。
39
+ const matches = await tools.deep_ptc_tools({ action: 'search', query: 'search files' });
40
+ const loaded = await tools.deep_ptc_tools({ action: 'load', names: ['实际工具名'] });
41
+ const skills = await tools.deep_ptc_tools({ action: 'skills', query: 'build test' });
42
+ // 之后按返回的真实 schema 调用工具,或通过官方 skill 加载选定技能。
47
43
  ```
48
44
 
49
- 上例名称须以实际安装版本的工具清单为准,不会安装插件或注册不存在的名称。配置与环境设置一样按预设版本应用于新会话;已创建会话保留原版本。
45
+ 可在 `deep-ptc-settings` 设置 `compactToolCatalog: false` 保留完整宿主 SDK,故障禁用与重载机制仍工作。`toolCompatibility: false` 则停用整套新增调用层。`toolPreferences` 继续支持对已有工具的可选优先关系。
50
46
 
51
- 离线测试覆盖两层指引、权限/取消/部分完成、会话隔离、工具重载、逐步激活和无新增工具。`scripts/check-compatibility.cjs` 使用真实 DSH 调用管线、官方 web 工具和不联网的测试 web 服务验证恢复指引及官方回退;`scripts/check-reachability.mjs` 在开启兼容层后继续验证原有可打断等待。它们不等于已完成真实 OPS 或在线模型端到端评测。
47
+ 精简只作用于当前官方渲染器生成且未被其他插件改写的 SDK 段;插件自建 SDK 继续由其自身加载器管理。外部插件仍须支持当前宿主并在 `deep-ptc` 作用域发布工具;本层不会绕过工具隐藏、授权或接管被卸载的整个执行器。未进行实际 OPS/在线模型端到端评测。
52
48
 
53
49
  ## 简介
54
50
 
@@ -126,10 +122,10 @@ WSL 命令使用 Linux/POSIX 语法;文件工具和 `workdir` 仍用 Windows
126
122
  本地目录或构建产物可通过插件管理器安装:
127
123
 
128
124
  ```js
129
- plugin_manager({ action: "install_bundle", target: "dsh-deep-ptc-mode@1.7.1" })
125
+ plugin_manager({ action: "install_bundle", target: "dsh-deep-ptc-mode@1.7.2" })
130
126
  // 也可从本地目录或安装包安装:
131
127
  plugin_manager({ action: "install_bundle", target: "C:\\path\\to\\dsh-deep-ptc-mode" })
132
- // 或 target: "C:\\path\\to\\dsh-deep-ptc-mode-1.7.1.tgz"
128
+ // 或 target: "C:\\path\\to\\dsh-deep-ptc-mode-1.7.2.tgz"
133
129
  ```
134
130
 
135
131
  GitHub 地址:`github:lishize20040802-rgb/dsh-deep-ptc-mode`。该地址安装远端实际内容;本地升级不会自动发布到 GitHub/npm。
package/lib/client.js CHANGED
@@ -97,6 +97,46 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
97
97
  );
98
98
  }
99
99
 
100
+ function ToolStateControls({ useProjection, reset, t }) {
101
+ const preset = useProjection('agentPreset');
102
+ const state = useProjection('deepPtcTools');
103
+ const [busy, setBusy] = React.useState(false);
104
+ const [message, setMessage] = React.useState('');
105
+ const generation = React.useRef(0);
106
+ React.useEffect(() => { generation.current++; setBusy(false); setMessage(''); return () => { generation.current++; }; }, [reset]);
107
+ if (preset !== 'deep-ptc' || !state) return null;
108
+ const failed = state?.report?.tools ?? [];
109
+ async function reload() {
110
+ const current = generation.current;
111
+ setBusy(true); setMessage('');
112
+ try {
113
+ const outcome = await reset();
114
+ if (current !== generation.current) return;
115
+ const result = outcome?.result ?? outcome;
116
+ if (result?.kind !== 'success') throw new Error(result?.text || t('toolResetFailed'));
117
+ setMessage(t('toolResetDone'));
118
+ } catch (error) { if (current === generation.current) setMessage(t('toolResetFailed')); }
119
+ finally { if (current === generation.current) setBusy(false); }
120
+ }
121
+ return h('div', { style: { display: 'grid', gap: '4px', padding: '4px 0', fontSize: '12px' } },
122
+ failed.length ? h('details', { role: 'status' },
123
+ h('summary', null, `${t('toolFailures')} (${failed.length})`),
124
+ h('p', null, t('toolFailureHint')),
125
+ h('ul', null, ...failed.map(row => h('li', { key: row.name }, `${row.name} — ${row.provider}`)))) : null,
126
+ h('button', { type: 'button', onClick: reload, disabled: busy, title: t('toolResetHint'),
127
+ style: { justifySelf: 'start', font: 'inherit', color: 'inherit', cursor: busy ? 'wait' : 'pointer' } }, busy ? t('toolResetBusy') : t('toolReset')),
128
+ message ? h('span', { role: 'status' }, message) : null);
129
+ }
130
+ Object.assign(dictionaries.zh, {
131
+ toolReset: '重载所有工具状态', toolResetBusy: '正在重载…', toolResetDone: '本对话工具状态已重载。',
132
+ toolResetFailed: '重载失败,请确认当前连接及操作权限。', toolResetHint: '清除本对话的故障标记和按需加载选择;正在运行的任务继续执行。',
133
+ toolFailures: '工具适配提醒', toolFailureHint: '以下外部工具调用失败,可能存在适配问题,已在本对话中禁用。任务会优先使用其他可用工具;未进一步排查故障原因。',
134
+ });
135
+ Object.assign(dictionaries.en, {
136
+ toolReset: 'Reload all tool states', toolResetBusy: 'Reloading…', toolResetDone: 'Tool states reloaded for this conversation.',
137
+ toolResetFailed: 'Reload failed. Check the connection and access permissions.', toolResetHint: 'Clear quarantine and on-demand selections in this conversation. Running jobs continue.',
138
+ toolFailures: 'Tool compatibility notice', toolFailureHint: 'These external tools failed and may have compatibility issues. They are disabled in this conversation. Continue with working alternatives; no root-cause investigation was performed.',
139
+ });
100
140
  function apply(ctx) {
101
141
  const t = ctx.locale.bind('deep-ptc');
102
142
  ctx.effect(() => ctx.locale.register('deep-ptc', dictionaries));
@@ -106,6 +146,10 @@ window.__ModuleLoader__.load({ id: 'dsh-deep-ptc-mode', factory: require => {
106
146
  name: 'plugins.item', id: 'deep-ptc', order: 41,
107
147
  label: () => t('title'), locale: 'deep-ptc',
108
148
  }, 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 }))));
109
153
  }
110
154
  return { apply, inject };
111
155
  } });
package/lib/host.mjs CHANGED
@@ -54,16 +54,25 @@ export function pluginOf(namespace) {
54
54
  */
55
55
  export async function applyOfficial(ctx, upstream, options, adapt) {
56
56
  const plugin = pluginOf(await importHost(upstream));
57
+ const tagged = child => adapt(adaptContext(child, {
58
+ tools: tools => registering(tools, definition => markOfficialTool(definition, upstream)),
59
+ }));
60
+ 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);
66
+ }
57
67
  if (typeof plugin?.apply !== 'function') {
58
68
  ctx.logger.warn('Deep PTC: %s is not an apply-style plugin; loading it without Deep PTC wait handling', upstream);
59
69
  return ctx.plugin(plugin, options);
60
70
  }
61
71
  return ctx.plugin({
72
+ ...plugin,
62
73
  name: plugin.name ?? upstream,
63
74
  ...plugin.inject === undefined ? {} : { inject: plugin.inject },
64
75
  ...plugin.Config === undefined ? {} : { Config: plugin.Config },
65
- apply: (child, config) => plugin.apply(adapt(adaptContext(child, {
66
- tools: tools => registering(tools, markOfficialTool),
67
- })), config),
76
+ apply: (child, config) => plugin.apply(tagged(child), config),
68
77
  }, options);
69
78
  }
package/lib/index.mjs CHANGED
@@ -15,6 +15,7 @@ export const Config = z.object({
15
15
  foregroundSeconds: z.number().step(1).min(5).max(600).default(DEFAULT_FOREGROUND_SECONDS).volatile(),
16
16
  toolCompatibility: z.boolean().default(true).volatile(),
17
17
  toolPreferences: z.any().default([]).volatile(),
18
+ compactToolCatalog: z.boolean().default(true).volatile(),
18
19
  hostPlatform: z.const(process.platform).default(process.platform).volatile(),
19
20
  });
20
21
 
@@ -25,6 +26,7 @@ function settingsOf(config) {
25
26
  foregroundSeconds: config.foregroundSeconds.get(),
26
27
  toolCompatibility: config.toolCompatibility.get(),
27
28
  toolPreferences: config.toolPreferences.get(),
29
+ compactToolCatalog: config.compactToolCatalog.get(),
28
30
  };
29
31
  }
30
32
 
package/lib/model.mjs CHANGED
@@ -150,9 +150,9 @@ export function isShellRow(row) {
150
150
 
151
151
  export function isOfficialCapabilityRow(row) {
152
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'));
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
156
  }
157
157
 
158
158
  function findRow(rows, { ids = [], names = [] }) {
@@ -312,7 +312,10 @@ export function deriveDeepPtc(upstream, options = {}, platform = process.platfor
312
312
  });
313
313
  plugins.push({
314
314
  id: uniqueRowId(plugins, 'tool-compatibility'), name: 'dsh-deep-ptc-mode/tool-compatibility',
315
- config: { enabled: options.toolCompatibility !== false, preferences: toolPreferences },
315
+ config: { enabled: options.toolCompatibility !== false, preferences: toolPreferences,
316
+ compact: options.compactToolCatalog !== false,
317
+ sdkProvider: findRow(upstream.plugins, {ids:['tool-executor-ptc'],names:['@deepseek-ai/dsh-tool-executor-ptc']})?.name ?? '@deepseek-ai/dsh-tool-executor-ptc',
318
+ skillProvider: findRow(upstream.plugins, {ids:['tool-skill'],names:['@deepseek-ai/dsh-tool-skill']})?.name ?? '@deepseek-ai/dsh-tool-skill' },
316
319
  });
317
320
 
318
321
  const description = `${PRESET_META.description} 当前环境:${environment}${environment === 'wsl' && distribution ? ` (${distribution})` : ''}`;
@@ -0,0 +1,45 @@
1
+ // Local metadata search only: no model calls, filesystem probing or skill-body reads.
2
+ const indexed = new WeakMap();
3
+ export const DIRECTORY_TOOL = 'deep_ptc_tools';
4
+ export const RESET_COMMAND = 'deep-ptc-reset-tools';
5
+ export const STATE_EVENT = 'plugin:dsh-deep-ptc-mode/tool-state';
6
+ export const STATE_KEY = 'deepPtcTools';
7
+ export function summary(definition) {
8
+ let row = indexed.get(definition);
9
+ if (!row) {
10
+ const name = String(definition.name);
11
+ const description = String(definition.description ?? '').slice(0, 240);
12
+ row = { name, description, text: `${name} ${description}`.toLowerCase() };
13
+ indexed.set(definition, row);
14
+ }
15
+ return row;
16
+ }
17
+ export function searchCatalog(definitions, query = '', offset = 0, limit = 6) {
18
+ const terms = String(query).slice(0, 512).toLowerCase().trim().split(/[\s,,]+/u).filter(Boolean).slice(0, 12);
19
+ const ranked = definitions.map(def => {
20
+ const row = summary(def);
21
+ const score = terms.reduce((sum, word) => sum + (row.name.toLowerCase().includes(word) ? 8 : row.text.includes(word) ? 1 : 0), 0);
22
+ return { row, score };
23
+ }).filter(entry => terms.length === 0 || entry.score > 0)
24
+ .sort((a, b) => b.score - a.score || (a.row.name < b.row.name ? -1 : a.row.name > b.row.name ? 1 : 0));
25
+ const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
26
+ const count = Math.max(1, Math.min(8, Number.isSafeInteger(limit) ? limit : 6));
27
+ return { total: ranked.length, results: ranked.slice(start, start + count).map(({ row }) => ({ name: row.name, description: row.description })),
28
+ nextOffset: start + count < ranked.length ? start + count : null };
29
+ }
30
+ export function toolSchema(def) {
31
+ return { name: def.name, description: def.description ?? '', parameters: def.parameters, output: def.output.schema };
32
+ }
33
+ export function blankState() { return { v: 1, epoch: 0, blocked: [], report: null }; }
34
+ export function parseState(value) {
35
+ if (!value || value.v !== 1 || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !Array.isArray(value.blocked)) throw new Error('Invalid Deep PTC tool state');
36
+ for (const row of value.blocked) if (!row || typeof row.name !== 'string' || row.name.length > 256 || typeof row.provider !== 'string' || typeof row.kind !== 'string') throw new Error('Invalid blocked tool');
37
+ return { v: 1, epoch: value.epoch, blocked: value.blocked.map(row => ({ name: row.name, provider: row.provider, kind: row.kind })), report: value.report ?? null };
38
+ }
39
+ export function foldToolState(state, event) {
40
+ if (event.type === STATE_EVENT && event.ignorable === true) {
41
+ try { return parseState(event.data); } catch { return state; }
42
+ }
43
+ if (event.type === 'turn/end' && state.blocked.length) return { ...state, report: { turn: event.data.turn, tools: state.blocked } };
44
+ return state;
45
+ }
@@ -1,7 +1,72 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
- import { installToolCompatibility } from './tool-policy.mjs';
2
+ import { installToolCompatibility, officialToolSource } from './tool-policy.mjs';
3
+ import { importHost } from './host.mjs';
4
+ import { DIRECTORY_TOOL, RESET_COMMAND, STATE_EVENT, STATE_KEY, blankState, parseState, foldToolState, searchCatalog, toolSchema } from './tool-catalog.mjs';
3
5
 
4
6
  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); }
7
+ export const inject = ['tools', 'systemPrompt', 'commands', 'sessionProjections'];
8
+ export const Config = z.object({ enabled: z.boolean().default(true), preferences: z.any().default([]),
9
+ compact: z.boolean().default(true), sdkProvider: z.string().default('@deepseek-ai/dsh-tool-executor-ptc'),
10
+ skillProvider: z.string().default('@deepseek-ai/dsh-tool-skill') });
11
+
12
+ export async function apply(ctx, config) {
13
+ if (!config.enabled) return;
14
+ const { appendPluginRecord } = await importHost('@deepseek-ai/dsh-session');
15
+ const schema = { parse: parseState };
16
+ const projection = await ctx.sessionProjections.register({ key: STATE_KEY, stateVersion: 1,
17
+ stateSchema: schema, init: blankState, apply: foldToolState,
18
+ wire: { viewSchema: schema, view: state => state, summary: false } });
19
+ ctx.effect(() => () => projection.dispose());
20
+ const state = installToolCompatibility(ctx, { preferences: config.preferences, storage: {
21
+ read: session => projection.stateOf(session),
22
+ write: (session, value) => appendPluginRecord(session, STATE_EVENT, value),
23
+ } });
24
+ ctx.commands.register({ name: RESET_COMMAND, description: '重载所有工具状态 / Reload all tool states',
25
+ handler: ({ agent }) => {
26
+ const count = state.reset(agent);
27
+ return { kind: 'success', text: `已重载本对话全部工具状态,清除 ${count} 个故障标记。正在运行的任务继续执行。 / All tool states reloaded for this conversation; ${count} quarantine marks cleared. Running jobs continue.` };
28
+ } });
29
+ ctx.tools.register({ name: DIRECTORY_TOOL,
30
+ description: 'Find tools or skills by function without loading all schemas. search returns compact tool summaries; load reveals complete schemas for selected tool names; skills returns summaries to load with the official skill tool. Never executes task tools or reads skill bodies.',
31
+ parameters: { type: 'object', additionalProperties: false, properties: {
32
+ action: { type: 'string', enum: ['search', 'load', 'skills'] }, query: { type: 'string' },
33
+ names: { type: 'array', items: { type: 'string' } }, offset: { type: 'integer' }, limit: { type: 'integer' },
34
+ }, required: ['action'] },
35
+ output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
36
+ async execute(args, exec) {
37
+ if (args.action === 'load') return state.load(exec.agent, args.names, exec.toolSet);
38
+ if (args.action === 'search') return state.search(exec.agent, args, exec.toolSet);
39
+ if (args.action !== 'skills') throw new Error('Unknown directory action');
40
+ const skills = ctx.get('skills');
41
+ const loader = ctx.tools.definitions(exec.agent, exec.toolSet).find(def => officialToolSource(def) === config.skillProvider);
42
+ if (typeof skills?.list !== 'function' || !loader) return { available: false, results: [], note: 'The official skill loader is unavailable.' };
43
+ const { isModelInvocable } = await importHost('@deepseek-ai/dsh-skill');
44
+ const directory = ctx.get('workingDirectory');
45
+ const lookup = { scope: exec.agent, signal: exec.signal, cwd: directory ? await directory.ensure(exec.agent, exec.signal) : undefined };
46
+ const entries = (await skills.list(lookup)).filter(isModelInvocable).map(row => ({ name: row.name, description: row.description ?? '' }));
47
+ return { available: true, ...searchCatalog(entries, args.query, args.offset, args.limit), loadWith: loader.name,
48
+ note: 'Load the exact selected name through the official skill tool, then follow its instructions. Reuse instructions already in context.' };
49
+ },
50
+ });
51
+ // Only reduce the installed official renderer's untouched generated SDK section.
52
+ let renderer;
53
+ const sdkCache = new WeakMap();
54
+ const same = (left, right) => left?.length === right.length && left.every((def, index) => def === right[index]);
55
+ try { renderer = await importHost(config.sdkProvider); } catch { ctx.logger.warn('Deep PTC: SDK renderer unavailable; retaining the complete host SDK.'); }
56
+ if (renderer?.renderToolsSdk) ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
57
+ const assembly = await next();
58
+ const runtime = ctx.get('ptcRuntime');
59
+ const render = runtime?.language === 'python' ? renderer.renderToolsSdkPy : runtime?.language === 'typescript' || runtime?.language === 'javascript' ? renderer.renderToolsSdk : undefined;
60
+ if (!render || !context.scope) return assembly;
61
+ const all = ctx.tools.definitions(context.scope, context.toolSet);
62
+ let cached = sdkCache.get(context.scope);
63
+ if (!cached || cached.render !== render || cached.format !== runtime.programFormat || !same(cached.all, all)) {
64
+ cached = { all, render, format: runtime.programFormat, original: render(all.map(toolSchema), runtime.programFormat) };
65
+ sdkCache.set(context.scope, cached);
66
+ }
67
+ const selected = state.sdkDefinitions(context.scope, context.toolSet, config.compact);
68
+ if (selected.length === all.length) return assembly;
69
+ if (!same(cached.selected, selected)) { cached.selected = selected; cached.text = render(selected.map(toolSchema), runtime.programFormat); }
70
+ return { ...assembly, sections: assembly.sections.map(section => section.name === 'tools:sdk' && section.text === cached.original ? { ...section, text: cached.text } : section) };
71
+ });
72
+ }
@@ -1,141 +1,184 @@
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
- }
1
+ import { DIRECTORY_TOOL, blankState, toolSchema, searchCatalog } from './tool-catalog.mjs';
2
+ const officialDefinitions = new WeakMap();
3
+ const validName = name => typeof name === 'string' && name.length > 0 && name.length <= 256 && !/[\u0000-\u001f]/u.test(name);
4
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ export function markOfficialTool(definition, provider = 'official PTC') { officialDefinitions.set(definition, provider); return definition; }
6
+ export function isOfficialTool(definition) { return officialDefinitions.has(definition); }
7
+ export function officialToolSource(definition) { return officialDefinitions.get(definition); }
8
+ export const compatibilityPolicy = `## Efficient tool cooperation
9
+ - Search available external capabilities by function using deep_ptc_tools. Load only matching definitions; then use their actual schemas. If none fit, use an admitted official PTC tool. Provider discovery/loaders remain authoritative for provider-specific SDKs.
10
+ - An external capability that fails is quarantined for this conversation. Do not retry, probe, diagnose or repair it; promptly use a working equivalent or the official fallback and focus on finishing the task. Only the user's Reload all tool states button resets quarantine.
11
+ - At task completion, briefly list the failed tool names and their declared plugins (or unknown source) and say there may be a compatibility problem. Do not claim a root cause. Mention completed work first.
12
+ - Preserve authorization, cancellation, the selected shell and managed jobs. Empty results and running/background jobs are not failures. Before replacing a partially completed write or command, read only the task state needed to avoid duplicate effects; this is task recovery, not plugin diagnosis.
13
+ - Search skills through deep_ptc_tools(action=skills), then use the official loader named by loadWith and follow its full instructions. Reuse already-loaded instructions in the current context; discovery summaries are not skill instructions.
14
+ - Never bypass hidden tools, policy denials, cancelled work or an unavailable whole executor. Deep PTC's existing foreground/steering wrappers continue to govern official execution.`;
15
+ export function classifyToolOutcome(exec, result) {
16
+ if (exec.signal?.aborted) return { kind: 'cancelled', effect: 'unknown' };
17
+ const value = object(result?.value) ? result.value : undefined;
18
+ if (value?.cancelled === true || ['cancelled', 'aborted'].includes(value?.status)) return { kind: 'cancelled', effect: 'unknown' };
19
+ if (value?.sandbox?.denied === true) return { kind: 'denied', effect: 'unknown' };
20
+ // Host job promotion is success even when the command has not finished yet.
21
+ if (!result?.isError && ['background', 'promoted'].includes(value?.kind)) return undefined;
22
+ if (!result?.isError && value?.kind === 'foreground' && typeof value.exitCode === 'number' && value.exitCode !== 0)
23
+ return { kind: 'command', effect: 'unknown' };
24
+ const status = typeof value?.status === 'string' ? value.status.toLowerCase() : '';
25
+ const failure = object(value?.failure) ? value.failure : undefined;
26
+ // A bounded read/page may be partial by design. Quarantine only a reported partial failure,
27
+ // not an ordinary continuation result with no failure indication.
28
+ if (!result?.isError && status === 'partial' && !failure) return undefined;
29
+ const failed = result?.isError === true || ['failed', 'error', 'unavailable', 'partial'].includes(status);
30
+ if (!failed) return undefined;
31
+ const rawCode = result?.error?.code ?? failure?.code;
32
+ const code = typeof rawCode === 'string' && /^[A-Z0-9_:-]{1,96}$/u.test(rawCode) ? rawCode : '';
33
+ const effect = ['none', 'unknown', 'partial', 'completed'].includes(failure?.effectState)
34
+ ? failure.effectState : 'unknown';
35
+ if (/ABORT|CANCEL/u.test(code) || status === 'cancelled') return { kind: 'cancelled', effect };
36
+ if (/DENIED|FORBIDDEN|POLICY|APPROVAL|PERMISSION|EACCES|EPERM|READ_ONLY/u.test(code))
37
+ return { kind: 'denied', effect };
38
+ if (/ARGUMENT|INVALID_ARGS|VALIDATION|ENOENT|NOT_FOUND/u.test(code) && code !== 'UNKNOWN_TOOL')
39
+ return { kind: 'input', effect };
40
+ if (status === 'partial') return { kind: 'partial', effect };
41
+ if (/UNKNOWN_TOOL|UNAVAILABLE|WORKER_MISSING|RUNTIME_MISSING/u.test(code) || status === 'unavailable')
42
+ return { kind: 'unavailable', effect };
43
+ return { kind: 'failure', effect };
44
+ }
45
+
46
+ export function normalizePreferences(preferences = []) {
47
+ if (!Array.isArray(preferences) || preferences.length > 32) throw new Error('toolPreferences must be an array with at most 32 entries');
48
+ const seen = new Set();
49
+ return preferences.map(row => {
50
+ if (!object(row) || !validName(row.preferred) || row.preferred === 'run_code'
51
+ || !Array.isArray(row.fallback) || row.fallback.length === 0 || row.fallback.length > 12
52
+ || row.fallback.some(name => !validName(name) || name === 'run_code' || name === row.preferred)
53
+ || seen.has(row.preferred)) throw new Error('Each tool preference needs a unique preferred tool and 1–12 distinct fallback names (not run_code)');
54
+ if (new Set(row.fallback).size !== row.fallback.length) throw new Error('Duplicate fallback names in toolPreferences');
55
+ seen.add(row.preferred);
56
+ return { preferred: row.preferred, fallback: [...row.fallback] };
57
+ });
58
+ }
59
+
60
+ export function createCompatibilityState(tools, preferences = [], storage = {}) {
61
+ const routes = normalizePreferences(preferences);
62
+ let sessions = new WeakMap();
63
+ let calls = new WeakMap();
64
+ const sessionOf = agent => object(agent?.session) ? agent.session : agent;
65
+ function entry(agent) {
66
+ if (storage.read && !object(agent?.session)) return undefined;
67
+ const session = sessionOf(agent);
68
+ if (!object(session)) return undefined;
69
+ let row = sessions.get(session);
70
+ if (!row) { row = { state: storage.read?.(session) ?? blankState(), selected: new Set() }; sessions.set(session, row); }
71
+ const current = storage.read?.(session);
72
+ if (current && current !== row.state) { if (current.epoch !== row.state.epoch) row.selected.clear(); row.state = current; }
73
+ return row;
74
+ }
75
+ function save(agent, row, state) {
76
+ storage.write?.(sessionOf(agent), state); // Persist first: an unsuccessful reset never clears quarantine.
77
+ row.state = state;
78
+ }
79
+ function definitions(agent, toolSet) { return tools.definitions(agent, toolSet).filter(def => validName(def.name)); }
80
+ const blocked = (agent, name) => entry(agent)?.state.blocked.some(row => row.name === name) ?? false;
81
+ const providerOf = def => officialDefinitions.get(def) ?? (typeof def?.deepPtc?.provider === 'string' ? def.deepPtc.provider.slice(0, 160) : 'unknown plugin');
82
+ const api = {
83
+ dispatched(exec) {
84
+ const row = entry(exec.agent);
85
+ if (!row || calls.has(exec)) return;
86
+ const definition = tools.get(exec.name, exec.agent, exec.toolSet);
87
+ calls.set(exec, { epoch: row.state.epoch, definition, official: !!definition && isOfficialTool(definition), provider: providerOf(definition) });
88
+ },
89
+ guard(exec) { return blocked(exec.agent, exec.name) ? `Deep PTC: ${JSON.stringify(exec.name)} is quarantined in this conversation. Do not retry or diagnose it. Continue with another admitted equivalent or official tool. Only the user can reload all tool states.` : undefined; },
90
+ observe(exec, result) {
91
+ const call = calls.get(exec);
92
+ if (!call || call.official || exec.name === DIRECTORY_TOOL || exec.name === 'run_code') return;
93
+ const row = entry(exec.agent);
94
+ if (!row || call.epoch !== row.state.epoch || blocked(exec.agent, exec.name)) return;
95
+ const outcome = classifyToolOutcome(exec, result);
96
+ // Authorization and cancelled actions must never be converted to provider failover.
97
+ if (!outcome || ['denied', 'cancelled', 'command', 'input'].includes(outcome.kind)) return;
98
+ const failure = { name: exec.name, provider: call.provider, kind: outcome.kind };
99
+ save(exec.agent, row, { ...row.state, blocked: [...row.state.blocked, failure] });
100
+ row.selected.delete(exec.name);
101
+ },
102
+ reset(agent) {
103
+ const row = entry(agent);
104
+ if (!row) throw new Error('No conversation is active');
105
+ const count = row.state.blocked.length;
106
+ save(agent, row, { ...blankState(), epoch: row.state.epoch + 1 });
107
+ row.selected.clear();
108
+ return count;
109
+ },
110
+ status(agent) { return entry(agent)?.state ?? blankState(); },
111
+ sdkDefinitions(agent, toolSet, compact = true) {
112
+ const row = entry(agent);
113
+ const excluded = new Set(row?.state.blocked.map(item => item.name));
114
+ return definitions(agent, toolSet).filter(def => !excluded.has(def.name)
115
+ && (!compact || isOfficialTool(def) || def.name === DIRECTORY_TOOL || row?.selected.has(def.name)));
116
+ },
117
+ search(agent, args, toolSet) {
118
+ const excluded = new Set(entry(agent)?.state.blocked.map(item => item.name));
119
+ const visible = definitions(agent, toolSet).filter(def => def.name !== DIRECTORY_TOOL && !excluded.has(def.name));
120
+ const external = visible.filter(def => !isOfficialTool(def));
121
+ const result = searchCatalog(external, args.query, args.offset, args.limit);
122
+ if (result.total) return { layer: 'external', ...result };
123
+ return { layer: 'official', ...searchCatalog(visible.filter(isOfficialTool), args.query, args.offset, args.limit) };
124
+ },
125
+ load(agent, names, toolSet) {
126
+ if (!Array.isArray(names) || names.length < 1 || names.length > 6 || names.some(name => !validName(name))) throw new Error('Load 1–6 exact tool names');
127
+ const live = new Map(definitions(agent, toolSet).map(def => [def.name, def]));
128
+ const row = entry(agent);
129
+ if (!row) throw new Error('No conversation is active');
130
+ let budget = 16000;
131
+ const loaded = [], unavailable = [];
132
+ for (const name of new Set(names)) {
133
+ const def = live.get(name);
134
+ if (!def || blocked(agent, name) || name === DIRECTORY_TOOL) { unavailable.push(name); continue; }
135
+ const schema = toolSchema(def);
136
+ const size = Buffer.byteLength(JSON.stringify(schema), 'utf8');
137
+ if (size > budget) { unavailable.push(name); continue; }
138
+ budget -= size;
139
+ row.selected.delete(name);
140
+ row.selected.add(name);
141
+ if (row.selected.size > 12) row.selected.delete(row.selected.values().next().value);
142
+ loaded.push(schema);
143
+ }
144
+ return { loaded, unavailable, nextStep: true, note: 'Unavailable names are hidden, quarantined, or exceed the complete-schema budget. No tool was executed. Use an equivalent or load fewer definitions.' };
145
+ },
146
+ text({ scope: agent, toolSet } = {}) {
147
+ if (!object(agent)) return '';
148
+ const row = entry(agent);
149
+ if (!row) return '';
150
+ const state = row.state;
151
+ const lines = [];
152
+ if (state.blocked.length) {
153
+ lines.push('Quarantined for this conversation; no retries or diagnosis. Finish the task using working equivalents. At completion briefly report these tool/plugin names and a possible compatibility problem:');
154
+ lines.push(JSON.stringify(state.blocked.slice(0, 8).map(({name,provider}) => ({name,provider}))));
155
+ if (state.blocked.length > 8) lines.push(`${state.blocked.length} tools total; the user interface retains the full list.`);
156
+ lines.push('Check only necessary task state before replacing a possibly partial mutation. Reset is a user action.');
157
+ }
158
+ const available = routes.length ? new Set(definitions(agent, toolSet).map(def => def.name)) : new Set();
159
+ for (const route of routes) {
160
+ if (available.has(route.preferred) && !blocked(agent, route.preferred)) lines.push(`Prefer ${JSON.stringify(route.preferred)} when applicable; visible equivalents: ${JSON.stringify(route.fallback.filter(name => available.has(name) && !blocked(agent, name)))}. Read live schemas.`);
161
+ }
162
+ return lines.join('\n');
163
+ },
164
+ dispose() { sessions = new WeakMap(); calls = new WeakMap(); },
165
+ };
166
+ return api;
167
+ }
168
+
169
+ export function installToolCompatibility(ctx, { enabled = true, preferences = [], storage } = {}) {
170
+ if (!enabled) return;
171
+ const state = createCompatibilityState(ctx.tools, preferences, storage);
172
+ ctx.systemPrompt.section({ name: 'deep-ptc:tool-compatibility', order: 10194, text: compatibilityPolicy });
173
+ ctx.systemPrompt.context({ name: 'deep-ptc:tool-recovery', order: 122, text: context => state.text(context) });
174
+ ctx.tools.guard(exec => state.guard(exec));
175
+ ctx.on('tools/execute', (exec, next) => {
176
+ const reason = state.guard(exec);
177
+ if (reason) return Promise.resolve({ isError: true, error: { message: reason }, content: [{ type: 'text', text: reason }] });
178
+ state.dispatched(exec);
179
+ return next();
180
+ });
181
+ ctx.on('tools/result', (exec, result) => state.observe(exec, result));
182
+ ctx.effect(() => () => state.dispose());
183
+ return state;
184
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-deep-ptc-mode",
3
- "version": "1.7.1",
4
- "description": "Plugin-first Deep PTC for DSH: multi-plugin cooperation, current official PTC fallback and interruptible background jobs. / DSH 深度 PTC:外部插件优先、多插件协作、动态官方工具兜底,保留后台运行与随时插话。",
3
+ "version": "1.7.2",
4
+ "description": "Lightweight Deep PTC: tool/skill discovery, multi-plugin cooperation, official fallback and interruptible jobs. / 轻量深度 PTC:工具与技能按需发现、多插件协作、官方兜底、后台可插话。",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "dsh-plugin",
@@ -53,7 +53,8 @@
53
53
  "inject": [
54
54
  "@deepseek-ai/dsh-client-locale",
55
55
  "@deepseek-ai/dsh-client-ui-settings",
56
- "@deepseek-ai/dsh-client-ui-plugin-manager"
56
+ "@deepseek-ai/dsh-client-ui-plugin-manager",
57
+ "@deepseek-ai/dsh-client-ui-commands"
57
58
  ]
58
59
  }
59
60
  },
@@ -85,7 +86,8 @@
85
86
  "@deepseek-ai/dsh-client-ui-slots": ">=0.2.2-rc.1",
86
87
  "@deepseek-ai/dsh-client-locale": ">=0.2.2-rc.1",
87
88
  "@deepseek-ai/dsh-web-app": ">=0.2.2-rc.1",
88
- "@deepseek-ai/dsh-base": ">=0.2.2-rc.1"
89
+ "@deepseek-ai/dsh-base": ">=0.2.2-rc.1",
90
+ "@deepseek-ai/dsh-client-ui-commands": ">=0.2.2-rc.1"
89
91
  },
90
92
  "peerDependenciesMeta": {
91
93
  "@deepseek-ai/schemastery": {
@@ -108,6 +110,9 @@
108
110
  },
109
111
  "@deepseek-ai/dsh-base": {
110
112
  "optional": true
113
+ },
114
+ "@deepseek-ai/dsh-client-ui-commands": {
115
+ "optional": true
111
116
  }
112
117
  },
113
118
  "dependencies": {