@sliday/tamp 0.5.1 → 0.5.4

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
@@ -48,7 +48,7 @@ Auto-detects API format, compresses tool output, forwards upstream. Error result
48
48
  | `diff` | Replace similar re-reads with diffs |
49
49
  | `prune` | Remove low-value metadata |
50
50
 
51
- Opt-in stages: `strip-comments`, `textpress` (LLM semantic compression), `graph` (session-scoped dedup across requests — shines on long Codex/Claude plan sessions that re-read the same files across turns, up to -99% per repeat block)
51
+ Opt-in stages: `strip-comments`, `textpress` (LLM semantic compression), `graph` (session-scoped dedup — works on any coding agent: Codex, Claude Code, Aider — anywhere the same file is read twice, up to -99% per repeat block)
52
52
 
53
53
  ## Quick Start
54
54
 
@@ -160,6 +160,18 @@ tamp compress-config ~/.config/tamp/config ~/.claude/CLAUDE.md
160
160
 
161
161
  Inspired by [JuliusBrussee/caveman-compress](https://github.com/JuliusBrussee/caveman).
162
162
 
163
+ ## Lifecycle
164
+
165
+ Tamp writes a PID file at `~/.config/tamp/tamp-${port}.pid` on start and cleans it up on graceful shutdown (SIGINT, SIGTERM, SIGHUP). If a terminal dies and leaves the port bound, `tamp -y` will now detect it and print a friendly error instead of a cryptic EADDRINUSE:
166
+
167
+ ```
168
+ [tamp] Tamp v0.5.4 already running on :7778 (pid 12345, started 3m ago).
169
+ Run 'tamp stop' to replace it, or set TAMP_PORT=7779 to run alongside it.
170
+ ```
171
+
172
+ - `tamp stop` — graceful SIGTERM to the running proxy, falls back to SIGKILL after 2s
173
+ - `tamp -y --force` — replace any existing Tamp on the same port in one step (for scripts)
174
+
163
175
  ## Installation
164
176
 
165
177
  ```bash
@@ -0,0 +1,165 @@
1
+ import { readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs'
2
+ import { join, dirname } from 'node:path'
3
+ import http from 'node:http'
4
+ import { CONFIG_PATH } from '../config.js'
5
+
6
+ const TAMP_DIR = dirname(CONFIG_PATH)
7
+
8
+ export function pidFilePath(port) {
9
+ return join(TAMP_DIR, `tamp-${port}.pid`)
10
+ }
11
+
12
+ export function writePidFile(port) {
13
+ mkdirSync(TAMP_DIR, { recursive: true })
14
+ const file = pidFilePath(port)
15
+ writeFileSync(file, `${process.pid}\n${Date.now()}\n`)
16
+ return file
17
+ }
18
+
19
+ export function readPidFile(port) {
20
+ try {
21
+ const [pidStr, startedStr] = readFileSync(pidFilePath(port), 'utf8').split('\n')
22
+ const pid = Number(pidStr)
23
+ if (!pid) return null
24
+ return { pid, startedAt: Number(startedStr) || null }
25
+ } catch { return null }
26
+ }
27
+
28
+ export function clearPidFile(port) {
29
+ try { unlinkSync(pidFilePath(port)) } catch {}
30
+ }
31
+
32
+ export function isProcessAlive(pid) {
33
+ if (!pid) return false
34
+ try { process.kill(pid, 0); return true } catch { return false }
35
+ }
36
+
37
+ export function checkPort(port, timeoutMs = 1000) {
38
+ return new Promise(resolve => {
39
+ const req = http.get(`http://127.0.0.1:${port}/health`, (res) => {
40
+ res.resume()
41
+ resolve(res.statusCode === 200)
42
+ })
43
+ req.on('error', () => resolve(false))
44
+ req.setTimeout(timeoutMs, () => { req.destroy(); resolve(false) })
45
+ })
46
+ }
47
+
48
+ export function fetchHealth(port, timeoutMs = 1500) {
49
+ return new Promise(resolve => {
50
+ const req = http.get(`http://127.0.0.1:${port}/health`, (res) => {
51
+ if (res.statusCode !== 200) { res.resume(); resolve(null); return }
52
+ const chunks = []
53
+ res.on('data', c => chunks.push(c))
54
+ res.on('end', () => {
55
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) }
56
+ catch { resolve(null) }
57
+ })
58
+ })
59
+ req.on('error', () => resolve(null))
60
+ req.setTimeout(timeoutMs, () => { req.destroy(); resolve(null) })
61
+ })
62
+ }
63
+
64
+ export function formatAge(ms) {
65
+ if (!ms || ms < 0) return 'unknown'
66
+ const s = Math.floor(ms / 1000)
67
+ if (s < 60) return `${s}s ago`
68
+ const m = Math.floor(s / 60)
69
+ if (m < 60) return `${m}m ago`
70
+ const h = Math.floor(m / 60)
71
+ if (h < 24) return `${h}h ago`
72
+ return `${Math.floor(h / 24)}d ago`
73
+ }
74
+
75
+ export async function diagnoseBindConflict(port) {
76
+ const health = await fetchHealth(port)
77
+ if (health && health.status === 'ok' && health.version) {
78
+ const rec = readPidFile(port)
79
+ const pidInfo = rec && rec.startedAt
80
+ ? ` (pid ${rec.pid}, started ${formatAge(Date.now() - rec.startedAt)})`
81
+ : rec ? ` (pid ${rec.pid})` : ''
82
+ return {
83
+ kind: 'tamp',
84
+ version: health.version,
85
+ pid: rec?.pid || null,
86
+ message: `Tamp v${health.version} already running on :${port}${pidInfo}.\n Run 'tamp stop' to replace it, or set TAMP_PORT=${Number(port) + 1} to run alongside it.`,
87
+ }
88
+ }
89
+ return {
90
+ kind: 'other',
91
+ message: `Port ${port} is in use by another process (not Tamp).\n Free it with: lsof -ti:${port} | xargs kill\n Or set TAMP_PORT=${Number(port) + 1}.`,
92
+ }
93
+ }
94
+
95
+ export async function reconcileStalePidFile(port) {
96
+ const rec = readPidFile(port)
97
+ if (rec && !isProcessAlive(rec.pid)) {
98
+ clearPidFile(port)
99
+ return { wasStale: true, pid: rec.pid }
100
+ }
101
+ return { wasStale: false }
102
+ }
103
+
104
+ export function installShutdown({ server, getSidecar, port, onBeforeExit }) {
105
+ let shuttingDown = false
106
+ const handlers = {}
107
+
108
+ function shutdown(signal) {
109
+ if (shuttingDown) return
110
+ shuttingDown = true
111
+
112
+ if (port != null) clearPidFile(port)
113
+
114
+ const sidecar = getSidecar?.()
115
+ if (sidecar && !sidecar.killed) {
116
+ try { sidecar.kill('SIGTERM') } catch {}
117
+ const killTimer = setTimeout(() => {
118
+ try { if (sidecar && !sidecar.killed) sidecar.kill('SIGKILL') } catch {}
119
+ }, 500)
120
+ killTimer.unref?.()
121
+ }
122
+
123
+ const forceExit = setTimeout(() => {
124
+ try { server?.closeAllConnections?.() } catch {}
125
+ process.exit(0)
126
+ }, 2000)
127
+ forceExit.unref?.()
128
+
129
+ try {
130
+ if (server && typeof server.close === 'function') {
131
+ server.close(() => {
132
+ clearTimeout(forceExit)
133
+ onBeforeExit?.(signal)
134
+ process.exit(0)
135
+ })
136
+ } else {
137
+ clearTimeout(forceExit)
138
+ onBeforeExit?.(signal)
139
+ process.exit(0)
140
+ }
141
+ } catch {
142
+ process.exit(0)
143
+ }
144
+ }
145
+
146
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
147
+ handlers[sig] = () => shutdown(sig)
148
+ process.on(sig, handlers[sig])
149
+ }
150
+
151
+ const exitHandler = () => {
152
+ if (port != null) clearPidFile(port)
153
+ const sidecar = getSidecar?.()
154
+ try { sidecar?.kill('SIGKILL') } catch {}
155
+ }
156
+ process.on('exit', exitHandler)
157
+ handlers.exit = exitHandler
158
+
159
+ return function uninstall() {
160
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
161
+ if (handlers[sig]) process.off(sig, handlers[sig])
162
+ }
163
+ if (handlers.exit) process.off('exit', handlers.exit)
164
+ }
165
+ }
package/bin/tamp.js CHANGED
@@ -5,9 +5,18 @@ 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 http from 'node:http'
9
8
  import { DEFAULT_STAGES, EXTRA_STAGES, STAGE_DESCRIPTIONS, VERSION } from '../metadata.js'
