clavarium 0.2.395-next.1 → 0.2.397-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.
@@ -21,17 +21,18 @@ node "$(dirname "$0")/json-set.mjs" .claude/settings.json "$keys" \
21
21
  # work folder trusted -- in its own file, as it records them itself; nothing to answer in the terminal.
22
22
  node "$(dirname "$0")/json-set.mjs" .claude.json '{"hasCompletedOnboarding": true, "projects": {"/work": {"hasTrustDialogAccepted": true}}}' \
23
23
  || echo "launch: Claude Code may ask its first questions in the terminal" >&2
24
- # ITS TOOLS (MCP), EACH THROUGH THE RELAY (02-11): a tool updated on the machine is taken up between two of
25
- # its requests -- whatever the tool, the session never restarted, nothing for the agent to do. Declared
26
- # once, by Claude Code itself (its other servers kept); an older declaration without the relay is replaced.
24
+ # ITS TOOLS (MCP), EACH THROUGH THE SHARED HOST (11-11, #350; the relay since 02-11): one program for all its
25
+ # tools (mcp-sock.sh -> tools-host.mjs), a tool updated on the machine taken up between two of its requests,
26
+ # the session never restarted. Declared once, by Claude Code itself (its other servers kept); an older
27
+ # declaration (the relay alone) is replaced.
27
28
  # Looked for in its settings first, since asking Claude Code takes seconds. Nothing stops the start.
28
- relay="$(dirname "$0")/mcp-relay.mjs"
29
+ relay="$(dirname "$0")/mcp-sock.sh"
29
30
  tool() { # NAME FOLDER COMMAND ARGS...
30
31
  name="$1"; folder="$2"; shift 2
31
- if grep -q "\"$folder\"" "$HOME/.claude.json" 2>/dev/null && grep -q "mcp-relay.mjs" "$HOME/.claude.json" 2>/dev/null \
32
- && node -e 'const d=require(process.argv[1]);const s=d.mcpServers?.[process.argv[2]];const a=JSON.stringify(s?.args??[]);process.exit(a.includes("mcp-relay.mjs")&&a.includes(JSON.stringify(process.argv[3]))?0:1)' "$HOME/.claude.json" "$name" "$1" 2>/dev/null; then return 0; fi
32
+ if grep -q "\"$folder\"" "$HOME/.claude.json" 2>/dev/null && grep -q "mcp-sock.sh" "$HOME/.claude.json" 2>/dev/null \
33
+ && node -e 'const d=require(process.argv[1]);const s=d.mcpServers?.[process.argv[2]];const a=JSON.stringify(s?.args??[]);process.exit(a.includes("mcp-sock.sh")&&a.includes(JSON.stringify(process.argv[3]))?0:1)' "$HOME/.claude.json" "$name" "$1" 2>/dev/null; then return 0; fi
33
34
  claude mcp remove --scope user "$name" >/dev/null 2>&1
34
- claude mcp add --scope user "$name" -- node "$relay" "$@" >/dev/null 2>&1 \
35
+ claude mcp add --scope user "$name" -- sh "$relay" "$@" >/dev/null 2>&1 \
35
36
  || echo "launch: $name was not given to Claude Code as tools: the command $name still works" >&2
36
37
  }
37
38
  # Parley, the chat of the conversation, when it has one: the version installed on the machine (parley-mcp),
@@ -5,7 +5,7 @@
5
5
  mode="$1"; shift
6
6
  case "$mode" in full|ask) ;; *) echo "launch: the first argument is full or ask" >&2; exit 64 ;; esac
