@sliday/tamp 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,14 +60,14 @@ curl -fsSL https://tamp.dev/setup.sh | bash
60
60
  # Option B: Manual
61
61
  npx @sliday/tamp
62
62
  export ANTHROPIC_BASE_URL=http://localhost:7778 # Claude Code
63
- export OPENAI_API_BASE=http://localhost:7778/v1 # Aider, Cursor, Cline
63
+ export OPENAI_API_BASE=http://localhost:7778/v1 # Aider, Cline
64
64
  ```
65
65
 
66
66
  Use your agent as normal — Tamp compresses silently.
67
67
 
68
68
  ### Codex CLI
69
69
 
70
- Codex CLI reads its upstream from `~/.codex/config.toml`, not `OPENAI_API_BASE`. Add a custom provider:
70
+ Codex CLI reads its upstream from `~/.codex/config.toml`, not an env var. Add a custom provider:
71
71
 
72
72
  ```toml
73
73
  model_provider = "tamp"
@@ -81,6 +81,14 @@ wire_api = "responses"
81
81
 
82
82
  Then `export OPENAI_API_KEY=sk-...` and run `codex` or `codex exec "..."` as usual. Tamp routes `/v1/responses` through the `openai-responses` adapter and compresses every `function_call_output` block.
83
83
 
84
+ **ChatGPT Plus / Pro subscription.** If you sign in with `codex login` instead of using an API key, add this line to `~/.codex/config.toml`:
85
+
86
+ ```toml
87
+ openai_base_url = "http://localhost:7778/v1"
88
+ ```
89
+
90
+ Tamp detects OAuth bearer tokens and routes them to `chatgpt.com/backend-api/codex` automatically, so your ChatGPT Plus/Pro subscription keeps paying for inference while Tamp compresses every tool result in flight.
91
+
84
92
  ### Cursor
85
93
 
86
94
  1. Start Tamp: `npx @sliday/tamp -y`
@@ -90,7 +98,24 @@ Then `export OPENAI_API_KEY=sk-...` and run `codex` or `codex exec "..."` as usu
90
98
  5. Click **Verify**, then enable any OpenAI-family model (`gpt-4o`, `gpt-5-codex`, etc.)
91
99
  6. Use Cursor as normal — Tamp compresses every tool call
92
100
 
93
- > Cursor's bundled `cursor-*` and `claude-*` models go through Cursor's own servers and bypass the override. Pick an OpenAI model to route through Tamp.
101
+ > **Cursor Pro subscription caveat.** Cursor's bundled `cursor-*`, `composer-*`, `claude-*`, and `gpt-*` models are routed through Cursor's own servers (`api2.cursor.sh`) regardless of the "Override OpenAI Base URL" setting — Tamp cannot intercept them. Compression only applies when you (a) bring your own OpenAI key and (b) select a model Cursor treats as external (e.g. an unbundled `gpt-4o` with BYOK, or a custom model name via a public tunnel).
102
+
103
+ ### opencode
104
+
105
+ opencode **silently ignores** `OPENAI_API_BASE` / `OPENAI_BASE_URL`. Configure base URLs per provider in `~/.config/opencode/opencode.json`:
106
+
107
+ ```json
108
+ {
109
+ "provider": {
110
+ "anthropic": { "options": { "baseURL": "http://localhost:7778" } },
111
+ "openai": { "options": { "baseURL": "http://localhost:7778/v1" } },
112
+ "openrouter": { "options": { "baseURL": "http://localhost:7778/v1/openrouter" } },
113
+ "opencode": { "options": { "baseURL": "http://localhost:7778/v1/zen" } }
114
+ }
115
+ }
116
+ ```
117
+
118
+ Restart opencode. Tamp's adapter table routes each provider to the correct upstream.
94
119
 
95
120
  ### VS Code
96
121
 
@@ -134,15 +159,41 @@ Copilot does not expose a base URL setting and routes everything through GitHub'
134
159
 
135
160
  Run `tamp init` to create `~/.config/tamp/config`. All variables work via env or config file.
136
161
 
137
- ### Compression Presets (New!)
162
+ ### Compression levels
163
+
164
+ One knob, nine stops. The 1–9 ladder is prefix-preserving (each level adds stages on top of the previous), so you can dial compression up or down without reasoning about individual stages.
138
165
 
139
- Simplify configuration with three intensity levels:
166
+ | Level | Stages (cumulative) | Lossy | Expected savings | Preset alias |
167
+ |---|---|---|---|---|
168
+ | 1 | minify | — | ~15% | — |
169
+ | 2 | + whitespace, strip-lines | — | ~25% | — |
170
+ | 3 | + cmd-strip | — | ~35% | — |
171
+ | 4 | + toon, dedup, diff | — | ~45% | `conservative` |
172
+ | 5 | + llmlingua, read-diff, prune | yes | ~53% | **`balanced` (default)** |
173
+ | 6 | + strip-comments | yes | ~58% | — |
174
+ | 7 | + textpress, br-cache | yes | ~62% | — |
175
+ | 8 | + disclosure, bm25-trim | yes | ~67% | `aggressive` |
176
+ | 9 | + graph, foundation-models | yes | ~72% | `max` |
140
177
 
141
- | Preset | Savings | Description |
142
- |--------|---------|-------------|
143
- | `conservative` | 45-50% | Lossless only (no neural) |
144
- | `balanced` (default) | 52-58% | Recommended, includes LLMLingua |
145
- | `aggressive` | 60-68% | Maximum, lossy stages enabled |
178
+ Three interchangeable ways to pick a level:
179
+
180
+ ```bash
181
+ tamp --level 7 # CLI flag
182
+ TAMP_LEVEL=7 tamp # Environment variable
183
+ tamp settings # Interactive slider (+ advanced stage picker)
184
+ ```
185
+
186
+ Precedence: `--level` > `TAMP_LEVEL` > config file > preset alias > default (`balanced` / L5). Setting `TAMP_STAGES` explicitly still wins over any level — the banner will show the full stage list instead of the Level line.
187
+
188
+ ### Compression Presets
189
+
190
+ The named presets are aliases of levels and still work unchanged:
191
+
192
+ | Preset | Level | Savings | Description |
193
+ |--------|-------|---------|-------------|
194
+ | `conservative` | L4 | 45-50% | Lossless only (no neural) |
195
+ | `balanced` (default) | L5 | 52-58% | Recommended, includes LLMLingua |
196
+ | `aggressive` | L8 | 60-68% | Maximum, lossy stages enabled |
146
197
 
147
198
  ```bash
148
199
  # Use a preset
@@ -186,14 +237,14 @@ Supported on all providers: Anthropic, OpenAI Chat, OpenAI Responses (Codex), Ge
186
237
  **Recommended setups:**
187
238
 
188
239
  ```bash
189
- # Default (balanced preset)
240
+ # Default (balanced preset = L5)
190
241
  npx @sliday/tamp
191
242
 
192
243
  # Conservative (no Python, lossless only)
193
- TAMP_COMPRESSION_PRESET=conservative npx @sliday/tamp -y
244
+ TAMP_LEVEL=4 npx @sliday/tamp -y
194
245
 
195
246
  # Aggressive (maximum compression)
