clavarium 0.2.193-beta.1 → 0.2.194-beta.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.
@@ -0,0 +1,47 @@
1
+ #!/bin/sh
2
+ # THE DOOR OF A CONVERSATION IN A SHARED MACHINE (#221), run as root by Clavarium for everything it runs for
3
+ # that conversation: clavarium-enter NAME -- COMMAND [ARGS...]
4
+ #
5
+ # The command runs as the conversation's own user (c-NAME, no sudo), in a mount namespace of its own where
6
+ # /work is THIS conversation's work (the host mounts it at /srv/clavarium/NAME/work),
7
+ # /resources/* are only those given to it (/srv/clavarium/NAME/resources),
8
+ # /tools is the machine's (the same for all, read-only),
9
+ # ~ is /home/c-NAME (closed to the others),
10
+ # /tmp is its own,
11
+ # within a slice of its own (memory, processes: /etc/clavarium/limits/NAME, set by Clavarium). Seen from inside,
12
+ # a conversation is alone in its machine: no tool, no agent needs to know.
13
+ set -eu
14
+ [ "$(id -u)" -eq 0 ] || { echo "clavarium-enter: run as root" >&2; exit 77; }
15
+ name="${1:-}"; shift || true
16
+ [ "${1:-}" = "--" ] && shift
17
+ printf '%s' "$name" | grep -Eq '^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$' || { echo "clavarium-enter: not a conversation name" >&2; exit 64; }
18
+ [ $# -gt 0 ] || { echo "clavarium-enter: no command" >&2; exit 64; }
19
+ user="c-$name"; base="/srv/clavarium/$name"
20
+ # Its user, made at its first entry: a home of its own, closed to the others; no sudo, ever.
21
+ if ! id "$user" >/dev/null 2>&1; then
22
+ useradd --create-home --home-dir "/home/$user" --shell /bin/bash --user-group "$user"
23
+ fi
24
+ chmod 700 "/home/$user"
25
+ mkdir -p "$base/work" "$base/resources" "$base/tmp"
26
+ chown "$user:$user" "$base/tmp"; chmod 700 "$base/tmp"
27
+ # Its limits (memory in MB, processes), when Clavarium set them.
28
+ mem=""; procs=""
29
+ [ -r "/etc/clavarium/limits/$name" ] && . "/etc/clavarium/limits/$name"
30
+ # Into its own mount namespace: its /work, its resources, its /tmp; then its user, in its slice.
31
+ exec unshare --mount --propagation private -- sh -c '
32
+ set -eu
33
+ base="$1"; user="$2"; mem="$3"; procs="$4"; shift 4
34
+ mkdir -p /work /resources
35
+ mount --bind "$base/work" /work
36
+ mount -t tmpfs -o mode=755,size=1m none /resources
37
+ for r in "$base"/resources/*; do [ -e "$r" ] || continue; mkdir -p "/resources/$(basename "$r")"; mount --rbind "$r" "/resources/$(basename "$r")"; done
38
+ mount --bind "$base/tmp" /tmp
39
+ # The processes of the others hidden (a procfs of its own, Linux 5.8+): only its own are seen.
40
+ mount -t proc -o hidepid=invisible proc /proc 2>/dev/null || true
41
+ cd "/home/$user" 2>/dev/null || cd /
42
+ set -- setpriv --reuid="$user" --regid="$user" --init-groups --reset-env -- env HOME="/home/$user" USER="$user" LOGNAME="$user" SHELL=/bin/bash PATH=/usr/local/bin:/usr/bin:/bin "$@"
43
+ if [ -n "$mem$procs" ] && command -v systemd-run >/dev/null 2>&1; then
44
+ exec systemd-run --quiet --scope --slice="clavarium-$user" ${mem:+-p MemoryMax=${mem}M} ${procs:+-p TasksMax=$procs} -- "$@"
45
+ fi
46
+ exec "$@"
47
+ ' clavarium-enter "$base" "$user" "$mem" "$procs" "$@"
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
  ]
@@ -1106,6 +1106,43 @@ case "$AREA $VERB" in
1106
1106
  *) refuse "a mount is of a folder, of a view, of a work folder or of the tools" ;;
1107
1107
  esac
1108
1108
  run "$MULTIPASS" mount -u "$4:$VM_ID" -g "$5:$VM_ID" "$source" "$target" ;;
1109
+ "vm share"|"vm unshare")
1110
+ # A SHARED MACHINE (#221): the conversations that live in it, kept here (DATA/shared/<vm>), so that a
1111
+ # work folder or a resource only ever goes into the machine its conversation lives in. <vm> <conversation>
1112
+ [ $# -eq 2 ] || usage; vm_of "$1"; is_name "$2" || refuse "not a conversation name: $2"
1113
+ [ "$1" != "clv-$2" ] || refuse "a conversation of its own is not shared"
1114
+ list="$DATA/shared/$1"
1115
+ if [ "$SAY" = "yes" ]; then printf '%s %s %s\n' "$VERB" "$list" "$2"; exit 0; fi
1116
+ mkdir -p "$DATA/shared"; touch "$list"
1117
+ if [ "$VERB" = "share" ]; then
1118
+ grep -qx "$2" "$list" || printf '%s\n' "$2" >> "$list"
1119
+ else
1120
+ grep -vx "$2" "$list" > "$list.new" || true; mv "$list.new" "$list"
1121
+ fi
1122
+ exit 0 ;;
1123
+ "vm smount")
1124
+ # <vm> <conversation> <work|folder|view> <resource> <uid> <gid> <its uid> <its gid>: into the conversation's
1125
+ # own place in a shared machine (/srv/clavarium/<conversation>/...), where its door (clavarium-enter) finds
1126
+ # it, owned there by ITS user (not the machine's admin) -- only for a conversation that lives in that machine.
1127
+ [ $# -eq 8 ] || usage; vm_of "$1"; is_name "$2" || refuse "not a conversation name: $2"; is_name "$4" || refuse "not a folder name: $4"; number "$5"; number "$6"; number "$7"; number "$8"
1128
+ [ "$7" -ge 1001 ] && [ "$8" -ge 1001 ] || refuse "its own user is not the machine's admin"
1129
+ [ -f "$DATA/shared/$1" ] && grep -qx "$2" "$DATA/shared/$1" || refuse "$2 does not live in $1"
1130
+ case "$3" in
1131
+ work) [ "$4" = "$2" ] || refuse "a work folder belongs to its own conversation"
1132
+ kept work; source="$MNT/work/$2"; held "$source"
1133
+ [ "$SAY" = "yes" ] || mountpoint -q "$source" || refuse "the work disk of $2 is not in place"
1134
+ target="$1:/srv/clavarium/$2/work" ;;
1135
+ folder) folder_of "$4"; source="$MNT/resources/$4"; target="$1:/srv/clavarium/$2/resources/$4" ;;
1136
+ view) kept views; source="$MNT/views/$4"; held "$source"
1137
+ [ "$SAY" = "yes" ] || mountpoint -q "$source" || refuse "the read-only view of $4 is not in place"
1138
+ target="$1:/srv/clavarium/$2/resources/$4" ;;
1139
+ *) refuse "a shared mount is of a work folder, a folder or a view" ;;
1140
+ esac
1141
+ run "$MULTIPASS" mount -u "$5:$7" -g "$6:$8" "$source" "$target" ;;
1142
+ "vm sumount")
1143
+ # <vm> <conversation> <work|resource name>: taken out of its place in a shared machine.
1144
+ [ $# -eq 3 ] || usage; vm_of "$1"; is_name "$2" || refuse "not a conversation name: $2"; is_name "$3" || refuse "not a name: $3"
1145
+ if [ "$3" = "work" ]; then run "$MULTIPASS" umount "$1:/srv/clavarium/$2/work"; else run "$MULTIPASS" umount "$1:/srv/clavarium/$2/resources/$3"; fi ;;
1109
1146
  "vm unwork")
1110
1147
  # The work folder is taken out of its machine (its work moves to the
1111
1148
  # machine's own disk, or a move is undone).
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.193-beta.1",
3
+ "version": "0.2.194-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.193-beta.1",
9
+ "version": "0.2.194-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -14,7 +14,7 @@
14
14
  "clavarium-binder": "0.1.62-next.1",
15
15
  "clavarium-docket": "0.1.2-next.2",
16
16
  "clavarium-parley": "0.17.91-next.1",
17
- "clavarium-tether": "0.1.0-next.60",
17
+ "clavarium-tether": "0.1.0-next.66",
18
18
  "mammoth": "1.13.0",
19
19
  "mermaid": "11.17.2",
20
20
  "node-pty": "^1.1.0",
@@ -800,9 +800,9 @@
800
800
  }
801
801
  },
802
802
  "node_modules/clavarium-tether": {
803
- "version": "0.1.0-next.60",
804
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.60.tgz",
805
- "integrity": "sha512-el+ekbsskuyyy0wAnocvV/VjvpbbnHl/IpPpjZRB+qu9CdyBJHcnfbtK5CcXH84IpUfQgPF+hSdZFB6v/1CSyg==",
803
+ "version": "0.1.0-next.66",
804
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.66.tgz",
805
+ "integrity": "sha512-Q1XPq+wVlZEOPuFNsHm9cATbAsVbr1QObIPa9u6e9V1KhMb1tGPpFsuU15jIflRa6tD/XaZo4VCrUtd1o8iz/w==",
806
806
  "license": "MIT",
807
807
  "bin": {
808
808
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.193-beta.1",
3
+ "version": "0.2.194-beta.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.",
@@ -48,7 +48,7 @@
48
48
  "clavarium-binder": "0.1.62-next.1",
49
49
  "clavarium-docket": "0.1.2-next.2",
50
50
  "clavarium-parley": "0.17.91-next.1",
51
- "clavarium-tether": "0.1.0-next.60",
51
+ "clavarium-tether": "0.1.0-next.66",
52
52
  "mammoth": "1.13.0",
53
53
  "mermaid": "11.17.2",
54
54
  "node-pty": "^1.1.0",
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,
@@ -19,6 +20,7 @@
19
20
  * POST /api/conversations/<name>/health look now (never wakes a machine)
20
21
  * POST /api/conversations/<name>/health/seen what it says now no longer calls its owner (Needs you)
21
22
  * POST /api/conversations/<name>/exit-report why its tool ended: { now (read in its machine, if it runs), last (kept at its end) }
23
+ * POST /api/conversations/<name>/machine {machineMb} in a shared machine: that machine's memory, all in it restarted
22
24
  * POST /api/conversations/<name>/archive
23
25
  * POST /api/binder/suggest {id}: at most three quick actions for that card -> {actions: [{key, label, why, on, ask?}]}
24
26
  * POST /api/mailboxes/<name>/live {smtp, email?}: that mailbox connected live too (send, move...), its password reused
@@ -292,6 +294,20 @@ export async function handleApi(request, response, conversations, headers, resou
292
294
  }
293
295
  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
296
  }
297
+ /* A CONVERSATION CARRIED ELSEWHERE (#351): its tool's state as one archive, streamed from its machine;
298
+ put back into a conversation of the same tool. Downloaded and sent by the person, from the page. */
299
+ const carry = /^\/api\/conversations\/([^/]+)\/(export|import)$/.exec(pathname);
300
+ if (carry && request.method === 'GET' && carry[2] === 'export') {
301
+ const out = await conversations.exportState(decodeURIComponent(carry[1]));
302
+ response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(out.name)}` });
303
+ out.stream.pipe(response);
304
+ response.on('close', () => { try { out.child?.kill(); } catch { /* ended */ } });
305
+ return true;
306
+ }
307
+ if (carry && request.method === 'POST' && carry[2] === 'import') {
308
+ if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
309
+ return send(200, await conversations.importState(decodeURIComponent(carry[1]), request)), true;
310
+ }
295
311
  if (pathname.startsWith('/api/files/')) {
296
312
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
297
313
  const answer = await changeRoute(request.method, pathname.slice('/api'.length), query, request, attached);
@@ -943,6 +959,8 @@ export async function handleApi(request, response, conversations, headers, resou
943
959
  if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
944
960
  /* Its watchdog (watchdog.mjs): on or off, and how long it waits. */
945
961
  if (body?.watchdog && typeof body.watchdog === 'object') return send(200, conversations.setWatchdog(conversation, { on: typeof body.watchdog.on === 'boolean' ? body.watchdog.on : undefined, delayMin: body.watchdog.delayMin })), true;
962
+ /* Its shared machine's own memory (#221): the whole machine restarted, every conversation in it. */
963
+ if (body?.machineMb !== undefined) return send(200, await conversations.resizeShared(conversation, { machineMb: body.machineMb })), true;
946
964
  const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
947
965
  /* Asleep, nothing was started: the choice is only kept, for its wake. */
948
966
  return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
@@ -1097,6 +1097,9 @@ export async function handleExternal(request, response, { keys, status, chats =
1097
1097
  try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error, '/mcp'); }
1098
1098
  let text = '';
1099
1099
  for await (const piece of request) { text += piece; if (text.length > MCP_BODY_MAX) { note(id, 413, '/mcp'); return send(413, { error: 'Too long.' }); } }
1100
+ /* A protocol version said in the header, and none spoken here: refused, as the spec asks (none said: the oldest assumed). */
1101
+ const said = request.headers['mcp-protocol-version'];
1102
+ if (typeof said === 'string' && said && !MCP_VERSIONS.includes(said)) { note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: `Unsupported MCP-Protocol-Version: ${said.slice(0, 20)} (spoken: ${MCP_VERSIONS.join(', ')})` } }); }
1100
1103
  let msg;
1101
1104
  try { msg = JSON.parse(text); } catch { note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
1102
1105
  if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
@@ -1174,6 +1177,7 @@ export async function handleExternal(request, response, { keys, status, chats =
1174
1177
  if (!(error instanceof Refusal)) throw error;
1175
1178
  /* Not given: refused as the API refuses it (too many, too). Anything else is the tool's own failure, said to the caller. */
1176
1179
  if (error.status === 429) { note(id, 429, what); return send(429, { jsonrpc: '2.0', id: msg.id, error: { code: -32002, message: error.message } }, { 'retry-after': String(error.retry ?? 60) }); }
1180
+ /* (An HTTP 403 for a scope not given is what the MCP authorization spec says: kept, MCP review 11-11.) */
1177
1181
  if (error.status === 403) { note(id, 403, what); return send(403, { jsonrpc: '2.0', id: msg.id, error: { code: -32001, message: error.message } }); }
1178
1182
  note(id, error.status, what);
1179
1183
  return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: error.message }], isError: true } });
@@ -13,10 +13,19 @@ 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';
17
+ import { readFileSync } from 'node:fs';
16
18
 
17
19
  export const SESSION = 'main';
18
20
  export const STOP_DELAY_MS = 60_000;
19
21
  const STEP_MS = 15 * 60_000;
22
+ /* The door of a conversation in a shared machine (#221), put in the machine by the server. */
23
+ export const DOOR = new URL('../config/machine/clavarium-enter', import.meta.url);
24
+ /* The most programs one conversation may run in a shared machine. */
25
+ export const SHARED_PROCS = 1024;
26
+ /* A NEW SHARED MACHINE's memory (12-11, operator): chosen when it is made, 4 GB unless said; the conversations
27
+ that live in it share it, each within its own limit. */
28
+ export const SHARED_MB = 4096;
20
29
  /* Moving a work folder: what must stay free after it, and how long a copy may take. */
21
30
  export const ROOM_MB = 1024;
22
31
  /* A file shown straight from a machine's disk: where, and how large at most. */
@@ -267,12 +276,15 @@ export class Conversations {
267
276
 
268
277
  /* Whether a new machine may be made for this request: what `create`
269
278
  checks, and the server's room (capacity.mjs). Asked before `create`. */
270
- async admit({ name, title, tool, memoryMb } = {}) {
279
+ async admit({ name, title, tool, memoryMb, machine, machineMb } = {}) {
271
280
  if (!name && typeof title === 'string' && !titleProblem(title)) ({ name } = this.#naming({ title }));
281
+ /* Into a shared machine that is there already: no new machine, no room asked for it. */
282
+ if (typeof machine === 'string' && this.#machineMbOf(machine) !== undefined) return;
272
283
  const chosen = this.#tools.find((t) => t.id === tool);
273
284
  /* What `create` refuses anyway is said by `create`. */
274
285
  if (!chosen || !isConversationName(name) || this.#store.get(name)) return;
275
- const memory = memoryMb ?? chosen.memoryMb;
286
+ /* A new shared machine: the room it takes is its own size, not the conversation's. */
287
+ const memory = typeof machine === 'string' ? (machineMb ?? SHARED_MB) : (memoryMb ?? chosen.memoryMb);
276
288
  if (!Number.isInteger(memory)) return;
277
289
  await this.room({ kind: 'create', memoryMb: memory });
278
290
  }
@@ -289,8 +301,19 @@ export class Conversations {
289
301
  return { name: id, title: title !== undefined && title !== id ? title : undefined };
290
302
  }
291
303
 
292
- create({ name: given, title: read, tool, memoryMb, cpus, diskGb, workOnDisk, group }) {
304
+ /* The size of a shared machine: what its first conversation made it with (each of its conversations carries
305
+ it); undefined while none lives in it. */
306
+ #machineMbOf(machine) {
307
+ const there = this.#store.all().filter((x) => x.sharedMachine === machine);
308
+ if (!there.length) return undefined;
309
+ return there.map((x) => x.machineMb).find(Number.isInteger) ?? Math.max(...there.map((x) => Number(x.memoryMb) || 0));
310
+ }
311
+
312
+ create({ name: given, title: read, tool, memoryMb, cpus, diskGb, workOnDisk, group, machine, machineMb }) {
293
313
  const { name, title } = this.#naming({ name: given, title: read });
314
+ /* IN A SHARED MACHINE (#221), named: its work is always kept here (mounted into its place there). */
315
+ if (machine !== undefined && (typeof machine !== 'string' || !isConversationName(machine))) throw new Refusal(400, 'A machine name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter.');
316
+ if (machine !== undefined && machine === given) throw new Refusal(400, 'A shared machine has a name of its own, not a conversation\'s.');
294
317
  if (group !== undefined) { const problem = groupProblem(group); if (problem) throw new Refusal(400, problem); }
295
318
  if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
296
319
  const chosen = this.#tools.find((t) => t.id === tool);
@@ -304,9 +327,18 @@ export class Conversations {
304
327
  if (!Number.isInteger(cores) || cores < 1 || cores > availableParallelism()) throw new Refusal(400, `Cores are 1 to ${availableParallelism()} (what this server has).`);
305
328
  const disk = diskGb ?? DISK_GB;
306
329
  if (!Number.isInteger(disk) || disk < DISK_GB || disk > DISK_MAX_GB) throw new Refusal(400, `Disk is ${DISK_GB} to ${DISK_MAX_GB} GB.`);
330
+ /* Its shared machine's size: chosen when it is made (4 GB unless said), then the same for all in it; a
331
+ conversation never asks more than its machine has. */
332
+ let size;
333
+ if (machine !== undefined) {
334
+ const there = this.#machineMbOf(machine);
335
+ size = there ?? machineMb ?? SHARED_MB;
336
+ if (there === undefined && (!Number.isInteger(size) || size < 1024 || size > 16384)) throw new Refusal(400, 'A shared machine has 1024 to 16384 MB of memory.');
337
+ if (memory > size) throw new Refusal(400, `The machine ${machine} has ${size} MB of memory: this conversation cannot have more (${memory} MB).`);
338
+ }
307
339
  if (this.#store.get(name)) throw new Refusal(409, 'A conversation already has this name.');
308
340
  const now = new Date().toISOString();
309
- const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, work: workOnDisk === true ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
341
+ const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, cpus: cores, diskGb: disk, fixed: FIXES, ...(machine ? { sharedMachine: machine, machineMb: size } : {}), work: workOnDisk === true && !machine ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
310
342
  /* A new one comes first in its folder (or first of those in none). */
311
343
  const { order, groups } = this.#order();
312
344
  this.#store.put(conversation);
@@ -317,6 +349,7 @@ export class Conversations {
317
349
 
318
350
  /* `again`: a machine built anew for a conversation that had one. */
319
351
  async #build(name, tool, memoryMb, again = false) {
352
+ if (this.#store.get(name)?.sharedMachine) return this.#buildShared(name, tool, memoryMb);
320
353
  const fail = (what, r) => { this.#store.patch(name, { phase: 'failed', step: undefined, progress: undefined, error: `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}` }); };
321
354
  /* The size chosen at creation (stored by create, kept on a rebuild): launched with it, or, for a
322
355
  copy of a ready-made machine, brought to it while the copy is still stopped. */
@@ -406,6 +439,59 @@ export class Conversations {
406
439
  return undefined;
407
440
  }
408
441
 
442
+ /* A CONVERSATION IN A SHARED MACHINE (#221): the machine made by the first one that lives in it (its door
443
+ installed), started if it sleeps; then this one's place in it -- told to the host, its own user made by its
444
+ door, its work mounted there for that user, its tool installed (what runs as root for the machine, the rest
445
+ as its user). The same end as a machine of its own: ready, its tool started by the next opening. */
446
+ async #buildShared(name, tool, memoryMb) {
447
+ const c = this.#store.get(name);
448
+ const fail = (what, r) => { this.#store.patch(name, { phase: 'failed', step: undefined, progress: undefined, error: `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`, buildingSince: undefined }); return undefined; };
449
+ let state = await this.#vms.state(name, { fresh: true }).catch(() => undefined);
450
+ if (state === undefined) {
451
+ this.#store.patch(name, { step: `Making the shared machine ${c.sharedMachine}` });
452
+ const launched = await this.#vms.launch(name, Number.isInteger(c.machineMb) ? c.machineMb : memoryMb);
453
+ if (launched.code !== 0) return fail('The shared machine did not start', launched);
454
+ const sharing = await this.#vms.execMachine(name, [...SHARING_STEP], { timeoutMs: STEP_MS });
455
+ if (sharing.code !== 0) return fail('The shared machine could not be prepared for shared folders', sharing);
456
+ } else if (state !== 'Running') {
457
+ const started = await this.#vms.start(name);
458
+ if (started.code !== 0) return fail('The shared machine did not start', started);
459
+ }
460
+ /* Its door, always the one of this version (put again: an older one is replaced). */
461
+ const door = await this.#vms.execMachine(name, ['sudo', '-n', 'install', '-m', '0755', '-o', 'root', '-g', 'root', '/dev/stdin', '/usr/local/sbin/clavarium-enter'], { input: readFileSync(DOOR, 'utf8'), timeoutMs: STEP_MS });
462
+ if (door.code !== 0) return fail('The door of the shared machine could not be put in place', door);
463
+ this.#store.patch(name, { step: 'Making its place in the shared machine' });
464
+ const told = await this.#vms.share(name);
465
+ if (told.code !== 0) return fail('The host did not take it into the shared machine', told);
466
+ const me = await this.#vms.execMachine(name, ['sudo', '-n', 'clavarium-enter', name, '--', 'sh', '-c', 'id -u; id -g'], { timeoutMs: STEP_MS });
467
+ const [uid, gid] = String(me.stdout ?? '').trim().split('\n').map(Number);
468
+ if (me.code !== 0 || !Number.isInteger(uid) || !Number.isInteger(gid)) return fail('Its own user could not be made', me);
469
+ this.#store.patch(name, { machineUser: { uid, gid } });
470
+ /* Its limits, read by its door at each entry: the memory chosen for it, and a bound on its programs -- one
471
+ conversation that runs away never takes the machine from the others. */
472
+ const limits = await this.#vms.execMachine(name, ['sudo', '-n', 'install', '-D', '-m', '0644', '-o', 'root', '-g', 'root', '/dev/stdin', `/etc/clavarium/limits/${name}`],
473
+ { input: `mem=${Number(c.memoryMb) || tool.memoryMb}\nprocs=${SHARED_PROCS}\n`, timeoutMs: STEP_MS });
474
+ if (limits.code !== 0) return fail('Its limits could not be set in the shared machine', limits);
475
+ const kept = await this.#vms.workMake(name);
476
+ const shown = kept.code === 0 ? await this.#vms.workMount(name, this.#uid, this.#gid) : kept;
477
+ if (shown.code !== 0) return fail('The work folder could not be shown in the shared machine', shown);
478
+ /* Its tool: there already (another conversation installed it), or installed -- a step as root for the
479
+ machine, any other as its own user (its settings, in its home). */
480
+ const there = tool.steps.length === 0 || (await this.#vms.exec(name, ['sh', '-c', `command -v ${tool.command[0]}`])).code === 0;
481
+ for (const [i, step] of (there ? [] : tool.steps).entries()) {
482
+ if (!this.#store.get(name)) return undefined;
483
+ this.#store.patch(name, { step: `Installing ${tool.label} (${i + 1}/${tool.steps.length})` });
484
+ const r = await this.#vms.exec(name, step.argv, { input: step.input, timeoutMs: STEP_MS });
485
+ if (r.code !== 0) return fail(`Installing ${tool.label} failed at step ${i + 1}`, r);
486
+ }
487
+ this.#store.patch(name, { phase: 'ready', step: undefined, buildingSince: undefined, toolStarted: false });
488
+ this.#reach(name, 'folders');
489
+ this.#fresh.add(name);
490
+ this.#mountAgain.add(name);
491
+ this.ready(name);
492
+ return undefined;
493
+ }
494
+
409
495
  /* Builds the machine of a conversation AGAIN: after a build that failed,
410
496
  or when the machine is gone (a backup put back on a new computer brings
411
497
  the conversation's name, tool and folders, not its machine). What was
@@ -825,6 +911,60 @@ export class Conversations {
825
911
  return true;
826
912
  }
827
913
 
914
+ /* CARRIED ELSEWHERE (11-11, #351): what the conversation is beyond /work -- its tool's state, where its
915
+ entry in config/tools.json says it is (`state.keep`, without `state.skip`) -- as one .tar.gz streamed
916
+ from its machine, a manifest first (clavarium-conversation.json: its tool, its name, its size). Nothing
917
+ of the tool is known here: any tool that says where its state is can be exported, imported, moved.
918
+ The machine must run (its home is in it). -> { name: the file's name, stream } */
919
+ async exportState(name) {
920
+ const c = this.#store.get(name);
921
+ if (!c) throw new Refusal(404, 'No such conversation.');
922
+ const tool = this.#tools.find((t) => t.id === c.tool);
923
+ if (!tool?.state) throw new Refusal(409, `${tool?.label ?? c.tool} does not say where it keeps its state: it cannot be exported.`);
924
+ if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
925
+ 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() });
926
+ /* In its machine: the manifest written aside, then one archive -- the manifest first, then what is kept
927
+ (a path it has not made yet left out), the cache left out. */
928
+ /* (Its paths are plain -- letters, digits, . _ / - -- checked by tools.mjs: given as words.) */
929
+ const script = 'set -e; m=$(mktemp -d); printf "%s" "$1" > "$m/clavarium-conversation.json"; '
930
+ + '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; '
931
+ + 'tar -czf - -C "$m" clavarium-conversation.json -C "$HOME" $ex $ks; rm -rf "$m"';
932
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, tool.state.skip.join(' '), tool.state.keep.join(' ')]);
933
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'ignore'] });
934
+ return { name: `${name}-${new Date().toISOString().slice(0, 10)}.clavarium.tar.gz`, stream: child.stdout, child };
935
+ }
936
+
937
+ /* PUT BACK an exported state in this conversation (same tool): its tool stopped, the archive unpacked in
938
+ its home, its tool started again, taking up its last session. -> { tool, from } */
939
+ async importState(name, input) {
940
+ const c = this.#busyCheck(name);
941
+ const tool = this.#tools.find((t) => t.id === c.tool);
942
+ 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.`);
943
+ if ((await this.#vms.state(name).catch(() => undefined)) !== 'Running') throw new Refusal(409, 'Its machine is not running: open the conversation first.', { retry: false });
944
+ this.drop(name);
945
+ await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'kill-server'], { timeoutMs: 10_000 }).catch(() => {});
946
+ /* Unpacked aside first: its manifest read, its tool checked; then moved into the home. */
947
+ /* Aside in the home itself (never /tmp, which may be memory): then each part moved in place of the old. */
948
+ const script = 'set -e; m=$(mktemp -d "$HOME/.clavarium-import.XXXXXX"); trap \'rm -rf "$m"\' EXIT; tar -xzf - -C "$m"; '
949
+ + 'grep -q "\\"kind\\":\\"clavarium-conversation\\"" "$m/clavarium-conversation.json" || { echo "not an exported conversation" >&2; exit 3; }; '
950
+ + 'grep -q "\\"tool\\":\\"$1\\"" "$m/clavarium-conversation.json" || { echo "another tool" >&2; exit 4; }; '
951
+ + 'cat "$m/clavarium-conversation.json"; rm -f "$m/clavarium-conversation.json"; '
952
+ + 'for e in "$m"/.[!.]* "$m"/*; do if [ ! -e "$e" ]; then continue; fi; b=$(basename "$e"); rm -rf "$HOME/$b"; mv "$e" "$HOME/$b"; done';
953
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'import', c.tool]);
954
+ const child = spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });
955
+ const out = []; const err = [];
956
+ child.stdout.on('data', (d) => out.push(d)); child.stderr.on('data', (d) => err.push(d));
957
+ input.pipe(child.stdin);
958
+ child.stdin.on('error', () => { /* it stopped reading: said below */ });
959
+ const code = await new Promise((ok) => child.on('close', ok));
960
+ this.ready(name);
961
+ if (code === 3) throw new Refusal(400, 'This is not an exported conversation.');
962
+ if (code === 4) throw new Refusal(400, `This export is of another tool: import it into a conversation with that tool.`);
963
+ if (code !== 0) throw new Refusal(502, `Not imported: ${firstLine(Buffer.concat(err).toString()) || `exit ${code}`}`);
964
+ let from = null; try { from = JSON.parse(Buffer.concat(out).toString()); } catch { /* said nothing */ }
965
+ return { tool: c.tool, from: from ? { name: from.name, at: from.at } : null };
966
+ }
967
+
828
968
  async #fixup(name, tool) {
