@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.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/LICENSE +21 -0
- package/README.md +45 -2
- package/client.js +646 -0
- package/dist/cdc.js +73 -0
- package/dist/cli.js +352 -0
- package/dist/context.js +262 -0
- package/dist/cron.js +98 -0
- package/dist/desk-ledger.js +91 -0
- package/dist/desk.js +518 -0
- package/dist/engine.js +733 -0
- package/dist/errors.js +46 -0
- package/dist/fs-safe.js +100 -0
- package/dist/http-plugin.js +33 -0
- package/dist/http.js +593 -0
- package/dist/inbox.js +194 -0
- package/dist/index.js +411 -0
- package/dist/live-diff.js +188 -0
- package/dist/live-snapshot.js +152 -0
- package/dist/provision.js +44 -0
- package/dist/router-plugin.js +14 -0
- package/dist/runtime-registry.js +36 -0
- package/dist/session-files.js +111 -0
- package/dist/session-previews.js +111 -0
- package/dist/store.js +598 -0
- package/dist/tools.js +357 -0
- package/dist/triggers.js +874 -0
- package/dist/work-admit.js +128 -0
- package/dist/work-child.js +73 -0
- package/dist/work-durable.js +53 -0
- package/dist/work-http.js +287 -0
- package/dist/work-ledger.js +217 -0
- package/dist/work-mock-host.js +187 -0
- package/dist/work-mock.js +131 -0
- package/dist/work-tickets.js +1042 -0
- package/dist/work-tools.js +150 -0
- package/dist/work-worker.js +1108 -0
- package/fixtures/mock-llm.mjs +267 -0
- package/package.json +54 -4
- package/public/assets/index-Be82iGwe.css +1 -0
- package/public/assets/index-ByU9a3Lh.js +61 -0
- package/public/index.html +14 -0
package/dist/cdc.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* FastCDC, same gear table and normalized masks as the weterm runner.
|
|
4
|
+
* Min 4KB, average 16KB, max 64KB. A buffer at or under the minimum is one chunk.
|
|
5
|
+
* Boundaries come from the bytes, so an insert changes only the chunks around it.
|
|
6
|
+
*/
|
|
7
|
+
export const CDC_MIN = 4096;
|
|
8
|
+
export const CDC_AVG = 16384;
|
|
9
|
+
export const CDC_MAX = 65536;
|
|
10
|
+
export const GEAR = new Uint32Array(256);
|
|
11
|
+
let seed = 1;
|
|
12
|
+
for (let i = 0; i < 256; i++) {
|
|
13
|
+
seed = Math.imul(seed, 1664525) + 1013904223;
|
|
14
|
+
GEAR[i] = seed;
|
|
15
|
+
}
|
|
16
|
+
export function chunkBuffer(data) {
|
|
17
|
+
const chunks = [];
|
|
18
|
+
const maskStrict = (1 << 16) - 1;
|
|
19
|
+
const maskNormal = (1 << 14) - 1;
|
|
20
|
+
const maskLenient = (1 << 12) - 1;
|
|
21
|
+
let offset = 0;
|
|
22
|
+
const n = data.length;
|
|
23
|
+
while (offset < n) {
|
|
24
|
+
if (n - offset <= CDC_MIN) {
|
|
25
|
+
chunks.push({ offset, length: n - offset });
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
let hash = 0;
|
|
29
|
+
let chunkLen = CDC_MIN;
|
|
30
|
+
while (chunkLen < CDC_MAX && offset + chunkLen < n) {
|
|
31
|
+
const b = data[offset + chunkLen];
|
|
32
|
+
hash = ((hash << 1) + GEAR[b]) | 0;
|
|
33
|
+
let mask = maskNormal;
|
|
34
|
+
if (chunkLen < CDC_AVG / 2)
|
|
35
|
+
mask = maskStrict;
|
|
36
|
+
else if (chunkLen >= CDC_AVG * 1.5)
|
|
37
|
+
mask = maskLenient;
|
|
38
|
+
if ((hash & mask) === 0) {
|
|
39
|
+
chunkLen++;
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
chunkLen++;
|
|
43
|
+
}
|
|
44
|
+
chunks.push({ offset, length: chunkLen });
|
|
45
|
+
offset += chunkLen;
|
|
46
|
+
}
|
|
47
|
+
return chunks;
|
|
48
|
+
}
|
|
49
|
+
/** Content-addressed cut of one buffer. The epoch is the hash of the ordered chunk hashes. */
|
|
50
|
+
export function planChunks(data) {
|
|
51
|
+
const parts = chunkBuffer(data);
|
|
52
|
+
const hashes = [];
|
|
53
|
+
const chunks = new Map();
|
|
54
|
+
for (const part of parts) {
|
|
55
|
+
const bytes = Buffer.from(data.subarray(part.offset, part.offset + part.length));
|
|
56
|
+
const hash = createHash('sha256').update(bytes).digest('hex');
|
|
57
|
+
hashes.push(hash);
|
|
58
|
+
if (!chunks.has(hash))
|
|
59
|
+
chunks.set(hash, bytes);
|
|
60
|
+
}
|
|
61
|
+
const epoch = createHash('sha256').update(hashes.join('\n')).digest('hex');
|
|
62
|
+
return { epoch, hashes, chunks, totalSize: data.length };
|
|
63
|
+
}
|
|
64
|
+
export function assembleChunks(hashes, chunks) {
|
|
65
|
+
const parts = [];
|
|
66
|
+
for (const hash of hashes) {
|
|
67
|
+
const body = chunks.get(hash);
|
|
68
|
+
if (!body)
|
|
69
|
+
return null;
|
|
70
|
+
parts.push(body);
|
|
71
|
+
}
|
|
72
|
+
return Buffer.concat(parts);
|
|
73
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { openStore, pidAlive, restoreBackup } from "./store.js";
|
|
6
|
+
import { createEngine } from "./engine.js";
|
|
7
|
+
import { toolDefinitions } from "./tools.js";
|
|
8
|
+
import { createTriggers } from "./triggers.js";
|
|
9
|
+
import { createWorkRuntime } from "./work-worker.js";
|
|
10
|
+
/**
|
|
11
|
+
* Admin-command usage. `program` is the command the operator typed, usually `dsh-bot`.
|
|
12
|
+
* @param {string} [program]
|
|
13
|
+
*/
|
|
14
|
+
export function usage(program = 'dsh-bot') {
|
|
15
|
+
return `usage:
|
|
16
|
+
${program} persona confirm --data-dir DIR --file SOUL.md [--session ID]
|
|
17
|
+
${program} persona show --data-dir DIR
|
|
18
|
+
${program} session bind --data-dir DIR --session ID [--persona ID]
|
|
19
|
+
${program} memory remember --data-dir DIR --session ID --content TEXT --key KEY [--target fact|memory] [--title TEXT] [--priority N]
|
|
20
|
+
${program} memory correct --data-dir DIR --session ID --id N --content TEXT --revision N --key KEY [--target fact|memory]
|
|
21
|
+
${program} memory forget --data-dir DIR --session ID --id N --revision N --key KEY [--target fact|memory]
|
|
22
|
+
${program} memory list --data-dir DIR --session ID
|
|
23
|
+
${program} skill register --data-dir DIR --session ID --id skill-id [--scope public|private]
|
|
24
|
+
${program} skill enable|disable|revoke --data-dir DIR --session ID --id skill-id
|
|
25
|
+
${program} skill list --data-dir DIR --session ID
|
|
26
|
+
${program} status --data-dir DIR [--session ID]
|
|
27
|
+
${program} message allow|deny --data-dir DIR --target ID --from ID
|
|
28
|
+
${program} message list --data-dir DIR [--session ID] [--correlation ID]
|
|
29
|
+
${program} message send --data-dir DIR --from ID --target ID --text TEXT --key KEY
|
|
30
|
+
${program} work dispatch --data-dir DIR --session ID --text TEXT [--key KEY]
|
|
31
|
+
${program} timer add --data-dir DIR --session ID (--at ISO | --cron EXPR) [--timezone Asia/Shanghai] [--note TEXT]
|
|
32
|
+
${program} timer list|pause|resume|delete --data-dir DIR [--id ID]
|
|
33
|
+
${program} webhook register --data-dir DIR --session ID
|
|
34
|
+
${program} webhook list|revoke --data-dir DIR [--id ID]
|
|
35
|
+
${program} backup --data-dir DIR [--to DIR]
|
|
36
|
+
${program} restore --data-dir DIR --from DIR`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Run one admin command. Does not start DSH.
|
|
40
|
+
* Sets `process.exitCode` and returns it.
|
|
41
|
+
* @param {string[]} argv
|
|
42
|
+
* @param {{ program?: string }} [options]
|
|
43
|
+
*/
|
|
44
|
+
export async function run(argv, options = {}) {
|
|
45
|
+
const program = options.program || 'dsh-bot';
|
|
46
|
+
const command = argv[0];
|
|
47
|
+
const action = argv[1] && !argv[1].startsWith('--') ? argv[1] : '';
|
|
48
|
+
const flags = flagsOf(action ? argv.slice(2) : argv.slice(1));
|
|
49
|
+
/** @type {import('./store.js').Store | null} */
|
|
50
|
+
let triggerStore = null;
|
|
51
|
+
/**
|
|
52
|
+
* Operator entry. `--session` is the session the operator is managing.
|
|
53
|
+
* Model tools ignore a different id and use the host agent id instead.
|
|
54
|
+
* @param {import('./engine.js').Engine} engine
|
|
55
|
+
* @param {string} name
|
|
56
|
+
* @param {Record<string, unknown>} args
|
|
57
|
+
*/
|
|
58
|
+
async function runTool(engine, name, args) {
|
|
59
|
+
const sessionId = required(flags, 'session');
|
|
60
|
+
const tools = Object.fromEntries(toolDefinitions(engine, () => 0).map(item => [item.name, item]));
|
|
61
|
+
const result = await tools[name].execute(args, { agent: { id: sessionId }, signal: AbortSignal.timeout(10000) });
|
|
62
|
+
console.log(JSON.stringify(result, null, 2));
|
|
63
|
+
engine.store.close();
|
|
64
|
+
if (!result || result.ok !== true)
|
|
65
|
+
process.exitCode = 1;
|
|
66
|
+
}
|
|
67
|
+
function dataDir() {
|
|
68
|
+
const dir = flags['data-dir'] ?? process.env.SESSION_FOUNDATIONS_DIR ?? '';
|
|
69
|
+
if (dir === '')
|
|
70
|
+
throw new Error('pass --data-dir or SESSION_FOUNDATIONS_DIR');
|
|
71
|
+
return dir;
|
|
72
|
+
}
|
|
73
|
+
function openEngine() {
|
|
74
|
+
return createEngine(openStore(dataDir()));
|
|
75
|
+
}
|
|
76
|
+
function openTriggers() {
|
|
77
|
+
triggerStore = openStore(dataDir());
|
|
78
|
+
return createTriggers(triggerStore, {
|
|
79
|
+
resident: false,
|
|
80
|
+
push: async () => ({ ok: false, error: 'cli-does-not-deliver' }),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function triggersClose() {
|
|
84
|
+
triggerStore?.close();
|
|
85
|
+
triggerStore = null;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
if (command === 'persona' && action === 'confirm') {
|
|
89
|
+
const engine = openEngine();
|
|
90
|
+
const text = flags.file ? readFileSync(flags.file, 'utf8') : flags.text;
|
|
91
|
+
if (!text)
|
|
92
|
+
throw new Error('pass --file or --text');
|
|
93
|
+
const persona = engine.confirmPersona(text, flags.note);
|
|
94
|
+
if (flags.session)
|
|
95
|
+
engine.bindPersona(flags.session, persona.id);
|
|
96
|
+
console.log(JSON.stringify({ ok: true, persona }, null, 2));
|
|
97
|
+
engine.store.close();
|
|
98
|
+
}
|
|
99
|
+
else if (command === 'persona' && action === 'show') {
|
|
100
|
+
const engine = openEngine();
|
|
101
|
+
const persona = engine.latestPersona();
|
|
102
|
+
const body = persona ? engine.store.readBlob('persona', persona.content_hash)?.toString('utf8') : '';
|
|
103
|
+
console.log(JSON.stringify({ ok: true, persona, body }, null, 2));
|
|
104
|
+
engine.store.close();
|
|
105
|
+
}
|
|
106
|
+
else if (command === 'session' && action === 'bind') {
|
|
107
|
+
const engine = openEngine();
|
|
108
|
+
const binding = engine.bindPersona(required(flags, 'session'), flags.persona ? Number(flags.persona) : engine.latestPersona()?.id ?? null);
|
|
109
|
+
console.log(JSON.stringify({ ok: true, binding }, null, 2));
|
|
110
|
+
engine.store.close();
|
|
111
|
+
}
|
|
112
|
+
else if (command === 'memory' && action === 'remember') {
|
|
113
|
+
const engine = openEngine();
|
|
114
|
+
await runTool(engine, 'foundations_remember', {
|
|
115
|
+
target: flags.target === 'memory' ? 'memory' : 'fact',
|
|
116
|
+
content: required(flags, 'content'),
|
|
117
|
+
idempotencyKey: required(flags, 'key'),
|
|
118
|
+
...(flags.title ? { title: flags.title } : {}),
|
|
119
|
+
...(flags.priority ? { priority: Number(flags.priority) } : {}),
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
else if (command === 'memory' && action === 'correct') {
|
|
123
|
+
const engine = openEngine();
|
|
124
|
+
await runTool(engine, 'foundations_correct', {
|
|
125
|
+
target: flags.target === 'memory' ? 'memory' : 'fact',
|
|
126
|
+
id: Number(required(flags, 'id')),
|
|
127
|
+
content: required(flags, 'content'),
|
|
128
|
+
expectedRevision: Number(required(flags, 'revision')),
|
|
129
|
+
idempotencyKey: required(flags, 'key'),
|
|
130
|
+
...(flags.title ? { title: flags.title } : {}),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
else if (command === 'memory' && action === 'forget') {
|
|
134
|
+
const engine = openEngine();
|
|
135
|
+
await runTool(engine, 'foundations_forget', {
|
|
136
|
+
target: flags.target === 'memory' ? 'memory' : 'fact',
|
|
137
|
+
id: Number(required(flags, 'id')),
|
|
138
|
+
expectedRevision: Number(required(flags, 'revision')),
|
|
139
|
+
idempotencyKey: required(flags, 'key'),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
else if (command === 'memory' && action === 'list') {
|
|
143
|
+
const engine = openEngine();
|
|
144
|
+
const sessionId = required(flags, 'session');
|
|
145
|
+
engine.ensureSession(sessionId);
|
|
146
|
+
console.log(JSON.stringify({
|
|
147
|
+
facts: engine.store.db.prepare('SELECT id, status, revision, priority, content FROM facts WHERE session_id = ? ORDER BY id').all(sessionId),
|
|
148
|
+
memories: engine.store.db.prepare('SELECT id, status, revision, title, content FROM memories WHERE session_id = ? ORDER BY id').all(sessionId),
|
|
149
|
+
state: engine.statePayload(sessionId),
|
|
150
|
+
}, null, 2));
|
|
151
|
+
engine.store.close();
|
|
152
|
+
}
|
|
153
|
+
else if (command === 'skill' && action === 'register') {
|
|
154
|
+
const engine = openEngine();
|
|
155
|
+
const row = engine.registerSkillFromDisk(required(flags, 'session'), flags.scope === 'private' ? 'private' : 'public', required(flags, 'id'));
|
|
156
|
+
console.log(JSON.stringify({ ok: true, skill: row }, null, 2));
|
|
157
|
+
engine.store.close();
|
|
158
|
+
}
|
|
159
|
+
else if (command === 'skill' && (action === 'enable' || action === 'disable' || action === 'revoke')) {
|
|
160
|
+
const engine = openEngine();
|
|
161
|
+
const row = engine.setSkillFlags(required(flags, 'session'), required(flags, 'id'), {
|
|
162
|
+
enabled: action === 'disable' ? false : action === 'enable' ? true : undefined,
|
|
163
|
+
revoked: action === 'revoke' ? true : undefined,
|
|
164
|
+
});
|
|
165
|
+
console.log(JSON.stringify({ ok: true, skill: row }, null, 2));
|
|
166
|
+
engine.store.close();
|
|
167
|
+
}
|
|
168
|
+
else if (command === 'skill' && action === 'list') {
|
|
169
|
+
const engine = openEngine();
|
|
170
|
+
const rows = engine.store.db.prepare('SELECT * FROM skill_bindings WHERE session_id = ? ORDER BY skill_id').all(required(flags, 'session'));
|
|
171
|
+
console.log(JSON.stringify({ ok: true, skills: rows }, null, 2));
|
|
172
|
+
engine.store.close();
|
|
173
|
+
}
|
|
174
|
+
else if (command === 'message' && action === 'allow') {
|
|
175
|
+
const triggers = openTriggers();
|
|
176
|
+
console.log(JSON.stringify(triggers.allow(required(flags, 'target'), required(flags, 'from')), null, 2));
|
|
177
|
+
triggersClose();
|
|
178
|
+
}
|
|
179
|
+
else if (command === 'message' && action === 'deny') {
|
|
180
|
+
const triggers = openTriggers();
|
|
181
|
+
console.log(JSON.stringify(triggers.deny(required(flags, 'target'), required(flags, 'from')), null, 2));
|
|
182
|
+
triggersClose();
|
|
183
|
+
}
|
|
184
|
+
else if (command === 'message' && action === 'list') {
|
|
185
|
+
const triggers = openTriggers();
|
|
186
|
+
console.log(JSON.stringify({ ok: true, acl: triggers.listAcl(), deliveries: triggers.listDeliveries(flags.session ?? '', flags.correlation ?? '') }, null, 2));
|
|
187
|
+
triggersClose();
|
|
188
|
+
}
|
|
189
|
+
else if (command === 'work' && action === 'dispatch') {
|
|
190
|
+
const engine = openEngine();
|
|
191
|
+
const sessionId = required(flags, 'session');
|
|
192
|
+
if (!engine.isBot(sessionId)) {
|
|
193
|
+
console.log(JSON.stringify({ ok: false, code: 'FORBIDDEN', message: 'An ordinary session stays on one loop and cannot dispatch work.' }, null, 2));
|
|
194
|
+
engine.store.close();
|
|
195
|
+
process.exitCode = 1;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
const work = createWorkRuntime(engine.store, engine, { resident: false, push: async () => ({ ok: false, ambiguous: true }) });
|
|
199
|
+
const result = await work.dispatch(sessionId, {
|
|
200
|
+
briefing: required(flags, 'text'),
|
|
201
|
+
idempotencyKey: flags.key,
|
|
202
|
+
});
|
|
203
|
+
console.log(JSON.stringify(result, null, 2));
|
|
204
|
+
engine.store.close();
|
|
205
|
+
if (result.ok !== true)
|
|
206
|
+
process.exitCode = 1;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
else if (command === 'message' && action === 'send') {
|
|
210
|
+
const triggers = openTriggers();
|
|
211
|
+
const result = await triggers.send(required(flags, 'from'), {
|
|
212
|
+
targetSessionId: required(flags, 'target'),
|
|
213
|
+
text: required(flags, 'text'),
|
|
214
|
+
idempotencyKey: required(flags, 'key'),
|
|
215
|
+
});
|
|
216
|
+
console.log(JSON.stringify({
|
|
217
|
+
...result,
|
|
218
|
+
...('status' in result && result.status === 'intent' ? {
|
|
219
|
+
queued: false,
|
|
220
|
+
note: 'Only the intent was written. A resident DSH host reconciles it and then followup reaches the native inbox. This process will not execute after it exits.',
|
|
221
|
+
} : {}),
|
|
222
|
+
}, null, 2));
|
|
223
|
+
triggersClose();
|
|
224
|
+
if (!result.ok)
|
|
225
|
+
process.exitCode = 1;
|
|
226
|
+
}
|
|
227
|
+
else if (command === 'timer' && (action === 'add' || action === 'list' || action === 'pause' || action === 'resume' || action === 'delete')) {
|
|
228
|
+
const triggers = openTriggers();
|
|
229
|
+
if (action === 'add') {
|
|
230
|
+
const result = triggers.addSchedule({
|
|
231
|
+
sessionId: required(flags, 'session'),
|
|
232
|
+
kind: flags.cron ? 'cron' : 'one-shot',
|
|
233
|
+
cron: flags.cron,
|
|
234
|
+
runAt: flags.at,
|
|
235
|
+
timezone: flags.timezone,
|
|
236
|
+
note: flags.note ?? '',
|
|
237
|
+
});
|
|
238
|
+
console.log(JSON.stringify({
|
|
239
|
+
...result,
|
|
240
|
+
note: 'The definition is in SQLite. Only a resident host tick performs the followup. The CLI does not deliver it.',
|
|
241
|
+
}, null, 2));
|
|
242
|
+
if (!result.ok)
|
|
243
|
+
process.exitCode = 1;
|
|
244
|
+
}
|
|
245
|
+
else if (action === 'list')
|
|
246
|
+
console.log(JSON.stringify({ ok: true, timers: triggers.listSchedules() }, null, 2));
|
|
247
|
+
else if (action === 'pause')
|
|
248
|
+
console.log(JSON.stringify(triggers.setScheduleEnabled(required(flags, 'id'), false), null, 2));
|
|
249
|
+
else if (action === 'resume')
|
|
250
|
+
console.log(JSON.stringify(triggers.setScheduleEnabled(required(flags, 'id'), true), null, 2));
|
|
251
|
+
else
|
|
252
|
+
console.log(JSON.stringify(triggers.deleteSchedule(required(flags, 'id')), null, 2));
|
|
253
|
+
triggersClose();
|
|
254
|
+
}
|
|
255
|
+
else if (command === 'webhook' && (action === 'register' || action === 'revoke' || action === 'list')) {
|
|
256
|
+
const triggers = openTriggers();
|
|
257
|
+
if (action === 'register') {
|
|
258
|
+
const result = triggers.registerWebhook(required(flags, 'session'));
|
|
259
|
+
console.log(JSON.stringify(result.ok ? { ok: true, hook: result.hook } : result, null, 2));
|
|
260
|
+
if (!result.ok)
|
|
261
|
+
process.exitCode = 1;
|
|
262
|
+
}
|
|
263
|
+
else if (action === 'revoke')
|
|
264
|
+
console.log(JSON.stringify(triggers.revokeWebhook(required(flags, 'id')), null, 2));
|
|
265
|
+
else
|
|
266
|
+
console.log(JSON.stringify({ ok: true, webhooks: triggers.listWebhooks() }, null, 2));
|
|
267
|
+
triggersClose();
|
|
268
|
+
}
|
|
269
|
+
else if (command === 'status') {
|
|
270
|
+
const engine = openEngine();
|
|
271
|
+
const sessionId = flags.session ?? '';
|
|
272
|
+
const binding = sessionId ? engine.binding(sessionId) : null;
|
|
273
|
+
console.log(JSON.stringify({
|
|
274
|
+
ok: true,
|
|
275
|
+
dataDir: dataDir(),
|
|
276
|
+
persona: engine.latestPersona(),
|
|
277
|
+
binding,
|
|
278
|
+
view: binding ? engine.currentView(sessionId) : null,
|
|
279
|
+
sandbox: false,
|
|
280
|
+
}, null, 2));
|
|
281
|
+
engine.store.close();
|
|
282
|
+
}
|
|
283
|
+
else if (command === 'backup') {
|
|
284
|
+
const engine = openEngine();
|
|
285
|
+
const dest = flags.to ?? join(dataDir(), 'backups', new Date().toISOString().replace(/[:.]/g, '-'));
|
|
286
|
+
const manifest = await engine.store.backupTo(dest);
|
|
287
|
+
console.log(JSON.stringify({ ok: true, dest, manifest }, null, 2));
|
|
288
|
+
engine.store.close();
|
|
289
|
+
}
|
|
290
|
+
else if (command === 'restore') {
|
|
291
|
+
const root = dataDir();
|
|
292
|
+
const owner = readOwner(root);
|
|
293
|
+
await restoreBackup(root, required(flags, 'from'), owner);
|
|
294
|
+
console.log(JSON.stringify({ ok: true, dataDir: root, from: flags.from }, null, 2));
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
console.error(usage(program));
|
|
298
|
+
process.exitCode = 2;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
303
|
+
process.exitCode = 1;
|
|
304
|
+
}
|
|
305
|
+
return process.exitCode ?? 0;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* @param {Record<string, string>} bag
|
|
309
|
+
* @param {string} name
|
|
310
|
+
*/
|
|
311
|
+
function required(bag, name) {
|
|
312
|
+
const value = bag[name];
|
|
313
|
+
if (!value)
|
|
314
|
+
throw new Error(`missing --${name}`);
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* @param {string[]} argv
|
|
319
|
+
*/
|
|
320
|
+
function flagsOf(argv) {
|
|
321
|
+
const out = {};
|
|
322
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
323
|
+
const token = argv[i];
|
|
324
|
+
if (!token.startsWith('--'))
|
|
325
|
+
continue;
|
|
326
|
+
const key = token.slice(2);
|
|
327
|
+
const value = argv[i + 1];
|
|
328
|
+
if (value == null || value.startsWith('--'))
|
|
329
|
+
out[key] = 'true';
|
|
330
|
+
else {
|
|
331
|
+
out[key] = value;
|
|
332
|
+
i += 1;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* @param {string} root
|
|
339
|
+
*/
|
|
340
|
+
function readOwner(root) {
|
|
341
|
+
try {
|
|
342
|
+
const owner = JSON.parse(readFileSync(join(root, 'owner.json'), 'utf8'));
|
|
343
|
+
return pidAlive(owner.pid) ? owner.pid : null;
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const entry = process.argv[1];
|
|
350
|
+
if (entry && import.meta.url === pathToFileURL(entry).href) {
|
|
351
|
+
await run(process.argv.slice(2));
|
|
352
|
+
}
|