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 inrun_codeinstead of nesting shell scripts insidetools.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, andoutlinecarries a short content hash (line#hash).patchverifies every hash and symbol across all target files atomically before writing a single byte. - Run checks in parallel:
checkis concurrency-safe, so multiple build, test, lint, and typecheck commands run side by side underPromise.alland return compact pass/fail summaries with deduplicatedfile:linelocations. - 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 exactread({ 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:
- Turn explosion & context bloat — bouncing across 8–10 sequential turns (
grepdumps 60 raw hits -> 3 full-filereads -> 3 single-fileeditcalls with whitespace/drift retries -> serialbashtypecheck + test dumps -> anotherreadto inspect the failing line). - Fragile
bash+ heredoc workarounds inrun_code— trying to avoid 10 turns by stuffingrg,sed,python3 -c, orcat << 'EOF'scripts intotools.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:outlineavoids full-file reads, a singlepatchcall updates multiple files atomically by symbol orline#hash, and multiplecheckcalls 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
writetool stays enabled for creating new files;dsh-ptc-kitonly 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
outlineand symbol-scopedpatch; 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:
- 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. - Model-specific rules (
modelGuidance): Ships concise default rules tuned forgpt-*,deepseek-*,gemini-*, andclaude-*models. Each rule can filter by:model— case-insensitive regex matched against the active model IDprovider— case-insensitive regex matched against the active provider IDmode—ptc,standard, orany(default)role—root,subagent, orany(default)enabled— setfalseto 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 multipleinspect(...)logs and top-levelutil.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
imageblocks 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 forread({ path, start, end }). - Compact read-only sub-call logs (default 1024 B): Trims persisted
tool/ptc-dispatchlog copies ofread,grep,glob, andoutlinesub-calls to a 1 KiB preview without creating spill files — keeping the session database lean while leaving the full values returned torun_codeand all error/write/check logs untouched (dispatchLogMaxBytes: 0disables).
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:
$PTC_KIT_GRAMMARS(or$PTC_KIT_GRAMMARS/grammars)$HELIX_RUNTIME/grammars- Standard Homebrew /
/usr/local//usr/share//usr/libHelix install paths ~/.config/helix/runtime/grammarsand~/.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
还没有评论,来写第一条。