829
969
  for (const step of tool.fixups) {
830
970
  const r = await this.#vms.exec(name, step.argv, { timeoutMs: 120_000 }).catch(() => ({ code: 1 }));
@@ -879,6 +1019,7 @@ export class Conversations {
879
1019
  async resize(name, asked = {}) {
880
1020
  const c = this.#busyCheck(name);
881
1021
  const tool = this.#tools.find((t) => t.id === c.tool);
1022
+ if (c.sharedMachine) return this.#limitShared(name, c, tool, asked);
882
1023
  const { memory, disk, cpus } = this.#sizeAsked(c, tool, asked);
883
1024
  if (c.asleep === true) return this.#later(name, c, { memoryMb: memory, cpus, diskGb: disk });
884
1025
  const act = this.#take(name, 'resize');
@@ -1112,7 +1253,7 @@ export class Conversations {
1112
1253
  const timer = setTimeout(() => {
1113
1254
  this.#timers.delete(name);
1114
1255
  /* Not under an action of its owner's (a restart, a sleep): that one decides. */
1115
- if (!this.#watching.has(name) && !this.#acts.has(name)) { this.drop(name); void this.#vms.stop(name); }
1256
+ if (!this.#watching.has(name) && !this.#acts.has(name)) { this.drop(name); void this.#stopUnlessShared(name); }
1116
1257
  }, this.#stopDelayMs);
1117
1258
  timer.unref?.();
1118
1259
  this.#timers.set(name, timer);
@@ -1563,12 +1704,36 @@ export class Conversations {
1563
1704
  this.#cancelStop(name);
1564
1705
  this.drop(name);
1565
1706
  const kept = this.#store.get(name).work === 'kept';
1566
- this.#store.remove(name);
1567
- if (await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
1707
+ if (this.#store.get(name).sharedMachine) await this.#leaveShared(name, { erase: false });
1708
+ else {
1709
+ this.#store.remove(name);
1710
+ if (await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
1711
+ }
1568
1712
  /* Its work is moved aside on the server, not erased. */
1569
1713
  if (kept) await this.#vms.workAside(name);
1570
1714
  }
1571
1715
 
1716
+ /* OUT OF A SHARED MACHINE (#221): its programs ended, its work taken out of its place there, the host told;
1717
+ its user and home removed when it is erased (kept when archived). The machine itself goes only with the last
1718
+ conversation that lived in it. The record is removed here, before the machine is looked at. */
1719
+ async #leaveShared(name, { erase }) {
1720
+ const shared = this.#store.get(name).sharedMachine;
1721
+ const others = this.#store.all().filter((x) => x.name !== name && x.sharedMachine === shared);
1722
+ const running = (await this.#vms.state(name, { fresh: true }).catch(() => undefined)) === 'Running';
1723
+ if (running) {
1724
+ await this.#vms.execMachine(name, ['sudo', '-n', 'pkill', '-KILL', '-u', `c-${name}`], { timeoutMs: 30_000 }).catch(() => {});
1725
+ await this.#vms.workUnmount(name).catch(() => {});
1726
+ if (erase) await this.#vms.execMachine(name, ['sudo', '-n', 'userdel', '--remove', `c-${name}`], { timeoutMs: 60_000 }).catch(() => {});
1727
+ if (erase) await this.#vms.execMachine(name, ['sudo', '-n', 'rm', '-f', `/etc/clavarium/limits/${name}`], { timeoutMs: 30_000 }).catch(() => {});
1728
+ }
1729
+ await this.#vms.unshare(name).catch(() => {});
1730
+ const last = others.length === 0;
1731
+ const state = last ? await this.#vms.state(name, { fresh: true }).catch(() => undefined) : undefined;
1732
+ this.#store.remove(name);
1733
+ /* (Its name gone from the store, the VM manager is still reached through the machine's own name.) */
1734
+ if (last && state !== undefined) await this.#vms.removeVm(`clv-${shared}`);
1735
+ }
1736
+
1572
1737
  /* DELETED FOR GOOD (01-11, its owner's ask, confirmed by typing its name): as archived, but its work is
1573
1738
  erased, not put aside. Whatever state its machine is in -- one that never started too. */
1574
1739
  async erase(name) {
@@ -1576,14 +1741,76 @@ export class Conversations {
1576
1741
  this.#cancelStop(name);
1577
1742
  this.drop(name);
1578
1743
  const kept = this.#store.get(name).work === 'kept';
1579
- this.#store.remove(name);
1580
- if (await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
1744
+ if (this.#store.get(name).sharedMachine) await this.#leaveShared(name, { erase: true });
1745
+ else {
1746
+ this.#store.remove(name);
1747
+ if (await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
1748
+ }
1581
1749
  if (kept) {
1582
1750
  const r = await this.#vms.workErase(name);
1583
1751
  if (r?.code) throw new Refusal(500, `Its machine is deleted, but its files could not be erased: ${firstLine(r.stderr) || `exit ${r.code}`}`);
1584
1752
  }
1585
1753
  }
1586
1754
 
1755
+ /* ITS TOOL ENDED, ITS MACHINE STOPPED -- unless it is a shared machine (#221) where another conversation still
1756
+ has its tool, a screen or an action: then only this one's programs end, the others go on. */
1757
+ async #stopUnlessShared(name) {
1758
+ const shared = this.#store.get(name)?.sharedMachine;
1759
+ if (!shared) return this.#vms.stop(name);
1760
+ for (const other of this.#store.all().filter((x) => x.name !== name && x.sharedMachine === shared)) {
1761
+ if (this.#watching.has(other.name) || this.#acts.has(other.name) || this.#timers.has(other.name)) return this.#endShared(name);
1762
+ const alive = await this.#vms.exec(other.name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`]).catch(() => ({ code: 1 }));
1763
+ if (alive.code === 0) return this.#endShared(name);
1764
+ }
1765
+ return this.#vms.stop(name);
1766
+ }
1767
+ #endShared(name) { return this.#vms.execMachine(name, ['sudo', '-n', 'pkill', '-KILL', '-u', `c-${name}`], { timeoutMs: STEP_MS }).catch(() => undefined); }
1768
+
1769
+ /* ITS SHARE OF A SHARED MACHINE (#221): its memory there is its limit, at most the machine's; set without
1770
+ stopping anything, read by its door when its tool starts again. Cores and disk are the machine's. */
1771
+ async #limitShared(name, c, tool, { memoryMb, diskGb, cpus } = {}) {
1772
+ if ((diskGb !== undefined && diskGb !== null && diskGb !== '' && Number(diskGb) !== (c.diskGb ?? DISK_GB)) || (cpus !== undefined && cpus !== null && cpus !== '' && Number(cpus) !== (c.cpus ?? 1))) throw new Refusal(400, `Cores and disk are those of the shared machine ${c.sharedMachine}.`);
1773
+ const memory = Number(memoryMb);
1774
+ const size = this.#machineMbOf(c.sharedMachine);
1775
+ const least = tool?.memoryMb ?? 512;
1776
+ if (!Number.isInteger(memory) || memory < least || memory > size) throw new Refusal(400, `Its memory is between ${least} MB (what ${tool?.label ?? 'its tool'} needs) and ${size} MB (its shared machine's).`);
1777
+ if (memory === c.memoryMb) throw new Refusal(409, 'Nothing to change: it already has this.');
1778
+ const r = await this.#vms.execMachine(name, ['sudo', '-n', 'install', '-D', '-m', '0644', '-o', 'root', '-g', 'root', '/dev/stdin', `/etc/clavarium/limits/${name}`], { input: `mem=${memory}\nprocs=${SHARED_PROCS}\n`, timeoutMs: STEP_MS });
1779
+ if (r.code !== 0) throw new Refusal(502, `Its limit could not be set: ${firstLine(r.stderr) || `exit ${r.code}`}`);
1780
+ this.#store.patch(name, { memoryMb: memory, restarted: `Its limit is now ${memory} MB, from its tool's next start.` });
1781
+ return this.#store.get(name);
1782
+ }
1783
+
1784
+ /* A SHARED MACHINE GIVEN MORE OR LESS MEMORY (#221), from the settings of any conversation in it: never less than
1785
+ the largest limit of those in it; stopped cleanly, set, started again -- every conversation in it is
1786
+ interrupted, the page says so before. Each then finds its place again (its work mounted) at its next opening. */
1787
+ async resizeShared(name, { machineMb } = {}) {
1788
+ const c = this.#busyCheck(name);
1789
+ if (!c.sharedMachine) throw new Refusal(400, 'Not in a shared machine.');
1790
+ const all = this.#store.all().filter((x) => x.sharedMachine === c.sharedMachine);
1791
+ const now = this.#machineMbOf(c.sharedMachine);
1792
+ const size = Number(machineMb);
1793
+ const largest = Math.max(...all.map((x) => Number(x.memoryMb) || 0));
1794
+ if (!Number.isInteger(size) || size < Math.max(1024, largest) || size > 16384) throw new Refusal(400, `The machine ${c.sharedMachine} has ${Math.max(1024, largest)} to 16384 MB (no less than the largest of its conversations).`);
1795
+ if (size === now) throw new Refusal(409, 'Nothing to change: it already has this.');
1796
+ for (const x of all) if (this.#acts.has(x.name)) throw this.#busy(x.name);
1797
+ const state = await this.#vms.state(name, { fresh: true }).catch(() => undefined);
1798
+ if (state === undefined) throw new Refusal(410, 'The shared machine no longer exists.');
1799
+ await this.room({ kind: 'grow', name, memoryMb: state === 'Running' ? Math.max(0, size - now) : 0, diskMb: 0 });
1800
+ for (const x of all) { this.#cancelStop(x.name); this.drop(x.name); }
1801
+ const fail = (what, r) => new Refusal(502, `${what}: ${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}`);
1802
+ if (state !== 'Stopped') { const r = await this.#vms.stop(name); if (r.code !== 0) throw fail('The shared machine did not stop', r); }
1803
+ const set = await this.#vms.setMemory(name, size);
1804
+ if (set.code !== 0) { await this.#vms.start(name).catch(() => undefined); throw fail('Its memory could not be set', set); }
1805
+ const started = await this.#vms.start(name);
1806
+ for (const x of all) {
1807
+ this.#store.patch(x.name, { machineMb: size, toolStarted: false, restarted: `Its shared machine was restarted with ${size} MB.` });
1808
+ this.#mountAgain.add(x.name); this.#fresh.add(x.name);
1809
+ }
1810
+ if (started.code !== 0) throw fail('The shared machine did not start again', started);
1811
+ return this.#store.get(name);
1812
+ }
1813
+
1587
1814
  #cancelStop(name) {
1588
1815
  const timer = this.#timers.get(name);
1589
1816
  if (timer) { clearTimeout(timer); this.#timers.delete(name); }
package/server/main.mjs CHANGED
@@ -310,8 +310,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
310
310
  const instance = new Instance({ file: new JsonFile(`${dataDir}/instance.json`, {}), origin: publicOrigin, given: appName });
311
311
  let repairTerminal = async () => { throw new Error('not ready'); };
312
312
  const asHost = runner(host);
313
- const vms = new Vms(asHost, host);
314
- const all = conversations ?? new Conversations({ store: new Store(`${dataDir}/conversations.json`), layout: new JsonFile(`${dataDir}/layout.json`, {}), vms, tools, ...(stopDelayMs === undefined ? {} : { stopDelayMs }) });
313
+ /* A conversation in a shared machine (#221) says which: the machine its VM operations reach. */
314
+ const conversationStore = new Store(`${dataDir}/conversations.json`);
315
+ const vms = new Vms(asHost, host, {
316
+ machineOf: (name) => { const m = conversationStore.get(name)?.sharedMachine; return typeof m === 'string' && m ? m : undefined; },
317
+ userOf: (name) => { const u = conversationStore.get(name)?.machineUser; return u && Number.isInteger(u.uid) && Number.isInteger(u.gid) ? u : undefined; },
318
+ });
319
+ const all = conversations ?? new Conversations({ store: conversationStore, layout: new JsonFile(`${dataDir}/layout.json`, {}), vms, tools, ...(stopDelayMs === undefined ? {} : { stopDelayMs }) });
315
320
  /* Who may do what with what: ONE table, shared by everything below. */
316
321
  const grants = new Grants(new Store(`${dataDir}/grants.json`));
317
322
  /* Folder-style boxes the owner drops assets into, to tidy the views and hand a whole box at once (groups.mjs). */
@@ -159,6 +159,10 @@ 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-mshared-with': 'Partagée « {m} », avec {others}.', 'set-mshared-alone': 'Machine partagée « {m} », seule pour l\'instant.',
163
+ 'set-carry': 'La mémoire de son outil', 'set-carry-hint': 'Mémoire, sessions, réglages : à emporter.',
164
+ 'set-carry-export': 'Exporter', 'set-carry-import': 'Importer…', 'set-carry-go': 'Importer',
165
+ 'set-carry-ask': '« {file} » dans « {name} » ? Mémoire remplacée.', 'set-carry-done': 'Importé depuis « {from} ».',
162
166
  'set-mcp-drop': 'Collez ici la configuration du service', 'set-mcp-drop-hint': 'le bloc { "mcpServers": … } de sa page d\'aide',
163
167
  'set-mcp-hand': 'Remplir à la main', 'set-mcp-add-n': 'Ajouter les {n}', 'set-mcp-nokey': 'aucune',
164
168
  '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/server/vm.mjs CHANGED
@@ -84,10 +84,12 @@ export class VmUnknown extends Error {
84
84
  export class Vms {
85
85
  /* `run(argv, options)` reaches the host program; `prefix` is the same
86
86
  route as an argument vector, for the one caller that needs a terminal. */
87
- #ask; #snapshot = null; #asking = null; #now; #freshMs;
87
+ #ask; #snapshot = null; #asking = null; #now; #freshMs; #machineOf; #userOf;
88
88
  /* `freshMs`: how long one answer serves every caller (0: only those asking meanwhile). */
89
- constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS } = {}) {
90
- this.#ask = run; this.prefix = prefix; this.#now = now; this.#freshMs = freshMs;
89
+ /* `machineOf(conversation)`: the shared machine it lives in (#221), or nothing -- its own, `clv-<conversation>`. */
90
+ constructor(run, prefix, { now = () => Date.now(), freshMs = STATES_FRESH_MS, machineOf = () => undefined, userOf = () => undefined } = {}) {
91
+ /* `userOf(conversation)`: its own user in a shared machine, { uid, gid } -- what its mounts are owned by there. */
92
+ this.#ask = run; this.prefix = prefix; this.#now = now; this.#freshMs = freshMs; this.#machineOf = machineOf; this.#userOf = userOf;
91
93
  /* What changes a machine makes the states asked again (not taken from before it). */
92
94
  this.run = async (argv, options) => {
93
95
  const changes = argv[0] === 'vm' && CHANGES.has(argv[1]);
@@ -115,25 +117,48 @@ export class Vms {
115
117
  return this.#asking;
116
118
  }
117
119
 
120
+ /* Whether it lives in a shared machine (#221). */
121
+ shared(conversation) { return this.#machineOf(conversation) !== undefined; }
122
+ /* ITS MACHINE (#221): a conversation's own (`clv-<name>`, as always), or the shared one it lives in. */
123
+ vmOf(conversation) {
124
+ const shared = this.#machineOf(conversation);
125
+ if (shared === undefined) return vmName(conversation);
126
+ vmName(conversation); /* its own name checked all the same */
127
+ return vmName(shared);
128
+ }
129
+ /* In a shared machine, everything run for a conversation goes through its door (clavarium-enter, as root):
130
+ its own /work, its own home and user, its limits -- each tool sees what it sees in a machine of its own. */
131
+ #door(conversation, argv) {
132
+ /* A command run as root (sudo) is the server's own work on the machine (an install, a mount): not
133
+ through the door. Everything else -- a terminal, a tool, a probe -- is the conversation's. */
134
+ if (this.#machineOf(conversation) === undefined || argv[0] === 'sudo') return argv;
135
+ return ['sudo', '-n', 'clavarium-enter', conversation, '--', ...argv];
136
+ }
137
+ /* In a shared machine: its machine-wide work, as its admin user, never through a door (the door itself installed). */
138
+ execMachine(conversation, argv, options) { return this.run(['vm', 'exec', this.vmOf(conversation), '--', ...argv], options); }
139
+ /* The host's list of who lives in a shared machine (vm share / unshare). */
140
+ share(conversation) { return this.run(['vm', 'share', this.vmOf(conversation), conversation]); }
141
+ unshare(conversation) { return this.run(['vm', 'unshare', this.vmOf(conversation), conversation]); }
142
+
118
143
  launch(conversation, memoryMb, diskGb, cpus) {
119
144
  /* The disk and cores go with the memory only when they are the chosen size, not the defaults. */
120
145
  const size = diskGb && cpus ? [String(diskGb), String(cpus)] : [];
121
- return this.run(['vm', 'launch', vmName(conversation), String(memoryMb), ...size], { timeoutMs: (LAUNCH_SECONDS + 60) * 1000 });
146
+ return this.run(['vm', 'launch', this.vmOf(conversation), String(memoryMb), ...size], { timeoutMs: (LAUNCH_SECONDS + 60) * 1000 });
122
147
  }
123
148
 
124
149
  /* The machine of a conversation as a COPY of the ready-made one (see
125
150
  shelf.mjs), with its own memory. Left stopped: started by the caller. */
126
151
  clone(conversation, shelf, memoryMb) {
127
- return this.run(['vm', 'clone', shelf, vmName(conversation), String(memoryMb)], { timeoutMs: CLONE_MS });
152
+ return this.run(['vm', 'clone', shelf, this.vmOf(conversation), String(memoryMb)], { timeoutMs: CLONE_MS });
128
153
  }
129
154
 
130
155
  exec(conversation, argv, options) {
131
- return this.run(['vm', 'exec', vmName(conversation), '--', ...argv], options);
156
+ return this.run(['vm', 'exec', this.vmOf(conversation), '--', ...this.#door(conversation, argv)], options);
132
157
  }
133
158
 
134
159
  /* What a terminal attaches to: the same `exec`, as an argument vector. */
135
160
  execArgv(conversation, argv) {
136
- return [...this.prefix, 'vm', 'exec', vmName(conversation), '--', ...argv];
161
+ return [...this.prefix, 'vm', 'exec', this.vmOf(conversation), '--', ...this.#door(conversation, argv)];
137
162
  }
138
163
 
139
164
  /* Every machine's state, by VM name (a Map); throws VmUnknown when the VM manager did not answer. */
@@ -150,7 +175,7 @@ export class Vms {
150
175
  frozen inside had "multipass info" fail, read as "no longer exists"). */
151
176
  /* `fresh`: asked now (an owner opening it, building it again), not taken from a few seconds ago. */
152
177
  async state(conversation, { fresh = false } = {}) {
153
- const name = vmName(conversation);
178
+ const name = this.vmOf(conversation);
154
179
  const snap = await this.#states(fresh);
155
180
  if (!snap.states) throw new VmUnknown(snap.why);
156
181
  return snap.states.get(name);
@@ -162,57 +187,64 @@ export class Vms {
162
187
  is on the host is decided by the host program, not here. `uid`/`gid`:
163
188
  files written in the VM belong, on the host, to this account. */
164
189
  mount(conversation, kind, name, uid, gid) {
165
- return this.run(['vm', 'mount', vmName(conversation), kind, name, String(uid), String(gid)], { timeoutMs: 600_000 });
190
+ /* In a shared machine (#221): into its own place there, where its door finds it. */
191
+ if (this.shared(conversation)) { const u = this.#userOf(conversation); if (!u) throw new Error('its own user in the shared machine is not known yet'); return this.run(['vm', 'smount', this.vmOf(conversation), conversation, kind, name, String(uid), String(gid), String(u.uid), String(u.gid)], { timeoutMs: 600_000 }); }
192
+ return this.run(['vm', 'mount', this.vmOf(conversation), kind, name, String(uid), String(gid)], { timeoutMs: 600_000 });
166
193
  }
167
194
 
168
195
  /* The work folder of a conversation: kept on the host, shown in its
169
196
  machine at /work. Made (or found again) before it is mounted. */
170
- workMake(conversation) { vmName(conversation); return this.run(['work', 'make', conversation]); }
197
+ workMake(conversation) { this.vmOf(conversation); return this.run(['work', 'make', conversation]); }
171
198
  workMount(conversation, uid, gid) {
172
- return this.run(['vm', 'mount', vmName(conversation), 'work', conversation, String(uid), String(gid)], { timeoutMs: 600_000 });
199
+ if (this.shared(conversation)) { const u = this.#userOf(conversation); if (!u) throw new Error('its own user in the shared machine is not known yet'); return this.run(['vm', 'smount', this.vmOf(conversation), conversation, 'work', conversation, String(uid), String(gid), String(u.uid), String(u.gid)], { timeoutMs: 600_000 }); }
200
+ return this.run(['vm', 'mount', this.vmOf(conversation), 'work', conversation, String(uid), String(gid)], { timeoutMs: 600_000 });
201
+ }
202
+ workUnmount(conversation) {
203
+ if (this.shared(conversation)) return this.run(['vm', 'sumount', this.vmOf(conversation), conversation, 'work'], { timeoutMs: 120_000 });
204
+ return this.run(['vm', 'unwork', this.vmOf(conversation)], { timeoutMs: 120_000 });
173
205
  }
174
- workUnmount(conversation) { return this.run(['vm', 'unwork', vmName(conversation)], { timeoutMs: 120_000 }); }
175
206
  /* Megabytes left: { disk, host }, or undefined if it cannot be told. */
176
207
  async workRoom(conversation) {
177
- vmName(conversation);
208
+ this.vmOf(conversation);
178
209
  const r = await this.run(['work', 'room', conversation]);
179
210
  const m = /^disk (\d+) host (\d+)$/m.exec(r.stdout ?? '');
180
211
  return r.code === 0 && m ? { disk: Number(m[1]), host: Number(m[2]) } : undefined;
181
212
  }
182
- workAside(conversation) { vmName(conversation); return this.run(['work', 'aside', conversation]); }
213
+ workAside(conversation) { this.vmOf(conversation); return this.run(['work', 'aside', conversation]); }
183
214
  /* Deleted for good, or reset, by its owner: its work disk erased, not put aside. */
184
- workErase(conversation) { vmName(conversation); return this.run(['work', 'erase', conversation]); }
215
+ workErase(conversation) { this.vmOf(conversation); return this.run(['work', 'erase', conversation]); }
185
216
 
186
217
  /* The tools folder (see toolbox.mjs), shown read-only at /tools. */
187
218
  mountTools(conversation, uid, gid) {
188
- return this.run(['vm', 'mount', vmName(conversation), 'tools', 'tools', String(uid), String(gid)], { timeoutMs: 600_000 });
219
+ return this.run(['vm', 'mount', this.vmOf(conversation), 'tools', 'tools', String(uid), String(gid)], { timeoutMs: 600_000 });
189
220
  }
190
- unmountTools(conversation) { return this.run(['vm', 'untools', vmName(conversation)], { timeoutMs: 120_000 }); }
221
+ unmountTools(conversation) { return this.run(['vm', 'untools', this.vmOf(conversation)], { timeoutMs: 120_000 }); }
191
222
 
192
223
  umount(conversation, name) {
193
- return this.run(['vm', 'umount', vmName(conversation), name], { timeoutMs: 120_000 });
224
+ if (this.shared(conversation)) return this.run(['vm', 'sumount', this.vmOf(conversation), conversation, name], { timeoutMs: 120_000 });
225
+ return this.run(['vm', 'umount', this.vmOf(conversation), name], { timeoutMs: 120_000 });
194
226
  }
195
227
 
196
228
  /* `signal`: a start given up (Force stop asked meanwhile). */
197
- start(conversation, { signal } = {}) { return this.run(['vm', 'start', vmName(conversation)], { timeoutMs: 300_000, ...(signal ? { signal } : {}) }); }
198
- stop(conversation, timeoutMs = 300_000) { return this.run(['vm', 'stop', vmName(conversation)], { timeoutMs }); }
229
+ start(conversation, { signal } = {}) { return this.run(['vm', 'start', this.vmOf(conversation)], { timeoutMs: 300_000, ...(signal ? { signal } : {}) }); }
230
+ stop(conversation, timeoutMs = 300_000) { return this.run(['vm', 'stop', this.vmOf(conversation)], { timeoutMs }); }
199
231
  /* Stopped without waiting for the system inside: after a clean stop hung. */
200
- kill(conversation) { return this.run(['vm', 'kill', vmName(conversation)], { timeoutMs: 300_000 }); }
232
+ kill(conversation) { return this.run(['vm', 'kill', this.vmOf(conversation)], { timeoutMs: 300_000 }); }
201
233
  /* STOPPED FOR SURE, step by step (the host program's `vm halt`): a polite stop, a stop by force,
202
234
  then its own qemu ended (SIGTERM, SIGKILL), then checked. `from`/`until`: the first and last
203
235
  step (polite|force|term|kill; until force|kill). Each `step ...` line is told to `onLine`. */
204
236
  halt(conversation, { from = 'polite', until = 'kill', onLine, signal } = {}) {
205
- return this.run(['vm', 'halt', vmName(conversation), from, until], { timeoutMs: HALT_MS, onLine, signal });
237
+ return this.run(['vm', 'halt', this.vmOf(conversation), from, until], { timeoutMs: HALT_MS, onLine, signal });
206
238
  }
207
239
  /* "Force stop", as a power cut: its qemu ended, nothing asked of the VM manager (`vm hardstop`). */
208
- hardstop(conversation, { onLine, signal } = {}) { return this.run(['vm', 'hardstop', vmName(conversation)], { timeoutMs: HARDSTOP_MS, onLine, signal }); }
240
+ hardstop(conversation, { onLine, signal } = {}) { return this.run(['vm', 'hardstop', this.vmOf(conversation)], { timeoutMs: HARDSTOP_MS, onLine, signal }); }
209
241
  /* Memory in megabytes, disk in gigabytes: only on a stopped machine. */
210
- setMemory(conversation, mb) { return this.run(['vm', 'set', vmName(conversation), 'memory', String(mb)], { timeoutMs: 120_000 }); }
211
- setCpus(conversation, n) { return this.run(['vm', 'set', vmName(conversation), 'cpus', String(n)], { timeoutMs: 120_000 }); }
212
- setDisk(conversation, gb) { return this.run(['vm', 'set', vmName(conversation), 'disk', String(gb)], { timeoutMs: 600_000 }); }
242
+ setMemory(conversation, mb) { return this.run(['vm', 'set', this.vmOf(conversation), 'memory', String(mb)], { timeoutMs: 120_000 }); }
243
+ setCpus(conversation, n) { return this.run(['vm', 'set', this.vmOf(conversation), 'cpus', String(n)], { timeoutMs: 120_000 }); }
244
+ setDisk(conversation, gb) { return this.run(['vm', 'set', this.vmOf(conversation), 'disk', String(gb)], { timeoutMs: 600_000 }); }
213
245
  /* What the machine really has: { memoryMb, diskGb }, each undefined when it cannot be told. */
214
246
  async size(conversation) {
215
- const r = await this.run(['vm', 'size', vmName(conversation)], { timeoutMs: 60_000 });
247
+ const r = await this.run(['vm', 'size', this.vmOf(conversation)], { timeoutMs: 60_000 });
216
248
  if (r.code !== 0) return { memoryMb: undefined, diskGb: undefined };
217
249
  const line = (key) => new RegExp(`^${key} (\\S+)$`, 'm').exec(r.stdout ?? '')?.[1];
218
250
  const mb = megabytes(line('memory'));
@@ -221,9 +253,11 @@ export class Vms {
221
253
  return { memoryMb: mb === undefined ? undefined : Math.round(mb), diskGb: disk === undefined ? undefined : Math.round(disk / 1024), cpus };
222
254
  }
223
255
  /* Its steps (`step suspend ...`, then a wake and sleep again, then a clean stop) told to `onLine`. */
224
- suspend(conversation, { signal, onLine } = {}) { return this.run(['vm', 'suspend', vmName(conversation)], { timeoutMs: 600_000, ...(signal ? { signal } : {}), ...(onLine ? { onLine } : {}) }); }
256
+ suspend(conversation, { signal, onLine } = {}) { return this.run(['vm', 'suspend', this.vmOf(conversation)], { timeoutMs: 600_000, ...(signal ? { signal } : {}), ...(onLine ? { onLine } : {}) }); }
225
257
  /* Free the RAM of a machine that is asleep but whose qemu still holds it (a
226
258
  suspend that did not end the process): wake+resleep, then a clean stop. */
227
- reclaim(conversation) { return this.run(['vm', 'reclaim', vmName(conversation)], { timeoutMs: 300_000 }); }
228
- remove(conversation) { return this.run(['vm', 'delete', vmName(conversation)], { timeoutMs: 300_000 }); }
259
+ reclaim(conversation) { return this.run(['vm', 'reclaim', this.vmOf(conversation)], { timeoutMs: 300_000 }); }
260
+ remove(conversation) { return this.run(['vm', 'delete', this.vmOf(conversation)], { timeoutMs: 300_000 }); }
261
+ /* A shared machine deleted by its own name (its last conversation gone: no conversation leads to it any more). */
262
+ removeVm(vm) { if (!/^clv-[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/.test(vm)) throw new Error('not one of our machines'); return this.run(['vm', 'delete', vm], { timeoutMs: 300_000 }); }
229
263
  }
package/web/app.js CHANGED
@@ -1987,7 +1987,7 @@
1987
1987
  let chosenTool = '';
1988
1988
  let newTools = [];
1989
1989
  const ID_SHAPE = /^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;
1990
- const NEW_FIELDS = ['name', 'group', 'id', 'memory'];
1990
+ const NEW_FIELDS = ['name', 'group', 'id', 'memory', 'machine'];
1991
1991
  function newError(field, text) {
1992
1992
  const at = field && NEW_FIELDS.includes(field) ? field : '';
1993
1993
  for (const f of NEW_FIELDS) {
@@ -2101,6 +2101,23 @@
2101
2101
  b.addEventListener('click', () => { for (const other of $('newconv-work').querySelectorAll('[data-work]')) other.setAttribute('aria-checked', String(other === b)); });
2102
2102
  }
2103
2103
  const newOnDisk = () => $('newconv-work').querySelector('[data-work="disk"]').getAttribute('aria-checked') === 'true';
2104
+ /* WHERE IT LIVES (#221): its own machine, or a shared one -- an existing one offered, or a new name. In a shared
2105
+ machine its files are always kept here: that choice is hidden. */
2106
+ const newShared = () => $('newconv-where').querySelector('[data-where="shared"]').getAttribute('aria-checked') === 'true';
2107
+ const paintWhere = () => {
2108
+ const shared = newShared();
2109
+ $('newconv-machine-row').hidden = !shared;
2110
+ $('newconv-files-card').hidden = shared;
2111
+ const names = [...new Set(conversations.map((c) => c.sharedMachine).filter(Boolean))].sort();
2112
+ $('machine-names').replaceChildren(...names.map((n) => Object.assign(document.createElement('option'), { value: n })));
2113
+ if (shared && !$('newconv-machine').value && names.length) $('newconv-machine').value = names[0];
2114
+ /* A new shared machine: its memory chosen here (12-11); one that is there keeps its own. */
2115
+ $('newconv-machine-mb-row').hidden = !shared || names.includes($('newconv-machine').value.trim());
2116
+ };
2117
+ $('newconv-machine').addEventListener('input', () => paintWhere());
2118
+ for (const b of $('newconv-where').querySelectorAll('[data-where]')) {
2119
+ b.addEventListener('click', () => { for (const other of $('newconv-where').querySelectorAll('[data-where]')) other.setAttribute('aria-checked', String(other === b)); paintWhere(); });
2120
+ }
2104
2121
  async function openNew({ push = true, group = null } = {}) {
2105
2122
  if (DEVICE) return;
2106
2123
  newError('', '');
@@ -2149,6 +2166,7 @@
2149
2166
  const group = $('newconv-group').value.trim();
2150
2167
  if (!title) { newError('name', 'Give a name.'); return; }
2151
2168
  if (id && !ID_SHAPE.test(id)) { newError('id', 'Lower-case letters, digits, hyphens'); return; }
2169
+ if (newShared() && !ID_SHAPE.test($('newconv-machine').value.trim())) { newError('machine', 'A name: lower-case letters, digits, hyphens'); return; }
2152
2170
  const least = newTools.find((t) => t.id === chosenTool)?.memoryMb;
2153
2171
  const memoryMb = Number($('newconv-memory').value);
2154
2172
  const cpus = Number($('newconv-cpus').value); const diskGb = Number($('newconv-disk').value);
@@ -2156,9 +2174,9 @@
2156
2174
  creating = true; $('newconv-create').disabled = true;
2157
2175
  try {
2158
2176
  const opencode = await openCodeChoice();
2159
- const made = await post(`${API}/conversations`, { ...(opencode ? { opencode } : {}), title, ...(id ? { name: id } : {}), ...(group ? { group } : {}), tool: chosenTool, workOnDisk: newOnDisk(), ...(document.getElementById('newconv-chat')?.checked === false ? { chat: false } : {}), ...(memoryMb && memoryMb !== least ? { memoryMb } : {}), ...(cpus && cpus !== 1 ? { cpus } : {}), ...(diskGb && diskGb !== 8 ? { diskGb } : {}) });
2177
+ const made = await post(`${API}/conversations`, { ...(opencode ? { opencode } : {}), title, ...(id ? { name: id } : {}), ...(group ? { group } : {}), tool: chosenTool, workOnDisk: newShared() ? false : newOnDisk(), ...(newShared() ? { machine: $('newconv-machine').value.trim(), ...($('newconv-machine-mb-row').hidden ? {} : { machineMb: Number($('newconv-machine-mb').value) }) } : {}), ...(document.getElementById('newconv-chat')?.checked === false ? { chat: false } : {}), ...(memoryMb && memoryMb !== least ? { memoryMb } : {}), ...(cpus && cpus !== 1 ? { cpus } : {}), ...(diskGb && diskGb !== 8 ? { diskGb } : {}) });
2160
2178
  $('newconv-name').value = ''; $('newconv-id').value = ''; $('newconv-id').placeholder = 'website-redesign'; $('newconv-group').value = '';
2161
- $('newconv-work').querySelector('[data-work="kept"]').click(); $('newconv-more').open = false; { const ch = document.getElementById('newconv-chat'); if (ch) ch.checked = true; }
2179
+ $('newconv-work').querySelector('[data-work="kept"]').click(); $('newconv-where').querySelector('[data-where="own"]').click(); $('newconv-machine').value = ''; $('newconv-more').open = false; { const ch = document.getElementById('newconv-chat'); if (ch) ch.checked = true; }
2162
2180
  await refresh();
2163
2181
  /* The new one is selected: the page gives way to it, with no step of it left behind. */
2164
2182
  select(made.name);
@@ -2574,6 +2592,34 @@
2574
2592
  catch (error) { show(error.message, 'Back to the terminal', enter); }
2575
2593
  }, () => { notice.hidden = true; focusTerminal(); });
2576
2594
  };
2595
+ /* In a shared machine (#221): its name and the others in it, said once -- stopping it stops them too. */
2596
+ const sharedIn = here?.sharedMachine;
2597
+ $('machine-shared').hidden = DEVICE || !sharedIn;
2598
+ if (sharedIn) {
2599
+ const others = conversations.filter((c) => c.sharedMachine === sharedIn && c.name !== current).map((c) => c.title ?? c.name);
2600
+ $('machine-shared').textContent = others.length
2601
+ ? uiSaid('set-mshared-with', 'Shared machine « {m} », with {others}. Stopping it stops them too.', { m: sharedIn, others: others.join(', ') })
2602
+ : uiSaid('set-mshared-alone', 'Shared machine « {m} », alone in it for now.', { m: sharedIn });
2603
+ }
2604
+ /* Its tool's memory, exported as one file, or put back from one (#351): the person's own act, from here. */
2605
+ $('carry-box').hidden = DEVICE || !here;
2606
+ $('carry-export').href = `${API}/conversations/${encodeURIComponent(current)}/export`;
2607
+ $('carry-import').onclick = () => $('carry-file').click();
2608
+ $('carry-file').onchange = () => {
2609
+ const file = $('carry-file').files?.[0]; $('carry-file').value = '';
2610
+ if (!file) return;
2611
+ const name = current;
2612
+ leavePanel();
2613
+ show(uiSaid('set-carry-ask', '« {file} » into « {name} »? Its memory is replaced.', { file: file.name, name }),
2614
+ uiSaid('set-carry-go', 'Import'), async () => {
2615
+ try {
2616
+ const r = await fetch(`${API}/conversations/${encodeURIComponent(name)}/import`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file });
2617
+ const said = await r.json().catch(() => ({}));
2618
+ if (!r.ok) throw new Error(said.error ?? `HTTP ${r.status}`);
2619
+ show(uiSaid('set-carry-done', 'Imported from « {from} ».', { from: said.from?.name ?? file.name }), 'OK', () => { notice.hidden = true; focusTerminal(); });
2620
+ } catch (error) { show(error.message, 'Back to the terminal', enter); }
2621
+ }, () => { notice.hidden = true; focusTerminal(); });
2622
+ };
2577
2623
  void paintAnswerer(); paintWakeups(); void paintTalkBox(); void paintShareHere();
2578
2624
  paintMachine(here);
2579
2625
  void paintGuide(here);
@@ -2906,7 +2952,8 @@
2906
2952
  cores.replaceChildren(...Array.from({ length: most }, (_, i) => i + 1).map((n) => { const o = document.createElement('option'); o.value = String(n); o.textContent = `${n}${n === (here.cpus ?? 1) ? ' (now)' : ''}${n === most && n > 1 ? ' (all of this server)' : ''}`; return o; }));
2907
2953
  cores.value = String(here.cpus ?? 1);
2908
2954
  const least = here.memoryMinMb ?? 512;
2909
- const mems = [...new Set([...MEMORY_CHOICES.filter((m) => m >= least), here.memoryMb])].sort((a, b) => a - b);
2955
+ /* In a shared machine (#221): its limit there, up to the machine's own memory. */
2956
+ const mems = [...new Set([...MEMORY_CHOICES.filter((m) => m >= least && (!here.sharedMachine || m <= (here.machineMb ?? m))), here.memoryMb])].sort((a, b) => a - b);
2910
2957
  memory.replaceChildren(...mems.map((m) => { const o = document.createElement('option'); o.value = String(m); o.textContent = `${sizeWords(m)}${m === here.memoryMb ? ' (now)' : ''}${m === least ? ' (least for its tool)' : ''}`; return o; }));
2911
2958
  memory.value = String(here.memoryMb);
2912
2959
  const now = here.diskGb ?? 8;
@@ -2928,6 +2975,21 @@
2928
2975
  $('machine-later-text').textContent = here?.sizeAtWake ? `Will be applied when it wakes: ${laterWords(here.sizeAtWake)}` : '';
2929
2976
  $('machine-later').hidden = !here?.sizeAtWake;
2930
2977
  $('machine-size-apply').textContent = here?.asleep === true ? 'Keep for its wake' : 'Apply...';
2978
+ /* In a shared machine (#221): its memory is its limit there (no restart), cores and disk the machine's; the
2979
+ machine's own memory below, which restarts all in it. */
2980
+ const sharedHere = Boolean(here?.sharedMachine) && !DEVICE;
2981
+ for (const id of ['machine-cpus', 'machine-disk']) { $(id).hidden = sharedHere; $(id).previousElementSibling.hidden = sharedHere; }
2982
+ $('machine-memory').previousElementSibling.textContent = sharedHere ? 'Its limit' : 'Memory';
2983
+ $('machine-size-title').textContent = sharedHere ? 'Memory' : 'Memory, cores and disk';
2984
+ if (sharedHere) { $('machine-size-hint').textContent = 'Its limit in the shared machine · from its next start'; $('machine-size-apply').textContent = 'Apply'; }
2985
+ $('shared-size').hidden = !sharedHere || here.phase !== 'ready';
2986
+ if (sharedHere && document.activeElement !== $('shared-memory')) {
2987
+ const inIt = conversations.filter((x) => x.sharedMachine === here.sharedMachine);
2988
+ const floor = Math.max(1024, ...inIt.map((x) => x.memoryMb ?? 0)); const now = here.machineMb ?? floor;
2989
+ const sizes = [...new Set([now, ...MEMORY_CHOICES.filter((m) => m >= floor)])].sort((a, b) => a - b);
2990
+ $('shared-memory').replaceChildren(...sizes.map((m) => Object.assign(document.createElement('option'), { value: String(m), textContent: `${sizeWords(m)}${m === now ? ' (now)' : ''}` })));
2991
+ $('shared-memory').value = String(now);
2992
+ }
2931
2993
  /* When its tool starts: its last session, or a new one -- for a tool that can take one up. */
2932
2994
  $('resume-box').hidden = DEVICE || !here?.resumes;
2933
2995
  for (const b of $('resume-on').children) b.setAttribute('aria-pressed', String((b.dataset.on === 'true') === (here?.resume !== false)));
@@ -3008,6 +3070,15 @@
3008
3070
  if (!here) return;
3009
3071
  const memoryMb = Number($('machine-memory').value); const diskGb = Number($('machine-disk').value); const cpus = Number($('machine-cpus').value) || (here.cpus ?? 1);
3010
3072
  if (memoryMb === here.memoryMb && diskGb === (here.diskGb ?? 8) && cpus === (here.cpus ?? 1)) { $('panel-error').textContent = 'Nothing to change: choose another memory, cores or disk first.'; $('panel-error').hidden = false; return; }
3073
+ /* In a shared machine: its limit, set at once -- nothing stopped. */
3074
+ if (here.sharedMachine) {
3075
+ $('panel-error').hidden = true;
3076
+ void (async () => {
3077
+ try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { memoryMb }); await refresh(); paintMachine(conversations.find((x) => x.name === name)); }
3078
+ catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
3079
+ })();
3080
+ return;
3081
+ }
3011
3082
  const changes = [memoryMb !== here.memoryMb ? `${sizeWords(memoryMb)} of memory (now ${sizeWords(here.memoryMb)})` : '', cpus !== (here.cpus ?? 1) ? `${cpus} core${cpus > 1 ? 's' : ''} (now ${here.cpus ?? 1})` : '', diskGb !== (here.diskGb ?? 8) ? `a disk of ${diskGb} GB (now ${here.diskGb ?? 8} GB; it can never shrink again)` : ''].filter(Boolean).join(' and ');
3012
3083
  /* Asleep: kept for its wake, from Settings, where it is then said; nothing is stopped or woken now. */
3013
3084
  if (here.asleep === true) {
@@ -3028,6 +3099,25 @@
3028
3099
  }, resume);
3029
3100
  });
3030
3101
 
3102
+ /* ITS SHARED MACHINE'S MEMORY (#221): asked first, naming every conversation it interrupts. */
3103
+ $('shared-size').addEventListener('submit', (event) => {
3104
+ event.preventDefault();
3105
+ const name = current;
3106
+ const here = conversations.find((x) => x.name === name);
3107
+ if (!here?.sharedMachine) return;
3108
+ const machineMb = Number($('shared-memory').value);
3109
+ if (machineMb === here.machineMb) { $('panel-error').textContent = 'Nothing to change: choose another memory first.'; $('panel-error').hidden = false; return; }
3110
+ const inIt = conversations.filter((x) => x.sharedMachine === here.sharedMachine).map((x) => x.title ?? x.name);
3111
+ leavePanel();
3112
+ const resume = socket && state.dataset.state === 'live' ? () => { notice.hidden = true; focusTerminal(); } : enter;
3113
+ show(`Give the shared machine « ${here.sharedMachine} » ${sizeWords(machineMb)} of memory (now ${sizeWords(here.machineMb ?? 0)})? IT IS STOPPED AND STARTED AGAIN: ${inIt.join(', ')} ${inIt.length > 1 ? 'are' : 'is'} interrupted.`,
3114
+ 'Change it', async () => {
3115
+ disconnect(); say('restarting', 'connecting'); show('Changing the shared machine...'); $('notice-spin').hidden = false;
3116
+ try { await post(`${API}/conversations/${encodeURIComponent(name)}/machine`, { machineMb }); await refresh(); enter(); }
3117
+ catch (error) { show(error.message, 'Back', enter); }
3118
+ }, resume);
3119
+ });
3120
+
3031
3121
  /* ---------- what its tool is told about where it is (server/guide.mjs) ---------- */
3032
3122
  /* One quiet line; behind "see", the exact text its tool reads, made by
3033
3123
  the server from these settings, the owner's own lines, and "Tell it
package/web/index.html CHANGED
@@ -203,6 +203,8 @@
203
203
  <div class="curves-head"><b>Over time</b><div class="levels curves-span" role="group" aria-label="Over"><button type="button" data-span="1h" aria-pressed="true">1 h</button><button type="button" data-span="24h" aria-pressed="false">24 h</button><button type="button" data-span="7d" aria-pressed="false">7 days</button></div></div>
204
204
  <div class="curves-row"></div>
205
205
  </div>
206
+ <!-- IN A SHARED MACHINE (#221): which, and who else lives in it -- its stop or restart stops them too. -->
207
+ <p id="machine-shared" class="hint machine-shared" hidden></p>
206
208
  <p id="machine-restarted" class="hint" role="status" hidden></p>
207
209
  <div id="resume-box" hidden>
208
210
  <div class="set-row"><div class="set-what"><b>When its tool starts</b><small id="resume-hint">After a wake or restart</small></div><div class="set-control"><div class="levels" id="resume-on" role="group" aria-label="When its tool starts"><button type="button" data-on="true">Resume its last session</button><button type="button" data-on="false">Start fresh</button></div></div></div>
@@ -211,7 +213,7 @@
211
213
  <div class="set-row"><div class="set-what"><b data-said="set-mesc">If a stop hangs</b></div><div class="set-control"><div class="levels" id="m-escalate" role="group" aria-label="If a stop hangs"><button type="button" data-on="true" data-said="set-mesc-auto">Force it</button><button type="button" data-on="false" data-said="set-mesc-ask">Ask me</button></div></div></div>
212
214
  <!-- ITS WATCHDOG (server/watchdog.mjs): mute or full that long, forced off then started, once. -->
213
215
  <div class="set-row" id="m-dog-row"><div class="set-what"><b data-said="set-mdog">Watchdog</b><small data-said="set-mdog-what">Restarts it if stuck</small></div><div class="set-control"><div class="levels" id="m-dog" role="group" aria-label="Watchdog"><button type="button" data-min="0" data-said="set-mdog-off">Off</button><button type="button" data-min="30">30 min</button><button type="button" data-min="60">1 h</button><button type="button" data-min="120">2 h</button><button type="button" data-min="custom" data-said="set-mdog-custom">Custom</button></div><label class="m-dog-min" id="m-dog-custom" hidden><input type="number" id="m-dog-min" min="10" max="1440" step="5" inputmode="numeric" aria-label="Minutes"> min</label></div></div>
214
- <div class="panel-top"><b>Memory, cores and disk</b></div>
216
+ <div class="panel-top"><b id="machine-size-title">Memory, cores and disk</b></div>
215
217
  <form id="machine-size" autocomplete="off">
216
218
  <label for="machine-memory">Memory</label>
217
219
  <select id="machine-memory"></select>
@@ -225,12 +227,26 @@
225
227
  <p class="hint" id="machine-later" role="status" hidden><span id="machine-later-text"></span> · <button type="button" id="machine-later-cancel" class="inline">cancel</button></p>
226
228
  <div class="row"><button type="submit" id="machine-size-apply">Apply...</button></div>
227
229
  </form>
230
+ <!-- ITS SHARED MACHINE'S OWN MEMORY (#221): the whole machine restarted, every conversation in it. -->
231
+ <form id="shared-size" autocomplete="off" hidden>
232
+ <label for="shared-memory">Shared machine memory</label>
233
+ <select id="shared-memory"></select>
234
+ <p class="hint" id="shared-size-hint">Restarts every conversation in it</p>
235
+ <div class="row"><button type="submit" id="shared-size-apply">Change...</button></div>
236
+ </form>
228
237
  <div id="work-box">
229
238
  <div class="panel-top"><b>Where the tool works</b></div>
230
239
  <p id="work-now" class="hint"><span><span id="work-now-text"></span></span><span id="work-now-why" class="tip" hidden></span></p>
231
240
  <p id="work-moved" class="hint" hidden></p>
232
241
  <button type="button" id="work-move"></button>
233
242
  </div>
243
+ <!-- CARRIED ELSEWHERE (#351): its tool's state (memory, sessions, settings) as one file; put back here. -->
244
+ <div id="carry-box">
245
+ <div class="panel-top"><b data-said="set-carry">Its tool's memory</b></div>
246
+ <p class="hint" data-said="set-carry-hint">Memory, sessions, settings: to take elsewhere.</p>
247
+ <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>
248
+ <p id="carry-said" class="hint" role="status" hidden></p>
249
+ </div>
234
250
  <!-- WHEN ITS MACHINE IS SHORT (server/healthreact.mjs): you are told either way. -->
235
251
  <form id="react-box" autocomplete="off">
236
252
  <div class="panel-top"><b>When its machine is short of room or memory</b></div>
@@ -1425,7 +1441,17 @@
1425
1441
  </div>
1426
1442
  <small id="newconv-oc-raw" class="hint" hidden>Set it up yourself in its terminal.</small>
1427
1443
  </div>
1428
- <div class="nc-card">
1444
+ <!-- WHERE IT LIVES (#221): a machine of its own, or a shared one (lighter, for assistants). -->
1445
+ <div class="nc-card" id="newconv-where-card">
1446
+ <span class="sub-head">Where it lives</span>
1447
+ <div id="newconv-where" class="pick two" role="radiogroup" aria-label="Where it lives">
1448
+ <button type="button" role="radio" data-where="own" aria-checked="true"><b>Its own machine</b><small>All to itself</small></button>
1449
+ <button type="button" role="radio" data-where="shared" aria-checked="false"><b>A shared machine</b><small>Trial · lighter, for assistants</small></button>
1450
+ </div>
1451
+ <div class="set-row" id="newconv-machine-row" hidden><div class="set-what"><label for="newconv-machine">Machine</label><small>An existing one, or a new name</small><span id="newconv-machine-error" class="err" role="alert" hidden></span></div><div class="set-control"><input id="newconv-machine" maxlength="32" list="machine-names" placeholder="assistants" spellcheck="false" autocapitalize="off" autocomplete="off"><datalist id="machine-names"></datalist></div></div>
1452
+ <div class="set-row" id="newconv-machine-mb-row" hidden><div class="set-what"><label for="newconv-machine-mb">Its memory</label><small>Shared by the conversations in it</small></div><div class="set-control"><select id="newconv-machine-mb"><option value="2048">2 GB</option><option value="4096" selected>4 GB</option><option value="6144">6 GB</option><option value="8192">8 GB</option><option value="12288">12 GB</option><option value="16384">16 GB</option></select></div></div>
1453
+ </div>
1454
+ <div class="nc-card" id="newconv-files-card">
1429
1455
  <span class="sub-head">Its files</span>
1430
1456
  <div id="newconv-work" class="pick two" role="radiogroup" aria-label="Its files">
1431
1457
  <button type="button" role="radio" data-work="kept" aria-checked="true"><b>Kept here</b><small>Seen in Files. Outlives the machine</small></button>
package/web/style.css CHANGED
@@ -498,9 +498,9 @@ details.chapter.reached { outline: 2px solid var(--brass); outline-offset: 2px;
498
498
  .facts { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0; }
499
499
  .facts dt { color: var(--ink2); }
500
500
  .facts dd { margin: 0; overflow-wrap: anywhere; }
501
- #machine-size { display: flex; flex-direction: column; gap: 6px; max-width: 30rem; }
502
- #machine-size label { font-size: .8125rem; color: var(--ink2); }
503
- #machine-size select { width: 100%; min-height: 40px; font: .875rem var(--sans); color: var(--ink); background-color: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 6px 8px; }
501
+ #machine-size, #shared-size { display: flex; flex-direction: column; gap: 6px; max-width: 30rem; }
502
+ #machine-size label, #shared-size label { font-size: .8125rem; color: var(--ink2); }
503
+ #machine-size select, #shared-size select { width: 100%; min-height: 40px; font: .875rem var(--sans); color: var(--ink); background-color: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 6px 8px; }
504
504
  .health-lines { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
505
505
  .health-lines li { padding-left: 1.3em; position: relative; }
506
506
  .health-lines li::before { content: ""; position: absolute; left: .2em; top: .45em; width: .55em; height: .55em; border-radius: 50%; background: var(--ok); }
@@ -1909,10 +1909,11 @@ button.tip-btn:hover, button.tip-btn[aria-expanded="true"] { color: var(--brass-
1909
1909
  :is(#settings, #panel) .chapter-body .panel-top { border: 0; }
1910
1910
  :is(#settings, #panel) .chapter-body .panel-top > b { font-size: .6875rem; letter-spacing: .06em; text-transform: uppercase; color: var(--ink2); }
1911
1911
  /* The machine's size: each a row, its name on the left, its choice on the right. */
1912
- #panel #machine-size { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 16rem); gap: 10px 16px; align-items: center; max-width: none; }
1913
- #panel #machine-size > label { font-size: .875rem; font-weight: 600; color: var(--ink); }
1914
- #panel #machine-size > :is(p, .row) { grid-column: 1 / -1; }
1915
- #panel #machine-size > .row { justify-content: flex-end; }
1912
+ #panel :is(#machine-size, #shared-size) { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 16rem); gap: 10px 16px; align-items: center; max-width: none; }
1913
+ #panel :is(#machine-size, #shared-size) > label { font-size: .875rem; font-weight: 600; color: var(--ink); }
1914
+ #panel :is(#machine-size, #shared-size) > :is(p, .row) { grid-column: 1 / -1; }
1915
+ #panel :is(#machine-size, #shared-size) > .row { justify-content: flex-end; }
1916
+ #shared-size[hidden] { display: none; }
1916
1917
  @media (max-width: 560px) { #panel #machine-size { grid-template-columns: minmax(0, 1fr); } }
1917
1918
  /* A chapter whose body is one block (Updates, Network): its pieces are the rows, not the block. */
1918
1919
  :is(#settings, #panel) .chapter-body > :is(#updates, #wifi) { padding: 0; }