Skip to content
deftaiPublic

About

Cross-model 1-token discovery, MCP/DSL schema auditing, and @deft/accretive prompt economics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@deft/monotok

Discover, classify, context-verify, cross-model intersect, and @deft/accretive-govern every 1-token word, symbol, delimiter, whitespace run, phrase, code construct, and statement on any LLM tokenizer.

Why?

Finding what compresses to 1 token works well for prompt, tool-schema, and DSL optimization — if you avoid two traps:

  1. The Context Boundary Trap: In BPE & SentencePiece, "1 token in isolation" does not guarantee "+1 token inside a prompt". Leading spaces, JSON quotes, and adjacent punctuation can merge a string (Δtok ≤ 0) or split it (Δtok ≥ 2). @deft/monotok verifies marginal token delta in context: $$\Delta\text{tok}(s \mid \text{prefix}, \text{suffix}) = \text{count}(\text{prefix} + s + \text{suffix}) - \text{count}(\text{prefix} + \text{suffix})$$
  2. The Per-Prompt Compression Trap: Saving raw input tokens with terse symbols or obscure words can hurt accuracy, trigger retries, bust prompt caches, or bloat output tokens (3–5× input cost). @deft/monotok wires every optimization directly into @deft/accretive (bet → accretive | dilutive → banked) with 95% CI non-inferiority guardrails on passRate & semanticFidelity and whole-task costPerTaskUsd scoring.

Live Frontier Benchmark Summary (@deft/accretive, LEDGER.md)

Paired A/B runs (n=12/model, n=36 pooled across claude-haiku-5-5, claude-fable-5-2, and claude-opus-5-5; see examples/07-live-claude-accretive-ab.ts, examples/08-live-frontier-architectural-ab.ts, and LEDGER.md):

Bet Verdict Key Live Result
staticPrefixCacheOrder ACCRETIVE -61.2% USD pooled (Holm p=0.000135), 73× cache reads (79→5,765 tok), 100%→100% passRate across Haiku 5.5 (-59.6%), Fable 5.2 (-61.5%), Opus 5.5 (-60.7%)
compactOneTokenOutputSchema ACCRETIVE -16.3% output tok (Holm p=0.0009) & -35.7% USD on Opus 5.5; -8.9% output tok (Holm p=0.0252) on Fable 5.2; -12.9% output tok & 91.7%→100% passRate on Haiku 5.5
oneTokenSynonyms DILUTIVE Saved only -0.08 o200k tok while regressing passRate (-8.3pp) and semanticFidelity (-4.2pp)
aggressiveSymbolShorthand DILUTIVE Saved 1.0 input tok but inflated outputTokens (+23.9%) and costPerTaskUsd (+4.5%)

