Описание
Ниже — оригинальный текст автора.
dsh-awesome-optimizer
English | 中文
High-performance runtime policy guards, persistent Python & Node evaluation daemons, PTC-backed composite batch tooling, standalone refined system prompt engine, and objective A/B turn telemetry plugin for the official DeepSeek Harness (@deepseek-ai/dsh-agent-loop).
Core Features & Architecture
1. Refined System Prompt & File-Driven Hot-Reload (customPrompt)
- Standalone Mode (
placement: "replace-all"): Hooks into the DSHsystem-prompt/assemblewaterfall to strip all official verbose sections (harness:*,deployment:*,tool:*,deliverable:*,web:*), preserving convergence guidance companion sections while presenting your refinedSYSTEM.mdas the standalone authority. This intentionally abandons those official prompt sections; add any instructions you still need toSYSTEM.md. - Dual-Layer Markdown Convention:
Automatically discovers global
~/.dsh/SYSTEM.md(or$DSH_HOME/SYSTEM.md) and project workspace.dsh/SYSTEM.md(orSYSTEM.md), cleanly separating developer system defaults from repo-specific instructions. - Millisecond Hot-Reload:
Uses debounced
fs.watchto 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) andworkspace-override(repo prompt completely replaces global prompt).
| Dimension | Official Default System Prompt | Optimized with This Plugin | Savings |
|---|---|---|---|
| Prompt Context Footprint | ~2,000 tokens / turn | ~380 tokens / turn (Template) | Frees context headroom; eliminates redundant rules |
| Long Multi-Turn Sessions | ~100K redundant tokens across 50 turns | Clean, focused, high-density context | Mitigates context drift & forgetting |
| Config Updates | Requires restart or reload | Instant hot-reload on file save | Immediate feedback |
2. PTC Native Composite Batch Tooling (compositeTools)
find_and_read: Searches 1–5 regex patterns without changing regex whitespace, merges and splits adjacent matches, and dispatches budget-aware batches of nativereadcalls in one round-trip. The host scheduler runs concurrency-safe subcalls in parallel, isolates exclusive tools, and commits results in input order. The complete returned text, including headers, errors, indexes, and omission notices, fitsmaxTotalBytes(24KB by default). Matched rows take priority; undisplayed locations become bounded indexes with explicit omission counts. Upstream truncation, failed patterns, totals, and recovery locators that fit are reported.maxWindowLines: 120: maximum requested lines per slice, preventing dense chained matches from becoming whole-file reads.maxReadLines: 600: maximum total requested lines across all files and windows in one call.readConcurrency: 3: maximum simultaneous reads per batch; remaining output space is checked before the next batch. Matches hidden by native read truncation remain in the recovery index.- Windows prioritize uncovered regex patterns, then diminishing returns for repeated patterns, line cost, and file diversity. Canonical paths and line numbers break ties deterministically.
maxFilesbounds selected files without excluding valuable windows in other files before ranking. - These bounds cover requested lines and returned bytes, not a fixed number of filesystem bytes or tokens.
readGuardinspection preflight: Only supported outline languages trigger extra inspection. The fs service resolves and stats the target before reading, preferring boundedreadBytesor text streaming. Oversized files (maxInspectBytes, default 512KB), cancellation, absent files, and service denials skip the outline while preserving the native read result. Service failures never fall back to local disk. Older readText-only services are supported after size preflight, subject to file-growth races between stat and read.- Default
astOutline: "auto"keeps ordinary files on the lexical path and invokes ast-grep on demand for JSX/TSX, TS decorators/exported namespaces, or declaration-like files with empty lexical results. Set"off"to disable or"always"to force AST for supported languages. Both levels prioritize top-level exports and sample across the unread tail. - The CLI receives only the fs-authorized snapshot on stdin, never the target path. It uses fixed plugin configuration, disables custom language libraries, and runs without a shell. Defaults
astTimeoutMs: 750andastMaxOutputBytes: 262144bound time/output. Cancellation terminates the child; missing CLI, timeout, and errors fall back to lexical results.astGrepCommandaccepts an executable name or absolute path; the CLI must supportoutline --stdin --json. - Current bundled ast-grep rules expose TS namespaces without children; lexical child declarations inside AST-confirmed namespace ranges are retained for navigation. AST successes and lexical fallbacks share the version LRU, preventing repeated launches for the same cached file version. Version changes, mutations, or eviction permit another attempt. Inspect
astAttempts/astSucceeded/astFallbacks/astTimeouts/outlineCacheHitscounters. - Run
npm run benchmark:outline -- outline-benchmark.windows.jsonfor real-CLI first-invocation, repeated uncached, lexical, and version-cache timings with 20 repeated samples. Seeoutline-benchmark.mdfor methodology and local Windows results. - Parsed-symbol caches are isolated by session, fs backend, resolved identity, language, and version. Every lookup still stats the file; misses validate the version again after reading. Defaults:
maxCacheEntries: 32,maxCacheBytes: 262144. Cached entries are filtered for the current truncation offset. Unversioned targets are not cached; mutation/code-execution tools and session disposal clear the cache. SetmaxCacheEntries: 0to disable it. The byte cap measures serialized payload, not JS heap usage. - The official standalone
session/disposedevent releases that session's backend caches, retained references, and statistics. Plugin disposal clears remaining caches. Inspections in flight cannot repopulate caches or inject late outlines after disposal; other sessions remain isolated. getStats(session)returns a detached per-turn snapshot, also exposed as telemetrysummary.readGuard(nullwhen disabled).outlineCacheLookups = outlineCacheHits + outlineCacheMisses;outlineCacheHitRate = hits / lookupsis in [0, 1], ornullwithout lookups. Only enabled caches with valid identity/version after successful preflight count as lookups. Absent, stale, or evicted entries count as misses even if the subsequent read or parse fails. Disabled, unidentified, unversioned, and standalone local backends count asoutlineCacheBypasses; rejected preflights count as neither. Ordinary and targeted reads do not inflate the lookup denominator.outlineCacheInvalidationscounts mutation/bash/eval events that clear an existing session cache group, including in-flight inspections. No group means no invalidation; version mismatches count as misses, and disposal cleanup does not count as invalidation. Counters reset onturn/startwhile caches survive turns. These metrics describe local outline caching separately from provider input caching.
- Default
edit_batch: Sequentially applies up to 10 literal edits through the native edit pipeline.atomic: truerequires a verifiable filesystem snapshot for every target, rejectssandbox_permissions, and aborts before dispatch if any preflight fails. After dispatch begins, strict mode stops at the first failure; there is no rollback or cross-file transaction. Mixed outcomes say[PARTIAL]; strict mode also reports the error codeEDIT_BATCH_PARTIAL. Do not retry edits that already succeeded.- 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 tonoProgressLimit(default2), the plugin blocks execution attools/pre-execute, forcing the agent to adapt its diagnostic approach. - Windows Oversized Shell Command Interception (
EMBEDDED_SHELL_PAYLOAD_TOO_LARGE): Automatically blocks commands exceeding4096bytes or inline scripts (node -e,python -c,pwsh -Command) exceeding512bytes, steering the model to write deliverables to disk first. - Bash Command Chaining (
CHAINED_HEAVY_COMMAND): Inenforcemode, the optimizer blocksnpm publishin&∨chains. Tests and builds can be chained by default. SetruntimePolicy.disallowChainedHeavyCommands: trueto also block chains containingnpm test,npm t,npm run build, orvitest. The legacydisallowChainedNetworkCommandsoption remains a fallback. - Playwright File Protocol Guard (
PLAYWRIGHT_FILE_PROTOCOL_BLOCKED): Pre-execution guard againstplaywright-cli open/goto file://...commands, steering models toward local HTTP loopback servers to prevent protocol errors and orphaned browser processes. - Full Overwrite Protection & Single-Shot Recovery (
failureRecovery): Prevents accidental destructivewriteoverwrites on existing large files wheneditis available. Automatically registersretry_failed_writewhen a large write (8KB–1MB) is rejected due to an unpaired justification, avoiding costly regeneration.
4. Lightweight Convergence & Objective A/B Telemetry
- Signal-Driven Soft Convergence (
convergence): Defaults tomode: "adaptive", injecting compact append-onlynoticedirectives only on efficiency degradation instead of blind step intervals: detects consecutive single-tool serial reads (serialReadThreshold: 4) to suggest parallel batching /find_and_read, detects long-tail exploration without edits or verification (longTailStepThreshold: 12,stallStepsThreshold: 6) with objective step anchors, stretches cooldowns/thresholds 2× for healthy high-parallel batches, enforcescooldownSteps(default6, preventing post-error bursts), suppresses reminders after top-level tool errors, and filters guidance to admitted tools. Setmode: "periodic"to opt into fixedstepIntervalreminders. - Objective A/B Telemetry (
telemetry): Collects model requests, tool calls, tool calls per batch (parallelismRatio), TTFT, token usage, and adapter message-prefix changes (prefixChanges).getSummary(session, turn)reads the latest tracked turn without changing it; older or unknown turns return an empty summary. For cache totals and reporting coverage, see HTTP cache diagnostics.
Installation & Quickstart
The runtime peer dependencies target DSH 0.2.2-rc.3. Use the host's compatible Cordis, Schemastery, LLM, and tool pipeline packages.
1. Via DSH Plugin Command (Recommended)
# Add directly to the active web profile
sole 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
The plugin works without extra configuration. Persistent eval registers both tools and prewarms their workers by default. Workers inherit the host environment and OS permissions, not the DSH filesystem or shell sandbox. The Node VM, per-session state, and watchdog are not security boundaries. Set persistentEval.enabled: false in any profile that serves untrusted workspaces or requires sandboxed execution. This disables both tool registration and prewarming.
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:
maxFiles: 8
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):
# AUTONOMOUS AGENT CORE DIRECTIVE
You are a master autonomous software engineer powered by DeepSeek Harness.
- MUST act directly rather than speculate.
- 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 / plan / review / diagnose: inspect and report without edits unless requested otherwise.
- Change / fix / build: make minimal, conservative, reversible edits within task scope, including necessary changes to related files. Preserve unrelated work; reset/clean the working tree ONLY if explicitly requested. No unrelated cleanup, reformatting, dependency changes, or test rewrites. May remove task-created temporary artifacts 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: Research/fetch STRICTLY via skills (`agent-reach`, `gh`, `opencli-*`) or shell CLIs via `bash`.
- Retry ONLY when the error or new evidence supports a specific correction; after two failures without progress, switch diagnostic approaches.
- Windows arguments & paths: use forward slashes in paths to prevent escape corruption. NEVER embed scripts or multiline code in shell arguments (`node -e`, `python -c`, `pwsh -Command`). Quote single-line patterns carefully (`ast-grep` patterns STRICTLY in single quotes `'...'` to prevent `$$` expansion). On quoting failures, switch input method rather than re-escaping.
- Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless explicitly requested.
- Tool exclusivity: STRICTLY native `glob`/`grep`/`find_and_read`/`read`/`edit_batch`/`edit`/`write`. NEVER use shell commands or redirects for workspace search or reading/writing files (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) and batch removing temporary artifacts (`rm -rf`) are permitted.
## Efficiency
- Workflow:
- Complexity: Execute simple tasks directly. For broader changes, define scope and acceptance criteria first. Write a plan file ONLY when explicitly requested.
- Scheduling: For searches across multiple source files that need matching code and surrounding context, use `find_and_read`. For known files, batch independent `read` calls in parallel. Keep dependent inspections and retries sequential.
- Diagnosis: Inspect contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
- Search & navigation:
- 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` ONLY when execution fails.
- Workspace: use the session working directory; do not modify the DSH installation directory unless explicitly requested.
- Code intelligence: Prioritize `lsp` CLI (`def`/`ref`/`hover`/`symbols`) and `ast-grep` (`-p`, `-k`, `outline`). `ast-grep run` exits with `1` on no matches. When `ast-grep scan` completes, it exits with `1` if any `severity: error` rules match and `0` otherwise.
- Files: use native `glob` to locate files (including hidden/ignored files), `grep` to search contents, and `read` for focused excerpts (`offset`/`limit`). Narrow searches when results are capped; use `bash` for Git status, history, and diffs.
- Modification & execution:
- File ops: MUST use `edit_batch` for 2+ edits (whether in one file or across multiple files); use `edit` for a single edit, and `write` for new files or ad-hoc Node/Python scripts.
- Staged refactor: Preview with `lsp rename` or `ast-grep run -p 'PATTERN' -r 'REWRITE' PATHS`. Review the proposed edits and affected files, then rerun the same command with `--apply` or `-U`, respectively.
- Structured data & calculations: MUST use persistent `eval_python`/`eval_node` kernels (key stdlib pre-imported) to query, filter, transform, and compute. Return compact results with minimal evidence; NEVER dump raw datasets or large intermediates. Follow tool rules for file access and external queries.
- Chain steps with `&&`. Run long tests or builds separately when they need their own timeouts or logs. Run `npm publish` alone and verify the version via a read-only registry query.
- Reporting: diffs, locators, minimal excerpts, and evidence first; zero filler. Routine status ≤ 300 Chinese characters (do not omit required check results or verification gaps to fit). Answer/explain/review/diagnose/plan: no length cap.
## Verification
Applies ONLY to review / diagnose / change / fix / build.
- NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
- Match checks to behavioral or contract risk; prefer existing checks. Review/diagnosis: run existing non-destructive checks as needed. Add or modify tests only for authorized changes; close coverage gaps in changed behavior. Repeat equivalent checks only when relevant code, configuration, environment, or evidence changes:
- Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
- Behavior changes: check static diagnostics via primary tools (e.g. `lsp diag <file|dir> -e`, skip if language unsupported; no redundant CLI linters), then 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; if primary diagnostics are unavailable, use an existing equivalent check when possible.
- Browser checks: `playwright-cli` ONLY for read-only review/diagnosis and post-change verification. Reuse active app URLs; serve static HTML over loopback HTTP (`http://127.0.0.1:<port>`; `file:` blocked). Prioritize `snapshot`/`console`/`requests`; for visual checks, stabilize with `set-reduced-motion reduce` and omit `screenshot --filename` unless an explicit path is required. NEVER pre-probe (`--help`/`--version`), create dummy pages, or switch tools. Batch-clean sessions (`close`/`close-all`), temp servers, and `.playwright-cli/` without redundant listings.
- Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
Verification & Benchmarking
Run these commands from the checkout or the extracted npm archive. Use the compatible DSH host, TypeScript (tsc), Python, and ast-grep.
# 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
- 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. - Zero Model Parameter Mutation:
The plugin never hooks
agent/requestto modify model identities, providers, or reasoning efforts. - Transparent Pipeline Security: All composite operations are audited and dispatched individually through the official ToolExecutionPipeline.
License
История версий
- 4.5.029 нояб. 2026 г. · 176 KB