undohaven-core 0.1.2 → 0.1.6

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
@@ -1,7 +1,40 @@
1
1
  # undohaven-core
2
2
 
3
+ ![dsh-plugin](https://img.shields.io/badge/dsh--plugin-181717)
4
+
3
5
  Library behind the `undohaven` CLI and the `dsh-undohaven` plugin. Unofficial third-party code, compatible with dsh. Not an official dsh package.
4
6
 
5
7
  It chunks a dsh home, encrypts the chunks on the machine, and restores them. The passphrase never leaves the process. Publish and install the `undohaven` package if you want the command; this package is the engine those commands import.
6
8
 
7
9
  Homepage: https://undohaven.com/
10
+
11
+ ## Paid API (x402)
12
+
13
+ This package does not pay and does not hold a key. Agents that want the hosted pay-per-call API use `@x402/fetch` against `https://undohaven.com`. UndoHaven is an unofficial third-party, compatible with dsh.
14
+
15
+ `POST /x402/snapshot` and `GET /x402/restore/{id}` are 0.05 USDC. `POST /x402/pass` is 6 USDC for 30 days of Pro, including hosted S3. That is the Stripe Pro monthly price, with no discount.
16
+
17
+ `X402_PAYER_KEY` is the caller's key, not a service secret.
18
+
19
+ ```js
20
+ import { wrapFetchWithPaymentFromConfig } from '@x402/fetch'
21
+ import { ExactEvmScheme } from '@x402/evm'
22
+ import { privateKeyToAccount } from 'viem/accounts'
23
+
24
+ const account = privateKeyToAccount(process.env.X402_PAYER_KEY)
25
+ const paidFetch = wrapFetchWithPaymentFromConfig(fetch, {
26
+ schemes: [{ network: 'eip155:84532', client: new ExactEvmScheme(account) }],
27
+ })
28
+
29
+ const response = await paidFetch('https://undohaven.com/x402/snapshot', {
30
+ method: 'POST',
31
+ headers: {
32
+ 'content-type': 'application/json',
33
+ 'idempotency-key': 'snapshot-example-001',
34
+ },
35
+ body: JSON.stringify({
36
+ label: 'agent-snapshot',
37
+ files: { 'config.json': '{"model":"demo"}' },
38
+ }),
39
+ })
40
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "undohaven-core",
3
- "version": "0.1.2",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "description": "Snapshot, encryption, and restore engine for UndoHaven.",
6
6
  "engines": {
@@ -15,6 +15,7 @@
15
15
  "keywords": [
16
16
  "dsh",
17
17
  "dsh-plugin",
18
+ "dsh-plugins",
18
19
  "dsh-bundle",
19
20
  "backup",
20
21
  "snapshot",
package/src/cloud.js CHANGED
@@ -124,4 +124,16 @@ export class CloudClient {
124
124
  startTrial() {
125
125
  return this.request('POST', '/v1/trial', { body: {} }).then((res) => res.body)
126
126
  }
127
+
128
+ createS3Key(body) {
129
+ return this.request('POST', '/v1/s3/keys', { body }).then((res) => res.body)
130
+ }
131
+
132
+ listS3Keys() {
133
+ return this.request('GET', '/v1/s3/keys').then((res) => res.body.keys)
134
+ }
135
+
136
+ revokeS3Key(id) {
137
+ return this.request('POST', `/v1/s3/keys/${encodeURIComponent(id)}/revoke`, { body: {} }).then((res) => res.body)
138
+ }
127
139
  }
package/src/engine.js CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  } from './store.js'
38
38
  import { loadStorageConfig } from './byo.js'
39
39
  import { detectDshVersions } from './versions.js'
40
+ import { collectPluginState, savePluginState } from './plugins.js'
40
41
 
41
42
  const require = createRequire(import.meta.url)
42
43
  const TOOL_VERSION = require('../package.json').version
@@ -204,6 +205,13 @@ export async function createSnapshot(opts) {
204
205
  pinned: kind === 'pre-upgrade',
205
206
  cloud: false,
206
207
  }
208
+ try {
209
+ const plugins = await collectPluginState(opts.dshHome)
210
+ record.plugins = plugins
211
+ await savePluginState(dataDir, plugins)
212
+ } catch {
213
+ record.plugins = null
214
+ }
207
215
  await writeSnapshotRecord(dataDir, record)
208
216
  let cloudError = null
209
217
  if (opts.cloud) {
package/src/index.js CHANGED
@@ -62,4 +62,13 @@ export { PLANS, PRICES, PRICE_ENV, effectivePlan, versionLine, isCrossMajorDowng
62
62
  export { padBlob, unpadBlob, loadStorageConfig, saveStorageConfig, redactStorage, s3Call, newDeviceLabel } from './byo.js'
63
63
  export { UPGRADE, readPrompts, writePrompts } from './prompts.js'
64
64
  export { ANONYMOUS_FUNNEL, anonymousMeta, funnelOptedIn, limitNudgeLine, reportAnonymousEvent, showLimitNudge, TRIAL_URL } from './funnel.js'
65
- export { readPaddedChunk } from './store.js'
65
+ export { readPaddedChunk, readSnapshotRecord } from './store.js'
66
+ export {
67
+ applyDisabledFlags,
68
+ collectPluginState,
69
+ diffPluginState,
70
+ installProfile,
71
+ loadPluginState,
72
+ restorePluginState,
73
+ savePluginState,
74
+ } from './plugins.js'
package/src/plugins.js ADDED
@@ -0,0 +1,189 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { parseYaml } from './yaml.js'
5
+
6
+ const STATE_NAME = 'plugins.json'
7
+
8
+ function statePath(dataDir) {
9
+ return join(dataDir, STATE_NAME)
10
+ }
11
+
12
+ async function readJson(file) {
13
+ try {
14
+ return JSON.parse(await readFile(file, 'utf8'))
15
+ } catch (error) {
16
+ if (error.code === 'ENOENT') return null
17
+ throw error
18
+ }
19
+ }
20
+
21
+ async function readText(file) {
22
+ try {
23
+ return await readFile(file, 'utf8')
24
+ } catch (error) {
25
+ if (error.code === 'ENOENT') return ''
26
+ throw error
27
+ }
28
+ }
29
+
30
+ function disabledFlag(value) {
31
+ if (value === true) return true
32
+ if (value === false) return false
33
+ return null
34
+ }
35
+
36
+ function rowsOf(parsed) {
37
+ const list = Array.isArray(parsed) ? parsed : []
38
+ return list.filter((row) => row && typeof row === 'object' && typeof row.id === 'string').map((row) => ({
39
+ id: row.id,
40
+ name: typeof row.name === 'string' ? row.name : null,
41
+ disabled: disabledFlag(row.disabled),
42
+ }))
43
+ }
44
+
45
+ /** Read installed package specs and boolean enabled flags. Non-boolean disabled lines are left as null. */
46
+ export async function collectPluginState(dshHome) {
47
+ const { readdir } = await import('node:fs/promises')
48
+ const root = join(dshHome, 'profiles')
49
+ let entries = []
50
+ try {
51
+ entries = await readdir(root, { withFileTypes: true })
52
+ } catch (error) {
53
+ if (error.code !== 'ENOENT') throw error
54
+ }
55
+ const profiles = {}
56
+ for (const entry of entries) {
57
+ if (!entry.isDirectory()) continue
58
+ const dir = join(root, entry.name)
59
+ const pkg = await readJson(join(dir, 'package.json'))
60
+ const patch = await readText(join(dir, 'cordis.patch.yml'))
61
+ let parsed = []
62
+ if (patch.trim()) {
63
+ try {
64
+ parsed = parseYaml(patch)
65
+ } catch {
66
+ parsed = []
67
+ }
68
+ }
69
+ const dependencies = {}
70
+ for (const [name, spec] of Object.entries(pkg?.dependencies || {})) {
71
+ if (typeof spec === 'string') dependencies[name] = spec
72
+ }
73
+ const bundles = Array.isArray(pkg?.dsh?.profile?.bundles)
74
+ ? pkg.dsh.profile.bundles.filter((name) => typeof name === 'string')
75
+ : []
76
+ profiles[entry.name] = { dependencies, bundles, rows: rowsOf(parsed) }
77
+ }
78
+ return { version: 1, capturedAt: new Date().toISOString(), profiles }
79
+ }
80
+
81
+ export async function savePluginState(dataDir, state) {
82
+ await mkdir(dataDir, { recursive: true })
83
+ await writeFile(statePath(dataDir), JSON.stringify(state, null, 2), { mode: 0o600 })
84
+ }
85
+
86
+ export async function loadPluginState(dataDir) {
87
+ return readJson(statePath(dataDir))
88
+ }
89
+
90
+ function escapeRegExp(value) {
91
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
92
+ }
93
+
94
+ export function applyDisabledFlags(text, rows) {
95
+ let next = text || ''
96
+ const appended = []
97
+ for (const row of rows) {
98
+ if (typeof row.disabled !== 'boolean') continue
99
+ const idRe = new RegExp(`^(\\s*)-\\s+id:\\s*${escapeRegExp(row.id)}\\s*$`)
100
+ const lines = next.split('\n')
101
+ let found = false
102
+ for (let i = 0; i < lines.length; i += 1) {
103
+ const match = idRe.exec(lines[i])
104
+ if (!match) continue
105
+ found = true
106
+ const base = match[1].length
107
+ let disabledAt = -1
108
+ for (let j = i + 1; j < lines.length; j += 1) {
109
+ if (lines[j].trim() === '') continue
110
+ const indent = lines[j].match(/^\s*/)[0].length
111
+ if (indent <= base && lines[j].trim().startsWith('-')) break
112
+ if (/^\s*disabled:/.test(lines[j]) && !lines[j].includes('!!')) {
113
+ disabledAt = j
114
+ break
115
+ }
116
+ }
117
+ if (disabledAt >= 0) lines[disabledAt] = lines[disabledAt].replace(/disabled:\s*.*/, `disabled: ${row.disabled}`)
118
+ else if (row.disabled) lines.splice(i + 1, 0, `${' '.repeat(base + 2)}disabled: true`)
119
+ break
120
+ }
121
+ next = lines.join('\n')
122
+ if (!found) appended.push(row)
123
+ }
124
+ if (appended.length) {
125
+ const blocks = appended.map((row) => {
126
+ const lines = [`- id: ${row.id}`]
127
+ if (row.name) lines.push(` name: ${row.name}`)
128
+ lines.push(` disabled: ${row.disabled}`)
129
+ return lines.join('\n')
130
+ })
131
+ next = `${next.replace(/\s*$/, '')}\n${blocks.join('\n')}\n`
132
+ }
133
+ return next
134
+ }
135
+
136
+ export async function restorePluginState(dshHome, state) {
137
+ const changed = []
138
+ for (const [name, profile] of Object.entries(state?.profiles || {})) {
139
+ const dir = join(dshHome, 'profiles', name)
140
+ await mkdir(dir, { recursive: true })
141
+ const pkgPath = join(dir, 'package.json')
142
+ const pkg = await readJson(pkgPath) || { private: true }
143
+ pkg.dependencies = { ...(pkg.dependencies || {}), ...(profile.dependencies || {}) }
144
+ if (Array.isArray(profile.bundles) && profile.bundles.length) {
145
+ pkg.dsh = pkg.dsh || {}
146
+ pkg.dsh.profile = pkg.dsh.profile || {}
147
+ const bundles = new Set([...(pkg.dsh.profile.bundles || []), ...profile.bundles])
148
+ pkg.dsh.profile.bundles = [...bundles]
149
+ }
150
+ await writeFile(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`)
151
+ const patchPath = join(dir, 'cordis.patch.yml')
152
+ const patch = applyDisabledFlags(await readText(patchPath), profile.rows || [])
153
+ await writeFile(patchPath, patch.endsWith('\n') ? patch : `${patch}\n`)
154
+ changed.push(name)
155
+ }
156
+ return changed
157
+ }
158
+
159
+ export function diffPluginState(saved, current) {
160
+ const names = new Set([...Object.keys(saved?.profiles || {}), ...Object.keys(current?.profiles || {})])
161
+ const profiles = {}
162
+ for (const name of names) {
163
+ const before = saved?.profiles?.[name] || { dependencies: {}, bundles: [], rows: [] }
164
+ const after = current?.profiles?.[name] || { dependencies: {}, bundles: [], rows: [] }
165
+ const missing = Object.keys(before.dependencies).filter((dep) => !(dep in after.dependencies))
166
+ const extra = Object.keys(after.dependencies).filter((dep) => !(dep in before.dependencies))
167
+ const beforeRows = new Map((before.rows || []).map((row) => [row.id, row]))
168
+ const afterRows = new Map((after.rows || []).map((row) => [row.id, row]))
169
+ const disabledChanged = []
170
+ for (const [id, row] of beforeRows) {
171
+ if (typeof row.disabled !== 'boolean') continue
172
+ const now = afterRows.get(id)
173
+ const currentDisabled = now ? now.disabled : false
174
+ if (currentDisabled !== row.disabled) disabledChanged.push({ id, saved: row.disabled, current: currentDisabled === true })
175
+ }
176
+ profiles[name] = { missing, extra, disabledChanged }
177
+ }
178
+ return { profiles }
179
+ }
180
+
181
+ export function installProfile(profileDir, env = process.env) {
182
+ return new Promise((resolve) => {
183
+ const child = spawn('pnpm', ['install'], { cwd: profileDir, env, stdio: ['ignore', 'pipe', 'pipe'] })
184
+ let err = ''
185
+ child.stderr.on('data', (chunk) => { err += chunk })
186
+ child.on('error', (error) => resolve({ installed: false, reason: error.code === 'ENOENT' ? 'pnpm-missing' : error.message }))
187
+ child.on('close', (code) => resolve({ installed: code === 0, reason: code === 0 ? null : err.slice(0, 400) || `exit ${code}` }))
188
+ })
189
+ }
@@ -0,0 +1,35 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import test from 'node:test'
6
+ import { applyDisabledFlags, collectPluginState, diffPluginState, restorePluginState, savePluginState, loadPluginState } from '../src/plugins.js'
7
+
8
+ test('plugin snapshot keeps package specs and boolean enabled flags', async () => {
9
+ const root = await mkdtemp(join(tmpdir(), 'plugins-'))
10
+ const dsh = join(root, 'dsh')
11
+ const profile = join(dsh, 'profiles', 'desktop')
12
+ await mkdir(profile, { recursive: true })
13
+ await writeFile(join(profile, 'package.json'), JSON.stringify({
14
+ dependencies: { 'dsh-ce': '0.1.1' },
15
+ dsh: { profile: { bundles: ['dsh-ce'] } },
16
+ }))
17
+ await writeFile(join(profile, 'cordis.patch.yml'), '- id: ce\n name: dsh-ce\n disabled: false\n')
18
+ const state = await collectPluginState(dsh)
19
+ assert.equal(state.profiles.desktop.dependencies['dsh-ce'], '0.1.1')
20
+ assert.deepEqual(state.profiles.desktop.bundles, ['dsh-ce'])
21
+ assert.equal(state.profiles.desktop.rows[0].disabled, false)
22
+ await savePluginState(root, state)
23
+ await writeFile(join(profile, 'package.json'), JSON.stringify({ dependencies: {} }))
24
+ await writeFile(join(profile, 'cordis.patch.yml'), '- id: ce\n disabled: true\n')
25
+ const diff = diffPluginState(await loadPluginState(root), await collectPluginState(dsh))
26
+ assert.deepEqual(diff.profiles.desktop.missing, ['dsh-ce'])
27
+ assert.deepEqual(diff.profiles.desktop.disabledChanged, [{ id: 'ce', saved: false, current: true }])
28
+ await restorePluginState(dsh, state)
29
+ const restored = JSON.parse(await readFile(join(profile, 'package.json'), 'utf8'))
30
+ assert.equal(restored.dependencies['dsh-ce'], '0.1.1')
31
+ assert.match(await readFile(join(profile, 'cordis.patch.yml'), 'utf8'), /disabled: false/)
32
+ const expression = applyDisabledFlags('- id: keep\n disabled: !!js "ctx.get(\'x\')"\n', [{ id: 'keep', disabled: false }])
33
+ assert.match(expression, /!!js/)
34
+ await rm(root, { recursive: true, force: true })
35
+ })