7
7
  [ $# -gt 0 ] || { echo "launch: no command to run" >&2; exit 64; }
8
- here="$(dirname "$0")"; relay="$here/mcp-relay.mjs"
8
+ here="$(dirname "$0")"; relay="$here/mcp-sock.sh"
9
9
  chat="${PARLEY_DIR:-/work/.parley}"; docket="/work/.docket"; tether="/work/.tether"
10
10
  # ITS SETTINGS (~/.codex/config.toml), in a block of their own, the rest kept: its work folder trusted (no
11
11
  # question at its first start), and its tools (MCP) each through the relay -- a tool updated on the
@@ -14,15 +14,15 @@ block='[projects."/work"]
14
14
  trust_level = "trusted"'
15
15
  if [ -f "$chat/server.mjs" ] && command -v parley-mcp >/dev/null 2>&1; then block="$block
16
16
  [mcp_servers.parley]
17
- command = \"node\"
17
+ command = \"sh\"
18
18
  args = [\"$relay\", \"parley-mcp\", \"--dir\", \"$chat\"]"; fi
19
19
  if [ -f "$chat/server.mjs" ] && command -v docket-mcp >/dev/null 2>&1; then block="$block
20
20
  [mcp_servers.docket]
21
- command = \"node\"
21
+ command = \"sh\"
22
22
  args = [\"$relay\", \"docket-mcp\", \"--dir\", \"$docket\"]"; fi
23
23
  if command -v tether-mcp >/dev/null 2>&1; then block="$block
24
24
  [mcp_servers.tether]
25
- command = \"node\"
25
+ command = \"sh\"
26
26
  args = [\"$relay\", \"tether-mcp\", \"--dir\", \"$tether\"]"; fi
27
27
  node "$here/toml-block.mjs" .codex/config.toml tools "$block" \
28
28
  || echo "launch: Codex may ask its first questions, and has not its tools (MCP)" >&2
@@ -0,0 +1,31 @@
1
+ #!/bin/sh
2
+ # A TOOL OF THE CONVERSATION, THROUGH THE SHARED HOST (11-11, card #350): what the agent starts for each of its
3
+ # tools (MCP) -- the same arguments as mcp-relay.mjs, COMMAND ARGS... -- but instead of a Node program of its
4
+ # own, a few lines of sh and netcat: the session goes to tools-host.mjs, one program for all the tools of this
5
+ # user. Anything missing (netcat, the host not starting): the relay of before, as if nothing changed.
6
+ here="$(dirname "$0")"
7
+ fallback() { exec node "$here/mcp-relay.mjs" "$@"; }
8
+ command -v nc >/dev/null 2>&1 || fallback "$@"
9
+ dir="${XDG_RUNTIME_DIR:-/tmp}/clavarium-tools-$(id -u)"
10
+ # Its folder: this user's alone (700), or the relay of before.
11
+ mkdir -p "$dir" 2>/dev/null && [ -O "$dir" ] && chmod 700 "$dir" 2>/dev/null || fallback "$@"
12
+ sock="$dir/host.sock"
13
+ up() { [ -S "$sock" ] && nc -zU "$sock" 2>/dev/null; }
14
+ if ! up; then
15
+ (
16
+ flock 9 # the host itself never holds the lock (9>&- below): two tools starting at once both get in
17
+ if ! up; then
18
+ # its own session (setsid): an agent ending its tools never ends the host the others use
19
+ ns=""; command -v setsid >/dev/null 2>&1 && ns=setsid
20
+ $ns nohup node "$here/tools-host.mjs" "$dir" >>"$dir/host.log" 2>&1 </dev/null 9>&- &
21
+ i=0; while [ $i -lt 30 ] && ! up; do sleep 0.1; i=$((i + 1)); done
22
+ fi
23
+ ) 9>"$dir/lock"
24
+ fi
25
+ up || fallback "$@"
26
+ # Its first line: which tool, with which arguments (JSON); then the session, both ways.
27
+ json() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'; }
28
+ head="{\"command\":\"$(json "$1")\",\"args\":["; shift
29
+ sep=""; for a in "$@"; do head="$head$sep\"$(json "$a")\""; sep=","; done
30
+ head="$head]}"
31
+ { printf '%s\n' "$head"; exec cat; } | exec nc -NU "$sock"
@@ -0,0 +1,93 @@
1
+ /* ONE PROGRAM FOR ALL THE TOOLS OF A CONVERSATION (11-11, card #350). Each tool (Parley, Docket, Tether...) was
2
+ * given to the agent as its own Node program, under its own relay: two Node programs a tool, ~435 MB for three.
3
+ * Here they share one: each session of a tool runs in a worker thread of this host, the same file started the
4
+ * same way (its own argv, stdin and stdout), so a tool runs unchanged. ~100 MB for three.
5
+ *
6
+ * The agent still starts one command a tool (mcp-sock.sh, a few lines of sh and netcat): it connects to this
7
+ * host's socket, says on its first line which tool and with which arguments, then the session flows through.
8
+ * The relay is the same as before (mcp-relay.mjs): a version installed under a session is taken up between two
9
+ * requests -- its worker replaced, the session told its tools may have changed.
10
+ *
11
+ * The socket lives in a folder of this user alone (700): in a machine shared by several conversations, one
12
+ * conversation never reaches another's tools. Nobody connected for 10 minutes: the host stops; the next tool
13
+ * started starts it again. */
14
+ import { createServer } from 'node:net';
15
+ import { Worker } from 'node:worker_threads';
16
+ import { spawn } from 'node:child_process';
17
+ import { PassThrough } from 'node:stream';
18
+ import { createInterface } from 'node:readline';
19
+ import { existsSync, realpathSync, rmSync, statSync, readFileSync } from 'node:fs';
20
+ import { delimiter, join, isAbsolute } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { relay, packageOf } from './mcp-relay.mjs';
23
+
24
+ const say = (text) => process.stderr.write(`${new Date().toISOString()} tools-host: ${text}\n`);
25
+
26
+ /* The script a command runs, when it is a Node script (node FILE, or a command whose file is one): its path. */
27
+ export function scriptOf(command, args, path = process.env.PATH ?? '') {
28
+ if (/(^|\/)node$/.test(command)) return args[0] ? { file: args[0], args: args.slice(1) } : null;
29
+ const found = isAbsolute(command) ? command : path.split(delimiter).map((d) => join(d, command)).find((f) => { try { return statSync(f).isFile(); } catch { return false; } });
30
+ if (!found) return null;
31
+ let file; try { file = realpathSync(found); } catch { return null; }
32
+ if (/\.(mjs|cjs|js)$/.test(file)) return { file, args };
33
+ try { if (/^#!.*\bnode\b/.test(readFileSync(file, 'utf8').slice(0, 120))) return { file, args }; } catch { /* unreadable */ }
34
+ return null;
35
+ }
36
+
37
+ /* A worker that looks like a child process to the relay: stdin, stdout, 'exit', kill. Not a Node script: a real
38
+ child, as before. */
39
+ export function workerSpawner(command, args, opts = {}) {
40
+ const script = scriptOf(command, args);
41
+ if (!script) return spawn(command, args, opts);
42
+ const w = new Worker(script.file, { argv: script.args, stdin: true, stdout: true, env: { ...(opts.env ?? process.env) } });
43
+ w.on('error', (error) => say(`${script.file}: ${error?.stack ?? error}`));
44
+ const child = {
45
+ stdin: w.stdin, stdout: w.stdout,
46
+ on(event, f) { if (event === 'exit') w.on('exit', f); return child; },
47
+ kill() { void w.terminate(); },
48
+ };
49
+ return child;
50
+ }
51
+
52
+ /* One session: its first line names the tool { command, args }; the rest is the session, relayed to a worker. */
53
+ export function session(socket, { spawner = workerSpawner } = {}) {
54
+ const input = new PassThrough();
55
+ let header = null;
56
+ const lines = createInterface({ input: socket });
57
+ lines.on('line', (line) => {
58
+ if (header) { input.write(`${line}\n`); return; }
59
+ try { header = JSON.parse(line); } catch { header = null; }
60
+ if (!header || typeof header.command !== 'string' || !Array.isArray(header.args)) { socket.end(); return; }
61
+ const script = scriptOf(header.command, header.args);
62
+ const target = script?.file ?? header.command;
63
+ relay({ command: header.command, args: header.args.map(String), packageJson: packageOf(target) ?? '/nonexistent/package.json',
64
+ input, output: socket, spawner, log: say });
65
+ });
66
+ lines.on('close', () => input.end());
67
+ socket.on('error', () => { /* the agent went: its worker ends with its input */ });
68
+ }
69
+
70
+ export function host(dir, { idleMs = 10 * 60_000 } = {}) {
71
+ const sock = join(dir, 'host.sock');
72
+ rmSync(sock, { force: true });
73
+ let open = 0; let idle = null;
74
+ const server = createServer((socket) => {
75
+ open++; clearTimeout(idle);
76
+ socket.on('close', () => { open--; if (open === 0) idle = setTimeout(() => { server.close(); rmSync(sock, { force: true }); process.exit(0); }, idleMs); });
77
+ session(socket);
78
+ });
79
+ server.listen(sock, () => say(`listening (${process.pid})`));
80
+ idle = setTimeout(() => { if (open === 0) { server.close(); rmSync(sock, { force: true }); process.exit(0); } }, idleMs);
81
+ return server;
82
+ }
83
+
84
+ const HERE = fileURLToPath(import.meta.url);
85
+ const main = (() => { try { return realpathSync(process.argv[1] ?? '') === realpathSync(HERE); } catch { return false; } })();
86
+ if (main) {
87
+ const dir = process.argv[2];
88
+ if (!dir || !existsSync(dir)) { say('a folder of its own, given first'); process.exit(64); }
89
+ /* Its folder: this user's, closed to others -- or nothing is served. */
90
+ const st = statSync(dir);
91
+ if (st.uid !== process.getuid() || (st.mode & 0o077) !== 0) { say(`${dir} is not closed to others: nothing served`); process.exit(77); }
92
+ host(dir);
93
+ }
@@ -5,7 +5,7 @@
5
5
  mode="$1"; shift
6
6
  case "$mode" in full|ask) ;; *) echo "launch: the first argument is full or ask" >&2; exit 64 ;; esac
7
7
  [ $# -gt 0 ] || { echo "launch: no command to run" >&2; exit 64; }
8
- here="$(dirname "$0")"; relay="$here/mcp-relay.mjs"
8
+ here="$(dirname "$0")"; relay="$here/mcp-sock.sh"
9
9
  chat="${PARLEY_DIR:-/work/.parley}"; docket="/work/.docket"; tether="/work/.tether"
10
10
  # ITS KEY: a secret named MISTRAL_API_KEY given to the conversation is in its environment; Vibe reads it
11
11
  # there, and asks nothing. Without it, Vibe asks for it in its terminal at its first start.
@@ -15,19 +15,19 @@ if [ -f "$chat/server.mjs" ] && command -v parley-mcp >/dev/null 2>&1; then bloc
15
15
  [[mcp_servers]]
16
16
  name = \"parley\"
17
17
  transport = \"stdio\"
18
- command = \"node\"
18
+ command = \"sh\"
19
19
  args = [\"$relay\", \"parley-mcp\", \"--dir\", \"$chat\"]"; fi
20
20
  if [ -f "$chat/server.mjs" ] && command -v docket-mcp >/dev/null 2>&1; then block="$block
21
21
  [[mcp_servers]]
22
22
  name = \"docket\"
23
23
  transport = \"stdio\"
24
- command = \"node\"
24
+ command = \"sh\"
25
25
  args = [\"$relay\", \"docket-mcp\", \"--dir\", \"$docket\"]"; fi
26
26
  if command -v tether-mcp >/dev/null 2>&1; then block="$block
27
27
  [[mcp_servers]]
28
28
  name = \"tether\"
29
29
  transport = \"stdio\"
30
- command = \"node\"
30
+ command = \"sh\"
31
31
  args = [\"$relay\", \"tether-mcp\", \"--dir\", \"$tether\"]"; fi
32
32
  node "$here/toml-block.mjs" .vibe/config.toml tools "$block" \
33
33
  || echo "launch: Vibe has not its tools (MCP)" >&2
package/config/tools.json CHANGED
@@ -12,6 +12,16 @@
12
12
  "--continue"
13
13
  ],
14
14
  "memoryMb": 2048,
15
+ "state": {
16
+ "keep": [
17
+ ".claude",
18
+ ".claude.json"
19
+ ],
20
+ "skip": [
21
+ ".claude/shell-snapshots",
22
+ ".claude/statsig"
23
+ ]
24
+ },
15
25
  "rights": {
16
26
  "full": [
17
27
  "--dangerously-skip-permissions",
@@ -76,6 +86,15 @@
76
86
  "--continue"
77
87
  ],
78
88
  "memoryMb": 2048,
89
+ "state": {
90
+ "keep": [
91
+ ".config/opencode",
92
+ ".local/share/opencode"
93
+ ],
94
+ "skip": [
95
+ ".local/share/opencode/log"
96
+ ]
97
+ },
79
98
  "rights": {
80
99
  "full": [
81
100
  "--auto"
@@ -156,6 +175,14 @@
156
175
  "--last"
157
176
  ],
158
177
  "memoryMb": 2048,
178
+ "state": {
179
+ "keep": [
180
+ ".codex"
181
+ ],
182
+ "skip": [
183
+ ".codex/log"
184
+ ]
185
+ },
159
186
  "rights": {
160
187
  "full": [
161
188
  "--dangerously-bypass-approvals-and-sandbox"
@@ -190,6 +217,11 @@
190
217
  "--continue"
191
218
  ],
192
219
  "memoryMb": 2048,
220
+ "state": {
221
+ "keep": [
222
+ ".vibe"
223
+ ]
224
+ },
193
225
  "rights": {
194
226
  "full": [
195
227
  "--auto-approve"
@@ -246,6 +278,11 @@
246
278
  "latest"
247
279
  ],
248
280
  "memoryMb": 2048,
281
+ "state": {
282
+ "keep": [
283
+ ".gemini"
284
+ ]
285
+ },
249
286
  "rights": {
250
287
  "full": [
251
288
  "--yolo",
@@ -275,6 +312,13 @@
275
312
  "-l"
276
313
  ],
277
314
  "memoryMb": 768,
315
+ "state": {
316
+ "keep": [
317
+ ".bash_history",
318
+ ".bashrc",
319
+ ".profile"
320
+ ]
321
+ },
278
322
  "install": []
279
323
  }
280
324
  ]
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.395-next.1",
3
+ "version": "0.2.397-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.395-next.1",
9
+ "version": "0.2.397-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.395-next.1",
3
+ "version": "0.2.397-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,6 +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
10
  * POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
10
11
  * asleep: checked and kept for its wake, as `sizeAtWake` (200)
11
12
  * POST /api/conversations/<name>/machine {action: start|stop|restart|sleep|force|force-now}: done on its machine,
@@ -292,6 +293,20 @@ export async function handleApi(request, response, conversations, headers, resou
292
293
  }
293
294
  return send(201, await importFile(attached('write'), query.get('p') ?? '', query.get('name') ?? '', request, { exists: query.get('exists') ?? 'keep', dir: query.get('dir') ?? '', batch: query.get('batch') ?? undefined })), true;
294
295
  }
296
+ /* A CONVERSATION CARRIED ELSEWHERE (#351): its tool's state as one archive, streamed from its machine;
297
+ put back into a conversation of the same tool. Downloaded and sent by the person, from the page. */
298
+ const carry = /^\/api\/conversations\/([^/]+)\/(export|import)$/.exec(pathname);
299
+ if (carry && request.method === 'GET' && carry[2] === 'export') {
300
+ const out = await conversations.exportState(decodeURIComponent(carry[1]));
301
+ response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(out.name)}` });
302
+ out.stream.pipe(response);
303
+ response.on('close', () => { try { out.child?.kill(); } catch { /* ended */ } });
304
+ return true;
305
+ }
306
+ if (carry && request.method === 'POST' && carry[2] === 'import') {
307
+ if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
308
+ return send(200, await conversations.importState(decodeURIComponent(carry[1]), request)), true;
309
+ }
295
310
  if (pathname.startsWith('/api/files/')) {
296
311
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
297
312
  const answer = await changeRoute(request.method, pathname.slice('/api'.length), query, request, attached);
@@ -13,6 +13,7 @@ import { WORK, VM_USER, SHARING_STEP, stepLine } from './vm.mjs';
13
13
  import { resumeOrFresh } from './tools.mjs';
14
14
  import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
15
15
  import { availableParallelism } from 'node:os';
16
+ import { spawn } from 'node:child_process';
16
17
 
17
18
  export const SESSION = 'main';
18
19
  export const STOP_DELAY_MS = 60_000;
@@ -825,6 +826,60 @@ export class Conversations {
825
826
  return true;
826
827
  }
827
828
 
829
+ /* CARRIED ELSEWHERE (11-11, #351): what the conversation is beyond /work -- its tool's state, where its
830
+ entry in config/tools.json says it is (`state.keep`, without `state.skip`) -- as one .tar.gz streamed
831
+ from its machine, a manifest first (clavarium-conversation.json: its tool, its name, its size). Nothing
832
+ of the tool is known here: any tool that says where its state is can be exported, imported, moved.
833
+ The machine must run (its home is in it). -> { name: the file's name, stream } */
834
+ async exportState(name) {
835
+ const c = this.#store.get(name);
836
+ if (!c) throw new Refusal(404, 'No such conversation.');
837
+ const tool = this.#tools.find((t) => t.id === c.tool);
838
+ if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: it cannot be exported.`);
839
+ if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
840
+ const manifest = JSON.stringify({ kind: 'clavarium-conversation', version: 1, 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() });
841
+ /* In its machine: the manifest written aside, then one archive -- the manifest first, then what is kept
842
+ (a path it has not made yet left out), the cache left out. */
843
+ /* (Its paths are plain -- letters, digits, . _ / - -- checked by tools.mjs: given as words.) */
844
+ const script = 'set -e; m=$(mktemp -d); printf "%s" "$1" > "$m/clavarium-conversation.json"; '
845
+ + 'ex=""; for a in $2; do ex="$ex --exclude=./$a"; done; ks=""; for a in $3; do if [ -e "$HOME/$a" ]; then ks="$ks ./$a"; fi; done; '
846
+ + 'tar -czf - -C "$m" clavarium-conversation.json -C "$HOME" $ex $ks; rm -rf "$m"';
847
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, tool.state.skip.join(' '), tool.state.keep.join(' ')]);
848
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'ignore'] });
849
+ return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium.tar.gz`, stream: child.stdout, child };
850
+ }
851
+
852
+ /* PUT BACK an exported state in this conversation (same tool): its tool stopped, the archive unpacked in
853
+ its home, its tool started again, taking up its last session. -> { tool, from } */
854
+ async importState(name, input) {
855
+ const c = this.#busyCheck(name);
856
+ const tool = this.#tools.find((t) => t.id === c.tool);
857
+ 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.`);
858
+ if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
859
+ this.drop(name);
860
+ await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'kill-server'], { timeoutMs: 10_000 }).catch(() => {});
861
+ /* Unpacked aside first: its manifest read, its tool checked; then moved into the home. */
862
+ /* Aside in the home itself (never /tmp, which may be memory): then each part moved in place of the old. */
863
+ const script = 'set -e; m=$(mktemp -d "$HOME/.clavarium-import.XXXXXX"); trap \'rm -rf "$m"\' EXIT; tar -xzf - -C "$m"; '
864
+ + 'grep -q "\\"kind\\":\\"clavarium-conversation\\"" "$m/clavarium-conversation.json" || { echo "not an exported conversation" >&2; exit 3; }; '
865
+ + 'grep -q "\\"tool\\":\\"$1\\"" "$m/clavarium-conversation.json" || { echo "another tool" >&2; exit 4; }; '
866
+ + 'cat "$m/clavarium-conversation.json"; rm -f "$m/clavarium-conversation.json"; '
867
+ + 'for e in "$m"/.[!.]* "$m"/*; do if [ ! -e "$e" ]; then continue; fi; b=$(basename "$e"); rm -rf "$HOME/$b"; mv "$e" "$HOME/$b"; done';
868
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'import', c.tool]);
869
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });
870
+ const out = []; const err = [];
871
+ child.stdout.on('data', (d) => out.push(d)); child.stderr.on('data', (d) => err.push(d));
872
+ input.pipe(child.stdin);
873
+ child.stdin.on('error', () => { /* it stopped reading: said below */ });
874
+ const code = await new Promise((ok) => child.on('close', ok));
875
+ this.ready(name);
876
+ if (code === 3) throw new Refusal(400, 'This is not an exported conversation.');
877
+ if (code === 4) throw new Refusal(400, `This export is of another tool: import it into a conversation with that tool.`);
878
+ if (code !== 0) throw new Refusal(502, `Not imported: ${firstLine(Buffer.concat(err).toString()) || `exit ${code}`}`);
879
+ let from = null; try { from = JSON.parse(Buffer.concat(out).toString()); } catch { /* said nothing */ }
880
+ return { tool: c.tool, from: from ? { name: from.name, at: from.at } : null };
881
+ }
882
+
828
883
  async #fixup(name, tool) {
