clavarium 0.2.447-next.1 → 0.2.448-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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.447-next.1",
3
+ "version": "0.2.448-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.447-next.1",
9
+ "version": "0.2.448-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.447-next.1",
3
+ "version": "0.2.448-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
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 its tool's state, one archive (#351) POST .../import put back (same tool)
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,
@@ -306,7 +306,9 @@ export async function handleApi(request, response, conversations, headers, resou
306
306
  put back into a conversation of the same tool. Downloaded and sent by the person, from the page. */
307
307
  const carry = /^\/api\/conversations\/([^/]+)\/(export|import)$/.exec(pathname);
308
308
  if (carry && request.method === 'GET' && carry[2] === 'export') {
309
- const out = await conversations.exportState(decodeURIComponent(carry[1]));
309
+ /* ?all=1: everything of it -- its home, its work, what it was given (conversations.exportWhole). */
310
+ const n = decodeURIComponent(carry[1]);
311
+ const out = query.get('all') === '1' ? await conversations.exportWhole(n) : await conversations.exportState(n);
310
312
  response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(out.name)}` });
311
313
  out.stream.pipe(response);
312
314
  response.on('close', () => { try { out.child?.kill(); } catch { /* ended */ } });
@@ -314,7 +316,8 @@ export async function handleApi(request, response, conversations, headers, resou
314
316
  }
315
317
  if (carry && request.method === 'POST' && carry[2] === 'import') {
316
318
  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
- return send(200, await conversations.importState(decodeURIComponent(carry[1]), request)), true;
319
+ /* ?replaceWork=1: a whole export may replace the work folder that holds files (asked first, on the page). */
320
+ return send(200, await conversations.importState(decodeURIComponent(carry[1]), request, { replaceWork: query.get('replaceWork') === '1' })), true;
318
321
  }
319
322
  if (pathname.startsWith('/api/files/')) {
320
323
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
@@ -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 ?? {}) } })); }
@@ -0,0 +1,139 @@
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 work: every file, its carried parts left out; named work/... (a link's target left as it is). */
46
+ child = spawn('tar', ['-cf', '-', '-b', '1', '-C', workDir, `--exclude=./${CARRY}`, '--transform', 's,^\\.,work,S', '.'], { stdio: ['ignore', 'pipe', 'pipe'] });
47
+ child.stdout.pipe(gzip);
48
+ child.on('error', end);
49
+ child.on('close', (code) => end(code === 0 || code === 1 ? undefined : new Error(`its work folder was not read (exit ${code})`)));
50
+ });
51
+ home.pipe(gzip, { end: false });
52
+ return { stream: out, kill: () => { home.destroy(); try { child?.kill(); } catch { /* ended */ } end(); } };
53
+ }
54
+
55
+ /* The manifest of an export, read from its first entry only (it is always first): its JSON, or null; throws when
56
+ the file is not compressed as an export is. */
57
+ export async function readManifest(file) {
58
+ const gunzip = createGunzip();
59
+ const input = createReadStream(file);
60
+ input.pipe(gunzip);
61
+ let got = Buffer.alloc(0);
62
+ try {
63
+ for await (const chunk of gunzip) {
64
+ got = Buffer.concat([got, chunk]);
65
+ if (got.length < 512) continue;
66
+ const name = got.subarray(0, 100).toString().replace(/\0.*$/s, '');
67
+ if (name !== 'clavarium-conversation.json' && name !== './clavarium-conversation.json') return null;
68
+ const length = parseInt(got.subarray(124, 136).toString().replace(/\0.*$/s, '').trim(), 8);
69
+ if (!(length >= 0) || length > 1_000_000) return null;
70
+ if (got.length < 512 + length) continue;
71
+ try { return JSON.parse(got.subarray(512, 512 + length).toString()); } catch { return null; }
72
+ }
73
+ return null;
74
+ } finally { input.destroy(); gunzip.destroy(); }
75
+ }
76
+
77
+ /* A work folder holds nothing of its own (its carried parts aside). */
78
+ export const workEmpty = (dir) => readdirSync(dir).every((e) => e === CARRY);
79
+
80
+ /* Unpacked here, into `into` (an empty folder): tar refuses names that climb out (..) and leading slashes. */
81
+ export function unpackHere(file, into) {
82
+ mkdirSync(into, { recursive: true });
83
+ return new Promise((ok, fail) => {
84
+ const child = spawn('tar', ['-xzf', file, '-C', into, '--no-same-owner'], { stdio: ['ignore', 'ignore', 'pipe'] });
85
+ let said = '';
86
+ child.stderr.on('data', (d) => { said = (said + d).slice(-500); });
87
+ child.on('error', fail);
88
+ child.on('close', (code) => (code === 0 ? ok() : fail(new Error(said.trim().split('\n').pop() || `exit ${code}`))));
89
+ });
90
+ }
91
+
92
+ /* ITS WORK PUT BACK, here: what it holds now thrown away only when asked (`replace`), then each entry of the
93
+ export's work/ moved in (the same disk: a rename). */
94
+ export function restoreWork(from, workDir, replace) {
95
+ if (replace) for (const e of readdirSync(workDir)) if (e !== CARRY) rmSync(join(workDir, e), { recursive: true, force: true });
96
+ let entries = [];
97
+ try { entries = readdirSync(from); } catch { return; }
98
+ for (const e of entries) if (e !== CARRY) renameSync(join(from, e), join(workDir, e));
99
+ }
100
+
101
+ /* WHAT IT WAS GIVEN, for a whole export, each by its id: a folder, a repository or a mailbox by its asset
102
+ (folder:x, git:x, mailbox:x), a secret by its NAME ONLY (never its value), its Tether targets and its lists by
103
+ theirs, with their levels; and whether its chat is on, its guide's lines. The same as a copy gives (copyRights). */
104
+ export function accessesOf({ folders, secrets, tethers, binders, talk, guide }, name) {
105
+ return {
106
+ resources: folders.of(name).map((r) => ({ id: folders.assetOf(folders.get(r.name) ?? { name: r.name }), access: r.access })),
107
+ secrets: secrets.of(name).map(String),
108
+ tethers: tethers?.grantsOf(name) ?? [],
109
+ binders: binders?.grantsOf(name) ?? [],
110
+ talk: talk.isOn(name) === true,
111
+ guide: guide.lines(name),
112
+ };
113
+ }
114
+
115
+ /* ITS IMPORT: each given again where the same id exists here, with the same level, through the calls a copy uses;
116
+ the rest said back, to link by hand. -> { linked: [id], missing: [id] } */
117
+ export async function relinkAccesses({ folders, secrets, tethers, binders, talk, guide, gitKeeper }, name, given = {}) {
118
+ const linked = []; const missing = [];
119
+ const list = (v) => (Array.isArray(v) ? v : []);
120
+ for (const r of list(given.resources)) {
121
+ const id = String(r?.id ?? ''); const at = id.indexOf(':');
122
+ const resource = at > 0 ? folders.get(id.slice(at + 1)) : undefined;
123
+ if (!resource || folders.assetOf(resource) !== id || (r.access !== 'read' && r.access !== 'write')) { missing.push(id); continue; }
124
+ try {
125
+ if (r.access === 'write') gitKeeper?.beforeWriter(resource.name, name, true);
126
+ await folders.attach(name, resource.name, r.access); linked.push(id);
127
+ } catch { missing.push(id); }
128
+ }
129
+ for (const s of list(given.secrets)) {
130
+ try { secrets.attach(name, String(s), true); linked.push(`secret:${s}`); } catch { missing.push(`secret:${s}`); }
131
+ }
132
+ for (const [kind, keeper, grants] of [['tether', tethers, list(given.tethers)], ['binder', binders, list(given.binders)]]) {
133
+ const absent = keeper ? keeper.regrant(name, grants) : grants.map((g) => g?.id);
134
+ for (const g of grants) (absent.includes(g?.id) ? missing : linked).push(`${kind}:${g?.id}`);
135
+ }
136
+ if (given.talk === true) await talk.set(name, true).catch(() => {});
137
+ if (list(given.guide).length) await guide.setLines(name, given.guide).catch(() => {});
138
+ return { linked, missing };
139
+ }
@@ -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. */
@@ -971,16 +976,88 @@ export class Conversations {
971
976
  return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium.tar.gz`, stream: child.stdout, child };
