clavarium 0.2.354-next.1 → 0.2.355-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.354-next.1",
3
+ "version": "0.2.355-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.354-next.1",
9
+ "version": "0.2.355-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.354-next.1",
3
+ "version": "0.2.355-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -96,7 +96,9 @@
96
96
  * POST /api/rooms/<id> {name?, host?, add?: {conversations, boxes}, remove?: [member ids]}
97
97
  * POST /api/rooms/<id>/remove the room and its thread
98
98
  * GET /api/rooms/<id>/talk?last= its thread, with the room: {room, messages, ...}
99
- * POST /api/rooms/<id>/talk {text, to?: [AI member ids]}: said in it; to its host, or to the AIs named
99
+ * POST /api/rooms/<id>/talk {text, to?: [AI member ids], files?}: said in it; to its host, or to the AIs named
100
+ * POST /api/rooms/<id>/talk/file?name= the body IS a file the person attaches there -> {path, name, size}
101
+ * GET /api/rooms/<id>/file?p=<id>/<name> a file attached in it
100
102
  * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
101
103
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
102
104
  * POST /api/machines/forget-old: the copy a move left behind, removed
@@ -299,6 +301,15 @@ export async function handleApi(request, response, conversations, headers, resou
299
301
  /* Rooms (#268, rooms.mjs): a thread shared by several AIs, the person and boxes. */
300
302
  if (pathname === '/api/rooms' && rooms) return send(200, rooms.list()), true;
301
303
  const roomTalk = /^\/api\/rooms\/([0-9a-f-]{36})\/talk$/.exec(pathname);
304
+ /* A file attached in a room, opened from its thread. */
305
+ const roomFile = /^\/api\/rooms\/([0-9a-f-]{36})\/file$/.exec(pathname);
306
+ if (roomFile && rooms) {
307
+ const file = await download(rooms.filesOf(roomFile[1]), query.get('p') ?? '');
308
+ response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
309
+ 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}` });
310
+ file.stream.pipe(response);
311
+ return true;
312
+ }
302
313
  if (roomTalk && rooms) { const last = Number(query.get('last')); return send(200, rooms.read(roomTalk[1], Number.isInteger(last) && last > 0 ? { last } : undefined)), true; }
303
314
  if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
304
315
  /* Which providers and kinds an account can be connected for here. */
@@ -433,6 +444,12 @@ export async function handleApi(request, response, conversations, headers, resou
433
444
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
434
445
  return send(201, await talk.attach(decodeURIComponent(attaching[1]), query.get('name') ?? '', request)), true;
435
446
  }
447
+ /* A file the person attaches in a room (06-11): the same as in a chat, kept in the room. */
448
+ const roomAttaching = /^\/api\/rooms\/([0-9a-f-]{36})\/talk\/file$/.exec(pathname);
449
+ if (roomAttaching && rooms) {
450
+ if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
451
+ return send(201, await rooms.attach(roomAttaching[1], query.get('name') ?? '', request)), true;
452
+ }
436
453
  /* A flow with its files, sent from the page: the body is the .tar.gz. */
437
454
  if (pathname === '/api/setup/bundle' && setup && bundles) {
438
455
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
@@ -450,7 +467,7 @@ export async function handleApi(request, response, conversations, headers, resou
450
467
  const r = /^\/api\/rooms\/([0-9a-f-]{36})(\/remove|\/talk)?$/.exec(pathname);
451
468
  if (r && !r[2]) return send(200, rooms.change(r[1], body ?? {})), true;
452
469
  if (r && r[2] === '/remove') { rooms.remove(r[1]); return send(200, { removed: r[1] }), true; }
453
- if (r && r[2] === '/talk') return send(201, await rooms.say(r[1], body?.text, { to: body?.to })), true;
470
+ if (r && r[2] === '/talk') return send(201, await rooms.say(r[1], body?.text, { to: body?.to, files: body?.files })), true;
454
471
  }
455
472
  if (pathname === '/api/conversations') {
456
473
  await conversations.admit?.(body);
package/server/main.mjs CHANGED
@@ -679,7 +679,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
679
679
  log: (line) => events.add({ kind: 'server', text: line }) });
680
680
  /* Rooms (#268): a thread shared by several AIs, the person and boxes (rooms.mjs). */
681
681
  rooms = new Rooms({ file: new JsonFile(`${dataDir}/rooms.json`, []), dir: `${dataDir}/rooms`,
682
- say: (name, text, extra) => talk.say(name, text, undefined, undefined, undefined, extra),
682
+ say: (name, text, extra, files) => talk.say(name, text, undefined, files, undefined, extra),
683
+ attach: (name, fileName, request) => talk.attach(name, fileName, request),
683
684
  rooms: (name, list) => talk.rooms(name, list), conversations: () => all.list(), boxes: () => boxes.all(),
684
685
  speak: (where, text, ids, how) => { void boxes.agentSaid(where, text, ids, how); } });
685
686
  rooms.boxesBound(boxes.all());
package/server/rooms.mjs CHANGED
@@ -14,9 +14,11 @@
14
14
  *
15
15
  * Each conversation of a room is told which rooms it is in, and who is there (Parley's rooms.json).
16
16
  */
17
- import { mkdirSync, rmSync } from 'node:fs';
17
+ import { createReadStream, lstatSync, mkdirSync, rmSync } from 'node:fs';
18
18
  import { randomUUID } from 'node:crypto';
19
- import { Parley } from 'clavarium-parley/host';
19
+ import { join } from 'node:path';
20
+ import { Parley, FILES_MAX } from 'clavarium-parley/host';
21
+ import { importFile } from './files.mjs';
20
22
  import { Refusal } from './conversations.mjs';
21
23
  import { scan } from './secret-scan.mjs';
22
24
 
@@ -28,6 +30,11 @@ export const HOPS_MAX = 8;
28
30
  /* How long an AI given a message is said to be thinking, at most (it may never answer). */
29
31
  export const THINKING_MS = 10 * 60_000;
30
32
  const KINDS = ['person', 'ai', 'box'];
33
+ /* A FILE THE PERSON ATTACHES IN A ROOM (06-11: a room carries what the chat carries): kept in the room's own folder
34
+ (rooms/<id>/attached/<uuid>/<name>), named in its thread by ROOM_FILE's path; a copy goes to each AI the message
35
+ goes to, attached in its own chat as the person attaches one there (talk.attach) -- never to the others. */
36
+ export const ATTACHED_DIR = 'attached';
37
+ const ROOM_FILE = /^\/room\/attached\/([0-9a-f-]{36})\/([^/]+)$/;
31
38
  const nameOf = (v) => String(v ?? '').replace(/\s+/g, ' ').trim().slice(0, ROOM_NAME_MAX);
32
39
 
33
40
  /* A SECRET IN A ROOM (06-11): a room's thread is read by all its members, now and later -- a token, a key pasted
@@ -40,17 +47,18 @@ export const masked = (text) => { const str = String(text ?? ''); const hits = s
40
47
  export const lookOf = (name) => { const text = String(name ?? ''); let h = 0; for (const ch of text) h = (h * 31 + ch.codePointAt(0)) >>> 0; return { initial: ([...text.trim()][0] ?? '?').toUpperCase(), hue: h % 360 }; };
41
48
 
42
49
  export class Rooms {
43
- #file; #dir; #say; #rooms; #conversations; #boxes; #now; #speak; #hops = new Map(); #thinking = new Map();
50
+ #file; #dir; #say; #attach; #rooms; #conversations; #boxes; #now; #speak; #hops = new Map(); #thinking = new Map();
44
51
  /* file: a JsonFile of the rooms; dir: where their threads are; say(name, text, extra): a message written in a
45
- conversation's own chat (talk.say); rooms(name, list): what a conversation is told of its rooms (talk.rooms);
52
+ conversation's own chat (talk.say; its 4th argument the paths of its files there); attach(name, fileName,
53
+ request): a file put in a conversation's chat as the person attaches one (talk.attach); rooms(name, list): what a conversation is told of its rooms (talk.rooms);
46
54
  conversations(): the conversations there are; boxes(): the voice boxes there are. */
47
- constructor({ file, dir, say, rooms = () => {}, conversations = () => [], boxes = () => [], speak = () => {}, now = () => new Date() }) {
48
- this.#speak = speak;
55
+ constructor({ file, dir, say, attach = async () => { throw new Refusal(409, 'Files cannot be given here.'); }, rooms = () => {}, conversations = () => [], boxes = () => [], speak = () => {}, now = () => new Date() }) {
56
+ this.#speak = speak; this.#attach = attach;
49
57
  this.#file = file; this.#dir = dir; this.#say = say; this.#rooms = rooms; this.#conversations = conversations; this.#boxes = boxes; this.#now = now;
50
58
  }
51
59
  #all() { const v = this.#file.get(); return Array.isArray(v) ? v : []; }
52
60
  #save(list) { this.#file.set(list); this.#tellConversations(list); }
53
- #thread(id) { mkdirSync(`${this.#dir}/${id}`, { recursive: true }); return new Parley(`${this.#dir}/${id}`, { room: true, now: this.#now }); }
61
+ #thread(id) { mkdirSync(`${this.#dir}/${id}`, { recursive: true }); return new Parley(`${this.#dir}/${id}`, { room: true, now: this.#now, reach: (path) => { const m = ROOM_FILE.exec(String(path ?? '')); return m ? `room:${m[1]}/${m[2]}` : null; } }); }
54
62
  #find(id) { const r = this.#all().find((x) => x.id === id); if (!r) throw new Refusal(404, 'No such room.'); return r; }
55
63
 
56
64
  /* Its members as they are now: names of the moment (a conversation renamed, a box renamed). */
@@ -143,23 +151,55 @@ export class Rooms {
143
151
  return { room: this.get(id), thinking, doing, ...read, messages: (read.messages ?? []).map((m) => (typeof m.text === 'string' && m.text.includes('@{') ? { ...m, text: named(m.text) } : m)) };
144
152
  }
145
153
 
154
+ /* A FILE THE PERSON ATTACHES, before the message that carries it: the same checks as in a conversation's chat
155
+ (its name, its size: importFile). Resolves with its path in the room, what the message then carries. */
156
+ async attach(id, fileName, request) {
157
+ const room = this.#find(id);
158
+ const root = join(this.#dir, room.id, ATTACHED_DIR); const one = randomUUID();
159
+ mkdirSync(join(root, one), { recursive: true });
160
+ try {
161
+ const kept = await importFile(root, one, String(fileName ?? ''), request);
162
+ return { path: `/room/${ATTACHED_DIR}/${one}/${kept.name}`, name: kept.name, size: kept.size };
163
+ } catch (error) { rmSync(join(root, one), { recursive: true, force: true }); throw error; }
164
+ }
165
+ /* Where its files are, for one to be read (files.mjs download walks in it). */
166
+ filesOf(id) { const room = this.#find(id); const root = join(this.#dir, room.id, ATTACHED_DIR); mkdirSync(root, { recursive: true }); return root; }
167
+ /* The files a message carries: only those attached in this room first, each there. */
168
+ #filesSaid(roomId, files) {
169
+ const given = files === undefined || files === null ? [] : files;
170
+ if (!Array.isArray(given) || given.length > FILES_MAX) throw new Refusal(400, `A message has ${FILES_MAX} files at most.`);
171
+ return given.map((item) => {
172
+ const path = item && typeof item === 'object' ? item.path : item;
173
+ const m = typeof path === 'string' ? ROOM_FILE.exec(path) : null;
174
+ const file = m ? join(this.#dir, roomId, ATTACHED_DIR, m[1], m[2]) : undefined;
175
+ const info = file ? lstatSync(file, { throwIfNoEntry: false }) : undefined;
176
+ if (!info?.isFile()) throw new Refusal(400, 'A file of this message was not attached here first.');
177
+ return { path, name: m[2], size: info.size, file };
178
+ });
179
+ }
180
+
146
181
  /* SOMEONE OF THE PERSON'S SIDE SPEAKS (the person here, a box): kept in the room, given to the host -- or to the
147
- AIs named (to: their member ids). */
148
- async say(id, text, { by, box, to } = {}) {
182
+ AIs named (to: their member ids). Its files (paths from attach): in the thread, and a copy to each of those AIs. */
183
+ async say(id, text, { by, box, to, files } = {}) {
149
184
  const room = this.#find(id); const members = this.#shown(room);
150
185
  /* A box bound to this room speaks in it in its own name (#281): found by its box id. */
151
186
  const who = box ? members.find((m) => m.kind === 'box' && m.ref === box) : by ? members.find((m) => m.id === by && m.kind !== 'ai') : members.find((m) => m.kind === 'person');
152
187
  if (!who) throw new Refusal(400, 'Not a member of this room.');
188
+ const attached = this.#filesSaid(room.id, files);
153
189
  const t = this.#thread(room.id);
154
190
  this.#hops.set(room.id, 0);
155
191
  /* The owner is the room's own side (no name over their words, as in any chat); anyone else is named. */
156
- const now = t.say(masked(text), undefined, [], who.ref === 'owner' ? {} : { by: { id: who.id, name: who.name, kind: who.kind, look: who.look } });
192
+ let now;
193
+ try { now = t.say(masked(text), undefined, attached.map(({ path, name, size }) => ({ path, name, size })), who.ref === 'owner' ? {} : { by: { id: who.id, name: who.name, kind: who.kind, look: who.look } }); } catch (error) { if (error instanceof RangeError) throw new Refusal(400, error.message); throw error; }
157
194
  const said = now.messages.at(-1);
158
195
  const named = (Array.isArray(to) ? to : []).map((x) => members.find((m) => m.id === x && m.kind === 'ai')).filter(Boolean);
159
196
  const host = members.find((m) => m.id === room.host);
160
197
  for (const ai of named.length ? named : host ? [host] : []) {
161
198
  this.#think(room.id, ai.id, true);
162
- await this.#say(ai.ref, text, { by: { id: who.id, name: who.name, kind: who.kind, look: who.look }, room: { id: room.id, name: room.name, message: said.id } });
199
+ /* Its own copy of each file, in its chat's files: as if attached there (a fresh read of the room's file). */
200
+ const copies = [];
201
+ for (const f of attached) { const stream = createReadStream(f.file); stream.headers = { 'content-length': String(f.size) }; copies.push((await this.#attach(ai.ref, f.name, stream)).path); }
202
+ await this.#say(ai.ref, text, { by: { id: who.id, name: who.name, kind: who.kind, look: who.look }, room: { id: room.id, name: room.name, message: said.id } }, ...(copies.length ? [copies] : []));
163
203
  }
164
204
  /* Handed to its AIs: read, as a conversation's agent would say it (06-11: the clock stayed on every message). */
165
205
  try { t.seen?.(); } catch { /* an older Parley */ }
package/web/app.js CHANGED
@@ -5330,7 +5330,10 @@
5330
5330
  if (known && JSON.stringify(thinkingOf(known)) !== JSON.stringify(who)) { known.thinking = who; paint(); }
5331
5331
  return d;
5332
5332
  }),
5333
- send: (text) => post(`${API}/rooms/${id}/talk`, { text }),
5333
+ send: (text, answers, files) => post(`${API}/rooms/${id}/talk`, { text, ...(files?.length ? { files: files.map((f) => f.path) } : {}) }),
5334
+ /* A file attached in a room (06-11): as in a conversation's chat; kept in the room, a copy to each AI the message goes to. */
5335
+ attach: { upload: async (file) => { const x = await fetch(`${API}/rooms/${id}/talk/file?${new URLSearchParams({ name: file.name })}`, { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file }); const j = await x.json().catch(() => ({})); if (!x.ok) throw new Error(j.error || 'The file could not be sent.'); return j; } },
5336
+ open: (file) => { if (!String(file.open ?? '').startsWith('room:')) return; const inner = file.open.slice('room:'.length); void preview('room', inner, file.name || inner.split('/').pop(), file.size ?? 0, `${API}/rooms/${id}/file?${new URLSearchParams({ p: inner })}`, { within: r.name }); },
5334
5337
  /* The same chat as a conversation's (03-11): its view, its formulas, its dictation, its keyboard rule. */
5335
5338
  view: chatView, onView: (v) => { chatView = v; try { localStorage.setItem('clavarium-chat-view', v); } catch { /* as above */ } },
5336
5339
  math: { url: new URL('vendor/katex/katex.mjs', new URL('/', location.href)).href },