clavarium 0.2.447-next.1 → 0.2.449-next.1
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/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +9 -4
- package/server/binders.mjs +21 -0
- package/server/carry.mjs +141 -0
- package/server/conversations.mjs +200 -25
- package/server/jobs.mjs +2 -0
- package/server/main.mjs +6 -0
- package/server/settingswords.mjs +5 -3
- package/server/tethers.mjs +17 -0
- package/web/app.js +35 -12
- package/web/index.html +6 -6
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.449-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.449-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* POST /api/conversations {name, tool, memoryMb?}
|
|
7
7
|
* POST /api/conversations/<name>/sleep
|
|
8
8
|
* POST /api/conversations/<name>/restart a clean stop (by force if it hangs), then a start
|
|
9
|
-
* GET /api/conversations/<name>/export
|
|
9
|
+
* GET /api/conversations/<name>/export[?all=1] its tool's state, or everything of it, one archive (#351) POST .../import[?replaceWork=1] put back (same tool)
|
|
10
10
|
* POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
|
|
11
11
|
* asleep: checked and kept for its wake, as `sizeAtWake` (200)
|
|
12
12
|
* POST /api/conversations/<name>/machine {action: start|stop|restart|sleep|force|force-now}: done on its machine,
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
* POST /api/binder/suggest {id}: at most three quick actions for that card -> {actions: [{key, label, why, on, ask?}]}
|
|
26
26
|
* POST /api/mailboxes/<name>/live {smtp, email?}: that mailbox connected live too (send, move...), its password reused
|
|
27
27
|
* POST /api/conversations/<name>/erase {confirm: <its name>}: deleted for good -- its machine and its work files
|
|
28
|
-
* POST /api/conversations/<name>/into-machine {machine, machineMb?}: moved into a shared machine (#221), its tool's state along (202)
|
|
28
|
+
* POST /api/conversations/<name>/into-machine {machine, machineMb?}: moved into a shared machine (#221), its tool's state along (202);
|
|
29
|
+
* {} (no machine): out of its shared machine, into one of its own (15-11)
|
|
29
30
|
* POST /api/conversations/<name>/copy {title?, machine?, machineMb?}: a copy -- its work, its tool's state, its accesses; it untouched (202)
|
|
30
31
|
* POST /api/conversations/<name>/rebuild {reset?, confirm?}: built again; reset (confirm: its name) for a working one too
|
|
31
32
|
* POST /api/conversations/<name>/ask-first {on}: its tool asks before acting (true), or acts without asking in its machine (false, the default), from its next start
|
|
@@ -306,7 +307,9 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
306
307
|
put back into a conversation of the same tool. Downloaded and sent by the person, from the page. */
|
|
307
308
|
const carry = /^\/api\/conversations\/([^/]+)\/(export|import)$/.exec(pathname);
|
|
308
309
|
if (carry && request.method === 'GET' && carry[2] === 'export') {
|
|
309
|
-
|
|
310
|
+
/* ?all=1: everything of it -- its home, its work, what it was given (conversations.exportWhole). */
|
|
311
|
+
const n = decodeURIComponent(carry[1]);
|
|
312
|
+
const out = query.get('all') === '1' ? await conversations.exportWhole(n) : await conversations.exportState(n);
|
|
310
313
|
response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(out.name)}` });
|
|
311
314
|
out.stream.pipe(response);
|
|
312
315
|
response.on('close', () => { try { out.child?.kill(); } catch { /* ended */ } });
|
|
@@ -314,7 +317,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
314
317
|
}
|
|
315
318
|
if (carry && request.method === 'POST' && carry[2] === 'import') {
|
|
316
319
|
if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
|
|
317
|
-
|
|
320
|
+
/* ?replaceWork=1: a whole export may replace the work folder that holds files (asked first, on the page). */
|
|
321
|
+
return send(200, await conversations.importState(decodeURIComponent(carry[1]), request, { replaceWork: query.get('replaceWork') === '1' })), true;
|
|
318
322
|
}
|
|
319
323
|
if (pathname.startsWith('/api/files/')) {
|
|
320
324
|
if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
|
|
@@ -1028,6 +1032,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
1028
1032
|
/* Moved into a shared machine (#221): one there already, or a new one of the size given. */
|
|
1029
1033
|
const moving = /^\/api\/conversations\/([^/]+)\/into-machine$/.exec(pathname);
|
|
1030
1034
|
if (moving) {
|
|
1035
|
+
if (body?.machine === undefined) return send(202, await conversations.moveToOwn(decodeURIComponent(moving[1]))), true;
|
|
1031
1036
|
const machineMb = body?.machineMb === undefined ? undefined : Number(body.machineMb);
|
|
1032
1037
|
return send(202, await conversations.moveToShared(decodeURIComponent(moving[1]), { machine: body?.machine, machineMb })), true;
|
|
1033
1038
|
}
|
package/server/binders.mjs
CHANGED
|
@@ -139,6 +139,27 @@ export class Binders {
|
|
|
139
139
|
if (level === 'read' || level === 'write') this.#keeper.store.grant(l.id, `${AGENT}${to}`, level, keeper);
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
+
/* WHAT IT WAS GIVEN, for a whole export (carry.mjs): each list by its id, with its access; and the same given
|
|
143
|
+
again, on an import, where the list exists here -> the ids not found. */
|
|
144
|
+
grantsOf(name) {
|
|
145
|
+
const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
|
|
146
|
+
const out = [];
|
|
147
|
+
for (const l of this.#keeper.store.lists(keeper)) {
|
|
148
|
+
const given = l.grants?.[`${AGENT}${name}`];
|
|
149
|
+
const level = typeof given === 'string' ? given : given?.access ?? given?.level;
|
|
150
|
+
if (level === 'read' || level === 'write') out.push({ id: l.id, level });
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
regrant(name, given = []) {
|
|
155
|
+
const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
|
|
156
|
+
const here = new Set(this.#keeper.store.lists(keeper).map((l) => l.id));
|
|
157
|
+
const missing = [];
|
|
158
|
+
for (const g of given) {
|
|
159
|
+
if (here.has(g?.id) && (g.level === 'read' || g.level === 'write')) this.#keeper.store.grant(g.id, `${AGENT}${name}`, g.level, keeper); else missing.push(g?.id);
|
|
160
|
+
}
|
|
161
|
+
return missing;
|
|
162
|
+
}
|
|
142
163
|
/* FOR API KEYS (apikeys.mjs): every list with who was given it, as a person sees them; a key given a list, or
|
|
143
164
|
taken back, on the list's own access -- as a conversation is. `identity`: the person, as its history says. */
|
|
144
165
|
lists() { return this.#keeper.store.lists({ id: 'person:keeper', kind: 'person', name: 'keeper' }).map((l) => ({ id: l.id, title: l.title, archived: Boolean(l.archived), grants: { ...(l.grants ?? {}) } })); }
|
package/server/carry.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/* A WHOLE CONVERSATION CARRIED ELSEWHERE (14-11, its owner's ask): beyond its tool's memory, the whole of its home,
|
|
2
|
+
its work folder and the list of what it was given -- one .tar.gz the person downloads, and puts back into a
|
|
3
|
+
conversation of the same tool, here or on another server. The parts made here, on this server's side; the
|
|
4
|
+
machine's part (its home) is in conversations.mjs (exportWhole, importState).
|
|
5
|
+
|
|
6
|
+
The archive, in this order:
|
|
7
|
+
clavarium-conversation.json its manifest (version 2, `whole`): its tool, its title, its sizes, its accesses
|
|
8
|
+
home/... its home, without what is rebuilt or thrown away (HOME_LEFT_OUT)
|
|
9
|
+
work/... its work folder, read here (it is kept on this server) */
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { createReadStream, readdirSync, renameSync, rmSync, statSync, openSync, readSync, closeSync, mkdirSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { PassThrough } from 'node:stream';
|
|
14
|
+
import { createGzip, createGunzip } from 'node:zlib';
|
|
15
|
+
|
|
16
|
+
/* WHAT A HOME IS CARRIED WITHOUT -- the one list: caches, packages fetched again, the bin, snaps, and what an
|
|
17
|
+
import left half done. Each word as tar takes it: `./x` only at the top of the home, a bare name anywhere. The
|
|
18
|
+
tool's own `state.skip` is added to it (its cache, as its entry in config/tools.json says). */
|
|
19
|
+
export const HOME_LEFT_OUT = ['./.cache', './.npm', 'node_modules', './.local/share/Trash', './snap', './.clavarium-import.*'];
|
|
20
|
+
export const homeExcludes = (skip = []) => [...HOME_LEFT_OUT, ...skip.map((a) => `./${a}`)];
|
|
21
|
+
|
|
22
|
+
/* Where the parts wait in its work folder: never shown as its work, never carried in it. */
|
|
23
|
+
export const CARRY = '.clavarium-carry';
|
|
24
|
+
|
|
25
|
+
/* A tar made with one block per record (-b 1) ends with exactly two empty blocks: taken off, another tar can follow. */
|
|
26
|
+
const END = 1024;
|
|
27
|
+
|
|
28
|
+
/* THE ONE ARCHIVE, streamed: its machine's part (the manifest and home/, a tar already written in its work folder)
|
|
29
|
+
without its end, then its work folder read here as work/, all compressed on the way -- nothing held in memory.
|
|
30
|
+
`done` is called once it ended, well or not (its part then thrown away by the caller). -> { stream, kill } */
|
|
31
|
+
export function wholeStream(homeTar, workDir, done = () => {}) {
|
|
32
|
+
const size = statSync(homeTar).size;
|
|
33
|
+
const tail = Buffer.alloc(END);
|
|
34
|
+
const fd = openSync(homeTar, 'r');
|
|
35
|
+
try { readSync(fd, tail, 0, END, Math.max(0, size - END)); } finally { closeSync(fd); }
|
|
36
|
+
if (size < END || tail.some((b) => b !== 0)) { done(); throw new Error('its home was not read whole'); }
|
|
37
|
+
const gzip = createGzip();
|
|
38
|
+
const out = new PassThrough();
|
|
39
|
+
gzip.pipe(out);
|
|
40
|
+
let child = null; let ended = false;
|
|
41
|
+
const end = (error) => { if (ended) return; ended = true; done(); if (error) out.destroy(error); };
|
|
42
|
+
const home = createReadStream(homeTar, { start: 0, end: size - END - 1 });
|
|
43
|
+
home.on('error', end);
|
|
44
|
+
home.on('end', () => {
|
|
45
|
+
/* Its home read whole: its part taken away now, before the file ends (15-11, a test saw it still there). */
|
|
46
|
+
done();
|
|
47
|
+
/* Its work: every file, its carried parts left out; named work/... (a link's target left as it is). */
|
|
48
|
+
child = spawn('tar', ['-cf', '-', '-b', '1', '-C', workDir, `--exclude=./${CARRY}`, '--transform', 's,^\\.,work,S', '.'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
49
|
+
child.stdout.pipe(gzip);
|
|
50
|
+
child.on('error', end);
|
|
51
|
+
child.on('close', (code) => end(code === 0 || code === 1 ? undefined : new Error(`its work folder was not read (exit ${code})`)));
|
|
52
|
+
});
|
|
53
|
+
home.pipe(gzip, { end: false });
|
|
54
|
+
return { stream: out, kill: () => { home.destroy(); try { child?.kill(); } catch { /* ended */ } end(); } };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/* The manifest of an export, read from its first entry only (it is always first): its JSON, or null; throws when
|
|
58
|
+
the file is not compressed as an export is. */
|
|
59
|
+
export async function readManifest(file) {
|
|
60
|
+
const gunzip = createGunzip();
|
|
61
|
+
const input = createReadStream(file);
|
|
62
|
+
input.pipe(gunzip);
|
|
63
|
+
let got = Buffer.alloc(0);
|
|
64
|
+
try {
|
|
65
|
+
for await (const chunk of gunzip) {
|
|
66
|
+
got = Buffer.concat([got, chunk]);
|
|
67
|
+
if (got.length < 512) continue;
|
|
68
|
+
const name = got.subarray(0, 100).toString().replace(/\0.*$/s, '');
|
|
69
|
+
if (name !== 'clavarium-conversation.json' && name !== './clavarium-conversation.json') return null;
|
|
70
|
+
const length = parseInt(got.subarray(124, 136).toString().replace(/\0.*$/s, '').trim(), 8);
|
|
71
|
+
if (!(length >= 0) || length > 1_000_000) return null;
|
|
72
|
+
if (got.length < 512 + length) continue;
|
|
73
|
+
try { return JSON.parse(got.subarray(512, 512 + length).toString()); } catch { return null; }
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
} finally { input.destroy(); gunzip.destroy(); }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* A work folder holds nothing of its own (its carried parts aside). */
|
|
80
|
+
export const workEmpty = (dir) => readdirSync(dir).every((e) => e === CARRY);
|
|
81
|
+
|
|
82
|
+
/* Unpacked here, into `into` (an empty folder): tar refuses names that climb out (..) and leading slashes. */
|
|
83
|
+
export function unpackHere(file, into) {
|
|
84
|
+
mkdirSync(into, { recursive: true });
|
|
85
|
+
return new Promise((ok, fail) => {
|
|
86
|
+
const child = spawn('tar', ['-xzf', file, '-C', into, '--no-same-owner'], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
87
|
+
let said = '';
|
|
88
|
+
child.stderr.on('data', (d) => { said = (said + d).slice(-500); });
|
|
89
|
+
child.on('error', fail);
|
|
90
|
+
child.on('close', (code) => (code === 0 ? ok() : fail(new Error(said.trim().split('\n').pop() || `exit ${code}`))));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/* ITS WORK PUT BACK, here: what it holds now thrown away only when asked (`replace`), then each entry of the
|
|
95
|
+
export's work/ moved in (the same disk: a rename). */
|
|
96
|
+
export function restoreWork(from, workDir, replace) {
|
|
97
|
+
if (replace) for (const e of readdirSync(workDir)) if (e !== CARRY) rmSync(join(workDir, e), { recursive: true, force: true });
|
|
98
|
+
let entries = [];
|
|
99
|
+
try { entries = readdirSync(from); } catch { return; }
|
|
100
|
+
for (const e of entries) if (e !== CARRY) renameSync(join(from, e), join(workDir, e));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/* WHAT IT WAS GIVEN, for a whole export, each by its id: a folder, a repository or a mailbox by its asset
|
|
104
|
+
(folder:x, git:x, mailbox:x), a secret by its NAME ONLY (never its value), its Tether targets and its lists by
|
|
105
|
+
theirs, with their levels; and whether its chat is on, its guide's lines. The same as a copy gives (copyRights). */
|
|
106
|
+
export function accessesOf({ folders, secrets, tethers, binders, talk, guide }, name) {
|
|
107
|
+
return {
|
|
108
|
+
resources: folders.of(name).map((r) => ({ id: folders.assetOf(folders.get(r.name) ?? { name: r.name }), access: r.access })),
|
|
109
|
+
secrets: secrets.of(name).map(String),
|
|
110
|
+
tethers: tethers?.grantsOf(name) ?? [],
|
|
111
|
+
binders: binders?.grantsOf(name) ?? [],
|
|
112
|
+
talk: talk.isOn(name) === true,
|
|
113
|
+
guide: guide.lines(name),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/* ITS IMPORT: each given again where the same id exists here, with the same level, through the calls a copy uses;
|
|
118
|
+
the rest said back, to link by hand. -> { linked: [id], missing: [id] } */
|
|
119
|
+
export async function relinkAccesses({ folders, secrets, tethers, binders, talk, guide, gitKeeper }, name, given = {}) {
|
|
120
|
+
const linked = []; const missing = [];
|
|
121
|
+
const list = (v) => (Array.isArray(v) ? v : []);
|
|
122
|
+
for (const r of list(given.resources)) {
|
|
123
|
+
const id = String(r?.id ?? ''); const at = id.indexOf(':');
|
|
124
|
+
const resource = at > 0 ? folders.get(id.slice(at + 1)) : undefined;
|
|
125
|
+
if (!resource || folders.assetOf(resource) !== id || (r.access !== 'read' && r.access !== 'write')) { missing.push(id); continue; }
|
|
126
|
+
try {
|
|
127
|
+
if (r.access === 'write') gitKeeper?.beforeWriter(resource.name, name, true);
|
|
128
|
+
await folders.attach(name, resource.name, r.access); linked.push(id);
|
|
129
|
+
} catch { missing.push(id); }
|
|
130
|
+
}
|
|
131
|
+
for (const s of list(given.secrets)) {
|
|
132
|
+
try { secrets.attach(name, String(s), true); linked.push(`secret:${s}`); } catch { missing.push(`secret:${s}`); }
|
|
133
|
+
}
|
|
134
|
+
for (const [kind, keeper, grants] of [['tether', tethers, list(given.tethers)], ['binder', binders, list(given.binders)]]) {
|
|
135
|
+
const absent = keeper ? keeper.regrant(name, grants) : grants.map((g) => g?.id);
|
|
136
|
+
for (const g of grants) (absent.includes(g?.id) ? missing : linked).push(`${kind}:${g?.id}`);
|
|
137
|
+
}
|
|
138
|
+
if (given.talk === true) await talk.set(name, true).catch(() => {});
|
|
139
|
+
if (list(given.guide).length) await guide.setLines(name, given.guide).catch(() => {});
|
|
140
|
+
return { linked, missing };
|
|
141
|
+
}
|
package/server/conversations.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { attachCommand, SOCKET } from './tmux.mjs';
|
|
|
12
12
|
import { WORK, VM_USER, SHARING_STEP, stepLine, vmName } from './vm.mjs';
|
|
13
13
|
import { resumeOrFresh } from './tools.mjs';
|
|
14
14
|
import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
|
|
15
|
+
import { homeExcludes, wholeStream, readManifest, workEmpty, unpackHere, restoreWork, CARRY } from './carry.mjs';
|
|
15
16
|
import { availableParallelism } from 'node:os';
|
|
16
17
|
import { spawn } from 'node:child_process';
|
|
17
18
|
import { readFileSync, createReadStream, createWriteStream, mkdtempSync, rmSync, statSync, copyFileSync, mkdirSync } from 'node:fs';
|
|
@@ -155,6 +156,10 @@ export class Conversations {
|
|
|
155
156
|
accesses of the original given to the copy (copy, below). */
|
|
156
157
|
copyWork = async () => {};
|
|
157
158
|
copyRights = async () => {};
|
|
159
|
+
/* Set by the server: what a conversation was given, for a whole export -- each by its id, a secret by its name
|
|
160
|
+
only (never its value); and the same given again on an import, where it exists here -> { linked, missing }. */
|
|
161
|
+
accessesOf = async () => ({});
|
|
162
|
+
relink = async () => ({ linked: [], missing: [] });
|
|
158
163
|
|
|
159
164
|
/* `uid`/`gid`: the account this server runs as; files the tool writes in
|
|
160
165
|
its kept work folder belong to it on the host. */
|
|
@@ -171,6 +176,7 @@ export class Conversations {
|
|
|
171
176
|
/* A move into a shared machine cut short (14-11): back in its own machine, as it was -- never « build it
|
|
172
177
|
again », which would make its own machine anew and lose its tool's memory. */
|
|
173
178
|
if (c.phase === 'building' && c.movingTo) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, sharedMachine: undefined, machineMb: undefined, machineUser: undefined, ...(c.movingFromMb ? { memoryMb: c.movingFromMb } : {}), movingTo: undefined, movingFromMb: undefined, stopped: true, moved: `The server restarted while it was moving to the shared machine ${c.movingTo}: it stays in its own machine, as it was. Move it again when you like.` });
|
|
179
|
+
else if (c.phase === 'building' && c.movingOutOf) store.patch(c.name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, ...c.movingOutOf, movingOutOf: undefined, stopped: true, moved: `The server restarted while it was moving out of the shared machine ${c.movingOutOf.sharedMachine}: it stays there. Move it again when you like.` });
|
|
174
180
|
else if (c.phase === 'building') store.patch(c.name, { phase: 'failed', error: 'The server restarted while this conversation was being built. Build it again, or archive it.' });
|
|
175
181
|
if (c.phase === 'restarting') store.patch(c.name, { phase: 'ready', step: undefined, restartingSince: undefined, restarted: 'The server restarted while this machine was being restarted: look at its state, and restart it again if needed.' });
|
|
176
182
|
/* An action cut short: said as such, never left running on the page. */
|
|
@@ -971,16 +977,88 @@ export class Conversations {
|
|
|
971
977
|
return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium.tar.gz`, stream: child.stdout, child };
|
|
972
978
|
}
|
|
973
979
|
|
|
980
|
+
/* EVERYTHING OF IT, CARRIED (14-11, its owner's ask): its manifest with what it was given (accesses, by id), its
|
|
981
|
+
whole home (without HOME_LEFT_OUT, carry.mjs) and its work folder, as one .tar.gz streamed to the person. Its
|
|
982
|
+
home is written by its machine into its work folder (never through the VM manager's output), then sent from
|
|
983
|
+
here followed by its work, read here. Its work must be kept on this server. -> { name, stream, child } */
|
|
984
|
+
async exportWhole(name) {
|
|
985
|
+
const c = this.#store.get(name);
|
|
986
|
+
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
987
|
+
const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
|
|
988
|
+
if (!workDir) throw new Refusal(409, 'Its work is on its own machine\'s disk: keep it here first (Its files), then export it.');
|
|
989
|
+
if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
|
|
990
|
+
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
991
|
+
const accesses = await this.accessesOf(name);
|
|
992
|
+
const manifest = JSON.stringify({ kind: 'clavarium-conversation', version: 2, whole: true, tool: c.tool, name: c.name, ...(c.title ? { title: c.title } : {}), memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB, at: new Date().toISOString(), accesses });
|
|
993
|
+
const id = `whole-${Date.now()}`;
|
|
994
|
+
/* In its machine: the manifest, then its home as home/ (a link's target left as it is), one block per record
|
|
995
|
+
so that its work can follow it (carry.mjs). Globs off: the words left out are given to tar as they are. */
|
|
996
|
+
const script = 'set -f; m=$(mktemp -d) || exit 2; printf "%s" "$1" > "$m/clavarium-conversation.json"; '
|
|
997
|
+
+ 'ex=""; for a in $2; do ex="$ex --exclude=$a"; done; mkdir -p /work/' + CARRY + '; '
|
|
998
|
+
+ 'rc=0; tar -cf "/work/' + CARRY + '/$3.tar" -b 1 --warning=no-file-changed -C "$m" clavarium-conversation.json -C "$HOME" $ex --transform "s,^\\.,home,S" . || rc=$?; rm -rf "$m"; '
|
|
999
|
+
/* 1: a file changed while read: the archive is whole all the same. */
|
|
1000
|
+
+ '[ "$rc" -le 1 ]';
|
|
1001
|
+
const homeTar = join(workDir, CARRY, `${id}.tar`);
|
|
1002
|
+
const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, homeExcludes(tool?.state?.skip ?? []).join(' '), id]);
|
|
1003
|
+
const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
1004
|
+
let said = '';
|
|
1005
|
+
child.stderr.on('data', (d) => { said = (said + d).slice(-2000); });
|
|
1006
|
+
const code = await new Promise((ok) => { child.on('error', () => ok(-1)); child.on('close', ok); });
|
|
1007
|
+
const drop = () => rmSync(homeTar, { force: true });
|
|
1008
|
+
if (code !== 0) { drop(); throw new Refusal(502, `Not exported: ${firstLine(said) || `exit ${code}`}`); }
|
|
1009
|
+
let out;
|
|
1010
|
+
try { out = wholeStream(homeTar, workDir, drop); } catch (error) { throw new Refusal(502, `Not exported: ${error.message}`); }
|
|
1011
|
+
return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium-all.tar.gz`, stream: out.stream, child: { kill: out.kill } };
|
|
1012
|
+
}
|
|
1013
|
+
|
|
974
1014
|
/* PUT BACK an exported state in this conversation (same tool): its tool stopped, the archive unpacked in
|
|
975
1015
|
its home, its tool started again, taking up its last session. -> { tool, from } */
|
|
976
|
-
|
|
1016
|
+
/* A WHOLE export (exportWhole) puts back its home, its work folder and its accesses: its work only into an empty
|
|
1017
|
+
one, unless `replaceWork` -- what is there is never thrown away silently. -> { tool, from, whole, linked, toLink } */
|
|
1018
|
+
async importState(name, input, { replaceWork = false } = {}) {
|
|
977
1019
|
const c = this.#busyCheck(name);
|
|
978
1020
|
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
979
|
-
if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: nothing can be imported in it.`);
|
|
980
1021
|
if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
|
|
1022
|
+
/* Received first, whole, beside its work when it has one here (the same disk its work goes to). */
|
|
1023
|
+
const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
|
|
1024
|
+
const id = `up-${Date.now()}`;
|
|
1025
|
+
const aside = workDir ? join(workDir, CARRY) : mkdtempSync(join(tmpdir(), 'clv-import-'));
|
|
1026
|
+
mkdirSync(aside, { recursive: true });
|
|
1027
|
+
const file = join(aside, `${id}.tgz`); const stage = join(aside, id);
|
|
1028
|
+
try {
|
|
1029
|
+
if (typeof input === 'string') copyFileSync(input, file);
|
|
1030
|
+
else await new Promise((ok, fail) => { const w = createWriteStream(file); input.on('error', fail); w.on('error', fail); w.on('finish', ok); input.pipe(w); });
|
|
1031
|
+
const manifest = await readManifest(file).catch((error) => { throw new Refusal(502, `Not imported: ${error.message}`); });
|
|
1032
|
+
if (manifest?.kind !== 'clavarium-conversation') throw new Refusal(400, 'This is not an exported conversation.');
|
|
1033
|
+
if (manifest.tool !== c.tool) throw new Refusal(400, 'This export is of another tool: import it into a conversation with that tool.');
|
|
1034
|
+
if (!manifest.whole) {
|
|
1035
|
+
if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: nothing can be imported in it.`);
|
|
1036
|
+
await this.#stopTool(name);
|
|
1037
|
+
try { return { tool: c.tool, from: await this.#unpack(name, c.tool, file) }; } finally { this.ready(name); }
|
|
1038
|
+
}
|
|
1039
|
+
if (!workDir) throw new Refusal(409, 'Its work is on its own machine\'s disk: keep it here first (Its files), then import into it.');
|
|
1040
|
+
if (!replaceWork && !workEmpty(workDir)) throw Object.assign(new Refusal(409, 'Its work folder is not empty: import again to replace it.'), { kind: 'work-not-empty' });
|
|
1041
|
+
await unpackHere(file, stage).catch((error) => { throw new Refusal(400, `Not imported: ${error.message}`); });
|
|
1042
|
+
rmSync(file, { force: true });
|
|
1043
|
+
await this.#stopTool(name);
|
|
1044
|
+
try {
|
|
1045
|
+
/* Its home: in its machine, each part of home/ in place of the old (as #unpackFrom does). */
|
|
1046
|
+
const script = 'set -e; s="/work/' + CARRY + '/$1/home"; [ -d "$s" ] || exit 0; '
|
|
1047
|
+
+ 'for e in "$s"/.[!.]* "$s"/*; do if [ ! -e "$e" ] && [ ! -L "$e" ]; then continue; fi; b=$(basename "$e"); rm -rf "$HOME/$b"; mv "$e" "$HOME/$b"; done';
|
|
1048
|
+
const r = await this.#vms.exec(name, ['sh', '-c', script, 'import', id], { timeoutMs: 30 * 60_000 });
|
|
1049
|
+
if (r.code !== 0) throw new Refusal(502, `Not imported: ${firstLine(r.stderr) || `exit ${r.code}`}`);
|
|
1050
|
+
restoreWork(join(stage, 'work'), workDir, replaceWork);
|
|
1051
|
+
const { linked, missing } = await this.relink(name, manifest.accesses ?? {});
|
|
1052
|
+
return { tool: c.tool, from: { name: manifest.name, at: manifest.at }, whole: true, linked, toLink: missing };
|
|
1053
|
+
} finally { this.ready(name); }
|
|
1054
|
+
} finally {
|
|
1055
|
+
rmSync(file, { force: true }); rmSync(stage, { recursive: true, force: true });
|
|
1056
|
+
if (!workDir) rmSync(aside, { recursive: true, force: true });
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
async #stopTool(name) {
|
|
981
1060
|
this.drop(name);
|
|
982
1061
|
await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'kill-server'], { timeoutMs: 10_000 }).catch(() => {});
|
|
983
|
-
try { return { tool: c.tool, from: await this.#unpack(name, c.tool, input) }; } finally { this.ready(name); }
|
|
984
1062
|
}
|
|
985
1063
|
|
|
986
1064
|
/* An exported state unpacked into its home (its tool stopped by the caller): its manifest checked, then each
|
|
@@ -1211,6 +1289,34 @@ export class Conversations {
|
|
|
1211
1289
|
return this.#store.get(name);
|
|
1212
1290
|
}
|
|
1213
1291
|
|
|
1292
|
+
/* ITS TOOL'S STATE, TAKEN ALONG for a move (12-11, 15-11): through its work folder, as a copy reads it (14-11),
|
|
1293
|
+
written to `carried`. -> undefined, or why it could not be. */
|
|
1294
|
+
async #takeState(name, c, tool, carried) {
|
|
1295
|
+
this.#store.patch(name, { step: `Taking ${tool.label}'s state along` });
|
|
1296
|
+
/* Through its work folder, as a copy reads it (14-11): the VM manager's output stalls past ~36 KB on
|
|
1297
|
+
the owner's server -- a move then waited for ever. Its size read as it grows, said; quiet too long: ended. */
|
|
1298
|
+
const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
|
|
1299
|
+
const carryId = workDir ? `move-${name}-${Date.now()}` : '';
|
|
1300
|
+
const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
|
|
1301
|
+
if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(name, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
|
|
1302
|
+
const { stream, child } = await this.exportState(name, inWork ? { toWork: carryId } : {});
|
|
1303
|
+
let read = 0; let lastAt = Date.now(); let stalled = false;
|
|
1304
|
+
const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); this.#store.patch(name, { step: `Taking ${tool.label}'s state along: ${sizeWords(read)}` }); };
|
|
1305
|
+
const sizing = setInterval(() => {
|
|
1306
|
+
if (inWork) { try { grew(statSync(inWork).size); } catch { /* not there yet */ } }
|
|
1307
|
+
if (Date.now() - lastAt >= COPY_QUIET_MS) { stalled = true; child.kill('SIGKILL'); }
|
|
1308
|
+
}, 1000);
|
|
1309
|
+
const failed = new Promise((ok) => child.on('error', () => ok(-1)));
|
|
1310
|
+
const file = inWork ? null : createWriteStream(carried, { mode: 0o600 });
|
|
1311
|
+
if (file) { stream.on('data', (d) => grew(read + d.length)); stream.pipe(file); } else stream.resume();
|
|
1312
|
+
const code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => clearInterval(sizing));
|
|
1313
|
+
if (file) await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
|
|
1314
|
+
if (inWork) { try { if (code === 0 && !stalled) copyFileSync(inWork, carried); } finally { rmSync(inWork, { force: true }); } }
|
|
1315
|
+
if (stalled) return `its tool's state stopped coming (${sizeWords(read)} read, then nothing for ${COPY_QUIET_MS / 60_000} min).`;
|
|
1316
|
+
if (code !== 0) return `its tool's state could not be taken (exit ${code}${firstLine(child.said) ? `: ${firstLine(child.said)}` : ''}).`;
|
|
1317
|
+
return undefined;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1214
1320
|
async #moving(name, c, tool, machine, size, memory, state) {
|
|
1215
1321
|
const old = vmName(name);
|
|
1216
1322
|
const dir = mkdtempSync(join(tmpdir(), 'clv-move-'));
|
|
@@ -1225,28 +1331,8 @@ export class Conversations {
|
|
|
1225
1331
|
this.drop(name);
|
|
1226
1332
|
if (state === 'Running') await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'kill-server'], { timeoutMs: 10_000 }).catch(() => {});
|
|
1227
1333
|
if (tool.state) {
|
|
1228
|
-
this.#
|
|
1229
|
-
|
|
1230
|
-
the owner's server -- a move then waited for ever. Its size read as it grows, said; quiet too long: ended. */
|
|
1231
|
-
const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
|
|
1232
|
-
const carryId = workDir ? `move-${name}-${Date.now()}` : '';
|
|
1233
|
-
const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
|
|
1234
|
-
if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(name, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
|
|
1235
|
-
const { stream, child } = await this.exportState(name, inWork ? { toWork: carryId } : {});
|
|
1236
|
-
let read = 0; let lastAt = Date.now(); let stalled = false;
|
|
1237
|
-
const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); this.#store.patch(name, { step: `Taking ${tool.label}'s state along: ${sizeWords(read)}` }); };
|
|
1238
|
-
const sizing = setInterval(() => {
|
|
1239
|
-
if (inWork) { try { grew(statSync(inWork).size); } catch { /* not there yet */ } }
|
|
1240
|
-
if (Date.now() - lastAt >= COPY_QUIET_MS) { stalled = true; child.kill('SIGKILL'); }
|
|
1241
|
-
}, 1000);
|
|
1242
|
-
const failed = new Promise((ok) => child.on('error', () => ok(-1)));
|
|
1243
|
-
const file = inWork ? null : createWriteStream(carried, { mode: 0o600 });
|
|
1244
|
-
if (file) { stream.on('data', (d) => grew(read + d.length)); stream.pipe(file); } else stream.resume();
|
|
1245
|
-
const code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => clearInterval(sizing));
|
|
1246
|
-
if (file) await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
|
|
1247
|
-
if (inWork) { try { if (code === 0 && !stalled) copyFileSync(inWork, carried); } finally { rmSync(inWork, { force: true }); } }
|
|
1248
|
-
if (stalled) return back(`its tool's state stopped coming (${sizeWords(read)} read, then nothing for ${COPY_QUIET_MS / 60_000} min).`);
|
|
1249
|
-
if (code !== 0) return back(`its tool's state could not be taken (exit ${code}${firstLine(child.said) ? `: ${firstLine(child.said)}` : ''}).`);
|
|
1334
|
+
const why = await this.#takeState(name, c, tool, carried);
|
|
1335
|
+
if (why) return back(why);
|
|
1250
1336
|
}
|
|
1251
1337
|
if (state !== undefined) {
|
|
1252
1338
|
this.#store.patch(name, { step: 'Stopping its own machine' });
|
|
@@ -1284,6 +1370,95 @@ export class Conversations {
|
|
|
1284
1370
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
1285
1371
|
}
|
|
1286
1372
|
|
|
1373
|
+
/* OUT OF ITS SHARED MACHINE, INTO ONE OF ITS OWN (#221, 15-11): the move the other way. Its tool's state carried
|
|
1374
|
+
(as into a shared machine), its programs there ended and its work taken out of its place, its own machine built
|
|
1375
|
+
as a new one's, the state put back, then its place in the shared machine removed -- its user and home there, or
|
|
1376
|
+
the whole machine when it was the last in it. Anything wrong before its own machine is ready: back in the shared
|
|
1377
|
+
machine, as it was (its place there kept until the end). -> the record, at once; `this.built`: the end of it. */
|
|
1378
|
+
async moveToOwn(name) {
|
|
1379
|
+
const c = this.#busyCheck(name);
|
|
1380
|
+
if (!c.sharedMachine) throw new Refusal(409, 'It has a machine of its own already.');
|
|
1381
|
+
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
1382
|
+
if (!tool) throw new Refusal(400, 'The tool of this conversation is no longer offered.');
|
|
1383
|
+
const state = await this.#vms.state(name, { fresh: true }).catch(() => undefined);
|
|
1384
|
+
if (tool.state && state !== 'Running') throw new Refusal(409, 'Its shared machine is not running: open the conversation first, so that its tool\'s state can come along.', { retry: false });
|
|
1385
|
+
const memory = Math.max(tool.memoryMb, Number(c.memoryMb) || tool.memoryMb);
|
|
1386
|
+
await this.room({ kind: 'create', memoryMb: memory });
|
|
1387
|
+
const act = this.#take(name, 'move');
|
|
1388
|
+
this.#cancelStop(name);
|
|
1389
|
+
const now = new Date().toISOString();
|
|
1390
|
+
/* `movingOutOf`: what a restart of this server finds, to put it back in its shared machine (constructor). */
|
|
1391
|
+
this.#store.patch(name, { phase: 'building', step: `Moving out of the shared machine ${c.sharedMachine}`, buildingSince: now, progress: buildProgress(now), movingOutOf: { sharedMachine: c.sharedMachine, machineMb: c.machineMb, machineUser: c.machineUser, memoryMb: c.memoryMb } });
|
|
1392
|
+
this.built = this.#movingOut(name, c, tool, memory, state).finally(() => this.#give(name, act));
|
|
1393
|
+
return this.#store.get(name);
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
async #movingOut(name, c, tool, memory, state) {
|
|
1397
|
+
const shared = c.sharedMachine;
|
|
1398
|
+
const was = { sharedMachine: shared, machineMb: c.machineMb, machineUser: c.machineUser, memoryMb: c.memoryMb };
|
|
1399
|
+
const dir = mkdtempSync(join(tmpdir(), 'clv-move-'));
|
|
1400
|
+
const carried = join(dir, 'state.tar.gz');
|
|
1401
|
+
let left = false;
|
|
1402
|
+
const back = async (why) => {
|
|
1403
|
+
/* Back in its shared machine, as it was: its own machine, if begun, removed; its work shown there again. */
|
|
1404
|
+
if (!this.#store.get(name)) return undefined;
|
|
1405
|
+
this.#store.patch(name, { sharedMachine: undefined });
|
|
1406
|
+
if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== undefined) await this.#vms.removeVm(vmName(name)).catch(() => {});
|
|
1407
|
+
this.#store.patch(name, { ...was, phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, error: undefined, movingOutOf: undefined });
|
|
1408
|
+
if (left) await this.#vms.workMount(name, this.#uid, this.#gid).catch(() => {});
|
|
1409
|
+
this.#fresh.add(name); this.#mountAgain.add(name);
|
|
1410
|
+
try { this.renewed(name, `Not moved out of the shared machine ${shared}: ${why} It stays there, as it was.`, false); } catch { /* told, nothing more */ }
|
|
1411
|
+
return undefined;
|
|
1412
|
+
};
|
|
1413
|
+
try {
|
|
1414
|
+
this.drop(name);
|
|
1415
|
+
if (state === 'Running') await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'kill-server'], { timeoutMs: 10_000 }).catch(() => {});
|
|
1416
|
+
if (tool.state) {
|
|
1417
|
+
const why = await this.#takeState(name, c, tool, carried);
|
|
1418
|
+
if (why) return back(why);
|
|
1419
|
+
}
|
|
1420
|
+
if (state === 'Running') {
|
|
1421
|
+
/* Its programs there ended, its work taken out of its place: nothing of it runs there any more. */
|
|
1422
|
+
this.#store.patch(name, { step: `Leaving the shared machine ${shared}` });
|
|
1423
|
+
await this.#vms.execMachine(name, ['sudo', '-n', 'pkill', '-KILL', '-u', `c-${name}`], { timeoutMs: 30_000 }).catch(() => {});
|
|
1424
|
+
await this.#vms.workUnmount(name).catch(() => {});
|
|
1425
|
+
left = true;
|
|
1426
|
+
}
|
|
1427
|
+
/* Its own machine, as a new conversation's: built with its name, held before its tool starts. */
|
|
1428
|
+
this.#store.patch(name, { sharedMachine: undefined, machineMb: undefined, machineUser: undefined, memoryMb: memory, step: 'Starting the machine' });
|
|
1429
|
+
/* One left behind by an attempt cut short: not this conversation's any more. */
|
|
1430
|
+
if ((await this.#vms.state(name, { fresh: true }).catch(() => undefined)) !== undefined) await this.#vms.removeVm(vmName(name)).catch(() => {});
|
|
1431
|
+
this.#holding.add(name);
|
|
1432
|
+
try { await this.#build(name, tool, memory); } finally { this.#holding.delete(name); }
|
|
1433
|
+
const now = this.#store.get(name);
|
|
1434
|
+
if (!now) return undefined; /* archived meanwhile */
|
|
1435
|
+
if (now.phase === 'failed') return back(`${String(now.error ?? 'its own machine could not be made.').replace(/\.?$/, '.')}`);
|
|
1436
|
+
let lost = '';
|
|
1437
|
+
if (tool.state) {
|
|
1438
|
+
this.#store.patch(name, { step: `Putting ${tool.label}'s state back` });
|
|
1439
|
+
try { await this.#unpack(name, c.tool, carried); } catch (error) { lost = error.message; }
|
|
1440
|
+
}
|
|
1441
|
+
this.#store.patch(name, { phase: 'ready', step: undefined, progress: undefined, buildingSince: undefined, toolStarted: false, movingOutOf: undefined });
|
|
1442
|
+
this.ready(name);
|
|
1443
|
+
/* There for good: its place in the shared machine goes -- the whole machine with the last one in it. */
|
|
1444
|
+
const others = this.#store.all().filter((x) => x.name !== name && x.sharedMachine === shared);
|
|
1445
|
+
if (others.length) {
|
|
1446
|
+
const there = this.#vms.run;
|
|
1447
|
+
await there(['vm', 'unshare', vmName(shared), name]).catch(() => {});
|
|
1448
|
+
if (left) {
|
|
1449
|
+
await there(['vm', 'exec', vmName(shared), '--', 'sudo', '-n', 'userdel', '--remove', `c-${name}`], { timeoutMs: 60_000 }).catch(() => {});
|
|
1450
|
+
await there(['vm', 'exec', vmName(shared), '--', 'sudo', '-n', 'rm', '-f', `/etc/clavarium/limits/${name}`], { timeoutMs: 30_000 }).catch(() => {});
|
|
1451
|
+
}
|
|
1452
|
+
} else await this.#vms.removeVm(vmName(shared)).catch(() => {});
|
|
1453
|
+
this.renewed(name, lost
|
|
1454
|
+
? `Moved out of the shared machine ${shared} into a machine of its own, but ${tool.label}'s state did not come along (${lost}): it starts afresh.`
|
|
1455
|
+
: `Moved out of the shared machine ${shared} into a machine of its own: its work folder${tool.state ? `, ${tool.label}'s state` : ''} and this chat came along.`, true);
|
|
1456
|
+
return undefined;
|
|
1457
|
+
} catch (error) {
|
|
1458
|
+
return back(`${String(error?.message ?? error).replace(/\.?$/, '.')}`);
|
|
1459
|
+
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1287
1462
|
async #fixup(name, tool) {
|
|
1288
1463
|
for (const step of tool.fixups) {
|
|
1289
1464
|
const r = await this.#vms.exec(name, step.argv, { timeoutMs: 120_000 }).catch(() => ({ code: 1 }));
|
package/server/jobs.mjs
CHANGED
|
@@ -33,6 +33,8 @@ const bare = ({ log, ...job }) => job;
|
|
|
33
33
|
export function jobWords(c) {
|
|
34
34
|
if (c.phase === 'moving') return `Moving ${titleOf(c)}${c.sharedMachine ? ` into « ${c.sharedMachine} »` : ''}`;
|
|
35
35
|
if (c.phase === 'restarting') return `Restarting ${titleOf(c)}`;
|
|
36
|
+
if (c.movingTo) return `Moving ${titleOf(c)} into « ${c.movingTo} »`;
|
|
37
|
+
if (c.movingOutOf) return `Moving ${titleOf(c)} out of « ${c.movingOutOf.sharedMachine} »`;
|
|
36
38
|
if (c.copyOf) return `Copy ${titleOf(c)}${c.sharedMachine ? ` in « ${c.sharedMachine} »` : ''}`;
|
|
37
39
|
return `Building ${titleOf(c)}${c.sharedMachine ? ` in « ${c.sharedMachine} »` : ''}`;
|
|
38
40
|
}
|
package/server/main.mjs
CHANGED
|
@@ -94,6 +94,7 @@ import { ApiKeys, handleExternal, handleApiKeys, statusOf } from './apikeys.mjs'
|
|
|
94
94
|
import { RelayJoin, handleRelayJoin, RELAY_JOIN_PATH } from './relayjoin.mjs';
|
|
95
95
|
import { WebSocketServer } from 'ws';
|
|
96
96
|
import { copyWorkFolder } from './copywork.mjs';
|
|
97
|
+
import { accessesOf, relinkAccesses } from './carry.mjs';
|
|
97
98
|
import { Jobs, withUpdates } from './jobs.mjs';
|
|
98
99
|
|
|
99
100
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
@@ -691,6 +692,11 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
691
692
|
const lines = guide.lines(from);
|
|
692
693
|
if (lines.length) await guide.setLines(to, lines).catch(() => {});
|
|
693
694
|
};
|
|
695
|
+
/* A WHOLE EXPORT (conversations.exportWhole): what it was given, each by its id -- a folder, a repository or a
|
|
696
|
+
mailbox by its asset, a secret by its name only (never its value), its Tether targets and its lists by theirs. */
|
|
697
|
+
all.accessesOf = async (name) => accessesOf({ folders, secrets, tethers, binders, talk, guide }, name);
|
|
698
|
+
/* ITS IMPORT: each given again where the same id exists here, with the same level (as copyRights does). */
|
|
699
|
+
all.relink = (name, given) => relinkAccesses({ folders, secrets, tethers, binders, talk, guide, gitKeeper }, name, given);
|
|
694
700
|
/* A tool that ended cut for lack of memory: said in the events, to the owner, and in its chat. */
|
|
695
701
|
all.onToolExit = (name, report) => {
|
|
696
702
|
if (!report?.oom?.length) return;
|
package/server/settingswords.mjs
CHANGED
|
@@ -181,10 +181,12 @@ export const SETTINGS_WORDS_FR = {
|
|
|
181
181
|
'set-cm-goes-work': 'Son dossier de travail', 'set-cm-goes-memory': 'La mémoire de son IA', 'set-cm-goes-access': 'Ses accès',
|
|
182
182
|
'set-cm-not': 'Ni ses appareils, ni ses rappels', 'set-cm-untouched': 'Celle-ci intacte : lue, puis remise en l\'état',
|
|
183
183
|
'set-cm-stay': 'Vous restez ici · « Ouvrir » une fois prête', 'set-cm-stops': 'Son outil s\'arrête environ une minute',
|
|
184
|
-
'set-cm-deleted': 'Sa propre machine est supprimée', 'set-cm-back': 'Retour', 'set-cm-copy-go': 'La copier', 'set-cm-move-go': 'La déplacer',
|
|
184
|
+
'set-cm-deleted': 'Sa propre machine est supprimée', 'set-cm-stops-out': 'Son outil s\'arrête quelques minutes', 'set-cm-shared-deleted': 'La machine partagée « {m} » est supprimée', 'set-cm-place-deleted': 'Sa place dans « {m} » est supprimée', 'set-cm-back': 'Retour', 'set-cm-copy-go': 'La copier', 'set-cm-move-go': 'La déplacer',
|
|
185
185
|
'set-cm-ready': 'Copie prête', 'set-cm-open': 'Ouvrir', 'set-cm-failed': 'Pas copiée', 'set-cm-see-why': 'Voir pourquoi',
|
|
186
|
-
'set-carry': '
|
|
187
|
-
'set-carry-export': '
|
|
186
|
+
'set-carry': 'Exporter / Importer', 'set-carry-hint': 'Mémoire de son IA, ou tout : à emporter.',
|
|
187
|
+
'set-carry-export': 'Mémoire de son IA', 'set-carry-all': 'Tout (dossier perso, travail, accès)', 'set-carry-all-off': 'Son travail doit être gardé ici.',
|
|
188
|
+
'set-carry-replace': 'Son travail a des fichiers. Tout remplacer ?', 'set-carry-replace-go': 'Remplacer son travail',
|
|
189
|
+
'set-carry-tolink': 'À relier à la main :', 'set-carry-import': 'Importer…', 'set-carry-go': 'Importer',
|
|
188
190
|
'set-carry-ask': '« {file} » dans « {name} » ? Mémoire remplacée.', 'set-carry-done': 'Importé depuis « {from} ».',
|
|
189
191
|
'set-mcp-drop': 'Collez ici la configuration du service', 'set-mcp-drop-hint': 'le bloc { "mcpServers": … } de sa page d\'aide',
|
|
190
192
|
'set-mcp-hand': 'Remplir à la main', 'set-mcp-add-n': 'Ajouter les {n}', 'set-mcp-nokey': 'aucune',
|
package/server/tethers.mjs
CHANGED
|
@@ -328,6 +328,23 @@ export class Tethers {
|
|
|
328
328
|
}
|
|
329
329
|
}
|
|
330
330
|
|
|
331
|
+
/* WHAT IT WAS GIVEN, for a whole export (carry.mjs): each target by its id, with its level and its allow rules;
|
|
332
|
+
and the same given again, on an import, to those that exist here -> the ids not found. */
|
|
333
|
+
grantsOf(name) {
|
|
334
|
+
return this.#keeper.store.targets().filter((t) => t.kind !== 'device' && t.kind !== 'voicebox' && t.grants?.[`${AGENT}${name}`]?.level)
|
|
335
|
+
.map((t) => ({ id: t.id, level: t.grants[`${AGENT}${name}`].level, ...(t.grants[`${AGENT}${name}`].rules?.length ? { rules: t.grants[`${AGENT}${name}`].rules } : {}) }));
|
|
336
|
+
}
|
|
337
|
+
regrant(name, given = []) {
|
|
338
|
+
const store = this.#keeper.store; const here = new Set(store.targets().filter((t) => t.kind !== 'device' && t.kind !== 'voicebox').map((t) => t.id));
|
|
339
|
+
const missing = [];
|
|
340
|
+
for (const g of given) {
|
|
341
|
+
if (!here.has(g?.id) || !g.level) { missing.push(g?.id); continue; }
|
|
342
|
+
store.grant(g.id, `${AGENT}${name}`, g.level);
|
|
343
|
+
for (const rule of g.rules ?? []) { try { store.allow(g.id, `${AGENT}${name}`, rule); } catch { /* a rule no longer valid: left out */ } }
|
|
344
|
+
}
|
|
345
|
+
return missing;
|
|
346
|
+
}
|
|
347
|
+
|
|
331
348
|
/* What each conversation was given: { name: count } -- the targets it may use. */
|
|
332
349
|
given() {
|
|
333
350
|
const out = {};
|
package/web/app.js
CHANGED
|
@@ -2686,6 +2686,12 @@
|
|
|
2686
2686
|
$('carry-export').href = `${API}/conversations/${encodeURIComponent(current)}/export`;
|
|
2687
2687
|
$('carry-export').toggleAttribute('aria-disabled', down);
|
|
2688
2688
|
$('carry-export').onclick = down ? (event) => { event.preventDefault(); } : null;
|
|
2689
|
+
/* Everything of it (14-11): its work is read here, so only when it is kept here. */
|
|
2690
|
+
const allOff = down || here?.work !== 'kept';
|
|
2691
|
+
$('carry-export-all').href = `${API}/conversations/${encodeURIComponent(current)}/export?all=1`;
|
|
2692
|
+
$('carry-export-all').toggleAttribute('aria-disabled', allOff);
|
|
2693
|
+
$('carry-export-all').title = here?.work !== 'kept' ? uiSaid('set-carry-all-off', 'Its work must be kept here.') : '';
|
|
2694
|
+
$('carry-export-all').onclick = allOff ? (event) => { event.preventDefault(); } : null;
|
|
2689
2695
|
$('carry-import').disabled = down;
|
|
2690
2696
|
$('carry-said').hidden = !down;
|
|
2691
2697
|
if (down) {
|
|
@@ -2694,20 +2700,30 @@
|
|
|
2694
2700
|
$('carry-said').replaceChildren(uiSaid('set-carry-down', 'It must run to export or import.'), ' ', start);
|
|
2695
2701
|
}
|
|
2696
2702
|
$('carry-import').onclick = () => $('carry-file').click();
|
|
2703
|
+
/* Sent; a whole export into a work folder that holds files asks first, then is sent again to replace it.
|
|
2704
|
+
What it was given that does not exist here is listed after, to link by hand. */
|
|
2705
|
+
const carryImport = async (name, file, replaceWork) => {
|
|
2706
|
+
try {
|
|
2707
|
+
const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import${replaceWork ? '?replaceWork=1' : ''}`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
|
|
2708
|
+
const said = await r.json().catch(() => ({}));
|
|
2709
|
+
if (!r.ok && said.kind === 'work-not-empty') {
|
|
2710
|
+
show(uiSaid('set-carry-replace', 'Its work folder has files. Replace them all?'), uiSaid('set-carry-replace-go', 'Replace its work'),
|
|
2711
|
+
() => carryImport(name, file, true), () => { notice.hidden = true; focusTerminal(); });
|
|
2712
|
+
return;
|
|
2713
|
+
}
|
|
2714
|
+
if (!r.ok) throw new Error(said.error ?? `HTTP ${r.status}`);
|
|
2715
|
+
const done = uiSaid('set-carry-done', 'Imported from « {from} ».', { from: said.from?.name ?? file.name });
|
|
2716
|
+
const toLink = Array.isArray(said.toLink) ? said.toLink.filter(Boolean) : [];
|
|
2717
|
+
show(toLink.length ? `${done} ${uiSaid('set-carry-tolink', 'To link by hand:')} ${toLink.join(', ')}` : done, 'OK', () => { notice.hidden = true; focusTerminal(); });
|
|
2718
|
+
} catch (error) { show(error.message, 'Back to the terminal', enter); }
|
|
2719
|
+
};
|
|
2697
2720
|
$('carry-file').onchange = () => {
|
|
2698
2721
|
const file = $('carry-file').files?.[0]; $('carry-file').value = '';
|
|
2699
2722
|
if (!file) return;
|
|
2700
2723
|
const name = current;
|
|
2701
2724
|
leavePanel();
|
|
2702
2725
|
show(uiSaid('set-carry-ask', '« {file} » into « {name} »? Its memory is replaced.', { file: file.name, name }),
|
|
2703
|
-
uiSaid('set-carry-go', 'Import'),
|
|
2704
|
-
try {
|
|
2705
|
-
const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
|
|
2706
|
-
const said = await r.json().catch(() => ({}));
|
|
2707
|
-
if (!r.ok) throw new Error(said.error ?? `HTTP ${r.status}`);
|
|
2708
|
-
show(uiSaid('set-carry-done', 'Imported from « {from} ».', { from: said.from?.name ?? file.name }), 'OK', () => { notice.hidden = true; focusTerminal(); });
|
|
2709
|
-
} catch (error) { show(error.message, 'Back to the terminal', enter); }
|
|
2710
|
-
}, () => { notice.hidden = true; focusTerminal(); });
|
|
2726
|
+
uiSaid('set-carry-go', 'Import'), () => carryImport(name, file, false), () => { notice.hidden = true; focusTerminal(); });
|
|
2711
2727
|
};
|
|
2712
2728
|
void paintAnswerer(); paintWakeups(); void paintTalkBox(); void paintShareHere();
|
|
2713
2729
|
paintMachine(here);
|
|
@@ -3251,11 +3267,13 @@
|
|
|
3251
3267
|
/* The places it may go, for a copy or a move of this one; the one chosen kept if it still is one. */
|
|
3252
3268
|
function cmPlaces(here) {
|
|
3253
3269
|
const machines = sharedMachines().filter((m) => !(cm.kind === 'move' && m.name === here.sharedMachine));
|
|
3254
|
-
|
|
3255
|
-
const
|
|
3270
|
+
/* Out of a shared machine (15-11): into one of its own, first; or into another shared one. */
|
|
3271
|
+
const own = cm.kind === 'copy' || Boolean(here.sharedMachine);
|
|
3272
|
+
const open = [...(own ? [''] : []), ...(cm.kind === 'move' && here.sharedMachine ? [] : [...machines.map((m) => m.name), 'new'])];
|
|
3256
3273
|
if (!open.includes(cm.place)) cm.place = open[0];
|
|
3257
3274
|
const cards = [];
|
|
3258
|
-
if (
|
|
3275
|
+
if (own) cards.push(cmCard('', uiSaid('set-where-own', 'Its own machine')));
|
|
3276
|
+
if (cm.kind === 'move' && here.sharedMachine) return { cards, open };
|
|
3259
3277
|
for (const m of machines) {
|
|
3260
3278
|
const small = [m.who.length ? uiSaid('set-cm-with', 'With {who}', { who: m.who.join(', ') }) : '', m.mb ? sizeWords(m.mb) : ''].filter(Boolean).join(' · ');
|
|
3261
3279
|
cards.push(cmCard(m.name, uiSaid('set-cm-shared', 'Shared machine « {m} »', { m: m.name }), small));
|
|
@@ -3300,7 +3318,7 @@
|
|
|
3300
3318
|
const here = conversations.find((x) => x.name === current);
|
|
3301
3319
|
if (DEVICE || !here || here.phase !== 'ready') return;
|
|
3302
3320
|
if (cm.of !== here.name) { $('cm-new-name').value = ''; $('cm-copy-title').value = ''; }
|
|
3303
|
-
Object.assign(cm, { of: here.name, kind, place: kind === 'copy' ? '' : (sharedMachines().find((m) => m.name !== here.sharedMachine)?.name ?? 'new') });
|
|
3321
|
+
Object.assign(cm, { of: here.name, kind, place: kind === 'copy' || here.sharedMachine ? '' : (sharedMachines().find((m) => m.name !== here.sharedMachine)?.name ?? 'new') });
|
|
3304
3322
|
$('machine-names').replaceChildren(...sharedMachines().map((m) => Object.assign(document.createElement('option'), { value: m.name })));
|
|
3305
3323
|
$('cm-copy-title').value = `${here.title ?? here.name} (copy)`;
|
|
3306
3324
|
/* Its sheep: two for a copy (the second slides out of the first), one walking for a move. */
|
|
@@ -3330,6 +3348,11 @@
|
|
|
3330
3348
|
$('cm-new-line')?.remove();
|
|
3331
3349
|
if (goes.machine && !goes.known) $('cm-check').prepend(Object.assign(document.createElement('p'), { id: 'cm-new-line', className: 'cm-not', textContent: uiSaid('set-cm-new-line', 'A new shared machine · {size}', { size: sizeWords(goes.machineMb) }) }));
|
|
3332
3350
|
$('cm-copy-part').hidden = cm.kind !== 'copy'; $('cm-move-part').hidden = cm.kind !== 'move';
|
|
3351
|
+
/* Out of a shared machine (15-11): its own machine is built, its place there removed -- the machine itself with the last one in it. */
|
|
3352
|
+
const out = cm.kind === 'move' && here.sharedMachine;
|
|
3353
|
+
const alone = out && !conversations.some((x) => x.name !== here.name && x.sharedMachine === here.sharedMachine);
|
|
3354
|
+
$('cm-stops').textContent = out ? uiSaid('set-cm-stops-out', 'Its tool stops for a few minutes') : uiSaid('set-cm-stops', 'Its tool stops for about a minute');
|
|
3355
|
+
$('cm-deleted').textContent = !out ? uiSaid('set-cm-deleted', 'Its own machine is deleted') : alone ? uiSaid('set-cm-shared-deleted', 'The shared machine « {m} » is deleted', { m: here.sharedMachine }) : uiSaid('set-cm-place-deleted', 'Its place in « {m} » is deleted', { m: here.sharedMachine });
|
|
3333
3356
|
$('cm-go').textContent = cm.kind === 'copy' ? uiSaid('set-cm-copy-go', 'Copy it') : uiSaid('set-cm-move-go', 'Move it');
|
|
3334
3357
|
$('cm-go').className = 'primary';
|
|
3335
3358
|
$('cm-choose').hidden = true; $('cm-check').hidden = false;
|
package/web/index.html
CHANGED
|
@@ -242,11 +242,11 @@
|
|
|
242
242
|
<p id="work-moved" class="hint" hidden></p>
|
|
243
243
|
<button type="button" id="work-move"></button>
|
|
244
244
|
</div>
|
|
245
|
-
<!-- CARRIED ELSEWHERE (#351): its tool's state (memory, sessions, settings) as one file; put back here. -->
|
|
245
|
+
<!-- CARRIED ELSEWHERE (#351): its tool's state (memory, sessions, settings), or everything of it (its home, its work, its accesses), as one file; put back here. -->
|
|
246
246
|
<div id="carry-box">
|
|
247
|
-
<div class="panel-top"><b data-said="set-carry">
|
|
248
|
-
<p class="hint" data-said="set-carry-hint">
|
|
249
|
-
<div class="row"><a id="carry-export" class="button" download data-said="set-carry-export">
|
|
247
|
+
<div class="panel-top"><b data-said="set-carry">Export / Import</b></div>
|
|
248
|
+
<p class="hint" data-said="set-carry-hint">Its AI's memory, or everything: to take elsewhere.</p>
|
|
249
|
+
<div class="row"><a id="carry-export" class="button" download data-said="set-carry-export">Its AI's memory</a><a id="carry-export-all" class="button" download data-said="set-carry-all">Everything (home, work, accesses)</a><button type="button" id="carry-import" data-said="set-carry-import">Import...</button><input type="file" id="carry-file" accept=".gz,application/gzip" hidden></div>
|
|
250
250
|
<p id="carry-said" class="hint" role="status" hidden></p>
|
|
251
251
|
</div>
|
|
252
252
|
<!-- WHEN ITS MACHINE IS SHORT (server/healthreact.mjs): you are told either way. -->
|
|
@@ -1520,8 +1520,8 @@
|
|
|
1520
1520
|
<p class="cm-box" data-said="set-cm-stay">You stay here · « Open it » when it is ready</p>
|
|
1521
1521
|
</div>
|
|
1522
1522
|
<div id="cm-move-part">
|
|
1523
|
-
<p class="cm-box" data-said="set-cm-stops">Its tool stops for about a minute</p>
|
|
1524
|
-
<p class="cm-box cm-danger" data-said="set-cm-deleted">Its own machine is deleted</p>
|
|
1523
|
+
<p class="cm-box" id="cm-stops" data-said="set-cm-stops">Its tool stops for about a minute</p>
|
|
1524
|
+
<p class="cm-box cm-danger" id="cm-deleted" data-said="set-cm-deleted">Its own machine is deleted</p>
|
|
1525
1525
|
</div>
|
|
1526
1526
|
<div class="cm-acts"><button type="button" id="cm-back" data-said="set-cm-back">Back</button><button type="button" class="primary" id="cm-go"></button></div>
|
|
1527
1527
|
</div>
|