clavarium 0.2.43-next.1 → 0.2.44-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.
@@ -724,8 +724,16 @@ AREA="$1"; VERB="$2"; shift 2
724
724
 
725
725
  case "$AREA $VERB" in
726
726
  "vm launch")
727
- [ $# -eq 2 ] || usage; vm_of "$1"; memory_ok "$2"
728
- run "$MULTIPASS" launch "$IMAGE" --name "$1" --memory "${2}M" --disk "$DISK" --cpus 1 --timeout "$LAUNCH_SECONDS" ;;
727
+ # <vm> <memory> [<disk-gigabytes> <cores>]: the size chosen at creation;
728
+ # without the last two, the defaults (DISK, one core).
729
+ [ $# -eq 2 ] || [ $# -eq 4 ] || usage; vm_of "$1"; memory_ok "$2"
730
+ disk="$DISK"; cores=1
731
+ if [ $# -eq 4 ]; then
732
+ [[ "$3" =~ ^[0-9]{1,4}$ ]] && [ "$3" -ge 5 ] && [ "$3" -le "$DISK_MAX_GB" ] || refuse "disk out of bounds: $3"
733
+ [[ "$4" =~ ^[0-9]{1,3}$ ]] && [ "$4" -ge 1 ] && [ "$4" -le "$(nproc)" ] || refuse "cores out of bounds: $4 (the host has $(nproc))"
734
+ disk="${3}G"; cores="$4"
735
+ fi
736
+ run "$MULTIPASS" launch "$IMAGE" --name "$1" --memory "${2}M" --disk "$disk" --cpus "$cores" --timeout "$LAUNCH_SECONDS" ;;
729
737
  "vm clone")
730
738
  # <shelf> <vm> <memory>: a conversation's machine, copied from the
731
739
  # ready-made one (which must be stopped: Multipass refuses otherwise).
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.43-next.1",
3
+ "version": "0.2.44-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.43-next.1",
9
+ "version": "0.2.44-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
- "clavarium-binder": "0.1.6-next.1",
14
+ "clavarium-binder": "0.1.8-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.4-next.1",
16
+ "clavarium-parley": "0.17.8-next.1",
17
17
  "mermaid": "11.17.2",
18
18
  "node-pty": "^1.1.0",
19
19
  "pdfjs-dist": "6.4.299",
@@ -688,9 +688,9 @@
688
688
  }
689
689
  },
690
690
  "node_modules/clavarium-binder": {
691
- "version": "0.1.6-next.1",
692
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.6-next.1.tgz",
693
- "integrity": "sha512-urE1ZZCYq9svQmQR1ailNX6r5OeBcT0wNDea498PMDRbmcUCOciqoF/1C3IGLT7z133eb4dOUEhVcbRE42/h3A==",
691
+ "version": "0.1.8-next.1",
692
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
693
+ "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
694
694
  "license": "MIT",
695
695
  "bin": {
696
696
  "binder": "bin/binder.mjs",
@@ -714,9 +714,9 @@
714
714
  }
715
715
  },
