すべてのプラグイン

dsh-awesome-optimizer

dsh-awesome-optimizer · バージョン 4.5.0 · 2026/11/29 更新

DSH に実行時のポリシーガード、常駐する Python と Node の評価プロセス、バッチツール、システムプロンプトエンジン、ターン単位の A/B テレメトリーを追加します。関数名での検索精度が上がり、出力をバイト数で切り詰めるときは一致した根拠が先に表示されます。

  • バージョンごとに審査
  • 開発ランタイム
  • MIT
  • 0回ダウンロード

説明

以下はプラグイン作者による原文です。

dsh-awesome-optimizer

English | 中文

npm version license GitHub release Tests TypeScript

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 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. This intentionally abandons those official prompt sections; add any instructions you still need to SYSTEM.md.
  • 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).
DimensionOfficial Default System PromptOptimized with This PluginSavings
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 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)

  • find_and_read: Searches 1–5 regex patterns without changing regex whitespace, merges and splits adjacent matches, and dispatches budget-aware batches of native read calls 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, fits maxTotalBytes (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. maxFiles bounds 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.
  • readGuard inspection preflight: Only supported outline languages trigger extra inspection. The fs service resolves and stats the target before reading, preferring bounded readBytes or 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: 750 and astMaxOutputBytes: 262144 bound time/output. Cancellation terminates the child; missing CLI, timeout, and errors fall back to lexical results. astGrepCommand accepts an executable name or absolute path; the CLI must support outline --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/outlineCacheHits counters.
    • Run npm run benchmark:outline -- outline-benchmark.windows.json for real-CLI first-invocation, repeated uncached, lexical, and version-cache timings with 20 repeated samples. See outline-benchmark.md for 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. Set maxCacheEntries: 0 to disable it. The byte cap measures serialized payload, not JS heap usage.
    • The official standalone session/disposed event 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 telemetry summary.readGuard (null when disabled). outlineCacheLookups = outlineCacheHits + outlineCacheMisses; outlineCacheHitRate = hits / lookups is in [0, 1], or null without 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 as outlineCacheBypasses; rejected preflights count as neither. Ordinary and targeted reads do not inflate the lookup denominator.
    • outlineCacheInvalidations counts 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 on turn/start while caches survive turns. These metrics describe local outline caching separately from provider input caching.
  • edit_batch: Sequentially applies up to 10 literal edits through the native edit pipeline. atomic: true requires a verifiable filesystem snapshot for every target, rejects sandbox_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 code EDIT_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 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.
  • Bash Command Chaining (CHAINED_HEAVY_COMMAND): In enforce mode, the optimizer blocks npm publish in && or ; chains. Tests and builds can be chained by default. Set runtimePolicy.disallowChainedHeavyCommands: true to also block chains containing npm test, npm t, npm run build, or vitest. The legacy disallowChainedNetworkCommands option remains a fallback.
  • Playwright File Protocol Guard (PLAYWRIGHT_FILE_PROTOCOL_BLOCKED): Pre-execution guard against playwright-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 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

  • Signal-Driven Soft Convergence (convergence): Defaults to mode: "adaptive", injecting compact append-only notice directives 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, enforces cooldownSteps (default 6, preventing post-error bursts), suppresses reminders after top-level tool errors, and filters guidance to admitted tools. Set mode: "periodic" to opt into fixed stepInterval reminders.
  • 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

  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

バージョン履歴

  • 4.5.02026/11/29 · 176 KB
dsh-awesome-optimizer · SoleAPI Agent プラグイン | SoleAPI