Capabilities

  • Exact offline vocab engines (zero native deps):
    • Official OpenAI .tiktoken auto-loader (loadTiktokenEncoding('o200k_base' | 'cl100k_base' | 'p50k_base' | 'r50k_base')) with pinned SHA-256 verification and local disk caching, plus custom .tiktoken files (createTiktokenBackend) and a createJsTiktokenAdapter() wrapper
    • HuggingFace tokenizer.json (createHfTokenizerBackend + loadHfTokenizer('qwen2.5' | 'deepseek-v3' | 'llama3' | '<org/repo>')) — both BPE (ByteLevel Ġ/Ċ & Metaspace ▁) and Unigram/SentencePiece (Viterbi) with local disk caching
    • Verifies round-trip reachability (countTokens(text) === 1) to filter unreachable BPE merge artifacts
  • Exhaustive Cross-Family Lexicon (intersectVocabularies, createUniversalLexiconLookup):
    • Computes the exact intersection across full vocabularies (o200k_base ∩ cl100k_base ∩ Qwen-2.5 ∩ DeepSeek-V3) and exports an O(1) serializable lookup index (suggestCompactKey(), pickUniversal()).
  • 1-Token DSL, JSON Tool-Schema & MCP Server Scorer (auditDslSyntax, auditJsonSchema, auditMcpTools, renderMcpAuditMarkdown):
    • Scores keywords, operators, delimiters, JSON keys, enums, and full MCP tools/list definitions (both per-turn input definition tax and 3–5× output call-payload tax) across model families
  • Frontier Providers, Adaptive Group-Testing & CLI Harness Runners (src/providers.ts, src/harness.ts):
    • Catalog + probers for opus-5.5, gemini-4-neon, grok-build (xAI /v1/tokenize-text), fable-5.2, sol-6.2, plus probeOneTokensAdaptive() (~70% fewer closed-API calls)
    • createCliHarnessTaskRunner() plugs real coding harnesses (agy, pi.dev, opencode, claude-code, codex, grok-build) directly into @deft/accretive paired A/B evaluations
  • Closed-API & subscription black-box probers (createAnthropicCountBackend, createClaudeCodeCountBackend, createGeminiCountBackend, createCountApiBackend):
    • Automatic message-envelope overhead calibration (including zero-API-key Claude probing via local claude CLI subscription)
    • Concurrency limiter, throttling, batching, and persistent JSONL cache
  • Taxonomic 1-token classification (classifyTokenText):
    • word, leading_space_word, symbol, punctuation, whitespace, number, phrase, code_construct, statement, fragment, special
  • Contextual marginal-cost verification (measureContextualCost, verifyOneTokenInContext):
    • Tests standalone, after_space, after_newline, inline_sentence, json_key, code_call, markdown_header, delimiter, or custom contexts
  • Cross-model matrix (compareTokenizers, findUniversalOneTokens, renderMatrixMarkdown):
    • Finds universal 1-token lexicons across OpenAI, Claude, Gemini, Llama, Qwen, etc., and highlights model-specific token divergences
  • Prompt / Grammar Optimizer (analyzePrompt, optimizePrompt):
    • Finds multi-token hotspots and applies ONLY exact-verified token-reducing rewrites
  • Fluent SDK, Visualizers & Budget Planner (createMonoTok, visualizeTokens, renderHtmlTokenReport, comparePromptAcrossModels, planBudgetReduction):
    • mt.why("utilize") explains exact token splits, leading-space merges, and 1-token swaps
    • ANSI, Markdown, plain-bracket, and dark-mode interactive HTML token boundary visualizers
    • Dogfooded internal @deft/accretive engineering ledger in INTERNAL_LEDGER.md
  • First-class @deft/accretive Governance + Live LLM Runners (src/accretive.ts, src/eval.ts, action.yml, skill/SKILL.md):
    • Versioned MONOTOK_ECONOMICS scorecard (guardrailMode: 'non-inferiority')
    • DEFAULT_MONOTOK_BETS + DEFAULT_MONOTOK_PROFILES + optimizePromptWithAccretive()
    • evaluateOptimizationBet() + createOpenAiCompatibleTaskRunner() / createAnthropicTaskRunner() — fixed-n paired A/B runner with discarded warmup reps, cached-token USD cost accounting, pairedTTest, Holm–Bonferroni adjustPValues, checkFactorBalance, AccretiveStore, and LEDGER.md generation
    • CI gate (monotok check + reusable action.yml) and drop-in agent skill (skill/SKILL.md)

Quickstart

import {
  createTiktokenBackend,
  createHfTokenizerBackend,
  createAnthropicCountBackend,
  discoverOneTokens,
  compareTokenizers,
  analyzePrompt,
  optimizePromptWithAccretive,
  evaluateOptimizationBet,
  DEFAULT_OPTIMIZATION_RULES,
} from '@deft/monotok';

// 1. Exhaustive 1-token discovery on an exact vocab (.tiktoken or HF tokenizer.json)
const gpt = createTiktokenBackend({
  id: 'openai:o200k',
  model: 'gpt-4o',
  ranksPath: './o200k_base.tiktoken',
  pattern: 'o200k_base',
});
const report = await discoverOneTokens(gpt, {
  categories: ['word', 'symbol', 'phrase', 'code_construct', 'statement'],
  verifyContexts: ['standalone', 'after_space', 'inline_sentence', 'json_key'],
  limit: 100,
});

// 2. Cross-model 1-token intersection (open + closed APIs together!)
const claude = createAnthropicCountBackend({
  model: 'claude-sonnet-4-5',
  cachePath: '.monotok/claude-cache.jsonl',
});
const matrix = await compareTokenizers([gpt, claude], {
  candidates: ['return', '->', '=>', '---', 'TODO', 'JSON', 'utilize', 'use'],
  verifyContexts: ['standalone', 'inline_sentence'],
});
console.log(matrix.universalOneTokens);

// 3. Audit & optimize under @deft/accretive bet/profile control
const audit = await analyzePrompt(gpt, mySystemPrompt);
const opt = await optimizePromptWithAccretive(gpt, mySystemPrompt, {
  envOverride: process.env.MONOTOK_BETS,
});

Drop-In CLI (npx) & GitHub Actions CI (Zero-Install, Zero-LLM)

Install nothing — run straight from npm:

npx monotok scan . --changed-only --base-ref origin/main --fail-on high
npx monotok fix .                                  # dry-run preview (--write to apply)
npx monotok trace ~/.claude/projects               # offline cache-hit & USD churn audit
npx monotok why "allowMultipleOccurrences"         # explain exact token splits