829
884
  for (const step of tool.fixups) {
830
885
  const r = await this.#vms.exec(name, step.argv, { timeoutMs: 120_000 }).catch(() => ({ code: 1 }));
@@ -159,6 +159,9 @@ export const SETTINGS_WORDS_FR = {
159
159
  'set-na-k-mcp': 'Serveur MCP', 'set-cx-mcp': 'serveur MCP',
160
160
  'set-mcp-head': 'Ajouter un serveur MCP', 'set-mcp-hint': 'Ses outils pour vos IA ; la clé reste ici.',
161
161
  'set-mcp-name': 'Nom', 'set-mcp-url': 'Adresse', 'set-mcp-key': 'Clé', 'set-mcp-add': 'Ajouter',
162
+ 'set-carry': 'La mémoire de son outil', 'set-carry-hint': 'Mémoire, sessions, réglages : à emporter.',
163
+ 'set-carry-export': 'Exporter', 'set-carry-import': 'Importer…', 'set-carry-go': 'Importer',
164
+ 'set-carry-ask': '« {file} » dans « {name} » ? Mémoire remplacée.', 'set-carry-done': 'Importé depuis « {from} ».',
162
165
  'set-mcp-drop': 'Collez ici la configuration du service', 'set-mcp-drop-hint': 'le bloc { "mcpServers": … } de sa page d\'aide',
163
166
  'set-mcp-hand': 'Remplir à la main', 'set-mcp-add-n': 'Ajouter les {n}', 'set-mcp-nokey': 'aucune',
164
167
  'set-mcp-notjson': 'Pas du JSON : collez tout le bloc.',
package/server/tools.mjs CHANGED
@@ -100,13 +100,24 @@ export function readTools(text) {
100
100
  if (t.instructions !== undefined && !INSTRUCTIONS.test(t.instructions)) throw new Error(`${t.id}: instructions is a relative path in the home, without ".."`);
101
101
  /* Where the tool keeps its own log, read when it ends (why it stopped): folders relative to the home. */
102
102
  if (t.logs !== undefined && (!Array.isArray(t.logs) || t.logs.some((d) => typeof d !== 'string' || !/^[A-Za-z0-9._/-]+$/.test(d) || d.startsWith('/') || d.split('/').includes('..')))) throw new Error(`${t.id}: logs is a list of folders relative to the home, without ".."`);
103
+ /* Optional: WHERE IT KEEPS ITS STATE (11-11, #351), relative to the home -- its memory, its sessions, its
104
+ settings, what a conversation is beyond /work: `keep`, the paths to carry when the conversation is
105
+ exported, imported or moved; `skip`, paths inside them that are only cache. Clavarium carries them for
106
+ any tool, with no case of its own. */
107
+ let state;
108
+ if (t.state !== undefined) {
109
+ const rel = (list) => Array.isArray(list) && list.every((d) => typeof d === 'string' && /^[A-Za-z0-9._/-]+$/.test(d) && !d.startsWith('/') && !d.split('/').includes('..') && d !== '.');
110
+ if (!t.state || typeof t.state !== 'object' || !rel(t.state.keep) || t.state.keep.length === 0 || (t.state.skip !== undefined && !rel(t.state.skip))) throw new Error(`${t.id}: state needs "keep", paths relative to the home without "..", and may have "skip"`);
111
+ if ((t.state.skip ?? []).some((d) => !t.state.keep.some((k) => d === k || d.startsWith(`${k}/`)))) throw new Error(`${t.id}: state "skip" names paths inside "keep"`);
112
+ state = Object.freeze({ keep: Object.freeze([...t.state.keep]), skip: Object.freeze([...(t.state.skip ?? [])]) });
113
+ }
103
114
  /* Optional: ITS LAUNCHER, a script of config/launch shown at /tools/launch: run at each start,
104
115
  given the rights chosen (full, ask) then the command; it sets what the tool needs,
105
116
  then runs it. Clavarium knows nothing more of the tool. */
106
117
  if (t.launch !== undefined && !/^[a-z][a-z0-9-]{0,40}\.sh$/.test(t.launch)) throw new Error(`${t.id}: launch is the name of a script of config/launch, such as "${t.id}.sh"`);
107
118
  /* Repairs an existing machine is given once (see FIXES in conversations.mjs). */
108
119
  const fixups = t.install.includes('npm-writable') ? NPM_WRITABLE : [];
109
- return Object.freeze({ id: t.id, label: t.label, ...(t.instructions ? { instructions: t.instructions } : {}), ...(t.logs ? { logs: Object.freeze([...t.logs]) } : {}), command: Object.freeze([...t.command]), ...(t.launch ? { launch: t.launch } : {}), ...(t.resume ? { resume: Object.freeze([...t.resume]) } : {}), memoryMb: t.memoryMb, ...(rights ? { rights } : {}), steps: Object.freeze(steps), fixups: Object.freeze(fixups), signin });
120
+ return Object.freeze({ id: t.id, label: t.label, ...(t.instructions ? { instructions: t.instructions } : {}), ...(t.logs ? { logs: Object.freeze([...t.logs]) } : {}), ...(state ? { state } : {}), command: Object.freeze([...t.command]), ...(t.launch ? { launch: t.launch } : {}), ...(t.resume ? { resume: Object.freeze([...t.resume]) } : {}), memoryMb: t.memoryMb, ...(rights ? { rights } : {}), steps: Object.freeze(steps), fixups: Object.freeze(fixups), signin });
110
121
  });
111
122
  }
