dsh-awesome-optimizer 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jaylor-Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,218 @@
1
- # Temporary Holding Version
1
+ # dsh-awesome-optimizer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [中文](README.zh.md)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
+ [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
+ [![GitHub release](https://img.shields.io/github/v/release/Jaylor-Wang/dsh-awesome-optimizer.svg)](https://github.com/Jaylor-Wang/dsh-awesome-optimizer/releases)
8
+ [![Tests](https://img.shields.io/badge/tests-21%20passed-brightgreen.svg)](test/)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
+
11
+ High-performance, non-invasive runtime policy, PTC-backed composite batch tooling, standalone refined system prompt engine (~80% token savings), and objective A/B turn telemetry plugin for the official [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`).
12
+
13
+ ---
14
+
15
+ ## Highlights in v1.5.0
16
+
17
+ - **RFC 2119 Restrictive Modal Capitalization & Salience**: Convergence reminders enforce `NEVER omit verification.` to block premature completion under step pressure. Restrictive boundaries (`ONLY`, `NEVER`, `STRICTLY`) are capitalized consistently across guidance, templates, and runtime intercept reasons.
18
+ - **Precision Tool Alignment with Official DSH Contracts**: `edit_batch` schema and parameter descriptions strictly mirror official `edit` tool semantics (`Provide file_path before old_string and new_string in the arguments`). Decoupled verbs (`produce deliverables`) prevent homonym collisions with native tools.
19
+ - **Refined Command Chaining Policy**: Relaxed `CHAINED_NETWORK_COMMAND` to safely permit chained non-blocking local commands like `git push` while strictly preventing Windows hanging on credentials and publish (`npm publish`).
20
+ - **Standalone `SYSTEM.md` Engine & ~80% Token Reduction (`placement: "replace-all"`)**: Completely prunes verbose official prompt sections, allowing a concise, standalone `~/.dsh/SYSTEM.md` (~380 tokens) to govern as the single authority. Saves ~1.6K tokens per turn.
21
+
22
+ ---
23
+
24
+ ## Core Features & Architecture
25
+
26
+ ### 1. Refined System Prompt & File-Driven Hot-Reload (`customPrompt`)
27
+
28
+ - **Standalone Mode (`placement: "replace-all"`)**:
29
+ Hooks into the DSH `system-prompt/assemble` waterfall to strip all official verbose sections (`harness:*`, `deployment:*`, `tool:*`, `deliverable:*`, `web:*`), preserving convergence guidance companion sections while presenting your refined `SYSTEM.md` as the standalone authority (~82% reduction from ~2,000 to ~380 tokens).
30
+ - **Dual-Layer Markdown Convention**:
31
+ Automatically discovers global `~/.dsh/SYSTEM.md` (or `$DSH_HOME/SYSTEM.md`) and project workspace `.dsh/SYSTEM.md` (or `SYSTEM.md`), cleanly separating developer system defaults from repo-specific instructions.
32
+ - **Millisecond Hot-Reload**:
33
+ Uses debounced `fs.watch` to detect prompt file edits and applies them reactively on the very next turn without restarting the DSH process.
34
+ - **Flexible Cascading Strategies**:
35
+ Supports `concat` (cascading global and workspace prompts, default) and `workspace-override` (repo prompt completely replaces global prompt).
36
+ - **Built-in Prompt Linter & Auto-Fixer**:
37
+ Provides `lintPrompt` / `fixPrompt` / `lintPromptFile` APIs with **preset-aware dynamic tool validation**. Eliminates subjective tool assumptions by verifying tool directives directly against active plugins: flags redundant defensive clauses for unloaded tools or conflicts with actively loaded tools, checks weak modals (`bias toward` -> `Prioritize`), unclosed backticks, and enforces RFC 2119 uppercase constraints with actionable health scoring (0-100).
38
+
39
+ | Dimension | Official Default System Prompt | Optimized with This Plugin | Savings |
40
+ | :--- | :--- | :--- | :--- |
41
+ | **Token Usage** | ~2,000 tokens / turn | **~380 tokens / turn** | **~82% token reduction** |
42
+ | **Long Multi-Turn Sessions** | ~100K redundant tokens across 50 turns | Clean, focused, high-density context | **Mitigates context drift & forgetting** |
43
+ | **Config Updates** | Requires restart or reload | Instant hot-reload on file save | **Immediate feedback** |
44
+
45
+ ### 2. PTC Native Composite Batch Tooling (`compositeTools`)
46
+
47
+ - **`read_batch`**:
48
+ Concurrently inspects up to 10 targeted file snippets in a single turn. Ideal for broad multi-file investigation and dependency tracing.
49
+ - **`edit_batch`**:
50
+ Sequentially applies up to 10 targeted literal text replacements across single or multiple files in one round trip. Tolerates partial failures without losing preceding valid edits.
51
+ - **Inherited Security & Sandboxing**:
52
+ Every sub-action is dispatched through the official `ToolExecutionPipeline` (`tool/ptc-dispatch-start` / `tool/ptc-dispatch`), preserving file policy locks, mutation guards, and audit hooks.
53
+
54
+ ### 3. Defensive Runtime Policy & Self-Healing Recovery
55
+
56
+ - **No-Progress Circuit Breaker (`NO_PROGRESS`)**:
57
+ Computes deterministic tool invocation fingerprints. If an identical failing tool call repeats up to `noProgressLimit` (default `2`), the plugin blocks execution at `tools/pre-execute`, forcing the agent to adapt its diagnostic approach.
58
+ - **Windows Oversized Shell Command Interception (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
59
+ Automatically blocks commands exceeding `4096` bytes or inline scripts (`node -e`, `python -c`, `pwsh -Command`) exceeding `512` bytes, steering the model to write deliverables to disk first.
60
+ - **Windows Chained Network Command Guard (`CHAINED_NETWORK_COMMAND`)**:
61
+ Intercepts compound shell commands that chain network/credential-bound operations (`npm publish`) with local operations during `tools/pre-execute`. Enforces clean two-tier execution: local operations chained via `&&` for zero-RTT speed, and network operations isolated standalone to eliminate Windows process handle hanging and 120s timeouts.
62
+ - **Full Overwrite Protection & Single-Shot Recovery (`failureRecovery`)**:
63
+ Prevents accidental destructive `write` overwrites on existing large files when `edit` is available. Automatically registers `retry_failed_write` when a large write (8KB–1MB) is rejected due to an unpaired justification, avoiding costly regeneration.
64
+
65
+ ### 4. Lightweight Convergence & Objective A/B Telemetry
66
+
67
+ - **Micro-Directive Convergence (`convergence`)**:
68
+ Appends soft guidance notices when steps approach budget intervals (default `stepInterval: 8`, max `4` per turn). Features **error-aware suppression**: automatically silences notices during debugging so trouble resolution remains uninterrupted.
69
+ - **Objective A/B Telemetry (`telemetry`)**:
70
+ Collects granular operational metrics including model requests, tool calls, composite parallelism ratio (`parallelismRatio`), time-to-first-token (TTFT), token consumption, and prefix cache stability (`prefixChanges`).
71
+
72
+ ---
73
+
74
+ ## Installation & Quickstart
75
+
76
+ ### 1. Via DSH Plugin Command (Recommended)
77
+
78
+ ```bash
79
+ # Add directly to the active web profile
80
+ dsh plugin --profile web add dsh-awesome-optimizer
81
+ ```
82
+
83
+ ### 2. Via npm / pnpm
84
+
85
+ ```bash
86
+ # Using npm
87
+ npm install dsh-awesome-optimizer
88
+
89
+ # Using pnpm
90
+ pnpm add dsh-awesome-optimizer
91
+ ```
92
+
93
+ ### 3. Zero-Config Out of the Box
94
+
95
+ All optimizations are enabled by default upon installation. **No extra lines are required in your global `cordis.patch.yml`**.
96
+
97
+ #### Optional Advanced Overrides / Disabling
98
+ Only when customizing paths or disabling specific subsystems do you need to add an entry in `cordis.patch.yml`:
99
+
100
+ ```yaml
101
+ # Example: Only declare overrides when customizing defaults
102
+ - id: agent-optimizer
103
+ config:
104
+ # Disable prompt takeover to revert to official verbose prompt
105
+ customPrompt:
106
+ enabled: false
107
+
108
+ # Or adjust batch limits
109
+ compositeTools:
110
+ maxBatchFiles: 15
111
+ maxBatchEdits: 15
112
+
113
+ # Or relax the no-progress circuit breaker
114
+ runtimePolicy:
115
+ noProgressLimit: 3
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Production-Ready SYSTEM.md Recommendation
121
+
122
+ With `placement: "replace-all"`, place your directives in `~/.dsh/SYSTEM.md` (Windows: `C:\Users\<Username>\.dsh\SYSTEM.md`):
123
+
124
+ <details>
125
+ <summary>Click to expand production-ready universal prompt template (50 lines, native tools only)</summary>
126
+
127
+ ```markdown
128
+ # AUTONOMOUS AGENT CORE DIRECTIVE
129
+
130
+ You are a master autonomous software engineer powered by DeepSeek Harness.
131
+
132
+ - Prioritize direct action over speculation: investigate via concurrent tools (fs, bash, skills) without orchestration overhead.
133
+ - NEVER emit pre-action narration. Deliver surgical edits and high-signal conclusions.
134
+ - Irreversible operations (npm publish): STRICTLY conservative and non-autonomous. NEVER bump versions or mutate artifacts to bypass failures; registry validation causes transient 404 or stale views—NEVER treat as failure or retry publish. MUST verify remote state with read-only commands before declaring status.
135
+
136
+ ## Defaults
137
+
138
+ - Reply in Chinese; code comments and commit messages in English unless requested otherwise. In user-facing text, preserve Windows path formats as written (`E:\...`).
139
+ - Answer / explain / review / diagnose / plan: inspect and report without edits unless requested otherwise.
140
+ - Change / build / fix: make the smallest in-scope edits necessary for the requested task; task authorization includes necessary edits to related files. Keep changes conservative and reversible. Preserve unrelated user work. Do not reset or clean the working tree unless explicitly requested. Do not perform unrelated cleanup, reformatting, dependency changes, or test rewrites. Task-created temporary artifacts may be removed after use. New tests ONLY via Verification.
141
+ - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
+ - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
+ - Web & external: research/fetch via available skills or bash CLIs.
144
+
145
+ ## Efficiency
146
+
147
+ ### Hard Constraints
148
+
149
+ - Tool exclusivity: STRICTLY native `glob`/`grep`/`read_batch`/`read`/`edit_batch`/`edit`/`write`. NEVER use shell commands or redirects for workspace search or file ops (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) is fine.
150
+ - Failure recovery: retry ONLY when errors or new evidence suggest a specific fix; after two consecutive failures without progress, switch diagnostic approaches or input methods instead of repeating attempts.
151
+ - Windows arguments & paths: use forward slashes or quoted paths in tool arguments to avoid escape corruption (`\t`, `\n`). For complex or multiline payloads (`node -e`, `python -c`, `pwsh -Command`), prioritize supported stdin or file inputs. Avoid raw multiline arguments through `.cmd`/`.bat` wrappers.
152
+ - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless conversion is explicitly requested.
153
+ - Policy denials (`file access denied`, network blocked, approval rejected) are policy boundaries, not command bugs: report immediately without retrying or bypassing. Request `sandbox_permissions` ONLY when escalation is explicitly available.
154
+
155
+ ### Execution & Context Efficiency
156
+
157
+ - Workflow:
158
+ - Complexity: simple → execute; high-scope (cross-module, API, schema) → generate / follow plan (`<name>.md`); define 1–3 sentence scope and exit criteria before edits.
159
+ - Scheduling: Prioritize `read_batch` for multi-file inspection; keep edits, retries, and dependent checks sequential.
160
+ - Diagnosis: contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
161
+ - Search & navigation:
162
+ - Files & text: native `glob`/`grep` (gitignore-aware by default; pass `gitignore: false` for ignored paths); broad matches → narrow `path`/glob or page via `skip`, NEVER truncate blindly. Use `git` via `bash` ONLY for git-specific facts (tracked status, history, diffs).
163
+ - Scope & environment: verify via `git rev-parse --is-inside-work-tree` when workspace boundary is ambiguous (do not probe `.git`). Probe binary availability via `which`/`command -v`, NEVER scan directory listings.
164
+ - Runtime context: `pwd`/runtime cwd defines the workspace; the DSH implementation checkout is ONLY for inspecting/extending DSH—NEVER infer cwd from it or edit it unless asked. "This page/GUI" means the runtime Web GUI URL (no implicit DOM). Editing `~/.dsh/SYSTEM.md` hot-reloads the live prompt.
165
+ - Modification & execution:
166
+ - File ops: produce deliverables directly. Prioritize `edit_batch` for applying targeted replacements across one or more files in a single turn. Prioritize `edit` for single partial modifications; use `write` for new files or necessary full replacements. Unified calc/verification scripts permitted via `write`.
167
+ - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
168
+ - Shell execution: system binaries, external CLIs, builds, package managers, test runners — STRICTLY via `bash`. Prioritize chaining local non-blocking operations via `&&` (`git add ... && git commit ... && npm test`) to eliminate round-trip latency; keep network- or credential-bound commands (`npm publish`, remote fetch) separate to prevent Windows process handle hanging and timeouts.
169
+ - Reporting: diffs and evidence first; zero filler. Routine status ≤ 300 Chinese characters. Answer/explain/review/diagnose/plan: no length cap. Compact locators, lists, and deltas only.
170
+
171
+ ## Verification
172
+
173
+ Applies ONLY to change/build/fix.
174
+
175
+ - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
176
+ - Tiered verification by risk; prioritize existing relevant checks; add targeted tests when behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
177
+ - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
178
+ - Behavior changes: run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
179
+ - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
180
+ - Report checks, results, and verification gaps.
181
+ - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
182
+ ```
183
+ </details>
184
+
185
+ ---
186
+
187
+ ## Verification & Benchmarking
188
+
189
+ ```bash
190
+ # Link local peer dependencies from installed DSH host (zero network requests)
191
+ npm run setup:local
192
+
193
+ # Run integration tests against official @deepseek-ai/dsh-agent-loop
194
+ npm test
195
+
196
+ # Run strict TypeScript declaration check
197
+ npm run typecheck
198
+
199
+ # Run offline A/B benchmark verification
200
+ npm run benchmark
201
+ ```
202
+
203
+ ---
204
+
205
+ ## Architectural Principles & Safety
206
+
207
+ 1. **Official Loop Ownership (`@deepseek-ai/dsh-agent-loop`)**:
208
+ Turn state machines, native parallel scheduling (`maxParallelToolCalls`), retries, and cancellation semantics remain fully owned by the official loop. This plugin purely mounts additively via Cordis and **never replaces or tampers with** `@deepseek-ai/dsh-agent-loop`.
209
+ 2. **Zero Model Parameter Mutation**:
210
+ The plugin never hooks `agent/request` to modify model identities, providers, or reasoning efforts.
211
+ 3. **Transparent Pipeline Security**:
212
+ All composite operations are audited and dispatched individually through the official ToolExecutionPipeline.
213
+
214
+ ---
215
+
216
+ ## License
217
+
218
+ [MIT](LICENSE) © [Jaylor-Wang](https://github.com/Jaylor-Wang)
package/README.zh.md ADDED
@@ -0,0 +1,218 @@
1
+ # dsh-awesome-optimizer
2
+
3
+ [English](README.md) | 中文
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
+ [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
+ [![GitHub release](https://img.shields.io/github/v/release/Jaylor-Wang/dsh-awesome-optimizer.svg)](https://github.com/Jaylor-Wang/dsh-awesome-optimizer/releases)
8
+ [![Tests](https://img.shields.io/badge/tests-21%20passed-brightgreen.svg)](test/)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
+
11
+ 围绕官方 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`) 打造的高性能非侵入式运行期防护、PTC 复合批处理工具、全新独立系统提示词接管(~80% Token 极致瘦身)与客观 A/B 轮次度量插件。
12
+
13
+ ---
14
+
15
+ ## v1.5.0 版本重要更新
16
+
17
+ - **RFC 2119 强约束语气与注意力锚定加固**:收敛软提醒全面升级为 `NEVER omit verification.`,杜绝步数压力下的偷懒与提前交卷;在常驻收敛规范、推荐模板及拦截提示中全局统一大写强约束词(`ONLY`、`NEVER`、`STRICTLY`)。
18
+ - **工具定义与官方 DSH 契约像素级对齐**:`edit_batch` 参数描述精准对齐官方 `edit` 工具约定(显式要求提供 `file_path` 优先顺序),彻底消除动词混淆(统一为 `produce deliverables`),确保模型复用对原生工具的先验理解。
19
+ - **细粒度复合网络命令拦截放行**:精准优化 `CHAINED_NETWORK_COMMAND` 防护规则,在彻底杜绝 `npm publish` 等 Windows 凭据与发布操作悬挂的同时,完全放行本地与协同的复合 `git push` 流水线。
20
+ - **全新 `SYSTEM.md` 独立接管与 80% Token 极致瘦身 (`placement: "replace-all"`)**:彻底剥离官方约 2,000 tokens 的冗长提示词,全局统一由独立的 `~/.dsh/SYSTEM.md`(约 380 tokens)作为唯一最高指令集,每轮节省约 1.6K tokens 上下文空间。
21
+
22
+ ---
23
+
24
+ ## 核心特性与架构设计
25
+
26
+ ### 1. 系统提示词精简与文件驱动热重载 (`customPrompt`)
27
+
28
+ - **独立接管模式 (`placement: "replace-all"`)**:
29
+ 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将原始高达 ~2,000 tokens 的提示词压缩至约 380 tokens(降幅达 **82%**)。
30
+ - **双层 Markdown 规约**:
31
+ 自动寻找全局配置 `~/.dsh/SYSTEM.md`(或 `$DSH_HOME/SYSTEM.md`)与项目级工作区配置 `.dsh/SYSTEM.md`(或 `SYSTEM.md`)。权责清晰,与面向角色的 `AGENTS.md` 解耦。
32
+ - **毫秒级防抖热重载(Hot-Reload)**:
33
+ 基于 `fs.watch` 深度监视提示词文件变更,修改保存后下一轮交互即刻生效,无需重启 DSH 守护进程。
34
+ - **级联策略灵活可选**:
35
+ 支持 `concat`(全局与工作区级联合并,默认)与 `workspace-override`(项目级完全覆盖全局)。
36
+ - **内置 Prompt Linter 健康度校验与一键修复**:
37
+ 提供 `lintPrompt` / `fixPrompt` / `lintPromptFile` API。**基于用户当前预设加载的插件工具做动态客观判定**,杜绝主观臆断:当工具未在预设加载时提示冗余防守,当工具已加载却声明禁用时提示配置冲突,并校验弱语气词(如 `bias toward` 自动升级为 `Prioritize`)、RFC 2119 强约束大写规范及未闭合反引号,输出健康度打分(0-100)并支持一键无损修复。
38
+
39
+ | 指标维度 | 官方默认 System Prompt | 开启本插件优化后 | 收益 |
40
+ | :--- | :--- | :--- | :--- |
41
+ | **Token 占用** | ~2,000 tokens / 轮 | **~380 tokens / 轮** | **节省 ~82% 提示词消耗** |
42
+ | **长轮次会话累积** | 50 轮累计消耗 ~100K 冗余上下文 | 上下文干净紧凑,核心指令专注 | **显著缓解上下文漂移与遗忘** |
43
+ | **配置修改生效** | 需重启服务或重载配置文件 | 文件修改保存即刻热生效 | **即写即调,毫秒级响应** |
44
+
45
+ ### 2. PTC 原生复合批处理工具 (`compositeTools`)
46
+
47
+ - **`read_batch`**:
48
+ 支持单次并发读取最多 10 个指定文件的文本片段。大幅加速多模块依赖排查、跨文件上下文搜集任务。
49
+ - **`edit_batch`**:
50
+ 支持单次顺序执行最多 10 处跨单个或多个文件的字面量精准文本替换。容忍局部错误而不影响同批次其他成功编辑,彻底避免多轮串行 `edit` 带来的网络空转。
51
+ - **原生沙箱与安全事务继承**:
52
+ 所有子操作均通过官方 `ToolExecutionPipeline` (`tool/ptc-dispatch-start` / `tool/ptc-dispatch`) 分发,完整保留 DSH 沙箱权限判定、文件变更审核与观察策略钩子。
53
+
54
+ ### 3. 运行期硬防护与失败自愈机制
55
+
56
+ - **连续无进展失败熔断 (`NO_PROGRESS`)**:
57
+ 基于输入参数指纹计算,当同一工具以相同参数连续失败达到 `noProgressLimit`(默认 `2` 次)时,在 `tools/pre-execute` 阶段立即硬拦截并强迫模型转换诊断思路,杜绝死循环。
58
+ - **Windows 超大 Shell 载荷拦截 (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
59
+ 自动拦截超过 `4096` 字节的 `bash` 命令,或超过 `512` 字节的内联脚本参数(`node -e`、`python -c`、`pwsh -Command` 等),引导模型先通过原生 `write` 落盘再执行,规避 Windows 命令行参数溢出崩溃。
60
+ - **Windows 复合网络命令挂起防御 (`CHAINED_NETWORK_COMMAND`)**:
61
+ 在 `tools/pre-execute` 阶段自动拦截将网络/凭据操作(`npm publish` 等)与本地耗时操作混合串联的复合命令,强行引导模型执行两分法:本地确定性操作(`git add ... && git commit ... && npm test`)复合提速,网络发布独立把关,彻底规避 Windows 子进程句柄悬挂与 120s 超时。
62
+ - **大文件覆写防御与快速重放恢复 (`failureRecovery`)**:
63
+ 保护已存在的大文件不被全量 `write` 误覆盖;针对大文件写入(8KB–1MB)因缺失配对 `justification` 被拒的场景,提供 `retry_failed_write` 快捷工具,由宿主从缓存直接重放,避免大模型重新生成数千行代码。
64
+
65
+ ### 4. 轻量软收敛提示与客观 A/B 度量
66
+
67
+ - **轻量微指令收敛 (`convergence`)**:
68
+ 在步数达到阈值后追加精简的 `notice` 收敛引导(默认 `stepInterval: 8`,每轮上限 `4` 次),且内置**错误感知避让**:模型上一步工具调用报错时自动静默,优先保证排错连贯性。
69
+ - **客观 A/B 效果度量 (`telemetry`)**:
70
+ 内置细粒度性能度量,实时追踪模型请求数、工具调用数、批处理并发比率(`parallelismRatio`)、首字延迟(TTFT)、Token 消耗与前缀稳定性(`prefixChanges`),支持基线差值对比。
71
+
72
+ ---
73
+
74
+ ## 安装与快速上手
75
+
76
+ ### 1. 通过 DSH 插件命令安装(推荐)
77
+
78
+ ```bash
79
+ # 直接安装至当前激活的 web profile
80
+ dsh plugin --profile web add dsh-awesome-optimizer
81
+ ```
82
+
83
+ ### 2. 通过 npm / pnpm 安装
84
+
85
+ ```bash
86
+ # 使用 npm
87
+ npm install dsh-awesome-optimizer
88
+
89
+ # 使用 pnpm
90
+ pnpm add dsh-awesome-optimizer
91
+ ```
92
+
93
+ ### 3. 零配置开箱即用
94
+
95
+ 本插件在安装后**开箱即用,默认最佳实践已全量激活**。用户的全局 `cordis.patch.yml` **无需添加任何多余配置行**。
96
+
97
+ #### 高级定制 / 仅维护禁用配置(可选)
98
+ 仅在需要覆盖默认路径或禁用某项能力时,才需在 `cordis.patch.yml` 中声明:
99
+
100
+ ```yaml
101
+ # 示例:仅在需要覆盖或局部禁用时编写
102
+ - id: agent-optimizer
103
+ config:
104
+ # 局部停用系统提示词接管(改用官方默认)
105
+ customPrompt:
106
+ enabled: false
107
+
108
+ # 或微调批处理大小
109
+ compositeTools:
110
+ maxBatchFiles: 15
111
+ maxBatchEdits: 15
112
+
113
+ # 或放宽无进展熔断阈值
114
+ runtimePolicy:
115
+ noProgressLimit: 3
116
+ ```
117
+
118
+ ---
119
+
120
+ ## 生产级 SYSTEM.md 最佳实践
121
+
122
+ 配合 `placement: "replace-all"` 模式,推荐在全局目录创建 `~/.dsh/SYSTEM.md`(Windows 下为 `C:\Users\<用户名>\.dsh\SYSTEM.md`):
123
+
124
+ <details>
125
+ <summary>点击展开查看开箱即用通用提示词模板(50 行,纯原生工具无外部依赖)</summary>
126
+
127
+ ```markdown
128
+ # AUTONOMOUS AGENT CORE DIRECTIVE
129
+
130
+ You are a master autonomous software engineer powered by DeepSeek Harness.
131
+
132
+ - Prioritize direct action over speculation: investigate via concurrent tools (fs, bash, skills) without orchestration overhead.
133
+ - NEVER emit pre-action narration. Deliver surgical edits and high-signal conclusions.
134
+ - Irreversible operations (npm publish): STRICTLY conservative and non-autonomous. NEVER bump versions or mutate artifacts to bypass failures; registry validation causes transient 404 or stale views—NEVER treat as failure or retry publish. MUST verify remote state with read-only commands before declaring status.
135
+
136
+ ## Defaults
137
+
138
+ - Reply in Chinese; code comments and commit messages in English unless requested otherwise. In user-facing text, preserve Windows path formats as written (`E:\...`).
139
+ - Answer / explain / review / diagnose / plan: inspect and report without edits unless requested otherwise.
140
+ - Change / build / fix: make the smallest in-scope edits necessary for the requested task; task authorization includes necessary edits to related files. Keep changes conservative and reversible. Preserve unrelated user work. Do not reset or clean the working tree unless explicitly requested. Do not perform unrelated cleanup, reformatting, dependency changes, or test rewrites. Task-created temporary artifacts may be removed after use. New tests ONLY via Verification.
141
+ - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
+ - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
+ - Web & external: research/fetch via available skills or bash CLIs.
144
+
145
+ ## Efficiency
146
+
147
+ ### Hard Constraints
148
+
149
+ - Tool exclusivity: STRICTLY native `glob`/`grep`/`read_batch`/`read`/`edit_batch`/`edit`/`write`. NEVER use shell commands or redirects for workspace search or file ops (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) is fine.
150
+ - Failure recovery: retry ONLY when errors or new evidence suggest a specific fix; after two consecutive failures without progress, switch diagnostic approaches or input methods instead of repeating attempts.
151
+ - Windows arguments & paths: use forward slashes or quoted paths in tool arguments to avoid escape corruption (`\t`, `\n`). For complex or multiline payloads (`node -e`, `python -c`, `pwsh -Command`), prioritize supported stdin or file inputs. Avoid raw multiline arguments through `.cmd`/`.bat` wrappers.
152
+ - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless conversion is explicitly requested.
153
+ - Policy denials (`file access denied`, network blocked, approval rejected) are policy boundaries, not command bugs: report immediately without retrying or bypassing. Request `sandbox_permissions` ONLY when escalation is explicitly available.
154
+
155
+ ### Execution & Context Efficiency
156
+
157
+ - Workflow:
158
+ - Complexity: simple → execute; high-scope (cross-module, API, schema) → generate / follow plan (`<name>.md`); define 1–3 sentence scope and exit criteria before edits.
159
+ - Scheduling: Prioritize `read_batch` for multi-file inspection; keep edits, retries, and dependent checks sequential.
160
+ - Diagnosis: contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
161
+ - Search & navigation:
162
+ - Files & text: native `glob`/`grep` (gitignore-aware by default; pass `gitignore: false` for ignored paths); broad matches → narrow `path`/glob or page via `skip`, NEVER truncate blindly. Use `git` via `bash` ONLY for git-specific facts (tracked status, history, diffs).
163
+ - Scope & environment: verify via `git rev-parse --is-inside-work-tree` when workspace boundary is ambiguous (do not probe `.git`). Probe binary availability via `which`/`command -v`, NEVER scan directory listings.
164
+ - Runtime context: `pwd`/runtime cwd defines the workspace; the DSH implementation checkout is ONLY for inspecting/extending DSH—NEVER infer cwd from it or edit it unless asked. "This page/GUI" means the runtime Web GUI URL (no implicit DOM). Editing `~/.dsh/SYSTEM.md` hot-reloads the live prompt.
165
+ - Modification & execution:
166
+ - File ops: produce deliverables directly. Prioritize `edit_batch` for applying targeted replacements across one or more files in a single turn. Prioritize `edit` for single partial modifications; use `write` for new files or necessary full replacements. Unified calc/verification scripts permitted via `write`.
167
+ - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
168
+ - Shell execution: system binaries, external CLIs, builds, package managers, test runners — STRICTLY via `bash`. Prioritize chaining local non-blocking operations via `&&` (`git add ... && git commit ... && npm test`) to eliminate round-trip latency; keep network- or credential-bound commands (`npm publish`, remote fetch) separate to prevent Windows process handle hanging and timeouts.
169
+ - Reporting: diffs and evidence first; zero filler. Routine status ≤ 300 Chinese characters. Answer/explain/review/diagnose/plan: no length cap. Compact locators, lists, and deltas only.
170
+
171
+ ## Verification
172
+
173
+ Applies ONLY to change/build/fix.
174
+
175
+ - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
176
+ - Tiered verification by risk; prioritize existing relevant checks; add targeted tests when behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
177
+ - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
178
+ - Behavior changes: run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
179
+ - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
180
+ - Report checks, results, and verification gaps.
181
+ - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
182
+ ```
183
+ </details>
184
+
185
+ ---
186
+
187
+ ## 本地验证与基准测试
188
+
189
+ ```bash
190
+ # 从本地已安装的 DSH 宿主链接依赖(零网络请求)
191
+ npm run setup:local
192
+
193
+ # 在官方 @deepseek-ai/dsh-agent-loop 上运行完整集成测试
194
+ npm test
195
+
196
+ # 运行 TypeScript 严格类型检查
197
+ npm run typecheck
198
+
199
+ # 运行离线 A/B 机制与度量对照脚本
200
+ npm run benchmark
201
+ ```
202
+
203
+ ---
204
+
205
+ ## 设计边界与安全保障
206
+
207
+ 1. **官方 Loop 独占控制流 (`@deepseek-ai/dsh-agent-loop`)**:
208
+ 生命周期、工具原生并发调度(`maxParallelToolCalls`)、重试、取消与结束语义全部由官方 Loop 负责。本插件通过 Cordis 机制注入,**绝不禁用、替换或篡改** `@deepseek-ai/dsh-agent-loop`。
209
+ 2. **零模型参数篡改**:
210
+ 本插件绝不在 `agent/request` 钩子中擅自降低或修改模型名称、Provider 或推理强度(`reasoningEffort`)。
211
+ 3. **事务性与沙箱透明度**:
212
+ 复合工具执行的所有原子子操作均在官方执行管线中逐一审计与授权,绝不绕过安全边界。
213
+
214
+ ---
215
+
216
+ ## 许可证
217
+
218
+ [MIT](LICENSE) © [Jaylor-Wang](https://github.com/Jaylor-Wang)
@@ -0,0 +1,42 @@
1
+ # Purely additive policy, composite-tool, and telemetry plugin.
2
+ # Never disables or replaces @deepseek-ai/dsh-agent-loop.
3
+ - insert:
4
+ - id: agent-optimizer
5
+ name: dsh-awesome-optimizer
6
+ config:
7
+ enabled: true
8
+ runtimePolicy:
9
+ mode: enforce
10
+ noProgressLimit: 2
11
+ recoveryAttemptLimit: 1
12
+ minLargeWriteBytes: 8192
13
+ maxShellCommandBytes: 4096
14
+ maxInlineScriptBytes: 512
15
+ fileMutationPolicy:
16
+ mode: observe
17
+ minLargeWriteBytes: 8192
18
+ recoverFailedWrites: true
19
+ compositeTools:
20
+ enabled: true
21
+ readBatch: true
22
+ editBatch: true
23
+ maxBatchFiles: 10
24
+ maxBatchEdits: 10
25
+ convergence:
26
+ enabled: true
27
+ injectGuidance: true
28
+ stepInterval: 8
29
+ maxRemindersPerTurn: 4
30
+ customPrompt:
31
+ enabled: true
32
+ globalFile: "~/.dsh/SYSTEM.md"
33
+ workspaceFile: ".dsh/SYSTEM.md"
34
+ # Placement modes:
35
+ # - "replace-all": Strip ALL verbose official sections and use ONLY the refined SYSTEM.md (~80% token savings!)
36
+ # - "suffix": Append to end of official system prompt (Order 10300)
37
+ placement: "replace-all"
38
+ mergeStrategy: "concat"
39
+ hotReload: true
40
+ telemetry:
41
+ enabled: true
42
+ trackStreams: true
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent Loop Policy & Convergence Optimizer",
4
+ "description": "Non-invasive runtime guards, PTC composite batch tools, soft convergence reminders, and A/B turn telemetry around the official DSH agent loop."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent 循环策略与收敛优化器",
4
+ "description": "围绕官方 DSH Agent Loop 的非侵入式运行期防护、PTC 复合批处理工具、轻量软预算提醒与 A/B 轮次度量插件。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,114 @@
1
1
  {
2
2
  "name": "dsh-awesome-optimizer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.5.0",
4
+ "description": "Non-invasive runtime policy, composite batch tooling, soft convergence guidance, reactive custom prompt engine, and A/B telemetry plugin for the official DeepSeek Harness (dsh) agent loop.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "types": "src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./policy": {
14
+ "types": "./src/runtime-policy.d.ts",
15
+ "default": "./src/runtime-policy.js"
16
+ },
17
+ "./mutation-policy": {
18
+ "types": "./src/file-mutation-policy.d.ts",
19
+ "default": "./src/file-mutation-policy.js"
20
+ },
21
+ "./recovery": {
22
+ "types": "./src/failure-recovery.d.ts",
23
+ "default": "./src/failure-recovery.js"
24
+ },
25
+ "./composite-tools": {
26
+ "types": "./src/composite-tools.d.ts",
27
+ "default": "./src/composite-tools.js"
28
+ },
29
+ "./convergence": {
30
+ "types": "./src/convergence.d.ts",
31
+ "default": "./src/convergence.js"
32
+ },
33
+ "./custom-prompt": {
34
+ "types": "./src/custom-prompt.d.ts",
35
+ "default": "./src/custom-prompt.js"
36
+ },
37
+ "./telemetry": {
38
+ "types": "./src/telemetry.d.ts",
39
+ "default": "./src/telemetry.js"
40
+ },
41
+ "./locale/*.json": "./locale/*.json",
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "src",
46
+ "cordis.patch.yml",
47
+ "locale/*.json",
48
+ "scripts/typecheck.mjs",
49
+ "scripts/benchmark.mjs",
50
+ "README.md",
51
+ "README.zh.md",
52
+ "LICENSE"
53
+ ],
54
+ "dsh": {
55
+ "bundle": {
56
+ "patch": "./cordis.patch.yml"
57
+ }
58
+ },
59
+ "engines": {
60
+ "node": ">=22.0.0",
61
+ "dsh": ">=0.2.2-rc.1"
62
+ },
63
+ "scripts": {
64
+ "setup:local": "node scripts/setup-local.mjs",
65
+ "test": "node --test --test-timeout=15000 test/*.test.js",
66
+ "typecheck": "node scripts/typecheck.mjs",
67
+ "benchmark": "node scripts/benchmark.mjs"
68
+ },
69
+ "author": "Jaylor-Wang",
70
+ "license": "MIT",
71
+ "homepage": "https://github.com/Jaylor-Wang/dsh-awesome-optimizer#readme",
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/Jaylor-Wang/dsh-awesome-optimizer.git"
75
+ },
76
+ "bugs": {
77
+ "url": "https://github.com/Jaylor-Wang/dsh-awesome-optimizer/issues"
78
+ },
79
+ "keywords": [
80
+ "deepseek-harness",
81
+ "dsh",
82
+ "dsh-plugin",
83
+ "cordis",
84
+ "agent-loop",
85
+ "runtime-policy",
86
+ "convergence",
87
+ "telemetry",
88
+ "composite-tools"
89
+ ],
90
+ "peerDependencies": {
91
+ "@deepseek-ai/cordis": ">=4.0.0",
92
+ "@deepseek-ai/dsh-agent": "*",
93
+ "@deepseek-ai/dsh-agent-loop": "*",
94
+ "@deepseek-ai/dsh-llm": "*",
95
+ "@deepseek-ai/dsh-session": "*",
96
+ "@deepseek-ai/dsh-system-prompt": "*",
97
+ "@deepseek-ai/dsh-tools": "*",
98
+ "@deepseek-ai/schemastery": ">=3.0.0"
99
+ },
100
+ "peerDependenciesMeta": {
101
+ "@deepseek-ai/dsh-agent": {
102
+ "optional": true
103
+ },
104
+ "@deepseek-ai/dsh-agent-loop": {
105
+ "optional": true
106
+ },
107
+ "@deepseek-ai/dsh-session": {
108
+ "optional": true
109
+ },
110
+ "@deepseek-ai/schemastery": {
111
+ "optional": true
112
+ }
113
+ }
114
+ }