Every monotok command except ledger uses strictly Node.js built-ins and runs directly on Node 22 with zero runtime dependencies, zero LLM API calls, and cached offline tokenizers (~70–450 ms per repo).

Option A — 4-line step in any existing CI workflow

- name: MonoTok token & prompt-cache scan
  uses: deftai/monotok@main
  with:
    scan-dir: .
    fail-on: high          # or omit for warn-only + Job Summary

Option B — Standalone reusable workflow (.github/workflows/monotok.yml)

name: MonoTok
on: [pull_request, merge_group, push]
jobs:
  monotok:
    uses: deftai/monotok/.github/workflows/monotok-ci.yml@main
    with:
      fail-on: high        # 'high' | 'medium' | 'low' | '' (warn-only)
      upload-sarif: false  # set true if GitHub Code Scanning is enabled

Option C — GitHub Enterprise Org Ruleset (zero files in target repos)

Attach deftai/monotok/.github/workflows/monotok-required.yml in Organization Settings → Rules → Rulesets → Require workflows to pass before merging. It scans only PR-changed files (changed-only: true with fetch-depth: 2), posts inline PR diff annotations (::warning/::error) + a Job Summary, and runs warn-only by default; set org or repo Actions variable MONOTOK_FAIL_ON=high to block new high-severity regressions (or MONOTOK_CHANGED_ONLY=false for full-repo scans).


CLI & Demo

# Run the zero-API-key end-to-end demo (discovery, context audit, cross-model matrix, Accretive A/B & profile selection)
npm run demo

# Run the live benchmark against real SHA-256-verified OpenAI o200k_base (200k) & cl100k_base (100k)
npm run demo:o200k

# Run the live 4-model multi-family audit (OpenAI o200k + cl100k, Qwen 2.5, DeepSeek-V3) on Verin DSL & JSON tool schemas
npm run demo:multifamily

# Compute the exact 4-family universal 1-token lexicon (o200k ∩ cl100k ∩ Qwen-2.5 ∩ DeepSeek-V3)
npm run demo:lexicon

# Run the frontier model × harness routing + adaptive group-testing benchmark
npm run demo:frontier

# Audit verbose vs 1-token compact MCP tool servers across all 4 live frontier tokenizers
npm run demo:mcp

# Run tests & typecheck
npm run typecheck
npm test

# CLI usage (after `npm run build`)
node dist/cli.js why "allowMultipleOccurrences" --encoding o200k_base
node dist/cli.js viz skill/SKILL.md --encoding o200k_base --format html --out .monotok/skill.html
node dist/cli.js compare skill/SKILL.md --encodings o200k_base,cl100k_base --hf-repos qwen2.5,deepseek-v3
node dist/cli.js budget skill/SKILL.md --target 650 --encoding o200k_base
node dist/cli.js discover --encoding o200k_base --ascii --categories symbol,statement --limit 25
node dist/cli.js matrix --encodings o200k_base,cl100k_base --hf-repos qwen2.5,deepseek-v3 --divergent --contexts
node dist/cli.js lexicon --encodings o200k_base,cl100k_base --hf-repos qwen2.5,deepseek-v3 --ascii --out universal-lexicon.json
node dist/cli.js check --prompt skill/SKILL.md --max-tokens 800 --encodings o200k_base,cl100k_base
node dist/cli.js check --mcp tools.json --max-mcp-tokens 900 --max-key-tokens 1 --allow-keys legacyKey --json
node dist/cli.js scan ../my-repo --encodings o200k_base,cl100k_base --hf-repos qwen2.5,deepseek-v3 --sarif --out monotok.sarif
node dist/cli.js scan . --changed-only --base-ref origin/main --fail-on high   # hunk-level PR diff gate
node dist/cli.js fix ../my-repo --encodings o200k_base                         # dry-run auto-fix preview (--write to apply)
node dist/cli.js trace ./sessions/agent.jsonl --model claude-sonnet-4-5        # offline cache-hit & USD waste report
node dist/cli.js ledger --internal --out INTERNAL_LEDGER.md

Per-Repo Config (.monotok.json) & Inline Ignores

Optional .monotok.json at repo root:

{
  "disableRules": ["large-prompt-literal"],
  "ignorePaths": ["legacy/"],
  "allowKeys": ["legacyCamelCaseKey"],
  "maxKeyTokens": 2
}

Inline suppressions: // monotok-ignore pretty-json-tool-response (same or previous line) or // monotok-ignore-file in the top 10 lines.

About

Cross-model 1-token discovery, MCP/DSL schema auditing, and @deft/accretive prompt economics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages