rea
morluto
Reverse engineer anything with agents, from app behavior down to native binaries.
PROJECT TOPICS
INSTALL REFERENCE
dsh plugin --profile web add github:SonettoGu14/dsh-tokeneconomizer
该命令指向仓库当前默认分支;尚无绑定当前 commit 的完整验证结果。
PROJECT README
Three small DeepSeek Harness components that make an agent spend fewer tokens on
the same work. They are native Cordis plugins, not a port of a script: each one
plugs into the harness's own typed events, so there is no shell wrapper, no
subprocess, no fail-open JSON dance, and no editing of another tool's settings
files.
The ideas come from microsoft/TokenEconomizer
(arXiv:2610.22732, Apache-2.0), which built the same three mechanisms
out-of-process for Claude Code, Codex and Copilot CLI. See NOTICE for the
attribution. This repository is an independent TypeScript implementation of
three of its mechanisms against a plugin API TokenEconomizer did not have.
From the npm registry:
dsh plugin --profile <profile> add dsh-te # all three
dsh plugin --profile <profile> add dsh-te-cost # or one at a time
That installs the package; it does not activate it. A package only takes effect
when the profile lists it as a bundle layer, so add the same name to
dsh.profile.bundles in ~/.dsh/profiles/<profile>/package.json — last, so its
rows apply after the shipped layers:
"dsh": {
"profile": {
"bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-headless", "dsh-te"]
}
}
Then confirm three rows appear:
dsh --profile <profile> --dump-config | grep "== dsh-te"
Set enabled: false in a row's config to keep a component installed but
dormant; that is how dsh-te-prune ships.
From a checkout, build once first: a link: install links sources and keeps
their node_modules, but it does not run the build for you, and the packages
resolve their entry points from lib/.
pnpm install
pnpm build # tsc -b -> packages/*/lib
dsh plugin --profile <profile> add link:<repo>/packages/bundle # or .../cost
Maintainer release: one command, no npm token anywhere.
pnpm release:dry # checks only: clean tree, tag free, verify, prints the plan
pnpm release patch # bump all five, commit, tag v<version>, push; CI publishes
The tag is the release. .github/workflows/publish.yml re-runs pnpm verify,
refuses a tag that disagrees with package.json, publishes all five packages
topologically through OIDC Trusted Publishing, and creates the GitHub Release.
Nothing to keep on a laptop: a lost token cannot publish, and a version that
already exists fails rather than being overwritten. pnpm publish:local is the
fallback when CI is unavailable and does need a token in ~/.npmrc.
prepublishOnly builds each package, files ships lib/ and src/, and pnpm
rewrites the intra-workspace workspace:* dependencies to the published
versions. The components have no dependency on each other: cost, facts and
prune depend only on dsh-te-core, and the one cross-component
interaction (facts reporting its own injected tokens to cost) is a soft,
optional lookup — lose the ledger and facts still work.
dsh-te-cost — cache-weighted accountingRaw token totals mislead, because most input tokens are cache reads billed at a
fraction of a fresh input token. This component folds the harness's own four
disjoint provider buckets (uncachedInput, cacheRead, cacheWrite, output)
into a single number that is unit-free: equivalent fresh-input tokens, using
the provider's real price ratios.
session/event (request/header, assistant/message), never touches
the prompt or the tool surface.$DSH_HOME/dsh-tokeneconomizer/repos/<key>/cost.json.recordOverhead(session, label, tokens)
puts injected text on the same books, so a saving cannot be manufactured by
moving cost into the plugin./te-cost [session|repo] prints the breakdown.Unknown models fall back to a default weight table, recorded as
weightsSource: 'default' rather than failing: a plugin must never be able to
break a session over a price table.
dsh-te-facts — repository facts, learned and retiredWatches shell calls; when a session ends, a form that failed here plus a
different form of the same intent that then worked is one fact (an
env_value repair is the second family). Facts are scoped to one repository
(git origin remote, else the working directory).
A fact is not shown because it was observed. It is promoted only after three separate sessions confirm it, and injected only while the waste it prevents is still happening in at least 40% of the sessions that exercised it, measured over at least four such sessions. When the model stops repeating the mistake, the fact stops being injected — and a later session that contradicts it retires it.
/te-facts lists what it knows, with state, score and firing rate.Ported constants: K_PROMOTE=3, GAMMA=0.8, LAMBDA=5.0, FIRE_GATE=0.40,
FIRE_MIN_N=4.
dsh-te-prune — stop sending tools nobody callsEvery tool definition rides along on every request. This component counts, per
repository, how many sessions a tool has gone unused; after idleSessions
(default 5) it hides the tool with the registry's own scoped restriction, which
is lifted when the session ends.
maxHidden bounds the damage to 8 tools per session./te-prune shows idle counters; /te-prune restore gives tools back and
records them as permanently kept.Each component takes a small Config; the profile's patch row is the place to
set it:
- id: te-facts
name: 'dsh-te-facts'
config:
enabled: true
maxFacts: 4
maxChars: 600
| Component | Setting | Default | Meaning |
|---|---|---|---|
| cost | enabled, persist |
true, true |
fold usage, write the repo ledger |
| facts | enabled |
true |
watch, learn, inject |
| facts | maxFacts, maxChars |
4, 600 |
injection budget |
| prune | enabled |
false |
hiding is opt-in |
| prune | idleSessions, maxHidden |
5, 8 |
when to hide, how many |
| prune | protected |
[] |
extra names never to hide |
State lives in $DSH_HOME/dsh-tokeneconomizer/ (default ~/.dsh/), partitioned
by repository key. Writes are atomic (tmp + rename), reads never throw.
pnpm build # tsc -b over the four source packages
pnpm typecheck # tsc -p tsconfig.test.json, includes all tests
pnpm test # vitest: 113 unit tests
pnpm test:integration # vitest: 8 integration tests against real DSH packages
pnpm verify # all four, in that order
Three levels, from cheapest to most convincing:
Unit tests mount the components in a bare Cordis Context with stubbed
services: cost is fed synthetic session events, facts and prune are driven
through four to six simulated sessions to prove promotion, the firing gate,
two-strike contradiction, idle counting, and that restrictions are lifted again.
Integration tests (test/integration/) are the interesting ones: they load
the real @deepseek-ai/dsh-agent-loop, dsh-llm, dsh-tools,
dsh-session and dsh-tool-executor-native packages, register a scripted
LlmAdapter in place of a provider, and run a genuine agent turn — no network,
no credentials, no model. What they assert is exactly what the components claim:
100 uncached, 50
cache-read, 5 cache-write, 20 output) land in cost.json unchanged and
fold to equivalent: 211.25; two sessions in one repository accumulate.dsh-te-facts message in the
first model request (not merely in state), and disappears when the fire gate
is not met; a real failing python -m pytest followed by a working pytest
in the same session teaches the fact end to end.toolNames while the
registry still knows it (hidden, not unregistered); a tool below the threshold
survives; write is never hidden.These tests caught a real composition requirement: DSH 0.2.2 refuses to run an agent unless a tool executor is mounted, which a bare event-level test never notices.
Manual, real model — a throwaway profile built from the shipped headless
template with the bundle installed answered a one-word task and exited cleanly:
$ dsh --profile te-headless "Reply with exactly: ok"
ok
That run produced $DSH_HOME/dsh-tokeneconomizer/repos/<key>/cost.json with
equivalent: 9189 for a three-token reply — the fixed prompt and tool
definitions, not the answer, are what a session costs. The same repo after a
second session read:
{"equivalent": 9471.76, "buckets": {"uncachedInput": 9266, "cacheRead": 9088,
"cacheWrite": 0, "output": 6}, "sessions": 2}
18,360 raw tokens against 9,472 equivalent ones: that gap is the whole reason the
ledger folds buckets instead of summing totalTokens. A profile with only
dsh-te-cost installed boots the same way, so the components really are
independent.
What no test can prove is the harness-level effect on token spend over many sessions; that needs the plugins left on in real work.
dsh-repeat-tool-reminder. Porting an unvalidated heuristic that can spend
model calls to interrupt a turn is not a good trade here.dsh-compaction*
and @linxin666/dsh-usage; duplicating them would only add overhead.boundary,
arg_repair, absent_tool, empty_probe). They are where TokenEconomizer's
extra model calls live; the mechanical two-family core is the cheap 80%.TokenEconomizer's headline numbers (18–31% cheaper on SWE-Bench, 16–21% on
Web-Bench) exist in that repository only as constants in
docs/assets/results_overview.py, covering the paper's Table 1; the repository
ships no run results and says so in that file. They are a reason to try these
mechanisms, not evidence that this port inherits them. What is verifiable here is
narrow and stated above: the arithmetic is exact, the lifecycle gates behave as
specified, and nothing the components do can alter the agent's transcript except
one bounded fact block at session start.
packages/core/ pure logic: pricing weights, bucket folding, fact lifecycle,
shell-transcript extraction, repo identity, atomic storage.
No Cordis dependency; unit-tested in isolation.
packages/cost/ ledger service + /te-cost
packages/facts/ fact watcher + pre-step injection + /te-facts
packages/prune/ idle counters + scoped tool restrictions + /te-prune
packages/bundle/ the install-all patch
test/integration/ real-composition harness (real dsh packages, scripted model)
docs/PLAN.md roadmap, priorities and the measurement protocol
The mechanisms implemented here come from this paper; cite it if you use them:
@misc{li2026tokeneconomizer,
title = {{TokenEconomizer}: Experience-Driven Black-Box Cost Control for Coding Agents},
author = {Li, Aaron J. and Xu, Weijia and Singh, Chandan and Chen, Zixiao and
Inala, Jeevana Priya and Siska, Charlotte and Tamersoy, Acar and Yu, Bin and
Stoica, Ion and Galley, Michel and Gao, Jianfeng},
year = {2026},
eprint = {2610.22732},
archivePrefix = {arXiv},
primaryClass = {cs.CL},
url = {https://arxiv.org/abs/2610.22732}
}
This project is licensed under the Apache License, Version 2.0; see
LICENSE. It is an independent implementation of mechanisms from
microsoft/TokenEconomizer
(Apache-2.0, Copyright (c) Microsoft Corporation and contributors); no source
file was copied verbatim. NOTICE records the attribution and which
parts are derived.
CLASSIFICATION EVIDENCE
系统优先读取 GitHub Topics,再与站内分类词典和词根规则比对。当前命中: deepseek。