DeepSeek Harness Plugin

zqh260619/dsh-dupguard

Stars ★ 4 Downloads (30d) 3,241 Category Development & Runtime Added 2026-10-17 npm dsh-dupguard

Stops a streaming model call when the same string repeats ten times in a row (threshold configurable), keeps the partial answer as a normal assistant message, and shows a stop notice with the workspace, session name and the repeated string. Repeat counts can vary by unit length through a piecewise table or a JavaScript module, and code regions (fenced, inline, indented) use a relaxed threshold.

Install

# from npm (prebuilt)

dsh plugin --profile web add dsh-dupguard

# from GitHub (first run asks for allowBuilds approval — follow the hint, retry)

dsh plugin --profile web add github:zqh260619/dsh-dupguard

Any plugin you install runs third-party code with your own permissions — it can read your files, use your credentials, and reach the network, and tool approvals don’t sandbox it. GitHub-sourced plugins also run build scripts at install time — pnpm blocks those until you allow them, so an install can stop with ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED or ERR_PNPM_IGNORED_BUILDS; dsh prints the exact key to add under allowBuilds in your profile’s pnpm-workspace.yaml, and the install works on the next run. Allowing a build is a trust decision: only install sources you trust, and pin a commit (github:owner/repo#sha).

README

中文 | English

CI

dupguard — a real-time repetition guard for DeepSeek Harness (DSH): when the same string repeats ≥ 10 times in the streamed output (configurable) it opens a decision card (output keeps streaming; stop now / allow to continue; without action it stops after both the multiplier and the minimum reaction time are reached; without a notice channel it stops immediately), and the partial answer is committed as a normal assistant message.

Badges are generated by npm / GitHub / dsh-plugin.org / dsh.so / awesome-dsh-plugin respectively; the version–compatibility matrix for this plugin is maintained in the README and CHANGELOG. Questions and suggestions are welcome in GitHub Issues.

Screenshots

Stop notice (you choose whether to continue) The stopped turn: output stops at the threshold
Stop notice card The stopped turn
Settings page: detection (per-length table mode) Settings page: stop & decisions
Settings page: detection Settings page: stop & decisions
Settings page: notices & log Advanced mode (experimental) risk confirmation
Settings page: notices & log Advanced mode risk confirmation
System notification (optional, Windows notification area)
System notification
Settings page: reasoning filler-word alert Settings page: recent records (collapsed by default)
Settings page: reasoning filler-word alert Settings page: recent records

All 9 screenshots are also listed in screenshots.json for plugin marketplaces/stores; workspace paths in the screenshots are redacted. The seventh image comes from the desktop (Electron) build, so the notification is attributed to the app itself; in the web build the browser forwards the notification and is credited instead.

Quick Start

Prerequisites: DSH ≥ 0.1.2-rc.1 (one-command install; the host API minimum is ≥ 0.1.1-rc.1), and the name of the profile you are installing into (the examples below use web).

Node follows DSH:

  • DSH 0.2.2-rc.1+ requires Node ≥ 24.9 (upstream requirement; upgrade the runtime before DSH);
  • DSH 0.2.1 and older: Node ≥ 20 (Node 18 is not supported).
dsh plugin --profile web add dsh-dupguard      # replace web with your profile name

Restart DSH to take effect (host code is loaded only at process start). Two signs mean the install worked:

  1. the settings page gains a 重复守卫 (repetition guard) section whose footer reads 设置通道:ready|构建 1.16.2|自动派生:检测窗口 …;
  2. the host log shows [dupguard] 生效参数:… (this line is the only proof that the settings are actually in effect).

The defaults work out of the box: ≥ 10 consecutive repeats open the decision card (output keeps streaming; without a notice channel or with decisions off it stops immediately; the partial answer is still committed as a normal assistant message), reasoning text is monitored too, and inside code regions (fenced code blocks, inline code and indented code blocks — all three handled alike) the threshold is relaxed 4×. Tune it on the settings page — no restart needed (values are written back to cordis.patch.yml, and the host hot-reads it).

Desktop (Electron): install from the app's Settings → Plugins page (the desktop profile is managed exclusively by the app; the CLI is rejected). Uninstall / upgrade: dsh plugin --profile web remove|update dsh-dupguard; for other installation methods (local checkout via --patch mount / dynamic plugin / manual patch layer / temporary disable) see alternative installs.

Compatibility

Item Supported range
Host API ≥ 0.1.1-rc.1 (declared under dsh.compatibility in package.json); one-command bundle install needs ≥ 0.1.2-rc.1
Verified with local records DSH 0.2.2-rc.5 (CLI / web profile, re-checked 2026-11-19; real-contract and full verification also passed on rc.3 / rc.4 / rc.5); DSH 0.2.2-rc.1 (CLI / web profile, re-checked 2026-11-05; the Config-backfill fix ships in 1.13.3); DSH 0.2.1-rc.2 (CLI / web profile and desktop, re-checked 2026-10-20), DSH 0.2.1-rc.1 (CLI / web profile, re-checked 2026-10-17), DSH 0.2.0-rc.2 (CLI / web profile and desktop); 0.1.7-rc.2, 0.1.7-rc.1, 0.1.2-rc.1, 0.1.1-rc.1 (see the corresponding CHANGELOG entries)
Earlier versions (no record in this repo) 0.1.5-rc.2 and 0.1.6-alpha.2 were verified while in use, but the repository has no record from that time, so they are not counted in the list above
Node DSH 0.2.2-rc.1+: ≥ 24.9 (enforced upstream); DSH ≤ 0.2.1: ≥ 20 (Node 18 is not supported). .mjs advanced modules rely on the runtime's require(ESM) support (built in for Node ≥ 20.19 / ≥ 22.12; Node 24 obviously satisfies it); the plugin itself stays Node ≥ 20 compatible
Settings namespace Since 0.1.7 it is the loader entry id (this bundle: include:dupguard); ≤ 0.1.6 used dsh-dupguard. Since 1.6.0 the route is chosen at runtime, so there is no need to swap plugin versions per DSH version
Upgrade note Since 0.1.7 the settings key changed from dsh-dupguard: to dupguard:; after upgrading, save once on the settings page (or move the old key's contents under the new key by hand). Since DSH 0.2.2-rc.1, upgrade Node to ≥ 24.9 before upgrading DSH
  • Conclusion: the detection/stop API is stable across 0.2.x; however DSH 0.2.2-rc.1 requires Node ≥ 24.9, and its loader reads Config only once when creating the runtime (a startup schemastery race makes the settings namespace disappear; the Config-backfill fix ships in 1.13.3; 1.13.2 and older can only try a restart to avoid the race — refreshing the page does not help). The desktop build ships the same version as the CLI, so all the API conclusions above apply.
  • Existing configuration carries over as-is: since 1.0.0 the keys have only grown, never been renamed (seven in 1.0.0 → ignoredChars in 1.0.2 → skipCodeBlocks/codeBlockMultiplier in 1.4.0 → ignoredSubstrings in 1.7.0 → thresholdMode/thresholdByLength/advancedThresholdFile in 1.8.0), the value ranges have only ever been widened (codeBlockMultiplier from 1–100 to 0–100; everything else unchanged since 1.3.0), and a missing key always falls back to its default. Keys not declared by the current schema (e.g. fixStandingMountConflict, typos) are ignored instead of invalidating the whole settings section ⇒ configuration saved through the settings page keeps its behaviour after an upgrade (regression case S23 covers this: keys only grow + ranges only widen).
  • The client settings section's only static dependencies are slots / locale; the settings service is wired in dynamically via ctx.inject() ⇒ under the three settings models it already supports (settings.register, settingsScope, typert remote.settings) the entry never gets stuck in pending; if DSH introduces a fourth model, it will still need adapting.
  • Detailed compatibility evidence is local-only and is not published with the repository.

Features

  • Per-delta detection: every text-delta is judged as it arrives (a delta may contain several tokens); a hit opens the decision card (by default; without a notice channel or with decisions off it stops immediately).

  • How it stops: end the stream early → upstream iterator.return() → in the adapter's finally, consumer.abort() cancels the underlying HTTP request (when the remote side stops is up to the server's behaviour); it does not abort() the agent step signal, and it emits protocol-compliant block-end + finish(stop), so the generated content is committed as a normal assistant message and the session log is not polluted.

  • Many repetition shapes: single characters, words, space / newline separated, line by line, and loops after a prefix (whitespace is stripped before detection by default).

  • Reasoning guard: reasoning text is monitored by default too, so loops in thinking are stopped as well (monitorReasoning: false turns this off).

  • Reasoning filler-word alert (optional; warning only, never stops): only the configured list is checked (default hmm / wait / hold on / actually / alternatively / let me) and edited as chips in the settings page, reusing the current detection window and computing occurrences per 1k chars. When the threshold is reached it suggests compressing the context or starting a new session; output is never stopped. Stop/decision cards take priority; when system notifications are enabled, both the web and desktop clients receive them.

  • Graphical settings page (npm resident build): a 重复守卫 (repetition guard) section next to "General / Models / Plugins / Agent presets" where you can edit the ignore list and all detection parameters visually; changes apply immediately and are persisted. Three top tabs split the page by task (similar to dsh-cost-meter):

    Page Contents
    Detection Mode (simple / per-length table / advanced) + that mode's count source (threshold / three-column table / module path) + threshold multiplier inside code regions; min / max repeat unit length; ignore whitespace / monitor reasoning / monitor tool arguments; reasoning filler-word alert; ignore list
    Stop & decisions Decision-card toggle + pause-display toggle + minimum reaction time + auto-stop multiplier + local no-force-stop toggle + local provider list
    Notices & log Stop-notice toggle + system-notification toggle (optional, with test button; also used by filler-word alerts) + continue-prompt text + Record stop / allow / filler logs toggle + confirmed full-content toggle + recent stops/allows/filler alerts viewer (read-only, with health and clear controls)
  • Stop notice + one-click continue (npm resident build): every stop raises a global notice — regardless of which session you have open — showing the workspace, the session name and the repeated string, the repeat count and the channel that matched; you then choose whether to "send continue prompt" (injected into the stopped session) or "don't send". See stop notices and continue prompts.

  • Optional system notification (npm resident build, off by default): when enabled, a stop or a filler-word alert while the page is not in the foreground (tab in the background, window minimised, or window unfocused) also sends a browser system notification (Windows notification area / macOS Notification Center); its title and body are fixed text with no workspace or session name; the first time you enable it the browser asks for permission.

  • Two delivery forms: the dynamic plugin plugin/host.js and the npm resident build lib/index.js / lib/client.js. The detection engine has a single source in lib/engine.js; the dynamic entry is generated by npm run build:host, and one test suite drives both entries (CI guards both stale generation and behaviour drift).

  • Stop / allow-continue / filler-alert records (persistent log, npm build only): every actual stop appends to ~/.dsh/dupgard/stops.jsonl; choosing Allow to continue on a decision card appends to allows.jsonl in the same directory; a reasoning filler-word alert appends to fillers.jsonl. Stops/allows share the same fields and format, filler alerts use their own fields; all three share the same switch and redaction; the settings page shows their latest records.

  • Whitelist follow-up after Allow to continue: a second card asks whether to add the repeated text to ignoredChars / ignoredSubstrings so it is not detected again; duplicates, over-long text or an unavailable settings channel only show a hint and write nothing.

  • Decision-card progress: current repeats vs. auto-stop target, a count progress bar and the minimum-reaction-time countdown; the original two-condition auto-stop is unchanged.

  • Simple-mode presets: Strict 10 / Balanced 15 / Loose 30 set only threshold.

  • Feedback entry: a prominent settings-page banner links to this repository's GitHub Issues; the repository ships Bug / Feature request / Compatibility issue templates.

  • Threshold decision card: hitting the threshold does not pause output by default; a card appears (stop now / allow to continue). Without action, it stops only when the actual repeats reach threshold × multiplier AND the minimum reaction time has passed (see "Decision card"; the dynamic build and hosts without the notice channel fall back to stopping immediately).

  • Built-in DSH compatibility patch (fixStandingMountConflict, on by default; see "Limitations").

What it catches / what it does not

Caught Not caught
Single-character / word / line-by-line repetition reaching the threshold Frequent words in normal text (only consecutive repeats count)
Repetition separated by spaces or newlines Repeat counts below the threshold (9 or fewer by default)
Loops after a prefix Tool-call arguments (monitorToolArguments is off by default)
Repetition in reasoning (on by default) Markdown table separator rows and long separator lines (-, | are on the ignore list by default)
Runaway repetition inside code regions (fenced / inline / indented), caught at "threshold × multiplier" Normal code / test fixtures / ASCII art inside those regions (relaxed 4× by default)

Configuration

Defaults are defined in CONFIG at the top of both entries (CI checks that behaviour matches). npm resident build: apart from fixStandingMountConflict (a code constant), the options below can be adjusted through the settings page or <profile>/cordis.patch.yml, taking effect immediately. detectionWindow, minUnitLength / maxUnitLength in table mode are derived values, skipCodeBlocks is hidden, and threshold is shown in simple mode only; the dynamic build always uses the constants.

Option Default Description
threshold 10 Trigger threshold with >= semantics (the 10th repetition opens the decision card; without a notice channel or with decisions off it stops immediately). Range 2–1000. Shown on the settings page in simple mode only; under table/module it is only the fallback value
thresholdMode 'simple' simple fixed threshold / table per-length table / module advanced mode (experimental; a safety confirmation pops up when it is selected) (settings-page dropdown). simple builds no table and takes the original fast path
thresholdByLength '' Per-length table for table mode: the settings page shows a three-column table (start, read-only / end / count, 1–16 rows; the first start is 1 and each later start = the previous end + 1), stored as "<end>:<count>[, …]", e.g. 1:40, 2:30, 8:12. The last row's end = the maximum detection length; the old *:<count> form is still accepted (migrated to the last row)
advancedThresholdFile '' Experimental: path to the JavaScript file used by module mode; it exports repeatCount(length) -> count (synchronous). The file runs inside the host process, and selecting advanced mode pops a safety confirmation; see "Advanced"
minUnitLength 1 Minimum repeat unit length, range 1–4096. In table mode this is a derived value: it equals the table start (fixed at 1) and is written back to the document by the plugin; you cannot type it in
maxUnitLength 80 Maximum repeat unit length, range 1–8192. In table mode this is a derived value: it equals the last row's "end" and is written back by the plugin; you cannot type it in
detectionWindow automatic Derived value (read-only): computed by the plugin and written back to the document; hand-written values are ignored. Formula in "Detection window (derived automatically)"
skipCodeBlocks true Master switch for code-region tiering. ⚠ Hidden on the settings page: false ≡ codeBlockMultiplier: 1, so express it with the multiplier instead; the key in old configs still behaves as before, and changing the multiplier clears it automatically
codeBlockMultiplier 4 Threshold multiplier applied uniformly inside code regions (fenced / inline / indented); labelled "code threshold multiplier" on the settings page. Three tiers: ≥2 judges at "threshold × multiplier" (the higher, the fewer false kills, and the later a runaway loop is caught); 1 is as strict as outside code; 0 disables detection inside regions entirely (and does not stitch regions to their surroundings). Range 0–100
stripWhitespace true Remove whitespace / newlines before detection, so separated repetition such as x x x or x\nx\nx is recognised
ignoredChars ['-', '|'] Per-character ignore list (Markdown table separator rows are not counted). Entries must be single characters (by Unicode code point); multi-character or empty entries are dropped at runtime with a warning. On the settings page this field shares one input box with the next one
ignoredSubstrings [] Substring ignore list (multi-character): whole-literal matching (case-sensitive, no regular expressions); a match is removed as a whole first, then whitespace stripping and the per-character rules apply, with longer substrings taking priority. Each entry ≤ 64 code points, at most 64 entries. Cost: to match across deltas, each block keeps (longest substring − 1) characters out of detection. On the settings page this field shares one input box with the previous one: one code point that is not whitespace ⇒ goes to ignoredChars; anything else (multi-character substrings, single whitespace characters) ⇒ goes to ignoredSubstrings; separate multiple entries with spaces / commas (- | adds two entries, -| is one substring)
monitorReasoning true Also monitor reasoning text; set to false to detect visible output only
monitorReasoningFillers false Master switch for the reasoning filler-word alert; off by default; warning only, never stops
reasoningFillerPatterns hmm, wait, hold on, actually, alternatively, let me Only these literals are checked; comma/newline/semicolon separated, at most 16 patterns of 64 code points, case-insensitive; English patterns use word boundaries (wait does not match await); empty disables detection
reasoningFillerThresholdPerK 40 Frequency threshold (occurrences per 1k chars); reuses detectionWindow, evaluates after at least 200 chars; reaching it only shows a warning suggesting context compression or a new session
monitorToolArguments false Also monitor tool-call arguments (repeated characters are common in JSON / base64; off by default)
fixStandingMountConflict true standing-mount conflict patch (on by default; the defect was reproduced on 0.1.1-rc.1 / 0.1.2-rc.1, later versions were not tested one by one; code constant only, see "Limitations")
notifyOnStop true Whether to raise a global notice on stop (see the next section). Turning it off only hides notices; stopping behaviour is unchanged
systemNotify false Whether to also send a system notification on stop or filler-word alerts (browser Notification → Windows notification area / macOS Notification Center). Only fires while the DSH page is not in the foreground (tab in the background, window minimised, or window unfocused); the title and body are fixed text (no workspace path, session name, pattern or repeated content); the first time you turn it on the browser asks for permission. Requires the DSH web page to be open (a background tab is enough)
persistStopLog true Whether to write stops to ~/.dsh/dupgard/stops.jsonl, allow-to-continue choices to allows.jsonl, and filler alerts to fillers.jsonl in the same directory (rotated after 2MB; npm/resident build only, one switch controls all three). Redacted by default (no repeated content / session title / workspace path / filler patterns); set DSH_DUPGUARD_STOP_LOG_REDACT=0 to record full content. DSH_DUPGUARD_STOP_LOG=off is the higher-priority master switch. See "Stop, allow-continue and filler-alert records"
stopLogFullContent false Whether to record the full repeated text, session title, workspace path, allow-lists and filler patterns in the logs; use only for debugging. DSH_DUPGUARD_STOP_LOG_REDACT takes precedence (1 forces redaction, 0 forces full content). The settings-page recent records viewer also cleans old full records according to the current mode
stopDecision true Master switch for the threshold decision card. With the notice channel available, hitting the threshold only raises a notice (output keeps streaming); you choose stop now / allow to continue. Off → legacy "stop at threshold"
pauseDecisionOutput false Pause display (optional; npm build + notice channel): the chunk containing the hit is held until you decide; server-side compute is not paused. For large-chunk / bursty local models
localNoForcedStop true No forced stop for local models: when the provider is in the local list below, only the decision card is shown and nothing stops automatically; you can still use "Stop now". Turn it off to auto-stop local models at threshold × multiplier. Without a notice channel, a hit never stops either
localProviderIds 'ollama,llama.cpp,llamacpp,llama-cpp,lmstudio,lm-studio,localai,vllm,sglang,mlx,tabby,koboldcpp,text-generation-webui' Comma/space separated local provider ids (covers common local inference servers by default); used to tell local / no-API-cost calls apart. Add your custom provider id if needed
decisionTimeoutMs 4000 Minimum reaction time (ms, 1000–15000, step 500): an automatic stop cannot happen earlier; output does not pause by default (with pause-display on, the hit chunk waits for your decision)
stopAtMultiplier 2 Auto-stop multiplier (2–10): stops only when the actual repeats reach threshold × this value and the minimum reaction time has passed; if the repetition breaks first, the decision is cancelled
continuePrompt '请从中断处继续,不要重复之前的内容。' User message text injected into the session when the user clicks "send continue prompt" in the notice (≤ 500 code points; empty falls back to the default)

Advanced

Semantics of per-length counts: detection evaluates need(p) for each candidate period p, and a periodic text is also a legitimate repetition at integer multiples of its period. Therefore raising only the count for length 1 usually does nothing (the same aaaa… also matches at p=2, 3, …); to genuinely relax short strings you must raise every small period that can match, e.g. 1:40, 2:40, 3:40, *:10 (39 identical characters do not trigger, 40 do); conversely, long units only need fewer counts to take effect on their own (if the module returns "length ≥ 20 → 3", a 20-character unit repeating 3 times opens the decision card; without a channel it stops).

Priority and fallback chain: module loads successfully ⇒ use the module; module fails ⇒ base threshold (one warning, no silent fallback to the table); table looks up each item ⇒ if uncovered use * ⇒ otherwise threshold.

Per-length table mode: the candidate range is decided entirely by the table — the minimum unit length is fixed at 1 and the maximum unit length = the last row's end, both derived values (written back to the document, shown only in the diagnostics line at the bottom of the settings page); the only number editable in that tab is "threshold multiplier inside code blocks". Only when you need more tiers (> 16 rows), non-monotonic rules or a formula (e.g. max(3, ceil(200/p))) must you switch to a module.

Module mode (experimental): the argument is the cleaned unit length (Unicode code points) and it returns the required number of consecutive repeats (integer 2–1000; < 2 or non-integer ⇒ no detection at that length); it must return synchronously. At host start and on settings change it prints a "count policy" summary (mode, number of covered lengths, count range, longest span) — use it to confirm that the module is really in effect.

Settings as an experimental feature: the dropdown shows 高级模式(实验性) (advanced mode, experimental). Switching to advanced mode from any other mode pops a risk confirmation (the same pattern as DSH's "full permissions" dialog): you must tick "I understand the risks and want to continue" before "enable advanced mode" is clickable; cancelling keeps the previous mode and writes no settings. Re-selecting while already in advanced mode does not pop it again; leaving and re-entering does.

⚠ Safety note: the module file is executed inside the DSH host process and has the same permissions as DSH — it can read and write files, make network requests or execute arbitrary code; the plugin cannot validate the file contents, so only point it at sources you fully trust. Any extension works: .js / .cjs are safest; .mjs relies on the runtime's require(ESM) support (built in for Node ≥ 20.19 / ≥ 22.12; older versions fall back and warn); other extensions (such as .txt) are also loaded as CommonJS by Node; .json is data only and parsed as JSON, so it cannot export a function. Keep it synchronous, cheap and free of side effects: the plugin only clamps the return value, and falls back to the base threshold if loading or calling fails.

Functional equivalences (once you know them, you need not agonise over which one to use):

Equivalence Explanation
skipCodeBlocks: false ≡ codeBlockMultiplier: 1 Both mean "inside blocks is as strict as outside". The toggle is hidden; express it via the multiplier (0 = no detection inside blocks / 1 = tiering off / ≥2 = relaxed to "threshold × multiplier"), and changing the multiplier clears the old key automatically
Single-row table N:C ≡ simple mode threshold: C + maxUnitLength: N A single-row table's candidate range is just 1..N with a constant count C, and the derived window is the same
Constant module () => C ≡ simple mode (threshold C) The module merely expresses the count as a function
Step module ≡ per-length table Tables are capped at 16 rows and must cover contiguously; only more tiers, non-monotonic rules or formulas force a module
Single-character ignoredSubstrings entry ≡ ignoredChars entry For a single non-whitespace character both detect the same result (removal works per character, so the order does not matter), which is why the settings page offers one input box: one code point and non-whitespace goes to the character list, everything else to the substring list; the character list is a convenience that is on by default, the substring list additionally supports multi-character substrings
*:<count> in thresholdByLength Compatibility for hand-edited configs only: the settings page only produces contiguous tables (never *)
Hand-written detectionWindow value Overwritten by the derived value (the host does not read it); the settings page no longer offers an input

Which one to use: one threshold is enough → simple mode; a few tiers and no code → per-length table; a formula / non-monotonic rule / long plateau → advanced mode (experimental, requires the safety confirmation).

Trial-run it in an isolated environment first (strongly recommended): the advanced-mode module runs inside the host process, with the host's permissions, so before putting it into a real profile trial-run it with the sandbox that ships with this repo — it loads the module in a restricted child process, reuses the plugin's real counting code and prints the effective count for every length:

npm run sandbox:module -- <your module file>        # file writes / child processes denied, infinite loops cut by a timeout, network unrestricted (see below)
npm run sandbox:selftest                            # verifies the expected verdicts of six built-in samples (CI runs it too)

The full "three-layer isolation" recipe (sandbox trial run → dedicated profile + throwaway workspace → separate DSH_HOME / WSL) is kept in local-only advanced-mode notes and is not published with the repository; the dedicated profile (advtest) and throwaway workspace are already provisioned — start it with powershell -File tools\run-advtest.ps1 (the script clears variables such as DSH_PROFILE_DIR inherited from the current DSH session — otherwise the plugin reads the settings of another profile, which in practice overwrote the mode to table). Measured effective parameters: 模式=module|覆盖长度 1000 种|次数区间 3–20|最长跨度 3000 字符 (mode = module, 1000 lengths covered, counts 3–20, longest span 3000 characters — exactly the sample module's return values ⇒ the module really was loaded by the host and drove the policy).

Code-region detection (fenced / inline / indented, all alike): all three region kinds use the same threshold threshold × codeBlockMultiplier, with priority fenced > indented > inline:

What about "long non-faulty repetition" inside code blocks (box drawing, separators, ASCII art)? Use codeBlockMultiplier, do not add characters to the ignore list — the ignore list is global (it would also hide real faults such as "the model spinning on symbols"), whereas the multiplier only affects code regions. Measured (npm run audit:false-positives wraps real repository sources in fences and replays the detector): the default config false-kills 2 of 260 files (a ─ box-drawing run and a stretch of a); adding any symbol character (= * / . # _ ~ + 0 1) to the ignore list reduced nothing at all; raising the code multiplier from 3 to 4 (today's default; in-code threshold 30→40) brought it down to 0.

Region Enters Exits / boundary
Fenced code block line start ≤3 spaces + ≥3 consecutive backticks or ~ (followed by an info string) a run line of the same character, at least as long as the opener (whitespace only after it); if unclosed, it extends to the end of the block
Indented code block line start indented ≥4 (a tab counts as 4, \r is not counted) and the previous line is blank, and the previous non-blank line is not a list-item / block-quote start the first line that is non-blank and indented <4; blank lines inside the block do not end it. Indentation after a list item and paragraph continuation lines do not count as code (a conservative rule that avoids misjudgement)
Inline code opened by 1–64 backticks (1, 2, … up to 64 all work) it must be closed on the same line by a backtick run of equal length; a newline / more than 256 characters retained / end of block without closure ⇒ the opener counts as plain text and the content is detected as usual
  • with multiplier 0, nothing inside the three region kinds is judged, and region boundaries clear the detection buffer (text on either side is not stitched into artificial repetition) — that is the price of "no false kills however long the code is"; the default 4 still catches runaway loops at "threshold × 4";
  • backticks / indentation inside a fence do not open another region; a ``` indented by 4 spaces is not a fence either (it stays inside the indented code block);
  • CRLF-compatible line endings: \r counts as whitespace (not part of indentation), so fence closing lines, blank lines and indented code blocks in \r\n documents are judged correctly line by line;
  • inline regions need bounded retention (at most 256 characters after the opener are withheld from emission), so single-line inline code longer than 256 characters is judged as plain text (a known limitation, see below); an unclosed backtick warns once in the host log;
  • if an old config explicitly set skipCodeBlocks: false, the settings page shows a one-time hint below the multiplier row (equivalent to multiplier 1).

Detection window (derived automatically)

detectionWindow is computed by the plugin from the current parameters and equals exactly the "strictest repetition span" (the formula appears only in this section):

required   = max(plainSpan, policySpan)
plainSpan  = max(threshold, threshold × codeBlockMultiplier) × maxUnitLength
policySpan = max over p of ( p × need(p) × code-region multiplier )
value      = clamp(required, 64, 1048576)
  • simple mode uses plainSpan; policy modes (table / module) use policySpan — the base threshold is not added on top (the base threshold only applies when the table does not cover a length and there is no *, and its contribution is already counted in the policy table);
  • with multiplier 0 (no detection inside blocks) it counts as 1;
  • policy-mode example: 1:20,2:15,10:10,20:5,*:3 + max unit 1000 + multiplier 0 → 3000 (*:3 × 1000), not 10 × 1000 = 10000;
  • the result is clamped to 64–1048576; when clamping happens the settings page separately shows ⚠ 自动窗口需要 N 字符,已达上限 … (the auto window needs N characters, which exceeds the cap), in which case lower the threshold / code multiplier / maximum unit length (or the policy span) — the window itself is not an adjustable option;
  • the three derived values are detectionWindow, and in table mode minUnitLength (= 1) and maxUnitLength (= the last row's end); every time settings take effect they are written back to the settings document, so the config file and the UI show the same, actually effective values;
  • the settings page offers no input box and no dedicated row (an uneditable placeholder only makes the UI noisier); the numbers are folded into the diagnostics line at the bottom: table mode shows 自动派生:检测窗口 9000 · 最大重复单元长度 1000(末行决定) (auto-derived: detection window 9000 · max repeat unit length 1000, decided by the last row), while module mode shows the window value the host wrote back to the document.

How it works

  1. Intercept: listen to the llm/stream waterfall event (wrapping every streaming model call) and return a wrapped AsyncIterable; chunks are accumulated by chunk.index, so interleaved multi-block output does not interfere.
  2. Cleaning / ignore lists: first remove whole substrings from the substring list (longest first; tails spanning deltas are covered by the flush at block end) → then strip whitespace (can be disabled) → finally remove ignored characters one by one. With the substring list enabled, each block keeps at most (longest substring − 1) characters out of detection.
  3. Tail detection: run tail-consecutive-repetition detection on the cleaned buffer — a trigger happens when the text ends with a run of at least need(p) consecutive repeats of a unit whose length is minUnitLength..maxUnitLength. A repetition loop shows up as a consecutive repetition at the tail of the streamed output, so tail detection catches it while it happens, and it also avoids the false positives of whole-window word-frequency counting (such as the frequent Chinese particle "的").
  4. Decision and wrap-up: a hit opens the decision card by default (output keeps streaming; stop now / allow; without action it stops only after both the multiplier and the minimum reaction time are reached); without a notice channel or with decisions off it stops immediately. When generation is stopped, end the stream early → upstream iterator.return() → in the adapter's finally, consumer.abort() cancels the underlying HTTP request; at the same time emit block-end for every open block (carrying the full generated text) and finish{kind:'stop'}, satisfying the real DSH stream contract (real llm/stream waterfall + BlockAssembler; the older llm-invariant suite also passes), and the agent-loop commits what was generated as a normal assistant message. It does not abort() options.signal directly (for loop requests that is the agent step signal). Stopping does not wait for network cancellation: with the real adapter, stopping completes in about 1 ms (see tests/experiment-cancel.mjs).

What gets stopped

Shape Example
Single-character loop aaaaaaaaaa
Word / space-separated repetition 哈哈 ×10, hello hello hello … ×10
Line-by-line repetition (including loops after a prefix) 好的,下面开始回答: + 循环 ×10; 抱歉,我无法完成。 ×10 lines

"Repetition in reasoning" also opens the decision card by default (without a notice channel or with decisions off it stops immediately); the full "what it does not catch" list is in the small table under "Features" above (only consecutive repeats count, 9 or fewer does not trigger, tool arguments are off by default, table separator rows are ignored by default).

Stop notices and continue prompts

Every stop (notifyOnStop is on by default) pops a notice card in the browser, and the host also prints one line: [dupguard] 截停通知 dupguard-stop-N:工作区=… 会话=… 重复="…" ×N.

Why it always shows: the notice is registered inside DSH's framework-level overlay shell.overlay (root scope), not inside a session view — so whichever session you have open (even a blank page or the settings page), the notice for the stopped session appears. The stopped session may not be in the foreground at all, which is exactly why it has to say "who it is".

Optional: also send a system notification (systemNotify, off by default). The in-app overlay is only visible while the DSH page is open; if you switch to another app, you will not see it — with this toggle on, a stop also sends a browser system notification (Windows notification area / macOS Notification Center), and a reasoning filler-word alert sends its own fixed-text system notification when the threshold is reached. clicking it focuses the window and jumps to the stopped session. Four design constraints:

  1. Only fires while the page is not in the foreground (document.visibilityState === 'hidden', or the window is unfocused document.hasFocus() === false) — no repeated interruption while you are looking at the page;
  2. Only fixed title/body text — stop title DSH: model output was stopped, body Repeated output detected and generation stopped. Click to open.; filler-alert title DSH: too many reasoning filler words, body Try compressing the context or starting a new session. — system notifications appear on the lock screen / in the notification centre, a wider privacy surface than the in-app overlay, so they carry no workspace path, session name, patterns or repeated content;
  3. Consecutive stops in the same session replace the previous one via tag, instead of stacking up;
  4. The first time you turn the toggle on, browser permission is requested within a user gesture; if denied or unsupported it simply does not fire, and the overlay keeps working.

Can the desktop (Electron) build show them? Yes. The desktop UI is a privileged scheme registered as dsh-app://app (standard + secure), so it is a secure context as well; and the desktop's permission handling approves every non-media permission (setPermissionCheckHandler returns true, setPermissionRequestHandler calls callback(true) directly) ⇒ system notification permission is automatically "granted" ✓, with no permission dialog. The desktop build itself uses Electron Notification for forced-update reminders, through the same Windows toast channel (the attribution is the app, not the browser) ✓. Two practical notes:

  • It only fires when the window is not in the foreground: minimising, switching to another tab, or switching to another window (the browser window is still visible but unfocused) all trigger it; it does not fire while the page is visible and focused, to avoid interrupting you while you are looking at the overlay. When the browser is fully closed there is no page to send a notification — an inherent constraint of browser page notifications;
  • the desktop build's plugins are managed exclusively by the app (the CLI is rejected), so update inside the app's Settings → Plugins to a version that has this feature.

Notice fields at minimum:

Field Source When missing
Workspace (name + path) session header.cwd + the workspace registry's name matched by path path only; if there is no path either, (未知工作区) (unknown workspace)
Session name the sessionTitle service's title projection (未命名会话) (untitled session) + a short session id
Repeated string the matched unit's original text (monospace + quotes; > 160 code points truncated, with the real length kept) empty / pure whitespace shows (空字符串/纯空白) (empty / whitespace only)
Repeat count / span / matched channel the count / span at the hit / text or reasoning or tool arguments —
Inside a code region? a hit inside any of the three code-region kinds (fenced / inline / indented) is marked 已按倍数放宽 (relaxed by the multiplier) —

Three actions:

  1. Send continue prompt — the host injects a user message (content = continuePrompt) into the stopped session; that session must still be running; on success the card is removed from the UI, on failure (e.g. the session is closed) the reason is shown on the card and the card stays for you to handle manually;
  2. Don't send — only records your choice, injects nothing;
  3. Open that session — jumps to the stopped session (client uiWorkspace.openSession; the button is hidden when unavailable).

Boundaries and costs (all covered by tests):

  • each stop produces one notice, and the queue keeps at most the latest 20; processed ones (sent / ignored) are no longer shown, even after a page refresh;
  • the notice channel is a host built-in same-origin HTTP route (/dsh-dupguard/…): cross-site requests are rejected, the request body is size-capped, and responses are not cached; clicking "send continue prompt" repeatedly for the same session is idempotent (injected once);
  • when the host has no webServer service (too old a DSH version) the notice is unavailable and only warns once in the host log — stopping itself is unaffected;
  • host code is loaded at process start: changing this feature requires restarting dsh web; changing only settings (including toggles and text) does not. Without a restart it is not silent: a hint card appears in the bottom-right corner of the page (saying the host half has not been loaded yet); click 知道了 (got it) to dismiss it, and it disappears automatically after the host restarts;
  • the injected message is an ordinary user message and enters the session history normally (subject to later compaction / rollback mechanisms); the plugin makes no hidden rewrites.

Decision card before stopping (output continues)

When stopDecision is on (default), notifyOnStop is on and the notice channel (webServer) is available, hitting the threshold does not pause output by default; it only shows a decision card:

  1. Output keeps streaming while the card is shown (idle polling 500ms, so the card usually appears within 1s);
  2. The card offers three choices:
    • Stop now: the next chunk wraps up immediately (normal stop wrap-up + the usual stop notice with the continue prompt);
    • Allow to continue: stop detecting for the rest of this generation;
    • Dismiss card: no decision; the auto-stop condition stays armed;
  3. Auto-stop condition = actual repeats reach threshold × stopAtMultiplier AND decisionTimeoutMs (minimum reaction time) has elapsed since the threshold — both conditions must hold (equivalent to the later of the two moments):
    • multiplier reached first → keep streaming and wait for the reaction time, then stop if still repeating;
    • reaction time elapsed first → keep watching until the multiplier is reached while still repeating;
    • repetition breaks in between → cancel the decision, no stop;
    • stream ends naturally → no stop.
  4. User actions take effect on the next streamed chunk.

One card per repetition episode: the decision stage judges continuation by the occurrences of the unit inside a recent window, not by strict trailing equality; so periodic/rotating text (an endless alphabet, for example) is not mistaken for an ended repetition when the tail phase shifts, and it does not flood the overlay with recovered cards; auto-stop counts occurrences in the same window and only cancels once enough genuinely non-repeating content has passed.

Optional: pause display on a hit (pauseDecisionOutput, off by default): this pauses display only, never server-side compute. The chunk that crossed the threshold is held back; "stop now" keeps only what was already displayed and discards the held chunk (the block is closed with the truncated text), while "allow to continue" releases it. Without action, if the multiplier is already reached it stops after the minimum reaction time; otherwise output resumes and the card switches to the watching state above. It targets large-chunk / bursty local models (Ollama / llama.cpp / vLLM / custom providers — anything that goes through the DSH llm/stream waterfall); the model service has no pause/resume protocol, so generation may continue while display is paused.

Local models are not force-stopped by default (localNoForcedStop is on): a local model only costs electricity, not API fees, so when the provider is in localProviderIds (common local services such as ollama, editable) the plugin only shows the decision card and never stops automatically; you can still use "Stop now" to end the call immediately. Without a notice channel (dynamic build / notices off), a hit does not stop the stream either — the plugin logs one note. Turn the switch off if you want local models to auto-stop at threshold × multiplier. Detection uses the DSH provider id, so models invoked outside DSH (for example directly by a script) are not covered.

Fallbacks (legacy "stop at threshold"):

  • host has no webServer (notice channel unavailable), notifyOnStop is off, or stopDecision=false;
  • the dynamic plugin build plugin/host.js (no notice channel, does not read settings);
  • DSH_DUPGUARD_DECISION=off forces the fallback for troubleshooting.

Latency and cost: the client polls every 500ms when idle and every 300ms while a decision card exists; by default nothing pauses, so content keeps streaming during the reaction window (at most the generation produced in that window), but there is no pause and no burst. The card also shows current repeats / auto-stop target, a count progress bar and the minimum-reaction-time countdown; local no-force-stop cards omit the auto-stop target.

Privacy: decision cards and reasoning filler-word alerts live only in host memory; filler alerts may be written to fillers.jsonl under the same switch/redaction as stops and allows, with dismissal/replacement outcomes. An actual stop writes stops.jsonl / sends a system notification; allow-to-continue writes only allows.jsonl (no notification).

Stop, allow-continue and filler-alert records (persistent log, npm build only)

The npm/resident bui

…

Content from the project README on GitHub ↗

Links

More in this category

View the whole category →

Community comments

Comments are public GitHub Discussions. Loading them connects to GitHub and Giscus; a GitHub account is required to post.