@sliday/tamp 0.5.9 → 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
@@ -39,6 +39,7 @@ Auto-detects API format, compresses tool output, forwards upstream. Error result
39
39
 
40
40
  | Stage | What |
41
41
  |-------|------|
42
+ | `cmd-strip` | Strip progress bars and spinners from command output (lossless) |
42
43
  | `minify` | Strip JSON whitespace |
43
44
  | `toon` | Columnar array encoding |
44
45
  | `strip-lines` | Remove line-number prefixes |
@@ -59,14 +60,14 @@ curl -fsSL https://tamp.dev/setup.sh | bash
59
60
  # Option B: Manual
60
61
  npx @sliday/tamp
61
62
  export ANTHROPIC_BASE_URL=http://localhost:7778 # Claude Code
62
- export OPENAI_API_BASE=http://localhost:7778/v1 # Aider, Cursor, Cline
63
+ export OPENAI_API_BASE=http://localhost:7778/v1 # Aider, Cline
63
64
  ```
64
65
 
65
66
  Use your agent as normal — Tamp compresses silently.
66
67
 
67
68
  ### Codex CLI
68
69
 
69
- 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:
70
71
 
71
72
  ```toml
72
73
  model_provider = "tamp"
@@ -80,6 +81,14 @@ wire_api = "responses"
80
81
 
81
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.
82
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
+
83
92
  ### Cursor
84
93
 
85
94
  1. Start Tamp: `npx @sliday/tamp -y`
@@ -89,7 +98,24 @@ Then `export OPENAI_API_KEY=sk-...` and run `codex` or `codex exec "..."` as usu
89
98
  5. Click **Verify**, then enable any OpenAI-family model (`gpt-4o`, `gpt-5-codex`, etc.)
90
99
  6. Use Cursor as normal — Tamp compresses every tool call
91
100
 
92
- > 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.
93
119
 
94
120
  ### VS Code
95
121
 
@@ -133,15 +159,41 @@ Copilot does not expose a base URL setting and routes everything through GitHub'
133
159
 
134
160
  Run `tamp init` to create `~/.config/tamp/config`. All variables work via env or config file.
135
161
 
136
- ### 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.
137
165
 
138
- 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` |
139
177
 
140
- | Preset | Savings | Description |
141
- |--------|---------|-------------|
142
- | `conservative` | 45-50% | Lossless only (no neural) |
143
- | `balanced` (default) | 52-58% | Recommended, includes LLMLingua |
144
- | `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 |
145
197
 
146
198
  ```bash
147
199
  # Use a preset
@@ -185,14 +237,14 @@ Supported on all providers: Anthropic, OpenAI Chat, OpenAI Responses (Codex), Ge
185
237
  **Recommended setups:**
186
238
 
187
239
  ```bash
188
- # Default (balanced preset)
240
+ # Default (balanced preset = L5)
189
241
  npx @sliday/tamp
190
242
 
191
243
  # Conservative (no Python, lossless only)
192
- TAMP_COMPRESSION_PRESET=conservative npx @sliday/tamp -y
244
+ TAMP_LEVEL=4 npx @sliday/tamp -y
193
245
 
194
246
  # Aggressive (maximum compression)
195
- TAMP_COMPRESSION_PRESET=aggressive npx @sliday/tamp -y
247
+ TAMP_LEVEL=8 npx @sliday/tamp -y
196
248
  ```
197
249
 
198
250
  ## CLI Tools
@@ -251,6 +303,21 @@ Claude Code sends full conversation history on every API call. Tool results accu
251
303
 
252
304
  **Combined impact:** With new Caveman-integrated features, Tamp achieves 60-70% total token savings (input + output) in balanced mode.
253
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
+
254
321
  ## Development
255
322
 
256
323
  ```bash
package/bin/lifecycle.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs'
1
+ import { readFileSync, writeFileSync, unlinkSync, mkdirSync, realpathSync, existsSync } from 'node:fs'
2
2
  import { join, dirname } from 'node:path'
3
3
  import http from 'node:http'
4
4
  import { CONFIG_PATH } from '../config.js'
@@ -9,16 +9,28 @@ export function pidFilePath(port) {
9
9
  return join(TAMP_DIR, `tamp-${port}.pid`)
10
10
  }
11
11
 
12
+ // Symlink-safe resolver. Returns the real filesystem path for an existing
13
+ // PID file, or the original path when the file doesn't exist yet (so write
14
+ // operations land on the expected path). This prevents a symlink-swap
15
+ // attacker from redirecting our read/write to a privileged file.
16
+ function resolvePidPath(port) {
17
+ const p = pidFilePath(port)
18
+ try {
19
+ if (existsSync(p)) return realpathSync(p)
20
+ } catch { /* fall through to raw path */ }
21
+ return p
22
+ }
23
+
12
24
  export function writePidFile(port) {
13
25
  mkdirSync(TAMP_DIR, { recursive: true })
14
- const file = pidFilePath(port)
26
+ const file = resolvePidPath(port)
15
27
  writeFileSync(file, `${process.pid}\n${Date.now()}\n`)
16
28
  return file
17
29
  }
18
30
 
19
31
  export function readPidFile(port) {
20
32
  try {
21
- const [pidStr, startedStr] = readFileSync(pidFilePath(port), 'utf8').split('\n')
33
+ const [pidStr, startedStr] = readFileSync(resolvePidPath(port), 'utf8').split('\n')
22
34
  const pid = Number(pidStr)
23
35
  if (!pid) return null
24
36
  return { pid, startedAt: Number(startedStr) || null }
@@ -26,7 +38,7 @@ export function readPidFile(port) {
26
38
  }
27
39
 
28
40
  export function clearPidFile(port) {
29
- try { unlinkSync(pidFilePath(port)) } catch {}
41
+ try { unlinkSync(resolvePidPath(port)) } catch {}
30
42
  }
31
43
 
32
44
  export function isProcessAlive(pid) {
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
+ }