beijingwahw/dsh-companion-dev

dsh-companion-dev

DeepSeek Companion 开发者版 — DeepSeek Harness 官方伴侣插件完整功能集:A–J 九大模块(对话导出/交接摘要/成本优化/全局检索 + 执行轨迹分析、Prompt 工程工作台、多模型竞技场、任务编排、安全审计),Cordis 插件化架构。

Uncategorizedai-agentscordisdeepseek-harness

DeepSeek Companion (Developer Edition)

English | 中文

Edition note: this repository is the Developer edition with all nine modules A–J. For the Lite edition (four core modules A–D), see beijingwahw/dsh-companion.

The official companion plugin for DeepSeek Harness — built on the Cordis framework and the Harness Plugin SDK, bringing nine capabilities to the DeepSeek Harness platform: smart conversation export, context handoff summaries, API cost optimization, global conversation search, execution-trace analysis, a prompt engineering workbench, a multi-model arena, task orchestration, and security audit.

  • Language: TypeScript (strict: true, ESM)
  • Runtime: DeepSeek Harness (Cordis ≥ 4.0, everything is a plugin)
  • API: direct connection to the official DeepSeek API (https://api.deepseek.com)
  • Data safety: all user data stays inside the Harness plugin sandbox; API keys are stored AES-256-GCM encrypted

Feature Overview

ModuleCapabilitiesToggle
A · Smart conversation exportMarkdown / PDF / JSON / long PNG export, timestamp switch, privacy redaction (auto-masking of phone numbers / emails / ID numbers / bank cards), multi-session batch ZIP; PDFs containing Chinese are rasterized client-side into print-free multi-page PDFs (no window.print() dialog freeze)enableExport
B · Context handoff summaryOne-click ≤500-char four-section handoff summary, editable, copy to clipboard, save as template; import a summary as the first system message of a new conversation for cross-conversation context inheritanceenableHandoff
C · API cost optimization (developer mode)Encrypted API-key vault, official dynamic pricing engine (hourly scraping of DeepSeek and domestic vendor pricing pages; new models / price changes auto-imported; silent fallback to the built-in snapshot on failure), peak/off-peak time-based pricing, peak-aware scheduling (peak windows resolved live from the pricing pages), smart model routing, daily/monthly dual-tier budgets with 80%/100% alerts and auto-pause of non-essential calls, cache-hit discounted billing, daily/weekly token and cost reportsenableCost
D · Global conversation search + in-conversation searchFuzzy keyword search, time-range filtering, custom tags (add/remove/filter), click-through to conversations; in-conversation search (Ctrl+F floating find bar, non-invasive highlighting via the CSS Custom Highlight API, case/whole-word toggles, query history, auto-resync during streaming output)enableSearch
E · Execution trace analyzer (developer)Parses harness-native traces into an interactive timeline (latency / token breakdown / model / cache hits), one-click location of the 3 slowest and 3 most expensive steps, automatic anomaly annotations (retry loops / token explosions / cache misses / infinite loops), trace diffing with HTML report export, daily aggregated trends with historical-baseline alertsenableTrace
F · Prompt engineering workbench (developer)Prompt version management (auto versioning / notes / tags / rollback), A/B testing panel (batch test sets, metric comparison, manual-rating win-rate stats), template library (categories / variable interpolation / one-click Python·Node.js·curl code generation), structured-output JSON Schema batch validation with compliance statsenablePrompt
G · Multi-model arena (developer)Same-prompt parallel model comparison (up to 5; output/latency/tokens/cost side by side), batch-evaluation leaderboards (accuracy / P50·P95·P99 / cost / compliance weighted score, MD/HTML reports), a model recommendation engine (task type + budget + latency + peak-aware pricing, with reasons), encrypted vault for external vendor keysenableArena
H · Resume-from-breakpoint task orchestration (developer)Visual pipelines (model / prompt / input source / conditional branches / timeouts / retries / dependencies, auto-generated YAML), resume-from-breakpoint (progress percentage, intermediate-result persistence, recovery from the last successful step), batch task queues (priority / deadlines / failure policies / bulk pause-resume-cancel), scheduled jobs (Cron + Chinese natural language, off-peak execution, history archiving)enableOrchestrator
J · Security and audit (enterprise developers)Multi-API-key management (scopes / rotation reminders / leak detection), operation audit logs (redacted prompt summaries / filtering / CSV·JSON export), DLP data-loss prevention (built-in + custom regex rules, strict-mode interception, pre-send checks), compliance reports (calls / costs / model share / interceptions / alerts, HTML export printable as PDF)enableSecurity

All nine modules are independent Cordis sub-plugins — enable or disable any combination without side effects.


Installation

Prerequisites

The recommended path is the dsh CLI one-liner (--profile picks the target profile, e.g. web; the built artifact lib/ ships with the repo, so installation needs no build scripts):

dsh plugin add beijingwahw/dsh-companion-dev --profile web
dsh web

Note: the package name is dsh-companion (manifest id deepseek-companion); installing from this repo with its -dev suffix is unaffected.

You can also install from source:

git clone https://github.com/beijingwahw/dsh-companion-dev.git
cd dsh-companion-dev
pnpm install
pnpm run build

Start

dsh web

The plugin panel loads automatically in the Harness Web UI.

Verify the installation

Run the usage command in the Harness command palette; a text report of this month's usage means the plugin mounted correctly.


Usage

Configure the DeepSeek API key (required by module C)

  1. Turn on the "Developer mode" master switch on the plugin settings page.
  2. Paste your DeepSeek API key into the "API Key management" input and save.
    • The key is AES-256-GCM encrypted into the companion storage domain of the Harness plugin sandbox;
    • The plaintext key never appears in any response, log, or event (/cost/state only returns the apiKeyConfigured boolean).
  3. Optional: click "Test connection" to validate the key (maps to /cost/test-call).

Module A: exporting conversations

  • Single export: click "Export" in the conversation header actions, or run the export command. Pick a format (Markdown / PDF / JSON / long PNG), choose whether to keep timestamps (default on) and whether to redact privacy, then the file downloads via the browser.
  • Long PNG: the whole conversation is rasterized client-side (SVG foreignObject, 2x retina) into one tall image downloaded directly; client-UI only (the command palette has no canvas) and not part of batch ZIP.
  • Batch export: select multiple sessions in the history list and click "Batch export" (or the export-batch command) to get a ZIP (up to 100 sessions per run, auto-deduplicated).
  • PDF notes: pure Latin-1 content produces a structured PDF directly; content with Chinese or other non-Latin-1 characters is rasterized client-side into a print-free multi-page PDF (A4 pagination, JPEG encoding, zero-dependency PDF assembly), never touching the window.print() dialog — that path freezes the whole browser on some platforms (notably Windows Chrome); environments without raster capability (command palette) fall back to a print view for the browser's save-as-PDF.

Module B: handoff summaries

  • Generate: click the "Handoff summary" button in the conversation header (or the handoff command); the plugin calls the DeepSeek API with a fixed four-section prompt: core conclusions / resolved problems / key background / open to-dos and unresolved questions (≤500 chars).
  • Edit and reuse: the summary appears in an editable dialog supporting "Copy to clipboard" and "Save as template"; templates can be viewed and deleted later, and an existing template can be used as the instruction text when generating (falling back to the fixed contract prompt by default).
  • Import for inheritance: in a new conversation, paste a summary via the "Import history summary" entry in the input dock (or the handoff-import command). The plugin arms it for the next new conversation, injecting it automatically as the first system message — cross-conversation context inheritance.

Module C: cost optimization

  • Official dynamic pricing: the pricing engine scrapes the official DeepSeek pricing page (including the peak/off-peak schedule) hourly, plus pages of domestic vendors (Zhipu / Baidu ERNIE / ByteDance Doubao / Kimi and more), auto-discovering priced models; persisted on change and reused after restart; scraping failures silently fall back to the built-in catalog snapshot without interrupting live pricing. Users can override unit prices per model id (longest-prefix match).
  • Peak/off-peak time-based pricing: peak windows declared on the pricing page (defaults 9:00–12:00 and 14:00–18:00 Beijing time) bill at peak rates, off-peak at off-peak rates; cache-hit inputs bill at the discounted rate.
  • Peak-aware scheduling: when enabled, tasks can be marked "urgent / normal". "Normal" tasks enter a deferred queue during peak windows (capacity 100) and fire in off-peak hours; peak windows prefer the pricing engine's live resolution of the pricing page, falling back to built-in defaults on error; queued tasks are re-checked against the budget before executing while paused; interactive operations (like generating a handoff summary) count as "urgent" and never defer.
  • Smart model routing: when enabled, the model is picked by task type — simple tasks (translation, summarization) go to deepseek-chat, complex ones (code generation, reasoning) to deepseek-coder; custom routing rules can override the default policy.
  • Daily/monthly dual-tier budgets: set daily and monthly caps independently (CNY, 0 = unlimited). At 80% of either tier the Harness notification system warns; at 100% it warns again and auto-pauses non-essential API calls (essential calls still pass with continuous alerts).
  • Cost reports: a dedicated view shows daily/weekly token usage, cost estimates (resolved live by the pricing engine), daily/monthly budget progress bars (yellow at 80%, red at 100%), pricing source (official live / built-in snapshot) and the peak/off-peak plan, plus manual pricing refresh and the amount saved by peak-aware scheduling. The usage command prints this month's text report inside the panel.
  • A global search box is injected atop the history list (or the search command):
    • Keywords: fuzzy match across all historical conversations;
    • Time: date pickers filter by range;
    • Tags: the tag command or the results page manages custom tags per session, filterable by tag.
  • Results render as a list with hit snippets; clicking jumps straight to the conversation.
  • In-conversation search (absorbed from dsh-conv-search): click "In-conversation search" in the header or press Ctrl/Cmd+F to open the floating find bar:
    • Enter / Shift+Enter, F3 / Ctrl+G: next / previous hit (wrapping); Esc closes; ↑ / ↓ browses query history;
    • Aa / ab toggles: case-sensitive / whole-word matching;
    • Highlights draw through the CSS Custom Highlight API as an overlay, never touching the React-managed transcript DOM; during streaming output or loading of earlier messages a MutationObserver resyncs automatically, with the active hit kept by "text node + offset" identity so the reader's scroll never jumps;
    • Matching scans only the conversation scrollport, excluding input drafts and the find bar itself — no phantom hits.

Configuration Reference

Root config (any field can be overridden via cordis.patch.yml):

FieldTypeDefaultDescription
enableExportbooleantrueEnable module A
enableHandoffbooleantrueEnable module B
enableCostbooleantrueEnable module C
enableSearchbooleantrueEnable module D
enableTracebooleantrueEnable module E
enablePromptbooleantrueEnable module F
enableArenabooleantrueEnable module G
enableOrchestratorbooleantrueEnable module H
enableSecuritybooleantrueEnable module J
apiBaseUrlstringhttps://api.deepseek.comDeepSeek API base URL (allowed by the manifest)
apiTimeoutMsnumber60000Per-call API timeout (ms)

To disable a single module: set its toggle to false (config layer) or turn it off in the module declarations of manifest.json. Modules are zero-coupled — disabling one never affects the rest.


Development-time hot reload (HMR)

LayerMethodScope
Runtime configEdit the dsh user-level cordis.patch.yml (~/.dsh/profiles/<name>/ or ~/.dsh/); saving applies immediatelydsh natively watches the user layer and transactionally reloads the line (bundle-level defaults are fully listed — copy the whole line to override)
Development codenpm run dev starts a standalone cordis + HMR processSaving any file under src/ or cordis.yml → old instance unloads (effects rolled back) → new code mounts, no restart needed
Installed artifactChange code → npm run build → re-run dsh plugin add → restart dshUpdates the installed plugin

What npm run dev consists of: the repo-root cordis.yml mounts logger / timer / hmr / host stubs / this plugin in order (loading src/index.ts directly, with config matching cordis.patch.yml key by key — development behavior = production bundle behavior); dev/host-stubs.ts provides minimal stubs for the 7 dsh host services (webServer / storageDomain / credentials / sessionQuery / commands / settings / systemPrompt) — the storage domain is in-memory and cached by name, so development data survives hot reloads.

Note: development HMR requires Node ≥ 24.11 (early 24.x releases such as 24.1.0 have Node-internal interfaces incompatible with cordis-plugin-loader 1.0.2 — the symptom is edits not triggering reloads).


Architecture at a Glance

src/
├── index.ts              # Host entry: mounts the core service + nine module sub-plugins per config
├── config.ts             # Root config schema (schemastery-validated)
├── core/                 # Core infrastructure
│   ├── service.ts        #   CompanionCore root service (ctx.companion, owns the pricing engine)
│   ├── vault.ts          #   SecretVault: AES-256-GCM encrypted vault
│   ├── crypto.ts         #   AES-256-GCM primitives (Node crypto)
│   ├── deepseek.ts       #   DeepSeek Chat Completions client
│   ├── usage.ts          #   Usage bookkeeping store (daily granularity, incl. cache-hit tokens)
│   ├── pricing.ts        #   Pricing bridge (official usage → engine usage shape)
│   ├── price/            #   Dynamic pricing engine (ported from dsh-usage-ledger):
│   │                     #   types / catalog (multi-vendor price catalog) / scrapers (pricing-page parsers) / service
│   ├── time.ts           #   Beijing-time peak/off-peak window math
│   ├── transcript.ts     #   Conversation transcript formatting (MD/JSON)
│   ├── privacy.ts        #   Privacy redaction (phone/email/ID/bank card)
│   ├── pdf.ts / zip.ts   #   Zero-dependency PDF generation / ZIP packing
│   └── http.ts           #   Private HTTP router (prefix /companion)
├── modules/
│   ├── export/           # Module A: export + batch ZIP + raster payloads (PNG / print-free PDF)
│   ├── handoff/          # Module B: summary generation / templates / armed import
│   ├── cost/             # Module C: gateway / scheduler / routing / dual-tier budgets / settings
│   ├── search/           # Module D: search + tags
│   ├── trace/            # Module E: trace derivation / anomaly annotations / diff / daily stats
│   ├── prompt/           # Module F: versioning / A/B testing / template library / schema validation
│   ├── arena/            # Module G: model catalog / parallel comparison / leaderboards / recommendations
│   ├── orchestrator/     # Module H: pipeline engine / queues / Cron and natural-language scheduling
│   └── security/         # Module J: named keys / audit logs / DLP / compliance reports
├── client/               # Browser UI (slot-injected, official component library)
│   ├── index.tsx         #   Client entry: slot registration + in-conversation search lifecycle
│   ├── raster.ts         #   Client raster export engine (ported from dsh-conv-export):
│   │                     #   long PNG / print-free multi-page PDF (foreignObject → canvas → JPEG → PDF assembly)
│   ├── convsearch/       #   In-conversation search (ported from dsh-conv-search):
│   │                     #   engine (Highlight API) / controller (floating bar + hotkeys) / styles
│   └── components/       #   Export dialog / summary dialog / import dock / search view / report view /
│                         #   trace analysis / prompt workbench / arena / orchestration / security views
└── types/                # Harness subsystem adapter type declarations

Key design decisions:

  • Everything is a plugin: the host entry only orchestrates mounting; each feature module is an independent Cordis function plugin — registration is an effect, and Cordis rolls lifecycles back automatically.
  • Single service facade: modules never import each other; cross-module collaboration goes through ctx.companion (core service) or ctx.companionCost (cost gateway).
  • Isomorphic dual channels: command-palette handlers and private HTTP endpoints (/companion/*) reuse the same module service functions — no duplicated logic.
  • Non-invasive UI: all UI is injected via Harness slots (conversation.session.header.actions, conversation.input.dock, conversation.view), components come from the official UI primitives library, colors use semantic tokens only — no floating windows, no global styles.

The complete internal contract (service signatures, HTTP API, command table, slot list) lives in DESIGN.md.


Security and Privacy

RequirementImplementation
Data localityConversation content, settings, and API keys are written only to the companion storage domain of the Harness plugin sandbox — never uploaded to any third-party server
API key encryptionAES-256-GCM (12-byte random IV + auth tag), self-describing payload v1.<iv>.<tag>.<ciphertext>; key and ciphertext stored separately
Network permissionsmanifest.json allows exactly the official DeepSeek API, all domestic and major international model-vendor endpoints, vendor pricing pages, and common relay/aggregation gateways for the multi-model arena's direct connections and the pricing engine's live scraping; storage is limited to companion; the service list is itemized
No trackingNo telemetry or behavioral-analytics code; manifest.json explicitly declares tracking: false, telemetry: false
No key leakageThe plaintext key never appears in any response, log, or event; export and summary content is generated locally in the browser only

Deliverables

  • Full Harness plugin source (src/, TypeScript strict)
  • manifest.json (permission and privacy declarations), package.json, cordis.patch.yml (bundle patch layer), tsconfig.json
  • README.md / README.en.md: feature intro, install guide, usage
  • DESIGN.md: architecture contract and development conventions
  • Independent module toggles: config switches + independent sub-plugins + manifest module declarations, three layers of assurance

Capability Origins

On top of the original four modules, this plugin absorbs and integrates the core capabilities of three sibling repositories:

Source repoAbsorbed capabilitiesLanding spots
dsh-usage-ledgerOfficial pricing-page dynamic pricing engine (live scraping/parsing/fallback snapshots), peak/off-peak time-based pricing, multi-vendor price catalog and dedicated parsers, cache-hit discounts, daily/monthly dual-tier budgetssrc/core/price/, src/modules/cost/
dsh-conv-exportLong-PNG raster export, print-free multi-page PDF (foreignObject → canvas → JPEG → zero-dependency PDF assembly), image data-URL inliningsrc/client/raster.ts, src/modules/export/ (kind:'raster' payloads)
dsh-conv-searchIn-conversation search engine (non-invasive CSS Custom Highlight API highlighting), floating find bar (hotkeys/query history/case and whole-word toggles), MutationObserver resync during streaming and hit-anchor preservationsrc/client/convsearch/

During porting we unified the namespace (companion-*), comment language, and error-handling discipline, and rewired everything onto this plugin's slots/dual-channel architecture; all changes pass tsc --noEmit strict type checking and 39 smoke assertions.

License

MIT