pi-undohaven 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Local encrypted snapshots of pi sessions, settings, and extensions, with per-file restore, a path exclude toggle, and a safety snapshot before session-file changes. Pro accounts can upload the same ciphertext to the existing UndoHaven service.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # pi-undohaven
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Unofficial third-party snapshots for the [pi](https://pi.dev) coding agent. This package is not affiliated with pi's authors or with DeepSeek.
4
+
5
+ It uses UndoHaven's existing encryption and, when you are logged into the same UndoHaven account, the same server and the same Pro prices. One subscription covers dsh and pi. Keys stay on this machine. `.env`, `auth.json`, and other credential files are never put in a snapshot, and nothing is uploaded in plaintext.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:pi-undohaven@0.1.0
11
+ ```
12
+
13
+ Or run the CLI directly after it is on your path:
14
+
15
+ ```bash
16
+ pi-undohaven snapshot
17
+ pi-undohaven list
18
+ pi-undohaven restore --to <snapshot> --file sessions/one.jsonl
19
+ pi-undohaven migrate --to <snapshot> --dest ~/.pi/agent
20
+ pi-undohaven exclude sessions/scratch.jsonl
21
+ pi-undohaven doctor
22
+ pi-undohaven before pi-update
23
+ ```
24
+
25
+ Inside pi the same actions are `/undohaven`, `/undohaven list`, `/undohaven restore <id>`, `/undohaven exclude <path>`, and `/undohaven doctor`.
26
+
27
+ `exclude` toggles a path. Secrets stay excluded either way.
28
+
29
+ The extension also takes a local safety snapshot before session compaction, tree edits, switches, and forks. Run `pi-undohaven before pi-update` yourself before a pi upgrade or a session-file migration. Pi does not emit a hook for its own updater.
30
+
31
+ ## Tiers
32
+
33
+ Free keeps encrypted snapshots on this machine and prints diagnostics. Pro, using the account you already pay for, also stores that encrypted history on UndoHaven. A free login does not upload.
34
+
35
+ Set `UNDOHAVEN_PASSPHRASE` the first time so a key can be created. Point `UNDOHAVEN_HOME` at an existing UndoHaven data directory if you want pi and dsh to share keys. `PI_AGENT_DIR` selects the pi agent directory. The default is `~/.pi/agent`.
36
+
37
+ Node 22.19 or newer.
38
+
39
+ ## Server
40
+
41
+ No new API. Cloud history uses the existing `POST /v1/snapshots` and chunk upload, with snapshot kind `manual` or `safety`. The encrypted manifest says `tool: pi-undohaven`.
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import { diagnosePi, listPi, migratePi, piAgentDir, restorePi, safetySnapshot, snapshotPi, toggleExclude, piDataDir } from '../src/index.js'
3
+
4
+ function flag(name) {
5
+ const index = process.argv.indexOf(name)
6
+ if (index === -1) return undefined
7
+ return process.argv[index + 1]
8
+ }
9
+
10
+ const [command, ...rest] = process.argv.slice(2).filter((arg) => !arg.startsWith('--'))
11
+ const env = process.env
12
+ const agentDir = flag('--pi-home') || piAgentDir(env)
13
+ const projectDir = flag('--project')
14
+ const dataDir = piDataDir(agentDir, env)
15
+ const json = process.argv.includes('--json')
16
+
17
+ function emit(payload) {
18
+ if (json) console.log(JSON.stringify(payload))
19
+ else console.log(payload.text || JSON.stringify(payload, null, 2))
20
+ }
21
+
22
+ try {
23
+ if (!command || command === 'help') {
24
+ console.log(`pi-undohaven snapshot|list|restore|migrate|exclude|doctor|before
25
+ Unofficial third-party snapshots for pi. Not affiliated with pi's authors or DeepSeek.
26
+ Keys stay on this machine. .env and credential files are never snapshotted.`)
27
+ process.exit(0)
28
+ }
29
+ if (command === 'snapshot') {
30
+ const record = await snapshotPi({ env, agentDir, projectDir, dataDir })
31
+ emit({ text: record.id, ...record })
32
+ } else if (command === 'list') {
33
+ const rows = await listPi({ env, agentDir, dataDir })
34
+ emit({ text: rows.map((row) => `${row.id} ${row.kind} ${row.fileCount}`).join('\n'), rows })
35
+ } else if (command === 'restore' || command === 'migrate') {
36
+ const id = flag('--to') || rest[0]
37
+ const file = flag('--file')
38
+ if (!id) throw new Error('pass --to <snapshot>')
39
+ const fn = command === 'migrate' ? migratePi : restorePi
40
+ const result = await fn({ env, agentDir, projectDir, dataDir, id, paths: file ? [file] : undefined, destAgent: flag('--dest') || agentDir, destProject: projectDir })
41
+ emit({ text: `${result.files.length} files from ${result.id}`, ...result })
42
+ } else if (command === 'exclude') {
43
+ const pattern = rest[0]
44
+ if (!pattern) {
45
+ const { loadExcludes } = await import('../src/scan.js')
46
+ emit({ text: (await loadExcludes(dataDir)).join('\n'), patterns: await loadExcludes(dataDir) })
47
+ } else {
48
+ const result = await toggleExclude(dataDir, pattern)
49
+ emit({ text: result.enabled ? `excluding ${pattern}` : `including ${pattern}`, ...result })
50
+ }
51
+ } else if (command === 'doctor') {
52
+ const report = await diagnosePi({ env, agentDir, projectDir, dataDir })
53
+ emit({ text: `${report.files} files, plan ${report.plan}, secrets skipped ${report.skippedSecrets.length}`, ...report })
54
+ } else if (command === 'before') {
55
+ const result = await safetySnapshot({ env, agentDir, projectDir, dataDir, reason: rest[0] || 'manual' })
56
+ emit({ text: result.reused ? `reused ${result.id}` : result.id, ...result })
57
+ } else {
58
+ throw new Error(`unknown command ${command}`)
59
+ }
60
+ } catch (error) {
61
+ console.error(error.message || error)
62
+ process.exit(1)
63
+ }
@@ -0,0 +1,47 @@
1
+ import { diagnosePi, piAgentDir, piDataDir, restorePi, safetySnapshot, snapshotPi, toggleExclude } from '../src/index.js'
2
+
3
+ const RISKS = ['session_before_compact', 'session_before_tree', 'session_before_switch', 'session_before_fork']
4
+
5
+ export default function undohaven(pi) {
6
+ for (const event of RISKS) {
7
+ pi.on(event, async (_payload, ctx) => {
8
+ const projectDir = ctx.isProjectTrusted?.() ? `${ctx.cwd}/.pi` : undefined
9
+ await safetySnapshot({
10
+ agentDir: ctx.sessionManager?.getSessionDir?.() ? undefined : undefined,
11
+ projectDir,
12
+ reason: event,
13
+ env: process.env,
14
+ }).catch(() => {})
15
+ })
16
+ }
17
+ pi.registerCommand('undohaven', {
18
+ description: 'Snapshot, list, or restore pi state. Unofficial third-party; not affiliated with pi or DeepSeek.',
19
+ handler: async (args, ctx) => {
20
+ const [action, extra] = String(args || '').trim().split(/\s+/)
21
+ const projectDir = ctx.isProjectTrusted?.() ? `${ctx.cwd}/.pi` : undefined
22
+ if (action === 'list') {
23
+ const { listPi } = await import('../src/index.js')
24
+ const rows = await listPi({ projectDir, env: process.env })
25
+ ctx.ui.notify(rows.map((row) => row.id).join('\n') || 'no snapshots', 'info')
26
+ return
27
+ }
28
+ if (action === 'restore') {
29
+ const result = await restorePi({ id: extra, projectDir, env: process.env })
30
+ ctx.ui.notify(`restored ${result.files.length}`, 'info')
31
+ return
32
+ }
33
+ if (action === 'exclude' && extra) {
34
+ const result = await toggleExclude(piDataDir(piAgentDir()), extra)
35
+ ctx.ui.notify(result.enabled ? `excluding ${extra}` : `including ${extra}`, 'info')
36
+ return
37
+ }
38
+ if (action === 'doctor') {
39
+ const report = await diagnosePi({ projectDir, env: process.env })
40
+ ctx.ui.notify(`${report.files} files, plan ${report.plan}`, 'info')
41
+ return
42
+ }
43
+ const record = await snapshotPi({ projectDir, env: process.env })
44
+ ctx.ui.notify(record.id, 'info')
45
+ },
46
+ })
47
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "pi-undohaven",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Unofficial third-party encrypted snapshots for the pi coding agent. Not affiliated with pi's authors or DeepSeek.",
6
+ "engines": {
7
+ "node": ">=22.19.0"
8
+ },
9
+ "bin": {
10
+ "pi-undohaven": "./bin/pi-undohaven.js"
11
+ },
12
+ "exports": {
13
+ ".": "./src/index.js"
14
+ },
15
+ "pi": {
16
+ "extensions": ["./extensions/index.js"]
17
+ },
18
+ "keywords": [
19
+ "pi-package",
20
+ "backup",
21
+ "snapshot",
22
+ "restore",
23
+ "encryption"
24
+ ],
25
+ "dependencies": {
26
+ "undohaven-core": "0.1.12"
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "src",
31
+ "extensions",
32
+ "README.md",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "license": "MIT",
36
+ "homepage": "https://undohaven.com/",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/Antipas/undohaven.git",
40
+ "directory": "packages/pi"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/Antipas/undohaven/issues",
44
+ "email": "support@undohaven.com"
45
+ }
46
+ }
package/src/index.js ADDED
@@ -0,0 +1,142 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import {
4
+ cloudFromConfig,
5
+ createFileSnapshot,
6
+ establishKeys,
7
+ listFileSnapshots,
8
+ loadDek,
9
+ readFileManifest,
10
+ restoreFileSnapshot,
11
+ } from 'undohaven-core'
12
+ import { collectPiFiles, loadExcludes, piAgentDir, toggleExclude } from './scan.js'
13
+
14
+ const SAFETY_MS = 10 * 60 * 1000
15
+
16
+ export function dataDirFor(agentDir, env = process.env) {
17
+ if (env.UNDOHAVEN_HOME) return env.UNDOHAVEN_HOME
18
+ return join(agentDir, 'undohaven')
19
+ }
20
+
21
+ async function dekOf(dataDir, env) {
22
+ try {
23
+ return (await loadDek(dataDir)).dek
24
+ } catch (error) {
25
+ const pass = env.UNDOHAVEN_PASSPHRASE
26
+ if (!pass) throw error
27
+ const created = await establishKeys(dataDir, pass)
28
+ return created.dek
29
+ }
30
+ }
31
+
32
+ async function proCloud(dataDir) {
33
+ const { cloud } = await cloudFromConfig(dataDir)
34
+ if (!cloud) return null
35
+ try {
36
+ const account = await cloud.account()
37
+ if (account.plan === 'pro' || account.features?.guardRealtime || account.features?.machineMigration) return cloud
38
+ } catch {
39
+ return null
40
+ }
41
+ return null
42
+ }
43
+
44
+ export async function snapshotPi(opts) {
45
+ const agentDir = piAgentDir(opts.env, opts.agentDir)
46
+ const dataDir = opts.dataDir || dataDirFor(agentDir, opts.env)
47
+ const patterns = await loadExcludes(dataDir)
48
+ const { files, skipped } = await collectPiFiles(agentDir, opts.projectDir, patterns)
49
+ const dek = await dekOf(dataDir, opts.env || process.env)
50
+ const cloud = opts.cloud === false ? null : (opts.cloudClient === undefined ? await proCloud(dataDir) : opts.cloudClient)
51
+ const record = await createFileSnapshot({
52
+ dataDir,
53
+ dek,
54
+ files,
55
+ kind: opts.kind || 'manual',
56
+ tags: ['pi', ...(opts.tags || [])],
57
+ tool: 'pi-undohaven',
58
+ cloud,
59
+ })
60
+ return { ...record, skipped, cloud: Boolean(record.cloud), local: true }
61
+ }
62
+
63
+ export async function listPi(opts) {
64
+ const agentDir = piAgentDir(opts.env, opts.agentDir)
65
+ const dataDir = opts.dataDir || dataDirFor(agentDir, opts.env)
66
+ return listFileSnapshots(dataDir)
67
+ }
68
+
69
+ export async function restorePi(opts) {
70
+ const agentDir = piAgentDir(opts.env, opts.agentDir)
71
+ const dataDir = opts.dataDir || dataDirFor(agentDir, opts.env)
72
+ const dek = await dekOf(dataDir, opts.env || process.env)
73
+ return restoreFileSnapshot({
74
+ dataDir,
75
+ dek,
76
+ id: opts.id,
77
+ paths: opts.paths,
78
+ dest: { agent: opts.destAgent || agentDir, project: opts.destProject || opts.projectDir || agentDir },
79
+ })
80
+ }
81
+
82
+ export async function migratePi(opts) {
83
+ await snapshotPi({ ...opts, agentDir: opts.destAgent, kind: 'safety', tags: ['pi', 'before-migrate'], cloud: false })
84
+ return restorePi(opts)
85
+ }
86
+
87
+ export async function safetySnapshot(opts) {
88
+ const agentDir = piAgentDir(opts.env, opts.agentDir)
89
+ const dataDir = opts.dataDir || dataDirFor(agentDir, opts.env)
90
+ const reason = opts.reason || 'risk'
91
+ const statePath = join(dataDir, 'pi-safety.json')
92
+ let state = {}
93
+ try {
94
+ state = JSON.parse(await readFile(statePath, 'utf8'))
95
+ } catch {
96
+ state = {}
97
+ }
98
+ const previous = state[reason]
99
+ if (previous && Date.now() - previous.at < SAFETY_MS) return { id: previous.id, reused: true }
100
+ const record = await snapshotPi({ ...opts, kind: 'safety', tags: ['pi', 'before', reason], cloud: false })
101
+ state[reason] = { id: record.id, at: Date.now() }
102
+ await mkdir(dataDir, { recursive: true })
103
+ await writeFile(statePath, JSON.stringify(state), { mode: 0o600 })
104
+ return { id: record.id, reused: false }
105
+ }
106
+
107
+ export async function diagnosePi(opts) {
108
+ const agentDir = piAgentDir(opts.env, opts.agentDir)
109
+ const dataDir = opts.dataDir || dataDirFor(agentDir, opts.env)
110
+ const patterns = await loadExcludes(dataDir)
111
+ const { files, skipped } = await collectPiFiles(agentDir, opts.projectDir, patterns)
112
+ let unlocked = true
113
+ try {
114
+ await loadDek(dataDir)
115
+ } catch {
116
+ unlocked = false
117
+ }
118
+ const { cloud, config } = await cloudFromConfig(dataDir)
119
+ let plan = 'free'
120
+ if (cloud) {
121
+ try {
122
+ const account = await cloud.account()
123
+ plan = account.plan || 'free'
124
+ } catch {
125
+ plan = 'unknown'
126
+ }
127
+ }
128
+ return {
129
+ agentDir,
130
+ files: files.length,
131
+ sessions: files.filter((file) => file.rel.startsWith('sessions/')).length,
132
+ skippedSecrets: skipped,
133
+ excludes: patterns,
134
+ unlocked,
135
+ loggedIn: Boolean(config.accessToken),
136
+ plan,
137
+ cloudHistory: plan === 'pro',
138
+ }
139
+ }
140
+
141
+ export { toggleExclude, loadExcludes, piAgentDir, dataDirFor as piDataDir }
142
+ export { readFileManifest }
package/src/scan.js ADDED
@@ -0,0 +1,82 @@
1
+ import { readdir, readFile, stat, writeFile, mkdir } from 'node:fs/promises'
2
+ import { join, relative, sep } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+
5
+ function asRel(root, abs) {
6
+ return relative(root, abs).split(sep).join('/')
7
+ }
8
+
9
+ const SECRET_NAME = /^(?:\.env(?:\..*)?|credentials(?:\.(?:json|ya?ml))?|auth\.json|secrets\.json|id_rsa|id_ed25519|.*\.(?:pem|key))$/i
10
+
11
+ export function piAgentDir(env = process.env, configured) {
12
+ if (configured) return configured
13
+ if (env.PI_AGENT_DIR) return env.PI_AGENT_DIR
14
+ return join(homedir(), '.pi', 'agent')
15
+ }
16
+
17
+ export function isSecretPath(rel) {
18
+ const name = rel.split('/').pop()
19
+ return SECRET_NAME.test(name)
20
+ }
21
+
22
+ export function isExcluded(rel, patterns) {
23
+ if (rel.split('/').includes('node_modules') || rel.split('/').includes('.git')) return true
24
+ if (isSecretPath(rel)) return true
25
+ return (patterns || []).some((pattern) => rel === pattern || rel.startsWith(`${pattern.replace(/\/$/, '')}/`))
26
+ }
27
+
28
+ async function walk(root, dir, out, patterns, skipped) {
29
+ let entries = []
30
+ try {
31
+ entries = await readdir(dir, { withFileTypes: true })
32
+ } catch (error) {
33
+ if (error.code !== 'ENOENT') throw error
34
+ return
35
+ }
36
+ for (const entry of entries) {
37
+ const abs = join(dir, entry.name)
38
+ const rel = asRel(root, abs)
39
+ if (entry.isDirectory()) {
40
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'undohaven') continue
41
+ await walk(root, abs, out, patterns, skipped)
42
+ continue
43
+ }
44
+ if (!entry.isFile()) continue
45
+ if (isExcluded(rel, patterns)) {
46
+ if (isSecretPath(rel)) skipped.push(rel)
47
+ continue
48
+ }
49
+ const info = await stat(abs)
50
+ out.push({ abs, rel, mode: info.mode, mtimeMs: info.mtimeMs })
51
+ }
52
+ }
53
+
54
+ export async function collectPiFiles(agentDir, projectDir, patterns) {
55
+ const files = []
56
+ const skipped = []
57
+ await walk(agentDir, agentDir, files, patterns, skipped)
58
+ const tagged = files.map((file) => ({ ...file, root: 'agent' }))
59
+ if (projectDir) {
60
+ const projectFiles = []
61
+ await walk(projectDir, projectDir, projectFiles, patterns, skipped)
62
+ tagged.push(...projectFiles.map((file) => ({ ...file, root: 'project' })))
63
+ }
64
+ return { files: tagged, skipped }
65
+ }
66
+
67
+ export async function loadExcludes(dataDir) {
68
+ try {
69
+ const parsed = JSON.parse(await readFile(join(dataDir, 'exclude.json'), 'utf8'))
70
+ return Array.isArray(parsed) ? parsed.map(String) : []
71
+ } catch {
72
+ return []
73
+ }
74
+ }
75
+
76
+ export async function toggleExclude(dataDir, pattern) {
77
+ const current = await loadExcludes(dataDir)
78
+ const next = current.includes(pattern) ? current.filter((item) => item !== pattern) : [...current, pattern]
79
+ await mkdir(dataDir, { recursive: true, mode: 0o700 })
80
+ await writeFile(join(dataDir, 'exclude.json'), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
81
+ return { patterns: next, enabled: next.includes(pattern) }
82
+ }