112
123
 
package/web/app.js CHANGED
@@ -2574,6 +2574,25 @@
2574
2574
  catch (error) { show(error.message, 'Back to the terminal', enter); }
2575
2575
  }, () => { notice.hidden = true; focusTerminal(); });
2576
2576
  };
2577
+ /* Its tool's memory, exported as one file, or put back from one (#351): the person's own act, from here. */
2578
+ $('carry-box').hidden = DEVICE || !here;
2579
+ $('carry-export').href = `${API}/conversations/${encodeURIComponent(current)}/export`;
2580
+ $('carry-import').onclick = () => $('carry-file').click();
2581
+ $('carry-file').onchange = () => {
2582
+ const file = $('carry-file').files?.[0]; $('carry-file').value = '';
2583
+ if (!file) return;
2584
+ const name = current;
2585
+ leavePanel();
2586
+ show(uiSaid('set-carry-ask', '« {file} » into « {name} »? Its memory is replaced.', { file: file.name, name }),
2587
+ uiSaid('set-carry-go', 'Import'), async () => {
2588
+ try {
2589
+ const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
2590
+ const said = await r.json().catch(() => ({}));
2591
+ if (!r.ok) throw new Error(said.error ?? `HTTP ${r.status}`);
2592
+ show(uiSaid('set-carry-done', 'Imported from « {from} ».', { from: said.from?.name ?? file.name }), 'OK', () => { notice.hidden = true; focusTerminal(); });
2593
+ } catch (error) { show(error.message, 'Back to the terminal', enter); }
2594
+ }, () => { notice.hidden = true; focusTerminal(); });
2595
+ };
2577
2596
  void paintAnswerer(); paintWakeups(); void paintTalkBox(); void paintShareHere();
2578
2597
  paintMachine(here);
2579
2598
  void paintGuide(here);
package/web/index.html CHANGED
@@ -231,6 +231,13 @@
231
231
  <p id="work-moved" class="hint" hidden></p>
232
232
  <button type="button" id="work-move"></button>
233
233
  </div>
234
+ <!-- CARRIED ELSEWHERE (#351): its tool's state (memory, sessions, settings) as one file; put back here. -->
235
+ <div id="carry-box">
236
+ <div class="panel-top"><b data-said="set-carry">Its tool's memory</b></div>
237
+ <p class="hint" data-said="set-carry-hint">Memory, sessions, settings: to take elsewhere.</p>
238
+ <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>
239
+ <p id="carry-said" class="hint" role="status" hidden></p>
240
+ </div>
234
241
  <!-- WHEN ITS MACHINE IS SHORT (server/healthreact.mjs): you are told either way. -->
235
242
  <form id="react-box" autocomplete="off">
236
243
  <div class="panel-top"><b>When its machine is short of room or memory</b></div>