196
- TAMP_COMPRESSION_PRESET=aggressive npx @sliday/tamp -y
247
+ TAMP_LEVEL=8 npx @sliday/tamp -y
197
248
  ```
198
249
 
199
250
  ## CLI Tools
@@ -252,6 +303,21 @@ Claude Code sends full conversation history on every API call. Tool results accu
252
303
 
253
304
  **Combined impact:** With new Caveman-integrated features, Tamp achieves 60-70% total token savings (input + output) in balanced mode.
254
305
 
306
+ ### Did v0.8 headline % improve over v0.5?
307
+
308
+ Short answer: **not much on the micro-benchmark, a lot on real sessions.**
309
+
310
+ On the short single-request fixtures in `bench/`, the headline percentage barely moves — v0.5 baseline lands at 45.1%, L5 (balanced) at 45.3%, L9 (max) at 45.4%. The fixtures are too small to exercise the new stages: they don't contain re-reads, don't cross the disclosure threshold (>32 KB tool_result bodies), don't include the noisy CLI streams `cmd-strip` targets, and fit entirely inside a single request so cross-request session dedup (`graph`) is a no-op.
311
+
312
+ Where v0.8 actually pays off is **session-scoped work**, which is what coding agents do all day:
313
+
314
+ - `read-diff` (L5) and `graph` (L9) eliminate the cost of re-reading the same file — a dominant pattern in multi-turn debugging sessions.
315
+ - `disclosure` (L8) keeps `tool_result` payloads over 32 KB from burning input tokens a second time when the agent references them later.
316
+ - `cmd-strip` (L3) removes per-command stdout noise (spinners, progress bars from `npm`, `pip`, `cargo`, `docker`) that the synthetic fixtures don't contain.
317
+ - `br-cache` (L7) and `bm25-trim` (L8) shave long-tail content the fixtures don't exercise.
318
+
319
+ The real win in v0.8 is **the level knob itself** — a zip-like 1–9 dial that lets you trade compression aggressiveness for risk without memorizing stage names. To reproduce the numbers above, run `node bench/runner.js --sweep` (set `OPENROUTER_API_KEY` for the live A/B pass).
320
+
255
321
  ## Development
256
322
 
257
323
  ```bash
package/bin/tamp.js CHANGED
@@ -5,8 +5,8 @@ import { spawn, execFileSync } from 'node:child_process'
5
5
  import { fileURLToPath } from 'node:url'
6
6
  import { dirname, join } from 'node:path'
7
7
  import { homedir } from 'node:os'