716
716
  "node_modules/clavarium-parley": {
717
- "version": "0.17.4-next.1",
718
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.4-next.1.tgz",
719
- "integrity": "sha512-/rQy9WLP9/XndInawH6mIhS9RivA1IQmMpB5IhYMUflnLSWBvP096Z0TF3xB3u2X1e8uni4tar5Tua5hq/wjWg==",
717
+ "version": "0.17.8-next.1",
718
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.8-next.1.tgz",
719
+ "integrity": "sha512-AJHz4V91heYRuCYh3KXRi8kw5ArNTLNsKpA2Svw6JoGKh7wCRr+Wp3ayiJDpukdjLHkijEuk7vhFE3c7L/LQ3g==",
720
720
  "license": "MIT",
721
721
  "bin": {
722
722
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.43-next.1",
3
+ "version": "0.2.44-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.",
@@ -44,9 +44,9 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.6-next.1",
47
+ "clavarium-binder": "0.1.8-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.4-next.1",
49
+ "clavarium-parley": "0.17.8-next.1",
50
50
  "mermaid": "11.17.2",
51
51
  "node-pty": "^1.1.0",
52
52
  "pdfjs-dist": "6.4.299",
package/server/api.mjs CHANGED
@@ -235,7 +235,7 @@ export async function handleApi(request, response, conversations, headers, resou
235
235
  if (pathname === '/api/tools') return send(200, conversations.tools()), true;
236
236
  if (pathname === '/api/conversations') {
237
237
  const lists = binders?.given() ?? {};
238
- return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
238
+ return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], ephemeralSecrets: secrets?.liveFor(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
239
239
  }
240
240
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
241
241
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
@@ -505,6 +505,14 @@ export async function handleApi(request, response, conversations, headers, resou
505
505
  retell(conversation);
506
506
  return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
507
507
  }
508
+ /* Forget an ephemeral secret now (its stars in the chat have a button): gone from the vault and the machine. */
509
+ const forgetSecret = /^\/api\/conversations\/([^/]+)\/secrets\/([^/]+)\/forget$/.exec(pathname);
510
+ if (forgetSecret && secrets) {
511
+ const conversation = decodeURIComponent(forgetSecret[1]);
512
+ if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
513
+ await secrets.drop(conversation, decodeURIComponent(forgetSecret[2]));
514
+ return send(200, { ok: true }), true;
515
+ }
508
516
  const share = /^\/api\/conversations\/([^/]+)\/share$/.exec(pathname);
509
517
  if (share && sharing) {
510
518
  const conversation = decodeURIComponent(share[1]);
@@ -260,7 +260,7 @@ export class Conversations {
260
260
  return { name: id, title: title !== undefined && title !== id ? title : undefined };
261
261
  }
262
262
 
263
- create({ name: given, title: read, tool, memoryMb, workOnDisk, group }) {
263
+ create({ name: given, title: read, tool, memoryMb, cpus, diskGb, workOnDisk, group }) {
264
264
  const { name, title } = this.#naming({ name: given, title: read });
265
265
  if (group !== undefined) { const problem = groupProblem(group); if (problem) throw new Refusal(400, problem); }
266
266
  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.');
@@ -270,9 +270,14 @@ export class Conversations {
270
270
  if (!Number.isInteger(memory) || memory < chosen.memoryMb || memory > 16384) {
271
271
  throw new Refusal(400, `This tool needs at least ${chosen.memoryMb} MB of memory.`);
272
272
  }
273
+ /* Cores and disk, chosen at creation like the memory; their defaults when not given. */
274
+ const cores = cpus ?? 1;
275
+ if (!Number.isInteger(cores) || cores < 1 || cores > availableParallelism()) throw new Refusal(400, `Cores are 1 to ${availableParallelism()} (what this server has).`);
276
+ const disk = diskGb ?? DISK_GB;
277
+ if (!Number.isInteger(disk) || disk < DISK_GB || disk > DISK_MAX_GB) throw new Refusal(400, `Disk is ${DISK_GB} to ${DISK_MAX_GB} GB.`);
273
278
  if (this.#store.get(name)) throw new Refusal(409, 'A conversation already has this name.');
274
279
  const now = new Date().toISOString();
275
- const conversation = { name, ...(title ? { title } : {}), ...(group ? { group } : {}), tool, memoryMb: memory, diskGb: DISK_GB, fixed: FIXES, work: workOnDisk === true ? 'disk' : 'kept', phase: 'building', step: 'Starting the machine', createdAt: now, buildingSince: now, progress: buildProgress(now) };
280
+ 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) };
276
281
  /* A new one comes first in its folder (or first of those in none). */
277
282
  const { order, groups } = this.#order();
278
283
  this.#store.put(conversation);
@@ -284,6 +289,11 @@ export class Conversations {
284
289
  /* `again`: a machine built anew for a conversation that had one. */
285
290
  async #build(name, tool, memoryMb, again = false) {
286
291
  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}`}` }); };
292
+ /* The size chosen at creation (stored by create, kept on a rebuild): launched with it, or, for a
293
+ copy of a ready-made machine, brought to it while the copy is still stopped. */
294
+ const made = this.#store.get(name);
295
+ const diskGb = made?.diskGb ?? DISK_GB; const cpus = made?.cpus ?? 1;
296
+ const custom = diskGb !== DISK_GB || cpus !== 1;
287
297
  /* A COPY OF THE READY-MADE MACHINE when there is one that holds this
288
298
  tool (see shelf.mjs): it only has to boot. Anything wrong with the
289
299
  copy -- an older VM manager without "clone", a copy that does not
@@ -293,13 +303,18 @@ export class Conversations {
293
303
  let readyMade = false;
294
304
  if (from) {
295
305
  const cloned = await this.#vms.clone(name, from, memoryMb);
306
+ if (cloned.code === 0 && custom) {
307
+ /* Still stopped, like the memory the clone set: its cores, and its disk grown to the chosen size. */
308
+ if (cpus !== 1) await this.#vms.setCpus(name, cpus).catch(() => {});
309
+ if (diskGb !== DISK_GB) await this.#vms.setDisk(name, diskGb).catch(() => {});
310
+ }
296
311
  const started = cloned.code === 0 ? await this.#vms.start(name) : cloned;
297
312
  readyMade = started.code === 0;
298
313
  if (!readyMade && await this.#vms.state(name, { fresh: true }) !== undefined) await this.#vms.remove(name);
299
314
  if (!this.#store.get(name)) return undefined; /* archived meanwhile */
300
315
  }
301
316
  if (!readyMade) {
302
- const launched = await this.#vms.launch(name, memoryMb);
317
+ const launched = await this.#vms.launch(name, memoryMb, custom ? diskGb : undefined, custom ? cpus : undefined);
303
318
  if (launched.code !== 0) return fail('The machine did not start', launched);
304
319
  }
305
320
  this.#store.patch(name, { step: 'Preparing the machine', readyMade: readyMade || undefined });
package/server/guide.mjs CHANGED
@@ -129,6 +129,8 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
129
129
  if (chat) out.push('- When you work in batches: keep them in a binder of batches, shown beside the chat. None yet: make it once (binder new batches; MCP: new-list, template batches). Then one card each (binder add Batches "title"), kept up to date; start only those the person ticked.');
130
130
  out.push(online === false ? '- Internet: off.' : '- Internet: on.');
131
131
  if (secrets.length) out.push(`- Secrets given, by name only: ${list(secrets.map((s) => plain(s, 40)))}.`);
132
+ /* A secret pasted in the chat is lifted out (talk.mjs, secret-scan.mjs): the message shows a marker, the value waits in /run/secrets. */
133
+ if (chat) out.push('- A secret the person pastes in the chat is kept OUT of it: the message shows ⟨secret:NAME⟩ and the value waits at /run/secrets/NAME for a few minutes. Use it only from there, inside a command (clv-run, or $(cat /run/secrets/NAME)); never write its value back into the chat. It clears itself when its time runs out, or at once with `parley forget NAME` when you are done.');
132
134
  const own = lines.map((l) => plain(l)).filter(Boolean).slice(0, LINES_MAX);
133
135
  if (own.length) out.push('', '## From the owner', '', ...own.map((l) => `- ${l}`));
134
136
  out.push('');
package/server/main.mjs CHANGED
@@ -35,6 +35,7 @@ import { Devices } from './devices.mjs';
35
35
  import { handleDoor, deviceTerminal } from './door.mjs';
36
36
  import { Vault } from './vault.mjs';
37
37
  import { Secrets, RUNNER } from './secrets.mjs';
38
+ import { scan, secretRef } from './secret-scan.mjs';
38
39
  import { Network } from './network.mjs';
39
40
  import { Answerer, answererConfig } from './answerer.mjs';
40
41
  import { Dockets } from './dockets.mjs';
@@ -420,6 +421,26 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
420
421
  what is already known of a machine used instead of asking (talk.mjs). */
421
422
  terminal: { open: (name) => bridge?.open(name) ?? false, type: (name, line, ms) => bridge?.type(name, line, ms) ?? false, droppedAt: (name) => bridge?.droppedAt(name) },
422
423
  health: { of: (name) => health?.of(name) ?? null },
424
+ /* A secret pasted in a message is lifted out before the message is kept:
425
+ it goes to the short-lived vault and the message keeps only a marker
426
+ the chat shows as stars; the value reaches the machine as
427
+ /run/secrets/<name>, and is swept after a few minutes. */
428
+ screen: async (conversation, text) => {
429
+ const hits = scan(text);
430
+ if (!hits.length) return text;
431
+ let out = ''; let last = 0; let any = false;
432
+ for (const h of hits) {
433
+ out += text.slice(last, h.start);
434
+ try { const { name, expiresAt } = secrets.stash(conversation, h.value); out += secretRef(name, Date.parse(expiresAt)); any = true; }
435
+ catch { out += text.slice(h.start, h.end); } /* cannot be stashed (too large): left as it is */
436
+ last = h.end;
437
+ }
438
+ out += text.slice(last);
439
+ if (any) { try { await secrets.deliver(conversation); } catch { /* machine not running: delivered at its next open */ } }
440
+ return out;
441
+ },
442
+ /* The agent asked to forget a short-lived secret (parley forget): drop it from the vault and machine. */
443
+ dropSecret: (conversation, name) => { void secrets.drop(conversation, name).catch(() => {}); },
423
444
  alert: (payload) => { void alerts.tell(payload); } });
424
445
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
425
446
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
@@ -0,0 +1,93 @@
1
+ /* SECRET SCANNER -- finds likely secrets in a message, without any model.
2
+ *
3
+ * Used when a person's message arrives (talk.mjs): what looks like a token,
4
+ * key or password is lifted out, kept in the vault for a few minutes, and the
5
+ * message keeps only a reference. The aim is FEW FALSE POSITIVES: we match
6
+ * shapes that are almost never anything but a secret (known token prefixes, a
7
+ * PEM private key), plus long high-entropy blobs. Ordinary prose, file paths,
8
+ * URLs, git hashes and UUIDs are left alone. A person can still mark a
9
+ * selection by hand (talk.mjs) for what the shapes miss, or undo a wrong one.
10
+ *
11
+ * `scan(text)` returns the non-overlapping matches, each { start, end, value,
12
+ * kind }, left to right. Nothing is stored here: the caller decides.
13
+ */
14
+
15
+ /* Shapes that are almost always a secret. Order matters only for the `kind`
16
+ label; overlaps are resolved by position below. */
17
+ const SHAPES = [
18
+ { kind: 'private-key', re: /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g },
19
+ { kind: 'github', re: /\bgithub_pat_[0-9A-Za-z_]{40,}\b/g },
20
+ { kind: 'github', re: /\bgh[pousr]_[0-9A-Za-z]{36,}\b/g },
21
+ { kind: 'npm', re: /\bnpm_[0-9A-Za-z]{36}\b/g },
22
+ { kind: 'aws', re: /\bAKIA[0-9A-Z]{16}\b/g },
23
+ { kind: 'google', re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
24
+ { kind: 'slack', re: /\bxox[baprs]-[0-9A-Za-z-]{10,}\b/g },
25
+ { kind: 'api-key', re: /\bsk-(?:ant-|proj-|live-|test-)?[0-9A-Za-z_-]{20,}\b/g },
26
+ { kind: 'jwt', re: /\beyJ[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,}\b/g },
27
+ ];
28
+
29
+ /* A long run of token characters, caught only when it looks random (not a
30
+ path, a hash or a word). */
31
+ const BLOB = /[0-9A-Za-z+/=_-]{40,}/g;
32
+ /* A SHORTER run of letters and digits only (no symbols, so a UUID's or path's dashes break it up): caught
33
+ when it is improbable -- it mixes upper, lower AND digits, and its entropy is high. This is the "unusual
34
+ word" net: a random-looking password or key the known shapes missed, without flagging a hash or an id. */
35
+ const WORD = /[A-Za-z0-9]{20,39}/g;
36
+ const ENTROPY_MIN = 3.5; /* bits per character */
37
+ const CLASSES_MIN = 3; /* of: lower, upper, digit, symbol */
38
+
39
+ function entropy(s) {
40
+ const count = new Map();
41
+ for (const c of s) count.set(c, (count.get(c) ?? 0) + 1);
42
+ let bits = 0;
43
+ for (const n of count.values()) { const p = n / s.length; bits -= p * Math.log2(p); }
44
+ return bits;
45
+ }
46
+ function classes(s) {
47
+ let n = 0;
48
+ if (/[a-z]/.test(s)) n += 1;
49
+ if (/[A-Z]/.test(s)) n += 1;
50
+ if (/[0-9]/.test(s)) n += 1;
51
+ if (/[^0-9A-Za-z]/.test(s)) n += 1;
52
+ return n;
53
+ }
54
+ /* A blob that is only hex (a git sha, a checksum) or only one case is not a
55
+ secret for us: too many false positives, and real tokens mix classes. */
56
+ function looksRandom(s) {
57
+ return classes(s) >= CLASSES_MIN && entropy(s) >= ENTROPY_MIN;
58
+ }
59
+ /* The shorter net: all three of upper, lower and digit present (a hash or a word misses one), and high entropy. */
60
+ function improbableWord(s) {
61
+ return /[a-z]/.test(s) && /[A-Z]/.test(s) && /[0-9]/.test(s) && entropy(s) >= ENTROPY_MIN;
62
+ }
63
+
64
+ /* How a lifted secret is written back into the message: a marker the chat
65
+ shows as stars (ui side), and the tool reads to use /run/secrets/<name>.
66
+ Named like `SECRET_` + 10 hex (secrets.mjs stash). The angle brackets
67
+ (U+27E8/U+27E9) are vanishingly rare in a real message. */
68
+ export const secretRef = (name, at) => `⟨secret:${name}${Number.isFinite(at) ? `@${at}` : ''}⟩`;
69
+ export const SECRET_REF = /⟨secret:(SECRET_[0-9A-F]{10})(?:@(\d+))?⟩/g;
70
+
71
+ export function scan(text) {
72
+ const str = String(text ?? '');
73
+ const found = [];
74
+ for (const { kind, re } of SHAPES) {
75
+ re.lastIndex = 0;
76
+ for (let m; (m = re.exec(str));) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind });
77
+ }
78
+ for (let m; (m = BLOB.exec(str));) {
79
+ if (looksRandom(m[0])) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
80
+ }
81
+ BLOB.lastIndex = 0;
82
+ for (let m; (m = WORD.exec(str));) {
83
+ if (improbableWord(m[0])) found.push({ start: m.index, end: m.index + m[0].length, value: m[0], kind: 'high-entropy' });
84
+ }
85
+ WORD.lastIndex = 0;
86
+ /* Keep left-to-right, and when two matches overlap keep the one that starts
87
+ first (and, equal, the longer): a known prefix wins over the blob rule. */
88
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
89
+ const out = [];
90
+ let reach = -1;
91
+ for (const f of found) { if (f.start >= reach) { out.push(f); reach = f.end; } }
92
+ return out;
93
+ }
@@ -21,6 +21,7 @@
21
21
  * should use on the agent's behalf (a push key, a mailbox password) does not