972
977
  }
973
978
 
979
+ /* EVERYTHING OF IT, CARRIED (14-11, its owner's ask): its manifest with what it was given (accesses, by id), its
980
+ whole home (without HOME_LEFT_OUT, carry.mjs) and its work folder, as one .tar.gz streamed to the person. Its
981
+ home is written by its machine into its work folder (never through the VM manager's output), then sent from
982
+ here followed by its work, read here. Its work must be kept on this server. -> { name, stream, child } */
983
+ async exportWhole(name) {
984
+ const c = this.#store.get(name);
985
+ if (!c) throw new Refusal(404, 'No such conversation.');
986
+ const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
987
+ if (!workDir) throw new Refusal(409, 'Its work is on its own machine\'s disk: keep it here first (Its files), then export it.');
988
+ if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
989
+ const tool = this.#tools.find((t) => t.id === c.tool);
990
+ const accesses = await this.accessesOf(name);
991
+ 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 });
992
+ const id = `whole-${Date.now()}`;
993
+ /* In its machine: the manifest, then its home as home/ (a link's target left as it is), one block per record
994
+ so that its work can follow it (carry.mjs). Globs off: the words left out are given to tar as they are. */
995
+ const script = 'set -f; m=$(mktemp -d) || exit 2; printf "%s" "$1" > "$m/clavarium-conversation.json"; '
996
+ + 'ex=""; for a in $2; do ex="$ex --exclude=$a"; done; mkdir -p /work/' + CARRY + '; '
997
+ + '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"; '
998
+ /* 1: a file changed while read: the archive is whole all the same. */
999
+ + '[ "$rc" -le 1 ]';
1000
+ const homeTar = join(workDir, CARRY, `${id}.tar`);
1001
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, homeExcludes(tool?.state?.skip ?? []).join(' '), id]);
1002
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'ignore', 'pipe'] });
1003
+ let said = '';
1004
+ child.stderr.on('data', (d) => { said = (said + d).slice(-2000); });
1005
+ const code = await new Promise((ok) => { child.on('error', () => ok(-1)); child.on('close', ok); });
1006
+ const drop = () => rmSync(homeTar, { force: true });
1007
+ if (code !== 0) { drop(); throw new Refusal(502, `Not exported: ${firstLine(said) || `exit ${code}`}`); }
1008
+ let out;
1009
+ try { out = wholeStream(homeTar, workDir, drop); } catch (error) { throw new Refusal(502, `Not exported: ${error.message}`); }
1010
+ return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium-all.tar.gz`, stream: out.stream, child: { kill: out.kill } };
1011
+ }
1012
+
974
1013
  /* PUT BACK an exported state in this conversation (same tool): its tool stopped, the archive unpacked in
975
1014
  its home, its tool started again, taking up its last session. -> { tool, from } */
976
- async importState(name, input) {
1015
+ /* A WHOLE export (exportWhole) puts back its home, its work folder and its accesses: its work only into an empty
1016
+ one, unless `replaceWork` -- what is there is never thrown away silently. -> { tool, from, whole, linked, toLink } */
1017
+ async importState(name, input, { replaceWork = false } = {}) {
977
1018
  const c = this.#busyCheck(name);
978
1019
  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
1020
  if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
1021
+ /* Received first, whole, beside its work when it has one here (the same disk its work goes to). */
1022
+ const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
1023
+ const id = `up-${Date.now()}`;
1024
+ const aside = workDir ? join(workDir, CARRY) : mkdtempSync(join(tmpdir(), 'clv-import-'));
1025
+ mkdirSync(aside, { recursive: true });
1026
+ const file = join(aside, `${id}.tgz`); const stage = join(aside, id);
1027
+ try {
1028
+ if (typeof input === 'string') copyFileSync(input, file);
1029
+ 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); });
1030
+ const manifest = await readManifest(file).catch((error) => { throw new Refusal(502, `Not imported: ${error.message}`); });
1031
+ if (manifest?.kind !== 'clavarium-conversation') throw new Refusal(400, 'This is not an exported conversation.');
1032
+ if (manifest.tool !== c.tool) throw new Refusal(400, 'This export is of another tool: import it into a conversation with that tool.');
1033
+ if (!manifest.whole) {
1034
+ 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.`);
1035
+ await this.#stopTool(name);
1036
+ try { return { tool: c.tool, from: await this.#unpack(name, c.tool, file) }; } finally { this.ready(name); }
1037
+ }
1038
+ 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.');
1039
+ 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' });
1040
+ await unpackHere(file, stage).catch((error) => { throw new Refusal(400, `Not imported: ${error.message}`); });
1041
+ rmSync(file, { force: true });
1042
+ await this.#stopTool(name);
1043
+ try {
1044
+ /* Its home: in its machine, each part of home/ in place of the old (as #unpackFrom does). */
1045
+ const script = 'set -e; s="/work/' + CARRY + '/$1/home"; [ -d "$s" ] || exit 0; '
1046
+ + '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';
1047
+ const r = await this.#vms.exec(name, ['sh', '-c', script, 'import', id], { timeoutMs: 30 * 60_000 });
1048
+ if (r.code !== 0) throw new Refusal(502, `Not imported: ${firstLine(r.stderr) || `exit ${r.code}`}`);
1049
+ restoreWork(join(stage, 'work'), workDir, replaceWork);
1050
+ const { linked, missing } = await this.relink(name, manifest.accesses ?? {});
1051
+ return { tool: c.tool, from: { name: manifest.name, at: manifest.at }, whole: true, linked, toLink: missing };
1052
+ } finally { this.ready(name); }
1053
+ } finally {
1054
+ rmSync(file, { force: true }); rmSync(stage, { recursive: true, force: true });
1055
+ if (!workDir) rmSync(aside, { recursive: true, force: true });
1056
+ }
1057
+ }
1058
+ async #stopTool(name) {
981
1059
  this.drop(name);
982
1060
  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
1061
  }
985
1062
 
986
1063
  /* An exported state unpacked into its home (its tool stopped by the caller): its manifest checked, then each
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;
@@ -183,8 +183,10 @@ export const SETTINGS_WORDS_FR = {
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
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',
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': 'La mémoire de son outil', 'set-carry-hint': 'Mémoire, sessions, réglages : à emporter.',
187
- 'set-carry-export': 'Exporter', 'set-carry-import': 'Importer…', 'set-carry-go': 'Importer',
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',
@@ -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'), async () => {
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);
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">Its tool's memory</b></div>
248
- <p class="hint" data-said="set-carry-hint">Memory, sessions, settings: to take elsewhere.</p>
249
- <div class="row"><a id="carry-export" class="button" download data-said="set-carry-export">Export</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>
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. -->