DSH HUB
HomePlugin StorePlugin PacksCommunityRankingsResourcesPublish Guide
Plugin source
Back to catalog

juliandzzz /

juliandzzz/dsh-ptc-kit

Topic repository only

Stop coding agents from falling back to brittle bash/heredoc hacks in DeepSeek Harness PTC mode: Rust-backed 55-language tree-sitter outlines, atomic line#hash patching, parallel checks & smart output budgeting.

★ 0 Stars0 Forks0 IssuesN/A Community rating0 Confirmed installs
View on GitHub
READMESource: main@ab190baf

dsh-ptc-kit

A fast, Rust-backed Programmatic Tool Calling (PTC) toolset for DeepSeek Harness (DSH) that replaces DSH's built-in read, glob, grep, edit, and apply_patch tools with six composable, schema-driven tools (read, glob, grep, outline, patch, check) — plus structure-aware output budgeting and mode/model-specific prompt guidance.

Designed to be mounted inside your PTC preset (alongside @deepseek-ai/dsh-tool-registry-ptc), leaving standard, minimal, and other presets completely untouched.

Why dsh-ptc-kit?

In DeepSeek Harness's PTC (run_code) mode, models frequently fall back to stuffing tools.bash(...) with multi-command pipelines, sed/awk, python -c, or cat << 'EOF' heredocs — and then break on nested TypeScript + shell quoting and escaping bugs. That happens because of tool-interface friction, not because models prefer bash: when file discovery, symbol navigation, multi-file editing, and parallel checks lack clean programmatic return values, shelling out becomes the path of least resistance.

  • Eliminate bash + heredoc fallback & escaping bugs: Gives the agent structured TypeScript primitives (glob, grep, outline, read, patch, check) so it filters, transforms, edits, and verifies directly in run_code instead of nesting shell scripts inside tools.bash(...).
  • Spend fewer context tokens on exploration: Inspect file structure first with 55-language tree-sitter outlines, read only the exact symbol or line ranges you need, and get bounded compiler/test diagnostics instead of raw log dumps.
  • Prevent drifted edits: Every line returned by read, grep, and outline carries a short content hash (line#hash). patch verifies every hash and symbol across all target files atomically before writing a single byte.
  • Run checks in parallel: check is concurrency-safe, so multiple build, test, lint, and typecheck commands run side by side under Promise.all and return compact pass/fail summaries with deduplicated file:line locations.
  • Smart output budgeting & prompt tuning: Keeps small fields and multiple inspect(...) entries 100% intact via water-filling, trims only oversized fields on clean line boundaries with exact read({ path, start, end }) spill coordinates, preserves images, and injects mode/model-specific workflow guidance (0 tokens for non-matching models).

Before & After: Eliminating Shell Friction & Composing Multi-Step Work

Consider a routine task: find createSession, update its signature and callers across 3 files, and verify typecheck + tests.

Before (default DSH tools)

Without composable PTC primitives, agents hit one of two failure modes:

  1. Turn explosion & context bloat — bouncing across 8–10 sequential turns (grep dumps 60 raw hits -> 3 full-file reads -> 3 single-file edit calls with whitespace/drift retries -> serial bash typecheck + test dumps -> another read to inspect the failing line).
  2. Fragile bash + heredoc workarounds in run_code — trying to avoid 10 turns by stuffing rg, sed, python3 -c, or cat << 'EOF' scripts into tools.bash(...), which routinely fails on double-escaped quotes, backslashes, and $ expansion while running checks serially:
// Common PTC anti-pattern caused by tool-interface friction:
const out = await tools.bash({
  description: "Search, patch files with python heredoc, and run checks",
  command: `rg -n 'createSession\\(' src && python3 - <<'EOF'
# nested JS string + bash quoting + Python regex escaping -> brittle & error-prone
...
EOF
pnpm typecheck && pnpm test`,
});

After (dsh-ptc-kit in PTC run_code mode)

All discovery, filtering, editing, parallel verification, and failure lookup collapse into 2 composed steps — and intermediate reads/filtering inside run_code cost 0 context tokens:

Step 1 — Discover, resolve enclosing symbols, and read only the relevant functions:

// 1. Parallel discovery (0 context tokens until inspect)
const [hits, pkg] = await Promise.all([
  tools.grep({ pattern: String.raw`\bcreateSession\s*\(`, path: "src", include: "*.ts" }),
  tools.read({ path: "package.json" }),
]);

// 2. Deduplicate hits in TypeScript and map each hit to its enclosing declaration
const unique = hits.matches.filter(
  (m, i, arr) => arr.findIndex((x) => x.path === m.path && Math.abs(x.lineNumber - m.lineNumber) < 20) === i,
);
const outlines = await Promise.all(
  unique.map((m) => tools.outline({ path: m.path, atLine: m.lineNumber })),
);
const slices = await Promise.all(
  unique.map((m, i) => {
    const sym = outlines[i].enclosing;
    return sym
      ? tools.read({ path: m.path, start: sym.start, end: sym.end })
      : tools.read({ path: m.path, around: m.lineNumber, ctx: 10 });
  }),
);

// 3. Surface only the exact slices (with line#hash refs ready for patch)
inspect({
  scripts: Object.keys(JSON.parse(pkg.text).scripts ?? {}),
  targets: unique.map((m, i) => ({
    loc: `${m.path}:${m.ref}`,
    symbol: outlines[i].enclosing?.qualifiedName,
    code: slices[i].formatted,
  })),
});

Step 2 — Atomic multi-file edit, parallel verification, and same-turn failure diagnosis:

// 1. Verify and apply edits across all 3 files atomically (all-or-nothing)
const edited = await tools.patch({
  files: [
    { path: "src/session.ts", edits: [{ symbol: "createSession", lines: ["export function createSession(ctx: Context, opts: Options) {", "  // ...", "}"] }] },
    { path: "src/server.ts",  edits: [{ in: "Server.handle", find: "createSession(opts)", replace: "createSession(this.ctx, opts)" }] },
    { path: "src/cli.ts",     edits: [{ from: "84#91c", lines: ["  const session = createSession(ctx, opts);"] }] },
  ],
});

// 2. Run typecheck and tests concurrently; only bounded diagnostics come back
const [typecheck, tests] = await Promise.all([
  tools.check({ command: "pnpm typecheck" }),
  tools.check({ command: "pnpm test" }),
]);

// 3. If anything failed, pull the implicated source window in the same turn
const firstFail = typecheck.locations?.[0] ?? tests.locations?.[0];
const failureContext = firstFail
  ? (await tools.read({ path: firstFail.path, around: firstFail.line, ctx: 6 })).formatted
  : null;

inspect({
  ok: typecheck.ok && tests.ok,
  edited: edited.affectedPaths,
  typecheck,
  tests,
  failureContext,
});

In standard tool-calling mode (without run_code), the same tools still cut round trips and token burn: outline avoids full-file reads, a single patch call updates multiple files atomically by symbol or line#hash, and multiple check calls run in parallel with compact diagnostics.

Included Tools

Tool What it does
read Reads UTF-8 files (whole file, line range, or symmetric context window) with line#hash anchors ready for patching.
glob Fast .gitignore-aware file discovery sorted by modification time (ignored: true to include hidden and ignored files).
grep Single-pass regex or literal content search with line#hash anchors, case-insensitive matching, and path-relative include globs.
outline Structural code and document outlines across 55 languages/formats with symbol spans and enclosing-declaration lookup (atLine).
patch Atomic single- or multi-file edits by symbol name (symbol, beforeSymbol, afterSymbol), verified line#hash range, or scoped find/replace.
check Concurrency-safe build, test, lint, and typecheck runner with built-in diagnostic parsers for 14 toolchains plus a generic fallback.

DSH's built-in write tool stays enabled for creating new files; dsh-ptc-kit only replaces file reading, searching, and patching.

Supported check diagnostic parsers: cargo, tsc, python, go, node, lean, cc, typst, latex, dotnet, jvm, cmake, terraform, ocaml, and generic (plus custom regex via pattern).

Quick Start

Prerequisites

  • DeepSeek Harness (DSH) >= 0.2.3-alpha.3
  • Node.js and pnpm
  • Rust toolchain (cargo, edition 2024)
  • Helix tree-sitter grammars (needed for outline and symbol-scoped patch; installed automatically by the setup script below)

1. Clone and build

git clone https://github.com/juliandzzz/dsh-ptc-kit.git
cd dsh-ptc-kit
pnpm install
./scripts/setup-grammars.sh   # locates or installs Helix tree-sitter grammars
pnpm run build                # compiles the Rust binary and TypeScript plugin

The plugin automatically uses the compiled binary inside the repository — no global installation is required.

2. Mount inside your PTC preset

Mount dsh-ptc-kit only inside your PTC preset's config.plugins list (not at the top level of cordis.patch.yml and not inside non-PTC presets), so standard, minimal, and other presets keep their default tools untouched.

Inside your PTC preset (@deepseek-ai/dsh-agent-preset) in ~/.dsh/profiles/<profile>/cordis.patch.yml, disable the overlapping tool-fs tools, omit/disable tool-fs-search, and add dsh-ptc-kit alongside tool-registry-ptc:

- id: preset-ptc-custom
  name: '@deepseek-ai/dsh-agent-preset'
  config:
    id: ptc-custom
    plugins:
      # ... your other preset plugins ...
      - id: tool-fs
        name: '@deepseek-ai/dsh-tool-fs'
        config:
          read: false
          edit: false
          applyPatch: false
      # omit or disable tool-fs-search (replaced by dsh-ptc-kit glob/grep)
      - id: dsh-ptc-kit
        name: 'file:///path/to/dsh-ptc-kit/lib/index.js'
      # ... keep tool-registry-ptc enabled for PTC (run_code) mode ...
      - id: tool-registry-ptc
        name: '@deepseek-ai/dsh-tool-registry-ptc'

Restart DSH (or start a new session with that preset) after editing your profile.

Configuration

All options are optional and work out of the box with sensible defaults:

Option Type Default Description
read boolean true Enable the read tool.
glob boolean true Enable the glob tool.
grep boolean true Enable the grep tool.
outline boolean true Enable the outline tool.
patch boolean true Enable the patch tool.
check boolean true Enable the check tool.
binaryPath string auto-detected Custom path to the ptc-kit binary (defaults to the repo build, then ~/.local/bin/ptc-kit, then PATH).
defaultMaxGlobResults number 2000 Default maximum paths returned by glob (0 = unlimited).
defaultMaxGrepMatches number 500 Default maximum matches returned by grep (0 = unlimited).
promptGuide boolean true Inject mode-aware (PTC vs. standard) workflow guidance into the system prompt.
modelGuidance boolean true Inject model-specific rules into the system prompt for matching models.
modelRules ModelPromptRule[] built-in rules Override the model-specific guidance rules.
outputBudget boolean | OutputBudgetConfig true Structure-aware output budgeting for PTC run_code (maxBytes: 24 KiB) and compact persisted logs for read-only sub-calls (dispatchLogMaxBytes: 1024 B; 0 disables). Set false to disable.

Example configuration

- id: dsh-ptc-kit
  name: 'file:///path/to/dsh-ptc-kit/lib/index.js'
  config:
    defaultMaxGrepMatches: 300
    outputBudget:
      maxBytes: 24576
      dispatchLogMaxBytes: 1024
    promptGuide: true
    modelGuidance: true
    modelRules:
      - id: my-team-rule
        model: '^gpt-'
        mode: ptc
        role: root
        text: '- Keep run_code batches focused and verify with tools.check before finishing.'

Prompt & Model Guidance

When enabled, dsh-ptc-kit contributes two lightweight sections right after the tool schemas:

  1. Workflow guide (promptGuide): Automatically detects whether the session is running in PTC (run_code) mode or standard tool-calling mode, and teaches the corresponding read/search/edit/verify discipline.
  2. Model-specific rules (modelGuidance): Ships concise default rules tuned for gpt-*, deepseek-*, gemini-*, and claude-* models. Each rule can filter by:
    • model — case-insensitive regex matched against the active model ID
    • provider — case-insensitive regex matched against the active provider ID
    • mode — ptc, standard, or any (default)
    • role — root, subagent, or any (default)
    • enabled — set false to disable a rule without removing it

Set promptGuide: false or modelGuidance: false if you prefer to manage all prompt instructions yourself.

Output Budgeting (PTC run_code)

Enabled by default (outputBudget: true), dsh-ptc-kit applies structure-aware output budgeting strictly to outer PTC run_code calls — leaving nested calls inside run_code and all standard-mode tools untouched (standard mode continues to rely on DSH's built-in spill policy):

  • Fair water-filling across inspect(...) & top-level fields (default 24 KiB): Splits multiple inspect(...) logs and top-level util.inspect / JSON objects & arrays so small fields stay 100% verbatim while oversized fields fill the remaining budget on clean line boundaries.
  • Large collections & mixed media: Huge arrays/objects keep complete head and tail items with an omission count, and image blocks are preserved untouched.
  • Lossless spill recovery: Full outputs are saved to DSH's spillStore (falling back to a local temp directory if unavailable), and every omission marker includes exact 1-based line numbers ready for read({ path, start, end }).
  • Compact read-only sub-call logs (default 1024 B): Trims persisted tool/ptc-dispatch log copies of read, grep, glob, and outline sub-calls to a 1 KiB preview without creating spill files — keeping the session database lean while leaving the full values returned to run_code and all error/write/check logs untouched (dispatchLogMaxBytes: 0 disables).

Supported Languages & Grammars

outline and symbol-scoped patch recognize 55 languages and formats by extension and filename (Makefile, justfile, Dockerfile*, CMakeLists.txt, .bashrc, etc.):

  • Systems & GPU: Rust, C, C++, Go, Zig, Swift, C#, Java, Kotlin, Scala, WGSL, GLSL
  • Web & Scripting: TypeScript, TSX, JavaScript, Python, Ruby, PHP, Lua, Dart, Bash/Shell, HTML, XML, CSS, SCSS, Vue, Svelte, Astro
  • Functional & Scientific: Haskell, OCaml/MLI, Elixir, Julia, R, Lean 4 (built-in scanner)
  • Build, Schema, Config & Docs: Make, Just, CMake, Dockerfile, SQL, Protobuf, GraphQL, HCL/Terraform, Nix, YAML, TOML, JSON, JSON5, INI, KDL, RON, Markdown (built-in scanner), Typst, LaTeX, BibTeX

Markdown and Lean 4 work with zero external dependencies. All other languages load Helix's compiled tree-sitter grammars dynamically in this order:

  1. $PTC_KIT_GRAMMARS (or $PTC_KIT_GRAMMARS/grammars)
  2. $HELIX_RUNTIME/grammars
  3. Standard Homebrew / /usr/local / /usr/share / /usr/lib Helix install paths
  4. ~/.config/helix/runtime/grammars and ~/.local/share/helix/runtime/grammars

If a file's language is unsupported or its grammar is missing, outline falls back cleanly instead of failing.

Development

pnpm run build       # compile Rust binary (release) + TypeScript bundle
pnpm run test:rust   # run Rust engine tests
pnpm run test        # run plugin & prompt tests
pnpm run check       # lint, typecheck, and format check

License

MIT

—/ 5

No ratings yet

Manifest verification required

Commit ab190baf7381

Community comments

No comments yet. Be the first to write one.

DSH HUB

A community index for DSH plugins. Not an official GitHub or DeepSeek AI product.

CommunityResourcesAPIAbout