8
- import { DEFAULT_STAGES, EXTRA_STAGES, STAGE_DESCRIPTIONS, STAGE_HINTS, VERSION, isLossy } from '../metadata.js'
9
- import { CONFIG_PATH, CONFIG_TEMPLATE } from '../config.js'
8
+ import { DEFAULT_STAGES, EXTRA_STAGES, STAGE_DESCRIPTIONS, STAGE_HINTS, VERSION, isLossy, DEFAULT_LEVEL } from '../metadata.js'
9
+ import { CONFIG_PATH, CONFIG_TEMPLATE, loadConfig } from '../config.js'
10
10
  import {
11
11
  checkPort,
12
12
  diagnoseBindConflict,
@@ -79,9 +79,83 @@ export async function startSidecar() {
79
79
  return null
80
80
  }
81
81
 
82
+ // Write (or update) a single scalar field in the config file. Preserves
83
+ // unrelated lines verbatim. Creates the file (seeded from CONFIG_TEMPLATE)
84
+ // if missing. Shared by `init` and `settings` — the single writer.
85
+ function writeConfigField(field, value) {
86
+ const dir = dirname(CONFIG_PATH)
87
+ mkdirSync(dir, { recursive: true })
88
+ const stringified = String(value)
89
+ let body
90
+ if (existsSync(CONFIG_PATH)) {
91
+ body = readFileSync(CONFIG_PATH, 'utf8')
92
+ } else {
93
+ body = CONFIG_TEMPLATE
94
+ }
95
+ const lines = body.split('\n')
96
+ const activeRe = new RegExp(`^\\s*${field}\\s*=`)
97
+ const commentedRe = new RegExp(`^\\s*#\\s*${field}\\s*=`)
98
+ let replaced = false
99
+ for (let i = 0; i < lines.length; i++) {
100
+ if (activeRe.test(lines[i])) {
101
+ lines[i] = `${field}=${stringified}`
102
+ replaced = true
103
+ break
104
+ }
105
+ }
106
+ if (!replaced) {
107
+ for (let i = 0; i < lines.length; i++) {
108
+ if (commentedRe.test(lines[i])) {
109
+ lines[i] = `${field}=${stringified}`
110
+ replaced = true
111
+ break
112
+ }
113
+ }
114
+ }
115
+ if (!replaced) {
116
+ if (lines.length && lines[lines.length - 1] !== '') lines.push('')
117
+ lines.push(`${field}=${stringified}`)
118
+ }
119
+ writeFileSync(CONFIG_PATH, lines.join('\n'))
120
+ }
121
+
82
122
  // --- Subcommands ---
83
123
  const subcommand = process.argv[2]
84
124
 
125
+ // --- Global --level flag parsing ---
126
+ // Supports '--level N', '--level=N'. Accepts integers 1..9 or alias strings
127
+ // (conservative, balanced, aggressive, max). Invalid values: print a friendly
128
+ // error and exit(2). Threaded into loadConfig via options.levelOverride so the
129
+ // precedence rules (stages-env > level-flag > level-env > preset-env > file > default)
130
+ // live entirely in config.js.
131
+ function parseLevelArgv(argv) {
132
+ const aliases = new Set(['conservative', 'balanced', 'aggressive', 'max'])
133
+ let raw = null
134
+ for (let i = 0; i < argv.length; i++) {
135
+ const a = argv[i]
136
+ if (a === '--level') { raw = argv[i + 1]; break }
137
+ if (a.startsWith('--level=')) { raw = a.slice('--level='.length); break }
138
+ }
139
+ if (raw === null || raw === undefined) return null
140
+ if (raw === '') {
141
+ console.error(`[tamp] --level requires a value (1..9 or one of: conservative, balanced, aggressive, max)`)
142
+ process.exit(2)
143
+ }
144
+ if (/^-?\d+$/.test(raw)) {
145
+ const n = parseInt(raw, 10)
146
+ if (n < 1 || n > 9) {
147
+ console.error(`[tamp] --level must be 1..9 (got ${raw})`)
148
+ process.exit(2)
149
+ }
150
+ return n
151
+ }
152
+ if (aliases.has(raw)) return raw
153
+ console.error(`[tamp] invalid --level=${raw} — expected 1..9 or one of: conservative, balanced, aggressive, max`)
154
+ process.exit(2)
155
+ }
156
+
157
+ const argvLevel = parseLevelArgv(process.argv.slice(2))
158
+
85
159
  if (subcommand === 'init') {
86
160
  const dir = dirname(CONFIG_PATH)
87
161
  if (existsSync(CONFIG_PATH)) {
@@ -97,6 +171,55 @@ if (subcommand === 'init') {
97
171
  process.exit(0)
98
172
  }
99
173
 
174
+ if (subcommand === 'settings' || subcommand === 'config') {
175
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
176
+ console.log(`Usage: tamp settings\n`)
177
+ console.log('Interactive editor for compression level (1..9) and stages.')
178
+ console.log('Writes to: ' + CONFIG_PATH)
179
+ process.exit(0)
180
+ }
181
+
182
+ const current = loadConfig()
183
+ const envLevel = Number.isInteger(current.level) ? current.level : DEFAULT_LEVEL
184
+
185
+ if (!process.stdin.isTTY) {
186
+ console.error('[tamp] settings requires an interactive terminal (TTY). Edit ' + CONFIG_PATH + ' directly.')
187
+ process.exit(1)
188
+ }
189
+
190
+ const { render } = await import('ink')
191
+ const React = await import('react')
192
+ const { LevelPicker } = await import('./ui/LevelPicker.js')
193
+ const h = React.createElement
194
+
195
+ let instance = null
196
+ const onSelect = (payload) => {
197
+ try {
198
+ if (payload.kind === 'level') {
199
+ writeConfigField('level', payload.level)
200
+ if (instance) instance.unmount()
201
+ console.log(`Saved level=${payload.level} to ${CONFIG_PATH}`)
202
+ process.exit(0)
203
+ } else if (payload.kind === 'stages') {
204
+ writeConfigField('TAMP_STAGES', payload.stages.join(','))
205
+ if (instance) instance.unmount()
206
+ console.log(`Saved TAMP_STAGES=${payload.stages.join(',')} to ${CONFIG_PATH}`)
207
+ process.exit(0)
208
+ }
209
+ } catch (err) {
210
+ if (instance) instance.unmount()
211
+ console.error(`[tamp] failed to write config: ${err.message}`)
212
+ process.exit(1)
213
+ }
214
+ }
215
+ const onCancel = () => {
216
+ if (instance) instance.unmount()
217
+ process.exit(0)
218
+ }
219
+
220
+ instance = render(h(LevelPicker, { version: VERSION, envLevel, onSelect, onCancel }))
221
+ }
222
+
100
223
  if (subcommand === 'install-service') {
101
224
  if (process.platform !== 'linux') {
102
225
  console.error('Service installation requires Linux (systemd).')
@@ -245,7 +368,7 @@ if (subcommand === 'stop') {
245
368
  process.exit(0)
246
369
  }
247
370
 
248
- if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
371
+ if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h' || process.argv.includes('--help') || process.argv.includes('-h')) {
249
372
  console.log(`Tamp v${VERSION} — Token compression proxy for coding agents\n`)
250
373
  console.log('Usage: tamp [command] [options]\n')
251
374
  console.log('Commands:')
@@ -255,10 +378,14 @@ if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
255
378
  console.log(' stop Stop a running Tamp on TAMP_PORT (default 7778)')
256
379
  console.log(' compress-config Compress CLAUDE.md or config files (caveman mode)')
257
380
  console.log(' init Create config file (~/.config/tamp/config)')
381
+ console.log(' settings Edit compression level and stages')
258
382
  console.log(' status Check if proxy is running')
259
383
  console.log(' install-service Install systemd user service (Linux)')
260
384
  console.log(' uninstall-service Remove systemd service')
261
385
  console.log(' help Show this help')
386
+ console.log('')
387
+ console.log('Options:')
388
+ console.log(' --level N Compression level 1..9 (or: conservative, balanced, aggressive, max)')
262
389
  console.log(`\nConfig: ${CONFIG_PATH}`)
263
390
  process.exit(0)
264
391
  }
@@ -303,8 +430,23 @@ if (skipPrompt) {
303
430
  // --- Non-interactive mode (plain text, no Ink) ---
304
431
  const { ANSI: c } = await import('./ui/theme.js')
305
432
 
306
- let selectedStages = envStages ? [...envStages] : [...DEFAULT_STAGES]
307
- process.env.TAMP_STAGES = selectedStages.join(',')
433
+ // When --level is given (and TAMP_STAGES is unset), resolve stages via
434
+ // loadConfig so the level ladder drives the selection. Otherwise keep legacy
435
+ // behavior (envStages-derived TAMP_STAGES auto-echo).
436
+ let selectedStages
437
+ if (envStages) {
438
+ selectedStages = [...envStages]
439
+ process.env.TAMP_STAGES = selectedStages.join(',')
440
+ } else if (argvLevel !== null) {
441
+ const { loadConfig } = await import('../config.js')
442
+ const probe = loadConfig(process.env, { levelOverride: argvLevel })
443
+ selectedStages = [...probe.stages]
444
+ // Do NOT set TAMP_STAGES — that would clobber level-flag source tracking
445
+ // when the full createProxy call runs below.
446
+ } else {
447
+ selectedStages = [...DEFAULT_STAGES]
448
+ process.env.TAMP_STAGES = selectedStages.join(',')
449
+ }
308
450
 
309
451
  if (selectedStages.includes('llmlingua')) {
310
452
  const sidecarUrl = await startSidecar()
@@ -320,7 +462,7 @@ if (skipPrompt) {
320
462
  }
321
463
  }
322
464
 
323
- const { config, server } = createProxy()
465
+ const { config, server } = createProxy({}, argvLevel !== null ? { levelOverride: argvLevel } : {})
324
466
 
325
467
  await ensurePortFree(config.port)
326
468
 
@@ -402,6 +544,7 @@ if (skipPrompt) {
402
544
  render(h(App, {
403
545
  version: VERSION,
404
546
  envStages,
547
+ argvLevel,
405
548
  startSidecar,
406
549
  createProxy,
407
550
  getSidecarProc,
package/bin/ui/App.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import React, { useState, useEffect, useCallback, useRef } from 'react'
2
2
  import { Box, Text, useApp } from 'ink'
3
- import { StagePicker } from './StagePicker.js'
3
+ import { LevelPicker } from './LevelPicker.js'
4
4
  import { SidecarLoader } from './SidecarLoader.js'
5
5
  import { Dashboard } from './Dashboard.js'
6
6
  import { installShutdown, writePidFile, diagnoseBindConflict } from '../lifecycle.js'
7
7
 
8
8
  const h = React.createElement
9
9
 
10
- export function App({ version, envStages, startSidecar, createProxy, getSidecarProc, ensurePortFree }) {
10
+ export function App({ version, envStages, argvLevel, startSidecar, createProxy, getSidecarProc, ensurePortFree }) {
11
11
  const { exit } = useApp()
12
12
  const [phase, setPhase] = useState('pick')
13
13
  const [stages, setStages] = useState(null)
@@ -70,6 +70,14 @@ export function App({ version, envStages, startSidecar, createProxy, getSidecarP
70
70
  }
71
71
  }, [startProxy])
72
72
 
73
+ const onPickerSubmit = useCallback((payload) => {
74
+ // payload: { kind: 'level', level, stages } | { kind: 'stages', stages }
75
+ if (payload && payload.kind === 'level' && Number.isInteger(payload.level)) {
76
+ process.env.TAMP_LEVEL = String(payload.level)
77
+ }
78
+ onStagesSelected(payload.stages)
79
+ }, [onStagesSelected])
80
+
73
81
  // Use stagesRef to avoid stale closure — SidecarLoader's useEffect
74
82
  // captures onReady/onFail on first render only
75
83
  const onSidecarReady = useCallback((url) => {
@@ -85,7 +93,7 @@ export function App({ version, envStages, startSidecar, createProxy, getSidecarP
85
93
  }, [startProxy])
86
94
 
87
95
  if (phase === 'pick') {
88
- return h(StagePicker, { version, envStages, onSelect: onStagesSelected })
96
+ return h(LevelPicker, { version, envLevel: argvLevel, envStages, onSelect: onPickerSubmit })
89
97
  }
90
98
 
91
99
  if (phase === 'loading') {
package/bin/ui/Banner.js CHANGED
@@ -5,13 +5,17 @@ import { ALL_STAGES, DEFAULT_STAGES, EXTRA_STAGES, STAGE_HINTS, isLossy } from '
5
5
 
6
6
  const h = React.createElement
7
7
 
8
- export function Banner({ version, port, stages, llmLinguaUrl, outputMode }) {
8
+ export function Banner({ version, port, stages, llmLinguaUrl, outputMode, level }) {
9
9
  const url = `http://localhost:${port}`
10
10
  const active = new Set(stages)
11
11
  const defaultActive = DEFAULT_STAGES.filter(s => active.has(s))
12
12
  const extraActive = EXTRA_STAGES.filter(s => active.has(s))
13
13
  const disabled = ALL_STAGES.filter(s => !active.has(s))
14
14
  const showOutput = outputMode && outputMode !== 'off'
15
+ const hasLevel = level != null
16
+ const stagesHeader = hasLevel
17
+ ? h(Text, { bold: true }, `Stages `, h(Text, { dimColor: true }, `(${stages.length} active \u2192 expand with TAMP_STAGES)`))
18
+ : h(Text, { bold: true }, `Stages `, h(Text, { dimColor: true }, `(${stages.length} of ${ALL_STAGES.length} active)`))
15
19
 
16
20
  return h(Box, { flexDirection: 'column', paddingX: 1 },
17
21
  h(Box, { gap: 2 },
@@ -20,6 +24,12 @@ export function Banner({ version, port, stages, llmLinguaUrl, outputMode }) {
20
24
  h(Badge, { color: 'green' }, 'READY'),
21
25
  h(Text, { color: 'green' }, url),
22
26
  ),
27
+ hasLevel ? h(Text, null, '') : null,
28
+ hasLevel ? h(Text, null,
29
+ h(Text, { bold: true }, 'Level '),
30
+ h(Text, { color: 'yellow' }, String(level)),
31
+ h(Text, { dimColor: true }, ` (${stages.length} stages \u2014 tamp settings to change)`),
32
+ ) : null,
23
33
  h(Text, null, ''),
24
34
  h(Text, { bold: true }, 'Setup'),
25
35
  h(Box, { paddingLeft: 2, flexDirection: 'column' },
@@ -40,8 +50,8 @@ export function Banner({ version, port, stages, llmLinguaUrl, outputMode }) {
40
50
  h(Text, { dimColor: true }, ' (caveman, task-aware)')
41
51
  ) : null,
42
52
  showOutput ? h(Text, null, '') : null,
43
- h(Text, { bold: true }, `Stages `, h(Text, { dimColor: true }, `(${stages.length} of ${ALL_STAGES.length} active)`)),
44
- h(Box, { paddingLeft: 2, flexDirection: 'column' },
53
+ stagesHeader,
54
+ hasLevel ? null : h(Box, { paddingLeft: 2, flexDirection: 'column' },
45
55
  ...defaultActive.map(s =>
46
56
  h(Text, { key: s },
47
57
  h(Text, { color: 'green' }, '\u2713 '),
@@ -57,9 +67,9 @@ export function Banner({ version, port, stages, llmLinguaUrl, outputMode }) {
57
67
  )
58
68
  ),
59
69
  ),
60
- disabled.length ? h(Text, null, '') : null,
61
- disabled.length ? h(Text, { bold: true }, 'Available ', h(Text, { dimColor: true }, '(not active — opt in for more savings)')) : null,
62
- disabled.length ? h(Box, { paddingLeft: 2, flexDirection: 'column' },
70
+ !hasLevel && disabled.length ? h(Text, null, '') : null,
71
+ !hasLevel && disabled.length ? h(Text, { bold: true }, 'Available ', h(Text, { dimColor: true }, '(not active — opt in for more savings)')) : null,
72
+ !hasLevel && disabled.length ? h(Box, { paddingLeft: 2, flexDirection: 'column' },
63
73
  ...disabled.flatMap(s => {
64
74
  const hint = STAGE_HINTS[s]
65
75
  const lines = [
@@ -0,0 +1,107 @@
1
+ import React, { useState } from 'react'
2
+ import { Box, Text, useInput } from 'ink'
3
+ import { StagePicker } from './StagePicker.js'
4
+ import { COMPRESSION_LEVELS, DEFAULT_LEVEL, resolveLevel } from '../../metadata.js'
5
+
6
+ const h = React.createElement
7
+
8
+ // Pure reducer — exported for testability. Handles clamping and NaN-safe jumps.
9
+ export function levelReducer(state, action) {
10
+ switch (action.type) {
11
+ case 'moveLeft':
12
+ return state > 1 ? state - 1 : 1
13
+ case 'moveRight':
14
+ return state < 9 ? state + 1 : 9
15
+ case 'jumpTo': {
16
+ const n = Number(action.value)
17
+ if (!Number.isInteger(n) || n < 1 || n > 9) return state
18
+ return n
19
+ }
20
+ default:
21
+ return state
22
+ }
23
+ }
24
+
25
+ export function initialLevel(envLevel) {
26
+ if (Number.isInteger(envLevel) && envLevel >= 1 && envLevel <= 9) return envLevel
27
+ return DEFAULT_LEVEL
28
+ }
29
+
30
+ // Build the payload emitted by onSelect when a level is confirmed.
31
+ export function buildLevelPayload(level) {
32
+ return { kind: 'level', level, stages: [...resolveLevel(level).stages] }
33
+ }
34
+
35
+ function Slider({ level }) {
36
+ // 9-position slider: o───●───o style
37
+ const cells = []
38
+ for (let i = 1; i <= 9; i++) {
39
+ if (i === level) cells.push(h(Text, { key: i, color: 'cyan', bold: true }, '●'))
40
+ else cells.push(h(Text, { key: i, dimColor: true }, '─'))
41
+ if (i < 9) cells.push(h(Text, { key: `s${i}`, dimColor: true }, '─'))
42
+ }
43
+ return h(Box, null, ...cells)
44
+ }
45
+
46
+ function Chips({ stages }) {
47
+ const children = []
48
+ stages.forEach((s, i) => {
49
+ children.push(h(Text, { key: `c${i}`, color: 'cyan' }, ` ${s} `))
50
+ if (i < stages.length - 1) children.push(h(Text, { key: `g${i}` }, ' '))
51
+ })
52
+ return h(Box, { flexWrap: 'wrap' }, ...children)
53
+ }
54
+
55
+ export function LevelPicker({ version, envLevel, envStages, onSelect, onCancel }) {
56
+ const [level, setLevel] = useState(() => initialLevel(envLevel))
57
+ const [advanced, setAdvanced] = useState(false)
58
+
59
+ useInput((input, key) => {
60
+ if (advanced) return
61
+ if (key.leftArrow || input === 'h') setLevel(s => levelReducer(s, { type: 'moveLeft' }))
62
+ else if (key.rightArrow || input === 'l') setLevel(s => levelReducer(s, { type: 'moveRight' }))
63
+ else if (input === 'a' || input === 'A') setAdvanced(true)
64
+ else if (key.return) onSelect(buildLevelPayload(level))
65
+ else if (key.escape) { if (onCancel) onCancel() }
66
+ else if (input && /^[1-9]$/.test(input)) setLevel(s => levelReducer(s, { type: 'jumpTo', value: input }))
67
+ })
68
+
69
+ if (advanced) {
70
+ return h(StagePicker, {
71
+ version,
72
+ envStages: envStages || resolveLevel(level).stages,
73
+ onSelect: (stages) => onSelect({ kind: 'stages', stages }),
74
+ })
75
+ }
76
+
77
+ const meta = resolveLevel(level) || COMPRESSION_LEVELS[DEFAULT_LEVEL]
78
+ const lossy = meta.lossy
79
+
80
+ return h(Box, { flexDirection: 'column', paddingX: 1 },
81
+ h(Box, { gap: 1, marginBottom: 1 },
82
+ h(Text, { bold: true, color: 'cyan' }, 'Tamp'),
83
+ h(Text, { dimColor: true }, `v${version}`),
84
+ ),
85
+ h(Text, { dimColor: true }, 'Compression level — ← → to adjust, 1-9 to jump, Enter to confirm'),
86
+ h(Box, { marginTop: 1, gap: 2, alignItems: 'center' },
87
+ h(Text, { bold: true, color: 'cyan' }, String(level)),
88
+ h(Slider, { level }),
89
+ h(Text, { color: lossy ? 'yellow' : 'green', bold: true }, lossy ? ' LOSSY ' : ' LOSSLESS '),
90
+ ),
91
+ h(Box, { marginTop: 1 },
92
+ h(Text, null, 'Expected savings: '),
93
+ h(Text, { bold: true, color: 'green' }, meta.savings),
94
+ ),
95
+ h(Box, { marginTop: 1, flexDirection: 'column' },
96
+ h(Text, { dimColor: true }, `Stages (${meta.stages.length})`),
97
+ h(Chips, { stages: meta.stages }),
98
+ ),
99
+ h(Box, { marginTop: 1 },
100
+ h(Text, { dimColor: true }, 'Press '),
101
+ h(Text, { bold: true }, 'A'),
102
+ h(Text, { dimColor: true }, ' for advanced per-stage picker · '),
103
+ h(Text, { bold: true }, 'Esc'),
104
+ h(Text, { dimColor: true }, ' to cancel'),
105
+ ),
106
+ )
107
+ }
package/config.js CHANGED
@@ -1,7 +1,15 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { homedir } from 'node:os'
3
3
  import { join } from 'node:path'
4
- import { DEFAULT_STAGES, VERSION, COMPRESSION_PRESETS } from './metadata.js'
4
+ import {
5
+ DEFAULT_STAGES,
6
+ VERSION,
7
+ COMPRESSION_PRESETS,
8
+ COMPRESSION_LEVELS,
9
+ DEFAULT_LEVEL,
10
+ LEVEL_ALIASES,
11
+ resolveLevel,
12
+ } from './metadata.js'
5
13
 
6
14
  const VALID_OUTPUT_MODES = new Set(['off', 'conservative', 'balanced', 'aggressive'])
7
15
 
@@ -12,20 +20,47 @@ function parseBoolean(value, defaultValue) {
12
20
  return defaultValue
13
21
  }
14
22
 
15
- function resolvePreset(presetName, explicitStages) {
16
- // If user explicitly set TAMP_STAGES, ignore preset
17
- if (explicitStages && explicitStages.length > 0) {
18
- return explicitStages
23
+ // Coerce numeric strings to integers; leave alias strings untouched.
24
+ // Returns { value, valid } — value is the coerced input for resolveLevel(),
25
+ // valid is whether the input is recognisable as a level at all.
26
+ function coerceLevelInput(raw) {
27
+ if (raw === undefined || raw === null || raw === '') return { value: null, valid: false }
28
+ if (typeof raw === 'number') {
29
+ const v = resolveLevel(raw) ? raw : null
30
+ return { value: v, valid: v !== null }
19
31
  }
20
-
21
- // Resolve preset name to stages
22
- const preset = COMPRESSION_PRESETS[presetName]
23
- if (preset) {
24
- return preset.stages
32
+ const s = String(raw).trim()
33
+ if (s === '') return { value: null, valid: false }
34
+ if (/^-?\d+$/.test(s)) {
35
+ const n = parseInt(s, 10)
36
+ const v = resolveLevel(n) ? n : null
37
+ return { value: v, valid: v !== null }
25
38
  }
39
+ if (s in LEVEL_ALIASES) return { value: s, valid: true }
40
+ return { value: null, valid: false }
41
+ }
42
+
43
+ // Convert a level input (number or alias) to its canonical integer.
44
+ function levelInputToInt(input) {
45
+ if (typeof input === 'number') return input
46
+ if (typeof input === 'string' && input in LEVEL_ALIASES) return LEVEL_ALIASES[input]
47
+ return null
48
+ }
49
+
50
+ // Preset levels are the "anchor" rungs of the ladder — when a resolved level
51
+ // matches one of these, prefer the preset's stage ordering. This preserves
52
+ // the L4 === conservative / L5 === balanced / L8 === aggressive identity
53
+ // promise and keeps pre-Phase-C stage ordering stable for downstream code.
54
+ const LEVEL_TO_PRESET = Object.freeze({
55
+ 4: 'conservative',
56
+ 5: 'balanced',
57
+ 8: 'aggressive',
58
+ })
26
59
 
27
- // Default to balanced preset if preset name not recognized
28
- return COMPRESSION_PRESETS.balanced.stages
60
+ function stagesForLevel(level) {
61
+ const presetName = LEVEL_TO_PRESET[level]
62
+ if (presetName) return [...COMPRESSION_PRESETS[presetName].stages]
63
+ return [...COMPRESSION_LEVELS[level].stages]
29
64
  }
30
65
 
31
66
  export const CONFIG_PATH = join(homedir(), '.config', 'tamp', 'config')
@@ -51,19 +86,97 @@ export function loadConfigFile(path) {
51
86
  } catch { return {} }
52
87
  }
53
88
 
54
- export function loadConfig(env = process.env) {
89
+ export function loadConfig(env = process.env, options = {}) {
55
90
  const fileVars = (env === process.env) ? loadConfigFile() : {}
56
91
  const get = (key) => env[key] !== undefined ? env[key] : fileVars[key]
57
92
 
58
- // Get explicit stages (if user set TAMP_STAGES directly)
93
+ // --- Stage/level resolution with explicit precedence ---
94
+ // 1. TAMP_STAGES (explicit stage list) — power-user override
95
+ // 2. --level CLI flag (options.levelOverride)
96
+ // 3. TAMP_LEVEL env
97
+ // 4. TAMP_COMPRESSION_PRESET env
98
+ // 5. config-file `level` field
99
+ // 6. DEFAULT_LEVEL (5)
100
+
59
101
  const explicitStagesStr = get('TAMP_STAGES')
60
- const explicitStages = explicitStagesStr ? explicitStagesStr.split(',').map(s => s.trim()).filter(Boolean) : []
102
+ const explicitStages = explicitStagesStr
103
+ ? explicitStagesStr.split(',').map(s => s.trim()).filter(Boolean)
104
+ : []
105
+
106
+ const presetNameRaw = get('TAMP_COMPRESSION_PRESET')
107
+ const presetExplicit = typeof presetNameRaw === 'string' && presetNameRaw.length > 0
61
108
 
62
- // Get compression preset
63
- const presetName = get('TAMP_COMPRESSION_PRESET') || 'balanced'
109
+ const fileLevelRaw = fileVars.level
110
+ const levelFlagRaw = options.levelOverride
111
+ const levelEnvRaw = get('TAMP_LEVEL')
64
112
 
65
- // Resolve preset to stages (or use explicit stages if provided)
66
- const stages = resolvePreset(presetName, explicitStages)
113
+ let stages = null
114
+ let level = null
115
+ let levelSource = null
116
+ let presetName = presetExplicit ? presetNameRaw : 'balanced'
117
+
118
+ if (explicitStages.length > 0) {
119
+ stages = explicitStages
120
+ level = null
121
+ levelSource = 'stages-env'
122
+ } else {
123
+ // Try level inputs in precedence order: CLI flag > env
124
+ const candidates = [
125
+ { raw: levelFlagRaw, source: 'level-flag' },
126
+ { raw: levelEnvRaw, source: 'level-env' },
127
+ ]
128
+ let chosen = null
129
+ for (const c of candidates) {
130
+ if (c.raw === undefined || c.raw === null || c.raw === '') continue
131
+ const { value, valid } = coerceLevelInput(c.raw)
132
+ if (valid) {
133
+ chosen = { value, source: c.source }
134
+ break
135
+ } else {
136
+ const label = c.source === 'level-flag' ? '--level' : 'TAMP_LEVEL'
137
+ process.stderr.write(
138
+ `[tamp] invalid ${label}=${JSON.stringify(c.raw)} — expected 1..9 or one of: ${Object.keys(LEVEL_ALIASES).join(', ')}. Ignoring.\n`
139
+ )
140
+ }
141
+ }
142
+
143
+ if (chosen) {
144
+ level = levelInputToInt(chosen.value)
145
+ stages = stagesForLevel(level)
146
+ levelSource = chosen.source
147
+ } else if (presetExplicit) {
148
+ const preset = COMPRESSION_PRESETS[presetNameRaw]
149
+ if (preset) {
150
+ stages = [...preset.stages]
151
+ level = typeof preset.level === 'number' ? preset.level : null
152
+ levelSource = 'preset-env'
153
+ } else {
154
+ // Unknown preset name — fall through to default balanced
155
+ stages = [...COMPRESSION_PRESETS.balanced.stages]
156
+ level = COMPRESSION_PRESETS.balanced.level
157
+ levelSource = 'default'
158
+ presetName = 'balanced'
159
+ }
160
+ } else if (fileLevelRaw !== undefined && fileLevelRaw !== '') {
161
+ const { value, valid } = coerceLevelInput(fileLevelRaw)
162
+ if (valid) {
163
+ level = levelInputToInt(value)
164
+ stages = stagesForLevel(level)
165
+ levelSource = 'config-file'
166
+ } else {
167
+ process.stderr.write(
168
+ `[tamp] invalid level=${JSON.stringify(fileLevelRaw)} in config file — expected 1..9 or one of: ${Object.keys(LEVEL_ALIASES).join(', ')}. Ignoring.\n`
169
+ )
170
+ level = DEFAULT_LEVEL
171
+ stages = stagesForLevel(DEFAULT_LEVEL)
172
+ levelSource = 'default'
173
+ }
174
+ } else {
175
+ level = DEFAULT_LEVEL
176
+ stages = stagesForLevel(DEFAULT_LEVEL)
177
+ levelSource = 'default'
178
+ }
179
+ }
67
180
 
68
181
  // Output mode precedence (highest wins):
69
182
  // 1. TAMP_OUTPUT_MODE — explicit per-session override
@@ -83,10 +196,23 @@ export function loadConfig(env = process.env) {
83
196
  openai: get('TAMP_UPSTREAM_OPENAI') || 'https://api.openai.com',
84
197
  'openai-responses': get('TAMP_UPSTREAM_OPENAI') || 'https://api.openai.com',
85
198
  gemini: get('TAMP_UPSTREAM_GEMINI') || 'https://generativelanguage.googleapis.com',
199
+ // Kimi Code (subscription CLI) — proprietary path /coding/v1/*
200
+ kimi: get('TAMP_UPSTREAM_KIMI') || 'https://api.kimi.com',
201
+ // Moonshot public OpenAI-compat API — strictly /v1/*
202
+ moonshot: get('TAMP_UPSTREAM_MOONSHOT') || 'https://api.moonshot.cn',
86
203
  }),
204
+ // Codex CLI ChatGPT Plus routes to https://chatgpt.com/backend-api/codex
205
+ // by default (not api.openai.com). Set TAMP_DISABLE_CHATGPT_ROUTE=1 to
206
+ // force legacy api.openai.com routing even when a JWT bearer / account
207
+ // id is detected.
208
+ disableChatgptRoute: parseBoolean(get('TAMP_DISABLE_CHATGPT_ROUTE'), false) ||
209
+ get('TAMP_DISABLE_CHATGPT_ROUTE') === '1',
210
+ chatgptUpstream: get('TAMP_UPSTREAM_CHATGPT') || 'https://chatgpt.com',
87
211
  minSize: parseInt(get('TAMP_MIN_SIZE'), 10) || 200,
88
212
  stages,
89
213
  preset: presetName,
214
+ level,
215
+ levelSource,
90
216
  outputMode,
91
217
  outputModeDefault: defaultOutputMode && VALID_OUTPUT_MODES.has(defaultOutputMode) ? defaultOutputMode : null,
92
218
  agent: get('TAMP_AGENT') || null,
@@ -115,6 +241,15 @@ export const CONFIG_TEMPLATE = `# Tamp configuration
115
241
  # TAMP_UPSTREAM=https://api.anthropic.com
116
242
  # TAMP_UPSTREAM_OPENAI=https://api.openai.com
117
243
  # TAMP_UPSTREAM_GEMINI=https://generativelanguage.googleapis.com
244
+ # TAMP_UPSTREAM_KIMI=https://api.kimi.com
245
+ # TAMP_UPSTREAM_MOONSHOT=https://api.moonshot.cn
246
+
247
+ # Codex CLI ChatGPT Plus routing (OAuth/JWT bearers land on chatgpt.com)
248
+ # Set to 1 to force legacy api.openai.com routing even when JWT is detected
249
+ # TAMP_DISABLE_CHATGPT_ROUTE=0
250
+
251
+ # Compression level 1..9 (or: conservative, balanced, aggressive, max)
252
+ # level=5
118
253
 
119
254
  # Compression preset (conservative | balanced | aggressive)
120
255
  # TAMP_COMPRESSION_PRESET=balanced
package/index.js CHANGED
@@ -5,7 +5,7 @@ import zlib from 'node:zlib'
5
5
  import * as fzstd from 'fzstd'
6
6
  import { loadConfig } from './config.js'
7
7
  import { compressRequest } from './compress.js'
8
- import { detectProvider } from './providers.js'
8
+ import { detectProvider, detectOpenAIAuthMode, resolveOpenAIUpstream } from './providers.js'
9
9
  import { createSession, formatRequestLog } from './stats.js'
10
10
  import { createSessionStore, deriveSessionKey } from './session-graph.js'
11
11
  import { createReadCache } from './lib/read-cache.js'
@@ -51,11 +51,40 @@ function buildUpstreamUrl(reqPath, base) {
51
51
  return parsed
52
52
  }
53
53
 
54
- export function createProxy(overrides = {}) {
55
- const base = loadConfig()
54
+ // Pick the upstream base + path transform for a resolved provider. For
55
+ // OpenAI-like providers we inspect auth headers to detect Codex CLI ChatGPT
56
+ // Plus mode (OAuth JWT + chatgpt-account-id), which must be routed to
57
+ // chatgpt.com/backend-api/codex instead of api.openai.com.
58
+ export function resolveUpstream(provider, headers, config) {
59
+ const defaultBase = config.upstreams?.[provider.name] || config.upstream
60
+ if (config.disableChatgptRoute) {
61
+ return { base: defaultBase, transformPath: (p) => p, mode: 'api-key' }
62
+ }
63
+ if (provider.name === 'openai' || provider.name === 'openai-responses') {
64
+ const mode = detectOpenAIAuthMode(headers)
65
+ if (mode === 'chatgpt-oauth') {
66
+ return resolveOpenAIUpstream({
67
+ mode,
68
+ base: config.chatgptUpstream || 'https://chatgpt.com',
69
+ providerName: provider.name,
70
+ })
71
+ }
72
+ }
73
+ return { base: defaultBase, transformPath: (p) => p, mode: 'api-key' }
74
+ }
75
+
76
+ export function createProxy(overrides = {}, loadOpts = {}) {
77
+ const base = loadConfig(process.env, loadOpts)
56
78
  const config = { ...base, ...overrides }
57
79
  if (overrides.upstream && !overrides.upstreams) {
58
- config.upstreams = { anthropic: overrides.upstream, openai: overrides.upstream, 'openai-responses': overrides.upstream, gemini: overrides.upstream }
80
+ config.upstreams = {
81
+ anthropic: overrides.upstream,
82
+ openai: overrides.upstream,
83
+ 'openai-responses': overrides.upstream,
84
+ gemini: overrides.upstream,
85
+ kimi: overrides.upstream,
86
+ moonshot: overrides.upstream,
87
+ }
59
88
  }
60
89
  const session = createSession()
61
90
  const brCache = (config.stages?.includes('graph') || config.stages?.includes('br-cache') || config.stages?.includes('disclosure'))
@@ -177,7 +206,7 @@ return http.createServer(async (req, res) => {
177
206
  return res.end(req.method === 'HEAD' ? undefined : body)
178
207
  }
179
208
 
180
- const provider = detectProvider(req.method, req.url)
209
+ const provider = detectProvider(req.method, req.url, req.headers)
181
210
 
182
211
  if (!provider) {
183
212
  log(`[tamp] ${req.method} ${req.url}`)
@@ -185,8 +214,10 @@ return http.createServer(async (req, res) => {
185
214
  return pipeRequest(req, res, upstreamUrl)
186
215
  }
187
216
 
188
- const upstream = config.upstreams?.[provider.name] || config.upstream
189
- const reqUrl = provider.normalizeUrl ? provider.normalizeUrl(req.url) : req.url
217
+ const route = resolveUpstream(provider, req.headers, config)
218
+ const upstream = route.base
219
+ const normalizedUrl = provider.normalizeUrl ? provider.normalizeUrl(req.url) : req.url
220
+ const reqUrl = route.transformPath(normalizedUrl)
190
221
  const upstreamUrl = buildUpstreamUrl(reqUrl, upstream)
191
222
 
192
223
  const chunks = []
package/metadata.js CHANGED
@@ -121,6 +121,7 @@ export const COMPRESSION_PRESETS = Object.freeze({
121
121
  stages: ['cmd-strip', 'minify', 'toon', 'strip-lines', 'whitespace', 'dedup', 'diff'],
122
122
  expectedSavings: '45-50%',
123
123
  risk: 'None',
124
+ level: 4,
124
125
  },
125
126
  balanced: {
126
127
  name: 'Balanced',
@@ -128,6 +129,7 @@ export const COMPRESSION_PRESETS = Object.freeze({
128
129
  stages: ['cmd-strip', 'minify', 'toon', 'strip-lines', 'whitespace', 'llmlingua', 'dedup', 'diff', 'read-diff', 'prune'],
129
130
  expectedSavings: '52-58%',
130
131
  risk: 'Low',
132
+ level: 5,
131
133
  },
132
134
  aggressive: {
133
135
  name: 'Aggressive',
@@ -135,5 +137,56 @@ export const COMPRESSION_PRESETS = Object.freeze({
135
137
  stages: ['cmd-strip', 'minify', 'toon', 'strip-lines', 'whitespace', 'llmlingua', 'dedup', 'diff', 'read-diff', 'prune', 'strip-comments', 'textpress', 'br-cache', 'disclosure', 'bm25-trim'],
136
138
  expectedSavings: '65-72%',
137
139
  risk: 'Medium (may lose comments, verbose text)',
140
+ level: 8,
138
141
  },
139
142
  })
143
+
144
+ // Flat 1..9 compression ladder, parallel to the named presets. Each level
145
+ // extends the previous level's stage list (prefix-preserving). L4/L5/L8 are
146
+ // set-equal to conservative/balanced/aggressive respectively; L6-L7 interpolate
147
+ // between balanced and aggressive; L9 extends past aggressive (max).
148
+ //
149
+ // NOTE: `lossy` goes true at L5 because `llmlingua` lives in the balanced
150
+ // preset (= L5). The ladder is aligned to preset semantics per spec.
151
+ function extend(base, adds) { return Object.freeze([...base, ...adds]) }
152
+
153
+ const L1_STAGES = extend([], ['minify'])
154
+ const L2_STAGES = extend(L1_STAGES, ['whitespace', 'strip-lines'])
155
+ const L3_STAGES = extend(L2_STAGES, ['cmd-strip'])
156
+ const L4_STAGES = extend(L3_STAGES, ['toon', 'dedup', 'diff'])
157
+ const L5_STAGES = extend(L4_STAGES, ['llmlingua', 'read-diff', 'prune'])
158
+ const L6_STAGES = extend(L5_STAGES, ['strip-comments'])
159
+ const L7_STAGES = extend(L6_STAGES, ['textpress', 'br-cache'])
160
+ const L8_STAGES = extend(L7_STAGES, ['disclosure', 'bm25-trim'])
161
+ const L9_STAGES = extend(L8_STAGES, ['graph', 'foundation-models'])
162
+
163
+ export const COMPRESSION_LEVELS = Object.freeze({
164
+ 1: Object.freeze({ stages: L1_STAGES, lossy: false, savings: '~15%' }),
165
+ 2: Object.freeze({ stages: L2_STAGES, lossy: false, savings: '~25%' }),
166
+ 3: Object.freeze({ stages: L3_STAGES, lossy: false, savings: '~35%' }),
167
+ 4: Object.freeze({ stages: L4_STAGES, lossy: false, savings: '~45%' }),
168
+ 5: Object.freeze({ stages: L5_STAGES, lossy: true, savings: '~53%' }),
169
+ 6: Object.freeze({ stages: L6_STAGES, lossy: true, savings: '~58%' }),
170
+ 7: Object.freeze({ stages: L7_STAGES, lossy: true, savings: '~62%' }),
171
+ 8: Object.freeze({ stages: L8_STAGES, lossy: true, savings: '~67%' }),
172
+ 9: Object.freeze({ stages: L9_STAGES, lossy: true, savings: '~72%' }),
173
+ })
174
+
175
+ export const DEFAULT_LEVEL = 5
176
+
177
+ export const LEVEL_ALIASES = Object.freeze({
178
+ conservative: 4,
179
+ balanced: 5,
180
+ aggressive: 8,
181
+ max: 9,
182
+ })
183
+
184
+ export function resolveLevel(input) {
185
+ if (typeof input === 'number' && Number.isInteger(input) && input >= 1 && input <= 9) {
186
+ return COMPRESSION_LEVELS[input]
187
+ }
188
+ if (typeof input === 'string' && input in LEVEL_ALIASES) {
189
+ return COMPRESSION_LEVELS[LEVEL_ALIASES[input]]
190
+ }
191
+ return null
192
+ }
package/package.json CHANGED
@@ -12,7 +12,7 @@
12
12
  "stats.js",
13
13
  "lib/"
14
14
  ],
15
- "version": "0.7.0",
15
+ "version": "0.8.0",
16
16
  "description": "Token compression proxy for coding agents. Works with Claude Code, Aider, Cursor, Cline, Windsurf. 60-70% combined input+output savings with Caveman-integrated presets and per-command rewriters.",
17
17
  "type": "module",
18
18
  "main": "index.js",
@@ -24,7 +24,9 @@
24
24
  "test": "node --test test/*.test.js",
25
25
  "test:sidecar": "node test/capture-golden.js --verify",
26
26
  "bench:semantic": "node bench/semantic-eval.js",
27
- "test:quality": "node bench/quality-eval.js"
27
+ "test:quality": "node bench/quality-eval.js",
28
+ "compat:probe": "node test/compat/probe-proxy.js",
29
+ "compat:run": "node test/compat/run.mjs"
28
30
  },
29
31
  "keywords": [
30
32
  "claude",
package/providers.js CHANGED
@@ -235,8 +235,30 @@ const anthropic = {
235
235
  },
236
236
  }
237
237
 
238
+ // OpenAI-compatible block types we don't know how to recompress safely.
239
+ // Kimi's "thinking" / "partial" deltas in particular must be left alone —
240
+ // they are not tool_result text and compressing them breaks the wire format.
241
+ const OPENAI_COMPAT_SKIP_BLOCK_TYPES = new Set(['thinking', 'partial'])
242
+
238
243
  function extractOpenAIChatTargets(msg, i) {
239
- if (msg.role !== 'tool' || typeof msg.content !== 'string') return []
244
+ if (msg.role !== 'tool') return []
245
+ // Some OpenAI-compat providers (Kimi, etc.) emit non-string tool content
246
+ // with typed blocks like { type: 'thinking' }. Skip those.
247
+ if (typeof msg.content !== 'string') {
248
+ if (Array.isArray(msg.content)) {
249
+ const targets = []
250
+ for (let j = 0; j < msg.content.length; j++) {
251
+ const block = msg.content[j]
252
+ if (!block || typeof block !== 'object') continue
253
+ if (OPENAI_COMPAT_SKIP_BLOCK_TYPES.has(block.type)) continue
254
+ if (block.type === 'text' && typeof block.text === 'string') {
255
+ targets.push({ path: ['messages', i, 'content', j, 'text'], text: block.text, index: i })
256
+ }
257
+ }
258
+ return targets
259
+ }
260
+ return []
261
+ }
240
262
  return [{ path: ['messages', i, 'content'], text: msg.content, index: i }]
241
263
  }
242
264
 
@@ -293,6 +315,54 @@ const openai = {
293
315
  },
294
316
  }
295
317
 
318
+ // Kimi Code (subscription) + Moonshot (OpenAI-compat API key) share wire
319
+ // format with OpenAI chat-completions aside from extra block types on
320
+ // streamed messages. Treat them as passthrough: same extract/apply contract
321
+ // as the openai adapter, but a different name so index.js can route them to
322
+ // api.kimi.com / api.moonshot.cn upstreams.
323
+ const kimi = {
324
+ name: 'kimi',
325
+ match(method, url) {
326
+ if (method !== 'POST') return false
327
+ return (
328
+ url.startsWith('/coding/v1/chat/completions') ||
329
+ url.startsWith('/kimi/v1/chat/completions') ||
330
+ url.startsWith('/kimi/coding/v1/chat/completions')
331
+ )
332
+ },
333
+ normalizeUrl(url) {
334
+ // Strip the tamp-mount prefix so the upstream receives the canonical
335
+ // Kimi Code path.
336
+ if (url.startsWith('/kimi/coding/v1/')) return url.slice('/kimi'.length)
337
+ if (url.startsWith('/kimi/v1/')) return '/coding' + url.slice('/kimi'.length)
338
+ return url
339
+ },
340
+ extract: openai.extract,
341
+ apply: openai.apply,
342
+ getLastUserText: openai.getLastUserText,
343
+ injectOutputHint: openai.injectOutputHint,
344
+ }
345
+
346
+ const moonshot = {
347
+ name: 'moonshot',
348
+ match(method, url) {
349
+ if (method !== 'POST') return false
350
+ return (
351
+ url.startsWith('/moonshot/v1/chat/completions') ||
352
+ url.startsWith('/moonshot/chat/completions')
353
+ )
354
+ },
355
+ normalizeUrl(url) {
356
+ if (url.startsWith('/moonshot/v1/')) return url.slice('/moonshot'.length)
357
+ if (url.startsWith('/moonshot/chat/completions')) return '/v1' + url.slice('/moonshot'.length)
358
+ return url
359
+ },
360
+ extract: openai.extract,
361
+ apply: openai.apply,
362
+ getLastUserText: openai.getLastUserText,
363
+ injectOutputHint: openai.injectOutputHint,
364
+ }
365
+
296
366
  function extractGeminiContentTargets(content, ci) {
297
367
  const targets = []
298
368
  if (!content.parts?.length) return targets
@@ -442,13 +512,103 @@ const openaiResponses = {
442
512
  },
443
513
  }
444
514
 
445
- const providers = [anthropic, openai, openaiResponses, gemini]
515
+ // ---- Auth-mode detection for OpenAI-like providers ----
516
+ //
517
+ // Codex CLI running in ChatGPT Plus mode does NOT use a traditional
518
+ // `sk-*` API key. It sends an OAuth JWT as the Bearer token, plus a
519
+ // `chatgpt-account-id` header. The upstream in that mode is
520
+ // https://chatgpt.com/backend-api/codex (NOT api.openai.com). See
521
+ // openai/codex `model-provider-info/src/lib.rs` for the canonical list.
522
+ //
523
+ // Returns:
524
+ // 'api-key' — classic `Authorization: Bearer sk-...`
525
+ // 'chatgpt-oauth' — JWT bearer OR chatgpt-account-id header present
526
+ // 'unknown' — neither
527
+ function headerValue(headers, name) {
528
+ if (!headers) return null
529
+ // Node's IncomingHeaders are already lowercased, but be defensive for
530
+ // plain objects passed from tests.
531
+ if (headers[name] !== undefined) return headers[name]
532
+ const lower = name.toLowerCase()
533
+ if (headers[lower] !== undefined) return headers[lower]
534
+ for (const k of Object.keys(headers)) {
535
+ if (k.toLowerCase() === lower) return headers[k]
536
+ }
537
+ return null
538
+ }
539
+
540
+ function extractBearer(auth) {
541
+ if (typeof auth !== 'string') return null
542
+ const m = auth.match(/^\s*Bearer\s+(.+?)\s*$/i)
543
+ return m ? m[1] : null
544
+ }
545
+
546
+ function looksLikeJwt(token) {
547
+ if (typeof token !== 'string') return false
548
+ // Compact JWS: three base64url segments separated by dots. Header segment
549
+ // starts with "eyJ" (base64-encoded `{"`). Good enough for detection.
550
+ if (!token.startsWith('eyJ')) return false
551
+ const parts = token.split('.')
552
+ return parts.length === 3 && parts.every(p => p.length > 0)
553
+ }
554
+
555
+ export function detectOpenAIAuthMode(headersOrRequest) {
556
+ const headers = headersOrRequest?.headers || headersOrRequest || {}
557
+ const accountId = headerValue(headers, 'chatgpt-account-id')
558
+ const auth = headerValue(headers, 'authorization')
559
+ const token = extractBearer(auth)
560
+
561
+ if (accountId) return 'chatgpt-oauth'
562
+ if (token && token.startsWith('sk-')) return 'api-key'
563
+ if (token && looksLikeJwt(token)) return 'chatgpt-oauth'
564
+ return 'unknown'
565
+ }
566
+
567
+ // Route selection for OpenAI-like requests. Returns the upstream base URL
568
+ // and a path transformer. Callers are responsible for enforcing
569
+ // TAMP_DISABLE_CHATGPT_ROUTE (handled in index.js).
570
+ export function resolveOpenAIUpstream({ mode, base, providerName }) {
571
+ if (mode === 'chatgpt-oauth') {
572
+ return {
573
+ base: 'https://chatgpt.com',
574
+ transformPath(path) {
575
+ // Codex calls land on /v1/responses or /v1/chat/completions. The
576
+ // ChatGPT backend expects /backend-api/codex<rest>.
577
+ if (path.startsWith('/backend-api/codex')) return path
578
+ return '/backend-api/codex' + path
579
+ },
580
+ mode,
581
+ providerName,
582
+ }
583
+ }
584
+ return {
585
+ base,
586
+ transformPath(path) { return path },
587
+ mode,
588
+ providerName,
589
+ }
590
+ }
446
591
 
447
- export function detectProvider(method, url) {
592
+ const providers = [anthropic, openai, openaiResponses, gemini, kimi, moonshot]
593
+
594
+ // detectProvider(method, url, headers?) — headers is optional for b/c. When
595
+ // the path is OpenAI-like but headers carry a `x-tamp-target: kimi|moonshot`
596
+ // hint we route to the corresponding adapter. Path-based matching runs
597
+ // first so existing mounts keep working.
598
+ export function detectProvider(method, url, headers) {
599
+ const hint = headers ? headerValue(headers, 'x-tamp-target') : null
600
+ if (hint) {
601
+ const hinted = providers.find(p => p.name === hint)
602
+ if (hinted && hinted.match(method, url)) return hinted
603
+ // Hint may point to a kimi/moonshot provider even if path doesn't carry
604
+ // the tamp mount prefix (e.g. user pointed their client at /v1/...).
605
+ if (hint === 'kimi' && openai.match(method, url)) return kimi
606
+ if (hint === 'moonshot' && openai.match(method, url)) return moonshot
607
+ }
448
608
  for (const p of providers) {
449
609
  if (p.match(method, url)) return p
450
610
  }
451
611
  return null
452
612
  }
453
613
 
454
- export { anthropic, openai, openaiResponses, gemini }
614
+ export { anthropic, openai, openaiResponses, gemini, kimi, moonshot }