Passer au contenu principal
J

dsh-awesome-optimizer

jaylor-wang/dsh-awesome-optimizer

Runtime policy guards that block repeated failing tool calls, oversized shell commands and network commands chained with local ones, composite batch tools (read_batch/edit_batch), a SYSTEM.md mode that replaces the official system-prompt sections with your own file, soft convergence notices, and turn telemetry for DeepSeek Harness.

Installer

dsh plugin --profile web add github:jaylor-wang/dsh-awesome-optimizer

README

dsh-awesome-optimizer

English | 中文

npm version license GitHub release Tests TypeScript

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 (@deepseek-ai/dsh-agent-loop).


Highlights in v1.5.0

  • 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.
  • 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.
  • 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).
  • 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.

Core Features & Architecture

1. Refined System Prompt & File-Driven Hot-Reload (customPrompt)

  • Standalone Mode (placement: "replace-all"): 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).
  • Dual-Layer Markdown Convention: 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.
  • Millisecond Hot-Reload: Uses debounced fs.watch to detect prompt file edits and applies them reactively on the very next turn without restarting the DSH process.
  • Flexible Cascading Strategies: Supports concat (cascading global and workspace prompts, default) and workspace-override (repo prompt completely replaces global prompt).
  • Built-in Prompt Linter & Auto-Fixer: 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).
DimensionOfficial Default System PromptOptimized with This PluginSavings
Token Usage~2,000 tokens / turn~380 tokens / turn~82% token reduction
Long Multi-Turn Sessions~100K redundant tokens across 50 turnsClean, focused, high-density contextMitigates context drift & forgetting
Config UpdatesRequires restart or reloadInstant hot-reload on file saveImmediate feedback

2. PTC Native Composite Batch Tooling (compositeTools)

  • read_batch: Concurrently inspects up to 10 targeted file snippets in a single turn. Ideal for broad multi-file investigation and dependency tracing.
  • edit_batch: 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.
  • Inherited Security & Sandboxing: 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.

3. Defensive Runtime Policy & Self-Healing Recovery

  • No-Progress Circuit Breaker (NO_PROGRESS): 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.
  • Windows Oversized Shell Command Interception (EMBEDDED_SHELL_PAYLOAD_TOO_LARGE): 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.
  • Windows Chained Network Command Guard (CHAINED_NETWORK_COMMAND): 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.
  • Full Overwrite Protection & Single-Shot Recovery (failureRecovery): 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.

4. Lightweight Convergence & Objective A/B Telemetry

  • Micro-Directive Convergence (convergence): 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.
  • Objective A/B Telemetry (telemetry): 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).

Installation & Quickstart

# Add directly to the active web profile
dsh plugin --profile web add dsh-awesome-optimizer

2. Via npm / pnpm

# Using npm
npm install dsh-awesome-optimizer

# Using pnpm
pnpm add dsh-awesome-optimizer

3. Zero-Config Out of the Box

All optimizations are enabled by default upon installation. No extra lines are required in your global cordis.patch.yml.

Optional Advanced Overrides / Disabling

Only when customizing paths or disabling specific subsystems do you need to add an entry in cordis.patch.yml:

# Example: Only declare overrides when customizing defaults
- id: agent-optimizer
  config:
    # Disable prompt takeover to revert to official verbose prompt
    customPrompt:
      enabled: false

    # Or adjust batch limits
    compositeTools:
      maxBatchFiles: 15
      maxBatchEdits: 15

    # Or relax the no-progress circuit breaker
    runtimePolicy:
      noProgressLimit: 3

Production-Ready SYSTEM.md Recommendation

With placement: "replace-all", place your directives in ~/.dsh/SYSTEM.md (Windows: C:\Users\<Username>\.dsh\SYSTEM.md):

Click to expand production-ready universal prompt template (50 lines, native tools only)
# AUTONOMOUS AGENT CORE DIRECTIVE

You are a master autonomous software engineer powered by DeepSeek Harness.

- Prioritize direct action over speculation: investigate via concurrent tools (fs, bash, skills) without orchestration overhead.
- NEVER emit pre-action narration. Deliver surgical edits and high-signal conclusions.
- 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.

## Defaults

- Reply in Chinese; code comments and commit messages in English unless requested otherwise. In user-facing text, preserve Windows path formats as written (`E:\...`).
- Answer / explain / review / diagnose / plan: inspect and report without edits unless requested otherwise.
- 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.
- Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
- Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
- Web & external: research/fetch via available skills or bash CLIs.

## Efficiency

### Hard Constraints

- 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.
- 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.
- 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.
- 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.
- 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.

### Execution & Context Efficiency

- Workflow:
  - Complexity: simple → execute; high-scope (cross-module, API, schema) → generate / follow plan (`<name>.md`); define 1–3 sentence scope and exit criteria before edits.
  - Scheduling: Prioritize `read_batch` for multi-file inspection; keep edits, retries, and dependent checks sequential.
  - Diagnosis: contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
- Search & navigation:
  - 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).
  - 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.
  - 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.
- Modification & execution:
  - 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`.
  - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
  - 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.
- 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.

## Verification

Applies ONLY to change/build/fix.

- NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
- 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:
  - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
  - Behavior changes: run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
  - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
- Report checks, results, and verification gaps.
- Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.

Verification & Benchmarking

# Link local peer dependencies from installed DSH host (zero network requests)
npm run setup:local

# Run integration tests against official @deepseek-ai/dsh-agent-loop
npm test

# Run strict TypeScript declaration check
npm run typecheck

# Run offline A/B benchmark verification
npm run benchmark

Architectural Principles & Safety

  1. Official Loop Ownership (@deepseek-ai/dsh-agent-loop): 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.
  2. Zero Model Parameter Mutation: The plugin never hooks agent/request to modify model identities, providers, or reasoning efforts.
  3. Transparent Pipeline Security: All composite operations are audited and dispatched individually through the official ToolExecutionPipeline.

License

MIT © Jaylor-Wang

Plugins associés