10
9
  import { CONFIG_PATH, CONFIG_TEMPLATE } from '../config.js'
10
+ import {
11
+ checkPort,
12
+ diagnoseBindConflict,
13
+ installShutdown,
14
+ reconcileStalePidFile,
15
+ readPidFile,
16
+ clearPidFile,
17
+ writePidFile,
18
+ isProcessAlive,
19
+ } from './lifecycle.js'
11
20
 
12
21
  const __dirname = dirname(fileURLToPath(import.meta.url))
13
22
  const root = join(__dirname, '..')
@@ -15,16 +24,7 @@ const root = join(__dirname, '..')
15
24
  // --- Sidecar helpers (shared by both modes) ---
16
25
 
17
26
  let sidecarProc = null
18
-
19
- function checkPort(port) {
20
- return new Promise(resolve => {
21
- const req = http.get(`http://127.0.0.1:${port}/health`, (res) => {
22
- res.resume(); resolve(res.statusCode === 200)
23
- })
24
- req.on('error', () => resolve(false))
25
- req.setTimeout(1000, () => { req.destroy(); resolve(false) })
26
- })
27
- }
27
+ export function getSidecarProc() { return sidecarProc }
28
28
 
29
29
  function hasCommand(cmd) {
30
30
  try { execFileSync('which', [cmd], { stdio: 'ignore' }); return true } catch { return false }
@@ -162,12 +162,56 @@ if (subcommand === 'status') {
162
162
  process.exit(healthy ? 0 : 1)
163
163
  }
164
164
 
165
+ if (subcommand === 'stop') {
166
+ const port = Number(process.env.TAMP_PORT) || 7778
167
+ await reconcileStalePidFile(port)
168
+ const rec = readPidFile(port)
169
+
170
+ if (!rec) {
171
+ const healthy = await checkPort(port)
172
+ if (healthy) {
173
+ console.error(`Tamp appears to be running on :${port} but no PID file was found.`)
174
+ console.error(` Kill manually: lsof -ti:${port} | xargs kill`)
175
+ process.exit(1)
176
+ }
177
+ console.log(`No Tamp running on :${port}.`)
178
+ process.exit(0)
179
+ }
180
+
181
+ try {
182
+ process.kill(rec.pid, 'SIGTERM')
183
+ } catch (err) {
184
+ if (err.code === 'ESRCH') {
185
+ clearPidFile(port)
186
+ console.log(`Tamp (pid ${rec.pid}) was already dead — cleaned up stale PID file.`)
187
+ process.exit(0)
188
+ }
189
+ throw err
190
+ }
191
+
192
+ for (let i = 0; i < 20; i++) {
193
+ await new Promise(r => setTimeout(r, 100))
194
+ if (!(await checkPort(port)) && !isProcessAlive(rec.pid)) break
195
+ }
196
+
197
+ if (await checkPort(port) || isProcessAlive(rec.pid)) {
198
+ try { process.kill(rec.pid, 'SIGKILL') } catch {}
199
+ console.warn(`Tamp (pid ${rec.pid}) did not respond to SIGTERM within 2s — sent SIGKILL.`)
200
+ } else {
201
+ console.log(`Stopped Tamp (pid ${rec.pid}) on :${port}.`)
202
+ }
203
+ clearPidFile(port)
204
+ process.exit(0)
205
+ }
206
+
165
207
  if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
166
208
  console.log(`Tamp v${VERSION} — Token compression proxy for coding agents\n`)
167
209
  console.log('Usage: tamp [command] [options]\n')
168
210
  console.log('Commands:')
169
211
  console.log(' (default) Start proxy (interactive stage picker)')
170
212
  console.log(' -y Start proxy (non-interactive, use defaults)')
213
+ console.log(' -y --force Replace any existing Tamp on the same port')
214
+ console.log(' stop Stop a running Tamp on TAMP_PORT (default 7778)')
171
215
  console.log(' init Create config file (~/.config/tamp/config)')
172
216
  console.log(' status Check if proxy is running')
173
217
  console.log(' install-service Install systemd user service (Linux)')
@@ -179,11 +223,40 @@ if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
179
223
 
180
224
  // --- Mode detection ---
181
225
  const skipPrompt = process.argv.includes('-y') || process.argv.includes('--no-interactive') || !process.stdin.isTTY
226
+ const forceReplace = process.argv.includes('--force')
182
227
 
183
228
  const envStages = process.env.TAMP_STAGES
184
229
  ? new Set(process.env.TAMP_STAGES.split(',').map(s => s.trim()).filter(Boolean))
185
230
  : null
186
231
 
232
+ async function ensurePortFree(port) {
233
+ await reconcileStalePidFile(port)
234
+ if (!(await checkPort(port))) return
235
+
236
+ if (forceReplace) {
237
+ const rec = readPidFile(port)
238
+ if (rec) {
239
+ try { process.kill(rec.pid, 'SIGTERM') } catch {}
240
+ for (let i = 0; i < 20; i++) {
241
+ await new Promise(r => setTimeout(r, 100))
242
+ if (!(await checkPort(port))) break
243
+ }
244
+ if (await checkPort(port)) {
245
+ try { process.kill(rec.pid, 'SIGKILL') } catch {}
246
+ await new Promise(r => setTimeout(r, 300))
247
+ }
248
+ clearPidFile(port)
249
+ if (!(await checkPort(port))) return
250
+ }
251
+ console.error(`[tamp] --force requested but port ${port} could not be freed.`)
252
+ process.exit(1)
253
+ }
254
+
255
+ const diag = await diagnoseBindConflict(port)
256
+ console.error(`[tamp] ${diag.message}`)
257
+ process.exit(1)
258
+ }
259
+
187
260
  if (skipPrompt) {
188
261
  // --- Non-interactive mode (plain text, no Ink) ---
189
262
  const { ANSI: c } = await import('./ui/theme.js')
@@ -207,6 +280,8 @@ if (skipPrompt) {
207
280
 
208
281
  const { config, server } = createProxy()
209
282
 
283
+ await ensurePortFree(config.port)
284
+
210
285
  function printBanner() {
211
286
  const url = `http://localhost:${config.port}`
212
287
  const active = config.stages
@@ -235,11 +310,25 @@ if (skipPrompt) {
235
310
  console.error('')
236
311
  }
237
312
 
238
- server.listen(config.port, () => { printBanner() })
313
+ server.on('error', async (err) => {
314
+ if (err.code === 'EADDRINUSE') {
315
+ const diag = await diagnoseBindConflict(config.port)
316
+ console.error(`[tamp] ${diag.message}`)
317
+ } else {
318
+ console.error(`[tamp] Failed to start: ${err.message}`)
319
+ }
320
+ try { sidecarProc?.kill() } catch {}
321
+ process.exit(1)
322
+ })
239
323
 
240
- process.on('exit', () => sidecarProc?.kill())
241
- process.on('SIGINT', () => { sidecarProc?.kill(); process.exit() })
242
- process.on('SIGTERM', () => { sidecarProc?.kill(); process.exit() })
324
+ server.listen(config.port, () => {
325
+ try { writePidFile(config.port) } catch (err) {
326
+ console.error(`[tamp] Warning: could not write PID file: ${err.message}`)
327
+ }
328
+ printBanner()
329
+ })
330
+
331
+ installShutdown({ server, getSidecar: getSidecarProc, port: config.port })
243
332
 
244
333
  } else {
245
334
  // --- Interactive mode (Ink TUI) ---
@@ -249,14 +338,12 @@ if (skipPrompt) {
249
338
 
250
339
  const h = React.createElement
251
340
 
252
- const cleanup = () => { sidecarProc?.kill() }
253
- process.on('exit', cleanup)
254
- process.on('SIGTERM', () => { cleanup(); process.exit() })
255
-
256
341
  render(h(App, {
257
342
  version: VERSION,
258
343
  envStages,
259
344
  startSidecar,
260
345
  createProxy,
346
+ getSidecarProc,
347
+ ensurePortFree,
261
348
  }))
262
349
  }
package/bin/ui/App.js CHANGED
@@ -3,10 +3,11 @@ import { Box, Text, useApp } from 'ink'
3
3
  import { StagePicker } from './StagePicker.js'
4
4
  import { SidecarLoader } from './SidecarLoader.js'
5
5
  import { Dashboard } from './Dashboard.js'
6
+ import { installShutdown, writePidFile, diagnoseBindConflict } from '../lifecycle.js'
6
7
 
7
8
  const h = React.createElement
8
9
 
9
- export function App({ version, envStages, startSidecar, createProxy }) {
10
+ export function App({ version, envStages, startSidecar, createProxy, getSidecarProc, ensurePortFree }) {
10
11
  const { exit } = useApp()
11
12
  const [phase, setPhase] = useState('pick')
12
13
  const [stages, setStages] = useState(null)
@@ -24,7 +25,7 @@ export function App({ version, envStages, startSidecar, createProxy }) {
24
25
  setTotals(newTotals)
25
26
  }, [])
26
27
 
27
- const startProxy = useCallback((selectedStages, sidecarUrl) => {
28
+ const startProxy = useCallback(async (selectedStages, sidecarUrl) => {
28
29
  process.env.TAMP_STAGES = selectedStages.join(',')
29
30
  if (sidecarUrl) process.env.TAMP_LLMLINGUA_URL = sidecarUrl
30
31
 
@@ -32,15 +33,32 @@ export function App({ version, envStages, startSidecar, createProxy }) {
32
33
  serverRef.current = server
33
34
  setConfig(proxyConfig)
34
35
 
35
- server.on('error', (err) => {
36
- exit()
37
- process.stderr.write(`\n[tamp] Failed to start: ${err.message}\n`)
36
+ if (ensurePortFree) {
37
+ try { await ensurePortFree(proxyConfig.port) } catch { return }
38
+ }
39
+
40
+ server.on('error', async (err) => {
41
+ if (err.code === 'EADDRINUSE') {
42
+ const diag = await diagnoseBindConflict(proxyConfig.port)
43
+ exit()
44
+ process.stderr.write(`\n[tamp] ${diag.message}\n`)
45
+ } else {
46
+ exit()
47
+ process.stderr.write(`\n[tamp] Failed to start: ${err.message}\n`)
48
+ }
38
49
  process.exit(1)
39
50
  })
40
51
  server.listen(proxyConfig.port, () => {
52
+ try { writePidFile(proxyConfig.port) } catch {}
53
+ installShutdown({
54
+ server,
55
+ getSidecar: getSidecarProc,
56
+ port: proxyConfig.port,
57
+ onBeforeExit: () => exit(),
58
+ })
41
59
  setPhase('running')
42
60
  })
43
- }, [onCompress, createProxy, exit])
61
+ }, [onCompress, createProxy, exit, getSidecarProc, ensurePortFree])
44
62
 
45
63
  const onStagesSelected = useCallback((selected) => {
46
64
  setStages(selected)
@@ -66,19 +84,6 @@ export function App({ version, envStages, startSidecar, createProxy }) {
66
84
  startProxy(filtered, null)
67
85
  }, [startProxy])
68
86
 
69
- useEffect(() => {
70
- const shutdown = () => {
71
- serverRef.current?.close()
72
- exit()
73
- }
74
- process.on('SIGINT', shutdown)
75
- process.on('SIGTERM', shutdown)
76
- return () => {
77
- process.off('SIGINT', shutdown)
78
- process.off('SIGTERM', shutdown)
79
- }
80
- }, [exit])
81
-
82
87
  if (phase === 'pick') {
83
88
  return h(StagePicker, { version, envStages, onSelect: onStagesSelected })
84
89
  }
package/package.json CHANGED
@@ -8,10 +8,11 @@
8
8
  "detect.js",
9
9
  "metadata.js",
10
10
  "providers.js",
11
+ "session-graph.js",
11
12
  "stats.js",
12
13
  "lib/"
13
14
  ],
14
- "version": "0.5.1",
15
+ "version": "0.5.4",
15
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.",
16
17
  "type": "module",
17
18
  "main": "index.js",
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ const SESSION_TTL_MS = 2 * 60 * 60 * 1000
4
+ const MAX_SESSIONS = 50
5
+ const MIN_BYTES = 512
6
+
7
+ export function createSessionStore({ ttlMs = SESSION_TTL_MS, maxSessions = MAX_SESSIONS } = {}) {
8
+ const store = new Map()
9
+
10
+ function prune() {
11
+ const cutoff = Date.now() - ttlMs
12
+ for (const [k, bucket] of store) {
13
+ if (bucket.lastSeen < cutoff) store.delete(k)
14
+ }
15
+ }
16
+
17
+ function getBucket(key) {
18
+ if (!key) return null
19
+ prune()
20
+ let bucket = store.get(key)
21
+ if (bucket) {
22
+ bucket.lastSeen = Date.now()
23
+ return bucket
24
+ }
25
+ if (store.size >= maxSessions) {
26
+ const oldest = store.keys().next().value
27
+ store.delete(oldest)
28
+ }
29
+ bucket = { refs: new Map(), nextId: 0, lastSeen: Date.now() }
30
+ store.set(key, bucket)
31
+ return bucket
32
+ }
33
+
34
+ return { getBucket, prune, _store: store }
35
+ }
36
+
37
+ export function deriveSessionKey(headers) {
38
+ if (!headers) return null
39
+ const auth = headers.authorization || headers['x-api-key'] || ''
40
+ if (!auth) return null
41
+ return createHash('sha256').update(auth).digest('hex').slice(0, 16)
42
+ }
43
+
44
+ export function graphDeduplicateTargets(targets, bucket, { minBytes = MIN_BYTES } = {}) {
45
+ if (!bucket) return
46
+ for (const target of targets) {
47
+ if (target.skip || target.dedup || target.diffed || target.compressed) continue
48
+ if (typeof target.text !== 'string' || target.text.length < minBytes) continue
49
+
50
+ const hash = createHash('sha256').update(target.text).digest('hex').slice(0, 12)
51
+ const existing = bucket.refs.get(hash)
52
+ if (existing) {
53
+ target.compressed = `<tamp-file-ref id="${existing.id}" sha="${hash}" bytes="${target.text.length}"/>`
54
+ target.graphed = true
55
+ continue
56
+ }
57
+ bucket.nextId += 1
58
+ bucket.refs.set(hash, { id: bucket.nextId, bytes: target.text.length })
59
+ }
60
+ }