22
22
  * belong here, and never enters a VM.
23
23
  */
24
+ import { randomBytes } from 'node:crypto';
24
25
  import { Refusal } from './conversations.mjs';
25
26
  import { Grants, conversationSubject } from './grants.mjs';
26
27
  import { isConversationName } from './names.mjs';
@@ -30,6 +31,12 @@ export const SECRETS_DIR = '/run/secrets';
30
31
  export const RUNNER = '/usr/local/bin/clv-run';
31
32
  export const VALUE_MAX = 8 * 1024;
32
33
  export const WARN_DAYS = 7;
34
+ /* A secret lifted from a message (secret-scan.mjs): a random name, a short
35
+ life in MINUTES (not days), swept when it runs out. */
36
+ export const EPHEMERAL_PREFIX = 'SECRET_';
37
+ export const TTL_DEFAULT_MS = 10 * 60_000;
38
+ export const TTL_MIN_MS = 60_000;
39
+ export const TTL_MAX_MS = 60 * 60_000;
33
40
  const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
34
41
  const DAY_MS = 86_400_000;
35
42
  const NAME = /^[A-Z][A-Z0-9_]{0,39}$/;
@@ -69,7 +76,7 @@ export function daysTo(day, now = new Date()) {
69
76
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
70
77
 
71
78
  export class Secrets {
72
- #store; #vault; #vms; #grants; #now;
79
+ #store; #vault; #vms; #grants; #now; #timers = new Map();
73
80
 
74
81
  /* `grants`: the one table of rights. "Handed to a conversation" is a
75
82
  line of it: the conversation may USE the secret. */
@@ -80,9 +87,19 @@ export class Secrets {
80
87
  for (const conversation of Object.keys(s.attachments)) this.#grants.give(conversationSubject(conversation), `secret:${s.name}`, 'x');
81
88
  delete s.attachments; store.put(s);
82
89
  }
90
+ /* A restart loses the sweep timers: drop the ephemeral secrets that ran
91
+ out while down, and set a fresh timer for those still alive. */
92
+ for (const s of store.all()) {
93
+ if (s.ephemeral !== true) continue;
94
+ const who = this.#users(s.name)[0];
95
+ const left = who ? Date.parse(s.expiresAt) - this.#now().getTime() : 0;
96
+ if (!who || !(left > 0)) { store.remove(s.name); this.#grants.forgetAsset(`secret:${s.name}`); }
97
+ else this.#schedule(who, s.name, left);
98
+ }
83
99
  }
84
100
  #handed(conversation, name) { return this.#grants.can(conversationSubject(conversation), `secret:${name}`, 'x'); }
85
- #expired(s) { return Boolean(s.expires) && daysTo(s.expires, this.#now()) <= 0; }
101
+ /* Ephemeral: gone at its moment (minutes). Otherwise: gone from its day on. */
102
+ #expired(s) { return s.expiresAt ? Date.parse(s.expiresAt) <= this.#now().getTime() : (Boolean(s.expires) && daysTo(s.expires, this.#now()) <= 0); }
86
103
  #users(name) { return this.#grants.on(`secret:${name}`).map((g) => g.subject.slice('conversation:'.length)); }
87
104
  /* What is delivered to this conversation: handed, and not expired. */
88
105
  #given(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name) && !this.#expired(s)); }
@@ -91,7 +108,8 @@ export class Secrets {
91
108
  days left (null without an expiry); `expired`: no longer delivered. */
92
109
  list() {
93
110
  return this.#store.all().map((s) => ({ name: s.name, conversations: this.#users(s.name), createdAt: s.createdAt,
94
- expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s) }));
111
+ expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s),
112
+ ...(s.ephemeral ? { ephemeral: true, expiresAt: s.expiresAt, expiresInMs: Math.max(0, Date.parse(s.expiresAt) - this.#now().getTime()) } : {}) }));
95
113
  }
96
114
  /* Past its expiry day: kept, not used (nor by dictation, voice.mjs). */
97
115
  isExpired(name) { const s = this.#store.get(name); return Boolean(s) && this.#expired(s); }
@@ -99,6 +117,9 @@ export class Secrets {
99
117
  of(conversation) { return this.#store.all().filter((s) => this.#handed(conversation, s.name)).map((s) => s.name); }
100
118
  /* Delivered to it at its next start. */
101
119
  given(conversation) { return this.#given(conversation).map((s) => s.name); }
120
+ /* The EPHEMERAL secrets live for it now (a message of it holds their marker), each with how long it has
121
+ left -- the chat shows the stars with that, and a way to forget it (talk/parley-ui). Never a value. */
122
+ liveFor(conversation) { return this.#given(conversation).filter((s) => s.ephemeral === true).map((s) => ({ name: s.name, expiresInMs: Math.max(0, Date.parse(s.expiresAt) - this.#now().getTime()) })); }
102
123
 
103
124
  /* The value, for this server's own use only (the key of the dictation
104
125
  engine, put in a request's header): never returned by any route. */
@@ -187,6 +208,48 @@ export class Secrets {
187
208
  for (const s of this.#store.all()) this.#grants.take(conversationSubject(conversation), `secret:${s.name}`);
188
209
  }
189
210
 
211
+ /* AN EPHEMERAL SECRET lifted from a message of `conversation` (talk.mjs):
212
+ a random name, a few minutes to live, handed at once to that
213
+ conversation, swept when it runs out. Returns { name, expiresAt } -- the
214
+ name is the reference the message keeps (its value is masked there). As
215
+ with every secret the value is sealed and never returned by any route;
216
+ the tool uses it only as /run/secrets/<name>, and never sees it. */
217
+ stash(conversation, value, { ttlMs } = {}) {
218
+ if (!isConversationName(conversation)) throw new Refusal(400, 'Not a conversation.');
219
+ const sealed = this.#seal(value);
220
+ const ttl = Math.min(TTL_MAX_MS, Math.max(TTL_MIN_MS, Number.isFinite(ttlMs) ? ttlMs : TTL_DEFAULT_MS));
221
+ let name; do { name = EPHEMERAL_PREFIX + randomBytes(5).toString('hex').toUpperCase(); } while (this.#store.get(name));
222
+ const expiresAt = new Date(this.#now().getTime() + ttl).toISOString();
223
+ this.#store.put({ name, sealed, createdAt: this.#now().toISOString(), expiresAt, ephemeral: true });
224
+ this.#grants.give(conversationSubject(conversation), `secret:${name}`, 'x');
225
+ this.#schedule(conversation, name, ttl);
226
+ return { name, expiresAt };
227
+ }
228
+
229
+ /* Forgotten before it runs out, on the tool's word or the owner's: gone
230
+ from the vault and, at once, from the running machine. */
231
+ async drop(conversation, name) {
232
+ const s = this.#store.get(name);
233
+ if (!s || s.ephemeral !== true) throw new Refusal(404, 'No such short-lived secret.');
234
+ const t = this.#timers.get(name); if (t) { clearTimeout(t); this.#timers.delete(name); }
235
+ await this.#reap(conversation, name);
236
+ return { name };
237
+ }
238
+
239
+ #schedule(conversation, name, ttl) {
240
+ const t = setTimeout(() => { this.#timers.delete(name); void this.#reap(conversation, name); }, ttl);
241
+ t.unref?.();
242
+ this.#timers.set(name, t);
243
+ }
244
+ /* Remove it, then rewrite the machine's /run/secrets without it (a tmpfs
245
+ already cleared if the machine is gone -- so a failure here is fine). */
246
+ async #reap(conversation, name) {
247
+ if (this.#store.get(name)) { this.#store.remove(name); this.#grants.forgetAsset(`secret:${name}`); }
248
+ try { await this.deliver(conversation); } catch { /* machine asleep or busy: /run/secrets is tmpfs */ }
249
+ try { this.reaped(conversation, name); } catch { /* told nowhere: never a reason to fail */ }
250
+ }
251
+ reaped = () => {};
252
+
190
253
  /* What a delivery to this conversation would contain, as one string that
191
254
  changes whenever a delivery would differ: names and sealed values. */
192
255
  signature(conversation) {
package/server/talk.mjs CHANGED
@@ -60,7 +60,7 @@
60
60
  */
61
61
  import { posix, join } from 'node:path';
62
62
  import { randomUUID, createHash } from 'node:crypto';
63
- import { mkdirSync, lstatSync, rmSync } from 'node:fs';
63
+ import { mkdirSync, lstatSync, rmSync, readFileSync } from 'node:fs';
64
64
  import { install, Parley, WAKE, reread, texts, fill, LANGUAGES, SHOWN_MAX, FILES_MAX } from 'clavarium-parley/host';
65
65
  import { importFile } from './files.mjs';
66
66
  import { KEYS } from 'clavarium-parley/ui';
@@ -182,7 +182,7 @@ const PART = /^[A-Za-z0-9._~-]{1,200}$/;
182
182
  export class Talk {
183
183
  #store; #words; #vms; #conversations; #resources; #toolbox; #warm; #alert; #listening = new Map(); #every; #now;
184
184
  #typedAt = new Map(); #nextTry = new Map(); #trying = new Map(); #timer; #lastLang = 'en'; #rereadAfter;
185
- #terminal; #health; #ranAt = new Map(); #kept;
185
+ #terminal; #health; #ranAt = new Map(); #kept; #screen; #dropSecret;
186
186
 
187
187
  /* `alert({ title, body, url })`: told when the tool asks, or waits.
188
188
  `words`: a store for the owner's choice of words (one record). */
@@ -192,8 +192,8 @@ export class Talk {
192
192
  /* `keptDir`: where each conversation's thread is kept (its own folder),
193
193
  in this server's data -- never in the work folder, which its machine
194
194
  writes. Without it, the bridge folder is all there is. */
195
- constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null }) {
196
- this.#terminal = terminal; this.#health = health; this.#kept = keptDir;
195
+ constructor({ store, words, vms, conversations, resources, toolbox = null, warm = async () => {}, alert = () => {}, listenEveryMs = 2000, now = () => Date.now(), rereadAfterMs = REREAD_AFTER_MS, terminal = null, health = null, keptDir = null, screen = null, dropSecret = null }) {
196
+ this.#terminal = terminal; this.#health = health; this.#kept = keptDir; this.#screen = screen; this.#dropSecret = dropSecret;
197
197
  this.#store = store; this.#words = words; this.#vms = vms; this.#conversations = conversations; this.#resources = resources; this.#toolbox = toolbox; this.#warm = warm; this.#alert = alert; this.#every = listenEveryMs; this.#now = now; this.#rereadAfter = rereadAfterMs;
198
198
  for (const s of store.all()) if (s.on === true) this.#listen(s.name);
199
199
  this.#timer = setInterval(() => { void this.#tick(); }, Math.min(listenEveryMs, 1000));
@@ -448,7 +448,13 @@ export class Talk {
448
448
  const note = item && typeof item === 'object' && typeof item.note === 'string' ? item.note : '';
449
449
  return { path, name: m[2], size: info.size, ...(note ? { note } : {}) };
450
450
  });
451
- try { this.#parley(name).say(text ?? '', answers, attached, { via: via === 'voice' ? 'voice' : undefined, ...(extra && typeof extra === 'object' ? { picked: extra.picked, replies: extra.replies, about: extra.about } : {}) }); } catch (error) { if (error instanceof RangeError) throw new Refusal(400, error.message); throw error; }
451
+ /* A secret pasted in the message (a token, a key) is lifted into a
452
+ short-lived store, and the message keeps only a reference -- the
453
+ thread never holds the value (secret-scan.mjs, secrets.mjs). It must
454
+ never lose a message: on any trouble the text is sent as it came. */
455
+ let said = text ?? '';
456
+ if (this.#screen && said) { try { said = await this.#screen(name, said); } catch { said = text ?? ''; } }
457
+ try { this.#parley(name).say(said, answers, attached, { via: via === 'voice' ? 'voice' : undefined, ...(extra && typeof extra === 'object' ? { picked: extra.picked, replies: extra.replies, about: extra.about } : {}) }); } catch (error) { if (error instanceof RangeError) throw new Refusal(400, error.message); throw error; }
452
458
  const told = await this.#wake(name);
453
459
  return { ...this.of(name), told };
454
460
  }
@@ -637,6 +643,7 @@ export class Talk {
637
643
 
638
644
  async #tick() {
639
645
  for (const r of this.#store.all()) {
646
+ if (r.on === true) this.#reapForgets(r);
640
647
  if (r.on === true && r.reread === true) { await this.#tryReread(r.name).catch(() => {}); continue; }
641
648
  if (r.on !== true || (!r.pending && !r.woke)) continue;
642
649
  /* It has read: what waited is done, and the next message wakes it again. */
@@ -646,6 +653,20 @@ export class Talk {
646
653
  }
647
654
  }
648
655
 
656
+ /* The agent asked to forget short-lived secrets (parley forget -> forget.jsonl beside its thread): the
657
+ parloir drops each from its vault and machine at once. Each request is acted on once, counted in the store. */
658
+ #reapForgets(r) {
659
+ if (!this.#dropSecret) return;
660
+ let lines;
661
+ try { lines = readFileSync(`${this.#dir(r.name)}/forget.jsonl`, 'utf8').split('\n').filter(Boolean); } catch { return; }
662
+ const done = r.forgotten ?? 0;
663
+ if (lines.length <= done) return;
664
+ for (const line of lines.slice(done)) {
665
+ try { const name = JSON.parse(line)?.name; if (typeof name === 'string' && /^SECRET_[0-9A-F]{10}$/.test(name)) void this.#dropSecret(r.name, name); } catch { /* a stray line */ }
666
+ }
667
+ this.#store.put({ ...r, forgotten: lines.length });
668
+ }
669
+
649
670
  forget(name) { this.#deaf(name); if (this.#keep(name)) rmSync(this.#keep(name), { recursive: true, force: true }); this.#store.remove(name); this.#typedAt.delete(name); this.#ranAt.delete(name); this.#nextTry.delete(name); this.#nextTry.delete(`reread:${name}`); }
650
671
  stop() { clearInterval(this.#timer); for (const name of [...this.#listening.keys()]) this.#deaf(name); }
651
672
  }
package/server/vm.mjs CHANGED
@@ -93,8 +93,10 @@ export class Vms {
93
93
  return this.#asking;
94
94
  }
95
95
 
96
- launch(conversation, memoryMb) {
97
- return this.run(['vm', 'launch', vmName(conversation), String(memoryMb)], { timeoutMs: (LAUNCH_SECONDS + 60) * 1000 });
96
+ launch(conversation, memoryMb, diskGb, cpus) {
97
+ /* The disk and cores go with the memory only when they are the chosen size, not the defaults. */
98
+ const size = diskGb && cpus ? [String(diskGb), String(cpus)] : [];
99
+ return this.run(['vm', 'launch', vmName(conversation), String(memoryMb), ...size], { timeoutMs: (LAUNCH_SECONDS + 60) * 1000 });
98
100
  }
99
101
 
100
102
  /* The machine of a conversation as a COPY of the ready-made one (see
package/web/app.js CHANGED
@@ -111,8 +111,10 @@
111
111
  $('notice-spin').hidden = true; $('notice-steps').hidden = true;
112
112
  $('notice-head').hidden = true; delete notice.dataset.progress; delete notice.dataset.loading;
113
113
  };
114
- /* A terminal on its way: a neutral word and the wheel, nothing that sounds like a fault. */
115
- const loading = () => { show('Loading the terminal\u2026'); $('notice-spin').hidden = false; notice.dataset.loading = 'yes'; };
114
+ /* A terminal on its way: a neutral word and the wheel, nothing that sounds like a fault. It
115
+ covers only when the terminal is what is on screen -- not the chat already there, which a tab
116
+ resume (its channel reopened) used to blank behind "Loading the terminal..." (found 26-10). */
117
+ const loading = () => { if (tabNow() !== 'terminal') return; show('Loading the terminal\u2026'); $('notice-spin').hidden = false; notice.dataset.loading = 'yes'; };
116
118
  /* A restart: when the page first saw it (when the server did not say), and the clock that tells it. */
117
119
  const restartSeen = new Map(); let restartTicking = 0;
118
120
  /* A START TOLD STEP BY STEP (a build, a restart, a wake: `progress`, see
@@ -833,6 +835,11 @@
833
835
  if (noTerminal()) $('files-open').hidden = deviceShared.length === 0;
834
836
  $('sleep').hidden = !usable || c.asleep === true;
835
837
  $('restart').hidden = DEVICE || !usable;
838
+ /* The same gestures, surfaced at the top of the panel: wake when asleep, else restart and sleep. */
839
+ $('quick-sleep').hidden = !usable || c.asleep === true;
840
+ $('quick-restart').hidden = DEVICE || !usable;
841
+ $('quick-wake').hidden = !c || c.asleep !== true;
842
+ $('panel-actions').hidden = DEVICE || !c || !(usable || c.asleep === true);
836
843
  /* Its own sheet is there as soon as it exists: archiving one that failed is done from it. */
837
844
  $('folders').hidden = DEVICE || !c;
838
845
  }
@@ -959,17 +966,21 @@
959
966
  full -- not marked "Seen"; a program stopped for lack of memory (its files safe) is only said. */
960
967
  const healthNeeds = (c) => c.phase === 'ready' && !c.asleep && (c.health?.problems ?? []).some((p) => (p.level === 'bad' || (p.level === 'warn' && ['memory', 'disk'].includes(p.kind) && !String(p.key).startsWith('oom:'))) && !(c.health.seen ?? []).includes(p.key));
961
968
  const needsYou = (c) => Boolean(talkNeeds(c) || c.answerer?.needs || c.phase === 'failed' || healthNeeds(c));
962
- /* ONE STATE PER CONVERSATION, one point for it: it needs you (red), something to watch (yellow: being built,
963
- restarted, moved), fine (green), asleep (a hollow ring). */
964
- const STATE_WORDS = { need: 'needs you', watch: 'to watch', ok: 'fine', sleep: 'asleep' };
965
- const stateOf = (c) => (needsYou(c) ? 'need' : c.asleep ? 'sleep' : holds(c) || ['building', 'restarting', 'moving'].includes(c.phase) ? 'watch' : 'ok');
969
+ /* ONE FLAT POINT per conversation, its colour the state -- the worst that applies: a machine problem (red),
970
+ the agent waits for you (blue), the agent at work (gold, pulsing), the machine busy (amber, pulsing),
971
+ fine (green), asleep (a hollow ring). The same point, same colours, sums a folded group below. */
972
+ const machineState = (c) => (c.asleep ? 'off' : (c.phase === 'failed' || healthNeeds(c)) ? 'problem'
973
+ : (holds(c) || ['building', 'restarting', 'moving'].includes(c.phase)) ? 'busy' : 'online');
974
+ const agentState = (c) => (c.asleep ? 'sleep' : (talkNeeds(c) || c.answerer?.needs) ? 'wait'
975
+ : c.talk?.state === 'working' ? 'work' : c.talk?.state === 'done' ? 'done' : 'idle');
976
+ const STATE_WORDS = { problem: 'a problem', wait: 'waits for you', work: 'at work', busy: 'busy', ok: 'fine', sleep: 'asleep' };
977
+ const rollup = (c) => { const m = machineState(c); const a = agentState(c);
978
+ return (m === 'off' ? 'sleep' : m === 'problem' ? 'problem' : a === 'wait' ? 'wait' : a === 'work' ? 'work' : m === 'busy' ? 'busy' : 'ok'); };
966
979
  const statePoint = (state) => { const d = document.createElement('span'); d.className = 'state-dot'; d.dataset.state = state; return d; };
967
- /* Folded, a heading says how its conversations are: at most four points, shared out like them -- every state
968
- there keeps at least one, the worst first -- and the same in words for a screen reader and the pointer. */
969
- const STATE_ORDER = ['need', 'watch', 'ok', 'sleep'];
980
+ const STATE_ORDER = ['problem', 'wait', 'work', 'busy', 'ok', 'sleep'];
970
981
  function stateSummary(list) {
971
982
  const count = Object.fromEntries(STATE_ORDER.map((k) => [k, 0]));
972
- for (const c of list) count[stateOf(c)] += 1;
983
+ for (const c of list) count[rollup(c)] += 1;
973
984
  const slots = Math.min(4, list.length);
974
985
  const present = STATE_ORDER.filter((k) => count[k] > 0);
975
986
  const got = Object.fromEntries(STATE_ORDER.map((k) => [k, 0]));
@@ -1011,7 +1022,8 @@
1011
1022
  const whenWords = (t) => {
1012
1023
  if (!t) return '';
1013
1024
  const d = new Date(t); const now = new Date();
1014
- if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
1025
+ /* Today: how long ago, not the clock -- the list is sorted by it, so "2 min" reads better than "15:05". */
1026
+ if (d.toDateString() === now.toDateString()) { const m = Math.max(0, Math.floor((now - d) / 60_000)); return m < 1 ? 'now' : m < 60 ? `${m} min` : `${Math.floor(m / 60)} h`; }
1015
1027
  const y = new Date(now); y.setDate(now.getDate() - 1);
1016
1028
  if (d.toDateString() === y.toDateString()) return 'yesterday';
1017
1029
  return now - d < 6 * 86_400_000 ? d.toLocaleDateString([], { weekday: 'short' }) : d.toLocaleDateString([], { day: 'numeric', month: 'short' });
@@ -1043,12 +1055,14 @@
1043
1055
  const when = document.createElement('small'); when.className = 'when'; when.textContent = whenWords(activityOf(c));
1044
1056
  b.append(title);
1045
1057
  /* Its last message, and who said it: so it reads as the last message, not as a subject. */
1046
- if (c.talk?.lastText) { const last = document.createElement('small'); last.className = 'last'; const who = c.talk.lastFrom === 'person' ? 'You' : (c.chatName || (c.ai ? 'Agent' : c.toolLabel)); last.textContent = `${who}: ${c.talk.lastText}`; b.append(last); }
1058
+ /* Its last message. The agent is the usual speaker, so its name is left off (just the words); only
1059
+ the person's own last word is marked "You:", which tells you it is your move. */
1060
+ if (c.talk?.lastText) { const last = document.createElement('small'); last.className = 'last'; last.textContent = c.talk.lastFrom === 'person' ? `You: ${c.talk.lastText}` : c.talk.lastText; b.append(last); }
1047
1061
  if (!plain) b.append(sub);
1048
1062
  b.append(when); b.dataset.when = 'true';
1049
1063
  } else b.append(title, ...(plain ? [] : [sub]));
1050
1064
  /* Its state: one point, on the right. */
1051
- const point = statePoint(stateOf(c)); point.title = STATE_WORDS[point.dataset.state]; b.append(point); b.dataset.state = point.dataset.state;
1065
+ const point = statePoint(rollup(c)); point.title = STATE_WORDS[point.dataset.state]; b.append(point);
1052
1066
  /* Found by a search while hidden: said. */
1053
1067
  if (c.hidden === true && query) { const mark = document.createElement('small'); mark.className = 'shared-mark'; mark.textContent = 'hidden'; b.append(mark); }
1054
1068
  /* Several models answer its simple questions; or they stopped, and it waits for its owner. */
@@ -1125,7 +1139,9 @@
1125
1139
  /* One in Needs you just above is not said twice. */
1126
1140
  /* The last day only: what is older is found in its group. */
1127
1141
  const dayAgo = Date.now() - 24 * 3600_000;
1128
- const recent = conversations.filter((c) => (c.hidden !== true || c.name === current) && !needsYou(c) && activityOf(c) >= dayAgo).sort((a, b) => activityOf(b) - activityOf(a));
1142
+ /* Asleep ones go to the bottom of Recent: they are frozen, not what you came back to. */
1143
+ const recent = conversations.filter((c) => (c.hidden !== true || c.name === current) && !needsYou(c) && activityOf(c) >= dayAgo)
1144
+ .sort((a, b) => (Number(a.asleep === true) - Number(b.asleep === true)) || (activityOf(b) - activityOf(a)));
1129
1145
  const few = 4;
1130
1146
  if (recent.length && groups.length && section(RECENT, 'Recent', recent)) {
1131
1147
  top.append(...unfolding(RECENT, recent.slice(0, showAllRecent ? recent.length : few).map((c) => itemButton(c, true))));
@@ -1420,6 +1436,15 @@
1420
1436
  select.replaceChildren(...mems.map((m) => { const o = document.createElement('option'); o.value = String(m); o.textContent = sizeWords(m); return o; }));
1421
1437
  select.value = String(mems.includes(was) ? was : least);
1422
1438
  $('newconv-memory-least').textContent = tool ? `${tool.label} needs ${sizeWords(least)} at least` : '';
1439
+ /* Cores: 1 to what this server has (learnt from any machine we know), default 1. */
1440
+ const hostCpus = Math.max(1, ...conversations.map((c) => c.hostCpus ?? 1));
1441
+ const cpus = $('newconv-cpus'); const wasCpus = Number(cpus.value) || 1;
1442
+ cpus.replaceChildren(...Array.from({ length: hostCpus }, (_, i) => i + 1).map((n) => { const o = document.createElement('option'); o.value = String(n); o.textContent = `${n}${n === 1 ? ' (default)' : ''}${n === hostCpus && n > 1 ? ' (all of this server)' : ''}`; return o; }));
1443
+ cpus.value = String(wasCpus <= hostCpus ? wasCpus : 1);
1444
+ /* Disk: from the default up; it only grows afterwards. */
1445
+ const disk = $('newconv-disk'); const wasDisk = Number(disk.value) || 8;
1446
+ disk.replaceChildren(...DISK_CHOICES.map((d) => { const o = document.createElement('option'); o.value = String(d); o.textContent = `${d} GB${d === 8 ? ' (default)' : ''}`; return o; }));
1447
+ disk.value = String(DISK_CHOICES.includes(wasDisk) ? wasDisk : 8);
1423
1448
  }
1424
1449
  function paintNewTools() {
1425
1450
  const box = $('newconv-tools');
@@ -1490,10 +1515,11 @@
1490
1515
  if (id && !ID_SHAPE.test(id)) { newError('id', 'Lower-case letters, digits, hyphens'); return; }
1491
1516
  const least = newTools.find((t) => t.id === chosenTool)?.memoryMb;
1492
1517
  const memoryMb = Number($('newconv-memory').value);
1518
+ const cpus = Number($('newconv-cpus').value); const diskGb = Number($('newconv-disk').value);
1493
1519
  newError('', '');
1494
1520
  creating = true; $('newconv-create').disabled = true;
1495
1521
  try {
1496
- const made = await post(`${API}/conversations`, { title, ...(id ? { name: id } : {}), ...(group ? { group } : {}), tool: chosenTool, workOnDisk: newOnDisk(), ...(memoryMb && memoryMb !== least ? { memoryMb } : {}) });
1522
+ const made = await post(`${API}/conversations`, { title, ...(id ? { name: id } : {}), ...(group ? { group } : {}), tool: chosenTool, workOnDisk: newOnDisk(), ...(memoryMb && memoryMb !== least ? { memoryMb } : {}), ...(cpus && cpus !== 1 ? { cpus } : {}), ...(diskGb && diskGb !== 8 ? { diskGb } : {}) });
1497
1523
  $('newconv-name').value = ''; $('newconv-id').value = ''; $('newconv-id').placeholder = 'website-redesign'; $('newconv-group').value = '';
1498
1524
  $('newconv-work').querySelector('[data-work="kept"]').click(); $('newconv-more').open = false;
1499
1525
  await refresh();
@@ -1672,6 +1698,9 @@
1672
1698
  function paintViews() {
1673
1699
  if (DEVICE) return;
1674
1700
  const now = tabNow();
1701
+ /* The "Loading the terminal..." veil belongs to the terminal: leaving it for the chat (or
1702
+ any other tab) takes the veil away, so a tab already there is not covered. */
1703
+ if (notice.dataset.loading && now !== 'terminal') notice.hidden = true;
1675
1704
  for (const [id, tab] of [['view-chat', 'chat'], ['view-terminal', 'terminal'], ['view-assets', 'assets'], ['view-lists', 'lists'], ['folders', 'settings']]) $(id).setAttribute('aria-pressed', String(now === tab));
1676
1705
  }
1677
1706
  /* THE FOUR TABS: Chat, Terminal, Assets, Settings. The one it opened on
@@ -2490,6 +2519,11 @@
2490
2519
  const name = current;
2491
2520
  if (name !== current || (thread && threadOf === current)) return;
2492
2521
  threadOf = name;
2522
+ /* The short-lived secrets live in this conversation now (secret-scan.mjs): the chat shows each as
2523
+ stars with its time left and a way to forget it. Kept current on each reload, read on each repaint. */
2524
+ const chatSecrets = {};
2525
+ const refreshSecrets = () => { for (const k of Object.keys(chatSecrets)) delete chatSecrets[k]; for (const s of conversations.find((x) => x.name === name)?.ephemeralSecrets ?? []) chatSecrets[s.name] = { expiresInMs: s.expiresInMs }; };
2526
+ refreshSecrets();
2493
2527
  /* The lines of its machine seen so far: what changed comes alone, and their buttons are worked out on all of them. */
2494
2528
  const lines = new Map();
2495
2529
  const withLines = (data, asked) => {
@@ -2503,7 +2537,7 @@
2503
2537
  onView: (v) => { chatView = v; try { localStorage.setItem('clavarium-chat-view', v); } catch { /* as above */ } },
2504
2538
  /* A part of the thread: its end at first, then what changed, the page before on demand (Parley's window). */
2505
2539
  window: windowFor(chatWindow),
2506
- load: (asked = {}) => fetch(talkPath(name, '', asked)).then((r) => r.json()).then((data) => withLines(data, asked)).then(machineLines).then((data) => withMachine(data, name)),
2540
+ load: (asked = {}) => fetch(talkPath(name, '', asked)).then((r) => r.json()).then((data) => withLines(data, asked)).then(machineLines).then((data) => withMachine(data, name)).then((data) => (refreshSecrets(), data)),
2507
2541
  /* The whole thread searched, however little of it is shown. */
2508
2542
  search: (q) => fetch(talkPath(name, '/search', { q })).then((r) => (r.ok ? r.json() : { matches: [], count: 0 })),
2509
2543
  /* `via: 'voice'`: part of it was dictated, said to the tool. */
@@ -2536,6 +2570,9 @@
2536
2570
  /* Its pictures, from the shared folders only, by the same route as the thumbnails of Files (type proved by the bytes, never SVG). */
2537
2571
  picture: (file) => { if (!file.open) return null; const at = file.open.indexOf(':'); return `${API}/files/thumb?${new URLSearchParams({ c: name, r: file.open.slice(0, at), p: file.open.slice(at + 1) })}`; },
2538
2572
  diagram: drawDiagram, highlight: colourCode,
2573
+ /* Short-lived secrets of this conversation: the stars say their time left and offer to forget them. */
2574
+ secrets: chatSecrets,
2575
+ forget: (secretName) => post(`${API}/conversations/${encodeURIComponent(name)}/secrets/${encodeURIComponent(secretName)}/forget`, {}).then(() => { delete chatSecrets[secretName]; if (thread && threadOf === name) void thread.refresh(); }).catch(() => {}),
2539
2576
  remind: () => post(talkPath(name, '/remind'), {}),
2540
2577
  /* The helpers of the terminal, in the chat: this page's voice, the owner's ready answers, the keyboard rule of this device. */
2541
2578
  voice: chatVoice(), autoSend: chatAuto,
@@ -3191,6 +3228,8 @@
3191
3228
  const gitSub = (r) => (r.from ? `from ${hostOf(r.from)}` : 'repository');
3192
3229
  /* A secret's expiry, as said: `due` when it asks for the person (near, or past). */
3193
3230
  const secretState = (s) => {
3231
+ /* Short-lived, lifted from a message (secrets.mjs): minutes, not days -- shown so it can be seen and let go. */
3232
+ if (s.ephemeral) { const mins = Math.max(0, Math.round((s.expiresInMs ?? 0) / 60_000)); return s.expired || mins <= 0 ? { text: 'Expired', tone: 'bad', due: true } : { text: `Short-lived, ${mins} min left`, tone: 'warn', due: true }; }
3194
3233
  if (s.expired) return { text: 'Expired', tone: 'bad', due: true };
3195
3234
  if (s.days === null || s.days === undefined) return { text: 'No expiry', tone: '', due: false };
3196
3235
  if (secretDue(s)) return { text: s.days === 1 ? 'Expires tomorrow' : `Expires in ${s.days} days`, tone: 'warn', due: true };
@@ -7707,7 +7746,7 @@
7707
7746
  $('share-done').addEventListener('click', leaveCompose);
7708
7747
 
7709
7748
  /* ---------- resting and archiving ---------- */
7710
- $('sleep').addEventListener('click', async () => {
7749
+ async function sleepMachine() {
7711
7750
  const name = current;
7712
7751
  leavePanel();
7713
7752
  disconnect();
@@ -7715,7 +7754,12 @@
7715
7754
  show('Going to sleep...');
7716
7755
  try { await post(`${API}/conversations/${encodeURIComponent(name)}/sleep`); await refresh(); enter(); }
7717
7756
  catch (error) { say('awake', 'ended'); show(error.message, 'Back to the terminal', connect); }
7718
- });
7757
+ }
7758
+ $('sleep').addEventListener('click', () => void sleepMachine());
7759
+ /* The quick actions at the top of the panel do the same as the Machine chapter's. */
7760
+ $('quick-sleep').addEventListener('click', () => void sleepMachine());
7761
+ $('quick-restart').addEventListener('click', () => { leavePanel(); void restartMachine(false); });
7762
+ $('quick-wake').addEventListener('click', () => { leavePanel(); seeTerminal(); });
7719
7763
  async function rebuild() {
7720
7764
  const name = current;
7721
7765
  disconnect();
package/web/index.html CHANGED
@@ -111,6 +111,12 @@
111
111
  <div id="clists" class="sheet as-room" hidden><div id="clists-binder" class="binder-holder"></div></div>
112
112
  <div id="panel" class="sheet" hidden>
113
113
  <div class="panel-top"><b id="panel-title">This conversation</b></div>
114
+ <!-- The gestures done often on the machine, without opening the Machine chapter (app.js, paintMachine). -->
115
+ <div class="row panel-actions" id="panel-actions" hidden>
116
+ <button type="button" id="quick-wake" class="primary" hidden>Wake it</button>
117
+ <button type="button" id="quick-restart" hidden>Restart&hellip;</button>
118
+ <button type="button" id="quick-sleep" hidden title="Freezes the tool as it is; it wakes when you open the conversation">Sleep</button>
119
+ </div>
114
120
  <p id="panel-error" class="error" role="alert" hidden></p>
115
121
  <details class="chapter" id="chapter-general" data-chapter="general">
116
122
  <summary><span class="chapter-title">General</span><span class="chapter-about">Name, group, chat.</span></summary>
@@ -372,6 +378,12 @@
372
378
  <!-- THE MAP (once "Who gets what"): every device, conversation and asset, and the rights between them (links.js). -->
373
379
  <div id="links" class="pane">
374
380
  <div id="links-legend" class="lk-legend"></div>
381
+ <!-- The column filters, kept out of the board's zoom so a crowded map does not shrink them (links.js). -->
382
+ <div id="links-filters" class="lk-filters">
383
+ <label class="lk-filter"><span>Devices</span><input type="search" class="lk-find" data-k="device" placeholder="Filter&hellip;" aria-label="Filter devices"></label>
384
+ <label class="lk-filter"><span>Conversations</span><input type="search" class="lk-find" data-k="conversation" placeholder="Filter&hellip;" aria-label="Filter conversations"></label>
385
+ <label class="lk-filter"><span>Assets</span><input type="search" class="lk-find" data-k="asset" placeholder="Filter&hellip;" aria-label="Filter assets"></label>
386
+ </div>
375
387
  <p id="links-hint" class="hint" aria-live="polite"></p>
376
388
  <p id="links-error" class="error" role="alert" hidden></p>
377
389
  <div id="links-card" class="lk-card" hidden aria-live="polite"></div>
@@ -892,10 +904,12 @@
892
904
  <details class="more"><summary>Which one?</summary>A code project that installs packages: its disk. Can be changed later.</details>
893
905
  </div>
894
906
  <details class="chapter" id="newconv-more">
895
- <summary><span class="chapter-title">More</span><span class="chapter-about">Identifier, memory.</span></summary>
907
+ <summary><span class="chapter-title">More</span><span class="chapter-about">Identifier, memory, cores, disk.</span></summary>
896
908
  <div class="chapter-body">
897
909
  <div class="set-row"><div class="set-what"><label for="newconv-id">Identifier</label><small>Its machine and address. Never changes</small><span id="newconv-id-error" class="err" role="alert" hidden></span></div><div class="set-control"><input id="newconv-id" maxlength="32" pattern="[a-z]([a-z0-9\-]{0,30}[a-z0-9])?" placeholder="website-redesign" spellcheck="false" autocapitalize="none"></div></div>
898
910
  <div class="set-row"><div class="set-what"><label for="newconv-memory">Memory</label><small id="newconv-memory-least"></small><span id="newconv-memory-error" class="err" role="alert" hidden></span></div><div class="set-control"><select id="newconv-memory"></select></div></div>
911
+ <div class="set-row"><div class="set-what"><label for="newconv-cpus">Cores</label><small>Shared with the server's machines</small></div><div class="set-control"><select id="newconv-cpus"></select></div></div>
912
+ <div class="set-row"><div class="set-what"><label for="newconv-disk">Disk</label><small>For code kept on the machine; a disk only grows</small></div><div class="set-control"><select id="newconv-disk"></select></div></div>
899
913
  </div>
900
914
  </details>
901
915
  </div>
package/web/links.js CHANGED
@@ -69,6 +69,12 @@
69
69
  let allLines = true;
70
70
  try { allLines = localStorage.getItem('clavarium-links-all') !== '0'; } catch { /* none kept */ }
71
71
  let picked = null; let pinned = null; let focus = null; let drag = null; let pop = null; let popLink = null; let drawnMany = false;
72
+ /* A box is shown only if its column's filter is empty or its name holds what was typed: so a
73
+ crowded map (many assets) is narrowed to a few boxes, their links with them. The layout is
74
+ kept while typing (no reorder), and a filter cleared brings everything back. */
75
+ const filters = { device: '', conversation: '', asset: '' };
76
+ let laidOut = null;
77
+ const matches = (n, k) => { const f = (filters[k] || '').trim().toLowerCase(); return !f || n.name.toLowerCase().includes(f) || String(n.sub || '').toLowerCase().includes(f); };
72
78
  const ph = { screen: 'list', kind: 'device', id: null, adding: false, sheet: null };
73
79
  let traceOf = '*';
74
80
 
@@ -182,27 +188,35 @@
182
188
  }
183
189
  return best;
184
190
  }
185
- function paint() {
191
+ /* `relayout` false keeps the order found last: used while typing a filter, so boxes do not jump. */
192
+ function paint(relayout = true) {
186
193
  for (const b of document.querySelectorAll('#links-tabs [data-view]')) b.setAttribute('aria-selected', String(b.dataset.view === view));
187
194
  $('links-all').checked = allLines;
188
195
  legend();
189
196
  const bd = board();
190
197
  bd.className = `lk-board ${VIEWS[view].cols.length === 3 ? 'three' : 'two'}`;
191
198
  bd.querySelectorAll('.lk-col, .lk-knob').forEach((e) => e.remove()); closePop();
192
- const lists = layout();
199
+ if (relayout || !laidOut) laidOut = layout();
200
+ const lists = laidOut;
193
201
  VIEWS[view].cols.forEach((cols, ci) => {
194
202
  const col = h('div', { class: 'lk-col' });
195
203
  cols.forEach((k, i) => {
196
204
  if (i) col.append(h('div', { class: 'lk-gap' }));
197
- col.append(h('h3', { class: 'lk-colh' }, h('span', { text: TITLES[k] }), plus(k)));
198
- const list = lists[ci][i];
205
+ col.append(h('h3', { class: 'lk-colh' }, h('span', { class: 'lk-colt', text: TITLES[k] }), plus(k)));
206
+ const whole = lists[ci][i];
207
+ const list = whole.filter((n) => matches(n, k));
199
208
  for (const n of list) col.append(nodeEl(n));
200
- if (!list.length) col.append(empty(k));
209
+ if (!list.length) col.append(whole.length ? h('p', { class: 'hint lk-none', text: 'Nothing matches.' }) : empty(k));
201
210
  });
202
211
  bd.append(col);
203
212
  });
204
213
  fit(); draw(); hint(); paintPhone();
205
214
  }
215
+ /* The filters sit in a bar of their own, ABOVE the board and out of its zoom, so that fitting
216
+ a crowded map (which zooms it down) never shrinks them. Each narrows its column; the board
217
+ is repainted without a relayout (the inputs are not rebuilt, so the caret stays). */
218
+ const onFind = (e) => { filters[e.target.dataset.k] = e.target.value; paint(false); };
219
+ for (const inp of document.querySelectorAll('#links-filters .lk-find')) inp.addEventListener('input', onFind);
206
220
  /* How each kind is made: a device paired, a conversation created, an asset added. The same,
207
221
  from the small round "+" by each column's title (always there, however many it holds)
208
222
  and from an empty column. */
package/web/style.css CHANGED
@@ -2,7 +2,7 @@
2
2
  a narrow one, the list and the conversation are two screens. */
3
3
  :root {
4
4
  --bg: #0f141a; --bar: #161d26; --panel: #131a22; --line: #2b3745; --ink: #e7edf4; --ink2: #a3b1c2;
5
- --brass: #d2a94e; --on-brass: #1b1405; --ok: #5fc39d; --warn: #e39a5c; --danger: #ee7f79;
5
+ --brass: #d2a94e; --on-brass: #1b1405; --ok: #5fc39d; --warn: #e39a5c; --danger: #ee7f79; --wait: #5aa9f0;
6
6
  /* Brass as the colour of text or of a small sign: darker on a light screen, to be read. */
7
7
  --brass-ink: #d2a94e;
8
8
  --sans: system-ui, -apple-system, "Segoe UI", sans-serif;
@@ -11,7 +11,7 @@
11
11
  colours of its own for it (app.js): a tool's "white" must stay readable. */
12
12
  :root[data-theme="light"] {
13
13
  --bg: #fbfbfa; --bar: #eef0f3; --panel: #ffffff; --line: #c5cdd8; --ink: #17202b; --ink2: #4f5d6d;
14
- --brass: #c79a3a; --on-brass: #1b1405; --ok: #1f7a5a; --warn: #a3581a; --danger: #b3261e; --button: #e6eaef; --brass-ink: #8a5d00;
14
+ --brass: #c79a3a; --on-brass: #1b1405; --ok: #1f7a5a; --warn: #a3581a; --danger: #b3261e; --wait: #2f7fd6; --button: #e6eaef; --brass-ink: #8a5d00;
15
15
  }
16
16
  * { box-sizing: border-box; }
17
17
  /* TEXT IS IN rem: one size at the root (set per device by app.js, as a
@@ -34,20 +34,25 @@ button:focus-visible, input:focus-visible { outline: 2px solid var(--brass); out
34
34
  .item[aria-current="true"] { border-color: var(--brass); box-shadow: 0 0 0 1px var(--brass); }
35
35
  .item b { display: block; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
36
36
  .item small { color: var(--ink2); }
37
- /* ITS STATE, one point on the right of its row: needs you, to watch, fine, asleep (a hollow ring). */
37
+ /* ITS STATE, one point on the right of its row, its colour the worst that
38
+ applies: a machine problem (red), the agent waits for you (blue), the agent
39
+ at work (gold, pulsing), the machine busy (amber, pulsing), fine (green),
40
+ asleep (a hollow ring). The same point, same colours, sums a folded group. */
38
41
  .item { position: relative; padding-right: 26px; }
39
42
  .state-dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0; box-sizing: border-box; background: var(--ok); }
40
- .state-dot[data-state="need"] { background: var(--danger); }
41
- .state-dot[data-state="watch"] { background: var(--warn); }
43
+ .state-dot[data-state="problem"] { background: var(--danger); }
44
+ .state-dot[data-state="wait"] { background: var(--wait); }
45
+ .state-dot[data-state="work"] { background: var(--brass); }
46
+ .state-dot[data-state="busy"] { background: var(--ink2); }
42
47
  .state-dot[data-state="sleep"] { background: transparent; border: 1.5px solid var(--ink2); }
43
48
  .item > .state-dot { position: absolute; right: 10px; top: 13px; }
44
- .item[data-state="watch"] > .state-dot { animation: pulse 1.6s ease-in-out infinite; }
49
+ .item > .state-dot[data-state="work"], .item > .state-dot[data-state="busy"] { animation: breathe 1.7s ease-in-out infinite; }
45
50
  /* Folded: up to four points, how its conversations are. */
46
51
  .state-sum { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; flex-shrink: 0; }
47
52
  /* Unfolded: it comes in gently, once. */
48
53
  .unfolding { animation: unfold .18s ease-out; }
49
54
  @keyframes unfold { from { opacity: 0; transform: translateY(-6px); } }
50
- @keyframes pulse { 50% { opacity: .25; } }
55
+ @keyframes breathe { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .5; transform: scale(.85); } }
51
56
  @media (prefers-reduced-motion: reduce) { .item > .state-dot, .unfolding { animation: none !important; } }
52
57
  .choices { display: flex; flex-wrap: wrap; gap: 6px; }
53
58
  .choices button[aria-checked="true"] { border-color: var(--brass); background: rgba(210, 169, 78, .16); }
@@ -127,6 +132,7 @@ footer button.wide { flex: 1 0 auto; background: var(--brass); border-color: var
127
132
  .chip[data-access="write"] { color: var(--ok); border-color: var(--ok); }
128
133
  .sheet { position: absolute; inset: 0; z-index: 3; display: flex; flex-direction: column; gap: 10px; padding: 14px; background: var(--panel); overflow-y: auto; }
129
134
  .panel-top { display: flex; align-items: center; justify-content: space-between; }
135
+ .panel-actions { margin: 2px 0 12px; }
130
136
  #panel-rows { display: flex; flex-direction: column; }
131
137
  .folder { display: flex; align-items: center; gap: 8px; padding: 8px 0; border-top: 1px solid var(--line); flex-wrap: wrap; }
132
138
  .folder b { flex: 1; min-width: 100px; overflow: hidden; text-overflow: ellipsis; }
@@ -190,6 +196,8 @@ a.button { font: 600 .8125rem var(--sans); text-decoration: none; border-radius:
190
196
  #mic { flex-basis: 55%; padding-block: 12px; }
191
197
  }
192
198
  .item[data-asleep="true"] .dot { background: var(--ink2); }
199
+ /* Asleep: faded in the list (and sorted to the bottom of Recent, app.js), so it is plainly not where you are. */
200
+ .item[data-asleep="true"]:not([aria-current="true"]) { opacity: .62; }
193
201
  footer button.careful { border-style: dashed; color: var(--ink2); }
194
202
  /* On a touch screen every control is at least a fingertip high. */
195
203
  @media (max-width: 700px) {
@@ -1281,6 +1289,14 @@ select.pill { appearance: auto; }
1281
1289
  /* The title of a column of the map, and its round "+" (a new device, conversation, asset): always there. */
1282
1290
  .lk-col h3.lk-colh, .lk-phead { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
1283
1291
  .lk-col h3.lk-colh .lk-add { width: 26px; height: 26px; font-size: .95rem; letter-spacing: 0; }
1292
+ /* The filters: their own bar above the board, out of its zoom, so they stay a usable size. */
1293
+ .lk-filters { display: flex; gap: 10px 16px; flex-wrap: wrap; margin: 2px 0 10px; }
1294
+ .lk-filter { display: flex; align-items: center; gap: 8px; flex: 1 1 200px; min-width: 160px; }
1295
+ .lk-filter > span { flex: none; font-size: .6875rem; letter-spacing: .08em; text-transform: uppercase; color: var(--ink2); }
1296
+ .lk-filters .lk-find { flex: 1 1 auto; min-width: 0; font: inherit; font-size: .9rem; padding: 7px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); color: var(--ink); }
1297
+ .lk-filters .lk-find::placeholder { color: var(--ink2); }
1298
+ /* The phone shows a list of its own, not the board: the column filters do not apply there. */
1299
+ @media (max-width: 600px) { #links-filters { display: none; } }
1284
1300
  .lk-phead { margin: 4px 0 6px; }
1285
1301
  .as-kinds { display: flex; flex-wrap: wrap; gap: 8px; } .as-kinds button { display: inline-flex; align-items: center; gap: 8px; }
1286
1302